@wirecat/cli-core 0.614.0 → 0.616.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 (106) hide show
  1. package/CHANGELOG.md +105 -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 +41 -5
  5. package/dist/background/report/render.js +115 -25
  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 +66 -0
  9. package/dist/background/report/stored-templates.js +85 -0
  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 +157 -0
  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 +13 -2
  34. package/dist/background/schedules.js +128 -30
  35. package/dist/cli/help/sections.js +1 -0
  36. package/dist/cli/index.d.ts +2 -1
  37. package/dist/cli/index.js +1 -1
  38. package/dist/cli/schedule/schedule-command.d.ts +2 -0
  39. package/dist/cli/schedule/schedule-command.js +21 -2
  40. package/dist/cli/shared-command-exports.d.ts +1 -0
  41. package/dist/cli/shared-command-exports.js +2 -0
  42. package/dist/cli/templates-command.d.ts +16 -0
  43. package/dist/cli/templates-command.js +266 -0
  44. package/dist/domain/links.d.ts +1 -1
  45. package/dist/domain/links.js +1 -1
  46. package/dist/entities/fact.d.ts +4 -0
  47. package/dist/entities/fact.js +2 -1
  48. package/dist/entities/fields.d.ts +5 -0
  49. package/dist/entities/fields.js +3 -0
  50. package/dist/entities/index.d.ts +21 -1
  51. package/dist/entities/index.js +3 -1
  52. package/dist/entities/list-results.d.ts +4 -2
  53. package/dist/entities/list-results.js +4 -2
  54. package/dist/entities/memory.d.ts +4 -0
  55. package/dist/entities/memory.js +2 -1
  56. package/dist/entities/template.d.ts +11 -0
  57. package/dist/entities/template.js +12 -0
  58. package/dist/errors/reasons.js +13 -0
  59. package/dist/meetings/mcp/index.d.ts +15 -15
  60. package/dist/services/metadata.d.ts +1 -1
  61. package/dist/store/exports.d.ts +2 -0
  62. package/dist/store/exports.js +2 -0
  63. package/dist/store/index.d.ts +4 -2
  64. package/dist/store/index.js +1 -0
  65. package/dist/store/people.d.ts +7 -0
  66. package/dist/store/people.js +4 -0
  67. package/dist/store/source-review.d.ts +21 -0
  68. package/dist/store/sqlite/accounts.d.ts +3 -1
  69. package/dist/store/sqlite/accounts.js +10 -3
  70. package/dist/store/sqlite/added-sources.d.ts +16 -0
  71. package/dist/store/sqlite/added-sources.js +22 -0
  72. package/dist/store/sqlite/facts.js +3 -2
  73. package/dist/store/sqlite/imported-documents.js +3 -2
  74. package/dist/store/sqlite/knowledge.js +6 -4
  75. package/dist/store/sqlite/manifest.js +1 -0
  76. package/dist/store/sqlite/memories.js +5 -4
  77. package/dist/store/sqlite/mention-drain.js +9 -1
  78. package/dist/store/sqlite/merged-persons.d.ts +24 -0
  79. package/dist/store/sqlite/merged-persons.js +59 -0
  80. package/dist/store/sqlite/migrations.generated.js +8 -0
  81. package/dist/store/sqlite/notes.js +5 -4
  82. package/dist/store/sqlite/person-links.d.ts +10 -1
  83. package/dist/store/sqlite/person-links.js +14 -6
  84. package/dist/store/sqlite/person-merges.d.ts +39 -0
  85. package/dist/store/sqlite/person-merges.js +136 -0
  86. package/dist/store/sqlite/person-preparation.js +11 -8
  87. package/dist/store/sqlite/person-resolution.js +2 -1
  88. package/dist/store/sqlite/person-scope.js +2 -1
  89. package/dist/store/sqlite/relation-list.js +3 -2
  90. package/dist/store/sqlite/reported-relations.js +6 -3
  91. package/dist/store/sqlite/schema/templates.d.ts +242 -0
  92. package/dist/store/sqlite/schema/templates.js +23 -0
  93. package/dist/store/sqlite/schema.d.ts +1 -0
  94. package/dist/store/sqlite/schema.js +1 -0
  95. package/dist/store/sqlite/source-review.d.ts +20 -1
  96. package/dist/store/sqlite/source-review.js +74 -3
  97. package/dist/store/sqlite/task-board.d.ts +6 -1
  98. package/dist/store/sqlite/task-board.js +22 -4
  99. package/dist/store/sqlite/templates.d.ts +38 -0
  100. package/dist/store/sqlite/templates.js +69 -0
  101. package/dist/store/sqlite/work-tasks.js +8 -9
  102. package/dist/store/store.d.ts +3 -0
  103. package/dist/store/store.js +5 -0
  104. package/dist/store/types.d.ts +2 -0
  105. package/package.json +4 -4
  106. package/parity.json +19 -0
