@wirecat/cli-core 1.0.0-rc.0 → 1.1.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 (96) hide show
  1. package/CHANGELOG.md +186 -0
  2. package/THIRD_PARTY_NOTICES +47 -0
  3. package/dist/cli/account-rename.js +1 -1
  4. package/dist/cli/bot/api-input.d.ts +5 -0
  5. package/dist/cli/bot/api-input.js +6 -1
  6. package/dist/cli/bot/api.js +7 -1
  7. package/dist/cli/domain-lists-command.d.ts +16 -0
  8. package/dist/cli/domain-lists-command.js +88 -0
  9. package/dist/cli/index.d.ts +4 -3
  10. package/dist/cli/index.js +3 -2
  11. package/dist/cli/model-catalogue-command.d.ts +6 -0
  12. package/dist/cli/model-catalogue-command.js +1 -1
  13. package/dist/cli/oauth-session.d.ts +38 -4
  14. package/dist/cli/oauth-session.js +66 -22
  15. package/dist/cli/service-api.js +3 -1
  16. package/dist/cli/shared-command-exports.d.ts +2 -0
  17. package/dist/cli/shared-command-exports.js +3 -0
  18. package/dist/cli/token-session.d.ts +9 -0
  19. package/dist/cli/token-session.js +29 -2
  20. package/dist/crm/manifest/map.d.ts +5 -2
  21. package/dist/crm/manifest/map.js +14 -2
  22. package/dist/domain/domain-lists.d.ts +86 -0
  23. package/dist/domain/domain-lists.js +110 -0
  24. package/dist/domain/free-mail-domains.generated.d.ts +1 -0
  25. package/dist/domain/free-mail-domains.generated.js +4 -0
  26. package/dist/domain/organization-sectors.d.ts +16 -0
  27. package/dist/domain/organization-sectors.generated.d.ts +12 -0
  28. package/dist/domain/organization-sectors.generated.js +15 -0
  29. package/dist/domain/organization-sectors.js +22 -0
  30. package/dist/domain/person-kinds.d.ts +5 -0
  31. package/dist/domain/person-kinds.js +5 -0
  32. package/dist/entities/domain-list.d.ts +27 -0
  33. package/dist/entities/domain-list.js +28 -0
  34. package/dist/entities/index.d.ts +20 -1
  35. package/dist/entities/index.js +3 -1
  36. package/dist/entities/knowledge-lists.d.ts +1 -0
  37. package/dist/entities/knowledge-lists.js +2 -0
  38. package/dist/errors/reasons.js +14 -3
  39. package/dist/mail/mail-types.d.ts +48 -0
  40. package/dist/mail/mail-types.js +218 -0
  41. package/dist/mail/score.d.ts +2 -0
  42. package/dist/mail/score.js +9 -2
  43. package/dist/oauth/index.d.ts +1 -1
  44. package/dist/oauth/storage.d.ts +10 -2
  45. package/dist/oauth/storage.js +23 -9
  46. package/dist/services/domain-lists-download.d.ts +26 -0
  47. package/dist/services/domain-lists-download.js +155 -0
  48. package/dist/services/search-all-rank.d.ts +44 -0
  49. package/dist/services/search-all-rank.js +112 -0
  50. package/dist/services/search-all-tracker.d.ts +58 -0
  51. package/dist/services/search-all-tracker.js +155 -0
  52. package/dist/services/search-all.d.ts +1 -8
  53. package/dist/services/search-all.js +18 -199
  54. package/dist/services/tracker-meaning.js +1 -1
  55. package/dist/store/areas.d.ts +1 -0
  56. package/dist/store/index.d.ts +2 -1
  57. package/dist/store/index.js +1 -1
  58. package/dist/store/people.d.ts +30 -0
  59. package/dist/store/people.js +16 -1
  60. package/dist/store/sqlite/accounts.js +3 -1
  61. package/dist/store/sqlite/domain-organizations.d.ts +36 -0
  62. package/dist/store/sqlite/domain-organizations.js +288 -0
  63. package/dist/store/sqlite/email-types.d.ts +79 -0
  64. package/dist/store/sqlite/email-types.js +261 -0
  65. package/dist/store/sqlite/emails.d.ts +11 -2
  66. package/dist/store/sqlite/emails.js +18 -7
  67. package/dist/store/sqlite/identities.d.ts +4 -1
  68. package/dist/store/sqlite/identities.js +11 -2
  69. package/dist/store/sqlite/identity-rekey.js +2 -0
  70. package/dist/store/sqlite/knowledge.d.ts +2 -9
  71. package/dist/store/sqlite/manifest.js +6 -0
  72. package/dist/store/sqlite/merged-persons.d.ts +3 -2
  73. package/dist/store/sqlite/merged-persons.js +5 -3
  74. package/dist/store/sqlite/migrations.generated.js +77 -0
  75. package/dist/store/sqlite/organizations.d.ts +12 -1
  76. package/dist/store/sqlite/organizations.js +9 -1
  77. package/dist/store/sqlite/people-list.js +69 -11
  78. package/dist/store/sqlite/person-links.js +13 -3
  79. package/dist/store/sqlite/person-match-scan.js +14 -1
  80. package/dist/store/sqlite/schema/sender-bots.d.ts +344 -0
  81. package/dist/store/sqlite/schema/sender-bots.js +30 -0
  82. package/dist/store/sqlite/schema.d.ts +49 -0
  83. package/dist/store/sqlite/schema.js +7 -0
  84. package/dist/store/sqlite/sender-bots.d.ts +108 -0
  85. package/dist/store/sqlite/sender-bots.js +431 -0
  86. package/dist/store/sqlite/sender-signals.d.ts +13 -3
  87. package/dist/store/sqlite/sender-signals.js +17 -13
  88. package/dist/store/sqlite/tracker.d.ts +11 -9
  89. package/dist/store/sqlite/tracker.js +27 -12
  90. package/dist/store/sqlite/work-tasks.js +2 -0
  91. package/dist/tracker/cli/index.d.ts +1 -1
  92. package/dist/tracker/cli/index.js +83 -24
  93. package/dist/tracker/sync.js +43 -20
  94. package/dist/tracker/writes.d.ts +28 -0
  95. package/dist/tracker/writes.js +141 -19
  96. package/package.json +3 -3
