@wirecat/cli-core 0.632.0 → 0.634.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/messenger/archive-commands.js +4 -1
  4. package/dist/cli/messenger/store-import-command.d.ts +4 -0
  5. package/dist/cli/messenger/store-import-command.js +166 -0
  6. package/dist/cli/messenger/stored.d.ts +7 -1
  7. package/dist/cli/messenger/stored.js +1 -1
  8. package/dist/domain/relation-role-labels.d.ts +10 -0
  9. package/dist/domain/relation-role-labels.js +40 -0
  10. package/dist/domain/relations.d.ts +7 -0
  11. package/dist/domain/relations.js +10 -0
  12. package/dist/entities/index.d.ts +17 -2
  13. package/dist/entities/index.js +3 -2
  14. package/dist/entities/store-maintenance.d.ts +16 -0
  15. package/dist/entities/store-maintenance.js +10 -0
  16. package/dist/index.d.ts +2 -1
  17. package/dist/index.js +2 -1
  18. package/dist/sends/permissions.js +1 -0
  19. package/dist/services/index.d.ts +1 -0
  20. package/dist/services/index.js +1 -0
  21. package/dist/services/metadata.d.ts +1 -1
  22. package/dist/services/project-activity.d.ts +45 -0
  23. package/dist/services/project-activity.js +76 -0
  24. package/dist/services/project-status/index.d.ts +11 -1
  25. package/dist/services/project-status/index.js +3 -3
  26. package/dist/store/exports.d.ts +1 -0
  27. package/dist/store/index.d.ts +2 -2
  28. package/dist/store/messages.d.ts +13 -0
  29. package/dist/store/messages.js +7 -0
  30. package/dist/store/path.d.ts +3 -0
  31. package/dist/store/path.js +25 -6
  32. package/dist/store/sqlite/chat-activity-counts.d.ts +19 -0
  33. package/dist/store/sqlite/chat-activity-counts.js +26 -0
  34. package/dist/store/sqlite/person-doubts.d.ts +10 -0
  35. package/dist/store/sqlite/person-doubts.js +10 -8
  36. package/dist/store/sqlite/relation-list.d.ts +3 -1
  37. package/dist/store/sqlite/relation-list.js +16 -9
  38. package/dist/store/sqlite/relation-roles.d.ts +4 -0
  39. package/dist/store/sqlite/relation-roles.js +19 -5
  40. package/dist/store/sqlite/reply-times.d.ts +2 -0
  41. package/dist/store/sqlite/reply-times.js +2 -1
  42. package/package.json +1 -1
  43. package/parity.json +3 -0
