@wirecat/cli-core 0.673.0 → 0.674.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 (71) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/config-command.d.ts +6 -0
  4. package/dist/cli/config-command.js +1 -1
  5. package/dist/cli/first-run.js +2 -1
  6. package/dist/cli/help/sections.js +1 -0
  7. package/dist/cli/index.d.ts +3 -1
  8. package/dist/cli/index.js +3 -1
  9. package/dist/cli/messenger/projects-command.js +12 -4
  10. package/dist/cli/project-evidence.js +1 -1
  11. package/dist/cli/project-status.js +1 -1
  12. package/dist/cli/settings.d.ts +1 -0
  13. package/dist/cli/settings.js +6 -3
  14. package/dist/cli/setup-command.d.ts +4 -0
  15. package/dist/cli/setup-command.js +394 -0
  16. package/dist/cli/shared-command-exports.d.ts +6 -0
  17. package/dist/cli/shared-command-exports.js +2 -0
  18. package/dist/cli/unknown-profile.js +1 -1
  19. package/dist/crm/cli/index.js +1 -0
  20. package/dist/entities/recorded-meeting.d.ts +2 -0
  21. package/dist/entities/recorded-meeting.js +3 -0
  22. package/dist/errors/reasons.js +7 -0
  23. package/dist/kit/index.d.ts +1 -0
  24. package/dist/kit/index.js +1 -0
  25. package/dist/meetings/answers.d.ts +1 -0
  26. package/dist/meetings/index.d.ts +3 -2
  27. package/dist/meetings/index.js +2 -1
  28. package/dist/meetings/item.d.ts +17 -1
  29. package/dist/meetings/item.js +16 -0
  30. package/dist/meetings/model.d.ts +23 -0
  31. package/dist/meetings/model.js +2 -1
  32. package/dist/meetings/pull.js +1 -0
  33. package/dist/meetings/store.d.ts +1 -1
  34. package/dist/oauth/storage.js +3 -1
  35. package/dist/services/metadata.d.ts +1 -1
  36. package/dist/services/person-meetings.d.ts +3 -0
  37. package/dist/services/person-meetings.js +3 -1
  38. package/dist/services/project-purposes.d.ts +1 -1
  39. package/dist/services/project-purposes.js +2 -2
  40. package/dist/setup/answers.d.ts +58 -0
  41. package/dist/setup/answers.js +194 -0
  42. package/dist/setup/define.d.ts +60 -0
  43. package/dist/setup/define.js +214 -0
  44. package/dist/setup/document.d.ts +205 -0
  45. package/dist/setup/document.js +215 -0
  46. package/dist/setup/files.d.ts +6 -0
  47. package/dist/setup/files.js +46 -0
  48. package/dist/store/index.d.ts +1 -0
  49. package/dist/store/people.d.ts +14 -0
  50. package/dist/store/people.js +8 -1
  51. package/dist/store/sqlite/facts.d.ts +28 -4
  52. package/dist/store/sqlite/facts.js +56 -6
  53. package/dist/store/sqlite/identity-rekey.d.ts +46 -0
  54. package/dist/store/sqlite/identity-rekey.js +191 -0
  55. package/dist/store/sqlite/manifest.js +1 -0
  56. package/dist/store/sqlite/meeting-reads.js +1 -1
  57. package/dist/store/sqlite/meeting-values.d.ts +2 -1
  58. package/dist/store/sqlite/meeting-values.js +23 -1
  59. package/dist/store/sqlite/meetings.js +10 -3
  60. package/dist/store/sqlite/migrations.generated.js +9 -0
  61. package/dist/store/sqlite/note-search.js +2 -2
  62. package/dist/store/sqlite/notes.d.ts +3 -1
  63. package/dist/store/sqlite/notes.js +8 -6
  64. package/dist/store/sqlite/schema.d.ts +153 -0
  65. package/dist/store/sqlite/schema.js +12 -0
  66. package/dist/store/sqlite/things.d.ts +2 -0
  67. package/dist/store/sqlite/things.js +5 -0
  68. package/dist/terminal/sign-in-steps.d.ts +12 -1
  69. package/dist/terminal/sign-in-steps.js +3 -3
  70. package/package.json +2 -2
  71. package/parity.json +3 -3
@@ -0,0 +1,46 @@
1
+ import { closeSync, openSync, readSync, realpathSync, statSync } from "node:fs";
2
+ import { relative, resolve, sep } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { SETUP_LIMITS } from "./document.js";
5
+ /** PNG, JPEG and WebP by their first bytes, whatever the file is named. */
6
+ const IMAGES = [
7
+ (head) => head.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
8
+ (head) => head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff,
9
+ (head) => head.toString("latin1", 0, 4) === "RIFF" && head.toString("latin1", 8, 12) === "WEBP",
10
+ ];
11
+ const headOf = (path) => {
12
+ const head = Buffer.alloc(12);
13
+ const fd = openSync(path, "r");
14
+ try {
15
+ readSync(fd, head, 0, head.length, 0);
16
+ }
17
+ finally {
18
+ closeSync(fd);
19
+ }
20
+ return head;
21
+ };
22
+ /**
23
+ * What is wrong with the flow's image files, from the package root: each exists inside it (links followed), is a PNG,
24
+ * JPEG or WebP by its first bytes, never SVG, and is at most 2 MB. For the CLI's own test, never at start.
25
+ */
26
+ export const setupFileProblems = (setup, packageRoot) => {
27
+ const root = realpathSync(typeof packageRoot === "string" ? packageRoot : fileURLToPath(packageRoot));
28
+ return Object.entries(setup.document.assets ?? {}).flatMap(([id, { file }]) => {
29
+ const where = `assets.${id} (${file})`;
30
+ let path;
31
+ try {
32
+ path = realpathSync(resolve(root, file));
33
+ }
34
+ catch {
35
+ return [`${where}: no such file in ${root}`];
36
+ }
37
+ const inside = relative(root, path);
38
+ if (inside.startsWith(`..${sep}`) || inside === "..")
39
+ return [`${where}: leads outside the package`];
40
+ const size = statSync(path).size;
41
+ if (size > SETUP_LIMITS.imageBytes)
42
+ return [`${where}: is ${size} bytes, over ${SETUP_LIMITS.imageBytes}`];
43
+ const head = headOf(path);
44
+ return IMAGES.some((matches) => matches(head)) ? [] : [`${where}: is not a PNG, JPEG or WebP image`];
45
+ });
46
+ };
@@ -63,6 +63,7 @@ export type { EvidenceSource } from "./sqlite/evidence-sources.js";
63
63
  export type { Fact, FactInput, FactsStore } from "./sqlite/facts.js";
