@wirecat/cli-core 0.615.0 → 0.617.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 +101 -0
  2. package/dist/background/report/messages.d.ts +108 -0
  3. package/dist/background/report/messages.js +230 -0
  4. package/dist/background/report/render.d.ts +26 -4
  5. package/dist/background/report/render.js +56 -7
  6. package/dist/background/report/schema.d.ts +7 -1
  7. package/dist/background/report/schema.js +9 -3
  8. package/dist/background/report/stored-templates.d.ts +21 -19
  9. package/dist/background/report/stored-templates.js +20 -15
  10. package/dist/background/report/templates/morning-digest.email.en.liquid +3 -0
  11. package/dist/background/report/templates/morning-digest.email.ru.liquid +3 -0
  12. package/dist/background/report/templates/morning-digest.sample.json +8 -1
  13. package/dist/background/report/templates/morning-digest.telegram.en.liquid +3 -0
  14. package/dist/background/report/templates/morning-digest.telegram.ru.liquid +3 -0
  15. package/dist/background/report/templates/morning-digest.text.en.liquid +3 -0
  16. package/dist/background/report/templates/morning-digest.text.ru.liquid +3 -0
  17. package/dist/background/report/templates/schedule-failed.email.en.liquid +12 -0
  18. package/dist/background/report/templates/schedule-failed.email.ru.liquid +12 -0
  19. package/dist/background/report/templates/schedule-failed.sample.json +10 -0
  20. package/dist/background/report/templates/schedule-failed.telegram.en.liquid +9 -0
  21. package/dist/background/report/templates/schedule-failed.telegram.ru.liquid +9 -0
  22. package/dist/background/report/templates/schedule-failed.text.en.liquid +9 -0
  23. package/dist/background/report/templates/schedule-failed.text.ru.liquid +9 -0
  24. package/dist/background/report/templates/weekly-gaps.email.en.liquid +19 -0
  25. package/dist/background/report/templates/weekly-gaps.email.ru.liquid +19 -0
  26. package/dist/background/report/templates/weekly-gaps.sample.json +33 -0
  27. package/dist/background/report/templates/weekly-gaps.telegram.en.liquid +15 -0
  28. package/dist/background/report/templates/weekly-gaps.telegram.ru.liquid +15 -0
  29. package/dist/background/report/templates/weekly-gaps.text.en.liquid +14 -0
  30. package/dist/background/report/templates/weekly-gaps.text.ru.liquid +14 -0
  31. package/dist/background/report/view.d.ts +5 -0
  32. package/dist/background/report/view.js +9 -1
  33. package/dist/background/schedules.d.ts +10 -1
  34. package/dist/background/schedules.js +127 -30
  35. package/dist/cli/help/sections.js +1 -0
  36. package/dist/cli/schedule/schedule-command.js +3 -2
  37. package/dist/cli/templates-command.js +43 -20
  38. package/dist/domain/links.d.ts +1 -1
  39. package/dist/domain/links.js +1 -1
  40. package/dist/domain/models.d.ts +6 -0
  41. package/dist/entities/fact.d.ts +4 -0
  42. package/dist/entities/fact.js +2 -1
  43. package/dist/entities/fields.d.ts +5 -0
  44. package/dist/entities/fields.js +3 -0
  45. package/dist/entities/index.d.ts +21 -1
  46. package/dist/entities/index.js +3 -1
  47. package/dist/entities/list-results.d.ts +4 -2
  48. package/dist/entities/list-results.js +4 -2
  49. package/dist/entities/memory.d.ts +4 -0
  50. package/dist/entities/memory.js +2 -1
  51. package/dist/entities/template.d.ts +11 -0
  52. package/dist/entities/template.js +12 -0
  53. package/dist/errors/reasons.js +6 -0
  54. package/dist/meetings/mcp/index.d.ts +15 -15
  55. package/dist/store/exports.d.ts +1 -0
  56. package/dist/store/exports.js +1 -0
  57. package/dist/store/index.d.ts +3 -2
  58. package/dist/store/index.js +1 -0
  59. package/dist/store/people.d.ts +7 -0
  60. package/dist/store/people.js +4 -0
  61. package/dist/store/source-review.d.ts +21 -0
  62. package/dist/store/sqlite/accounts.d.ts +3 -1
  63. package/dist/store/sqlite/accounts.js +10 -3
  64. package/dist/store/sqlite/added-sources.d.ts +16 -0
  65. package/dist/store/sqlite/added-sources.js +22 -0
  66. package/dist/store/sqlite/bot-tokens.d.ts +11 -0
  67. package/dist/store/sqlite/bot-tokens.js +57 -0
  68. package/dist/store/sqlite/chats.js +2 -0
  69. package/dist/store/sqlite/facts.js +3 -2
  70. package/dist/store/sqlite/imported-documents.js +3 -2
  71. package/dist/store/sqlite/knowledge.js +6 -4
  72. package/dist/store/sqlite/memories.js +5 -4
  73. package/dist/store/sqlite/mention-drain.js +9 -1
  74. package/dist/store/sqlite/merged-persons.d.ts +24 -0
  75. package/dist/store/sqlite/merged-persons.js +59 -0
  76. package/dist/store/sqlite/messages.d.ts +1 -1
  77. package/dist/store/sqlite/messages.js +3 -1
  78. package/dist/store/sqlite/notes.js +5 -4
  79. package/dist/store/sqlite/open-store.js +2 -0
  80. package/dist/store/sqlite/person-links.d.ts +10 -1
  81. package/dist/store/sqlite/person-links.js +14 -6
  82. package/dist/store/sqlite/person-merges.d.ts +39 -0
  83. package/dist/store/sqlite/person-merges.js +136 -0
  84. package/dist/store/sqlite/person-preparation.js +11 -8
  85. package/dist/store/sqlite/person-resolution.js +2 -1
  86. package/dist/store/sqlite/person-scope.js +2 -1
  87. package/dist/store/sqlite/relation-list.js +3 -2
  88. package/dist/store/sqlite/reported-relations.js +6 -3
  89. package/dist/store/sqlite/source-review.d.ts +20 -1
  90. package/dist/store/sqlite/source-review.js +74 -3
  91. package/dist/store/sqlite/task-board.d.ts +6 -1
  92. package/dist/store/sqlite/task-board.js +22 -4
  93. package/dist/store/sqlite/work-tasks.js +8 -9
  94. package/dist/store/types.d.ts +2 -0
  95. package/package.json +2 -2
  96. package/parity.json +19 -0