@@ -0,0 +1,45 @@
1
+ import type { AccountKey, MessageStore } from "../store/store.js";
2
+ export interface ProjectActivityInput {
3
+ since: number;
4
+ /** Exclusive; now when left out. */
5
+ until?: number;
6
+ /** Only chats of these accounts count, as under a group lock; every account when left out. */
7
+ accounts?: AccountKey[];
8
+ limit: number;
9
+ offset: number;
10
+ /** The busiest chats named per project. */
11
+ top?: number;
12
+ }
13
+ export interface ProjectActivityChat {
14
+ ref: string;
15
+ title: string | null;
16
+ messages: number;
17
+ }
18
+ export interface ProjectActivity {
19
+ ref: string;
20
+ key: string | null;
21
+ name: string;
22
+ /** Chats linked to the project or its child projects, confirmed, in the accounts read. */
23
+ chats: number;
24
+ /** Of them, muted now: their messages are not counted. */
25
+ muted: number;
26
+ messages: number;
27
+ /** Of `messages`, the owner's. */
28
+ sent: number;
29
+ /** The newest message of an unmuted linked chat, in or before the window. */
30
+ lastAt: string | null;
31
+ top: ProjectActivityChat[];
32
+ /** Some child projects were past the depth or count `projects status` reads, so their chats are not counted. */
33
+ partial: boolean;
34
+ }
35
+ export interface ProjectActivities {
36
+ items: ProjectActivity[];
37
+ total: number;
38
+ hasMore: boolean;
39
+ }
40
+ /**
41
+ * Every project's linked chats and how busy they were, in one pass: every confirmed link of the project and its
42
+ * children, any purpose and with no chat limit (`projects status` caps both), counted by when each message was sent. A
43
+ * muted chat is named in `muted` and left out of the counts, as everywhere the owner's activity is counted.
44
+ */
45
+ export declare const projectActivity: (store: MessageStore, input: ProjectActivityInput) => Promise<ProjectActivities>;
@@ -0,0 +1,76 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { formatReference } from "../domain/references.js";
3
+ import { childrenOf, inAccounts, projectsCatalog } from "./project-status/index.js";
4
+ import { linkedChatsOf } from "./stored-project-gathering.js";
5
+ const TOP = 3;
6
+ /**
7
+ * Every project's linked chats and how busy they were, in one pass: every confirmed link of the project and its
8
+ * children, any purpose and with no chat limit (`projects status` caps both), counted by when each message was sent. A
9
+ * muted chat is named in `muted` and left out of the counts, as everywhere the owner's activity is counted.
10
+ */
11
+ export const projectActivity = async (store, input) => {
12
+ const until = input.until ?? Date.now();
13
+ if (!(input.since < until))
14
+ throw new CliError("validation_error", "the window must start before it ends");
15
+ const whole = (n) => n === undefined || (Number.isInteger(n) && n >= 0);
16
+ if (!(input.limit >= 1 && whole(input.limit) && whole(input.offset) && whole(input.top)))
17
+ throw new CliError("validation_error", "limit must be at least 1; offset and top whole numbers from 0");
18
+ const catalog = await projectsCatalog(store);
19
+ const linked = [];
20
+ for (const [ref, entry] of catalog) {
21
+ const root = { ref, key: entry.key ?? null, name: entry.name };
22
+ const { children, cut } = await childrenOf(store, root, catalog);
23
+ const chats = new Map();
24
+ for (const project of [root, ...children])
25
+ for (const link of await linkedChatsOf(store, project.ref)) {
26
+ if (!inAccounts(input.accounts, link.provider, link.account))
27
+ continue;
28
+ chats.set(refOf(link), link);
29
+ }
30
+ linked.push({
31
+ project: ref,
32
+ key: root.key,
33
+ name: root.name,
34
+ chats: [...chats.values()],
35
+ partial: cut.some((one) => one.reason !== "cycle"),
36
+ });
37
+ }
38
+ const unique = new Map(linked.flatMap(({ chats }) => chats.map((chat) => [refOf(chat), chat])));
39
+ const asked = [...unique.values()];
40
+ const counts = await store.messages.chatActivityCounts(asked.map((chat) => ({ account: { provider: chat.provider, account: chat.account }, chatId: chat.chat })), { since: input.since, until, now: Date.now() });
41
+ const countOf = new Map(asked.map((chat, index) => [refOf(chat), counts[index]]));
42
+ const all = linked.map(({ project, key, name, chats, partial }) => {
43
+ const known = chats.flatMap((chat) => {
44
+ const count = countOf.get(refOf(chat));
45
+ return count ? [{ ref: refOf(chat), ...count }] : [];
46
+ });
47
+ const counted = known.filter((chat) => !chat.muted);
48
+ const last = counted.map((chat) => chat.lastAt).filter((at) => at !== null);
49
+ return {
50
+ ref: project,
51
+ key,
52
+ name,
53
+ chats: chats.length,
54
+ muted: known.length - counted.length,
55
+ messages: counted.reduce((sum, chat) => sum + chat.messages, 0),
56
+ sent: counted.reduce((sum, chat) => sum + chat.sent, 0),
57
+ lastAt: last.sort().at(-1) ?? null,
58
+ top: counted
59
+ .filter((chat) => chat.messages > 0)
60
+ .sort((a, b) => b.messages - a.messages || a.ref.localeCompare(b.ref, undefined, { numeric: true }))
61
+ .slice(0, input.top ?? TOP)
62
+ .map(({ ref, title, messages }) => ({ ref, title, messages })),
63
+ partial,
64
+ };
65
+ });
66
+ all.sort((a, b) => b.messages - a.messages ||
67
+ (b.lastAt ?? "").localeCompare(a.lastAt ?? "") ||
68
+ b.chats - a.chats ||
69
+ a.ref.localeCompare(b.ref, undefined, { numeric: true }));
70
+ return {
71
+ items: all.slice(input.offset, input.offset + input.limit),
72
+ total: all.length,
73
+ hasMore: input.offset + input.limit < all.length,
74
+ };
75
+ };
76
+ const refOf = (chat) => formatReference({ type: "chat", provider: chat.provider, account: chat.account, chat: chat.chat });
@@ -3,7 +3,7 @@ import type { AccountKey, MessageStore } from "../../store/store.js";
3
3
  import { type PurposeConfig } from "../project-purposes.js";
4
4
  import { type ChatCount, type ChatCounter } from "../stored-project-gathering.js";
5
5
  import { STATUS_SIGNALS } from "./signals/index.js";
6
- import type { StatusAttention, StatusChat, StatusItem, StatusProject, StatusSignal } from "./types.js";
6
+ import type { StatusAttention, StatusChat, StatusChild, StatusItem, StatusProject, StatusSignal } from "./types.js";
7
7
  export type * from "./types.js";
8
8
  export { STATUS_SIGNALS };
9
9
  /** Messages read per chat; the newest of the window. */
@@ -78,6 +78,16 @@ export interface ProjectStatus {
78
78
  version: number;
79
79
  }[];
80
80
  }
