@wirecat/cli-core 0.728.0 → 0.730.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.
@@ -0,0 +1,718 @@
1
+ import { readFileSync, realpathSync, rmSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join, parse, relative, resolve, sep } from "node:path";
4
+ import { CliError, isCliError, resolvePaths } from "@wirecat/cli-base";
5
+ import { annotate } from "@wirecat/cli-base/commands";
6
+ import { Command, Option } from "commander";
7
+ import * as v from "valibot";
8
+ import { deadlineMargin } from "../../background/budget.js";
9
+ import { exclusionPattern, fileMirrorStatus, fileRemoteChanges, fileSyncState, fileVersions, mirrorId, restoreFileVersion, syncFileMirrors, watchMirrors, } from "../../documents.js";
10
+ import { parseDuration } from "../../domain/duration.js";
11
+ import { writeFileAtomic } from "../../files/atomic-write.js";
12
+ import { acquireLock } from "../../files/lock.js";
13
+ import { guardedWrite } from "../../sends/guarded.js";
14
+ import { newOperationId } from "../../sends/send-id.js";
15
+ import { refusedPlace } from "../../sends/upload.js";
16
+ import { environmentOf, outputFor } from "../context.js";
17
+ import { FETCH, LOCAL_READ, LOCAL_WRITE, ownerOnlyOption, REMOTE_READ, REMOTE_WRITE } from "../effects.js";
18
+ import { itemOf, jsonlRecords, listOf, snakeKeys } from "../envelope.js";
19
+ import { commandPath } from "../list-query.js";
20
+ import { terminalAsker } from "../messenger/ask.js";
21
+ import { fileConflictsCommand } from "./file-conflicts.js";
22
+ /** A mirror with the account it was added for: a sync signed in to another account is refused. */
23
+ const SavedMirror = v.strictObject({
24
+ id: v.string(),
25
+ path: v.string(),
26
+ folder: v.string(),
27
+ account: v.string(),
28
+ exclude: v.optional(v.array(v.string())),
29
+ });
30
+ const ID = "mirror id from mirrors list";
31
+ const PATH = "the file's path inside the mirror, like notes/plan.md";
32
+ /** The engine's refusals of a whole run, which a sync ends with instead of the generic partial one. */
33
+ const STOPS = new Set(["mirror.too-many-deletions", "mirror.too-many-replacements", "mirror.no-space"]);
34
+ const errorOf = (error) => isCliError(error) ? error : new CliError("provider_error", error instanceof Error ? error.message : String(error));
35
+ const accountOf = (chosen) => {
36
+ const accounts = new Set(chosen.map((mirror) => mirror.account));
37
+ if (accounts.size > 1)
38
+ throw new CliError("validation_error", "these mirrors belong to different accounts; sync them one at a time");
39
+ return chosen[0]?.account;
40
+ };
41
+ const realOf = (path) => {
42
+ try {
43
+ return realpathSync(path);
44
+ }
45
+ catch {
46
+ return resolve(path);
47
+ }
48
+ };
49
+ /** A path inside the mirror as the version log names it: relative, with `/`, from a relative or absolute path. */
50
+ const insideOf = (root, input) => {
51
+ const path = isAbsolute(input) ? relative(root, input) : input;
52
+ return path.split(sep).join("/");
53
+ };
54
+ const collect = (value, previous = []) => [...previous, value];
55
+ const allOf = (command, items) => listOf(command, { items, limit: Math.max(1, items.length), has_more: false });
56
+ /** The target with each listing's size kept by remote folder, so the answer says how far it got. */
57
+ const recorded = (target) => {
58
+ const listings = new Map();
59
+ const list = async (folder, signal, options) => {
60
+ const listing = await target.list(folder, signal, options);
61
+ if (listing)
62
+ listings.set(folder, {
63
+ files: listing.files.length,
64
+ complete: listing.complete,
65
+ ...(options?.from === undefined ? {} : { resumed: true }),
66
+ });
67
+ return listing;
68
+ };
69
+ return { listings, target: { ...target, list } };
70
+ };
71
+ const moved = (item) => "uploaded" in item &&
72
+ [item.uploaded, item.downloaded, item.merged, item.trashed, item.renamed, item.adopted].some((done) => done.length);
73
+ /** A sync kept its place in the remote's listing, so the next run lists from there instead of from the start. */
74
+ const keptPlace = (item) => "listed" in item && item.listed?.soFar !== undefined;
75
+ /**
76
+ * Fires a margin before the run's deadline (cli-core's, at most half the run), so a sync stops on its own between
77
+ * steps, saves and answers instead of being cut with nothing said.
78
+ */
79
+ const beforeDeadline = (command) => {
80
+ const environment = environmentOf(command);
81
+ const deadline = environment.deadline?.();
82
+ const soon = new AbortController();
83
+ const timer = deadline &&
84
+ setTimeout(() => soon.abort(), Math.max(0, deadline.endsAt - Math.min(deadlineMargin(deadline), deadline.ms / 2) - Date.now()));
85
+ timer?.unref();
86
+ return {
87
+ signal: environment.signal ? AbortSignal.any([environment.signal, soon.signal]) : soon.signal,
88
+ deadline,
89
+ clear: () => clearTimeout(timer),
90
+ };
91
+ };
92
+ /**
93
+ * `mirrors add|list|status|preview|sync|watch|update|remove`, `mirrors versions list|restore` and `mirrors conflicts
94
+ * list|show|resolve`: local folders and remote folders kept the same both ways, file by file, over `syncFileMirrors`.
95
+ * The app gives its remote, how `add` finds a remote folder, its write guard and its keys. Each profile keeps its
96
+ * mirrors in `mirrors.json` under its state folder, and each mirror's state, versions and the sync lock in `mirrors/`.
97
+ */
98
+ export const fileMirrorsCommand = (helpers) => {
99
+ const { identity, service, remote: REMOTE } = helpers;
100
+ const CLI = identity.command;
101
+ const output = helpers.output;
102
+ /** The profile's mirrors, their sync state, version stores and lock, under its state folder. */
103
+ const homeOf = (command) => {
104
+ const profile = helpers.profile(command);
105
+ const dir = helpers.stateDir(command);
106
+ const listPath = join(dir, "mirrors.json");
107
+ const states = join(dir, "mirrors");
108
+ const mirrors = () => {
109
+ let value;
110
+ try {
111
+ value = JSON.parse(readFileSync(listPath, "utf8"));
112
+ }
113
+ catch (error) {
114
+ if (error.code === "ENOENT")
115
+ return [];
116
+ throw new CliError("configuration_error", `${listPath} is unreadable; refusing to reset it`);
117
+ }
118
+ const parsed = v.safeParse(v.array(SavedMirror), value);
119
+ if (!parsed.success)
120
+ throw new CliError("configuration_error", `${listPath} is invalid; refusing to reset it`);
121
+ return parsed.output;
122
+ };
123
+ const find = (id) => {
124
+ const mirror = mirrors().find((one) => one.id === id);
125
+ if (!mirror)
126
+ throw new CliError("not_found", `no mirror ${id} in profile ${profile}; see ${CLI} ${profile} mirrors list`, {
127
+ reason: "mirror.not-found",
128
+ });
129
+ return mirror;
130
+ };
131
+ const keepForDays = helpers.keepForDays(command);
132
+ return {
133
+ profile,
134
+ mirrors,
135
+ find,
136
+ chosen: (id) => {
137
+ const chosen = id ? [find(id)] : mirrors();
138
+ if (!chosen.length)
139
+ throw new CliError("not_found", `profile ${profile} has no mirrors; add one with ${CLI} ${profile} mirrors add`, { reason: "mirror.none" });
140
+ return chosen;
141
+ },
142
+ save: (list) => writeFileAtomic(listPath, JSON.stringify(list, null, 2), { mode: 0o600 }),
143
+ statePath: (mirror) => join(states, `${mirror.id}.json`),
144
+ stateOf: (mirror) => fileSyncState(states, mirror, mirror.account),
145
+ versionsOf: (mirror) => fileVersions(join(states, `${mirror.id}.versions`), Date.now, keepForDays),
146
+ lock: () => acquireLock(join(states, "sync.lock")).catch((error) => {
147
+ throw new CliError("provider_unavailable", "another mirrors sync or watch holds this profile; retry later", {
148
+ reason: "profile.busy",
149
+ ...(isCliError(error) ? { holders: error.details.holders } : {}),
150
+ });
151
+ }),
152
+ };
153
+ };
154
+ const hintsOf = (profile) => ({
155
+ preview: `${CLI} ${profile} mirrors preview <id>`,
156
+ repin: `\`${CLI} ${profile} mirrors sync <id> --repin\``,
157
+ sync: `${CLI} ${profile} mirrors sync <id>`,
158
+ allowDeletions: "--allow-deletions <count>",
159
+ exclude: `${CLI} ${profile} mirrors update <id> --ignore <path>`,
160
+ });
161
+ /**
162
+ * What the engine needs beside the mirrors: the remote, the account and each write behind the command's own key
163
+ * and the keys the app names for it. One question per set of keys, however many files.
164
+ */
165
+ const engineOf = (command, target, chosen, signal) => {
166
+ const home = homeOf(command);
167
+ const key = commandPath(command).replaceAll(" ", ".");
168
+ const guards = new Map();
169
+ // Each set of keys has its own guard, so a deny on a delete key still lets additions through; a key the owner
170
+ // allowed once is not asked again in the same run.
171
+ const approved = new Set();
172
+ const terminal = terminalAsker(command);
173
+ const ask = async (question, request) => {
174
+ const keys = question.split(" and ");
175
+ if (keys.every((one) => approved.has(one)))
176
+ return;
177
+ await terminal(question, request);
178
+ for (const one of keys)
179
+ approved.add(one);
180
+ };
181
+ const guard = (attempt, act) => {
182
+ const extra = [...helpers.keysOf({ action: attempt.action, side: attempt.side })];
183
+ const name = extra.join(" ");
184
+ const keyed = guards.get(name) ?? helpers.writeGuard(command, extra, ask);
185
+ guards.set(name, keyed);
186
+ const request = { chatId: null, kind: "edit", key, operationId: attempt.operationId };
187
+ keyed.refuse(request);
188
+ return guardedWrite(keyed, request, act);
189
+ };
190
+ const own = signal ?? environmentOf(command).signal;
191
+ return {
192
+ target,
193
+ principal: accountOf(chosen),
194
+ guard,
195
+ operationId: newOperationId,
196
+ errorOf,
197
+ lock: home.lock,
198
+ hints: hintsOf(home.profile),
199
+ stateOf: (mirror) => home.stateOf(mirror),
200
+ versionsOf: home.versionsOf,
201
+ remote: REMOTE,
202
+ ...(own ? { signal: own } : {}),
203
+ };
204
+ };
205
+ /**
206
+ * Each mirror in turn until the deadline is near; one left for then is answered as stopped, since the engine refuses
207
+ * to start once the signal has fired. The remote files a stopped listing did not reach are counted, not listed: a
208
+ * big remote's would pass the output's limit, none of them is deleted, and the next sync lists them.
209
+ */
210
+ const syncEach = async (command, remoteTarget, chosen, options, stop) => {
211
+ const { listings, target } = recorded(remoteTarget);
212
+ const engine = engineOf(command, target, chosen, stop);
213
+ const items = [];
214
+ const issues = [];
215
+ // One lock for the run, as one call for every mirror takes it, so no watch syncs between two mirrors.
216
+ const held = await engine.lock();
217
+ const lock = async () => ({ held: () => held.held(), release: () => { } });
218
+ try {
219
+ for (const mirror of chosen) {
220
+ if (stop.aborted) {
221
+ items.push({ id: mirror.id, path: mirror.path, stopped: true });
222
+ continue;
223
+ }
224
+ const one = await syncFileMirrors({ ...engine, ...options, lock, mirrors: [mirror] });
225
+ // A dry run saves no listing, so only a sync's kept place says the next run goes on from it.
226
+ const kept = options.dryRun ? undefined : engine.stateOf(mirror).read().listing;
227
+ const run = listings.get(mirror.folder);
228
+ const listed = run && kept ? { ...run, soFar: kept.files.length } : run;
229
+ for (const item of one.items) {
230
+ const cut = item.stopped === true || (listed?.complete === false && stop.aborted);
231
+ const unreached = cut && listed?.complete === false;
232
+ const unknown = unreached ? item.unknown.filter((file) => file.side !== "remote") : item.unknown;
233
+ if (item.errors.length || item.conflicts.length || unknown.length)
234
+ for (const issue of one.issues)
235
+ issues.push(issue);
236
+ items.push({
237
+ ...item,
238
+ unknown,
239
+ ...(listed ? { listed } : {}),
240
+ ...(cut ? { stopped: true } : {}),
241
+ ...(unreached ? { unlisted: item.unknown.length - unknown.length } : {}),
242
+ });
243
+ }
244
+ }
245
+ }
246
+ finally {
247
+ await held.release();
248
+ }
249
+ return { items, issues };
250
+ };
251
+ /**
252
+ * What a stopped run offers: the same run again when it moved or kept its place in the listing, since it goes on
253
+ * from where it stopped; when only a listing that cannot go on fit (a folder's, or any preview's), a longer run, as
254
+ * the same deadline would list the same files again.
255
+ */
256
+ const resumeOf = (command, name, items, deadline, id) => {
257
+ const stopped = items.filter((item) => item.stopped);
258
+ if (!stopped.length)
259
+ return [];
260
+ const only = stopped.length === 1 ? stopped[0]?.id : id;
261
+ const timeout = command.optsWithGlobals().timeout;
262
+ const ms = deadline?.ms ?? 0;
263
+ const longer = ms < 15 * 60_000 ? "15m" : `${Math.ceil((ms * 2) / 3_600_000)}h`;
264
+ const again = name === "sync" && items.some((item) => moved(item) || keptPlace(item));
265
+ const listing = again && !items.some(moved);
266
+ return [
267
+ {
268
+ kind: "command",
269
+ step: again ? "mirrors.sync" : `mirrors.${name}.longer`,
270
+ command: `mirrors ${name}`,
271
+ args: { ...(only ? { id: only } : {}), ...(again ? (timeout ? { timeout } : {}) : { timeout: longer }) },
272
+ why: listing
273
+ ? `the ${service} listing stopped before its deadline and kept its place; run it again to go on from there`
274
+ : again
275
+ ? "the sync stopped before its deadline and kept what it did; run it again to go on from there"
276
+ : `listing ${service} took the whole run; give it more time, in a terminal`,
277
+ safe_to_auto_execute: false,
278
+ },
279
+ ];
280
+ };
281
+ /**
282
+ * A mirror would send every file under its folder to the remote. `files upload`'s rule refuses credential folders,
283
+ * the WireCat apps' folders and the store; a folder holding this CLI's own folders would also send its state and
284
+ * the versions it keeps, and change under every sync.
285
+ */
286
+ const refuseSensitive = (root, env) => {
287
+ const real = realOf(root);
288
+ const own = Object.values(resolvePaths({ appName: identity.appName, prefix: identity.envPrefix, env })).map(realOf);
289
+ const holds = (dir) => {
290
+ const way = relative(real, dir);
291
+ return way === "" || (!way.startsWith("..") && !isAbsolute(way));
292
+ };
293
+ // The home folder, or one holding it, is never a mirror, even with the CLI's folders moved out of it.
294
+ // On Windows a drive root other than the home's drive holds none of the folders above, yet is a whole disk.
295
+ const driveRoot = real === parse(real).root;
296
+ if (driveRoot || own.some(holds) || holds(realOf(env.HOME ?? homedir())) || refusedPlace(root, identity, env))
297
+ throw new CliError("validation_error", `${root} is not mirrored: the home folder, credential folders, the WireCat apps' folders and a folder holding ` +
298
+ `${CLI}'s own settings or state are never sent to ${service}; mirror a folder of its own`, { reason: "mirror.not-folder" });
299
+ };
300
+ const ignoreOption = () => new Option("--ignore <path>", "leave this path out on both sides, a path or a glob; repeat it for more: a name at any depth (node_modules, " +
301
+ "*.iso) or a path from the mirror's root (/Photos)").argParser(collect);
302
+ const keepOption = () => new Option("--keep <side>", `settle each conflict: keep the local file, the ${service} one, or both`).choices([
303
+ "local",
304
+ REMOTE,
305
+ "both",
306
+ ]);
307
+ const keepOf = (side) => (side === REMOTE ? "remote" : side);
308
+ const addCommand = () => annotate(new Command("add"), {
309
+ effects: FETCH,
310
+ offline: false,
311
+ mcp: false,
312
+ examples: helpers.root.examples.map((example) => `${CLI} personal mirrors add ${example}`),
313
+ })
314
+ .summary(`mirror a local folder and a ${helpers.root.place} both ways`)
315
+ .description(`mirror a local folder and a ${helpers.root.place} both ways: checks the ${helpers.root.place} and saves the ` +
316
+ `pair; nothing is copied until mirrors sync${helpers.root.note ? `. ${helpers.root.note}` : ""}`)
317
+ .argument("<folder>", helpers.root.description)
318
+ .argument("<path>", "the local folder")
319
+ .addOption(ignoreOption())
320
+ .action(async function (folder, path, args) {
321
+ const root = resolve(path);
322
+ let directory = false;
323
+ try {
324
+ directory = statSync(root).isDirectory();
325
+ }
326
+ catch { }
327
+ if (!directory)
328
+ throw new CliError("validation_error", "the local path is not a folder", { reason: "mirror.not-folder" });
329
+ refuseSensitive(root, environmentOf(this).env ?? process.env);
330
+ const exclude = [...new Set((args.ignore ?? []).map(exclusionPattern))];
331
+ const home = homeOf(this);
332
+ const found = await helpers.connect(this, async (remote) => ({
333
+ ...(await remote.root(folder)),
334
+ account: await remote.target.identity(),
335
+ }));
336
+ const mirror = {
337
+ path: root,
338
+ folder: found.folder,
339
+ account: found.account,
340
+ ...(exclude.length ? { exclude } : {}),
341
+ };
342
+ const id = mirrorId(mirror.path, mirror.folder);
343
+ const list = home.mirrors();
344
+ const added = !list.some((one) => one.id === id);
345
+ if (added) {
346
+ list.push({ id, ...mirror });
347
+ // The remote folder is pinned now, so a folder put in its place before the first sync is refused, not
348
+ // mirrored. A fresh state, whatever a removal cut short left behind: an old one would read every file
349
+ // missing since as deleted.
350
+ home.stateOf({ id, ...mirror }).save({
351
+ version: 1,
352
+ principal: mirror.account,
353
+ root: mirror.path,
354
+ target: mirror.folder,
355
+ rootId: found.rootId,
356
+ entries: {},
357
+ pending: {},
358
+ });
359
+ await home.save(list);
360
+ }
361
+ const saved = home.find(id);
362
+ output(this, itemOf({ id, path: root, folder: mirror.folder, ignore: saved.exclude ?? [], added }));
363
+ });
364
+ /** Changes what a mirror ignores under the sync lock, so no running sync reads half of it. */
365
+ const updateCommand = () => annotate(new Command("update"), {
366
+ effects: LOCAL_WRITE,
367
+ mcp: false,
368
+ examples: [
369
+ `${CLI} personal mirrors update 1a2b3c4d --ignore Photos --ignore "*.iso"`,
370
+ `${CLI} personal mirrors update 1a2b3c4d --clear --ignore Photos`,
371
+ ],
372
+ })
373
+ .summary("add paths a mirror ignores, or clear the list; nothing is deleted on either side")
374
+ .description("add paths to what a mirror ignores, as mirrors list shows it. --clear empties the list first, so --clear " +
375
+ "with --ignore keeps only the paths given: that is how one path stops being ignored. An ignored path is " +
376
+ "left alone on both sides and never deleted, now or later; one no longer ignored is synced as a new " +
377
+ "folder, copying one-sided files and reporting different ones as conflicts, deleting nothing")
378
+ .argument("<id>", ID)
379
+ .addOption(ignoreOption())
380
+ .addOption(new Option("--clear", "empty the list before adding any --ignore paths; alone, sync every path again"))
381
+ .action(async function (id, args) {
382
+ const home = homeOf(this);
383
+ home.find(id);
384
+ if (!args.ignore?.length && !args.clear)
385
+ throw new CliError("validation_error", "give a path to ignore with --ignore, or --clear to empty the list", {
386
+ param: "--ignore",
387
+ });
388
+ const added = (args.ignore ?? []).map(exclusionPattern);
389
+ const held = await home.lock();
390
+ let exclude = [];
391
+ try {
392
+ await home.save(home.mirrors().map((one) => {
393
+ if (one.id !== id)
394
+ return one;
395
+ exclude = [...new Set([...(args.clear ? [] : (one.exclude ?? [])), ...added])];
396
+ const { exclude: _, ...rest } = one;
397
+ return exclude.length ? { ...rest, exclude } : rest;
398
+ }));
399
+ }
400
+ finally {
401
+ await held.release();
402
+ }
403
+ output(this, itemOf({ id, ignore: exclude }));
404
+ });
405
+ const listCommand = () => annotate(new Command("list"), {
406
+ effects: LOCAL_READ,
407
+ examples: [`${CLI} personal mirrors list --json`],
408
+ })
409
+ .description("list this profile's mirrors")
410
+ .action(function () {
411
+ output(this, allOf("mirrors list", homeOf(this)
412
+ .mirrors()
413
+ .map(({ id, path, folder, exclude }) => ({ id, path, folder, ignore: exclude ?? [] }))));
414
+ });
415
+ const removeCommand = () => annotate(new Command("remove"), {
416
+ effects: LOCAL_WRITE,
417
+ mcp: false,
418
+ examples: [`${CLI} personal mirrors remove 1a2b3c4d`],
419
+ })
420
+ .summary("stop mirroring a folder; nothing on either side changes")
421
+ .description(`stop mirroring a folder: nothing on ${service} or in the local folder is changed; its kept versions stay`)
422
+ .argument("<id>", ID)
423
+ .action(async function (id) {
424
+ const home = homeOf(this);
425
+ const mirror = home.find(id);
426
+ const held = await home.lock();
427
+ try {
428
+ // The state goes first: added again later, the pair starts as a first sync, which deletes nothing.
429
+ rmSync(home.statePath(mirror), { force: true });
430
+ await home.save(home.mirrors().filter((one) => one.id !== id));
431
+ }
432
+ finally {
433
+ await held.release();
434
+ }
435
+ output(this, itemOf({ id, removed: true }));
436
+ });
437
+ const statusCommand = () => annotate(new Command("status"), {
438
+ effects: LOCAL_READ,
439
+ examples: [`${CLI} personal mirrors status --json`],
440
+ })
441
+ .summary("show what the next sync would send from local changes")
442
+ .description(`show which local files the next sync would send or delete on ${service}; ${service} is not asked`)
443
+ .argument("[id]", `${ID}; every mirror of the profile when omitted`)
444
+ .action(async function (id) {
445
+ const home = homeOf(this);
446
+ const chosen = id ? [home.find(id)] : home.mirrors();
447
+ const items = await fileMirrorStatus(chosen, (mirror) => home.stateOf(mirror));
448
+ output(this, allOf("mirrors status", items.map((item) => ({
449
+ id: item.id,
450
+ path: item.path,
451
+ folder: item.folder,
452
+ upload: item.upload.length,
453
+ delete: item.delete.length,
454
+ unchanged: item.unchanged,
455
+ remote_checked: item.remote_checked,
456
+ }))));
457
+ });
458
+ const previewCommand = () => annotate(new Command("preview"), {
459
+ effects: REMOTE_READ,
460
+ offline: false,
461
+ // Listing a big remote can take minutes: it stops before its deadline (5 min, 45 s over MCP) and says so.
462
+ cooperative: true,
463
+ examples: [`${CLI} personal mirrors preview --json`, `${CLI} personal mirrors preview 1a2b3c4d --keep ${REMOTE}`],
464
+ })
465
+ .summary(`list ${service} and show what mirrors sync would do`)
466
+ .description(`list ${service} and show what mirrors sync would do: each upload, download, merge, rename, trash and ` +
467
+ "conflict; nothing is changed on either side")
468
+ .argument("[id]", `${ID}; every mirror of the profile when omitted`)
469
+ .addOption(keepOption())
470
+ .action(async function (id, args) {
471
+ const chosen = homeOf(this).chosen(id);
472
+ const keep = keepOf(args.keep);
473
+ const soon = beforeDeadline(this);
474
+ const { items } = await helpers
475
+ .connect(this, (remote) => syncEach(this, remote.target, chosen, { dryRun: true, ...(keep ? { keep } : {}) }, soon.signal))
476
+ .finally(soon.clear);
477
+ const body = allOf("mirrors preview", items.map((item) => snakeKeys(item)));
478
+ const stopped = items.filter((item) => item.stopped);
479
+ // Not a resumable command: a plan cut short is no plan, so it exits with the issue's code.
480
+ if (stopped.length) {
481
+ body.meta = {
482
+ complete: false,
483
+ issues: stopped.map((item) => ({
484
+ code: "timeout",
485
+ reason: "mirror.stopped",
486
+ source: `mirror ${item.id}`,
487
+ })),
488
+ };
489
+ body.next = resumeOf(this, "preview", items, soon.deadline, id);
490
+ }
491
+ output(this, body);
492
+ });
493
+ const syncCommand = () => annotate(new Command("sync"), {
494
+ effects: REMOTE_WRITE,
495
+ offline: false,
496
+ // A big remote's first sync takes hours: each run stops before its deadline (15 min, 45 s over MCP), keeps
497
+ // what it did and answers partial, and the next goes on from there.
498
+ cooperative: true,
499
+ partial: true,
500
+ examples: [`${CLI} personal mirrors sync`, `${CLI} personal mirrors sync 1a2b3c4d --keep ${REMOTE}`],
501
+ })
502
+ .summary("sync mirrors both ways once")
503
+ .description("sync mirrors both ways once: a change on one side is copied to the other, a deletion goes to the other " +
504
+ "side's trash, a text file changed on both sides in different places is merged, and any other file " +
505
+ "changed on both sides is reported for mirrors conflicts or --keep; mirrors preview shows the plan first. " +
506
+ "A run stops before its deadline, keeps what it did, and the next sync goes on from there")
507
+ .argument("[id]", `${ID}; every mirror of the profile when omitted`)
508
+ .addOption(keepOption())
509
+ .addOption(ownerOnlyOption("--allow-deletions <count>", "let this run delete up to this many files when the guard stops it"))
510
+ .addOption(ownerOnlyOption("--allow-replacements <count>", "let this run overwrite up to this many existing files when the guard stops it; each is kept as a version first"))
511
+ .addOption(ownerOnlyOption("--replace", "let this run overwrite any number of existing files when the guard stops it; each is kept as a version first"))
512
+ .addOption(ownerOnlyOption("--repin", `the ${service} or local folder was replaced and the new one is right: record it and sync`))
513
+ .action(async function (id, args) {
514
+ const home = homeOf(this);
515
+ const chosen = home.chosen(id);
516
+ // An approval is for the files one mirror's preview showed, never for every mirror at once.
517
+ const oneMirror = (flag) => {
518
+ if (chosen.length > 1)
519
+ throw new CliError("validation_error", `${flag} needs the mirror's id; see ${CLI} ${home.profile} mirrors list`, { param: flag });
520
+ };
521
+ const countOf = (flag, value, what) => {
522
+ if (value === undefined)
523
+ return undefined;
524
+ const count = Number(value);
525
+ if (!Number.isSafeInteger(count) || count < 1)
526
+ throw new CliError("validation_error", `${flag} takes the number of files the run may ${what}`, {
527
+ param: flag,
528
+ });
529
+ oneMirror(flag);
530
+ return count;
531
+ };
532
+ const allowDeletions = countOf("--allow-deletions", args.allowDeletions, "delete");
533
+ if (args.replace && args.allowReplacements !== undefined)
534
+ throw new CliError("validation_error", "give --allow-replacements <count> or --replace, not both", {
535
+ param: "--replace",
536
+ });
537
+ if (args.replace)
538
+ oneMirror("--replace");
539
+ const allowReplacements = args.replace
540
+ ? Number.POSITIVE_INFINITY
541
+ : countOf("--allow-replacements", args.allowReplacements, "replace");
542
+ const keep = keepOf(args.keep);
543
+ const soon = beforeDeadline(this);
544
+ const { items, issues } = await helpers
545
+ .connect(this, (remote) => syncEach(this, remote.target, chosen, {
546
+ ...(keep ? { keep } : {}),
547
+ ...(allowDeletions ? { allowDeletions } : {}),
548
+ ...(allowReplacements ? { allowReplacements } : {}),
549
+ ...(args.repin ? { repin: true } : {}),
550
+ }, soon.signal))
551
+ .finally(soon.clear);
552
+ const body = allOf("mirrors sync", items.map((item) => snakeKeys(item)));
553
+ const stopped = items.some((item) => item.stopped);
554
+ if (issues.length || stopped)
555
+ body.meta = { ...body.meta, complete: false, ...(issues.length ? { issues } : {}) };
556
+ if (stopped)
557
+ body.next = resumeOf(this, "sync", items, soon.deadline, id);
558
+ output(this, body);
559
+ const stop = items
560
+ .flatMap((item) => ("errors" in item ? item.errors : []))
561
+ .find((error) => error.reason && STOPS.has(error.reason));
562
+ if (stop)
563
+ throw new CliError(stop.code === "confirmation_required" ? stop.code : "validation_error", stop.message, {
564
+ reason: stop.reason,
565
+ });
566
+ if (issues.length)
567
+ throw new CliError("provider_error", `some files were not synced; see conflicts, unknown and errors, then settle each conflict with mirrors ` +
568
+ `conflicts resolve, or rerun with --keep local, ${REMOTE} or both`, { reason: "mirror.partial" });
569
+ });
570
+ const describeCycle = (cycle) => {
571
+ const time = cycle.at.slice(11, 19);
572
+ if (cycle.error)
573
+ return `${time} ${cycle.triggers.join("+")}: ${cycle.error.message}; trying again`;
574
+ const parts = (cycle.results ?? []).map((result) => `${result.id} ${result.uploaded.length} sent, ${result.downloaded.length} pulled, ` +
575
+ (result.merged.length ? `${result.merged.length} merged, ` : "") +
576
+ `${result.trashed.length} trashed` +
577
+ (result.conflicts.length
578
+ ? `, ${result.conflicts.length} conflicts (mirrors conflicts list ${result.id})`
579
+ : "") +
580
+ // A run the guard or a root problem stopped says why at every cycle, until the owner settles it.
581
+ result.errors
582
+ .filter((error) => error.path === ".")
583
+ .map((error) => `; stopped: ${error.message}`)
584
+ .join(""));
585
+ return `${time} ${cycle.triggers.join("+")}: ${parts.join("; ") || "nothing to do"}`;
586
+ };
587
+ const watchCommand = () => annotate(new Command("watch"), {
588
+ effects: REMOTE_WRITE,
589
+ offline: false,
590
+ lifetime: "persistent",
591
+ examples: [`${CLI} personal mirrors watch`, `${CLI} personal mirrors watch 1a2b3c4d --every 2m --jsonl`],
592
+ })
593
+ .summary("keep syncing both ways until Ctrl-C or --timeout")
594
+ .description(`keep syncing both ways until Ctrl-C or --timeout: on each local save, and when ${service} changes; a file ` +
595
+ "changed on both sides that cannot be merged is reported for mirrors conflicts")
596
+ .argument("[id]", `${ID}; every mirror of the profile when omitted`)
597
+ .option("--every <duration>", `how often to ask ${service} whether anything changed`, helpers.every ?? "60s")
598
+ .action(async function (id, args) {
599
+ const pollMs = parseDuration(args.every, "--every");
600
+ if (pollMs < 10_000)
601
+ throw new CliError("validation_error", "--every must be at least 10s", { param: "--every" });
602
+ const chosen = homeOf(this).chosen(id);
603
+ const environment = environmentOf(this);
604
+ const { format, streams } = outputFor(this);
605
+ // cli-core bounds a persistent command by nothing, so its --timeout is the watch's own to keep.
606
+ const timeout = this.optsWithGlobals().timeout;
607
+ const signal = AbortSignal.any([
608
+ environment.untilStopped?.(),
609
+ timeout === undefined ? undefined : AbortSignal.timeout(parseDuration(timeout, "--timeout")),
610
+ ].filter((one) => one !== undefined));
611
+ const print = (text) => streams.data(`${text}\n`);
612
+ let cycles = 0;
613
+ await helpers.connect(this, async (remote) => {
614
+ const engine = engineOf(this, remote.target, chosen);
615
+ const local = async (mirrors) => (await fileMirrorStatus(mirrors, engine.stateOf))
616
+ .filter((item) => item.upload.length || item.delete.length)
617
+ .map((item) => item.id);
618
+ for await (const event of watchMirrors((mirrors) => syncFileMirrors({ ...engine, mirrors }), {
619
+ mirrors: chosen,
620
+ signal,
621
+ localChanges: local,
622
+ remoteChanges: fileRemoteChanges(engine.target),
623
+ pollMs,
624
+ })) {
625
+ cycles++;
626
+ const data = {
627
+ at: new Date().toISOString(),
628
+ triggers: event.triggers,
629
+ mirrors: event.mirrors,
630
+ ...("error" in event
631
+ ? { error: { code: event.error.code, message: event.error.message } }
632
+ : {
633
+ results: event.result.items,
634
+ ...(event.result.issues.length ? { issues: event.result.issues } : {}),
635
+ }),
636
+ };
637
+ print(format === "pretty" ? describeCycle(data) : JSON.stringify({ type: "item", data: snakeKeys(data) }));
638
+ }
639
+ }, { unbounded: true });
640
+ if (format === "pretty")
641
+ return;
642
+ const end = listOf("mirrors watch", {
643
+ items: [],
644
+ limit: Math.max(1, cycles),
645
+ has_more: false,
646
+ paging: "cursor",
647
+ meta: { complete: true },
648
+ });
649
+ for (const record of jsonlRecords(end))
650
+ print(JSON.stringify(record));
651
+ });
652
+ const versionsCommand = () => annotate(new Command("versions"), { effects: LOCAL_READ, mcp: false })
653
+ .summary("versions of mirrored files that syncs replaced or deleted")
654
+ .description("the versions of a mirrored file that syncs replaced or deleted, kept on this computer")
655
+ .addCommand(annotate(new Command("list"), {
656
+ effects: LOCAL_READ,
657
+ examples: [`${CLI} personal mirrors versions list 1a2b3c4d notes/plan.md --json`],
658
+ })
659
+ .summary("list what syncs did to a mirrored file, oldest first")
660
+ .description("list what syncs did to a mirrored file, oldest first, and which versions are still kept")
661
+ .argument("<id>", ID)
662
+ .argument("<path>", PATH)
663
+ .action(function (id, input) {
664
+ const home = homeOf(this);
665
+ const mirror = home.find(id);
666
+ const path = insideOf(mirror.path, input);
667
+ output(this, allOf("mirrors versions list", home
668
+ .versionsOf(mirror)
669
+ .list(path)
670
+ .map((one) => snakeKeys(one))));
671
+ }))
672
+ .addCommand(annotate(new Command("restore"), {
673
+ effects: LOCAL_WRITE,
674
+ examples: [`${CLI} personal mirrors versions restore 1a2b3c4d notes/plan.md 9f86d081…`],
675
+ })
676
+ .summary("put a kept version back into the local folder")
677
+ .description("put a kept version back into the local folder; the file there now is kept first, and the next mirrors " +
678
+ `sync sends the restored one to ${service}`)
679
+ .argument("<id>", ID)
680
+ .argument("<path>", PATH)
681
+ .argument("<sha256>", "the version's hash, old or new in mirrors versions list")
682
+ .action(async function (id, input, sha256) {
683
+ const home = homeOf(this);
684
+ const mirror = home.find(id);
685
+ const path = insideOf(mirror.path, input);
686
+ if (!(await restoreFileVersion(mirror.path, path, sha256, home.versionsOf(mirror), home.lock)))
687
+ throw new CliError("not_found", "that version is no longer kept, or the file changed while it was restored; see mirrors versions list");
688
+ output(this, itemOf({ id, path, sha256, restored: true }));
689
+ }));
690
+ /** `mirrors conflicts list|show|resolve` over this profile's mirrors; a resolve writes as a sync does. */
691
+ const conflictsCommand = () => fileConflictsCommand({
692
+ identity,
693
+ remote: REMOTE,
694
+ output,
695
+ mirrors: (command, id) => homeOf(command).chosen(id),
696
+ pathOf: (mirror, input) => insideOf(mirror.path, input),
697
+ stateOf: (command, mirror) => homeOf(command).stateOf(mirror),
698
+ versionsOf: (command, mirror) => homeOf(command).versionsOf(mirror),
699
+ connect: (command, mirror, body) => helpers.connect(command, (remote) => {
700
+ const { target, principal, guard, operationId, lock, signal } = engineOf(command, remote.target, [
701
+ mirror,
702
+ ]);
703
+ return body({ target, principal, guard, operationId, lock, ...(signal ? { signal } : {}) });
704
+ }),
705
+ });
706
+ return annotate(new Command("mirrors"), { effects: LOCAL_READ })
707
+ .description(`keep local folders and ${helpers.root.place}s the same, both ways, file by file`)
708
+ .addCommand(addCommand())
709
+ .addCommand(listCommand())
710
+ .addCommand(statusCommand())
711
+ .addCommand(previewCommand())
712
+ .addCommand(syncCommand())
713
+ .addCommand(watchCommand())
714
+ .addCommand(updateCommand())
715
+ .addCommand(removeCommand())
716
+ .addCommand(versionsCommand())
717
+ .addCommand(conflictsCommand());
718
+ };