@wirecat/cli-core 0.600.0 → 0.602.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 (80) hide show
  1. package/CHANGELOG.md +83 -1
  2. package/dist/calendar/cli/search-all.js +9 -2
  3. package/dist/cli/app-doctor-command.js +18 -10
  4. package/dist/cli/bot/api-input.js +8 -2
  5. package/dist/cli/context.d.ts +2 -0
  6. package/dist/cli/contract-templates.js +2 -1
  7. package/dist/cli/effects.d.ts +5 -0
  8. package/dist/cli/effects.js +5 -0
  9. package/dist/cli/index.d.ts +2 -1
  10. package/dist/cli/index.js +2 -1
  11. package/dist/cli/messenger/search-answers.d.ts +5 -1
  12. package/dist/cli/messenger/search-answers.js +4 -1
  13. package/dist/cli/messenger/store-maintenance-command.d.ts +2 -0
  14. package/dist/cli/messenger/store-maintenance-command.js +1 -0
  15. package/dist/cli/new-file.d.ts +2 -0
  16. package/dist/cli/new-file.js +13 -0
  17. package/dist/cli/program.js +3 -0
  18. package/dist/cli/search-left-out.d.ts +27 -0
  19. package/dist/cli/search-left-out.js +31 -0
  20. package/dist/cli/store-recover.d.ts +2 -0
  21. package/dist/cli/store-recover.js +2 -0
  22. package/dist/crm/cli/index.js +2 -7
  23. package/dist/crm/cli/search-all.js +17 -2
  24. package/dist/crm/index.d.ts +1 -1
  25. package/dist/crm/index.js +1 -1
  26. package/dist/crm/writes.d.ts +17 -0
  27. package/dist/crm/writes.js +31 -16
  28. package/dist/errors/reasons.js +16 -0
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.js +1 -1
  31. package/dist/meetings/cli/index.d.ts +14 -0
  32. package/dist/meetings/cli/index.js +18 -6
  33. package/dist/meetings/hit-query.d.ts +2 -0
  34. package/dist/meetings/hit-query.js +2 -0
  35. package/dist/meetings/index.d.ts +2 -2
  36. package/dist/meetings/index.js +1 -1
  37. package/dist/meetings/mcp/index.d.ts +15 -15
  38. package/dist/meetings/pull.d.ts +13 -1
  39. package/dist/meetings/pull.js +34 -8
  40. package/dist/meetings/source.d.ts +5 -0
  41. package/dist/resolve.d.ts +2 -2
  42. package/dist/resolve.js +4 -3
  43. package/dist/search/lucene/plain.d.ts +9 -0
  44. package/dist/search/lucene/plain.js +124 -0
  45. package/dist/services/events-search.js +2 -0
  46. package/dist/services/index.d.ts +1 -0
  47. package/dist/services/index.js +1 -0
  48. package/dist/services/meeting-hit-search.js +3 -2
  49. package/dist/services/messages-archive-search.js +3 -0
  50. package/dist/services/notes-search.js +3 -0
  51. package/dist/services/search-all.d.ts +4 -1
  52. package/dist/services/search-all.js +6 -3
  53. package/dist/speech/local.d.ts +2 -1
  54. package/dist/speech/local.js +12 -1
  55. package/dist/speech/recognize.d.ts +2 -0
  56. package/dist/speech/recognize.js +15 -0
  57. package/dist/store/damage.js +6 -1
  58. package/dist/store/decision-requests.d.ts +10 -0
  59. package/dist/store/decision-requests.js +16 -0
  60. package/dist/store/health.d.ts +15 -0
  61. package/dist/store/health.js +31 -1
  62. package/dist/store/index.d.ts +3 -1
  63. package/dist/store/index.js +1 -0
  64. package/dist/store/recover.d.ts +14 -2
  65. package/dist/store/recover.js +179 -95
  66. package/dist/store/sqlite/deals.d.ts +3 -1
  67. package/dist/store/sqlite/deals.js +2 -2
  68. package/dist/store/sqlite/decision-requests.d.ts +59 -0
  69. package/dist/store/sqlite/decision-requests.js +111 -0
  70. package/dist/store/sqlite/manifest.js +2 -0
  71. package/dist/store/sqlite/meeting-hit-search.js +3 -2
  72. package/dist/store/sqlite/migrations.generated.js +12 -0
  73. package/dist/store/sqlite/schema/decision-requests.d.ts +233 -0
  74. package/dist/store/sqlite/schema/decision-requests.js +20 -0
  75. package/dist/store/sqlite/schema.d.ts +1 -0
  76. package/dist/store/sqlite/schema.js +1 -0
  77. package/dist/store/store.d.ts +3 -0
  78. package/dist/store/store.js +5 -0
  79. package/docs/search/recipes.json +0 -1
  80. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -5,7 +5,89 @@ 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
