@wirecat/cli-core 0.727.0 → 0.729.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.
@@ -1,4 +1,4 @@
1
- import { isDocumentAccountProvider, isFolderProvider } from "../../domain/providers.js";
1
+ import { alsoListedByKey, isDocumentAccountProvider, isFolderProvider } from "../../domain/providers.js";
2
2
  import { parseReference } from "../../domain/references.js";
3
3
  import { ENTITY_TABLES, isEntityType } from "./entity-types.js";
4
4
  import { storedThing, thingOf } from "./things.js";
@@ -9,11 +9,15 @@ const accountKeys = (database, ids) => {
9
9
  return database
10
10
  .prepare(`SELECT id, provider, external_id FROM accounts WHERE id IN (${unique.map(() => "?").join(",")})`)
11
11
  .all(...unique)
12
- .map(({ id, provider, external_id }) =>
13
- // A notes folder or a documents account is `notes:<its store id>`, as source lists and groups name it.
14
- isFolderProvider(String(provider)) || isDocumentAccountProvider(String(provider))
15
- ? { provider: "notes", account: String(id) }
16
- : { provider: String(provider), account: String(external_id) });
12
+ .flatMap(({ id, provider, external_id }) => {
13
+ const own = { provider: String(provider), account: String(external_id) };
14
+ // A notes folder or a documents account is `notes:<its store id>`, as source lists and groups name it; one that
15
+ // holds another kind too (Linear's tracker copy) is also its own key, so a group naming either holds it.
16
+ if (!isFolderProvider(own.provider) && !isDocumentAccountProvider(own.provider))
17
+ return [own];
18
+ const notes = { provider: "notes", account: String(id) };
19
+ return alsoListedByKey(own.provider) ? [notes, own] : [notes];
20
+ });
17
21
  };
18
22
  // Per connection: a long-lived process (`commands --serve`) outlives a migration another CLI runs on the store.
19
23
  const hasAccountColumn = new WeakMap();
@@ -1,4 +1,5 @@
1
1
  import { type Command } from "commander";
2
+ import type { DocumentSyncStep } from "../../cli/documents/library.js";
2
3
  import type { AppIdentity } from "../../ports/app.js";
3
4
  import type { MessageStore } from "../../store/store.js";
4
5
  import type { AccountKey } from "../../store/types.js";
@@ -24,6 +25,11 @@ export interface TrackerCommandOptions {
24
25
  }) => Promise<TrackerRun>;
25
26
  /** What the tracker's writer takes (`TrackerWriter.writes`): mounts `issues create`, `update` and `comment`. */
26
27
  writes?: readonly TrackerWrite[];
28
+ /**
29
+ * The documents half of `sync`, from `documentLibrary`, for a CLI that mounts the shared documents commands too:
30
+ * one `sync` then brings both and answers the documents under `documents`.
31
+ */
32
+ documents?: DocumentSyncStep;
27
33
  now?: () => number;
28
34
  }
