@wirecat/cli-core 0.687.0 → 0.689.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/documents/index.d.ts +1 -0
  4. package/dist/cli/documents/index.js +1 -0
  5. package/dist/cli/documents/library.d.ts +107 -0
  6. package/dist/cli/documents/library.js +514 -0
  7. package/dist/cli/documents/testing/source-contract.d.ts +11 -6
  8. package/dist/cli/documents/testing/source-contract.js +54 -23
  9. package/dist/cli/documents/testing/source.d.ts +11 -3
  10. package/dist/cli/documents/testing/source.js +15 -10
  11. package/dist/cli/documents/words.d.ts +1 -1
  12. package/dist/cli/envelope.js +2 -3
  13. package/dist/cli/meeting-batch.js +5 -1
  14. package/dist/cli/meeting-passage-text.d.ts +1 -1
  15. package/dist/cli/meeting-passage-text.js +3 -5
  16. package/dist/cli/messenger/conversations-command.js +4 -0
  17. package/dist/cli/messenger/messages-search-command.js +6 -1
  18. package/dist/cli/messenger/search-answers.js +2 -0
  19. package/dist/cli/search-left-out.d.ts +3 -0
  20. package/dist/cli/search-left-out.js +12 -0
  21. package/dist/cli/store-settings.js +23 -4
  22. package/dist/cli/untrusted-marks.d.ts +2 -0
  23. package/dist/cli/untrusted-marks.js +6 -0
  24. package/dist/crm/cli/files.d.ts +68 -0
  25. package/dist/crm/cli/files.js +616 -0
  26. package/dist/crm/cli/index.d.ts +1 -0
  27. package/dist/crm/cli/index.js +3 -0
  28. package/dist/crm/cli/search-all.js +3 -2
  29. package/dist/crm/file-fetch.d.ts +15 -0
  30. package/dist/crm/file-fetch.js +61 -0
  31. package/dist/crm/index.d.ts +1 -0
  32. package/dist/crm/index.js +1 -0
  33. package/dist/crm/testing/files-contract.d.ts +17 -0
  34. package/dist/crm/testing/files-contract.js +142 -0
  35. package/dist/crm/testing/index.d.ts +1 -0
  36. package/dist/crm/testing/index.js +1 -0
  37. package/dist/crm/testing/source.d.ts +5 -0
  38. package/dist/crm/testing/source.js +3 -1
  39. package/dist/documents/index.d.ts +3 -1
  40. package/dist/documents/index.js +2 -0
  41. package/dist/documents/model.d.ts +20 -6
  42. package/dist/documents/model.js +2 -1
  43. package/dist/entities/hit.d.ts +3 -3
  44. package/dist/entities/hit.js +14 -3
  45. package/dist/entities/index.d.ts +1 -1
  46. package/dist/errors/reasons.d.ts +1 -1
  47. package/dist/errors/reasons.js +23 -1
  48. package/dist/files/safe-name.d.ts +2 -1
  49. package/dist/files/safe-name.js +21 -3
  50. package/dist/meetings/mcp/passage.d.ts +6 -2
  51. package/dist/meetings/mcp/passage.js +7 -3
  52. package/dist/resolve.d.ts +1 -1
  53. package/dist/resolve.js +1 -1
  54. package/dist/search/account-list.d.ts +2 -0
  55. package/dist/search/account-list.js +32 -4
  56. package/dist/search/respell.d.ts +10 -0
  57. package/dist/search/respell.js +63 -0
  58. package/dist/search/stem.d.ts +16 -3
  59. package/dist/search/stem.js +32 -4
  60. package/dist/services/documents/file-text.d.ts +13 -0
  61. package/dist/services/documents/file-text.js +33 -0
  62. package/dist/services/documents/plan.d.ts +3 -2
  63. package/dist/services/documents/plan.js +50 -16
  64. package/dist/services/documents/ports.d.ts +2 -2
  65. package/dist/services/documents/sync.js +2 -2
  66. package/dist/services/embeddings-search.js +169 -141
  67. package/dist/services/embeddings.d.ts +8 -0
  68. package/dist/services/message-resolution.d.ts +1 -1
  69. package/dist/services/message-resolution.js +1 -1
  70. package/dist/services/messages-archive-search.js +55 -3
  71. package/dist/services/messages-search.d.ts +2 -1
  72. package/dist/services/messages-search.js +19 -7
  73. package/dist/services/messages.d.ts +8 -0
  74. package/dist/services/metadata.d.ts +1 -1
  75. package/dist/services/named-chat.d.ts +20 -0
  76. package/dist/services/named-chat.js +63 -0
  77. package/dist/services/search-all.d.ts +7 -2
  78. package/dist/services/search-all.js +35 -1
  79. package/dist/store/exports.d.ts +1 -1
  80. package/dist/store/exports.js +1 -1
  81. package/dist/store/search-index.d.ts +2 -0
  82. package/dist/store/search-index.js +1 -0
  83. package/dist/store/sqlite/crm-files.d.ts +3 -0
  84. package/dist/store/sqlite/crm-files.js +2 -0
  85. package/dist/store/sqlite/crm-settings.d.ts +42 -1
  86. package/dist/store/sqlite/crm-settings.js +46 -2
  87. package/dist/store/sqlite/lucene-fields.d.ts +2 -0
  88. package/dist/store/sqlite/lucene-fields.js +6 -2
  89. package/dist/store/sqlite/lucene.js +2 -2
  90. package/dist/store/sqlite/manifest.js +2 -0
  91. package/dist/store/sqlite/migrations.generated.js +20 -0
  92. package/dist/store/sqlite/schema.d.ts +169 -0
  93. package/dist/store/sqlite/schema.js +18 -0
  94. package/dist/store/sqlite/stems.d.ts +2 -0
  95. package/dist/store/sqlite/stems.js +5 -0
  96. package/dist/store/sqlite/vectors.d.ts +26 -1
  97. package/dist/store/sqlite/vectors.js +72 -15
  98. package/dist/store/vectors.js +6 -2
  99. package/package.json +2 -2