81
+ export declare const projectsCatalog: (store: MessageStore) => Promise<Map<string, import("../../store/index.js").VocabularyEntry>>;
82
+ /** Confirmed `member-of` links from another project; depth two, eight at most, a project seen twice skipped. */
83
+ export declare const childrenOf: (store: MessageStore, root: StatusProject, catalog: Awaited<ReturnType<typeof projectsCatalog>>) => Promise<{
84
+ children: StatusChild[];
85
+ cut: {
86
+ ref: string;
87
+ reason: "depth" | "cycle" | "limit";
88
+ }[];
89
+ }>;
90
+ export declare const inAccounts: (accounts: AccountKey[] | undefined, provider: string, account: string) => boolean;
81
91
  /**
82
92
  * Where a project stands, from the store alone: its linked chats and its children's, each read once, then every
83
93
  * signal on its own. A signal that fails is named in `failed` and the others still answer. No model call.
@@ -14,9 +14,9 @@ export const STATUS_WINDOW = 300;
14
14
  export const STATUS_CHATS = 16;
15
15
  const CHILD_DEPTH = 2;
16
16
  const CHILDREN = 8;
17
- const projectsCatalog = async (store) => new Map((await store.knowledge.vocabulary({ kind: "project" })).entries.map((entry) => [`project:${entry.id}`, entry]));
17
+ export const projectsCatalog = async (store) => new Map((await store.knowledge.vocabulary({ kind: "project" })).entries.map((entry) => [`project:${entry.id}`, entry]));
18
18
  /** Confirmed `member-of` links from another project; depth two, eight at most, a project seen twice skipped. */