@@ -4,16 +4,14 @@ import { crmViewerOf } from "../crm/index.js";
4
4
  import { hitFiles } from "../domain/attachments.js";
5
5
  import { parseLocator } from "../domain/locator.js";
6
6
  import { senderIsMe } from "../domain/models.js";
7
- import { hasGlobalItemIds, holdsKind, INTERNAL_NOTES, isDocumentAccountProvider } from "../domain/providers.js";
8
- import { trackerBodyOf, trackerTitleOf } from "../domain/tracker.js";
7
+ import { holdsKind, INTERNAL_NOTES, isDocumentAccountProvider } from "../domain/providers.js";
9
8
  import { runEmbedders } from "../embeddings/embed.js";
10
9
  import { chosenTextModel } from "../embeddings/models.js";
11
10
  import { formatMeetingReference } from "../meetings/index.js";
12
11
  import { entriesOfList, fitting, listedHolds } from "../search/account-list.js";
13
12
  import { RRF_K } from "../search/fusion.js";
14
- import { meaningWords } from "../search/lucene/meaning-parts.js";
15
13
  import { plainQuery } from "../search/lucene/plain.js";
16
- import { MESSAGE_PARSING, SEARCH_QUERY } from "../search/lucene/types.js";
14
+ import { MESSAGE_PARSING } from "../search/lucene/types.js";
17
15
  import { questionPeriod } from "../search/question-period.js";
18
16
  import { planQuestion, questionLookup, questionText } from "../search/question-plan.js";
19
17
  import { nearestCrmActivities } from "./crm-meaning.js";
@@ -24,9 +22,11 @@ import { nearEligible } from "./messages-discovery.js";
24
22
  import { importAccounts, notesScopeOf, searchNotes } from "./notes-search.js";
25
23
  import { BUSINESS_WORDS_ONLY, searchBusiness } from "./search-all-business.js";
26
24
  import { meetingLane } from "./search-all-meetings.js";
25
+ import { contentWords, fusedLane, insidePeriodFirst, meaningWordsOf, oneList, PERIOD_DEPTH, titleWords, } from "./search-all-rank.js";
26
+ import { trackerLane } from "./search-all-tracker.js";
27
27
  import { HARDER_CANDIDATES, reorderHarder } from "./search-harder.js";
