@wirecat/cli-core 0.604.0 → 0.605.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 (68) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/dist/calendar/prepare.d.ts +4 -2
  3. package/dist/calendar/prepare.js +8 -8
  4. package/dist/cli/index.d.ts +1 -1
  5. package/dist/cli/index.js +1 -1
  6. package/dist/cli/messenger/contacts-command.js +3 -2
  7. package/dist/cli/messenger/doctor-command.js +14 -7
  8. package/dist/cli/messenger/store-maintenance-command.d.ts +34 -2
  9. package/dist/cli/messenger/store-maintenance-command.js +31 -4
  10. package/dist/cli/program.js +11 -2
  11. package/dist/cli/steps.js +9 -1
  12. package/dist/cli/store-recover.d.ts +10 -2
  13. package/dist/cli/store-recover.js +18 -4
  14. package/dist/domain/record-types.d.ts +61 -0
  15. package/dist/domain/record-types.js +26 -0
  16. package/dist/domain/records.d.ts +3 -5
  17. package/dist/domain/records.js +10 -13
  18. package/dist/entities/contact-activity.d.ts +4 -0
  19. package/dist/entities/contact-activity.js +1 -0
  20. package/dist/entities/contact-context.d.ts +20 -0
  21. package/dist/entities/contact-context.js +2 -0
  22. package/dist/entities/index.d.ts +22 -0
  23. package/dist/errors/failures.d.ts +17 -1
  24. package/dist/errors/failures.js +57 -1
  25. package/dist/errors/reasons.js +16 -0
  26. package/dist/mcp/tool.js +2 -1
  27. package/dist/runs/recording.js +13 -4
  28. package/dist/services/deps.js +4 -6
  29. package/dist/services/index.d.ts +1 -1
  30. package/dist/services/link-scorers/chat-senders.d.ts +3 -2
  31. package/dist/services/link-scorers/chat-senders.js +7 -4
  32. package/dist/services/link-scorers/mail-thread.js +1 -0
  33. package/dist/services/link-scorers/member-chats.js +1 -0
  34. package/dist/services/link-scorers/member-dialog.d.ts +1 -1
  35. package/dist/services/link-scorers/member-dialog.js +4 -3
  36. package/dist/services/link-scorers/scan.d.ts +5 -2
  37. package/dist/services/link-scorers/scan.js +98 -53
  38. package/dist/services/link-scorers/shared.d.ts +2 -2
  39. package/dist/services/link-scorers/shared.js +7 -4
  40. package/dist/services/link-scorers/types.d.ts +3 -0
  41. package/dist/services/metadata.d.ts +1 -1
  42. package/dist/services/person-context.d.ts +24 -7
  43. package/dist/services/person-context.js +45 -11
  44. package/dist/services/person-preparation.js +4 -5
  45. package/dist/store/damage.d.ts +3 -1
  46. package/dist/store/damage.js +19 -12
  47. package/dist/store/document-transfer/index.js +7 -0
  48. package/dist/store/index.d.ts +1 -0
  49. package/dist/store/index.js +1 -0
  50. package/dist/store/marks.d.ts +57 -0
  51. package/dist/store/marks.js +121 -0
  52. package/dist/store/project-transfer/preview.js +12 -7
  53. package/dist/store/recover.js +16 -1
  54. package/dist/store/sqlite/finance.d.ts +8 -1
  55. package/dist/store/sqlite/finance.js +10 -3
  56. package/dist/store/sqlite/open-store.js +4 -1
  57. package/dist/store/sqlite/own-identities.d.ts +1 -1
  58. package/dist/store/sqlite/own-identities.js +7 -5
  59. package/dist/store/sqlite/person-links.d.ts +5 -2
  60. package/dist/store/sqlite/person-links.js +24 -18
  61. package/dist/store/sqlite/person-separation.d.ts +5 -0
  62. package/dist/store/sqlite/person-separation.js +26 -0
  63. package/dist/store/sqlite/record-projectors.d.ts +44 -0
  64. package/dist/store/sqlite/record-projectors.js +72 -0
  65. package/dist/store/sqlite/records.js +12 -70
  66. package/dist/store/sqlite/transaction.js +2 -5
  67. package/dist/store/types.d.ts +5 -0
  68. package/package.json +3 -3
