@wirecat/cli-core 0.603.0 → 0.604.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 CHANGED
@@ -7,6 +7,37 @@ shape of this file.
7
7
 
8
8
  ## Unreleased
9
9
 
10
+ ## 0.604.0 — 07.11.2026
11
+
12
+ ### Added
13
+
14
+ - **A file note can carry the time its source gives it, and searches read that time.**
15
+ `store.notes.dateFileNotes(folderId, [{ path, modifiedAt }])` sets it (memo passes the front matter `date` or the
16
+ file's modification time) without counting as an edit: text, revision and `updatedAt` stay, so nothing is
17
+ re-embedded. `Note.modifiedAt` holds it (`null` when the source gave none, always for a note written in memo). The
18
+ column is the one Drive documents already fill, so `date:`, the `at` of a notes hit and `search all`'s `timestamp`
19
+ show it without a store version. Until now a local note was dated by the moment it was imported.
20
+ - **`models download --json` writes byte progress lines to stderr** while a model downloads:
21
+ `{"event":"progress","step":"download","done","total","unit":"bytes","label":<model id>}`, at most two a second plus
22
+ the first and last line, so a desktop app can draw a bar. `installFiles`, `install` and the `download*Model`
23
+ services take a `bytes(done, total)` callback for the same count.
24
+
25
+ - **A source `search all` skips names why, for a program too.** Each `skipped` entry keeps the sentence in `reason` and
26
+ now adds `why`, the dotted reason (`query.unknown-value`), and `token`, the part of the query that was refused
27
+ (`kind:nonsense`). `meta.issues` of `search all` carries `why` as `reason`, as the output standard allows.
28
+
29
+ ### Changed — may break callers
30
+
31
+ - **A `?` that ends a bare word is a question mark, not a wildcard.** `invoice?` and `что с бюджетом?` find
32
+ "invoice" and "бюджет"; before, `?` asked for one more character and `invoice` itself was missed. A `?` inside a
33
+ word (`inv?ice`) or after a field (`text:invoice?`) is still one character.
34
+
35
+ ### Fixed
36
+
37
+ - **`search all` ranks higher the record a question words differently.** For a question, a mail, message or note
38
+ that both the words and the meaning found kept only its words rank, so one meaning ranked first and words ranked
39
+ last stayed at the bottom of the page or off it. It now keeps the better of its two ranks, still with no second vote.
40
+
10
41
  ## 0.603.0 — 07.11.2026
11
42
 
12
43
  ### Changed — may break callers
@@ -97,7 +97,14 @@ const metaOf = (accounts, skipped = [], heldInPart = false) => ({
97
97
  accounts: accounts.map(accountName),
98
98
  complete: skipped.length === 0 && !heldInPart,
99
99
  ...(skipped.length
100
- ? { issues: skipped.map(({ source, resource, code }) => ({ code, source: source ?? resource ?? "" })) }
100
+ ? {
101
+ issues: skipped.map(({ source, resource, code, why }) => ({
102
+ code,
103
+ // The output standard takes a dotted reason only; the sentence goes to a person as a note.
104
+ ...(why && /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/u.test(why) ? { reason: why } : {}),
105
+ source: source ?? resource ?? "",
106
+ })),
107
+ }
101
108
  : {}),
102
109
  });
103
110
  const day = (at) => at?.slice(0, 10) ?? "no date";
@@ -8,6 +8,7 @@ import { DEFAULT_TEXT_MODEL, TEXT_MODELS } from "../embeddings/models.js";
8
8
  import { downloadTextModel } from "../services/model-downloads.js";
9
9
  import { install, installedBytes, isInstalled, modelsDirectory } from "../speech/install.js";
10
10
  import { DEFAULT_ORDER, orderedModels, speechModel } from "../speech/models.js";
11
+ import { stepLines } from "../terminal/step-lines.js";
11
12
  import { FETCH, LOCAL_READ, NO_EFFECTS } from "./effects.js";
12
13
  import { itemOf, listOf } from "./envelope.js";
13
14
  import { listQuery, nativeTerms, termField, typedQuery, withQuery } from "./list-query.js";
@@ -90,16 +91,26 @@ export const modelCatalogueCommand = (app, options) => {
90
91
  reason: "model.offline",
91
92
  });