28
28
  import { listContextOf } from "./search-kind.js";
29
- import { nearestTracker } from "./tracker-meaning.js";
29
+ export { titleWords } from "./search-all-rank.js";
30
30
  export const RESOURCES_SEARCHED = [
31
31
  "messages",
32
32
  "mail",
@@ -61,24 +61,6 @@ const filtersBeside = (text) => {
61
61
  ? planQuestion(text).scope
62
62
  : undefined;
63
63
  };
64
- /**
65
- * What a deal or a lead is found by: plain words or phrases, all of them, or any with OR. Anything else is refused,
66
- * so `search all` skips deals with the reason instead of matching a field they do not have.
67
- */
68
- export const titleWords = (text, refused = "deals and leads are found by the words of their title, company, contacts and activities only") => {
69
- const { root } = parseLucene(text, SEARCH_QUERY);
70
- const clauses = root.kind === "boolean" ? root.clauses : [{ node: root, occur: "must" }];
71
- const words = clauses.map(({ node, occur }) => occur !== "must_not" &&
72
- node.kind === "predicate" &&
73
- (node.field === "text" || node.field === "title") &&
74
- (node.operator === "term" || node.operator === "phrase")
75
- ? // A title holds "invoice", not the question mark of "invoice?".
76
- node.value.replace(/\?+$/u, "") || node.value
77
- : (() => {
78
- throw new CliError("validation_error", refused);
79
- })());
80
- return { words, anyWord: clauses.length > 1 && clauses.every(({ occur }) => occur === "should") };
81
- };
82
64
  /** The single words of an all-words query, when it has two to eight of them; none for OR, fields or phrases. */
83
65
  const strictWords = (text) => {
84
66
  try {
@@ -140,75 +122,8 @@ const copyViewers = async (store) => {
140
122
  }
141
123
  return viewers;
142
124
  };
143
- const TRACKER_HIT_KINDS = { issue: "issue", project: "project", comment: "issue_comment" };
144
125
  /** The accounts of every tracker the store holds copies of. */
145
126
  export const trackerAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "tracker"));
146
- /** An issue is titled as people say it, `ENG-12 Fix login`; anything else by its name or its first line. */
147
- const trackerTitle = ({ kind, record }) => {
148
- const title = trackerTitleOf(kind, record);
149
- const key = kind === "issue" ? record.key : undefined;
150
- return key ? `${key} ${title}` : title;
151
- };
152
- /**
153
- * What the meaning half embeds: the words and phrases asked for, OR included, as notes take them. `title:` narrows to
154
- * the title, which a hit by meaning cannot be held to, so such a query is searched by words only.
155
- */
156
- const meaningWordsOf = (text) => {
157
- try {
158
- const { root } = parseLucene(text, SEARCH_QUERY);
159
- const nodes = root.kind === "boolean" ? root.clauses.map(({ node }) => node) : [root];
160
- if (!nodes.every((node) => node.kind === "predicate" && node.field === "text"))
161
- return undefined;
162
- return meaningWords(root) || undefined;
163
- }
164
- catch {
165
- return undefined;
166
- }
167
- };
168
- const trackerExcerpt = ({ kind, record }, query) => excerpt([trackerTitleOf(kind, record), trackerBodyOf(kind, record)].filter(Boolean).join("\n"), query);
169
- /**
170
- * One hit per tracker item, best first: the copies other sign-ins hold of one item (`items` maps a hit's ref to the
171
- * item, for a provider whose ids name one item across its accounts) join the best-placed one, which names every account and takes the best cosine and every way any was found.
172
- */
173
- const oneHitPerItem = (ordered, cosines, items) => {
174
- const kept = new Map();
175
- for (const hit of ordered) {
176
- const key = items.get(hit.ref) ?? hit.ref;
177
- const held = kept.get(key);
178
- if (!held) {
179
- kept.set(key, hit);
180
- continue;
181
- }
182
- held.accounts = [...(held.accounts ?? [held.account]), hit.account];
183
- held.foundBy = ["words", "meaning"].filter((by) => [held, hit].some(({ foundBy }) => foundBy.includes(by)));
184
- const cosine = cosines.get(hit.ref);
185
- if (cosine !== undefined && cosine > (cosines.get(held.ref) ?? Number.NEGATIVE_INFINITY))
186
- cosines.set(held.ref, cosine);
187
- }
188
- return [...kept.values()];
189
- };
190
- /**
191
- * One list for a lane found both ways, as notes and messages fuse theirs: each hit's rank in either list votes, a
192
- * question's hit voting once; a hit found both ways keeps its words' text and is found by meaning too.
193
- */
194
- const fusedLane = (byWords, byMeaning, discover, cosines) => {
195
- const fused = new Map();
196
- byWords.forEach((item, rank) => {
197
- fused.set(item.ref, { item, score: 1 / (RRF_K + rank + 1) });
198
- });
199
- byMeaning.forEach(({ hit, score }, rank) => {
200
- cosines.set(hit.ref, score);
201
- const held = fused.get(hit.ref);
202
- if (held && !held.item.foundBy.includes("meaning"))
203
- held.item.foundBy = [...held.item.foundBy, "meaning"];
204
- const vote = 1 / (RRF_K + rank + 1);
205
- if (held && discover)
206
- held.score = Math.max(held.score, vote);
207
- else
208
- fused.set(hit.ref, { item: held?.item ?? hit, score: (held?.score ?? 0) + vote });
209
- });
210
- return [...fused.values()].sort((a, b) => b.score - a.score).map(({ item }) => item);
211
- };
212
127
  /** The accounts of every CRM the store holds copies of. */