@@ -0,0 +1,121 @@
1
+ import { readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { isCliFailure, isStoreDamage } from "../errors/failures.js";
4
+ import { refuseOwnerStoreInTests } from "./path.js";
5
+ /**
6
+ * Both marks live beside the store, not in it: the store may be the file that cannot be read. Each holds no content,
7
+ * only times, command names and SQLite's own message.
8
+ */
9
+ export const damageMarkPath = (store) => `${store}.damaged.json`;
10
+ export const healthMarkPath = (store) => `${store}.health.json`;
11
+ const inodeOf = (store) => statSync(store, { throwIfNoEntry: false })?.ino;
12
+ const readJson = (path) => {
13
+ try {
14
+ return JSON.parse(readFileSync(path, "utf8"));
15
+ }
16
+ catch (error) {
17
+ if (error.code === "ENOENT")
18
+ return null;
19
+ throw error;
20
+ }
21
+ };
22
+ const ownerStoreInTests = (store) => {
23
+ try {
24
+ refuseOwnerStoreInTests(store);
25
+ return false;
26
+ }
27
+ catch {
28
+ return true;
29
+ }
30
+ };
31
+ /** SQLite's own failure under a `store.damaged` CliError, or the error itself; the mark's own refusal has none. */
32
+ const sqliteFailure = (error) => isCliFailure(error) && error.details?.reason === "store.damaged" ? error.cause : error;
33
+ /**
34
+ * Leaves the damage mark when `error` is SQLite saying the store is damaged; the first sighting is kept. Never
35
+ * throws: the failure being reported matters more than the mark.
36
+ */
37
+ export const markStoreDamaged = (error, { store, command, version, runId, now = Date.now, }) => {
38
+ const failure = sqliteFailure(error);
39
+ if (!isStoreDamage(failure) || ownerStoreInTests(store))
40
+ return false;
41
+ const inode = inodeOf(store);
42
+ if (inode === undefined)
43
+ return false;
44
+ const mark = {
45
+ at: new Date(now()).toISOString(),
46
+ command,
47
+ ...(version ? { cli_version: version } : {}),
48
+ ...(runId ? { run_id: runId } : {}),
49
+ error: failure.message.slice(0, 500),
50
+ inode,
51
+ };
52
+ try {
53
+ writeFileSync(damageMarkPath(store), `${JSON.stringify(mark, null, 2)}\n`, { flag: "wx", mode: 0o600 });
54
+ return true;
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ };
60
+ /** The mark, or null; a mark left by another file at this path is removed. An unreadable mark still counts. */
61
+ export const readDamageMark = (store) => {
62
+ const path = damageMarkPath(store);
63
+ let mark;
64
+ try {
65
+ mark = readJson(path);
66
+ }
67
+ catch {
68
+ return { at: "unknown", command: "unknown", error: `${path} cannot be read`, inode: inodeOf(store) ?? 0 };
69
+ }
70
+ if (mark === null)
71
+ return null;
72
+ if (mark.inode !== inodeOf(store)) {
73
+ clearDamageMark(store);
74
+ return null;
75
+ }
76
+ return mark;
77
+ };
78
+ export const clearDamageMark = (store) => rmSync(damageMarkPath(store), { force: true });
79
+ /** Thrown by a writable open of a store a run found damaged, so timers fail fast instead of writing into it. */
80
+ export const refuseDamagedStore = (store, cli) => {
81
+ const mark = readDamageMark(store);
82
+ if (!mark)
83
+ return;
84
+ throw new CliError("configuration_error", `the store was found damaged at ${mark.at} by \`${mark.command}\` (${mark.error}), so nothing writes to it until ` +
85
+ `it is recovered; \`${cli ?? "<cli>"} store recover\` says what is damaged and what to do`, { reason: "store.damaged" });
86
+ };
87
+ export const readHealthMark = (store) => {
88
+ try {
89
+ return readJson(healthMarkPath(store));
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ };
95
+ /**
96
+ * Records a deep check of the store. One that passed also removes the damage mark: the file reads whole. Returns the
97
+ * mark it replaced, whose `last_ok_at` is the last known good before this check, and the damage mark it removed.
98
+ */
99
+ export const recordDeepCheck = (store, health, { cli, version, schema, now = Date.now, }) => {
100
+ const previous = readHealthMark(store);
101
+ if (ownerStoreInTests(store))
102
+ return { previous, cleared: null };
103
+ const checkedAt = new Date(now()).toISOString();
104
+ const mark = {
105
+ checked_at: checkedAt,
106
+ ok: health.ok,
107
+ problems: health.problems ?? 0,
108
+ schema,
109
+ cli,
110
+ ...(version ? { cli_version: version } : {}),
111
+ last_ok_at: health.ok ? checkedAt : (previous?.last_ok_at ?? null),
112
+ };
113
+ const cleared = health.ok ? readDamageMark(store) : null;
114
+ try {
115
+ writeFileSync(healthMarkPath(store), `${JSON.stringify(mark, null, 2)}\n`, { mode: 0o600 });
116
+ }
117
+ catch { }
118
+ if (cleared)
119
+ clearDamageMark(store);
120
+ return { previous, cleared };
121
+ };
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { damagedFile } from "../../errors/failures.js";
2
3
  import { openStoreContext } from "../sqlite/open-store.js";
3
4
  import { SnapshotBudget } from "../sqlite/project-transfer/budget.js";
4
5
  import { previewAnnotationSnapshot } from "../sqlite/project-transfer/preview.js";
@@ -19,11 +20,15 @@ export const previewProjectAnnotationSnapshot = async (options) => {
19
20
  !Number.isSafeInteger(Number(options.project.slice(8))))
20
21
  throw new CliError("validation_error", "project preview project is a project:<safe integer id> reference");
21
22
  const budget = new SnapshotBudget(options.maxReadBytes ?? 4 * 1024 * 1024);
22
- const context = await openStoreContext({ path: options.target, env: options.env, readOnly: true });
23
- try {
24
- return previewAnnotationSnapshot(context.database, Number(options.project.slice(8)), snapshot, options.bindings, budget);
25
- }
26
- finally {
27
- context.database.close();
28
- }
23
+ const target = options.target;
24
+ const project = options.project;
25
+ return damagedFile([target], async () => {
26
+ const context = await openStoreContext({ path: target, env: options.env, readOnly: true });
27
+ try {
28
+ return previewAnnotationSnapshot(context.database, Number(project.slice(8)), snapshot, options.bindings, budget);
29
+ }
30
+ finally {
31
+ context.database.close();
32
+ }
33
+ });
29
34
  };
@@ -4,7 +4,10 @@ import { basename, dirname, join } from "node:path";
4
4
  import { Transform } from "node:stream";
5
5
  import { CliError } from "@wirecat/cli-base";
6
6
  import { holdersOf } from "../background/processes.js";
7
+ import { isStoreDamage } from "../errors/failures.js";
8
+ import { fileSchemaOf } from "./compatibility.js";
7
9
  import { fts5Tables, invalidJson, storeHealth } from "./health.js";
10
+ import { recordDeepCheck } from "./marks.js";
8
11
  import { migrate } from "./migrations.js";
9
12
  import { resetAttachmentWords } from "./sqlite/attachment-texts.js";
10
13
  import { involvementStoreOver } from "./sqlite/involvements.js";
@@ -393,7 +396,16 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
393
396
  };
394
397
  try {
395
398
  const dataVersion = () => Number(watch.prepare("PRAGMA data_version").get()?.data_version);
396
- const rowsBefore = tableRows(watch);
399
+ let rowsBefore;
400
+ try {
401
+ rowsBefore = tableRows(watch);
402
+ }
403
+ catch (error) {
404
+ if (!isStoreDamage(error))
405
+ throw error;
406
+ throw new CliError("configuration_error", "the store file's header or schema is damaged, so its tables cannot be listed and it cannot be recovered; " +
407
+ "the file was left as it was", { reason: "store.unreadable" });
408
+ }
397
409
  const before = { data: dataVersion(), inode: statSync(path).ino };
398
410
  const stamp = new Date(now()).toISOString().replace(/[:.]/g, "-");
399
411
  const target = `${path}.recovering-${stamp}`;
@@ -422,6 +434,7 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
422
434
  let dangling;
423
435
  let json;
424
436
  let fetch;
437
+ let schema;
425
438
  try {
426
439
  kept = tableRows(opened.database);
427
440
  migrate(opened.database, { command, ...(version ? { version } : {}) });
@@ -431,6 +444,7 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
431
444
  note("looking for rows that point at rows that were lost");
432
445
  dangling = danglingRows(opened.database);
433
446
  fetch = mailToFetch(opened.database);
447
+ schema = fileSchemaOf(opened.database).version;
434
448
  opened.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
435
449
  }
436
450
  catch (error) {
@@ -459,6 +473,7 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
459
473
  for (const suffix of STORE_PARTS)
460
474
  if (existsSync(`${target}${suffix}`))
461
475
  renameSync(`${target}${suffix}`, `${path}${suffix}`);
476
+ recordDeepCheck(path, health, { cli: command, ...(version ? { version } : {}), schema, now });
462
477
  const lost = Object.entries(rowsBefore)
463
478
  .map(([table, before]) => ({ table, before, read: read[table] ?? 0, kept: kept[table] ?? 0 }))
464
479
  .filter(({ before, read, kept }) => before === null || before > kept || read > kept);
@@ -1,5 +1,6 @@
1
1
  import { type FinanceReview, type InvoiceDirection, type InvoiceStatus, type MoneyDirection } from "../../domain/finance.js";
2
2
  import { type Money } from "../../domain/money.js";
3
+ import { RECORD_TYPES } from "../../domain/record-types.js";
3
4
  import { type Decider } from "../decisions.js";
4
5
  import { type Actor, type ProposedByFilter } from "./actors.js";
5
6
  import { type Author } from "./memories.js";
@@ -207,6 +208,12 @@ export interface FinanceStore {
207
208
  }>;
208
209
  }
209
210
  type Row = Record<string, unknown>;
211
+ /** The types `decide` settles money for; other proposal types get their own route. */
212
+ declare const FINANCE_TYPES: readonly ["invoice", "payment"];
213
+ type FinanceType = (typeof FINANCE_TYPES)[number];
214
+ type FinanceTable = (typeof RECORD_TYPES)[FinanceType]["table"];
215
+ /** One article, for the first prefix only: `an invoice: or payment:`. */
216
+ export declare const prefixesText: (types: readonly string[]) => string;
210
217
  export declare const refuse: (message: string, reason: string, code?: "validation_error" | "permission_error") => never;
211
218
  export declare const oneOf: <T extends string>(value: unknown, allowed: readonly T[], what: string) => T;
212
219
  export declare const text: (value: unknown, what: string, limit: number) => string | null;
@@ -242,7 +249,7 @@ export declare const reviewedRowsOver: (context: StoreContext) => {
242
249
  evidence: string[];
243
250
  }>) => void;
244
251
  ownerOnly: (by: Author, what: string) => void;
245
- keepDecision: (table: "invoices" | "payments" | "orders" | "opportunities", id: number, by: Decider, reason?: string) => void;
252
+ keepDecision: (table: FinanceTable | "orders", id: number, by: Decider, reason?: string) => void;
246
253
  };
