@wirecat/cli-core 0.629.0 → 0.631.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 (58) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/base-stages-command.d.ts +5 -0
  4. package/dist/cli/base-stages-command.js +75 -1
  5. package/dist/cli/stage-suggest.d.ts +48 -0
  6. package/dist/cli/stage-suggest.js +105 -0
  7. package/dist/crm/cli/index.js +22 -2
  8. package/dist/crm/sync.d.ts +3 -1
  9. package/dist/crm/sync.js +5 -0
  10. package/dist/domain/crm.d.ts +2 -1
  11. package/dist/domain/name-variants.d.ts +21 -0
  12. package/dist/domain/name-variants.js +147 -0
  13. package/dist/entities/contact-activity.d.ts +2 -0
  14. package/dist/entities/contact-activity.js +2 -0
  15. package/dist/entities/contact-context.d.ts +6 -0
  16. package/dist/entities/identity.d.ts +3 -0
  17. package/dist/entities/identity.js +3 -0
  18. package/dist/entities/index.d.ts +10 -0
  19. package/dist/entities/person.d.ts +2 -0
  20. package/dist/errors/reasons.js +8 -0
  21. package/dist/services/metadata.d.ts +1 -1
  22. package/dist/store/identity-links.d.ts +3 -2
  23. package/dist/store/identity-links.js +3 -2
  24. package/dist/store/index.d.ts +1 -1
  25. package/dist/store/index.js +1 -1
  26. package/dist/store/sqlite/accounts.d.ts +7 -0
  27. package/dist/store/sqlite/accounts.js +13 -5
  28. package/dist/store/sqlite/base-suggest.d.ts +4 -1
  29. package/dist/store/sqlite/base-suggest.js +5 -3
  30. package/dist/store/sqlite/crm-contacts.d.ts +26 -0
  31. package/dist/store/sqlite/crm-contacts.js +134 -0
  32. package/dist/store/sqlite/crm-settings.d.ts +2 -0
  33. package/dist/store/sqlite/crm-settings.js +5 -0
  34. package/dist/store/sqlite/crm.d.ts +12 -0
  35. package/dist/store/sqlite/crm.js +13 -5
  36. package/dist/store/sqlite/mail-findings.js +3 -1
  37. package/dist/store/sqlite/manifest.js +2 -0
  38. package/dist/store/sqlite/migrations.generated.js +30 -0
  39. package/dist/store/sqlite/name-traces.d.ts +8 -3
  40. package/dist/store/sqlite/name-traces.js +26 -21
  41. package/dist/store/sqlite/note-index.js +2 -1
  42. package/dist/store/sqlite/own-identities.d.ts +5 -3
  43. package/dist/store/sqlite/own-identities.js +66 -12
  44. package/dist/store/sqlite/people-list.d.ts +2 -0
  45. package/dist/store/sqlite/people-list.js +23 -10
  46. package/dist/store/sqlite/person-links.d.ts +10 -2
  47. package/dist/store/sqlite/person-links.js +54 -10
  48. package/dist/store/sqlite/person-match-scan.js +97 -17
  49. package/dist/store/sqlite/person-merges.js +3 -1
  50. package/dist/store/sqlite/person-ties.d.ts +1 -1
  51. package/dist/store/sqlite/person-ties.js +53 -21
  52. package/dist/store/sqlite/task-candidates.js +2 -2
  53. package/dist/store/sqlite/task-titles.d.ts +12 -0
  54. package/dist/store/sqlite/task-titles.js +42 -0
  55. package/dist/store/sqlite/tasks.js +2 -1
  56. package/dist/store/sqlite/work-tasks.js +2 -1
  57. package/dist/store/types.d.ts +3 -0
  58. package/package.json +2 -2