213
128
  export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
214
129
  /**
@@ -429,7 +344,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
429
344
  accounts.push(...read.map(({ provider, account }) => ({ resource, provider, account })));
430
345
  }
431
346
  else if (resource === "crm") {
432
- const { words, anyWord } = titleWords(request.text);
347
+ const { words, anyWord } = contentWords(titleWords(request.text), discover);
433
348
  const chosen = scope?.crm;
434
349
  // memo's, tg's and the MCP's search all pass no viewers: each copy's own rule decides, as a CRM CLI's does.
435
350
  const viewers = request.crmViewers ?? (await copyViewers(store));
@@ -540,78 +455,25 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
540
455
  const read = scope?.tracker ?? (await trackerAccounts(store));
541
456
  if (!read.length)
542
457
  continue;
543
- const { words, anyWord } = titleWords(request.text, "issues, projects and comments are found by the words and meaning of their title and text only");
544
- // Two sign-ins to one workspace hold each item twice, and the copies fold into one hit: read deep enough
545
- // that the folded list still fills the page.
546
- const deep = Math.min(depth * read.length, 500);
547
- const found = await store.tracker.find({
548
- words,
549
- anyWord: anyWord || discover,
550
- ...(request.exact ? { exact: true } : {}),
551
- kinds: ["issue", "project", "comment"],
552
- limit: deep,
458
+ const found = await trackerLane(store, {
459
+ text: request.text,
553
460
  accounts: read,
461
+ depth,
462
+ discover,
463
+ cosines,
464
+ embedders,
465
+ ...(request.exact ? { exact: true } : {}),
466
+ ...(command === undefined ? {} : { command }),
467
+ ...(request.env === undefined ? {} : { env: request.env }),
554
468
  });
555
469
  hasMore ||= found.hasMore;
556
- const items = new Map();
557
- const hitOf = (at, item, text, foundBy) => {
558
- const ref = `tracker:${at.provider}/${at.account}/${item.kind}/${item.record.externalId}`;
559
- if (hasGlobalItemIds(at.provider))
560
- items.set(ref, JSON.stringify([at.provider, item.kind, item.record.externalId]));
561
- return {
562
- kind: TRACKER_HIT_KINDS[item.kind],
563
- // Two sign-ins see the same issue under the same id, so the account keeps their hits apart.
564
- ref,
565
- provider: at.provider,
566
- account: at.account,
567
- ...(item.record.url ? { url: item.record.url } : {}),
568
- title: trackerTitle(item),
569
- timestamp: new Date(item.record.updatedAt ?? item.syncedAt).toISOString(),
570
- text,
571
- foundBy,
572
- };
573
- };
574
- const byWords = found.items.map(({ account: at, item, excerpt: text }) => hitOf(at, item, text, ["words"]));
575
- const plain = meaningWordsOf(discover ? questionText(request.text) : request.text);
576
- let near;
577
- let meaningSkipped;
578
- if (request.exact)
579
- meaningSkipped = "--exact searches words as written";
580
- else if (plain === undefined)
581
- meaningSkipped = "the query names a title, which meaning cannot follow";
582
- else
583
- try {
584
- near = await nearestTracker(store, plain, {
585
- limit: deep,
586
- accounts: read,
587
- embedders,
588
- ...(command === undefined ? {} : { command }),
589
- ...(request.env === undefined ? {} : { env: request.env }),
590
- });
591
- }
592
- catch (error) {
593
- if (!(error instanceof CliError && error.code === "not_found"))
594
- throw error;
595
- meaningSkipped = error.message;
596
- }
597
- tracker = {
598
- by: near === undefined ? "words" : "words and meaning",
599
- ...(meaningSkipped === undefined ? {} : { meaningSkipped }),
600
- };
601
- if (near === undefined)
602
- lists.push(oneHitPerItem(byWords, cosines, items));
603
- else {
604
- const byMeaning = near.map(({ account: at, item, score }) => ({
605
- hit: hitOf(at, item, trackerExcerpt(item, request.text), ["meaning"]),
606
- score,
607
- }));
608
- lists.push(oneHitPerItem(fusedLane(byWords, byMeaning, discover, cosines), cosines, items));
609
- }
470
+ tracker = found.tracker;
471
+ lists.push(found.hits);
610
472
  for (const { provider, account } of read)
611
473
  accounts.push({ resource, provider, account });
612
474
  }
613
475
  else if (resource === "business") {
614
- const { words, anyWord } = titleWords(request.text, BUSINESS_WORDS_ONLY);
476
+ const { words, anyWord } = contentWords(titleWords(request.text, BUSINESS_WORDS_ONLY), discover);
615
477
  const found = await searchBusiness(store, {
616
478
  words,
617
479
  anyWord: anyWord || discover,
@@ -740,46 +602,3 @@ const withMeetingDocuments = async (store, lists, read) => {
740
602
  ];
741
603
  }));
742
604
  };
743
- /** Passages of one meeting share its `ref`, the reference evidence cites; each is still a hit of its own. */
744
- const hitKey = (item) => item.kind === "meeting" ? `${item.ref}\u0000${item.scope}\u0000${item.id}` : item.ref;
745
- /**
746
- * Every source's hits as one list: each source's best hit first, then every other hit by cosine, then by its rank in
747
- * its source. Taking turns by rank (MEMO-37) gave each of two sources half of a ten-hit page however weak its hits;
748
- * one model scores every source, so cosine compares across them. A hit only words found takes the cosine of
749
- * the hit above it in its source: its source ranked it there, and with none it would follow every hit meaning found.
750
- */
751
- const oneList = (lists, cosines) => {
752
- const place = new Map();
753
- for (const list of lists) {
754
- let above = Number.NEGATIVE_INFINITY;
755
- list.forEach((item, rank) => {
756
- const key = hitKey(item);
757
- above = cosines.get(item.ref) ?? above;
758
- const held = place.get(key);
759
- if (!held || rank < held.rank)
760
- place.set(key, { item, rank, cosine: above });
761
- });
762
- }
763
- const head = (rank) => Math.min(rank, 1);
764
- return [...place.values()]
765
- .sort((a, b) => head(a.rank) - head(b.rank) || b.cosine - a.cosine || a.rank - b.rank)
766
- .map(({ item }) => item);
767
- };
768
- const PERIOD_DEPTH = 100;
769
- const PERIOD_BOOST = 0.5;
770
- /**
771
- * A hit dated inside the question's period gains 0.5 over its place, 1 - rank/100: by rank, because only some hits have
772
- * a cosine to compare. One scale for every page, so paging past the first 100 never reorders what came before.
773
- */
774
- const insidePeriodFirst = (ordered, period) => {
775
- if (!period)
776
- return ordered;
777
- const inside = ({ timestamp }) => {
778
- const at = timestamp === null ? Number.NaN : Date.parse(timestamp);
779
- return at >= period.from && at < period.to;
780
- };
781
- return ordered
782
- .map((item, rank) => ({ item, score: 1 - rank / PERIOD_DEPTH + (inside(item) ? PERIOD_BOOST : 0) }))
783
- .sort((a, b) => b.score - a.score)
784
- .map(({ item }) => item);
785
- };
@@ -20,7 +20,7 @@ export const embedTracker = async (store, options = {}) => {
20
20
  export const nearestTracker = async (store, words, { limit, accounts, env, command, embedders, }) => {
21
21
  const { model, directory, key } = localModel(await meaningModel(store, env), env, command);
22
22
  if (!(await store.tracker.embedded(key, accounts)))
23
- throw new CliError("not_found", `no issue, project or comment has vectors of ${model.id} yet, so only words were matched`);
23
+ throw new CliError("not_found", `no issue, project or comment has vectors of ${model.id} yet, so only words were matched`, { reason: "tracker.no-vectors", model: model.id });
24
24
  const [vector] = await withLocal(model, directory, undefined, (embedder) => embedder.embed([words], "query"), embedders);
25
25
  const floor = meaningFloor(key);
26
26
  return (await store.tracker.nearest(key, vector, { limit, accounts })).filter(({ score }) => score > floor);
@@ -30,6 +30,7 @@ export type { ProductFilter } from "./sqlite/products.js";
30
30
  export { PROPOSAL_STATUSES, type ProposedAction } from "./sqlite/proposed-actions.js";
31
31
  export type { MatchRun, RecordKey } from "./sqlite/records.js";
32
32
  export type { RelationListItem } from "./sqlite/relation-list.js";
33
+ export type { BotIdentity, BotList, BotListOptions, BotMove, SenderBot, SenderBotDetails, } from "./sqlite/sender-bots.js";
33
34
  export type { SubscriptionFilter } from "./sqlite/subscriptions.js";
34
35
  export { PROJECT_TASK_FIELDS, TASK_SORTS, type TaskSort } from "./sqlite/task-board.js";
35
36
  export { TASK_RELATION_KINDS, type TaskRelationKind } from "./sqlite/task-relations.js";
@@ -1,7 +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
+ export { type KindSignal, PERSON_KINDS, type PersonKind, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
5
5
  export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js";
6
6
  export type { TagConsolidationApplyOptions, TagConsolidationOptions, TagConsolidationPreview, TagConsolidationReceipt, TagConsolidationStore, } from "../domain/tag-consolidation.js";
7
7
  export type { TagRedirectIndex, TagRedirectResolution, TagRedirectSnapshot } from "../domain/tag-redirects.js";
@@ -104,6 +104,7 @@ export type { RelationRole, RelationRoles } from "./sqlite/relation-roles.js";
104
104
  export type { RelationsStore, ReportedIssue, ReportedRelation, ReportedScope, ReportedSync, } from "./sqlite/reported-relations.js";
105
105
  export type { AuthorInfo, Party, Reviewed, Written } from "./sqlite/reviewed.js";
106
106
  export { fillSearchIndex, resetSearchIndex, type SearchIndexFill, type SearchIndexState, searchIndexState, } from "./sqlite/search-index.js";
107
+ export type { BotIdentity, BotList, BotListOptions, BotMove, SenderBot, SenderBotDetails, } from "./sqlite/sender-bots.js";
107
108
  export { REACHES, type Reach, type SenderSignal } from "./sqlite/sender-signals.js";
108
109
  export type { ChallengeInput, SourceReviewDecision } from "./sqlite/source-review.js";
109
110
  export type { PriceFilter, PriceInput, Subscription, SubscriptionDetail, SubscriptionFields, SubscriptionFilter, SubscriptionInput, SubscriptionPrice, SubscriptionsStore, SubscriptionUpdate, } from "./sqlite/subscriptions.js";
@@ -1,6 +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
+ export { PERSON_KINDS, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
4
4
  export { createTagRedirectIndex } from "../domain/tag-redirects.js";
5
5
  export { note } from "../entities/note.js";
6
6
  export { PAYMENT_DIRECTIONS, PAYMENT_STATES, paymentTitle, validatePayment } from "../meetings/index.js";
@@ -15,6 +15,7 @@ import { type PersonPreparationRead } from "./sqlite/person-preparation.js";
15
15
  import { type ShownBecause } from "./sqlite/person-ties.js";
16
16
  import type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
17
17
  import type { ProposedAction } from "./sqlite/proposed-actions.js";
18
+ import { type BotList, type BotListOptions, type SenderBot, type SenderBotDetails } from "./sqlite/sender-bots.js";
18
19
  import type { AccountKey, IdentityRef, LinkOptions, PersonFacts, PersonRecord, StoredAccount, UnlinkOptions } from "./types.js";
19
20
  /** @experimental */
20
21
  export interface AccountPeople {
@@ -208,6 +209,35 @@ export interface PeopleStore extends AccountPeople {
208
209
  }): Promise<SimilarPerson[]>;
209
210
  /** Why each `person:<uid>` is shown by default, as `list` gives it; an empty list for one with no tie. */
210
211
  ties(people: readonly string[]): Promise<Record<string, ShownBecause[]>>;
212
+ /**
213
+ * The sender bots: programs that write to the owner, apart from people (`sender-bot:<id>`), by name. `query` looks in
214
+ * their names, addresses and usernames; `organization` (`organization:<id>`) keeps the ones that send for it.
215
+ * @experimental
216
+ */
217
+ listBots(options: BotListOptions): Promise<BotList>;
218
+ /** One sender bot (`sender-bot:<id>`), its identities and every move to or from it. @experimental */
219
+ showBot(bot: string): Promise<SenderBotDetails>;
220
+ /**
221
+ * The owner says a sender is a program: a person (`person:<uid>`), a bot (`sender-bot:<id>`) or one identity moves
222
+ * to a sender bot for its whole history, and no rule gives it back. Its messages keep pointing at the identity. `bot`
223
+ * joins a stored bot; else a bot already holding it keeps it, or a new one takes it. A person every identity left is
224
+ * hidden from lists, and a move back gives their uid back. The owner's alone; refused for the owner's own person.
225
+ * @experimental
226
+ */
227
+ moveToBot(subject: string | IdentityRef, by: Decider, options?: {
228
+ bot?: string;
229
+ name?: string;
230
+ reason?: string;
231
+ }): Promise<SenderBot>;
232
+ /**
233
+ * The owner says a sender is a person: a bot (`sender-bot:<id>`) or one identity of it moves to a person for its
234
+ * whole history, and no rule makes it a bot again. `person` takes it; else each identity goes back to the person it
235
+ * came from, or a person of its own. Said of a person, it keeps them one. The owner's alone. @experimental
236
+ */
237
+ moveToPerson(subject: string | IdentityRef, by: Decider, options?: {
238
+ person?: string;
239
+ reason?: string;
240
+ }): Promise<PersonRecord>;
211
241
  }
212
242
  export declare const accountPeopleOver: (context: StoreContext) => AccountPeople;
213
243
  export declare const peopleStoreOver: (context: StoreContext, keyed: AccountPeople) => PeopleStore;
@@ -7,16 +7,18 @@ import * as identityProposals from "./sqlite/identity-proposals.js";
7
7
  import { rekeyIdentities } from "./sqlite/identity-rekey.js";
8
8
  import * as identitySplits from "./sqlite/identity-split-proposals.js";
9
9
  import { linkToOwner } from "./sqlite/own-identities.js";
10
- import { countPeople, listPeople, similarPeople, } from "./sqlite/people-list.js";
10
+ import { countPeople, listPeople, similarPeople, storeKinds, } from "./sqlite/people-list.js";
11
11
  import { keepPerson, markTestData, personDoubts, } from "./sqlite/person-doubts.js";
12
12
  import { erasePerson } from "./sqlite/person-erase.js";
13
13
  import * as personLinks from "./sqlite/person-links.js";
14
14
  import { linkPhones, PROPOSAL_SCORE, RULE, scanMatches } from "./sqlite/person-match-scan.js";
15
15
  import * as personMerges from "./sqlite/person-merges.js";
16
+ import { ownerOnly } from "./sqlite/person-merges.js";
16
17
  import { personPreparation } from "./sqlite/person-preparation.js";
17
18
  import { personSeenInAccounts } from "./sqlite/person-scope.js";
18
19
  import { shownReasons } from "./sqlite/person-ties.js";
19
20
  import * as privatePeople from "./sqlite/private-people.js";
21
+ import { listBots, moveToBot, moveToPerson, showBot, } from "./sqlite/sender-bots.js";
20
22
  import { write } from "./sqlite/transaction.js";
21
23
  export const accountPeopleOver = (context) => {
22
24
  const { database } = context;
@@ -165,5 +167,18 @@ export const peopleStoreOver = (context, keyed) => {
165
167
  const reasons = shownReasons(database);
166
168
  return Object.fromEntries(people.map((ref) => [ref, reasons.get(Number(ref.replace(/^person:/, ""))) ?? []]));
167
169
  },
170
+ listBots: async (options) => {
171
+ storeKinds(database);
172
+ return listBots(database, options);
173
+ },
174
+ showBot: async (bot) => showBot(database, bot),
175
+ moveToBot: async (subject, by, options) => {
176
+ ownerOnly(by, "moves a sender to a bot");
177
+ return moveToBot(context, subject, options);
178
+ },
179
+ moveToPerson: async (subject, by, options) => {
180
+ ownerOnly(by, "moves a sender to a person");
181
+ return moveToPerson(context, subject, options);
182
+ },
168
183
  };
169
184
  };
@@ -147,8 +147,10 @@ export const dropOrphanPeople = (database, unseenBefore) => {
147
147
  const persons = database
148
148
  .prepare(`SELECT person_id AS id FROM identity_links WHERE identity_id IN (SELECT value FROM json_each(?))
149
149
  UNION SELECT from_person_id FROM identity_link_events WHERE identity_id IN (SELECT value FROM json_each(?))
150
+ AND from_person_id IS NOT NULL
151
+ UNION SELECT from_person_id FROM sender_bot_moves WHERE identity_id IN (SELECT value FROM json_each(?))
150
152
  AND from_person_id IS NOT NULL`)
151
- .all(gone, gone)
153
+ .all(gone, gone, gone)
152
154
  .map(({ id }) => Number(id));
153
155
  for (const table of ["identity_revisions", "identity_link_events", "identity_links"])
154
156
  database.prepare(`DELETE FROM ${table} WHERE identity_id IN (SELECT value FROM json_each(?))`).run(gone);
@@ -0,0 +1,36 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ /**
3
+ * Newsletter hosts and mail services that send for many customers. Their domain names none of the senders, so it never
4
+ * makes an organization; the bounce and signing domains are here for mail whose `From` carries them.
5
+ */
6
+ export declare const SENDING_PLATFORMS: ReadonlySet<string>;
7
+ /** How a rule's hold on an address is marked in `organization_identities.method`. */
8
+ export declare const BY_DOMAIN = "domain";
9
+ /** A rejected `proposed_actions` row of this kind keeps a rule from making an organization for its domain again. */
10
+ export declare const REFUSED_DOMAIN = "organization-domain";
11
+ /** The registrable domain whose organization an address joins; none for free, throwaway and platform mail. */
12
+ export declare const companyDomainOf: (address: string) => string | undefined;
13
+ /**
14
+ * A person or a sender bot (`bot`, its `sender_bots` id) as the kind pass leaves them: `holds` for a bot or a shared
15
+ * mailbox, whose addresses the organization owns; never for one the owner kept as a person.
16
+ */
17
+ export interface Sorted {
18
+ id: number;
19
+ displayName: string | null;
20
+ holds: boolean;
21
+ bot?: boolean;
22
+ }
23
+ /**
24
+ * Plan step 5: a sender bot or a shared mailbox at a company domain joins that domain's organization, made when none holds
25
+ * it; a human there becomes a `member-of` it, never merged. Free mail, throwaway mail and sending platforms make none.
26
+ * An organization holding a domain of the built-in Wikidata list or of the domain-list pack gets its `metadata.sector`.
27
+ * The owner's word holds: a membership the owner removed and a domain whose organization the owner erased are not made
28
+ * again. The caller holds the write lock.
29
+ */
30
+ export declare const groupByDomain: (database: CacheDatabase, people: readonly Sorted[], at: number) => void;
31
+ /** Which lists the sectors in the store come from: this build's table and the pack in place. */
32
+ export declare const SECTORS_FROM = "organizations.sectors_from";
33
+ /** The owner erased an organization: no rule makes one for the company domains it held again. */
34
+ export declare const refuseDomainsOf: (database: CacheDatabase, organization: number, at: number) => void;
35
+ /** The owner moved these identities to a person: the holds a rule gave them go, so they read as a person's again. */
36
+ export declare const releaseDomainHolds: (database: CacheDatabase, identities: readonly number[]) => void;