@@ -0,0 +1,57 @@
1
+ import { NORMALIZER_VERSION, normalize } from "../normalize.js";
2
+ import { write } from "./transaction.js";
3
+ import { purgeVectorsOf } from "./vectors.js";
4
+ // Only a digit may not come before: `bot<id>:<secret>` in an API URL is the shape pasted most often.
5
+ const BOT_TOKEN = /(?<!\d)(\d{6,12}):[A-Za-z0-9_-]{30,40}(?![A-Za-z0-9_-])/g;
6
+ const MAY_HOLD = "*[0-9][0-9][0-9][0-9][0-9][0-9]:*";
7
+ const MASKED_THROUGH = "bot_tokens_masked_through";
8
+ /** A messenger bot's token keeps the bot's id, which is public, and loses its secret half. */
9
+ export const withoutBotTokens = (text) => text.replace(BOT_TOKEN, "$1:<bot token hidden>");
10
+ export const withoutBotTokensIn = (message) => {
11
+ const { replyTo } = message;
12
+ return {
13
+ ...message,
14
+ text: withoutBotTokens(message.text),
15
+ ...(replyTo ? { replyTo: { ...replyTo, text: withoutBotTokens(replyTo.text) } } : {}),
16
+ };
17
+ };
18
+ /**
19
+ * Masks the tokens in messages this build did not write: those stored before it, and those an older build saves
20
+ * later. On every open, from the newest message checked last time; a store with nothing new costs two index probes.
21
+ * The scan reads outside a write, so the first one, over the whole archive, does not hold other writers back.
22
+ */
23
+ export const maskStoredBotTokens = (context) => {
24
+ const { database, now } = context;
25
+ const through = Number(database.prepare("SELECT value FROM store_settings WHERE key = ?").get(MASKED_THROUGH)?.value ?? 0);
26
+ const newest = Number(database.prepare("SELECT max(id) AS id FROM messages").get()?.id ?? 0);
27
+ if (newest <= through)
28
+ return 0;
29
+ const messages = database
30
+ .prepare("SELECT id, text, reply_to FROM messages WHERE id > ? AND id <= ? AND (text GLOB ? OR reply_to GLOB ?)")
31
+ .all(through, newest, MAY_HOLD, MAY_HOLD)
32
+ .filter((row) => masks(row.text) || masks(row.reply_to));
33
+ const revisions = database
34
+ .prepare("SELECT id, text FROM message_revisions WHERE message_id > ? AND message_id <= ? AND text GLOB ?")
35
+ .all(through, newest, MAY_HOLD)
36
+ .filter((row) => masks(row.text));
37
+ write(database, () => {
38
+ // Only the text read above: a message another process changed since then was written by a build that masks.
39
+ const message = database.prepare(`UPDATE messages SET text = ?, normalized_text = ?, normalizer_version = ?, reply_to = ?
40
+ WHERE id = ? AND text = ? AND reply_to IS ?`);
41
+ for (const row of messages) {
42
+ const text = withoutBotTokens(String(row.text));
43
+ const quote = row.reply_to == null ? null : withoutBotTokens(String(row.reply_to));
44
+ const { changes } = message.run(text, normalize(text), NORMALIZER_VERSION, quote, Number(row.id), row.text, row.reply_to);
45
+ if (Number(changes) > 0)
46
+ purgeVectorsOf(context, Number(row.id));
47
+ }
48
+ const revision = database.prepare("UPDATE message_revisions SET text = ? WHERE id = ? AND text = ?");
49
+ for (const row of revisions)
50
+ revision.run(withoutBotTokens(String(row.text)), Number(row.id), row.text);
51
+ database
52
+ .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
53
+ .run(MASKED_THROUGH, String(newest), now());
54
+ });
55
+ return messages.length + revisions.length;
56
+ };
57
+ const masks = (value) => value != null && withoutBotTokens(String(value)) !== value;
@@ -150,6 +150,7 @@ export const upsertChat = (context, accountKey, chat) => {
150
150
  metadata: mergedMetadata(stored?.metadata ?? null, chat.providerMetadata),
151
151
  membershipState: chat.membershipState === "member" ? null : (chat.membershipState ?? null),
152
152
  ...stateOf(chat, now()),
153
+ ...(chat.searchable === false ? { searchable: 0 } : {}),
153
154
  createdAt: now(),
154
155
  updatedAt: now(),
155
156
  })