@@ -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) => {
@@ -122,6 +122,7 @@ export const MANIFEST = [
122
122
  { name: "20261108010754_version-57-business-rules", version: 57, minCompatible: 56 },
123
123
  { name: "20261108104659_version-58-enrichments", version: 58, minCompatible: 56 },
124
124
  { name: "20261108104701_version-58-enrichments-deletes", version: 58, minCompatible: 56 },
125
+ { name: "20261108165309_version-59-templates", version: 59, minCompatible: 56 },
125
126
  ];
126
127
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
127
128
  const migrations = [];
@@ -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]);
@@ -1208,5 +1208,13 @@ export const GENERATED = [
1208
1208
  "CREATE TRIGGER enrichments_note_gone AFTER DELETE ON notes BEGIN\n DELETE FROM enrichments WHERE subject_type = 'note' AND subject_id = OLD.id;\nEND;",
1209
1209
  "CREATE TRIGGER enrichments_email_gone AFTER DELETE ON emails BEGIN\n DELETE FROM enrichments WHERE subject_type = 'email' AND subject_id = OLD.id;\n DELETE FROM chunks WHERE chunkable_type = 'email_enrichment' AND chunkable_id = OLD.id;\nEND;"
1210
1210
  ]
1211
+ },
1212
+ {
1213
+ "name": "20261108165309_version-59-templates",
1214
+ "statements": [
1215
+ "CREATE TABLE `templates` (\n\t`key` text NOT NULL,\n\t`channel` text NOT NULL,\n\t`language` text NOT NULL,\n\t`body` text NOT NULL,\n\t`updated_at` integer NOT NULL,\n\t`updated_by` text NOT NULL,\n\tCONSTRAINT `templates_pk` PRIMARY KEY(`key`, `channel`, `language`)\n);",
1216
+ "CREATE TABLE `templates_history` (\n\t`id` integer PRIMARY KEY,\n\t`key` text NOT NULL,\n\t`channel` text NOT NULL,\n\t`language` text NOT NULL,\n\t`body` text NOT NULL,\n\t`saved_at` integer NOT NULL,\n\t`saved_by` text NOT NULL,\n\t`replaced_at` integer NOT NULL\n);",
1217
+ "CREATE INDEX `templates_history_by_key_channel_language_id` ON `templates_history` (`key`,`channel`,`language`,`id`);"
1218
+ ]
1211
1219
  }
1212
1220
  ];