- ## Unreleased
8
+ ## 0.602.0 — 07.11.2026
9
+
10
+ ### Fixed
11
+
12
+ - **`store recover run` refuses while another recovery runs, and no longer fails because a tool only read the store.**
13
+ A recovery keeps a lock file beside the store (`<store>.recover-lock`, with its process number); a second run is
14
+ refused with the reason `store.recovering`, and `store recover` and `storeHolders` list the running one. A lock whose
15
+ process ended is taken over. The check for writes during the recovery now asks SQLite (`PRAGMA data_version` on a
16
+ connection kept open to the swap, and the file's inode) instead of comparing file times and sizes, which a reader's
17
+ open and close changed without changing a row (`store.changed-during-recovery` on a store nobody wrote to).
18
+ - **A recovery clears values that are not valid JSON, and `doctor --deep` reports them.** `.recover` copied a damaged
19
+ value that still read, and a JSON read of its row then failed with "malformed JSON" (`mail sync` on an `emails.headers`
20
+ value). Every `metadata` column and the other columns the tools read as JSON (`emails.headers`, `accounts.settings`,
21
+ `messages.mentions`, `messages.reply_to`, …) are checked: an invalid value is set to NULL, or its row is dropped where
22
+ the column may not be NULL, and the recovery lists each column as `invalidJson`. The deep health check
23
+ (`storeHealth(path, { deep: true })`, `doctor --deep`, `store recover`) reports them as `invalidJson` and fails.
24
+
25
+ ### Changed — may break callers
26
+
27
+ - **A search for plain text with a colon, a URL or another special character finds what holds it.** `meeting at 10:30`,
28
+ `Answer as HH:MM` and `a:b` read the word before the colon as a field, so every source of `search all` refused the
29
+ query and the answer was empty. Now a `word:` that names no search field, and a word the parser cannot read as
30
+ syntax (a URL, an unbalanced quote or bracket, `^`, `~home`, `[draft]`, `<tag>`), are searched as words; a lone
31
+ emoji or punctuation mark beside other words no longer empties the answer. Field queries, Boolean operators,
32
+ phrases, `word*` and `/regex/` keep their meaning, and `word~1`, `/x/i` and punctuation alone keep their errors.
33
+ A caller that relied on the refusal of `foo:bar`, an unbalanced quote or `link:click?id=1` now gets hits, and
34
+ `meetings search` reads `subject:` (a message field) as a word. `plainQuery` in `./services` gives a caller the text
35
+ as the search reads it (cli-memo#674).
36
+
37
+ ## 0.601.0 — 07.11.2026
38
+
39
+ ### Added
40
+
41
+ - **Store version 55: `decision_requests`, the one-time keys behind buttons that ask the owner to decide a batch.**
42
+ `store.decisionRequests.create` makes one token per button for one message (22 characters, 16 random bytes in
43
+ base64url; only a SHA-256 digest is kept), `take` uses a token once, cancels the message's other open tokens in the
44
+ same transaction and first checks the bot, chat, message and owner (a mismatch reveals nothing of the token's state), `cancelOpen` voids every open token (of one bot, if
45
+ given) and `open` lists a message's live buttons, `prune` drops rows 30 days past their expiry, use or cancel. Tokens last 72 hours. A refusal carries a reason:
46
+ `decision.token-unknown`, `-used`, `-cancelled`, `-expired` or `-mismatch`. `callbackDataOf` and
47
+ `parseCallbackData` give and read the 27-byte `wcr1:<token>` data of a button, strictly. Forward-only,
48
+ `minCompatible` stays 34.
49
+ - **`@wirecat/cli-core/crm` exports the field lookup the CRM writes use**, so a CRM CLI drops its copy:
50
+ `foldFieldName`, `fieldNamed`, `optionOf`, `unknownField`, `fieldPairsOf` and the `NamedField` type they read.
51
+ `foldName` is exported from the package root.
52
+ - **`MeetingCommandDeps.newFileOutput`, `writesNewFileOnlyWith` and `writeNewFile`**, so `meetings export` runs under
53
+ the read-only lock and over MCP's `read` tool. It was refused under `<PREFIX>_READ_ONLY` even when it only printed.
54
+ A CLI that passes `newFileOutput: writesNewFileOnlyWith` and a `writeFile` that refuses a file that exists, such as
55
+ `writeNewFile`, gets an export that is a read without `--output` and, with it, only ever adds a file.
56
+ - **`meetings sync` can stop itself before its deadline and go on next time.** A CLI that passes
57
+ `MeetingCommandDeps.budgetOf` (`runBudgetOf` from `@wirecat/cli-core/cli`) gets a cooperative, partial sync: it
58
+ reads meetings oldest first, asks the budget before each, and on a stop keeps what it saved, answers `stopped` and
59
+ `remaining`, and moves the cursor to the first meeting it did not reach (never past one that failed). Without it the
60
+ sync keeps the one-shot deadline, as before.
61
+ - **`meetings sync --rescan`** reads the last 30 days again instead of only what came after the last sync.
62
+ - **`MeetingSource.overlapMs`**: a source's own look-back before the cursor, for a provider that lists a meeting late;
63
+ `--lookback-days` widens it, never narrows it. 0 when absent.
64
+ - **`recognizeLocalPieces` takes a `signal`** and stops between two pieces of speech when it aborts, freeing the
65
+ engine; a backend gives `piecesUntil` for it. Without a signal nothing changes.
66
+
67
+ ### Changed — may break callers
68
+
69
+ - **`foldName` folds ё into е**, so a chat, a person and a CRM field typed with е find the one named with ё. A name
70
+ that matched one chat or person exactly may now match two (`Алена` and `Алёна`); that is refused with both
71
+ candidates, as any other ambiguous name is. й stays apart from и. The CRM field lookup now folds on top of
72
+ `foldName`, so it also takes composed and decomposed letters as one.
73
+ - **`meetings export --output` is the owner's only**: an MCP tool no longer offers it (an agent would choose where on
74
+ the owner's disk to write) and gets the export in the answer, as `events export` does.
75
+
76
+ ### Fixed
77
+
78
+ - **`doctor --online` of a CLI built on `appDoctorCommand` runs inside cli-core's run.** It answered outside one, so
79
+ `--record` kept no run of it and its call out was not the command's own. A config that will not load still gets an
80
+ answer, outside a run.
81
+ - **`apiJson` and `apiPlainJson` refuse a body holding `NaN` or `Infinity`** with `validation_error`, naming the field,
82
+ before anything is sent. JSON writes them as `null`, so a failed `Number(…)` reached the service as a cleared field:
83
+ bitrix24-cli's `deals update --owner anna` sent `assignedById: null`.
84
+ - **`search all` in a CRM CLI and in a calendar CLI leaves out every kind whose list the profile denies.**
85
+ Under `deals: deny` it showed every deal's title, stage and amount, on the command line and over MCP. Each kind is
86
+ judged by its list key (`deals.list`, `leads.list`, `events.list`, `messages.list`, `notes.list`,
87
+ `meetings.list`) at the levels the run uses: the profile's, `--permission` and an MCP server's own. Each kind left
88
+ out is named in `missing` and on stderr; when every kind asked for is denied, the search is refused with
89
+ `permission_error` (`search.all-denied`). `DealSearch.kinds` and `SearchAllRequest.crmKinds` narrow the CRM kinds
90
+ read, and `run()` hands a command its CLI's built-in levels as `permissionDefaults`.
9
91
 
10
92
  ## 0.600.0 — 07.11.2026
11
93
 
@@ -6,6 +6,7 @@ import { LOCAL_READ } from "../../cli/effects.js";
6
6
  import { historySkipsOf } from "../../cli/messenger/history-gaps.js";
7
7
  import { allAnswer, offsetOf, SOURCE_SEARCHED } from "../../cli/messenger/search-answers.js";
8
8
  import { searchAllLine, searchAllOptions } from "../../cli/messenger/search-command.js";
9
+ import { deniedKinds } from "../../cli/search-left-out.js";
9
10
  import { SAVE_HELP } from "../../meetings/index.js";
10
11
  import { meaningLane } from "../../services/messages-meaning.js";
11
12
  import { searchAllWithMeetings } from "../../services/search-all-meetings.js";
@@ -33,6 +34,10 @@ export const addSearchAll = (searches, { within, app, zone, example }) => {
33
34
  await within(leaf, async (run) => {
34
35
  if (run.locked && opts.source !== undefined)
35
36
  throw new CliError("permission_error", "this process is locked to one profile; search all reads its own calendar only, without --source", { reason: "profile.locked" });
37
+ const denied = deniedKinds(leaf, app, opts.only ?? SOURCE_SEARCHED);
38
+ const only = (opts.only ?? SOURCE_SEARCHED).filter((one) => !denied.some(({ kind }) => kind === one));
39
+ if (!only.length)
40
+ throw new CliError("permission_error", `search all has nothing it may read: ${denied.map(({ why }) => why).join("; ")}`, { reason: "search.all-denied" });
36
41
  const store = messagesOf(run, "search all");
37
42
  const limit = opts.limit ?? DEFAULT_LIMIT;
38
43
  const offset = offsetOf(opts.page, limit);
@@ -44,12 +49,14 @@ export const addSearchAll = (searches, { within, app, zone, example }) => {
44
49
  ...(opts.exact ? { exact: true } : {}),
45
50
  timezone: opts.timezone ?? zone(),
46
51
  env,
47
- only: opts.only ?? SOURCE_SEARCHED,
52
+ only,
48
53
  ...(opts.source === undefined ? {} : { source: opts.source }),
49
54
  ...(opts.maxMeetings === undefined ? {} : { maxMeetings: opts.maxMeetings }),
50
55
  ...(run.locked ? { scope: { events: [run.account] } } : {}),
51
56
  }, { app }, undefined, meaningLane({ env, messenger: { app }, store: async () => store }));
52
57
  const note = (text) => outputFor(leaf).renderer.note(text);
58
+ for (const { why } of denied)
59
+ note(why);
53
60
  const globals = leaf.optsWithGlobals();
54
61
  if (!globals.json && !globals.jsonl)
55
62
  note(`searched: ${found.accounts.map(({ provider, account }) => `${provider}:${account}`).join(", ") || "nothing"}`);
@@ -71,7 +78,7 @@ export const addSearchAll = (searches, { within, app, zone, example }) => {
71
78
  note("nothing found in what the local store holds");
72
79
  const skips = await historySkipsOf(store, found.accounts).catch(() => []);
73
80
  lines = found.items.map(searchAllLine).join("");
74
- return allAnswer("search all", found, { limit, page: opts.page ?? 1, again }, opts.exact === true, skips);
81
+ return allAnswer("search all", found, { limit, page: opts.page ?? 1, again }, opts.exact === true, skips, denied);
75
82
  }, () => lines);
76
83
  });
77
84
  };
