@wirecat/cli-core 0.721.0 → 0.722.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,76 @@ 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.722.0 — 23.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`account remove` for every CRM CLI, with its guard.** `addCrmCommands({ account })` mounts cli-core's
13
+ `account remove`, which refuses `--delete-data` while another profile here holds the same account, whose one copy
14
+ the store shares (`account-remove.account-shared`); `--dry-run` warns instead. `refuseTakenCrmAccount` and
15
+ `crmAccountClaim` (the `claim` of `tokenSessionCommand`) refuse a sign-in to an account and user another profile is
16
+ signed in to (`session.duplicate`), and a profile named `files` or `foreign-contacts`, the folders every account
17
+ shares (`profile.reserved`). A `held` hook says which account a profile holds; unset, it is the account
18
+ `session start` remembered. bitrix24-cli, amo-cli and hubspot-cli can drop their own copies
19
+ ([CRM.md](docs/dev/CRM.md#one-account-one-profile)).
20
+ - **`tokenSessionCommand`'s `claim` gets the run's keyring** as its fifth argument, so a check of the other profiles'
21
+ sign-ins reads the same keyring a test hands in.
22
+ - **Earlier versions of every synced document, and a change log (store version 72).** The store keeps a document's
23
+ text, title and front matter before each change and before each removal, so a deleted page's last text is never
24
+ lost. `documents history <document>` lists the versions and `--revision <n>` shows one. `changes --since 1d` lists
25
+ what was added, changed, deleted, no longer visible, left the synced folders or came back, with titles. Both are
26
+ local reads, so agents get them over MCP too. `documentLibraryCommands` mounts them, and `addDocumentCommands` does
27
+ when the CLI gives `history`. A CLI with its own `documents` group calls `addDocumentHistoryCommands`
28
+ ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#history-and-the-change-log)).
29
+ - **`keep_versions_for_days`, 365 by default.** A sync that completes its pass drops older versions and change log
30
+ rows of that account. A CLI adds `DOCUMENT_HISTORY_SETTINGS` to `settingsFor` and passes `keepVersionsForDays` to
31
+ `syncDocuments`. Without it the sync keeps one year.
32
+ - **A source can say a document is no longer visible rather than deleted.** A change takes `gone: "deleted"` or
33
+ `gone: "unavailable"`, and `SourceIndex.remove` and `deleteFileNotes` take the reason.
34
+ - **Office files edited in place, and earlier versions put back.** `addFileEditCommands` mounts under a CLI's files
35
+ group `sheets show|update` for .xlsx cells, `documents show|update` for .docx paragraphs, `history` for what this
36
+ profile's writes replaced, and `restore <path> [version]`, besides `update`. A show gives the file's sha256; every
37
+ edit and restore takes it as `--expected-fingerprint` and writes through `guardedFileWrite`, so a change made
38
+ meanwhile is a conflict with nothing uploaded and the replaced content is kept. The Office editors' refusals pass
39
+ through with their reasons ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#edit-office-files-in-place)).
40
+
41
+ ### Changed — may break callers
42
+
43
+ - **A file mirror's guard on mass replacements names the count to allow.** A sync stopped before more than 50
44
+ replacements now says to pass `--allow-replacements <count>` with the count filled in, where its default hint said
45
+ `--replace`; `allowReplacements` already took a count. A CLI that offers neither option and relied on the default
46
+ hint should add `--allow-replacements <count>`. One that keeps its `--replace` switch passes
47
+ `allowReplacements: Number.POSITIVE_INFINITY` and its own `allowReplacements` hint, as before
48
+ ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#plain-files-both-ways)).
49
+ - **Uses `@wirecat/cli-base` 0.127.0**, whose vocabulary has `mirrors`, `conflicts`, `--keep <side>`,
50
+ `--allow-deletions <count>`, `--allow-replacements <count>` and `--repin`: the mirror's conflict commands pass
51
+ `cli-dev lint` with no override for them.
52
+ - **`files update` refuses a .pdf, .docx or .xlsx** (`file.not-plain-text`): a read gives their extracted text, which
53
+ would replace the whole document. A CLI leaves the sha256 out of a truncated or extracted text read
54
+ ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#write-one-file-at-the-hash-read)).
55
+
56
+ ### Fixed
57
+
58
+ - **Only a direct signal deletes a synced document's text.** A removal from a change feed without `gone`, a 404 or a
59
+ refusal when the content is read, and a file a finished walk did not find now mark the document no longer visible.
60
+ It leaves lists and search but keeps its text, and comes back as it was. Before, its text was blanked. The trash or
61
+ `gone: "deleted"` still deletes. A file that left the scope because the owner changed the chosen folders is marked
62
+ unsynced.
63
+ - **A messenger's `never` hides ten more commands, and a group left empty.** `messages forward`, `contacts block`
64
+ and `unblock`, `chats links show` and `reset`, `chats requests list`, `confirm` and `reject`, and `chats admins add`
65
+ and `remove` now refuse before connecting when their one method is in `lacks` or `never`, and `never` hides them
66
+ from help, `commands` and MCP. A group whose every command is hidden, such as `account sessions` or `chats folders`,
67
+ is hidden too, so a messenger can put those methods in `never` instead of `lacks`.
68
+ - **A server search no longer erases what the store knew about a message.** A hit is a partial copy: saved over a
69
+ held message, it now adds to its provider metadata instead of replacing it, so a Slack thread root found by
70
+ `search.messages` keeps the reply count a sync saved. A fetch from history still replaces the metadata.
71
+ - **A file mirror no longer merges edits to neighbouring lines.** Two changes with no unchanged line between them,
72
+ one on each side, are now a conflict, as in Git's merge. They used to be combined silently. This includes an
73
+ insertion right after the other side's edit, and edits to neighbouring Markdown blocks such as two list items.
74
+ Changes with at least one unchanged line between them still merge, and a checklist tick still merges with a text
75
+ edit. Document push keeps merging neighbouring blocks as before
76
+ ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#plain-files-both-ways)).
77
+
8
78
  ## 0.721.0 — 23.11.2026
9
79
 
10
80
  ### Added
@@ -24,12 +24,12 @@ export interface DailyArchiveTimerInput {
24
24
  }
25
25
  export declare const dailyArchiveTimer: (input: DailyArchiveTimerInput) => DailyArchiveTimer;
26
26
  export declare const manageDailyArchiveTimer: (plan: DailyArchiveTimer, action: "install" | "start" | "stop" | "status" | "uninstall", system: Pick<ServerSystem, "platform" | "run">, env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<{
27
- action?: undefined;
28
27
  name: string;
29
28
  installed: boolean;
30
29
  active: boolean;
31
30
  servicePath: string;
32
31
  timerPath: string;
32
+ action?: undefined;
33
33
  } | {
34
34
  active?: undefined;
35
35
  name: string;
@@ -20,7 +20,8 @@ export declare const lackedNeed: (messenger: Lacking | undefined, path: string)
20
20
  export declare const refuseLacking: (messenger: Lacking | undefined, path: readonly string[]) => void;
21
21
  /**
22
22
  * Hides under `group` each command whose one method this messenger can `never` have, from help, `commands` and MCP;
23
- * typed anyway, it still refuses. A method it only `lacks` keeps its command in sight, since it may come.
23
+ * typed anyway, it still refuses. A group left with nothing in sight is hidden too, since an empty group lists
24
+ * nothing to run. A method it only `lacks` keeps its command in sight, since it may come.
24
25
  */
25
26
  export declare const hideNever: <T extends Command>(messenger: Lacking, group: T) => T;
26
27
  export {};
@@ -15,10 +15,20 @@ export const COMMAND_NEEDS = {
15
15
  "chats folders create": ["createFolder", "create a folder"],
16
16
  "chats folders update": ["updateFolder", "change a folder"],
17
17
  "chats folders delete": ["deleteFolder", "delete a folder"],
18
+ "chats links show": ["group", "read a group"],
19
+ "chats links reset": ["resetInviteLink", "replace an invite link"],
20
+ "chats requests list": ["joinRequests", "read join requests"],
21
+ "chats requests confirm": ["answerJoinRequest", "answer join requests"],
22
+ "chats requests reject": ["answerJoinRequest", "answer join requests"],
23
+ "chats admins add": ["addAdmin", "make someone an admin"],
24
+ "chats admins remove": ["removeAdmin", "take admin rights back"],
18
25
  "contacts add": ["addContact", "add a contact"],
19
26
  "contacts remove": ["removeContact", "remove a contact"],
20
27
  "contacts rename": ["renameContact", "rename a contact"],
21
28
  "contacts import": ["importContacts", "import contacts"],
29
+ "contacts block": ["block", "block a person"],
30
+ "contacts unblock": ["unblock", "unblock a person"],
31
+ "messages forward": ["forward", "forward a message"],
22
32
  "messages comments": ["comments", "read comments on a channel post"],
23
33
  "messages pin": ["pin", "pin a message"],
24
34
  "messages unpin": ["unpin", "unpin a message"],
@@ -47,7 +57,8 @@ export const refuseLacking = (messenger, path) => {
47
57
  };
48
58
  /**
49
59
  * Hides under `group` each command whose one method this messenger can `never` have, from help, `commands` and MCP;
50
- * typed anyway, it still refuses. A method it only `lacks` keeps its command in sight, since it may come.
60
+ * typed anyway, it still refuses. A group left with nothing in sight is hidden too, since an empty group lists
61
+ * nothing to run. A method it only `lacks` keeps its command in sight, since it may come.
51
62
  */
52
63
  export const hideNever = (messenger, group) => {
53
64
  const walk = (command, path) => {
@@ -57,6 +68,8 @@ export const hideNever = (messenger, group) => {
57
68
  if (need && messenger.never?.includes(need[0]))
58
69
  child._hidden = true;
59
70
  walk(child, at);
71
+ if (child.commands.length > 0 && child.commands.every((one) => one._hidden))
72
+ child._hidden = true;
60
73
  }
61
74
  };
62
75
  walk(group, [group.name()]);
@@ -1,3 +1,4 @@
1
+ import { type KeyringStore } from "@wirecat/cli-base";
1
2
  import type { FetchLike } from "@wirecat/cli-base/http";
2
3
  import { Command } from "commander";
3
4
  import type { CliVerify } from "../manifest/index.js";
@@ -41,7 +42,7 @@ export interface TokenSessionOptions {
41
42
  * Keeps the account a profile signed in to; by default only remembers it. A CLI that refuses a taken one says so.
42
43
  * With `site`, `id` is `<site>:<id>`, the site as `--site` was cleaned.
43
44
  */
44
- claim?: (env: NodeJS.ProcessEnv, profile: string, id: string, tokens: ProfileTokenStore) => void;
45
+ claim?: (env: NodeJS.ProcessEnv, profile: string, id: string, tokens: ProfileTokenStore, keyring: KeyringStore | undefined) => void;
45
46
  /** What the token is, for the prompt and help: "API token" when not given. */
46
47
  token?: string;
47
48
  /** One sentence more for `session start --help`: which token, and what it can see. */
@@ -79,7 +79,7 @@ export const tokenSessionCommand = (options) => {
79
79
  if (options.site)
80
80
  start.option("--site <address>", `the ${service} site, as https://${options.site.example} or ${options.site.example}`);
81
81
  start.action(async function (args) {
82
- const { env, profile, tokens, run, renderer } = contextOf(this);
82
+ const { env, profile, tokens, run, renderer, keyring } = contextOf(this);
83
83
  refuseCommandName(profile, commandWords(rootOf(this)), app.command);
84
84
  if (options.site && args.site === undefined)
85
85
  throw new CliError("validation_error", `give the ${service} site: --site ${options.site.example}`);
@@ -102,7 +102,7 @@ export const tokenSessionCommand = (options) => {
102
102
  throw new CliError("validation_error", `no ${word} was given`);
103
103
  const token = login === undefined ? secret : `${login}:${secret}`;
104
104
  const { id, account } = await run((events) => options.verify(this, token, events, site));
105
- (options.claim ?? ((at, name, key) => rememberAccount(app, name, key, at)))(env, profile, siteAccount(site, id), tokens);
105
+ (options.claim ?? ((at, name, key) => rememberAccount(app, name, key, at)))(env, profile, siteAccount(site, id), tokens, keyring);
106
106
  const storedIn = tokens.write(profile, token, args.credentialStorage, site === undefined ? {} : { site });
107
107
  answer(this, { profile, state: "saved", stored_in: storedIn, verified: true, ...siteOf(site), ...account });
108
108
  });
@@ -0,0 +1,60 @@
1
+ import { type KeyringStore } from "@wirecat/cli-base";
2
+ import { Command } from "commander";
3
+ import { ProfileTokenStore } from "../../cli/profile-token.js";
4
+ import type { GlobalFlags, ResolveOptions, Settings } from "../../cli/settings.js";
5
+ import type { TokenSessionOptions } from "../../cli/token-session.js";
6
+ import type { AppIdentity } from "../../ports/app.js";
7
+ export interface CrmAccountContext {
8
+ env: NodeJS.ProcessEnv;
9
+ /** The run's keyring; `undefined` is the system one. */
10
+ keyring?: KeyringStore;
11
+ }
12
+ /** The CRM account a profile holds: `account` as the store names it, `user` where one account has several users. */
13
+ export interface CrmHeld {
14
+ account: string;
15
+ user?: string;
16
+ /** A sign-in is saved for the profile here. False: only what `session start` remembered outlives `session end`. */
17
+ signedIn: boolean;
18
+ }
19
+ /** `addCrmCommands`'s `account`: mounts `account remove`, which refuses `--delete-data` on an account others read. */
20
+ export interface CrmAccountOptions {
21
+ /** The store's provider name for the CRM, the `provider` of the account's `AccountKey`. */
22
+ provider: string;
23
+ /** The CRM's name, as the owner knows it: "HubSpot". */
24
+ service: string;
25
+ /**
26
+ * What a profile holds, from its saved sign-in or else from what `session start` remembered. Unset: the account
27
+ * `rememberAccount` recorded, signed in while a token is saved in the profile's entry. A CLI whose remembered
28
+ * account is not the store's name for it (bitrix24's and amo's `<host>:<userId>`) passes its own.
29
+ */
30
+ held?: (profile: string, context: CrmAccountContext) => CrmHeld | undefined;
31
+ /** What `account remove` says the sign-out removed, when the CRM keeps more than a token valid. */
32
+ signedOut?: (profile: string) => string;
33
+ /** Unset: the one `run()` set. `crmAccountClaim` needs it to see the profiles the configuration names. */
34
+ resolveSettings?: (flags: GlobalFlags, options?: ResolveOptions) => Settings;
35
+ }
36
+ type Tokens = Pick<ProfileTokenStore, "read">;
37
+ export interface CrmSignIn extends CrmAccountContext {
38
+ /** The profile signing in. */
39
+ profile: string;
40
+ /** The profiles the configuration names; those `session start` remembered are added. */
41
+ profiles?: readonly string[];
42
+ /** The run's token store, whose warnings go where the run's do. Unset: one that keeps them quiet. */
43
+ tokens?: Tokens;
44
+ }
45
+ /**
46
+ * Refuses a sign-in to an account and user another profile here is signed in to: two profiles would sync the same
47
+ * copy twice and split its permissions. A profile that ended its session no longer holds the account.
48
+ */
49
+ export declare const refuseTakenCrmAccount: (app: AppIdentity, options: CrmAccountOptions, { profile, profiles, tokens, ...context }: CrmSignIn, at: {
50
+ account: string;
51
+ user?: string;
52
+ }) => void;
53
+ /** `claim` for `tokenSessionCommand`: refuses an account another profile is signed in to, then remembers it. */
54
+ export declare const crmAccountClaim: (app: AppIdentity, options: CrmAccountOptions) => NonNullable<TokenSessionOptions["claim"]>;
55
+ /**
56
+ * `account remove` of a CRM CLI: cli-core's own, which refuses `--delete-data` while another profile here reads the
57
+ * same account, whose one copy the store shares. Under `--dry-run` it warns instead.
58
+ */
59
+ export declare const crmAccountCommand: (app: AppIdentity, options: CrmAccountOptions) => Command;
60
+ export {};
@@ -0,0 +1,147 @@
1
+ import { join } from "node:path";
2
+ import { CliError, resolvePaths } from "@wirecat/cli-base";
3
+ import { annotate } from "@wirecat/cli-base/commands";
4
+ import { Command } from "commander";
5
+ import { accountRemoveCommand } from "../../cli/account-remove.js";
6
+ import { baseContext, environmentOf } from "../../cli/context.js";
7
+ import { LOCAL_READ, LOCAL_WRITE } from "../../cli/effects.js";
8
+ import { profilesHere, recalledAccount, rememberAccount } from "../../cli/messenger/accounts.js";
9
+ import { ProfileTokenStore } from "../../cli/profile-token.js";
10
+ import { oauthAccount } from "../../oauth/storage.js";
11
+ import { CRM_SHARED_FOLDERS } from "../state-folders.js";
12
+ const SHARED = new Set(Object.values(CRM_SHARED_FOLDERS));
13
+ // A folder named Files is the folder files on macOS and Windows.
14
+ const isShared = (profile) => SHARED.has(profile.toLowerCase());
15
+ /** The account alone, which the delete guard needs: the default reads no keyring, so it cannot fail. */
16
+ const accountBy = (app, options) => (profile, context) => options.held
17
+ ? options.held(profile, context)?.account
18
+ : recalledAccount(app, options.provider, profile, context.env)?.account;
19
+ const signedInBy = (app, options, tokens) => (profile, context) => {
20
+ try {
21
+ if (options.held)
22
+ return options.held(profile, context);
23
+ const account = recalledAccount(app, options.provider, profile, context.env)?.account;
24
+ if (account === undefined)
25
+ return undefined;
26
+ const saved = (tokens ?? new ProfileTokenStore({ app, ...context, warn: () => { } })).read(profile);
27
+ // `<PREFIX>_TOKEN` is every profile's at once, so it is no profile's own sign-in.
28
+ return { account, signedIn: saved !== undefined && saved.source !== "environment" };
29
+ }
30
+ catch {
31
+ // A keyring that does not answer for one profile must not stop another profile's sign-in.
32
+ return undefined;
33
+ }
34
+ };
35
+ const also = (names) => `${names.join(", ")} also read${names.length === 1 ? "s" : ""}`;
36
+ /**
37
+ * Refuses a sign-in to an account and user another profile here is signed in to: two profiles would sync the same
38
+ * copy twice and split its permissions. A profile that ended its session no longer holds the account.
39
+ */
40
+ export const refuseTakenCrmAccount = (app, options, { profile, profiles = [], tokens, ...context }, at) => {
41
+ if (isShared(profile))
42
+ throw new CliError("validation_error", `"${profile}" names a folder every account shares, where this profile's own files would land. Pick another ` +
43
+ `name than ${Object.values(CRM_SHARED_FOLDERS).join(" or ")}`, { reason: "profile.reserved", profile });
44
+ const held = signedInBy(app, options, tokens);
45
+ const other = profilesHere(app, profiles, context.env).find((one) => {
46
+ if (one === profile)
47
+ return false;
48
+ const found = held(one, context);
49
+ return found?.signedIn === true && found.account === at.account && found.user === at.user;
50
+ });
51
+ if (!other)
52
+ return;
53
+ const command = app.command;
54
+ throw new CliError("conflict", `profile ${other} already signs in to ${options.service} account ${at.account}` +
55
+ `${at.user === undefined ? "" : ` as user ${at.user}`}. Use \`${command} ${other}\`, ` +
56
+ // Another user's token on the account is a second sign-in only where the account has users.
57
+ (at.user === undefined ? "" : `sign it in again with \`${command} ${other} session start\`, `) +
58
+ `or end it with \`${command} ${other} session end\` first`, { reason: "session.duplicate", profile: other, account: at.account });
59
+ };
60
+ /** `claim` for `tokenSessionCommand`: refuses an account another profile is signed in to, then remembers it. */
61
+ export const crmAccountClaim = (app, options) => (env, profile, id, tokens, keyring) => {
62
+ const profiles = options.resolveSettings?.({}, { env, needsProfile: false }).configuredProfiles ?? [];
63
+ refuseTakenCrmAccount(app, options, { env, profile, profiles, tokens, ...(keyring ? { keyring } : {}) }, { account: id });
64
+ rememberAccount(app, profile, id, env);
65
+ };
66
+ /** The store keeps one copy per account, so deleting one profile's data deletes every profile's on that account. */
67
+ const refuseSharedDelete = (app, options, command) => {
68
+ const given = command.opts();
69
+ if (given.deleteData !== true)
70
+ return;
71
+ const resolveSettings = options.resolveSettings ?? environmentOf(command).resolveSettings;
72
+ if (!resolveSettings)
73
+ return;
74
+ const { env, keyring, settings, renderer } = baseContext(command, resolveSettings);
75
+ const context = { env, ...(keyring ? { keyring } : {}) };
76
+ const accountOf = accountBy(app, options);
77
+ const read = (profile) => {
78
+ try {
79
+ return accountOf(profile, context);
80
+ }
81
+ catch {
82
+ throw new CliError("conflict", `${app.command} could not tell which ${options.service} account ${profile} holds, so --delete-data could ` +
83
+ `delete a copy ${profile} still reads. Fix ${profile}'s sign-in, or use --keep-data`, { reason: "account-remove.account-unknown", profile });
84
+ }
85
+ };
86
+ const own = read(settings.profile);
87
+ if (own === undefined)
88
+ return;
89
+ const sharing = settings.profilesHere.filter((one) => one !== settings.profile && read(one) === own);
90
+ if (sharing.length === 0)
91
+ return;
92
+ if (given.dryRun === true) {
93
+ renderer.warn(`without --dry-run this refuses: ${also(sharing)} ${options.service} account ${own}`);
94
+ return;
95
+ }
96
+ const names = sharing.join(", ");
97
+ throw new CliError("conflict", `${also(sharing)} ${options.service} account ${own}, and the store keeps one copy of an account: ` +
98
+ `--delete-data would delete their deals, contacts and companies too. Use --keep-data, or remove ${names} first`, { reason: "account-remove.account-shared", profiles: sharing, account: own });
99
+ };
100
+ const removalOf = (app, options) => {
101
+ const accountOf = accountBy(app, options);
102
+ const folders = (env) => resolvePaths({ appName: app.appName, prefix: app.envPrefix, env });
103
+ return {
104
+ // A CRM's API token has no call that revokes it; the CRM's own settings do.
105
+ signOut: async (profile) => ({
106
+ revoked: null,
107
+ removed: [
108
+ options.signedOut?.(profile) ??
109
+ `the sign-in of ${profile} (the token stays valid in ${options.service} until you delete it there)`,
110
+ ],
111
+ }),
112
+ account: (profile, context) => {
113
+ try {
114
+ const account = accountOf(profile, context);
115
+ return account === undefined ? undefined : { provider: options.provider, account };
116
+ }
117
+ catch {
118
+ // --delete-data was refused before this; --keep-data only names the account it keeps.
119
+ return undefined;
120
+ }
121
+ },
122
+ secrets: (profile, { env, keyring }) => [
123
+ {
124
+ credentials: {
125
+ configDir: folders(env).config,
126
+ service: app.appName,
127
+ envVar: `${app.envPrefix}_TOKEN`,
128
+ env,
129
+ ...(keyring ? { keyring } : {}),
130
+ },
131
+ // An OAuth sign-in's entry; removing a missing one is fine.
132
+ accounts: [`token:${profile}`, oauthAccount(options.provider, profile)],
133
+ },
134
+ ],
135
+ // A profile named after a folder every account shares has no folder of its own there.
136
+ stateFiles: (profile, { env }) => (isShared(profile) ? [] : [join(folders(env).state, "crm", profile)]),
137
+ };
138
+ };
139
+ /**
140
+ * `account remove` of a CRM CLI: cli-core's own, which refuses `--delete-data` while another profile here reads the
141
+ * same account, whose one copy the store shares. Under `--dry-run` it warns instead.
142
+ */
143
+ export const crmAccountCommand = (app, options) => annotate(new Command("account"), { effects: LOCAL_READ })
144
+ .description("this profile on this computer")
145
+ .addCommand(annotate(accountRemoveCommand(app, removalOf(app, options), {
146
+ ...(options.resolveSettings ? { resolveSettings: options.resolveSettings } : {}),
147
+ }), { effects: LOCAL_WRITE }).hook("preAction", (_, action) => refuseSharedDelete(app, options, action)));
@@ -18,6 +18,7 @@ import { safeName } from "../../files/safe-name.js";
18
18
  import { crmIdentityId } from "../../store/sqlite/crm-rows.js";
19
19
  import { parseCrmFileId } from "../files.js";
20
20
  import { foreignContacts, foreignContactsPathFor } from "../foreign-contacts.js";
21
+ import { CRM_SHARED_FOLDERS } from "../state-folders.js";
21
22
  import { integer } from "./records.js";
22
23
  const MB = 1024 * 1024;
23
24
  const PAGE = 500;
@@ -72,7 +73,7 @@ const OWNER_FLAGS = [
72
73
  const iso = (ms) => (ms === null ? null : new Date(ms).toISOString());
73
74
  const segment = (text) => text.replace(/[^\w.-]+/gu, "_");
74
75
  /** The account's own folder of downloads: what the disk cap counts and drops. */
75
- const accountFolder = (app, run) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env: run.env ?? process.env }).state, "crm", "files", segment(`${run.account.provider}-${run.account.account}`));
76
+ const accountFolder = (app, run) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env: run.env ?? process.env }).state, "crm", CRM_SHARED_FOLDERS.files, segment(`${run.account.provider}-${run.account.account}`));
76
77
  /** Each folder from `top` down to `folder` is the OS user's alone, whatever the umask or an earlier run left. */
77
78
  const ownFolder = (top, folder) => {
78
79
  mkdirSync(folder, { recursive: true, mode: 0o700 });
@@ -6,7 +6,9 @@ import type { AccountKey } from "../../store/types.js";
6
6
  import type { CrmSource } from "../source.js";
7
7
  import type { CrmWriteCapabilities } from "../writer.js";
8
8
  import { type CrmWrites } from "../writes.js";
9
+ import { type CrmAccountOptions } from "./account.js";
9
10
  import { type CrmLiveRecord } from "./records.js";
11
+ export * from "./account.js";
10
12
  export { type CsvField, type CsvPage, csvColumnPaths, csvFormatOption, DEAL_CSV_COLUMNS, printCsv, refuseCsvConflict, } from "./csv.js";
11
13
  export { CRM_ORGANIZATIONS_QUERY, CRM_PEOPLE_QUERY, CRM_USERS_QUERY, type CrmLiveRecord, crmOrganizationOf, crmOrganizationSchema, crmPersonOf, crmPersonSchema, crmUserOf, crmUserSchema, } from "./records.js";
12
14
  export { type CrmStoreOptions, openCrmStore } from "./store.js";
@@ -59,6 +61,7 @@ export interface CrmCommandOptions {
59
61
  activities?: boolean;
60
62
  files?: boolean;
61
63
  now?: () => number;
64
+ account?: CrmAccountOptions;
62
65
  }
63
66
  /** What `deals list` and `leads list` narrow by, the same in memo and every CRM CLI (WC-OUT-11). */
64
67
  export declare const DEALS_QUERY: {
@@ -25,12 +25,14 @@ import { openStageTasks } from "../stage-tasks.js";
25
25
  import { crmStatus, syncRecorded } from "../sync.js";
26
26
  import { ownerOf, shortened, viewerOf, withReadableDeal } from "../viewer.js";
27
27
  import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
28
+ import { crmAccountCommand } from "./account.js";
28
29
  import { addCrmChangeCommands } from "./changes.js";
29
30
  import { csvFormatOption, renderCsv } from "./csv.js";
30
31
  import { addCrmFileCommands } from "./files.js";
31
32
  import { pipelineView } from "./pipeline-view.js";
32
33
  import { addCrmRecordCommands, integer } from "./records.js";
33
34
  import { addCrmSearchAll } from "./search-all.js";
35
+ export * from "./account.js";
34
36
  export { csvColumnPaths, csvFormatOption, DEAL_CSV_COLUMNS, printCsv, refuseCsvConflict, } from "./csv.js";
35
37
  export { CRM_ORGANIZATIONS_QUERY, CRM_PEOPLE_QUERY, CRM_USERS_QUERY, crmOrganizationOf, crmOrganizationSchema, crmPersonOf, crmPersonSchema, crmUserOf, crmUserSchema, } from "./records.js";
36
38
  export { openCrmStore } from "./store.js";
@@ -681,6 +683,8 @@ const addCrmCommandsDefinition = (program, options) => {
681
683
  const search = program.commands.find((one) => one.name() === "search") ??
682
684
  annotate(program.command("search"), { effects: NO_EFFECTS }).description("search what the local store holds");
683
685
  addCrmSearchAll(search, { within, app: options.app, example, viewerOf, leads: hasLeads });
686
+ if (options.account)
687
+ program.addCommand(crmAccountCommand(options.app, options.account));
684
688
  };
685
689
  // honoursDryRun: a host program other than `run` would otherwise let a write through under --dry-run.
686
690
  export const addCrmCommands = honoursDryRun(sharedCommand(addCrmCommandsDefinition));
@@ -2,13 +2,14 @@ import { readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { CliError, resolvePaths, writeSecurely } from "@wirecat/cli-base";
4
4
  import { withFileLockAsync } from "../sends/file-lock.js";
5
+ import { CRM_SHARED_FOLDERS } from "./state-folders.js";
5
6
  /**
6
7
  * The owner's rule (NEED-2487, NEED-2703 B): a user sees at most this many other people's records a UTC day: a
7
8
  * contact's or company's details, or a deal's, lead's, contact's or company's files.
8
9
  */
9
10
  export const DAILY_FOREIGN_CONTACTS = 100;
10
11
  /** Where the day's count of one CRM user is kept: the CLI's state folder, a file per account and user. */
11
- export const foreignContactsPathFor = (app, account, env = process.env, user) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, "crm", "foreign-contacts", `${[account.provider, account.account, ...(user ? [user] : [])].join("-").replace(/[^\w.-]+/gu, "_")}.json`);
12
+ export const foreignContactsPathFor = (app, account, env = process.env, user) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, "crm", CRM_SHARED_FOLDERS.foreignContacts, `${[account.provider, account.account, ...(user ? [user] : [])].join("-").replace(/[^\w.-]+/gu, "_")}.json`);
12
13
  const shownIn = (file, day) => {
13
14
  try {
14
15
  const found = JSON.parse(readFileSync(file, "utf8"));
@@ -0,0 +1,5 @@
1
+ /** The folders cli-core keeps for every account under `<state>/crm/`, beside each profile's own `<state>/crm/<profile>`. */
2
+ export declare const CRM_SHARED_FOLDERS: {
3
+ readonly files: "files";
4
+ readonly foreignContacts: "foreign-contacts";
5
+ };
@@ -0,0 +1,2 @@
1
+ /** The folders cli-core keeps for every account under `<state>/crm/`, beside each profile's own `<state>/crm/<profile>`. */
2
+ export const CRM_SHARED_FOLDERS = { files: "files", foreignContacts: "foreign-contacts" };
@@ -7,7 +7,7 @@ export declare const REASONS: ErrorReason[];
7
7
  * Detail keys an error from this package may carry, until each is registered on its own reason. Not `cause`:
8
8
  * that can hold a provider's or SQLite's raw text.
9
9
  */
10
- export declare const DETAILS: readonly ["holders", "profile", "contracts", "calendars", "allowed", "alternative", "arguments", "at", "available", "batch", "budget", "built", "candidates", "chat", "chat_id", "cli", "column", "complete", "emitted_bytes", "exact", "file", "forum", "guide", "hint", "id", "index", "kind", "limit", "limit_source", "line", "max_bytes", "model", "name", "operation_id", "operation_ids", "text_limit", "store_refused_in", "partial_output", "parent", "path", "permission", "person_ids", "previous_chat_id", "profiles", "provider_error", "provider", "recovery", "reference", "remembered", "retry_at", "retry_after_ms", "runtime", "saved", "scheduled_for", "script", "sent", "sent_count", "settlement_failed", "span", "sqlite", "stage", "standing", "state", "stderr", "term", "total", "upgraded", "wanted"];
10
+ export declare const DETAILS: readonly ["account", "holders", "profile", "contracts", "calendars", "allowed", "alternative", "arguments", "at", "available", "batch", "budget", "built", "candidates", "chat", "chat_id", "cli", "column", "complete", "emitted_bytes", "exact", "file", "forum", "guide", "hint", "id", "index", "kind", "limit", "limit_source", "line", "max_bytes", "model", "name", "operation_id", "operation_ids", "text_limit", "store_refused_in", "partial_output", "parent", "path", "permission", "person_ids", "previous_chat_id", "profiles", "provider_error", "provider", "recovery", "reference", "remembered", "retry_at", "retry_after_ms", "runtime", "saved", "scheduled_for", "script", "sent", "sent_count", "settlement_failed", "span", "sqlite", "stage", "standing", "state", "stderr", "term", "total", "upgraded", "wanted"];
11
11
  /** What a CLI adds to the shared registry: its own reasons, and the detail keys its adapters raise. */
12
12
  export interface AppErrors {
13
13
  reasons?: readonly ErrorReason[];
@@ -50,6 +50,14 @@ const SIGN_IN = [
50
50
  validation("profile.missing", "no profile named, and none is picked for the owner; details.profiles lists the ones here"),
51
51
  ["profile.unknown", "not_found", "no profile by this name on this computer; details.profiles lists the ones here"],
52
52
  ["account-remove.busy", "conflict", "a serve or a sync runs for this profile; stop it first"],
53
+ ["account-remove.account-shared", "conflict", "another profile reads the same account, whose copy the store shares"],
54
+ ["session.duplicate", "conflict", "another profile here already signs in to this account as this user"],
55
+ [
56
+ "account-remove.account-unknown",
57
+ "conflict",
58
+ "which account another profile holds could not be read, so --delete-data waits",
59
+ ],
60
+ validation("profile.reserved", "the profile name is a folder every CRM account shares; pick another"),
53
61
  ["account-remove.unconfirmed", "confirmation_required", "removing an account asks first; add --yes"],
54
62
  ["account-remove.path-outside", "configuration_error", "the tool named a path outside its own folders"],
55
63
  [
@@ -629,6 +637,8 @@ const OTHERS = [
629
637
  validation("identity.agent-unnamed", "an agent's link names the agent, and never as the owner"),
630
638
  validation("identity.not-shared", "only a match on a shared mailbox can say the mailbox is a company's"),
631
639
  ["organization.not-found", "not_found", "no stored organization has that id"],
640
+ validation("organization.own", "the organization is one of your own companies and is never deleted"),
641
+ validation("organization.erase-blocked", "an invoice, order, subscription or a row the organization wrote still names it; change those first, nothing was deleted"),
632
642
  validation("organization.unnamed", "a free mailbox names no company; name the organization or the company"),
633
643
  validation("organization.ambiguous", "more than one organization matches; name the one meant as a reference"),
634
644
  validation("identity.shared-phone", "more than six people share the phone number, so it proposes no one"),
@@ -766,6 +776,7 @@ export const REASONS = defineReasons([
766
776
  * that can hold a provider's or SQLite's raw text.
767
777
  */
768
778
  export const DETAILS = [
779
+ "account",
769
780
  "holders",
770
781
  "profile",
771
782
  "contracts",
@@ -24,7 +24,10 @@ export interface FileMirrorOptions {
24
24
  dryRun?: boolean;
25
25
  /** Lets a run delete this many files although the guard would stop it. */
26
26
  allowDeletions?: number;
27
- /** Lets a run replace this many existing files, on either side, although the guard would stop it. */
27
+ /**
28
+ * Lets a run replace this many existing files, on either side, although the guard would stop it. An app with a
29
+ * `--replace` switch passes `Number.POSITIVE_INFINITY`.
30
+ */
28
31
  allowReplacements?: number;
29
32
  /** Globs of paths the mirror leaves alone on both sides, as `excludedBy` reads them. */
30
33
  exclude?: string[];
@@ -70,7 +73,7 @@ export interface MirrorHints {
70
73
  sync: string;
71
74
  /** How a sync allows deletions: `--allow-deletions <count>`. */
72
75
  allowDeletions: string;
73
- /** How a sync allows replacements: `--replace`, the vocabulary's overwrite switch. */
76
+ /** How a sync allows replacements: `--allow-replacements <count>`. */
74
77
  allowReplacements: string;
75
78
  /** How to leave a folder out: `ydisk work mirrors update <id> --ignore <path>`. */
76
79
  exclude: string;
@@ -14,7 +14,7 @@ const HINTS = {
14
14
  repin: "--repin",
15
15
  sync: "sync",
16
16
  allowDeletions: "--allow-deletions <count>",
17
- allowReplacements: "--replace",
17
+ allowReplacements: "--allow-replacements <count>",
18
18
  exclude: "--ignore <path>",
19
19
  };
20
20
  /**
@@ -85,6 +85,7 @@ export { type NearestNote, NOTE_FIELDS, type NoteChunkToEmbed, type NoteHit, typ
85
85
  export type { FileNoteInput, Link, LinkInput, LinkListFilter, Note, NoteFolder, NotesStore, NoteTag, } from "./sqlite/notes.js";
86
86
  export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from "./sqlite/orders.js";
87
87
  export type { OrganizationFilter } from "./sqlite/organization-categories.js";
88
+ export type { OrganizationErasure } from "./sqlite/organization-erase.js";
88
89
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
89
90
  export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
90
91
  export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type KeptPerson, type PersonDoubt, type PersonDoubts, type TestDataPerson, } from "./sqlite/person-doubts.js";
@@ -3,6 +3,7 @@ import { calendarCursorKey, calendarWritesOver } from "./calendar.js";
3
3
  import { forgetCalendarRows } from "./calendar-forget.js";
4
4
  import { eq, inArray, sql } from "./drizzle/core.js";
5
5
  import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
6
+ import { eraseImportedOrganizations, importedOrganizations } from "./organization-erase.js";
6
7
  import { eraseImportedPeople, importedPeople } from "./person-erase.js";
7
8
  import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
8
9
  import { dropUnusedVectors } from "./vector-index.js";
@@ -11,6 +12,7 @@ export const purgeAccount = (context, accountKey) => {
11
12
  const { orm, database, now } = context;
12
13
  const unseenBefore = unreferenced(database, "identities");
13
14
  const imported = importedPeople(database, accountKey);
15
+ const importedCompanies = importedOrganizations(database, accountKey);
14
16
  const at = now();
15
17
  const meetingIds = "SELECT id FROM meetings WHERE account_id = ?";
16
18
  const transcriptIds = `SELECT id FROM meeting_transcripts WHERE meeting_id IN (${meetingIds})`;
@@ -114,6 +116,7 @@ export const purgeAccount = (context, accountKey) => {
114
116
  orm.delete(accounts).where(eq(accounts.id, accountKey)).run();
115
117
  dropOrphanPeople(database, unseenBefore);
116
118
  eraseImportedPeople(context, imported);
119
+ eraseImportedOrganizations(context, importedCompanies);
117
120
  forgetDanglingEvidence(database, at);
118
121
  dropUnusedVectors(database, hashes);
119
122
  // The links' delete trigger writes a revision naming the account it is purging; the history goes with the links.
@@ -7,6 +7,7 @@ export const STAGE_ENTRY_DAYS = 90;
7
7
  /** A stage entered longer ago than this opens no task: the copy missed the deal for more than a sync or two. */
8
8
  const STAGE_TASK_DAYS = 7;
9
9
  const DAY = 86_400_000;
10
+ const SECOND = 1000;
10
11
  /**
11
12
  * Every stage entry of the kind's rows in one pipeline, or of one row, oldest first per row: the CRM's own history
12
13
  * where a row has any, else the copy's diffs, never both for one row. Entries handled or expired stay history.
@@ -79,6 +80,8 @@ export const crmStageEntriesOver = (context) => {
79
80
  const accountId = findAccountPk(context, key);
80
81
  if (accountId === undefined)
81
82
  return [];
83
+ // A CRM's history keeps whole seconds: a move in the second the rules were set would read as made before them.
84
+ const from = Math.max(Math.floor(since / SECOND) * SECOND, at - STAGE_TASK_DAYS * DAY);
82
85
  return database
83
86
  .prepare("SELECT r.id, r.external_id, json_extract(r.fields, '$.kind') AS kind, coalesce(d.id, l.id) AS item_id, " +
84
87
  "s.external_id AS stage, s.name AS stage_name, p.name AS pipeline_name FROM records r " +
@@ -91,7 +94,7 @@ export const crmStageEntriesOver = (context) => {
91
94
  "WHERE r.account_id = ? AND r.type = ? AND r.deleted_at IS NULL AND coalesce(d.id, l.id) IS NOT NULL " +
92
95
  "AND json_extract(r.fields, '$.handled') IS NULL AND json_extract(r.fields, '$.at') >= ? " +
93
96
  "ORDER BY json_extract(r.fields, '$.at'), r.id")
94
- .all(accountId, STAGE_ENTRY_RECORD, Math.max(since, at - STAGE_TASK_DAYS * DAY))
97
+ .all(accountId, STAGE_ENTRY_RECORD, from)
95
98
  .map((row) => {
96
99
  const ref = `${String(row.kind)}:${String(row.item_id)}`;
97
100
  return {
@@ -0,0 +1,19 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ export declare const count: (database: CacheDatabase, sql: string, ...params: (string | number)[]) => number;
3
+ /**
4
+ * What deleting an entity does to the rows that name it, read from the store's own `*_type`/`*_id` pointers and
5
+ * foreign keys, so the plan shown and the delete run read one list. A row that only ties something to the entity
6
+ * goes; one that can be without it loses the pointer; one that cannot, or that the entity wrote, blocks the delete.
7
+ */
8
+ export declare class ErasePlan {
9
+ #private;
10
+ private readonly database;
11
+ readonly deleted: Record<string, number>;
12
+ readonly detached: Record<string, number>;
13
+ readonly blocked: string[];
14
+ constructor(database: CacheDatabase);
15
+ pointers(type: string, among: string, params: (string | number)[]): this;
16
+ /** Foreign keys to `target`, but those in `own`, which the caller deletes with the entity. */
17
+ foreignKeys(target: string, id: number, own: ReadonlySet<string>): this;
18
+ run(): void;
19
+ }
@@ -0,0 +1,74 @@
1
+ import { pointerPairs } from "./entity-types.js";
2
+ /** Who wrote or approved a row: the row is the writer's history, never silently rewritten. */
3
+ const AUTHORS = new Set(["author", "confirmed_by", "decided_by", "proposed_by", "actor", "closed_by"]);
4
+ /** A link is about both ends: one that loses an end means nothing, so it goes. */
5
+ const LINK_ROWS = new Set(["links", "mentions", "task_assignments"]);
6
+ const hasChildren = (database, table) => database
7
+ .prepare(`SELECT 1 FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f WHERE m.type = 'table' AND f."table" = ?
8
+ LIMIT 1`)
9
+ .get(table) !== undefined;
10
+ const nullable = (database, table, column) => Number(database.prepare(`SELECT "notnull" AS n FROM pragma_table_info('${table}') WHERE name = ?`).get(column)?.n) ===
11
+ 0;
12
+ export const count = (database, sql, ...params) => Number(database.prepare(`SELECT count(*) AS n FROM ${sql}`).get(...params)?.n);
13
+ /**
14
+ * What deleting an entity does to the rows that name it, read from the store's own `*_type`/`*_id` pointers and
15
+ * foreign keys, so the plan shown and the delete run read one list. A row that only ties something to the entity
16
+ * goes; one that can be without it loses the pointer; one that cannot, or that the entity wrote, blocks the delete.
17
+ */
18
+ export class ErasePlan {
19
+ database;
20
+ deleted = {};
21
+ detached = {};
22
+ blocked = [];
23
+ #steps = [];
24
+ constructor(database) {
25
+ this.database = database;
26
+ }
27
+ pointers(type, among, params) {
28
+ for (const { table, pointer } of pointerPairs(this.database)) {
29
+ const where = `${pointer}_type = '${type}' AND ${pointer}_id IN (${among})`;
30
+ const n = count(this.database, `"${table}" WHERE ${where}`, ...params);
31
+ if (n === 0)
32
+ continue;
33
+ const key = `${table}.${pointer}`;
34
+ if (LINK_ROWS.has(table) || !nullable(this.database, table, `${pointer}_id`)) {
35
+ if (!LINK_ROWS.has(table) && (AUTHORS.has(pointer) || hasChildren(this.database, table))) {
36
+ this.blocked.push(`${n} ${table} (${pointer})`);
37
+ continue;
38
+ }
39
+ this.#add(this.deleted, key, n, `DELETE FROM "${table}" WHERE ${where}`, params);
40
+ }
41
+ else
42
+ this.#add(this.detached, key, n, `UPDATE "${table}" SET ${pointer}_type = NULL, ${pointer}_id = NULL WHERE ${where}`, params);
43
+ }
44
+ return this;
45
+ }
46
+ /** Foreign keys to `target`, but those in `own`, which the caller deletes with the entity. */
47
+ foreignKeys(target, id, own) {
48
+ for (const row of this.database
49
+ .prepare(`SELECT m.name AS tbl, f."from" AS col FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f
50
+ WHERE m.type = 'table' AND f."table" = ?`)
51
+ .all(target)) {
52
+ const table = String(row.tbl);
53
+ const column = String(row.col);
54
+ if (own.has(table))
55
+ continue;
56
+ const n = count(this.database, `"${table}" WHERE "${column}" = ?`, id);
57
+ if (n === 0)
58
+ continue;
59
+ if (nullable(this.database, table, column))
60
+ this.#add(this.detached, `${table}.${column}`, n, `UPDATE "${table}" SET "${column}" = NULL WHERE "${column}" = ?`, [id]);
61
+ else
62
+ this.blocked.push(`${n} ${table} (${column})`);
63
+ }
64
+ return this;
65
+ }
66
+ run() {
67
+ for (const step of this.#steps)
68
+ step();
69
+ }
70
+ #add(into, key, n, sql, params) {
71
+ into[key] = (into[key] ?? 0) + n;
72
+ this.#steps.push(() => this.database.prepare(sql).run(...params));
73
+ }
74
+ }
@@ -171,7 +171,8 @@ export const upsertMessage = (context, key, accountKey, chatKey, received, via,
171
171
  for (const field of ["views", "comments"])
172
172
  if (!validCounter(incoming[field]) && validCounter(previous[field]))
173
173
  incoming[field] = previous[field];
174
- fields.metadata = JSON.stringify(edit ? { ...previous, ...incoming } : incoming);
174
+ // A server search hit is a partial copy: what it leaves out (a thread's reply count) is not gone.
175
+ fields.metadata = JSON.stringify(edit || via === "search" ? { ...previous, ...incoming } : incoming);
175
176
  }
176
177
  }
177
178
  catch {
@@ -0,0 +1,29 @@
1
+ import type { Decider } from "../decisions.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ import type { StoreContext } from "./open.js";
4
+ export interface OrganizationErasure {
5
+ organization: string;
6
+ name: string;
7
+ /** `false`: what `erase` would do, nothing changed. */
8
+ erased: boolean;
9
+ /** Identities the organization held, such as its domain; the identities stay, the holding goes. */
10
+ identities: string[];
11
+ /** Rows that only tied something to the organization, such as a tag, a link or a mention, by `table.column`. */
12
+ deleted: Record<string, number>;
13
+ /** Rows that stay and lose the organization, such as a deal, a lead, a project or an account. */
14
+ detached: Record<string, number>;
15
+ }
16
+ /**
17
+ * Deletes an organization and what memo knows of it alone: the tags, links, aliases and mentions that name it, and
18
+ * which identities it held. A deal, lead, project, account, fact or note that names it stays and loses the name.
19
+ * Refused for one of the owner's own companies, and while an invoice, order, subscription or a row it wrote cannot
20
+ * be without it. `apply: false` answers the same without changing anything.
21
+ */
22
+ export declare const eraseOrganization: (context: StoreContext, ref: string, by: Decider, apply: boolean) => OrganizationErasure;
23
+ /** The organizations an account's records made: read before a purge deletes the records. */
24
+ export declare const importedOrganizations: (database: CacheDatabase, accountKey: number) => number[];
25
+ /**
26
+ * After a purge, the organizations only its records made go too: no other row names them. One the owner tagged,
27
+ * linked, gave a deal to or calls his own stays.
28
+ */
29
+ export declare const eraseImportedOrganizations: (context: StoreContext, organizations: readonly number[]) => void;
@@ -0,0 +1,83 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { ErasePlan } from "./erase-plan.js";
3
+ import { forgetDanglingEvidence } from "./evidence-signature.js";
4
+ import { ownerOnly } from "./person-merges.js";
5
+ const OWN_ROWS = new Set(["organization_identities"]);
6
+ const organizationOf = (database, ref) => {
7
+ const asked = /^(?:organization:)?([1-9]\d*)$/u.exec(ref.trim())?.[1];
8
+ const row = asked === undefined
9
+ ? undefined
10
+ : database.prepare("SELECT id, name, metadata FROM organizations WHERE id = ?").get(Number(asked));
11
+ if (row === undefined)
12
+ throw new CliError("not_found", `the store has no organization for "${ref}"`, { reason: "organization.not-found" });
13
+ return {
14
+ id: Number(row.id),
15
+ name: String(row.name),
16
+ own: [true, 1].includes(JSON.parse(String(row.metadata ?? "{}"))?.own),
17
+ };
18
+ };
19
+ /**
20
+ * Deletes an organization and what memo knows of it alone: the tags, links, aliases and mentions that name it, and
21
+ * which identities it held. A deal, lead, project, account, fact or note that names it stays and loses the name.
22
+ * Refused for one of the owner's own companies, and while an invoice, order, subscription or a row it wrote cannot
23
+ * be without it. `apply: false` answers the same without changing anything.
24
+ */
25
+ export const eraseOrganization = (context, ref, by, apply) => {
26
+ ownerOnly(by, "deletes an organization");
27
+ const { database } = context;
28
+ const organization = organizationOf(database, ref);
29
+ if (organization.own)
30
+ throw new CliError("validation_error", `organization:${organization.id} is one of your own companies`, {
31
+ reason: "organization.own",
32
+ });
33
+ const identities = database
34
+ .prepare(`SELECT i.provider || ':' || i.external_id AS ref FROM organization_identities o
35
+ JOIN identities i ON i.id = o.identity_id WHERE o.organization_id = ? ORDER BY i.id`)
36
+ .all(organization.id)
37
+ .map((one) => String(one.ref));
38
+ const plan = new ErasePlan(database)
39
+ .pointers("organization", "?", [organization.id])
40
+ .foreignKeys("organizations", organization.id, OWN_ROWS);
41
+ if (plan.blocked.length > 0)
42
+ throw new CliError("validation_error", `organization:${organization.id} is still named by ${plan.blocked.join(", ")}; change those first — nothing ` +
43
+ "was deleted", { reason: "organization.erase-blocked", blocked: plan.blocked });
44
+ const answer = (erased) => ({
45
+ organization: `organization:${organization.id}`,
46
+ name: organization.name,
47
+ erased,
48
+ identities,
49
+ deleted: plan.deleted,
50
+ detached: plan.detached,
51
+ });
52
+ if (!apply)
53
+ return answer(false);
54
+ plan.run();
55
+ database.prepare("DELETE FROM organization_identities WHERE organization_id = ?").run(organization.id);
56
+ database.prepare("DELETE FROM organizations WHERE id = ?").run(organization.id);
57
+ forgetDanglingEvidence(database, context.now());
58
+ return answer(true);
59
+ };
60
+ /** The organizations an account's records made: read before a purge deletes the records. */
61
+ export const importedOrganizations = (database, accountKey) => database
62
+ .prepare("SELECT DISTINCT entity_id AS id FROM records WHERE account_id = ? AND entity_type = 'organization'")
63
+ .all(accountKey)
64
+ .map(({ id }) => Number(id));
65
+ /**
66
+ * After a purge, the organizations only its records made go too: no other row names them. One the owner tagged,
67
+ * linked, gave a deal to or calls his own stays.
68
+ */
69
+ export const eraseImportedOrganizations = (context, organizations) => {
70
+ for (const id of organizations) {
71
+ if (context.database.prepare("SELECT 1 FROM organizations WHERE id = ?").get(id) === undefined)
72
+ continue;
73
+ try {
74
+ const plan = eraseOrganization(context, String(id), "owner", false);
75
+ if (Object.keys(plan.deleted).length === 0 && Object.keys(plan.detached).length === 0)
76
+ eraseOrganization(context, String(id), "owner", true);
77
+ }
78
+ catch (error) {
79
+ if (!(error instanceof CliError))
80
+ throw error;
81
+ }
82
+ }
83
+ };
@@ -1,7 +1,9 @@
1
1
  import { type QueryAst } from "@wirecat/cli-base/query";
2
+ import type { Decider } from "../decisions.js";
2
3
  import type { Organization } from "./knowledge.js";
3
4
  import type { StoreContext } from "./open.js";
4
5
  import { type OrganizationFilter } from "./organization-categories.js";
6
+ import { type OrganizationErasure } from "./organization-erase.js";
5
7
  type Row = Record<string, unknown>;
6
8
  export declare const organizationOf: (row: Row) => Organization;
7
9
  export interface OrganizationsStore {
@@ -21,6 +23,13 @@ export interface OrganizationsStore {
21
23
  }>;
22
24
  /** The owner's own companies: the owner's mark, else a CRM's own-company flag (`metadata.own`). */
23
25
  ownOrganizations(): Promise<Organization[]>;
26
+ /**
27
+ * Deletes an organization and what memo knows of it alone; see `eraseOrganization`. `apply: false` answers what
28
+ * would go and changes nothing. The owner's alone; refused for the owner's own companies.
29
+ */
30
+ eraseOrganization(organization: string, by: Decider, options: {
31
+ apply: boolean;
32
+ }): Promise<OrganizationErasure>;
24
33
  }
25
- export declare const organizationsStoreOver: ({ database, now }: StoreContext) => OrganizationsStore;
34
+ export declare const organizationsStoreOver: (context: StoreContext) => OrganizationsStore;
26
35
  export {};
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { evaluate, timezoneOf, walkQuery } from "@wirecat/cli-base/query";
3
3
  import { ORGANIZATIONS_QUERY } from "../knowledge-query.js";
4
4
  import { categorySql } from "./organization-categories.js";
5
+ import { eraseOrganization } from "./organization-erase.js";
5
6
  import { queryFilter } from "./query-filter.js";
6
7
  import { thingOf } from "./things.js";
7
8
  import { write } from "./transaction.js";
@@ -13,7 +14,11 @@ export const organizationOf = (row) => ({
13
14
  scope: row.scope,
14
15
  createdAt: new Date(Number(row.created_at)).toISOString(),
15
16
  });
16
- export const organizationsStoreOver = ({ database, now }) => ({
17
+ export const organizationsStoreOver = (context) => ({
18
+ eraseOrganization: async (organization, by, { apply }) => write(context.database, () => eraseOrganization(context, organization, by, apply)),
19
+ ...organizationsReadsOver(context),
20
+ });
21
+ const organizationsReadsOver = ({ database, now }) => ({
17
22
  organizations: async (query, filter = {}) => {
18
23
  const category = categorySql(filter, now());
19
24
  const inCategory = category ? ` AND ${category.sql}` : "";
@@ -1,24 +1,12 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { OWN, referencesTo } from "./accounts.js";
3
- import { pointerPairs } from "./entity-types.js";
3
+ import { count, ErasePlan } from "./erase-plan.js";
4
4
  import { forgetDanglingEvidence } from "./evidence-signature.js";
5
5
  import { forgetErasedLinks } from "./identity-link-rows.js";
6
6
  import { forgetErasedSplits } from "./identity-split-proposals.js";
7
7
  import { currentPerson } from "./merged-persons.js";
8
8
  import { ownerOnly } from "./person-merges.js";
9
9
  import { forgetErasedTestData } from "./test-people.js";
10
- /** Who wrote or approved a row: the row is the writer's history, never silently rewritten. */
11
- const AUTHORS = new Set(["author", "confirmed_by", "decided_by", "proposed_by", "actor", "closed_by"]);
12
- /** Business rows that cannot be without the person: the owner moves them first. */
13
- const blocking = (table, pointer, database) => AUTHORS.has(pointer) || hasChildren(database, table);
14
- const hasChildren = (database, table) => database
15
- .prepare(`SELECT 1 FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f WHERE m.type = 'table' AND f."table" = ?
16
- LIMIT 1`)
17
- .get(table) !== undefined;
18
- const nullable = (database, table, column) => Number(database.prepare(`SELECT "notnull" AS n FROM pragma_table_info('${table}') WHERE name = ?`).get(column)?.n) ===
19
- 0;
20
- /** A link is about both ends: one that loses an end means nothing, so it goes. */
21
- const LINK_ROWS = new Set(["links", "mentions", "task_assignments"]);
22
10
  const personOf = (context, uid) => {
23
11
  const asked = /^(?:person:)?([1-9]\d*)$/u.exec(uid.trim())?.[1];
24
12
  const known = asked === undefined ? undefined : context.database.prepare("SELECT id FROM persons WHERE id = ?").get(Number(asked));
@@ -26,7 +14,6 @@ const personOf = (context, uid) => {
26
14
  throw new CliError("not_found", `the store has no person for "${uid}"`, { reason: "person.unknown" });
27
15
  return currentPerson(context.database, Number(known.id));
28
16
  };
29
- const count = (database, sql, ...params) => Number(database.prepare(`SELECT count(*) AS n FROM ${sql}`).get(...params)?.n);
30
17
  /**
31
18
  * Deletes a person and what memo knows of them alone: their identities, the tags, links, aliases and mentions that
32
19
  * name them, their involvements. A fact, a note, a record or a task that names them stays and loses the name. A
@@ -57,35 +44,8 @@ export const erasePerson = (context, uid, by, apply) => {
57
44
  const going = linked.filter(({ id }) => !named.has(id));
58
45
  const kept = linked.filter(({ id }) => named.has(id));
59
46
  const goingIds = JSON.stringify(going.map(({ id }) => id));
60
- const deleted = {};
61
- const detached = {};
62
- const blocked = [];
63
- const plan = [];
64
- const pointing = (type, among, params) => {
65
- for (const { table, pointer } of pointerPairs(database)) {
66
- const where = `${pointer}_type = '${type}' AND ${pointer}_id IN (${among})`;
67
- const n = count(database, `"${table}" WHERE ${where}`, ...params);
68
- if (n === 0)
69
- continue;
70
- const key = `${table}.${pointer}`;
71
- if (LINK_ROWS.has(table) || !nullable(database, table, `${pointer}_id`)) {
72
- if (!LINK_ROWS.has(table) && blocking(table, pointer, database)) {
73
- blocked.push(`${n} ${table} (${pointer})`);
74
- continue;
75
- }
76
- deleted[key] = (deleted[key] ?? 0) + n;
77
- plan.push(() => database.prepare(`DELETE FROM "${table}" WHERE ${where}`).run(...params));
78
- }
79
- else {
80
- detached[key] = (detached[key] ?? 0) + n;
81
- plan.push(() => database
82
- .prepare(`UPDATE "${table}" SET ${pointer}_type = NULL, ${pointer}_id = NULL WHERE ${where}`)
83
- .run(...params));
84
- }
85
- }
86
- };
87
- pointing("person", "?", [person]);
88
- pointing("identity", theirs, [goingIds]);
47
+ const plan = new ErasePlan(database).pointers("person", "?", [person]).pointers("identity", theirs, [goingIds]);
48
+ const { deleted, detached, blocked } = plan;
89
49
  const involvements = count(database, `involvements WHERE person_id = ? OR identity_id IN (${theirs})`, person, goingIds);
90
50
  if (involvements > 0)
91
51
  deleted["involvements.person"] = (deleted["involvements.person"] ?? 0) + involvements;
@@ -105,8 +65,7 @@ export const erasePerson = (context, uid, by, apply) => {
105
65
  });
106
66
  if (!apply)
107
67
  return answer(false);
108
- for (const step of plan)
109
- step();
68
+ plan.run();
110
69
  database.prepare(`DELETE FROM involvements WHERE person_id = ? OR identity_id IN (${theirs})`).run(person, goingIds);
111
70
  database.prepare("UPDATE bots SET owner_person_id = NULL WHERE owner_person_id = ?").run(person);
112
71
  for (const table of ["account_identities", "organization_identities", "identity_revisions"])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.721.0",
3
+ "version": "0.722.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",
@@ -334,7 +334,7 @@
334
334
  "@types/pngjs": "6.0.5",
335
335
  "@types/ssh2": "1.15.5",
336
336
  "@vitest/coverage-v8": "^5.0.5",
337
- "@wirecat/cli-base": "0.126.1",
337
+ "@wirecat/cli-base": "0.127.0",
338
338
  "@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
339
339
  "ajv": "8.17.1",
340
340
  "commander": "15.0.0",