@wirecat/cli-core 0.668.0 → 0.670.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 (71) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/documents/catalog.js +3 -14
  4. package/dist/cli/documents/sync.d.ts +21 -5
  5. package/dist/cli/documents/sync.js +39 -8
  6. package/dist/cli/documents/testing/source-contract.d.ts +9 -0
  7. package/dist/cli/documents/testing/source-contract.js +12 -0
  8. package/dist/cli/documents/words.d.ts +1 -1
  9. package/dist/cli/store-settings.js +5 -3
  10. package/dist/crm/cli/csv.d.ts +1 -1
  11. package/dist/crm/cli/csv.js +2 -2
  12. package/dist/crm/cli/index.d.ts +11 -1
  13. package/dist/crm/cli/index.js +11 -5
  14. package/dist/crm/cli/records.d.ts +94 -0
  15. package/dist/crm/cli/records.js +412 -0
  16. package/dist/crm/foreign-contacts.d.ts +34 -0
  17. package/dist/crm/foreign-contacts.js +104 -0
  18. package/dist/crm/index.d.ts +9 -3
  19. package/dist/crm/index.js +7 -1
  20. package/dist/crm/provider-call.d.ts +23 -0
  21. package/dist/crm/provider-call.js +49 -0
  22. package/dist/crm/query.d.ts +32 -0
  23. package/dist/crm/query.js +122 -0
  24. package/dist/crm/source.d.ts +41 -4
  25. package/dist/crm/sync.d.ts +1 -1
  26. package/dist/crm/sync.js +13 -7
  27. package/dist/crm/testing/source-contract.d.ts +5 -0
  28. package/dist/crm/testing/source-contract.js +39 -0
  29. package/dist/crm/testing/source.d.ts +9 -3
  30. package/dist/crm/testing/source.js +109 -10
  31. package/dist/crm/testing/write-contract.d.ts +2 -2
  32. package/dist/crm/testing/write-contract.js +41 -2
  33. package/dist/crm/values.d.ts +33 -0
  34. package/dist/crm/values.js +75 -0
  35. package/dist/crm/walk.d.ts +18 -0
  36. package/dist/crm/walk.js +23 -0
  37. package/dist/crm/writer.d.ts +41 -6
  38. package/dist/crm/writer.js +16 -10
  39. package/dist/crm/writes.d.ts +38 -2
  40. package/dist/crm/writes.js +163 -9
  41. package/dist/documents/model.d.ts +4 -0
  42. package/dist/domain/crm.d.ts +41 -5
  43. package/dist/entities/deal.d.ts +8 -2
  44. package/dist/entities/deal.js +4 -1
  45. package/dist/errors/reasons.js +23 -2
  46. package/dist/oauth/index.d.ts +1 -1
  47. package/dist/oauth/index.js +1 -1
  48. package/dist/oauth/keeper.js +4 -0
  49. package/dist/oauth/storage.d.ts +21 -0
  50. package/dist/oauth/storage.js +32 -1
  51. package/dist/services/documents/ingestion.d.ts +3 -0
  52. package/dist/services/documents/ingestion.js +9 -2
  53. package/dist/services/documents/plan.d.ts +16 -1
  54. package/dist/services/documents/plan.js +163 -103
  55. package/dist/services/documents/ports.d.ts +13 -0
  56. package/dist/services/documents/sync.d.ts +11 -0
  57. package/dist/services/documents/sync.js +41 -3
  58. package/dist/services/metadata.d.ts +1 -1
  59. package/dist/store/sqlite/catalog.d.ts +2 -1
  60. package/dist/store/sqlite/catalog.js +4 -1
  61. package/dist/store/sqlite/crm-contacts.d.ts +5 -4
  62. package/dist/store/sqlite/crm-contacts.js +8 -4
  63. package/dist/store/sqlite/crm-rows.d.ts +1 -0
  64. package/dist/store/sqlite/crm-rows.js +37 -7
  65. package/dist/store/sqlite/crm-settings.d.ts +2 -2
  66. package/dist/store/sqlite/crm-settings.js +4 -3
  67. package/dist/store/sqlite/crm.d.ts +5 -3
  68. package/dist/store/sqlite/crm.js +20 -3
  69. package/dist/store/sqlite/note-search.d.ts +10 -1
  70. package/dist/store/sqlite/note-search.js +35 -1
  71. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,131 @@ 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.670.0 — 15.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`addCrmCommands` mounts `people`, `organizations` and `users` list and show, read live from the CRM.** A CLI passes