64
64
  export type { FileListQuery, FilesStore, StoredFile } from "./sqlite/files.js";
65
65
  export type { Allocation, FinanceStore, Invoice, InvoiceDetail, InvoiceInput, InvoiceLine, InvoiceLineInput, OpenTotal, Payment as FinancePayment, PaymentDetail as FinancePaymentDetail, PaymentInput as FinancePaymentInput, } from "./sqlite/finance.js";
66
+ export type { IdentityRekey, IdentityRekeyOutcome, IdentityRekeys } from "./sqlite/identity-rekey.js";
66
67
  export { IMPORTED_DOCUMENT_QUERY, type ImportedDocuments } from "./sqlite/imported-documents.js";
67
68
  export type { Involvement, InvolvementStore } from "./sqlite/involvements.js";
68
69
  export type { Annotation, KnowledgeRelation, KnowledgeStore, KnowledgeTarget, LabelledType, Organization, Project, Reminder, } from "./sqlite/knowledge.js";
@@ -5,6 +5,7 @@ import type { Decider } from "./decisions.js";
5
5
  import type { IdentityLinkDecision, IdentityLinkFilter, IdentityLinkInput, IdentityLinkRow, MatchScan } from "./identity-links.js";
6
6
  import type { IdentitySplitDecision, IdentitySplitFilter, IdentitySplitInput, IdentitySplitRow } from "./identity-splits.js";
7
7
  import type { ContactFilter } from "./sqlite/identities.js";
8
+ import { type IdentityRekey, type IdentityRekeys } from "./sqlite/identity-rekey.js";
8
9
  import type { StoreContext } from "./sqlite/open.js";
9
10
  import { type PeopleList, type PeopleListOptions, type SimilarPerson } from "./sqlite/people-list.js";
10
11
  import { type KeptPerson, type PersonDoubts, type TestDataPerson } from "./sqlite/person-doubts.js";