@@ -8,7 +8,7 @@ import { isNewer, latestVersion } from "@wirecat/cli-base/update";
8
8
  import { Command } from "commander";
9
9
  import { envName, readOnlyLockOf } from "../ports/app.js";
10
10
  import { storePath } from "../store/path.js";
11
- import { environmentOf, outputFor } from "./context.js";
11
+ import { environmentOf, inCommandRun, outputFor } from "./context.js";
12
12
  import { DOCTOR_ONLINE_OPTION, DOCTOR_SUMMARY } from "./doctor-text.js";
13
13
  import { REMOTE_READ } from "./effects.js";
14
14
  import { itemOf, renderAnswer } from "./envelope.js";
@@ -147,13 +147,21 @@ export const appDoctorCommand = (app, configuration, options = {}) => profileFre
147
147
  const env = environment.env ?? process.env;
148
148
  const { report, fixes } = appDoctorReport(app, configuration, env, this, options);
149
149
  const local = localCheck(env, options);
150
- const online = this.opts().online
151
- ? await onlineCheck(app, env, environment.fetch ?? fetch, options)
152
- : undefined;
153
- const output = outputFor(this);
154
- renderAnswer(this, output, itemOf({ ...report, ...local.fields, ...(online ? { online } : {}) }, { meta: clockMeta(Date.now(), timezoneOf()) }));
155
- for (const fix of fixes)
156
- output.renderer.note(`to make it private: ${fix}`);
157
- for (const note of local.notes)
158
- output.renderer.note(note);
150
+ const answer = async () => {
151
+ const online = this.opts().online
152
+ ? await onlineCheck(app, env, environment.fetch ?? fetch, options)
153
+ : undefined;
154
+ const output = outputFor(this);
155
+ renderAnswer(this, output, itemOf({ ...report, ...local.fields, ...(online ? { online } : {}) }, { meta: clockMeta(Date.now(), timezoneOf()) }));
156
+ for (const fix of fixes)
157
+ output.renderer.note(`to make it private: ${fix}`);
158
+ for (const note of local.notes)
159
+ output.renderer.note(note);
160
+ };
161
+ // A call out is recorded and ended by `--timeout` as any other command's; a config that will not load opens no
162
+ // run, and doctor still answers.
163
+ if (this.opts().online && !("settings" in report))
164
+ await inCommandRun(this, answer);
165
+ else
166
+ await answer();
159
167
  });
@@ -101,5 +101,11 @@ export const parseApiJson = (text) => {
101
101
  throw new CliError("validation_error", "the body is not valid JSON");
102
102
  }
