@wirecat/cli-core 0.639.0 → 0.641.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 (64) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/dist/cli/messenger/backfill-command.js +16 -1
  3. package/dist/cli/messenger/search-answers.js +2 -0
  4. package/dist/cli/store-settings.d.ts +4 -1
  5. package/dist/cli/store-settings.js +26 -9
  6. package/dist/crm/cli/csv.js +2 -0
  7. package/dist/crm/cli/index.js +8 -2
  8. package/dist/crm/cli/search-all.js +4 -4
  9. package/dist/crm/stage-tasks.d.ts +8 -0
  10. package/dist/crm/stage-tasks.js +42 -0
  11. package/dist/domain/crm.d.ts +9 -0
  12. package/dist/domain/name-variants.d.ts +2 -0
  13. package/dist/domain/name-variants.js +107 -0
  14. package/dist/domain/person-kinds.d.ts +6 -3
  15. package/dist/domain/person-kinds.js +5 -2
  16. package/dist/entities/contact-activity.d.ts +3 -0
  17. package/dist/entities/contact-activity.js +3 -0
  18. package/dist/entities/contact-context.d.ts +6 -0
  19. package/dist/entities/deal.d.ts +6 -0
  20. package/dist/entities/deal.js +3 -0
  21. package/dist/entities/index.d.ts +10 -0
  22. package/dist/errors/reasons.js +2 -1
  23. package/dist/resolve.d.ts +8 -0
  24. package/dist/resolve.js +48 -6
  25. package/dist/runs/events.d.ts +9 -1
  26. package/dist/runs/events.js +5 -1
  27. package/dist/runs/log-events.js +2 -0
  28. package/dist/search/lucene/registry.js +17 -15
  29. package/dist/services/deal-context.js +17 -0
  30. package/dist/services/message-resolution.d.ts +13 -1
  31. package/dist/services/message-resolution.js +44 -3
  32. package/dist/services/messages-search.js +41 -20
  33. package/dist/services/metadata.d.ts +1 -1
  34. package/dist/services/search-all.d.ts +10 -3
  35. package/dist/services/search-all.js +10 -4
  36. package/dist/store/index.d.ts +2 -2
  37. package/dist/store/people.d.ts +10 -3
  38. package/dist/store/people.js +2 -1
  39. package/dist/store/sqlite/accounts.js +2 -0
  40. package/dist/store/sqlite/crm-rows.js +2 -0
  41. package/dist/store/sqlite/crm-settings.d.ts +26 -1
  42. package/dist/store/sqlite/crm-settings.js +104 -1
  43. package/dist/store/sqlite/crm.d.ts +12 -0
  44. package/dist/store/sqlite/crm.js +9 -1
  45. package/dist/store/sqlite/deals.d.ts +28 -5
  46. package/dist/store/sqlite/deals.js +158 -14
  47. package/dist/store/sqlite/hit-places.js +19 -6
  48. package/dist/store/sqlite/identities.js +21 -1
  49. package/dist/store/sqlite/lucene-fields.d.ts +2 -1
  50. package/dist/store/sqlite/lucene-fields.js +129 -16
  51. package/dist/store/sqlite/lucene.js +8 -8
  52. package/dist/store/sqlite/note-search.js +9 -0
  53. package/dist/store/sqlite/people-list.js +14 -8
  54. package/dist/store/sqlite/person-doubts.d.ts +13 -3
  55. package/dist/store/sqlite/person-doubts.js +92 -48
  56. package/dist/store/sqlite/person-links.js +15 -2
  57. package/dist/store/sqlite/tasks.js +9 -8
  58. package/dist/store/sqlite/test-people.d.ts +24 -0
  59. package/dist/store/sqlite/test-people.js +92 -0
  60. package/dist/store/types.d.ts +6 -0
  61. package/dist/tasks/model.d.ts +6 -2
  62. package/dist/tasks/service.d.ts +2 -0
  63. package/docs/search/recipes.json +3 -0
  64. package/package.json +1 -1
@@ -1,14 +1,16 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { displayName } from "../../domain/display-names.js";
3
- import { nameSkeletons } from "../../domain/name-variants.js";
4
- import { RESERVED_ADDRESS_GLOBS, SEED_ID_GLOBS, SEED_PEOPLE } from "../../domain/test-data.js";
3
+ import { FIRST_NAMES } from "../../domain/first-names.js";
4
+ import { fullNames, nameSkeletons, wordSkeleton } from "../../domain/name-variants.js";
5
+ import { foldName } from "../../resolve.js";
5
6
  import { keepTogether, keptTogether } from "./identity-split-proposals.js";