@@ -75,6 +76,19 @@ export interface PeopleStore extends AccountPeople {
75
76
  /** Records the decision in `identity_link_events`; `unlinkIdentity` undoes it. */
76
77
  linkIdentities(person: IdentityRef, other: IdentityRef, options: LinkOptions): Promise<PersonRecord>;
77
78
  unlinkIdentity(identity: IdentityRef, options: UnlinkOptions): Promise<PersonRecord>;
79
+ /**
80
+ * The provider now names its identities by other ids, such as a phone number written another way. Each pair, in
81
+ * order and each in its own savepoint: with no `to` stored the identity takes the new id, and `phone` when given
82
+ * (`renamed`); with `to` stored, `from` merges into it, with its person and every row that points at it (`merged`);
83
+ * with no `from`, or `from` equal to `to`, nothing changes (`unchanged`), so a second run is all `unchanged`; an
84
+ * empty `to` is `skipped`. Stops once it has held the write lock for `lockMs` (default 250): `taken` says how many
85
+ * pairs it got to, so the caller passes the rest again. A pair that cannot merge is in `refused`, and the others
86
+ * still apply. Then the phone rule links the renamed and merged identities to the people with their number.
87
+ */
88
+ rekeyIdentities(provider: Provider, pairs: readonly IdentityRekey[], options?: {
89
+ lockMs?: number;
90
+ by?: string;
91
+ }): Promise<IdentityRekeys>;
78
92
  /** The people merged into this one, newest first, each with the identities that came from it. */
79
93
  merges(uid: string): Promise<PersonMerge[]>;
80
94
  /** The owner's undo of a merge: the identities that came from `from` go back to it. Gives `from` again. */
@@ -3,12 +3,13 @@ import { keysOver } from "./keys.js";
3
3
  import { ownerPerson } from "./sqlite/actors.js";
4
4
  import * as identities from "./sqlite/identities.js";
5
5
  import * as identityProposals from "./sqlite/identity-proposals.js";
6
+ import { rekeyIdentities } from "./sqlite/identity-rekey.js";
6
7
  import * as identitySplits from "./sqlite/identity-split-proposals.js";
7
8
  import { linkToOwner } from "./sqlite/own-identities.js";
8
9
  import { countPeople, listPeople, similarPeople, } from "./sqlite/people-list.js";
9
10
  import { keepPerson, markTestData, personDoubts, } from "./sqlite/person-doubts.js";
10
11
  import * as personLinks from "./sqlite/person-links.js";
11
- import { PROPOSAL_SCORE, RULE, scanMatches } from "./sqlite/person-match-scan.js";
12
+ import { linkPhones, PROPOSAL_SCORE, RULE, scanMatches } from "./sqlite/person-match-scan.js";
12
13
  import * as personMerges from "./sqlite/person-merges.js";
13
14
  import { personPreparation } from "./sqlite/person-preparation.js";
14
15
  import { personSeenInAccounts } from "./sqlite/person-scope.js";
@@ -124,6 +125,12 @@ export const peopleStoreOver = (context, keyed) => {
124
125
  unlinkIdentity: async (identity, options) => {
125
126
  return write(database, () => personLinks.unlinkIdentity(context, identity, options));
126
127
  },
128
+ rekeyIdentities: async (provider, pairs, { lockMs = 250, by = provider } = {}) => {
129
+ const done = write(database, () => rekeyIdentities(context, provider, pairs, { lockMs, by }));
130
+ if (done.touched.length > 0)
131
+ linkPhones(context, new Set(done.touched));
132
+ return done;
133
+ },
127
134
  merges: async (uid) => personMerges.merges(context, uid),
128
135
  undoMerge: async (to, from, by) => write(database, () => personMerges.undoMerge(context, to, from, by)),
129
136
  split: async (uid, chosen, by) => write(database, () => personMerges.split(context, uid, chosen, by)),
@@ -39,9 +39,27 @@ export interface Fact {
39
39
  evidence: string[];
40
40
  /** The open review of its sources (`memory_source_review`), when one waits for the owner. */
41
41
  sourceReview: SourceReviewMarker | null;
42
+ /** Who reversed a decision, when and why; only on a decision reversed with a reason or by an agent. */
43
+ reversal?: {
44
+ by: "owner" | "agent";
45
+ bot: string | null;
46
+ at: string;
47
+ reason: string | null;
48
+ };
42
49
  createdAt: string;
43
50
  updatedAt: string;
44
51
  }
52
+ /** That a fact was removed, by whom, when and why: never what it said. */
53
+ export interface FactRemoval {
54
+ /** The removed fact's `fact:<id>`; it no longer opens. */
55
+ fact: string;
56
+ /** What it was about, as it was then; `null` for nothing. */
57
+ subject: string | null;
58
+ removedBy: "owner" | "agent";
59
+ bot: string | null;
60
+ reason: string | null;
61
+ removedAt: string;
62
+ }
45
63
  export interface FactInput {
46
64
  type: Fact["type"];
47
65
  statement: string;
@@ -75,8 +93,8 @@ export interface FactsStore {
75
93
  }): Promise<ListResult<Fact>>;
76
94
  /** The owner, or an agent for the owner, accepts a proposed fact; the fact it supersedes stops holding. */
77
95
  accept(reference: string, by: Decider, reason?: string): Promise<Fact>;
78
- /** An accepted decision no longer holds and nothing replaced it. */
79
- reverse(reference: string, by: Decider): Promise<Fact>;
96
+ /** An accepted decision no longer holds and nothing replaced it; the reason is kept in `reversal`. */
97
+ reverse(reference: string, by: Decider, reason?: string): Promise<Fact>;
80
98
  /**
81
99
  * The owner takes back the approval of an accepted fact an agent proposed: it waits as `proposed` again. The step is
82
100
  * kept in `metadata.history`, with the decision it took back.
@@ -87,13 +105,19 @@ export interface FactsStore {
87
105
  /**
88
106
  * Erases the fact: its row, its links, its tags, and the memory it was migrated from, which still held its text.
89
107
  * Evidence of memories and facts that cited it stays with no pointer and shows as a missing source; `links` counts
90
- * the links erased. A decision that replaced it no longer names it. A backup made before keeps it.
108
+ * the links erased. A decision that replaced it no longer names it. A backup made before keeps it. The removal is
109
+ * logged without the fact's text or value: its id, what it was about, who removed it, when and why (`removed`).
91
110
  */
92
- remove(reference: string, by: Decider): Promise<{
111
+ remove(reference: string, by: Decider, reason?: string): Promise<{
93
112
  ref: string;
94
113
  removed: true;
95
114
  links: number;
96
115
  }>;
116
+ /** The removal log, newest first: what `remove` kept of each removed fact. */
117
+ removed(options?: {
118
+ limit?: number;
119
+ offset?: number;
120
+ }): Promise<ListResult<FactRemoval>>;
97
121
  /** Each reference it rests on, read back; one deleted since is `missing`. */
98
122
  sources(reference: string): Promise<EvidenceSource[]>;
99
123
  }
@@ -39,6 +39,7 @@ export const factOperationsOver = (context) => {
39
39
  source: String(row.source),
40
40
  evidence: evidenceOf(context, { type: "fact", id: Number(row.id) }),
41
41
  sourceReview: sourceReviewOf(database, { type: "fact", id: Number(row.id) }),
42
+ ...reversalOf(row),
42
43
  createdAt: iso(row.created_at),
43
44
  updatedAt: iso(row.updated_at),
44
45
  });
@@ -63,9 +64,11 @@ export const factOperationsOver = (context) => {
63
64
  row.supersedes_id != null &&
64
65
  database.prepare("SELECT 1 FROM facts WHERE id = ? AND status = 'accepted'").get(Number(row.supersedes_id)) !==
65
66
  undefined;
67
+ /** Who removed or reversed it and why: the agent's own reason first, then the one given. */
68
+ const whyOf = (by, reason) => [by === "owner" ? undefined : by.reason.trim(), reason?.trim() || undefined].filter(Boolean).join(": ") || null;
66
69
  /** Keeps who decided for the owner and why in `metadata.decision`; the decider's actor is in `confirmed_by`. */
67
70
  const keepDecision = (id, by, reason) => {
68
- const why = [by === "owner" ? undefined : by.reason.trim(), reason?.trim() || undefined].filter(Boolean).join(": ");
71
+ const why = whyOf(by, reason) ?? "";
69
72
  if (by === "owner" && !why)
70
73
  return;
71
74
  const decision = by === "owner" ? { by: "owner", reason: why } : { by: "agent", bot: by.bot, reason: why };
@@ -160,7 +163,7 @@ export const factOperationsOver = (context) => {
160
163
  write(database, () => accept(id, by));
161
164
  return factOf(rowOf(reference));
162
165
  },
163
- reverse: (reference, by) => {
166
+ reverse: (reference, by, reason) => {
164
167
  const row = rowOf(reference);
165
168
  assertMayWithdraw({ id: `fact:${row.id}`, proposedBy: { type: "unknown" }, proposed: false }, by);
166
169
  if (row.type !== "decision")
@@ -168,7 +171,17 @@ export const factOperationsOver = (context) => {
168
171
  if (row.status !== "accepted")
169
172
  throw new CliError("validation_error", "only an accepted decision can be reversed");
170
173
  write(database, () => {
171
- database.prepare("UPDATE facts SET status = 'reversed', updated_at = ? WHERE id = ?").run(now(), Number(row.id));
174
+ const at = now();
175
+ const why = whyOf(by, reason);
176
+ database.prepare("UPDATE facts SET status = 'reversed', updated_at = ? WHERE id = ?").run(at, Number(row.id));
177
+ // Metadata keeps a project's facts out of a project transfer, so a bare owner's reversal writes none.
178
+ if (by !== "owner" || why !== null) {
179
+ const step = { step: "reversed", by: by === "owner" ? "owner" : "agent", bot: by === "owner" ? null : by.bot };
180
+ database
181
+ .prepare("UPDATE facts SET metadata = json_set(coalesce(metadata, '{}'), '$.history', " +
182
+ "json(coalesce(json_extract(metadata, '$.history'), '[]')), '$.history[#]', json(?)) WHERE id = ?")
183
+ .run(JSON.stringify({ ...step, at: iso(at), reason: why }), Number(row.id));
184
+ }
172
185
  closing(Number(row.id), by, "reversed");
173
186
  });
174
187
  return factOf(rowOf(reference));
@@ -216,10 +229,11 @@ export const factOperationsOver = (context) => {
216
229
  });
217
230
  return factOf(rowOf(reference));
218
231
  },
219
- remove: (reference, by) => {
232
+ remove: (reference, by, reason) => {
220
233
  const row = rowOf(reference);
221
234
  withdrawn(row, by);
222
235
  const id = Number(row.id);
236
+ const { subject } = subjectOf(database, row);
223
237
  const twin = row.source === "memory" && row.metadata != null ? migratedFrom(String(row.metadata)) : undefined;
224
238
  const links = erase(database, () => {
225
239
  keepHighestId(database, "facts", now());
@@ -231,15 +245,50 @@ export const factOperationsOver = (context) => {
231
245
  database.prepare("DELETE FROM links WHERE from_type = 'fact' AND from_id = ?").run(id);
232
246
  database.prepare("DELETE FROM taggings WHERE taggable_type = 'fact' AND taggable_id = ?").run(id);
233
247
  database.prepare("DELETE FROM facts WHERE id = ?").run(id);
248
+ database
249
+ .prepare("INSERT INTO fact_removals (fact_id, subject, removed_by, bot, reason, removed_at) VALUES (?, ?, ?, ?, ?, ?)")
250
+ .run(id, subject, by === "owner" ? "owner" : "agent", by === "owner" ? null : by.bot, whyOf(by, reason), now());
234
251
  if (twin !== undefined)
235
252
  database.prepare("DELETE FROM memories WHERE id = ? AND deleted_at IS NOT NULL").run(twin);
236
253
  return count;
237
254
  });
238
255
  return { ref: `fact:${id}`, removed: true, links };
239
256
  },
257
+ removed: (options = {}) => {
258
+ const limit = Math.min(Math.max(options.limit ?? 100, 1), 500);
259
+ const offset = Math.max(options.offset ?? 0, 0);
260
+ const rows = database
261
+ .prepare("SELECT * FROM fact_removals ORDER BY removed_at DESC, id DESC LIMIT ? OFFSET ?")
262
+ .all(limit + 1, offset)
263
+ .map((one) => ({
264
+ fact: `fact:${one.fact_id}`,
265
+ subject: one.subject == null ? null : String(one.subject),
266
+ removedBy: one.removed_by === "agent" ? "agent" : "owner",
267
+ bot: one.bot == null ? null : String(one.bot),
268
+ reason: one.reason == null ? null : String(one.reason),
269
+ removedAt: iso(one.removed_at),
270
+ }));
271
+ return pageOfRows(rows, limit, offset);
272
+ },
240
273
  sources: (reference) => evidenceSourcesOf(database, { type: "fact", id: Number(rowOf(reference).id) }),
241
274
  };
242
275
  };
276
+ const reversalOf = (row) => {
277
+ if (row.status !== "reversed" || row.metadata == null)
278
+ return {};
279
+ const { history } = JSON.parse(String(row.metadata));
280
+ const step = history?.findLast((one) => one.step === "reversed");
281
+ if (!step)
282
+ return {};
283
+ return {
284
+ reversal: {
285
+ by: step.by === "agent" ? "agent" : "owner",
286
+ bot: typeof step.bot === "string" ? step.bot : null,
287
+ at: String(step.at),
288
+ reason: typeof step.reason === "string" ? step.reason : null,
289
+ },
290
+ };
291
+ };
243
292
  const migratedFrom = (metadata) => {
244
293
  try {
245
294
  const { memory } = JSON.parse(metadata);
@@ -256,10 +305,11 @@ export const factsStoreOver = (context) => {
256
305
  get: async (reference) => operations.get(reference),
257
306
  list: async (options) => operations.list(options),
258
307
  accept: async (reference, by, reason) => operations.accept(reference, by, reason),
259
- reverse: async (reference, by) => operations.reverse(reference, by),
308
+ reverse: async (reference, by, reason) => operations.reverse(reference, by, reason),
260
309
  revoke: async (reference, by, reason) => operations.revoke(reference, by, reason),
261
310
  reject: async (reference, by, reason) => operations.reject(reference, by, reason),
262
- remove: async (reference, by) => operations.remove(reference, by),
311
+ remove: async (reference, by, reason) => operations.remove(reference, by, reason),
312
+ removed: async (options) => operations.removed(options),
263
313
  sources: async (reference) => operations.sources(reference),
264
314
  };
265
315
  };
@@ -0,0 +1,46 @@
1
+ import type { Id, Provider } from "../../domain/models.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ import type { StoreContext } from "./open.js";
4
+ export type IdentityRekeyOutcome = "renamed" | "merged" | "unchanged" | "skipped";
5
+ export interface IdentityRekey {
6
+ from: Id;
7
+ to: Id;
8
+ /** The identity's phone under its new id, such as the E.164 number the new id holds; left as it is when absent. */
9
+ phone?: string | null;
10
+ }
11
+ export interface IdentityRekeys {
12
+ /** How many of the pairs this pass got to, from the first: the rest wait for another call. */
13
+ taken: number;
14
+ renamed: number;
15
+ merged: number;
16
+ unchanged: number;
17
+ /** Pairs with an empty `to`. */
18
+ skipped: number;
19
+ refused: {
20
+ from: Id;
21
+ to: Id;
22
+ error: unknown;
23
+ }[];
24
+ /** The identities a pair renamed or merged into, by their new id: what the phone rule then looked at. */
25
+ touched: number[];
26
+ }
27
+ /** Every column a foreign key points from at `table`, identity_links last: deleting its row drops involvements. */
28
+ export declare const foreignKeysTo: (database: CacheDatabase, table: string) => {
29
+ table: string;
30
+ column: string;
31
+ }[];
32
+ /**
33
+ * The provider now names one of its identities `to` instead of `from`. With no `to` stored, the identity takes the new
34
+ * id. With `to` stored too, `from` merges into it: its people become one person (the owner's stays), and every row
35
+ * that points at `from`, through a foreign key or an `<x>_type = 'identity'` pointer, points at `to`. Replaying it
36
+ * changes nothing. Runs inside `write`.
37
+ */
38
+ export declare const rekeyIdentity: (context: StoreContext, provider: Provider, { from, to, phone }: IdentityRekey, by: string) => IdentityRekeyOutcome;
39
+ /**
40
+ * `rekeyIdentity` for a run of pairs, in order, each in its own savepoint so a refused one leaves the others applied,
41
+ * stopping once `lockMs` has passed so other processes get the write lock. Runs inside `write`.
42
+ */
43
+ export declare const rekeyIdentities: (context: StoreContext, provider: Provider, pairs: readonly IdentityRekey[], { lockMs, by }: {
44
+ lockMs: number;
45
+ by: string;
46
+ }) => IdentityRekeys;
@@ -0,0 +1,191 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { pointerPairs } from "./entity-types.js";
3
+ import { settleLinks } from "./identity-link-rows.js";
4
+ import { mergePerson } from "./person-links.js";
5
+ import { write } from "./transaction.js";
6
+ const quoted = (name) => `"${name.replace(/"/g, '""')}"`;
7
+ const columnsOf = (database, table) => database.prepare("SELECT name, pk, type FROM pragma_table_info(?)").all(table);
8
+ /** Every column a foreign key points from at `table`, identity_links last: deleting its row drops involvements. */
9
+ export const foreignKeysTo = (database, table) => database
10
+ .prepare(`SELECT m.name AS tbl, f."from" AS col FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f
11
+ WHERE m.type = 'table' AND f."table" = ? ORDER BY m.name = 'identity_links', m.name, f."from"`)
12
+ .all(table)
13
+ .map((row) => ({ table: String(row.tbl), column: String(row.col) }));
14
+ /** The unique keys of `table` that hold `column`: indexes, and an integer primary key, which has none. */
15
+ const uniqueKeys = (database, table, column) => {
16
+ const keys = [];
17
+ const primary = columnsOf(database, table).filter((one) => Number(one.pk) > 0);
18
+ if (primary.length === 1 && primary[0]?.name === column && String(primary[0]?.type).toLowerCase() === "integer")
19
+ keys.push({ columns: [column], where: null });
20
+ for (const index of database
21
+ .prepare('SELECT name, partial FROM pragma_index_list(?) WHERE "unique" = 1')
22
+ .all(table)) {
23
+ const columns = database
24
+ .prepare("SELECT name FROM pragma_index_info(?) ORDER BY seqno")
25
+ .all(String(index.name))
26
+ .map((one) => String(one.name));
27
+ if (!columns.includes(column))
28
+ continue;
29
+ const sql = Number(index.partial)
30
+ ? String(database.prepare("SELECT sql FROM sqlite_master WHERE name = ?").get(String(index.name))?.sql ?? "")
31
+ : "";
32
+ const where = /\bWHERE\b([\s\S]*)$/i.exec(sql)?.[1]?.trim() ?? null;
33
+ keys.push({ columns, where });
34
+ }
35
+ return keys;
36
+ };
37
+ const rowKey = (database, table) => columnsOf(database, table).some((one) => one.name === "id" && Number(one.pk) === 1) ? "id" : "rowid";
38
+ /**
39
+ * Moves every row of `table` whose `column` holds `from` to `to`. A row the kept identity already has under a unique
40
+ * key folds into that twin: the twin keeps its values and takes the ones it lacks, what pointed at the row points at
41
+ * the twin, and the row goes. A row with no twin is refused, so nothing is dropped unseen.
42
+ */
43
+ const moveRows = (context, table, column, from, to) => {
44
+ const { database } = context;
45
+ const t = quoted(table);
46
+ const c = quoted(column);
47
+ database.prepare(`UPDATE OR IGNORE ${t} SET ${c} = ? WHERE ${c} = ?`).run(to, from);
48
+ const key = rowKey(database, table);
49
+ const left = database.prepare(`SELECT ${key} AS pk, * FROM ${t} WHERE ${c} = ?`).all(from);
50
+ if (left.length === 0)
51
+ return;
52
+ const keys = uniqueKeys(database, table, column);
53
+ const fill = columnsOf(database, table)
54
+ .map((one) => String(one.name))
55
+ .filter((name) => name !== column && name !== "id");
56
+ for (const row of left) {
57
+ const twin = twinOf(database, table, column, to, row, keys);
58
+ if (twin === undefined)
59
+ throw new CliError("conflict", `${table}.${column}: a row of the old identity has no counterpart to merge into`, {
60
+ reason: "identity.merge-conflict",
61
+ });
62
+ foldRow(context, table, key, fill, Number(row.pk), twin);
63
+ for (const ref of foreignKeysTo(database, table))
64
+ moveRows(context, ref.table, ref.column, Number(row.pk), twin);
65
+ database.prepare(`DELETE FROM ${t} WHERE ${key} = ?`).run(Number(row.pk));
66
+ }
67
+ };
68
+ const twinOf = (database, table, column, to, row, keys) => {
69
+ const key = rowKey(database, table);
70
+ for (const unique of keys) {
71
+ const others = unique.columns.filter((one) => one !== column);
72
+ const found = database
73
+ .prepare(`SELECT ${key} AS pk FROM ${quoted(table)} WHERE ${quoted(column)} = ?` +
74
+ others.map((one) => ` AND ${quoted(one)} IS ?`).join("") +
75
+ (unique.where ? ` AND (${unique.where})` : ""))
76
+ .get(to, ...others.map((one) => row[one]));
77
+ if (found)
78
+ return Number(found.pk);
79
+ }
80
+ return undefined;
81
+ };
82
+ /** The twin keeps what it has; `account_identities` keeps the newest message and the address book mark of either. */
83
+ const foldRow = (context, table, key, fill, from, to) => {
84
+ const t = quoted(table);
85
+ const latest = new Set(table === "account_identities" ? ["last_messaged_at", "address_book"] : []);
86
+ const sets = fill.map((name) => latest.has(name)
87
+ ? `${quoted(name)} = max(coalesce(${quoted(name)}, 0), coalesce((SELECT o.${quoted(name)} FROM ${t} o WHERE o.${key} = ?), 0))`
88
+ : `${quoted(name)} = coalesce(${quoted(name)}, (SELECT o.${quoted(name)} FROM ${t} o WHERE o.${key} = ?))`);
89
+ if (sets.length === 0)
90
+ return;
91
+ context.database.prepare(`UPDATE ${t} SET ${sets.join(", ")} WHERE ${key} = ?`).run(...fill.map(() => from), to);
92
+ };
93
+ /** `provider:id` strings in the owner's open and decided proposals follow the identity. */
94
+ const renameInProposals = (database, provider, from, to) => {
95
+ const [old, renamed] = [`${provider}:${from}`, `${provider}:${to}`];
96
+ const persons = [];
97
+ const rows = database
98
+ .prepare("SELECT id, payload FROM proposed_actions WHERE kind IN ('identity_link', 'identity_split') AND instr(payload, ?) > 0")
99
+ .all(JSON.stringify(old));
100
+ for (const row of rows) {
101
+ const payload = JSON.parse(String(row.payload));
102
+ for (const field of ["identity", "with"])
103
+ if (payload[field] === old)
104
+ payload[field] = renamed;
105
+ if (Array.isArray(payload.identities))
106
+ payload.identities = payload.identities.map((one) => (one === old ? renamed : one));
107
+ if (Array.isArray(payload.persons))
108
+ for (const one of payload.persons)
109
+ persons.push(Number(one));
110
+ database
111
+ .prepare("UPDATE proposed_actions SET payload = ? WHERE id = ?")
112
+ .run(JSON.stringify(payload), Number(row.id));
113
+ }
114
+ return persons;
115
+ };
116
+ const personOfIdentity = (database, identity) => {
117
+ const row = database.prepare("SELECT person_id FROM identity_links WHERE identity_id = ?").get(identity);
118
+ return row ? Number(row.person_id) : undefined;
119
+ };
120
+ /**
121
+ * The provider now names one of its identities `to` instead of `from`. With no `to` stored, the identity takes the new
122
+ * id. With `to` stored too, `from` merges into it: its people become one person (the owner's stays), and every row
123
+ * that points at `from`, through a foreign key or an `<x>_type = 'identity'` pointer, points at `to`. Replaying it
124
+ * changes nothing. Runs inside `write`.
125
+ */
126
+ export const rekeyIdentity = (context, provider, { from, to, phone }, by) => {
127
+ const { database } = context;
128
+ if (!to.trim())
129
+ return "skipped";
130
+ if (from === to)
131
+ return "unchanged";
132
+ const find = database.prepare("SELECT * FROM identities WHERE provider = ? AND external_id = ?");
133
+ const old = find.get(provider, from);
134
+ if (!old)
135
+ return "unchanged";
136
+ const oldId = Number(old.id);
137
+ const kept = find.get(provider, to);
138
+ const persons = renameInProposals(database, provider, from, to);
139
+ if (!kept) {
140
+ database.prepare("UPDATE identities SET external_id = ?, updated_at = ? WHERE id = ?").run(to, context.now(), oldId);
141
+ if (phone !== undefined)
142
+ database.prepare("UPDATE identities SET phone = ? WHERE id = ?").run(phone, oldId);
143
+ settleLinks(database, persons);
144
+ return "renamed";
145
+ }
146
+ const keptId = Number(kept.id);
147
+ const [mine, theirs] = [personOfIdentity(database, oldId), personOfIdentity(database, keptId)];
148
+ if (mine !== undefined && theirs !== undefined && mine !== theirs)
149
+ persons.push(mergePerson(context, mine, theirs, { method: "identity-rekey", by }));
150
+ for (const { table, pointer } of pointerPairs(database)) {
151
+ const where = `WHERE ${pointer}_type = 'identity' AND ${pointer}_id = ?`;
152
+ database.prepare(`UPDATE OR IGNORE ${quoted(table)} SET ${pointer}_id = ? ${where}`).run(keptId, oldId);
153
+ database.prepare(`DELETE FROM ${quoted(table)} ${where}`).run(oldId);
154
+ }
155
+ for (const { table, column } of foreignKeysTo(database, "identities"))
156
+ moveRows(context, table, column, oldId, keptId);
157
+ const fill = ["username", "name", "bot", "phone_hmac", "metadata", "description", "email", "phone"];
158
+ database
159
+ .prepare(`UPDATE identities SET ${fill.map((name) => `${name} = coalesce(${name}, (SELECT o.${name} FROM identities o WHERE o.id = ?))`).join(", ")}, updated_at = ? WHERE id = ?`)
160
+ .run(...fill.map(() => oldId), context.now(), keptId);
161
+ database.prepare("DELETE FROM identities WHERE id = ?").run(oldId);
162
+ if (phone !== undefined)
163
+ database.prepare("UPDATE identities SET phone = ? WHERE id = ?").run(phone, keptId);
164
+ settleLinks(database, [...persons, ...(theirs === undefined ? [] : [theirs])]);
165
+ return "merged";
166
+ };
167
+ /**
168
+ * `rekeyIdentity` for a run of pairs, in order, each in its own savepoint so a refused one leaves the others applied,
169
+ * stopping once `lockMs` has passed so other processes get the write lock. Runs inside `write`.
170
+ */
171
+ export const rekeyIdentities = (context, provider, pairs, { lockMs, by }) => {
172
+ const done = { taken: 0, renamed: 0, merged: 0, unchanged: 0, skipped: 0, refused: [], touched: [] };
173
+ const started = performance.now();
174
+ const now = context.database.prepare("SELECT id FROM identities WHERE provider = ? AND external_id = ?");
175
+ for (const pair of pairs) {
176
+ if (done.taken > 0 && performance.now() - started >= lockMs)
177
+ break;
178
+ done.taken += 1;
179
+ try {
180
+ const outcome = write(context.database, () => rekeyIdentity(context, provider, pair, by));
181
+ done[outcome] += 1;
182
+ const id = now.get(provider, pair.to)?.id;
183
+ if ((outcome === "renamed" || outcome === "merged") && id != null)
184
+ done.touched.push(Number(id));
185
+ }
186
+ catch (error) {
187
+ done.refused.push({ from: pair.from, to: pair.to, error });
188
+ }
189
+ }
190
+ return done;
191
+ };
@@ -131,6 +131,7 @@ export const MANIFEST = [
131
131
  { name: "20261110084658_version-64-deal-link-triggers", version: 64, minCompatible: 56 },
132
132
  { name: "20261110182602_version-65-found-task-titles", version: 65, minCompatible: 56 },
133
133
  { name: "20261110233711_version-66-identity-name-trigger", version: 66, minCompatible: 56 },
134
+ { name: "20261113154357_version-67-fact-removals-call-fields", version: 67, minCompatible: 56 },
134
135
  ];
135
136
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
136
137
  const migrations = [];
@@ -47,7 +47,7 @@ const parent = (database, input, budget, load) => {
47
47
  return {
48
48
  bytes,
49
49
  meeting: load
50
- ? meetingOf(database.prepare("SELECT * FROM meetings WHERE id = ?").get(input.meetingId) ?? missing())
50
+ ? meetingOf(database, database.prepare("SELECT * FROM meetings WHERE id = ?").get(input.meetingId) ?? missing())
51
51
  : undefined,
52
52
  };
53
53
  };
@@ -1,6 +1,7 @@
1
1
  import type { Meeting, Transcript, TranscriptRow } from "../../meetings/index.js";
2
+ import type { CacheDatabase } from "../driver.js";
2
3
  type Row = Record<string, unknown>;
3
- export declare const meetingOf: (row: Row) => Meeting;
4
+ export declare const meetingOf: (database: CacheDatabase, row: Row) => Meeting;
4
5
  export declare const transcriptOf: (row: Row) => Transcript;
5
6
  export declare const transcriptRowOf: (row: Row) => TranscriptRow;
6
7
  export {};
@@ -1,5 +1,26 @@
1
1
  import { fromJson, int, str } from "./events.js";
2
- export const meetingOf = (row) => ({
2
+ /** The participant a phone-line source marked `manager`, read only for a call. */
3
+ const managerOf = (database, meetingId) => {
4
+ const found = database
5
+ .prepare("SELECT p.display_name, i.name, l.person_id FROM meeting_participants p JOIN identities i ON i.id = p.identity_id " +
6
+ "LEFT JOIN identity_links l ON l.identity_id = p.identity_id WHERE p.meeting_id = ? AND p.role = 'manager' " +
7
+ "ORDER BY p.id LIMIT 1")
8
+ .get(meetingId);
9
+ if (!found)
10
+ return null;
11
+ return {
12
+ name: str(found.display_name) ?? str(found.name),
13
+ person: found.person_id == null ? null : `person:${found.person_id}`,
14
+ };
15
+ };
16
+ const callOf = (database, row) => row.direction == null && row.client_phone == null
17
+ ? {}
18
+ : {
19
+ direction: str(row.direction),
20
+ clientPhone: str(row.client_phone),
21
+ manager: managerOf(database, Number(row.id)),
22
+ };
23
+ export const meetingOf = (database, row) => ({
3
24
  id: Number(row.id),
4
25
  accountId: Number(row.account_id),
5
26
  meetingSeriesId: int(row.meeting_series_id),
@@ -17,6 +38,7 @@ export const meetingOf = (row) => ({
17
38
  participantsCount: int(row.participants_count),
18
39
  metadata: fromJson(row.metadata),
19
40
  deletedAt: int(row.deleted_at),
41
+ ...callOf(database, row),
20
42
  createdAt: Number(row.created_at),
21
43
  updatedAt: Number(row.updated_at),
22
44
  });
@@ -1,6 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { timezoneOf } from "@wirecat/cli-base/query";
3
- import { formatMeetingReference, joinKeyOf, MeetingError } from "../../meetings/index.js";
3
+ import { formatMeetingReference, joinKeyOf, MEETING_CALL_DIRECTIONS, MeetingError, } from "../../meetings/index.js";
4
4
  import { normalize } from "../normalize.js";
5
5
  import * as eventQueries from "./events.js";
6
6
  import { fromJson, int, page, str, toJson } from "./events.js";
@@ -106,7 +106,7 @@ const details = (database, id) => {
106
106
  const row = database.prepare("SELECT * FROM meetings WHERE id = ?").get(id);
107
107
  if (!row)
108
108
  return null;
109
- const meeting = meetingOf(row);
109
+ const meeting = meetingOf(database, row);
110
110
  const series = meeting.meetingSeriesId === null
111
111
  ? null
112
112
  : seriesOf(database.prepare("SELECT * FROM meeting_series WHERE id = ?").get(meeting.meetingSeriesId));
@@ -219,6 +219,11 @@ const fillGap = (context, input, meetingId) => {
219
219
  saveTranscripts(database, meetingId, input.transcripts, (position) => (position === null ? null : (participantIds[position] ?? null)), input.now);
220
220
  return meetingId;
221
221
  };
222
+ const callDirection = (value) => {
223
+ if (value === null || MEETING_CALL_DIRECTIONS.includes(value))
224
+ return value;
225
+ throw new CliError("validation_error", `a call's direction is in or out, not ${String(value)}`);
226
+ };
222
227
  const save = (context, input) => {
223
228
  const { database } = context;
224
229
  const { meeting: { series: seriesInput, ...meeting }, now, } = input;
@@ -271,6 +276,8 @@ const save = (context, input) => {
271
276
  ...(meeting.participantsCount === undefined ? {} : { participants_count: meeting.participantsCount }),
272
277
  metadata: toJson(meeting.metadata),
273
278
  deleted_at: meeting.deletedAt,
279
+ ...(meeting.direction === undefined ? {} : { direction: callDirection(meeting.direction) }),
280
+ ...(meeting.clientPhone === undefined ? {} : { client_phone: meeting.clientPhone?.trim() || null }),
274
281
  }, now);
275
282
  const participantIds = (input.participants ?? []).map(({ identity, ...p }) => upsert(database, "meeting_participants", {
276
283
  meeting_id: meetingId,
@@ -661,7 +668,7 @@ export const meetingStoreOver = (context) => {
661
668
  return database
662
669
  .prepare(sql)
663
670
  .all(...params)
664
- .map(meetingOf);
671
+ .map((row) => meetingOf(database, row));
665
672
  },
666
673
  async account(id) {
667
674
  const row = database.prepare("SELECT provider, external_id FROM accounts WHERE id = ?").get(id);