103
103
  };
104
- export const apiJson = (value) => stringify(value) ?? "null";
105
- export const apiPlainJson = (value) => JSON.parse(stringify(value, (_, inner) => isLosslessNumber(inner) && !isSafeNumber(inner.value) ? inner.toString() : inner) ?? "null");
104
+ /** JSON writes NaN and Infinity as `null`: a bad `Number(…)` would reach the service as a cleared field. */
105
+ const finite = (key, value) => {
106
+ if (typeof value === "number" && !Number.isFinite(value))
107
+ throw new CliError("validation_error", `${key === "" ? "the body" : key} is ${value}, which a request cannot carry; nothing was sent`, { sent: false });
108
+ return value;
109
+ };
110
+ export const apiJson = (value) => stringify(value, finite) ?? "null";
111
+ export const apiPlainJson = (value) => JSON.parse(stringify(value, (key, inner) => isLosslessNumber(inner) && !isSafeNumber(inner.value) ? inner.toString() : finite(key, inner)) ?? "null");
@@ -36,6 +36,8 @@ export interface BaseEnvironment {
36
36
  app?: AppIdentity;
37
37
  /** Set by `run()`: the app's own, so a shared command group opens its run with the app's settings. */
38
38
  resolveSettings?: (flags: GlobalFlags, options?: ResolveOptions) => Settings;
39
+ /** Set by `run()` for a CLI that declares its keys: its built-in levels, which only tighten the owner's. */
40
+ permissionDefaults?: Readonly<Record<string, import("../sends/permissions.js").Level>>;
39
41
  /** Set by `run()` from `process.platform` unless a test hands one in: the OS a command's paths and units are for. */
40
42
  platform?: NodeJS.Platform;
41
43
  /** The local speech recognizer in place of the downloaded model; tests hand one in. */
@@ -4,7 +4,7 @@ import { Command } from "commander";
4
4
  import { note } from "../entities/note.js";
5
5
  import { addMeetingCommands } from "../meetings/cli/index.js";
6
6
  import { commandsCommand } from "./commands-command.js";
7
- import { LOCAL_READ, LOCAL_WRITE, NO_EFFECTS, REMOTE_WRITE } from "./effects.js";
7
+ import { LOCAL_READ, LOCAL_WRITE, NO_EFFECTS, REMOTE_WRITE, writesNewFileOnlyWith } from "./effects.js";
8
8
  import { unfilteredQuery, withQuery } from "./list-query.js";
9
9
  import { doctorCommand } from "./messenger/doctor-command.js";
10
10
  import { mcpCommand } from "./messenger/mcp-command.js";
@@ -42,6 +42,7 @@ export const sharedCommandTemplate = (app, name) => {
42
42
  accountId: 0,
43
43
  write: unavailable,
44
44
  inRun: unavailable,
45
+ newFileOutput: writesNewFileOnlyWith,
45
46
  });
46
47
  const meetings = root.commands.find((command) => command.name() === "meetings");
47
48
  if (!meetings)
@@ -77,6 +77,11 @@ export declare const fetchesOnlyAt: (root: Command) => (path: readonly string[])
77
77
  * attribute name, `output`.
78
78
  */
79
79
  export declare const writesFileOnlyWith: <T extends Command>(command: T, option: string) => T;
