@wirecat/cli-core 0.631.0 → 0.633.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/dist/calendar/mcp/index.d.ts +12 -12
  3. package/dist/cli/messenger/archive-commands.js +4 -1
  4. package/dist/cli/messenger/context.d.ts +2 -0
  5. package/dist/cli/messenger/reply-stats-command.js +1 -1
  6. package/dist/cli/messenger/serve-relay.d.ts +1 -0
  7. package/dist/cli/messenger/stats-answers.d.ts +5 -2
  8. package/dist/cli/messenger/stats-answers.js +8 -2
  9. package/dist/cli/messenger/store-import-command.d.ts +4 -0
  10. package/dist/cli/messenger/store-import-command.js +166 -0
  11. package/dist/cli/messenger/stored.d.ts +7 -1
  12. package/dist/cli/messenger/stored.js +1 -1
  13. package/dist/cli/messenger/tasks-command.js +5 -3
  14. package/dist/domain/test-data.d.ts +15 -0
  15. package/dist/domain/test-data.js +18 -0
  16. package/dist/entities/chat-stats.d.ts +2 -0
  17. package/dist/entities/chat-stats.js +2 -0
  18. package/dist/entities/index.d.ts +18 -2
  19. package/dist/entities/index.js +3 -2
  20. package/dist/entities/store-maintenance.d.ts +16 -0
  21. package/dist/entities/store-maintenance.js +10 -0
  22. package/dist/errors/reasons.js +9 -0
  23. package/dist/kit/seed.js +6 -7
  24. package/dist/search/lucene/registry.js +11 -0
  25. package/dist/sends/permissions.js +1 -0
  26. package/dist/services/proposals/kinds/identity-split.d.ts +4 -0
  27. package/dist/services/proposals/kinds/identity-split.js +65 -0
  28. package/dist/services/proposals/registry.js +2 -0
  29. package/dist/services/reply-stats.js +11 -3
  30. package/dist/services/task-stats.d.ts +7 -2
  31. package/dist/services/task-stats.js +53 -20
  32. package/dist/services/tasks.d.ts +1 -0
  33. package/dist/services/tasks.js +16 -4
  34. package/dist/store/decisions.js +3 -1
  35. package/dist/store/drivers/bun-sqlite.js +2 -0
  36. package/dist/store/drivers/node-sqlite.js +2 -0
  37. package/dist/store/identity-splits.d.ts +60 -0
  38. package/dist/store/identity-splits.js +5 -0
  39. package/dist/store/index.d.ts +2 -0
  40. package/dist/store/index.js +2 -0
  41. package/dist/store/path.d.ts +3 -0
  42. package/dist/store/path.js +25 -6
  43. package/dist/store/people.d.ts +23 -0
  44. package/dist/store/people.js +6 -0
  45. package/dist/store/sqlite/accounts.js +4 -0
  46. package/dist/store/sqlite/crm-contacts.js +5 -1
  47. package/dist/store/sqlite/identity-link-rows.d.ts +5 -0
  48. package/dist/store/sqlite/identity-link-rows.js +5 -3
  49. package/dist/store/sqlite/identity-split-proposals.d.ts +29 -0
  50. package/dist/store/sqlite/identity-split-proposals.js +195 -0
  51. package/dist/store/sqlite/lucene-fields.js +3 -0
  52. package/dist/store/sqlite/person-doubts.d.ts +36 -0
  53. package/dist/store/sqlite/person-doubts.js +229 -0
  54. package/dist/store/sqlite/proposed-actions.js +6 -0
  55. package/dist/store/sqlite/reply-times.d.ts +3 -1
  56. package/dist/store/sqlite/reply-times.js +11 -6
  57. package/package.json +1 -1
  58. package/parity.json +3 -0
@@ -85,7 +85,7 @@ import { responseTimes, waitingChats } from "./reply-stats.js";
85
85
  import { retention } from "./retention.js";
86
86
  import { savedSearch, searchHistoryClear } from "./saved-search.js";
87
87
  import { sendAttempt } from "./send-attempt.js";
88
- import { storeBackup, storeCheck, storeCopyRemoval, storeDecrypt, storeInfo, storeMigration, storeReindex, storeRepair, storeReset, storeRestore, } from "./store-maintenance.js";
88
+ import { storeBackup, storeCheck, storeCopyRemoval, storeDecrypt, storeImport, storeInfo, storeMigration, storeReindex, storeRepair, storeReset, storeRestore, } from "./store-maintenance.js";
89
89
  import { chatCoverage, storeChatStatus, storeClear, storeExport, storeGapPlan, storeGapRepair, storeJobCancel, storeJobClear, storeJobDetails, storeJobRetry, syncProgress, } from "./store-records.js";
90
90
  import { storeTable } from "./store-table.js";
91
91
  import { automaticTags, tagChange } from "./tag-change.js";
@@ -100,7 +100,7 @@ import { topic } from "./topic.js";
100
100
  * subset of its fields, never a renamed one. Commands move onto these one by one; until then, a schema
101
101
  * is the target, not a description of today's output.
102
102
  */