6
7
  import { currentPerson } from "./merged-persons.js";
7
8
  import { merges, ownerOnly } from "./person-merges.js";
9
+ import { hiddenTestPeople, judgeTestData, testIdentitySql, testVerdicts } from "./test-people.js";
8
10
  /** Why a person may be wrong, most urgent first: the owner's own person holding someone else matters most. */
9
11
  export const DOUBT_REASONS = ["owner-other-name", "test-data", "shared-address", "mixed-names"];
10
12
  const COLUMNS = "l.person_id AS person, p.owner, p.name AS person_name, i.id AS pk, i.provider, i.external_id, i.name, i.phone, " +
11
- "i.email, l.method, l.author, l.created_at, EXISTS (SELECT 1 FROM accounts a WHERE a.provider = i.provider " +
13
+ "i.email, i.username, l.method, l.author, l.created_at, EXISTS (SELECT 1 FROM accounts a WHERE a.provider = i.provider " +
12
14
  "AND a.external_id = i.external_id) AS account FROM identity_links l JOIN identities i ON i.id = l.identity_id " +
13
15
  "JOIN persons p ON p.id = l.person_id";
14
16
  const text = (value) => (typeof value === "string" && value.trim() !== "" ? value : null);
@@ -21,6 +23,7 @@ const heldOf = (row) => ({
21
23
  name: text(row.name),
22
24
  phone: text(row.phone)?.replace(/\D/gu, "") || null,
23
25
  email: text(row.email)?.toLowerCase() ?? null,
26
+ username: text(row.username),
24
27
  account: Number(row.account) === 1,
25
28
  method: String(row.method),
26
29
  by: String(row.author),
@@ -32,36 +35,41 @@ const sharedPeople = (database) => database
32
35
  "ORDER BY l.person_id, i.id")
33
36
  .all()
34
37
  .map(heldOf);
35
- /**
36
- * Identities a test run left: the seed's word ids, an address at a reserved domain, or a seed name with its username
37
- * or beside another seed name in one provider, since one name alone may be a real person's.
38
- */
38
+ /** Identities a test run left, the owner's word aside. */
39
39
  const testData = (database) => {
40
- const names = JSON.stringify(SEED_PEOPLE.map(({ name }) => name));
41
- const usernames = JSON.stringify(SEED_PEOPLE.flatMap(({ username }) => (username === null ? [] : [username])));
42
- const globs = (column, patterns) => patterns.map((pattern) => `${column} GLOB '${pattern}'`).join(" OR ");
40
+ const { where, sure, params } = testIdentitySql();
43
41
  return database
44
- .prepare(`SELECT ${COLUMNS} WHERE ${globs("i.external_id", SEED_ID_GLOBS)} OR ${globs("lower(i.email)", RESERVED_ADDRESS_GLOBS)} ` +
45
- "OR (i.name IN (SELECT value FROM json_each(?)) AND (i.username IN (SELECT value FROM json_each(?)) " +
46
- "OR (SELECT count(DISTINCT j.name) FROM identities j WHERE j.provider = i.provider " +
47
- "AND j.name IN (SELECT value FROM json_each(?))) >= 2)) ORDER BY l.person_id, i.id")
48
- .all(names, usernames, names)
49
- .map(heldOf);
42
+ .prepare(`SELECT ${sure}, ${COLUMNS} WHERE ${where} ORDER BY l.person_id, i.id`)
43
+ .all(...params)
44
+ .map((row) => ({ ...heldOf(row), sure: Number(row.sure) === 1 }));
50
45
  };
51
- /** A name's words, script and spelling aside; none for an address or a placeholder, which say nothing of a name. */
52
- const wordsOf = (name) => {
46
+ const FIRST = new Set(FIRST_NAMES.map(wordSkeleton));
47
+ /** «Ivan» at ivan@… is still a name; «msx04x» at msx04x@… is not. */
48
+ const isFirstName = (name) => nameSkeletons(name).some((word) => FIRST.has(word));
49
+ const bare = (text) => foldName(text).replace(/[^\p{L}\p{N}]/gu, "");
50
+ /**
51
+ * A name's words, script, spelling and short forms aside; none for an address or a placeholder, which say nothing of a
52
+ * name, nor for a name that only repeats the identity's own mailbox or username and is no first name, as Drive and
53
+ * mail show «msx04x» for msx04x@….
54
+ */
55
+ const wordsOf = (name, handles = []) => {
53
56
  const shown = displayName(name);
54
57
  if (shown === null || shown.includes("@"))
55
58
  return new Set();
56
- return new Set(nameSkeletons(shown).filter((word) => word.length >= 2 && !/^\d+$/u.test(word)));
59
+ if (handles.some((handle) => handle !== null && bare(handle) === bare(shown)) && !isFirstName(shown))
60
+ return new Set();
61
+ return new Set(nameSkeletons(shown)
62
+ .filter((word) => word.length >= 2 && !/^\d+$/u.test(word))
63
+ .flatMap(fullNames));
57
64
  };
65
+ const heldWords = ({ name, email, username }) => wordsOf(name, [email?.split("@")[0] ?? null, username]);
58
66
  const sharesWord = (one, other) => [...one].some((word) => other.has(word));
59
67
  /**
60
68
  * The identities grouped by names that share a word, the person's own first: the most identities, counting double what
61
69
  * the owner linked by hand, an account the owner connected and the person's own name.
62
70
  */
63
71
  const nameGroups = (held) => {
64
- const named = held.map((one) => ({ one, words: wordsOf(one.name) })).filter(({ words }) => words.size > 0);
72
+ const named = held.map((one) => ({ one, words: heldWords(one) })).filter(({ words }) => words.size > 0);
65
73
  const group = named.map((_, index) => index);
66
74
  const root = (at) => {
67
75
  let top = at;
@@ -94,7 +102,7 @@ const nameGroups = (held) => {
94
102
  }
95
103
  const own = wordsOf(held[0]?.personName ?? null);
96
104
  const weight = (members) => members.reduce((sum, one) => sum + 1 + (one.by === "owner" ? 2 : 0) + (one.account ? 2 : 0), 0) +
97
- (members.some(({ name }) => sharesWord(wordsOf(name), own)) ? 2 : 0);
105
+ (members.some((one) => sharesWord(heldWords(one), own)) ? 2 : 0);
98
106
  return [...groups.values()].sort((a, b) => weight(b) - weight(a) || a[0].pk - b[0].pk);
99
107
  };
100
108
  const quoted = (held) => [...new Set(held.map(({ name, ref }) => name ?? ref))].map((name) => `«${name}»`).join(", ");
@@ -154,24 +162,36 @@ const byPerson = (held) => {
154
162
  return found;
155
163
  };
156
164
  const ORDER = new Map(DOUBT_REASONS.map((reason, index) => [reason, index]));
165
+ /** The identities a test run left that the owner has not called real, and the people memo hides as test data. */
166
+ const testState = (database) => {
167
+ const verdicts = testVerdicts(database);
168
+ const test = testData(database).filter(({ ref }) => verdicts.get(ref) !== false);
169
+ return { verdicts, test, pks: new Set(test.map(({ pk }) => pk)), hidden: hiddenTestPeople(database) };
170
+ };
157
171
  /** Everything in doubt, the owner first, then by reason and person. A few thousand people are read, never every row. */
158
172
  const everyDoubt = (database) => {
159
- const test = testData(database);
160
- const testPks = new Set(test.map(({ pk }) => pk));
173
+ const { verdicts, test, pks, hidden } = testState(database);
161
174
  const kept = keptTogether(database);
162
175
  const found = [];
163
176
  for (const [person, held] of byPerson(sharedPeople(database)))
164
- for (const one of doubtsOf(held, kept.get(person) ?? new Set(), testPks))
177
+ for (const one of doubtsOf(held, kept.get(person) ?? new Set(), pks))
165
178
  found.push(one);
166
- for (const held of byPerson(test).values()) {
167
- const [first] = held;
179
+ const holds = database.prepare("SELECT count(*) AS n FROM identity_links WHERE person_id = ?");
180
+ for (const [person, held] of byPerson(test)) {
181
+ if (hidden.has(person))
182
+ continue;
183
+ const open = held.filter(({ ref }) => !verdicts.has(ref));
184
+ const [first] = open;
185
+ if (first === undefined)
186
+ continue;
168
187
  found.push({
169
- person: first.person,
188
+ person,
170
189
  owner: first.owner,
171
190
  name: first.personName,
172
191
  reason: "test-data",
173
- held,
192
+ held: open,
174
193
  doubted: [],
194
+ whole: !first.owner && Number(holds.get(person)?.n) === held.length,
175
195
  });
176
196
  }
177
197
  return found.sort((a, b) => Number(b.owner) - Number(a.owner) ||
@@ -183,8 +203,12 @@ const everyDoubt = (database) => {
183
203
  * unlink per name group of the rest, so two strangers on one person do not land on one new person together.
184
204
  */
185
205
  const movesOf = (context, found) => {
186
- if (found.reason === "test-data" || found.reason === "mixed-names")
206
+ if (found.reason === "mixed-names")
187
207
  return [];
208
+ if (found.reason === "test-data")
209
+ return found.whole
210
+ ? [{ op: "test-data", person: `person:${found.person}` }]
211
+ : [{ op: "unlink", identities: found.held.map(({ ref }) => ref), from: `person:${found.person}` }];
188
212
  const doubted = new Set(found.held.map(({ ref }) => ref));
189
213
  const moves = [];
190
214
  const unmerged = new Set();
@@ -203,7 +227,9 @@ const movesOf = (context, found) => {
203
227
  };
204
228
  const commandOf = (move) => move.op === "unmerge"
205
229
  ? `people unmerge ${move.merge}`
206
- : `people unlink ${move.identities.map(shellWord).join(" ")} --from ${move.from}`;
230
+ : move.op === "test-data"
231
+ ? `people links resolve ${move.person} test`
232
+ : `people unlink ${move.identities.map(shellWord).join(" ")} --from ${move.from}`;
207
233
  /** A ref as one shell word: an id may hold a space or a quote, and the fix is pasted into a terminal. */
208
234
  const shellWord = (ref) => (/^[\w@.:+/=-]+$/u.test(ref) ? ref : `'${ref.replaceAll("'", "'\\''")}'`);
209
235
  const shown = (context, found) => {
@@ -243,31 +269,49 @@ export const personDoubts = (context, { limit, offset }) => {
243
269
  hasMore: found.length > offset + limit,
244
270
  };
245
271
  };
246
- /**
247
- * The owner's answer to a doubt: this person is right as they are. Test data is not a link and stays listed. Refused
248
- * when nothing about the person is in doubt.
249
- */
250
- export const keepPerson = (context, uid, by) => {
251
- ownerOnly(by, "says a person's links are right");
272
+ const personFor = (context, uid) => {
252
273
  const asked = /^(?:person:)?([1-9]\d*)$/u.exec(uid.trim())?.[1];
253
274
  const known = asked === undefined || !Number.isSafeInteger(Number(asked))
254
275
  ? undefined
255
276
  : context.database.prepare("SELECT id FROM persons WHERE id = ?").get(Number(asked));
256
277
  if (known === undefined)
257
278
  throw new CliError("not_found", `the store has no person for "${uid}"`, { reason: "person.unknown" });
258
- const person = currentPerson(context.database, Number(known.id));
259
- const held = context.database.prepare(`SELECT ${COLUMNS} WHERE l.person_id = ? ORDER BY i.id`).all(person).map(heldOf);
260
- const test = new Set(testData(context.database).map(({ pk }) => pk));
279
+ return currentPerson(context.database, Number(known.id));
280
+ };
281
+ const heldOn = (context, person) => context.database.prepare(`SELECT ${COLUMNS} WHERE l.person_id = ? ORDER BY i.id`).all(person).map(heldOf);
282
+ /**
283
+ * The owner's answer to a doubt: this person is right as they are, and what looked like test data is a real contact,
284
+ * which also brings back a person memo hid as test data. Refused when nothing about the person is in doubt or hidden.
285
+ */
286
+ export const keepPerson = (context, uid, by) => {
287
+ ownerOnly(by, "says a person's links are right");
288
+ const person = personFor(context, uid);
289
+ const held = heldOn(context, person);
290
+ const { verdicts, pks } = testState(context.database);
261
291
  const doubted = [
262
- ...new Set(doubtsOf(held, keptTogether(context.database).get(person) ?? new Set(), test).flatMap((found) => found.doubted.map(({ ref }) => ref))),
292
+ ...new Set(doubtsOf(held, keptTogether(context.database).get(person) ?? new Set(), pks).flatMap((found) => found.doubted.map(({ ref }) => ref))),
263
293
  ];
264
- if (doubted.length === 0) {
265
- if (held.some(({ pk }) => test.has(pk)))
266
- throw new CliError("validation_error", `person:${person} is in doubt only as test data, which is not kept`, {
267
- reason: "person.test-data",
268
- });
294
+ const real = held.filter(({ pk, ref }) => pks.has(pk) || verdicts.get(ref) === true).map(({ ref }) => ref);
295
+ if (doubted.length === 0 && real.length === 0)
269
296
  throw new CliError("not_found", `nothing about person:${person} is in doubt`, { reason: "person.no-doubt" });
270
- }
271
- keepTogether(context, person, doubted);
272
- return { person: `person:${person}`, kept: doubted };
297
+ if (doubted.length > 0)
298
+ keepTogether(context, person, doubted);
299
+ if (real.length > 0)
300
+ judgeTestData(context, person, real, false);
301
+ return { person: `person:${person}`, kept: [...new Set([...doubted, ...real])] };
302
+ };
303
+ /** The owner's answer to a doubt: the person is test data, hidden from every list until the owner calls them real. */
304
+ export const markTestData = (context, uid, by) => {
305
+ ownerOnly(by, "calls a person test data");
306
+ const person = personFor(context, uid);
307
+ const held = heldOn(context, person);
308
+ if (held[0]?.owner === true)
309
+ throw new CliError("validation_error", "your own person is not test data", { reason: "person.owner" });
310
+ if (held.length === 0)
311
+ throw new CliError("validation_error", `person:${person} has no identity to call test data`, {
312
+ reason: "person.no-identity",
313
+ });
314
+ const identities = held.map(({ ref }) => ref);
315
+ judgeTestData(context, person, identities, true);
316
+ return { person: `person:${person}`, identities };
273
317
  };
@@ -21,6 +21,14 @@ export const required = (context, ref) => {
21
21
  throw new CliError("not_found", `no ${ref.provider} person ${ref.id} in the store`);
22
22
  return found;
23
23
  };
24
+ /** Every phone and address an identity holds: the source's lists, else the one `phone` and `email`. */
25
+ const contactListsOf = ({ phone, email }, metadata) => {
26
+ const stored = metadata === null ? {} : JSON.parse(metadata);
27
+ const list = (values, one) => [
28
+ ...new Set([...(one === null ? [] : [one]), ...(Array.isArray(values) ? values.map(String) : [])]),
29
+ ];
30
+ return { phones: list(stored.phones, phone), emails: list(stored.emails, email) };
31
+ };
24
32
  export const recordOf = ({ orm }, personPk) => {
25
33
  const person = orm.select().from(persons).where(eq(persons.id, personPk)).get();
26
34
  if (!person)
@@ -34,6 +42,7 @@ export const recordOf = ({ orm }, personPk) => {
34
42
  username: identities.username,
35
43
  phone: identities.phone,
36
44
  email: identities.email,
45
+ metadata: identities.metadata,
37
46
  isBot: identities.bot,
38
47
  method: identityLinks.method,
39
48
  linkedBy: identityLinks.author,
@@ -50,19 +59,23 @@ export const recordOf = ({ orm }, personPk) => {
50
59
  .innerJoin(accounts, eq(accounts.id, accountIdentities.accountId))
51
60
  .where(inArray(accountIdentities.identityId, rows.map((row) => row.pk)))
52
61
  .all();
53
- const identitiesOf = rows.map(({ pk, isBot, linkedAt, ...row }) => {
62
+ const identitiesOf = rows.map(({ pk, isBot, linkedAt, metadata, ...row }) => {
54
63
  const seenIn = seen
55
64
  .filter((one) => one.identityPk === pk)
56
65
  .map(({ account, scope }) => ({ account, scope: scope }));
57
66
  return {
58
67
  ...row,
68
+ ...contactListsOf(row, metadata),
59
69
  isBot: isBot === null ? null : isBot === 1,
60
70
  accounts: seenIn.map((one) => one.account),
61
71
  seenIn,
62
72
  linkedAt: new Date(linkedAt).toISOString(),
63
73
  };
64
74
  });
65
- const fallbacks = [...rows].sort((a, b) => a.pk - b.pk).reduce(takeFallbacks, noFallbacks());
75
+ const fallbacks = [...rows]
76
+ .map(({ metadata: _, ...row }) => row)
77
+ .sort((a, b) => a.pk - b.pk)
78
+ .reduce(takeFallbacks, noFallbacks());
66
79
  return {
67
80
  uid: String(person.id),
68
81
  name: person.name,
@@ -178,17 +178,18 @@ export const taskStoreOver = (context) => {
178
178
  const key = typedKey(database, task.kind);
179
179
  const author = actorOfOrigin(database, task.origin);
180
180
  const closedBy = task.closedBy ? actorOfOrigin(database, task.closedBy) : undefined;
181
- const title = displayTitleOf(database, {
182
- type: task.kind,
183
- title: `${task.kind} — ${task.source}`,
184
- source_locator: task.source,
185
- });
181
+ const title = task.title ??
182
+ displayTitleOf(database, {
183
+ type: task.kind,
184
+ title: `${task.kind} — ${task.source}`,
185
+ source_locator: task.source,
186
+ });
186
187
  const made = database
187
188
  .prepare("INSERT INTO tasks (project_id, number, key, title, type, status, due_at, closed_at, closed_by_type, closed_by_id, " +
188
189
  "close_reason, author_type, author_id, source, package_id, source_locator, source_kind, source_group, created_at, updated_at, " +
189
- "title_folded, close_reason_folded, category) " +
190
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
191
- .get(project, number, key, title, task.kind, task.state, time(task.dueAt), time(task.closedAt), closedBy?.type ?? null, closedBy?.id ?? null, task.reason ?? null, author.type, author.id, task.origin, task.id, task.source, task.sourceKind, task.group, task.createdAt.getTime(), now(), folded(title), folded(task.reason), task.category ?? null);
190
+ "title_folded, close_reason_folded, category, description) " +
191
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
192
+ .get(project, number, key, title, task.kind, task.state, time(task.dueAt), time(task.closedAt), closedBy?.type ?? null, closedBy?.id ?? null, task.reason ?? null, author.type, author.id, task.origin, task.id, task.source, task.sourceKind, task.group, task.createdAt.getTime(), now(), folded(title), folded(task.reason), task.category ?? null, task.description ?? null);
192
193
  recordTaskEvent(database, Number(made?.id), author, "created", null, task.createdAt.getTime());
193
194
  });
194
195
  },
@@ -0,0 +1,24 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import type { StoreContext } from "./open.js";
3
+ /** The owner's word on identities: approved, they are test data; rejected, a real contact. */
4
+ export declare const TEST_DATA_KIND = "test_data";
5
+ /** The SQL that picks a test run's identities, aliased `i`, and its parameters; `sure` is a column of it. */
6
+ export declare const testIdentitySql: () => {
7
+ where: string;
8
+ sure: string;
9
+ params: string[];
10
+ };
11
+ /** The owner's newest word on each identity: `true` test data, `false` a real contact. */
12
+ export declare const testVerdicts: (database: CacheDatabase) => Map<string, boolean>;
13
+ /**
14
+ * People memo keeps out of every list as test data: each identity is a sure test run's or one the owner called test
15
+ * data, and the owner called none a real contact. Never the owner.
16
+ */
17
+ export declare const hiddenTestPeople: (database: CacheDatabase) => Set<number>;
18
+ /**
19
+ * Records the owner's word on the identities: test data, or a real contact. The next people list works the person's
20
+ * kind out again, since no trigger watches a decision.
21
+ */
22
+ export declare const judgeTestData: (context: StoreContext, person: number, identities: readonly string[], test: boolean) => void;
23
+ /** Deletes the owner's words on identities no longer in the store: a payload names the address. */
24
+ export declare const forgetErasedTestData: (database: CacheDatabase) => void;
@@ -0,0 +1,92 @@
1
+ import { RESERVED_ADDRESS_GLOBS, SEED_ID_GLOBS, SEED_PEOPLE } from "../../domain/test-data.js";
2
+ import { personOf, pkOf } from "./identity-link-rows.js";
3
+ import { proposalOperationsOver } from "./proposed-actions.js";
4
+ /** The owner's word on identities: approved, they are test data; rejected, a real contact. */
5
+ export const TEST_DATA_KIND = "test_data";
6
+ const globs = (column, patterns) => patterns.map((pattern) => `${column} GLOB '${pattern}'`).join(" OR ");
7
+ /** A seed id or an address at a reserved domain: nothing real has one, so memo hides it without asking. */
8
+ const SURE = `(${globs("i.external_id", SEED_ID_GLOBS)} OR ${globs("lower(i.email)", RESERVED_ADDRESS_GLOBS)})`;
9
+ /** A seed name with its username or beside another seed name in one provider: one name alone may be a real person's. */
10
+ const SEED_NAMED = "(i.name IN (SELECT value FROM json_each(?)) AND (i.username IN (SELECT value FROM json_each(?)) " +
11
+ "OR (SELECT count(DISTINCT j.name) FROM identities j WHERE j.provider = i.provider " +
12
+ "AND j.name IN (SELECT value FROM json_each(?))) >= 2))";
13
+ const seedParams = () => {
14
+ const names = JSON.stringify(SEED_PEOPLE.map(({ name }) => name));
15
+ const usernames = JSON.stringify(SEED_PEOPLE.flatMap(({ username }) => (username === null ? [] : [username])));
16
+ return [names, usernames, names];
17
+ };
18
+ /** The SQL that picks a test run's identities, aliased `i`, and its parameters; `sure` is a column of it. */
19
+ export const testIdentitySql = () => ({
20
+ where: `(${SURE} OR ${SEED_NAMED})`,
21
+ sure: `${SURE} AS sure`,
22
+ params: seedParams(),
23
+ });
24
+ /** The owner's newest word on each identity: `true` test data, `false` a real contact. */
25
+ export const testVerdicts = (database) => {
26
+ const verdicts = new Map();
27
+ for (const row of database
28
+ .prepare("SELECT status, payload FROM proposed_actions WHERE kind = ? AND status IN ('approved', 'rejected') ORDER BY id")
29
+ .all(TEST_DATA_KIND))
30
+ for (const ref of JSON.parse(String(row.payload)).identities)
31
+ verdicts.set(ref, row.status === "approved");
32
+ return verdicts;
33
+ };
34
+ /**
35
+ * People memo keeps out of every list as test data: each identity is a sure test run's or one the owner called test
36
+ * data, and the owner called none a real contact. Never the owner.
37
+ */
38
+ export const hiddenTestPeople = (database) => {
39
+ const { where, sure, params } = testIdentitySql();
40
+ const verdicts = testVerdicts(database);
41
+ const test = new Map();
42
+ const note = (person, ref, isSure) => {
43
+ const refs = test.get(person) ?? new Map();
44
+ refs.set(ref, isSure || refs.get(ref) === true);
45
+ test.set(person, refs);
46
+ };
47
+ for (const row of database
48
+ .prepare(`SELECT l.person_id AS person, i.provider || ':' || i.external_id AS ref, ${sure} FROM identity_links l ` +
49
+ `JOIN identities i ON i.id = l.identity_id WHERE ${where}`)
50
+ .all(...params))
51
+ note(Number(row.person), String(row.ref), Number(row.sure) === 1);
52
+ for (const [ref, isTest] of verdicts) {
53
+ if (!isTest)
54
+ continue;
55
+ const person = personOf(database, pkOf(database, ref));
56
+ if (person !== undefined)
57
+ note(person, ref, false);
58
+ }
59
+ const hidden = new Set();
60
+ const held = database.prepare("SELECT count(*) AS n, max(p.owner) AS owner FROM identity_links l JOIN persons p ON p.id = l.person_id " +
61
+ "WHERE l.person_id = ?");
62
+ for (const [person, refs] of test) {
63
+ const told = [...refs].every(([ref, isSure]) => verdicts.get(ref) ?? isSure);
64
+ if (!told)
65
+ continue;
66
+ const row = held.get(person);
67
+ if (Number(row?.owner) !== 1 && Number(row?.n) === refs.size)
68
+ hidden.add(person);
69
+ }
70
+ return hidden;
71
+ };
72
+ /**
73
+ * Records the owner's word on the identities: test data, or a real contact. The next people list works the person's
74
+ * kind out again, since no trigger watches a decision.
75
+ */
76
+ export const judgeTestData = (context, person, identities, test) => {
77
+ const operations = proposalOperationsOver(context);
78
+ const payload = { person: String(person), identities: [...identities] };
79
+ const reason = test ? "the owner called it test data" : "the owner called it a real contact";
80
+ const proposed = operations.propose({ kind: TEST_DATA_KIND, by: "owner", payload, reason });
81
+ if (test)
82
+ operations.approve(proposed.id, { reason });
83
+ else
84
+ operations.reject(proposed.id, "owner", { reason });
85
+ context.database.prepare("UPDATE persons SET kind = NULL WHERE id = ?").run(person);
86
+ };
87
+ /** Deletes the owner's words on identities no longer in the store: a payload names the address. */
88
+ export const forgetErasedTestData = (database) => {
89
+ for (const row of database.prepare("SELECT id, payload FROM proposed_actions WHERE kind = ?").all(TEST_DATA_KIND))
90
+ if (JSON.parse(String(row.payload)).identities.some((ref) => pkOf(database, ref) === undefined))
91
+ database.prepare("DELETE FROM proposed_actions WHERE id = ?").run(Number(row.id));
92
+ };
@@ -36,6 +36,9 @@ export interface PersonFacts {
36
36
  email?: string | null;
37
37
  /** As the provider showed it, whole; only where it shows it to the owner. */
38
38
  phone?: string | null;
39
+ /** Every phone and address the source gives, as a CRM contact holds several; left out, the stored ones stay. */
40
+ phones?: string[];
41
+ emails?: string[];
39
42
  }
40
43
  /** One identity in one messenger, by the messenger's own id. `provider` is any string: `email` is one. */
41
44
  export interface IdentityRef {
@@ -57,6 +60,9 @@ export interface LinkedIdentity extends IdentityRef {
57
60
  /** The phone and address its source gave it, when it gave one. */
58
61
  phone?: string | null;
59
62
  email?: string | null;
63
+ /** Every phone and address its source gave, `phone` and `email` among them; empty when it gave none. */
64
+ phones?: string[];
65
+ emails?: string[];
60
66
  isBot: boolean | null;
61
67
  /** The accounts in this store that have seen it. */
62
68
  accounts: Id[];
@@ -11,8 +11,9 @@ export type TaskVerdict = (typeof TASK_VERDICTS)[number];
11
11
  export type ClosedState = (typeof CLOSED_STATES)[number];
12
12
  export declare const isClosedState: (state: string) => state is ClosedState;
13
13
  /**
14
- * A task points at what it is about and never holds its text: `source` is a locator the host
15
- * resolves (`msg:…` for a message), so a deleted message leaves nothing behind here.
14
+ * A task points at what it is about and never copies its source's text: `source` is a locator the host resolves
15
+ * (`msg:…` for a message), so a deleted message leaves nothing behind here. Only a rule that wrote its own `title` and
16
+ * `description`, such as an owner's stage rule naming a deal, stores text with it.
16
17
  */
17
18
  export interface Task {
18
19
  id: string;
@@ -32,6 +33,9 @@ export interface Task {
32
33
  key?: string;
33
34
  /** One name from the host's category list; a host without one leaves it unset. */
34
35
  category?: string;
36
+ /** Given by a rule that knows what to do, such as an owner's stage rule; a found task's comes from its source. */
37
+ title?: string;
38
+ description?: string;
35
39
  /** Who works on it now, until `claimedUntil`; a lapsed claim holds nothing. */
36
40
  claimedBy?: string;
37
41
  claimedUntil?: Date;
@@ -9,6 +9,8 @@ export interface NewTask {
9
9
  origin: TaskOrigin;
10
10
  dueAt?: Date;
11
11
  category?: string;
12
+ title?: string;
13
+ description?: string;
12
14
  }
13
15
  export interface CloseOptions {
14
16
  as: ClosedState;
@@ -88,6 +88,7 @@
88
88
  "fileTexts": [{ "chat": "7", "message": "105", "attachment": 1, "text": "Накладная № 17, оплата до 31 января" }],
89
89
  "recipes": [
90
90
  { "title": "Слово", "query": "invoice", "ids": ["101", "102", "105", "106"] },
91
+ { "title": "Слово по началу", "query": "invoi*", "ids": ["101", "102", "105", "106"] },
91
92
  { "title": "Другие формы слова", "query": "квартира", "ids": ["109"] },
92
93
  { "title": "Фраза в кавычках — тоже в любой форме", "query": "\"квартира\"", "ids": ["109"] },
93
94
  { "title": "Только точная форма", "query": "exact:квартира", "ids": [] },
@@ -98,8 +99,10 @@
98
99
  "ids": ["101", "102", "105", "106"]
99
100
  },
100
101
  { "title": "Чат по имени", "query": "chat:\"Work fixture\" AND invoice", "ids": ["101", "102", "105", "106"] },
102
+ { "title": "Чат по части названия", "query": "chat:*work* AND invoice", "ids": ["101", "102", "105", "106"] },
101
103
  { "title": "Диапазон дат", "query": "invoice date:[2026-01-20 TO 2026-01-22}", "ids": ["101", "102"] },
102
104
  { "title": "Все сообщения автора", "query": "from:\"Bob Synthetic\"", "ids": ["106", "107", "108"] },
105
+ { "title": "Автор по части имени", "query": "from:Bo*", "ids": ["106", "107", "108"] },
103
106
  { "title": "Начиная с даты", "query": "invoice date>=2026-01-21", "ids": ["102", "105", "106"] },
104
107
  { "title": "Личная переписка", "query": "passport kind:private", "ids": ["103"] },
105
108
  { "title": "Кандидат secret в Избранном", "query": "preset:secret kind:saved", "ids": ["104"] },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.639.0",
3
+ "version": "0.641.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",