13
+ `live: ["person", "organization", "user"]` for what its source reads: `CrmSource.list(kind, query)` and
14
+ `get(kind, id)` for contacts and companies, the existing `users()` for users. `--offline` is refused. Lists take the
15
+ same query language as `deals list` (`name:anna*`, `assigned_to:7`, `created_at>=7d`, a custom field by its code or
16
+ label), `--limit`, `--page`, `--format csv`, and `--json=provider_metadata.<code>`. The answers are the shared
17
+ entities `crm_person`, `crm_organization` and `crm_user` (`crmPersonOf`, `crmOrganizationOf`, `crmUserOf`).
18
+ See [CRM](docs/dev/CRM.md).
19
+ - **`people create|update` and `organizations create|update`** go through the guarded write path of `deals create`:
20
+ the read-only lock, the keys `people.create`, `people.update`, `organizations.create`, `organizations.update`, and
21
+ `crm.assign-others` for another owner, the journal and `operation_id`. The CRM's answer is stored as a sync stores it
22
+ (`createCrmRecord`, `updateCrmRecord`).
23
+ - **The daily limit on foreign contacts is shared.** With `CrmSource.isAdmin()`, anyone but the CRM's administrator
24
+ sees phones and e-mails only of their own clients (`assignee` is the sign-in's user, or `CrmSource.ownClients()`
25
+ names them) and at most `DAILY_FOREIGN_CONTACTS` (100) other contacts or companies a UTC day in `show`, by id or
26
+ exact name. The count is kept per CRM user under a file lock, so two runs never both take the last slot
27
+ (`foreignContacts`). A write of a foreign contact answers it stripped and does not store it (`stored: false`); an
28
+ update that gives a company to someone else removes it from the copy. A foreign record's custom values go where the
29
+ field definition says it holds a phone or an e-mail (new `CrmField.holds`), or all of them when the CRM gives none.
30
+ - **Helpers every CRM adapter needs**, from `@wirecat/cli-core/crm`: `providerCall` (paced calls, reads retried, writes
31
+ retried only on `rate_limited`, a write with no answer `outcome_unknown`, one token refresh on `oauth.expired`),
32
+ `walk` and `crmWindowOf` (the CRM's pages into one answer page with `hasMore`), `conditionsOf` and the custom-field
33
+ query helpers, `crmCustomValues` (`--field` pairs), `crmValues` (JSON coercions and `crmValuesOf`, custom values
34
+ with labels), and `refuseForeignClientReads` for an `api call` that reads clients.
35
+ - **`accountTokenCodec(provider)`** in `@wirecat/cli-core/oauth`: a sign-in entry bound to one CRM account through
36
+ the owner's own app, which keeps the app's secret, the account's `host` and `userId` beside the tokens and saves a
37
+ rotated refresh token. It is `rotating` (new `TokenCodec.rotating`, `TokenStorage.rotating`): a run with moved
38
+ folders refuses to refresh it (`oauth.moved-rotating`).
39
+ - **Money is checked before a deal write is sent:** a currency or a precision the store cannot keep is refused
40
+ (`money.currency`, `money.amount`). A list option label two options share is refused with both
41
+ (`field.ambiguous-option`).
42
+ - **`@wirecat/cli-core/crm/testing`:** `fakeCrmSource` has `list`, `get`, contact and company writes, and `admin` and
43
+ `ownClients` options; `crmSourceContract` checks live pages and `get`, and `crmWriteContract` contact and company
44
+ writes.
45
+
46
+ ### Changed — may break callers
47
+
48
+ - **`CrmWriter.create` and `update` take every CRM kind** (`CrmDrafts[K]`, `CrmWriteFields[K]`) and answer
49
+ `CrmRecords[K]`; `CrmWriteCapabilities.kinds` and the `alsoChecks` hooks take `CrmKind`. A writer that writes only
50
+ deals and leads casts its answer and leaves `person` and `organization` out of `kinds`.
51
+ - **`CrmPerson` and `CrmOrganization` carry what a live read answers:** `createdAt`, `updatedAt`, a person's
52
+ `firstName`, `lastName`, `url`, `metadata` and `contactTypes`, a company's `assignee`, `phones`, `emails` and
53
+ `people`. Of these the store keeps a contact's `assignee` only.
54
+ - **`fakeCrmSource` writes every kind by default:** `FakeCrmWrite.kind` is any `CrmKind`, and `calls` counts `list`
55
+ and `get`.
56
+ - **`crmSourceContract` asks more of a source:** a source with `list` must list at least one contact and one company,
57
+ give back every id the fixture names in its new `live`, and keep phones and e-mails out of `metadata`.
58
+ `crmWriteContract` runs contact and company cases for a writer whose `kinds` include them.
59
+ - **A `providerCall` write that ends in `cancelled` or `invalid_response` is `outcome_unknown`.**
60
+ - **`CrmOrganization.metadata` is `Record<string, CrmValue>`**, as a person's; `EncodeInput` gains `signIn`.
61
+ - **A chosen `unassigned` list replaces your own user in scope `mine`.** With `unassigned` set, a sync copies only
62
+ those users' deals and leads, and your own user's only when the list names it, as bitrix24-cli already reads them.
63
+ Before, cli-core kept your own deals while bitrix24-cli no longer sent their changes, so they went stale and were
64
+ later counted as deleted on the CRM. Now they leave the copy as out of scope, or, under the default `mine`, the
65
+ narrowing is held until you set `scope`. To keep your own deals as well, add your own user id to `unassigned`.
66
+ `store status` no longer lists your own user under `applied.users` while `unassigned` names anyone. While a
67
+ narrowing is held, the daily id check marks deleted only deals inside the scope.
68
+ - **A CRM deal whose amount the store cannot hold is kept, with no amount, and says why.** Before, a deal in a
69
+ currency the store has no scale for (BRL, MXN, SGD and others), with more decimals than its currency has, below
70
+ zero or too large, was left out of `deals list`, the funnel and the totals, with `crm.item-invalid` in the sync
71
+ answer. Now the deal is stored with `amount` and `currency` empty, and the sync answer names it as
72
+ `crm.amount-unkept`. Its `provider_metadata.amount_note` ("Amount not kept") is WireCat's own note, not a CRM
73
+ field: what the CRM had and why it was not kept.
74
+
75
+ ### Fixed
76
+
77
+ - **Under scope `mine`, a contact assigned to a user in scope is no longer removed when it is on no deal.** A source
78
+ that sends the contact's `assignee` keeps such a contact through the cleanup after a narrowing or `sync --rescan`.
79
+ - **A held narrowing on a small copy is no longer undone by the same run's list of ids.** While the narrowing waits
80
+ for you, the id check marks deleted only deals inside the scope, so no deal outside it is marked deleted.
81
+ - **A deal in a new stage, skipped because the run's budget ran out before the pipelines were read again, is read
82
+ again.** The next run reads that page again instead of moving past it.
83
+
84
+ ## 0.669.0 — 15.11.2026
85
+
86
+ ### Added
87
+
88
+ - **`syncDocuments` takes a `budget`** (a `RunBudget`), asked before each folder listing and each file read: a stop
89
+ ends the call with its work saved. The shared `sync` command passes `runBudgetOf(command)` as `budget` in its
90
+ arguments, for the CLI to hand on. See [Walks over several syncs](docs/dev/DOCUMENTS.md#walks-over-several-syncs).
91
+ - **`SourceIndex.settle` and `store.notes.indexWritten`.** At the end of a sync the engine indexes the store's waiting
92
+ text for word search, so a read-only reader finds a page by the words of its text right after the sync; before, the
93
+ text waited until a writable store ran a search. The queue is shared by every tool on the store. It works 50 rows at
94
+ a time and yields between them, and stops after 10 s, at `deadline` less its margin, or on the signal; it is skipped
95
+ after a budget stop. `documentIngestion` supplies `settle`; `indexWritten` answers 0 on a read-only store.
96
+ - **`SyncOptions.deadline` and `DocumentSyncArgs.deadline`:** the run's hard limit, which the shared `sync` command
97
+ passes for the CLI to hand on.
98
+ - **`documentSourceContract` checks a deep change** when the fixture gives `addNested`: the feed must name a file
99
+ added two levels below the root, or its own folder.
100
+ - **The catalog's `parent` filter takes several ids** (`parent: [a, b]`), read in one pass of the account's catalog.
101
+ `catalog tree` asks about the branches it cuts this way: 1 000 branches in a 12 000-entry account take about
102
+ 0.06 s instead of 3.2 s ([measured](https://github.com/WireCatLabs/cli-testing/blob/main/performance/documents/sync-scale/README.md)). `documentIngestion`'s `catalog.get` and `catalog.list` take an id with or without `.md`.
103
+
104
+ ### Changed — may break callers
105
+
106
+ - **A sync no longer fails for the size of the chosen folders.** `maxEntries` now bounds one call: a walk past it
107
+ saves where it stopped, answers `complete: false`, `stopped: "entries"` and `walk: { folders_left, entries,
108
+ listed }`, and the next sync goes on from there. `limitError` is no longer called. `SyncResult` gains `complete`,
109
+ `stopped` and `walk`. The shared `sync` command declares `partial`: an unfinished pass (a walk or pending
110
+ operations) answers `meta.complete: false`, exits 0 and names the same `sync --limit` as its next step
111
+ (`sync.run`, safe to run unasked). Its help no longer says one sync reads at most that many entries.
112
+ - **A changed folder lists only its direct children.** A round of changes no longer walks the whole subtree of each
113
+ folder the feed names: a child folder the last finished pass held is not listed again. An edit to a page with 500
114
+ pages below it, and to one of them, lists those 2 pages instead of 501. A source must therefore name in its feed
115
+ each changed entry or its own folder: one that names only an ancestor misses a file two levels below until a
116
+ rescan. A folder new to the scope
117
+ (new, restored, or moved in from outside) is still walked in full, so the files under a Drive folder moved in are
118
+ found. A round a call cuts short is saved and goes on in the next sync.
119
+ - **`--rescan` goes on until it finishes.** It drops the cursor and any saved walk and saves that at once, so the
120
+ following plain syncs continue its walk. A dropped batch's work saved to the index without the state knowing is
121
+ removed when the batch is dropped, no longer counted in `removed`, and the state is saved right after.
122
+ - **A folder deleted or unshared since the walk saved it is dropped**, with what was below it, when listing it answers
123
+ `not_found` and reading it again with `metadata` answers `not_found` too or finds it trashed. On any doubt the sync
124
+ fails as before and the next one lists the folder again, so a passing 404 never removes a subtree. `sync --help`
125
+ says each `--rescan` starts the walk over, so it is run once and continued with a plain `sync`.
126
+ - **A test that expects the sync to fail for size now fails.** drive's
127
+ `says to choose smaller folders when the chosen ones hold more entries than one sync reads` (`src/sync.test.ts`)
128
+ expects that error; on its bump it should expect `complete: false` instead. drive's own bound on one folder
129
+ listing or one change feed (10 000 entries, in `google.ts`) is unchanged.
130
+ - **The saved walk keeps only `SourceWalk`'s fields.** drive's saved `walk.json` and `state.json` keep working as
131
+ they are; a round of changes is saved under the scope `<scope>:changes:<cursor>`.
132
+
8
133
  ## 0.668.0 — 15.11.2026
9
134
 
10
135
  ### 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;
27
28
  name: string;
28
29
  installed: boolean;
29
30
  active: boolean;
30
31
  servicePath: string;
31
32
  timerPath: string;
32
- action?: undefined;
33
33
  } | {
34
34
  active?: undefined;
35
35
  name: string;
@@ -11,29 +11,18 @@ import { allOf, examples, nonnegative, positive, wordsOf } from "./words.js";
11
11
  export const CATALOG_TREE_LIMIT = 10_000;
12
12
  const CATALOG_PAGE = 1000;
13
13
  const PARENT_BATCH = 200;
14
- /** `parent:a OR parent:b …` over ids as they are: the values go into a parsed template, so none needs escaping. */
15
- const anyParent = (ids) => {
16
- const ast = parseLucene(Array.from({ length: Math.max(2, ids.length) }, () => "parent:x").join(" OR "), {
17
- defaultField: "none",
18
- });
19
- const clauses = ast.root.clauses;
20
- clauses.forEach((clause, i) => {
21
- clause.node.value = ids[Math.min(i, ids.length - 1)];
22
- });
23
- return validateQuery(ast, CATALOG_QUERY);
24
- };
25
14
  /** The tree's reads through the CLI's catalog, which takes ids without the `.md` the store's entries carry. */
26
15
  export const catalogSource = (catalog, principal) => ({
27
16
  get: (externalId) => catalog.get(principal, catalogId({ externalId })),
28
17
  children: (externalId, page) => catalog.list(principal, { parent: catalogId({ externalId }), ...page }),
29
- // Each read scans the account's catalog, so the branches cut at the depth are asked about 200 at a time.
18
+ // Each read scans the account's catalog, so the branches cut at the depth are asked about 200 at a time, in one read.
30
19
  withChildren: async (externalIds) => {
31
20
  const found = new Set();
32
21
  for (let start = 0; start < externalIds.length; start += PARENT_BATCH) {
33
22
  const batch = new Set(externalIds.slice(start, start + PARENT_BATCH));
34
- const ast = anyParent([...batch].map((externalId) => catalogId({ externalId })));
23
+ const parent = [...batch].map((externalId) => catalogId({ externalId }));
35
24
  for (let offset = 0;; offset += CATALOG_PAGE) {
36
- const page = await catalog.list(principal, { ast, limit: CATALOG_PAGE, offset });
25
+ const page = await catalog.list(principal, { parent, limit: CATALOG_PAGE, offset });
37
26
  for (const item of page.items)
38
27
  for (const parent of item.parents)
39
28
  if (batch.delete(parent))
@@ -1,4 +1,5 @@
1
1
  import type { Command } from "commander";
2
+ import type { Deadline, RunBudget } from "../../background/budget.js";
2
3
  import { type Body } from "../envelope.js";
3
4
  import { type DocumentWords } from "./words.js";
4
5
  export interface DocumentSyncArgs {
@@ -6,6 +7,24 @@ export interface DocumentSyncArgs {
6
7
  rescan?: boolean;
7
8
  /** Also index pending text for meaning search, with a model already downloaded. */
8
9
  embed?: boolean;
10
+ /** Sized to the run's deadline; pass it to `syncDocuments` so a sync stops in time and says how to go on. */
11
+ budget?: RunBudget;
12
+ /** The run's hard limit; pass it to `syncDocuments` so its last step, the word index, ends before it. */
13
+ deadline?: Deadline;
14
+ }
15
+ export interface DocumentSyncAnswer {
16
+ errors: unknown[];
17
+ pending: number;
18
+ /** `false` while the pass is unfinished: a folder walk or operations are left for the next sync. */
19
+ complete?: boolean;
20
+ walk?: {
21
+ folders_left: number;
22
+ listed: number;
23
+ };
24
+ saved?: number;
25
+ names_only?: number;
26
+ removed?: number;
27
+ unchanged?: number;
9
28
  }
10
29
  export interface DocumentSyncCommands {
11
30
  words: DocumentWords;
@@ -14,16 +33,13 @@ export interface DocumentSyncCommands {
14
33
  diagnostic(text: string): void;
15
34
  /** The selected profile, as `sync again` names it. */
16
35
  profile(): string;
17
- /** The most entries one sync reads under the chosen folders, as `sync --help` says. */
36
+ /** The entries one sync walks under the chosen folders before it stops and saves, as `sync --help` says. */
18
37
  maxEntries: number;
19
38
  /**
20
39
  * Syncs the selected profile into the shared store under the lock the CLI's writes take. `errors` are the failed
21
40
  * operations still pending; `pending` counts every operation left for the next sync.
22
41
  */
23
- sync(args: DocumentSyncArgs): Promise<{
24
- errors: unknown[];
25
- pending: number;
26
- }>;
42
+ sync(args: DocumentSyncArgs): Promise<DocumentSyncAnswer>;
27
43
  /** What `status` answers: the last sync, imported documents and pending work, from local files only. */
28
44
  status(): object | Promise<object>;
29
45
  }
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
3
+ import { environmentOf, runBudgetOf } from "../context.js";
3
4
  import { honoursDryRun } from "../dry-run-guard.js";
4
5
  import { FETCH, LOCAL_READ } from "../effects.js";
5
6
  import { itemOf } from "../envelope.js";
@@ -8,25 +9,55 @@ const addDocumentSyncCommandsDefinition = (program, helpers) => {
8
9
  const { output } = helpers;
9
10
  const wording = wordsOf(helpers.words);
10
11
  const { prefix, text } = wording;
11
- const sync = examples(annotate(program.command("sync"), { effects: FETCH })
12
+ const sync = examples(annotate(program.command("sync"), { effects: FETCH, partial: true })
12
13
  .summary("import what changed in the chosen folders, and finish an unfinished sync")
13
14
  .description("import what changed in the chosen folders, and finish an unfinished sync; " +
14
- `one sync reads at most ${helpers.maxEntries} entries under the chosen folders, and as many changes`), [`${prefix} sync`, `${prefix} sync --rescan --limit 500`])
15
+ `one sync walks about ${helpers.maxEntries} entries under the chosen folders, saves where it stopped, and ` +
16
+ "the next sync goes on from there"), [`${prefix} sync`, `${prefix} sync --rescan --limit 500`])
15
17
  .option("--limit <n>", text.syncLimit, positive, 200)
16
- .option("--rescan", "read every chosen folder again instead of only what changed")
18
+ .option("--rescan", "read every chosen folder again instead of only what changed; each --rescan starts the walk over, so run it " +
19
+ "once and continue with a plain sync")
17
20
  .option("--embed", "also index pending text for meaning search, with a model already downloaded")
18
- .action(async (args) => {
19
- const result = await helpers.sync(args);
21
+ .action(async (args, command) => {
22
+ const deadline = environmentOf(command).deadline?.();
23
+ const result = await helpers.sync({ ...args, budget: runBudgetOf(command), ...(deadline ? { deadline } : {}) });
24
+ const unfinished = result.complete === false || result.pending > 0;
25
+ const moved = (result.walk?.listed ?? 0) > 0 ||
26
+ [result.saved, result.names_only, result.removed, result.unchanged].some((count) => (count ?? 0) > 0);
27
+ const again = `${wording.app} ${helpers.profile()} sync`;
28
+ const timeout = command.optsWithGlobals().timeout;
29
+ // The same sync again, never --rescan, which would start the pass over; a run that moved nothing gets no step.
30
+ const next = unfinished && !result.errors.length && moved
31
+ ? [
32
+ {
33
+ kind: "command",
34
+ step: "sync.run",
35
+ command: "sync",
36
+ args: {
37
+ limit: args.limit,
38
+ ...(timeout === undefined ? {} : { timeout }),
39
+ ...(args.embed ? { embed: true } : {}),
40
+ },
41
+ why: "the sync stopped before the end of its pass; running it again goes on from there",
42
+ safe_to_auto_execute: true,
43
+ },
44
+ ]
45
+ : [];
20
46
  output(itemOf(result, {
21
47
  meta: result.errors.length
22
48
  ? {
23
49
  complete: false,
24
50
  issues: [{ code: "provider_error", reason: "sync.partial", source: wording.source }],
25
51
  }
26
- : {},
52
+ : unfinished
53
+ ? { complete: false }
54
+ : {},
55
+ next,
27
56
  }));
28
- if (result.errors.length || result.pending)
29
- helpers.diagnostic(`${result.pending} source operations remain; run ${wording.app} ${helpers.profile()} sync again\n`);
57
+ if (result.walk)
58
+ helpers.diagnostic(`${result.walk.folders_left} folders remain to list; run ${again} again\n`);
59
+ else if (result.errors.length || result.pending)
60
+ helpers.diagnostic(`${result.pending} source operations remain; run ${again} again\n`);
30
61
  if (result.errors.length)
31
62
  throw new CliError("provider_error", "sync completed partially; failed operations remain pending", {
32
63
  reason: "sync.partial",
@@ -11,6 +11,15 @@ export interface DocumentSourceFixture<M extends SourceFile = SourceFile> {
11
11
  isDocument?(file: M): boolean;
12
12
  /** Makes a change on the provider's side (a new or edited file) for the change feed to list; absent skips that check. */
13
13
  change?(): Promise<void>;
14
+ /**
15
+ * Adds a file inside a folder two levels below the root on the provider's side, and names both. A round of changes
16
+ * lists only the direct children of a folder the feed names, so the feed must name the new file or its own folder;
17
+ * absent skips that case.
18
+ */
19
+ addNested?(): Promise<{
20
+ file: string;
21
+ folder: string;
22
+ }>;
14
23
  /** An id the provider does not know; absent skips that case. */
15
24
  missing?: string;
16
25
  }
@@ -99,6 +99,18 @@ export const documentSourceContract = (make) => {
99
99
  },
100
100
  },
101
101
  ];
102
+ cases.push({
103
+ name: "changes: a file added deep in the tree is named in the feed, itself or by its own folder",
104
+ async run() {
105
+ const { source, addNested } = await make();
106
+ if (!addNested)
107
+ return;
108
+ const token = await source.startToken();
109
+ const { file, folder } = await addNested();
110
+ const named = new Set((await source.changes(token)).items.map((item) => item.id));
111
+ assert.ok(named.has(file) || named.has(folder), `the feed names ${file} or its folder ${folder}`);
112
+ },
113
+ });
102
114
  cases.push({
103
115
  name: "metadata: an id the provider does not know is not_found",
104
116
  async run() {
@@ -56,9 +56,9 @@ export interface CopyAge {
56
56
  }
57
57
  export declare const ageOf: (lastSync: string | undefined, now?: number) => CopyAge;
58
58
  export declare const staleCopy: (provider: string, lastSync: string | undefined, now?: number) => {
59
- next?: undefined;
60
59
  readonly missing?: undefined;
61
60
  meta?: undefined;
61
+ next?: undefined;
62
62
  } | {
63
63
  missing: {
64
64
  field: string;
@@ -286,10 +286,12 @@ const crmNote = (name, now) => {
286
286
  if (name === "scope")
287
287
  return now === "all"
288
288
  ? "store-wide — the next sync of that account copies every deal and lead, listing them all again"
289
- : "store-wide — the next sync of that account copies only the deals and leads of the sign-in's own user and " +
290
- "of the unassigned users, and marks the others deleted here; contacts and companies stay whole";
289
+ : "store-wide — the next sync of that account copies only the deals and leads of the unassigned users, or " +
290
+ "of the sign-in's own user while that list is empty, and marks the others deleted here; contacts and " +
291
+ "companies stay whole";
291
292
  if (name === "unassigned")
292
- return "store-wide — with scope mine, the next sync also copies the deals and leads of these users";
293
+ return ("store-wide — with scope mine, the next sync copies only these users' deals and leads, in place of the " +
294
+ "sign-in's own user's (add your own id to keep yours), and marks the others deleted here");
293
295
  if (name === "activities")
294
296
  return now === "on"
295
297
  ? "store-wide — the next sync also reads the activities and tasks on the deals and leads it keeps, from the " +
@@ -33,4 +33,4 @@ export declare const renderCsv: <R extends {
33
33
  close?: () => Promise<void>;
34
34
  }>(command: Command, open: (command: Command, access: {
35
35
  readOnly: boolean;
36
- }) => Promise<R>, read: (run: R) => Promise<CsvPage>) => Promise<void>;
36
+ }) => Promise<R>, read: (run: R) => Promise<CsvPage>, defaults?: readonly string[]) => Promise<void>;
@@ -132,7 +132,7 @@ export const printCsv = (command, page, paths) => {
132
132
  renderer.note(`→ more rows: run it again with --page ${page.page + 1}`);
133
133
  };
134
134
  /** Reads a page in the profile's run and closes it before the table is printed. */
135
- export const renderCsv = (command, open, read) => {
135
+ export const renderCsv = (command, open, read, defaults = DEAL_CSV_COLUMNS) => {
136
136
  refuseCsvConflict(command);
137
137
  return inCommandRun(command, async () => {
138
138
  const run = await open(command, { readOnly: true });
@@ -143,6 +143,6 @@ export const renderCsv = (command, open, read) => {
143
143
  finally {
144
144
  await run.close?.();
145
145
  }
146
- printCsv(command, page, csvColumnPaths(command));
146
+ printCsv(command, page, csvColumnPaths(command, defaults));
147
147
  });
148
148
  };
@@ -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 CrmLiveRecord } from "./records.js";
9
10
  export { type CsvField, type CsvPage, csvColumnPaths, csvFormatOption, DEAL_CSV_COLUMNS, printCsv, refuseCsvConflict, } from "./csv.js";
11
+ export { CRM_ORGANIZATIONS_QUERY, CRM_PEOPLE_QUERY, CRM_USERS_QUERY, type CrmLiveRecord, crmOrganizationOf, crmOrganizationSchema, crmPersonOf, crmPersonSchema, crmUserOf, crmUserSchema, } from "./records.js";
10
12
  export { type CrmStoreOptions, openCrmStore } from "./store.js";
11
13
  /**
12
14
  * The selected profile's CRM account, opened by the app for one command and closed once its answer is built, before
@@ -36,8 +38,16 @@ export interface CrmCommandOptions {
36
38
  }) => Promise<CrmRun>;
37
39
  /** The CRM has leads: mounts `leads list|show`. True when absent. */
38
40
  leads?: boolean;
39
- /** The writer's capabilities: mounts `create`, `update`, `move`, `close` and `delete` of each kind it writes. */
41
+ /**
42
+ * The writer's capabilities: mounts `create`, `update`, `move`, `close` and `delete` of each deal kind it writes, and
43
+ * `create` and `update` of `people` and `organizations` when they are mounted too.
44
+ */
40
45
  writes?: CrmWriteCapabilities;
46
+ /**
47
+ * What the source reads live: `person` and `organization` mount `people` and `organizations` list/show over
48
+ * `source.list`/`get`, `user` mounts `users` list/show over `source.users`. None when absent.
49
+ */
50
+ live?: readonly CrmLiveRecord[];
41
51
  now?: () => number;
42
52
  }
43
53
  /** What `deals list` and `leads list` narrow by, the same in memo and every CRM CLI (WC-OUT-11). */
@@ -23,8 +23,10 @@ import { crmStatus, syncCrm } from "../sync.js";
23
23
  import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
24
24
  import { csvFormatOption, renderCsv } from "./csv.js";
25
25
  import { pipelineView } from "./pipeline-view.js";
26
+ import { addCrmRecordCommands, integer } from "./records.js";
26
27
  import { addCrmSearchAll } from "./search-all.js";
27
28
  export { csvColumnPaths, csvFormatOption, DEAL_CSV_COLUMNS, printCsv, refuseCsvConflict, } from "./csv.js";
29
+ export { CRM_ORGANIZATIONS_QUERY, CRM_PEOPLE_QUERY, CRM_USERS_QUERY, crmOrganizationOf, crmOrganizationSchema, crmPersonOf, crmPersonSchema, crmUserOf, crmUserSchema, } from "./records.js";
28
30
  export { openCrmStore } from "./store.js";
29
31
  const MOST = 500;
30
32
  /** A stage by the store's reference, as memo's `stages list` and a deal's `base_stage` name it. */
@@ -171,11 +173,6 @@ const collect = (value, previous = []) => {
171
173
  throw new InvalidArgumentError("expected key=value");
172
174
  return [...previous, value];
173
175
  };
174
- const integer = (most) => (value) => {
175
- if (!/^[1-9]\d*$/.test(value) || Number(value) > most)
176
- throw new InvalidArgumentError(`expected 1 to ${most}`);
177
- return Number(value);
178
- };
179
176
  /** The words below the program, as `page.next` and `sync`'s next step run it again. */
180
177
  const pathOf = (command) => command.parent?.parent ? [...pathOf(command.parent), command.name()] : [command.name()];
181
178
  /** A CRM's own field codes are its keys, never ours to rename. */
@@ -558,6 +555,15 @@ const addCrmCommandsDefinition = (program, options) => {
558
555
  });
559
556
  });
560
557
  });
558
+ addCrmRecordCommands(program, {
559
+ within,
560
+ example,
561
+ open: options.open,
562
+ app: options.app,
563
+ live: options.live ?? [],
564
+ ...(writes ? { writes } : {}),
565
+ now,
566
+ });
561
567
  const fieldKinds = Object.keys(FIELD_KINDS).filter((word) => word !== "leads" || options.leads !== false);
562
568
  const fields = annotate(program.command("fields"), { effects: NO_EFFECTS }).description("the CRM's own fields on deals, leads, people and organizations, as last synced");
563
569
  example(withQuery(answerEntity(annotate(fields.command("list"), { effects: LOCAL_READ }), "crm_field", crmField)
@@ -0,0 +1,94 @@
1
+ import { type QueryRegistry } from "@wirecat/cli-base/query";
2
+ import { type Command } from "commander";
3
+ import * as v from "valibot";
4
+ import type { CrmOrganization, CrmPerson, CrmUser } from "../../domain/crm.js";
5
+ import type { AppIdentity } from "../../ports/app.js";
6
+ import type { CrmLiveKind } from "../source.js";
7
+ import type { CrmWriteCapabilities } from "../writer.js";
8
+ import type { CrmRun, CrmWithin } from "./index.js";
9
+ /** The kinds a CRM CLI reads live: its contacts and companies by `list`/`get`, its users by `users()`. */
10
+ export type CrmLiveRecord = CrmLiveKind | "user";
11
+ /** A CRM contact as the CRM holds it now. `emails` and `phones` are left out where the sign-in may not see them. */
12
+ export declare const crmPersonSchema: v.StrictObjectSchema<{
13
+ readonly id: v.StringSchema<undefined>;
14
+ readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
15
+ readonly first_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
16
+ readonly last_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
17
+ readonly position: v.NullableSchema<v.StringSchema<undefined>, undefined>;
18
+ readonly organization_ids: v.ArraySchema<v.StringSchema<undefined>, undefined>;
19
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StrictObjectSchema<{
20
+ readonly value: v.StringSchema<undefined>;
21
+ readonly type: v.NullableSchema<v.StringSchema<undefined>, undefined>;
22
+ }, undefined>, undefined>, undefined>;
23
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StrictObjectSchema<{
24
+ readonly value: v.StringSchema<undefined>;
25
+ readonly type: v.NullableSchema<v.StringSchema<undefined>, undefined>;
26
+ }, undefined>, undefined>, undefined>;
27
+ readonly assigned_to: v.NullableSchema<v.StringSchema<undefined>, undefined>;
28
+ readonly created_at: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>, undefined>;
29
+ readonly updated_at: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>, undefined>;
30
+ readonly url: v.NullableSchema<v.StringSchema<undefined>, undefined>;
31
+ readonly provider_metadata: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StrictObjectSchema<{
32
+ readonly label: v.NullableSchema<v.StringSchema<undefined>, undefined>;
33
+ readonly value: v.UnknownSchema;
34
+ readonly option_id: v.OptionalSchema<v.UnionSchema<[v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>], undefined>, undefined>;
35
+ }, undefined>, undefined>, undefined>;
36
+ readonly untrusted: v.ArraySchema<v.StringSchema<undefined>, undefined>;
37
+ }, undefined>;
38
+ /** A CRM company as the CRM holds it now. */
39
+ export declare const crmOrganizationSchema: v.StrictObjectSchema<{
40
+ readonly id: v.StringSchema<undefined>;
41
+ readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
42
+ readonly type: v.NullableSchema<v.StringSchema<undefined>, undefined>;
43
+ readonly own: v.BooleanSchema<undefined>;
44
+ readonly person_ids: v.ArraySchema<v.StringSchema<undefined>, undefined>;
45
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StrictObjectSchema<{
46
+ readonly value: v.StringSchema<undefined>;
47
+ readonly type: v.NullableSchema<v.StringSchema<undefined>, undefined>;
48
+ }, undefined>, undefined>, undefined>;
49
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StrictObjectSchema<{
50
+ readonly value: v.StringSchema<undefined>;
51
+ readonly type: v.NullableSchema<v.StringSchema<undefined>, undefined>;
52
+ }, undefined>, undefined>, undefined>;
53
+ readonly assigned_to: v.NullableSchema<v.StringSchema<undefined>, undefined>;
54
+ readonly created_at: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>, undefined>;
55
+ readonly updated_at: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>, undefined>;
56
+ readonly url: v.NullableSchema<v.StringSchema<undefined>, undefined>;
57
+ readonly provider_metadata: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StrictObjectSchema<{
58
+ readonly label: v.NullableSchema<v.StringSchema<undefined>, undefined>;
59
+ readonly value: v.UnknownSchema;
60
+ readonly option_id: v.OptionalSchema<v.UnionSchema<[v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>], undefined>, undefined>;
61
+ }, undefined>, undefined>, undefined>;
62
+ readonly untrusted: v.ArraySchema<v.StringSchema<undefined>, undefined>;
63
+ }, undefined>;
64
+ /** A user of the CRM account: someone of the owner's own company. */
65
+ export declare const crmUserSchema: v.StrictObjectSchema<{
66
+ readonly id: v.StringSchema<undefined>;
67
+ readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
68
+ readonly email: v.NullableSchema<v.StringSchema<undefined>, undefined>;
69
+ readonly position: v.NullableSchema<v.StringSchema<undefined>, undefined>;
70
+ readonly active: v.BooleanSchema<undefined>;
71
+ readonly department_ids: v.ArraySchema<v.StringSchema<undefined>, undefined>;
72
+ readonly untrusted: v.ArraySchema<v.StringSchema<undefined>, undefined>;
73
+ }, undefined>;
74
+ export declare const crmPersonOf: (person: CrmPerson) => v.InferOutput<typeof crmPersonSchema>;
75
+ export declare const crmOrganizationOf: (organization: CrmOrganization) => v.InferOutput<typeof crmOrganizationSchema>;
76
+ export declare const crmUserOf: (user: CrmUser) => v.InferOutput<typeof crmUserSchema>;
77
+ export declare const CRM_PEOPLE_QUERY: QueryRegistry;
78
+ export declare const CRM_ORGANIZATIONS_QUERY: QueryRegistry;
79
+ export declare const CRM_USERS_QUERY: QueryRegistry;
80
+ /** A whole number from 1 to `most`, as `--limit` and `--page` take it. */
81
+ export declare const integer: (most: number) => (value: string) => number;
82
+ export interface CrmRecordCommandOptions {
83
+ within: CrmWithin;
84
+ example: (command: Command, ...lines: string[]) => Command;
85
+ open: (command: Command, access: {
86
+ readOnly: boolean;
87
+ }) => Promise<CrmRun>;
88
+ app: AppIdentity;
89
+ live: readonly CrmLiveRecord[];
90
+ writes?: CrmWriteCapabilities;
91
+ now: () => number;
92
+ }
93
+ /** `people`, `organizations` and `users`: read live from the CRM, so `--offline` is refused (NEED-2661). */
94
+ export declare const addCrmRecordCommands: (program: Command, options: CrmRecordCommandOptions) => void;