@wirecat/cli-core 0.668.0 → 0.669.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 +49 -0
- package/dist/calendar/mcp/index.d.ts +12 -12
- package/dist/cli/documents/catalog.js +3 -14
- package/dist/cli/documents/sync.d.ts +21 -5
- package/dist/cli/documents/sync.js +39 -8
- package/dist/cli/documents/testing/source-contract.d.ts +9 -0
- package/dist/cli/documents/testing/source-contract.js +12 -0
- package/dist/documents/model.d.ts +4 -0
- package/dist/services/documents/ingestion.d.ts +3 -0
- package/dist/services/documents/ingestion.js +9 -2
- package/dist/services/documents/plan.d.ts +16 -1
- package/dist/services/documents/plan.js +163 -103
- package/dist/services/documents/ports.d.ts +13 -0
- package/dist/services/documents/sync.d.ts +11 -0
- package/dist/services/documents/sync.js +41 -3
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/sqlite/catalog.d.ts +2 -1
- package/dist/store/sqlite/catalog.js +4 -1
- package/dist/store/sqlite/note-search.d.ts +10 -1
- package/dist/store/sqlite/note-search.js +35 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,55 @@ 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.669.0 — 15.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`syncDocuments` takes a `budget`** (a `RunBudget`), asked before each folder listing and each file read: a stop
|
|
13
|
+
ends the call with its work saved. The shared `sync` command passes `runBudgetOf(command)` as `budget` in its
|
|
14
|
+
arguments, for the CLI to hand on. See [Walks over several syncs](docs/dev/DOCUMENTS.md#walks-over-several-syncs).
|
|
15
|
+
- **`SourceIndex.settle` and `store.notes.indexWritten`.** At the end of a sync the engine indexes the store's waiting
|
|
16
|
+
text for word search, so a read-only reader finds a page by the words of its text right after the sync; before, the
|
|
17
|
+
text waited until a writable store ran a search. The queue is shared by every tool on the store. It works 50 rows at
|
|
18
|
+
a time and yields between them, and stops after 10 s, at `deadline` less its margin, or on the signal; it is skipped
|
|
19
|
+
after a budget stop. `documentIngestion` supplies `settle`; `indexWritten` answers 0 on a read-only store.
|
|
20
|
+
- **`SyncOptions.deadline` and `DocumentSyncArgs.deadline`:** the run's hard limit, which the shared `sync` command
|
|
21
|
+
passes for the CLI to hand on.
|
|
22
|
+
- **`documentSourceContract` checks a deep change** when the fixture gives `addNested`: the feed must name a file
|
|
23
|
+
added two levels below the root, or its own folder.
|
|
24
|
+
- **The catalog's `parent` filter takes several ids** (`parent: [a, b]`), read in one pass of the account's catalog.
|
|
25
|
+
`catalog tree` asks about the branches it cuts this way: 1 000 branches in a 12 000-entry account take about
|
|
26
|
+
0.06 s instead of 3.2 s ([measured](https://github.com/WireCatLabs/cli-testing/blob/main/performance/documents/sync-scale/README.md)). `documentIngestion`'s `catalog.get` and `catalog.list` take an id with or without `.md`.
|
|
27
|
+
|
|
28
|
+
### Changed — may break callers
|
|
29
|
+
|
|
30
|
+
- **A sync no longer fails for the size of the chosen folders.** `maxEntries` now bounds one call: a walk past it
|
|
31
|
+
saves where it stopped, answers `complete: false`, `stopped: "entries"` and `walk: { folders_left, entries,
|
|
32
|
+
listed }`, and the next sync goes on from there. `limitError` is no longer called. `SyncResult` gains `complete`,
|
|
33
|
+
`stopped` and `walk`. The shared `sync` command declares `partial`: an unfinished pass (a walk or pending
|
|
34
|
+
operations) answers `meta.complete: false`, exits 0 and names the same `sync --limit` as its next step
|
|
35
|
+
(`sync.run`, safe to run unasked). Its help no longer says one sync reads at most that many entries.
|
|
36
|
+
- **A changed folder lists only its direct children.** A round of changes no longer walks the whole subtree of each
|
|
37
|
+
folder the feed names: a child folder the last finished pass held is not listed again. An edit to a page with 500
|
|
38
|
+
pages below it, and to one of them, lists those 2 pages instead of 501. A source must therefore name in its feed
|
|
39
|
+
each changed entry or its own folder: one that names only an ancestor misses a file two levels below until a
|
|
40
|
+
rescan. A folder new to the scope
|
|
41
|
+
(new, restored, or moved in from outside) is still walked in full, so the files under a Drive folder moved in are
|
|
42
|
+
found. A round a call cuts short is saved and goes on in the next sync.
|
|
43
|
+
- **`--rescan` goes on until it finishes.** It drops the cursor and any saved walk and saves that at once, so the
|
|
44
|
+
following plain syncs continue its walk. A dropped batch's work saved to the index without the state knowing is
|
|
45
|
+
removed when the batch is dropped, no longer counted in `removed`, and the state is saved right after.
|
|
46
|
+
- **A folder deleted or unshared since the walk saved it is dropped**, with what was below it, when listing it answers
|
|
47
|
+
`not_found` and reading it again with `metadata` answers `not_found` too or finds it trashed. On any doubt the sync
|
|
48
|
+
fails as before and the next one lists the folder again, so a passing 404 never removes a subtree. `sync --help`
|
|
49
|
+
says each `--rescan` starts the walk over, so it is run once and continued with a plain `sync`.
|
|
50
|
+
- **A test that expects the sync to fail for size now fails.** drive's
|
|
51
|
+
`says to choose smaller folders when the chosen ones hold more entries than one sync reads` (`src/sync.test.ts`)
|
|
52
|
+
expects that error; on its bump it should expect `complete: false` instead. drive's own bound on one folder
|
|
53
|
+
listing or one change feed (10 000 entries, in `google.ts`) is unchanged.
|
|
54
|
+
- **The saved walk keeps only `SourceWalk`'s fields.** drive's saved `walk.json` and `state.json` keep working as
|
|
55
|
+
they are; a round of changes is saved under the scope `<scope>:changes:<cursor>`.
|
|
56
|
+
|
|
8
57
|
## 0.668.0 — 15.11.2026
|
|
9
58
|
|
|
10
59
|
### Added
|
|
@@ -10,13 +10,13 @@ export declare const calendarTools: ({
|
|
|
10
10
|
inputSchema: {
|
|
11
11
|
type: string;
|
|
12
12
|
properties: {
|
|
13
|
-
limit?: undefined;
|
|
14
13
|
account_id: {
|
|
15
14
|
type: string;
|
|
16
15
|
minimum: number;
|
|
17
16
|
};
|
|
18
17
|
query?: undefined;
|
|
19
18
|
timezone?: undefined;
|
|
19
|
+
limit?: undefined;
|
|
20
20
|
page?: undefined;
|
|
21
21
|
event?: undefined;
|
|
22
22
|
} | {
|
|
@@ -45,9 +45,9 @@ export declare const calendarTools: ({
|
|
|
45
45
|
};
|
|
46
46
|
event?: undefined;
|
|
47
47
|
} | {
|
|
48
|
-
limit?: undefined;
|
|
49
48
|
query?: undefined;
|
|
50
49
|
timezone?: undefined;
|
|
50
|
+
limit?: undefined;
|
|
51
51
|
page?: undefined;
|
|
52
52
|
event: {
|
|
53
53
|
type: string;
|
|
@@ -58,9 +58,9 @@ export declare const calendarTools: ({
|
|
|
58
58
|
minimum: number;
|
|
59
59
|
};
|
|
60
60
|
} | {
|
|
61
|
-
limit?: undefined;
|
|
62
61
|
query?: undefined;
|
|
63
62
|
timezone?: undefined;
|
|
63
|
+
limit?: undefined;
|
|
64
64
|
page?: undefined;
|
|
65
65
|
event?: undefined;
|
|
66
66
|
account_id?: undefined;
|
|
@@ -80,13 +80,13 @@ export declare const calendarTools: ({
|
|
|
80
80
|
inputSchema: {
|
|
81
81
|
type: string;
|
|
82
82
|
properties: {
|
|
83
|
-
limit?: undefined;
|
|
84
83
|
account_id: {
|
|
85
84
|
type: string;
|
|
86
85
|
minimum: number;
|
|
87
86
|
};
|
|
88
87
|
query?: undefined;
|
|
89
88
|
timezone?: undefined;
|
|
89
|
+
limit?: undefined;
|
|
90
90
|
page?: undefined;
|
|
91
91
|
event?: undefined;
|
|
92
92
|
} | {
|
|
@@ -115,9 +115,9 @@ export declare const calendarTools: ({
|
|
|
115
115
|
};
|
|
116
116
|
event?: undefined;
|
|
117
117
|
} | {
|
|
118
|
-
limit?: undefined;
|
|
119
118
|
query?: undefined;
|
|
120
119
|
timezone?: undefined;
|
|
120
|
+
limit?: undefined;
|
|
121
121
|
page?: undefined;
|
|
122
122
|
event: {
|
|
123
123
|
type: string;
|
|
@@ -128,9 +128,9 @@ export declare const calendarTools: ({
|
|
|
128
128
|
minimum: number;
|
|
129
129
|
};
|
|
130
130
|
} | {
|
|
131
|
-
limit?: undefined;
|
|
132
131
|
query?: undefined;
|
|
133
132
|
timezone?: undefined;
|
|
133
|
+
limit?: undefined;
|
|
134
134
|
page?: undefined;
|
|
135
135
|
event?: undefined;
|
|
136
136
|
account_id?: undefined;
|
|
@@ -150,13 +150,13 @@ export declare const calendarTools: ({
|
|
|
150
150
|
inputSchema: {
|
|
151
151
|
type: string;
|
|
152
152
|
properties: {
|
|
153
|
-
limit?: undefined;
|
|
154
153
|
account_id: {
|
|
155
154
|
type: string;
|
|
156
155
|
minimum: number;
|
|
157
156
|
};
|
|
158
157
|
query?: undefined;
|
|
159
158
|
timezone?: undefined;
|
|
159
|
+
limit?: undefined;
|
|
160
160
|
page?: undefined;
|
|
161
161
|
event?: undefined;
|
|
162
162
|
} | {
|
|
@@ -185,9 +185,9 @@ export declare const calendarTools: ({
|
|
|
185
185
|
};
|
|
186
186
|
event?: undefined;
|
|
187
187
|
} | {
|
|
188
|
-
limit?: undefined;
|
|
189
188
|
query?: undefined;
|
|
190
189
|
timezone?: undefined;
|
|
190
|
+
limit?: undefined;
|
|
191
191
|
page?: undefined;
|
|
192
192
|
event: {
|
|
193
193
|
type: string;
|
|
@@ -198,9 +198,9 @@ export declare const calendarTools: ({
|
|
|
198
198
|
minimum: number;
|
|
199
199
|
};
|
|
200
200
|
} | {
|
|
201
|
-
limit?: undefined;
|
|
202
201
|
query?: undefined;
|
|
203
202
|
timezone?: undefined;
|
|
203
|
+
limit?: undefined;
|
|
204
204
|
page?: undefined;
|
|
205
205
|
event?: undefined;
|
|
206
206
|
account_id?: undefined;
|
|
@@ -220,13 +220,13 @@ export declare const calendarTools: ({
|
|
|
220
220
|
inputSchema: {
|
|
221
221
|
type: string;
|
|
222
222
|
properties: {
|
|
223
|
-
limit?: undefined;
|
|
224
223
|
account_id: {
|
|
225
224
|
type: string;
|
|
226
225
|
minimum: number;
|
|
227
226
|
};
|
|
228
227
|
query?: undefined;
|
|
229
228
|
timezone?: undefined;
|
|
229
|
+
limit?: undefined;
|
|
230
230
|
page?: undefined;
|
|
231
231
|
event?: undefined;
|
|
232
232
|
} | {
|
|
@@ -255,9 +255,9 @@ export declare const calendarTools: ({
|
|
|
255
255
|
};
|
|
256
256
|
event?: undefined;
|
|
257
257
|
} | {
|
|
258
|
-
limit?: undefined;
|
|
259
258
|
query?: undefined;
|
|
260
259
|
timezone?: undefined;
|
|
260
|
+
limit?: undefined;
|
|
261
261
|
page?: undefined;
|
|
262
262
|
event: {
|
|
263
263
|
type: string;
|
|
@@ -268,9 +268,9 @@ export declare const calendarTools: ({
|
|
|
268
268
|
minimum: number;
|
|
269
269
|
};
|
|
270
270
|
} | {
|
|
271
|
-
limit?: undefined;
|
|
272
271
|
query?: undefined;
|
|
273
272
|
timezone?: undefined;
|
|
273
|
+
limit?: undefined;
|
|
274
274
|
page?: undefined;
|
|
275
275
|
event?: undefined;
|
|
276
276
|
account_id?: undefined;
|
|
@@ -11,29 +11,18 @@ import { allOf, examples, nonnegative, positive, wordsOf } from "./words.js";
|
|
|
11
11
|
export const CATALOG_TREE_LIMIT = 10_000;
|
|
12
12
|
const CATALOG_PAGE = 1000;
|
|
13
13
|
const PARENT_BATCH = 200;
|
|
14
|
-
/** `parent:a OR parent:b …` over ids as they are: the values go into a parsed template, so none needs escaping. */
|
|
15
|
-
const anyParent = (ids) => {
|
|
16
|
-
const ast = parseLucene(Array.from({ length: Math.max(2, ids.length) }, () => "parent:x").join(" OR "), {
|
|
17
|
-
defaultField: "none",
|
|
18
|
-
});
|
|
19
|
-
const clauses = ast.root.clauses;
|
|
20
|
-
clauses.forEach((clause, i) => {
|
|
21
|
-
clause.node.value = ids[Math.min(i, ids.length - 1)];
|
|
22
|
-
});
|
|
23
|
-
return validateQuery(ast, CATALOG_QUERY);
|
|
24
|
-
};
|
|
25
14
|
/** The tree's reads through the CLI's catalog, which takes ids without the `.md` the store's entries carry. */
|
|
26
15
|
export const catalogSource = (catalog, principal) => ({
|
|
27
16
|
get: (externalId) => catalog.get(principal, catalogId({ externalId })),
|
|
28
17
|
children: (externalId, page) => catalog.list(principal, { parent: catalogId({ externalId }), ...page }),
|
|
29
|
-
// Each read scans the account's catalog, so the branches cut at the depth are asked about 200 at a time.
|
|
18
|
+
// Each read scans the account's catalog, so the branches cut at the depth are asked about 200 at a time, in one read.
|
|
30
19
|
withChildren: async (externalIds) => {
|
|
31
20
|
const found = new Set();
|
|
32
21
|
for (let start = 0; start < externalIds.length; start += PARENT_BATCH) {
|
|
33
22
|
const batch = new Set(externalIds.slice(start, start + PARENT_BATCH));
|
|
34
|
-
const
|
|
23
|
+
const parent = [...batch].map((externalId) => catalogId({ externalId }));
|
|
35
24
|
for (let offset = 0;; offset += CATALOG_PAGE) {
|
|
36
|
-
const page = await catalog.list(principal, {
|
|
25
|
+
const page = await catalog.list(principal, { parent, limit: CATALOG_PAGE, offset });
|
|
37
26
|
for (const item of page.items)
|
|
38
27
|
for (const parent of item.parents)
|
|
39
28
|
if (batch.delete(parent))
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Command } from "commander";
|
|
2
|
+
import type { Deadline, RunBudget } from "../../background/budget.js";
|
|
2
3
|
import { type Body } from "../envelope.js";
|
|
3
4
|
import { type DocumentWords } from "./words.js";
|
|
4
5
|
export interface DocumentSyncArgs {
|
|
@@ -6,6 +7,24 @@ export interface DocumentSyncArgs {
|
|
|
6
7
|
rescan?: boolean;
|
|
7
8
|
/** Also index pending text for meaning search, with a model already downloaded. */
|
|
8
9
|
embed?: boolean;
|
|
10
|
+
/** Sized to the run's deadline; pass it to `syncDocuments` so a sync stops in time and says how to go on. */
|
|
11
|
+
budget?: RunBudget;
|
|
12
|
+
/** The run's hard limit; pass it to `syncDocuments` so its last step, the word index, ends before it. */
|
|
13
|
+
deadline?: Deadline;
|
|
14
|
+
}
|
|
15
|
+
export interface DocumentSyncAnswer {
|
|
16
|
+
errors: unknown[];
|
|
17
|
+
pending: number;
|
|
18
|
+
/** `false` while the pass is unfinished: a folder walk or operations are left for the next sync. */
|
|
19
|
+
complete?: boolean;
|
|
20
|
+
walk?: {
|
|
21
|
+
folders_left: number;
|
|
22
|
+
listed: number;
|
|
23
|
+
};
|
|
24
|
+
saved?: number;
|
|
25
|
+
names_only?: number;
|
|
26
|
+
removed?: number;
|
|
27
|
+
unchanged?: number;
|
|
9
28
|
}
|
|
10
29
|
export interface DocumentSyncCommands {
|
|
11
30
|
words: DocumentWords;
|
|
@@ -14,16 +33,13 @@ export interface DocumentSyncCommands {
|
|
|
14
33
|
diagnostic(text: string): void;
|
|
15
34
|
/** The selected profile, as `sync again` names it. */
|
|
16
35
|
profile(): string;
|
|
17
|
-
/** The
|
|
36
|
+
/** The entries one sync walks under the chosen folders before it stops and saves, as `sync --help` says. */
|
|
18
37
|
maxEntries: number;
|
|
19
38
|
/**
|
|
20
39
|
* Syncs the selected profile into the shared store under the lock the CLI's writes take. `errors` are the failed
|
|
21
40
|
* operations still pending; `pending` counts every operation left for the next sync.
|
|
22
41
|
*/
|
|
23
|
-
sync(args: DocumentSyncArgs): Promise<
|
|
24
|
-
errors: unknown[];
|
|
25
|
-
pending: number;
|
|
26
|
-
}>;
|
|
42
|
+
sync(args: DocumentSyncArgs): Promise<DocumentSyncAnswer>;
|
|
27
43
|
/** What `status` answers: the last sync, imported documents and pending work, from local files only. */
|
|
28
44
|
status(): object | Promise<object>;
|
|
29
45
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
2
|
import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
|
|
3
|
+
import { environmentOf, runBudgetOf } from "../context.js";
|
|
3
4
|
import { honoursDryRun } from "../dry-run-guard.js";
|
|
4
5
|
import { FETCH, LOCAL_READ } from "../effects.js";
|
|
5
6
|
import { itemOf } from "../envelope.js";
|
|
@@ -8,25 +9,55 @@ const addDocumentSyncCommandsDefinition = (program, helpers) => {
|
|
|
8
9
|
const { output } = helpers;
|
|
9
10
|
const wording = wordsOf(helpers.words);
|
|
10
11
|
const { prefix, text } = wording;
|
|
11
|
-
const sync = examples(annotate(program.command("sync"), { effects: FETCH })
|
|
12
|
+
const sync = examples(annotate(program.command("sync"), { effects: FETCH, partial: true })
|
|
12
13
|
.summary("import what changed in the chosen folders, and finish an unfinished sync")
|
|
13
14
|
.description("import what changed in the chosen folders, and finish an unfinished sync; " +
|
|
14
|
-
`one sync
|
|
15
|
+
`one sync walks about ${helpers.maxEntries} entries under the chosen folders, saves where it stopped, and ` +
|
|
16
|
+
"the next sync goes on from there"), [`${prefix} sync`, `${prefix} sync --rescan --limit 500`])
|
|
15
17
|
.option("--limit <n>", text.syncLimit, positive, 200)
|
|
16
|
-
.option("--rescan", "read every chosen folder again instead of only what changed"
|
|
18
|
+
.option("--rescan", "read every chosen folder again instead of only what changed; each --rescan starts the walk over, so run it " +
|
|
19
|
+
"once and continue with a plain sync")
|
|
17
20
|
.option("--embed", "also index pending text for meaning search, with a model already downloaded")
|
|
18
|
-
.action(async (args) => {
|
|
19
|
-
const
|
|
21
|
+
.action(async (args, command) => {
|
|
22
|
+
const deadline = environmentOf(command).deadline?.();
|
|
23
|
+
const result = await helpers.sync({ ...args, budget: runBudgetOf(command), ...(deadline ? { deadline } : {}) });
|
|
24
|
+
const unfinished = result.complete === false || result.pending > 0;
|
|
25
|
+
const moved = (result.walk?.listed ?? 0) > 0 ||
|
|
26
|
+
[result.saved, result.names_only, result.removed, result.unchanged].some((count) => (count ?? 0) > 0);
|
|
27
|
+
const again = `${wording.app} ${helpers.profile()} sync`;
|
|
28
|
+
const timeout = command.optsWithGlobals().timeout;
|
|
29
|
+
// The same sync again, never --rescan, which would start the pass over; a run that moved nothing gets no step.
|
|
30
|
+
const next = unfinished && !result.errors.length && moved
|
|
31
|
+
? [
|
|
32
|
+
{
|
|
33
|
+
kind: "command",
|
|
34
|
+
step: "sync.run",
|
|
35
|
+
command: "sync",
|
|
36
|
+
args: {
|
|
37
|
+
limit: args.limit,
|
|
38
|
+
...(timeout === undefined ? {} : { timeout }),
|
|
39
|
+
...(args.embed ? { embed: true } : {}),
|
|
40
|
+
},
|
|
41
|
+
why: "the sync stopped before the end of its pass; running it again goes on from there",
|
|
42
|
+
safe_to_auto_execute: true,
|
|
43
|
+
},
|
|
44
|
+
]
|
|
45
|
+
: [];
|
|
20
46
|
output(itemOf(result, {
|
|
21
47
|
meta: result.errors.length
|
|
22
48
|
? {
|
|
23
49
|
complete: false,
|
|
24
50
|
issues: [{ code: "provider_error", reason: "sync.partial", source: wording.source }],
|
|
25
51
|
}
|
|
26
|
-
:
|
|
52
|
+
: unfinished
|
|
53
|
+
? { complete: false }
|
|
54
|
+
: {},
|
|
55
|
+
next,
|
|
27
56
|
}));
|
|
28
|
-
if (result.
|
|
29
|
-
helpers.diagnostic(`${result.
|
|
57
|
+
if (result.walk)
|
|
58
|
+
helpers.diagnostic(`${result.walk.folders_left} folders remain to list; run ${again} again\n`);
|
|
59
|
+
else if (result.errors.length || result.pending)
|
|
60
|
+
helpers.diagnostic(`${result.pending} source operations remain; run ${again} again\n`);
|
|
30
61
|
if (result.errors.length)
|
|
31
62
|
throw new CliError("provider_error", "sync completed partially; failed operations remain pending", {
|
|
32
63
|
reason: "sync.partial",
|
|
@@ -11,6 +11,15 @@ export interface DocumentSourceFixture<M extends SourceFile = SourceFile> {
|
|
|
11
11
|
isDocument?(file: M): boolean;
|
|
12
12
|
/** Makes a change on the provider's side (a new or edited file) for the change feed to list; absent skips that check. */
|
|
13
13
|
change?(): Promise<void>;
|
|
14
|
+
/**
|
|
15
|
+
* Adds a file inside a folder two levels below the root on the provider's side, and names both. A round of changes
|
|
16
|
+
* lists only the direct children of a folder the feed names, so the feed must name the new file or its own folder;
|
|
17
|
+
* absent skips that case.
|
|
18
|
+
*/
|
|
19
|
+
addNested?(): Promise<{
|
|
20
|
+
file: string;
|
|
21
|
+
folder: string;
|
|
22
|
+
}>;
|
|
14
23
|
/** An id the provider does not know; absent skips that case. */
|
|
15
24
|
missing?: string;
|
|
16
25
|
}
|
|
@@ -99,6 +99,18 @@ export const documentSourceContract = (make) => {
|
|
|
99
99
|
},
|
|
100
100
|
},
|
|
101
101
|
];
|
|
102
|
+
cases.push({
|
|
103
|
+
name: "changes: a file added deep in the tree is named in the feed, itself or by its own folder",
|
|
104
|
+
async run() {
|
|
105
|
+
const { source, addNested } = await make();
|
|
106
|
+
if (!addNested)
|
|
107
|
+
return;
|
|
108
|
+
const token = await source.startToken();
|
|
109
|
+
const { file, folder } = await addNested();
|
|
110
|
+
const named = new Set((await source.changes(token)).items.map((item) => item.id));
|
|
111
|
+
assert.ok(named.has(file) || named.has(folder), `the feed names ${file} or its folder ${folder}`);
|
|
112
|
+
},
|
|
113
|
+
});
|
|
102
114
|
cases.push({
|
|
103
115
|
name: "metadata: an id the provider does not know is not_found",
|
|
104
116
|
async run() {
|
|
@@ -107,6 +107,10 @@ export interface SourceIndex<M extends SourceFile = SourceFile> {
|
|
|
107
107
|
save(principal: string, content: SourceContent<M>, hash: string): Promise<string>;
|
|
108
108
|
remove(principal: string, id: string): Promise<void>;
|
|
109
109
|
openPictures(): Promise<PictureWriter>;
|
|
110
|
+
/** Indexes what the sync saved for word search, until `until` says stop; the rest waits for the next search. */
|
|
111
|
+
settle?(options: {
|
|
112
|
+
until: () => boolean;
|
|
113
|
+
}): Promise<unknown>;
|
|
110
114
|
}
|
|
111
115
|
export interface SourceStatePort<M extends SourceFile = SourceFile> {
|
|
112
116
|
read(): SourceState<M>;
|
|
@@ -28,6 +28,9 @@ export declare const documentIngestion: <M extends SourceFile>(store: Pick<Messa
|
|
|
28
28
|
}>;
|
|
29
29
|
};
|
|
30
30
|
collection: (principal: string, create: boolean) => Promise<import("../../store/index.js").NoteFolder | undefined>;
|
|
31
|
+
settle: ({ until }: {
|
|
32
|
+
until: () => boolean;
|
|
33
|
+
}) => Promise<number>;
|
|
31
34
|
save: (principal: string, content: SourceContent<M>, hash: string) => Promise<string>;
|
|
32
35
|
remove: (principal: string, id: string) => Promise<void>;
|
|
33
36
|
};
|
|
@@ -10,6 +10,8 @@ export const documentIngestion = (store, options) => {
|
|
|
10
10
|
const found = (await store.notes.folders()).find((item) => item.name === name);
|
|
11
11
|
return found ?? (create ? await store.notes.addFolder({ name, format: "markdown" }) : undefined);
|
|
12
12
|
};
|
|
13
|
+
// The catalog answers external ids (`<id>.md`), so an id given back as it was answered is found too.
|
|
14
|
+
const both = (id) => [...new Set([options.externalId(id), id])];
|
|
13
15
|
const stale = async (ref) => {
|
|
14
16
|
for (const status of ["proposed", "confirmed"]) {
|
|
15
17
|
for (let batch = 0;; batch++) {
|
|
@@ -44,7 +46,10 @@ export const documentIngestion = (store, options) => {
|
|
|
44
46
|
},
|
|
45
47
|
get: async (principal, id) => {
|
|
46
48
|
const selected = await folder(principal, false);
|
|
47
|
-
|
|
49
|
+
if (!selected)
|
|
50
|
+
return undefined;
|
|
51
|
+
const entry = await store.catalog.get(selected.id, options.externalId(id));
|
|
52
|
+
return entry ?? (options.externalId(id) === id ? undefined : store.catalog.get(selected.id, id));
|
|
48
53
|
},
|
|
49
54
|
list: async (principal, query = {}) => {
|
|
50
55
|
const selected = await folder(principal, false);
|
|
@@ -57,12 +62,14 @@ export const documentIngestion = (store, options) => {
|
|
|
57
62
|
? store.catalog.list(selected.id, {
|
|
58
63
|
...query,
|
|
59
64
|
...(ast ? { ast } : {}),
|
|
60
|
-
...(query.parent === undefined ? {} : { parent:
|
|
65
|
+
...(query.parent === undefined ? {} : { parent: [query.parent].flat().flatMap(both) }),
|
|
61
66
|
})
|
|
62
67
|
: { items: [], hasMore: false };
|
|
63
68
|
},
|
|
64
69
|
},
|
|
65
70
|
collection: folder,
|
|
71
|
+
// A store fake that predates `indexWritten` leaves the text for the next search to index.
|
|
72
|
+
settle: async ({ until }) => store.notes.indexWritten?.({ until }),
|
|
66
73
|
save: async (principal, content, hash) => {
|
|
67
74
|
const selected = await folder(principal, true);
|
|
68
75
|
if (!selected)
|
|
@@ -7,5 +7,20 @@ interface WalkStore<M extends SourceFile> {
|
|
|
7
7
|
read: (scope: string) => SourceWalk<M> | undefined;
|
|
8
8
|
save: (walk: SourceWalk<M>) => void;
|
|
9
9
|
}
|
|
10
|
-
export
|
|
10
|
+
export type WalkStop = "entries" | "requests" | "deadline" | "cancelled";
|
|
11
|
+
/** A folder walk this call stopped before its end, saved for the next sync to go on from. */
|
|
12
|
+
export interface WalkProgress {
|
|
13
|
+
folders_left: number;
|
|
14
|
+
/** Entries the walk has found over every call so far. */
|
|
15
|
+
entries: number;
|
|
16
|
+
/** Folders this call listed: 0 means it moved nothing on. */
|
|
17
|
+
listed: number;
|
|
18
|
+
stopped: WalkStop;
|
|
19
|
+
}
|
|
20
|
+
export type Plan<M extends SourceFile> = {
|
|
21
|
+
pending: NonNullable<SourceState<M>["pending"]>;
|
|
22
|
+
} | {
|
|
23
|
+
walk: WalkProgress;
|
|
24
|
+
};
|
|
25
|
+
export declare const planDocuments: <M extends SourceFile>(options: SyncOptions<M>, source: DocumentSource<M> | undefined, state: SourceState<M>, roots: string[], limit: number, pictures: boolean, walks?: WalkStore<M>) => Promise<Plan<M>>;
|
|
11
26
|
export {};
|
|
@@ -12,134 +12,78 @@ export const changedSince = (previous, file) => previous.version !== file.versio
|
|
|
12
12
|
previous.canDownload !== file.canDownload ||
|
|
13
13
|
JSON.stringify(previous.parents) !== JSON.stringify(file.parents);
|
|
14
14
|
const SAVE_EVERY_MS = 2000;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
// A round of changes is saved under its own scope: a CLI that validates the walk file keeps only the fields it knows,
|
|
16
|
+
// and these say both what the walk is and which cursor it started from.
|
|
17
|
+
const changesScope = (scope, cursor) => `${scope}:changes:${cursor}`;
|
|
18
|
+
export const planDocuments = async (options, source, state, roots, limit, pictures, walks) => {
|
|
19
|
+
const { isFolder, skipReason, retryable, maxEntries, errorOf, query, budget } = options;
|
|
18
20
|
const scope = scopeHash(roots, query, options.isDocument !== undefined);
|
|
19
21
|
if (!roots.length && query?.mode !== "include")
|
|
20
22
|
return {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
pending: {
|
|
24
|
+
scope,
|
|
25
|
+
cursor: state.cursor ?? "",
|
|
26
|
+
folders: {},
|
|
27
|
+
skipped: [],
|
|
28
|
+
jobs: Object.keys(state.documents).map((id) => ({ id, kind: "remove" })),
|
|
29
|
+
},
|
|
26
30
|
};
|
|
27
31
|
if (!source)
|
|
28
32
|
throw new CliError("configuration_error", "selected folders or a saved query require an authenticated source");
|
|
29
33
|
if (query?.mode === "include" && !query.list)
|
|
30
34
|
throw new CliError("configuration_error", "a query that includes files must list them");
|
|
31
|
-
// Listed before the walk: a failure here then costs no folder already walked.
|
|
32
|
-
const found = query?.mode === "include" && query.list ? await query.list() : [];
|
|
33
35
|
const initial = !state.cursor || scope !== state.scope;
|
|
34
|
-
const resumed = initial ?
|
|
35
|
-
const cursor = initial ? (resumed?.cursor ?? (await source.startToken())) : state.cursor;
|
|
36
|
+
const resumed = walks?.read(initial ? scope : changesScope(scope, state.cursor));
|
|
36
37
|
const folders = initial ? {} : structuredClone(state.folders);
|
|
37
38
|
const files = new Map(Object.values(state.documents).map((doc) => [doc.metadata.id, doc.metadata]));
|
|
38
39
|
const changed = new Set();
|
|
40
|
+
// What the walk saves: every file of a full walk, or what a round of changes touched, a removed file as trashed.
|
|
41
|
+
const delta = new Map();
|
|
39
42
|
for (const skipped of state.skipped)
|
|
40
43
|
if (skipped.file)
|
|
41
44
|
files.set(skipped.id, skipped.file);
|
|
45
|
+
if (initial)
|
|
46
|
+
files.clear();
|
|
42
47
|
const keep = (file) => {
|
|
43
48
|
files.set(file.id, file);
|
|
44
49
|
changed.add(file.id);
|
|
50
|
+
delta.set(file.id, file);
|
|
51
|
+
};
|
|
52
|
+
const drop = (id) => {
|
|
53
|
+
const known = files.get(id);
|
|
54
|
+
if (known)
|
|
55
|
+
delta.set(id, { ...known, trashed: true });
|
|
56
|
+
files.delete(id);
|
|
45
57
|
};
|
|
46
58
|
const container = (file) => {
|
|
47
59
|
if (options.isDocument?.(file))
|
|
48
60
|
keep(file);
|
|
49
61
|
};
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
folders[folder.id] = folder;
|
|
59
|
-
for (const file of await source.children(folder.id)) {
|
|
60
|
-
if (++discovered > MAX_ENTRIES)
|
|
61
|
-
throw tooManyEntries();
|
|
62
|
-
if (isFolder(file)) {
|
|
63
|
-
container(file);
|
|
64
|
-
await crawl(file, new Set([...ancestry, folder.id]));
|
|
65
|
-
}
|
|
66
|
-
else
|
|
67
|
-
keep(file);
|
|
68
|
-
}
|
|
69
|
-
};
|
|
70
|
-
let finalCursor = cursor;
|
|
71
|
-
if (initial) {
|
|
72
|
-
files.clear();
|
|
73
|
-
const walk = resumed ?? {
|
|
62
|
+
// A folder the last finished pass walked keeps its subtree: a round lists only its direct children, and the
|
|
63
|
+
// source's changes name what changed below them. A new, restored or moved-in folder is walked in full.
|
|
64
|
+
const walked = (id) => !initial && state.folders[id] !== undefined && !state.folders[id]?.trashed;
|
|
65
|
+
let walk = resumed;
|
|
66
|
+
let cursor = state.cursor ?? "";
|
|
67
|
+
if (!walk && initial) {
|
|
68
|
+
const start = await source.startToken();
|
|
69
|
+
walk = {
|
|
74
70
|
scope,
|
|
75
|
-
cursor,
|
|
71
|
+
cursor: start,
|
|
76
72
|
stack: [...roots].reverse().map((id) => ({ id, ancestry: [] })),
|
|
77
73
|
visited: [],
|
|
78
74
|
folders: {},
|
|
79
75
|
files: [],
|
|
80
76
|
discovered: 0,
|
|
81
77
|
};
|
|
82
|
-
for (const id of walk.visited)
|
|
83
|
-
visited.add(id);
|
|
84
|
-
Object.assign(folders, walk.folders);
|
|
85
|
-
for (const file of walk.files) {
|
|
86
|
-
files.set(file.id, file);
|
|
87
|
-
changed.add(file.id);
|
|
88
|
-
}
|
|
89
|
-
discovered = walk.discovered;
|
|
90
|
-
let savedAt = (options.now ?? Date.now)();
|
|
91
|
-
const record = () => {
|
|
92
|
-
walks?.save({ ...walk, visited: [...visited], folders, files: [...files.values()], discovered });
|
|
93
|
-
savedAt = (options.now ?? Date.now)();
|
|
94
|
-
};
|
|
95
|
-
try {
|
|
96
|
-
for (let step = walk.stack.at(-1); step; step = walk.stack.at(-1)) {
|
|
97
|
-
if (step.ancestry.includes(step.id))
|
|
98
|
-
throw new CliError("invalid_response", "folder traversal contains a cycle");
|
|
99
|
-
if (visited.has(step.id)) {
|
|
100
|
-
walk.stack.pop();
|
|
101
|
-
continue;
|
|
102
|
-
}
|
|
103
|
-
const folder = step.folder ?? (await source.metadata(step.id));
|
|
104
|
-
if (!step.folder && (!isFolder(folder) || folder.trashed))
|
|
105
|
-
throw new CliError("validation_error", "configured root is not an accessible folder");
|
|
106
|
-
if (!step.folder)
|
|
107
|
-
container(folder);
|
|
108
|
-
const children = await source.children(folder.id);
|
|
109
|
-
if (discovered + children.length > MAX_ENTRIES)
|
|
110
|
-
throw tooManyEntries();
|
|
111
|
-
discovered += children.length;
|
|
112
|
-
walk.stack.pop();
|
|
113
|
-
visited.add(folder.id);
|
|
114
|
-
folders[folder.id] = folder;
|
|
115
|
-
const nested = [];
|
|
116
|
-
for (const file of children)
|
|
117
|
-
if (isFolder(file)) {
|
|
118
|
-
container(file);
|
|
119
|
-
nested.push({ id: file.id, ancestry: [...step.ancestry, folder.id], folder: file });
|
|
120
|
-
}
|
|
121
|
-
else
|
|
122
|
-
keep(file);
|
|
123
|
-
for (const entry of nested.reverse())
|
|
124
|
-
walk.stack.push(entry);
|
|
125
|
-
if ((options.now ?? Date.now)() - savedAt > SAVE_EVERY_MS)
|
|
126
|
-
record();
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
catch (error) {
|
|
130
|
-
record();
|
|
131
|
-
throw error;
|
|
132
|
-
}
|
|
133
78
|
}
|
|
134
|
-
else {
|
|
79
|
+
else if (!walk) {
|
|
135
80
|
const page = await source.changes(cursor);
|
|
136
|
-
finalCursor = page.cursor;
|
|
137
81
|
const latest = new Map(page.items.map((change) => [change.id, change]));
|
|
138
82
|
const entering = [];
|
|
139
83
|
// Apply all ancestry changes before classifying document scope.
|
|
140
84
|
for (const change of latest.values()) {
|
|
141
85
|
if (change.removed || change.file?.trashed) {
|
|
142
|
-
|
|
86
|
+
drop(change.id);
|
|
143
87
|
if (folders[change.id])
|
|
144
88
|
folders[change.id] = { ...folders[change.id], trashed: true };
|
|
145
89
|
}
|
|
@@ -171,10 +115,126 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
171
115
|
folders[root] = { ...previous, trashed: true };
|
|
172
116
|
}
|
|
173
117
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
118
|
+
const stack = entering
|
|
119
|
+
.filter((folder) => within(folder, roots, folders))
|
|
120
|
+
.reverse()
|
|
121
|
+
.map((folder) => ({ id: folder.id, ancestry: [], folder }));
|
|
122
|
+
if (stack.length)
|
|
123
|
+
walk = {
|
|
124
|
+
scope: changesScope(scope, cursor),
|
|
125
|
+
cursor: page.cursor,
|
|
126
|
+
stack,
|
|
127
|
+
visited: [],
|
|
128
|
+
folders: {},
|
|
129
|
+
files: [],
|
|
130
|
+
discovered: 0,
|
|
131
|
+
};
|
|
132
|
+
else
|
|
133
|
+
cursor = page.cursor;
|
|
177
134
|
}
|
|
135
|
+
const vanished = async (id) => {
|
|
136
|
+
try {
|
|
137
|
+
return (await source.metadata(id)).trashed;
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
return errorOf(error).code === "not_found";
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
let found = [];
|
|
144
|
+
if (walk) {
|
|
145
|
+
const visited = new Set(walk.visited);
|
|
146
|
+
Object.assign(folders, walk.folders);
|
|
147
|
+
for (const file of walk.files) {
|
|
148
|
+
if (file.trashed)
|
|
149
|
+
drop(file.id);
|
|
150
|
+
else
|
|
151
|
+
keep(file);
|
|
152
|
+
}
|
|
153
|
+
cursor = walk.cursor;
|
|
154
|
+
const now = options.now ?? Date.now;
|
|
155
|
+
let savedAt = now();
|
|
156
|
+
const current = walk;
|
|
157
|
+
const record = () => {
|
|
158
|
+
walks?.save({ ...current, visited: [...visited], folders, files: [...delta.values()] });
|
|
159
|
+
savedAt = now();
|
|
160
|
+
};
|
|
161
|
+
let spent = 0;
|
|
162
|
+
let listed = 0;
|
|
163
|
+
let stopped = null;
|
|
164
|
+
try {
|
|
165
|
+
for (let step = walk.stack.at(-1); step; step = walk.stack.at(-1)) {
|
|
166
|
+
if (step.ancestry.includes(step.id))
|
|
167
|
+
throw new CliError("invalid_response", "folder traversal contains a cycle");
|
|
168
|
+
if (visited.has(step.id)) {
|
|
169
|
+
walk.stack.pop();
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
// One folder at least per call, so a folder with more children than the bound still gets listed.
|
|
173
|
+
stopped = listed > 0 && spent >= maxEntries ? "entries" : (budget?.take() ?? null);
|
|
174
|
+
if (stopped)
|
|
175
|
+
break;
|
|
176
|
+
const folder = step.folder ?? (await source.metadata(step.id));
|
|
177
|
+
if (!step.folder && (!isFolder(folder) || folder.trashed))
|
|
178
|
+
throw new CliError("validation_error", "configured root is not an accessible folder");
|
|
179
|
+
if (!step.folder)
|
|
180
|
+
container(folder);
|
|
181
|
+
let children;
|
|
182
|
+
try {
|
|
183
|
+
children = await source.children(folder.id);
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
// Deleted or unshared since the walk saved it: gone, with what is below it, instead of failing every sync.
|
|
187
|
+
// A listing's 404 alone can be passing, so the folder is read again and is gone only when that read is a
|
|
188
|
+
// 404 too or finds it trashed; on any doubt the call fails and the next sync lists it again.
|
|
189
|
+
if (errorOf(error).code !== "not_found" || !(await vanished(folder.id)))
|
|
190
|
+
throw error;
|
|
191
|
+
walk.stack.pop();
|
|
192
|
+
visited.add(folder.id);
|
|
193
|
+
folders[folder.id] = { ...folder, trashed: true };
|
|
194
|
+
drop(folder.id);
|
|
195
|
+
spent++;
|
|
196
|
+
listed++;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
spent += 1 + children.length;
|
|
200
|
+
listed++;
|
|
201
|
+
walk.discovered += children.length;
|
|
202
|
+
walk.stack.pop();
|
|
203
|
+
visited.add(folder.id);
|
|
204
|
+
folders[folder.id] = folder;
|
|
205
|
+
const nested = [];
|
|
206
|
+
for (const file of children)
|
|
207
|
+
if (isFolder(file)) {
|
|
208
|
+
container(file);
|
|
209
|
+
if (walked(file.id))
|
|
210
|
+
folders[file.id] = file;
|
|
211
|
+
else
|
|
212
|
+
nested.push({ id: file.id, ancestry: [...step.ancestry, folder.id], folder: file });
|
|
213
|
+
}
|
|
214
|
+
else
|
|
215
|
+
keep(file);
|
|
216
|
+
for (const entry of nested.reverse())
|
|
217
|
+
walk.stack.push(entry);
|
|
218
|
+
if (now() - savedAt > SAVE_EVERY_MS)
|
|
219
|
+
record();
|
|
220
|
+
}
|
|
221
|
+
if (stopped) {
|
|
222
|
+
record();
|
|
223
|
+
return {
|
|
224
|
+
walk: { folders_left: walk.stack.length, entries: walk.discovered, listed, stopped },
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
// Listed once the walk is done: a call the walk does not finish would read it for nothing.
|
|
228
|
+
if (query?.mode === "include" && query.list)
|
|
229
|
+
found = await query.list();
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
record();
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
else if (query?.mode === "include" && query.list)
|
|
237
|
+
found = await query.list();
|
|
178
238
|
const matched = new Set();
|
|
179
239
|
for (const file of found) {
|
|
180
240
|
if ((isFolder(file) && !options.isDocument?.(file)) ||
|
|
@@ -182,8 +242,6 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
182
242
|
!query?.matches(file) ||
|
|
183
243
|
matched.has(file.id))
|
|
184
244
|
continue;
|
|
185
|
-
if (!files.has(file.id) && ++discovered > MAX_ENTRIES)
|
|
186
|
-
throw tooManyEntries();
|
|
187
245
|
// Listed again on every sync, so only a new or changed file is work; a skipped one keeps its skip.
|
|
188
246
|
const prior = state.documents[file.id]?.metadata ?? state.skipped.find((item) => item.id === file.id)?.file;
|
|
189
247
|
if (initial || !prior || changedSince(prior, file))
|
|
@@ -219,7 +277,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
219
277
|
jobs.push({ id, kind: "save", file });
|
|
220
278
|
}
|
|
221
279
|
}
|
|
222
|
-
for (const id of
|
|
280
|
+
for (const id of Object.keys(state.documents)) {
|
|
223
281
|
const file = files.get(id);
|
|
224
282
|
if (!file || !inScope(file, roots, folders, matched, query))
|
|
225
283
|
jobs.push({ id, kind: "remove" });
|
|
@@ -227,11 +285,13 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
227
285
|
// Only retain metadata for selected ancestry; the account-wide feed includes unrelated folders.
|
|
228
286
|
const scopedFolders = Object.fromEntries(Object.entries(folders).filter(([, file]) => within(file, roots, folders) || roots.includes(file.id)));
|
|
229
287
|
return {
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
288
|
+
pending: {
|
|
289
|
+
scope,
|
|
290
|
+
cursor,
|
|
291
|
+
folders: scopedFolders,
|
|
292
|
+
jobs,
|
|
293
|
+
skipped,
|
|
294
|
+
...(query?.mode === "include" ? { matched: [...matched] } : {}),
|
|
295
|
+
},
|
|
236
296
|
};
|
|
237
297
|
};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import type { Deadline } from "../../background/budget.js";
|
|
2
3
|
import type { DocumentSource, SourceFile, SourceIndex, SourceSkip, SourceStatePort } from "../../documents/model.js";
|
|
3
4
|
import type { SourceQuery } from "../../documents/scope.js";
|
|
4
5
|
export interface SyncOptions<M extends SourceFile> {
|
|
@@ -10,8 +11,20 @@ export interface SyncOptions<M extends SourceFile> {
|
|
|
10
11
|
query?: SourceQuery<M>;
|
|
11
12
|
textLimit: number;
|
|
12
13
|
max: number;
|
|
14
|
+
/**
|
|
15
|
+
* The entries one call walks, each folder listing counted as one too; the walk saves where it stopped and the next
|
|
16
|
+
* sync goes on from there, so a tree of any size is synced over several calls.
|
|
17
|
+
*/
|
|
13
18
|
maxEntries: number;
|
|
19
|
+
/** @deprecated No longer used: a walk past `maxEntries` stops and goes on in the next sync instead of failing. */
|
|
14
20
|
limitError?(): CliError;
|
|
21
|
+
/** Asked before each folder listing and each file read: a stop ends the call with its work saved. */
|
|
22
|
+
budget?: {
|
|
23
|
+
take(): "requests" | "deadline" | "cancelled" | null;
|
|
24
|
+
readonly stopped?: string | null;
|
|
25
|
+
};
|
|
26
|
+
/** The run's hard limit: the word index at the end of a sync stops before it, less its margin. */
|
|
27
|
+
deadline?: Deadline;
|
|
15
28
|
isFolder(file: M): boolean;
|
|
16
29
|
/**
|
|
17
30
|
* A folder that is a document too, such as a wiki page with sub-pages: walked for its children and imported
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { SourceFile } from "../../documents/model.js";
|
|
2
|
+
import { type WalkStop } from "./plan.js";
|
|
2
3
|
import type { SyncOptions } from "./ports.js";
|
|
3
4
|
export interface SyncResult {
|
|
4
5
|
saved: number;
|
|
@@ -19,5 +20,15 @@ export interface SyncResult {
|
|
|
19
20
|
message: string;
|
|
20
21
|
}[];
|
|
21
22
|
coverage: string;
|
|
23
|
+
/** The pass is done: the folder walk finished and no operation is left for another sync. */
|
|
24
|
+
complete: boolean;
|
|
25
|
+
/** Why this call stopped before the pass's end: its entry bound (`maxEntries`) or its request budget. */
|
|
26
|
+
stopped?: WalkStop;
|
|
27
|
+
/** A folder walk still under way; the next sync goes on from where this one stopped. */
|
|
28
|
+
walk?: {
|
|
29
|
+
folders_left: number;
|
|
30
|
+
entries: number;
|
|
31
|
+
listed: number;
|
|
32
|
+
};
|
|
22
33
|
}
|
|
23
34
|
export declare const syncDocuments: <M extends SourceFile>(options: SyncOptions<M>) => Promise<SyncResult>;
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
3
|
+
import { deadlineMargin } from "../../background/budget.js";
|
|
3
4
|
import { catalogFiles } from "../../documents/catalog.js";
|
|
4
5
|
import { inScope } from "../../documents/scope.js";
|
|
5
6
|
import { changedSince, planDocuments, scopeHash } from "./plan.js";
|
|
6
7
|
const MAX_PICTURE_BYTES = 25 * 1024 * 1024;
|
|
7
8
|
const SAVE_EVERY_MS = 2000;
|
|
8
9
|
const SAVE_EVERY_ITEMS = 25;
|
|
10
|
+
const SETTLE_MS = 10_000;
|
|
9
11
|
const isPicture = (file) => file.mime.startsWith("image/") && file.canDownload;
|
|
10
12
|
const hashText = (text) => createHash("sha256").update(text).digest("hex");
|
|
11
13
|
export const syncDocuments = async (options) => {
|
|
@@ -25,6 +27,7 @@ export const syncDocuments = async (options) => {
|
|
|
25
27
|
pending: 0,
|
|
26
28
|
skipped: [],
|
|
27
29
|
errors: [],
|
|
30
|
+
complete: true,
|
|
28
31
|
coverage: query?.mode === "include"
|
|
29
32
|
? "selected folders and the files a saved query finds; unsupported files are reported"
|
|
30
33
|
: query?.mode === "exclude"
|
|
@@ -44,18 +47,37 @@ export const syncDocuments = async (options) => {
|
|
|
44
47
|
if (state.principal !== principal)
|
|
45
48
|
throw new CliError("configuration_error", "sync state belongs to another source account");
|
|
46
49
|
const currentScope = scopeHash(profile.roots, query, options.isDocument !== undefined);
|
|
47
|
-
|
|
48
|
-
|
|
50
|
+
if (state.pending && (state.pending.scope !== currentScope || rescan)) {
|
|
51
|
+
// Work the new plan cannot see: a file saved to the index before its state was.
|
|
52
|
+
for (const job of state.pending.jobs)
|
|
53
|
+
if (!state.documents[job.id]) {
|
|
54
|
+
await index.remove(profile.principal, job.id);
|
|
55
|
+
statePort.removeSnapshot(job.id);
|
|
56
|
+
}
|
|
49
57
|
delete state.pending;
|
|
58
|
+
// Saved at once: a call the walk cuts short would otherwise find the old batch again and repeat these removals.
|
|
59
|
+
statePort.save(state);
|
|
60
|
+
}
|
|
61
|
+
// A rescan starts the walk over, a saved one included; the cursor is dropped on disk, so the syncs after it
|
|
62
|
+
// continue the walk until it ends.
|
|
50
63
|
if (rescan) {
|
|
51
64
|
delete state.cursor;
|
|
52
65
|
statePort.removeWalk();
|
|
66
|
+
statePort.save(state);
|
|
53
67
|
}
|
|
54
68
|
if (!state.pending) {
|
|
55
|
-
|
|
69
|
+
const plan = await planDocuments(options, source, state, profile.roots, limit, profile.picture_search ?? false, {
|
|
56
70
|
read: (scope) => statePort.readWalk(scope),
|
|
57
71
|
save: (walk) => statePort.saveWalk(walk),
|
|
58
72
|
});
|
|
73
|
+
if ("walk" in plan) {
|
|
74
|
+
result.complete = false;
|
|
75
|
+
result.stopped = plan.walk.stopped;
|
|
76
|
+
result.walk = { folders_left: plan.walk.folders_left, entries: plan.walk.entries, listed: plan.walk.listed };
|
|
77
|
+
result.skipped = state.skipped.map(({ id, reason }) => ({ id, reason }));
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
state.pending = plan.pending;
|
|
59
81
|
state.skipped = state.pending.skipped;
|
|
60
82
|
statePort.save(state);
|
|
61
83
|
statePort.removeWalk();
|
|
@@ -144,6 +166,11 @@ export const syncDocuments = async (options) => {
|
|
|
144
166
|
else {
|
|
145
167
|
if (!source)
|
|
146
168
|
throw new CliError("configuration_error", "a pending save requires source sign-in");
|
|
169
|
+
const stop = options.budget?.take();
|
|
170
|
+
if (stop) {
|
|
171
|
+
result.stopped = stop;
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
147
174
|
const content = await source.content(job.id, limit);
|
|
148
175
|
const listed = query?.mode === "include" && (pending.matched?.includes(job.id) ?? query.matches(content.metadata));
|
|
149
176
|
if (!listed && !inScope(content.metadata, profile.roots, pending.folders, new Set(), query)) {
|
|
@@ -205,6 +232,7 @@ export const syncDocuments = async (options) => {
|
|
|
205
232
|
}
|
|
206
233
|
flush();
|
|
207
234
|
result.pending = pending.jobs.length;
|
|
235
|
+
result.complete = !pending.jobs.length;
|
|
208
236
|
if (!pending.jobs.length) {
|
|
209
237
|
state.cursor = pending.cursor;
|
|
210
238
|
state.scope = pending.scope;
|
|
@@ -217,6 +245,16 @@ export const syncDocuments = async (options) => {
|
|
|
217
245
|
state.lastSync = new Date(now()).toISOString();
|
|
218
246
|
statePort.save(state);
|
|
219
247
|
}
|
|
248
|
+
// A reader that cannot write finds the text by its words only once it is indexed; a search that can write does it
|
|
249
|
+
// itself, so what this bound leaves, or a failure here, is indexed by the next one. Skipped after a stop, and kept
|
|
250
|
+
// inside the run's deadline less its margin, so the partial answer and its next step still reach the caller.
|
|
251
|
+
// Real time: `now` may be fixed.
|
|
252
|
+
const settleFrom = Date.now();
|
|
253
|
+
const settleUntil = Math.min(settleFrom + SETTLE_MS, options.deadline ? options.deadline.endsAt - deadlineMargin(options.deadline) : Number.POSITIVE_INFINITY);
|
|
254
|
+
if (!result.stopped && !options.budget?.stopped && settleUntil > settleFrom)
|
|
255
|
+
await index
|
|
256
|
+
.settle?.({ until: () => signal?.aborted === true || Date.now() >= settleUntil })
|
|
257
|
+
.catch(() => undefined);
|
|
220
258
|
return result;
|
|
221
259
|
}
|
|
222
260
|
finally {
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
+
error?: undefined;
|
|
17
18
|
chatId: string;
|
|
18
19
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
19
20
|
algorithm: string;
|
|
20
21
|
fetchedAt: string | null;
|
|
21
22
|
source: string;
|
|
22
|
-
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
|
@@ -30,7 +30,8 @@ export interface CatalogEntry extends CatalogInput {
|
|
|
30
30
|
export declare const CATALOG_QUERY: import("@wirecat/cli-base/query").QueryRegistry;
|
|
31
31
|
export interface CatalogQuery {
|
|
32
32
|
ast?: QueryAst;
|
|
33
|
-
parent
|
|
33
|
+
/** A direct parent's external ID, or several: an entry under any of them. */
|
|
34
|
+
parent?: string | string[];
|
|
34
35
|
kind?: CatalogInput["kind"];
|
|
35
36
|
mime?: string;
|
|
36
37
|
search?: string;
|
|
@@ -205,7 +205,10 @@ export const catalogStoreOver = ({ database, now }) => {
|
|
|
205
205
|
const actorSql = "json_each(d.metadata, '$.catalog.folded.people')";
|
|
206
206
|
const tagSql = "SELECT 1 FROM taggings g JOIN resolved_tags t ON t.id=g.tag_id WHERE g.taggable_type='document' AND g.taggable_id=d.id AND t.name=?";
|
|
207
207
|
const tag = (name) => canonicalTagNamed(database, name)?.name ?? normalizeTag(name);
|
|
208
|
-
|
|
208
|
+
// Several parents in one json_each per entry: an OR of one EXISTS each read the entry's parents once per parent.
|
|
209
|
+
if (Array.isArray(query.parent))
|
|
210
|
+
add("EXISTS(SELECT 1 FROM json_each(d.metadata, '$.catalog.parents') WHERE value IN (SELECT value FROM json_each(?)))", JSON.stringify(query.parent.map((parent) => field(parent))));
|
|
211
|
+
else if (query.parent !== undefined)
|
|
209
212
|
add("EXISTS(SELECT 1 FROM json_each(d.metadata, '$.catalog.parents') WHERE value=?)", query.parent);
|
|
210
213
|
if (query.kind !== undefined)
|
|
211
214
|
add("json_extract(d.metadata, '$.catalog.kind')=?", query.kind);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ResolvedNode } from "../../search/lucene/resolved.js";
|
|
2
2
|
import type { Stemmer } from "../../search/stem.js";
|
|
3
|
-
import type
|
|
3
|
+
import { type SqlValue } from "../driver.js";
|
|
4
4
|
import { type DocumentPictureStore } from "./document-pictures.js";
|
|
5
5
|
import { type NoteIndexState } from "./note-index.js";
|
|
6
6
|
import { type Note } from "./notes.js";
|
|
@@ -112,6 +112,15 @@ export interface NoteSearch extends DocumentPictureStore {
|
|
|
112
112
|
hasMore: boolean;
|
|
113
113
|
}>;
|
|
114
114
|
indexState(): Promise<NoteIndexState | undefined>;
|
|
115
|
+
/**
|
|
116
|
+
* Indexes the documents and notes written since the last search, so a reader that cannot write finds them by their
|
|
117
|
+
* words. The queue is the store's own, shared by every tool that writes to it, not only the caller's rows. Works a
|
|
118
|
+
* batch of 50 at a time and yields between batches, so `until` (a deadline, a signal) is asked often; 0 under a
|
|
119
|
+
* read-only store.
|
|
120
|
+
*/
|
|
121
|
+
indexWritten(options?: {
|
|
122
|
+
until?: () => boolean;
|
|
123
|
+
}): Promise<number>;
|
|
115
124
|
/** Live notes' chunks with no vector of `model`, by hash from `after`, each with its text cut again. */
|
|
116
125
|
chunksToEmbed(model: string, options: {
|
|
117
126
|
after?: string;
|
|
@@ -4,13 +4,14 @@ import { fuseRanked } from "../../search/fusion.js";
|
|
|
4
4
|
import { compileAutomaton, foldRegex, wildcardPattern, } from "../../search/lucene/automaton.js";
|
|
5
5
|
import { isStemmed } from "../../search/lucene/resolved.js";
|
|
6
6
|
import { exhausted, outOfTime, QUERY_LIMITS, searchError } from "../../search/lucene/types.js";
|
|
7
|
+
import { isQueryOnly } from "../driver.js";
|
|
7
8
|
import { normalize } from "../normalize.js";
|
|
8
9
|
import { contextDocumentTime } from "./context-document-source.js";
|
|
9
10
|
import { documentPicturesOver } from "./document-pictures.js";
|
|
10
11
|
import { ENRICHMENT_POSITION, enrichmentText } from "./enrichments.js";
|
|
11
12
|
import { linkKind } from "./link-kinds.js";
|
|
12
13
|
import { prefixOf } from "./lucene.js";
|
|
13
|
-
import { drainNoteIndex, noteIndexState, noteIndexText } from "./note-index.js";
|
|
14
|
+
import { drainCorpus, drainNoteIndex, fillTrigrams, CORPORA as INDEXED, noteIndexState, noteIndexText, } from "./note-index.js";
|
|
14
15
|
import { documentOf, noteOf } from "./notes.js";
|
|
15
16
|
import { stemmerCache } from "./stems.js";
|
|
16
17
|
import { canonicalTagNamed } from "./tags.js";
|
|
@@ -336,6 +337,7 @@ export const searchCorpus = (context, query, corpus) => {
|
|
|
336
337
|
});
|
|
337
338
|
};
|
|
338
339
|
const SCAN_PAGE = 5_000;
|
|
340
|
+
const SETTLE_BATCH = 50;
|
|
339
341
|
/** The live documents and notes of a chunk scan, narrowed by folder and source. */
|
|
340
342
|
const LIVE = "((k.chunkable_type = 'document' AND EXISTS (SELECT 1 FROM documents d WHERE d.id = k.chunkable_id AND d.deleted_at IS NULL AND coalesce(json_extract(d.metadata, '$.catalog.active'), 1)=1 " +
|
|
341
343
|
"AND (? IS NULL OR d.account_id IN (SELECT CAST(value AS INTEGER) FROM json_each(?))))) " +
|
|
@@ -367,6 +369,38 @@ export const noteSearchOver = (context) => {
|
|
|
367
369
|
return matchingNoteRefs(context, query);
|
|
368
370
|
},
|
|
369
371
|
indexState: async () => noteIndexState(database),
|
|
372
|
+
indexWritten: async ({ until = () => false } = {}) => {
|
|
373
|
+
if (isQueryOnly(database))
|
|
374
|
+
return 0;
|
|
375
|
+
// One batch per step: a step's own `until` lets it run once, so every corpus moves on each round.
|
|
376
|
+
const once = () => {
|
|
377
|
+
let ran = false;
|
|
378
|
+
return () => {
|
|
379
|
+
const stop = ran;
|
|
380
|
+
ran = true;
|
|
381
|
+
return stop;
|
|
382
|
+
};
|
|
383
|
+
};
|
|
384
|
+
const steps = [
|
|
385
|
+
() => drainCorpus(database, INDEXED.document, stemmerFor, { batch: SETTLE_BATCH, until: once() }),
|
|
386
|
+
() => drainCorpus(database, INDEXED.note, stemmerFor, { batch: SETTLE_BATCH, until: once() }),
|
|
387
|
+
() => fillTrigrams(database, { batch: SETTLE_BATCH, until: once() }),
|
|
388
|
+
];
|
|
389
|
+
let total = 0;
|
|
390
|
+
for (;;) {
|
|
391
|
+
let done = 0;
|
|
392
|
+
for (const step of steps) {
|
|
393
|
+
if (until())
|
|
394
|
+
return total;
|
|
395
|
+
done += step();
|
|
396
|
+
}
|
|
397
|
+
total += done;
|
|
398
|
+
if (done === 0)
|
|
399
|
+
return total;
|
|
400
|
+
// A synchronous drain would hide an abort or a timer until it ends.
|
|
401
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
402
|
+
}
|
|
403
|
+
},
|
|
370
404
|
chunksToEmbed: async (model, { after, limit }) => {
|
|
371
405
|
drain();
|
|
372
406
|
const scope = live(undefined, undefined);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.669.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",
|