80
+ /**
81
+ * `writesFileOnlyWith` for a command whose file is always a new one, its writer refusing a file that exists: then it
82
+ * destroys nothing, and the read-only lock lets it through (`meetings export --output`).
83
+ */
84
+ export declare const writesNewFileOnlyWith: <T extends Command>(command: T, option: string) => T;
80
85
  /**
81
86
  * What an MCP server runs through `read`: a command that only fetches into the store (`fetchesOnly`), and one whose
82
87
  * only write is a file the tool cannot name (`writesFileOnlyWith`).
@@ -145,6 +145,11 @@ export const writesFileOnlyWith = (command, option) => {
145
145
  FILE_OPTION.set(command, option);
146
146
  return command;
147
147
  };
148
+ /**
149
+ * `writesFileOnlyWith` for a command whose file is always a new one, its writer refusing a file that exists: then it
150
+ * destroys nothing, and the read-only lock lets it through (`meetings export --output`).
151
+ */
152
+ export const writesNewFileOnlyWith = (command, option) => destroysNothing(writesFileOnlyWith(command, option));
148
153
  const writesFileNow = (command) => {
149
154
  const option = FILE_OPTION.get(command);
150
155
  return option === undefined || command.opts()[option] !== undefined;
@@ -72,7 +72,7 @@ export { sharedCommandTemplate } from "./contract-templates.js";
72
72
  export { type Closeable, withDeadline } from "./deadline.js";
73
73
  export { DEFAULT_CONFIG, ensureDefaultConfig } from "./default-config.js";
74
74
  export { DISCOVERY_DESCRIPTIONS } from "./discovery-descriptions.js";
75
- export { admittedUnderLock, changesAuthority, changesAuthorityAt, changesAuthorityNow, destroysNothing, FETCH, fetchesOnly, fetchesOnlyAt, grantsAuthority, isLogin, isOtherServiceCall, isProposal, isStoreChange, judgedEffects, judgedTargets, LOCAL_READ, LOCAL_WRITE, LOCKED_AUTHORITY_COMMANDS, logsInOrOut, NO_EFFECTS, narrowsUnderLock, ownerOnlyOption, PROPOSE_COMMANDS, previewFlag, proposesOnly, REMOTE_READ, REMOTE_WRITE, reachesOtherService, readsOverMcp, readsOverMcpAt, refuseUnderReadOnly, storeChangeRefusal, writesFileOnlyWith, } from "./effects.js";
75
+ export { admittedUnderLock, changesAuthority, changesAuthorityAt, changesAuthorityNow, destroysNothing, FETCH, fetchesOnly, fetchesOnlyAt, grantsAuthority, isLogin, isOtherServiceCall, isProposal, isStoreChange, judgedEffects, judgedTargets, LOCAL_READ, LOCAL_WRITE, LOCKED_AUTHORITY_COMMANDS, logsInOrOut, NO_EFFECTS, narrowsUnderLock, ownerOnlyOption, PROPOSE_COMMANDS, previewFlag, proposesOnly, REMOTE_READ, REMOTE_WRITE, reachesOtherService, readsOverMcp, readsOverMcpAt, refuseUnderReadOnly, storeChangeRefusal, writesFileOnlyWith, writesNewFileOnlyWith, } from "./effects.js";
76
76
  export { type CliEntry, type EntryContext, type EntryIo, openBrowser, startCli } from "./entry.js";
77
77
  export { type AnswerOutput, answerSchema, type Body, type ItemBody, isBody, itemAnswer, itemOf, jsonlRecords, judgedAnswer, type ListBody, type ListInput, listOf, metaNow, printItem, renderAnswer, sealed, snakeKeys, snakeKeysKeeping, } from "./envelope.js";
78
78
  export { withAbort } from "./execution.js";
@@ -115,6 +115,7 @@ export { storeSummary } from "./messenger/store-maintenance-command.js";
115
115
  export { type Saving, stored } from "./messenger/stored.js";
116
116
  export { dateOrNone } from "./messenger/tasks-command.js";
117
117
  export { MODEL_CATALOGUE_QUERY, type ModelCatalogueOptions } from "./model-catalogue-command.js";
118
+ export { writeNewFile } from "./new-file.js";
118
119
  export { positiveCount, window, withPaging } from "./paging.js";
119
120
  export { type CommandPermissions, type ConditionalKey, commandPathKey, commandPermissions, knownBeside, knownPermissionKeys, type PermissionKeyOf, type PermissionKeySource, refuseUnknownPermissionKeys, unknownPermissionIssues, unknownPermissionKeys, } from "./permission-keys.js";
120
121
  export { asFirstWord, commandWords, liftProfile, profileFree, refuseCommandName, rootOf, takesProfile, usableProfileName, } from "./profile.js";
package/dist/cli/index.js CHANGED
@@ -63,7 +63,7 @@ export { sharedCommandTemplate } from "./contract-templates.js";
63
63
  export { withDeadline } from "./deadline.js";
64
64
  export { DEFAULT_CONFIG, ensureDefaultConfig } from "./default-config.js";
65
65
  export { DISCOVERY_DESCRIPTIONS } from "./discovery-descriptions.js";
66
- export { admittedUnderLock, changesAuthority, changesAuthorityAt, changesAuthorityNow, destroysNothing, FETCH, fetchesOnly, fetchesOnlyAt, grantsAuthority, isLogin, isOtherServiceCall, isProposal, isStoreChange, judgedEffects, judgedTargets, LOCAL_READ, LOCAL_WRITE, LOCKED_AUTHORITY_COMMANDS, logsInOrOut, NO_EFFECTS, narrowsUnderLock, ownerOnlyOption, PROPOSE_COMMANDS, previewFlag, proposesOnly, REMOTE_READ, REMOTE_WRITE, reachesOtherService, readsOverMcp, readsOverMcpAt, refuseUnderReadOnly, storeChangeRefusal, writesFileOnlyWith, } from "./effects.js";
66
+ export { admittedUnderLock, changesAuthority, changesAuthorityAt, changesAuthorityNow, destroysNothing, FETCH, fetchesOnly, fetchesOnlyAt, grantsAuthority, isLogin, isOtherServiceCall, isProposal, isStoreChange, judgedEffects, judgedTargets, LOCAL_READ, LOCAL_WRITE, LOCKED_AUTHORITY_COMMANDS, logsInOrOut, NO_EFFECTS, narrowsUnderLock, ownerOnlyOption, PROPOSE_COMMANDS, previewFlag, proposesOnly, REMOTE_READ, REMOTE_WRITE, reachesOtherService, readsOverMcp, readsOverMcpAt, refuseUnderReadOnly, storeChangeRefusal, writesFileOnlyWith, writesNewFileOnlyWith, } from "./effects.js";
67
67
  export { openBrowser, startCli } from "./entry.js";
68
68
  export { answerSchema, isBody, itemAnswer, itemOf, jsonlRecords, judgedAnswer, listOf, metaNow, printItem, renderAnswer, sealed, snakeKeys, snakeKeysKeeping, } from "./envelope.js";
69
69
  export { withAbort } from "./execution.js";
@@ -104,6 +104,7 @@ export { storeSummary } from "./messenger/store-maintenance-command.js";
104
104
  export { stored } from "./messenger/stored.js";
105
105
  export { dateOrNone } from "./messenger/tasks-command.js";
106
106
  export { MODEL_CATALOGUE_QUERY } from "./model-catalogue-command.js";
107
+ export { writeNewFile } from "./new-file.js";
107
108
  export { positiveCount, window, withPaging } from "./paging.js";
108
109
  export { commandPathKey, commandPermissions, knownBeside, knownPermissionKeys, refuseUnknownPermissionKeys, unknownPermissionIssues, unknownPermissionKeys, } from "./permission-keys.js";
109
110
  export { asFirstWord, commandWords, liftProfile, profileFree, refuseCommandName, rootOf, takesProfile, usableProfileName, } from "./profile.js";
@@ -50,4 +50,8 @@ export declare const allHitItem: (item: SearchAllItem | MeetingSearchItem) => Hi
50
50
  /** `search notes`, CLI and MCP alike. */
51
51
  export declare const notesAnswer: (command: string, found: NotesFoundOf, { limit, page, again }: Paging, exact?: boolean) => ListBody<NoteHitItem>;
52
52
  /** `search all`, CLI and MCP alike. A bounded meeting scan that could not tell whether more match says so. */
53
- export declare const allAnswer: (command: string, found: SearchAllIncludingMeetingsFound, { limit, page, again }: Paging, exact?: boolean, skips?: StoredHistorySkip[]) => ListBody<HitItem>;
53
+ export declare const allAnswer: (command: string, found: SearchAllIncludingMeetingsFound, { limit, page, again }: Paging, exact?: boolean, skips?: StoredHistorySkip[],
54
+ /** Kinds the profile's levels kept out of the search, each with why. */
55
+ leftOut?: readonly {
56
+ why: string;
57
+ }[]) => ListBody<HitItem>;
@@ -341,7 +341,9 @@ export const notesAnswer = (command, found, { limit, page, again }, exact = fals
341
341
  meta: metaOf(found.accounts, found.skipped),
342
342
  });