@@ -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);
@@ -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;
@@ -0,0 +1,136 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { currentPerson, mergeSql, SEPARATIONS } from "./merged-persons.js";
3
+ import { move, recordOf, required } from "./person-links.js";
4
+ import { persons } from "./schema.js";
5
+ export const mergeId = (to, from) => `merge:${to}-${from}`;
6
+ /** The two uids a `merge:<to>-<from>` id names. */
7
+ export const parseMergeId = (id) => {
8
+ const found = /^merge:([1-9]\d*)-([1-9]\d*)$/.exec(id.trim());
9
+ if (!found)
10
+ throw new CliError("validation_error", `${id} is not a merge id; it looks like merge:12-34`);
11
+ return { to: found[1], from: found[2] };
12
+ };
13
+ const personPk = ({ database }, uid) => {
14
+ const found = /^[1-9]\d*$/.test(uid) ? database.prepare("SELECT id FROM persons WHERE id = ?").get(uid) : undefined;
15
+ if (!found)
16
+ throw new CliError("not_found", `no person:${uid} in the store`);
17
+ return Number(found.id);
18
+ };
19
+ const ownerOnly = (by, what) => {
20
+ if (by !== "owner")
21
+ throw new CliError("permission_error", `only the owner ${what}`, { reason: "identity.owner-only" });
22
+ };
23
+ /**
24
+ * The merge that brought each identity now on `to` there. An undo that brought one back to `to` restores the merge
25
+ * it had before it left, so a chain of merges undoes newest first; any other arrival means it came by no merge.
26
+ */
27
+ const arrivals = ({ database }, to) => {
28
+ const rows = database
29
+ .prepare(`SELECT e.identity_id AS pk, e.from_person_id AS person, e.method, e.author, e.created_at, ${mergeSql("e")} AS merge
30
+ FROM identity_link_events e JOIN identity_links l ON l.identity_id = e.identity_id AND l.person_id = e.to_person_id
31
+ WHERE e.to_person_id = ? ORDER BY e.id`)
32
+ .all(to);
33
+ const found = new Map();
34
+ for (const row of rows) {
35
+ const pk = Number(row.pk);
36
+ if (Number(row.merge))
37
+ found.set(pk, {
38
+ pk,
39
+ from: Number(row.person),
40
+ method: String(row.method),
41
+ by: String(row.author),
42
+ at: Number(row.created_at),
43
+ });
44
+ else if (row.method !== "undo-merge")
45
+ found.set(pk, undefined);
46
+ }
47
+ return new Map([...found].filter((entry) => entry[1] !== undefined));
48
+ };
49
+ /**
50
+ * The people merged into this person, each with the identities from it that are still here. Grouped by person, not
51
+ * by time: a merge stamps each identity on its own.
52
+ */
53
+ export const merges = (context, uid) => {
54
+ const to = currentPerson(context.database, personPk(context, uid));
55
+ const named = context.database.prepare("SELECT provider, external_id, name FROM identities WHERE id = ?");
56
+ const found = new Map();
57
+ for (const arrival of [...arrivals(context, to).values()].sort((a, b) => a.at - b.at || a.pk - b.pk)) {
58
+ const row = named.get(arrival.pk);
59
+ const identities = found.get(arrival.from)?.identities ?? [];
60
+ identities.push({
61
+ provider: String(row?.provider),
62
+ id: String(row?.external_id),
63
+ name: row?.name == null ? null : String(row.name),
64
+ });
65
+ found.set(arrival.from, {
66
+ id: mergeId(to, arrival.from),
67
+ from: String(arrival.from),
68
+ to: String(to),
69
+ identities,
70
+ method: arrival.method,
71
+ by: arrival.by,
72
+ at: new Date(arrival.at).toISOString(),
73
+ });
74
+ }
75
+ return [...found.values()].sort((a, b) => b.at.localeCompare(a.at) || a.id.localeCompare(b.id));
76
+ };
77
+ /**
78
+ * Moves the identities that came from `from` and are still on `to` back to `from`, as the owner's move, so no
79
+ * automatic link joins them again. One the owner split or unlinked off since stays where the owner put it. Refused
80
+ * with `identity.stale` when one left `to` by a merge: undoing would take it from wherever it is now.
81
+ *
82
+ * `by` is `"owner"` only on a path that established the owner ran it: an agent's call must never pass it.
83
+ */
84
+ export const undoMerge = (context, toUid, fromUid, by) => {
85
+ ownerOnly(by, "undoes a merge");
86
+ const to = personPk(context, toUid);
87
+ const from = personPk(context, fromUid);
88
+ const here = [...arrivals(context, to).values()].filter((arrival) => arrival.from === from);
89
+ const left = context.database
90
+ .prepare(`SELECT (SELECT n.method FROM identity_link_events n WHERE n.identity_id = m.identity_id AND n.id > m.id
91
+ AND n.from_person_id = m.to_person_id ORDER BY n.id LIMIT 1) AS method
92
+ FROM identity_link_events m JOIN identity_links l ON l.identity_id = m.identity_id AND l.person_id NOT IN (?, ?)
93
+ WHERE m.from_person_id = ? AND m.to_person_id = ? AND ${mergeSql("m")}
94
+ AND m.id = (SELECT max(y.id) FROM identity_link_events y WHERE y.identity_id = m.identity_id
95
+ AND y.from_person_id = m.from_person_id AND y.to_person_id = m.to_person_id)`)
96
+ .all(to, from, from, to);
97
+ if (left.some(({ method }) => !SEPARATIONS.includes(method)))
98
+ throw new CliError("conflict", `an identity of ${mergeId(toUid, fromUid)} was merged on since; undo that first`, {
99
+ reason: "identity.stale",
100
+ });
101
+ if (here.length === 0)
102
+ throw new CliError("not_found", `nothing of person:${fromUid} is merged into person:${toUid}`);
103
+ for (const { pk } of here)
104
+ move(context, pk, to, from, { method: "undo-merge", by });
105
+ return recordOf(context, from);
106
+ };
107
+ /**
108
+ * Moves the chosen identities to one new person, as the owner's move; the person keeps the rest.
109
+ *
110
+ * `by` is `"owner"` only on a path that established the owner ran it: an agent's call must never pass it.
111
+ */
112
+ export const split = (context, uid, refs, by) => {
113
+ ownerOnly(by, "splits a person");
114
+ const person = currentPerson(context.database, personPk(context, uid));
115
+ const chosen = [...new Map(refs.map((ref) => [`${ref.provider}:${ref.id}`, ref])).values()];
116
+ if (chosen.length === 0)
117
+ throw new CliError("validation_error", "name at least one identity to split off");
118
+ const found = chosen.map((ref) => {
119
+ const row = required(context, ref);
120
+ if (row.personPk !== person)
121
+ throw new CliError("validation_error", `${ref.provider}:${ref.id} is not an identity of person:${person}`);
122
+ return row;
123
+ });
124
+ if (found.length === recordOf(context, person).identities.length)
125
+ throw new CliError("validation_error", "a split leaves at least one identity with the person");
126
+ const at = context.now();
127
+ const name = context.database.prepare("SELECT name FROM identities WHERE id = ?").get(found[0].pk);
128
+ const alone = Number(context.orm
129
+ .insert(persons)
130
+ .values({ name: name?.name == null ? null : String(name.name), createdAt: at, updatedAt: at })
131
+ .returning({ pk: persons.id })
132
+ .get()?.pk);
133
+ for (const { pk } of found)
134
+ move(context, pk, person, alone, { method: "split", by });
135
+ return recordOf(context, alone);
136
+ };
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { notOverriddenSql, usableLinkSql } from "../../domain/relations.js";
3
3
  import { linkKind } from "./link-kinds.js";