92
93
  const env = options.env();
94
+ const bytes = downloadProgress(stepLines(options.diagnostic, Boolean(this.optsWithGlobals().json)), id);
93
95
  if (TEXT_MODELS.some((model) => model.id === id)) {
94
96
  if (!options.kinds.includes("text"))
95
97
  throw new CliError("validation_error", "this tool does not use text models");
96
- await downloadTextModel(id, { env, acceptTerms: given.acceptTerms === true, progress: options.diagnostic });
98
+ await downloadTextModel(id, {
99
+ env,
100
+ acceptTerms: given.acceptTerms === true,
101
+ progress: options.diagnostic,
102
+ bytes,
103
+ });
97
104
  options.output(itemOf(text(id, env)), this);
98
105
  }
99
106
  else {
100
107
  if (!options.kinds.includes("audio"))
101
108
  throw new CliError("validation_error", "this tool does not use audio models");
102
- await install(speechModel(id), modelsDirectory(env), { verifyExisting: true, progress: options.diagnostic });
109
+ await install(speechModel(id), modelsDirectory(env), {
110
+ verifyExisting: true,
111
+ progress: options.diagnostic,
112
+ bytes,
113
+ });
103
114
  options.output(itemOf(audio(id, env)), this);
104
115
  }
105
116
  });
@@ -108,3 +119,18 @@ export const modelCatalogueCommand = (app, options) => {
108
119
  command.option("--json", "print JSON");
109
120
  return models;
110
121
  };
122
+ const PROGRESS_EVERY_MS = 500;
123
+ /**
124
+ * `{"event":"progress","step":"download",…}` on stderr under --json, for a window to draw a bar by: at most every half
125
+ * second, but always the first line and the last.
126
+ */
127
+ const downloadProgress = (emit, label) => {
128
+ let last = Number.NEGATIVE_INFINITY;
129
+ return (done, total) => {
130
+ const now = Date.now();
131
+ if (done !== total && now - last < PROGRESS_EVERY_MS)
132
+ return;
133
+ last = now;
134
+ emit({ event: "progress", step: "download", done, total, unit: "bytes", label });
135
+ };
136
+ };
@@ -2,7 +2,8 @@
2
2
  * Free text as the search reads it: a character the query language takes as syntax where it cannot be syntax — the
3
3
  * colon of `10:30` or `HH:MM`, a URL's slashes, an unbalanced quote or bracket — is made literal by quoting the word
4
4
  * that holds it, a `word:` that names no search field is that word, and a bare emoji or punctuation mark beside other
5
- * words is dropped. A query that already reads well comes back unchanged, so this can run again on its own output;
5
+ * words is dropped. A `?` that ends a bare word is a question mark, not a one-character wildcard. A query that
6
+ * already reads well, and has no such word, comes back unchanged, so this can run again on its own output;
6
7
  * field queries and Boolean operators keep their meaning. A field's own mistake (`kind:nonsense`) is left for the
7
8
  * search to report. `fields` are the names a list of its own (memories: `text`, `scope`) reads as fields.
8
9
  */