@@ -157,6 +158,7 @@ export const upsertChat = (context, accountKey, chat) => {
157
158
  target: [chats.accountId, chats.externalId],
158
159
  set: {
159
160
  kind: sql `excluded.kind`,
161
+ ...(chat.searchable === false ? { searchable: 0 } : {}),
160
162
  ...(chat.parentChatId === undefined ? {} : { parentChatId: sql `excluded.parent_chat_id` }),
161
163
  scope: sql `coalesce(excluded.scope, ${chats.scope})`,
162
164
  ...(chat.title === undefined ? {} : { title: sql `excluded.title`, titleFolded: sql `excluded.title_folded` }),
@@ -6,6 +6,7 @@ import { proposedBySql, proposerOf } from "./actors.js";
6
6
  import { evidenceSourcesOf } from "./evidence-sources.js";
7
7
  import { linkKind } from "./link-kinds.js";
8
8
  import { authorActor, authorOf, dropLinksOf, erase, evidenceOf, keepHighestId, linkEvidence, nextId, projectOf, subjectOf, } from "./memories.js";
9
+ import { idsOf } from "./merged-persons.js";
9
10
  import { requiredThing } from "./notes.js";
10
11
  import { closeSourceReviews, eraseSourceReviews, sourceReviewOf } from "./source-review-marks.js";
11
12
  import { write } from "./transaction.js";
@@ -139,9 +140,9 @@ export const factOperationsOver = (context) => {
139
140
  const order = options.order === "created" ? "f.created_at" : "coalesce(f.occurred_at, f.created_at)";
140
141
  return database
141
142
  .prepare(`${NAMED} WHERE f.deleted_at IS NULL AND (? IS NULL OR f.type = ?) AND (? IS NULL OR f.project_id = ?) ` +
142
- "AND (? IS NULL OR (f.subject_type = ? AND f.subject_id = ?)) AND (? IS NULL OR f.status = ?) " +
143
+ "AND (? IS NULL OR (f.subject_type = ? AND f.subject_id IN (SELECT value FROM json_each(?)))) AND (? IS NULL OR f.status = ?) " +
143
144
  `AND ${by.sql} ORDER BY ${order} DESC, f.id DESC LIMIT ?`)
144
- .all(options.type ?? null, options.type ?? null, project?.id ?? null, project?.id ?? null, subject?.type ?? null, subject?.type ?? null, subject?.id ?? null, options.status ?? null, options.status ?? null, ...by.params, Math.min(Math.max(options.limit ?? 100, 1), 500))
145
+ .all(options.type ?? null, options.type ?? null, project?.id ?? null, project?.id ?? null, subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, options.status ?? null, options.status ?? null, ...by.params, Math.min(Math.max(options.limit ?? 100, 1), 500))
145
146
  .map(factOf);
146
147
  },
147
148
  accept: (reference, by, reason) => {
@@ -1,5 +1,6 @@
1
1
  import { defineQuery, validateQuery } from "@wirecat/cli-base/query";
2
2
  import { normalizeTag } from "../../domain/tags.js";
3
+ import { idsOf } from "./merged-persons.js";
3
4
  import { queryFilter } from "./query-filter.js";
4
5
  import { canonicalTagNamed } from "./tags.js";
5
6
  import { thingOf } from "./things.js";
@@ -44,8 +45,8 @@ export const importedDocumentWhere = (database, query) => {
44
45
  return { sql: "0", params: [] };
45
46
  return {
46
47
  sql: "EXISTS (SELECT 1 FROM links l WHERE l.from_type = 'document' AND l.from_id = d.id " +
47
- "AND l.to_type = ? AND l.to_id = ?)",
48
- params: [found.type, found.id],
48
+ "AND l.to_type = ? AND l.to_id IN (SELECT value FROM json_each(?)))",
49
+ params: [found.type, idsOf(database, found.type, found.id)],
49
50
  };
50
51
  },
51
52
  },
@@ -16,6 +16,7 @@ import { forgetEvidenceToRow } from "./evidence-signature.js";
16
16
  import { LABELLED } from "./labelled.js";
17
17
  import { linkKind, RELATION_KINDS } from "./link-kinds.js";
18
18
  import { meetingProjectsStoreOver } from "./meeting-projects.js";
19
+ import { idsOf } from "./merged-persons.js";
19
20
  import { holdingText } from "./note-index.js";
20
21
  import { insertLink, linkOf } from "./notes.js";
21
22
  import { organizationOf, organizationsStoreOver } from "./organizations.js";
@@ -65,6 +66,7 @@ const RELATED = ["person", "organization", "project", "task"];
65
66
  const DEALS = ["deal", "lead"];
66
67
  export const knowledgeStoreOver = (context) => {
67
68
  const { database, now } = context;
69
+ const ids = (thing) => thing ? idsOf(database, thing.type, thing.id) : null;
68
70
  const account = (key) => {
69
71
  const row = database
70
72
  .prepare("SELECT id FROM accounts WHERE provider=? AND external_id=?")
@@ -332,9 +334,9 @@ export const knowledgeStoreOver = (context) => {
332
334
  return { items: [], hasMore: false };
333
335
  const text = options.search === undefined ? undefined : holdingText("note", "id", options.search);
334
336
  const rows = database
335
- .prepare("SELECT * FROM notes WHERE deleted_at IS NULL AND (? IS NULL OR (notable_type = ? AND notable_id = ?)) " +
337
+ .prepare("SELECT * FROM notes WHERE deleted_at IS NULL AND (? IS NULL OR (notable_type = ? AND notable_id IN (SELECT value FROM json_each(?)))) " +
336
338
  `${text ? `AND ${text.sql} ` : ""}ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`)
337
- .all(thing?.type ?? null, thing?.type ?? null, thing?.id ?? null, ...(text?.params ?? []), limit + 1, offset);
339
+ .all(thing?.type ?? null, thing?.type ?? null, ids(thing), ...(text?.params ?? []), limit + 1, offset);
338
340
  const items = rows.slice(0, limit).flatMap((row) => annotationOf(row) ?? []);
339
341
  return { items, hasMore: rows.length > limit };
340
342
  },
@@ -520,8 +522,8 @@ export const knowledgeStoreOver = (context) => {
520
522
  return database
521
523
  .prepare(
522
524
  // Live ones first: a long history of withdrawn links never pushes them past the cap.
523
- `${RELATIONS} AND ${notOverriddenSql("links")} AND (? IS NULL OR (from_type=? AND from_id=?) OR (to_type=? AND to_id=?)) ORDER BY deleted_at IS NOT NULL, created_at, id LIMIT 500`)
524
- .all(thing?.type ?? null, thing?.type ?? null, thing?.id ?? null, thing?.type ?? null, thing?.id ?? null)
525
+ `${RELATIONS} AND ${notOverriddenSql("links")} AND (? IS NULL OR (from_type=? AND from_id IN (SELECT value FROM json_each(?))) OR (to_type=? AND to_id IN (SELECT value FROM json_each(?)))) ORDER BY deleted_at IS NOT NULL, created_at, id LIMIT 500`)
526
+ .all(thing?.type ?? null, thing?.type ?? null, ids(thing), thing?.type ?? null, ids(thing))
525
527
  .map((row) => relationOf(linkOf(database, row)));
526
528
  },
527
529
  removeRelation: async (key, id, by) => {
@@ -6,6 +6,7 @@ import { botNamed, ownerPerson, proposedBySql, proposerOf } from "./actors.js";
6
6
  import { assertQuoted, evidenceInputOf, evidenceMetadata, evidenceSignature, forgetEvidenceToRow, } from "./evidence-signature.js";
7
7
  import { evidenceSourcesOf } from "./evidence-sources.js";
8
8
  import { linkKind } from "./link-kinds.js";
9
+ import { idsOf } from "./merged-persons.js";
9
10
  import { CORPORA, corpusIndexState, drainCorpus } from "./note-index.js";
10
11
  import { requiredThing } from "./notes.js";
11
12
  import { closeSourceReviews, eraseSourceReviews, sourceReviewOf } from "./source-review-marks.js";
@@ -267,10 +268,10 @@ export const memoriesStoreOver = (context) => {
267
268
  const project = options.project === undefined ? null : projectId(database, options.project);
268
269
  const by = proposedBySql("m.author_type", "m.author_id", options.proposedBy);
269
270
  return database
270
- .prepare(`${NAMED} WHERE m.deleted_at IS NULL AND (? IS NULL OR (m.subject_type = ? AND m.subject_id = ?)) ` +
271
+ .prepare(`${NAMED} WHERE m.deleted_at IS NULL AND (? IS NULL OR (m.subject_type = ? AND m.subject_id IN (SELECT value FROM json_each(?)))) ` +
271
272
  "AND (? IS NULL OR m.project_id = ?) AND (? IS NULL OR m.kind = ?) AND (? IS NULL OR m.status = ?) AND (? IS NULL OR m.scope = ?) " +
272
273
  `AND ${by.sql} ORDER BY m.created_at DESC, m.id DESC LIMIT ?`)
273
- .all(subject?.type ?? null, subject?.type ?? null, subject?.id ?? null, project, project, options.kind ?? null, options.kind ?? null, options.status ?? null, options.status ?? null, options.scope ?? null, options.scope ?? null, ...by.params, Math.min(Math.max(options.limit ?? 100, 1), 500))
274
+ .all(subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, project, project, options.kind ?? null, options.kind ?? null, options.status ?? null, options.status ?? null, options.scope ?? null, options.scope ?? null, ...by.params, Math.min(Math.max(options.limit ?? 100, 1), 500))
274
275
  .map(memoryOf);
275
276
  },
276
277
  update: async (reference, change) => write(database, () => {
@@ -322,9 +323,9 @@ export const memoriesStoreOver = (context) => {
322
323
  return database
323
324
  .prepare("SELECT m.*, b.name AS author_name, b.kind AS author_kind FROM memory_words w JOIN memories m ON m.id = w.rowid " +
324
325
  "LEFT JOIN bots b ON m.author_type = 'bot' AND b.id = m.author_id WHERE memory_words MATCH ? " +
325
- "AND m.deleted_at IS NULL AND (? IS NULL OR (m.subject_type = ? AND m.subject_id = ?)) " +
326
+ "AND m.deleted_at IS NULL AND (? IS NULL OR (m.subject_type = ? AND m.subject_id IN (SELECT value FROM json_each(?)))) " +
326
327
  "AND (? IS NULL OR m.scope = ?) ORDER BY bm25(memory_words), m.id LIMIT ?")
327
- .all(match, subject?.type ?? null, subject?.type ?? null, subject?.id ?? null, scope ?? null, scope ?? null, Math.min(Math.max(limit, 1), 200))
328
+ .all(match, subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, scope ?? null, scope ?? null, Math.min(Math.max(limit, 1), 200))
328
329
  .map(memoryOf);
329
330
  },
330
331
  indexState: async () => corpusIndexState(database, CORPORA.memory),
@@ -2,6 +2,7 @@ import { findMentions, MENTION_KINDS, MENTION_VERSIONS, oneTrackedLinkPerSite, t
2
2
  import { findNames, findUnknownNames, nameIndex } from "../../domain/person-names.js";
3
3
  import { createStemmer } from "../../search/stem.js";
4
4
  import { mentionField, mentionText } from "./lucene-fields.js";
5
+ import { currentPerson } from "./merged-persons.js";
5
6
  import { storePhoneCountries } from "./phone-countries.js";
6
7
  import { placeOf } from "./place-key.js";
7
8
  /** Mentions a store write finds before it commits: an older binary may have queued thousands. */
@@ -70,8 +71,15 @@ export const knownPeople = (database) => {
70
71
  "JOIN met ON met.id = l.person_id WHERE a.aliasable_type = 'identity'")
71
72
  .all();
72
73
  const people = new Map();
74
+ const owners = new Set(database
75
+ .prepare("SELECT id FROM persons WHERE owner = 1")
76
+ .all()
77
+ .map((row) => Number(row.id)));
73
78
  for (const row of rows) {
74
- const id = Number(row.id);
79
+ // Only a person's own alias can sit on a merged-away person; it names whoever that person is now.
80
+ const id = Number(row.alias) ? currentPerson(database, Number(row.id)) : Number(row.id);
81
+ if (owners.has(id))
82
+ continue;
75
83
  const person = people.get(id) ?? { id, names: [], aliases: [] };
76
84
  (Number(row.alias) ? person.aliases : person.names).push(String(row.name));
77
85
  people.set(id, person);
@@ -0,0 +1,24 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ /** Moves that take identities apart, never a merge. */
3
+ export declare const SEPARATIONS: readonly ["unlink", "split", "undo-merge"];
4
+ /**
5
+ * Whether a logged move joined two people, judged by what it did: a merge empties its person, so every other
6
+ * identity on it then moves the same way next. An unlink leaves the rest behind, which is how an unlink stored before
7
+ * it had its own method, or one identity linked out of a person, is told apart. The owner's person has no move of its
8
+ * own, so the person a move goes to says nothing.
9
+ */
10
+ export declare const mergeSql: (event: string) => string;
11
+ /**
12
+ * A person every identity left by a merge, so another person holds them now. The row stays so that undoing the merge
13
+ * gives the uid back; a person added by name has no identity and no move, and stays visible.
14
+ */
15
+ export declare const mergedAwaySql: (person: string) => string;
16
+ /** The person `pk` is now: itself, or where its identities went, by the latest merge of each merged-away person. */
17
+ export declare const currentPerson: (database: CacheDatabase, pk: number) => number;
18
+ /** The person `pk` is now, then every merged-away person whose references now mean it. */
19
+ export declare const samePersons: (database: CacheDatabase, pk: number) => number[];
20
+ /**
21
+ * The ids a filter on `type`/`id` covers, as JSON for `IN (SELECT value FROM json_each(?))`: a person with everyone
22
+ * merged into them, since rows naming a merged-away person stay as they were written, so undoing the merge loses none.
23
+ */
24
+ export declare const idsOf: (database: CacheDatabase, type: string, id: number) => string;
@@ -0,0 +1,59 @@
1
+ /** Moves that take identities apart, never a merge. */
2
+ export const SEPARATIONS = ["unlink", "split", "undo-merge"];
3
+ /**
4
+ * Whether a logged move joined two people, judged by what it did: a merge empties its person, so every other
5
+ * identity on it then moves the same way next. An unlink leaves the rest behind, which is how an unlink stored before
6
+ * it had its own method, or one identity linked out of a person, is told apart. The owner's person has no move of its
7
+ * own, so the person a move goes to says nothing.
8
+ */
9
+ export const mergeSql = (event) => `(${event}.from_person_id IS NOT NULL AND ${event}.from_person_id <> ${event}.to_person_id ` +
10
+ `AND ${event}.method NOT IN (${SEPARATIONS.map((method) => `'${method}'`).join(", ")}) ` +
11
+ `AND NOT EXISTS (SELECT 1 FROM identity_link_events stay WHERE stay.to_person_id = ${event}.from_person_id ` +
12
+ `AND stay.identity_id <> ${event}.identity_id AND stay.id < ${event}.id ` +
13
+ `AND stay.id = (SELECT max(s.id) FROM identity_link_events s WHERE s.identity_id = stay.identity_id ` +
14
+ `AND s.id < ${event}.id) ` +
15
+ `AND NOT EXISTS (SELECT 1 FROM identity_link_events went WHERE went.identity_id = stay.identity_id ` +
16
+ `AND went.from_person_id = ${event}.from_person_id AND went.to_person_id = ${event}.to_person_id ` +
17
+ `AND went.id = (SELECT min(w.id) FROM identity_link_events w WHERE w.identity_id = stay.identity_id ` +
18
+ `AND w.id > ${event}.id))))`;
19
+ /**
20
+ * A person every identity left by a merge, so another person holds them now. The row stays so that undoing the merge
21
+ * gives the uid back; a person added by name has no identity and no move, and stays visible.
22
+ */
23
+ export const mergedAwaySql = (person) => `(${person}.owner = 0 AND NOT EXISTS (SELECT 1 FROM identity_links ml WHERE ml.person_id = ${person}.id) ` +
24
+ `AND EXISTS (SELECT 1 FROM identity_link_events me WHERE me.from_person_id = ${person}.id AND ${mergeSql("me")}))`;
25
+ const LATEST_MOVE = (person) => `(SELECT e.to_person_id FROM identity_link_events e WHERE e.from_person_id = ${person}.id AND ${mergeSql("e")}
26
+ ORDER BY e.id DESC LIMIT 1)`;
27
+ /** The person `pk` is now: itself, or where its identities went, by the latest merge of each merged-away person. */
28
+ export const currentPerson = (database, pk) => {
29
+ const seen = new Set();
30
+ let at = pk;
31
+ while (!seen.has(at)) {
32
+ seen.add(at);
33
+ const next = database
34
+ .prepare(`SELECT ${LATEST_MOVE("p")} AS next FROM persons p WHERE p.id = ? AND ${mergedAwaySql("p")}`)
35
+ .get(at);
36
+ if (next?.next == null)
37
+ return at;
38
+ at = Number(next.next);
39
+ }
40
+ return at;
41
+ };
42
+ /** The person `pk` is now, then every merged-away person whose references now mean it. */
43
+ export const samePersons = (database, pk) => {
44
+ const found = [currentPerson(database, pk)];
45
+ const into = database.prepare(`SELECT p.id FROM persons p WHERE p.id IN (SELECT from_person_id FROM identity_link_events WHERE to_person_id = ?)
46
+ AND ${mergedAwaySql("p")} AND ${LATEST_MOVE("p")} = ?`);
47
+ for (let at = 0; at < found.length; at++) {
48
+ const target = found[at];
49
+ for (const row of into.all(target, target))
50
+ if (!found.includes(Number(row.id)))
51
+ found.push(Number(row.id));
52
+ }
53
+ return found;
54
+ };
55
+ /**
56
+ * The ids a filter on `type`/`id` covers, as JSON for `IN (SELECT value FROM json_each(?))`: a person with everyone
57
+ * merged into them, since rows naming a merged-away person stay as they were written, so undoing the merge loses none.
58
+ */
59
+ export const idsOf = (database, type, id) => JSON.stringify(type === "person" ? samePersons(database, id) : [id]);
@@ -1,7 +1,7 @@
1
1
  import type { Delivery, Id, Message, PersonReaction, PollVote, Provider, Reactions, Reactor } from "../../domain/models.js";
2
2
  import type { AccountKey, DeletionScope } from "../types.js";
3
3
  import type { StoreContext } from "./open.js";
4
- export declare const upsertMessage: (context: StoreContext, key: AccountKey, accountKey: number, chatKey: number, message: Message, via: string, seenAt?: number) => boolean;
4
+ export declare const upsertMessage: (context: StoreContext, key: AccountKey, accountKey: number, chatKey: number, received: Message, via: string, seenAt?: number) => boolean;
5
5
  /**
6
6
  * One more unread for a message from someone else that the store first saw now, sent after the messenger's count was
7
7
  * taken. A chat the messenger never gave a count for is left alone: the store would count its whole history.
@@ -1,5 +1,6 @@
1
1
  import { validCounter } from "../../domain/counters.js";
2
2
  import { NORMALIZER_VERSION, normalize } from "../normalize.js";
3
+ import { withoutBotTokensIn } from "./bot-tokens.js";
3
4
  import { findChatPk } from "./chats.js";
4
5
  import { applyCounterObservations } from "./counters.js";
5
6
  import { and, eq, isNull, sql } from "./drizzle/core.js";
@@ -113,8 +114,9 @@ const fieldsOf = (message, sender) => ({
113
114
  normalizedText: normalize(message.text),
114
115
  normalizerVersion: NORMALIZER_VERSION,
115
116
  });
116
- export const upsertMessage = (context, key, accountKey, chatKey, message, via, seenAt) => {
117
+ export const upsertMessage = (context, key, accountKey, chatKey, received, via, seenAt) => {
117
118
  const { orm, now } = context;
119
+ const message = withoutBotTokensIn(received);
118
120
  const statements = statementsOf(orm);
119
121
  const sender = message.senderId === null || message.senderIsChat
120
122
  ? null
@@ -15,6 +15,7 @@ import { PREFERRED_FILE, syncFile } from "./files.js";
15
15
  import { importedDocumentWhere } from "./imported-documents.js";
16
16
  import { LINK_KINDS, LINK_ORIGINS, linkKind } from "./link-kinds.js";
17
17
  import { reviewLink } from "./link-reviews.js";
18
+ import { currentPerson, idsOf } from "./merged-persons.js";
18
19
  import { dateFileNotes } from "./note-dates.js";
19
20
  import { holdingText } from "./note-index.js";
20
21
  import { addTags, ensureTag, labelsOf } from "./tags.js";
@@ -125,7 +126,7 @@ const personsNamed = (database, key) => {
125
126
  .all(key, key);
126
127
  for (const row of aliases)
127
128
  if (row.person_id != null)
128
- found.add(Number(row.person_id));
129
+ found.add(currentPerson(database, Number(row.person_id)));
129
130
  return found;
130
131
  };
131
132
  const resolveKey = (database, key) => {
@@ -563,7 +564,7 @@ export const notesStoreOver = (context) => {
563
564
  const documentText = options.search === undefined ? undefined : holdingText("document", "d.id", options.search);
564
565
  const noteText = options.search === undefined ? undefined : holdingText("note", "n.id", options.search);
565
566
  const aboutType = about?.type ?? null;
566
- const aboutId = about?.id ?? null;
567
+ const aboutId = about ? idsOf(database, about.type, about.id) : null;
567
568
  const files = options.source === "internal"
568
569
  ? []
569
570
  : database
@@ -577,7 +578,7 @@ export const notesStoreOver = (context) => {
577
578
  "JOIN documents d ON d.id = f.document_id JOIN accounts a ON a.id = f.account_id " +
578
579
  "WHERE f.deleted_at IS NULL AND d.deleted_at IS NULL AND f.account_id = ? AND ? IS NOT NULL ") +
579
580
  "AND coalesce(json_extract(d.metadata, '$.catalog.active'), 1)=1 " +
580
- `AND (? IS NULL OR EXISTS (SELECT 1 FROM links l WHERE l.from_type = 'document' AND l.from_id = d.id AND l.kind = ${linkKind("about")} AND l.to_type = ? AND l.to_id = ?)) ` +
581
+ `AND (? IS NULL OR EXISTS (SELECT 1 FROM links l WHERE l.from_type = 'document' AND l.from_id = d.id AND l.kind = ${linkKind("about")} AND l.to_type = ? AND l.to_id IN (SELECT value FROM json_each(?)))) ` +
581
582
  `${documentText ? `AND ${documentText.sql} ` : ""}ORDER BY d.created_at DESC, d.id DESC LIMIT ?`)
582
583
  .all(folder, folder, aboutType, aboutType, aboutId, ...(documentText?.params ?? []), limit + offset + 1)
583
584
  .map(documentOf);
@@ -585,7 +586,7 @@ export const notesStoreOver = (context) => {
585
586
  ? []
586
587
  : database
587
588
  .prepare("SELECT n.* FROM notes n WHERE n.deleted_at IS NULL " +
588
- `AND (? IS NULL OR (n.notable_type = ? AND n.notable_id = ?) OR EXISTS (SELECT 1 FROM links l WHERE l.from_type = 'note' AND l.from_id = n.id AND l.kind = ${linkKind("about")} AND l.to_type = ? AND l.to_id = ?)) ` +
589
+ `AND (? IS NULL OR (n.notable_type = ? AND n.notable_id IN (SELECT value FROM json_each(?))) OR EXISTS (SELECT 1 FROM links l WHERE l.from_type = 'note' AND l.from_id = n.id AND l.kind = ${linkKind("about")} AND l.to_type = ? AND l.to_id IN (SELECT value FROM json_each(?)))) ` +
589
590
  `${noteText ? `AND ${noteText.sql} ` : ""}ORDER BY n.created_at DESC, n.id DESC LIMIT ?`)
590
591
  .all(aboutType, aboutType, aboutId, aboutType, aboutId, ...(noteText?.params ?? []), limit + offset + 1)
591
592
  .map(noteOf);
@@ -8,6 +8,7 @@ import { storeCapable } from "../open.js";
8
8
  import { refuseOwnerStoreInTests, storePath } from "../path.js";
9
9
  import { sharedConfigPath } from "../shared-config.js";
10
10
  import { backfillNormalized, pendingNormalization } from "./backfill.js";
11
+ import { maskStoredBotTokens } from "./bot-tokens.js";
11
12
  import { fillFiles } from "./files.js";
12
13
  import { fillFolded } from "./folded.js";
13
14
  import { fillJoinKeys } from "./join-keys.js";
@@ -102,6 +103,7 @@ export const openStoreContext = async (options = {}) => {
102
103
  moveSuggestedLinks(database, now);
103
104
  movePaymentFacts({ ...opened, now, decisions });
104
105
  purgeTestAccounts({ ...opened, now, decisions }, warn);
106
+ maskStoredBotTokens({ ...opened, now, decisions });
105
107
  const pending = pendingNormalization(database);
106
108
  if (pending > 0 && pending <= BACKFILL_ON_OPEN)
107
109
  backfillNormalized(database);
@@ -1,10 +1,19 @@
1
1
  import type { Id, Page } from "../../domain/models.js";
2
2
  import type { IdentityRef, LinkOptions, PersonRecord, StoredHit } from "../types.js";
3
3
  import type { StoreContext } from "./open.js";
4
- /** A person by the uid a `person:` reference holds, with every identity linked to them. */
4
+ export declare const required: (context: StoreContext, ref: IdentityRef) => {
5
+ pk: number;
6
+ personPk: number;
7
+ };
8
+ export declare const recordOf: ({ orm }: StoreContext, personPk: number) => PersonRecord;
9
+ /**
10
+ * A person by the uid a `person:` reference holds, with every identity linked to them. A uid merged into someone
11
+ * else answers with that person, and `mergedInto` says so.
12
+ */
5
13
  export declare const personByUid: (context: StoreContext, uid: string) => PersonRecord | undefined;
6
14
  /** The person an identity belongs to, with every identity linked to them. */
7
15
  export declare const personOf: (context: StoreContext, ref: IdentityRef) => PersonRecord | undefined;
16
+ export declare const move: (context: StoreContext, identityPk: number, from: number, to: number, { method, by }: LinkOptions) => void;
8
17
  /**
9
18
  * A reviewed meeting participant association moves only its selected identity. Only the owner may move it back
10
19
  * over a separation the owner made.
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { and, eq, inArray, isNull, sql } from "./drizzle/core.js";
3
3
  import { identityOf } from "./identities.js";
4
+ import { currentPerson } from "./merged-persons.js";
4
5
  import { resolvePersonLinks } from "./person-resolution.js";
5
6
  import { identitySeparated, separated } from "./person-separation.js";
6
7
  import { accountIdentities, accounts, chats, identities, identityLinkEvents, identityLinks, messages, persons, } from "./schema.js";
@@ -11,13 +12,13 @@ const identityRow = ({ orm }, { provider, id }) => orm
11
12
  .innerJoin(identityLinks, eq(identityLinks.identityId, identities.id))
12
13
  .where(and(eq(identities.provider, provider), eq(identities.externalId, id)))
13
14
  .get();
14
- const required = (context, ref) => {
15
+ export const required = (context, ref) => {
15
16
  const found = identityRow(context, ref);
16
17
  if (!found)
17
18
  throw new CliError("not_found", `no ${ref.provider} person ${ref.id} in the store`);
18
19
  return found;
19
20
  };
20
- const recordOf = ({ orm }, personPk) => {
21
+ export const recordOf = ({ orm }, personPk) => {
21
22
  const person = orm.select().from(persons).where(eq(persons.id, personPk)).get();
22
23
  if (!person)
23
24
  throw new CliError("not_found", "that person is not in the store");
@@ -58,19 +59,26 @@ const recordOf = ({ orm }, personPk) => {
58
59
  });
59
60
  return { uid: String(person.id), name: person.name, identities: identitiesOf };
60
61
  };
61
- /** A person by the uid a `person:` reference holds, with every identity linked to them. */
62
+ /**
63
+ * A person by the uid a `person:` reference holds, with every identity linked to them. A uid merged into someone
64
+ * else answers with that person, and `mergedInto` says so.
65
+ */
62
66
  export const personByUid = (context, uid) => {
63
67
  if (!/^[1-9]\d*$/.test(uid) || !Number.isSafeInteger(Number(uid)))
64
68
  return undefined;
65
69
  const found = context.database.prepare("SELECT id AS pk FROM persons WHERE id = ?").get(uid);
66
- return found ? recordOf(context, Number(found.pk)) : undefined;
70
+ if (!found)
71
+ return undefined;
72
+ const current = currentPerson(context.database, Number(found.pk));
73
+ const record = recordOf(context, current);
74
+ return current === Number(found.pk) ? record : { ...record, mergedInto: String(current) };
67
75
  };
68
76
  /** The person an identity belongs to, with every identity linked to them. */
69
77
  export const personOf = (context, ref) => {
70
78
  const found = identityRow(context, ref);
71
79
  return found ? recordOf(context, found.personPk) : undefined;
72
80
  };
73
- const move = (context, identityPk, from, to, { method, by }) => {
81
+ export const move = (context, identityPk, from, to, { method, by }) => {
74
82
  const at = context.now();
75
83
  context.orm
76
84
  .update(identityLinks)
@@ -190,7 +198,7 @@ export const unlinkIdentity = (context, ref, options) => {
190
198
  .values({ name: named?.name ?? null, createdAt: at, updatedAt: at })
191
199
  .returning({ pk: persons.id })
192
200
  .get()?.pk);
193
- move(context, found.pk, found.personPk, alone, options);
201
+ move(context, found.pk, found.personPk, alone, { ...options, method: "unlink" });
194
202
  return recordOf(context, alone);
195
203
  };
196
204
  /** Messages that name the person: by id where the messenger said so, or by `@username` in the text. */
@@ -0,0 +1,39 @@
1
+ import type { IdentityRef, PersonRecord } from "../types.js";
2
+ import type { StoreContext } from "./open.js";
3
+ export interface PersonMerge {
4
+ /** `merge:<to>-<from>`, what `undoMerge` takes back. */
5
+ id: string;
6
+ from: string;
7
+ to: string;
8
+ identities: (IdentityRef & {
9
+ name: string | null;
10
+ })[];
11
+ method: string;
12
+ by: string;
13
+ at: string;
14
+ }
15
+ export declare const mergeId: (to: number | string, from: number | string) => string;
16
+ /** The two uids a `merge:<to>-<from>` id names. */
17
+ export declare const parseMergeId: (id: string) => {
18
+ to: string;
19
+ from: string;
20
+ };
21
+ /**
22
+ * The people merged into this person, each with the identities from it that are still here. Grouped by person, not
23
+ * by time: a merge stamps each identity on its own.
24
+ */
25
+ export declare const merges: (context: StoreContext, uid: string) => PersonMerge[];
26
+ /**
27
+ * Moves the identities that came from `from` and are still on `to` back to `from`, as the owner's move, so no
28
+ * automatic link joins them again. One the owner split or unlinked off since stays where the owner put it. Refused
29
+ * with `identity.stale` when one left `to` by a merge: undoing would take it from wherever it is now.
30
+ *
31
+ * `by` is `"owner"` only on a path that established the owner ran it: an agent's call must never pass it.
32
+ */
33
+ export declare const undoMerge: (context: StoreContext, toUid: string, fromUid: string, by: string) => PersonRecord;
34
+ /**
35
+ * Moves the chosen identities to one new person, as the owner's move; the person keeps the rest.
36
+ *
37
+ * `by` is `"owner"` only on a path that established the owner ran it: an agent's call must never pass it.
38
+ */
39
+ export declare const split: (context: StoreContext, uid: string, refs: IdentityRef[], by: string) => PersonRecord;