343
343
  /** `search all`, CLI and MCP alike. A bounded meeting scan that could not tell whether more match says so. */
344
- export const allAnswer = (command, found, { limit, page, again }, exact = false, skips = []) => {
344
+ export const allAnswer = (command, found, { limit, page, again }, exact = false, skips = [],
345
+ /** Kinds the profile's levels kept out of the search, each with why. */
346
+ leftOut = []) => {
345
347
  const limited = historyLimitGaps(skips);
346
348
  const scan = found.meetings?.complete === false ? found.meetings : undefined;
347
349
  const notes = meaningGap(found.notes?.meaningSkipped, exact);
@@ -382,6 +384,7 @@ export const allAnswer = (command, found, { limit, page, again }, exact = false,
382
384
  ...messages.missing,
383
385
  ...archive.missing,
384
386
  ...limited.missing,
387
+ ...leftOut.map(({ why }) => ({ field: "items", why })),
385
388
  ],
386
389
  meta: metaOf(found.accounts, found.skipped, archive.missing.length > 0 || skips.length > 0),
387
390
  });
@@ -19,6 +19,7 @@ export declare const storeSummary: (env: NodeJS.ProcessEnv, { deep, command }?:
19
19
  ms: number;
20
20
  problems?: number | undefined;
21
21
  damagedTables?: import("../../store/health.js").DamagedTable[] | undefined;
22
+ invalidJson?: import("../../store/health.js").InvalidJson[] | undefined;
22
23
  damagedSearchIndexes?: string[] | undefined;
23
24
  };
24
25
  damage?: import("../../store/damage.js").DamageExplanation | undefined;
@@ -37,6 +38,7 @@ export declare const storeSummary: (env: NodeJS.ProcessEnv, { deep, command }?:
37
38
  ms: number;
38
39
  problems?: number | undefined;
39
40
  damagedTables?: import("../../store/health.js").DamagedTable[] | undefined;
41
+ invalidJson?: import("../../store/health.js").InvalidJson[] | undefined;
40
42
  damagedSearchIndexes?: string[] | undefined;
41
43
  };
42
44
  damage?: import("../../store/damage.js").DamageExplanation | undefined;