@@ -56,6 +56,13 @@ const read = (text, fields) => {
56
56
  const unknown = leaves.find(({ field }) => !fields.has(field));
57
57
  if (unknown)
58
58
  return { at: text.lastIndexOf(unknown.field, unknown.span.start) };
59
+ // "invoice?" and "что с бюджетом?" ask a question; a `?` inside a word (`inv?ice`) stays one character.
60
+ const questions = leaves.flatMap(({ implicit, operator, value, span }) => {
61
+ const mark = /^[^*?]*[^*?\\]\?+$/u.test(value) && implicit && operator === "wildcard" ? /\?+$/u.exec(value) : null;
62
+ return mark ? [span.end - mark[0].length] : [];
63
+ });
64
+ if (questions.length)
65
+ return { questions };
59
66
  // An emoji or a lone `^` is no word of the index, so ANDed with the rest it would find nothing at all.
60
67
  const wordless = leaves.filter(({ implicit, operator, value }) => implicit && (operator === "term" || operator === "phrase") && !/[\p{L}\p{N}]/u.test(value));
61
68
  const words = wordless.length < leaves.length;
@@ -79,7 +86,8 @@ const without = (text, leaves) => [...leaves]
79
86
  * Free text as the search reads it: a character the query language takes as syntax where it cannot be syntax — the
80
87
  * colon of `10:30` or `HH:MM`, a URL's slashes, an unbalanced quote or bracket — is made literal by quoting the word
81
88
  * that holds it, a `word:` that names no search field is that word, and a bare emoji or punctuation mark beside other
82
- * words is dropped. A query that already reads well comes back unchanged, so this can run again on its own output;
89
+ * words is dropped. A `?` that ends a bare word is a question mark, not a one-character wildcard. A query that
90
+ * already reads well, and has no such word, comes back unchanged, so this can run again on its own output;
83
91
  * field queries and Boolean operators keep their meaning. A field's own mistake (`kind:nonsense`) is left for the
84
92
  * search to report. `fields` are the names a list of its own (memories: `text`, `scope`) reads as fields.
85
93
  */
@@ -94,6 +102,12 @@ export const plainQuery = (text, fields = SEARCH_FIELDS) => {
94
102
  catch {
95
103
  return text;
96
104
  }
105
+ if ("questions" in reading) {
106
+ current = reading.questions
107
+ .sort((a, b) => b - a)
108
+ .reduce((left, at) => left.slice(0, at) + left.slice(at).replace(/^\?+/u, (marks) => "\\?".repeat(marks.length)), current);
109
+ continue;
110
+ }
97
111
  if ("wordless" in reading) {
98
112
  // Punctuation alone (`!!!`) is no search; the parser's error says so better than an empty answer.
99
113
  if (!reading.words && current !== text)
@@ -4,6 +4,8 @@ export interface ModelDownloadOptions {
4
4
  env: NodeJS.ProcessEnv;
5
5
  /** One line at a time: the size before the download, its progress, then the check. */
6
6
  progress?: (line: string) => void;
7
+ /** The model's bytes in place so far, of its total; not the ONNX Runtime fetched after it. */
8
+ bytes?: (done: number, total: number) => void;
7
9
  }
8
10
  export interface DownloadedModel<M> {
9
11
  model: M;
@@ -13,10 +15,10 @@ export interface DownloadedModel<M> {
13
15
  * The text embedding model into the shared models folder, checked against the sha256 this version expects and
14
16
  * loaded once on a word. Nothing is downloaded when it is already there; it is still loaded.
15
17
  */
16
- export declare const downloadTextModel: (id: string, { env, progress, acceptTerms }: ModelDownloadOptions & {
18
+ export declare const downloadTextModel: (id: string, { env, progress, bytes, acceptTerms }: ModelDownloadOptions & {
17
19
  acceptTerms?: boolean;
18
20
  }) => Promise<DownloadedModel<TextModel>>;
19
21
  /** A reranker, the same way as {@link downloadTextModel}, into the same folder. */
20
- export declare const downloadRerankModel: (id: string, { env, progress }: ModelDownloadOptions) => Promise<DownloadedModel<RerankModel>>;
22
+ export declare const downloadRerankModel: (id: string, { env, progress, bytes }: ModelDownloadOptions) => Promise<DownloadedModel<RerankModel>>;
21
23
  /** The picture model, the same way as {@link downloadTextModel}. */
22
- export declare const downloadImageModel: (id: string, { env, progress }: ModelDownloadOptions) => Promise<DownloadedModel<ImageModel>>;
24
+ export declare const downloadImageModel: (id: string, { env, progress, bytes }: ModelDownloadOptions) => Promise<DownloadedModel<ImageModel>>;
@@ -21,7 +21,7 @@ const nativeRuntime = async ({ env, progress = () => { } }) => {
21
21
  * The text embedding model into the shared models folder, checked against the sha256 this version expects and
22
22
  * loaded once on a word. Nothing is downloaded when it is already there; it is still loaded.
23
23
  */
24
- export const downloadTextModel = async (id, { env, progress = () => { }, acceptTerms = false }) => {
24
+ export const downloadTextModel = async (id, { env, progress = () => { }, bytes, acceptTerms = false }) => {
25
25
  const model = textModel(id);
26
26
  if (model.terms && !acceptTerms) {
27
27
  throw new CliError("validation_error", `${model.id} comes under the ${model.licence} (${model.terms}): read them, then run this again with --accept-terms`);
@@ -29,7 +29,7 @@ export const downloadTextModel = async (id, { env, progress = () => { }, acceptT
29
29
  const directory = textModelsDirectory(env);
30
30
  if (!isTextModelInstalled(model, directory)) {
31
31
  progress(`${model.id}: ${megabytes(bytesOf(model))} from Hugging Face`);
32
- await installFiles(placedText(model, directory), { progress });
32
+ await installFiles(placedText(model, directory), { progress, ...(bytes ? { bytes } : {}) });
33
33
  }
34
34
  await nativeRuntime({ env, progress });
35
35
  progress(`${model.id}: loading it once to check it works`);
@@ -46,12 +46,12 @@ export const downloadTextModel = async (id, { env, progress = () => { }, acceptT
46
46
  return { model, directory };
47
47
  };
48
48
  /** A reranker, the same way as {@link downloadTextModel}, into the same folder. */
49
- export const downloadRerankModel = async (id, { env, progress = () => { } }) => {
49
+ export const downloadRerankModel = async (id, { env, progress = () => { }, bytes }) => {
50
50
  const model = rerankModel(id);
51
51
  const directory = textModelsDirectory(env);
52
52
  if (!isTextModelInstalled(model, directory)) {
53
53
  progress(`${model.id}: ${megabytes(bytesOf(model))} from Hugging Face`);
54
- await installFiles(placedText(model, directory), { progress });
54
+ await installFiles(placedText(model, directory), { progress, ...(bytes ? { bytes } : {}) });
55
55
  }
56
56
  await nativeRuntime({ env, progress });
57
57
  progress(`${model.id}: loading it once to check it works`);
@@ -66,12 +66,12 @@ export const downloadRerankModel = async (id, { env, progress = () => { } }) =>
66
66
  return { model, directory };
67
67
  };
68
68
  /** The picture model, the same way as {@link downloadTextModel}. */
69
- export const downloadImageModel = async (id, { env, progress = () => { } }) => {
69
+ export const downloadImageModel = async (id, { env, progress = () => { }, bytes }) => {
70
70
  const model = imageModel(id);
71
71
  const directory = imageModelsDirectory(env);
72
72
  if (!isImageModelInstalled(model, directory)) {
73
73
  progress(`${model.id}: ${megabytes(bytesOf(model))} from Hugging Face`);
74
- await installFiles(placedImage(model, directory), { progress });
74
+ await installFiles(placedImage(model, directory), { progress, ...(bytes ? { bytes } : {}) });
75
75
  }
76
76
  progress(`${model.id}: loading it once to check it works`);
77
77
  const { openPictureEmbedder } = await import("../images/picture/embedder.js");
@@ -420,11 +420,13 @@ export const searchNotes = async (store, query, { limit = 20, offset = 0, tag, f
420
420
  const held = ranked.get(ref) ?? { note, at, score: 0, foundBy: [] };
421
421
  held.foundBy.push(by);
422
422
  ranked.set(ref, held);
423
+ const vote = 1 / (RRF_K + rank + 1);
423
424
  // A question's any-word list holds nearly every note meaning finds; a second vote there buried notes found by
424
425
  // words alone (recall@10 0.55 against 1.00, cli-testing knowledge-graph-memory, MEMO-36).
425
426
  if (by === "meaning" && lookup !== undefined && held.foundBy.includes("words"))
426
- return;
427
- held.score += 1 / (RRF_K + rank + 1);
427
+ held.score = Math.max(held.score, vote);
428
+ else
429
+ held.score += vote;
428
430
  });
429
431
  add(matched.items, "words");
430
432
  if (meaning !== undefined)
@@ -44,9 +44,15 @@ export interface SearchedAccount {
44
44
  account: string;
45
45
  }
46
46
  /** A resource not read, or a `--source` entry naming no account the search reads. */
47
+ /**
48
+ * `reason` is the sentence for a person; `code` and `why` (a dotted reason such as `query.unknown-value`) are for a
49
+ * program, and `token` is the part of the query the source refused, when the refusal points at one.
50
+ */
47
51
  export type Skipped<R extends string> = {
48
52
  code: ErrorCode;
49
53
  reason: string;
54
+ why?: string;
55
+ token?: string;
50
56
  } & ({
51
57
  resource: R;
52
58
  source?: undefined;
@@ -15,6 +15,14 @@ import { MAX_SEARCH_OFFSET, searchStore } from "./messages-archive-search.js";
15
15
  import { nearEligible } from "./messages-discovery.js";
16
16
  import { notesScopeOf, RRF_K, searchNotes } from "./notes-search.js";
17
17
  export const RESOURCES_SEARCHED = ["messages", "mail", "notes", "events", "crm"];
18
+ const refusal = (error, text) => {
19
+ const { reason, span } = (error.details ?? {});
20
+ const why = typeof reason === "string" ? reason : undefined;
21
+ const token = span && Number.isInteger(span.start) && Number.isInteger(span.end)
22
+ ? text.slice(span.start, span.end).trim()
23
+ : "";
24
+ return { ...(why ? { why } : {}), ...(token ? { token } : {}) };
25
+ };
18
26
  /** A query a resource cannot answer is skipped with its reason, never a failure of the whole search. */
19
27
  const skippable = (error) => error instanceof CliError && (error.code === "validation_error" || error.code === "not_found");
20
28
  /**
@@ -42,7 +50,8 @@ export const titleWords = (text) => {
42
50
  node.kind === "predicate" &&
43
51
  node.field === "text" &&
44
52
  (node.operator === "term" || node.operator === "phrase")
45
- ? node.value
53
+ ? // A title holds "invoice", not the question mark of "invoice?".
54
+ node.value.replace(/\?+$/u, "") || node.value
46
55
  : (() => {
47
56
  throw new CliError("validation_error", "deals and leads are found by the words of their title only");
48
57
  })());
@@ -164,13 +173,12 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
164
173
  const held = fused.get(hit.locator);
165
174
  if (held)
166
175
  held.item.foundBy = ["words", "meaning"];
167
- // As in notes: a question's any-word list already holds what meaning finds, and a second vote buries the rest.
176
+ const vote = 1 / (RRF_K + rank + 1);
177
+ // As in notes: a question's any-word list holds most of what meaning finds, so a second vote would bury the rest.
168
178
  if (held && discovers)
169
- return;
170
- fused.set(hit.locator, {
171
- item: held?.item ?? itemOf(hit, ["meaning"]),
172
- score: (held?.score ?? 0) + 1 / (RRF_K + rank + 1),
173
- });
179
+ held.score = Math.max(held.score, vote);
180
+ else
181
+ fused.set(hit.locator, { item: held?.item ?? itemOf(hit, ["meaning"]), score: (held?.score ?? 0) + vote });
174
182
  });
175
183
  return [...fused.values()].sort((a, b) => b.score - a.score).map(({ item }) => item);
176
184
  };
@@ -285,7 +293,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
285
293
  catch (error) {
286
294
  if (!skippable(error))
287
295
  throw error;
288
- skipped.push({ resource, code: error.code, reason: error.message });
296
+ skipped.push({ resource, code: error.code, reason: error.message, ...refusal(error, request.text) });
289
297
  }
290
298
  }
291
299
  }
@@ -14,15 +14,14 @@ export declare const installedBytes: (model: SpeechModel) => number;
14
14
  export type Fetch = (url: string, init?: {
15
15
  signal?: AbortSignal;
16
16
  }) => Promise<Response>;
17
- export declare const install: (model: SpeechModel, directory: string, { fetch: get, progress, verifyExisting, }?: {
17
+ export interface InstallOptions {
18
18
  fetch?: Fetch;
19
19
  progress?: (line: string) => void;
20
+ /** Bytes in place so far, of all the files', a file already there counted whole; called as each chunk lands. */
21
+ bytes?: (done: number, total: number) => void;
20
22
  verifyExisting?: boolean;
21
- }) => Promise<void>;
23
+ }
24
+ export declare const install: (model: SpeechModel, directory: string, { fetch: get, progress, bytes, verifyExisting }?: InstallOptions) => Promise<void>;
22
25
  /** Each file not already in place, downloaded and checked against its sha256 before it takes its name. */
23
- export declare const installFiles: (files: [ModelFile, string][], { fetch: get, progress, verifyExisting, }?: {
24
- fetch?: Fetch;
25
- progress?: (line: string) => void;
26
- verifyExisting?: boolean;
27
- }) => Promise<void>;
26
+ export declare const installFiles: (files: [ModelFile, string][], { fetch: get, progress, bytes, verifyExisting }?: InstallOptions) => Promise<void>;
28
27
  export declare const megabytes: (bytes: number) => string;
@@ -45,12 +45,12 @@ const sizeOf = (path) => {
45
45
  }
46
46
  };
47
47
  export const installedBytes = (model) => model.files.reduce((sum, file) => sum + file.bytes, 0);
48
- export const install = async (model, directory, { fetch: get = fetch, progress, verifyExisting, } = {}) => {
48
+ export const install = async (model, directory, { fetch: get = fetch, progress, bytes, verifyExisting } = {}) => {
49
49
  mkdirSync(join(directory, model.id), { recursive: true, mode: 0o700 });
50
- await installFiles(placed(model, directory), { fetch: get, progress, verifyExisting });
50
+ await installFiles(placed(model, directory), { fetch: get, progress, bytes, verifyExisting });
51
51
  };
52
52
  /** Each file not already in place, downloaded and checked against its sha256 before it takes its name. */
53
- export const installFiles = async (files, { fetch: get = fetch, progress, verifyExisting, } = {}) => {
53
+ export const installFiles = async (files, { fetch: get = fetch, progress, bytes = () => { }, verifyExisting } = {}) => {
54
54
  if (verifyExisting)
55
55
  for (const [file, path] of files) {
56
56
  if (sizeOf(path) !== undefined) {
@@ -63,18 +63,24 @@ export const installFiles = async (files, { fetch: get = fetch, progress, verify
63
63
  }
64
64
  }
65
65
  }
66
- for (const [file, path] of files) {
67
- if (sizeOf(path) === file.bytes)
68
- continue;
66
+ const total = files.reduce((sum, [file]) => sum + file.bytes, 0);
67
+ const missing = files.filter(([file, path]) => sizeOf(path) !== file.bytes);
68
+ let done = total - missing.reduce((sum, [file]) => sum + file.bytes, 0);
69
+ bytes(done, total);
70
+ for (const [file, path] of missing) {
69
71
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
70
72
  progress?.(`downloading ${file.name} (${megabytes(file.bytes)})`);
71
- await fetchVerified(file, path, get);
73
+ const before = done;
74
+ await fetchVerified(file, path, get, (received) => {
75
+ done = before + received;
76
+ bytes(done, total);
77
+ });
72
78
  }
73
79
  };
74
- const fetchVerified = async (file, path, get) => {
80
+ const fetchVerified = async (file, path, get, received) => {
75
81
  const stalled = watchdog(STALL_MS);
76
82
  try {
77
- await fetchInto(file, path, get, stalled);
83
+ await fetchInto(file, path, get, stalled, received);
78
84
  }
79
85
  catch (error) {
80
86
  if (stalled.signal.aborted) {
@@ -86,7 +92,7 @@ const fetchVerified = async (file, path, get) => {
86
92
  stalled.stop();
87
93
  }
88
94
  };
89
- const fetchInto = async (file, path, get, stalled) => {
95
+ const fetchInto = async (file, path, get, stalled, received) => {
90
96
  const response = await get(file.url, { signal: stalled.signal });
91
97
  if (!response.ok || !response.body) {
92
98
  await response.body?.cancel();
@@ -104,6 +110,7 @@ const fetchInto = async (file, path, get, stalled) => {
104
110
  return;
105
111
  }
106
112
  hash.update(chunk);
113
+ received(bytes);
107
114
  done(null, chunk);
108
115
  },
109
116
  });
@@ -0,0 +1,6 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ /** `store.notes.dateFileNotes` for a folder's account row: only the time column moves, so it is not an edit. */
3
+ export declare const dateFileNotes: (database: CacheDatabase, folder: number, dates: {
4
+ path: string;
5
+ modifiedAt: string;
6
+ }[]) => number;
@@ -0,0 +1,23 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ /** `store.notes.dateFileNotes` for a folder's account row: only the time column moves, so it is not an edit. */
3
+ export const dateFileNotes = (database, folder, dates) => {
4
+ const fileAt = database.prepare("SELECT id, document_id FROM files WHERE account_id = ? AND external_id = ? AND kind <> 'folder' AND deleted_at IS NULL");
5
+ const legacy = database.prepare("SELECT id FROM documents WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL");
6
+ const dateFile = database.prepare("UPDATE files SET external_updated_at = ? WHERE id = ? AND external_updated_at IS NOT ?");
7
+ // Only the document's own file dates the document; a copy in another folder dates its file row.
8
+ const dateDocument = database.prepare("UPDATE documents SET external_updated_at = ? WHERE id = ? AND account_id = ? AND external_id = ? " +
9
+ "AND external_updated_at IS NOT ?");
10
+ let changed = 0;
11
+ for (const { path, modifiedAt } of dates) {
12
+ const time = Date.parse(modifiedAt);
13
+ if (!Number.isFinite(time))
14
+ throw new CliError("validation_error", `${modifiedAt} is not a time`);
15
+ const place = fileAt.get(folder, path);
16
+ const id = place?.document_id ?? legacy.get(folder, path)?.id;
17
+ const file = place ? dateFile.run(time, Number(place.id), time).changes : 0;
18
+ const document = id == null ? 0 : dateDocument.run(time, Number(id), folder, path, time).changes;
19
+ if (file + document > 0)
20
+ changed++;
21
+ }
22
+ return changed;
23
+ };
@@ -42,6 +42,11 @@ export interface Note {
42
42
  contentHash: string | null;
43
43
  revision: number;
44
44
  exportPath: string | null;
45
+ /**
46
+ * When the source dates the note: a local file's front matter date or modification time, a Drive file's last
47
+ * edit; `null` when the source gave none. `createdAt` and `updatedAt` are the store's own times.
48
+ */
49
+ modifiedAt: string | null;
45
50
  createdAt: string;
46
51
  updatedAt: string;
47
52
  deletedAt: string | null;
@@ -127,6 +132,14 @@ export interface NotesStore extends NoteSearch, ImportedDocuments {
127
132
  }>;
128
133
  /** Moves a file note to a new path in its folder, keeping its id, links and tags; a gone note at `to` is dropped. */
129
134
  renameFileNote(folderId: string, from: string, to: string): Promise<Note>;
135
+ /**
136
+ * Sets the time the source dates each note at these paths (ISO 8601), the note's `modifiedAt`, without counting
137
+ * as an edit: text, revision and `updatedAt` stay. Answers how many notes it changed.
138
+ */
139
+ dateFileNotes(folderId: string, dates: {
140
+ path: string;
141
+ modifiedAt: string;
142
+ }[]): Promise<number>;
130
143
  /** Marks the folder's notes at these paths deleted; answers how many were live. */
131
144
  deleteFileNotes(folderId: string, paths: string[]): Promise<number>;
132
145
  /** A note about the things named, the first of them its subject; about nothing, a note to self. */
@@ -13,6 +13,7 @@ import { PREFERRED_FILE, syncFile } from "./files.js";
13
13
  import { importedDocumentWhere } from "./imported-documents.js";
14
14
  import { LINK_KINDS, LINK_ORIGINS, linkKind } from "./link-kinds.js";
15
15
  import { reviewLink } from "./link-reviews.js";
16
+ import { dateFileNotes } from "./note-dates.js";
16
17
  import { holdingText } from "./note-index.js";
17
18
  import { addTags, ensureTag, labelsOf } from "./tags.js";
18
19
  import { referenceOfThing, storedThing, thingOf } from "./things.js";
@@ -46,6 +47,7 @@ export const documentOf = (row) => ({
46
47
  contentHash: row.content_hash == null ? null : String(row.content_hash),
47
48
  revision: Number(row.revision),
48
49
  exportPath: row.export_path == null ? null : String(row.export_path),
50
+ modifiedAt: optionalIso(row.external_updated_at),
49
51
  createdAt: iso(row.created_at),
50
52
  updatedAt: iso(row.updated_at),
51
53
  deletedAt: optionalIso(row.deleted_at),
@@ -62,6 +64,7 @@ export const noteOf = (row) => ({
62
64
  contentHash: null,
63
65
  revision: Number(row.revision),
64
66
  exportPath: null,
67
+ modifiedAt: null,
65
68
  createdAt: iso(row.created_at),
66
69
  updatedAt: iso(row.updated_at),
67
70
  deletedAt: optionalIso(row.deleted_at),
@@ -484,6 +487,7 @@ export const notesStoreOver = (context) => {
484
487
  });
485
488
  return noteAt(id, folder, target);
486
489
  }),
490
+ dateFileNotes: async (folderId, dates) => write(database, () => dateFileNotes(database, Number(folderRow(folderId).id), dates)),
487
491
  deleteFileNotes: async (folderId, paths) => write(database, () => {
488
492
  const folder = Number(folderRow(folderId).id);
489
493
  let deleted = 0;
@@ -557,7 +561,8 @@ export const notesStoreOver = (context) => {
557
561
  (folder === null
558
562
  ? "SELECT d.* FROM documents d WHERE d.deleted_at IS NULL AND ? IS NULL AND ? IS NULL "
559
563
  : "SELECT d.*, f.account_id AS account_id, CASE WHEN a.provider IN ('local', 'obsidian') " +
560
- "THEN f.external_id ELSE d.external_id END AS external_id FROM files f " +
564
+ "THEN f.external_id ELSE d.external_id END AS external_id, " +
565
+ "coalesce(f.external_updated_at, d.external_updated_at) AS external_updated_at FROM files f " +
561
566
  "JOIN documents d ON d.id = f.document_id JOIN accounts a ON a.id = f.account_id " +
562
567
  "WHERE f.deleted_at IS NULL AND d.deleted_at IS NULL AND f.account_id = ? AND ? IS NOT NULL ") +
563
568
  "AND coalesce(json_extract(d.metadata, '$.catalog.active'), 1)=1 " +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.603.0",
3
+ "version": "0.604.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",
package/parity.json CHANGED
@@ -4369,7 +4369,9 @@
4369
4369
  "options": {
4370
4370
  "--answer-stdin": {
4371
4371
  "in": ["tg", "max"],
4372
- "reason": "only tg and max ask questions during sign-in (app keys, codes, a 2FA or cloud password); WhatsApp's QR sign-in asks nothing, and its phone login is not ported to signInSteps yet"
4372
+ "planned": {
4373
+ "wa": "whatsapp-cli's next cli-core bump: its phone link asks the number through signInSteps"
4374
+ }
4373
4375
  },
4374
4376
  "--app": {
4375
4377
  "in": ["tg"],