@wirecat/cli-core 0.634.0 → 0.635.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 +66 -0
- package/dist/domain/display-names.d.ts +4 -2
- package/dist/domain/display-names.js +5 -2
- package/dist/errors/reasons.js +5 -0
- package/dist/search/groups.d.ts +2 -0
- package/dist/search/groups.js +1 -0
- package/dist/services/account-groups.d.ts +30 -1
- package/dist/services/account-groups.js +27 -0
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/accounts.d.ts +10 -1
- package/dist/store/accounts.js +3 -2
- package/dist/store/chats.d.ts +5 -0
- package/dist/store/chats.js +6 -0
- package/dist/store/exports.d.ts +1 -1
- package/dist/store/identity-links.d.ts +21 -0
- package/dist/store/identity-splits.d.ts +2 -0
- package/dist/store/index.d.ts +1 -1
- package/dist/store/keys.d.ts +1 -1
- package/dist/store/keys.js +1 -1
- package/dist/store/people.d.ts +10 -4
- package/dist/store/sqlite/accounts.d.ts +12 -2
- package/dist/store/sqlite/accounts.js +42 -3
- package/dist/store/sqlite/address-organization.d.ts +18 -0
- package/dist/store/sqlite/address-organization.js +48 -0
- package/dist/store/sqlite/chats.d.ts +3 -1
- package/dist/store/sqlite/chats.js +8 -0
- package/dist/store/sqlite/identity-link-rows.d.ts +5 -1
- package/dist/store/sqlite/identity-link-rows.js +9 -3
- package/dist/store/sqlite/identity-proposals.d.ts +5 -3
- package/dist/store/sqlite/identity-proposals.js +66 -7
- package/dist/store/sqlite/identity-split-proposals.js +3 -1
- package/dist/store/sqlite/mail-findings.js +10 -44
- package/dist/store/sqlite/manifest.js +1 -0
- package/dist/store/sqlite/migrations.generated.js +6 -0
- package/dist/store/sqlite/name-traces.d.ts +5 -2
- package/dist/store/sqlite/name-traces.js +8 -5
- package/dist/store/sqlite/open-store.js +2 -0
- package/dist/store/sqlite/people-list.js +7 -3
- package/dist/store/sqlite/person-doubts.d.ts +4 -1
- package/dist/store/sqlite/person-doubts.js +4 -2
- package/dist/store/sqlite/person-links.d.ts +7 -2
- package/dist/store/sqlite/person-links.js +26 -1
- package/dist/store/sqlite/person-match-scan.js +74 -4
- package/dist/store/sqlite/person-merges.js +3 -7
- package/dist/store/sqlite/task-titles.d.ts +12 -1
- package/dist/store/sqlite/task-titles.js +42 -1
- package/dist/store/sqlite/tasks.js +6 -1
- package/dist/store/types.d.ts +4 -0
- package/package.json +2 -2
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { FREE_MAIL } from "../../mail/score.js";
|
|
3
|
+
import { fold } from "../normalize.js";
|
|
4
|
+
const BY_ADDRESS = "SELECT DISTINCT o.id FROM organizations o JOIN organization_identities oi ON oi.organization_id = o.id " +
|
|
5
|
+
"JOIN identities i ON i.id = oi.identity_id WHERE o.deleted_at IS NULL AND i.provider = 'email' AND ";
|
|
6
|
+
const idsOf = (rows) => rows.map((row) => Number(row.id));
|
|
7
|
+
/** Gives the address to the organization, making its `email` identity when the store has none. */
|
|
8
|
+
export const holdAddress = ({ database, now }, organization, email, { method, author }) => {
|
|
9
|
+
const at = now();
|
|
10
|
+
database
|
|
11
|
+
.prepare("INSERT INTO identities (provider, external_id, created_at, updated_at) VALUES ('email', ?, ?, ?) " +
|
|
12
|
+
"ON CONFLICT (provider, external_id) DO NOTHING")
|
|
13
|
+
.run(email, at, at);
|
|
14
|
+
database
|
|
15
|
+
.prepare("INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
|
|
16
|
+
"SELECT id, ?, ?, ?, ?, ? FROM identities WHERE provider = 'email' AND external_id = ? " +
|
|
17
|
+
"ON CONFLICT (identity_id, organization_id) DO NOTHING")
|
|
18
|
+
.run(organization, method, author, at, at, email);
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The organization an address belongs to: the one holding the address, else the one holding its company domain, else
|
|
22
|
+
* the one of exactly this name; else a new company of this name. The address joins it, so the next lookup finds it.
|
|
23
|
+
* More than one match is refused with `reason`, for the caller to name the one meant.
|
|
24
|
+
*/
|
|
25
|
+
export const organizationOfAddress = (context, { name, email, method, author, reason, }) => {
|
|
26
|
+
const { database, now } = context;
|
|
27
|
+
const domain = email?.split("@")[1];
|
|
28
|
+
let found = email === undefined ? [] : idsOf(database.prepare(`${BY_ADDRESS}lower(i.external_id) = ?`).all(email));
|
|
29
|
+
if (!found.length && domain && !FREE_MAIL.has(domain))
|
|
30
|
+
found = idsOf(database.prepare(`${BY_ADDRESS}substr(lower(i.external_id), -length(?)) = ?`).all(`@${domain}`, `@${domain}`));
|
|
31
|
+
if (!found.length)
|
|
32
|
+
found = database
|
|
33
|
+
.prepare("SELECT id, name FROM organizations WHERE deleted_at IS NULL")
|
|
34
|
+
.all()
|
|
35
|
+
.filter((row) => fold(String(row.name)).trim() === fold(name).trim())
|
|
36
|
+
.map((row) => Number(row.id));
|
|
37
|
+
if (found.length > 1)
|
|
38
|
+
throw new CliError("validation_error", `${found.length} organizations match ${name} (${found.map((id) => `organization:${id}`).join(", ")}); ` +
|
|
39
|
+
"name the one meant as a reference", { reason });
|
|
40
|
+
const at = now();
|
|
41
|
+
const id = found[0] ??
|
|
42
|
+
Number(database
|
|
43
|
+
.prepare("INSERT INTO organizations (kind, name, scope, created_at, updated_at) VALUES ('company', ?, 'work', ?, ?) RETURNING id")
|
|
44
|
+
.get(name, at, at)?.id);
|
|
45
|
+
if (email !== undefined)
|
|
46
|
+
holdAddress(context, id, email, { method, author });
|
|
47
|
+
return id;
|
|
48
|
+
};
|
|
@@ -5,10 +5,12 @@ import type { StoreContext } from "./open.js";
|
|
|
5
5
|
/** The chat's own id, when the store key is a chat of this account. */
|
|
6
6
|
export declare const chatOf: ({ orm }: StoreContext, accountKey: number, chatKey: number) => Id | undefined;
|
|
7
7
|
export declare const findChatPk: ({ orm }: StoreContext, accountKey: number, chatId: Id) => number | undefined;
|
|
8
|
+
/** The owner pins a chat's scope, or with `null` lets it follow its account again; `false` for a chat not stored. */
|
|
9
|
+
export declare const setChatScope: (context: StoreContext, accountKey: number, chatId: Id, scope: string | null) => boolean;
|
|
8
10
|
/** A chat known only from its messages, until the chat list names it. */
|
|
9
11
|
export declare const chatPkFor: (context: StoreContext, accountKey: number, chatId: Id) => number;
|
|
10
12
|
/** The store write a `chat_revisions` row names; a writer that sets none is recorded as NULL. */
|
|
11
|
-
export type ChatRevisionSource = "chats" | "delta" | "left" | "rejoin" | "rekey" | "merge" | "send" | "details";
|
|
13
|
+
export type ChatRevisionSource = "chats" | "delta" | "left" | "rejoin" | "rekey" | "merge" | "send" | "details" | "owner";
|
|
12
14
|
/**
|
|
13
15
|
* Runs `body` with `source` as what the `chat_revisions` trigger records, inside the caller's transaction. The row is
|
|
14
16
|
* gone again before the commit, so an older build's write in a later transaction records no source rather than this
|
|
@@ -20,6 +20,14 @@ export const findChatPk = ({ orm }, accountKey, chatId) => orm
|
|
|
20
20
|
.from(chats)
|
|
21
21
|
.where(and(eq(chats.accountId, accountKey), eq(chats.externalId, chatId)))
|
|
22
22
|
.get()?.pk;
|
|
23
|
+
/** The owner pins a chat's scope, or with `null` lets it follow its account again; `false` for a chat not stored. */
|
|
24
|
+
export const setChatScope = (context, accountKey, chatId, scope) => {
|
|
25
|
+
const pk = findChatPk(context, accountKey, chatId);
|
|
26
|
+
if (pk === undefined)
|
|
27
|
+
return false;
|
|
28
|
+
revisedBy(context, "owner", () => context.database.prepare("UPDATE chats SET scope = ?, updated_at = ? WHERE id = ?").run(scope, context.now(), pk));
|
|
29
|
+
return true;
|
|
30
|
+
};
|
|
23
31
|
/** A chat known only from its messages, until the chat list names it. */
|
|
24
32
|
export const chatPkFor = (context, accountKey, chatId) => findChatPk(context, accountKey, chatId) ??
|
|
25
33
|
Number(context.orm
|
|
@@ -14,10 +14,14 @@ export declare const pkOf: (database: CacheDatabase, ref: string) => number | un
|
|
|
14
14
|
export declare const personOf: (database: CacheDatabase, identity: number | undefined) => number | undefined;
|
|
15
15
|
/** The people a proposal's identities are on now; merges since may have moved either side. */
|
|
16
16
|
export declare const currentPairOf: (database: CacheDatabase, payload: IdentityLinkPayload) => [number, number] | undefined;
|
|
17
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* The proposals that still say something: waiting for the owner, or turned down by them. A `page` is newest first, or
|
|
19
|
+
* by score with `order: "score"`; without a page, oldest first.
|
|
20
|
+
*/
|
|
18
21
|
export declare const linkRows: (database: CacheDatabase, statuses?: readonly string[], page?: {
|
|
19
22
|
limit: number;
|
|
20
23
|
offset: number;
|
|
24
|
+
order?: "newest" | "score";
|
|
21
25
|
}) => LinkRow[];
|
|
22
26
|
/**
|
|
23
27
|
* What a proposal rests on: its signal and the two identities it names, in either order. The owner's rejection
|
|
@@ -23,10 +23,16 @@ export const currentPairOf = (database, payload) => {
|
|
|
23
23
|
: personOf(database, pkOf(database, payload.with));
|
|
24
24
|
return from === undefined || to === undefined ? undefined : [from, to];
|
|
25
25
|
};
|
|
26
|
-
|
|
26
|
+
const BY_SCORE = "json_extract(payload, '$.score') IS NULL, json_extract(payload, '$.score') DESC, id DESC";
|
|
27
|
+
/**
|
|
28
|
+
* The proposals that still say something: waiting for the owner, or turned down by them. A `page` is newest first, or
|
|
29
|
+
* by score with `order: "score"`; without a page, oldest first.
|
|
30
|
+
*/
|
|
27
31
|
export const linkRows = (database, statuses = ["proposed", "rejected"], page) => database
|
|
28
|
-
.prepare("SELECT id, status, payload FROM proposed_actions WHERE kind = ? " +
|
|
29
|
-
|
|
32
|
+
.prepare("SELECT id, status, payload FROM proposed_actions WHERE kind = ? AND status IN (SELECT value FROM json_each(?)) " +
|
|
33
|
+
(page === undefined
|
|
34
|
+
? "ORDER BY id"
|
|
35
|
+
: `ORDER BY ${page.order === "score" ? BY_SCORE : "id DESC"} LIMIT ? OFFSET ?`))
|
|
30
36
|
.all(IDENTITY_LINK_KIND, JSON.stringify(statuses), ...(page === undefined ? [] : [page.limit, page.offset]))
|
|
31
37
|
.map((row) => {
|
|
32
38
|
const payload = JSON.parse(String(row.payload));
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type IdentityLinkDecision, type IdentityLinkFilter, type IdentityLinkInput, type IdentityLinkPayload, type IdentityLinkRow, type IdentityLinkSignal } from "../identity-links.js";
|
|
1
|
+
import { type IdentityLinkDecision, type IdentityLinkFilter, type IdentityLinkInput, type IdentityLinkPayload, type IdentityLinkRow, type IdentityLinkSignal, type SharedMailbox } from "../identity-links.js";
|
|
2
2
|
import type { IdentityRef, LinkOptions } from "../types.js";
|
|
3
3
|
import { type LinkIndex } from "./identity-link-rows.js";
|
|
4
4
|
import type { Author } from "./memories.js";
|
|
@@ -17,6 +17,8 @@ export interface Opening {
|
|
|
17
17
|
score?: number | undefined;
|
|
18
18
|
evidence?: string[] | undefined;
|
|
19
19
|
candidates?: number[] | undefined;
|
|
20
|
+
shared?: SharedMailbox | undefined;
|
|
21
|
+
mailbox?: string | undefined;
|
|
20
22
|
}
|
|
21
23
|
export type Opened = {
|
|
22
24
|
outcome: "proposed" | "open";
|
|
@@ -46,8 +48,8 @@ export declare const linkOrPropose: (context: StoreContext, identity: number, ta
|
|
|
46
48
|
* proposes the pair again.
|
|
47
49
|
*/
|
|
48
50
|
export declare const decideIdentityLink: (context: StoreContext, id: string, decision: IdentityLinkDecision) => ProposedAction;
|
|
49
|
-
/** The `identity_link` proposals, newest first, each naming its people as they are now; a page and whether more follow. */
|
|
50
|
-
export declare const identityLinkRows: (context: StoreContext, { person, status, limit, offset }: IdentityLinkFilter) => {
|
|
51
|
+
/** The `identity_link` proposals, newest first or by score, each naming its people as they are now; a page and whether more follow. */
|
|
52
|
+
export declare const identityLinkRows: (context: StoreContext, { person, status, order, limit, offset }: IdentityLinkFilter) => {
|
|
51
53
|
items: IdentityLinkRow[];
|
|
52
54
|
hasMore: boolean;
|
|
53
55
|
};
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { FREE_MAIL } from "../../mail/score.js";
|
|
2
3
|
import { assertMayDecide, deciderAuthor } from "../decisions.js";
|
|
3
4
|
import { IDENTITY_LINK_KIND, } from "../identity-links.js";
|
|
5
|
+
import { holdAddress, organizationOfAddress } from "./address-organization.js";
|
|
4
6
|
import { ensurePerson } from "./identities.js";
|
|
5
|
-
import { evidenceKeyOf, linkIndex, linkRows, settleLinks, sidesOf } from "./identity-link-rows.js";
|
|
7
|
+
import { evidenceKeyOf, linkIndex, linkRows, settleLinks, sidesOf, } from "./identity-link-rows.js";
|
|
6
8
|
import { currentPerson } from "./merged-persons.js";
|
|
7
9
|
import { linkIdentityToPerson, mergePerson, move, recordOf, required, survivorOf } from "./person-links.js";
|
|
8
10
|
import { resolvePersonLinks } from "./person-resolution.js";
|
|
@@ -56,6 +58,8 @@ export const openIdentityLink = (context, opening, index) => write(context.datab
|
|
|
56
58
|
score: opening.score ?? null,
|
|
57
59
|
...(opening.candidates && opening.candidates.length > 2 ? { candidates: opening.candidates.map(String) } : {}),
|
|
58
60
|
evidence: opening.evidence ?? [],
|
|
61
|
+
...(opening.shared === undefined ? {} : { shared: opening.shared }),
|
|
62
|
+
...(opening.mailbox === undefined ? {} : { mailbox: opening.mailbox }),
|
|
59
63
|
};
|
|
60
64
|
const action = operations.propose({
|
|
61
65
|
kind: IDENTITY_LINK_KIND,
|
|
@@ -145,6 +149,53 @@ const settleMentions = ({ database, now }, payload, to) => {
|
|
|
145
149
|
"AND target_id = ?")
|
|
146
150
|
.run(to, now(), Number(identity.id));
|
|
147
151
|
};
|
|
152
|
+
const organizationExists = ({ database }, id) => Number.isSafeInteger(id) &&
|
|
153
|
+
database.prepare("SELECT 1 FROM organizations WHERE id = ? AND deleted_at IS NULL").get(id) !== undefined;
|
|
154
|
+
/**
|
|
155
|
+
* NEED-2528: the shared mailbox is a company's, not one of the two people. The address goes to the organization and
|
|
156
|
+
* the proposal is turned down, so the pair is not proposed again on it (the rejected evidence), and nobody is joined.
|
|
157
|
+
*/
|
|
158
|
+
const toCompany = (context, proposal, company, author, noted) => {
|
|
159
|
+
const payload = proposal.payload;
|
|
160
|
+
if (proposal.status !== "proposed")
|
|
161
|
+
throw new CliError("validation_error", `${proposal.id} is already ${proposal.status}`, {
|
|
162
|
+
reason: "proposal.wrong-state",
|
|
163
|
+
});
|
|
164
|
+
const address = payload.mailbox;
|
|
165
|
+
if (payload.shared === undefined || address === undefined)
|
|
166
|
+
throw new CliError("validation_error", `${proposal.id} is not about a shared mailbox; confirm or reject it`, {
|
|
167
|
+
reason: "identity.not-shared",
|
|
168
|
+
});
|
|
169
|
+
const name = company.name?.trim() || undefined;
|
|
170
|
+
const domain = address.split("@")[1] ?? "";
|
|
171
|
+
let organization;
|
|
172
|
+
if (company.organization !== undefined) {
|
|
173
|
+
if (!organizationExists(context, company.organization))
|
|
174
|
+
throw new CliError("not_found", `no organization:${company.organization}`, { reason: "organization.not-found" });
|
|
175
|
+
organization = company.organization;
|
|
176
|
+
holdAddress(context, organization, address, { method: CONFIRMED, author: "owner" });
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
if (name === undefined && FREE_MAIL.has(domain))
|
|
180
|
+
throw new CliError("validation_error", `${address} is a free mailbox; name the company or its organization`, {
|
|
181
|
+
reason: "organization.unnamed",
|
|
182
|
+
});
|
|
183
|
+
organization = organizationOfAddress(context, {
|
|
184
|
+
name: name ?? domain,
|
|
185
|
+
email: address,
|
|
186
|
+
method: CONFIRMED,
|
|
187
|
+
author: "owner",
|
|
188
|
+
reason: "organization.ambiguous",
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const rejected = proposalOperationsOver(context).reject(proposal.id, author, {
|
|
192
|
+
dismissed: true,
|
|
193
|
+
organization: `organization:${organization}`,
|
|
194
|
+
...noted,
|
|
195
|
+
});
|
|
196
|
+
settleMentions(context, payload, "found");
|
|
197
|
+
return rejected;
|
|
198
|
+
};
|
|
148
199
|
/**
|
|
149
200
|
* Decides an `identity_link`, the owner's alone. Confirm links the two people as the owner's link, refused with
|
|
150
201
|
* `identity.stale` when either person changed since it was proposed; reject keeps them apart, and only new evidence
|
|
@@ -159,6 +210,11 @@ export const decideIdentityLink = (context, id, decision) => write(context.datab
|
|
|
159
210
|
const author = deciderAuthor(decision.by);
|
|
160
211
|
const reason = decision.reason?.trim() || undefined;
|
|
161
212
|
const noted = reason === undefined ? {} : { reason };
|
|
213
|
+
if (decision.company !== undefined) {
|
|
214
|
+
if (decision.confirm)
|
|
215
|
+
throw new CliError("validation_error", "a company's mailbox keeps the two people apart; it is not a confirm");
|
|
216
|
+
return toCompany(context, proposal, decision.company, author, noted);
|
|
217
|
+
}
|
|
162
218
|
if (!decision.confirm) {
|
|
163
219
|
const rejected = operations.reject(id, author, { dismissed: true, ...noted });
|
|
164
220
|
settleMentions(context, proposal.payload, "found");
|
|
@@ -200,8 +256,10 @@ const SHOWN = {
|
|
|
200
256
|
executed: "confirmed",
|
|
201
257
|
failed: "confirmed",
|
|
202
258
|
};
|
|
203
|
-
/**
|
|
204
|
-
|
|
259
|
+
/** Newest first in, highest score first out, proposals without a score last; a stable sort keeps the dates' order. */
|
|
260
|
+
const byOrder = (rows, order) => order !== "score" ? rows : rows.sort((a, b) => (b.payload.score ?? -1) - (a.payload.score ?? -1));
|
|
261
|
+
/** The `identity_link` proposals, newest first or by score, each naming its people as they are now; a page and whether more follow. */
|
|
262
|
+
export const identityLinkRows = (context, { person, status = "proposed", order = "newest", limit, offset }) => {
|
|
205
263
|
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
|
|
206
264
|
throw new CliError("validation_error", "a list of link proposals takes 1–500 items");
|
|
207
265
|
const asked = person === undefined ? undefined : currentPerson(context.database, Number(person));
|
|
@@ -209,11 +267,10 @@ export const identityLinkRows = (context, { person, status = "proposed", limit,
|
|
|
209
267
|
const statuses = Object.keys(SHOWN).filter((one) => status === "all" || SHOWN[one] === status);
|
|
210
268
|
// Whose a proposal is now depends on merges since, so only a list for one person reads every proposal.
|
|
211
269
|
const rows = asked === undefined
|
|
212
|
-
? linkRows(context.database, statuses, { limit: limit + 1, offset })
|
|
213
|
-
: linkRows(context.database, statuses)
|
|
270
|
+
? linkRows(context.database, statuses, { limit: limit + 1, offset, order })
|
|
271
|
+
: byOrder(linkRows(context.database, statuses)
|
|
214
272
|
.filter((row) => row.pair?.includes(asked) ?? false)
|
|
215
|
-
.reverse()
|
|
216
|
-
.slice(offset, offset + limit + 1);
|
|
273
|
+
.reverse(), order).slice(offset, offset + limit + 1);
|
|
217
274
|
const items = rows.slice(0, limit).map((row) => {
|
|
218
275
|
const action = operations.get(row.id);
|
|
219
276
|
const payload = row.payload;
|
|
@@ -227,6 +284,8 @@ export const identityLinkRows = (context, { person, status = "proposed", limit,
|
|
|
227
284
|
joins: payload.joins,
|
|
228
285
|
signal: payload.signal,
|
|
229
286
|
score: payload.score,
|
|
287
|
+
shared: payload.shared ?? null,
|
|
288
|
+
mailbox: payload.mailbox ?? null,
|
|
230
289
|
candidates: (payload.candidates ?? []).map((uid) => `person:${uid}`),
|
|
231
290
|
reason: action.reason,
|
|
232
291
|
evidence: payload.evidence,
|
|
@@ -4,7 +4,7 @@ import { IDENTITY_SPLIT_KIND, } from "../identity-splits.js";
|
|
|
4
4
|
import { personOf, pkOf, sideOf } from "./identity-link-rows.js";
|
|
5
5
|
import { parseIdentityRef } from "./identity-proposals.js";
|
|
6
6
|
import { currentPerson } from "./merged-persons.js";
|
|
7
|
-
import { recordOf, required, unlinkIdentity } from "./person-links.js";
|
|
7
|
+
import { heldBy, recordOf, required, unlinkIdentity } from "./person-links.js";
|
|
8
8
|
import { mergeId, merges, parseMergeId, split, undoMerge } from "./person-merges.js";
|
|
9
9
|
import { proposalOperationsOver, proposerOfAction } from "./proposed-actions.js";
|
|
10
10
|
import { write } from "./transaction.js";
|
|
@@ -25,6 +25,8 @@ const planOf = (context, input) => {
|
|
|
25
25
|
const chosen = [...new Map(input.identities.map((ref) => [refOf(ref), ref])).values()];
|
|
26
26
|
if (chosen.length === 0)
|
|
27
27
|
throw new CliError("validation_error", "name at least one identity to split off");
|
|
28
|
+
if (input.from !== undefined)
|
|
29
|
+
heldBy(context, input.from, chosen);
|
|
28
30
|
const persons = new Set(chosen.map((ref) => required(context, ref).personPk));
|
|
29
31
|
if (persons.size > 1)
|
|
30
32
|
throw new CliError("validation_error", "the identities that leave are all of one person", {
|
|
@@ -2,11 +2,11 @@ import { CliError } from "@wirecat/cli-base";
|
|
|
2
2
|
import { contextEvidenceFingerprint } from "../../context/evidence.js";
|
|
3
3
|
import { parseLocator } from "../../domain/locator.js";
|
|
4
4
|
import { checkMailFindings, MAIL_FINDINGS_PER_SENDER, mailFindingFingerprint, mailFindingProblem, validateMailFindings, } from "../../mail/findings.js";
|
|
5
|
-
import { FREE_MAIL } from "../../mail/score.js";
|
|
6
5
|
import { findingHash } from "../../meetings/index.js";
|
|
7
6
|
import { assertMayDecide } from "../decisions.js";
|
|
8
7
|
import { MAIL_FINDINGS_KIND } from "../mail-findings.js";
|
|
9
8
|
import { fold } from "../normalize.js";
|
|
9
|
+
import { organizationOfAddress } from "./address-organization.js";
|
|
10
10
|
import { financeOperationsOver } from "./finance.js";
|
|
11
11
|
import { findingsAgent, findingsCoreOver } from "./findings-core.js";
|
|
12
12
|
import { authorActor, linkEvidence, memoriesStoreOver } from "./memories.js";
|
|
@@ -141,51 +141,17 @@ export const mailFindingsStoreOver = (context) => {
|
|
|
141
141
|
}
|
|
142
142
|
return read;
|
|
143
143
|
};
|
|
144
|
-
const organizationsOf = (sql, ...params) => [
|
|
145
|
-
...new Set(database
|
|
146
|
-
.prepare(sql)
|
|
147
|
-
.all(...params)
|
|
148
|
-
.map((row) => Number(row.id))),
|
|
149
|
-
];
|
|
150
|
-
const BY_ADDRESS = "SELECT o.id FROM organizations o JOIN organization_identities oi ON oi.organization_id = o.id " +
|
|
151
|
-
"JOIN identities i ON i.id = oi.identity_id WHERE o.deleted_at IS NULL AND i.provider = 'email' AND ";
|
|
152
144
|
/**
|
|
153
|
-
* The organization a finding names but does not reference
|
|
154
|
-
*
|
|
155
|
-
* next mail from it finds it. Only the owner's accept runs this for real; staging runs it and rolls it back.
|
|
145
|
+
* The organization a finding names but does not reference, found or made by `organizationOfAddress`. Only the
|
|
146
|
+
* owner's accept runs this for real; staging runs it and rolls it back.
|
|
156
147
|
*/
|
|
157
|
-
const organizationNamed = (name, email) => {
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
.prepare("SELECT id, name FROM organizations WHERE deleted_at IS NULL")
|
|
165
|
-
.all()
|
|
166
|
-
.filter((row) => fold(String(row.name)).trim() === fold(name).trim())
|
|
167
|
-
.map((row) => Number(row.id));
|
|
168
|
-
if (found.length > 1)
|
|
169
|
-
return invalid(`${found.length} organizations match ${name} (${found.map((id) => `organization:${id}`).join(", ")}); ` +
|
|
170
|
-
"name the one meant as a reference", "finance.party");
|
|
171
|
-
const at = now();
|
|
172
|
-
const id = found[0] ??
|
|
173
|
-
Number(database
|
|
174
|
-
.prepare("INSERT INTO organizations (kind, name, scope, created_at, updated_at) VALUES ('company', ?, 'work', ?, ?) RETURNING id")
|
|
175
|
-
.get(name, at, at)?.id);
|
|
176
|
-
if (email !== undefined) {
|
|
177
|
-
database
|
|
178
|
-
.prepare("INSERT INTO identities (provider, external_id, created_at, updated_at) VALUES ('email', ?, ?, ?) " +
|
|
179
|
-
"ON CONFLICT (provider, external_id) DO NOTHING")
|
|
180
|
-
.run(email, at, at);
|
|
181
|
-
database
|
|
182
|
-
.prepare("INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
|
|
183
|
-
"SELECT id, ?, 'mail-finding', 'owner', ?, ? FROM identities WHERE provider = 'email' AND external_id = ? " +
|
|
184
|
-
"ON CONFLICT (identity_id, organization_id) DO NOTHING")
|
|
185
|
-
.run(id, at, at, email);
|
|
186
|
-
}
|
|
187
|
-
return `organization:${id}`;
|
|
188
|
-
};
|
|
148
|
+
const organizationNamed = (name, email) => `organization:${organizationOfAddress(context, {
|
|
149
|
+
name,
|
|
150
|
+
...(email === undefined ? {} : { email }),
|
|
151
|
+
method: "mail-finding",
|
|
152
|
+
author: "owner",
|
|
153
|
+
reason: "finance.party",
|
|
154
|
+
})}`;
|
|
189
155
|
const partyOf = (reference, name, email) => reference ?? (name === undefined ? undefined : organizationNamed(name, email));
|
|
190
156
|
/** The invoice, payment or order an accepted finding records: the owner's own entry, citing the mail it came from. */
|
|
191
157
|
const entry = (finding, evidence) => {
|
|
@@ -129,6 +129,7 @@ export const MANIFEST = [
|
|
|
129
129
|
{ name: "20261110005200_version-62-person-kinds-triggers", version: 62, minCompatible: 56 },
|
|
130
130
|
{ name: "20261110020704_version-63-people-ties-messages-crm", version: 63, minCompatible: 56 },
|
|
131
131
|
{ name: "20261110084658_version-64-deal-link-triggers", version: 64, minCompatible: 56 },
|
|
132
|
+
{ name: "20261110182602_version-65-found-task-titles", version: 65, minCompatible: 56 },
|
|
132
133
|
];
|
|
133
134
|
export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
|
|
134
135
|
const migrations = [];
|
|
@@ -1321,5 +1321,11 @@ export const GENERATED = [
|
|
|
1321
1321
|
"DROP TRIGGER IF EXISTS person_kind_deal_owner_person_au;",
|
|
1322
1322
|
"CREATE TRIGGER person_kind_deal_owner_person_au AFTER UPDATE OF owner ON persons\nWHEN OLD.owner IS NOT NEW.owner BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links o JOIN links d ON d.from_type = o.from_type AND d.from_id = o.from_id AND d.kind = 'related-to' AND +d.to_type = 'person' WHERE o.to_type = 'person' AND o.role = 'owner' AND o.from_type IN ('deal', 'lead') AND o.to_id IN (SELECT NEW.id UNION SELECT e.from_person_id FROM identity_link_events e JOIN identity_links l ON l.identity_id = e.identity_id WHERE l.person_id = NEW.id));\nEND;"
|
|
1323
1323
|
]
|
|
1324
|
+
},
|
|
1325
|
+
{
|
|
1326
|
+
"name": "20261110182602_version-65-found-task-titles",
|
|
1327
|
+
"statements": [
|
|
1328
|
+
"-- A found task's title was its message's first line only while reading, so it went blank when the message was deleted.\n-- The line comes from displayTitleOf in code, so the next writable open stores it for the tasks still titled\n-- `<kind> — <source>` and deletes this key (fillFoundTaskTitles). A store with no such task gets no key.\nINSERT OR REPLACE INTO store_settings (key, value, at)\nSELECT 'found_task_titles_to_fill', '1', unixepoch() * 1000 WHERE EXISTS (\n SELECT 1 FROM tasks WHERE package_id IS NOT NULL AND deleted_at IS NULL AND source_locator LIKE 'msg:%'\n AND title = type || ' — ' || source_locator\n);"
|
|
1329
|
+
]
|
|
1324
1330
|
}
|
|
1325
1331
|
];
|
|
@@ -18,5 +18,8 @@ export interface SharedTrace {
|
|
|
18
18
|
evidence: string[];
|
|
19
19
|
reason: string;
|
|
20
20
|
}
|
|
21
|
-
/**
|
|
22
|
-
|
|
21
|
+
/**
|
|
22
|
+
* The traces two people share, strongest first: each phone, each address, a chat, a company's domain. `except` is an
|
|
23
|
+
* address left out, with its domain, when it is the very thing being weighed.
|
|
24
|
+
*/
|
|
25
|
+
export declare function sharedTraces(database: CacheDatabase, a: number, b: number, name: string, except?: string): Generator<SharedTrace>;
|
|
@@ -33,7 +33,7 @@ const companyDomain = (address) => {
|
|
|
33
33
|
const domain = address.split("@")[1];
|
|
34
34
|
return domain === undefined || FREE_MAIL.has(domain) || isRoleAddress(address) ? undefined : domain;
|
|
35
35
|
};
|
|
36
|
-
const tracesOf = (database, person) => {
|
|
36
|
+
const tracesOf = (database, person, except) => {
|
|
37
37
|
const traces = { phones: [], emails: [], domains: [] };
|
|
38
38
|
for (const row of database
|
|
39
39
|
.prepare("SELECT i.id, i.provider, i.external_id, i.phone, i.email FROM identity_links l " +
|
|
@@ -46,7 +46,7 @@ const tracesOf = (database, person) => {
|
|
|
46
46
|
if (stored !== undefined)
|
|
47
47
|
traces.phones.push({ identity, value: stored });
|
|
48
48
|
for (const address of [addressOf(row.email), provider === "email" ? addressOf(row.external_id) : undefined]) {
|
|
49
|
-
if (address === undefined)
|
|
49
|
+
if (address === undefined || address === except)
|
|
50
50
|
continue;
|
|
51
51
|
traces.emails.push({ identity, value: address });
|
|
52
52
|
const domain = companyDomain(address);
|
|
@@ -73,9 +73,12 @@ const commonChat = (database, a, b) => database
|
|
|
73
73
|
"JOIN identity_links l2 ON l2.identity_id = m2.identity_id " +
|
|
74
74
|
"WHERE l1.person_id = ? AND l2.person_id = ? ORDER BY m1.chat_id LIMIT 1")
|
|
75
75
|
.get(a, b);
|
|
76
|
-
/**
|
|
77
|
-
|
|
78
|
-
|
|
76
|
+
/**
|
|
77
|
+
* The traces two people share, strongest first: each phone, each address, a chat, a company's domain. `except` is an
|
|
78
|
+
* address left out, with its domain, when it is the very thing being weighed.
|
|
79
|
+
*/
|
|
80
|
+
export function* sharedTraces(database, a, b, name, except) {
|
|
81
|
+
const [one, other] = [tracesOf(database, a, except), tracesOf(database, b, except)];
|
|
79
82
|
for (const phone of common(one.phones, other.phones))
|
|
80
83
|
yield {
|
|
81
84
|
identity: phone[0].identity,
|
|
@@ -22,6 +22,7 @@ import { pruneRollbackCopies } from "./rollback-copy.js";
|
|
|
22
22
|
import { stemsState } from "./stems.js";
|
|
23
23
|
import { fillStems, followDefaultStemmers } from "./stems-fill.js";
|
|
24
24
|
import { moveSuggestedLinks } from "./suggested-links.js";
|
|
25
|
+
import { fillFoundTaskTitles } from "./task-titles.js";
|
|
25
26
|
import { purgeTestAccounts } from "./test-accounts.js";
|
|
26
27
|
import { fillVectorIndexes } from "./vector-index.js";
|
|
27
28
|
export const BACKFILL_ON_OPEN = 5_000;
|
|
@@ -107,6 +108,7 @@ export const openStoreContext = async (options = {}) => {
|
|
|
107
108
|
movePaymentFacts({ ...opened, now, decisions });
|
|
108
109
|
purgeTestAccounts({ ...opened, now, decisions }, warn);
|
|
109
110
|
maskStoredBotTokens({ ...opened, now, decisions });
|
|
111
|
+
fillFoundTaskTitles(database, warn);
|
|
110
112
|
const pending = pendingNormalization(database);
|
|
111
113
|
if (pending > 0 && pending <= BACKFILL_ON_OPEN)
|
|
112
114
|
backfillNormalized(database);
|
|
@@ -43,7 +43,7 @@ const MAIL_COUNTS = (scope) => "SELECT l.person_id AS person, count(*) AS n, sum
|
|
|
43
43
|
"JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk')) AS bulk " +
|
|
44
44
|
"FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
|
|
45
45
|
`WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND ${IN_SCOPE(scope, "l.person_id")} GROUP BY 1`;
|
|
46
|
-
const IDENTITIES = (scope) => "SELECT l.person_id AS person, i.id, i.provider, i.external_id, i.username, i.phone, i.email, i.bot " +
|
|
46
|
+
const IDENTITIES = (scope) => "SELECT l.person_id AS person, i.id, i.provider, i.external_id, i.name, i.username, i.phone, i.email, i.bot " +
|
|
47
47
|
`FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE ${IN_SCOPE(scope, "l.person_id")} ORDER BY i.id`;
|
|
48
48
|
/** Few identities have these; one pass each beats a lookup per identity. */
|
|
49
49
|
const NEVER_REPLIED = "SELECT identity_id FROM account_identities WHERE mail_signals LIKE '%bulk_never_replied%'";
|
|
@@ -67,6 +67,7 @@ const factsOf = (database, scope) => {
|
|
|
67
67
|
for (const row of database.prepare(IDENTITIES(scope)).all(...scopeParams(scope))) {
|
|
68
68
|
const person = Number(row.person);
|
|
69
69
|
const one = facts.get(person) ?? {
|
|
70
|
+
name: null,
|
|
70
71
|
username: null,
|
|
71
72
|
usernameSource: null,
|
|
72
73
|
phone: null,
|
|
@@ -77,6 +78,9 @@ const factsOf = (database, scope) => {
|
|
|
77
78
|
organization: false,
|
|
78
79
|
};
|
|
79
80
|
const email = text(row.email) ?? (row.provider === "email" ? text(row.external_id) : null);
|
|
81
|
+
const named = displayName(text(row.name));
|
|
82
|
+
if (one.name === null && isReadable(named) && !named?.startsWith("@"))
|
|
83
|
+
one.name = named;
|
|
80
84
|
if (one.username === null && text(row.username) !== null) {
|
|
81
85
|
one.username = text(row.username);
|
|
82
86
|
one.usernameSource = String(row.provider);
|
|
@@ -143,7 +147,7 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
|
|
|
143
147
|
return people.map(({ id, name, owner }) => {
|
|
144
148
|
const own = facts.get(id);
|
|
145
149
|
const contact = { username: own?.username ?? null, phone: own?.phone ?? null, email: own?.email ?? null };
|
|
146
|
-
const shown = displayName(name, contact);
|
|
150
|
+
const shown = displayName(name, { ...contact, name: own?.name ?? null });
|
|
147
151
|
const ties = reasons.get(id) ?? [];
|
|
148
152
|
const { kind, signals } = kindOf(shown, own, ties, mail.get(id));
|
|
149
153
|
return {
|
|
@@ -179,7 +183,7 @@ const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOr
|
|
|
179
183
|
* Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
|
|
180
184
|
* every stored one is worked out again on the next list.
|
|
181
185
|
*/
|
|
182
|
-
const KIND_RULES = "
|
|
186
|
+
const KIND_RULES = "3";
|
|
183
187
|
const RULES_KEY = "people.kind_rules";
|
|
184
188
|
/** Past this many people to work out, one pass over everyone beats a lookup per person. */
|
|
185
189
|
const WHOLE_PASS = 20_000;
|
|
@@ -30,9 +30,12 @@ export interface PersonDoubt {
|
|
|
30
30
|
export type DoubtMove = {
|
|
31
31
|
op: "unmerge";
|
|
32
32
|
merge: string;
|
|
33
|
-
}
|
|
33
|
+
}
|
|
34
|
+
/** `from` is the person they leave, `person:<uid>`. */
|
|
35
|
+
| {
|
|
34
36
|
op: "unlink";
|
|
35
37
|
identities: string[];
|
|
38
|
+
from: string;
|
|
36
39
|
};
|
|
37
40
|
export interface PersonDoubts {
|
|
38
41
|
items: PersonDoubt[];
|
|
@@ -186,10 +186,12 @@ const movesOf = (context, found) => {
|
|
|
186
186
|
}
|
|
187
187
|
const rest = found.held.filter(({ ref }) => !unmerged.has(ref));
|
|
188
188
|
for (const group of nameGroups(rest))
|
|
189
|
-
moves.push({ op: "unlink", identities: group.map(({ ref }) => ref) });
|
|
189
|
+
moves.push({ op: "unlink", identities: group.map(({ ref }) => ref), from: `person:${found.person}` });
|
|
190
190
|
return moves;
|
|
191
191
|
};
|
|
192
|
-
const commandOf = (move) => move.op === "unmerge"
|
|
192
|
+
const commandOf = (move) => move.op === "unmerge"
|
|
193
|
+
? `people unmerge ${move.merge}`
|
|
194
|
+
: `people unlink ${move.identities.map(shellWord).join(" ")} --from ${move.from}`;
|
|
193
195
|
/** A ref as one shell word: an id may hold a space or a quote, and the fix is pasted into a terminal. */
|
|
194
196
|
const shellWord = (ref) => (/^[\w@.:+/=-]+$/u.test(ref) ? ref : `'${ref.replaceAll("'", "'\\''")}'`);
|
|
195
197
|
const shown = (context, found) => {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Id, Page } from "../../domain/models.js";
|
|
2
|
-
import type { IdentityRef, LinkOptions, PersonRecord, StoredHit } from "../types.js";
|
|
2
|
+
import type { IdentityRef, LinkOptions, PersonRecord, StoredHit, UnlinkOptions } from "../types.js";
|
|
3
3
|
import type { StoreContext } from "./open.js";
|
|
4
4
|
export declare const required: (context: StoreContext, ref: IdentityRef) => {
|
|
5
5
|
pk: number;
|
|
@@ -55,8 +55,13 @@ export declare const joinByAddress: (context: StoreContext, ref: IdentityRef, ad
|
|
|
55
55
|
* owner merged with a partner's CRM contact kept the partner's name after the split (BUG-677).
|
|
56
56
|
*/
|
|
57
57
|
export declare const renameAfterLeaving: (context: StoreContext, person: number, left: readonly number[]) => void;
|
|
58
|
+
/**
|
|
59
|
+
* Refuses identities that sit on anyone but `from` (a uid, or `person:<uid>` as doubts and refusals give it), so a
|
|
60
|
+
* caller that guessed the person never takes them off someone else. The refusal names who holds them.
|
|
61
|
+
*/
|
|
62
|
+
export declare const heldBy: (context: StoreContext, from: string, refs: readonly IdentityRef[]) => void;
|
|
58
63
|
/** Gives the identity a person of its own again; the ones left keep theirs. */
|
|
59
|
-
export declare const unlinkIdentity: (context: StoreContext, ref: IdentityRef, options:
|
|
64
|
+
export declare const unlinkIdentity: (context: StoreContext, ref: IdentityRef, options: UnlinkOptions) => PersonRecord;
|
|
60
65
|
/** Messages that name the person: by id where the messenger said so, or by `@username` in the text. */
|
|
61
66
|
export declare const mentioning: (context: StoreContext, accountKey: number, { id, username }: {
|
|
62
67
|
id: Id;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
2
|
import { isEmailAddress, isRoleAddress } from "../../domain/addresses.js";
|
|
3
|
+
import { displayName } from "../../domain/display-names.js";
|
|
3
4
|
import { and, eq, inArray, isNull, sql } from "./drizzle/core.js";
|
|
4
5
|
import { identityOf } from "./identities.js";
|
|
5
6
|
import { rejectedEvidence, settleLinks } from "./identity-link-rows.js";
|
|
@@ -262,8 +263,32 @@ export const renameAfterLeaving = (context, person, left) => {
|
|
|
262
263
|
.prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ?")
|
|
263
264
|
.run(typeof kept === "string" ? kept : null, context.now(), person);
|
|
264
265
|
};
|
|
266
|
+
const shownAs = (person) => `${displayName(person.name, { name: person.identities.find((identity) => identity.name)?.name ?? null }) ?? "a person with no name"} (person:${person.uid})`;
|
|
267
|
+
/**
|
|
268
|
+
* Refuses identities that sit on anyone but `from` (a uid, or `person:<uid>` as doubts and refusals give it), so a
|
|
269
|
+
* caller that guessed the person never takes them off someone else. The refusal names who holds them.
|
|
270
|
+
*/
|
|
271
|
+
export const heldBy = (context, from, refs) => {
|
|
272
|
+
const uid = from.startsWith("person:") ? from.slice("person:".length) : from;
|
|
273
|
+
const found = /^[1-9]\d*$/.test(uid)
|
|
274
|
+
? context.database.prepare("SELECT id FROM persons WHERE id = ?").get(uid)
|
|
275
|
+
: undefined;
|
|
276
|
+
if (found === undefined)
|
|
277
|
+
throw new CliError("not_found", `no person:${uid} in the store`, { param: "from" });
|
|
278
|
+
const pk = currentPerson(context.database, Number(found.id));
|
|
279
|
+
for (const ref of refs) {
|
|
280
|
+
const row = required(context, ref);
|
|
281
|
+
if (row.personPk === pk)
|
|
282
|
+
continue;
|
|
283
|
+
const holder = recordOf(context, row.personPk);
|
|
284
|
+
throw new CliError("validation_error", `${ref.provider}:${ref.id} sits on ${shownAs(holder)}, not on ${shownAs(recordOf(context, pk))}; nothing changed. ` +
|
|
285
|
+
`Name person:${holder.uid} to take it off them`, { reason: "identity.held-elsewhere", param: "from", reference: `person:${holder.uid}` });
|
|
286
|
+
}
|
|
287
|
+
};
|
|
265
288
|
/** Gives the identity a person of its own again; the ones left keep theirs. */
|
|
266
289
|
export const unlinkIdentity = (context, ref, options) => {
|
|
290
|
+
if (options.from !== undefined)
|
|
291
|
+
heldBy(context, options.from, [ref]);
|
|
267
292
|
const found = required(context, ref);
|
|
268
293
|
const others = context.orm
|
|
269
294
|
.select({ n: sql `count(*)` })
|
|
@@ -279,7 +304,7 @@ export const unlinkIdentity = (context, ref, options) => {
|
|
|
279
304
|
.values({ name: named?.name ?? null, createdAt: at, updatedAt: at })
|
|
280
305
|
.returning({ pk: persons.id })
|
|
281
306
|
.get()?.pk);
|
|
282
|
-
move(context, found.pk, found.personPk, alone, {
|
|
307
|
+
move(context, found.pk, found.personPk, alone, { method: "unlink", by: options.by });
|
|
283
308
|
renameAfterLeaving(context, found.personPk, [found.pk]);
|
|
284
309
|
return recordOf(context, alone);
|
|
285
310
|
};
|