4
+ import { samePersons } from "./merged-persons.js";
4
5
  import { taskIdOf } from "./things.js";
5
6
  import { read } from "./transaction.js";
6
7
  const GLOBAL_PROJECT = "SELECT id FROM main.projects WHERE account_id IS NULL AND deleted_at IS NULL";
@@ -10,17 +11,19 @@ const iso = (value) => (value == null ? null : new Date(Number(value)).toISOStri
10
11
  * account's: its facts never come along, and its tasks only when `accounts` holds it.
11
12
  */
12
13
  export const personPreparation = ({ database, now }, uid, { accounts, limit }) => {
13
- const person = Number(uid);
14
- if (!/^[1-9]\d*$/.test(uid) || !Number.isSafeInteger(person) || !Number.isSafeInteger(limit) || limit < 1)
14
+ const asked = Number(uid);
15
+ if (!/^[1-9]\d*$/.test(uid) || !Number.isSafeInteger(asked) || !Number.isSafeInteger(limit) || limit < 1)
15
16
  throw new CliError("validation_error", "person preparation takes a person id and a positive limit");
16
17
  const page = (rows) => ({ items: rows.slice(0, limit), hasMore: rows.length > limit });
17
18
  return read(database, () => {
18
- const projects = `SELECT l.to_id FROM links l WHERE l.from_type='person' AND l.from_id=? AND l.to_type='project'
19
- AND l.kind=${linkKind("member-of")} AND ${usableLinkSql("l", now())} AND ${notOverriddenSql("l")} AND l.to_id IN (${GLOBAL_PROJECT})`;
19
+ const person = JSON.stringify(samePersons(database, asked));
20
+ const projects = `SELECT l.to_id FROM links l WHERE l.from_type='person' AND l.from_id IN (SELECT value FROM json_each(?))
21
+ AND l.to_type='project' AND l.kind=${linkKind("member-of")} AND ${usableLinkSql("l", now())}
22
+ AND ${notOverriddenSql("l")} AND l.to_id IN (${GLOBAL_PROJECT})`;
20
23
  const facts = database
21
24
  .prepare(`SELECT f.id,f.type,f.statement,f.subject_type,f.subject_id,f.project_id,f.updated_at FROM facts f
22
25
  WHERE f.status='accepted' AND f.deleted_at IS NULL
23
- AND ((f.subject_type='person' AND f.subject_id=?) OR (f.subject_type='project' AND f.subject_id IN (${projects}))
26
+ AND ((f.subject_type='person' AND f.subject_id IN (SELECT value FROM json_each(?))) OR (f.subject_type='project' AND f.subject_id IN (${projects}))
24
27
  OR f.project_id IN (${projects}))
25
28
  AND (f.subject_type IS NOT 'project' OR f.subject_id IN (${GLOBAL_PROJECT}))
26
29
  AND (f.project_id IS NULL OR f.project_id IN (${GLOBAL_PROJECT}))
@@ -38,8 +41,8 @@ export const personPreparation = ({ database, now }, uid, { accounts, limit }) =
38
41
  .prepare(`SELECT n.id,n.title,n.body,n.revision,n.updated_at FROM notes n
39
42
  JOIN persons owner ON n.author_type='person' AND n.author_id=owner.id AND owner.owner=1
40
43
  WHERE n.deleted_at IS NULL
41
- AND ((n.notable_type='person' AND n.notable_id=?) OR EXISTS(SELECT 1 FROM links l WHERE l.from_type='note'
42
- AND l.from_id=n.id AND l.to_type='person' AND l.to_id=? AND l.kind=${linkKind("about")} AND l.confirmed=1))
44
+ AND ((n.notable_type='person' AND n.notable_id IN (SELECT value FROM json_each(?))) OR EXISTS(SELECT 1 FROM links l WHERE l.from_type='note'
45
+ AND l.from_id=n.id AND l.to_type='person' AND l.to_id IN (SELECT value FROM json_each(?)) AND l.kind=${linkKind("about")} AND l.confirmed=1))
43
46
  AND (n.notable_type='person' OR (n.notable_type='project' AND n.notable_id IN (${GLOBAL_PROJECT})))
44
47
  ORDER BY n.updated_at DESC, n.id DESC LIMIT ?`)
45
48
  .all(person, person, limit + 1)
@@ -53,7 +56,7 @@ export const personPreparation = ({ database, now }, uid, { accounts, limit }) =
53
56
  const tasks = database
54
57
  .prepare(`SELECT t.id,t.title,t.due_at,t.project_id,t.source_locator,t.created_at,group_concat(DISTINCT ta.role) AS role
55
58
  FROM task_assignments ta JOIN tasks t ON t.id=ta.task_id JOIN main.projects p ON p.id=t.project_id
56
- WHERE ta.assignee_type='person' AND ta.assignee_id=? AND t.deleted_at IS NULL AND t.status NOT IN ('done','dismissed')
59
+ WHERE ta.assignee_type='person' AND ta.assignee_id IN (SELECT value FROM json_each(?)) AND t.deleted_at IS NULL AND t.status NOT IN ('done','dismissed')
57
60
  AND p.deleted_at IS NULL AND (p.account_id IS NULL OR p.account_id IN (SELECT a.id FROM accounts a
58
61
  JOIN json_each(?) k ON a.provider=json_extract(k.value,'$.provider')
59
62
  AND a.external_id=json_extract(k.value,'$.account')))
@@ -1,4 +1,5 @@
1
1
  import { fold } from "../normalize.js";
2
+ import { currentPerson } from "./merged-persons.js";
2
3
  const keyOf = (name) => fold(name).trim().replace(/^@/, "");
3
4
  export const resolvePersonLinks = (database, names) => {
4
5
  for (const key of new Set(names.filter((name) => !!name?.trim()).map(keyOf))) {
@@ -15,7 +16,7 @@ export const resolvePersonLinks = (database, names) => {
15
16
  .prepare("SELECT a.name, il.person_id FROM aliases a JOIN identity_links il ON il.identity_id=a.aliasable_id WHERE a.aliasable_type='identity' UNION ALL SELECT name, aliasable_id AS person_id FROM aliases WHERE aliasable_type='person'")
16
17
  .all())
17
18
  if (keyOf(String(row.name)) === key)
18
- people.add(Number(row.person_id));
19
+ people.add(currentPerson(database, Number(row.person_id)));
19
20
  if (people.size === 1)
20
21
  database
21
22
  .prepare("UPDATE links SET to_type='person', to_id=? WHERE to_id IS NULL AND target_folded=?")
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { currentPerson } from "./merged-persons.js";
2
3
  export const personSeenInAccounts = ({ database }, uid, accountIds) => {
3
4
  const id = Number(uid);
4
5
  if (!/^[1-9]\d*$/.test(uid) ||
@@ -9,5 +10,5 @@ export const personSeenInAccounts = ({ database }, uid, accountIds) => {
9
10
  throw new CliError("validation_error", "Person scope requires a positive safe person ID and 1–1000 positive safe account IDs");
10
11
  return Boolean(database
11
12
  .prepare("SELECT 1 FROM persons p JOIN identity_links l ON l.person_id=p.id JOIN account_identities a ON a.identity_id=l.identity_id WHERE p.id=? AND a.account_id IN (SELECT value FROM json_each(?)) LIMIT 1")
12
- .get(id, JSON.stringify(accountIds)));
13
+ .get(currentPerson(database, id), JSON.stringify(accountIds)));
13
14
  };
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { inverseOf, notOverriddenSql, RELATION_KINDS, rolesOf, STANDINGS, } from "../../domain/relations.js";
3
3
  import { linkKind } from "./link-kinds.js";
4
+ import { idsOf } from "./merged-persons.js";
4
5
  import { linkOf } from "./notes.js";
5
6
  import { proposalOperationsOver } from "./proposed-actions.js";
6
7
  import { relationOf } from "./relation-proposals.js";
@@ -34,7 +35,7 @@ export const relationListOver = (context) => {
34
35
  };
35
36
  const end = (side, ref) => {
36
37
  const found = thing(ref, `the ${side} end`);
37
- add(`r.${side}_type = ? AND r.${side}_id = ?`, found.type, found.id);
38
+ add(`r.${side}_type = ? AND r.${side}_id IN (SELECT value FROM json_each(?))`, found.type, idsOf(database, found.type, found.id));
38
39
  };
39
40
  if (filter.kind !== undefined)
40
41
  add("r.kind = ?", filter.kind);
@@ -46,7 +47,7 @@ export const relationListOver = (context) => {
46
47
  end("to", filter.to);
47
48
  const about = filter.about === undefined ? undefined : thing(filter.about, "the reference");
48
49
  if (about)
49
- add("((r.from_type = ? AND r.from_id = ?) OR (r.to_type = ? AND r.to_id = ?))", about.type, about.id, about.type, about.id);
50
+ add(`((r.from_type = ? AND r.from_id IN (SELECT value FROM json_each(?))) OR (r.to_type = ? AND r.to_id IN (SELECT value FROM json_each(?))))`, about.type, idsOf(database, about.type, about.id), about.type, idsOf(database, about.type, about.id));
50
51
  if (filter.at !== undefined)
51
52
  add("(r.starts_at IS NULL OR r.starts_at <= ?) AND (r.ends_at IS NULL OR ? < r.ends_at)", filter.at, filter.at);
52
53
  if (filter.standing !== undefined)