@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
package/CHANGELOG.md CHANGED
@@ -5,6 +5,54 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.633.0 — 10.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`<tool> <profile> store import <file.json>` loads made-up chats, people and messages into a test store**, for
13
+ WireCat Desktop's sandbox: Search and Analytics get messenger data without anyone signing in. The file is the
14
+ adapter kit's `Seed` shape plus `"synthetic": true` (the format: the API reference, "Made-up data for a test store");
15
+ it is written as a pushed sync writes, so the same file twice adds nothing and a changed message is updated in
16
+ place. Without `--yes` it only says what it would load. It refuses a file not marked synthetic, the owner's real
17
+ store (whatever `HOME` says), and a profile recorded as another account. New permission key `store.import`, `ask`.
18
+
19
+ ## 0.632.0 — 10.11.2026
20
+
21
+ ### Added
22
+
23
+ - **`PeopleStore.doubts` lists people that may be wrong**, a page at a time, the owner first, each with a plain reason,
24
+ the identities in doubt, the evidence and the owner's commands that would fix it: the owner's person holding an
25
+ identity under another name (spelling and script aside; what the owner linked by hand never counts), test data (the
26
+ contract seed's people, an address at a reserved domain such as `.test` or `example.com`), an identity joined by an
27
+ address that a person of another name has, and one person with different names and no phone or address in common.
28
+ It reads only the people with more than one identity and one pass over identities: about 0.1 s on a store of 150k
29
+ people.
30
+ - **An agent's unlink or unmerge waits for the owner.** `PeopleStore.proposeSplit` stores an `identity_split`
31
+ proposal (the identities that leave, all of one person, or a `merge:<to>-<from>`) with its reason;
32
+ `decideSplit` is the owner's alone and carries it out as the owner's own unlink, split or undo of the merge, refused
33
+ with `identity.stale` when the person changed since. `splitProposals` lists them, and the shared review
34
+ (`proposalRegistry`) shows and decides them as kind `identity_split`, owner-only. Proposing an open split again
35
+ renews it after the person changed. A split the owner turned down is not proposed again while its identities stay
36
+ on that person, and `doubts` leaves them out. Removing a CRM contact or erasing an identity deletes the splits that
37
+ name it. No store migration: older builds see the kind as a plain action, and one they approve is never carried
38
+ out (`splitProposals` shows it as `dropped`).
39
+ - `SEED_PEOPLE`, `RESERVED_ADDRESS_GLOBS` and `SEED_ID_GLOBS` in the domain, which the contract seed now uses.
40
+ - **`muted:` in the query language.** `muted:true` matches messages in chats the owner muted, until the mute runs
41
+ out; `muted:false` matches every other chat, so `stats messages show 'muted:false date>=30d'` counts only what the
42
+ sync still reads. A messenger that keeps no mute state counts its chats as not muted. `stats messages responses`
43
+ and `stats messages waiting` take it too.
44
+ - **`stats tasks show` can count every account at once.** A `Messenger` that sets `accountsOf(command)` gets one answer
45
+ across the accounts it returns, when the command names none: memo uses it so `memo stats tasks show` needs no
46
+ `--source`. The answer lists them in `accounts`, and each chat row's `chat` names its own account. `--chat` and a
47
+ `chat:` naming one chat are then refused, since a chat belongs to one account.
48
+
49
+ ### Fixed
50
+
51
+ - **A test can no longer reach the owner's real store through `openCache` either.** The refusal of 0.560.0 covered
52
+ `openStore` and `openSqlite`; `openCache` and `openFile`, which first-run, store settings, schedules and store
53
+ backups use, opened the file without it. The check now sits in both SQLite drivers, so every opening under vitest
54
+ refuses a file in the owner's WireCat folder.
55
+
8
56
  ## 0.631.0 — 10.11.2026
9
57
 
10
58
  ### Added
@@ -10,13 +10,13 @@ export declare const calendarTools: ({
10
10
  inputSchema: {
11
11
  type: string;
12
12
  properties: {
13
+ limit?: undefined;
13
14
  account_id: {
14
15
  type: string;
15
16
  minimum: number;
16
17
  };
17
18
  query?: undefined;
18
19
  timezone?: undefined;
19
- limit?: undefined;
20
20
  page?: undefined;
21
21
  event?: undefined;
22
22
  } | {
@@ -45,9 +45,9 @@ export declare const calendarTools: ({
45
45
  };
46
46
  event?: undefined;
47
47
  } | {
48
+ limit?: undefined;
48
49
  query?: undefined;
49
50
  timezone?: undefined;
50
- limit?: undefined;
51
51
  page?: undefined;
52
52
  event: {
53
53
  type: string;
@@ -58,9 +58,9 @@ export declare const calendarTools: ({
58
58
  minimum: number;
59
59
  };
60
60
  } | {
61
+ limit?: undefined;
61
62
  query?: undefined;
62
63
  timezone?: undefined;
63
- limit?: undefined;
64
64
  page?: undefined;
65
65
  event?: undefined;
66
66
  account_id?: undefined;
@@ -80,13 +80,13 @@ export declare const calendarTools: ({
80
80
  inputSchema: {
81
81
  type: string;
82
82
  properties: {
83
+ limit?: undefined;
83
84
  account_id: {
84
85
  type: string;
85
86
  minimum: number;
86
87
  };
87
88
  query?: undefined;
88
89
  timezone?: undefined;
89
- limit?: undefined;
90
90
  page?: undefined;
91
91
  event?: undefined;
92
92
  } | {
@@ -115,9 +115,9 @@ export declare const calendarTools: ({
115
115
  };
116
116
  event?: undefined;
117
117
  } | {
118
+ limit?: undefined;
118
119
  query?: undefined;
119
120
  timezone?: undefined;
120
- limit?: undefined;
121
121
  page?: undefined;
122
122
  event: {
123
123
  type: string;
@@ -128,9 +128,9 @@ export declare const calendarTools: ({
128
128
  minimum: number;
129
129
  };
130
130
  } | {
131
+ limit?: undefined;
131
132
  query?: undefined;
132
133
  timezone?: undefined;
133
- limit?: undefined;
134
134
  page?: undefined;
135
135
  event?: undefined;
136
136
  account_id?: undefined;
@@ -150,13 +150,13 @@ export declare const calendarTools: ({
150
150
  inputSchema: {
151
151
  type: string;
152
152
  properties: {
153
+ limit?: undefined;
153
154
  account_id: {
154
155
  type: string;
155
156
  minimum: number;
156
157
  };
157
158
  query?: undefined;
158
159
  timezone?: undefined;
159
- limit?: undefined;
160
160
  page?: undefined;
161
161
  event?: undefined;
162
162
  } | {
@@ -185,9 +185,9 @@ export declare const calendarTools: ({
185
185
  };
186
186
  event?: undefined;
187
187
  } | {
188
+ limit?: undefined;
188
189
  query?: undefined;
189
190
  timezone?: undefined;
190
- limit?: undefined;
191
191
  page?: undefined;
192
192
  event: {
193
193
  type: string;
@@ -198,9 +198,9 @@ export declare const calendarTools: ({
198
198
  minimum: number;
199
199
  };
200
200
  } | {
201
+ limit?: undefined;
201
202
  query?: undefined;
202
203
  timezone?: undefined;
203
- limit?: undefined;
204
204
  page?: undefined;
205
205
  event?: undefined;
206
206
  account_id?: undefined;
@@ -220,13 +220,13 @@ export declare const calendarTools: ({
220
220
  inputSchema: {
221
221
  type: string;
222
222
  properties: {
223
+ limit?: undefined;
223
224
  account_id: {
224
225
  type: string;
225
226
  minimum: number;
226
227
  };
227
228
  query?: undefined;
228
229
  timezone?: undefined;
229
- limit?: undefined;
230
230
  page?: undefined;
231
231
  event?: undefined;
232
232
  } | {
@@ -255,9 +255,9 @@ export declare const calendarTools: ({
255
255
  };
256
256
  event?: undefined;
257
257
  } | {
258
+ limit?: undefined;
258
259
  query?: undefined;
259
260
  timezone?: undefined;
260
- limit?: undefined;
261
261
  page?: undefined;
262
262
  event: {
263
263
  type: string;
@@ -268,9 +268,9 @@ export declare const calendarTools: ({
268
268
  minimum: number;
269
269
  };
270
270
  } | {
271
+ limit?: undefined;
271
272
  query?: undefined;
272
273
  timezone?: undefined;
273
- limit?: undefined;
274
274
  page?: undefined;
275
275
  event?: undefined;
276
276
  account_id?: undefined;
@@ -20,6 +20,7 @@ import { gapsCommand } from "./gaps-command.js";
20
20
  import { historyLimitGaps } from "./history-gaps.js";
21
21
  import { messageItems } from "./message-items.js";
22
22
  import { ENCRYPT_OPTION, passwordOf } from "./password.js";
23
+ import { storeImportCommand } from "./store-import-command.js";
23
24
  import { storeMaintenanceCommands } from "./store-maintenance-command.js";
24
25
  /** `store`: the local store of messages — what it holds, filling it, reading it out, and looking after the file. */
25
26
  export const storeCommand = (messenger) => {
@@ -30,7 +31,8 @@ export const storeCommand = (messenger) => {
30
31
  .addCommand(gapsCommand(messenger))
31
32
  .addCommand(jobsCommand(messenger))
32
33
  .addCommand(exportCommand(messenger))
33
- .addCommand(clearCommand(messenger));
34
+ .addCommand(clearCommand(messenger))
35
+ .addCommand(storeImportCommand(messenger));
34
36
  for (const command of storeMaintenanceCommands(messenger))
35
37
  store.addCommand(command);
36
38
  const examples = {
@@ -43,6 +45,7 @@ export const storeCommand = (messenger) => {
43
45
  export: '"Book club" --output ./messages.jsonl',
44
46
  "gaps show": '"Book club"',
45
47
  "gaps repair": '"Book club" --limit 100',
48
+ import: "./synthetic-chats.json --yes",
46
49
  info: "",
47
50
  "jobs cancel": "job-101",
48
51
  "jobs clear": "",
@@ -201,6 +201,8 @@ export interface Messenger extends ServiceMessenger {
201
201
  * profile and mounts the local task builders with `--provider --account`.
202
202
  */
203
203
  accountOf?: (command: Command) => AccountKey | undefined;
204
+ /** Every account a read covers when the command names none: memo's `stats tasks show` without `--source`. */
205
+ accountsOf?: (command: Command) => readonly AccountKey[] | undefined;
204
206
  /**
205
207
  * Whether a stored chat may hold a message the messenger deleted without naming its chat. When
206
208
  * unset, the store applies Telegram's rule.
@@ -4,7 +4,7 @@ import { LOCAL_READ } from "../effects.js";
4
4
  import { renderAnswer } from "../envelope.js";
5
5
  import { messengerContext } from "./context.js";
6
6
  import { refuseJsonl, responsesAnswer, waitingAnswer } from "./stats-answers.js";
7
- const QUERY = "date:, chat: and kind: terms, AND-ed — date>=30d, date:[60d TO 30d]; none reads all time";
7
+ const QUERY = "date:, chat:, kind: and muted: terms, AND-ed — date>=30d, date:[60d TO 30d], muted:false; none reads all time";
8
8
  const GUIDE = "Guide: https://github.com/WireCatLabs/cli-core/blob/main/docs/rankings.md#reply-times-and-chats-waiting-on-you";
9
9
  const minutes = (ms) => (ms === null ? "—" : `${Math.round(ms / 60_000)} min`);
10
10
  export const replyResponsesCommand = (messenger) => annotate(new Command("responses"), { effects: LOCAL_READ, output: { entity: "response_times" } })
@@ -91,6 +91,7 @@ export declare const serveRelay: (command: Command, messenger: Messenger) => {
91
91
  adminRights?: readonly import("../../domain/models.js").AdminRight[];
92
92
  pickAdminRights?: boolean;
93
93
  accountOf?: (command: Command) => import("../../store/types.js").AccountKey | undefined;
94
+ accountsOf?: (command: Command) => readonly import("../../store/types.js").AccountKey[] | undefined;
94
95
  deletedWithoutChat?: import("../../store/types.js").DeletionScope;
95
96
  officialStats?: boolean;
96
97
  tracksMembers?: boolean;
@@ -71,8 +71,11 @@ export declare const refuseJsonl: (format: string) => void;
71
71
  export declare const chatStatsAnswer: (stats: ChatStats, account: AccountKey, meta?: Partial<Meta>) => ItemBody<Of<"chat_stats">>;
72
72
  /** Said where the store has kept no join, leave or other chat event for the chat: a 0 would read as nobody joined. */
73
73
  export declare const MEMBERS_UNRECORDED = "joins and leaves are not recorded for this chat yet, so they are not counted";
74
- /** `stats tasks show`, CLI and MCP alike. A row of `--by chat` also names its chat as `chat`, as it always has. */
75
- export declare const taskStatsAnswer: (stats: TaskStats, account: AccountKey) => ItemBody<Of<"task_stats">>;
74
+ /**
75
+ * `stats tasks show`, CLI and MCP alike. A row of `--by chat` also names its chat as `chat`, as it always has;
76
+ * `account` is the one account read, and an answer across several names each row's own.
77
+ */
78
+ export declare const taskStatsAnswer: (stats: TaskStats, account: AccountKey | undefined) => ItemBody<Of<"task_stats">>;
76
79
  export declare const responsesAnswer: (found: ReplyTimes) => ItemBody<Of<"response_times">>;
77
80
  export declare const waitingAnswer: (found: Waiting) => ItemBody<Of<"waiting_chats">>;
78
81
  export {};
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { formatLocator } from "../../domain/locator.js";
3
+ import { taskAccount } from "../../services/task-rules.js";
3
4
  import { itemOf, listOf } from "../envelope.js";
4
5
  import { nextStep } from "../steps.js";
5
6
  import { chatRef, contactRef } from "./chat-answers.js";
@@ -410,15 +411,20 @@ export const chatStatsAnswer = (stats, account, meta) => {
410
411
  };
411
412
  /** Said where the store has kept no join, leave or other chat event for the chat: a 0 would read as nobody joined. */
412
413
  export const MEMBERS_UNRECORDED = "joins and leaves are not recorded for this chat yet, so they are not counted";
413
- /** `stats tasks show`, CLI and MCP alike. A row of `--by chat` also names its chat as `chat`, as it always has. */
414
+ /**
415
+ * `stats tasks show`, CLI and MCP alike. A row of `--by chat` also names its chat as `chat`, as it always has;
416
+ * `account` is the one account read, and an answer across several names each row's own.
417
+ */
414
418
  export const taskStatsAnswer = (stats, account) => itemOf({
419
+ ...(stats.accounts ? { accounts: stats.accounts.map(taskAccount) } : {}),
415
420
  open: stats.open,
416
421
  created: stats.created,
417
422
  closed: stats.closed,
418
423
  median_close_ms: stats.medianCloseMs ?? null,
419
424
  mean_open_age_ms: stats.meanOpenAgeMs ?? null,
420
425
  rows: stats.rows.map((row) => {
421
- const chat = stats.by === "chat" ? chatRef(account, row.group) : undefined;
426
+ const own = row.account ?? account;
427
+ const chat = stats.by === "chat" && own ? chatRef(own, row.group) : undefined;
422
428
  return {
423
429
  ...(chat === undefined ? {} : { chat }),
424
430
  key: chat ?? (stats.by === "project" ? `project:${row.group}` : row.group),
@@ -0,0 +1,4 @@
1
+ import { Command } from "commander";
2
+ import { type Messenger } from "./context.js";
3
+ /** `store import` — made-up chats, people and messages into a test or sandbox store, through the sync's own writes. */
4
+ export declare const storeImportCommand: (messenger: Messenger) => Command;
@@ -0,0 +1,166 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { annotate } from "@wirecat/cli-base/commands";
4
+ import { Command } from "commander";
5
+ import * as v from "valibot";
6
+ import { accountHome, inOwnerFolder, storePath } from "../../store/path.js";
7
+ import { openStore } from "../../store/store.js";
8
+ import { changesStore, LOCAL_WRITE } from "../effects.js";
9
+ import { itemOf, renderAnswer, snakeKeys } from "../envelope.js";
10
+ import { accountFileFor, recalledAccount, rememberAccount } from "./accounts.js";
11
+ import { messengerContext } from "./context.js";
12
+ import { fill } from "./stored.js";
13
+ const id = v.pipe(v.string(), v.nonEmpty());
14
+ const time = v.pipe(v.string(), v.isoTimestamp(), v.transform((at) => new Date(at).toISOString()));
15
+ const name = v.nullish(v.string(), null);
16
+ const person = v.object({ id, name, username: name });
17
+ /** The adapter kit's `Seed` (`src/kit/seed.ts`) as a file: what a sync would have read, with the defaults filled in. */
18
+ const importFile = v.object({
19
+ synthetic: v.literal(true),
20
+ account: person,
21
+ people: v.optional(v.array(person), []),
22
+ chats: v.array(v.object({
23
+ id,
24
+ title: name,
25
+ kind: v.picklist(["dialog", "group", "channel", "saved", "unknown"]),
26
+ unreadCount: v.nullish(v.pipe(v.number(), v.integer(), v.minValue(0)), null),
27
+ lastMessageAt: v.nullish(time, null),
28
+ participantsCount: v.nullish(v.pipe(v.number(), v.integer(), v.minValue(0)), null),
29
+ })),
30
+ members: v.optional(v.record(v.string(), v.array(person)), {}),
31
+ messages: v.optional(v.array(v.object({
32
+ id,
33
+ chatId: id,
34
+ senderId: v.nullish(id, null),
35
+ senderName: name,
36
+ timestamp: time,
37
+ editedAt: v.nullish(time, null),
38
+ text: v.string(),
39
+ outgoing: v.optional(v.boolean()),
40
+ replyToId: v.optional(id),
41
+ })), []),
42
+ });
43
+ const readImport = (path) => {
44
+ let raw;
45
+ try {
46
+ raw = JSON.parse(readFileSync(path, "utf8"));
47
+ }
48
+ catch {
49
+ // The parser's message quotes the file, which may be anything its caller can read.
50
+ throw new CliError("validation_error", `cannot read ${path} as JSON`);
51
+ }
52
+ if (raw?.synthetic !== true)
53
+ throw new CliError("validation_error", `${path} does not say "synthetic": true — store import loads made-up test data only, never a real account's`);
54
+ const parsed = v.safeParse(importFile, raw);
55
+ if (!parsed.success) {
56
+ const issue = parsed.issues[0];
57
+ const at = v.getDotPath(issue) ?? "the file";
58
+ throw new CliError("validation_error", `${path}: ${at}: expected ${issue.expected ?? "another value"}`);
59
+ }
60
+ const file = parsed.output;
61
+ const chats = new Set(file.chats.map((chat) => chat.id));
62
+ for (const message of file.messages)
63
+ if (!chats.has(message.chatId))
64
+ throw new CliError("validation_error", `${path}: message ${message.id} names chat ${message.chatId}, not in chats`);
65
+ for (const chatId of Object.keys(file.members))
66
+ if (!chats.has(chatId))
67
+ throw new CliError("validation_error", `${path}: members name chat ${chatId}, not in chats`);
68
+ return file;
69
+ };
70
+ const messagesOf = (file) => file.messages.map(({ outgoing, ...message }) => ({
71
+ ...message,
72
+ outgoing: outgoing === undefined ? message.senderId === file.account.id : outgoing,
73
+ attachments: [],
74
+ replyTo: null,
75
+ forwardedFrom: null,
76
+ reactions: null,
77
+ }));
78
+ /** A chat's newest message stands in for its `lastMessageAt` when the file leaves it out, as a chat list would say. */
79
+ const chatsOf = (file, messages) => {
80
+ const newest = new Map();
81
+ for (const { chatId, timestamp } of messages)
82
+ if ((newest.get(chatId) ?? "") < timestamp)
83
+ newest.set(chatId, timestamp);
84
+ return file.chats.map((chat) => ({ ...chat, lastMessageAt: chat.lastMessageAt ?? newest.get(chat.id) ?? null }));
85
+ };
86
+ const heldCounts = async (store, key) => ({
87
+ chats: await store.chats.countChats(key),
88
+ messages: (await store.chats.chatStats(key)).reduce((sum, chat) => sum + chat.messages, 0),
89
+ });
90
+ const refuseOwnerFolders = (messenger, profile, env, target) => {
91
+ const home = accountHome();
92
+ const ownState = home !== undefined &&
93
+ accountFileFor(messenger.app, profile, env) === accountFileFor(messenger.app, profile, { HOME: home });
94
+ if (!inOwnerFolder(target, home) && !ownState)
95
+ return;
96
+ throw new CliError("permission_error", `store import writes made-up data, and ${ownState ? `profile ${profile}'s state` : target} is the owner's real ` +
97
+ "one — run it in a sandbox (WireCat Desktop's bin/sandbox), with HOME, MESSAGING_STORE and the tool's state " +
98
+ "folder of its own");
99
+ };
100
+ /** `store import` — made-up chats, people and messages into a test or sandbox store, through the sync's own writes. */
101
+ export const storeImportCommand = (messenger) => changesStore(annotate(new Command("import"), { output: { entity: "store_import" }, effects: LOCAL_WRITE })
102
+ .summary("load made-up chats, people and messages from a file into a test or sandbox store")
103
+ .description('load a JSON file marked "synthetic": true (account, people, chats, members, messages) into this profile\'s ' +
104
+ "account in the local store, as a sync would save them; the same file twice adds nothing and a changed " +
105
+ "message is updated in place. Refuses the owner's real store. Without --yes, says what it would load and " +
106
+ "changes nothing")
107
+ .argument("<file>", "the JSON file to load")
108
+ .action(async function (path) {
109
+ const context = messengerContext(this, messenger);
110
+ const { profile, env } = context;
111
+ const { command } = messenger.app;
112
+ const file = readImport(path);
113
+ const target = storePath(env);
114
+ refuseOwnerFolders(messenger, profile, env, target);
115
+ if (!context.settings.profilesHere.includes(profile))
116
+ throw new CliError("not_found", `no profile named "${profile}" — make it first with \`${command} ${profile} config set …\``);
117
+ const key = { provider: messenger.provider, account: file.account.id };
118
+ const remembered = recalledAccount(messenger.app, messenger.provider, profile, env);
119
+ if (remembered && remembered.account !== key.account)
120
+ throw new CliError("validation_error", `profile ${profile} is account ${remembered.account}, and ${path} is account ${key.account} — ` +
121
+ "import it into a profile of its own");
122
+ const messages = messagesOf(file);
123
+ const chats = chatsOf(file, messages);
124
+ const people = [...file.people, ...Object.values(file.members).flat()];
125
+ // Over MCP an `ask` write goes ahead (NEED-773): nobody is there to add --yes.
126
+ const yes = this.optsWithGlobals().yes === true || context.agent;
127
+ const planned = {
128
+ store: target,
129
+ profile,
130
+ account: key.account,
131
+ file: { chats: chats.length, people: new Set(people.map((one) => one.id)).size, messages: messages.length },
132
+ };
133
+ if (!yes) {
134
+ context.renderer.note(`would load ${messages.length} messages in ${chats.length} chats into ${target} as profile ${profile} ` +
135
+ `(account ${key.account}); nothing changed — add --yes to load them`);
136
+ renderAnswer(this, context, itemOf(snakeKeys({ ...planned, imported: false })));
137
+ return;
138
+ }
139
+ const answer = await context.run(async () => {
140
+ const store = await openStore({ env, command, version: messenger.app.version });
141
+ try {
142
+ const mapped = (await store.accounts.profiles())[command]?.[profile];
143
+ if (mapped && (mapped.provider !== key.provider || mapped.account !== key.account))
144
+ throw new CliError("validation_error", `the store has profile ${profile} as account ${mapped.account}, and ${path} is account ` +
145
+ `${key.account} — import it into a profile of its own`);
146
+ const before = await heldCounts(store, key);
147
+ await store.accounts.saveAccount(key, { name: file.account.name });
148
+ await store.accounts.saveProfile(command, profile, key);
149
+ rememberAccount(messenger.app, profile, key.account, env);
150
+ await store.people.savePeople(key, [file.account, ...people]);
151
+ await fill(store, key, { chats, messages });
152
+ for (const [chatId, members] of Object.entries(file.members))
153
+ await store.roster.saveMembers(key, chatId, members.map((member) => member.id));
154
+ const after = await heldCounts(store, key);
155
+ return {
156
+ ...planned,
157
+ imported: true,
158
+ added: { chats: after.chats - before.chats, messages: after.messages - before.messages },
159
+ };
160
+ }
161
+ finally {
162
+ await store.close();
163
+ }
164
+ });
165
+ renderAnswer(this, context, itemOf(snakeKeys(answer)));
166
+ }));
@@ -1,5 +1,5 @@
1
1
  import type { Id } from "../../domain/models.js";
2
- import { type MessengerAdapter } from "../../ports/messenger.js";
2
+ import { type HistoryBatch, type MessengerAdapter } from "../../ports/messenger.js";
3
3
  import type { MessengerTraits } from "../../ports/traits.js";
4
4
  import type { EventSink, Warn } from "../../runs/events.js";
5
5
  import { type HistoryLimits } from "../../services/history-limits.js";
@@ -56,3 +56,9 @@ export interface Saving {
56
56
  * known to be whole, and `saveMembers` replaces the list.
57
57
  */
58
58
  export declare const stored: (messenger: MessengerAdapter, { account, store, warn, events, pending, announcing, deletedWithoutChat, profile, rekeyed, rekeyPacing, closing, namesFromStore, recipientIds, countsUnread, historyLimits, command, }: Saving) => MessengerAdapter;
59
+ /**
60
+ * A pushed batch as the store keeps it. No `markChatsLeft`: a push names some chats, never all of them.
61
+ * No `seenAt`: a pushed snapshot may be older than a deletion this store already holds. A chat's votes and stars go
62
+ * in the transaction of its messages, after them, so a message in the batch is held, or known deleted, before them.
63
+ */
64
+ export declare const fill: (store: MessageStore, account: AccountKey, batch: HistoryBatch) => Promise<void>;
@@ -606,7 +606,7 @@ const onlyRekeys = (batch) => Object.entries(batch).every(([part, items]) => (pa
606
606
  * No `seenAt`: a pushed snapshot may be older than a deletion this store already holds. A chat's votes and stars go
607
607
  * in the transaction of its messages, after them, so a message in the batch is held, or known deleted, before them.
608
608
  */
609
- const fill = async (store, account, batch) => {
609
+ export const fill = async (store, account, batch) => {
610
610
  if (batch.chats?.length)
611
611
  await store.chats.saveChats(account, batch.chats);
612
612
  if (batch.people?.length)
@@ -566,6 +566,7 @@ export const tasksStatsCommand = (messenger) => {
566
566
  const { by, chat, type, timezone } = this.opts();
567
567
  refuseJsonl(context.format);
568
568
  const query = listQuery(typedQuery(words), TASK_STATS_QUERY, "stats tasks show");
569
+ const accounts = messenger.accountsOf?.(this);
569
570
  const { stats, account } = await context.withServices(async (services) => ({
570
571
  stats: await services.tasks.stats({
571
572
  ...(by === undefined ? {} : { by }),
@@ -573,16 +574,17 @@ export const tasksStatsCommand = (messenger) => {
573
574
  ...(type === undefined ? {} : { kind: type }),
574
575
  ...(query === undefined ? {} : { query }),
575
576
  ...(timezone === undefined ? {} : { timezone }),
577
+ ...(accounts === undefined ? {} : { accounts }),
576
578
  }),
577
- account: await services.messages.reader(),
579
+ account: accounts === undefined ? await services.messages.reader() : undefined,
578
580
  }));
579
581
  if (stats.rows.length === 0)
580
582
  context.renderer.note("no tasks yet");
581
583
  renderAnswer(this, context, taskStatsAnswer(stats, account), () => stats.rows.length === 0
582
584
  ? ""
583
585
  : `${stats.rows
584
- .map(({ group, name, open, created, closed, oldestOpenAt, medianCloseMs }) => [
585
- name ? `${name} (${group})` : group,
586
+ .map(({ group, account: own, name, open, created, closed, oldestOpenAt, medianCloseMs }) => [
587
+ `${name ? `${name} (${group})` : group}${own ? ` ${own.provider}:${own.account}` : ""}`,
586
588
  `${open} open`,
587
589
  `${created} created`,
588
590
  `${closed} closed`,
@@ -0,0 +1,15 @@
1
+ /** The people the shared contract seed (`src/kit/seed.ts`) makes, so a test run that reached a real store shows. */
2
+ export declare const SEED_PEOPLE: readonly [{
3
+ readonly name: "Owner";
4
+ readonly username: "owner";
5
+ }, {
6
+ readonly name: "Ann Lee";
7
+ readonly username: "ann";
8
+ }, {
9
+ readonly name: "Bob Ray";
10
+ readonly username: null;
11
+ }];
12
+ /** Domains no real mailbox has (RFC 2606 and RFC 6761), as SQLite `GLOB` patterns over a lower-cased address. */
13
+ export declare const RESERVED_ADDRESS_GLOBS: readonly ["*@example.com", "*@example.net", "*@example.org", "*.example", "*.test", "*.invalid", "*.localhost"];
14
+ /** Ids made by the seed's `wordIds`; numeric ids are real for some providers, so `digitIds` are not counted. */
15
+ export declare const SEED_ID_GLOBS: readonly ["person-[0-9]*"];
@@ -0,0 +1,18 @@
1
+ /** The people the shared contract seed (`src/kit/seed.ts`) makes, so a test run that reached a real store shows. */
2
+ export const SEED_PEOPLE = [
3
+ { name: "Owner", username: "owner" },
4
+ { name: "Ann Lee", username: "ann" },
5
+ { name: "Bob Ray", username: null },
6
+ ];
7
+ /** Domains no real mailbox has (RFC 2606 and RFC 6761), as SQLite `GLOB` patterns over a lower-cased address. */
8
+ export const RESERVED_ADDRESS_GLOBS = [
9
+ "*@example.com",
10
+ "*@example.net",
11
+ "*@example.org",
12
+ "*.example",
13
+ "*.test",
14
+ "*.invalid",
15
+ "*.localhost",
16
+ ];
17
+ /** Ids made by the seed's `wordIds`; numeric ids are real for some providers, so `digitIds` are not counted. */
18
+ export const SEED_ID_GLOBS = ["person-[0-9]*"];
@@ -67,6 +67,8 @@ export declare const chatStats: v.StrictObjectSchema<{
67
67
  * tasks opened and closed in the query's period, every task without one.
68
68
  */
69
69
  export declare const taskStats: v.StrictObjectSchema<{
70
+ /** Every account counted, `provider:account`, when the answer reads several (memo without `--source`). */
71
+ readonly accounts: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
70
72
  /** Open tasks across every row. */
71
73
  readonly open: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
72
74
  readonly created: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
@@ -60,6 +60,8 @@ const ms = v.nullable(v.pipe(v.number(), v.minValue(0)));
60
60
  * tasks opened and closed in the query's period, every task without one.
61
61
  */
62
62
  export const taskStats = v.strictObject({
63
+ /** Every account counted, `provider:account`, when the answer reads several (memo without `--source`). */
64
+ accounts: v.optional(v.array(text)),
63
65
  /** Open tasks across every row. */
64
66
  open: count,
65
67
  created: count,
@@ -76,7 +76,7 @@ import { responseTimes, waitingChats } from "./reply-stats.js";
76
76
  import { retention } from "./retention.js";
77
77
  import { savedSearch, searchHistoryClear } from "./saved-search.js";
78
78
  import { sendAttempt } from "./send-attempt.js";
79
- import { storeBackup, storeCheck, storeCopyRemoval, storeDecrypt, storeInfo, storeMigration, storeReindex, storeRepair, storeReset, storeRestore } from "./store-maintenance.js";
79
+ import { storeBackup, storeCheck, storeCopyRemoval, storeDecrypt, storeImport, storeInfo, storeMigration, storeReindex, storeRepair, storeReset, storeRestore } from "./store-maintenance.js";
80
80
  import { chatCoverage, storeChatStatus, storeClear, storeExport, storeGapPlan, storeGapRepair, storeJobCancel, storeJobClear, storeJobDetails, storeJobRetry } from "./store-records.js";
81
81
  import { storeTable } from "./store-table.js";
82
82
  import { automaticTags, tagChange } from "./tag-change.js";
@@ -91,7 +91,7 @@ import { topic } from "./topic.js";
91
91
  * subset of its fields, never a renamed one. Commands move onto these one by one; until then, a schema
92
92
  * is the target, not a description of today's output.
93
93
  */
94
- 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, };
94
+ 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, };
95
95
  export declare const ENTITIES: {
96
96
  readonly meeting_ingestion: v.StrictObjectSchema<{
97
97
  readonly meetings: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
@@ -9851,6 +9851,21 @@ export declare const ENTITIES: {
9851
9851
  }, undefined>, undefined>;
9852
9852
  readonly schema: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
9853
9853
  }, undefined>], undefined>;
9854
+ readonly store_import: v.StrictObjectSchema<{
9855
+ readonly store: v.StringSchema<undefined>;
9856
+ readonly profile: v.StringSchema<undefined>;
9857
+ readonly account: v.StringSchema<undefined>;
9858
+ readonly imported: v.BooleanSchema<undefined>;
9859
+ readonly file: v.StrictObjectSchema<{
9860
+ readonly chats: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
9861
+ readonly people: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
9862
+ readonly messages: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
9863
+ }, undefined>;
9864
+ readonly added: v.OptionalSchema<v.StrictObjectSchema<{
9865
+ readonly chats: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
9866
+ readonly messages: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
9867
+ }, undefined>, undefined>;
9868
+ }, undefined>;
9854
9869
  readonly store_repair: v.UnionSchema<[v.StrictObjectSchema<{
9855
9870
  readonly path: v.StringSchema<undefined>;
9856
9871
  readonly exists: v.LiteralSchema<false, undefined>;
@@ -11929,6 +11944,7 @@ export declare const ENTITIES: {
11929
11944
  readonly tracked: v.BooleanSchema<undefined>;
11930
11945
  }, undefined>;
11931
11946
  readonly task_stats: v.StrictObjectSchema<{
11947
+ readonly accounts: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
11932
11948
  readonly open: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
11933
11949
  readonly created: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
11934
11950
  readonly closed: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;