@@ -6,6 +6,8 @@ const linkedIdentity = v.strictObject({
6
6
  id,
7
7
  name: v.nullable(text),
8
8
  username: v.nullable(text),
9
+ phone: v.optional(v.nullable(text)),
10
+ email: v.optional(v.nullable(text)),
9
11
  is_bot: v.nullable(v.boolean()),
10
12
  accounts: v.array(id),
11
13
  seen_in: v.array(v.strictObject({ account: id, scope: v.picklist(["personal", "work"]) })),
@@ -30,6 +30,8 @@ declare const context: v.StrictObjectSchema<{
30
30
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
31
31
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
32
32
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
33
+ readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
34
+ readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
33
35
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
34
36
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
35
37
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -820,6 +822,8 @@ export declare const contactContext: v.UnionSchema<[v.StrictObjectSchema<{
820
822
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
821
823
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
822
824
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
825
+ readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
826
+ readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
823
827
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
824
828
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
825
829
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -1621,6 +1625,8 @@ export declare const contactPreparation: v.StrictObjectSchema<{
1621
1625
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
1622
1626
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
1623
1627
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
1628
+ readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
1629
+ readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
1624
1630
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
1625
1631
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
1626
1632
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -8,6 +8,9 @@ export declare const identity: v.StrictObjectSchema<{
8
8
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
9
9
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
10
10
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
11
+ /** The number or address the source gave for them, when it gave one. */
12
+ readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
13
+ readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
11
14
  /** The `person:` they are linked to, when one is. */
12
15
  readonly person: v.OptionalSchema<v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>, undefined>;
13
16
  }, undefined>;
@@ -9,6 +9,9 @@ export const identity = v.strictObject({
9
9
  id,
10
10
  name: v.nullable(text),
11
11
  username: v.nullable(text),
12
+ /** The number or address the source gave for them, when it gave one. */
13
+ phone: v.optional(v.nullable(text)),
14
+ email: v.optional(v.nullable(text)),
12
15
  /** The `person:` they are linked to, when one is. */
13
16
  person: v.optional(v.nullable(reference)),
14
17
  });
@@ -2690,6 +2690,8 @@ export declare const ENTITIES: {
2690
2690
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
2691
2691
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
2692
2692
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
2693
+ readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
2694
+ readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
2693
2695
  readonly person: v.OptionalSchema<v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>, undefined>;
2694
2696
  }, undefined>, undefined>, undefined>;
2695
2697
  }, undefined>;
@@ -2700,6 +2702,8 @@ export declare const ENTITIES: {
2700
2702
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
2701
2703
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
2702
2704
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
2705
+ readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
2706
+ readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
2703
2707
  readonly person: v.OptionalSchema<v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>, undefined>;
2704
2708
  }, undefined>;
2705
2709
  readonly contact_context: v.UnionSchema<[v.StrictObjectSchema<{
@@ -2711,6 +2715,8 @@ export declare const ENTITIES: {
2711
2715
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
2712
2716
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
2713
2717
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
2718
+ readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
2719
+ readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
2714
2720
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
2715
2721
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
2716
2722
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -3497,6 +3503,8 @@ export declare const ENTITIES: {
3497
3503
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
3498
3504
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
3499
3505
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
3506
+ readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3507
+ readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3500
3508
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
3501
3509
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
3502
3510
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -3797,6 +3805,8 @@ export declare const ENTITIES: {
3797
3805
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
3798
3806
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
3799
3807
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
3808
+ readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3809
+ readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3800
3810
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
3801
3811
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
3802
3812
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -10,6 +10,8 @@ export declare const person: v.StrictObjectSchema<{
10
10
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
11
11
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
12
12
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
13
+ readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
14
+ readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
13
15
  readonly person: v.OptionalSchema<v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>, undefined>;
14
16
  }, undefined>, undefined>, undefined>;
15
17
  }, undefined>;
@@ -313,6 +313,13 @@ const OTHERS = [
313
313
  ["stage.owner-only", "permission_error", "only the owner confirms mappings and edits a base set, not an agent"],
314
314
  validation("stage.unmapped", "no stage of the row's pipeline maps to that base stage; map one first"),
315
315
  ["stage.not-found", "not_found", "no stored stage has that reference or name"],
316
+ validation("stage.answer-invalid", "the agent's answer to stages suggest is not the JSON stage map it asks for"),
317
+ ["stage.model-answer-invalid", "invalid_response", "the AI model's answer to stages suggest is not the stage map"],
318
+ [
319
+ "stage.model-agent",
320
+ "permission_error",
321
+ "an agent's run does not send stages to the AI model; it answers the task itself with --dry-run and --text-file",
322
+ ],
316
323
  validation("pipeline.ambiguous", "more than one pipeline has that name; name it by its pipeline: reference"),
317
324
  validation("pipeline.duplicate", "a pipeline of that name and kind is already stored"),
318
325
  validation("pipeline.field", "a pipeline needs a name and at least one stage, each named once"),
@@ -392,6 +399,7 @@ const OTHERS = [
392
399
  validation("identity.same", "the two identities are one person already"),
393
400
  validation("identity.shared-phone", "more than six people share the phone number, so it proposes no one"),
394
401
  validation("identity.common-name", "more than six people have the name, so it proposes no one"),
402
+ validation("identity.owner", "one side is the owner's person, and only the owner joins anyone to themselves"),
395
403
  validation("identity.shared-email", "more than six people share the address, so it proposes no one"),
396
404
  validation("identity-link.dedicated-review", "an identity link is staged and decided through the people review"),
397
405
  ["transcription.no-key", "authentication_error", "no OpenAI key is set for transcription"],
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
+ error?: undefined;
17
18
  chatId: string;
18
19
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
19
20
  algorithm: string;
20
21
  fetchedAt: string | null;
21
22
  source: string;
22
- error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -4,9 +4,10 @@ import type { IdentityRef } from "./types.js";
4
4
  export declare const IDENTITY_LINK_KIND = "identity_link";
5
5
  /**
6
6
  * Why two people may be one: an agent said so, they share a phone or an address with others, a meeting guest typed
7
- * an address another person has, or they have one name and share a phone, an address, a chat or a company's domain.
7
+ * an address another person has, they have one name and share a phone, an address, a chat or a company's domain, or
8
+ * an account the owner connected carries another name than the owner's (`account`).
8
9
  */
9
- export declare const IDENTITY_LINK_SIGNALS: readonly ["agent", "phone", "email", "guest-email", "name"];
10
+ export declare const IDENTITY_LINK_SIGNALS: readonly ["agent", "phone", "email", "guest-email", "name", "account"];
10
11
  export type IdentityLinkSignal = (typeof IDENTITY_LINK_SIGNALS)[number];
11
12
  /** An `identity_link` proposal's payload. */
12
13
  export interface IdentityLinkPayload {
@@ -1,6 +1,7 @@
1
1
  export const IDENTITY_LINK_KIND = "identity_link";
2
2
  /**
3
3
  * Why two people may be one: an agent said so, they share a phone or an address with others, a meeting guest typed
4
- * an address another person has, or they have one name and share a phone, an address, a chat or a company's domain.
4
+ * an address another person has, they have one name and share a phone, an address, a chat or a company's domain, or
5
+ * an account the owner connected carries another name than the owner's (`account`).
5
6
  */
6
- export const IDENTITY_LINK_SIGNALS = ["agent", "phone", "email", "guest-email", "name"];
7
+ export const IDENTITY_LINK_SIGNALS = ["agent", "phone", "email", "guest-email", "name", "account"];
@@ -48,7 +48,7 @@ export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
48
48
  export type { CatalogActor, CatalogEntry, CatalogInput, CatalogQuery, CatalogStore } from "./sqlite/catalog.js";
49
49
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
50
50
  export type { ChatMetadata } from "./sqlite/chats.js";
51
- export { type CrmCopies, type CrmRelationIssue, type CrmSaved, type CrmSkipped, crmIdentityId } from "./sqlite/crm.js";
51
+ export { type CrmContactsRemoved, type CrmCopies, type CrmRelationIssue, type CrmSaved, type CrmSkipped, crmIdentityId, } from "./sqlite/crm.js";
52
52
  export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, crmSettingKey, } from "./sqlite/crm-settings.js";
53
53
  export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, StageChange, } from "./sqlite/deals.js";
54
54
  export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
@@ -31,7 +31,7 @@ export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
31
31
  export { baseSettingKey } from "./sqlite/base-suggest.js";
32
32
  export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
33
33
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
34
- export { crmIdentityId } from "./sqlite/crm.js";
34
+ export { crmIdentityId, } from "./sqlite/crm.js";
35
35
  export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
36
36
  export { EVENT_FIELDS, } from "./sqlite/event-search.js";
37
37
  export { QUOTE_LIMIT, quoteKept } from "./sqlite/evidence-signature.js";
@@ -11,6 +11,13 @@ export declare const storedAccounts: ({ orm }: StoreContext) => StoredAccount[];
11
11
  export declare const storedAccount: ({ orm }: StoreContext, { provider, account }: AccountKey) => StoredAccount;
12
12
  /** Everything the account holds, children before parents: the foreign keys are enforced. */
13
13
  export declare const purgeAccount: ({ orm, database, now }: StoreContext, accountKey: number) => void;
14
+ /** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */
15
+ export declare const OWN: Set<string>;
16
+ /**
17
+ * Every row that points at `table`: foreign keys and `<name>_type` pointers, read from the store so a new one counts.
18
+ * `among`, a subquery of ids, limits each arm to them, so each reads its index rather than its whole table.
19
+ */
20
+ export declare const referencesTo: (database: CacheDatabase, table: "identities" | "persons", skip: Set<string>, among?: string) => string;
14
21
  export declare const unreferenced: (database: CacheDatabase, table: "identities") => Set<number>;
15
22
  /**
16
23
  * People only the purged account had seen go with it. An identity stays while anything else points at it
@@ -149,17 +149,25 @@ export const purgeAccount = ({ orm, database, now }, accountKey) => {
149
149
  dropUnusedVectors(database, hashes);
150
150
  };
151
151
  /** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */
152
- const OWN = new Set(["identity_links", "identity_link_events", "identity_revisions"]);
153
- /** Every row that points at `table`: foreign keys and `<name>_type` pointers, read from the store so a new one counts. */
154
- const referencesTo = (database, table, skip) => {
152
+ export const OWN = new Set(["identity_links", "identity_link_events", "identity_revisions"]);
153
+ /**
154
+ * Every row that points at `table`: foreign keys and `<name>_type` pointers, read from the store so a new one counts.
155
+ * `among`, a subquery of ids, limits each arm to them, so each reads its index rather than its whole table.
156
+ */
157
+ export const referencesTo = (database, table, skip, among) => {
158
+ const within = (column) => (among === undefined ? "" : ` ${column} IN (${among})`);
155
159
  const keys = database
156
160
  .prepare(`SELECT m.name AS tbl, f."from" AS col FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f
157
161
  WHERE m.type = 'table' AND f."table" = ?`)
158
162
  .all(table)
159
163
  .filter((row) => !skip.has(String(row.tbl)))
160
- .map((row) => `SELECT "${String(row.col)}" AS id FROM "${String(row.tbl)}"`);
164
+ .map((row) => {
165
+ const column = `"${String(row.col)}"`;
166
+ return `SELECT ${column} AS id FROM "${String(row.tbl)}"${among === undefined ? "" : ` WHERE${within(column)}`}`;
167
+ });
161
168
  const type = table === "identities" ? "identity" : "person";
162
- const pointers = pointerPairs(database).map(({ table: tbl, pointer }) => `SELECT ${pointer}_id AS id FROM "${tbl}" WHERE ${pointer}_type = '${type}'`);
169
+ const pointers = pointerPairs(database).map(({ table: tbl, pointer }) => `SELECT ${pointer}_id AS id FROM "${tbl}" WHERE ${pointer}_type = '${type}'` +
170
+ (among === undefined ? "" : ` AND${within(`${pointer}_id`)}`));
163
171
  return [...keys, ...pointers].join(" UNION ");
164
172
  };
165
173
  export const unreferenced = (database, table) => new Set(database
@@ -8,6 +8,9 @@ export declare const baseStagesOf: (database: CacheDatabase, pipeline: number) =
8
8
  /**
9
9
  * Suggests a base stage for every unconfirmed live stage of `pipelines` (every pipeline of the kind but the set's when absent): won and lost by outcome; an open one by its relative place among its pipeline's open stages, and when that
10
10
  * falls between two base stages, the one of the same name, else the nearer. Does nothing before the set exists.
11
+ * `onlyEmpty` leaves a stage that already has a suggestion: a sync must not replace one a model or an agent made.
11
12
  */
12
- export declare const suggestBaseStages: (database: CacheDatabase, kind: DealKind, pipelines?: readonly number[]) => void;
13
+ export declare const suggestBaseStages: (database: CacheDatabase, kind: DealKind, pipelines?: readonly number[], { onlyEmpty }?: {
14
+ onlyEmpty?: boolean;
15
+ }) => void;
13
16
  export {};
@@ -19,8 +19,9 @@ export const baseStagesOf = (database, pipeline) => database.prepare("SELECT * F
19
19
  /**
20
20
  * Suggests a base stage for every unconfirmed live stage of `pipelines` (every pipeline of the kind but the set's when absent): won and lost by outcome; an open one by its relative place among its pipeline's open stages, and when that
21
21
  * falls between two base stages, the one of the same name, else the nearer. Does nothing before the set exists.
22
+ * `onlyEmpty` leaves a stage that already has a suggestion: a sync must not replace one a model or an agent made.
22
23
  */
23
- export const suggestBaseStages = (database, kind, pipelines) => {
24
+ export const suggestBaseStages = (database, kind, pipelines, { onlyEmpty = false } = {}) => {
24
25
  const base = basePipelineOf(database, kind);
25
26
  if (base === undefined)
26
27
  return;
@@ -33,7 +34,8 @@ export const suggestBaseStages = (database, kind, pipelines) => {
33
34
  .prepare("SELECT id FROM pipelines WHERE kind = ? AND id <> ? AND deleted_at IS NULL")
34
35
  .all(kind, base)
35
36
  .map((row) => Number(row.id));
36
- const update = database.prepare("UPDATE pipeline_stages SET base_stage_id = ? WHERE id = ? AND base_confirmed = 0 AND base_stage_id IS NOT ?");
37
+ const update = database.prepare("UPDATE pipeline_stages SET base_stage_id = ? WHERE id = ? AND base_confirmed = 0 AND base_stage_id IS NOT ? " +
38
+ "AND (? = 0 OR base_stage_id IS NULL)");
37
39
  for (const pipeline of ids) {
38
40
  if (pipeline === base)
39
41
  continue;
@@ -56,7 +58,7 @@ export const suggestBaseStages = (database, kind, pipelines) => {
56
58
  else if (stage.outcome !== "open")
57
59
  chosen = ends[stage.outcome];
58
60
  const target = chosen === undefined ? null : Number(chosen.id);
59
- update.run(target, Number(stage.id), target);
61
+ update.run(target, Number(stage.id), target, onlyEmpty ? 1 : 0);
60
62
  }
61
63
  }
62
64
  };
@@ -0,0 +1,26 @@
1
+ import type { AccountKey } from "../types.js";
2
+ import type { StoreContext } from "./open.js";
3
+ /** What removing a CRM account's contacts outside its scope did, or would do. */
4
+ export interface CrmContactsRemoved {
5
+ /** Contacts no kept deal, lead or company names, removed with their link to a person. */
6
+ contacts: number;
7
+ /** People those contacts made, deleted because nothing else was left on them. */
8
+ persons: number;
9
+ /** People those contacts were on that stay: another identity, a note, an alias, the owner's decision, a mention. */
10
+ personsKept: number;
11
+ /** People whose name still carried a CRM import's `null #<id>`, given the name without it. */
12
+ names: number;
13
+ }
14
+ export declare const withoutPlaceholder: (name: string) => string | null;
15
+ /**
16
+ * Removes, in one transaction, every contact of the account that no kept deal or lead (not deleted, and inside
17
+ * `users` when given) names in a client's role, and that is no contact of a kept company. A contact the owner decided
18
+ * about, or one anything else points at, stays; so does one saved at or after `before`, whose deal may still be on
19
+ * its way. A person the removed contacts leave empty is deleted unless anything still points at them. People named
20
+ * after a contact keep that name without the import's `null #<id>`; the owner's person is never renamed.
21
+ */
22
+ export declare const removeCrmContacts: (context: StoreContext, key: AccountKey, { users, before, dryRun }: {
23
+ users?: readonly string[];
24
+ before: number;
25
+ dryRun?: boolean;
26
+ }) => CrmContactsRemoved;
@@ -0,0 +1,134 @@
1
+ import { findAccountPk, OWN, referencesTo } from "./accounts.js";
2
+ import { crmAccountPrefix, crmIdentityId } from "./crm-rows.js";
3
+ import { write } from "./transaction.js";
4
+ /** A CRM import can leave `null` or `null #<id>` in a name field; no person is called that. */
5
+ const PLACEHOLDER = /(?:^|\s)null(?:\s+#\d+)?(?=\s|$)/gi;
6
+ export const withoutPlaceholder = (name) => name.replace(PLACEHOLDER, " ").replace(/\s+/g, " ").trim() || null;
7
+ class DryRun extends Error {
8
+ counts;
9
+ constructor(counts) {
10
+ super("dry run");
11
+ this.counts = counts;
12
+ }
13
+ }
14
+ const NONE = { contacts: 0, persons: 0, personsKept: 0, names: 0 };
15
+ /**
16
+ * Removes, in one transaction, every contact of the account that no kept deal or lead (not deleted, and inside
17
+ * `users` when given) names in a client's role, and that is no contact of a kept company. A contact the owner decided
18
+ * about, or one anything else points at, stays; so does one saved at or after `before`, whose deal may still be on
19
+ * its way. A person the removed contacts leave empty is deleted unless anything still points at them. People named
20
+ * after a contact keep that name without the import's `null #<id>`; the owner's person is never renamed.
21
+ */
22
+ export const removeCrmContacts = (context, key, { users, before, dryRun = false }) => {
23
+ const { database } = context;
24
+ const accountId = findAccountPk(context, key);
25
+ if (accountId === undefined)
26
+ return NONE;
27
+ const prefix = `${crmAccountPrefix(key)}contact/`;
28
+ const contactOf = "i.provider = ? AND substr(i.external_id, 1, ?) = ?";
29
+ const contact = [key.provider, prefix.length, prefix];
30
+ const inScope = (item) => users === undefined
31
+ ? ""
32
+ : `AND (json_extract(${item}.metadata, '$.assignee') IS NULL OR ` +
33
+ `json_extract(${item}.metadata, '$.assignee') IN (SELECT id FROM temp.crm_scope))`;
34
+ const named = (table, type) => `EXISTS (SELECT 1 FROM links k JOIN ${table} d ON d.id = k.from_id WHERE k.to_type = 'person' ` +
35
+ `AND k.to_id = l.person_id AND k.from_type = '${type}' AND k.source = 'crm' AND k.role IS NOT 'owner' ` +
36
+ `AND k.deleted_at IS NULL AND d.account_id = ${accountId} AND d.deleted_at IS NULL ${inScope("d")})`;
37
+ const counted = () => {
38
+ for (const table of ["crm_scope", "crm_gone", "crm_persons", "crm_names", "crm_proposed"])
39
+ database.exec(`DROP TABLE IF EXISTS temp.${table}`);
40
+ database.exec("CREATE TEMP TABLE crm_scope (id TEXT PRIMARY KEY)");
41
+ database.exec("CREATE TEMP TABLE crm_gone (id INTEGER PRIMARY KEY, person INTEGER)");
42
+ database.exec("CREATE TEMP TABLE crm_persons (id INTEGER PRIMARY KEY)");
43
+ database.exec("CREATE TEMP TABLE crm_names (id INTEGER PRIMARY KEY, name TEXT)");
44
+ database.exec("CREATE TEMP TABLE crm_proposed (ref TEXT PRIMARY KEY, decided INTEGER NOT NULL)");
45
+ database
46
+ .prepare("INSERT INTO temp.crm_scope SELECT DISTINCT value FROM json_each(?)")
47
+ .run(JSON.stringify((users ?? []).map((id) => crmIdentityId(key, id, "user"))));
48
+ // An identity link the owner approved or rejected is his decision about this contact; one only proposed is not.
49
+ database.exec("INSERT INTO temp.crm_proposed SELECT ref, max(decided) FROM (" +
50
+ "SELECT json_extract(payload, '$.identity') AS ref, status <> 'proposed' AS decided FROM proposed_actions " +
51
+ "WHERE kind = 'identity_link' UNION ALL SELECT json_extract(payload, '$.with'), status <> 'proposed' " +
52
+ "FROM proposed_actions WHERE kind = 'identity_link') WHERE ref IS NOT NULL GROUP BY ref");
53
+ const identityRefs = referencesTo(database, "identities", new Set([...OWN, "account_identities", "involvements"]), "SELECT id FROM temp.crm_gone");
54
+ database
55
+ .prepare("INSERT INTO temp.crm_gone SELECT i.id, l.person_id FROM identities i " +
56
+ `LEFT JOIN identity_links l ON l.identity_id = i.id WHERE ${contactOf} ` +
57
+ "AND i.created_at < ? AND i.updated_at < ? " +
58
+ `AND NOT ${named("deals", "deal")} AND NOT ${named("leads", "lead")} ` +
59
+ "AND NOT EXISTS (SELECT 1 FROM links k JOIN records r ON r.entity_type = 'organization' " +
60
+ "AND r.entity_id = k.to_id WHERE k.from_type = 'person' AND k.from_id = l.person_id " +
61
+ "AND +k.to_type = 'organization' AND k.kind = 'member-of' AND k.role = 'contact' AND k.source = 'crm' " +
62
+ `AND k.deleted_at IS NULL AND r.account_id = ${accountId} AND r.type = 'organization' ` +
63
+ "AND r.deleted_at IS NULL) " +
64
+ "AND NOT EXISTS (SELECT 1 FROM identity_link_events e WHERE e.identity_id = i.id AND e.author = 'owner') " +
65
+ "AND NOT EXISTS (SELECT 1 FROM temp.crm_proposed c WHERE c.decided AND c.ref = i.provider || ':' || " +
66
+ "i.external_id)")
67
+ .run(...contact, before, before);
68
+ database.exec(`DELETE FROM temp.crm_gone WHERE id IN (${identityRefs})`);
69
+ // A same-email join left the contact's first person empty; it goes too, unless something points at it.
70
+ database.exec("INSERT OR IGNORE INTO temp.crm_persons SELECT person FROM temp.crm_gone WHERE person IS NOT NULL");
71
+ database.exec("INSERT OR IGNORE INTO temp.crm_persons SELECT from_person_id FROM identity_link_events " +
72
+ "WHERE identity_id IN (SELECT id FROM temp.crm_gone) AND from_person_id IS NOT NULL");
73
+ const names = database
74
+ .prepare("SELECT DISTINCT p.id, p.name, i.name AS was FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
75
+ `JOIN persons p ON p.id = l.person_id WHERE ${contactOf} AND p.owner = 0 AND p.name LIKE '%null%'`)
76
+ .all(...contact)
77
+ .flatMap((row) => {
78
+ const name = String(row.name);
79
+ const clean = withoutPlaceholder(name);
80
+ const was = typeof row.was === "string" ? withoutPlaceholder(row.was) : null;
81
+ return clean !== name && clean === was ? [{ id: Number(row.id), name: clean }] : [];
82
+ });
83
+ database
84
+ .prepare("INSERT OR IGNORE INTO temp.crm_names SELECT json_extract(value, '$.id'), json_extract(value, '$.name') " +
85
+ "FROM json_each(?)")
86
+ .run(JSON.stringify(names));
87
+ const gone = "(SELECT id FROM temp.crm_gone)";
88
+ const persons = "(SELECT id FROM temp.crm_persons)";
89
+ database
90
+ .prepare(`DELETE FROM links WHERE source = 'crm' AND account_id = ? AND ((to_type = 'person' AND to_id IN ${persons} ` +
91
+ "AND from_type IN ('deal', 'lead') AND role IS NOT 'owner') OR (from_type = 'person' " +
92
+ `AND from_id IN ${persons} AND kind = 'member-of' AND role = 'contact'))`)
93
+ .run(accountId);
94
+ database.exec("DELETE FROM proposed_actions WHERE kind = 'identity_link' AND status = 'proposed' AND (" +
95
+ `json_extract(payload, '$.identity') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}) ` +
96
+ `OR json_extract(payload, '$.with') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}))`);
97
+ for (const table of ["identity_revisions", "identity_link_events", "identity_links", "account_identities"])
98
+ database.exec(`DELETE FROM ${table} WHERE identity_id IN ${gone}`);
99
+ const contacts = database.prepare(`DELETE FROM identities WHERE id IN ${gone}`).run().changes;
100
+ // Involvements are worked out again from what is left; they keep no one.
101
+ const personRefs = referencesTo(database, "persons", new Set(["identity_links", "involvements"]), "SELECT id FROM temp.crm_persons");
102
+ // A proposal names its people in its payload: deleting one would leave the owner's answer about nobody.
103
+ const proposed = "SELECT CAST(substr(value, 8) AS INTEGER) AS id FROM proposed_actions, json_each(json_array(" +
104
+ "json_extract(payload, '$.from'), json_extract(payload, '$.to'))) WHERE value LIKE 'person:%' " +
105
+ "UNION SELECT CAST(value AS INTEGER) FROM proposed_actions, json_each(payload, '$.persons') " +
106
+ "WHERE json_type(payload, '$.persons') = 'array'";
107
+ database.exec(`DELETE FROM temp.crm_persons WHERE id IN (SELECT id FROM persons WHERE owner <> 0) ` +
108
+ "OR id IN (SELECT person_id FROM identity_links) " +
109
+ `OR id IN (${personRefs}) OR id IN (${proposed})`);
110
+ database.exec(`DELETE FROM involvements WHERE person_id IN ${persons}`);
111
+ const deleted = database.prepare(`DELETE FROM persons WHERE id IN ${persons}`).run().changes;
112
+ const personsKept = Number(database
113
+ .prepare("SELECT count(DISTINCT person) AS n FROM temp.crm_gone WHERE person IN (SELECT id FROM persons)")
114
+ .get()?.n);
115
+ const renamed = database
116
+ .prepare("UPDATE persons SET name = (SELECT name FROM temp.crm_names n WHERE n.id = persons.id), updated_at = ? " +
117
+ "WHERE id IN (SELECT id FROM temp.crm_names)")
118
+ .run(context.now()).changes;
119
+ return { contacts, persons: deleted, personsKept, names: renamed };
120
+ };
121
+ try {
122
+ return write(database, () => {
123
+ const counts = counted();
124
+ if (dryRun)
125
+ throw new DryRun(counts);
126
+ return counts;
127
+ });
128
+ }
129
+ catch (error) {
130
+ if (error instanceof DryRun)
131
+ return error.counts;
132
+ throw error;
133
+ }
134
+ };
@@ -23,6 +23,8 @@ export declare const crmLinkMode: (database: CacheDatabase, key: AccountKey) =>
23
23
  export declare const crmCompanyTypes: (database: CacheDatabase, key: AccountKey) => Record<string, CompanyTypeMeaning>;
24
24
  /** `mine` unless the owner chose `all`: a sync never copies other people's deals without being asked. */
25
25
  export declare const crmScope: (database: CacheDatabase, key: AccountKey) => CrmScopeSetting;
26
+ /** The users whose deals and leads scope mine keeps, whatever the scope is now: `self` and the `unassigned` list. */
27
+ export declare const crmScopeUsers: (database: CacheDatabase, key: AccountKey) => string[];
26
28
  /**
27
29
  * `links`: reported or review; `scope`: mine or all; `unassigned`: the CRM's user ids, comma-separated;
28
30
  * `company-types`: `TYPE=meaning` pairs, comma-separated.
@@ -53,6 +53,11 @@ const picked = (name, text, values) => {
53
53
  throw new CliError("validation_error", `a CRM account's ${name} setting is ${values.join(" or ")}`);
54
54
  return text;
55
55
  };
56
+ /** The users whose deals and leads scope mine keeps, whatever the scope is now: `self` and the `unassigned` list. */
57
+ export const crmScopeUsers = (database, key) => {
58
+ const self = crmOwnUser(database, key);
59
+ return [...new Set([...(self ? [self] : []), ...userIds(stored(database, crmSettingKey(key, "unassigned")))])];
60
+ };
56
61
  /**
57
62
  * `links`: reported or review; `scope`: mine or all; `unassigned`: the CRM's user ids, comma-separated;
58
63
  * `company-types`: `TYPE=meaning` pairs, comma-separated.
@@ -2,6 +2,7 @@ import { type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type Crm
2
2
  import { type DealKind } from "../../domain/deals.js";
3
3
  import type { AccountPeople } from "../people.js";
4
4
  import type { AccountKey } from "../types.js";
5
+ import { type CrmContactsRemoved } from "./crm-contacts.js";
5
6
  import { type CrmSkipped } from "./crm-rows.js";
6
7
  import type { StoreContext } from "./open.js";
7
8
  /**
@@ -88,10 +89,21 @@ export interface CrmCopies {
88
89
  removeOutOfScope(key: AccountKey, kind: DealKind, userIds: readonly string[], options?: {
89
90
  dryRun?: boolean;
90
91
  }): Promise<number>;
92
+ /**
93
+ * Removes the contacts no kept deal, lead or company names, and the people they leave empty; see
94
+ * `removeCrmContacts`. A deal or lead assigned to a user outside `users` counts as gone; without `users`, outside
95
+ * those scope mine keeps (`self` and `unassigned`), whatever the scope is now. `dryRun` only counts.
96
+ */
97
+ removeContacts(key: AccountKey, options: {
98
+ users?: readonly string[];
99
+ before: number;
100
+ dryRun?: boolean;
101
+ }): Promise<CrmContactsRemoved>;
91
102
  /** How many of the kind the account holds, not deleted; every contact it ever saved. */
92
103
  count(key: AccountKey, kind: CrmKind): Promise<number>;
93
104
  /** The stored copy's `deal:<id>` or `lead:<id>`, deleted or not; `null` when the store holds none. */
94
105
  refOf(key: AccountKey, kind: DealKind, externalId: string): Promise<string | null>;
95
106
  }
107
+ export type { CrmContactsRemoved } from "./crm-contacts.js";
96
108
  export { type CrmSkipped, crmIdentityId, crmRowsOver, type ItemWriter } from "./crm-rows.js";
97
109
  export declare const crmCopiesOver: (context: StoreContext, people: AccountPeople) => CrmCopies;
@@ -1,11 +1,12 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { isItemKind, } from "../../domain/crm.js";
2
+ import { isItemKind, normalCrmUserId, } from "../../domain/crm.js";
3
3
  import { DEAL_ROLES } from "../../domain/deals.js";
4
4
  import { recordFingerprint } from "../../domain/records.js";
5
5
  import { accountPk, findAccountPk } from "./accounts.js";
6
6
  import { suggestBaseStages } from "./base-suggest.js";
7
+ import { removeCrmContacts } from "./crm-contacts.js";
7
8
  import { crmAccountPrefix, crmIdentityId, crmRowsOver, SOURCE, TABLES, textOf } from "./crm-rows.js";
8
- import { crmCompanyTypes, crmOwnUser, crmScope, crmSettingKey, saveCrmSetting } from "./crm-settings.js";
9
+ import { crmCompanyTypes, crmOwnUser, crmScope, crmScopeUsers, crmSettingKey, saveCrmSetting } from "./crm-settings.js";
9
10
  import { syncReportedIn } from "./reported-relations.js";
10
11
  import { clearState, syncStateOf, writeState } from "./sync.js";
11
12
  import { write } from "./transaction.js";
@@ -32,7 +33,7 @@ export const crmCopiesOver = (context, people) => {
32
33
  const accountId = account(key);
33
34
  const at = now();
34
35
  const saved = pipelines.map((pipeline) => savePipeline(accountId, kind, pipeline, at));
35
- suggestBaseStages(database, kind, saved);
36
+ suggestBaseStages(database, kind, saved, { onlyEmpty: true });
36
37
  if (pipelines.length === 0)
37
38
  return { saved: 0, skipped: [] };
38
39
  const listed = new Set(pipelines.map(({ externalId }) => externalId));
@@ -115,12 +116,15 @@ export const crmCopiesOver = (context, people) => {
115
116
  "WHERE i.email = ?")
116
117
  .get(email)?.n);
117
118
  };
118
- /** A person a CRM contact or user made has no name when it joined the mail contact of its address first. */
119
+ /**
120
+ * A person a CRM contact or user made has no name when it joined the mail contact of its address first. The owner's
121
+ * name is never a CRM's: a contact on the owner's person by mistake must not rename them.
122
+ */
119
123
  const nameUnnamed = (key, externalId, type, name) => {
120
124
  const person = personIdOf(key, externalId, type);
121
125
  if (person !== null && name)
122
126
  database
123
- .prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ? AND name IS NULL")
127
+ .prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ? AND name IS NULL AND owner = 0")
124
128
  .run(name, now(), person);
125
129
  return person;
126
130
  };
@@ -591,6 +595,10 @@ export const crmCopiesOver = (context, people) => {
591
595
  .filter((row) => row.assignee != null && !keep.has(String(row.assignee)));
592
596
  return dryRun ? rows.length : markDeleted(key, kind, rows);
593
597
  }),
598
+ removeContacts: async (key, options) => removeCrmContacts(context, key, {
599
+ ...options,
600
+ users: options.users ?? crmScopeUsers(database, key).map(normalCrmUserId),
601
+ }),
594
602
  count: async (key, kind) => kind === "person"
595
603
  ? Number(database
596
604
  .prepare("SELECT count(*) AS n FROM identities WHERE provider = ? AND substr(external_id, 1, ?) = ?")
@@ -395,7 +395,9 @@ export const mailFindingsStoreOver = (context) => {
395
395
  }
396
396
  case "new_contact": {
397
397
  const person = Number(identityOfAddress(finding.address)?.person_id);
398
- database.prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ?").run(finding.name, now(), person);
398
+ database
399
+ .prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ? AND owner = 0")
400
+ .run(finding.name, now(), person);
399
401
  return `person:${person}`;
400
402
  }
401
403
  }
@@ -127,6 +127,8 @@ export const MANIFEST = [
127
127
  { name: "20261109170741_version-61-people-ties", version: 61, minCompatible: 56 },
128
128
  { name: "20261110005159_version-62-person-kinds", version: 62, minCompatible: 56 },
129
129
  { name: "20261110005200_version-62-person-kinds-triggers", version: 62, minCompatible: 56 },
130
+ { name: "20261110020704_version-63-people-ties-messages-crm", version: 63, minCompatible: 56 },
131
+ { name: "20261110084658_version-64-deal-link-triggers", version: 64, minCompatible: 56 },
130
132
  ];
131
133
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
132
134
  const migrations = [];