19
- const childrenOf = async (store, root, catalog) => {
19
+ export const childrenOf = async (store, root, catalog) => {
20
20
  const children = [];
21
21
  const cut = [];
22
22
  const seen = new Set([root.ref]);
@@ -52,7 +52,7 @@ const childrenOf = async (store, root, catalog) => {
52
52
  }
53
53
  return { children, cut };
54
54
  };
55
- const inAccounts = (accounts, provider, account) => accounts === undefined || accounts.some((one) => one.provider === provider && one.account === account);
55
+ export const inAccounts = (accounts, provider, account) => accounts === undefined || accounts.some((one) => one.provider === provider && one.account === account);
56
56
  const failure = (error) => (error instanceof Error ? error.message : String(error));
57
57
  const owed = (item) => {
58
58
  const data = item.data;
@@ -20,6 +20,7 @@ export { type AttachmentTextEntry, type AttachmentView, attachmentColumns, type
20
20
  export { pendingNormalization } from "./sqlite/backfill.js";
21
21
  export type { BaseScope, BaseSet, BaseStagesStore, StageMapping } from "./sqlite/base-stages.js";
22
22
  export { BUSINESS_FIND_MAX, type BusinessHit, type BusinessSearch, type BusinessSearchStore, type BusinessSource, } from "./sqlite/business-search.js";
23
+ export type { ChatActivityCount } from "./sqlite/chat-activity-counts.js";
23
24
  export type { ChatRekey, ChatRekeys } from "./sqlite/chat-rekey.js";
24
25
  export { CHAT_COLUMNS, TRACKED_CHAT_COLUMNS, titlePart } from "./sqlite/chats.js";
25
26
  export { storeClients } from "./sqlite/clients.js";
@@ -80,7 +80,7 @@ export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from ".
80
80
  export type { OrganizationFilter } from "./sqlite/organization-categories.js";
81
81
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
82
82
  export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
83
- export { DOUBT_REASONS, type DoubtIdentity, type DoubtReason, type PersonDoubt, type PersonDoubts, } from "./sqlite/person-doubts.js";
83
+ export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type PersonDoubt, type PersonDoubts, } from "./sqlite/person-doubts.js";
84
84
  export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
85
85
  export { ALWAYS_SHOWN, PERSON_TIES, type PersonTie, type ShownBecause, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
86
86
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
@@ -116,4 +116,4 @@ export type { TagPreflight, VocabularyAlias, VocabularyAliasReceipt, VocabularyA
116
116
  export type { Wallet, WalletFilter, WalletInput, WalletsStore, WalletUpdate } from "./sqlite/wallets.js";
117
117
  export type { BoardCounts, BoardOptions, EditedTask, MovedSubtask, NewWorkTask, RevisionCheck, TaskAssignment, TaskDetails, TaskEvent, TaskFields, TaskMove, TaskMoved, TaskRole, TaskType, WorkTaskType, } from "./sqlite/work-tasks.js";
118
118
  export { TASK_EVENT_KINDS, TASK_ROLES } from "./sqlite/work-tasks.js";
119
- export { type AccountAccounts, type AccountAttachments, type AccountCounters, type AccountGroupChange, type AccountKey, type AccountMentions, type AccountMessageFilter, type AccountMessages, type AccountPeople, type AccountsStore, type AccountVectors, type AttachmentsStore, type AttachmentTextEntry, type AttachmentView, type ChatStats, type ChatsStore, type ConversationsStore, type CountersStore, type DeletionScope, type Delta, type FileAttachment, type IdentityRef, type IngestedVia, type LinkedIdentity, type LinkOptions, MENTION_QUERY, MENTION_STATUSES, type MentionsStore, type MessageFilter, type MessageStore, type MessagesStore, OTHER_SOURCES, openStore, type PeopleStore, type PersonFacts, type PersonRecord, type QueriesStore, type Range, type RankedEvidence, type RankedStoreFound, type RankedStoreRow, type RankingEvidenceItem, type RankingEvidenceRequest, type RankingRequest, type RosterStore, type SearchCommand, type SearchesStore, type SearchIndexStore, type SearchRecord, type StoredAccount, type StoredChatFilter, type StoredHit, type StoredSearch, type StoredTag, type StoreOptions, type SyncStore, type TagFilter, type TagsStore, type TagTarget, type TaskAnalysisMark, type TaskAnalysisMarkWrite, type TaskTagTarget, type TextOrigin, type VectorsStore, } from "./store.js";
119
+ export { type AccountAccounts, type AccountAttachments, type AccountCounters, type AccountGroupChange, type AccountKey, type AccountMentions, type AccountMessageFilter, type AccountMessages, type AccountPeople, type AccountsStore, type AccountVectors, type AttachmentsStore, type AttachmentTextEntry, type AttachmentView, type ChatActivityCount, type ChatStats, type ChatsStore, type ConversationsStore, type CountersStore, type DeletionScope, type Delta, type FileAttachment, type IdentityRef, type IngestedVia, type LinkedIdentity, type LinkOptions, MENTION_QUERY, MENTION_STATUSES, type MentionsStore, type MessageFilter, type MessageStore, type MessagesStore, OTHER_SOURCES, openStore, type PeopleStore, type PersonFacts, type PersonRecord, type QueriesStore, type Range, type RankedEvidence, type RankedStoreFound, type RankedStoreRow, type RankingEvidenceItem, type RankingEvidenceRequest, type RankingRequest, type RosterStore, type SearchCommand, type SearchesStore, type SearchIndexStore, type SearchRecord, type StoredAccount, type StoredChatFilter, type StoredHit, type StoredSearch, type StoredTag, type StoreOptions, type SyncStore, type TagFilter, type TagsStore, type TagTarget, type TaskAnalysisMark, type TaskAnalysisMarkWrite, type TaskTagTarget, type TextOrigin, type VectorsStore, } from "./store.js";
@@ -1,5 +1,6 @@
1
1
  import type { CounterObservations } from "../domain/counters.js";
2
2
  import type { Delivery, Id, Message, Page, PersonReaction, PollVote, Reactions, Reactor, WindowedMessage } from "../domain/models.js";
3
+ import { type ChatActivityCount } from "./sqlite/chat-activity-counts.js";
3
4
  import { type DocumentLinkMessage } from "./sqlite/document-links.js";
4
5
  import type { StoreContext } from "./sqlite/open.js";
5
6
  import * as reads from "./sqlite/reads.js";
@@ -162,6 +163,18 @@ export interface MessagesStore extends AccountMessages {
162
163
  rareAt: number;
163
164
  limit: number;
164
165
  }): Promise<StoredHit[][]>;
166
+ /**
167
+ * Per chat, in the order asked: its messages and the owner's in the window (`until` exclusive), its newest message,
168
+ * whether it is muted at `now`, and its title; `undefined` for a chat the store does not know.
169
+ */
170
+ chatActivityCounts(chats: readonly {
171
+ account: AccountKey;
172
+ chatId: Id;
173
+ }[], window: {
174
+ since: number;
175
+ until: number;
176
+ now: number;
177
+ }): Promise<(ChatActivityCount | undefined)[]>;
165
178
  }
166
179
  export declare const accountMessagesOver: (context: StoreContext) => AccountMessages;
167
180
  export declare const messagesStoreOver: (context: StoreContext, keyed: AccountMessages) => MessagesStore;
@@ -1,4 +1,5 @@
1
1
  import { keysOver } from "./keys.js";
2
+ import { chatActivityCounts } from "./sqlite/chat-activity-counts.js";
2
3
  import { applyCounterObservations } from "./sqlite/counters.js";
3
4
  import { documentLinkMessages } from "./sqlite/document-links.js";
4
5
  import { laterSharingRare } from "./sqlite/follow-ups.js";
@@ -142,6 +143,12 @@ export const accountMessagesOver = (context) => {
142
143
  };
143
144
  export const messagesStoreOver = (context, keyed) => ({
144
145
  ...keyed,
146
+ chatActivityCounts: async (chats, window) => {
147
+ const { chatKeyOf } = keysOver(context);
148
+ const keys = chats.map(({ account, chatId }) => chatKeyOf(account, chatId));
149
+ const found = chatActivityCounts(context, keys.filter((key) => key !== undefined), window);
150
+ return keys.map((key) => (key === undefined ? undefined : found.get(key)));
151
+ },
145
152
  search: async (query, { limit, account }) => search.find(context, { text: query, limit, ...(account ? { account } : {}) }),
146
153
  find: async (filter) => search.find(context, filter),
147
154
  directReplies: async (parents, limit) => search.directReplies(context, parents, limit),
@@ -6,5 +6,8 @@ export declare const wirecatDirectory: (env?: NodeJS.ProcessEnv, platform?: Node
6
6
  * before this one: a build still installed would open that name and run its own migrations over these tables.
7
7
  */
8
8
  export declare const storePath: (env?: NodeJS.ProcessEnv) => string;
9
+ export declare const accountHome: () => string | undefined;
10
+ /** Whether `file` is in the owner's real WireCat folder, whatever HOME or MESSAGING_STORE this process was given. */
11
+ export declare const inOwnerFolder: (file: string, home?: string | undefined) => boolean;
9
12
  /** Throws when a test is about to open a file in the owner's real WireCat folder. */
10
13
  export declare const refuseOwnerStoreInTests: (file: string, env?: NodeJS.ProcessEnv, home?: string | undefined) => void;
@@ -1,5 +1,6 @@
1
+ import { realpathSync } from "node:fs";
1
2
  import { userInfo } from "node:os";
2
- import { isAbsolute, join, relative, resolve } from "node:path";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
3
4
  import { resolvePaths } from "@wirecat/cli-base";
4
5
  /** The folder the CLIs share: the store, its backups and the models. `WIRECAT_STATE_DIR` moves all of it. */
5
6
  export const wirecatDirectory = (env = process.env, platform) => resolvePaths({ appName: "WireCat", prefix: "WIRECAT", env, ...(platform ? { platform } : {}) }).state;
@@ -11,7 +12,7 @@ export const wirecatDirectory = (env = process.env, platform) => resolvePaths({
11
12
  export const storePath = (env = process.env) => env.MESSAGING_STORE ?? join(wirecatDirectory(env), "wirecat.db");
12
13
  // The account's home from the user database, not HOME: the test sandbox moves HOME, and a worker thread's
13
14
  // `os.homedir()` still answers the real one (the 2026-10-18 leak).
14
- const accountHome = () => {
15
+ export const accountHome = () => {
15
16
  try {
16
17
  return userInfo().homedir;
17
18
  }
@@ -19,12 +20,30 @@ const accountHome = () => {
19
20
  return undefined;
20
21
  }
21
22
  };
23
+ /** Whether `file` is in the owner's real WireCat folder, whatever HOME or MESSAGING_STORE this process was given. */
24
+ export const inOwnerFolder = (file, home = accountHome()) => {
25
+ if (!home || file === ":memory:")
26
+ return false;
27
+ const owner = wirecatDirectory({ HOME: home, USERPROFILE: home });
28
+ const within = (path, folder) => {
29
+ const inside = relative(folder, path);
30
+ return !(inside.startsWith("..") || isAbsolute(inside));
31
+ };
32
+ return within(resolve(file), owner) || within(settled(resolve(file)), settled(owner));
33
+ };
34
+ /** The path with every link in its existing part followed, so a link into the owner's folder is seen as one. */
35
+ const settled = (path) => {
36
+ try {
37
+ return realpathSync(path);
38
+ }
39
+ catch {
40
+ const parent = dirname(path);
41
+ return parent === path ? path : join(settled(parent), basename(path));
42
+ }
43
+ };
22
44
  /** Throws when a test is about to open a file in the owner's real WireCat folder. */
23
45
  export const refuseOwnerStoreInTests = (file, env = process.env, home = accountHome()) => {
24
- if (!env.VITEST || !home || file === ":memory:")
25
- return;
26
- const inside = relative(wirecatDirectory({ HOME: home, USERPROFILE: home }), resolve(file));
27
- if (inside.startsWith("..") || isAbsolute(inside))
46
+ if (!env.VITEST || !inOwnerFolder(file, home))
28
47
  return;
29
48
  throw new Error(`a test tried to open ${file}, in the owner's real WireCat folder; give it a MESSAGING_STORE or HOME of its own`);
30
49
  };
@@ -0,0 +1,19 @@
1
+ import type { StoreContext } from "./open.js";
2
+ export interface ChatActivityCount {
3
+ /** A dialog has no title: it takes the name its other side last wrote under. */
4
+ title: string | null;
5
+ /** Muted now, until the mute runs out, as the query field `muted:` reads it. */
6
+ muted: boolean;
7
+ /** Live messages sent in the window, `until` exclusive. */
8
+ messages: number;
9
+ /** Of them, the owner's. */
10
+ sent: number;
11
+ /** The newest live message the store holds of the chat, in or before the window. */
12
+ lastAt: string | null;
13
+ }
14
+ /** The window of each chat is read once over `messages_by_time`, so a busy chat costs that chat, not the store. */
15
+ export declare const chatActivityCounts: ({ database }: StoreContext, chatKeys: readonly number[], { since, until, now }: {
16
+ since: number;
17
+ until: number;
18
+ now: number;
19
+ }) => Map<number, ChatActivityCount>;
@@ -0,0 +1,26 @@
1
+ import { MUTED_NOW } from "./reply-times.js";
2
+ import { toIso } from "./values.js";
3
+ const SQL = "SELECT coalesce(nullif(trim(c.title), ''), (SELECT sender_name FROM messages WHERE chat_id = c.id AND " +
4
+ "outgoing = 0 AND deleted_at IS NULL ORDER BY sent_at DESC LIMIT 1)) AS title, " +
5
+ `${MUTED_NOW} AS muted, w.messages, w.sent, ` +
6
+ "(SELECT max(sent_at) FROM messages WHERE chat_id = c.id AND deleted_at IS NULL AND sent_at < ?) AS last " +
7
+ "FROM chats c, (SELECT count(*) AS messages, coalesce(sum(outgoing = 1), 0) AS sent FROM messages " +
8
+ "WHERE chat_id = ? AND deleted_at IS NULL AND sent_at >= ? AND sent_at < ?) w WHERE c.id = ?";
9
+ /** The window of each chat is read once over `messages_by_time`, so a busy chat costs that chat, not the store. */
10
+ export const chatActivityCounts = ({ database }, chatKeys, { since, until, now }) => {
11
+ const statement = database.prepare(SQL);
12
+ const found = new Map();
13
+ for (const key of new Set(chatKeys)) {
14
+ const row = statement.get(now, until, key, since, until, key);
15
+ if (!row)
16
+ continue;
17
+ found.set(key, {
18
+ title: typeof row.title === "string" && row.title.trim() !== "" ? row.title : null,
19
+ muted: Number(row.muted) === 1,
20
+ messages: Number(row.messages),
21
+ sent: Number(row.sent),
22
+ lastAt: row.last == null ? null : (toIso(Number(row.last)) ?? null),
23
+ });
24
+ }
25
+ return found;
26
+ };
@@ -23,7 +23,17 @@ export interface PersonDoubt {
23
23
  evidence: string[];
24
24
  /** memo commands, after `memo`, that would take the doubted identities off; empty when none fits. */
25
25
  fix: string[];
26
+ /** The same moves as `fix`, one each, for an app that runs them without a command line. */
27
+ moves: DoubtMove[];
26
28
  }
29
+ /** Undo a merge, or move identities to one new person. */
30
+ export type DoubtMove = {
31
+ op: "unmerge";
32
+ merge: string;
33
+ } | {
34
+ op: "unlink";
35
+ identities: string[];
36
+ };
27
37
  export interface PersonDoubts {
28
38
  items: PersonDoubt[];
29
39
  total: number;
@@ -170,29 +170,30 @@ const everyDoubt = (database) => {
170
170
  * The owner's moves that take the doubted identities off: undoing a merge that brought only doubted ones, and one
171
171
  * unlink per name group of the rest, so two strangers on one person do not land on one new person together.
172
172
  */
173
- const fixOf = (context, found) => {
173
+ const movesOf = (context, found) => {
174
174
  if (found.reason === "test-data" || found.reason === "mixed-names")
175
175
  return [];
176
176
  const doubted = new Set(found.held.map(({ ref }) => ref));
177
- const commands = [];
177
+ const moves = [];
178
178
  const unmerged = new Set();
179
179
  for (const merge of merges(context, String(found.person))) {
180
180
  const refs = merge.identities.map(({ provider, id }) => `${provider}:${id}`);
181
181
  if (refs.length === 0 || !refs.every((ref) => doubted.has(ref)))
182
182
  continue;
183
- commands.push(`people unmerge ${merge.id}`);
183
+ moves.push({ op: "unmerge", merge: merge.id });
184
184
  for (const ref of refs)
185
185
  unmerged.add(ref);
186
186
  }
187
187
  const rest = found.held.filter(({ ref }) => !unmerged.has(ref));
188
188
  for (const group of nameGroups(rest))
189
- commands.push(`people unlink ${group.map(({ ref }) => shellWord(ref)).join(" ")}`);
190
- return commands;
189
+ moves.push({ op: "unlink", identities: group.map(({ ref }) => ref) });
190
+ return moves;
191
191
  };
192
+ const commandOf = (move) => move.op === "unmerge" ? `people unmerge ${move.merge}` : `people unlink ${move.identities.map(shellWord).join(" ")}`;
192
193
  /** A ref as one shell word: an id may hold a space or a quote, and the fix is pasted into a terminal. */
193
194
  const shellWord = (ref) => (/^[\w@.:+/=-]+$/u.test(ref) ? ref : `'${ref.replaceAll("'", "'\\''")}'`);
194
195
  const shown = (context, found) => {
195
- const fix = fixOf(context, found);
196
+ const moves = movesOf(context, found);
196
197
  return {
197
198
  person: `person:${found.person}`,
198
199
  name: found.name,
@@ -209,9 +210,10 @@ const shown = (context, found) => {
209
210
  evidence: [
210
211
  ...found.held.map(({ ref }) => ref),
211
212
  ...(found.address === undefined ? [] : [`email:${found.address}`]),
212
- ...fix.flatMap((command) => command.match(/merge:\d+-\d+/u) ?? []),
213
+ ...moves.flatMap((move) => (move.op === "unmerge" ? [move.merge] : [])),
213
214
  ],
214
- fix,
215
+ fix: moves.map(commandOf),
216
+ moves,
215
217
  };
216
218
  };
217
219
  /** People that may be wrong, a page at a time, each with why and the owner's moves that would set it right. */
@@ -1,4 +1,4 @@
1
- import { type RelationKind, type Standing } from "../../domain/relations.js";
1
+ import { type RelationKind, type RoleList, type Standing } from "../../domain/relations.js";
2
2
  import type { AccountKey } from "../types.js";
3
3
  import type { StoreContext } from "./open.js";
4
4
  import { type KnowledgeRelation } from "./relation-proposals.js";
@@ -35,6 +35,8 @@ export interface RelationListItem extends KnowledgeRelation {
35
35
  inverse?: string | null;
36
36
  /** A stored role off the list its ends take, such as one written before the lists. */
37
37
  custom: boolean;
38
+ /** The list `relationships roles list` offers for this role; `null` where it is free text. */
39
+ roleList: RoleList | null;
38
40
  }
39
41
  export interface RelationList {
40
42
  /** Relationships and pending relationship proposals, filtered and paged in one query (WC-CMD-20). */
@@ -1,11 +1,11 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { inverseOf, notOverriddenSql, RELATION_KINDS, rolesOf, STANDINGS, } from "../../domain/relations.js";
2
+ import { inverseOf, notOverriddenSql, RELATION_KINDS, ROLE_LISTS, roleListOf, STANDINGS, } from "../../domain/relations.js";
3
3
  import { linkKind } from "./link-kinds.js";
4
4
  import { idsOf } from "./merged-persons.js";
5
5
  import { linkOf } from "./notes.js";
6
6
  import { proposalOperationsOver } from "./proposed-actions.js";
7
7
  import { relationOf } from "./relation-proposals.js";
8
- import { extraRolesOf } from "./relation-roles.js";
8
+ import { ownerRolesOf } from "./relation-roles.js";
9
9
  import { thingOf } from "./things.js";
10
10
  const KINDS = RELATION_KINDS.map(linkKind).join(", ");
11
11
  /** The ends a relationship may have that belong to one account. */
@@ -113,17 +113,24 @@ export const relationListOver = (context) => {
113
113
  return { items, hasMore: rows.length > limit };
114
114
  },
115
115
  };
116
- function custom(kind, from, to, role) {
116
+ /** The list a relationship's role is offered from, and whether its role is off that list and the owner's own. */
117
+ function roleOf(kind, from, to, role) {
117
118
  const fromThing = thingOf(database, from);
118
119
  const toThing = thingOf(database, to);
119
- const roles = fromThing && toThing ? rolesOf(kind, fromThing.type, toThing.type) : undefined;
120
- if (role === null || roles === undefined || roles.includes(role) || !fromThing || !toThing)
121
- return false;
122
- return !extraRolesOf(database, kind, fromThing.type, toThing.type).includes(role);
120
+ const roleList = (fromThing && toThing && roleListOf(kind, fromThing.type, toThing.type)) || null;
121
+ const custom = role !== null &&
122
+ roleList !== null &&
123
+ !ROLE_LISTS[roleList].includes(role) &&
124
+ !ownerRolesOf(database, roleList).some(({ id }) => id === role);
125
+ return { roleList, custom };
123
126
  }
124
127
  function linkItem(id, at) {
125
128
  const relation = relationOf(linkOf(database, database.prepare("SELECT * FROM links WHERE id = ?").get(id)), at);
126
- return { ...relation, source: "link", custom: custom(relation.kind, relation.from, relation.to, relation.role) };
129
+ return {
130
+ ...relation,
131
+ source: "link",
132
+ ...roleOf(relation.kind, relation.from, relation.to, relation.role),
133
+ };
127
134
  }
128
135
  function proposalItem(id) {
129
136
  const action = operations.get(id);
@@ -148,7 +155,7 @@ export const relationListOver = (context) => {
148
155
  endsAt: iso(payload.endsAt),
149
156
  createdAt: action.createdAt,
150
157
  source: "proposal",
151
- custom: custom(payload.kind, payload.from, payload.to, payload.role ?? null),
158
+ ...roleOf(payload.kind, payload.from, payload.to, payload.role ?? null),
152
159
  };
153
160
  }
154
161
  };
@@ -1,9 +1,13 @@
1
+ import { type RoleLabels } from "../../domain/relation-role-labels.js";
1
2
  import { type RoleList } from "../../domain/relations.js";
2
3
  import type { CacheDatabase } from "../driver.js";
3
4
  import type { StoreContext } from "./open.js";
4
5
  export interface RelationRole {
5
6
  id: string;
7
+ /** The owner's own word for his role; a built-in one has none and reads by `labels`. */
6
8
  label: string | null;
9
+ /** A built-in role in English, Russian and Spanish; `null` for the owner's own. */
10
+ labels: RoleLabels | null;
7
11
  builtIn: boolean;
8
12
  }
9
13
  export interface RelationRoles {
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { ROLE_LABELS } from "../../domain/relation-role-labels.js";
2
3
  import { checkRole, ROLE_LISTS, roleListOf } from "../../domain/relations.js";
3
4
  import { write } from "./transaction.js";
4
5
  const settingOf = (list) => `relationships.roles.${list}`;
@@ -29,19 +30,27 @@ export const extraRolesOf = (database, kind, from, to) => {
29
30
  /** `checkRole` with the owner's own roles for the list the ends take. */
30
31
  export const checkStoredRole = (database, kind, from, to, role) => checkRole(kind, from, to, role, extraRolesOf(database, kind, from, to));
31
32
  /** The `related-to` links whose role comes from a list, by the types that name it. */
32
- const RELATED_FROM = { deal: "'deal', 'lead'", contract: "'contract'" };
33
+ const RELATED_FROM = {
34
+ deal: "'deal', 'lead'",
35
+ contract: "'contract'",
36
+ related: "'person', 'organization'",
37
+ };
33
38
  /**
34
39
  * The links whose role comes from this list: a person's on an organization or a project, a deal's or a lead's people,
35
40
  * a contract's parties.
36
41
  */
37
42
  const usedBy = (database, list, role) => {
38
43
  const related = RELATED_FROM[list];
44
+ const parties = list === "related";
39
45
  const links = related
40
- ? `kind = 'related-to' AND from_type IN (${related})`
46
+ ? `kind = 'related-to' AND from_type IN (${related})${parties ? ` AND to_type IN (${related})` : ""}`
41
47
  : `kind = 'member-of' AND from_type = 'person' AND to_type = '${list}'`;
42
48
  // A pending proposal would make the role a relationship's once approved: it counts as a use.
43
49
  const proposals = related
44
- ? `target_type IN (${related}) AND json_extract(payload, '$.kind') = 'related-to'`
50
+ ? `target_type IN (${related}) AND json_extract(payload, '$.kind') = 'related-to'` +
51
+ (parties
52
+ ? " AND (json_extract(payload, '$.to') LIKE 'person:%' OR json_extract(payload, '$.to') LIKE 'organization:%')"
53
+ : "")
45
54
  : `target_type = 'person' AND json_extract(payload, '$.kind') = 'member-of' AND json_extract(payload, '$.to') LIKE '${list}:%'`;
46
55
  return Number(database
47
56
  .prepare(`SELECT (SELECT count(*) FROM links WHERE role = ? AND deleted_at IS NULL AND ${links}) + (SELECT count(*) FROM proposed_actions ` +
@@ -51,8 +60,13 @@ const usedBy = (database, list, role) => {
51
60
  };
52
61
  export const relationRolesOver = ({ database, now }) => {
53
62
  const all = (list) => [
54
- ...ROLE_LISTS[list].map((id) => ({ id, label: null, builtIn: true })),
55
- ...ownerRolesOf(database, list).map((role) => ({ ...role, builtIn: false })),
63
+ ...ROLE_LISTS[list].map((id) => ({
64
+ id,
65
+ label: null,
66
+ labels: ROLE_LABELS[list][id],
67
+ builtIn: true,
68
+ })),
69
+ ...ownerRolesOf(database, list).map((role) => ({ ...role, labels: null, builtIn: false })),
56
70
  ];
57
71
  const save = (list, roles) => database
58
72
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
@@ -31,6 +31,8 @@ export interface NewestMessage {
31
31
  /** Muted or archived, and not marked unread: what `inbox` leaves out. */
32
32
  quiet: boolean;
33
33
  }
34
+ /** Muted now, until the mute runs out; one bound parameter, now. */
35
+ export declare const MUTED_NOW = "(coalesce(c.muted,0)=1 AND (c.muted_until IS NULL OR c.muted_until>?))";
34
36
  /**
35
37
  * 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
36
38
  * period, so a reply early in the period is timed from the first message it answers, however old.
@@ -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 MUTED_NOW = "(coalesce(c.muted,0)=1 AND (c.muted_until IS NULL OR c.muted_until>?))";
4
+ /** Muted now, until the mute runs out; one bound parameter, now. */
5
+ export const MUTED_NOW = "(coalesce(c.muted,0)=1 AND (c.muted_until IS NULL OR c.muted_until>?))";
5
6
  const chatsIn = (scope, kinds, now) => {
6
7
  const params = [...scope.accounts.flatMap(({ provider, account }) => [provider, account]), ...kinds];
7
8
  const parts = [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.632.0",
3
+ "version": "0.634.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",
package/parity.json CHANGED
@@ -4878,6 +4878,9 @@
4878
4878
  "store gaps show": {
4879
4879
  "in": "all"
4880
4880
  },
4881
+ "store import": {
4882
+ "in": "all"
4883
+ },
4881
4884
  "store info": {
4882
4885
  "in": "all"
4883
4886
  },