247
254
  type FinanceOperations = {
248
255
  [K in keyof FinanceStore]: FinanceStore[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => R : never;
@@ -1,11 +1,18 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { FINANCE_REVIEWS, INVOICE_DIRECTIONS, INVOICE_STATUSES, invoiceTitle, MONEY_DIRECTIONS, paymentEntryTitle, settledStatus, } from "../../domain/finance.js";
3
3
  import { currencyOf, formatDecimal, lineUnits, minorUnits, moneyLabel, moneyOf, quantityOf, scaleOf, } from "../../domain/money.js";
4
+ import { RECORD_TYPES } from "../../domain/record-types.js";
4
5
  import { assertMayDecide, botKey, deciderAuthor } from "../decisions.js";
5
6
  import { proposedBySql, proposerOf } from "./actors.js";
6
7
  import { authorActor, authorOf, evidenceOf, linkEvidence, projectId, projectOf, subjectOf, } from "./memories.js";
7
8
  import { requiredThing } from "./notes.js";
8
9
  import { write } from "./transaction.js";
10
+ /** The types `decide` settles money for; other proposal types get their own route. */
11
+ const FINANCE_TYPES = ["invoice", "payment"];
12
+ const isFinanceType = (type) => FINANCE_TYPES.includes(type);
13
+ const article = (word) => (/^[aeiou]/.test(word) ? "an" : "a");
14
+ /** One article, for the first prefix only: `an invoice: or payment:`. */
15
+ export const prefixesText = (types) => `${article(types[0] ?? "")} ${types.map((type) => `${type}:`).join(" or ")}`;
9
16
  export const refuse = (message, reason, code = "validation_error") => {
10
17
  throw new CliError(code, message, { reason });
11
18
  };
@@ -287,10 +294,10 @@ export const financeOperationsOver = (context) => {
287
294
  };
288
295
  const decide = (reference, by, reason, confirm) => {
289
296
  const thing = requiredThing(database, reference, "the proposal");
290
- if (thing.type !== "invoice" && thing.type !== "payment")
291
- return refuse(`${reference} is not an invoice: or payment:`, "finance.ref");
297
+ if (!isFinanceType(thing.type))
298
+ return refuse(`${reference} is not ${prefixesText(FINANCE_TYPES)}`, "finance.ref");
292
299
  const type = thing.type;
293
- const table = type === "invoice" ? "invoices" : "payments";
300
+ const table = RECORD_TYPES[type].table;
294
301
  const row = rowOf(reference, type);
295
302
  const ref = `${type}:${row.id}`;
296
303
  assertMayDecide({ id: ref, proposedBy: proposerOf(database, row.author_type, row.author_id), ownerOnly: true }, by, context.decisions);
@@ -2,6 +2,7 @@ import { accessSync, constants, existsSync, mkdirSync, statSync, writeFileSync }
2
2
  import { dirname } from "node:path";
3
3
  import { CliError } from "@wirecat/cli-base";
4
4
  import { DEFAULT_DECISION_POLICY } from "../decisions.js";
5
+ import { refuseDamagedStore } from "../marks.js";
5
6
  import { migrate } from "../migrations.js";
6
7
  import { storeCapable } from "../open.js";
7
8
  import { refuseOwnerStoreInTests, storePath } from "../path.js";
@@ -78,8 +79,10 @@ export const openStoreContext = async (options = {}) => {
78
79
  if (!statSync(file, { throwIfNoEntry: false })?.isFile())
79
80
  throw new CliError("not_found", "The store does not exist as a file; read-only opening does not create it");
80
81
  }
81
- else
82
+ else {
82
83
  createWritable(file);
84
+ refuseDamagedStore(file, command);
85
+ }
83
86
  const opened = readOnly ? await openReadable(file, options) : await openSqlite(file, { readOnly });
84
87
  const database = opened.database;
85
88
  try {
@@ -3,7 +3,7 @@ import type { StoreContext } from "./open.js";
3
3
  /**
4
4
  * An account's own identity (same provider and id as the account) is the owner. Messengers save it like anyone
5
5
  * else's, as a person of its own, so the owner's name counted as a contact's. Links it, and whoever was linked
6
- * with it, to the owner; nothing to do once done.
6
+ * with it, to the owner, unless the owner separated that person from themselves; nothing to do once done.
7
7
  */
8
8
  export declare const linkOwnIdentities: (context: StoreContext) => number;
9
9
  /** `contacts link <person> me`: an identity the account id does not name, a Zoom user for one, is the owner. */
@@ -1,11 +1,12 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { ownerPerson } from "./actors.js";
3
3
  import { mergePerson, personOf } from "./person-links.js";
4
+ import { separated } from "./person-separation.js";
4
5
  import { write } from "./transaction.js";
5
6
  /**
6
7
  * An account's own identity (same provider and id as the account) is the owner. Messengers save it like anyone
7
8
  * else's, as a person of its own, so the owner's name counted as a contact's. Links it, and whoever was linked
8
- * with it, to the owner; nothing to do once done.
9
+ * with it, to the owner, unless the owner separated that person from themselves; nothing to do once done.
9
10
  */
10
11
  export const linkOwnIdentities = (context) => {
11
12
  const owner = ownerPerson(context.database).id;
@@ -15,11 +16,12 @@ export const linkOwnIdentities = (context) => {
15
16
  .all(owner);
16
17
  if (strays.length === 0)
17
18
  return 0;
18
- write(context.database, () => {
19
- for (const { person } of strays)
20
- mergePerson(context, Number(person), owner, { method: "account", by: "rules" });
19
+ return write(context.database, () => {
20
+ const joining = strays.map(({ person }) => Number(person)).filter((person) => !separated(context, person, owner));
21
+ for (const person of joining)
22
+ mergePerson(context, person, owner, { method: "account", by: "rules" });
23
+ return joining.length;
21
24
  });
22
- return strays.length;
23
25
  };
24
26
  /** `contacts link <person> me`: an identity the account id does not name, a Zoom user for one, is the owner. */
25
27
  export const linkToOwner = (context, ref) => {
@@ -5,7 +5,10 @@ import type { StoreContext } from "./open.js";
5
5
  export declare const personByUid: (context: StoreContext, uid: string) => PersonRecord | undefined;
6
6
  /** The person an identity belongs to, with every identity linked to them. */
7
7
  export declare const personOf: (context: StoreContext, ref: IdentityRef) => PersonRecord | undefined;
8
- /** A reviewed meeting participant association moves only its selected identity. */
8
+ /**
9
+ * A reviewed meeting participant association moves only its selected identity. Only the owner may move it back
10
+ * over a separation the owner made.
11
+ */
9
12
  export declare const linkIdentityToPerson: (context: StoreContext, identityPk: number, target: number, options: LinkOptions) => void;
10
13
  /**
11
14
  * Makes `other` and everyone already linked to it the same person as `person`. Never inferred from a
@@ -17,7 +20,7 @@ export declare const mergePerson: (context: StoreContext, from: number, to: numb
17
20
  /**
18
21
  * Joins the identity to the person of the mail contact with this exact address, making that contact when mail has
19
22
  * not seen it yet, so whichever import comes second lands on one person. The contact is seen by no account, so it is
20
- * no one's mail correspondent. An owner's unlink wins: two identities the owner separated stay apart.
23
+ * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart.
21
24
  */
22
25
  export declare const joinByAddress: (context: StoreContext, ref: IdentityRef, address: string, by: string) => void;
23
26
  /** Gives the identity a person of its own again; the ones left keep theirs. */
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { and, eq, inArray, isNull, sql } from "./drizzle/core.js";
3
3
  import { identityOf } from "./identities.js";
4
4
  import { resolvePersonLinks } from "./person-resolution.js";
5
+ import { identitySeparated, separated } from "./person-separation.js";
5
6
  import { accountIdentities, accounts, chats, identities, identityLinkEvents, identityLinks, messages, persons, } from "./schema.js";
6
7
  import { hitsWhere } from "./search.js";
7
8
  const identityRow = ({ orm }, { provider, id }) => orm
@@ -38,17 +39,23 @@ const recordOf = ({ orm }, personPk) => {
38
39
  .orderBy(identities.provider, identities.externalId)
39
40
  .all();
40
41
  const seen = orm
41
- .select({ identityPk: accountIdentities.identityId, account: accounts.externalId })
42
+ .select({ identityPk: accountIdentities.identityId, account: accounts.externalId, scope: accounts.scope })
42
43
  .from(accountIdentities)
43
44
  .innerJoin(accounts, eq(accounts.id, accountIdentities.accountId))
44
45
  .where(inArray(accountIdentities.identityId, rows.map((row) => row.pk)))
45
46
  .all();
46
- const identitiesOf = rows.map(({ pk, isBot, linkedAt, ...row }) => ({
47
- ...row,
48
- isBot: isBot === null ? null : isBot === 1,
49
- accounts: seen.filter((one) => one.identityPk === pk).map((one) => one.account),
50
- linkedAt: new Date(linkedAt).toISOString(),
51
- }));
47
+ const identitiesOf = rows.map(({ pk, isBot, linkedAt, ...row }) => {
48
+ const seenIn = seen
49
+ .filter((one) => one.identityPk === pk)
50
+ .map(({ account, scope }) => ({ account, scope: scope }));
51
+ return {
52
+ ...row,
53
+ isBot: isBot === null ? null : isBot === 1,
54
+ accounts: seenIn.map((one) => one.account),
55
+ seenIn,
56
+ linkedAt: new Date(linkedAt).toISOString(),
57
+ };
58
+ });
52
59
  return { uid: String(person.id), name: person.name, identities: identitiesOf };
53
60
  };
54
61
  /** A person by the uid a `person:` reference holds, with every identity linked to them. */
@@ -75,13 +82,20 @@ const move = (context, identityPk, from, to, { method, by }) => {
75
82
  .values({ identityId: identityPk, fromPersonId: from, toPersonId: to, method, createdAt: at, author: by })
76
83
  .run();
77
84
  };
78
- /** A reviewed meeting participant association moves only its selected identity. */
85
+ /**
86
+ * A reviewed meeting participant association moves only its selected identity. Only the owner may move it back
87
+ * over a separation the owner made.
88
+ */
79
89
  export const linkIdentityToPerson = (context, identityPk, target, options) => {
80
90
  const found = context.orm
81
91
  .select({ personId: identityLinks.personId })
82
92
  .from(identityLinks)
83
93
  .where(eq(identityLinks.identityId, identityPk))
84
94
  .get();
95
+ if (options.by !== "owner" && found?.personId !== target && identitySeparated(context, identityPk, target))
96
+ throw new CliError("conflict", "the owner separated this identity from that person; only the owner links it again", {
97
+ reason: "identity.separated",
98
+ });
85
99
  if (found) {
86
100
  move(context, identityPk, found.personId, target, options);
87
101
  return;
@@ -136,18 +150,10 @@ export const mergePerson = (context, from, to, options) => {
136
150
  for (const { identityPk } of together)
137
151
  move(context, identityPk, from, to, options);
138
152
  };
139
- /** The owner once moved one of the two identities away from a person the other belonged to. */
140
- const separatedByOwner = ({ database }, one, other) => database
141
- .prepare(`SELECT 1 FROM identity_link_events moved
142
- JOIN identity_link_events held ON held.to_person_id = moved.from_person_id
143
- WHERE moved.author = 'owner' AND ((moved.identity_id = ? AND held.identity_id = ?)
144
- OR (moved.identity_id = ? AND held.identity_id = ?))
145
- LIMIT 1`)
146
- .get(one, other, other, one) !== undefined;
147
153
  /**
148
154
  * Joins the identity to the person of the mail contact with this exact address, making that contact when mail has
149
155
  * not seen it yet, so whichever import comes second lands on one person. The contact is seen by no account, so it is
150
- * no one's mail correspondent. An owner's unlink wins: two identities the owner separated stay apart.
156
+ * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart.
151
157
  */
152
158
  export const joinByAddress = (context, ref, address, by) => {
153
159
  const key = address.trim().toLowerCase();
@@ -162,7 +168,7 @@ export const joinByAddress = (context, ref, address, by) => {
162
168
  if (!mail)
163
169
  identityOf(context, "email", key, null);
164
170
  const contact = required(context, { provider: "email", id: mail ? String(mail.external_id) : key });
165
- if (contact.personPk === found.personPk || separatedByOwner(context, found.pk, contact.pk))
171
+ if (contact.personPk === found.personPk || separated(context, found.personPk, contact.personPk))
166
172
  return;
167
173
  mergePerson(context, found.personPk, contact.personPk, { method: "same-email", by });
168
174
  resolvePersonLinks(context.database, recordOf(context, contact.personPk).identities.flatMap(({ name, username }) => [name, username]));
@@ -0,0 +1,5 @@
1
+ import type { StoreContext } from "./open.js";
2
+ /** Whether the owner separated anyone of `one` from anyone of `other`; nothing automatic may join them again. */
3
+ export declare const separated: (context: StoreContext, one: number, other: number) => boolean;
4
+ /** Whether the owner separated this one identity from `person` or from anyone of it. */
5
+ export declare const identitySeparated: (context: StoreContext, identity: number, person: number) => boolean;
@@ -0,0 +1,26 @@
1
+ const identitiesOf = ({ database }, person) => database
2
+ .prepare("SELECT identity_id AS pk FROM identity_links WHERE person_id = ?")
3
+ .all(person)
4
+ .map(({ pk }) => Number(pk));
5
+ const MOVED_AWAY = `moved.identity_id IN (SELECT value FROM json_each(?))
6
+ AND (moved.from_person_id IN (SELECT value FROM json_each(?))
7
+ OR EXISTS (SELECT 1 FROM identity_link_events held WHERE held.to_person_id = moved.from_person_id
8
+ AND held.identity_id IN (SELECT value FROM json_each(?))))`;
9
+ /**
10
+ * The owner once moved an identity of one side out of the other side's person, or out of a person that held an
11
+ * identity of the other side. Checked over whole people because a merge moves whole people: a pair check lets a
12
+ * third identity carry two separated people back together.
13
+ */
14
+ const apart = ({ database }, one, other) => {
15
+ const ids = (side) => JSON.stringify(side.identities);
16
+ const person = (side) => JSON.stringify(side.person === undefined ? [] : [side.person]);
17
+ return (database
18
+ .prepare(`SELECT 1 FROM identity_link_events moved WHERE moved.author = 'owner'
19
+ AND ((${MOVED_AWAY}) OR (${MOVED_AWAY})) LIMIT 1`)
20
+ .get(ids(one), person(other), ids(other), ids(other), person(one), ids(one)) !== undefined);
21
+ };
22
+ /** Whether the owner separated anyone of `one` from anyone of `other`; nothing automatic may join them again. */
23
+ export const separated = (context, one, other) => one !== other &&
24
+ apart(context, { identities: identitiesOf(context, one), person: one }, { identities: identitiesOf(context, other), person: other });
25
+ /** Whether the owner separated this one identity from `person` or from anyone of it. */
26
+ export const identitySeparated = (context, identity, person) => apart(context, { identities: [identity] }, { identities: identitiesOf(context, person).filter((pk) => pk !== identity), person });
@@ -0,0 +1,44 @@
1
+ import { type RecordEntityType } from "../../domain/record-types.js";
2
+ import type { EnvelopeSource } from "../../domain/records.js";
3
+ import type { financeOperationsOver, PaymentDetail } from "./finance.js";
4
+ export type Row = Record<string, unknown>;
5
+ export interface Share {
6
+ invoice: string;
7
+ /** As the source gave it; `null` settles as far as both allow. */
8
+ amount: string | null;
9
+ }
10
+ /** The entities a record's relations resolved to, by role, and what each invoice a payment settles gets. */
11
+ export interface Related {
12
+ related: Map<string, string[]>;
13
+ shares: Share[];
14
+ }
15
+ export interface ProjectionTools {
16
+ finance: ReturnType<typeof financeOperationsOver>;
17
+ settle: (made: PaymentDetail, shares: Share[]) => string;
18
+ }
19
+ /** Makes the proposal a record stands for and returns its ref. */
20
+ export type Projector = (fields: Row, related: Related, source: EnvelopeSource, tools: ProjectionTools) => string;
21
+ export declare const IMPORTER: {
22
+ readonly bot: "import";
23
+ };
24
+ /** `at` names the record's member at fault; a refused entity is the fields' fault. */
25
+ export declare const refusal: (message: string, code: string, at?: string | (string | number)[]) => never;
26
+ export declare const stringField: (fields: Row, name: string) => string | undefined;
27
+ /** `null` for a type whose entity only the owner's `map` gives. */
28
+ export declare const RECORD_PROJECTORS: {
29
+ readonly invoice: (fields: Row, { related }: Related, source: EnvelopeSource, { finance }: ProjectionTools) => string;
30
+ readonly payment: (fields: Row, { related, shares }: Related, source: EnvelopeSource, { finance, settle }: ProjectionTools) => string;
31
+ readonly person: null;
32
+ readonly organization: null;
33
+ readonly project: null;
34
+ };
35
+ export type ProjectedType = {
36
+ [K in RecordEntityType]: (typeof RECORD_PROJECTORS)[K] extends null ? never : K;
37
+ }[RecordEntityType];
38
+ export declare const PROJECTED_TYPES: ProjectedType[];
39
+ export declare const isProjected: (type: unknown) => type is ProjectedType;
40
+ /**
41
+ * Single roles a record may also name in `fields.<role>`. Pooled across the projected types on purpose: an invoice
42
+ * whose `fields.payer` is not text is refused, as before the registry.
43
+ */
44
+ export declare const FIELD_REFERENCE_ROLES: string[];
@@ -0,0 +1,72 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { RECORD_ENTITY_TYPES, roleNames } from "../../domain/record-types.js";
3
+ export const IMPORTER = { bot: "import" };
4
+ /** `at` names the record's member at fault; a refused entity is the fields' fault. */
5
+ export const refusal = (message, code, at) => {
6
+ throw new CliError("validation_error", message, { reason: code, ...(at === undefined ? {} : { at }) });
7
+ };
8
+ export const stringField = (fields, name) => {
9
+ const value = fields[name];
10
+ if (value === undefined || value === null)
11
+ return undefined;
12
+ if (typeof value !== "string")
13
+ return refusal(`fields.${name} is text`, "record.invalid");
14
+ return value;
15
+ };
16
+ const written = (source) => ({
17
+ by: IMPORTER,
18
+ source: `import:${source.provider}`,
19
+ reason: `imported from ${source.provider} account ${source.account}, batch ${source.batch_id}`,
20
+ });
21
+ const invoiceOf = (fields, related, source) => {
22
+ if (!Array.isArray(fields.lines) || fields.lines.some((line) => typeof line !== "object" || line === null))
23
+ return refusal("an invoice's fields.lines is a list of lines", "record.invalid");
24
+ const one = (role) => related.get(role)?.[0] ?? stringField(fields, role);
25
+ return {
26
+ ...written(source),
27
+ direction: fields.direction,
28
+ number: stringField(fields, "number"),
29
+ issuer: one("issuer"),
30
+ counterparty: one("counterparty"),
31
+ project: one("project"),
32
+ currency: fields.currency,
33
+ issueDate: stringField(fields, "issue_date"),
34
+ dueDate: stringField(fields, "due_date"),
35
+ total: fields.total,
36
+ lines: fields.lines.map((line) => ({
37
+ description: line.description,
38
+ quantity: line.quantity,
39
+ unitPrice: line.unit_price,
40
+ amount: line.amount,
41
+ })),
42
+ };
43
+ };
44
+ const paymentOf = (fields, related, source) => {
45
+ const one = (role) => related.get(role)?.[0] ?? stringField(fields, role);
46
+ return {
47
+ ...written(source),
48
+ direction: fields.direction,
49
+ payer: one("payer"),
50
+ payee: one("payee"),
51
+ project: one("project"),
52
+ amount: fields.amount,
53
+ currency: fields.currency,
54
+ date: fields.date,
55
+ reference: stringField(fields, "reference"),
56
+ };
57
+ };
58
+ /** `null` for a type whose entity only the owner's `map` gives. */
59
+ export const RECORD_PROJECTORS = {
60
+ invoice: (fields, { related }, source, { finance }) => finance.addInvoice(invoiceOf(fields, related, source)).ref,
61
+ payment: (fields, { related, shares }, source, { finance, settle }) => settle(finance.addPayment(paymentOf(fields, related, source)), shares),
62
+ person: null,
63
+ organization: null,
64
+ project: null,
65
+ };
66
+ export const PROJECTED_TYPES = RECORD_ENTITY_TYPES.filter((type) => RECORD_PROJECTORS[type] !== null);
67
+ export const isProjected = (type) => PROJECTED_TYPES.includes(type);
68
+ /**
69
+ * Single roles a record may also name in `fields.<role>`. Pooled across the projected types on purpose: an invoice
70
+ * whose `fields.payer` is not text is refused, as before the registry.
71
+ */
72
+ export const FIELD_REFERENCE_ROLES = roleNames(PROJECTED_TYPES, (role) => !role.many);