@wirecat/cli-core 0.631.0 → 0.632.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 +37 -0
- package/dist/calendar/mcp/index.d.ts +12 -12
- package/dist/cli/messenger/context.d.ts +2 -0
- package/dist/cli/messenger/reply-stats-command.js +1 -1
- package/dist/cli/messenger/serve-relay.d.ts +1 -0
- package/dist/cli/messenger/stats-answers.d.ts +5 -2
- package/dist/cli/messenger/stats-answers.js +8 -2
- package/dist/cli/messenger/tasks-command.js +5 -3
- package/dist/domain/test-data.d.ts +15 -0
- package/dist/domain/test-data.js +18 -0
- package/dist/entities/chat-stats.d.ts +2 -0
- package/dist/entities/chat-stats.js +2 -0
- package/dist/entities/index.d.ts +1 -0
- package/dist/errors/reasons.js +9 -0
- package/dist/kit/seed.js +6 -7
- package/dist/search/lucene/registry.js +11 -0
- package/dist/services/proposals/kinds/identity-split.d.ts +4 -0
- package/dist/services/proposals/kinds/identity-split.js +65 -0
- package/dist/services/proposals/registry.js +2 -0
- package/dist/services/reply-stats.js +11 -3
- package/dist/services/task-stats.d.ts +7 -2
- package/dist/services/task-stats.js +53 -20
- package/dist/services/tasks.d.ts +1 -0
- package/dist/services/tasks.js +16 -4
- package/dist/store/decisions.js +3 -1
- package/dist/store/drivers/bun-sqlite.js +2 -0
- package/dist/store/drivers/node-sqlite.js +2 -0
- package/dist/store/identity-splits.d.ts +60 -0
- package/dist/store/identity-splits.js +5 -0
- package/dist/store/index.d.ts +2 -0
- package/dist/store/index.js +2 -0
- package/dist/store/people.d.ts +23 -0
- package/dist/store/people.js +6 -0
- package/dist/store/sqlite/accounts.js +4 -0
- package/dist/store/sqlite/crm-contacts.js +5 -1
- package/dist/store/sqlite/identity-link-rows.d.ts +5 -0
- package/dist/store/sqlite/identity-link-rows.js +5 -3
- package/dist/store/sqlite/identity-split-proposals.d.ts +29 -0
- package/dist/store/sqlite/identity-split-proposals.js +195 -0
- package/dist/store/sqlite/lucene-fields.js +3 -0
- package/dist/store/sqlite/person-doubts.d.ts +36 -0
- package/dist/store/sqlite/person-doubts.js +229 -0
- package/dist/store/sqlite/proposed-actions.js +6 -0
- package/dist/store/sqlite/reply-times.d.ts +3 -1
- package/dist/store/sqlite/reply-times.js +11 -6
- package/package.json +1 -1
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { assertMayDecide, deciderAuthor } from "../decisions.js";
|
|
3
|
+
import { IDENTITY_SPLIT_KIND, } from "../identity-splits.js";
|
|
4
|
+
import { personOf, pkOf, sideOf } from "./identity-link-rows.js";
|
|
5
|
+
import { parseIdentityRef } from "./identity-proposals.js";
|
|
6
|
+
import { currentPerson } from "./merged-persons.js";
|
|
7
|
+
import { recordOf, required, unlinkIdentity } from "./person-links.js";
|
|
8
|
+
import { mergeId, merges, parseMergeId, split, undoMerge } from "./person-merges.js";
|
|
9
|
+
import { proposalOperationsOver, proposerOfAction } from "./proposed-actions.js";
|
|
10
|
+
import { write } from "./transaction.js";
|
|
11
|
+
const refOf = ({ provider, id }) => `${provider}:${id}`;
|
|
12
|
+
const keyOf = (split, person, identities) => `${split} ${person} ${[...identities].sort().join(" ")}`;
|
|
13
|
+
/** What the split would move, checked as the owner's own move would check it, so a proposal can be carried out. */
|
|
14
|
+
const planOf = (context, input) => {
|
|
15
|
+
if ("merge" in input) {
|
|
16
|
+
const { to, from } = parseMergeId(input.merge);
|
|
17
|
+
const id = mergeId(to, from);
|
|
18
|
+
const found = merges(context, to).find((merge) => merge.id === id);
|
|
19
|
+
if (found === undefined)
|
|
20
|
+
throw new CliError("not_found", `nothing of person:${from} is merged into person:${to}`, {
|
|
21
|
+
reason: "identity.no-merge",
|
|
22
|
+
});
|
|
23
|
+
return { split: "unmerge", person: Number(to), identities: found.identities.map(refOf), merge: id };
|
|
24
|
+
}
|
|
25
|
+
const chosen = [...new Map(input.identities.map((ref) => [refOf(ref), ref])).values()];
|
|
26
|
+
if (chosen.length === 0)
|
|
27
|
+
throw new CliError("validation_error", "name at least one identity to split off");
|
|
28
|
+
const persons = new Set(chosen.map((ref) => required(context, ref).personPk));
|
|
29
|
+
if (persons.size > 1)
|
|
30
|
+
throw new CliError("validation_error", "the identities that leave are all of one person", {
|
|
31
|
+
reason: "identity.several-persons",
|
|
32
|
+
});
|
|
33
|
+
const person = [...persons][0];
|
|
34
|
+
if (chosen.length >= recordOf(context, person).identities.length)
|
|
35
|
+
throw new CliError("validation_error", "a split leaves at least one identity with the person", {
|
|
36
|
+
reason: "identity.nothing-left",
|
|
37
|
+
});
|
|
38
|
+
return { split: "unlink", person, identities: chosen.map(refOf), merge: null };
|
|
39
|
+
};
|
|
40
|
+
const splitRows = (database, statuses, page, made) => database
|
|
41
|
+
.prepare("SELECT id, status, payload FROM proposed_actions WHERE kind = ? AND status IN (SELECT value FROM json_each(?)) " +
|
|
42
|
+
(made === undefined ? "" : `AND json_extract(result, '$.person') IS ${made ? "NOT " : ""}NULL `) +
|
|
43
|
+
`ORDER BY id DESC${page === undefined ? "" : " LIMIT ? OFFSET ?"}`)
|
|
44
|
+
.all(IDENTITY_SPLIT_KIND, JSON.stringify(statuses), ...(page === undefined ? [] : [page.limit, page.offset]))
|
|
45
|
+
.map((row) => ({
|
|
46
|
+
id: String(row.id),
|
|
47
|
+
status: String(row.status),
|
|
48
|
+
payload: JSON.parse(String(row.payload)),
|
|
49
|
+
}));
|
|
50
|
+
/**
|
|
51
|
+
* The person the proposal is about now: the one it was proposed for, or whom that person was merged into, while every
|
|
52
|
+
* identity it names is still there. `undefined` once one left, was erased or went elsewhere.
|
|
53
|
+
*/
|
|
54
|
+
const holder = (database, payload) => {
|
|
55
|
+
const person = currentPerson(database, Number(payload.person));
|
|
56
|
+
return payload.identities.every((ref) => personOf(database, pkOf(database, ref)) === person) ? person : undefined;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* The identities the owner turned a split down for, by the person they are still on: the owner said they belong there.
|
|
60
|
+
* `people doubts` leaves them out. One that moved since counts no longer.
|
|
61
|
+
*/
|
|
62
|
+
export const keptTogether = (database) => {
|
|
63
|
+
const kept = new Map();
|
|
64
|
+
for (const { payload } of splitRows(database, ["rejected"])) {
|
|
65
|
+
const person = currentPerson(database, Number(payload.person));
|
|
66
|
+
for (const ref of payload.identities) {
|
|
67
|
+
if (personOf(database, pkOf(database, ref)) !== person)
|
|
68
|
+
continue;
|
|
69
|
+
const refs = kept.get(person) ?? new Set();
|
|
70
|
+
refs.add(ref);
|
|
71
|
+
kept.set(person, refs);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return kept;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Proposes to take identities off their person, or to undo a merge, as an `identity_split` only the owner decides. An
|
|
78
|
+
* open proposal for the same identities is given back instead of a second, brought up to date with the person as it
|
|
79
|
+
* is now and with the new evidence added, so proposing again is how a stale one is renewed; its first reason and
|
|
80
|
+
* proposer stay. An identity the owner kept on this person by turning a split down is refused.
|
|
81
|
+
*/
|
|
82
|
+
export const proposeIdentitySplit = (context, input) => write(context.database, () => {
|
|
83
|
+
const reason = input.reason.trim();
|
|
84
|
+
if (!reason)
|
|
85
|
+
throw new CliError("validation_error", "a proposal to split a person says why", {
|
|
86
|
+
reason: "proposal.reason-required",
|
|
87
|
+
});
|
|
88
|
+
const plan = planOf(context, input);
|
|
89
|
+
const kept = keptTogether(context.database).get(plan.person);
|
|
90
|
+
if (plan.identities.some((ref) => kept?.has(ref)))
|
|
91
|
+
throw new CliError("conflict", "the owner kept these identities together; only the owner splits them", {
|
|
92
|
+
reason: "identity.kept-together",
|
|
93
|
+
});
|
|
94
|
+
const key = keyOf(plan.split, plan.person, plan.identities);
|
|
95
|
+
const operations = proposalOperationsOver(context);
|
|
96
|
+
const payload = {
|
|
97
|
+
split: plan.split,
|
|
98
|
+
person: String(plan.person),
|
|
99
|
+
identities: plan.identities,
|
|
100
|
+
merge: plan.merge,
|
|
101
|
+
side: sideOf(context.database, plan.person),
|
|
102
|
+
evidence: input.evidence ?? [],
|
|
103
|
+
};
|
|
104
|
+
for (const row of splitRows(context.database, ["proposed"])) {
|
|
105
|
+
const person = holder(context.database, row.payload);
|
|
106
|
+
if (person === undefined || keyOf(row.payload.split, person, row.payload.identities) !== key)
|
|
107
|
+
continue;
|
|
108
|
+
const evidence = [...new Set([...row.payload.evidence, ...payload.evidence])];
|
|
109
|
+
context.database
|
|
110
|
+
.prepare("UPDATE proposed_actions SET payload = ? WHERE id = ?")
|
|
111
|
+
.run(JSON.stringify({ ...payload, evidence }), Number(row.id));
|
|
112
|
+
return operations.get(row.id);
|
|
113
|
+
}
|
|
114
|
+
return operations.propose({ kind: IDENTITY_SPLIT_KIND, by: input.by, payload, reason });
|
|
115
|
+
});
|
|
116
|
+
/**
|
|
117
|
+
* Decides an `identity_split`, the owner's alone. Confirm carries it out as the owner's own unlink or unmerge, so no
|
|
118
|
+
* automatic match joins them again; it is refused with `identity.stale` when the person changed since it was proposed.
|
|
119
|
+
* Only a waiting proposal is carried out: one an older build approved as a plain action stays as it is.
|
|
120
|
+
*/
|
|
121
|
+
export const decideIdentitySplit = (context, id, decision) => write(context.database, () => {
|
|
122
|
+
const operations = proposalOperationsOver(context);
|
|
123
|
+
const proposal = operations.get(id);
|
|
124
|
+
if (proposal.kind !== IDENTITY_SPLIT_KIND)
|
|
125
|
+
throw new CliError("validation_error", `${id} is a ${proposal.kind} proposal, not a split of a person`);
|
|
126
|
+
assertMayDecide({ id, kind: IDENTITY_SPLIT_KIND, ownerOnly: true, proposedBy: proposerOfAction(proposal) }, decision.by, context.decisions);
|
|
127
|
+
const author = deciderAuthor(decision.by);
|
|
128
|
+
const reason = decision.reason?.trim() || undefined;
|
|
129
|
+
const noted = reason === undefined ? {} : { reason };
|
|
130
|
+
if (!decision.confirm)
|
|
131
|
+
return operations.reject(id, author, noted);
|
|
132
|
+
if (proposal.status !== "proposed")
|
|
133
|
+
throw new CliError("validation_error", `${id} is already ${proposal.status}`, { reason: "proposal.wrong-state" });
|
|
134
|
+
const payload = proposal.payload;
|
|
135
|
+
const person = Number(payload.person);
|
|
136
|
+
const refs = payload.identities.map(parseIdentityRef);
|
|
137
|
+
if (holder(context.database, payload) !== person || sideOf(context.database, person) !== payload.side)
|
|
138
|
+
throw new CliError("conflict", `the person ${id} names changed since it was proposed; propose it again`, {
|
|
139
|
+
reason: "identity.stale",
|
|
140
|
+
});
|
|
141
|
+
const owner = { method: "unlink", by: "owner" };
|
|
142
|
+
let made;
|
|
143
|
+
if (payload.split === "unmerge") {
|
|
144
|
+
const { to, from } = parseMergeId(payload.merge ?? "");
|
|
145
|
+
made = undoMerge(context, to, from, "owner");
|
|
146
|
+
}
|
|
147
|
+
else
|
|
148
|
+
made =
|
|
149
|
+
refs.length === 1
|
|
150
|
+
? unlinkIdentity(context, refs[0], owner)
|
|
151
|
+
: split(context, String(person), refs, "owner");
|
|
152
|
+
return operations.approve(id, { person: made.uid, ...noted }, author);
|
|
153
|
+
});
|
|
154
|
+
/** A split carried out records the person it made; an older build's approval as a plain action made none. */
|
|
155
|
+
const shownStatus = (status, result) => {
|
|
156
|
+
if (status === "proposed" || status === "rejected")
|
|
157
|
+
return status;
|
|
158
|
+
return typeof result?.person === "string" ? "confirmed" : "dropped";
|
|
159
|
+
};
|
|
160
|
+
const STORED = {
|
|
161
|
+
proposed: ["proposed"],
|
|
162
|
+
rejected: ["rejected"],
|
|
163
|
+
confirmed: ["approved", "executed", "failed"],
|
|
164
|
+
};
|
|
165
|
+
/** The `identity_split` proposals, newest first, each naming the person as they are now. */
|
|
166
|
+
export const identitySplitRows = (context, { status = "proposed", limit, offset }) => {
|
|
167
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
|
|
168
|
+
throw new CliError("validation_error", "a list of split proposals takes 1–500 items");
|
|
169
|
+
const statuses = status === "all" ? Object.values(STORED).flat() : STORED[status === "dropped" ? "confirmed" : status];
|
|
170
|
+
const made = status === "dropped" ? false : status === "confirmed" ? true : undefined;
|
|
171
|
+
const operations = proposalOperationsOver(context);
|
|
172
|
+
const rows = splitRows(context.database, statuses, { limit: limit + 1, offset }, made);
|
|
173
|
+
const items = rows.slice(0, limit).map((row) => {
|
|
174
|
+
const action = operations.get(row.id);
|
|
175
|
+
return {
|
|
176
|
+
id: row.id,
|
|
177
|
+
status: shownStatus(row.status, action.result),
|
|
178
|
+
split: row.payload.split,
|
|
179
|
+
person: `person:${holder(context.database, row.payload) ?? currentPerson(context.database, Number(row.payload.person))}`,
|
|
180
|
+
identities: row.payload.identities,
|
|
181
|
+
merge: row.payload.merge,
|
|
182
|
+
reason: action.reason,
|
|
183
|
+
evidence: row.payload.evidence,
|
|
184
|
+
proposedBy: proposerOfAction(action),
|
|
185
|
+
createdAt: action.createdAt,
|
|
186
|
+
};
|
|
187
|
+
});
|
|
188
|
+
return { items, hasMore: rows.length > limit };
|
|
189
|
+
};
|
|
190
|
+
/** Deletes every `identity_split` that names an identity no longer in the store: its payload names the address. */
|
|
191
|
+
export const forgetErasedSplits = (database) => {
|
|
192
|
+
for (const row of splitRows(database, ["proposed", "approved", "rejected", "executed", "failed"]))
|
|
193
|
+
if (row.payload.identities.some((ref) => pkOf(database, ref) === undefined))
|
|
194
|
+
database.prepare("DELETE FROM proposed_actions WHERE id = ?").run(Number(row.id));
|
|
195
|
+
};
|
|
@@ -347,6 +347,8 @@ const topic = messengerOnly(({ value }) => always(bound("m.thread_external_id =
|
|
|
347
347
|
/** What `kind:` matches for a chat aliased `c`: private, saved, bot, service, group, channel or unknown. */
|
|
348
348
|
export const PEER_KIND = "CASE WHEN json_extract(c.metadata,'$.peerKind') IN ('private','saved','bot','service','group','channel','unknown') THEN json_extract(c.metadata,'$.peerKind') WHEN c.kind='dialog' AND json_extract(c.metadata,'$.isBot')=1 THEN 'bot' WHEN c.kind='dialog' THEN 'private' ELSE c.kind END";
|
|
349
349
|
const kind = messengerOnly(({ value }) => always(bound(`${PEER_KIND} = ?`, value.toLowerCase())));
|
|
350
|
+
/** A chat the owner muted, until its mute runs out; a chat whose messenger keeps no mute is not muted. */
|
|
351
|
+
const muted = messengerOnly(({ value }) => always(bound(`${value.toLowerCase() === "true" ? "" : "NOT "}(coalesce(c.muted, 0) = 1 AND (c.muted_until IS NULL OR c.muted_until > ?))`, Date.now())));
|
|
350
352
|
const has = ({ value }, { corpus, mail }) => {
|
|
351
353
|
const wanted = value.toLowerCase();
|
|
352
354
|
if (wanted === "transcript")
|
|
@@ -440,6 +442,7 @@ export const FIELD_COMPILERS = {
|
|
|
440
442
|
tag,
|
|
441
443
|
topic,
|
|
442
444
|
kind,
|
|
445
|
+
muted,
|
|
443
446
|
has,
|
|
444
447
|
in: inSourceField,
|
|
445
448
|
to: recipient,
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { StoreContext } from "./open.js";
|
|
2
|
+
/** Why a person may be wrong, most urgent first: the owner's own person holding someone else matters most. */
|
|
3
|
+
export declare const DOUBT_REASONS: readonly ["owner-other-name", "test-data", "shared-address", "mixed-names"];
|
|
4
|
+
export type DoubtReason = (typeof DOUBT_REASONS)[number];
|
|
5
|
+
export interface DoubtIdentity {
|
|
6
|
+
identity: string;
|
|
7
|
+
name: string | null;
|
|
8
|
+
/** How the identity came to this person, and who linked it. */
|
|
9
|
+
method: string;
|
|
10
|
+
by: string;
|
|
11
|
+
at: string;
|
|
12
|
+
}
|
|
13
|
+
export interface PersonDoubt {
|
|
14
|
+
person: string;
|
|
15
|
+
name: string | null;
|
|
16
|
+
owner: boolean;
|
|
17
|
+
reason: DoubtReason;
|
|
18
|
+
/** The reason in plain words, naming what was found. */
|
|
19
|
+
why: string;
|
|
20
|
+
/** The identities in doubt, not every identity of the person. */
|
|
21
|
+
identities: DoubtIdentity[];
|
|
22
|
+
/** What the doubt rests on: the identities, a shared address, the merges that brought them. */
|
|
23
|
+
evidence: string[];
|
|
24
|
+
/** memo commands, after `memo`, that would take the doubted identities off; empty when none fits. */
|
|
25
|
+
fix: string[];
|
|
26
|
+
}
|
|
27
|
+
export interface PersonDoubts {
|
|
28
|
+
items: PersonDoubt[];
|
|
29
|
+
total: number;
|
|
30
|
+
hasMore: boolean;
|
|
31
|
+
}
|
|
32
|
+
/** People that may be wrong, a page at a time, each with why and the owner's moves that would set it right. */
|
|
33
|
+
export declare const personDoubts: (context: StoreContext, { limit, offset }: {
|
|
34
|
+
limit: number;
|
|
35
|
+
offset: number;
|
|
36
|
+
}) => PersonDoubts;
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { displayName } from "../../domain/display-names.js";
|
|
3
|
+
import { nameSkeletons } from "../../domain/name-variants.js";
|
|
4
|
+
import { RESERVED_ADDRESS_GLOBS, SEED_ID_GLOBS, SEED_PEOPLE } from "../../domain/test-data.js";
|
|
5
|
+
import { keptTogether } from "./identity-split-proposals.js";
|
|
6
|
+
import { merges } from "./person-merges.js";
|
|
7
|
+
/** Why a person may be wrong, most urgent first: the owner's own person holding someone else matters most. */
|
|
8
|
+
export const DOUBT_REASONS = ["owner-other-name", "test-data", "shared-address", "mixed-names"];
|
|
9
|
+
const COLUMNS = "l.person_id AS person, p.owner, p.name AS person_name, i.id AS pk, i.provider, i.external_id, i.name, i.phone, " +
|
|
10
|
+
"i.email, l.method, l.author, l.created_at, EXISTS (SELECT 1 FROM accounts a WHERE a.provider = i.provider " +
|
|
11
|
+
"AND a.external_id = i.external_id) AS account FROM identity_links l JOIN identities i ON i.id = l.identity_id " +
|
|
12
|
+
"JOIN persons p ON p.id = l.person_id";
|
|
13
|
+
const text = (value) => (typeof value === "string" && value.trim() !== "" ? value : null);
|
|
14
|
+
const heldOf = (row) => ({
|
|
15
|
+
pk: Number(row.pk),
|
|
16
|
+
person: Number(row.person),
|
|
17
|
+
owner: Number(row.owner) === 1,
|
|
18
|
+
personName: text(row.person_name),
|
|
19
|
+
ref: `${String(row.provider)}:${String(row.external_id)}`,
|
|
20
|
+
name: text(row.name),
|
|
21
|
+
phone: text(row.phone)?.replace(/\D/gu, "") || null,
|
|
22
|
+
email: text(row.email)?.toLowerCase() ?? null,
|
|
23
|
+
account: Number(row.account) === 1,
|
|
24
|
+
method: String(row.method),
|
|
25
|
+
by: String(row.author),
|
|
26
|
+
at: Number(row.created_at),
|
|
27
|
+
});
|
|
28
|
+
/** Only these people can carry two names or someone else's identity; the store has a few thousand of them. */
|
|
29
|
+
const sharedPeople = (database) => database
|
|
30
|
+
.prepare(`SELECT ${COLUMNS} WHERE l.person_id IN (SELECT person_id FROM identity_links GROUP BY person_id HAVING count(*) > 1) ` +
|
|
31
|
+
"ORDER BY l.person_id, i.id")
|
|
32
|
+
.all()
|
|
33
|
+
.map(heldOf);
|
|
34
|
+
/**
|
|
35
|
+
* Identities a test run left: the seed's word ids, an address at a reserved domain, or a seed name with its username
|
|
36
|
+
* or beside another seed name in one provider, since one name alone may be a real person's.
|
|
37
|
+
*/
|
|
38
|
+
const testData = (database) => {
|
|
39
|
+
const names = JSON.stringify(SEED_PEOPLE.map(({ name }) => name));
|
|
40
|
+
const usernames = JSON.stringify(SEED_PEOPLE.flatMap(({ username }) => (username === null ? [] : [username])));
|
|
41
|
+
const globs = (column, patterns) => patterns.map((pattern) => `${column} GLOB '${pattern}'`).join(" OR ");
|
|
42
|
+
return database
|
|
43
|
+
.prepare(`SELECT ${COLUMNS} WHERE ${globs("i.external_id", SEED_ID_GLOBS)} OR ${globs("lower(i.email)", RESERVED_ADDRESS_GLOBS)} ` +
|
|
44
|
+
"OR (i.name IN (SELECT value FROM json_each(?)) AND (i.username IN (SELECT value FROM json_each(?)) " +
|
|
45
|
+
"OR (SELECT count(DISTINCT j.name) FROM identities j WHERE j.provider = i.provider " +
|
|
46
|
+
"AND j.name IN (SELECT value FROM json_each(?))) >= 2)) ORDER BY l.person_id, i.id")
|
|
47
|
+
.all(names, usernames, names)
|
|
48
|
+
.map(heldOf);
|
|
49
|
+
};
|
|
50
|
+
/** A name's words, script and spelling aside; none for an address or a placeholder, which say nothing of a name. */
|
|
51
|
+
const wordsOf = (name) => {
|
|
52
|
+
const shown = displayName(name);
|
|
53
|
+
if (shown === null || shown.includes("@"))
|
|
54
|
+
return new Set();
|
|
55
|
+
return new Set(nameSkeletons(shown).filter((word) => word.length >= 2 && !/^\d+$/u.test(word)));
|
|
56
|
+
};
|
|
57
|
+
const sharesWord = (one, other) => [...one].some((word) => other.has(word));
|
|
58
|
+
/**
|
|
59
|
+
* The identities grouped by names that share a word, the person's own first: the most identities, counting double what
|
|
60
|
+
* the owner linked by hand, an account the owner connected and the person's own name.
|
|
61
|
+
*/
|
|
62
|
+
const nameGroups = (held) => {
|
|
63
|
+
const named = held.map((one) => ({ one, words: wordsOf(one.name) })).filter(({ words }) => words.size > 0);
|
|
64
|
+
const group = named.map((_, index) => index);
|
|
65
|
+
const root = (at) => {
|
|
66
|
+
let top = at;
|
|
67
|
+
while (group[top] !== top)
|
|
68
|
+
top = group[top];
|
|
69
|
+
let step = at;
|
|
70
|
+
while (group[step] !== top) {
|
|
71
|
+
const next = group[step];
|
|
72
|
+
group[step] = top;
|
|
73
|
+
step = next;
|
|
74
|
+
}
|
|
75
|
+
return top;
|
|
76
|
+
};
|
|
77
|
+
const firstWith = new Map();
|
|
78
|
+
for (const [index, { words }] of named.entries())
|
|
79
|
+
for (const word of words) {
|
|
80
|
+
const first = firstWith.get(word);
|
|
81
|
+
if (first === undefined)
|
|
82
|
+
firstWith.set(word, index);
|
|
83
|
+
else
|
|
84
|
+
group[root(index)] = root(first);
|
|
85
|
+
}
|
|
86
|
+
const groups = new Map();
|
|
87
|
+
for (const [index, { one }] of named.entries()) {
|
|
88
|
+
const same = groups.get(root(index));
|
|
89
|
+
if (same)
|
|
90
|
+
same.push(one);
|
|
91
|
+
else
|
|
92
|
+
groups.set(root(index), [one]);
|
|
93
|
+
}
|
|
94
|
+
const own = wordsOf(held[0]?.personName ?? null);
|
|
95
|
+
const weight = (members) => members.reduce((sum, one) => sum + 1 + (one.by === "owner" ? 2 : 0) + (one.account ? 2 : 0), 0) +
|
|
96
|
+
(members.some(({ name }) => sharesWord(wordsOf(name), own)) ? 2 : 0);
|
|
97
|
+
return [...groups.values()].sort((a, b) => weight(b) - weight(a) || a[0].pk - b[0].pk);
|
|
98
|
+
};
|
|
99
|
+
const quoted = (held) => [...new Set(held.map(({ name, ref }) => name ?? ref))].map((name) => `«${name}»`).join(", ");
|
|
100
|
+
const whyOf = (found) => {
|
|
101
|
+
const names = quoted(found.held);
|
|
102
|
+
if (found.reason === "owner-other-name")
|
|
103
|
+
return `your own person holds ${names}, under another name than yours: an account or mailbox you read may be someone else's`;
|
|
104
|
+
if (found.reason === "test-data")
|
|
105
|
+
return `${names} looks like test data, not a real contact: a name from the test seed, or an address at a reserved test domain`;
|
|
106
|
+
if (found.reason === "shared-address")
|
|
107
|
+
return `${names} joined this person by the address ${found.address}, which people with other names share: a shared or company mailbox may hold two people`;
|
|
108
|
+
return `this person carries different names (${names}) with no phone or address in common`;
|
|
109
|
+
};
|
|
110
|
+
const doubtsOf = (held, kept, test) => {
|
|
111
|
+
const [first] = held;
|
|
112
|
+
if (first === undefined)
|
|
113
|
+
return [];
|
|
114
|
+
const groups = nameGroups(held.filter(({ pk }) => !test.has(pk)));
|
|
115
|
+
if (groups.length < 2)
|
|
116
|
+
return [];
|
|
117
|
+
const main = groups[0];
|
|
118
|
+
const outside = groups
|
|
119
|
+
.slice(1)
|
|
120
|
+
.flat()
|
|
121
|
+
.filter(({ by, ref }) => by !== "owner" && !kept.has(ref));
|
|
122
|
+
const base = { person: first.person, owner: first.owner, name: first.personName };
|
|
123
|
+
if (first.owner)
|
|
124
|
+
return outside.length ? [{ ...base, reason: "owner-other-name", held: outside }] : [];
|
|
125
|
+
const found = [];
|
|
126
|
+
const mixed = [];
|
|
127
|
+
for (const one of outside) {
|
|
128
|
+
if (one.phone !== null && main.some(({ phone }) => phone === one.phone))
|
|
129
|
+
continue;
|
|
130
|
+
const address = one.email === null ? undefined : main.find(({ email }) => email === one.email)?.email;
|
|
131
|
+
if (typeof address === "string")
|
|
132
|
+
found.push({ ...base, reason: "shared-address", held: [one], address });
|
|
133
|
+
else
|
|
134
|
+
mixed.push(one);
|
|
135
|
+
}
|
|
136
|
+
if (mixed.length)
|
|
137
|
+
found.push({ ...base, reason: "mixed-names", held: [...main, ...mixed] });
|
|
138
|
+
return found;
|
|
139
|
+
};
|
|
140
|
+
const byPerson = (held) => {
|
|
141
|
+
const found = new Map();
|
|
142
|
+
for (const one of held) {
|
|
143
|
+
const same = found.get(one.person);
|
|
144
|
+
if (same)
|
|
145
|
+
same.push(one);
|
|
146
|
+
else
|
|
147
|
+
found.set(one.person, [one]);
|
|
148
|
+
}
|
|
149
|
+
return found;
|
|
150
|
+
};
|
|
151
|
+
const ORDER = new Map(DOUBT_REASONS.map((reason, index) => [reason, index]));
|
|
152
|
+
/** Everything in doubt, the owner first, then by reason and person. A few thousand people are read, never every row. */
|
|
153
|
+
const everyDoubt = (database) => {
|
|
154
|
+
const test = testData(database);
|
|
155
|
+
const testPks = new Set(test.map(({ pk }) => pk));
|
|
156
|
+
const kept = keptTogether(database);
|
|
157
|
+
const found = [];
|
|
158
|
+
for (const [person, held] of byPerson(sharedPeople(database)))
|
|
159
|
+
for (const one of doubtsOf(held, kept.get(person) ?? new Set(), testPks))
|
|
160
|
+
found.push(one);
|
|
161
|
+
for (const held of byPerson(test).values()) {
|
|
162
|
+
const [first] = held;
|
|
163
|
+
found.push({ person: first.person, owner: first.owner, name: first.personName, reason: "test-data", held });
|
|
164
|
+
}
|
|
165
|
+
return found.sort((a, b) => Number(b.owner) - Number(a.owner) ||
|
|
166
|
+
(ORDER.get(a.reason) ?? 0) - (ORDER.get(b.reason) ?? 0) ||
|
|
167
|
+
a.person - b.person);
|
|
168
|
+
};
|
|
169
|
+
/**
|
|
170
|
+
* The owner's moves that take the doubted identities off: undoing a merge that brought only doubted ones, and one
|
|
171
|
+
* unlink per name group of the rest, so two strangers on one person do not land on one new person together.
|
|
172
|
+
*/
|
|
173
|
+
const fixOf = (context, found) => {
|
|
174
|
+
if (found.reason === "test-data" || found.reason === "mixed-names")
|
|
175
|
+
return [];
|
|
176
|
+
const doubted = new Set(found.held.map(({ ref }) => ref));
|
|
177
|
+
const commands = [];
|
|
178
|
+
const unmerged = new Set();
|
|
179
|
+
for (const merge of merges(context, String(found.person))) {
|
|
180
|
+
const refs = merge.identities.map(({ provider, id }) => `${provider}:${id}`);
|
|
181
|
+
if (refs.length === 0 || !refs.every((ref) => doubted.has(ref)))
|
|
182
|
+
continue;
|
|
183
|
+
commands.push(`people unmerge ${merge.id}`);
|
|
184
|
+
for (const ref of refs)
|
|
185
|
+
unmerged.add(ref);
|
|
186
|
+
}
|
|
187
|
+
const rest = found.held.filter(({ ref }) => !unmerged.has(ref));
|
|
188
|
+
for (const group of nameGroups(rest))
|
|
189
|
+
commands.push(`people unlink ${group.map(({ ref }) => shellWord(ref)).join(" ")}`);
|
|
190
|
+
return commands;
|
|
191
|
+
};
|
|
192
|
+
/** A ref as one shell word: an id may hold a space or a quote, and the fix is pasted into a terminal. */
|
|
193
|
+
const shellWord = (ref) => (/^[\w@.:+/=-]+$/u.test(ref) ? ref : `'${ref.replaceAll("'", "'\\''")}'`);
|
|
194
|
+
const shown = (context, found) => {
|
|
195
|
+
const fix = fixOf(context, found);
|
|
196
|
+
return {
|
|
197
|
+
person: `person:${found.person}`,
|
|
198
|
+
name: found.name,
|
|
199
|
+
owner: found.owner,
|
|
200
|
+
reason: found.reason,
|
|
201
|
+
why: whyOf(found),
|
|
202
|
+
identities: found.held.map(({ ref, name, method, by, at }) => ({
|
|
203
|
+
identity: ref,
|
|
204
|
+
name,
|
|
205
|
+
method,
|
|
206
|
+
by,
|
|
207
|
+
at: new Date(at).toISOString(),
|
|
208
|
+
})),
|
|
209
|
+
evidence: [
|
|
210
|
+
...found.held.map(({ ref }) => ref),
|
|
211
|
+
...(found.address === undefined ? [] : [`email:${found.address}`]),
|
|
212
|
+
...fix.flatMap((command) => command.match(/merge:\d+-\d+/u) ?? []),
|
|
213
|
+
],
|
|
214
|
+
fix,
|
|
215
|
+
};
|
|
216
|
+
};
|
|
217
|
+
/** People that may be wrong, a page at a time, each with why and the owner's moves that would set it right. */
|
|
218
|
+
export const personDoubts = (context, { limit, offset }) => {
|
|
219
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
|
|
220
|
+
throw new CliError("validation_error", "a list of doubts takes 1–500 items");
|
|
221
|
+
if (!Number.isSafeInteger(offset) || offset < 0)
|
|
222
|
+
throw new CliError("validation_error", "a list of doubts takes a nonnegative offset");
|
|
223
|
+
const found = everyDoubt(context.database);
|
|
224
|
+
return {
|
|
225
|
+
items: found.slice(offset, offset + limit).map((one) => shown(context, one)),
|
|
226
|
+
total: found.length,
|
|
227
|
+
hasMore: found.length > offset + limit,
|
|
228
|
+
};
|
|
229
|
+
};
|
|
@@ -3,6 +3,7 @@ import { MEETING_FINDINGS_KIND } from "../../meetings/index.js";
|
|
|
3
3
|
import { assertMayDecide, deciderAuthor } from "../decisions.js";
|
|
4
4
|
import { EVIDENCE_FINDINGS_KIND } from "../evidence-findings.js";
|
|
5
5
|
import { IDENTITY_LINK_KIND } from "../identity-links.js";
|
|
6
|
+
import { IDENTITY_SPLIT_KIND } from "../identity-splits.js";
|
|
6
7
|
import { MAIL_FINDINGS_KIND } from "../mail-findings.js";
|
|
7
8
|
import { SOURCE_REVIEW_KIND } from "../source-review.js";
|
|
8
9
|
import { proposedBySql } from "./actors.js";
|
|
@@ -191,6 +192,11 @@ const DEDICATED_REVIEW = {
|
|
|
191
192
|
reason: "identity-link.dedicated-review",
|
|
192
193
|
through: "the people review, which checks that neither person changed",
|
|
193
194
|
},
|
|
195
|
+
[IDENTITY_SPLIT_KIND]: {
|
|
196
|
+
what: "a proposed split of a person",
|
|
197
|
+
reason: "identity-split.dedicated-review",
|
|
198
|
+
through: "the people review, which checks that the person did not change",
|
|
199
|
+
},
|
|
194
200
|
};
|
|
195
201
|
/** Refuses a dedicated kind on a generic action path: approving one as an action would skip its own checks. */
|
|
196
202
|
export const assertGenericAction = (kind) => {
|
|
@@ -9,6 +9,8 @@ export interface ChatScope {
|
|
|
9
9
|
chatId: string;
|
|
10
10
|
}[];
|
|
11
11
|
kinds: string[];
|
|
12
|
+
/** Only chats muted (true) or not muted (false) now; absent reads both. */
|
|
13
|
+
muted?: boolean;
|
|
12
14
|
/** Inclusive bounds in ms; absent is open. */
|
|
13
15
|
since?: number;
|
|
14
16
|
until?: number;
|
|
@@ -33,7 +35,7 @@ export interface NewestMessage {
|
|
|
33
35
|
* One row per reply in one-to-one chats. Each chat is read from the start of the run before the first message in the
|
|
34
36
|
* period, so a reply early in the period is timed from the first message it answers, however old.
|
|
35
37
|
*/
|
|
36
|
-
export declare const replyDelaysQuery: (scope: ChatScope, who: "me" | "others") => {
|
|
38
|
+
export declare const replyDelaysQuery: (scope: ChatScope, who: "me" | "others", now: number) => {
|
|
37
39
|
sql: string;
|
|
38
40
|
params: SqlValue[];
|
|
39
41
|
};
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { PEER_KIND } from "./lucene-fields.js";
|
|
2
2
|
import { read } from "./transaction.js";
|
|
3
3
|
const FAR = Number.MAX_SAFE_INTEGER;
|
|
4
|
-
const
|
|
4
|
+
const MUTED_NOW = "(coalesce(c.muted,0)=1 AND (c.muted_until IS NULL OR c.muted_until>?))";
|
|
5
|
+
const chatsIn = (scope, kinds, now) => {
|
|
5
6
|
const params = [...scope.accounts.flatMap(({ provider, account }) => [provider, account]), ...kinds];
|
|
6
7
|
const parts = [
|
|
7
8
|
`(${scope.accounts.map(() => "(ac.provider=? AND ac.external_id=?)").join(" OR ") || "0"})`,
|
|
@@ -15,6 +16,10 @@ const chatsIn = (scope, kinds) => {
|
|
|
15
16
|
parts.push(`${PEER_KIND}=?`);
|
|
16
17
|
params.push(kind);
|
|
17
18
|
}
|
|
19
|
+
if (scope.muted !== undefined) {
|
|
20
|
+
parts.push(scope.muted ? MUTED_NOW : `NOT ${MUTED_NOW}`);
|
|
21
|
+
params.push(now);
|
|
22
|
+
}
|
|
18
23
|
// As in search: a chat named is read even when it is not searchable.
|
|
19
24
|
if (scope.chats.length === 0)
|
|
20
25
|
parts.push("c.searchable=1");
|
|
@@ -24,10 +29,10 @@ const chatsIn = (scope, kinds) => {
|
|
|
24
29
|
* One row per reply in one-to-one chats. Each chat is read from the start of the run before the first message in the
|
|
25
30
|
* period, so a reply early in the period is timed from the first message it answers, however old.
|
|
26
31
|
*/
|
|
27
|
-
export const replyDelaysQuery = (scope, who) => {
|
|
32
|
+
export const replyDelaysQuery = (scope, who, now) => {
|
|
28
33
|
const since = scope.since ?? -FAR;
|
|
29
34
|
const until = scope.until ?? FAR;
|
|
30
|
-
const chats = chatsIn(scope, ["private"]);
|
|
35
|
+
const chats = chatsIn(scope, ["private"], now);
|
|
31
36
|
return {
|
|
32
37
|
sql: `WITH scoped AS MATERIALIZED (
|
|
33
38
|
SELECT c.id AS chat_id, coalesce((
|
|
@@ -51,7 +56,7 @@ WHERE asked_at IS NOT NULL AND mine=? AND sent_at>=? AND sent_at<=?`,
|
|
|
51
56
|
};
|
|
52
57
|
};
|
|
53
58
|
export const replyDelays = (context, scope, who) => {
|
|
54
|
-
const { sql, params } = replyDelaysQuery(scope, who);
|
|
59
|
+
const { sql, params } = replyDelaysQuery(scope, who, context.now());
|
|
55
60
|
return read(context.database, () => context.database
|
|
56
61
|
.prepare(sql)
|
|
57
62
|
.all(...params)
|
|
@@ -59,7 +64,7 @@ export const replyDelays = (context, scope, who) => {
|
|
|
59
64
|
};
|
|
60
65
|
/** Each one-to-one chat's and group's newest message, found by index per chat, its time within the scope's bounds. */
|
|
61
66
|
export const newestMessagesQuery = (scope, now) => {
|
|
62
|
-
const chats = chatsIn(scope, ["private", "group"]);
|
|
67
|
+
const chats = chatsIn(scope, ["private", "group"], now);
|
|
63
68
|
return {
|
|
64
69
|
sql: `SELECT c.id AS chat_id, ${PEER_KIND} AS kind, m.sent_at, coalesce(m.outgoing,0) AS mine, m.text,
|
|
65
70
|
(EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(m.mentions) THEN m.mentions ELSE '[]' END) WHERE value=ac.external_id)
|
|
@@ -67,7 +72,7 @@ export const newestMessagesQuery = (scope, now) => {
|
|
|
67
72
|
OR EXISTS (SELECT 1 FROM messages q WHERE q.chat_id=c.id AND q.external_id=m.reply_to_external_id AND q.outgoing=1)
|
|
68
73
|
) AS addressed,
|
|
69
74
|
(SELECT i.username FROM identities i WHERE i.provider=ac.provider AND i.external_id=ac.external_id) AS owner_username,
|
|
70
|
-
(
|
|
75
|
+
(${MUTED_NOW} OR coalesce(c.archived,0)=1)
|
|
71
76
|
AND coalesce(c.marked_unread,0)=0 AS quiet
|
|
72
77
|
FROM chats c JOIN accounts ac ON ac.id=c.account_id
|
|
73
78
|
JOIN messages m ON m.id=(SELECT n.id FROM messages n WHERE n.chat_id=c.id AND n.deleted_at IS NULL ORDER BY n.sent_at DESC LIMIT 1)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.632.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|