103
- export { account, accountChange, accountPrivacy, accountPrivacyChange, accountProfile, accountSession, adminReport, agenda, analysisConsent, analysisConsentRevocation, attachment, attachmentBytes, attachmentExtraction, attachmentTextChange, automaticTags, botAdmin, botMenuEntry, botProfile, botSeenChat, botTemplate, botWebhook, cachedChatMetadata, callRecord, chart, chat, chatAdminChange, chatArchive, chatCoverage, chatEvent, chatFolderChange, chatFolderOrder, chatFolderRemoval, chatGroupChange, chatInspection, chatInvite, chatInviteChange, chatMembersChange, chatMembersFetch, chatMetadata, chatMetadataRefresh, chatModeration, chatMuting, chatPin, chatRead, chatRemoval, chatRequestChange, chatRules, chatSender, chatStats, chatTracking, chatUnread, contact, contactActivity, contactAlias, contactCheck, contactContext, contactImport, contactLookup, contactNote, contactNoteRemoval, contactPreparation, contactStateChange, contactSync, contactUpdate, conversation, conversationBatch, conversationBatchStatus, conversationBuildResult, conversationChange, conversationDetails, conversationEmbedding, conversationEmbeddingStatus, conversationHit, conversationPreparation, conversationReadiness, counterRefresh, counters, document, documentLink, endedAccountSessions, evidence, evidencePacket, fact, folder, hit, identity, imageEmbedding, inviteLink, job, joinRequest, linkedPerson, mailCounts, mediaArchive, mediaArchiveCheck, mediaArchiveMove, mediaArchiveTimer, meeting, meetingProjectCandidates, meetingSeriesInventory, member, memory, mention, mentionDecision, mentionDetails, mentionDomain, mentionRebuild, message, messageContext, messageCounts, messageDeletion, messageDownload, messageEvent, messageLink, messageLinks, messagePin, messageStar, messageSync, messageTranscript, messageWrite, model, modelKey, note, officialStats, organization, person, place, poll, pollChange, pollVote, project, ranking, reaction, reactionChange, recipient, recipientAdded, recipientChange, recipientOff, recipientRemoved, recordedRun, reference, relationship, reminder, removedModelKey, responseTimes, retention, runDetails, runHit, runLocation, savedSearch, scheduledJob, searchHistoryClear, sendAttempt, serveSummary, stickerInventory, storeBackup, storeChatStatus, storeCheck, storeClear, storeCopyRemoval, storeDecrypt, storedModelKey, storeExport, storeGapPlan, storeGapRepair, storeInfo, storeJobCancel, storeJobClear, storeJobDetails, storeJobRetry, storeMigration, storeReindex, storeRepair, storeReset, storeRestore, storeTable, tagChange, tagging, task, taskAnalysis, taskAnalysisMark, taskCard, taskCategories, taskClosed, taskCreated, taskLinks, taskMerge, taskPair, taskScan, taskSimilar, taskStats, taskUnmerge, template, topic, topicIcon, trackedChat, trackedChatHistory, waitingChats, watchedMessage, watchItem, };
103
+ export { account, accountChange, accountPrivacy, accountPrivacyChange, accountProfile, accountSession, adminReport, agenda, analysisConsent, analysisConsentRevocation, attachment, attachmentBytes, attachmentExtraction, attachmentTextChange, automaticTags, botAdmin, botMenuEntry, botProfile, botSeenChat, botTemplate, botWebhook, cachedChatMetadata, callRecord, chart, chat, chatAdminChange, chatArchive, chatCoverage, chatEvent, chatFolderChange, chatFolderOrder, chatFolderRemoval, chatGroupChange, chatInspection, chatInvite, chatInviteChange, chatMembersChange, chatMembersFetch, chatMetadata, chatMetadataRefresh, chatModeration, chatMuting, chatPin, chatRead, chatRemoval, chatRequestChange, chatRules, chatSender, chatStats, chatTracking, chatUnread, contact, contactActivity, contactAlias, contactCheck, contactContext, contactImport, contactLookup, contactNote, contactNoteRemoval, contactPreparation, contactStateChange, contactSync, contactUpdate, conversation, conversationBatch, conversationBatchStatus, conversationBuildResult, conversationChange, conversationDetails, conversationEmbedding, conversationEmbeddingStatus, conversationHit, conversationPreparation, conversationReadiness, counterRefresh, counters, document, documentLink, endedAccountSessions, evidence, evidencePacket, fact, folder, hit, identity, imageEmbedding, inviteLink, job, joinRequest, linkedPerson, mailCounts, mediaArchive, mediaArchiveCheck, mediaArchiveMove, mediaArchiveTimer, meeting, meetingProjectCandidates, meetingSeriesInventory, member, memory, mention, mentionDecision, mentionDetails, mentionDomain, mentionRebuild, message, messageContext, messageCounts, messageDeletion, messageDownload, messageEvent, messageLink, messageLinks, messagePin, messageStar, messageSync, messageTranscript, messageWrite, model, modelKey, note, officialStats, organization, person, place, poll, pollChange, pollVote, project, ranking, reaction, reactionChange, recipient, recipientAdded, recipientChange, recipientOff, recipientRemoved, recordedRun, reference, relationship, reminder, removedModelKey, responseTimes, retention, runDetails, runHit, runLocation, savedSearch, scheduledJob, searchHistoryClear, sendAttempt, serveSummary, stickerInventory, storeBackup, storeChatStatus, storeCheck, storeClear, storeCopyRemoval, storeDecrypt, storedModelKey, storeExport, storeGapPlan, storeGapRepair, storeImport, storeInfo, storeJobCancel, storeJobClear, storeJobDetails, storeJobRetry, storeMigration, storeReindex, storeRepair, storeReset, storeRestore, storeTable, tagChange, tagging, task, taskAnalysis, taskAnalysisMark, taskCard, taskCategories, taskClosed, taskCreated, taskLinks, taskMerge, taskPair, taskScan, taskSimilar, taskStats, taskUnmerge, template, topic, topicIcon, trackedChat, trackedChatHistory, waitingChats, watchedMessage, watchItem, };
104
104
  export const ENTITIES = {
105
105
  sync_progress: syncProgress,
106
106
  deal,
@@ -327,6 +327,7 @@ export const ENTITIES = {
327
327
  store_decrypt: storeDecrypt,
328
328
  store_restore: storeRestore,
329
329
  store_reset: storeReset,
330
+ store_import: storeImport,
330
331
  store_repair: storeRepair,
331
332
  store_copy_removal: storeCopyRemoval,
332
333
  store_table: storeTable,
@@ -362,6 +362,22 @@ export declare const storeRestore: v.UnionSchema<[v.StrictObjectSchema<{
362
362
  readonly rebuilt: v.ArraySchema<v.StringSchema<undefined>, undefined>;
363
363
  readonly foreign_key_violations: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
364
364
  }, undefined>], undefined>;
365
+ /** Made-up data for a test store: what the file holds and, once loaded, what it added to the account. */
366
+ export declare const storeImport: v.StrictObjectSchema<{
367
+ readonly store: v.StringSchema<undefined>;
368
+ readonly profile: v.StringSchema<undefined>;
369
+ readonly account: v.StringSchema<undefined>;
370
+ readonly imported: v.BooleanSchema<undefined>;
371
+ readonly file: v.StrictObjectSchema<{
372
+ readonly chats: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
373
+ readonly people: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
374
+ readonly messages: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
375
+ }, undefined>;
376
+ readonly added: v.OptionalSchema<v.StrictObjectSchema<{
377
+ readonly chats: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
378
+ readonly messages: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
379
+ }, undefined>, undefined>;
380
+ }, undefined>;
365
381
  export declare const storeReset: v.UnionSchema<[v.StrictObjectSchema<{
366
382
  readonly path: v.StringSchema<undefined>;
367
383
  readonly exists: v.LiteralSchema<false, undefined>;
@@ -174,6 +174,16 @@ export const storeRestore = v.union([
174
174
  foreign_key_violations: count,
175
175
  }),
176
176
  ]);
177
+ const importCounts = v.strictObject({ chats: count, messages: count });
178
+ /** Made-up data for a test store: what the file holds and, once loaded, what it added to the account. */
179
+ export const storeImport = v.strictObject({
180
+ store: text,
181
+ profile: text,
182
+ account: text,
183
+ imported: v.boolean(),
184
+ file: v.strictObject({ chats: count, people: count, messages: count }),
185
+ added: v.optional(importCounts),
186
+ });
177
187
  export const storeReset = v.union([
178
188
  v.strictObject({ ...absent.entries, reset: v.literal(false) }),
179
189
  v.strictObject({
@@ -391,6 +391,14 @@ const OTHERS = [
391
391
  "conflict",
392
392
  "the people a merge or a proposed link names changed since; undo the later merge, or propose the link again",
393
393
  ],
394
+ ["identity.no-merge", "not_found", "nothing of that person is merged into the other; people show lists the merges"],
395
+ validation("identity.several-persons", "the identities that leave a person are all of that one person"),
396
+ validation("identity.nothing-left", "a split leaves at least one identity with the person"),
397
+ [
398
+ "identity.kept-together",
399
+ "conflict",
400
+ "the owner kept these identities together by turning down their split; only the owner splits them",
401
+ ],
394
402
  [
395
403
  "identity.rejected",
396
404
  "conflict",
@@ -402,6 +410,7 @@ const OTHERS = [
402
410
  validation("identity.owner", "one side is the owner's person, and only the owner joins anyone to themselves"),
403
411
  validation("identity.shared-email", "more than six people share the address, so it proposes no one"),
404
412
  validation("identity-link.dedicated-review", "an identity link is staged and decided through the people review"),
413
+ validation("identity-split.dedicated-review", "a split of a person is staged and decided through the people review"),
405
414
  ["transcription.no-key", "authentication_error", "no OpenAI key is set for transcription"],
406
415
  validation("transcription.too-large", "the audio is over the transcription provider's size limit"),
407
416
  [
package/dist/kit/seed.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { SEED_PEOPLE } from "../domain/test-data.js";
1
2
  export const BUSY_PAGE = 3;
2
3
  const BUSY_MESSAGES = 10;
3
4
  /** Ids that are not numbers, so no code may take them for one. */
@@ -12,15 +13,13 @@ const START = Date.parse("2026-09-01T09:00:00.000Z");
12
13
  */
13
14
  export const contractSeed = ({ ids = wordIds, loggedIn = true } = {}) => {
14
15
  const at = (minute) => new Date(START + minute * 60_000);
15
- const owner = {
16
- id: ids("person", 1, at(0)),
17
- name: "Owner",
18
- username: "owner",
16
+ const [owner, ann, bob] = SEED_PEOPLE.map(({ name, username }, index) => ({
17
+ id: ids("person", index + 1, at(0)),
18
+ name,
19
+ username,
19
20
  description: null,
20
21
  lastMessagedAt: null,
21
- };
22
- const ann = { ...owner, id: ids("person", 2, at(0)), name: "Ann Lee", username: "ann" };
23
- const bob = { ...owner, id: ids("person", 3, at(0)), name: "Bob Ray", username: null };
22
+ }));
24
23
  let messageNumber = 0;
25
24
  const message = (chatId, minute, from, text) => {
26
25
  messageNumber += 1;
@@ -189,6 +189,17 @@ export const QUERY_FIELDS = [
189
189
  support: "A1",
190
190
  values: ["private", "saved", "bot", "service", "group", "channel", "unknown"],
191
191
  },
192
+ {
193
+ name: "muted",
194
+ example: "muted:false",
195
+ index: "chats.muted / chats.muted_until",
196
+ aliases: [],
197
+ type: "enum",
198
+ operators: terms,
199
+ normalization: "lowercase; true is a chat the owner muted, until the mute runs out; false is every other chat",
200
+ support: "A1",
201
+ values: ["true", "false"],
202
+ },
192
203
  {
193
204
  name: "has",
194
205
  example: "has:file",
@@ -24,6 +24,7 @@ export const DEFAULT_PERMISSIONS = {
24
24
  "store.migrate": "ask",
25
25
  "store.repair": "ask",
26
26
  "store.reset": "ask",
27
+ "store.import": "ask",
27
28
  "store.clear": "ask",
28
29
  "store.decrypt": "ask",
29
30
  "store.copies.delete": "ask",
@@ -0,0 +1,4 @@
1
+ import type { MessageStore } from "../../../store/index.js";
2
+ import type { ProposalKind } from "../types.js";
3
+ /** Identities that may not belong to their person; only the owner takes them off. */
4
+ export declare const identitySplitKind: (store: Pick<MessageStore, "people" | "proposedActions">) => ProposalKind;
@@ -0,0 +1,65 @@
1
+ import { IDENTITY_SPLIT_KIND, proposerOfAction } from "../../../store/index.js";
2
+ import { actionStatus, kept, pushed, storedStatus } from "./shared.js";
3
+ const summaryOf = (payload, person) => payload.split === "unmerge"
4
+ ? `undo ${payload.merge}: ${payload.identities.join(", ")} go back to their own person`
5
+ : `${payload.identities.join(", ")} may not be ${person}: they would move to a person of their own`;
6
+ /** An older build approved it as a plain action and split nothing: it shows as turned down, not as done. */
7
+ const dropped = (action) => action.status !== "proposed" &&
8
+ action.status !== "rejected" &&
9
+ typeof action.result?.person !== "string";
10
+ const rowOf = (store) => async (action) => {
11
+ const payload = action.payload;
12
+ const [first] = payload.identities;
13
+ const now = first === undefined
14
+ ? undefined
15
+ : await store.people.personOf({
16
+ provider: first.slice(0, first.indexOf(":")),
17
+ id: first.slice(first.indexOf(":") + 1),
18
+ });
19
+ const person = `person:${now?.uid ?? payload.person}`;
20
+ const summary = summaryOf(payload, person);
21
+ return {
22
+ id: action.id,
23
+ kind: IDENTITY_SPLIT_KIND,
24
+ status: dropped(action) ? "rejected" : actionStatus(action.status),
25
+ project: null,
26
+ subject: person,
27
+ object: null,
28
+ summary: dropped(action)
29
+ ? `not carried out: an older version approved it without splitting; ${summary}`
30
+ : summary,
31
+ proposedBy: proposerOfAction(action),
32
+ reason: action.reason,
33
+ evidence: payload.evidence.slice(0, 5),
34
+ score: null,
35
+ signals: null,
36
+ parts: null,
37
+ createdAt: action.createdAt,
38
+ };
39
+ };
40
+ /** Identities that may not belong to their person; only the owner takes them off. */
41
+ export const identitySplitKind = (store) => ({
42
+ kind: IDENTITY_SPLIT_KIND,
43
+ stored: [IDENTITY_SPLIT_KIND],
44
+ ownerOnly: true,
45
+ list: async (filter) => {
46
+ const status = storedStatus(filter);
47
+ const stored = await store.proposedActions.list({
48
+ kinds: [IDENTITY_SPLIT_KIND],
49
+ ...(status === undefined ? {} : { status }),
50
+ ...pushed(filter),
51
+ });
52
+ return kept(await Promise.all(stored.map(rowOf(store))), filter);
53
+ },
54
+ get: async (id) => rowOf(store)(await store.proposedActions.get(id)),
55
+ decide: async (id, { confirm, by, reason }) => {
56
+ const decided = await store.people.decideSplit(id, { confirm, by, ...(reason === undefined ? {} : { reason }) });
57
+ const person = decided.result?.person;
58
+ return {
59
+ id,
60
+ kind: IDENTITY_SPLIT_KIND,
61
+ status: confirm ? "confirmed" : "rejected",
62
+ made: person === undefined ? [] : [`person:${person}`],
63
+ };
64
+ },
65
+ });
@@ -6,6 +6,7 @@ import { factKind } from "./kinds/fact.js";
6
6
  import { invoiceKind, paymentKind } from "./kinds/finance.js";
7
7
  import { findingsKind } from "./kinds/findings.js";
8
8
  import { identityLinkKind } from "./kinds/identity-link.js";
9
+ import { identitySplitKind } from "./kinds/identity-split.js";
9
10
  import { keyDocumentKind } from "./kinds/key-document.js";
10
11
  import { mailFindingsKind } from "./kinds/mail-findings.js";
11
12
  import { meetingFindingsKind } from "./kinds/meeting-findings.js";
@@ -154,6 +155,7 @@ export const proposalRegistry = (store) => {
154
155
  taskCloseKind(store),
155
156
  sourceReviewKind(store),
156
157
  identityLinkKind(store),
158
+ identitySplitKind(store),
157
159
  ])
158
160
  registry.register(kind);
159
161
  registry.register(actionKind(store, registry.claimed));
@@ -5,15 +5,15 @@ import { calendarKey } from "../domain/calendar.js";
5
5
  import { rankingQuestion } from "../domain/rankings-options.js";
6
6
  import { MESSAGE_PARSING } from "../search/lucene/types.js";
7
7
  import { prepareLucene } from "./messages-search.js";
8
- const FIELDS = ["date", "chat", "kind"];
8
+ const FIELDS = ["date", "chat", "kind", "muted"];
9
9
  /** Per waiting chat, how far back its unanswered messages are counted. */
10
10
  export const WAITING_TAIL = 100;
11
- /** Only AND-ed `date:`, `chat:` and `kind:` terms: each becomes an index bound, so no query reads every message. */
11
+ /** Only AND-ed `date:`, `chat:`, `kind:` and `muted:` terms: each becomes an index bound, so no query reads every message. */
12
12
  const plainOnly = (text, command) => {
13
13
  if (text === undefined)
14
14
  return;
15
15
  const refuse = () => {
16
- throw new CliError("validation_error", `${command} reads date:, chat: and kind: terms, AND-ed — not words, other fields, OR or NOT`, { reason: "query.unsupported-field" });
16
+ throw new CliError("validation_error", `${command} reads date:, chat:, kind: and muted: terms, AND-ed — not words, other fields, OR or NOT`, { reason: "query.unsupported-field" });
17
17
  };
18
18
  const visit = (node) => {
19
19
  if (node.kind === "boolean")
@@ -40,6 +40,14 @@ const scopeOf = (root, accounts) => {
40
40
  scope.chats.push(chat);
41
41
  else if (node.field === "kind")
42
42
  scope.kinds.push(node.value.toLowerCase());
43
+ else if (node.field === "muted") {
44
+ const muted = node.value.toLowerCase() === "true";
45
+ if (scope.muted !== undefined && scope.muted !== muted)
46
+ throw new CliError("validation_error", "muted:true and muted:false cannot both hold", {
47
+ reason: "query.conflict",
48
+ });
49
+ scope.muted = muted;
50
+ }
43
51
  else if (date) {
44
52
  if (date.lower !== undefined) {
45
53
  const lower = date.lower + (date.lower_inclusive ? 0 : 1);
@@ -17,6 +17,8 @@ export interface TaskStatsRequest {
17
17
  export interface TaskStatsGroup {
18
18
  /** The stored chat id, `meeting:<account>/<meeting>`, or the project's store id. */
19
19
  group: string;
20
+ /** The group's account, when the answer reads several. */
21
+ account?: AccountKey;
20
22
  name: string | null;
21
23
  open: number;
22
24
  created: number;
@@ -27,6 +29,8 @@ export interface TaskStatsGroup {
27
29
  }
28
30
  export interface TaskStats {
29
31
  by: TaskStatsBy;
32
+ /** Every account read, when the answer reads several. */
33
+ accounts?: AccountKey[];
30
34
  open: number;
31
35
  created: number;
32
36
  closed: number;
@@ -36,6 +40,7 @@ export interface TaskStats {
36
40
  }
37
41
  /**
38
42
  * `stats tasks show`: `open` is open now, `created` the tasks opened in the period, `closed` those closed in it; the
39
- * other terms of the query narrow all three. `columns` reads the task query's fields on the row `t`.
43
+ * other terms of the query narrow all three. `columns` reads the task query's fields on the row `t`. Given several
44
+ * accounts it reads each one's tasks and counts them together; every row then names its account.
40
45
  */
41
- export declare const taskStatsOf: (store: MessageStore, account: AccountKey, { by, query, timezone, group, kind }: TaskStatsRequest, columns: ColumnMap, now?: number) => Promise<TaskStats>;
46
+ export declare const taskStatsOf: (store: MessageStore, accounts: AccountKey | readonly AccountKey[], { by, query, timezone, group, kind }: TaskStatsRequest, columns: ColumnMap, now?: number) => Promise<TaskStats>;
@@ -42,11 +42,16 @@ const and = (parts) => parts.length === 0
42
42
  : { sql: parts.map(({ sql }) => `(${sql})`).join(" AND "), params: parts.flatMap(({ params }) => params) };
43
43
  /**
44
44
  * `stats tasks show`: `open` is open now, `created` the tasks opened in the period, `closed` those closed in it; the
45
- * other terms of the query narrow all three. `columns` reads the task query's fields on the row `t`.
45
+ * other terms of the query narrow all three. `columns` reads the task query's fields on the row `t`. Given several
46
+ * accounts it reads each one's tasks and counts them together; every row then names its account.
46
47
  */
47
- export const taskStatsOf = async (store, account, { by = "chat", query, timezone, group, kind }, columns, now = Date.now()) => {
48
+ export const taskStatsOf = async (store, accounts, { by = "chat", query, timezone, group, kind }, columns, now = Date.now()) => {
48
49
  if (query)
49
50
  refuseNestedPeriod(query.root);
51
+ const several = Array.isArray(accounts);
52
+ const list = several
53
+ ? [...new Map(accounts.map((one) => [taskAccount(one), one])).values()]
54
+ : [accounts];
50
55
  const time = (sql) => ({ type: "time", sql });
51
56
  const read = { ...columns, [PERIOD_FIELD]: time("t.created_at"), closed: time("t.closed_at") };
52
57
  const fixed = [
@@ -56,17 +61,30 @@ export const taskStatsOf = async (store, account, { by = "chat", query, timezone
56
61
  ];
57
62
  const options = { command: "stats tasks show", now, ...(timezone === undefined ? {} : { zone: timezone }) };
58
63
  const where = (ast, more = []) => and([...fixed, ...more, ...(ast ? [queryFilter(ast, read, options)] : [])]);
59
- const scope = by === "project" ? { board: true } : { account: taskAccount(account) };
60
- const all = await store.tasks.statRows(scope, where(withoutField(query, PERIOD_FIELD)));
61
- const created = await store.tasks.statRows(scope, where(query));
62
- const closed = await store.tasks.statRows(scope, where(query && { ...query, root: renamed(query.root, PERIOD_FIELD, "closed") }, [
64
+ // Project tasks belong to no account: one board read, whatever the accounts.
65
+ const scopes = by === "project"
66
+ ? [{ scope: { board: true } }]
67
+ : list.map((one) => ({ account: one, scope: { account: taskAccount(one) } }));
68
+ const rowsOf = async (filter) => (await Promise.all(scopes.map(async ({ account, scope }) => (await store.tasks.statRows(scope, filter)).map((row) => (account ? { ...row, account } : row))))).flat();
69
+ const all = await rowsOf(where(withoutField(query, PERIOD_FIELD)));
70
+ const created = await rowsOf(where(query));
71
+ const closed = await rowsOf(where(query && { ...query, root: renamed(query.root, PERIOD_FIELD, "closed") }, [
63
72
  { sql: "t.closed_at IS NOT NULL", params: [] },
64
73
  ]));
65
- const keyOf = (row) => (by === "project" ? String(row.projectId) : (row.group ?? ""));
74
+ // Chat ids repeat across accounts, so a row is one account's chat.
75
+ const keyOf = (row) => by === "project" ? String(row.projectId) : `${row.account ? taskAccount(row.account) : ""}\t${row.group ?? ""}`;
66
76
  const groups = new Map();
67
77
  const slot = (row) => {
68
78
  const key = keyOf(row);
69
- const found = groups.get(key) ?? { open: [], created: 0, closeMs: [] };
79
+ const found = groups.get(key) ?? {
80
+ group: by === "project" ? String(row.projectId) : (row.group ?? ""),
81
+ ...(row.account ? { account: row.account } : {}),
82
+ first: row.createdAt,
83
+ open: [],
84
+ created: 0,
85
+ closeMs: [],
86
+ };
87
+ found.first = Math.min(found.first, row.createdAt);
70
88
  groups.set(key, found);
71
89
  return found;
72
90
  };
@@ -77,26 +95,26 @@ export const taskStatsOf = async (store, account, { by = "chat", query, timezone
77
95
  slot(row).created++;
78
96
  for (const row of closed)
79
97
  slot(row).closeMs.push((row.closedAt ?? row.createdAt) - row.createdAt);
80
- const kept = [...groups].filter(([, one]) => one.open.length + one.created + one.closeMs.length > 0);
81
- const ids = kept.map(([key]) => key);
82
- const names = by === "chat"
83
- ? await store.tasks.statNames("chat", ids, taskAccount(account))
84
- : by === "project"
85
- ? await store.tasks.statNames("project", ids)
86
- : await meetingNames(store, ids);
87
- const rows = kept.map(([key, one]) => ({
88
- group: key,
89
- name: names.get(key) ?? null,
98
+ const kept = [...groups.values()].filter((one) => one.open.length + one.created + one.closeMs.length > 0);
99
+ // Each account's rows come oldest first; across accounts the groups are put back in that order.
100
+ if (several)
101
+ kept.sort((a, b) => a.first - b.first);
102
+ const nameOf = await namesOf(store, by, kept);
103
+ const rows = kept.map((one) => ({
104
+ group: one.group,
105
+ ...(several && one.account ? { account: one.account } : {}),
106
+ name: nameOf(one) ?? null,
90
107
  open: one.open.length,
91
108
  created: one.created,
92
109
  closed: one.closeMs.length,
93
110
  ...(one.open[0] ? { oldestOpenAt: new Date(one.open[0].createdAt) } : {}),
94
111
  ...spread(one.open, one.closeMs, now),
95
112
  }));
96
- const open = kept.flatMap(([, one]) => one.open);
97
- const closeMs = kept.flatMap(([, one]) => one.closeMs);
113
+ const open = kept.flatMap((one) => one.open);
114
+ const closeMs = kept.flatMap((one) => one.closeMs);
98
115
  return {
99
116
  by,
117
+ ...(several ? { accounts: [...list] } : {}),
100
118
  open: open.length,
101
119
  created: created.length,
102
120
  closed: closeMs.length,
@@ -104,6 +122,21 @@ export const taskStatsOf = async (store, account, { by = "chat", query, timezone
104
122
  rows,
105
123
  };
106
124
  };
125
+ /** Each group's title: chats within their own account, meetings and projects by their store id. */
126
+ const namesOf = async (store, by, groups) => {
127
+ if (by === "project") {
128
+ const names = await store.tasks.statNames("project", groups.map(({ group }) => group));
129
+ return ({ group }) => names.get(group);
130
+ }
131
+ if (by === "meeting") {
132
+ const names = await meetingNames(store, groups.map(({ group }) => group));
133
+ return ({ group }) => names.get(group);
134
+ }
135
+ const byAccount = new Map();
136
+ for (const account of new Set(groups.flatMap(({ account }) => (account ? [taskAccount(account)] : []))))
137
+ byAccount.set(account, await store.tasks.statNames("chat", groups.filter((one) => one.account && taskAccount(one.account) === account).map(({ group }) => group), account));
138
+ return ({ group, account }) => (account ? byAccount.get(taskAccount(account))?.get(group) : undefined);
139
+ };
107
140
  const meetingIdOf = (group) => {
108
141
  try {
109
142
  return String(parseMeetingReference(group).meetingId);
@@ -179,6 +179,7 @@ export interface TasksService {
179
179
  /** `chat` narrows to one chat, by name or id; see `taskStatsOf` for what each count means. */
180
180
  stats(request?: Omit<TaskStatsRequest, "group"> & {
181
181
  chat?: string;
182
+ accounts?: readonly AccountKey[];
182
183
  }): Promise<TaskStats>;
183
184
  /** Title, description, due date and next check; `null` clears one. */
184
185
  plan(id: string, plan: TaskPlan, by: TaskOrigin): Promise<TaskCard>;
@@ -505,10 +505,22 @@ export const tasksService = (deps, categories) => {
505
505
  await owned(store, account, subject);
506
506
  return store.tasks.similar({ task: subject }, options);
507
507
  }),
508
- stats: ({ chat, ...request } = {}) => inStore(async (store, account) => {
509
- const group = await groupOf(store, account, chat);
510
- return taskStatsOf(store, account, { ...request, ...(group === undefined ? {} : { group }) }, await queryColumns(store, account, request.query));
511
- }),
508
+ stats: ({ chat, accounts, ...request } = {}) => accounts
509
+ ? (async () => {
510
+ const store = await deps.store();
511
+ const named = request.query
512
+ ? walkQuery(request.query.root).some(({ field, operator }) => field === "chat" && operator !== "wildcard")
513
+ : false;
514
+ if (chat !== undefined || named)
515
+ throw new CliError("validation_error", "a chat belongs to one account: name the account as well");
516
+ // No chat is named, so the columns need no account.
517
+ const columns = taskColumns(new Map(), await taskTagFilters(store, request.query));
518
+ return taskStatsOf(store, accounts, request, columns);
519
+ })()
520
+ : inStore(async (store, account) => {
521
+ const group = await groupOf(store, account, chat);
522
+ return taskStatsOf(store, account, { ...request, ...(group === undefined ? {} : { group }) }, await queryColumns(store, account, request.query));
523
+ }),
512
524
  };
513
525
  };
514
526
  const iso = (at) => (at === undefined ? null : at.toISOString());
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { MEETING_FINDINGS_KIND } from "../meetings/index.js";
3
3
  import { IDENTITY_LINK_KIND } from "./identity-links.js";
4
+ import { IDENTITY_SPLIT_KIND } from "./identity-splits.js";
4
5
  import { MAIL_FINDINGS_KIND } from "./mail-findings.js";
5
6
  import { SOURCE_REVIEW_KIND } from "./source-review.js";
6
7
  /** An agent's suggested close of a task: kept on the task, not in `proposed_actions`. */
@@ -14,7 +15,8 @@ export const isOwnerOnlyKind = (kind) => kind === MAIL_FINDINGS_KIND ||
14
15
  kind === MEETING_FINDINGS_KIND ||
15
16
  kind === TASK_CLOSE_KIND ||
16
17
  kind === SOURCE_REVIEW_KIND ||
17
- kind === IDENTITY_LINK_KIND;
18
+ kind === IDENTITY_LINK_KIND ||
19
+ kind === IDENTITY_SPLIT_KIND;
18
20
  /**
19
21
  * The one check every decide path runs before it confirms or rejects a proposal. `null` means allowed. Every Claude
20
22
  * Code session is the bot `claude-code`, so comparing bot names keeps one session from deciding another's proposal.
@@ -1,3 +1,4 @@
1
+ import { refuseOwnerStoreInTests } from "../path.js";
1
2
  import { loadVectorExtension, vectorExtension } from "../vector-extension.js";
2
3
  let customised = false;
3
4
  /**
@@ -33,6 +34,7 @@ export const bunDatabase = async () => {
33
34
  export const openWithBunSqlite = async (path) => cacheOverBunSqlite(await bunClient(path));
34
35
  /** A connection with the vector extension loaded; it closes again when the extension does not load. */
35
36
  export const bunClient = async (path, options) => {
37
+ refuseOwnerStoreInTests(path);
36
38
  const Database = await bunDatabase();
37
39
  const extension = await vectorExtension();
38
40
  const client = options ? new Database(path, options) : new Database(path);
@@ -1,6 +1,7 @@
1
1
  // biome-ignore-all lint/plugin/no-sqlite-driver: cli-core owns the store, so it opens the driver itself
2
2
  import { DatabaseSync } from "node:sqlite";
3
3
  import { beforeTimeLimit, TIME_LIMIT_FUNCTION, } from "../driver.js";
4
+ import { refuseOwnerStoreInTests } from "../path.js";
4
5
  import { loadVectorExtension, vectorExtension } from "../vector-extension.js";
5
6
  /**
6
7
  * Import this module only through a dynamic import that follows `quietSqliteWarning()`: a static import loads
@@ -9,6 +10,7 @@ import { loadVectorExtension, vectorExtension } from "../vector-extension.js";
9
10
  export const openWithNodeSqlite = async (path) => cacheOverNodeSqlite(await nodeClient(path));
10
11
  /** A connection with the vector extension loaded; it closes again when the extension does not load. */
11
12
  export const nodeClient = async (path, { readOnly = false } = {}) => {
13
+ refuseOwnerStoreInTests(path);
12
14
  const extension = await vectorExtension();
13
15
  const client = new DatabaseSync(path, { readOnly, allowExtension: true });
14
16
  try {
@@ -0,0 +1,60 @@
1
+ import type { Decider, Proposer } from "./decisions.js";
2
+ import type { Author } from "./sqlite/memories.js";
3
+ import type { IdentityRef } from "./types.js";
4
+ /**
5
+ * A stored kind of its own, not an `identity_link`: every reader of those takes a row for two people who may be one,
6
+ * and would settle a split of one person away as moot.
7
+ */
8
+ export declare const IDENTITY_SPLIT_KIND = "identity_split";
9
+ /** `unlink` moves the identities to one new person; `unmerge` gives a merge's identities back to their person. */
10
+ export type IdentitySplitMove = "unlink" | "unmerge";
11
+ /** An `identity_split` proposal's payload. */
12
+ export interface IdentitySplitPayload {
13
+ split: IdentitySplitMove;
14
+ /** The person the identities would leave, as a uid when it was proposed. */
15
+ person: string;
16
+ /** `provider:id` of each identity that would leave. */
17
+ identities: string[];
18
+ /** `merge:<to>-<from>` for an unmerge, `null` for an unlink. */
19
+ merge: string | null;
20
+ /** The person's identities when it was proposed, so a confirm after the person changed is refused. */
21
+ side: string;
22
+ evidence: string[];
23
+ }
24
+ /** Either the identities that leave, all of one person, or the merge to undo. */
25
+ export type IdentitySplitInput = ({
26
+ identities: IdentityRef[];
27
+ } | {
28
+ merge: string;
29
+ }) & {
30
+ by: Author;
31
+ reason: string;
32
+ evidence?: string[];
33
+ };
34
+ export interface IdentitySplitDecision {
35
+ confirm: boolean;
36
+ /** `"owner"` only on a path that established the owner decides; anyone else is refused. */
37
+ by: Decider;
38
+ reason?: string;
39
+ }
40
+ /** One `identity_split`, naming the person as they are now. */
41
+ export interface IdentitySplitRow {
42
+ id: string;
43
+ /** `dropped`: an older build approved it as a plain action, and nothing was split. */
44
+ status: "proposed" | "confirmed" | "rejected" | "dropped";
45
+ split: IdentitySplitMove;
46
+ /** `person:<uid>` the identities are on now. */
47
+ person: string;
48
+ identities: string[];
49
+ merge: string | null;
50
+ reason: string | null;
51
+ evidence: string[];
52
+ proposedBy: Proposer;
53
+ createdAt: string;
54
+ }
55
+ export interface IdentitySplitFilter {
56
+ /** `proposed` unless named. */
57
+ status?: IdentitySplitRow["status"] | "all";
58
+ limit: number;
59
+ offset: number;
60
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * A stored kind of its own, not an `identity_link`: every reader of those takes a row for two people who may be one,
3
+ * and would settle a split of one person away as moot.
4
+ */
5
+ export const IDENTITY_SPLIT_KIND = "identity_split";
@@ -21,6 +21,7 @@ export { PRAGMAS } from "./driver.js";
21
21
  export { type CitableRecord, EVIDENCE_FINDINGS_KIND, type EvidenceFindingsBatch, type EvidenceFindingsDecider, type EvidenceFindingsReceipt, type EvidenceFindingsStore, validateEvidenceFindings, } from "./evidence-findings.js";
22
22
  export { type DamagedTable, type InvalidJson, QUICK_HEALTH_CHECKS, type SearchIndexHealth, type StoreHealth, storeHealth, } from "./health.js";
23
23
  export { IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, type IdentityLinkDecision, type IdentityLinkFilter, type IdentityLinkInput, type IdentityLinkPayload, type IdentityLinkRow, type IdentityLinkSignal, type MatchScan, } from "./identity-links.js";
24
+ export { IDENTITY_SPLIT_KIND, type IdentitySplitDecision, type IdentitySplitFilter, type IdentitySplitInput, type IdentitySplitMove, type IdentitySplitPayload, type IdentitySplitRow, } from "./identity-splits.js";
24
25
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
25
26
  export { MAIL_FINDINGS_KIND, type MailFindingsBatch, type MailFindingsCheck, type MailFindingsStore, } from "./mail-findings.js";
26
27
  export { clearDamageMark, type DamageMark, damageMarkPath, type HealthMark, healthMarkPath, type JournalMark, journalMarkPath, markStoreDamaged, readDamageMark, readHealthMark, readJournalMark, recordDeepCheck, } from "./marks.js";
@@ -79,6 +80,7 @@ export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from ".
79
80
  export type { OrganizationFilter } from "./sqlite/organization-categories.js";
80
81
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
81
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";
82
84
  export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
83
85
  export { ALWAYS_SHOWN, PERSON_TIES, type PersonTie, type ShownBecause, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
84
86
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
@@ -13,6 +13,7 @@ export { PRAGMAS } from "./driver.js";
13
13
  export { EVIDENCE_FINDINGS_KIND, validateEvidenceFindings, } from "./evidence-findings.js";
14
14
  export { QUICK_HEALTH_CHECKS, storeHealth, } from "./health.js";
15
15
  export { IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, } from "./identity-links.js";
16
+ export { IDENTITY_SPLIT_KIND, } from "./identity-splits.js";
16
17
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
17
18
  export { MAIL_FINDINGS_KIND, } from "./mail-findings.js";
18
19
  export { clearDamageMark, damageMarkPath, healthMarkPath, journalMarkPath, markStoreDamaged, readDamageMark, readHealthMark, readJournalMark, recordDeepCheck, } from "./marks.js";
@@ -40,6 +41,7 @@ export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js
40
41
  export { NOTE_FIELDS, } from "./sqlite/note-search.js";
41
42
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
42
43
  export { PEOPLE_SORTS, } from "./sqlite/people-list.js";
44
+ export { DOUBT_REASONS, } from "./sqlite/person-doubts.js";
43
45
  export { mergeId, parseMergeId } from "./sqlite/person-merges.js";
44
46
  export { ALWAYS_SHOWN, PERSON_TIES, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
45
47
  export { assertGenericAction, PROPOSAL_STATUSES, proposerOfAction, } from "./sqlite/proposed-actions.js";
@@ -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;