@wirecat/cli-core 0.726.0 → 0.728.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/dist/cli/documents/index.d.ts +1 -1
- package/dist/cli/documents/index.js +1 -1
- package/dist/cli/documents/library.d.ts +44 -2
- package/dist/cli/documents/library.js +62 -12
- package/dist/cli/documents/sync.d.ts +26 -0
- package/dist/cli/documents/sync.js +67 -53
- package/dist/documents/file-mirror-model.d.ts +16 -4
- package/dist/domain/providers.d.ts +7 -2
- package/dist/domain/providers.js +13 -5
- package/dist/errors/reasons.js +5 -0
- package/dist/search/account-list.js +9 -5
- package/dist/services/files/conflicts.js +24 -10
- package/dist/services/files/mirror.d.ts +2 -0
- package/dist/services/files/mirror.js +44 -9
- package/dist/services/files/versions.d.ts +5 -4
- package/dist/services/files/versions.js +10 -7
- package/dist/services/search-all.js +12 -2
- package/dist/services/search-kind.js +6 -5
- package/dist/store/sqlite/ref-accounts.js +10 -6
- package/dist/tracker/cli/index.d.ts +6 -0
- package/dist/tracker/cli/index.js +185 -49
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,54 @@ 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.728.0 — 23.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **One `sync` for a tracker that holds documents too.** `documentLibrary(options)` answers the shared documents
|
|
13
|
+
commands without their `sync`, and that sync as a step; `addTrackerCommands({ documents: library.sync })` then mounts
|
|
14
|
+
one `sync` that brings the issues and the documents, so linear-cli can mount both and the owner and Desktop keep one
|
|
15
|
+
`<cli> sync`. The answer is the tracker's report with the documents' answer under `documents`; a part that fails is
|
|
16
|
+
named there and in `meta.issues` and the other's answer still shows. `--rescan` lists both again, `--max-pages`
|
|
17
|
+
bounds each part, `--embed` indexes the documents' text, and `--limit` is refused with the reason. A tracker CLI
|
|
18
|
+
without `documents` keeps its `sync` unchanged ([TRACKER.md](docs/dev/TRACKER.md#one-sync-with-documents)).
|
|
19
|
+
|
|
20
|
+
### Changed — may break callers
|
|
21
|
+
|
|
22
|
+
- **`linear` holds documents beside its tracker copy.** Its registry entry is `kind: "tracker"`,
|
|
23
|
+
`kinds: ["tracker", "documents"]`, and a provider that holds `documents` among its kinds is a documents account
|
|
24
|
+
provider, as Drive is: `documentAccountProviders()` and `isDocumentAccountProvider` now answer `linear` too.
|
|
25
|
+
`search all` reads a Linear account once in the tracker lane, under its own key, and once in the notes lane, as
|
|
26
|
+
`notes:<id>`, also when `--source` names `linear` or `linear:<account>`. A group naming `linear:<account>` holds
|
|
27
|
+
its documents too, so a locked run shows and opens them; one naming only `notes:<id>` holds no issues.
|
|
28
|
+
- **The combined `sync` skips the documents while no folder is chosen.** With no folder and no kept documents it asks
|
|
29
|
+
the provider nothing and writes no documents state, answering `documents: { skipped: "no folders chosen" }`.
|
|
30
|
+
- **A failed document is a partial answer that exits 0 in the combined `sync`.** It is named in `meta.issues` with
|
|
31
|
+
`source` `documents`, beside the tracker's report; notion-cli's and drive-cli's documents-only `sync` still exits
|
|
32
|
+
non-zero there.
|
|
33
|
+
|
|
34
|
+
## 0.727.0 — 23.11.2026
|
|
35
|
+
|
|
36
|
+
### Added
|
|
37
|
+
|
|
38
|
+
- **A file mirror works with a remote that rewrites the text it is sent.** A `FileTarget` with `rewrites: true` (Notion,
|
|
39
|
+
which keeps a page as blocks and gives back its own Markdown) no longer turns every upload into a conflict. When an
|
|
40
|
+
upload reads back with other bytes, the mirror keeps the local file's version, writes the remote's form into the
|
|
41
|
+
local file while it is unchanged, and logs it. Both sides then hold the same bytes, so the next sync compares and
|
|
42
|
+
merges against one base. `mirrors conflicts resolve` does the same with the final content. The result lists such
|
|
43
|
+
files in `rewritten` ([DOCUMENTS.md](docs/dev/DOCUMENTS.md)). Without `rewrites`, nothing changes (#3232).
|
|
44
|
+
|
|
45
|
+
### Changed — may break callers
|
|
46
|
+
|
|
47
|
+
- **A file mirror keeps earlier versions for 365 days, not 30.** `fileVersions(dir, now, keepForDays)` takes the
|
|
48
|
+
period, so a CLI passes the profile's `keep_versions_for_days` (`keepVersionsForDays(settings)`), as documents
|
|
49
|
+
history does. Without it the default is 365 days, the owner's rule for every sync. A mirror's version store grows
|
|
50
|
+
for longer: yandex-disk-cli users keep a year of replaced files unless they set a shorter period.
|
|
51
|
+
- **`FileTarget.exists` answers false only for a real deletion.** A provider that cannot tell a deletion from lost
|
|
52
|
+
access throws instead, and the file is left alone as unknown. yandex-disk-cli's target already answers that way.
|
|
53
|
+
It also gets the file's id from the last sync, so a provider that keeps ids across a move can tell a file moved out
|
|
54
|
+
of the folder from a deleted one.
|
|
55
|
+
|
|
8
56
|
## 0.726.0 — 23.11.2026
|
|
9
57
|
|
|
10
58
|
### Added
|
|
@@ -41,6 +41,6 @@ export interface DocumentCommands<S> {
|
|
|
41
41
|
* `search`, `catalog`, the knowledge groups and, when given, `mirrors`, in that order. Answers the `documents` group, for the CLI's live subcommands.
|
|
42
42
|
*/
|
|
43
43
|
export declare const addDocumentCommands: <S>(program: Command, options: DocumentCommands<S>) => Command;
|
|
44
|
-
export { claimDocumentAccount, type DocumentLibraryOptions, type DocumentLibraryTools, type DocumentSourceRun, type DocumentWarning, documentLibraryCommands, documentProfile, } from "./library.js";
|
|
44
|
+
export { claimDocumentAccount, type DocumentLibraryOptions, type DocumentLibraryTools, type DocumentSourceRun, type DocumentSyncOutcome, type DocumentSyncStep, type DocumentWarning, documentLibrary, documentLibraryCommands, documentProfile, } from "./library.js";
|
|
45
45
|
export { type DocumentCall, type DocumentFileMap, type DocumentManifest, parseDocumentManifest, } from "./manifest/manifest.js";
|
|
46
46
|
export { type DocumentManifestSourceOptions, type DocumentManifestTools, type DocumentSlots, documentSourceFromManifest, type ManifestDocumentSource, } from "./manifest/source.js";
|
|
@@ -37,6 +37,6 @@ export const addDocumentCommands = (program, options) => {
|
|
|
37
37
|
addDocumentMirrorCommands(program, { ...shared, ...options.mirrors });
|
|
38
38
|
return documents;
|
|
39
39
|
};
|
|
40
|
-
export { claimDocumentAccount, documentLibraryCommands, documentProfile, } from "./library.js";
|
|
40
|
+
export { claimDocumentAccount, documentLibrary, documentLibraryCommands, documentProfile, } from "./library.js";
|
|
41
41
|
export { parseDocumentManifest, } from "./manifest/manifest.js";
|
|
42
42
|
export { documentSourceFromManifest, } from "./manifest/source.js";
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type ErrorCode } from "@wirecat/cli-base";
|
|
2
|
+
import type { NextStep } from "@wirecat/cli-base/standards";
|
|
2
3
|
import { Command } from "commander";
|
|
3
|
-
import type { Deadline } from "../../background/budget.js";
|
|
4
|
+
import type { Deadline, RunBudget } from "../../background/budget.js";
|
|
4
5
|
import { type documentIngestion, type FeedlessDocumentSource, type SourceContent, type SourceFile, type SourceStatePort } from "../../documents.js";
|
|
5
6
|
import type { ProviderEntry } from "../../domain/providers.js";
|
|
6
7
|
import type { AppIdentity } from "../../ports/app.js";
|
|
@@ -10,7 +11,8 @@ import { baseContext } from "../context.js";
|
|
|
10
11
|
import { type Body } from "../envelope.js";
|
|
11
12
|
import { ProfileTokenStore } from "../profile-token.js";
|
|
12
13
|
import type { DocumentKnowledgePort } from "./knowledge.js";
|
|
13
|
-
import type
|
|
14
|
+
import { type DocumentSyncAnswer } from "./sync.js";
|
|
15
|
+
import { type DocumentWords } from "./words.js";
|
|
14
16
|
type Resolve = Parameters<typeof baseContext>[1];
|
|
15
17
|
type Ingestion<M extends SourceFile> = ReturnType<typeof documentIngestion<M>>;
|
|
16
18
|
/** Something a source met on its way and went on past: one per file, gathered into the answer's issues. */
|
|
@@ -102,6 +104,46 @@ export declare const documentProfile: <M extends SourceFile>(app: AppIdentity, e
|
|
|
102
104
|
* it was synced from.
|
|
103
105
|
*/
|
|
104
106
|
export declare const claimDocumentAccount: (app: AppIdentity, env: NodeJS.ProcessEnv, profile: string, account: string, tokens: Pick<ProfileTokenStore, "read">) => void;
|
|
107
|
+
/** The documents half of a `sync` another group mounts, as the shared `sync` would have answered it. */
|
|
108
|
+
export interface DocumentSyncOutcome {
|
|
109
|
+
/** The shared `sync`'s answer, its warnings included; `skipped` when the profile has nothing to sync. */
|
|
110
|
+
item: (DocumentSyncAnswer & {
|
|
111
|
+
warnings: unknown[];
|
|
112
|
+
}) | {
|
|
113
|
+
skipped: string;
|
|
114
|
+
};
|
|
115
|
+
meta: {
|
|
116
|
+
complete?: false;
|
|
117
|
+
issues?: {
|
|
118
|
+
code: ErrorCode;
|
|
119
|
+
reason: string;
|
|
120
|
+
source: string;
|
|
121
|
+
}[];
|
|
122
|
+
};
|
|
123
|
+
next: NextStep[];
|
|
124
|
+
diagnostics: string[];
|
|
125
|
+
}
|
|
126
|
+
/** Runs the documents sync inside the command another group mounted as `sync`. */
|
|
127
|
+
export type DocumentSyncStep = (command: Command, args: {
|
|
128
|
+
rescan?: boolean;
|
|
129
|
+
embed?: boolean;
|
|
130
|
+
budget: RunBudget;
|
|
131
|
+
deadline?: Deadline;
|
|
132
|
+
/** The account the other group's part synced; the documents of another account of it are refused. */
|
|
133
|
+
account?: {
|
|
134
|
+
provider: string;
|
|
135
|
+
account: string;
|
|
136
|
+
};
|
|
137
|
+
}) => Promise<DocumentSyncOutcome>;
|
|
138
|
+
/**
|
|
139
|
+
* `documentLibraryCommands` without its `sync`, and that sync as a step, for a CLI whose own `sync` brings the
|
|
140
|
+
* documents too: linear-cli's tracker `sync` (`addTrackerCommands({ documents })`), so the owner and Desktop keep one
|
|
141
|
+
* `<cli> sync`.
|
|
142
|
+
*/
|
|
143
|
+
export declare const documentLibrary: <M extends SourceFile>(options: DocumentLibraryOptions<M>) => {
|
|
144
|
+
commands: Command[];
|
|
145
|
+
sync: DocumentSyncStep;
|
|
146
|
+
};
|
|
105
147
|
/**
|
|
106
148
|
* cli-core's shared `folders`, `sync`, `status`, `documents`, `search`, `catalog` and knowledge groups over a CLI's
|
|
107
149
|
* document source, its files under the CLI's state folder and the shared store. The CLI gives the source, how it
|
|
@@ -26,7 +26,8 @@ import { addDocumentHistoryCommands, keepVersionsForDays } from "./history.js";
|
|
|
26
26
|
import { addDocumentKnowledgeCommands } from "./knowledge.js";
|
|
27
27
|
import { factItem, memoryItem } from "./queries.js";
|
|
28
28
|
import { addDocumentSearchCommand } from "./search.js";
|
|
29
|
-
import { addDocumentSyncCommands } from "./sync.js";
|
|
29
|
+
import { addDocumentSyncCommands, DOCUMENT_SYNC_LIMIT, documentSyncPart, } from "./sync.js";
|
|
30
|
+
import { wordsOf } from "./words.js";
|
|
30
31
|
const readJson = (path) => {
|
|
31
32
|
try {
|
|
32
33
|
return JSON.parse(readFileSync(path, "utf8"));
|
|
@@ -136,17 +137,21 @@ export const claimDocumentAccount = (app, env, profile, account, tokens) => {
|
|
|
136
137
|
};
|
|
137
138
|
const DOCUMENT_REF = /^document:[1-9]\d*$/u;
|
|
138
139
|
/**
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
*
|
|
140
|
+
* `documentLibraryCommands` without its `sync`, and that sync as a step, for a CLI whose own `sync` brings the
|
|
141
|
+
* documents too: linear-cli's tracker `sync` (`addTrackerCommands({ documents })`), so the owner and Desktop keep one
|
|
142
|
+
* `<cli> sync`.
|
|
142
143
|
*/
|
|
143
|
-
export const
|
|
144
|
+
export const documentLibrary = (options) => libraryOf(options, false);
|
|
145
|
+
const libraryOf = (options, withSync) => {
|
|
144
146
|
const { app } = options;
|
|
145
147
|
const holder = new Command(app.command);
|
|
146
148
|
// The shared helpers take no command, so each run's command is caught as it starts; an MCP server builds the tree
|
|
147
149
|
// anew for every call.
|
|
148
150
|
let running;
|
|
149
151
|
let warnings = [];
|
|
152
|
+
// Set while another group's `sync` runs the documents step: a named run leaves the answer's run_id to that sync.
|
|
153
|
+
let sideRun;
|
|
154
|
+
let expected;
|
|
150
155
|
const command = () => {
|
|
151
156
|
if (!running)
|
|
152
157
|
throw new CliError("configuration_error", "a shared documents port ran outside a command");
|
|
@@ -189,15 +194,18 @@ export const documentLibraryCommands = (options) => {
|
|
|
189
194
|
};
|
|
190
195
|
const locked = (write, fn) => write ? files().locked(fn) : fn(() => undefined);
|
|
191
196
|
const writes = () => metaOf(command()).effects?.local === "write";
|
|
192
|
-
const
|
|
197
|
+
const warningIssues = () => {
|
|
193
198
|
const seen = new Set();
|
|
194
|
-
|
|
199
|
+
return warnings.flatMap((warning) => {
|
|
195
200
|
const key = `${warning.code}:${warning.reason}`;
|
|
196
201
|
if (seen.has(key))
|
|
197
202
|
return [];
|
|
198
203
|
seen.add(key);
|
|
199
204
|
return [{ code: warning.code, reason: warning.reason, source: options.provider.name }];
|
|
200
205
|
});
|
|
206
|
+
};
|
|
207
|
+
const output = (body) => {
|
|
208
|
+
const issues = warningIssues();
|
|
201
209
|
renderAnswer(command(), outputFor(command()), {
|
|
202
210
|
...body,
|
|
203
211
|
...(issues.length ? { meta: { ...body.meta, issues: [...(body.meta?.issues ?? []), ...issues] } } : {}),
|
|
@@ -221,7 +229,7 @@ export const documentLibraryCommands = (options) => {
|
|
|
221
229
|
};
|
|
222
230
|
const withSource = (body, deadline) => {
|
|
223
231
|
refuseOffline(command(), options.service);
|
|
224
|
-
return context().run((events) => body(known(options.source(command(), events, { warn: (one) => warnings.push(one), ...(deadline ? { deadline } : {}) }))));
|
|
232
|
+
return context().run((events) => body(known(options.source(command(), events, { warn: (one) => warnings.push(one), ...(deadline ? { deadline } : {}) }))), sideRun === undefined ? {} : { name: sideRun });
|
|
225
233
|
};
|
|
226
234
|
const errorOf = (error) => isCliError(error)
|
|
227
235
|
? error
|
|
@@ -328,6 +336,9 @@ export const documentLibraryCommands = (options) => {
|
|
|
328
336
|
const chosen = roots();
|
|
329
337
|
const synced = await withSource(async (source) => {
|
|
330
338
|
const live = await source.identity();
|
|
339
|
+
if (expected !== undefined && live !== expected)
|
|
340
|
+
throw new CliError("configuration_error", `the documents are signed in as ${options.service} account ${live}, not ${expected}, the account the ` +
|
|
341
|
+
`rest of this sync read; sign in again with one account (\`${app.command} ${name} session start\`)`, { reason: "documents.other-account" });
|
|
331
342
|
claimDocumentAccount(app, env(), name, live, tokens());
|
|
332
343
|
return files().locked((assertHeld) => withStore(true, async (store) => {
|
|
333
344
|
const result = await syncDocuments({
|
|
@@ -528,10 +539,49 @@ export const documentLibraryCommands = (options) => {
|
|
|
528
539
|
writesOwnerFiles(find(folders, "add"));
|
|
529
540
|
if (options.browse)
|
|
530
541
|
annotate(find(folders, "browse"), { partial: true });
|
|
542
|
+
const start = (action, side, account) => {
|
|
543
|
+
running = action;
|
|
544
|
+
warnings = [];
|
|
545
|
+
sideRun = side;
|
|
546
|
+
expected = account;
|
|
547
|
+
};
|
|
531
548
|
for (const group of holder.commands)
|
|
532
|
-
group.hook("preAction", (_group, action) =>
|
|
533
|
-
|
|
534
|
-
|
|
549
|
+
group.hook("preAction", (_group, action) => start(action));
|
|
550
|
+
const sync = async (action, { rescan, embed, budget, deadline, account }) => {
|
|
551
|
+
start(action, `${environmentOf(action).agent ? "mcp " : ""}sync documents`, account?.provider === options.provider.name ? account.account : undefined);
|
|
552
|
+
const held = files().state("").read();
|
|
553
|
+
// With no folder chosen and nothing kept, a sync would only ask who is signed in; a held copy still runs, so the
|
|
554
|
+
// documents of folders removed since leave it.
|
|
555
|
+
if (!roots().length && !Object.keys(held.documents).length && !held.pending && !files().walkUnderWay())
|
|
556
|
+
return { item: { skipped: "no folders chosen" }, meta: {}, next: [], diagnostics: [] };
|
|
557
|
+
const item = await groups.sync.sync({
|
|
558
|
+
limit: DOCUMENT_SYNC_LIMIT,
|
|
559
|
+
budget,
|
|
560
|
+
...(rescan ? { rescan } : {}),
|
|
561
|
+
...(embed ? { embed } : {}),
|
|
562
|
+
...(deadline ? { deadline } : {}),
|
|
563
|
+
});
|
|
564
|
+
const timeout = action.optsWithGlobals().timeout;
|
|
565
|
+
const part = documentSyncPart(item, {
|
|
566
|
+
again: `${app.command} ${profile()} sync`,
|
|
567
|
+
source: wordsOf(options.words).source,
|
|
568
|
+
resume: { ...(timeout === undefined ? {} : { timeout }), ...(embed ? { embed: true } : {}) },
|
|
569
|
+
longer: {},
|
|
535
570
|
});
|
|
536
|
-
|
|
571
|
+
// The other group's answer names its parts by what they sync, as `tracker` and `documents`.
|
|
572
|
+
const issues = [...(part.meta.issues ?? []), ...warningIssues()].map((one) => ({ ...one, source: "documents" }));
|
|
573
|
+
return {
|
|
574
|
+
item: item,
|
|
575
|
+
meta: { ...part.meta, ...(issues.length ? { complete: false, issues } : {}) },
|
|
576
|
+
next: part.next,
|
|
577
|
+
diagnostics: part.diagnostics,
|
|
578
|
+
};
|
|
579
|
+
};
|
|
580
|
+
return { commands: holder.commands.filter((one) => withSync || one.name() !== "sync"), sync };
|
|
537
581
|
};
|
|
582
|
+
/**
|
|
583
|
+
* cli-core's shared `folders`, `sync`, `status`, `documents`, `search`, `catalog` and knowledge groups over a CLI's
|
|
584
|
+
* document source, its files under the CLI's state folder and the shared store. The CLI gives the source, how it
|
|
585
|
+
* files a document and its words. Returned as commands to add to the program.
|
|
586
|
+
*/
|
|
587
|
+
export const documentLibraryCommands = (options) => libraryOf(options, true).commands;
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import type { NextStep } from "@wirecat/cli-base/standards";
|
|
1
2
|
import type { Command } from "commander";
|
|
2
3
|
import type { Deadline, RunBudget } from "../../background/budget.js";
|
|
3
4
|
import { type Body } from "../envelope.js";
|
|
4
5
|
import { type DocumentWords } from "./words.js";
|
|
6
|
+
/** The documents one sync reads when `--limit` does not say. */
|
|
7
|
+
export declare const DOCUMENT_SYNC_LIMIT = 200;
|
|
5
8
|
export interface DocumentSyncArgs {
|
|
6
9
|
limit: number;
|
|
7
10
|
rescan?: boolean;
|
|
@@ -45,5 +48,28 @@ export interface DocumentSyncCommands {
|
|
|
45
48
|
/** What `status` answers: the last sync, imported documents and pending work, from local files only. */
|
|
46
49
|
status(): object | Promise<object>;
|
|
47
50
|
}
|
|
51
|
+
/** What a documents sync's answer tells its caller: its meta, the steps to go on and the lines for the person. */
|
|
52
|
+
export interface DocumentSyncPart {
|
|
53
|
+
meta: {
|
|
54
|
+
complete?: false;
|
|
55
|
+
issues?: {
|
|
56
|
+
code: "provider_error";
|
|
57
|
+
reason: "sync.partial";
|
|
58
|
+
source: string;
|
|
59
|
+
}[];
|
|
60
|
+
};
|
|
61
|
+
next: NextStep[];
|
|
62
|
+
diagnostics: string[];
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* `resume` and `longer` are the arguments of the same sync again and of a longer one, beside the ones each adds:
|
|
66
|
+
* a CLI whose `sync` takes other options than the shared one names its own.
|
|
67
|
+
*/
|
|
68
|
+
export declare const documentSyncPart: (result: DocumentSyncAnswer, words: {
|
|
69
|
+
again: string;
|
|
70
|
+
source: string;
|
|
71
|
+
resume: Record<string, unknown>;
|
|
72
|
+
longer: Record<string, unknown>;
|
|
73
|
+
}) => DocumentSyncPart;
|
|
48
74
|
/** `sync` into the shared store and `status` of the local copy, for the selected profile. */
|
|
49
75
|
export declare const addDocumentSyncCommands: (program: Command, helpers: DocumentSyncCommands) => Command[];
|
|
@@ -5,6 +5,8 @@ import { honoursDryRun } from "../dry-run-guard.js";
|
|
|
5
5
|
import { FETCH, LOCAL_READ } from "../effects.js";
|
|
6
6
|
import { itemOf } from "../envelope.js";
|
|
7
7
|
import { examples, positive, wordsOf } from "./words.js";
|
|
8
|
+
/** The documents one sync reads when `--limit` does not say. */
|
|
9
|
+
export const DOCUMENT_SYNC_LIMIT = 200;
|
|
8
10
|
/** `embedNotes`' answer says enrichment never had the time to send a batch. */
|
|
9
11
|
const enrichmentOutOfTime = (embeddings) => {
|
|
10
12
|
const enrichment = typeof embeddings === "object" && embeddings !== null && "enrichment" in embeddings
|
|
@@ -12,6 +14,57 @@ const enrichmentOutOfTime = (embeddings) => {
|
|
|
12
14
|
: undefined;
|
|
13
15
|
return enrichment?.reason_id === "enrichment.deadline" && enrichment.enriched === 0;
|
|
14
16
|
};
|
|
17
|
+
/**
|
|
18
|
+
* `resume` and `longer` are the arguments of the same sync again and of a longer one, beside the ones each adds:
|
|
19
|
+
* a CLI whose `sync` takes other options than the shared one names its own.
|
|
20
|
+
*/
|
|
21
|
+
export const documentSyncPart = (result, words) => {
|
|
22
|
+
const unfinished = result.complete === false || result.pending > 0;
|
|
23
|
+
const moved = (result.walk?.listed ?? 0) > 0 ||
|
|
24
|
+
[result.saved, result.names_only, result.removed, result.unchanged].some((count) => (count ?? 0) > 0);
|
|
25
|
+
// The same sync again, never --rescan, which would start the pass over; a run that moved nothing gets no step.
|
|
26
|
+
const resume = unfinished && !result.errors.length && moved
|
|
27
|
+
? [
|
|
28
|
+
{
|
|
29
|
+
kind: "command",
|
|
30
|
+
step: "sync.run",
|
|
31
|
+
command: "sync",
|
|
32
|
+
args: words.resume,
|
|
33
|
+
why: "the sync stopped before the end of its pass; running it again goes on from there",
|
|
34
|
+
safe_to_auto_execute: true,
|
|
35
|
+
},
|
|
36
|
+
]
|
|
37
|
+
: [];
|
|
38
|
+
// Enrichment starts a batch only when it ends before the deadline; one that never had the time would not move in
|
|
39
|
+
// a run like this one either, so the step asks for a longer run and is not run unasked.
|
|
40
|
+
const longer = enrichmentOutOfTime(result.embeddings)
|
|
41
|
+
? [
|
|
42
|
+
{
|
|
43
|
+
kind: "command",
|
|
44
|
+
step: "sync.longer",
|
|
45
|
+
command: "sync",
|
|
46
|
+
args: { ...words.longer, embed: true, timeout: "15m" },
|
|
47
|
+
why: "enrichment needs more time than this run had left, so it sent nothing; run this in a terminal, " +
|
|
48
|
+
"where a sync may take 15 minutes",
|
|
49
|
+
safe_to_auto_execute: false,
|
|
50
|
+
},
|
|
51
|
+
]
|
|
52
|
+
: [];
|
|
53
|
+
const diagnostics = result.walk
|
|
54
|
+
? [`${result.walk.folders_left} folders remain to list; run ${words.again} again\n`]
|
|
55
|
+
: result.errors.length || result.pending
|
|
56
|
+
? [`${result.pending} source operations remain; run ${words.again} again\n`]
|
|
57
|
+
: [];
|
|
58
|
+
return {
|
|
59
|
+
meta: result.errors.length
|
|
60
|
+
? { complete: false, issues: [{ code: "provider_error", reason: "sync.partial", source: words.source }] }
|
|
61
|
+
: unfinished
|
|
62
|
+
? { complete: false }
|
|
63
|
+
: {},
|
|
64
|
+
next: [...resume, ...longer],
|
|
65
|
+
diagnostics,
|
|
66
|
+
};
|
|
67
|
+
};
|
|
15
68
|
const addDocumentSyncCommandsDefinition = (program, helpers) => {
|
|
16
69
|
const { output } = helpers;
|
|
17
70
|
const wording = wordsOf(helpers.words);
|
|
@@ -24,66 +77,27 @@ const addDocumentSyncCommandsDefinition = (program, helpers) => {
|
|
|
24
77
|
.description("import what changed in the chosen folders, and finish an unfinished sync; " +
|
|
25
78
|
`one sync walks about ${helpers.maxEntries} entries under the chosen folders, saves where it stopped, and ` +
|
|
26
79
|
"the next sync goes on from there"), [`${prefix} sync`, `${prefix} sync --rescan --limit 500`])
|
|
27
|
-
.option("--limit <n>", text.syncLimit, positive,
|
|
80
|
+
.option("--limit <n>", text.syncLimit, positive, DOCUMENT_SYNC_LIMIT)
|
|
28
81
|
.option("--rescan", "read every chosen folder again instead of only what changed; each --rescan starts the walk over, so run it " +
|
|
29
82
|
"once and continue with a plain sync")
|
|
30
83
|
.option("--embed", "also index pending text for meaning search, with a model already downloaded")
|
|
31
84
|
.action(async (args, command) => {
|
|
32
85
|
const deadline = environmentOf(command).deadline?.();
|
|
33
86
|
const result = await helpers.sync({ ...args, budget: runBudgetOf(command), ...(deadline ? { deadline } : {}) });
|
|
34
|
-
const unfinished = result.complete === false || result.pending > 0;
|
|
35
|
-
const moved = (result.walk?.listed ?? 0) > 0 ||
|
|
36
|
-
[result.saved, result.names_only, result.removed, result.unchanged].some((count) => (count ?? 0) > 0);
|
|
37
|
-
const again = `${wording.app} ${helpers.profile()} sync`;
|
|
38
87
|
const timeout = command.optsWithGlobals().timeout;
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
safe_to_auto_execute: true,
|
|
53
|
-
},
|
|
54
|
-
]
|
|
55
|
-
: [];
|
|
56
|
-
// Enrichment starts a batch only when it ends before the deadline; one that never had the time would not move in
|
|
57
|
-
// a run like this one either, so the step asks for a longer run and is not run unasked.
|
|
58
|
-
const longer = enrichmentOutOfTime(result.embeddings)
|
|
59
|
-
? [
|
|
60
|
-
{
|
|
61
|
-
kind: "command",
|
|
62
|
-
step: "sync.longer",
|
|
63
|
-
command: "sync",
|
|
64
|
-
args: { limit: args.limit, embed: true, timeout: "15m" },
|
|
65
|
-
why: "enrichment needs more time than this run had left, so it sent nothing; run this in a terminal, " +
|
|
66
|
-
"where a sync may take 15 minutes",
|
|
67
|
-
safe_to_auto_execute: false,
|
|
68
|
-
},
|
|
69
|
-
]
|
|
70
|
-
: [];
|
|
71
|
-
const next = [...resume, ...longer];
|
|
72
|
-
output(itemOf(result, {
|
|
73
|
-
meta: result.errors.length
|
|
74
|
-
? {
|
|
75
|
-
complete: false,
|
|
76
|
-
issues: [{ code: "provider_error", reason: "sync.partial", source: wording.source }],
|
|
77
|
-
}
|
|
78
|
-
: unfinished
|
|
79
|
-
? { complete: false }
|
|
80
|
-
: {},
|
|
81
|
-
next,
|
|
82
|
-
}));
|
|
83
|
-
if (result.walk)
|
|
84
|
-
helpers.diagnostic(`${result.walk.folders_left} folders remain to list; run ${again} again\n`);
|
|
85
|
-
else if (result.errors.length || result.pending)
|
|
86
|
-
helpers.diagnostic(`${result.pending} source operations remain; run ${again} again\n`);
|
|
88
|
+
const part = documentSyncPart(result, {
|
|
89
|
+
again: `${wording.app} ${helpers.profile()} sync`,
|
|
90
|
+
source: wording.source,
|
|
91
|
+
resume: {
|
|
92
|
+
limit: args.limit,
|
|
93
|
+
...(timeout === undefined ? {} : { timeout }),
|
|
94
|
+
...(args.embed ? { embed: true } : {}),
|
|
95
|
+
},
|
|
96
|
+
longer: { limit: args.limit },
|
|
97
|
+
});
|
|
98
|
+
output(itemOf(result, { meta: part.meta, next: part.next }));
|
|
99
|
+
for (const line of part.diagnostics)
|
|
100
|
+
helpers.diagnostic(line);
|
|
87
101
|
if (result.errors.length)
|
|
88
102
|
throw new CliError("provider_error", "sync completed partially; failed operations remain pending", {
|
|
89
103
|
reason: "sync.partial",
|
|
@@ -43,13 +43,19 @@ export interface FileTarget {
|
|
|
43
43
|
next?: string;
|
|
44
44
|
} | undefined>;
|
|
45
45
|
/**
|
|
46
|
-
* Whether anything is at `path` now, read directly rather than from a listing; false only when the provider says
|
|
47
|
-
*
|
|
46
|
+
* Whether anything is at `path` now, read directly rather than from a listing; false only when the provider says the
|
|
47
|
+
* file was deleted. A file missing from a listing is deleted only once this says so. An answer that cannot tell a
|
|
48
|
+
* deletion from lost access (a 404 that may mean "no longer shared") throws, and the file is left alone. `id` is
|
|
49
|
+
* the file's id at the last sync: a provider that keeps a file's id across a move asks by it, so a file moved out of
|
|
50
|
+
* the folder is still there, not deleted.
|
|
48
51
|
*/
|
|
49
|
-
exists(path: string, signal?: AbortSignal): Promise<boolean>;
|
|
52
|
+
exists(path: string, signal?: AbortSignal, id?: string): Promise<boolean>;
|
|
50
53
|
/** Streams the file into `into`, a new local file. */
|
|
51
54
|
download(path: string, into: string, signal?: AbortSignal): Promise<void>;
|
|
52
|
-
/**
|
|
55
|
+
/**
|
|
56
|
+
* Streams the local file `from` to `path` and returns the file as the remote now has it. With `rewrites`, its hash
|
|
57
|
+
* is of the remote's own form of the text, the bytes `download` gives.
|
|
58
|
+
*/
|
|
53
59
|
upload(path: string, from: string, expect: Expect, signal?: AbortSignal): Promise<RemoteFile>;
|
|
54
60
|
/** Moves the file to the remote's trash, where the owner can restore it. */
|
|
55
61
|
trash(path: string, expect: Exclude<Expect, {
|
|
@@ -57,6 +63,12 @@ export interface FileTarget {
|
|
|
57
63
|
}>, signal?: AbortSignal): Promise<void>;
|
|
58
64
|
/** Creates the folder and its parents; a folder that exists is fine. */
|
|
59
65
|
ensureFolder(path: string, signal?: AbortSignal): Promise<void>;
|
|
66
|
+
/**
|
|
67
|
+
* The remote keeps its own form of the text it is sent (Notion's Markdown), so an upload may read back with another
|
|
68
|
+
* hash. The mirror then writes that form into the local file, the earlier one kept, and both sides hold the same
|
|
69
|
+
* bytes again. Without it, such an upload is a conflict.
|
|
70
|
+
*/
|
|
71
|
+
rewrites?: boolean;
|
|
60
72
|
/** A value that moves with every change on the remote, when the provider has one: a watch reads it before listing. */
|
|
61
73
|
revision?(signal?: AbortSignal): Promise<string>;
|
|
62
74
|
}
|
|
@@ -46,8 +46,8 @@ export declare const folderProviderSql: (column?: string) => string;
|
|
|
46
46
|
export declare const folderProviderOf: (format: "obsidian" | "markdown") => "obsidian" | "local";
|
|
47
47
|
/**
|
|
48
48
|
* Providers whose account holds documents the way a notes folder does: one account per remote principal, its
|
|
49
|
-
* files as `documents` rows. Any registry entry
|
|
50
|
-
* keeps its documents beside its other records instead.
|
|
49
|
+
* files as `documents` rows. Any registry entry holding `documents` that a sync fills, as its first kind or beside
|
|
50
|
+
* another (Linear's tracker); an import-only one (`import`) keeps its documents beside its other records instead.
|
|
51
51
|
*/
|
|
52
52
|
export declare const documentAccountProviders: () => string[];
|
|
53
53
|
export declare const isDocumentAccountProvider: (provider: unknown) => boolean;
|
|
@@ -103,6 +103,11 @@ export declare const kindsIn: (provider: Provider) => readonly Kind[];
|
|
|
103
103
|
export declare const importedOf: (entry: ProviderEntry, held: ProviderEntry | undefined) => boolean;
|
|
104
104
|
/** Whether a provider's accounts hold only what imports wrote: the one place a records import writes messages and events. */
|
|
105
105
|
export declare const isImportedProvider: (provider: Provider) => boolean;
|
|
106
|
+
/**
|
|
107
|
+
* A documents account that holds another kind too, as Linear's holds a tracker's copy: listed and grouped under its
|
|
108
|
+
* own key for that kind, and as `notes:<id>` for its documents.
|
|
109
|
+
*/
|
|
110
|
+
export declare const alsoListedByKey: (provider: Provider) => boolean;
|
|
106
111
|
/** Whether a provider's accounts hold `kind`: what a search lane picks its accounts by. */
|
|
107
112
|
export declare const holdsKind: (provider: Provider, kind: Kind) => boolean;
|
|
108
113
|
/** `holdsKind`, with a provider no entry names counted as a messenger, as `kindOf` counts it. */
|
package/dist/domain/providers.js
CHANGED
|
@@ -22,8 +22,9 @@ export const PROVIDERS = [
|
|
|
22
22
|
// Google Meet has no tool of its own: its meetings are gcal's, since every meeting is on the calendar.
|
|
23
23
|
{ name: "google-meet", kind: "meetings", aliases: [], command: "gcal" },
|
|
24
24
|
{ name: "google-drive", kind: "documents", aliases: [] },
|
|
25
|
-
// Seeded: linear-cli registers no entry, and without one its accounts would count as a messenger's.
|
|
26
|
-
|
|
25
|
+
// Seeded: linear-cli registers no entry, and without one its accounts would count as a messenger's. One sign-in holds
|
|
26
|
+
// the issues and the documents, so the account is a tracker's and a documents account at once.
|
|
27
|
+
{ name: "linear", kind: "tracker", kinds: ["tracker", "documents"], aliases: [], command: "linear" },
|
|
27
28
|
// Its meetings come from the notes Telemost mails (`keeper@telemost.yandex.ru`), read by a mail rule.
|
|
28
29
|
{ name: "telemost", kind: "meetings", aliases: [] },
|
|
29
30
|
// A phone export's records: its SMS and its calls in the one account the import names.
|
|
@@ -60,10 +61,12 @@ export const folderProviderSql = (column = "provider") => `${column} IN (${FOLDE
|
|
|
60
61
|
export const folderProviderOf = (format) => format === "markdown" ? "local" : "obsidian";
|
|
61
62
|
/**
|
|
62
63
|
* Providers whose account holds documents the way a notes folder does: one account per remote principal, its
|
|
63
|
-
* files as `documents` rows. Any registry entry
|
|
64
|
-
* keeps its documents beside its other records instead.
|
|
64
|
+
* files as `documents` rows. Any registry entry holding `documents` that a sync fills, as its first kind or beside
|
|
65
|
+
* another (Linear's tracker); an import-only one (`import`) keeps its documents beside its other records instead.
|
|
65
66
|
*/
|
|
66
|
-
export const documentAccountProviders = () => registry
|
|
67
|
+
export const documentAccountProviders = () => registry
|
|
68
|
+
.filter((entry) => kindsOfEntry(entry).includes("documents") && entry.imported !== true)
|
|
69
|
+
.map(({ name }) => name);
|
|
67
70
|
export const isDocumentAccountProvider = (provider) => typeof provider === "string" && documentAccountProviders().includes(provider);
|
|
68
71
|
/** The documents account providers as a SQL list, for `IN (…)`; names are checked words, so they need no binding. */
|
|
69
72
|
export const documentAccountProvidersSql = () => documentAccountProviders()
|
|
@@ -235,6 +238,11 @@ export const importedOf = (entry, held) => {
|
|
|
235
238
|
};
|
|
236
239
|
/** Whether a provider's accounts hold only what imports wrote: the one place a records import writes messages and events. */
|
|
237
240
|
export const isImportedProvider = (provider) => registry.find(({ name }) => name === provider)?.imported === true;
|
|
241
|
+
/**
|
|
242
|
+
* A documents account that holds another kind too, as Linear's holds a tracker's copy: listed and grouped under its
|
|
243
|
+
* own key for that kind, and as `notes:<id>` for its documents.
|
|
244
|
+
*/
|
|
245
|
+
export const alsoListedByKey = (provider) => isDocumentAccountProvider(provider) && kindsIn(provider).some((kind) => kind !== "documents");
|
|
238
246
|
/** Whether a provider's accounts hold `kind`: what a search lane picks its accounts by. */
|
|
239
247
|
export const holdsKind = (provider, kind) => kindsIn(provider).includes(kind);
|
|
240
248
|
/** `holdsKind`, with a provider no entry names counted as a messenger, as `kindOf` counts it. */
|
package/dist/errors/reasons.js
CHANGED
|
@@ -240,6 +240,11 @@ const OTHERS = [
|
|
|
240
240
|
["profile.busy", "provider_unavailable", "another sync or write holds this profile's local copy"],
|
|
241
241
|
["profile.account-taken", "conflict", "another profile here already uses this provider account"],
|
|
242
242
|
["profile.other-account", "conflict", "this profile's copy was synced from another provider account"],
|
|
243
|
+
[
|
|
244
|
+
"documents.other-account",
|
|
245
|
+
"configuration_error",
|
|
246
|
+
"the documents are signed in as another account than the tracker copy of the same provider",
|
|
247
|
+
],
|
|
243
248
|
["profile.not-synced", "not_found", "the profile has no local copy yet; sync it first"],
|
|
244
249
|
["provider.failed", "provider_error", "a read from the provider failed"],
|
|
245
250
|
["identity.none", "not_found", "the provider shows no accounts on a document"],
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
-
import { ADDED_PROVIDER, INTERNAL_NOTES, isDocumentAccountProvider, isFolderProvider, isKind, kindIn, kindOf, kindsIn, providerNamed, providers as registered, UNKNOWN_PROVIDER, } from "../domain/providers.js";
|
|
2
|
+
import { ADDED_PROVIDER, alsoListedByKey, INTERNAL_NOTES, isDocumentAccountProvider, isFolderProvider, isKind, kindIn, kindOf, kindsIn, providerNamed, providers as registered, UNKNOWN_PROVIDER, } from "../domain/providers.js";
|
|
3
3
|
import { isBotProvider } from "./query.js";
|
|
4
4
|
/** Store-wide: every profile, tg, MAX and memo reads the same groups. */
|
|
5
5
|
export const ACCOUNT_GROUPS = "accountGroups";
|
|
@@ -30,13 +30,15 @@ const describe = (accounts) => accounts.map(({ provider, account, name }) => `${
|
|
|
30
30
|
export const listedHolds = (account, kind) => (account.kinds ?? (account.kind === undefined ? [] : [account.kind])).includes(kind);
|
|
31
31
|
/** The app running knows its own provider is a messenger, entry or not. */
|
|
32
32
|
const kindHere = (provider, running) => provider === running.provider ? kindOf(provider) : kindIn(provider);
|
|
33
|
+
// A documents account's documents are listed as `notes:<id>`, so its own key keeps only the other kinds it holds.
|
|
34
|
+
const listedKinds = (provider) => kindsIn(provider).filter((kind) => kind !== "documents" || !isDocumentAccountProvider(provider));
|
|
33
35
|
const kindsOfHere = (provider, running) => {
|
|
34
|
-
const kinds =
|
|
36
|
+
const kinds = listedKinds(provider);
|
|
35
37
|
return { kind: kindHere(provider, running), ...(kinds.length > 1 ? { kinds } : {}) };
|
|
36
38
|
};
|
|
37
39
|
const heldOf = (stored, running) => [
|
|
38
40
|
...stored
|
|
39
|
-
.filter(({ provider }) => kindIn(provider) !== "notes" && !isDocumentAccountProvider(provider))
|
|
41
|
+
.filter(({ provider }) => kindIn(provider) !== "notes" && (!isDocumentAccountProvider(provider) || alsoListedByKey(provider)))
|
|
40
42
|
.map(({ provider, account, name }) => ({ provider, account, name, ...kindsOfHere(provider, running) })),
|
|
41
43
|
{ provider: "notes", account: INTERNAL_NOTES, name: null, kind: "notes" },
|
|
42
44
|
...stored
|
|
@@ -80,7 +82,9 @@ const providerOf = (prefix, held, { running, profiles }) => {
|
|
|
80
82
|
const profilesOf = (provider, profiles) => Object.values(profiles).flatMap((named) => Object.entries(named).filter(([, key]) => key.provider === provider));
|
|
81
83
|
const accountOf = (prefix, ref, held, context) => {
|
|
82
84
|
const provider = providerOf(prefix, held, context);
|
|
83
|
-
if (isDocumentAccountProvider(provider) &&
|
|
85
|
+
if (isDocumentAccountProvider(provider) &&
|
|
86
|
+
!alsoListedByKey(provider) &&
|
|
87
|
+
!context.profiles[prefix.toLowerCase()]?.[ref]) {
|
|
84
88
|
const stored = storedAs(held, { provider, account: ref })[0];
|
|
85
89
|
if (stored)
|
|
86
90
|
return stored;
|
|
@@ -147,7 +151,7 @@ const accountsOfWord = (word, held, context) => {
|
|
|
147
151
|
return Object.keys(recorded).map((profile) => accountOf(word, profile, held, context));
|
|
148
152
|
const provider = providerOf(word, held, context);
|
|
149
153
|
if (isDocumentAccountProvider(provider) || isFolderProvider(provider))
|
|
150
|
-
return storedAs(held, { provider, account: "" });
|
|
154
|
+
return [...held.filter((one) => one.provider === provider), ...storedAs(held, { provider, account: "" })];
|
|
151
155
|
return held.filter((one) => one.provider === provider);
|
|
152
156
|
};
|
|
153
157
|
const isDocumentAccount = ({ stored }) => stored !== undefined && isDocumentAccountProvider(stored.provider);
|
|
@@ -106,25 +106,33 @@ export const resolveFileConflict = async (options) => {
|
|
|
106
106
|
if (parent !== ".")
|
|
107
107
|
await write("folder", "remote", parent, () => target.ensureFolder(remotePath(parent), signal));
|
|
108
108
|
const sent = await write("absent" in expect ? "create" : "update", "remote", at, () => target.upload(remotePath(at), from, expect, signal));
|
|
109
|
-
if (sent.sha256
|
|
109
|
+
if (sent.sha256 === undefined || sent.sha256 === hash)
|
|
110
|
+
return { sent, settled: hash };
|
|
111
|
+
if (!target.rewrites)
|
|
110
112
|
throw new CliError("conflict", "the file changed during the upload", { reason: "upload.mismatch" });
|
|
111
|
-
|
|
113
|
+
// The remote keeps its own form of the text: the local side takes that form, so both hold the same bytes.
|
|
114
|
+
const form = await versions.keep((temp) => target.download(remotePath(at), temp, signal));
|
|
115
|
+
if (form !== sent.sha256)
|
|
116
|
+
throw changed(`the ${options.remote} file`, "mirror.remote-changed");
|
|
117
|
+
return { sent, settled: form };
|
|
112
118
|
};
|
|
113
119
|
const expectRemote = found.remote
|
|
114
120
|
? { sha256: found.remote, ...(found.remoteFile?.md5 ? { md5: found.remoteFile.md5 } : {}) }
|
|
115
121
|
: { absent: true };
|
|
116
122
|
let sent = final === found.remote ? found.remoteFile : undefined;
|
|
123
|
+
/** What both sides hold once resolved: `final`, or the remote's own form of it. */
|
|
124
|
+
let settled = final;
|
|
117
125
|
if (final !== found.remote) {
|
|
118
126
|
if (final === undefined) {
|
|
119
127
|
await write("delete", "remote", path, () => target.trash(remotePath(path), expectRemote, signal));
|
|
120
128
|
}
|
|
121
129
|
else
|
|
122
|
-
sent = await send(path, "file" in choice ? choice.file : absolute, final, expectRemote);
|
|
130
|
+
({ sent, settled } = await send(path, "file" in choice ? choice.file : absolute, final, expectRemote));
|
|
123
131
|
}
|
|
124
|
-
if (
|
|
125
|
-
const placed =
|
|
132
|
+
if (settled !== found.local) {
|
|
133
|
+
const placed = settled === undefined
|
|
126
134
|
? await write("delete", "local", path, () => trashLocal(root, path, found.local, date))
|
|
127
|
-
: await write(found.local ? "update" : "create", "local", path, () => versions.write(
|
|
135
|
+
: await write(found.local ? "update" : "create", "local", path, () => versions.write(settled, absolute, found.local));
|
|
128
136
|
if (!placed)
|
|
129
137
|
throw changed("the local file", "mirror.local-changed");
|
|
130
138
|
}
|
|
@@ -143,16 +151,20 @@ export const resolveFileConflict = async (options) => {
|
|
|
143
151
|
syncedAt: new Date(now()).toISOString(),
|
|
144
152
|
};
|
|
145
153
|
};
|
|
146
|
-
if (
|
|
154
|
+
if (settled === undefined)
|
|
147
155
|
delete state.entries[path];
|
|
148
156
|
else if (sent)
|
|
149
|
-
await entry(path, sent,
|
|
157
|
+
await entry(path, sent, settled);
|
|
150
158
|
if (keep === "both" && found.local && found.remote) {
|
|
151
159
|
const name = copyName(path, options.remote, date, (at) => existsSync(join(root, at)) || at in state.entries);
|
|
152
160
|
await assertNoLink(root, name);
|
|
153
161
|
if (!(await write("create", "local", name, () => versions.write(found.remote, join(root, name)))))
|
|
154
162
|
throw changed("the local folder", "mirror.local-changed");
|
|
155
|
-
|
|
163
|
+
const copied = await send(name, join(root, name), found.remote, { absent: true });
|
|
164
|
+
if (copied.settled !== found.remote &&
|
|
165
|
+
!(await write("update", "local", name, () => versions.write(copied.settled, join(root, name), found.remote))))
|
|
166
|
+
throw changed("the local folder", "mirror.local-changed");
|
|
167
|
+
await entry(name, copied.sent, copied.settled);
|
|
156
168
|
copy = name;
|
|
157
169
|
}
|
|
158
170
|
if (state.conflicts) {
|
|
@@ -175,7 +187,9 @@ export const resolveFileConflict = async (options) => {
|
|
|
175
187
|
...(final ? { new: final } : {}),
|
|
176
188
|
resolution,
|
|
177
189
|
});
|
|
178
|
-
|
|
190
|
+
if (final && settled && settled !== final)
|
|
191
|
+
versions.log({ path, event: "changed", direction: "remote-to-local", old: final, from: "local", new: settled });
|
|
192
|
+
return { path, resolution, sha256: settled ?? null, ...(copy ? { copy } : {}) };
|
|
179
193
|
}
|
|
180
194
|
finally {
|
|
181
195
|
await held.release();
|
|
@@ -89,6 +89,8 @@ export interface FileMirrorResult {
|
|
|
89
89
|
downloaded: string[];
|
|
90
90
|
/** Text files both sides changed, merged and written to both. */
|
|
91
91
|
merged: string[];
|
|
92
|
+
/** Local files given the remote's own form of what was just uploaded, for a target that `rewrites`. */
|
|
93
|
+
rewritten?: string[];
|
|
92
94
|
trashed: {
|
|
93
95
|
path: string;
|
|
94
96
|
side: Side;
|
|
@@ -287,7 +287,7 @@ export const syncFileMirror = async (options) => {
|
|
|
287
287
|
const absent = steps.filter((step) => step.kind === "trash-local");
|
|
288
288
|
for (let at = 0; at < absent.length; at += CHECKS)
|
|
289
289
|
await Promise.all(absent.slice(at, at + CHECKS).map(async (step) => {
|
|
290
|
-
const why = await target.exists(remotePath(step.path), signal).then((there) => (there ? `missing from the ${options.remote} listing, but still there` : undefined), (error) => {
|
|
290
|
+
const why = await target.exists(remotePath(step.path), signal, step.base?.id).then((there) => (there ? `missing from the ${options.remote} listing, but still there` : undefined), (error) => {
|
|
291
291
|
if (signal?.aborted)
|
|
292
292
|
throw error;
|
|
293
293
|
return `the ${options.remote} could not say whether it was deleted: ${options.errorOf(error).message}`;
|
|
@@ -484,21 +484,56 @@ export const syncFileMirror = async (options) => {
|
|
|
484
484
|
folders.add(up);
|
|
485
485
|
}
|
|
486
486
|
const sent = await write(created ? "create" : "update", "remote", path, () => target.upload(remotePath(path), from.absolute, expect, signal));
|
|
487
|
-
|
|
487
|
+
const rewritten = sent.sha256 !== undefined && sent.sha256 !== from.hash;
|
|
488
|
+
if (rewritten && !target.rewrites)
|
|
488
489
|
throw new CliError("conflict", "the local file changed during the upload", { reason: "upload.mismatch" });
|
|
490
|
+
if (!merged) {
|
|
491
|
+
versions.log({
|
|
492
|
+
path,
|
|
493
|
+
event: created ? "created" : "changed",
|
|
494
|
+
direction: "local-to-remote",
|
|
495
|
+
...("sha256" in expect ? { old: expect.sha256, from: "remote" } : {}),
|
|
496
|
+
new: from.hash,
|
|
497
|
+
size: from.size,
|
|
498
|
+
});
|
|
499
|
+
result.uploaded.push(path);
|
|
500
|
+
}
|
|
501
|
+
if (rewritten)
|
|
502
|
+
return takeRewrite(path, sent, from);
|
|
489
503
|
record(path, sent, from, from.hash);
|
|
490
504
|
await keepBase(path, from.absolute, from.hash, from.size);
|
|
491
|
-
|
|
505
|
+
};
|
|
506
|
+
/**
|
|
507
|
+
* Puts the remote's own form of an upload into the local file, so both sides hold the same bytes and the next
|
|
508
|
+
* merge has one base. The local file keeps its version first; one saved meanwhile stays, sent by the next sync.
|
|
509
|
+
*/
|
|
510
|
+
const takeRewrite = async (path, sent, from) => {
|
|
511
|
+
const form = sent.sha256;
|
|
512
|
+
const kept = await versions.keep((temp) => target.download(remotePath(path), temp, signal));
|
|
513
|
+
if (kept !== form)
|
|
514
|
+
throw new CliError("conflict", `the ${options.remote} file changed right after the upload`, {
|
|
515
|
+
reason: "mirror.remote-changed",
|
|
516
|
+
});
|
|
517
|
+
const absolute = join(root, path);
|
|
518
|
+
await assertNoLink(root, path);
|
|
519
|
+
const old = await versions.keep(absolute);
|
|
520
|
+
const placed = old === from.hash && (await write("update", "local", path, () => versions.write(form, absolute, from.hash)));
|
|
521
|
+
if (!placed) {
|
|
522
|
+
// A local size no file has: the file is hashed again and sent, never taken for the remote's form.
|
|
523
|
+
record(path, sent, { size: -1, mtimeMs: -1 }, form);
|
|
492
524
|
return;
|
|
525
|
+
}
|
|
526
|
+
record(path, sent, await stat(absolute), form);
|
|
493
527
|
versions.log({
|
|
494
528
|
path,
|
|
495
|
-
event:
|
|
496
|
-
direction: "
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
529
|
+
event: "changed",
|
|
530
|
+
direction: "remote-to-local",
|
|
531
|
+
old,
|
|
532
|
+
from: "local",
|
|
533
|
+
new: form,
|
|
534
|
+
size: sent.size,
|
|
500
535
|
});
|
|
501
|
-
result.
|
|
536
|
+
result.rewritten = [...(result.rewritten ?? []), path];
|
|
502
537
|
};
|
|
503
538
|
/**
|
|
504
539
|
* False when the local file changed (or appeared) during the sync, so nothing was written. Without `recorded`, the
|
|
@@ -75,11 +75,12 @@ export interface FileVersions {
|
|
|
75
75
|
/**
|
|
76
76
|
* A mirror's local version store: `<dir>/objects/<sha256>` holds each kept content once, `<dir>/log.jsonl` is
|
|
77
77
|
* append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention: a
|
|
78
|
-
* content stays while an event newer than
|
|
79
|
-
*
|
|
80
|
-
*
|
|
78
|
+
* content stays while an event newer than `keepForDays` (the profile's `keep_versions_for_days`, 365 by default) names
|
|
79
|
+
* it; the last content of a path whose newest event is a deletion, and every content a merge, a conflict or a
|
|
80
|
+
* resolution names, stay for good. A content no event names stays as long after it was last kept, so a crash between
|
|
81
|
+
* keeping a file and logging the change loses nothing.
|
|
81
82
|
*/
|
|
82
|
-
export declare const fileVersions: (dir: string, now?: () => number) => FileVersions;
|
|
83
|
+
export declare const fileVersions: (dir: string, now?: () => number, keepForDays?: number) => FileVersions;
|
|
83
84
|
/**
|
|
84
85
|
* Puts a kept version of `path` back into the mirrored folder; the file there now is kept first. The next sync sends
|
|
85
86
|
* it like any local change. False when the store no longer has the version or the file changed meanwhile. Runs under
|
|
@@ -7,7 +7,8 @@ import { pipeline } from "node:stream/promises";
|
|
|
7
7
|
import { CliError } from "@wirecat/cli-base";
|
|
8
8
|
import { heldCheck } from "../documents/mirrors.js";
|
|
9
9
|
import { assertNoLink, hashFile, replaceLocal, safePath } from "../documents/push.js";
|
|
10
|
-
|
|
10
|
+
import { KEEP_VERSIONS_FOR_DAYS } from "../documents/sync.js";
|
|
11
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
11
12
|
/** Errors of the local file system: a writer that fails with one could not write the store, whatever it was reading. */
|
|
12
13
|
const LOCAL_FAILURES = new Set(["ENOSPC", "EDQUOT", "EROFS", "EACCES", "EPERM", "EIO", "EFBIG", "EMFILE", "ENFILE"]);
|
|
13
14
|
const notKept = (error) => {
|
|
@@ -50,11 +51,13 @@ const rolesOf = (event) => {
|
|
|
50
51
|
/**
|
|
51
52
|
* A mirror's local version store: `<dir>/objects/<sha256>` holds each kept content once, `<dir>/log.jsonl` is
|
|
52
53
|
* append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention: a
|
|
53
|
-
* content stays while an event newer than
|
|
54
|
-
*
|
|
55
|
-
*
|
|
54
|
+
* content stays while an event newer than `keepForDays` (the profile's `keep_versions_for_days`, 365 by default) names
|
|
55
|
+
* it; the last content of a path whose newest event is a deletion, and every content a merge, a conflict or a
|
|
56
|
+
* resolution names, stay for good. A content no event names stays as long after it was last kept, so a crash between
|
|
57
|
+
* keeping a file and logging the change loses nothing.
|
|
56
58
|
*/
|
|
57
|
-
export const fileVersions = (dir, now = Date.now) => {
|
|
59
|
+
export const fileVersions = (dir, now = Date.now, keepForDays = KEEP_VERSIONS_FOR_DAYS) => {
|
|
60
|
+
const retainMs = keepForDays * DAY_MS;
|
|
58
61
|
const objects = join(dir, "objects");
|
|
59
62
|
const logPath = join(dir, "log.jsonl");
|
|
60
63
|
const events = () => {
|
|
@@ -140,7 +143,7 @@ export const fileVersions = (dir, now = Date.now) => {
|
|
|
140
143
|
const last = new Map();
|
|
141
144
|
for (const event of all) {
|
|
142
145
|
last.set(event.path, event);
|
|
143
|
-
if (Date.parse(event.at) > now() -
|
|
146
|
+
if (Date.parse(event.at) > now() - retainMs)
|
|
144
147
|
for (const hash of [event.old, event.new])
|
|
145
148
|
if (hash)
|
|
146
149
|
keep.add(hash);
|
|
@@ -166,7 +169,7 @@ export const fileVersions = (dir, now = Date.now) => {
|
|
|
166
169
|
return undefined;
|
|
167
170
|
throw error;
|
|
168
171
|
});
|
|
169
|
-
if (kept && kept.mtimeMs <= now() -
|
|
172
|
+
if (kept && kept.mtimeMs <= now() - retainMs)
|
|
170
173
|
await rm(object, { force: true });
|
|
171
174
|
}
|
|
172
175
|
},
|
|
@@ -4,7 +4,7 @@ import { crmViewerOf } from "../crm/index.js";
|
|
|
4
4
|
import { hitFiles } from "../domain/attachments.js";
|
|
5
5
|
import { parseLocator } from "../domain/locator.js";
|
|
6
6
|
import { senderIsMe } from "../domain/models.js";
|
|
7
|
-
import { holdsKind, INTERNAL_NOTES } from "../domain/providers.js";
|
|
7
|
+
import { holdsKind, INTERNAL_NOTES, isDocumentAccountProvider } from "../domain/providers.js";
|
|
8
8
|
import { trackerTitleOf } from "../domain/tracker.js";
|
|
9
9
|
import { runEmbedders } from "../embeddings/embed.js";
|
|
10
10
|
import { chosenTextModel } from "../embeddings/models.js";
|
|
@@ -92,7 +92,8 @@ const strictWords = (text) => {
|
|
|
92
92
|
const accountKeyOf = ({ provider, account }) => `${provider}\u0000${account}`;
|
|
93
93
|
/** `--source` as the accounts each kind reads; a kind it names no account of is skipped, not read in full. */
|
|
94
94
|
const sourceScope = async (store, account, source, asked, messenger) => {
|
|
95
|
-
const
|
|
95
|
+
const context = await listContextOf(store, account, messenger.app);
|
|
96
|
+
const entries = entriesOfList(source, context);
|
|
96
97
|
// Any provider's import may write business data, so its accounts are the ones that hold some, whatever their kind.
|
|
97
98
|
const imported = asked.includes("business")
|
|
98
99
|
? new Set((await store.business.accounts()).map(accountKeyOf))
|
|
@@ -104,10 +105,19 @@ const sourceScope = async (store, account, source, asked, messenger) => {
|
|
|
104
105
|
const holds = (resource, one) => resource === "business"
|
|
105
106
|
? holdsBusiness(one)
|
|
106
107
|
: listedHolds(one, resource) || (resource === "notes" && holdsDocuments(one));
|
|
108
|
+
// A documents account named by its own key (`linear:user-1`, whose tracker copy is listed so) is read by the notes
|
|
109
|
+
// lane as the `notes:<id>` it is also listed as, so naming it both ways reads it once.
|
|
110
|
+
const asNotes = (one) => {
|
|
111
|
+
if (!isDocumentAccountProvider(one.provider))
|
|
112
|
+
return one;
|
|
113
|
+
const stored = context.held.find(({ provider, account }) => provider === one.provider && account === one.account);
|
|
114
|
+
return stored ? { provider: "notes", account: String(stored.id) } : one;
|
|
115
|
+
};
|
|
107
116
|
const named = (resource) => [
|
|
108
117
|
...new Map(entries
|
|
109
118
|
.flatMap(({ accounts }) => accounts)
|
|
110
119
|
.filter((one) => holds(resource, one))
|
|
120
|
+
.map((one) => (resource === "notes" ? asNotes(one) : one))
|
|
111
121
|
.map(({ provider, account }) => [`${provider}\u0000${account}`, { provider, account }])).values(),
|
|
112
122
|
];
|
|
113
123
|
const scope = Object.fromEntries(asked.map((resource) => [resource, named(resource)]));
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
-
import { holdsKindOf, isDocumentAccountProvider, isFolderProvider, isKind, providerNamed } from "../domain/providers.js";
|
|
2
|
+
import { alsoListedByKey, holdsKindOf, isDocumentAccountProvider, isFolderProvider, isKind, providerNamed, } from "../domain/providers.js";
|
|
3
3
|
import { envName } from "../ports/app.js";
|
|
4
4
|
import { entriesOfList, fitting, isAccountList, keyOf, } from "../search/account-list.js";
|
|
5
5
|
import { ALL, groupEntries, groupMembership, hasGroup, OWNER_NOTES } from "../search/groups.js";
|
|
@@ -36,13 +36,14 @@ export const listContextOf = async (store, account, app, stored, env) => {
|
|
|
36
36
|
if (!members)
|
|
37
37
|
throw new CliError("permission_error", `this process is locked to group ${lock} (${envName(app, "GROUP_LOCK")}), which does not exist`);
|
|
38
38
|
const only = new Set([...members, OWNER_NOTES].map(keyOf));
|
|
39
|
-
// A notes folder or a documents account is held under its own key but listed as `notes:<store id
|
|
39
|
+
// A notes folder or a documents account is held under its own key but listed as `notes:<store id>`; one that holds
|
|
40
|
+
// another kind too (Linear's tracker copy) is also listed under its own key.
|
|
40
41
|
const listedAs = (one) => isFolderProvider(one.provider) || isDocumentAccountProvider(one.provider)
|
|
41
|
-
? { provider: "notes", account: String(one.id) }
|
|
42
|
-
: one;
|
|
42
|
+
? [{ provider: "notes", account: String(one.id) }, ...(alsoListedByKey(one.provider) ? [one] : [])]
|
|
43
|
+
: [one];
|
|
43
44
|
return {
|
|
44
45
|
...context,
|
|
45
|
-
held: held.filter((one) => only.has(keyOf(
|
|
46
|
+
held: held.filter((one) => listedAs(one).some((key) => only.has(keyOf(key)))),
|
|
46
47
|
groups: { [lock]: groups[lock] ?? [] },
|
|
47
48
|
membership: {
|
|
48
49
|
groups: { [lock]: members },
|
|
@@ -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
|
-
.
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
-
|
|
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.
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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
|
-
...(
|
|
312
|
+
...(account ? { account } : {}),
|
|
158
313
|
...(opts.rescan ? { rescan: true } : {}),
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
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.
|
|
3
|
+
"version": "0.728.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",
|