@wirecat/cli-core 0.732.0 → 0.734.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.
- package/CHANGELOG.md +30 -0
- package/dist/cli/messenger/search-command.js +1 -0
- package/dist/cli/option-hints.d.ts +7 -0
- package/dist/cli/option-hints.js +25 -0
- package/dist/cli/program.js +13 -23
- package/dist/cli/steps.d.ts +2 -0
- package/dist/cli/steps.js +15 -0
- package/dist/crm/cli/activities.d.ts +12 -2
- package/dist/crm/cli/activities.js +101 -6
- package/dist/crm/cli/changes.d.ts +3 -0
- package/dist/crm/cli/changes.js +11 -2
- package/dist/crm/cli/index.d.ts +3 -2
- package/dist/crm/index.d.ts +2 -2
- package/dist/crm/index.js +2 -2
- package/dist/crm/testing/index.d.ts +1 -1
- package/dist/crm/testing/source.d.ts +8 -0
- package/dist/crm/testing/source.js +56 -2
- package/dist/crm/writer.d.ts +30 -1
- package/dist/crm/writer.js +4 -0
- package/dist/crm/writes.d.ts +34 -2
- package/dist/crm/writes.js +100 -0
- package/dist/errors/reasons.js +1 -0
- package/dist/ports/messenger.d.ts +1 -1
- package/dist/services/archive.js +3 -2
- package/dist/services/embeddings-search.js +29 -3
- package/dist/store/conversations.d.ts +16 -0
- package/dist/store/conversations.js +7 -0
- package/dist/store/sqlite/account-purge.js +8 -15
- package/dist/store/sqlite/conversations.d.ts +16 -0
- package/dist/store/sqlite/conversations.js +49 -1
- package/dist/store/sqlite/erase-plan.js +27 -5
- package/dist/store/sqlite/organization-erase.d.ts +2 -1
- package/dist/store/sqlite/organization-erase.js +2 -1
- package/dist/store/sqlite/person-erase.d.ts +6 -3
- package/dist/store/sqlite/person-erase.js +33 -17
- package/package.json +1 -1
package/dist/crm/writer.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import type { ConditionalKey } from "../cli/permission-keys.js";
|
|
2
|
-
import type { CrmItem, CrmKind, CrmRecords } from "../domain/crm.js";
|
|
2
|
+
import type { CrmActivity, CrmItem, CrmKind, CrmRecords } from "../domain/crm.js";
|
|
3
3
|
import type { DealKind, DealRole } from "../domain/deals.js";
|
|
4
4
|
import type { Level, PermissionKey } from "../sends/permissions.js";
|
|
5
5
|
export declare const CRM_VERBS: readonly ["create", "update", "move", "close", "remove"];
|
|
6
6
|
export type CrmVerb = (typeof CRM_VERBS)[number];
|
|
7
|
+
/** The activities a CRM CLI may write: a comment (a note) on a record, and a task, which it may later mark done. */
|
|
8
|
+
export declare const CRM_ACTIVITY_WRITES: readonly ["comment", "task"];
|
|
9
|
+
export type CrmActivityWrite = (typeof CRM_ACTIVITY_WRITES)[number];
|
|
7
10
|
export interface CrmWriteCapabilities {
|
|
8
11
|
/** The kinds the CRM takes writes for; a contact or a company takes only `create` and `update`. */
|
|
9
12
|
kinds: readonly CrmKind[];
|
|
@@ -14,6 +17,11 @@ export interface CrmWriteCapabilities {
|
|
|
14
17
|
* create repeated with one REST 3.0 `Idempotency-Key` a second time.
|
|
15
18
|
*/
|
|
16
19
|
idempotent: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* The activities the writer makes: mounts `activities create` for these kinds, and `activities close` for a task.
|
|
22
|
+
* Left out, the CLI gets neither, and the writer needs no `createActivity` or `completeActivity`.
|
|
23
|
+
*/
|
|
24
|
+
activities?: readonly CrmActivityWrite[];
|
|
17
25
|
}
|
|
18
26
|
/**
|
|
19
27
|
* A deal's or lead's fields in `CrmItem`'s names, each the CRM's own id; `null` clears one. `custom` holds the CRM's
|
|
@@ -81,6 +89,23 @@ export interface CrmDrafts {
|
|
|
81
89
|
name: string;
|
|
82
90
|
};
|
|
83
91
|
}
|
|
92
|
+
/** A new comment or task on one or more of the CRM's deals, leads, contacts and companies. */
|
|
93
|
+
export interface CrmActivityDraft {
|
|
94
|
+
kind: CrmActivityWrite;
|
|
95
|
+
/** A task's title; a comment's title, for a CRM that keeps one. Required for a task. */
|
|
96
|
+
subject?: string;
|
|
97
|
+
/** A comment's text, or a task's description. Required for a comment. */
|
|
98
|
+
body?: string;
|
|
99
|
+
/** A task's deadline, epoch ms. */
|
|
100
|
+
dueAt?: number;
|
|
101
|
+
/** A task's CRM user, by the CRM's id; left out, the CRM's own default (most often the sign-in's user). */
|
|
102
|
+
assignee?: string;
|
|
103
|
+
/** The records it is on, by the CRM's ids: at least one. */
|
|
104
|
+
on: {
|
|
105
|
+
kind: CrmKind;
|
|
106
|
+
externalId: string;
|
|
107
|
+
}[];
|
|
108
|
+
}
|
|
84
109
|
export interface CrmWriteOptions {
|
|
85
110
|
/** Journaled before the call; an idempotent CRM gets it as its idempotency key. */
|
|
86
111
|
operationId: string;
|
|
@@ -106,6 +131,10 @@ export interface CrmWriter {
|
|
|
106
131
|
reason?: string;
|
|
107
132
|
}): Promise<CrmItem>;
|
|
108
133
|
remove(kind: DealKind, externalId: string, options: CrmWriteOptions): Promise<void>;
|
|
134
|
+
/** Needed when `capabilities.activities` names any: the new activity as the CRM holds it. */
|
|
135
|
+
createActivity?(draft: CrmActivityDraft, options: CrmWriteOptions): Promise<CrmActivity>;
|
|
136
|
+
/** Needed when `capabilities.activities` names `task`: the task, done, as the CRM holds it. */
|
|
137
|
+
completeActivity?(externalId: string, options: CrmWriteOptions): Promise<CrmActivity>;
|
|
109
138
|
}
|
|
110
139
|
/** Giving a record to a CRM user other than the one the sign-in acts as. */
|
|
111
140
|
export declare const CRM_ASSIGN_OTHERS_KEY: PermissionKey;
|
package/dist/crm/writer.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export const CRM_VERBS = ["create", "update", "move", "close", "remove"];
|
|
2
|
+
/** The activities a CRM CLI may write: a comment (a note) on a record, and a task, which it may later mark done. */
|
|
3
|
+
export const CRM_ACTIVITY_WRITES = ["comment", "task"];
|
|
2
4
|
/** Giving a record to a CRM user other than the one the sign-in acts as. */
|
|
3
5
|
export const CRM_ASSIGN_OTHERS_KEY = "crm.assign-others";
|
|
4
6
|
/** The keys the CRM writes check beyond their command paths, for a CLI's `commandPermissions({ extra })`. */
|
|
@@ -23,6 +25,8 @@ const VERB_OF = {
|
|
|
23
25
|
*/
|
|
24
26
|
export const crmAlsoChecks = (also) => (path) => {
|
|
25
27
|
const [noun, command] = path;
|
|
28
|
+
if (noun === "activities" && command === "create" && path.length === 2)
|
|
29
|
+
return [{ key: CRM_ASSIGN_OTHERS_KEY, when: "--owner other than the sign-in's user" }];
|
|
26
30
|
const kind = noun === undefined ? undefined : PLURALS[noun];
|
|
27
31
|
const verb = command === undefined ? undefined : VERB_OF[command];
|
|
28
32
|
if (path.length !== 2 || kind === undefined || verb === undefined)
|
package/dist/crm/writes.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
-
import type
|
|
2
|
+
import { type CrmActivity, type CrmField, type CrmKind, type CrmOrganization, type CrmPerson } from "../domain/crm.js";
|
|
3
3
|
import type { DealKind } from "../domain/deals.js";
|
|
4
4
|
import type { Asker } from "../sends/guard.js";
|
|
5
5
|
import type { PermissionKey } from "../sends/permissions.js";
|
|
@@ -8,7 +8,7 @@ import type { Deal, PipelineOptions, PipelineReport } from "../store/sqlite/deal
|
|
|
8
8
|
import type { MessageStore } from "../store/store.js";
|
|
9
9
|
import type { AccountKey } from "../store/types.js";
|
|
10
10
|
import type { CrmSource } from "./source.js";
|
|
11
|
-
import { type CrmVerb, type CrmWriter } from "./writer.js";
|
|
11
|
+
import { type CrmActivityWrite, type CrmVerb, type CrmWriter } from "./writer.js";
|
|
12
12
|
/** What a CLI hands the CRM writes for one profile. */
|
|
13
13
|
export interface CrmWrites extends ProfileWrites {
|
|
14
14
|
writer: CrmWriter;
|
|
@@ -135,3 +135,35 @@ export declare const createCrmRecord: <K extends CrmRecordKind>(context: CrmWrit
|
|
|
135
135
|
export declare const updateCrmRecord: <K extends CrmRecordKind>(context: CrmWriteContext, kind: K, externalId: string, input: CrmRecordInput, options?: {
|
|
136
136
|
operationId?: string;
|
|
137
137
|
}) => Promise<CrmRecordWritten<K>>;
|
|
138
|
+
/** A comment or task as typed: `on`, the records it is on, as `deal:12`, `lead:4` (the copy's), or `person:<id>`, `organization:<id>` (the CRM's). */
|
|
139
|
+
export interface CrmActivityInput {
|
|
140
|
+
title?: string;
|
|
141
|
+
body?: string;
|
|
142
|
+
/** A task's deadline, epoch ms. */
|
|
143
|
+
dueAt?: number;
|
|
144
|
+
owner?: string;
|
|
145
|
+
on: readonly string[];
|
|
146
|
+
}
|
|
147
|
+
/** A record an activity is on: the copy's reference and title when the copy holds it. */
|
|
148
|
+
export interface CrmActivityTarget {
|
|
149
|
+
kind: CrmKind;
|
|
150
|
+
externalId: string;
|
|
151
|
+
ref: string | null;
|
|
152
|
+
title: string | null;
|
|
153
|
+
}
|
|
154
|
+
export interface CrmActivityWritten {
|
|
155
|
+
operationId: string;
|
|
156
|
+
/** The CRM's answer. */
|
|
157
|
+
activity: CrmActivity;
|
|
158
|
+
/** Whether the copy keeps it: only with the activities setting on, and on a record the copy keeps, as a sync does. */
|
|
159
|
+
stored: boolean;
|
|
160
|
+
on: CrmActivityTarget[];
|
|
161
|
+
}
|
|
162
|
+
/** A new comment or task on records of the CRM, through the guarded path; the CRM's answer is stored as a sync would. */
|
|
163
|
+
export declare const createCrmActivity: (context: CrmWriteContext, kind: CrmActivityWrite, input: CrmActivityInput, options?: {
|
|
164
|
+
operationId?: string;
|
|
165
|
+
}) => Promise<CrmActivityWritten>;
|
|
166
|
+
/** A task marked done in the CRM by its id, as `activities list` prints it; the copy is stored again. */
|
|
167
|
+
export declare const completeCrmActivity: (context: CrmWriteContext, externalId: string, options?: {
|
|
168
|
+
operationId?: string;
|
|
169
|
+
}) => Promise<CrmActivityWritten>;
|
package/dist/crm/writes.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
|
+
import { isItemKind, } from "../domain/crm.js";
|
|
2
3
|
import { currencyOf, minorUnits } from "../domain/money.js";
|
|
3
4
|
import { e164Of } from "../domain/phones.js";
|
|
4
5
|
import { foldName } from "../resolve.js";
|
|
@@ -511,3 +512,102 @@ export const updateCrmRecord = async (context, kind, externalId, input, options
|
|
|
511
512
|
const operationId = operationOf(context, options.operationId);
|
|
512
513
|
return writeRecord(context, kind, "update", fields, operationId, () => writer.update(kind, externalId, fields, { operationId }));
|
|
513
514
|
};
|
|
515
|
+
const MOST_SUBJECT = 500;
|
|
516
|
+
const MOST_BODY = 20_000;
|
|
517
|
+
const activityInvalid = (message, param) => new CliError("validation_error", message, { reason: "crm.activity-field", ...(param ? { param } : {}) });
|
|
518
|
+
const activityUnsupported = (what) => new CliError("validation_error", `this CRM does not take ${what}`, { reason: "crm.write-unsupported", sent: false });
|
|
519
|
+
/** `deal:12` and `lead:4` by the copy, as `deals list` shows them; a contact or company by the CRM's id. */
|
|
520
|
+
const activityTargetOf = async (context, given) => {
|
|
521
|
+
const at = given.indexOf(":");
|
|
522
|
+
const kind = given.slice(0, at);
|
|
523
|
+
const id = given.slice(at + 1);
|
|
524
|
+
if (kind === "deal" || kind === "lead") {
|
|
525
|
+
const copy = await copyOf(context, kind, given.trim());
|
|
526
|
+
return { kind, externalId: copy.externalId, ref: copy.ref, title: copy.title };
|
|
527
|
+
}
|
|
528
|
+
if ((kind === "person" || kind === "organization") && RECORD_ID.test(id))
|
|
529
|
+
return { kind, externalId: id, ref: null, title: null };
|
|
530
|
+
throw new CliError("validation_error", `--subject takes deal:<id> or lead:<id> as a list shows it, or person:<id> or organization:<id> by the CRM's id; got ${given}`, { reason: "ref.malformed", param: "--subject" });
|
|
531
|
+
};
|
|
532
|
+
const activityKeys = async (context, key, owner) => ({
|
|
533
|
+
key,
|
|
534
|
+
extra: owner !== undefined && owner !== (await selfOf(context)) ? [CRM_ASSIGN_OTHERS_KEY] : [],
|
|
535
|
+
});
|
|
536
|
+
/** The CRM's answer into the store, as a sync saves it; a failure names the activity, which the CRM has written. */
|
|
537
|
+
const keptActivity = async (context, activity, operationId) => {
|
|
538
|
+
try {
|
|
539
|
+
if (!(await context.store.crm.activitiesOn(context.account)))
|
|
540
|
+
return false;
|
|
541
|
+
return (await context.store.crm.saveActivities(context.account, [activity])).saved === 1;
|
|
542
|
+
}
|
|
543
|
+
catch (error) {
|
|
544
|
+
throw new CliError("invalid_response", `the CRM wrote activity ${activity.externalId}, but the local store did not keep it ` +
|
|
545
|
+
`(${error instanceof Error ? error.message : String(error)}); sync to store it — do not write it again`, { external_id: activity.externalId, operation_id: operationId, sent: true });
|
|
546
|
+
}
|
|
547
|
+
};
|
|
548
|
+
/** The records the CRM answered it is on; a deal or lead the copy holds by its reference too. */
|
|
549
|
+
const answeredTargets = async (context, activity, known) => Promise.all(activity.on.map(async ({ kind, externalId }) => known.find((one) => one.kind === kind && one.externalId === externalId) ?? {
|
|
550
|
+
kind,
|
|
551
|
+
externalId,
|
|
552
|
+
ref: isItemKind(kind) ? await context.store.crm.refOf(context.account, kind, externalId) : null,
|
|
553
|
+
title: null,
|
|
554
|
+
}));
|
|
555
|
+
/** A new comment or task on records of the CRM, through the guarded path; the CRM's answer is stored as a sync would. */
|
|
556
|
+
export const createCrmActivity = async (context, kind, input, options = {}) => {
|
|
557
|
+
const { writer } = context.writes;
|
|
558
|
+
const create = writer.createActivity?.bind(writer);
|
|
559
|
+
if (!create || !writer.capabilities.activities?.includes(kind))
|
|
560
|
+
throw activityUnsupported(`a new ${kind}`);
|
|
561
|
+
const subject = input.title?.trim();
|
|
562
|
+
const body = input.body?.trim();
|
|
563
|
+
if (subject !== undefined && (subject === "" || subject.length > MOST_SUBJECT))
|
|
564
|
+
throw activityInvalid(`--title is 1 to ${MOST_SUBJECT} characters`, "--title");
|
|
565
|
+
if (body !== undefined && (body === "" || body.length > MOST_BODY))
|
|
566
|
+
throw activityInvalid(`--text is 1 to ${MOST_BODY} characters`, "--text");
|
|
567
|
+
if (kind === "task" && subject === undefined)
|
|
568
|
+
throw activityInvalid("a new task needs --title", "--title");
|
|
569
|
+
if (kind === "comment" && body === undefined)
|
|
570
|
+
throw activityInvalid("a new comment needs --text", "--text");
|
|
571
|
+
if (kind === "comment" && input.dueAt !== undefined)
|
|
572
|
+
throw activityInvalid("a comment has no --due", "--due");
|
|
573
|
+
if (kind === "comment" && input.owner !== undefined)
|
|
574
|
+
throw activityInvalid("a comment has no --owner", "--owner");
|
|
575
|
+
const owner = input.owner?.trim();
|
|
576
|
+
if (owner !== undefined && !owner)
|
|
577
|
+
throw activityInvalid("--owner is the CRM user's id", "--owner");
|
|
578
|
+
if (input.on.length === 0)
|
|
579
|
+
throw activityInvalid("name the record it is on with --subject, such as deal:12", "--subject");
|
|
580
|
+
const targets = [];
|
|
581
|
+
for (const given of input.on) {
|
|
582
|
+
const target = await activityTargetOf(context, given);
|
|
583
|
+
if (!targets.some((one) => one.kind === target.kind && one.externalId === target.externalId))
|
|
584
|
+
targets.push(target);
|
|
585
|
+
}
|
|
586
|
+
const draft = {
|
|
587
|
+
kind,
|
|
588
|
+
...(subject === undefined ? {} : { subject }),
|
|
589
|
+
...(body === undefined ? {} : { body }),
|
|
590
|
+
...(input.dueAt === undefined ? {} : { dueAt: input.dueAt }),
|
|
591
|
+
...(owner === undefined ? {} : { assignee: owner }),
|
|
592
|
+
on: targets.map(({ kind, externalId }) => ({ kind, externalId })),
|
|
593
|
+
};
|
|
594
|
+
const operationId = operationOf(context, options.operationId);
|
|
595
|
+
const activity = await written(context, await activityKeys(context, "activities.create", owner), operationId, () => create(draft, { operationId }));
|
|
596
|
+
const stored = await keptActivity(context, activity, operationId);
|
|
597
|
+
return { operationId, activity, stored, on: await answeredTargets(context, activity, targets) };
|
|
598
|
+
};
|
|
599
|
+
/** A task marked done in the CRM by its id, as `activities list` prints it; the copy is stored again. */
|
|
600
|
+
export const completeCrmActivity = async (context, externalId, options = {}) => {
|
|
601
|
+
const { writer } = context.writes;
|
|
602
|
+
const complete = writer.completeActivity?.bind(writer);
|
|
603
|
+
if (!complete || !writer.capabilities.activities?.includes("task"))
|
|
604
|
+
throw activityUnsupported("a task marked done");
|
|
605
|
+
if (!RECORD_ID.test(externalId))
|
|
606
|
+
throw new CliError("validation_error", "name the task by the CRM's id, as activities list prints it", {
|
|
607
|
+
reason: "ref.malformed",
|
|
608
|
+
});
|
|
609
|
+
const operationId = operationOf(context, options.operationId);
|
|
610
|
+
const activity = await written(context, await activityKeys(context, "activities.close", undefined), operationId, () => complete(externalId, { operationId }));
|
|
611
|
+
const stored = await keptActivity(context, activity, operationId);
|
|
612
|
+
return { operationId, activity, stored, on: await answeredTargets(context, activity, []) };
|
|
613
|
+
};
|
package/dist/errors/reasons.js
CHANGED
|
@@ -567,6 +567,7 @@ const OTHERS = [
|
|
|
567
567
|
validation("field.not-filterable", "the CRM cannot filter a list by that custom field"),
|
|
568
568
|
validation("query.bad-value", "a term's value is not the kind its field takes, such as an id or a number"),
|
|
569
569
|
validation("crm.record-field", "a contact's or company's field is not valid"),
|
|
570
|
+
validation("crm.activity-field", "a comment's or task's field is not valid, or the kind does not take it"),
|
|
570
571
|
validation("crm.owner-unknown", "owner: names no CRM user: me without a known sign-in user, or not a user id"),
|
|
571
572
|
validation("crm.write-unsupported", "the CRM does not take this write, or does not recognise a repeated one"),
|
|
572
573
|
validation("crm.unlisted-held", "a list of every id would mark most of a kind deleted; nothing was, until --rescan"),
|
|
@@ -306,7 +306,7 @@ export interface ThreadReplies {
|
|
|
306
306
|
*/
|
|
307
307
|
threadReplies(chatId: Id, window: {
|
|
308
308
|
since?: number;
|
|
309
|
-
}): Promise<Message[]
|
|
309
|
+
}): Promise<Message[] | AsyncIterable<Message[]>> | AsyncIterable<Message[]>;
|
|
310
310
|
}
|
|
311
311
|
export interface MessageButtons {
|
|
312
312
|
/** The keyboard one message carries, row by row; a message without one answers `[]`. */
|
package/dist/services/archive.js
CHANGED
|
@@ -437,8 +437,9 @@ const savedReplies = async (connection, store, account, chatId, stop) => {
|
|
|
437
437
|
return 0;
|
|
438
438
|
const startedAt = Date.now();
|
|
439
439
|
const point = Number((await store.sync.syncState(account, threadsKey(chatId)))?.value);
|
|
440
|
-
|
|
441
|
-
const
|
|
440
|
+
// Awaited first: the flood wrapper turns every adapter method async, so batches arrive inside a promise.
|
|
441
|
+
const answer = await connection.threadReplies(chatId, Number.isFinite(point) ? { since: point } : {});
|
|
442
|
+
const batches = Symbol.asyncIterator in answer ? answer : [answer];
|
|
442
443
|
let saved = 0;
|
|
443
444
|
for await (const replies of batches) {
|
|
444
445
|
if (replies.length > 0)
|
|
@@ -38,6 +38,8 @@ const SHOWN_HEAD = 80;
|
|
|
38
38
|
const CHUNK_READ = 60;
|
|
39
39
|
/** Replies from outside a hit's chunk read per hit; the best one is shown with its lines. */
|
|
40
40
|
const REPLIES_READ = 60;
|
|
41
|
+
/** A conversation with more chunks than this is near any question, so its nearest chunk is often another topic. */
|
|
42
|
+
const BIG_CONVERSATION = 50;
|
|
41
43
|
/** Reciprocal rank fusion's usual constant (phase 5 E9). */
|
|
42
44
|
const RRF_K = 60;
|
|
43
45
|
export const embeddingsSearch = (deps) => {
|
|
@@ -211,9 +213,10 @@ export const embeddingsSearch = (deps) => {
|
|
|
211
213
|
const meaning = texts.map(() => []);
|
|
212
214
|
const own = [];
|
|
213
215
|
const sources = words.sources;
|
|
216
|
+
let vectors = [];
|
|
214
217
|
if (target.installed && prepared.scopeAccounts.length && eligibility?.conversations.length !== 0) {
|
|
215
218
|
await withEmbedder(deps, target, choice, {}, async (embedder) => {
|
|
216
|
-
|
|
219
|
+
vectors = (await embedder.embed(texts, "query"));
|
|
217
220
|
for (const [at, vector] of vectors.entries())
|
|
218
221
|
for (const one of prepared.scopeAccounts) {
|
|
219
222
|
const scope = scopeOf(one);
|
|
@@ -300,9 +303,26 @@ export const embeddingsSearch = (deps) => {
|
|
|
300
303
|
locator: formatLocator({ ...source, chat: hit.summary.chatId, message: hit.chunk.firstMessageId }),
|
|
301
304
|
};
|
|
302
305
|
};
|
|
303
|
-
|
|
306
|
+
// Only with a made-up reply: on the question alone it moved shown answers off their chunk.
|
|
307
|
+
const stemmed = [
|
|
308
|
+
...chunkStems(query).map((stem) => ({ stem, weight: 2 })),
|
|
309
|
+
...texts.slice(1).flatMap((text) => chunkStems(text).map((stem) => ({ stem, weight: 1 }))),
|
|
310
|
+
];
|
|
311
|
+
const rechunked = async (hit) => {
|
|
312
|
+
const source = sources.get(hit.summary.id);
|
|
313
|
+
if (texts.length < 2 || hit.matchedIn || !vectors.length || !source)
|
|
314
|
+
return hit;
|
|
315
|
+
const chunk = await store.conversations.bestChunk(source, hit.summary.id, {
|
|
316
|
+
model: target.key,
|
|
317
|
+
vectors,
|
|
318
|
+
stems: stemmed,
|
|
319
|
+
over: BIG_CONVERSATION,
|
|
320
|
+
});
|
|
321
|
+
return chunk ? { ...hit, chunk } : hit;
|
|
322
|
+
};
|
|
323
|
+
const hits = (await Promise.all(fused(meaning.map((list) => list.map(({ hit }) => hit)), words.hits, meaningFloor(target.key))
|
|
304
324
|
.slice(0, limit)
|
|
305
|
-
.map(located);
|
|
325
|
+
.map(rechunked))).map(located);
|
|
306
326
|
const shown = new Set(hits.map((hit) => hit.summary.id));
|
|
307
327
|
const ownOf = (keep) => own
|
|
308
328
|
.filter(keep)
|
|
@@ -482,6 +502,12 @@ const fused = (meaning, words, minimumCosine) => {
|
|
|
482
502
|
.sort((a, b) => b.fused - a.fused || (b.score ?? -2) - (a.score ?? -2))
|
|
483
503
|
.map(({ fused: _, ...hit }) => hit);
|
|
484
504
|
};
|
|
505
|
+
/** Every word of three letters or more, stop words too, by its first five letters. */
|
|
506
|
+
const chunkStems = (text) => [
|
|
507
|
+
...new Set((text.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? [])
|
|
508
|
+
.filter((word) => word.length >= 3)
|
|
509
|
+
.map((word) => word.slice(0, 5))),
|
|
510
|
+
];
|
|
485
511
|
/** Each word's first five letters, lowercased: enough to match its other forms in Russian and English. */
|
|
486
512
|
const wordStems = (text) => [...new Set(queryWords(text).map((word) => word.slice(0, 5)))];
|
|
487
513
|
/**
|
|
@@ -58,6 +58,22 @@ export interface ConversationsStore {
|
|
|
58
58
|
text: string;
|
|
59
59
|
outgoing: boolean;
|
|
60
60
|
}[][]>;
|
|
61
|
+
/**
|
|
62
|
+
* In a conversation of more than `over` chunks, the chunk that ranks best by summed cosine to `vectors` and by the
|
|
63
|
+
* weighted rarity of `stems` among its chunks, fused; `undefined` for a smaller conversation.
|
|
64
|
+
*/
|
|
65
|
+
bestChunk(key: AccountKey, conversationId: string, search: {
|
|
66
|
+
model: string;
|
|
67
|
+
vectors: Float32Array[];
|
|
68
|
+
stems: {
|
|
69
|
+
stem: string;
|
|
70
|
+
weight: number;
|
|
71
|
+
}[];
|
|
72
|
+
over: number;
|
|
73
|
+
}): Promise<{
|
|
74
|
+
firstMessageId: Id;
|
|
75
|
+
lastMessageId: Id;
|
|
76
|
+
} | undefined>;
|
|
61
77
|
/** Every link a message has, the messenger's first. */
|
|
62
78
|
links(key: AccountKey, chatId: Id, messageId: Id, options?: {
|
|
63
79
|
limit: number;
|
|
@@ -64,6 +64,13 @@ export const conversationsStoreOver = (context) => {
|
|
|
64
64
|
? chunks.map(() => [])
|
|
65
65
|
: conversationQueries.chunkRepliesOf(context, accountPk, chunks, limit);
|
|
66
66
|
},
|
|
67
|
+
bestChunk: async (key, conversationId, search) => {
|
|
68
|
+
const accountPk = findAccountPk(key);
|
|
69
|
+
const pk = Number(conversationId);
|
|
70
|
+
return accountPk === undefined || !Number.isSafeInteger(pk)
|
|
71
|
+
? undefined
|
|
72
|
+
: conversationQueries.bestChunkOf(context, accountPk, pk, search);
|
|
73
|
+
},
|
|
67
74
|
links: async (key, chatId, messageId, options) => {
|
|
68
75
|
const chatKey = chatKeyOf(key, chatId);
|
|
69
76
|
return chatKey === undefined ? [] : conversationQueries.linksOf(context, chatKey, messageId, options?.limit);
|
|
@@ -2,6 +2,7 @@ import { dropOrphanPeople, unreferenced } from "./accounts.js";
|
|
|
2
2
|
import { calendarCursorKey, calendarWritesOver } from "./calendar.js";
|
|
3
3
|
import { forgetCalendarRows } from "./calendar-forget.js";
|
|
4
4
|
import { eq, inArray, sql } from "./drizzle/core.js";
|
|
5
|
+
import { ErasePlan } from "./erase-plan.js";
|
|
5
6
|
import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
|
|
6
7
|
import { eraseImportedOrganizations, importedOrganizations } from "./organization-erase.js";
|
|
7
8
|
import { eraseImportedPeople, importedPeople } from "./person-erase.js";
|
|
@@ -113,6 +114,9 @@ export const purgeAccount = (context, accountKey) => {
|
|
|
113
114
|
const recordsOf = sql `(SELECT id FROM records WHERE account_id = ${accountKey})`;
|
|
114
115
|
orm.run(sql `DELETE FROM record_relations WHERE record_id IN ${recordsOf} OR target_id IN ${recordsOf}`);
|
|
115
116
|
orm.run(sql `DELETE FROM records WHERE account_id = ${accountKey}`);
|
|
117
|
+
// Relationships the account reported carry its id and no foreign key: left behind, the next account given that id
|
|
118
|
+
// would own them.
|
|
119
|
+
orm.run(sql `DELETE FROM links WHERE account_id = ${accountKey}`);
|
|
116
120
|
orm.delete(accounts).where(eq(accounts.id, accountKey)).run();
|
|
117
121
|
dropOrphanPeople(database, unseenBefore);
|
|
118
122
|
eraseImportedPeople(context, imported);
|
|
@@ -132,21 +136,10 @@ const purgeCrmCopies = (database, accountKey) => {
|
|
|
132
136
|
const leadsOf = "(SELECT id FROM leads WHERE account_id = ?)";
|
|
133
137
|
const pipelinesOf = "(SELECT id FROM pipelines WHERE account_id = ?)";
|
|
134
138
|
const stagesOf = `(SELECT id FROM pipeline_stages WHERE pipeline_id IN ${pipelinesOf})`;
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
run(`DELETE FROM links WHERE (from_type = ? AND from_id IN ${ids}) OR (to_type = ? AND to_id IN ${ids})`, type, accountKey, type, accountKey);
|
|
140
|
-
for (const [table, pointer] of [
|
|
141
|
-
["taggings", "taggable"],
|
|
142
|
-
["aliases", "aliasable"],
|
|
143
|
-
["attachments", "attachable"],
|
|
144
|
-
["link_reviews", "linkable"],
|
|
145
|
-
["entity_link_events", "linkable"],
|
|
146
|
-
])
|
|
147
|
-
run(`DELETE FROM ${table} WHERE ${pointer}_type = ? AND ${pointer}_id IN ${ids}`, type, accountKey);
|
|
148
|
-
run(`DELETE FROM pipeline_stage_changes WHERE item_type = ? AND item_id IN ${ids}`, type, accountKey);
|
|
149
|
-
}
|
|
139
|
+
new ErasePlan(database)
|
|
140
|
+
.pointers("deal", dealsOf.slice(1, -1), [accountKey])
|
|
141
|
+
.pointers("lead", leadsOf.slice(1, -1), [accountKey])
|
|
142
|
+
.run();
|
|
150
143
|
run(`DELETE FROM pipeline_stage_changes WHERE pipeline_id IN ${pipelinesOf}`, accountKey);
|
|
151
144
|
for (const table of ["leads", "orders", "contracts"])
|
|
152
145
|
run(`UPDATE ${table} SET deal_id = NULL WHERE deal_id IN ${dealsOf}`, accountKey);
|
|
@@ -90,6 +90,22 @@ export declare const chunkRepliesOf: ({ orm }: StoreContext, accountPk: number,
|
|
|
90
90
|
text: string;
|
|
91
91
|
outgoing: boolean;
|
|
92
92
|
}[][];
|
|
93
|
+
/**
|
|
94
|
+
* Rarity counts over the conversation's own chunks, not the store: a word every chunk holds says nothing about which
|
|
95
|
+
* one is meant. A word may sit anywhere in a chunk's text, as the shown lines match it.
|
|
96
|
+
*/
|
|
97
|
+
export declare const bestChunkOf: ({ orm }: StoreContext, accountPk: number, conversationPk: number, { model, vectors, stems, over, }: {
|
|
98
|
+
model: string;
|
|
99
|
+
vectors: Float32Array[];
|
|
100
|
+
stems: {
|
|
101
|
+
stem: string;
|
|
102
|
+
weight: number;
|
|
103
|
+
}[];
|
|
104
|
+
over: number;
|
|
105
|
+
}) => {
|
|
106
|
+
firstMessageId: Id;
|
|
107
|
+
lastMessageId: Id;
|
|
108
|
+
} | undefined;
|
|
93
109
|
/** Every link a message has, the messenger's first, then the strongest. */
|
|
94
110
|
export declare const linksOf: ({ orm }: StoreContext, chatKey: number, messageId: Id, limit?: number) => StoredLink[];
|
|
95
111
|
/** Candidates only: the caller checks which parent each child chooses, using the same link reader. */
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { setTimeout } from "node:timers/promises";
|
|
2
|
+
import { RRF_K } from "../../search/fusion.js";
|
|
2
3
|
import { and, asc, desc, eq, isNull, sql } from "./drizzle/core.js";
|
|
3
4
|
import { linkKind } from "./link-kinds.js";
|
|
4
5
|
import { bound } from "./query-filter.js";
|
|
@@ -6,7 +7,7 @@ import { selectMessages, toMessages } from "./reads.js";
|
|
|
6
7
|
import { accounts, chats, chunkMessages, chunks as chunkRows, conversationMessages, conversationState, conversations, identities, messageLinks, messages, } from "./schema.js";
|
|
7
8
|
import { writeBatch } from "./transaction.js";
|
|
8
9
|
import { toIso } from "./values.js";
|
|
9
|
-
import { purgeVectorHashes } from "./vectors.js";
|
|
10
|
+
import { dot, purgeVectorHashes } from "./vectors.js";
|
|
10
11
|
const position = (sentAt, pk) => `${sentAt}:${pk}`;
|
|
11
12
|
/** A chat's live messages for the rules, oldest first, a page at a time; `next` continues it. */
|
|
12
13
|
export const linkInputs = ({ orm }, chatKey, { after, limit }) => {
|
|
@@ -433,6 +434,53 @@ export const chunkRepliesOf = ({ orm }, accountPk, chunks, limit) => {
|
|
|
433
434
|
}
|
|
434
435
|
return found;
|
|
435
436
|
};
|
|
437
|
+
/**
|
|
438
|
+
* Rarity counts over the conversation's own chunks, not the store: a word every chunk holds says nothing about which
|
|
439
|
+
* one is meant. A word may sit anywhere in a chunk's text, as the shown lines match it.
|
|
440
|
+
*/
|
|
441
|
+
export const bestChunkOf = ({ orm }, accountPk, conversationPk, { model, vectors, stems, over, }) => {
|
|
442
|
+
const chunks = orm.all(sql `SELECT f.external_id AS first, l.external_id AS last, f.sent_at AS fs, f.id AS fi, l.sent_at AS ls, l.id AS li,
|
|
443
|
+
v.vector
|
|
444
|
+
FROM chunks k JOIN chunk_messages r ON r.chunk_id = k.id
|
|
445
|
+
JOIN conversations c ON c.id = k.chunkable_id
|
|
446
|
+
JOIN chats ch ON ch.id = c.chat_id AND ch.account_id = ${accountPk}
|
|
447
|
+
JOIN conversation_state s ON s.chat_id = c.chat_id AND s.current_build = c.build
|
|
448
|
+
JOIN messages f ON f.id = r.first_message_id JOIN messages l ON l.id = r.last_message_id
|
|
449
|
+
LEFT JOIN embeddings v ON v.model = ${model} AND v.content_hash = k.content_hash
|
|
450
|
+
WHERE k.chunkable_type = 'conversation' AND k.chunkable_id = ${conversationPk} ORDER BY k.position`);
|
|
451
|
+
if (chunks.length <= over || !vectors.length)
|
|
452
|
+
return undefined;
|
|
453
|
+
const texts = chunks.map(() => "");
|
|
454
|
+
const rows = orm.all(sql `SELECT m.sent_at AS at, m.id AS pk, m.text FROM conversation_messages cm JOIN messages m ON m.id = cm.message_id
|
|
455
|
+
WHERE cm.conversation_id = ${conversationPk} AND m.deleted_at IS NULL`);
|
|
456
|
+
const after = (at, pk, than, thanPk) => at > than || (at === than && pk >= thanPk);
|
|
457
|
+
for (const { at, pk, text } of rows)
|
|
458
|
+
chunks.forEach(({ fs, fi, ls, li }, index) => {
|
|
459
|
+
if (after(at, pk, fs, fi) && after(ls, li, at, pk))
|
|
460
|
+
texts[index] += ` ${(text ?? "").toLowerCase()}`;
|
|
461
|
+
});
|
|
462
|
+
const weights = new Map();
|
|
463
|
+
for (const { stem, weight } of stems)
|
|
464
|
+
weights.set(stem, (weights.get(stem) ?? 0) + weight);
|
|
465
|
+
const words = texts.map(() => 0);
|
|
466
|
+
for (const [stem, weight] of weights) {
|
|
467
|
+
const holding = texts.flatMap((text, index) => (text.includes(stem) ? [index] : []));
|
|
468
|
+
const rarity = Math.log(chunks.length / holding.length);
|
|
469
|
+
for (const index of holding)
|
|
470
|
+
words[index] = words[index] + weight * rarity;
|
|
471
|
+
}
|
|
472
|
+
const meaning = chunks.map(({ vector }) => vector ? vectors.reduce((sum, query) => sum + dot(query, vector), 0) : Number.NEGATIVE_INFINITY);
|
|
473
|
+
const fused = chunks.map(() => 0);
|
|
474
|
+
for (const scores of [meaning, words])
|
|
475
|
+
scores
|
|
476
|
+
.map((_, index) => index)
|
|
477
|
+
.sort((a, b) => scores[b] - scores[a] || a - b)
|
|
478
|
+
.forEach((index, rank) => {
|
|
479
|
+
fused[index] = fused[index] + 1 / (RRF_K + rank + 1);
|
|
480
|
+
});
|
|
481
|
+
const best = chunks[fused.reduce((top, score, at) => (score > fused[top] ? at : top), 0)];
|
|
482
|
+
return best && { firstMessageId: best.first, lastMessageId: best.last };
|
|
483
|
+
};
|
|
436
484
|
const staleLink = (chatKey) => sql `(${messageLinks.staleAt} IS NOT NULL
|
|
437
485
|
OR EXISTS (SELECT 1 FROM message_revisions r WHERE r.message_id IN (${messageLinks.messageId}, ${messageLinks.parentId})
|
|
438
486
|
AND r.created_at >= ${messageLinks.createdAt})
|
|
@@ -3,10 +3,13 @@ import { pointerPairs } from "./entity-types.js";
|
|
|
3
3
|
const AUTHORS = new Set(["author", "confirmed_by", "decided_by", "proposed_by", "actor", "closed_by"]);
|
|
4
4
|
/** A link is about both ends: one that loses an end means nothing, so it goes. */
|
|
5
5
|
const LINK_ROWS = new Set(["links", "mentions", "task_assignments"]);
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
.
|
|
6
|
+
/** A row's own history: it goes before the row, and never keeps the row alive. */
|
|
7
|
+
const HISTORY = new Set(["note_revisions"]);
|
|
8
|
+
const childrenOf = (database, table) => database
|
|
9
|
+
.prepare(`SELECT m.name AS child, f."from" AS col, coalesce(f."to", 'id') AS parent FROM sqlite_master m
|
|
10
|
+
JOIN pragma_foreign_key_list(m.name) f WHERE m.type = 'table' AND f."table" = ?`)
|
|
11
|
+
.all(table)
|
|
12
|
+
.map((row) => ({ child: String(row.child), col: String(row.col), parent: String(row.parent) }));
|
|
10
13
|
const nullable = (database, table, column) => Number(database.prepare(`SELECT "notnull" AS n FROM pragma_table_info('${table}') WHERE name = ?`).get(column)?.n) ===
|
|
11
14
|
0;
|
|
12
15
|
export const count = (database, sql, ...params) => Number(database.prepare(`SELECT count(*) AS n FROM ${sql}`).get(...params)?.n);
|
|
@@ -32,7 +35,7 @@ export class ErasePlan {
|
|
|
32
35
|
continue;
|
|
33
36
|
const key = `${table}.${pointer}`;
|
|
34
37
|
if (LINK_ROWS.has(table) || !nullable(this.database, table, `${pointer}_id`)) {
|
|
35
|
-
if (!LINK_ROWS.has(table) && (AUTHORS.has(pointer) ||
|
|
38
|
+
if (!LINK_ROWS.has(table) && (AUTHORS.has(pointer) || !this.#history(table, where, params))) {
|
|
36
39
|
this.blocked.push(`${n} ${table} (${pointer})`);
|
|
37
40
|
continue;
|
|
38
41
|
}
|
|
@@ -67,6 +70,25 @@ export class ErasePlan {
|
|
|
67
70
|
for (const step of this.#steps)
|
|
68
71
|
step();
|
|
69
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Whether the rows `where` picks in `table` can go: rows of other tables that hang on them must be their history,
|
|
75
|
+
* which then goes first. Another table's row, such as an invoice under a contract, keeps them.
|
|
76
|
+
*/
|
|
77
|
+
#history(table, where, params) {
|
|
78
|
+
const steps = [];
|
|
79
|
+
for (const { child, col, parent } of childrenOf(this.database, table)) {
|
|
80
|
+
const hanging = `"${col}" IN (SELECT "${parent}" FROM "${table}" WHERE ${where})`;
|
|
81
|
+
const n = count(this.database, `"${child}" WHERE ${hanging}`, ...params);
|
|
82
|
+
if (n === 0)
|
|
83
|
+
continue;
|
|
84
|
+
if (!HISTORY.has(child))
|
|
85
|
+
return false;
|
|
86
|
+
steps.push([`${child}.${col}`, n, `DELETE FROM "${child}" WHERE ${hanging}`]);
|
|
87
|
+
}
|
|
88
|
+
for (const [key, n, sql] of steps)
|
|
89
|
+
this.#add(this.deleted, key, n, sql, params);
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
70
92
|
#add(into, key, n, sql, params) {
|
|
71
93
|
into[key] = (into[key] ?? 0) + n;
|
|
72
94
|
this.#steps.push(() => this.database.prepare(sql).run(...params));
|
|
@@ -15,7 +15,8 @@ export interface OrganizationErasure {
|
|
|
15
15
|
}
|
|
16
16
|
/**
|
|
17
17
|
* Deletes an organization and what memo knows of it alone: the tags, links, aliases and mentions that name it, and
|
|
18
|
-
* which identities it held. A deal, lead, project, account
|
|
18
|
+
* which identities it held, and the owner's notes about it. A deal, lead, project, account or fact that names it stays
|
|
19
|
+
* and loses the name.
|
|
19
20
|
* Refused for one of the owner's own companies, and while an invoice, order, subscription or a row it wrote cannot
|
|
20
21
|
* be without it. `apply: false` answers the same without changing anything.
|
|
21
22
|
*/
|
|
@@ -18,7 +18,8 @@ const organizationOf = (database, ref) => {
|
|
|
18
18
|
};
|
|
19
19
|
/**
|
|
20
20
|
* Deletes an organization and what memo knows of it alone: the tags, links, aliases and mentions that name it, and
|
|
21
|
-
* which identities it held. A deal, lead, project, account
|
|
21
|
+
* which identities it held, and the owner's notes about it. A deal, lead, project, account or fact that names it stays
|
|
22
|
+
* and loses the name.
|
|
22
23
|
* Refused for one of the owner's own companies, and while an invoice, order, subscription or a row it wrote cannot
|
|
23
24
|
* be without it. `apply: false` answers the same without changing anything.
|
|
24
25
|
*/
|
|
@@ -6,6 +6,8 @@ export interface PersonErasure {
|
|
|
6
6
|
name: string | null;
|
|
7
7
|
/** `false`: what `erase` would do, nothing changed. */
|
|
8
8
|
erased: boolean;
|
|
9
|
+
/** People merged into this one earlier: the same person, so they go too. */
|
|
10
|
+
merged: string[];
|
|
9
11
|
/** Identities that go with the person. */
|
|
10
12
|
identities: string[];
|
|
11
13
|
/**
|
|
@@ -23,7 +25,8 @@ export interface PersonErasure {
|
|
|
23
25
|
}
|
|
24
26
|
/**
|
|
25
27
|
* Deletes a person and what memo knows of them alone: their identities, the tags, links, aliases and mentions that
|
|
26
|
-
* name them, their involvements
|
|
28
|
+
* name them, their involvements, the owner's notes about them, and the people merged into them earlier. A fact, a
|
|
29
|
+
* record or a task that names them stays and loses the name. A
|
|
27
30
|
* message, mail or meeting is the source's: its sender stays as an identity with no person. Refused for the owner,
|
|
28
31
|
* and while an invoice, order, subscription or a row they wrote cannot be without them. `apply: false` answers the
|
|
29
32
|
* same without changing anything.
|
|
@@ -33,7 +36,7 @@ export declare const erasePerson: (context: StoreContext, uid: string, by: Decid
|
|
|
33
36
|
export declare const importedPeople: (database: CacheDatabase, accountKey: number) => number[];
|
|
34
37
|
/**
|
|
35
38
|
* After a purge, the people only its records made go too: nothing else names them, and no message, mail or meeting
|
|
36
|
-
* names their identities; their involvements are derived and go with them. One the owner tagged, linked
|
|
37
|
-
*
|
|
39
|
+
* names their identities; their involvements are derived and go with them. One the owner tagged, linked, gave a task
|
|
40
|
+
* to or merged with another person stays: a merge says the owner knows them from somewhere else too.
|
|
38
41
|
*/
|
|
39
42
|
export declare const eraseImportedPeople: (context: StoreContext, people: readonly number[]) => void;
|