29
35
  /**
@@ -1,5 +1,6 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
1
2
  import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
2
- import { InvalidArgumentError } from "commander";
3
+ import { InvalidArgumentError, Option } from "commander";
3
4
  import * as v from "valibot";
4
5
  import { answerEntity } from "../../cli/answer-entity.js";
5
6
  import { environmentOf, inCommandRun, outputFor, runBudgetOf } from "../../cli/context.js";
@@ -90,6 +91,110 @@ const trackerSync = v.strictObject({
90
91
  v.strictObject({ skipped: text }),
91
92
  ])),
92
93
  });
94
+ const partError = v.strictObject({ code: text, reason: v.optional(text), message: text });
95
+ /** The tracker's answer as `tracker_sync` has it, or the error it failed with, and the documents' answer or error. */
96
+ const trackerDocumentsSync = v.union([
97
+ v.strictObject({
98
+ ...trackerSync.entries,
99
+ documents: v.union([v.looseObject({}), v.strictObject({ error: partError })]),
100
+ }),
101
+ v.strictObject({
102
+ complete: v.literal(false),
103
+ synced: v.tuple([]),
104
+ error: partError,
105
+ documents: v.union([v.looseObject({}), v.strictObject({ error: partError })]),
106
+ }),
107
+ ]);
108
+ const resumeStep = (opts, why, extra = {}) => ({
109
+ kind: "command",
110
+ step: "tracker.sync",
111
+ command: "sync",
112
+ args: { ...(opts.maxPages === undefined ? {} : { max_pages: opts.maxPages }), ...extra },
113
+ why,
114
+ safe_to_auto_execute: true,
115
+ });
116
+ const trackerIssues = (report) => [
117
+ ...report.synced
118
+ .filter((one) => one.error !== undefined)
119
+ .map((one) => ({ code: "provider_error", reason: "sync.partial", source: `tracker:${one.kind}` })),
120
+ ...report.synced
121
+ .filter((one) => one.pass === "held")
122
+ .map((one) => ({
123
+ code: "validation_error",
124
+ reason: "tracker.unlisted-held",
125
+ source: `tracker:${one.kind}`,
126
+ })),
127
+ ];
128
+ const trackerNext = (report, opts) => report.state === "partial" && report.progress.steps > 0
129
+ ? [
130
+ resumeStep(opts, report.synced.some((one) => one.error !== undefined)
131
+ ? "a kind failed to sync; running sync again retries it"
132
+ : "the sync stopped before its end; running it again goes on from there"),
133
+ ]
134
+ : [];
135
+ const trackerAnswer = (report, opts) => {
136
+ const issues = trackerIssues(report);
137
+ const next = trackerNext(report, opts);
138
+ return itemOf(report, {
139
+ ...(report.state === "partial" || issues.length
140
+ ? { meta: { complete: false, ...(issues.length ? { issues } : {}) } }
141
+ : {}),
142
+ ...(next.length ? { next } : {}),
143
+ });
144
+ };
145
+ const errorOf = (error) => {
146
+ if (!isCliError(error))
147
+ return {
148
+ code: "provider_error",
149
+ reason: "sync.failed",
150
+ message: error instanceof Error ? error.message : String(error),
151
+ };
152
+ const reason = error.details.reason;
153
+ return { code: error.code, ...(typeof reason === "string" ? { reason } : {}), message: error.message };
154
+ };
155
+ /**
156
+ * Both parts in one answer: the tracker's report as `tracker_sync` has it, the documents' under `documents`. A part
157
+ * that fails is named in its place and in `meta.issues`, so the other's answer still shows; `complete` is both parts'.
158
+ */
159
+ const combinedAnswer = (tracker, documents, opts) => {
160
+ const failed = (part, error) => ({
161
+ code: error.code,
162
+ reason: error.reason ?? "sync.failed",
163
+ source: part,
164
+ });
165
+ const trackerError = "error" in tracker ? errorOf(tracker.error) : undefined;
166
+ const documentsError = "error" in documents ? errorOf(documents.error) : undefined;
167
+ const report = "value" in tracker ? tracker.value : undefined;
168
+ const outcome = "value" in documents ? documents.value : undefined;
169
+ const issues = [
170
+ ...(report ? trackerIssues(report) : []),
171
+ ...(trackerError ? [failed("tracker", trackerError)] : []),
172
+ ...(outcome?.meta.issues ?? []),
173
+ ...(documentsError ? [failed("documents", documentsError)] : []),
174
+ ];
175
+ const complete = report?.state === "complete" && outcome !== undefined && outcome.meta.complete !== false && issues.length === 0;
176
+ const [trackerStep] = report ? trackerNext(report, opts) : [];
177
+ const resume = trackerStep !== undefined || outcome?.next.some(({ step }) => step === "sync.run");
178
+ const next = [
179
+ ...(resume
180
+ ? [
181
+ resumeStep(opts, trackerStep?.why ?? "the sync stopped before its end; running it again goes on from there", {
182
+ ...(opts.timeout === undefined ? {} : { timeout: opts.timeout }),
183
+ ...(opts.embed ? { embed: true } : {}),
184
+ }),
185
+ ]
186
+ : []),
187
+ ...(outcome?.next.filter(({ step }) => step !== "sync.run") ?? []),
188
+ ];
189
+ const documentsPart = outcome ? outcome.item : { error: documentsError };
190
+ const item = report
191
+ ? { ...report, complete, documents: documentsPart }
192
+ : { complete: false, synced: [], error: trackerError, documents: documentsPart };
193
+ return itemOf(item, {
194
+ ...(complete ? {} : { meta: { complete: false, ...(issues.length ? { issues } : {}) } }),
195
+ ...(next.length ? { next } : {}),
196
+ });
197
+ };
93
198
  const trackerWrite = v.strictObject({
94
199
  operation_id: text,
95
200
  issue: v.optional(trackerView),
@@ -141,59 +246,90 @@ const addTrackerCommandsDefinition = (program, options) => {
141
246
  const paging = (command) => command
142
247
  .option("--limit <n>", `rows per page, 1–${MOST}`, integer(MOST), 50)
143
248
  .option("--page <n>", "which page, starting at 1", integer(1_000_000), 1);
144
- example(answerEntity(annotate(program.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), "tracker_sync", trackerSync).description("bring the tracker's copy in the local store up to date: teams, users, states, labels, projects, issues and " +
249
+ const syncOf = (command, opts) => (run) => {
250
+ const { signal } = environmentOf(command);
251
+ return syncTracker(run.source(), run.store, run.account, {
252
+ now: now(),
253
+ budget: runBudgetOf(command, opts.maxPages),
254
+ ...(signal ? { signal } : {}),
255
+ ...(opts.rescan ? { rescan: true } : {}),
256
+ });
257
+ };
258
+ const trackerPart = (command, opts, opened = () => { }) => inCommandRun(command, async () => {
259
+ const run = await options.open(command, { readOnly: false });
260
+ opened(run.account);
261
+ try {
262
+ return await syncOf(command, opts)(run);
263
+ }
264
+ finally {
265
+ await run.close?.();
266
+ }
267
+ });
268
+ const { documents } = options;
269
+ const sync = example(answerEntity(annotate(program.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), documents ? "tracker_documents_sync" : "tracker_sync", documents ? trackerDocumentsSync : trackerSync).description("bring the tracker's copy in the local store up to date: teams, users, states, labels, projects, issues and " +
145
270
  "comments that changed since the last sync, or everything with --rescan; once a day it also finds what the " +
146
271
  "tracker deleted. Open issues assigned to you become your tasks, and close when the issue is done, " +
147
- "canceled, deleted or goes to someone else. A run stops before its deadline or --max-pages and the next " +
148
- "one goes on from there"), "sync", "sync --rescan")
149
- .option("--rescan", "list everything again, every id too, dropping a round in progress")
150
- .option("--max-pages <pages>", "at most this many requests to the tracker in this run", integer(100_000))
151
- .action(async (opts, command) => {
152
- const { signal } = environmentOf(command);
153
- await within(command, false, async (run) => {
154
- const report = await syncTracker(run.source(), run.store, run.account, {
155
- now: now(),
272
+ "canceled, deleted or goes to someone else. " +
273
+ (documents
274
+ ? "It also imports what changed in the chosen document folders, answered under documents; a part that " +
275
+ "fails leaves the other's answer. "
276
+ : "") +
277
+ "A run stops before its deadline or --max-pages and the next one goes on from there"), "sync", "sync --rescan")
278
+ .option("--rescan", documents
279
+ ? "list everything again, issues and documents, dropping a round in progress; a rescan of the documents " +
280
+ "starts their walk over each time, so run it once and continue with a plain sync"
281
+ : "list everything again, every id too, dropping a round in progress")
282
+ .option("--max-pages <pages>", documents
283
+ ? "at most this many requests for the issues in this run, and as many for the documents"
284
+ : "at most this many requests to the tracker in this run", integer(100_000));
285
+ if (!documents)
286
+ sync.action(async (opts, command) => {
287
+ await within(command, false, async (run) => trackerAnswer(await syncOf(command, opts)(run), opts));
288
+ });
289
+ else
290
+ sync
291
+ .option("--embed", "also index the documents' pending text for meaning search, with a model already downloaded")
292
+ .addOption(new Option("--limit <n>", "refused: it would count documents only").hideHelp().argParser(() => {
293
+ throw new InvalidArgumentError("--limit counts documents only, and this sync brings the issues too; --max-pages bounds both parts");
294
+ }))
295
+ .action(async (opts, command) => {
296
+ const settled = async (part) => {
297
+ try {
298
+ return { value: await part() };
299
+ }
300
+ catch (error) {
301
+ // A cancel ends the whole command: it is not one part's failure.
302
+ if (environmentOf(command).signal?.aborted)
303
+ throw error;
304
+ return { error };
305
+ }
306
+ };
307
+ let account;
308
+ const tracker = await settled(() => trackerPart(command, opts, (one) => (account = one)));
309
+ const deadline = environmentOf(command).deadline?.();
310
+ const docs = await settled(() => documents(command, {
156
311
  budget: runBudgetOf(command, opts.maxPages),
157
- ...(signal ? { signal } : {}),
312
+ ...(account ? { account } : {}),
158
313
  ...(opts.rescan ? { rescan: true } : {}),
159
- });
160
- const failed = report.synced.filter((one) => one.error !== undefined);
161
- const next = report.state === "partial" && report.progress.steps > 0
162
- ? [
163
- {
164
- kind: "command",
165
- step: "tracker.sync",
166
- command: "sync",
167
- args: opts.maxPages === undefined ? {} : { max_pages: opts.maxPages },
168
- why: failed.length
169
- ? "a kind failed to sync; running sync again retries it"
170
- : "the sync stopped before its end; running it again goes on from there",
171
- safe_to_auto_execute: true,
172
- },
173
- ]
174
- : undefined;
175
- const issues = [
176
- ...failed.map((one) => ({
177
- code: "provider_error",
178
- reason: "sync.partial",
179
- source: `tracker:${one.kind}`,
180
- })),
181
- ...report.synced
182
- .filter((one) => one.pass === "held")
183
- .map((one) => ({
184
- code: "validation_error",
185
- reason: "tracker.unlisted-held",
186
- source: `tracker:${one.kind}`,
187
- })),
188
- ];
189
- return itemOf(report, {
190
- ...(report.state === "partial" || issues.length
191
- ? { meta: { complete: false, ...(issues.length ? { issues } : {}) } }
192
- : {}),
193
- ...(next ? { next } : {}),
194
- });
314
+ ...(opts.embed ? { embed: true } : {}),
315
+ ...(deadline ? { deadline } : {}),
316
+ }));
317
+ if ("error" in tracker && "error" in docs) {
318
+ const failed = errorOf(docs.error);
319
+ // An error envelope has no meta and keeps only the details its reason registers, so the documents'
320
+ // failure is told in the message of the tracker's error, which answers as a tracker-only sync's would.
321
+ throw isCliError(tracker.error)
322
+ ? new CliError(tracker.error.code, `${tracker.error.message}; the documents failed too ` +
323
+ `(${failed.reason ?? failed.code}): ${failed.message}`, tracker.error.details)
324
+ : tracker.error;
325
+ }
326
+ const timeout = command.optsWithGlobals().timeout;
327
+ const answer = combinedAnswer(tracker, docs, { ...opts, ...(timeout === undefined ? {} : { timeout }) });
328
+ renderAnswer(command, outputFor(command), answer);
329
+ if ("value" in docs)
330
+ for (const line of docs.value.diagnostics)
331
+ outputFor(command).streams.diagnostic(line);
195
332
  });
196
- });
197
333
  const issues = annotate(program.command("issues"), { effects: NO_EFFECTS }).description("the tracker's issues as last synced: state, team, project, assignee and labels");
198
334
  example(paging(withQuery(answerEntity(annotate(issues.command("list"), { effects: LOCAL_READ }), "tracker_issue", trackerView), ISSUES_QUERY).description("issues copied from the tracker, newest change first; run sync to bring them up to date")), "issues list type:started", "issues list assignee:none --json").action(async (words, opts, command) => {
199
335
  const lists = nativeTermLists(listQuery(typedQuery(words), ISSUES_QUERY, "issues list"), "issues list", ["type"]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.727.0",
3
+ "version": "0.729.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.130.0",
337
+ "@wirecat/cli-base": "0.131.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",