@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,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)
@@ -3,6 +3,7 @@ import { checkEnds, isSymmetric } from "../../domain/relations.js";
3
3
  import { accountPk } from "./accounts.js";
4
4
  import { crmLinkMode } from "./crm-settings.js";
5
5
  import { linkKind } from "./link-kinds.js";
6
+ import { idsOf } from "./merged-persons.js";
6
7
  import { relationProposalsOver } from "./relation-proposals.js";
7
8
  import { checkStoredRole } from "./relation-roles.js";
8
9
  import { referenceOfThing, thingOf } from "./things.js";
@@ -108,14 +109,16 @@ export const syncReportedIn = (context, key, relationships, scope, { source = "i
108
109
  const thing = thingOf(database, ref);
109
110
  if (!thing)
110
111
  continue;
112
+ // What the source said about a person since merged into this one is withdrawn too, or it would show twice.
113
+ const ids = idsOf(database, thing.type, thing.id);
111
114
  // A partnership is stored once, either way round, so either end covers it.
112
115
  const match = end === "from"
113
- ? `((from_type = ? AND from_id = ?) OR (kind = ${linkKind("partner-of")} AND to_type = ? AND to_id = ?))`
114
- : `((to_type = ? AND to_id = ?) OR (kind = ${linkKind("partner-of")} AND from_type = ? AND from_id = ?))`;
116
+ ? `((from_type = ? AND from_id IN (SELECT value FROM json_each(?))) OR (kind = ${linkKind("partner-of")} AND to_type = ? AND to_id IN (SELECT value FROM json_each(?))))`
117
+ : `((to_type = ? AND to_id IN (SELECT value FROM json_each(?))) OR (kind = ${linkKind("partner-of")} AND from_type = ? AND from_id IN (SELECT value FROM json_each(?))))`;
115
118
  const rows = database
116
119
  .prepare(`SELECT id FROM links WHERE account_id = ? AND confirmed = 0 AND deleted_at IS NULL AND kind IN (${kinds}) ` +
117
120
  `AND ${match}${roles ? ` AND ifnull(role, '') IN (${roles})` : ""}`)
118
- .all(accountId, thing.type, thing.id, thing.type, thing.id, ...(scope.roles ?? []));
121
+ .all(accountId, thing.type, ids, thing.type, ids, ...(scope.roles ?? []));
119
122
  for (const row of rows)
120
123
  if (!seen.has(Number(row.id))) {
121
124
  seen.add(Number(row.id));
@@ -1,5 +1,5 @@
1
1
  import { type Decider } from "../decisions.js";
2
- import { type SourceCheck } from "../source-review.js";
2
+ import { type ChangedSource, type SourceCheck, type SourceReviewText } from "../source-review.js";
3
3
  import { type Author } from "./memories.js";
4
4
  import type { StoreContext } from "./open.js";
5
5
  import { type ProposedAction } from "./proposed-actions.js";
@@ -27,6 +27,11 @@ export declare const sourceReviewOver: (context: StoreContext) => {
27
27
  limit?: number;
28
28
  }) => SourceCheck;
29
29
  challenge: (reference: string, input: ChallengeInput) => ProposedAction;
30
+ changedSince: ({ since, limit }: {
31
+ since: number;
32
+ limit?: number;
33
+ }) => ChangedSource[];
34
+ texts: (id: string) => SourceReviewText[];
30
35
  decide: (id: string, decision: SourceReviewDecision) => ProposedAction;
31
36
  };
32
37
  /** The knowledge store's part that watches what memories and facts cite. */
@@ -50,5 +55,19 @@ export interface SourceReviewStore {
50
55
  * reject dismisses the review. Both sign its sources again as they are now.
51
56
  */
52
57
  decideSourceReview(id: string, decision: SourceReviewDecision): Promise<ProposedAction>;
58
+ /**
59
+ * Each source of a `memory_source_review`, as it was cited and as it is now, with the quote the claim rested on.
60
+ * The review itself never holds source text; this reads it when the owner looks.
61
+ */
62
+ sourceReviewTexts(id: string): Promise<SourceReviewText[]>;
63
+ /**
64
+ * Cited sources a check found changed since `since` (ms) that differ from the version cited, newest first, at most
65
+ * `limit` (500): what `checkSources` reported once as `changedRefs`, still there after another run took it.
66
+ * Deleted sources, cited memories or facts, and what an open `evidence_findings` batch cites are left out.
67
+ */
68
+ changedSources(options: {
69
+ since: number;
70
+ limit?: number;
71
+ }): Promise<ChangedSource[]>;
53
72
  }
54
73
  export declare const sourceReviewStoreOver: (context: StoreContext) => SourceReviewStore;
@@ -1,7 +1,8 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { assertMayDecide, deciderAuthor } from "../decisions.js";
3
- import { SOURCE_REVIEW_KIND } from "../source-review.js";
4
- import { evidenceSignature, resignEvidence, sourceHolds, storedEvidenceMetadata, } from "./evidence-signature.js";
3
+ import { EVIDENCE_FINDINGS_KIND } from "../evidence-findings.js";
4
+ import { SOURCE_REVIEW_KIND, } from "../source-review.js";
5
+ import { evidenceSignature, resignEvidence, sourceHolds, sourceTextAt, storedEvidenceMetadata, } from "./evidence-signature.js";
5
6
  import { linkKind } from "./link-kinds.js";
6
7
  import { authorActor } from "./memories.js";
7
8
  import { requiredThing } from "./notes.js";
@@ -95,6 +96,13 @@ export const sourceReviewOver = (context) => {
95
96
  for (const link of evidenceLinksOf(target))
96
97
  resignEvidence(database, Number(link.id), evidenceSignature(database, storedThing(link.to_type, link.to_id)), at, storedEvidenceMetadata(link.metadata));
97
98
  };
99
+ /** Every reference an open evidence findings batch cites, so a changed source already being read is not offered. */
100
+ const inExtraction = () => new Set(database
101
+ .prepare("SELECT DISTINCT json_extract(e.value, '$.reference') AS ref FROM proposed_actions p, " +
102
+ "json_each(p.payload, '$.findings') f, json_each(f.value, '$.evidence') e " +
103
+ "WHERE p.kind = ? AND p.status = 'proposed' AND json_valid(p.payload)")
104
+ .all(EVIDENCE_FINDINGS_KIND)
105
+ .flatMap((row) => (typeof row.ref === "string" ? [row.ref] : [])));
98
106
  const cursor = () => Number(database.prepare("SELECT value FROM store_settings WHERE key = ?").get(CURSOR)?.value ?? 0);
99
107
  /**
100
108
  * The next evidence links after the cursor, at most `limit`, read from a window of `SCAN_FACTOR * limit` link ids
@@ -116,7 +124,8 @@ export const sourceReviewOver = (context) => {
116
124
  throw new CliError("validation_error", "a source check takes 1–10000 evidence links");
117
125
  return write(database, () => {
118
126
  const at = now();
119
- const counts = { checked: 0, baselined: 0, raised: 0, refreshed: 0, closed: 0 };
127
+ const counts = { checked: 0, baselined: 0, raised: 0, refreshed: 0, closed: 0, changedRefs: [] };
128
+ const changed = new Set();
120
129
  const raised = new Map();
121
130
  const retired = new Map();
122
131
  const { links, next } = nextLinks(limit);
@@ -134,6 +143,13 @@ export const sourceReviewOver = (context) => {
134
143
  if (verdict.outcome === "same")
135
144
  continue;
136
145
  resignEvidence(database, Number(link.id), signature, at, storedEvidenceMetadata(link.metadata));
146
+ if (verdict.outcome !== "baselined" &&
147
+ !signature.deleted &&
148
+ asReviewTarget(thing.type, thing.id) === undefined) {
149
+ const ref = referenceOfThing(database, thing);
150
+ if (ref !== undefined)
151
+ changed.add(ref);
152
+ }
137
153
  if (verdict.outcome === "baselined")
138
154
  counts.baselined++;
139
155
  else if (verdict.outcome === "refreshed")
@@ -153,6 +169,10 @@ export const sourceReviewOver = (context) => {
153
169
  database
154
170
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
155
171
  .run(CURSOR, String(next), at);
172
+ if (changed.size > 0) {
173
+ const read = inExtraction();
174
+ counts.changedRefs = [...changed].filter((ref) => !read.has(ref));
175
+ }
156
176
  return counts;
157
177
  });
158
178
  },
@@ -186,6 +206,55 @@ export const sourceReviewOver = (context) => {
186
206
  return operations.get(id);
187
207
  });
188
208
  },
209
+ changedSince: ({ since, limit = DEFAULT_LIMIT }) => {
210
+ if (!Number.isFinite(since))
211
+ throw new CliError("validation_error", "changed sources take a start time");
212
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 10_000)
213
+ throw new CliError("validation_error", "changed sources take 1–10000 references");
214
+ const rows = database
215
+ .prepare("SELECT to_type, to_id, max(json_extract(metadata, '$.checked_at')) AS at FROM links " +
216
+ `WHERE kind = ${linkKind("evidence")} AND from_type IN ('memory', 'fact') AND to_id IS NOT NULL ` +
217
+ "AND to_type NOT IN ('memory', 'fact') AND json_valid(metadata) " +
218
+ "AND json_extract(metadata, '$.checked_at') >= ? AND json_extract(metadata, '$.gone') IS NULL " +
219
+ "AND json_extract(metadata, '$.rev') IS NOT json_extract(metadata, '$.cited_rev') " +
220
+ "GROUP BY to_type, to_id ORDER BY at DESC")
221
+ .all(since);
222
+ const read = inExtraction();
223
+ const changed = [];
224
+ for (const row of rows) {
225
+ if (changed.length === limit)
226
+ break;
227
+ const thing = storedThing(row.to_type, row.to_id);
228
+ if (evidenceSignature(database, thing).deleted)
229
+ continue;
230
+ const ref = referenceOfThing(database, thing);
231
+ if (ref !== undefined && !read.has(ref))
232
+ changed.push({ ref, checkedAt: iso(Number(row.at)) });
233
+ }
234
+ return changed;
235
+ },
236
+ texts: (id) => {
237
+ const proposal = operations.get(id);
238
+ if (proposal.kind !== SOURCE_REVIEW_KIND)
239
+ throw new CliError("validation_error", `${id} is a ${proposal.kind} proposal, not a source review`);
240
+ const link = database.prepare(`SELECT to_type, to_id, metadata FROM links WHERE id = ? AND kind = ${linkKind("evidence")}`);
241
+ return proposal.payload.sources.map((source) => {
242
+ const row = link.get(source.link);
243
+ const quote = row ? (storedEvidenceMetadata(row.metadata)?.quote ?? null) : null;
244
+ if (!row || row.to_id == null || source.ref === null)
245
+ return { link: source.link, ref: source.ref, quote, cited: null, now: null };
246
+ const thing = storedThing(row.to_type, row.to_id);
247
+ const signature = evidenceSignature(database, thing);
248
+ const at = (rev) => (rev === null ? null : (sourceTextAt(database, thing, rev) ?? null));
249
+ return {
250
+ link: source.link,
251
+ ref: source.ref,
252
+ quote,
253
+ cited: at(source.citedRev),
254
+ now: signature.deleted ? null : at(signature.rev),
255
+ };
256
+ });
257
+ },
189
258
  decide: (id, decision) => write(database, () => {
190
259
  const proposal = operations.get(id);
191
260
  if (proposal.kind !== SOURCE_REVIEW_KIND)
@@ -217,5 +286,7 @@ export const sourceReviewStoreOver = (context) => {
217
286
  checkSources: async (options) => sourceReview.checkSources(options),
218
287
  challenge: async (reference, input) => sourceReview.challenge(reference, input),
219
288
  decideSourceReview: async (id, decision) => sourceReview.decide(id, decision),
289
+ sourceReviewTexts: async (id) => sourceReview.texts(id),
290
+ changedSources: async (options) => sourceReview.changedSince(options),
220
291
  };
221
292
  };
@@ -1,4 +1,5 @@
1
1
  import { type FieldSpec, type QueryAst } from "@wirecat/cli-base/query";
2
+ import type { CacheDatabase } from "../driver.js";
2
3
  import type { ColumnMap } from "./query-filter.js";
3
4
  export declare const TASK_SORTS: readonly ["priority", "due", "created", "updated", "key", "state"];
4
5
  export type TaskSort = (typeof TASK_SORTS)[number];
@@ -16,10 +17,14 @@ export declare const dueGroups: (now: number, zone: string) => {
16
17
  };
17
18
  export type DueGroup = keyof ReturnType<typeof dueGroups>;
18
19
  /** `now` and `zone` place today; one value per answer, so the list and its counts agree. */
19
- export declare const projectTaskColumns: (now: number, zone: string) => ColumnMap;
20
+ export declare const projectTaskColumns: (now: number, zone: string, database: CacheDatabase) => ColumnMap;
20
21
  /** Live tasks of the owner's projects; an account's inbox is listed by its account, never here. */
21
22
  export declare const BOARD_SCOPE = "t.deleted_at IS NULL AND t.project_id IN (SELECT id FROM projects WHERE deleted_at IS NULL AND length(key) <> 10)";
22
23
  /** The chosen order first, then priority, age and id, so a page boundary never splits a tie. */
23
24
  export declare const boardOrder: (sort: TaskSort, descending: boolean) => string;
24
25
  /** The query without its required terms on `name`: a picker counts the choices its own filter hides. */
25
26
  export declare const withoutField: (query: QueryAst | undefined, name: string) => QueryAst | undefined;
27
+ /** The people tasks name; a merged-away person is left out and its tasks count for the person it is now. */
28
+ export declare const TASK_PEOPLE: string;
29
+ /** Merged-away people a task is assigned to, with the person each is now, as JSON pairs for `TASK_PEOPLE`. */
30
+ export declare const mergedAssignees: (database: CacheDatabase) => string;
@@ -3,6 +3,7 @@ import { dayBoundary, OPERATORS_BY_TYPE, walkQuery, } from "@wirecat/cli-base/qu
3
3
  import { TASK_TYPES } from "../../domain/knowledge.js";
4
4
  import { taskWordsOf } from "../../search/task-similarity.js";
5
5
  import { PRIORITY_LABELS, priorityBand, TASK_STATES } from "../../tasks/index.js";
6
+ import { currentPerson, idsOf, mergedAwaySql } from "./merged-persons.js";
6
7
  import { INBOX_KEY_LENGTH } from "./task-keys.js";
7
8
  export const TASK_SORTS = ["priority", "due", "created", "updated", "key", "state"];
8
9
  const field = (name, type, example, more = {}) => ({
@@ -71,7 +72,7 @@ const projectWhere = (node) => {
71
72
  params: [key],
72
73
  };
73
74
  };
74
- const assigneeWhere = (node) => {
75
+ const assigneeWhere = (database, node) => {
75
76
  const value = node.value.trim().toLowerCase();
76
77
  if (value === "any" || (node.operator === "wildcard" && value === "*"))
77
78
  return { sql: `EXISTS (${ASSIGNED})`, params: [] };
@@ -80,7 +81,10 @@ const assigneeWhere = (node) => {
80
81
  const id = /^(?:person:)?(\d+)$/.exec(value)?.[1];
81
82
  if (id === undefined)
82
83
  throw new CliError("validation_error", `assignee: takes any, none or "person:<id>", not "${node.value}"`);
83
- return { sql: `EXISTS (${ASSIGNED} AND a.assignee_id = ?)`, params: [Number(id)] };
84
+ return {
85
+ sql: `EXISTS (${ASSIGNED} AND a.assignee_id IN (SELECT value FROM json_each(?)))`,
86
+ params: [idsOf(database, "person", Number(id))],
87
+ };
84
88
  };
85
89
  const bound = (value, side, node) => {
86
90
  const word = value.trim().toLowerCase();
@@ -175,11 +179,11 @@ export const dueGroups = (now, zone) => {
175
179
  };
176
180
  };
177
181
  /** `now` and `zone` place today; one value per answer, so the list and its counts agree. */
178
- export const projectTaskColumns = (now, zone) => ({
182
+ export const projectTaskColumns = (now, zone, database) => ({
179
183
  state: { type: "enum", sql: "t.status" },
180
184
  kind: { type: "enum", sql: "t.type" },
181
185
  project: { where: projectWhere },
182
- assignee: { where: assigneeWhere },
186
+ assignee: { where: (node) => assigneeWhere(database, node) },
183
187
  priority: { where: priorityWhere },
184
188
  agent: { where: agentWhere },
185
189
  parent: { where: parentWhere },
@@ -243,3 +247,17 @@ export const withoutField = (query, name) => {
243
247
  const root = strip(query.root);
244
248
  return root === undefined ? undefined : { ...query, root };
245
249
  };
250
+ /** The people tasks name; a merged-away person is left out and its tasks count for the person it is now. */
251
+ export const TASK_PEOPLE = "WITH merged AS (SELECT json_extract(value, '$[0]') AS id, json_extract(value, '$[1]') AS now FROM json_each(?)), " +
252
+ "counts AS (SELECT coalesce(m.now, a.assignee_id) AS person, count(DISTINCT t.id) AS n FROM task_assignments a " +
253
+ "JOIN tasks t ON t.id = a.task_id AND t.deleted_at IS NULL LEFT JOIN merged m ON m.id = a.assignee_id " +
254
+ "WHERE a.assignee_type = 'person' GROUP BY 1) " +
255
+ "SELECT p.id, p.name, p.owner, coalesce(c.n, 0) AS n FROM persons p LEFT JOIN counts c ON c.person = p.id " +
256
+ `WHERE NOT ${mergedAwaySql("p")} ` +
257
+ "ORDER BY p.owner DESC, n DESC, p.name IS NULL, p.name COLLATE NOCASE, p.id LIMIT ?";
258
+ /** Merged-away people a task is assigned to, with the person each is now, as JSON pairs for `TASK_PEOPLE`. */
259
+ export const mergedAssignees = (database) => JSON.stringify(database
260
+ .prepare("SELECT DISTINCT a.assignee_id AS id FROM task_assignments a JOIN persons p ON p.id = a.assignee_id " +
261
+ `WHERE a.assignee_type = 'person' AND ${mergedAwaySql("p")}`)
262
+ .all()
263
+ .map(({ id }) => [Number(id), currentPerson(database, Number(id))]));
@@ -5,11 +5,12 @@ import { TASK_TYPES, WORK_TASK_TYPES } from "../../domain/knowledge.js";
5
5
  import { checkedScore, isClosedState, legacyPriority, PRIORITY_LABELS, priorityBand, priorityLabel, TASK_STATES, } from "../../tasks/index.js";
6
6
  import { folded } from "./folded.js";
7
7
  import { authorActor } from "./memories.js";
8
+ import { idsOf } from "./merged-persons.js";
8
9
  import { CORPORA, drainCorpus } from "./note-index.js";
9
10
  import { requiredThing } from "./notes.js";
10
11
  import { queryFilter } from "./query-filter.js";
11
12
  import { stemmerCache } from "./stems.js";
12
- import { BOARD_SCOPE, boardOrder, dueGroups, projectTaskColumns, withoutField, } from "./task-board.js";
13
+ import { BOARD_SCOPE, boardOrder, dueGroups, mergedAssignees, projectTaskColumns, TASK_PEOPLE, withoutField, } from "./task-board.js";
13
14
  import { closeSuggestionOf, SUGGESTION_COLUMNS } from "./task-close.js";
14
15
  import { addComment, authorNamed, commentsOf } from "./task-comments.js";
15
16
  import { INBOX_KEY_LENGTH, inboxKey } from "./task-keys.js";
@@ -161,7 +162,7 @@ export const workTaskOperationsOver = (context) => {
161
162
  const boardWhere = (query, zone, at) => {
162
163
  if (query === undefined)
163
164
  return { sql: BOARD_SCOPE, params: [] };
164
- const where = queryFilter(query, projectTaskColumns(at, timezoneOf(zone)), {
165
+ const where = queryFilter(query, projectTaskColumns(at, timezoneOf(zone), database), {
165
166
  command: "tasks list",
166
167
  now: at,
167
168
  ...(zone ? { zone } : {}),
@@ -438,8 +439,9 @@ export const workTaskOperationsOver = (context) => {
438
439
  checkRevision(rowById(task), check.revision);
439
440
  const person = personOf(to);
440
441
  const held = database
441
- .prepare("SELECT 1 FROM task_assignments WHERE task_id = ? AND assignee_type = 'person' AND assignee_id = ? AND role = ?")
442
- .get(task, person, role);
442
+ .prepare("SELECT 1 FROM task_assignments WHERE task_id = ? AND assignee_type = 'person' " +
443
+ "AND assignee_id IN (SELECT value FROM json_each(?)) AND role = ?")
444
+ .get(task, idsOf(database, "person", person), role);
443
445
  if (held)
444
446
  return;
445
447
  const at = now();
@@ -622,11 +624,8 @@ export const workTaskOperationsOver = (context) => {
622
624
  };
623
625
  },
624
626
  taskPeople: async ({ limit = 500 } = {}) => database
625
- .prepare("SELECT p.id, p.name, p.owner, count(DISTINCT t.id) AS n FROM persons p " +
626
- "LEFT JOIN task_assignments a ON a.assignee_type = 'person' AND a.assignee_id = p.id " +
627
- "LEFT JOIN tasks t ON t.id = a.task_id AND t.deleted_at IS NULL " +
628
- "GROUP BY p.id ORDER BY p.owner DESC, n DESC, p.name IS NULL, p.name COLLATE NOCASE, p.id LIMIT ?")
629
- .all(Math.min(Math.max(limit, 1), 5000))
627
+ .prepare(`${TASK_PEOPLE}`)
628
+ .all(mergedAssignees(database), Math.min(Math.max(limit, 1), 5000))
630
629
  .map((row) => ({
631
630
  person: `person:${row.id}`,
632
631
  name: row.name == null ? null : String(row.name),
@@ -67,6 +67,8 @@ export interface PersonRecord {
67
67
  uid: string;
68
68
  name: string | null;
69
69
  identities: LinkedIdentity[];
70
+ /** Set when the uid asked for was merged away: the uid of the person its identities are now, the same as `uid`. */
71
+ mergedInto?: string;
70
72
  }
71
73
  /** What a search of one account's messages takes, the account given apart. */
72
74
  export interface AccountMessageFilter {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.615.0",
3
+ "version": "0.617.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
@@ -278,7 +278,7 @@
278
278
  "@types/node": "^22.20.5",
279
279
  "@types/pngjs": "6.0.5",
280
280
  "@vitest/coverage-v8": "^5.0.5",
281
- "@wirecat/cli-base": "0.87.0",
281
+ "@wirecat/cli-base": "0.90.0",
282
282
  "@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
283
283
  "ajv": "8.17.1",
284
284
  "commander": "15.0.0",
package/parity.json CHANGED
@@ -304,6 +304,9 @@
304
304
  "--defaults": {
305
305
  "meaning": "change what every profile gets, rather than this profile"
306
306
  },
307
+ "--delete-data": {
308
+ "meaning": "also delete the account's messages and files on this computer"
309
+ },
307
310
  "--deliver-to": {
308
311
  "value": "<route>",
309
312
  "meaning": "where a schedule's result also goes, when --notify-on says so: telegram-bot:<profile>/<chat>, email:<profile>/<address>; repeat it for more"
@@ -499,6 +502,9 @@
499
502
  "--jsonl": {
500
503
  "meaning": "machine-readable output: one JSON object per line, for streaming and jq"
501
504
  },
505
+ "--keep-data": {
506
+ "meaning": "keep the account's messages on this computer; search still finds them"
507
+ },
502
508
  "--kind": {
503
509
  "value": "<kind>",
504
510
  "meaning": "the kind of link to record; the command lists the supported task and evidence relations"
@@ -1293,6 +1299,19 @@
1293
1299
  "wa": "wa backlog: account privacy"
1294
1300
  }
1295
1301
  },
1302
+ "account remove": {
1303
+ "in": [],
1304
+ "options": {
1305
+ "--delete-data": "all",
1306
+ "--dry-run": "all",
1307
+ "--keep-data": "all"
1308
+ },
1309
+ "planned": {
1310
+ "max": "account remove: adopt Messenger.accountRemoval (WireCat Desktop removal)",
1311
+ "tg": "account remove: adopt Messenger.accountRemoval (WireCat Desktop removal)",
1312
+ "wa": "account remove: adopt Messenger.accountRemoval (WireCat Desktop removal)"
1313
+ }
1314
+ },
1296
1315
  "account sessions": {
1297
1316
  "in": "all"
1298
1317
  },