@@ -74,6 +74,7 @@ export const storeSummary = async (env, { deep = false, command } = {}) => {
74
74
  ms: checked.ms,
75
75
  ...(checked.problems ? { problems: checked.problems } : {}),
76
76
  ...(checked.damagedTables?.length ? { damagedTables: checked.damagedTables } : {}),
77
+ ...(checked.invalidJson?.length ? { invalidJson: checked.invalidJson } : {}),
77
78
  ...(checked.searchIndexes?.some((index) => !index.ok)
78
79
  ? { damagedSearchIndexes: checked.searchIndexes.filter((index) => !index.ok).map((index) => index.name) }
79
80
  : {}),
@@ -0,0 +1,2 @@
1
+ /** Writes a file that did not exist, private to the owner; one that exists is refused and left as it was. */
2
+ export declare const writeNewFile: (path: string, content: string) => Promise<void>;
@@ -0,0 +1,13 @@
1
+ import { writeFile } from "node:fs/promises";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ /** Writes a file that did not exist, private to the owner; one that exists is refused and left as it was. */
4
+ export const writeNewFile = async (path, content) => {
5
+ try {
6
+ await writeFile(path, content, { flag: "wx", mode: 0o600 });
7
+ }
8
+ catch (error) {
9
+ if (error.code === "EEXIST")
10
+ throw new CliError("validation_error", "output file already exists; choose another path", { param: "--output" });
11
+ throw error;
12
+ }
13
+ };
@@ -231,6 +231,9 @@ const runOnce = async (argv, definition, options) => {
231
231
  // `settingsFor`'s, which every CLI passes; the definition's type is looser only so a test can stub it.
232
232
  resolveSettings: (definition.configuration ?? settingsFor(definition.app))
233
233
  .resolveSettings,
234
+ ...(definition.configuration?.permissions
235
+ ? { permissionDefaults: definition.configuration.permissions.defaults }
236
+ : {}),
234
237
  ...(definition.rows ? { rows: definition.rows } : {}),
235
238
  platform: options.platform ?? process.platform,
236
239
  exit,
@@ -0,0 +1,27 @@
1
+ import type { Command } from "commander";
2
+ import type { AppIdentity } from "../ports/app.js";
3
+ import { type PermissionKey } from "../sends/permissions.js";
4
+ /** The list command whose level guards each kind a shared `search all` reads. */
5
+ declare const LIST_KEYS: {
6
+ readonly deal: "deals.list";
7
+ readonly lead: "leads.list";
8
+ readonly messages: "messages.list";
9
+ readonly mail: "mail.list";
10
+ readonly notes: "notes.list";
11
+ readonly events: "events.list";
12
+ readonly meetings: "meetings.list";
13
+ };
14
+ export type SearchedKind = keyof typeof LIST_KEYS;
15
+ export interface LeftOut<K extends SearchedKind> {
16
+ kind: K;
17
+ key: PermissionKey;
18
+ /** `deal left out: profile work denies deals.list` */
19
+ why: string;
20
+ }
21
+ /**
22
+ * The kinds whose list the profile denies, so `search all` leaves them out rather than show their titles and excerpts
23
+ * under another key (SEC-144). Levels as the run judged the command: the profile's, `--permission`, and an MCP
24
+ * server's own stricter ones.
25
+ */
26
+ export declare const deniedKinds: <K extends SearchedKind>(command: Command, app: AppIdentity, kinds: readonly K[]) => LeftOut<K>[];
27
+ export {};
@@ -0,0 +1,31 @@
1
+ import { levelFor } from "../sends/permissions.js";
2
+ import { environmentOf, withAgentLevels } from "./context.js";
3
+ import { settingsFor } from "./settings.js";
4
+ /** The list command whose level guards each kind a shared `search all` reads. */
5
+ const LIST_KEYS = {
6
+ deal: "deals.list",
7
+ lead: "leads.list",
8
+ messages: "messages.list",
9
+ mail: "mail.list",
10
+ notes: "notes.list",
11
+ events: "events.list",
12
+ meetings: "meetings.list",
13
+ };
14
+ /**
15
+ * The kinds whose list the profile denies, so `search all` leaves them out rather than show their titles and excerpts
16
+ * under another key (SEC-144). Levels as the run judged the command: the profile's, `--permission`, and an MCP
17
+ * server's own stricter ones.
18
+ */
19
+ export const deniedKinds = (command, app, kinds) => {
20
+ const environment = environmentOf(command);
21
+ const resolve = environment.resolveSettings ?? settingsFor(app).resolveSettings;
22
+ const { permissions, profile } = resolve(withAgentLevels(command, command.optsWithGlobals()), {
23
+ env: environment.env ?? process.env,
24
+ needsProfile: false,
25
+ readOnly: true,
26
+ });
27
+ return kinds
28
+ .map((kind) => ({ kind, key: LIST_KEYS[kind] }))
29
+ .filter(({ key }) => levelFor(permissions, key, environment.permissionDefaults).level === "deny")
30
+ .map((one) => ({ ...one, why: `${one.kind} left out: profile ${profile} denies ${one.key}` }));
31
+ };
@@ -1,5 +1,6 @@
1
1
  import { Command } from "commander";
2
2
  import { type DamageExplanation } from "../store/damage.js";
3
+ import { type InvalidJson } from "../store/health.js";
3
4
  import { type RecoverOptions, type Recovery } from "../store/recover.js";
4
5
  export interface RecoveryCheck {
5
6
  path: string;
@@ -16,6 +17,7 @@ export interface RecoveryCheck {
16
17
  name: string;
17
18
  error?: string;
18
19
  }[];
20
+ invalidJson?: InvalidJson[];
19
21
  rows?: Record<string, number | null>;
20
22
  explanation?: DamageExplanation | null;
21
23
  inUse?: {
@@ -65,6 +65,7 @@ export const storeRecoveryCheck = async (env, command) => {
65
65
  damagedSearchIndexes: (health.searchIndexes ?? [])
66
66
  .filter((index) => !index.ok)
67
67
  .map(({ name, error }) => ({ name, ...(error ? { error } : {}) })),
68
+ invalidJson: health.invalidJson ?? [],
68
69
  rows,
69
70
  explanation,
70
71
  inUse,
@@ -107,6 +108,7 @@ export const recoveryNotes = (answer) => {
107
108
  `recovered in ${answer.seconds.total} s; the damaged file is kept at ${answer.keptAt}`,
108
109
  ...(lost.length ? lost : ["no table lost a row"]),
109
110
  ...answer.dangling.map(({ table, parent, rows }) => `${rows} rows of ${table} point at ${parent} rows the store does not hold`),
111
+ ...answer.invalidJson.map(({ table, column, rows, required }) => `${table}.${column}: ${rows} values were not valid JSON — ${required ? "those rows were dropped" : "set to empty"}`),
110
112
  ...answer.next.map((line) => `next: ${line}`),
111
113
  ];
112
114
  }
@@ -15,7 +15,7 @@ import { DEAL_KINDS, DEAL_STATUSES } from "../../domain/deals.js";
15
15
  import { deal as dealEntity } from "../../entities/deal.js";
16
16
  import { count, text } from "../../entities/fields.js";
17
17
  import { crmStatus, syncCrm } from "../sync.js";
18
- import { closeCrmItem, createCrmItem, moveCrmItem, removeCrmItem, updateCrmItem, } from "../writes.js";
18
+ import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, removeCrmItem, updateCrmItem, } from "../writes.js";
19
19
  import { addCrmSearchAll } from "./search-all.js";
20
20
  const MOST = 500;
21
21
  const DEAL_FIELDS = [
@@ -125,11 +125,6 @@ const collect = (value, previous = []) => {
125
125
  throw new InvalidArgumentError("expected key=value");
126
126
  return [...previous, value];
127
127
  };
128
- /** `--field` as typed, split at the first `=`. */
129
- const pairsOf = (typed) => typed.map((pair) => {
130
- const at = pair.indexOf("=");
131
- return [pair.slice(0, at), pair.slice(at + 1)];
132
- });
133
128
  const integer = (most) => (value) => {
134
129
  if (!/^[1-9]\d*$/.test(value) || Number(value) > most)
135
130
  throw new InvalidArgumentError(`expected 1 to ${most}`);
@@ -327,7 +322,7 @@ const addCrmCommandsDefinition = (program, options) => {
327
322
  []);
328
323
  const inputOf = ({ field, operationId: _id, ...rest }) => ({
329
324
  ...Object.fromEntries(Object.entries(rest).filter(([, value]) => value !== undefined)),
330
- ...(field?.length ? { custom: pairsOf(field) } : {}),
325
+ ...(field?.length ? { custom: fieldPairsOf(field) } : {}),
331
326
  });
332
327
  const idOf = (opts) => opts.operationId === undefined ? {} : { operationId: opts.operationId };
333
328
  const run = (command, work) => within(command, (opened) => work(contextOf(opened, command)));
@@ -6,6 +6,8 @@ import { LOCAL_READ } from "../../cli/effects.js";
6
6
  import { historySkipsOf } from "../../cli/messenger/history-gaps.js";
7
7
  import { allAnswer, offsetOf, SOURCE_SEARCHED } from "../../cli/messenger/search-answers.js";
8
8
  import { searchAllOptions } from "../../cli/messenger/search-command.js";
9
+ import { deniedKinds } from "../../cli/search-left-out.js";
10
+ import { DEAL_KINDS } from "../../domain/deals.js";
9
11
  import { SAVE_HELP } from "../../meetings/index.js";
10
12
  import { meaningLane } from "../../services/messages-meaning.js";
11
13
  import { searchAllWithMeetings } from "../../services/search-all-meetings.js";
@@ -30,6 +32,16 @@ export const addCrmSearchAll = (searches, { within, app, example, }) => {
30
32
  await within(leaf, async (run) => {
31
33
  if (run.locked && opts.source !== undefined)
32
34
  throw new CliError("permission_error", "this process is locked to one profile; search all reads its own CRM account only, without --source", { reason: "profile.locked" });
35
+ const asked = opts.only ?? SEARCHED;
36
+ const denied = deniedKinds(leaf, app, [
37
+ ...(asked.includes("crm") ? DEAL_KINDS : []),
38
+ ...asked.filter((one) => one !== "crm" && one !== "mail"),
39
+ ]);
40
+ const out = new Set(denied.map(({ kind }) => kind));
41
+ const crmKinds = DEAL_KINDS.filter((kind) => !out.has(kind));
42
+ const only = asked.filter((one) => (one === "crm" ? crmKinds.length > 0 : !out.has(one)));
43
+ if (!only.length)
44
+ throw new CliError("permission_error", `search all has nothing it may read: ${denied.map(({ why }) => why).join("; ")}`, { reason: "search.all-denied" });
33
45
  const limit = opts.limit ?? DEFAULT_LIMIT;
34
46
  const offset = offsetOf(opts.page, limit);
35
47
  const env = run.env ?? process.env;
@@ -40,12 +52,15 @@ export const addCrmSearchAll = (searches, { within, app, example, }) => {
40
52
  ...(opts.exact ? { exact: true } : {}),
41
53
  ...(opts.timezone === undefined ? {} : { timezone: opts.timezone }),
42
54
  env,
43
- only: opts.only ?? SEARCHED,
55
+ only,
56
+ ...(crmKinds.length < DEAL_KINDS.length ? { crmKinds } : {}),
44
57
  ...(opts.source === undefined ? {} : { source: opts.source }),
45
58
  ...(opts.maxMeetings === undefined ? {} : { maxMeetings: opts.maxMeetings }),
46
59
  ...(run.locked ? { scope: { crm: [run.account] } } : {}),
47
60
  }, { app }, undefined, meaningLane({ env, messenger: { app }, store: async () => run.store }));
48
61
  const note = (text) => outputFor(leaf).renderer.note(text);
62
+ for (const { why } of denied)
63
+ note(why);
49
64
  for (const { resource, source, reason } of found.skipped)
50
65
  note(`${resource ?? source} not searched: ${reason}`);
51
66
  if (!found.items.length)
@@ -57,7 +72,7 @@ export const addCrmSearchAll = (searches, { within, app, example, }) => {
57
72
  ...(opts.source === undefined ? {} : { source: opts.source }),
58
73
  ...(opts.exact ? { exact: true } : {}),
59
74
  };
60
- return allAnswer("search all", found, { limit, page: opts.page ?? 1, again }, opts.exact === true, skips);
75
+ return allAnswer("search all", found, { limit, page: opts.page ?? 1, again }, opts.exact === true, skips, denied);
61
76
  });
62
77
  });
63
78
  };
@@ -1,4 +1,4 @@
1
1
  export type { CrmChanges, CrmIdPage, CrmPage, CrmSource, CrmSourceTraits } from "./source.js";
2
2
  export { type CrmCursor, type CrmSyncIssue, type CrmSyncOptions, type CrmSyncReport, type CrmSyncResult, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
3
3
  export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, type CrmDraft, type CrmFields, type CrmVerb, type CrmWriteCapabilities, type CrmWriteOptions, type CrmWriter, crmAlsoChecks, } from "./writer.js";
4
- export { type CrmFieldsInput, type CrmWriteContext, type CrmWrites, type CrmWritten, closeCrmItem, createCrmItem, moveCrmItem, removeCrmItem, updateCrmItem, } from "./writes.js";
4
+ export { type CrmFieldsInput, type CrmWriteContext, type CrmWrites, type CrmWritten, closeCrmItem, createCrmItem, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, type NamedField, optionOf, removeCrmItem, unknownField, updateCrmItem, } from "./writes.js";
package/dist/crm/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  export { crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
2
2
  export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, crmAlsoChecks, } from "./writer.js";
3
- export { closeCrmItem, createCrmItem, moveCrmItem, removeCrmItem, updateCrmItem, } from "./writes.js";
3
+ export { closeCrmItem, createCrmItem, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, optionOf, removeCrmItem, unknownField, updateCrmItem, } from "./writes.js";
@@ -1,3 +1,5 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import type { CrmField } from "../domain/crm.js";
1
3
  import type { DealKind } from "../domain/deals.js";
2
4
  import type { AppIdentity } from "../ports/app.js";
3
5
  import type { Warn } from "../runs/events.js";
@@ -52,6 +54,21 @@ export interface CrmFieldsInput {
52
54
  */
53
55
  custom?: readonly (readonly [name: string, value: string])[];
54
56
  }
57
+ /** What the field lookup reads of a field definition: a CRM CLI's own type fits. */
58
+ export type NamedField = Pick<CrmField, "code" | "label" | "options">;
59
+ /**
60
+ * A field's code, label or option as the lookup compares them: `foldName` (letter case, composed letters, ё as е),
61
+ * with spaces and underscores aside, so `lead_source` and `Lead source` are one name.
62
+ */
63
+ export declare const foldFieldName: (name: string) => string;
64
+ /** No field by that name: the fields whose code or label holds it, or is held in it, are its candidates. */
65
+ export declare const unknownField: (fields: readonly NamedField[], name: string) => CliError;
66
+ /** A field by its code or its whole label; two with that label are refused with both, never guessed. */
67
+ export declare const fieldNamed: <F extends NamedField>(fields: readonly F[], name: string) => F;
68
+ /** A list field's option id, by its id or its whole label; a field with no options takes the value as typed. */
69
+ export declare const optionOf: (field: NamedField, value: string) => string;
70
+ /** `--field` pairs as typed, split at the first `=`; a pair with no key before it is refused. */
71
+ export declare const fieldPairsOf: (typed: readonly string[]) => [string, string][];
55
72
  export interface CrmWritten {
56
73
  operationId: string;
57
74
  item: Deal;