@@ -135,6 +135,10 @@ const accountsOfWord = (word, held, context) => {
135
135
  return [...held];
136
136
  if (wanted === "personal" || wanted === "bots")
137
137
  return held.filter((one) => listedHolds(one, "messages") && isBotProvider(one.provider) === (wanted === "bots"));
138
+ // Drive and Notion accounts are stored and searched as notes folders, so their kind stays `notes`; the word still
139
+ // names them, beside the imports whose kind is documents.
140
+ if (wanted === "documents")
141
+ return held.filter((one) => listedHolds(one, "documents") || isDocumentAccount(one));
138
142
  if (isKind(wanted))
139
143
  return held.filter((one) => listedHolds(one, wanted));
140
144
  const recorded = context.profiles[wanted];
@@ -146,6 +150,24 @@ const accountsOfWord = (word, held, context) => {
146
150
  return storedAs(held, { provider, account: "" });
147
151
  return held.filter((one) => one.provider === provider);
148
152
  };
153
+ const isDocumentAccount = ({ stored }) => stored !== undefined && isDocumentAccountProvider(stored.provider);
154
+ /** The words that name something the store holds: the groups no one saves, each kind with an account, each provider. */
155
+ const choices = (held) => {
156
+ const kinds = held.flatMap((one) => one.kinds ?? (one.kind ? [one.kind] : []));
157
+ const messengers = held.filter((one) => listedHolds(one, "messages"));
158
+ // `added` names no account by itself: the owner's added sources are found as notes.
159
+ const providers = held.flatMap(({ stored, provider }) => stored?.provider === ADDED_PROVIDER ? [] : [stored?.provider ?? provider]);
160
+ return [
161
+ ...new Set([
162
+ "all",
163
+ ...(messengers.some((one) => !isBotProvider(one.provider)) ? ["personal"] : []),
164
+ ...(messengers.some((one) => isBotProvider(one.provider)) ? ["bots"] : []),
165
+ ...kinds,
166
+ ...(held.some(isDocumentAccount) ? ["documents"] : []),
167
+ ...providers,
168
+ ]),
169
+ ].join(", ");
170
+ };
149
171
  export const keyOf = ({ provider, account }) => `${provider}\u0000${account}`;
150
172
  export const sourceOf = ({ provider, account }) => `${provider}:${account}`;
151
173
  export const sameAs = (key) => (one) => one.provider === key.provider && one.account === key.account;
@@ -161,7 +183,9 @@ export const entriesOfList = (value, context) => {
161
183
  const colon = item.indexOf(":");
162
184
  if (colon === -1) {
163
185
  try {
164
- entries.push({ entry: item, accounts: accountsOfWord(item, held, context) });
186
+ const accounts = accountsOfWord(item, held, context);
187
+ // A search that reads nothing because a word named nothing answers with the words that do name something.
188
+ entries.push({ entry: item, accounts, ...(accounts.length === 0 && !group ? { holds: choices(held) } : {}) });
165
189
  }
166
190
  catch (error) {
167
191
  if (!group || !(error instanceof CliError))
@@ -192,8 +216,9 @@ export const entriesOfList = (value, context) => {
192
216
  for (const item of itemsOf(value))
193
217
  entry(item);
194
218
  const { only } = context;
195
- return entries.map(({ entry, accounts }) => ({
219
+ return entries.map(({ entry, accounts, holds }) => ({
196
220
  entry,
221
+ ...(holds === undefined ? {} : { holds }),
197
222
  accounts: accounts
198
223
  .filter((one) => only === undefined || only.has(keyOf(one)))
199
224
  .map(({ provider, account, kind, kinds }) => ({
@@ -249,7 +274,10 @@ export const fitting = (entries, kinds, what, reasonOf = (kind) => READS[kind],
249
274
  ? { source: entry, code: "not_found", reason: UNKNOWN_PROVIDER }
250
275
  : { source: entry, code: "not_found", reason: "no account in the store" });
251
276
  }
252
- if (chosen.size === 0)
253
- fail(`--source names nothing ${what} reads: ${skipped.map(({ source, reason }) => `${source} (${reason})`).join(", ")}`);
277
+ if (chosen.size === 0) {
278
+ const words = entries.length === 1 ? entries[0]?.holds : undefined;
279
+ fail(`--source names nothing ${what} reads: ${skipped.map(({ source, reason }) => `${source} (${reason})`).join(", ")}` +
280
+ (words === undefined ? "" : ` — the store holds ${words}`));
281
+ }
254
282
  return { accounts: [...chosen.values()], skipped };
255
283
  };
@@ -0,0 +1,10 @@
1
+ import { type Vocabulary } from "./correct.js";
2
+ /** A Cyrillic word as Latin letters, the way a Latin name is written in Russian («хецнер», «ноксвел» for noxvel). */
3
+ export declare const latinSpellings: (word: string) => string[];
4
+ /**
5
+ * For each word no message holds, not even as the beginning of a longer one, the words the store does hold that it
6
+ * may stand for: its Latin spelling or the nearest known spellings of that, and only when there are none, its own
7
+ * nearest known spellings (up to two edits, as `correctWords` allows). A word any message holds is left alone, so a
8
+ * correct word never turns into another.
9
+ */
10
+ export declare const respelled: (vocabulary: Vocabulary, words: string[]) => Promise<Map<string, string[]>>;
@@ -0,0 +1,63 @@
1
+ import { normalize } from "../store/normalize.js";
2
+ import { correctWords } from "./correct.js";
3
+ const LATIN = {
4
+ а: "a",
5
+ б: "b",
6
+ в: "v",
7
+ г: "g",
8
+ д: "d",
9
+ е: "e",
10
+ ж: "zh",
11
+ з: "z",
12
+ и: "i",
13
+ к: "k",
14
+ л: "l",
15
+ м: "m",
16
+ н: "n",
17
+ о: "o",
18
+ п: "p",
19
+ р: "r",
20
+ с: "s",
21
+ т: "t",
22
+ у: "u",
23
+ ф: "f",
24
+ х: "h",
25
+ ц: "ts",
26
+ ч: "ch",
27
+ ш: "sh",
28
+ щ: "sch",
29
+ ъ: "",
30
+ ы: "y",
31
+ ь: "",
32
+ э: "e",
33
+ ю: "yu",
34
+ я: "ya",
35
+ };
36
+ /** A Cyrillic word as Latin letters, the way a Latin name is written in Russian («хецнер», «ноксвел» for noxvel). */
37
+ export const latinSpellings = (word) => {
38
+ if (!/\p{Script=Cyrillic}/u.test(word))
39
+ return [];
40
+ const plain = [...normalize(word)].map((letter) => LATIN[letter] ?? letter).join("");
41
+ return [...new Set([plain, plain.replaceAll("ks", "x")])];
42
+ };
43
+ /**
44
+ * For each word no message holds, not even as the beginning of a longer one, the words the store does hold that it
45
+ * may stand for: its Latin spelling or the nearest known spellings of that, and only when there are none, its own
46
+ * nearest known spellings (up to two edits, as `correctWords` allows). A word any message holds is left alone, so a
47
+ * correct word never turns into another.
48
+ */
49
+ export const respelled = async (vocabulary, words) => {
50
+ const known = await vocabulary.knownTerms(words);
51
+ const found = new Map();
52
+ for (const word of words.filter((one) => !known.has(one))) {
53
+ const latin = latinSpellings(word);
54
+ const held = await vocabulary.knownTerms(latin);
55
+ const nearLatin = await correctWords(vocabulary, latin.filter((one) => !held.has(one)));
56
+ const asLatin = [...new Set([...held, ...[...nearLatin.values()].flat()])];
57
+ // A Latin name found in Latin letters says what the word was; its Cyrillic neighbours are then other words.
58
+ const forms = asLatin.length ? asLatin : ((await correctWords(vocabulary, [word])).get(normalize(word)) ?? []);
59
+ if (forms.length)
60
+ found.set(word, forms);
61
+ }
62
+ return found;
63
+ };
@@ -20,6 +20,8 @@ export declare const DEFAULT_STEMMERS_VERSION = 2;
20
20
  * Between the stem sequences of one text when several Latin stemmers give different ones, so a phrase
21
21
  * never matches across two sequences. Letters and digits, so `unicode61` keeps it as one token.
22
22
  */
23
+ /** The fewest letters a searched word has for the longer words it begins to count too: `рост` finds `ростовщик`. */
24
+ export declare const START_LETTERS = 4;
23
25
  export declare const STEM_SEPARATOR = "0stemsep0";
24
26
  /** Clear-all rather than LRU: the 1M benchmark corpus holds 523k distinct words, and a Map stays cheap below this. */
25
27
  export declare const STEM_CACHE_LIMIT = 200000;
@@ -40,8 +42,13 @@ export type Stemmer = {
40
42
  indexText(text: string): string;
41
43
  /** An FTS5 expression for a text as phrases of stems, one per sequence; `undefined` when no word stems. */
42
44
  phrases(text: string): string | undefined;
43
- /** Each word of a text with its stem and the stemmer its script chose — what a search answer shows. */
44
- explain(text: string): {
45
+ /**
46
+ * Each word of a text with its stem and the stemmer its script chose — what a search answer shows. With `query`, the
47
+ * stem `phrases` searches, which keeps a word whole where its stem would be another word.
48
+ */
49
+ explain(text: string, options?: {
50
+ query?: boolean;
51
+ }): {
45
52
  word: string;
46
53
  stem: string;
47
54
  stemmer: CyrillicStemmer | LatinStemmer;
@@ -53,6 +60,12 @@ export type Stemmer = {
53
60
  * (`Москвa` with a Latin `a`) are usually homoglyph spoofing or code, and `covid19` is a name, not a word form.
54
61
  * Ukrainian and other Cyrillic languages go through the Russian stemmer — there is no language detection.
55
62
  */
56
- export declare const createStemmer: (stemmers?: Stemmers, { cacheLimit }?: {
63
+ /**
64
+ * Whether Snowball cuts a word to a stem so short that it may be another word's: «домен» → «дом», the stem of «дом»
65
+ * and «дома». The search keeps such a word whole when the stems show it is a stem itself («доменов» → «домен»).
66
+ */
67
+ export declare const cutsDeep: (stemmer: Stemmer, token: string) => boolean;
68
+ export declare const createStemmer: (stemmers?: Stemmers, { cacheLimit, whole }?: {
57
69
  cacheLimit?: number;
70
+ whole?: ReadonlySet<string>;
58
71
  }) => Stemmer;
@@ -18,6 +18,8 @@ export const DEFAULT_STEMMERS_VERSION = 2;
18
18
  * Between the stem sequences of one text when several Latin stemmers give different ones, so a phrase
19
19
  * never matches across two sequences. Letters and digits, so `unicode61` keeps it as one token.
20
20
  */
21
+ /** The fewest letters a searched word has for the longer words it begins to count too: `рост` finds `ростовщик`. */
22
+ export const START_LETTERS = 4;
21
23
  export const STEM_SEPARATOR = "0stemsep0";
22
24
  /** Clear-all rather than LRU: the 1M benchmark corpus holds 523k distinct words, and a Map stays cheap below this. */
23
25
  export const STEM_CACHE_LIMIT = 200_000;
@@ -66,7 +68,16 @@ const snowball = {
66
68
  * (`Москвa` with a Latin `a`) are usually homoglyph spoofing or code, and `covid19` is a name, not a word form.
67
69
  * Ukrainian and other Cyrillic languages go through the Russian stemmer — there is no language detection.
68
70
  */
69
- export const createStemmer = (stemmers = DEFAULT_STEMMERS, { cacheLimit = STEM_CACHE_LIMIT } = {}) => {
71
+ /**
72
+ * Whether Snowball cuts a word to a stem so short that it may be another word's: «домен» → «дом», the stem of «дом»
73
+ * and «дома». The search keeps such a word whole when the stems show it is a stem itself («доменов» → «домен»).
74
+ */
75
+ export const cutsDeep = (stemmer, token) => {
76
+ const word = [...normalize(token.normalize("NFC").toLowerCase().replace(MARKS, ""))];
77
+ const stem = [...stemmer.stemToken(token)];
78
+ return stem.length < 4 && word.length - stem.length >= 2;
79
+ };
80
+ export const createStemmer = (stemmers = DEFAULT_STEMMERS, { cacheLimit = STEM_CACHE_LIMIT, whole = new Set() } = {}) => {
70
81
  const valid = parseStemmers(stemmers);
71
82
  const cyrillic = snowball[valid.cyrillic]();
72
83
  const latinNames = valid.latin.split(",");
@@ -92,6 +103,23 @@ export const createStemmer = (stemmers = DEFAULT_STEMMERS, { cacheLimit = STEM_C
92
103
  return stem;
93
104
  };
94
105
  const stemToken = (token) => stemOf(token, 0);
106
+ const queryStemOf = (token, variant) => {
107
+ const word = normalize(token.normalize("NFC").toLowerCase().replace(MARKS, ""));
108
+ return whole.has(word) ? word : stemOf(token, variant);
109
+ };
110
+ const querySequences = (text) => {
111
+ const seen = new Set();
112
+ return latins.flatMap((_, variant) => {
113
+ const sequence = tokensOf(text)
114
+ .map((token) => queryStemOf(token, variant))
115
+ .filter(Boolean);
116
+ const key = sequence.join(" ");
117
+ if (seen.has(key))
118
+ return [];
119
+ seen.add(key);
120
+ return [sequence];
121
+ });
122
+ };
95
123
  const tokensOf = (text) => text.normalize("NFC").toLowerCase().match(TOKEN) ?? [];
96
124
  const stemSequences = (text) => {
97
125
  const tokens = tokensOf(text);
@@ -116,12 +144,12 @@ export const createStemmer = (stemmers = DEFAULT_STEMMERS, { cacheLimit = STEM_C
116
144
  .filter(Boolean)
117
145
  .join(` ${STEM_SEPARATOR} `),
118
146
  phrases: (text) => {
119
- const phrases = stemSequences(text)
147
+ const phrases = querySequences(text)
120
148
  .filter((sequence) => sequence.length > 0)
121
149
  .map((sequence) => `"${sequence.join(" ").replaceAll('"', '""')}"`);
122
150
  return phrases.length ? phrases.join(" OR ") : undefined;
123
151
  },
124
- explain: (text) => tokensOf(text).flatMap((word) => {
152
+ explain: (text, { query = false } = {}) => tokensOf(text).flatMap((word) => {
125
153
  const bare = word.replace(MARKS, "");
126
154
  const script = CYRILLIC.test(bare) ? "cyrillic" : LATIN.test(bare) ? "latin" : "none";
127
155
  const variants = script === "latin"
@@ -129,7 +157,7 @@ export const createStemmer = (stemmers = DEFAULT_STEMMERS, { cacheLimit = STEM_C
129
157
  : [{ name: script === "cyrillic" ? valid.cyrillic : "none", variant: 0 }];
130
158
  const seen = new Set();
131
159
  return variants.flatMap(({ name, variant }) => {
132
- const stem = stemOf(word, variant);
160
+ const stem = query ? queryStemOf(word, variant) : stemOf(word, variant);
133
161
  if (!stem || seen.has(stem))
134
162
  return [];
135
163
  seen.add(stem);
@@ -0,0 +1,13 @@
1
+ /** A file a documents sync reads the text of: PDF, docx, xlsx, CSV, TSV, plain text and Markdown. */
2
+ export declare const readableFile: ({ name, mime }: {
3
+ name: string;
4
+ mime: string;
5
+ }) => boolean;
6
+ /**
7
+ * The text of a downloaded file through cli-core's readers, or a `validation_error` that says why there is none, in
8
+ * words a person acts on. `command` names the CLI in the hint for a missing reader.
9
+ */
10
+ export declare const fileText: (bytes: Uint8Array, file: {
11
+ name: string;
12
+ mime: string;
13
+ }, command: string, env?: NodeJS.ProcessEnv) => Promise<string>;
@@ -0,0 +1,33 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { engineHint, extractText, importEngine, MAX_TEXT_CHARS } from "../../attachments/extract.js";
3
+ import { attachmentMaxBytes } from "../../attachments/limits.js";
4
+ const READABLE = new Set([
5
+ "application/pdf",
6
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
7
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
8
+ "text/csv",
9
+ "text/tab-separated-values",
10
+ "text/plain",
11
+ "text/markdown",
12
+ ]);
13
+ /** A file a documents sync reads the text of: PDF, docx, xlsx, CSV, TSV, plain text and Markdown. */
14
+ export const readableFile = ({ name, mime }) => READABLE.has(mime) || /\.(md|markdown|txt|pdf|docx|xlsx|csv|tsv)$/iu.test(name);
15
+ /**
16
+ * The text of a downloaded file through cli-core's readers, or a `validation_error` that says why there is none, in
17
+ * words a person acts on. `command` names the CLI in the hint for a missing reader.
18
+ */
19
+ export const fileText = async (bytes, file, command, env = process.env) => {
20
+ const read = await extractText(bytes, { kind: "document", name: file.name, mime: file.mime, path: file.name }, importEngine, undefined, env);
21
+ if (read.status === "extracted")
22
+ return read.text;
23
+ const reason = read.status === "needs-agent"
24
+ ? "file has no text layer (a scan or images only); OCR is not supported"
25
+ : read.status === "engine-missing"
26
+ ? engineHint(read.engine, command)
27
+ : read.status === "unreadable"
28
+ ? "file could not be read as text; it may be damaged or protected"
29
+ : read.status === "unsupported"
30
+ ? "file contents do not match its type"
31
+ : `file is too large for the document readers (over ${Math.round(attachmentMaxBytes(env) / 1024 / 1024)} MB, or over ${MAX_TEXT_CHARS} characters of text)`;
32
+ throw new CliError("validation_error", reason);
33
+ };
@@ -1,4 +1,4 @@
1
- import type { DocumentSource, SourceFile, SourceState, SourceWalk } from "../../documents/model.js";
1
+ import { type FeedlessDocumentSource, type SourceFile, type SourceState, type SourceWalk } from "../../documents/model.js";
2
2
  import { type SourceQuery } from "../../documents/scope.js";
3
3
  import type { SyncOptions } from "./ports.js";
4
4
  export declare const scopeHash: (roots: string[], query?: Pick<SourceQuery, "key" | "mode">, pages?: boolean) => string;
@@ -22,5 +22,6 @@ export type Plan<M extends SourceFile> = {
22
22
  } | {
23
23
  walk: WalkProgress;
24
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>>;
25
+ export declare const WALKED = "walked";
26
+ export declare const planDocuments: <M extends SourceFile>(options: SyncOptions<M>, source: FeedlessDocumentSource<M> | undefined, state: SourceState<M>, roots: string[], limit: number, pictures: boolean, walks?: WalkStore<M>) => Promise<Plan<M>>;
26
27
  export {};
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError } from "@wirecat/cli-base";
3
+ import { feedOf, } from "../../documents/model.js";
3
4
  import { inScope, within } from "../../documents/scope.js";
4
5
  // Without a query or pages the hash stays what it was, so a profile that never set them keeps its checkpoint. Turning
5
6
  // pages on changes it, so the next sync walks again and imports the pages an incremental one would never revisit.
@@ -12,6 +13,9 @@ export const changedSince = (previous, file) => previous.version !== file.versio
12
13
  previous.canDownload !== file.canDownload ||
13
14
  JSON.stringify(previous.parents) !== JSON.stringify(file.parents);
14
15
  const SAVE_EVERY_MS = 2000;
16
+ // What a pass of a source without a change feed records as its cursor: the next pass is not a first one, so it saves
17
+ // only what changed.
18
+ export const WALKED = "walked";
15
19
  // A round of changes is saved under its own scope: a CLI that validates the walk file keeps only the fields it knows,
16
20
  // and these say both what the walk is and which cursor it started from.
17
21
  const changesScope = (scope, cursor) => `${scope}:changes:${cursor}`;
@@ -47,8 +51,11 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
47
51
  if (query?.mode === "include" && !query.list)
48
52
  throw new CliError("configuration_error", "a query that includes files must list them");
49
53
  const initial = !state.cursor || scope !== state.scope;
50
- const resumed = walks?.read(initial ? scope : changesScope(scope, state.cursor));
51
- const folders = initial ? {} : structuredClone(state.folders);
54
+ // Without a feed every pass walks the whole tree again; only a first one saves every file.
55
+ const feed = feedOf(source);
56
+ const full = initial || !feed;
57
+ const resumed = walks?.read(full ? scope : changesScope(scope, state.cursor));
58
+ const folders = full ? {} : structuredClone(state.folders);
52
59
  const files = new Map(Object.values(state.documents).map((doc) => [doc.metadata.id, doc.metadata]));
53
60
  const changed = new Set();
54
61
  // What the walk saves: every file of a full walk, or what a round of changes touched, a removed file as trashed.
@@ -56,11 +63,17 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
56
63
  for (const skipped of state.skipped)
57
64
  if (skipped.file)
58
65
  files.set(skipped.id, skipped.file);
59
- if (initial)
66
+ if (full)
60
67
  files.clear();
68
+ // A pass without a feed lists every file again; only one new or changed since the last pass is work, so a file kept
69
+ // by name only is not read again each sync. A changed path (a folder renamed above it) counts as a change.
70
+ const prior = (id) => state.documents[id]?.metadata ?? state.skipped.find((item) => item.id === id)?.file;
71
+ const moved = (before, file) => JSON.stringify(before.providerMetadata ?? null) !== JSON.stringify(file.providerMetadata ?? null);
61
72
  const keep = (file) => {
62
73
  files.set(file.id, file);
63
- changed.add(file.id);
74
+ const before = feed || initial ? undefined : prior(file.id);
75
+ if (!before || changedSince(before, file) || moved(before, file))
76
+ changed.add(file.id);
64
77
  delta.set(file.id, file);
65
78
  };
66
79
  const drop = (id) => {
@@ -75,7 +88,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
75
88
  };
76
89
  // A folder the last finished pass walked keeps its subtree: a round lists only its direct children, and the
77
90
  // source's changes name what changed below them. A new, restored or moved-in folder is walked in full.
78
- const walked = (id) => !initial && state.folders[id] !== undefined && !state.folders[id]?.trashed;
91
+ const walked = (id) => !full && state.folders[id] !== undefined && !state.folders[id]?.trashed;
79
92
  let walk = resumed;
80
93
  let cursor = state.cursor ?? "";
81
94
  // Each read takes a request from the budget, the start token and a root's own metadata as much as a listing: a run
@@ -84,11 +97,11 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
84
97
  const taken = options.signal?.aborted ? "cancelled" : budget?.take();
85
98
  return taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
86
99
  };
87
- if (!walk && initial) {
100
+ if (!walk && full) {
88
101
  const before = charge();
89
102
  if (before)
90
103
  return { walk: { folders_left: roots.length, entries: 0, listed: 0, stopped: before } };
91
- const start = await source.startToken();
104
+ const start = feed ? await feed.startToken() : WALKED;
92
105
  walk = {
93
106
  scope,
94
107
  cursor: start,
@@ -105,7 +118,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
105
118
  const before = charge();
106
119
  if (before)
107
120
  return { walk: { folders_left: 0, entries: 0, listed: 0, stopped: before } };
108
- const page = await source.changes(cursor);
121
+ const page = await feed.changes(cursor);
109
122
  const latest = new Map(page.items.map((change) => [change.id, change]));
110
123
  const entering = [];
111
124
  // Apply all ancestry changes before classifying document scope.
@@ -129,7 +142,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
129
142
  for (const root of roots) {
130
143
  const previous = folders[root];
131
144
  try {
132
- const current = await source.metadata(root);
145
+ const current = await source.metadata(root, folders[root]);
133
146
  if (current.id !== root || !isFolder(current))
134
147
  throw new CliError("invalid_response", "selected folder metadata is inconsistent");
135
148
  folders[root] = current;
@@ -160,9 +173,9 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
160
173
  else
161
174
  cursor = page.cursor;
162
175
  }
163
- const vanished = async (id) => {
176
+ const vanished = async (id, known) => {
164
177
  try {
165
- return (await source.metadata(id)).trashed;
178
+ return (await source.metadata(id, known)).trashed;
166
179
  }
167
180
  catch (error) {
168
181
  return errorOf(error).code === "not_found";
@@ -210,7 +223,24 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
210
223
  if (stopped)
211
224
  break;
212
225
  if (!step.folder) {
213
- const root = await source.metadata(step.id);
226
+ const known = state.folders[step.id];
227
+ let root;
228
+ try {
229
+ root = await source.metadata(step.id, known);
230
+ }
231
+ catch (error) {
232
+ // Without a feed, a folder the last pass held and the provider no longer finds is skipped as unavailable,
233
+ // as a round of changes does, so a moved or deleted root does not fail every sync. A source with a feed
234
+ // walks in full only on a rescan, where a root it cannot read still fails and keeps what it holds.
235
+ if (feed || !known || errorOf(error).code !== "not_found")
236
+ throw error;
237
+ walk.stack.pop();
238
+ visited.add(step.id);
239
+ folders[step.id] = { ...known, trashed: true };
240
+ spent++;
241
+ listed++;
242
+ continue;
243
+ }
214
244
  if (!isFolder(root) || root.trashed)
215
245
  throw new CliError("validation_error", "configured root is not an accessible folder");
216
246
  container(root);
@@ -225,9 +255,9 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
225
255
  let more;
226
256
  try {
227
257
  if (source.childrenPage)
228
- ({ files: children, cursor: more } = await source.childrenPage(folder.id, step.listing));
258
+ ({ files: children, cursor: more } = await source.childrenPage(folder.id, step.listing, folder));
229
259
  else
230
- children = await source.children(folder.id);
260
+ children = await source.children(folder.id, folder);
231
261
  }
232
262
  catch (error) {
233
263
  if (errorOf(error).code !== "not_found")
@@ -243,7 +273,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
243
273
  // Deleted or unshared since the walk saved it: gone, with what is below it, instead of failing every sync.
244
274
  // A listing's 404 alone can be passing, so the folder is read again and is gone only when that read is a
245
275
  // 404 too or finds it trashed; on any doubt the call fails and the next sync lists it again.
246
- if (!(await vanished(folder.id)))
276
+ if (!(await vanished(folder.id, folder)))
247
277
  throw error;
248
278
  walk.stack.pop();
249
279
  visited.add(folder.id);
@@ -336,7 +366,11 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
336
366
  continue;
337
367
  }
338
368
  if (changed.has(id) || retry || known?.notRead) {
339
- if (!known || known.notRead || changedSince(known.metadata, file) || initial)
369
+ if (!known ||
370
+ known.notRead ||
371
+ changedSince(known.metadata, file) ||
372
+ initial ||
373
+ (!feed && moved(known.metadata, file)))
340
374
  jobs.push({ id, kind: "save", file });
341
375
  }
342
376
  }
@@ -1,9 +1,9 @@
1
1
  import type { CliError } from "@wirecat/cli-base";
2
2
  import type { Deadline } from "../../background/budget.js";
3
- import type { DocumentSource, SourceFile, SourceIndex, SourceSkip, SourceStatePort } from "../../documents/model.js";
3
+ import type { FeedlessDocumentSource, SourceFile, SourceIndex, SourceSkip, SourceStatePort } from "../../documents/model.js";
4
4
  import type { SourceQuery } from "../../documents/scope.js";
5
5
  export interface SyncOptions<M extends SourceFile> {
6
- source: DocumentSource<M> | undefined;
6
+ source: FeedlessDocumentSource<M> | undefined;
7
7
  index: SourceIndex<M>;
8
8
  state: SourceStatePort<M>;
9
9
  principal: string;
@@ -135,7 +135,7 @@ export const syncDocuments = async (options) => {
135
135
  const stop = ask();
136
136
  if (stop)
137
137
  return stop;
138
- const bytes = await source.bytes(file.id);
138
+ const bytes = await source.bytes(file.id, file);
139
139
  if (bytes.length > MAX_PICTURE_BYTES) {
140
140
  entry.picture = "too-large";
141
141
  result.pictures_too_large = (result.pictures_too_large ?? 0) + 1;
@@ -187,7 +187,7 @@ export const syncDocuments = async (options) => {
187
187
  result.stopped = stop;
188
188
  break;
189
189
  }
190
- const content = await source.content(job.id, limit);
190
+ const content = await source.content(job.id, limit, job.file);
191
191
  const listed = query?.mode === "include" && (pending.matched?.includes(job.id) ?? query.matches(content.metadata));
192
192
  if (!listed && !inScope(content.metadata, profile.roots, pending.folders, new Set(), query)) {
193
193
  await index.remove(profile.principal, job.id);