@wirecat/cli-core 0.601.0 → 0.602.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
@@ -5,7 +5,34 @@ 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
- ## Unreleased
8
+ ## 0.602.0 — 07.11.2026
9
+
10
+ ### Fixed
11
+
12
+ - **`store recover run` refuses while another recovery runs, and no longer fails because a tool only read the store.**
13
+ A recovery keeps a lock file beside the store (`<store>.recover-lock`, with its process number); a second run is
14
+ refused with the reason `store.recovering`, and `store recover` and `storeHolders` list the running one. A lock whose
15
+ process ended is taken over. The check for writes during the recovery now asks SQLite (`PRAGMA data_version` on a
16
+ connection kept open to the swap, and the file's inode) instead of comparing file times and sizes, which a reader's
17
+ open and close changed without changing a row (`store.changed-during-recovery` on a store nobody wrote to).
18
+ - **A recovery clears values that are not valid JSON, and `doctor --deep` reports them.** `.recover` copied a damaged
19
+ value that still read, and a JSON read of its row then failed with "malformed JSON" (`mail sync` on an `emails.headers`
20
+ value). Every `metadata` column and the other columns the tools read as JSON (`emails.headers`, `accounts.settings`,
21
+ `messages.mentions`, `messages.reply_to`, …) are checked: an invalid value is set to NULL, or its row is dropped where
22
+ the column may not be NULL, and the recovery lists each column as `invalidJson`. The deep health check
23
+ (`storeHealth(path, { deep: true })`, `doctor --deep`, `store recover`) reports them as `invalidJson` and fails.
24
+
25
+ ### Changed — may break callers
26
+
27
+ - **A search for plain text with a colon, a URL or another special character finds what holds it.** `meeting at 10:30`,
28
+ `Answer as HH:MM` and `a:b` read the word before the colon as a field, so every source of `search all` refused the
29
+ query and the answer was empty. Now a `word:` that names no search field, and a word the parser cannot read as
30
+ syntax (a URL, an unbalanced quote or bracket, `^`, `~home`, `[draft]`, `<tag>`), are searched as words; a lone
31
+ emoji or punctuation mark beside other words no longer empties the answer. Field queries, Boolean operators,
32
+ phrases, `word*` and `/regex/` keep their meaning, and `word~1`, `/x/i` and punctuation alone keep their errors.
33
+ A caller that relied on the refusal of `foo:bar`, an unbalanced quote or `link:click?id=1` now gets hits, and
34
+ `meetings search` reads `subject:` (a message field) as a word. `plainQuery` in `./services` gives a caller the text
35
+ as the search reads it (cli-memo#674).
9
36
 
10
37
  ## 0.601.0 — 07.11.2026
11
38
 
@@ -19,6 +19,7 @@ export declare const storeSummary: (env: NodeJS.ProcessEnv, { deep, command }?:
19
19
  ms: number;
20
20
  problems?: number | undefined;
21
21
  damagedTables?: import("../../store/health.js").DamagedTable[] | undefined;
22
+ invalidJson?: import("../../store/health.js").InvalidJson[] | undefined;
22
23
  damagedSearchIndexes?: string[] | undefined;
23
24
  };
24
25
  damage?: import("../../store/damage.js").DamageExplanation | undefined;
@@ -37,6 +38,7 @@ export declare const storeSummary: (env: NodeJS.ProcessEnv, { deep, command }?:
37
38
  ms: number;
38
39
  problems?: number | undefined;
39
40
  damagedTables?: import("../../store/health.js").DamagedTable[] | undefined;
41
+ invalidJson?: import("../../store/health.js").InvalidJson[] | undefined;
40
42
  damagedSearchIndexes?: string[] | undefined;
41
43
  };
42
44
  damage?: import("../../store/damage.js").DamageExplanation | undefined;
@@ -74,6 +74,7 @@ export const storeSummary = async (env, { deep = false, command } = {}) => {
74
74
  ms: checked.ms,
75
75
  ...(checked.problems ? { problems: checked.problems } : {}),
76
76
  ...(checked.damagedTables?.length ? { damagedTables: checked.damagedTables } : {}),
77
+ ...(checked.invalidJson?.length ? { invalidJson: checked.invalidJson } : {}),
77
78
  ...(checked.searchIndexes?.some((index) => !index.ok)
78
79
  ? { damagedSearchIndexes: checked.searchIndexes.filter((index) => !index.ok).map((index) => index.name) }
79
80
  : {}),
@@ -1,5 +1,6 @@
1
1
  import { Command } from "commander";
2
2
  import { type DamageExplanation } from "../store/damage.js";
3
+ import { type InvalidJson } from "../store/health.js";
3
4
  import { type RecoverOptions, type Recovery } from "../store/recover.js";
4
5
  export interface RecoveryCheck {
5
6
  path: string;
@@ -16,6 +17,7 @@ export interface RecoveryCheck {
16
17
  name: string;
17
18
  error?: string;
18
19
  }[];
20
+ invalidJson?: InvalidJson[];
19
21
  rows?: Record<string, number | null>;
20
22
  explanation?: DamageExplanation | null;
21
23
  inUse?: {
@@ -65,6 +65,7 @@ export const storeRecoveryCheck = async (env, command) => {
65
65
  damagedSearchIndexes: (health.searchIndexes ?? [])
66
66
  .filter((index) => !index.ok)
67
67
  .map(({ name, error }) => ({ name, ...(error ? { error } : {}) })),
68
+ invalidJson: health.invalidJson ?? [],
68
69
  rows,
69
70
  explanation,
70
71
  inUse,
@@ -107,6 +108,7 @@ export const recoveryNotes = (answer) => {
107
108
  `recovered in ${answer.seconds.total} s; the damaged file is kept at ${answer.keptAt}`,
108
109
  ...(lost.length ? lost : ["no table lost a row"]),
109
110
  ...answer.dangling.map(({ table, parent, rows }) => `${rows} rows of ${table} point at ${parent} rows the store does not hold`),
111
+ ...answer.invalidJson.map(({ table, column, rows, required }) => `${table}.${column}: ${rows} values were not valid JSON — ${required ? "those rows were dropped" : "set to empty"}`),
110
112
  ...answer.next.map((line) => `next: ${line}`),
111
113
  ];
112
114
  }
@@ -164,6 +164,7 @@ const OTHERS = [
164
164
  "recovering the store needs the sqlite3 program, 3.43 or newer, with its .recover command",
165
165
  ],
166
166
  validation("store.recovery-failed", "the recovered store did not pass its check, so the store was left as it was"),
167
+ validation("store.recovering", "another recovery of the store is running; wait for it to finish"),
167
168
  validation("store.changed-during-recovery", "the store was written to during the recovery, so it was left as it was"),
168
169
  [
169
170
  "store.vector-extension-missing",
@@ -4,6 +4,8 @@ import type { MeetingHitSearchRequest } from "./search-store.js";
4
4
  export declare const MOST_LINES_APART = 20;
5
5
  /** The messages query language over meeting text: the same fields, a narrower set of operators. */
6
6
  export declare const MEETING_HIT_QUERY: import("@wirecat/cli-base/query").QueryRegistry;
7
+ /** Every name a meeting search reads as a field, lifted or not; another `word:` there is words. */
8
+ export declare const MEETING_FIELD_NAMES: ReadonlySet<string>;
7
9
  /**
8
10
  * `budget project:RES date>=30d` → the words, and the meetings to look in as filters. A meeting field must be
9
11
  * joined to the words with AND and given once, in the query or as an option. Text the language refuses is left as
@@ -64,6 +64,8 @@ const MEETING_FIELDS = defineQuery({
64
64
  ],
65
65
  });
66
66
  const LIFTED = new Set(["date", "project", "tag", "topic"]);
67
+ /** Every name a meeting search reads as a field, lifted or not; another `word:` there is words. */
68
+ export const MEETING_FIELD_NAMES = new Set(MEETING_FIELDS.fields.map(({ name }) => name));
67
69
  /**
68
70
  * `budget project:RES date>=30d` → the words, and the meetings to look in as filters. A meeting field must be
69
71
  * joined to the words with AND and given once, in the query or as an option. Text the language refuses is left as
@@ -10,7 +10,7 @@ export { linkEvent } from "./events.js";
10
10
  export { exportMeeting, type MeetingExport, type MeetingExportFormat, type MeetingExportOptions, serializeVtt, } from "./export.js";
11
11
  export { type FindingEvidence, type FindingOutcome, findingHash, MEETING_FINDINGS_KIND, type MeetingFactFinding, type MeetingFinding, type MeetingFindingsInput, type MeetingFindingsReceipt, type MeetingTaskFinding, meetingFindingFingerprint, validateMeetingFindings, } from "./findings.js";
12
12
  export { type FactFinding, type Finding, type FindingsInput, type FindingsReceipt, type FindingsRules, findingFields, findingFingerprint, findingId, findingNeeds, findingText, type PaymentFinding, snakeCase, type TaskFinding, validateBatch, validateFinding, validateFindings, validEvidence, } from "./findings-rules.js";
13
- export { liftMeetingFields, MEETING_HIT_QUERY, meetingWordsQuery, parseMeetingQuery } from "./hit-query.js";
13
+ export { liftMeetingFields, MEETING_FIELD_NAMES, MEETING_HIT_QUERY, meetingWordsQuery, parseMeetingQuery, } from "./hit-query.js";
14
14
  export { type ImportFile, importFiles } from "./import.js";
15
15
  export { MEETING_ISSUES, MEETING_QUERY, type MeetingIssue, type MeetingItem, type MeetingOwner, meeting, meetingIssuesOf, meetingItem, } from "./item.js";
16
16
  export { joinKeyOf, joinUrlWithoutQuery } from "./join-key.js";
@@ -7,7 +7,7 @@ export { linkEvent } from "./events.js";
7
7
  export { exportMeeting, serializeVtt, } from "./export.js";
8
8
  export { findingHash, MEETING_FINDINGS_KIND, meetingFindingFingerprint, validateMeetingFindings, } from "./findings.js";
9
9
  export { findingFields, findingFingerprint, findingId, findingNeeds, findingText, snakeCase, validateBatch, validateFinding, validateFindings, validEvidence, } from "./findings-rules.js";
10
- export { liftMeetingFields, MEETING_HIT_QUERY, meetingWordsQuery, parseMeetingQuery } from "./hit-query.js";
10
+ export { liftMeetingFields, MEETING_FIELD_NAMES, MEETING_HIT_QUERY, meetingWordsQuery, parseMeetingQuery, } from "./hit-query.js";
11
11
  export { importFiles } from "./import.js";
12
12
  export { MEETING_ISSUES, MEETING_QUERY, meeting, meetingIssuesOf, meetingItem, } from "./item.js";
13
13
  export { joinKeyOf, joinUrlWithoutQuery } from "./join-key.js";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Free text as the search reads it: a character the query language takes as syntax where it cannot be syntax — the
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
+ * 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;
6
+ * field queries and Boolean operators keep their meaning. A field's own mistake (`kind:nonsense`) is left for the
7
+ * search to report. `fields` are the names a list of its own (memories: `text`, `scope`) reads as fields.
8
+ */
9
+ export declare const plainQuery: (text: string, fields?: ReadonlySet<string>) => string;
@@ -0,0 +1,124 @@
1
+ import { isCliError } from "@wirecat/cli-base";
2
+ import { parseLucene, walkQuery } from "@wirecat/cli-base/query";
3
+ import { QUERY_FIELDS } from "./registry.js";
4
+ import { MESSAGE_PARSING } from "./types.js";
5
+ // The parser's own mistakes about plain text: a character it read as syntax. Errors about a field's value stay errors.
6
+ const REPAIRED = new Set([
7
+ "query.invalid-syntax",
8
+ "query.unclosed-literal",
9
+ "query.unsupported-operator",
10
+ "query.invalid-escape",
11
+ ]);
12
+ // Every source's fields are message fields; after: and before: are refused with a hint to write date:.
13
+ const SEARCH_FIELDS = new Set([...QUERY_FIELDS.map(({ name }) => name), "after", "before"]);
14
+ const FIELD_PREFIX = /^[+-]?([\p{L}\p{N}_.]+)(?:[:=]|[<>]=?)/u;
15
+ const space = (c) => c !== undefined && /[ \t\n\r\u3000]/u.test(c);
16
+ // A quoted word is read as words, whatever it holds; only its quote marks and a trailing backslash need escaping.
17
+ const quoted = (text) => {
18
+ let out = "";
19
+ for (let at = 0; at < text.length; at++) {
20
+ const c = text[at];
21
+ if (c === "\\" && at + 1 < text.length && (text[at + 1] !== "u" || /^u[0-9a-fA-F]{4}/u.test(text.slice(at + 1)))) {
22
+ out += c + text[at + 1];
23
+ at++;
24
+ }
25
+ else
26
+ out += c === '"' || c === "\\" ? `\\${c}` : c;
27
+ }
28
+ return `"${out}"`;
29
+ };
30
+ /** One word as a phrase, so the parser reads none of it as syntax; a known `field:` and modifiers stay outside. */
31
+ const literal = (word, keepParens, fields) => {
32
+ const prefix = FIELD_PREFIX.exec(word);
33
+ const field = prefix && fields.has(prefix[1] ?? "") ? prefix[0] : "";
34
+ const rest = word.slice(field.length);
35
+ const opening = keepParens ? (/^[(+-]*/u.exec(rest)?.[0] ?? "") : "";
36
+ const closing = keepParens ? (/\)*$/u.exec(rest.slice(opening.length))?.[0] ?? "") : "";
37
+ const body = rest.slice(opening.length, rest.length - closing.length);
38
+ if (!body)
39
+ return keepParens ? literal(word, false, fields) : `${field}${quoted(rest)}`;
40
+ return `${field}${opening}${quoted(body)}${closing}`;
41
+ };
42
+ const wordAround = (text, at) => {
43
+ let start = at;
44
+ while (start > 0 && !space(text[start - 1]))
45
+ start--;
46
+ let end = at;
47
+ while (end < text.length && !space(text[end]))
48
+ end++;
49
+ return { start, end };
50
+ };
51
+ const everyWordLiteral = (text, fields) => text.replace(/[^ \t\n\r\u3000]+/gu, (word) => literal(word, false, fields));
52
+ /** Where `text` stops being a search query (-1: somewhere unknown), or the bare words the index holds nothing for. */
53
+ const read = (text, fields) => {
54
+ try {
55
+ const leaves = walkQuery(parseLucene(text, MESSAGE_PARSING).root);
56
+ const unknown = leaves.find(({ field }) => !fields.has(field));
57
+ if (unknown)
58
+ return { at: text.lastIndexOf(unknown.field, unknown.span.start) };
59
+ // An emoji or a lone `^` is no word of the index, so ANDed with the rest it would find nothing at all.
60
+ const wordless = leaves.filter(({ implicit, operator, value }) => implicit && (operator === "term" || operator === "phrase") && !/[\p{L}\p{N}]/u.test(value));
61
+ const words = wordless.length < leaves.length;
62
+ return { wordless: words ? wordless : [], words };
63
+ }
64
+ catch (error) {
65
+ const details = isCliError(error) ? error.details : undefined;
66
+ if (!details?.span || !REPAIRED.has(details.reason ?? ""))
67
+ throw error;
68
+ // `word~1` is Lucene's fuzzy search, which the error answers with the prefix search to use instead.
69
+ if (/^~\d/u.test(text.slice(details.span.start)))
70
+ throw error;
71
+ return { at: details.span.start };
72
+ }
73
+ };
74
+ const without = (text, leaves) => [...leaves]
75
+ .sort((a, b) => b.span.start - a.span.start)
76
+ .reduce((left, { span }) => left.slice(0, span.start) + left.slice(span.end), text)
77
+ .trim();
78
+ /**
79
+ * Free text as the search reads it: a character the query language takes as syntax where it cannot be syntax — the
80
+ * colon of `10:30` or `HH:MM`, a URL's slashes, an unbalanced quote or bracket — is made literal by quoting the word
81
+ * 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;
83
+ * field queries and Boolean operators keep their meaning. A field's own mistake (`kind:nonsense`) is left for the
84
+ * search to report. `fields` are the names a list of its own (memories: `text`, `scope`) reads as fields.
85
+ */
86
+ export const plainQuery = (text, fields = SEARCH_FIELDS) => {
87
+ let current = text;
88
+ let whole = false;
89
+ for (let tries = 0; tries <= 64; tries++) {
90
+ let reading;
91
+ try {
92
+ reading = read(current, fields);
93
+ }
94
+ catch {
95
+ return text;
96
+ }
97
+ if ("wordless" in reading) {
98
+ // Punctuation alone (`!!!`) is no search; the parser's error says so better than an empty answer.
99
+ if (!reading.words && current !== text)
100
+ return text;
101
+ if (!reading.wordless.length)
102
+ return current;
103
+ current = without(current, reading.wordless);
104
+ continue;
105
+ }
106
+ // At the end, the parser is still waiting for a `)` or a term, and no one word is to blame.
107
+ const word = reading.at < 0 || reading.at >= current.length ? undefined : wordAround(current, reading.at);
108
+ const paren = "()".includes(current[reading.at] ?? "");
109
+ const repaired = word
110
+ ? current.slice(0, word.start) +
111
+ literal(current.slice(word.start, word.end), !paren, fields) +
112
+ current.slice(word.end)
113
+ : current;
114
+ if (repaired !== current) {
115
+ current = repaired;
116
+ continue;
117
+ }
118
+ if (whole)
119
+ return text;
120
+ whole = true;
121
+ current = everyWordLiteral(text, fields);
122
+ }
123
+ return text;
124
+ };
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { kindIn } from "../domain/providers.js";
3
3
  import { meaningFloor } from "../embeddings/models.js";
4
+ import { plainQuery } from "../search/lucene/plain.js";
4
5
  import { questionLookup, questionText } from "../search/question-plan.js";
5
6
  import { excerpt } from "./excerpt.js";
6
7
  import { localModel, RRF_K, storeQuery, withLocal } from "./notes-search.js";
@@ -55,6 +56,7 @@ const keyOf = ({ event }) => event.eventSeriesId === null ? `e${event.id}` : `s$
55
56
  export const searchEvents = async (store, query, { limit = 20, offset = 0, accounts, exact, discover, newest, timezone, signal, candidates, env, command, embedders, } = {}) => {
56
57
  if (!query.trim())
57
58
  throw new CliError("validation_error", "say what to find in the events");
59
+ query = plainQuery(query);
58
60
  const asked = discover && !exact && !newest ? questionLookup(query) : undefined;
59
61
  const { root, stemmer } = await storeQuery(store, asked ?? query, {
60
62
  ...(exact ? { exact: true } : {}),
@@ -152,6 +152,7 @@ export type Override = (base: Services, deps: ServiceDeps) => Partial<Services>;
152
152
  /** The shared services, with the messenger's `services` override applied — commands and MCP tools alike. */
153
153
  export declare const servicesFor: (deps: ServiceDeps) => Services;
154
154
  export { entriesOfList, type ListContext, type ListedEntry } from "../search/account-list.js";
155
+ export { plainQuery } from "../search/lucene/plain.js";
155
156
  export { FIELD_VERSION, QUERY_FIELDS, QUERY_OPERATORS, validateAst } from "../search/lucene/registry.js";
156
157
  export { QUERY_LIMITS, QUERY_VERSION } from "../search/lucene/types.js";
157
158
  export { questionLookup } from "../search/question-plan.js";
@@ -117,6 +117,7 @@ export const servicesFor = (deps) => {
117
117
  return deps.messenger.services ? { ...base, ...deps.messenger.services(base, deps) } : base;
118
118
  };
119
119
  export { entriesOfList } from "../search/account-list.js";
120
+ export { plainQuery } from "../search/lucene/plain.js";
120
121
  export { FIELD_VERSION, QUERY_FIELDS, QUERY_OPERATORS, validateAst } from "../search/lucene/registry.js";
121
122
  export { QUERY_LIMITS, QUERY_VERSION } from "../search/lucene/types.js";
122
123
  export { questionLookup } from "../search/question-plan.js";
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { liftMeetingFields } from "../meetings/index.js";
2
+ import { liftMeetingFields, MEETING_FIELD_NAMES } from "../meetings/index.js";
3
+ import { plainQuery } from "../search/lucene/plain.js";
3
4
  /** Each batch commits on its own, so a search cut short by its deadline keeps the progress it made. */
4
5
  export const refreshMeetingIndex = async (meetings, accountId, signal) => {
5
6
  let before = Number.POSITIVE_INFINITY;
@@ -55,7 +56,7 @@ export const resolveMeetingSelection = async (store, request) => {
55
56
  return { input, selection };
56
57
  };
57
58
  export const searchMeetingHits = async (store, query, request, options = {}) => {
58
- const lifted = liftMeetingFields(query, request);
59
+ const lifted = liftMeetingFields(plainQuery(query, MEETING_FIELD_NAMES), request);
59
60
  const { input, selection } = await resolveMeetingSelection(store, lifted.request);
60
61
  if (options.refreshIndex !== false)
61
62
  await refreshMeetingIndex(store.meetings, input.accountId, input.signal);
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { parseLocator } from "../domain/locator.js";
3
+ import { plainQuery } from "../search/lucene/plain.js";
3
4
  import { isQueryLimit } from "../search/lucene/types.js";
4
5
  import { TOTAL_CAP, totalOf } from "../search/total.js";
5
6
  import { discoveryRequest, searchDiscovery } from "./messages-discovery.js";
@@ -46,6 +47,8 @@ export const MAX_SEARCH_OFFSET = 1000;
46
47
  * the next page starts. A page is the hits up to `offset + limit` read again and cut, so deep pages cost more.
47
48
  */
48
49
  export const searchStore = async (store, account, request, messenger = {}, meaning, rerank) => {
50
+ if (request.text !== undefined)
51
+ request = { ...request, text: plainQuery(request.text) };
49
52
  const offset = request.offset ?? 0;
50
53
  if (!Number.isInteger(offset) || offset < 0 || offset > MAX_SEARCH_OFFSET)
51
54
  throw new CliError("validation_error", `offset takes a whole number from 0 to ${MAX_SEARCH_OFFSET}`);
@@ -7,6 +7,7 @@ import { DEFAULT_TEXT_MODEL, meaningFloor, textModel, vectorModelKey } from "../
7
7
  import { DEFAULT_IMAGE_MODEL, imageModel } from "../images/picture/models.js";
8
8
  import { entriesOfList, fitting } from "../search/account-list.js";
9
9
  import { fieldsOfQuery as fieldsOf, meaningWords } from "../search/lucene/meaning-parts.js";
10
+ import { plainQuery } from "../search/lucene/plain.js";
10
11
  import { validateFields } from "../search/lucene/registry.js";
11
12
  import { hasStems } from "../search/lucene/resolved.js";
12
13
  import { isQueryLimit, SEARCH_QUERY } from "../search/lucene/types.js";
@@ -326,6 +327,7 @@ const notesTotal = async (store, text, { exact, scope, shown, hasMore, }, others
326
327
  * of `filter` holds for every hit, found by words or by meaning; a query of fields alone is not searched by meaning.
327
328
  */
328
329
  export const searchNotes = async (store, query, { limit = 20, offset = 0, tag, filter: expression, folderIds, withInternal, source: given, exact = false, discover = false, timezone, env, command, embedders, pictures: withPictures = false, pictureLimit = 5, pictureEmbedder, } = {}) => {
330
+ query = plainQuery(query);
329
331
  const typed = noteSourceOfQuery(query);
330
332
  const source = given ?? typed.source;
331
333
  const rest = typed.source !== undefined && typed.source === source ? typed.rest : query;
@@ -517,6 +519,7 @@ export const notesScopeOf = (accounts) => {
517
519
  * — and every entry naming none of them in `skipped`. Without a list, every notes account `type` leaves in.
518
520
  */
519
521
  export const searchNotesOf = async (store, account, text, { accounts: list, app, ...query }) => {
522
+ text = plainQuery(text);
520
523
  const own = app?.command ?? query.command;
521
524
  const what = `${own === undefined ? "" : `${own} `}search notes`;
522
525
  const held = [
@@ -130,4 +130,4 @@ export declare const crmAccounts: (store: MessageStore) => Promise<AccountKey[]>
130
130
  * server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
131
131
  * resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
132
132
  */
133
- export declare const searchAll: (store: MessageStore, account: AccountKey, request: SearchAllRequest, messenger?: SearchAllMessenger, searchMessages?: (query: SearchQuery) => Promise<SearchFound>, meaning?: MeaningLane) => Promise<SearchAllFound>;
133
+ export declare const searchAll: (store: MessageStore, account: AccountKey, asked: SearchAllRequest, messenger?: SearchAllMessenger, searchMessages?: (query: SearchQuery) => Promise<SearchFound>, meaning?: MeaningLane) => Promise<SearchAllFound>;
@@ -6,6 +6,7 @@ import { senderIsMe } from "../domain/models.js";
6
6
  import { INTERNAL_NOTES, kindIn } from "../domain/providers.js";
7
7
  import { runEmbedders } from "../embeddings/embed.js";
8
8
  import { DEFAULT_TEXT_MODEL } from "../embeddings/models.js";
9
+ import { plainQuery } from "../search/lucene/plain.js";
9
10
  import { MESSAGE_PARSING, SEARCH_QUERY } from "../search/lucene/types.js";
10
11
  import { planQuestion, questionLookup } from "../search/question-plan.js";
11
12
  import { calendarAccounts, searchEvents } from "./events-search.js";
@@ -54,9 +55,10 @@ export const crmAccounts = async (store) => (await store.accounts.accounts()).fi
54
55
  * server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
55
56
  * resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
56
57
  */
57
- export const searchAll = async (store, account, request, messenger = {}, searchMessages = (query) => searchStore(store, account, query, messenger), meaning) => {
58
- if (!request.text.trim())
58
+ export const searchAll = async (store, account, asked, messenger = {}, searchMessages = (query) => searchStore(store, account, query, messenger), meaning) => {
59
+ if (!asked.text.trim())
59
60
  throw new CliError("validation_error", "say what to find");
61
+ const request = { ...asked, text: plainQuery(asked.text) };
60
62
  const offset = request.offset ?? 0;
61
63
  if (!Number.isInteger(offset) || offset < 0 || offset > MAX_SEARCH_OFFSET)
62
64
  throw new CliError("validation_error", `offset takes a whole number from 0 to ${MAX_SEARCH_OFFSET}`);
@@ -293,7 +295,7 @@ export const searchAll = async (store, account, request, messenger = {}, searchM
293
295
  const ordered = oneList(lists, cosines);
294
296
  const more = hasMore || ordered.length > window;
295
297
  return {
296
- query: request.text,
298
+ query: asked.text,
297
299
  items: ordered.slice(offset, window),
298
300
  hasMore: more,
299
301
  ...(more && window <= MAX_SEARCH_OFFSET ? { nextOffset: window } : {}),
@@ -17,13 +17,15 @@ export const explainDamage = (health, command) => {
17
17
  const sources = tables.filter((table) => !isDerivedTable(table, indexNames));
18
18
  const derived = [...new Set([...tables.filter((table) => isDerivedTable(table, indexNames)), ...badIndexes])];
19
19
  const unopened = health.error !== undefined;
20
+ const json = (health.invalidJson ?? []).map(({ table, column }) => `${table}.${column}`);
20
21
  const what = unopened
21
22
  ? `the store file cannot be opened: ${health.error}`
22
23
  : health.checked === "quick"
23
24
  ? "the store file's header or schema is damaged"
24
25
  : `the store file is damaged: ${health.problems ?? 0} problems` +
25
26
  (sources.length ? ` in the data of ${named(sources)}` : "") +
26
- (derived.length ? `${sources.length ? ", and" : " in"} the search data of ${named(derived)}` : "");
27
+ (derived.length ? `${sources.length ? ", and" : " in"} the search data of ${named(derived)}` : "") +
28
+ (json.length ? `; values that are not valid JSON in ${named(json)}` : "");
27
29
  const impact = [
28
30
  ...(sources.length
29
31
  ? [`some rows of ${named(sources)} cannot be read; a recovery keeps every row it can read and names the rest`]
@@ -31,6 +33,9 @@ export const explainDamage = (health, command) => {
31
33
  ...(derived.length
32
34
  ? [`searches may miss results or fail; ${named(derived)} hold nothing that is not elsewhere, and are rebuilt`]
33
35
  : []),
36
+ ...(json.length
37
+ ? [`a read of a row with a broken JSON value fails ("malformed JSON"); a recovery clears those values`]
38
+ : []),
34
39
  "reads that do not touch a damaged page work; a write that touches one fails until the store is recovered",
35
40
  ];
36
41
  return {
@@ -27,8 +27,23 @@ export interface StoreHealth {
27
27
  /** Lines `quick_check` gave in all, capped at `QUICK_CHECK_LIMIT`. */
28
28
  problems?: number;
29
29
  searchIndexes?: SearchIndexHealth[];
30
+ /** Deep only: values the tools read as JSON that SQLite's JSON functions refuse, so a read of the row fails. */
31
+ invalidJson?: InvalidJson[];
30
32
  ms: number;
31
33
  }
34
+ export interface InvalidJson {
35
+ table: string;
36
+ column: string;
37
+ rows: number;
38
+ /** The column may not be NULL, so a recovery drops the row instead of clearing the value. */
39
+ required: boolean;
40
+ }
41
+ export declare const jsonColumns: (database: CacheDatabase) => {
42
+ table: string;
43
+ column: string;
44
+ required: boolean;
45
+ }[];
46
+ export declare const invalidJson: (database: CacheDatabase) => InvalidJson[];
32
47
  export declare const QUICK_CHECK_LIMIT = 10000;
33
48
  /** What `doctor` checks by default, said where it answers. */
34
49
  export declare const QUICK_HEALTH_CHECKS = "the file header, its size against its page count, and the schema's own pages";
@@ -1,5 +1,33 @@
1
1
  import { existsSync, statSync } from "node:fs";
2
2
  import { openSqlite } from "./sqlite/open.js";
3
+ /** Besides every `metadata` column: the TEXT columns the tools read with SQLite's JSON functions or JSON.parse. */
4
+ const JSON_COLUMNS = {
5
+ accounts: ["settings"],
6
+ account_identities: ["mail_signals"],
7
+ bot_updates: ["payload"],
8
+ documents: ["front_matter"],
9
+ emails: ["headers"],
10
+ meeting_participants: ["sessions"],
11
+ messages: ["mentions", "reply_to"],
12
+ proposed_actions: ["payload", "result"],
13
+ searches: ["params"],
14
+ tag_consolidations: ["source_member_ids", "survivor_member_ids"],
15
+ task_events: ["changes"],
16
+ };
17
+ export const jsonColumns = (database) => database
18
+ .prepare(`SELECT m.name AS "table", c.name AS "column", c."notnull" AS required FROM sqlite_master m, pragma_table_info(m.name) c
19
+ WHERE m.type = 'table' AND m.sql NOT LIKE 'CREATE VIRTUAL%' ORDER BY 1, 2`)
20
+ .all()
21
+ .map((row) => ({ table: String(row.table), column: String(row.column), required: Number(row.required) === 1 }))
22
+ .filter(({ table, column }) => column === "metadata" || JSON_COLUMNS[table]?.includes(column));
23
+ export const invalidJson = (database) => jsonColumns(database)
24
+ .map((one) => ({
25
+ ...one,
26
+ rows: Number(database
27
+ .prepare(`SELECT count(*) AS n FROM "${one.table}" WHERE "${one.column}" IS NOT NULL AND NOT json_valid("${one.column}")`)
28
+ .get()?.n),
29
+ }))
30
+ .filter(({ rows }) => rows > 0);
3
31
  export const QUICK_CHECK_LIMIT = 10_000;
4
32
  /** What `doctor` checks by default, said where it answers. */
5
33
  export const QUICK_HEALTH_CHECKS = "the file header, its size against its page count, and the schema's own pages";
@@ -153,12 +181,14 @@ export const storeHealth = async (path, { deep = false } = {}) => {
153
181
  const lines = checkLines(database);
154
182
  const pagesOk = lines.length === 1 && lines[0] === "ok";
155
183
  const indexes = searchIndexHealth(database);
184
+ const json = pagesOk ? invalidJson(database) : [];
156
185
  return done({
157
- ok: pagesOk && problems.length === 0 && indexes.every((index) => index.ok),
186
+ ok: pagesOk && problems.length === 0 && indexes.every((index) => index.ok) && json.length === 0,
158
187
  file,
159
188
  problems: pagesOk ? 0 : lines.length,
160
189
  damagedTables: pagesOk ? [] : damagedTables(database, lines),
161
190
  searchIndexes: indexes,
191
+ invalidJson: json,
162
192
  });
163
193
  }
164
194
  catch (error) {
@@ -17,7 +17,7 @@ export { applyDocumentTransfer, previewDocumentTransfer } from "./document-trans
17
17
  export type { CacheDatabase, CacheStatement, OpenDatabase, SqlValue } from "./driver.js";
18
18
  export { PRAGMAS } from "./driver.js";
19
19
  export { EVIDENCE_FINDINGS_KIND, type EvidenceFindingsBatch, type EvidenceFindingsDecider, type EvidenceFindingsReceipt, type EvidenceFindingsStore, validateEvidenceFindings, } from "./evidence-findings.js";
20
- export { type DamagedTable, QUICK_HEALTH_CHECKS, type SearchIndexHealth, type StoreHealth, storeHealth, } from "./health.js";
20
+ export { type DamagedTable, type InvalidJson, QUICK_HEALTH_CHECKS, type SearchIndexHealth, type StoreHealth, storeHealth, } from "./health.js";
21
21
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
22
22
  export { MAIL_FINDINGS_KIND, type MailFindingsBatch, type MailFindingsCheck, type MailFindingsStore, } from "./mail-findings.js";
23
23
  export type { MeetingFindingsBatch, MeetingFindingsStore } from "./meeting-findings.js";
@@ -1,5 +1,5 @@
1
1
  import type { CacheDatabase } from "./driver.js";
2
- import { type StoreHealth } from "./health.js";
2
+ import { type InvalidJson, type StoreHealth } from "./health.js";
3
3
  /** `contentless_delete`, which every word index uses, came in SQLite 3.43. */
4
4
  export declare const SQLITE3_MINIMUM: readonly [3, 43, 0];
5
5
  export declare const sqlite3Program: (program?: string) => {
@@ -9,7 +9,12 @@ export declare const sqlite3Program: (program?: string) => {
9
9
  };
10
10
  /** The WireCat timers still scheduled: each may open the store while it is being recovered. Linux only. */
11
11
  export declare const activeTimers: () => string[] | undefined;
12
- /** Processes that have any of the store's files open, by PID and program name, never their arguments. */
12
+ /** The process recovering the store now, from the lock file it keeps beside it; a lock whose process ended is none. */
13
+ export declare const runningRecovery: (path: string) => number | null;
14
+ /**
15
+ * Processes that have any of the store's files open, by PID and program name, never their arguments, and the one
16
+ * recovering it.
17
+ */
13
18
  export declare const storeHolders: (path: string) => {
14
19
  pid: number;
15
20
  name: string;
@@ -53,6 +58,11 @@ export interface DanglingRows {
53
58
  }
54
59
  /** Rows that point at a row the store does not hold: after a recovery, mostly rows that could not be read. */
55
60
  export declare const danglingRows: (database: CacheDatabase) => DanglingRows[];
61
+ /**
62
+ * Sets each value the tools read as JSON that SQLite's JSON functions refuse to NULL, or drops its row where the
63
+ * column may not be NULL: `.recover` copies a damaged value that still reads, and a JSON read of it fails.
64
+ */
65
+ export declare const clearInvalidJson: (database: CacheDatabase) => InvalidJson[];
56
66
  export interface LostRows {
57
67
  table: string;
58
68
  before: number | null;
@@ -69,6 +79,8 @@ export interface Recovery {
69
79
  */
70
80
  lost: LostRows[];
71
81
  dangling: DanglingRows[];
82
+ /** Values that were not valid JSON: set to NULL, or the row dropped where `required`. */
83
+ invalidJson: InvalidJson[];
72
84
  mailToFetch: {
73
85
  account: string;
74
86
  emails: number;
@@ -4,7 +4,7 @@ import { basename, dirname, join } from "node:path";
4
4
  import { Transform } from "node:stream";
5
5
  import { CliError } from "@wirecat/cli-base";
6
6
  import { holdersOf } from "../background/processes.js";
7
- import { fts5Tables, storeHealth } from "./health.js";
7
+ import { fts5Tables, invalidJson, storeHealth } from "./health.js";
8
8
  import { migrate } from "./migrations.js";
9
9
  import { resetAttachmentWords } from "./sqlite/attachment-texts.js";
10
10
  import { involvementStoreOver } from "./sqlite/involvements.js";
@@ -19,6 +19,7 @@ import { fillVectorIndexes } from "./sqlite/vector-index.js";
19
19
  /** `contentless_delete`, which every word index uses, came in SQLite 3.43. */
20
20
  export const SQLITE3_MINIMUM = [3, 43, 0];
21
21
  const STORE_PARTS = ["", "-wal", "-shm"];
22
+ const RECOVER_LOCK = ".recover-lock";
22
23
  /** The start of a row `.recover` writes; a value's own lines cannot start a line with it, its quotes are doubled. */
23
24
  const INSERTED = /^INSERT OR IGNORE INTO '([^']+)'/;
24
25
  const LOST_AND_FOUND = "recover_lost_and_found";
@@ -65,13 +66,66 @@ export const activeTimers = () => {
65
66
  return undefined;
66
67
  }
67
68
  };
68
- /** Processes that have any of the store's files open, by PID and program name, never their arguments. */
69
+ const alive = (pid) => {
70
+ try {
71
+ process.kill(pid, 0);
72
+ return true;
73
+ }
74
+ catch (error) {
75
+ return error.code === "EPERM";
76
+ }
77
+ };
78
+ /** The process recovering the store now, from the lock file it keeps beside it; a lock whose process ended is none. */
79
+ export const runningRecovery = (path) => {
80
+ let pid;
81
+ try {
82
+ pid = Number(readFileSync(`${path}${RECOVER_LOCK}`, "utf8").trim());
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ return Number.isInteger(pid) && pid > 0 && alive(pid) ? pid : null;
88
+ };
89
+ /** Between its copy and its swap a recovery holds none of the store's files, so only its lock shows it. */
90
+ const takeRecoverLock = (path) => {
91
+ const lock = `${path}${RECOVER_LOCK}`;
92
+ const take = () => writeFileSync(lock, String(process.pid), { flag: "wx", mode: 0o600 });
93
+ try {
94
+ take();
95
+ }
96
+ catch (error) {
97
+ if (error.code !== "EEXIST")
98
+ throw error;
99
+ const pid = runningRecovery(path);
100
+ if (pid === null) {
101
+ rmSync(lock, { force: true });
102
+ take();
103
+ }
104
+ else {
105
+ throw new CliError("validation_error", `the store is being recovered by process ${pid} — wait for it to finish`, {
106
+ reason: "store.recovering",
107
+ });
108
+ }
109
+ }
110
+ return () => rmSync(lock, { force: true });
111
+ };
112
+ /**
113
+ * Processes that have any of the store's files open, by PID and program name, never their arguments, and the one
114
+ * recovering it.
115
+ */
69
116
  export const storeHolders = (path) => {
70
117
  const folder = realpathSync(dirname(path));
71
118
  const files = STORE_PARTS.map((suffix) => join(folder, `${basename(path)}${suffix}`));
72
119
  // A process that kept writing after its log was deleted holds it as "<path> (deleted)" (BUG-557).
73
120
  const wanted = process.platform === "linux" ? files.flatMap((file) => [file, `${file} (deleted)`]) : files.filter(existsSync);
74
- return holdersOf(wanted)?.map((pid) => {
121
+ const recovering = runningRecovery(path);
122
+ const pids = holdersOf(wanted);
123
+ if (pids === undefined && recovering === null)
124
+ return undefined;
125
+ const all = [
126
+ ...new Set([...(pids ?? []), ...(recovering !== null && recovering !== process.pid ? [recovering] : [])]),
127
+ ];
128
+ return all.map((pid) => {
75
129
  let name = "?";
76
130
  try {
77
131
  name = readFileSync(`/proc/${pid}/comm`, "utf8").trim();
@@ -278,13 +332,20 @@ const mailToFetch = (database) => {
278
332
  return [];
279
333
  }
280
334
  };
281
- /** The file and its log; the shared-memory file changes on every read, so it says nothing. */
282
- const fingerprint = (path) => ["", "-wal"]
283
- .map((suffix) => {
284
- const stat = statSync(`${path}${suffix}`, { throwIfNoEntry: false });
285
- return stat ? `${stat.size}:${stat.mtimeMs}` : "-";
286
- })
287
- .join("|");
335
+ /**
336
+ * Sets each value the tools read as JSON that SQLite's JSON functions refuse to NULL, or drops its row where the
337
+ * column may not be NULL: `.recover` copies a damaged value that still reads, and a JSON read of it fails.
338
+ */
339
+ export const clearInvalidJson = (database) => {
340
+ const found = invalidJson(database);
341
+ for (const { table, column, required } of found) {
342
+ const invalid = `"${column}" IS NOT NULL AND NOT json_valid("${column}")`;
343
+ database.exec(required
344
+ ? `DELETE FROM "${table}" WHERE ${invalid}`
345
+ : `UPDATE "${table}" SET "${column}" = NULL WHERE ${invalid}`);
346
+ }
347
+ return found;
348
+ };
288
349
  const refuseInUse = (path) => {
289
350
  const holders = storeHolders(path);
290
351
  if (holders && holders.length > 0) {
@@ -307,98 +368,121 @@ export const recoverStore = async ({ path, command, version, sqlite3 = "sqlite3"
307
368
  ? `sqlite3 ${program.version} cannot recover: the recovery needs ${SQLITE3_MINIMUM.join(".")} or newer, built with .recover`
308
369
  : "the recovery needs the sqlite3 program with its .recover command: install it (apt install sqlite3, brew install sqlite)", { reason: "store.sqlite3-missing" });
309
370
  }
310
- refuseInUse(path);
311
- const bytes = STORE_PARTS.reduce((sum, suffix) => sum + (statSync(`${path}${suffix}`, { throwIfNoEntry: false })?.size ?? 0), 0);
312
- const { bavail, bsize } = statfsSync(dirname(path));
313
- if (Number(bavail) * Number(bsize) < bytes * 1.2)
314
- throw new CliError("validation_error", `the recovery needs about ${Math.ceil((bytes * 1.2) / 1e9)} GB free beside the store`);
315
- const old = await openSqlite(path, { readOnly: true });
316
- let rowsBefore;
371
+ const releaseLock = takeRecoverLock(path);
317
372
  try {
318
- rowsBefore = tableRows(old.database);
373
+ refuseInUse(path);
374
+ const bytes = STORE_PARTS.reduce((sum, suffix) => sum + (statSync(`${path}${suffix}`, { throwIfNoEntry: false })?.size ?? 0), 0);
375
+ const { bavail, bsize } = statfsSync(dirname(path));
376
+ if (Number(bavail) * Number(bsize) < bytes * 1.2)
377
+ throw new CliError("validation_error", `the recovery needs about ${Math.ceil((bytes * 1.2) / 1e9)} GB free beside the store`);
378
+ return await recoverLocked({ path, command, version, sqlite3, now, note, copy, started, program });
319
379
  }
320
380
  finally {
321
- old.database.close();
381
+ releaseLock();
322
382
  }
323
- const before = fingerprint(path);
324
- const stamp = new Date(now()).toISOString().replace(/[:.]/g, "-");
325
- const target = `${path}.recovering-${stamp}`;
326
- writeFileSync(target, "", { flag: "wx", mode: 0o600 });
327
- const dropTarget = () => {
328
- for (const suffix of [...STORE_PARTS, "-journal"])
329
- rmSync(`${target}${suffix}`, { force: true });
383
+ };
384
+ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy, started, program, }) => {
385
+ // Kept open to the swap: data_version moves only when another connection commits, never for a reader's
386
+ // checkpoint or a log reset, which change the files' times and sizes but not one row.
387
+ const watch = (await openSqlite(path, { readOnly: true })).database;
388
+ let watching = true;
389
+ const stopWatching = () => {
390
+ if (watching)
391
+ watch.close();
392
+ watching = false;
330
393
  };
331
- note(`copying the readable rows into ${target}`);
332
- let copied;
333
- let copyErrors;
334
- let read;
335
- let opened;
336
394
  try {
337
- ;
338
- ({ errors: copyErrors, read } = await (copy ?? ((from, to) => copyReadableRows(from, to, sqlite3)))(path, target));
339
- copied = Date.now();
340
- opened = await openSqlite(target);
341
- }
342
- catch (error) {
343
- dropTarget();
344
- throw error;
345
- }
346
- let rebuilt;
347
- let kept;
348
- let dangling;
349
- let fetch;
350
- try {
351
- kept = tableRows(opened.database);
352
- migrate(opened.database, { command, ...(version ? { version } : {}) });
353
- rebuilt = rebuildDerived(opened.database, { now, note });
354
- note("looking for rows that point at rows that were lost");
355
- dangling = danglingRows(opened.database);
356
- fetch = mailToFetch(opened.database);
357
- opened.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
358
- }
359
- catch (error) {
395
+ const dataVersion = () => Number(watch.prepare("PRAGMA data_version").get()?.data_version);
396
+ const rowsBefore = tableRows(watch);
397
+ const before = { data: dataVersion(), inode: statSync(path).ino };
398
+ const stamp = new Date(now()).toISOString().replace(/[:.]/g, "-");
399
+ const target = `${path}.recovering-${stamp}`;
400
+ writeFileSync(target, "", { flag: "wx", mode: 0o600 });
401
+ const dropTarget = () => {
402
+ for (const suffix of [...STORE_PARTS, "-journal"])
403
+ rmSync(`${target}${suffix}`, { force: true });
404
+ };
405
+ note(`copying the readable rows into ${target}`);
406
+ let copied;
407
+ let copyErrors;
408
+ let read;
409
+ let opened;
410
+ try {
411
+ ;
412
+ ({ errors: copyErrors, read } = await (copy ?? ((from, to) => copyReadableRows(from, to, sqlite3)))(path, target));
413
+ copied = Date.now();
414
+ opened = await openSqlite(target);
415
+ }
416
+ catch (error) {
417
+ dropTarget();
418
+ throw error;
419
+ }
420
+ let rebuilt;
421
+ let kept;
422
+ let dangling;
423
+ let json;
424
+ let fetch;
425
+ try {
426
+ kept = tableRows(opened.database);
427
+ migrate(opened.database, { command, ...(version ? { version } : {}) });
428
+ note("clearing values that are not valid JSON");
429
+ json = clearInvalidJson(opened.database);
430
+ rebuilt = rebuildDerived(opened.database, { now, note });
431
+ note("looking for rows that point at rows that were lost");
432
+ dangling = danglingRows(opened.database);
433
+ fetch = mailToFetch(opened.database);
434
+ opened.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
435
+ }
436
+ catch (error) {
437
+ opened.database.close();
438
+ dropTarget();
439
+ throw error;
440
+ }
360
441
  opened.database.close();
361
- dropTarget();
362
- throw error;
363
- }
364
- opened.database.close();
365
- const rebuiltAt = Date.now();
366
- note("checking the recovered file");
367
- const health = await storeHealth(target, { deep: true });
368
- const checkedAt = Date.now();
369
- if (!health.ok) {
370
- throw new CliError("validation_error", `the recovered file did not pass its check, so the store was left as it was; the file is kept at ${target}`, { reason: "store.recovery-failed" });
442
+ const rebuiltAt = Date.now();
443
+ note("checking the recovered file");
444
+ const health = await storeHealth(target, { deep: true });
445
+ const checkedAt = Date.now();
446
+ if (!health.ok) {
447
+ throw new CliError("validation_error", `the recovered file did not pass its check, so the store was left as it was; the file is kept at ${target}`, { reason: "store.recovery-failed" });
448
+ }
449
+ refuseInUse(path);
450
+ const changed = dataVersion() !== before.data || statSync(path, { throwIfNoEntry: false })?.ino !== before.inode;
451
+ stopWatching();
452
+ if (changed) {
453
+ throw new CliError("validation_error", `the store was written to during the recovery, so it was left as it was — stop every timer and run it again; ${target} can be deleted`, { reason: "store.changed-during-recovery" });
454
+ }
455
+ const keptAt = `${path}.before-recover-${stamp}`;
456
+ for (const suffix of STORE_PARTS)
457
+ if (existsSync(`${path}${suffix}`))
458
+ renameSync(`${path}${suffix}`, `${keptAt}${suffix}`);
459
+ for (const suffix of STORE_PARTS)
460
+ if (existsSync(`${target}${suffix}`))
461
+ renameSync(`${target}${suffix}`, `${path}${suffix}`);
462
+ const lost = Object.entries(rowsBefore)
463
+ .map(([table, before]) => ({ table, before, read: read[table] ?? 0, kept: kept[table] ?? 0 }))
464
+ .filter(({ before, read, kept }) => before === null || before > kept || read > kept);
465
+ const seconds = (from, to) => Math.round((to - from) / 100) / 10;
466
+ return {
467
+ path,
468
+ keptAt,
469
+ sqlite3: program.version,
470
+ lost,
471
+ dangling,
472
+ invalidJson: json,
473
+ mailToFetch: fetch,
474
+ rebuilt,
475
+ copyErrors,
476
+ health,
477
+ seconds: {
478
+ copy: seconds(started, copied),
479
+ rebuild: seconds(copied, rebuiltAt),
480
+ check: seconds(rebuiltAt, checkedAt),
481
+ total: seconds(started, Date.now()),
482
+ },
483
+ };
371
484
  }
372
- refuseInUse(path);
373
- if (fingerprint(path) !== before) {
374
- throw new CliError("validation_error", `the store was written to during the recovery, so it was left as it was — stop every timer and run it again; ${target} can be deleted`, { reason: "store.changed-during-recovery" });
485
+ finally {
486
+ stopWatching();
375
487
  }
376
- const keptAt = `${path}.before-recover-${stamp}`;
377
- for (const suffix of STORE_PARTS)
378
- if (existsSync(`${path}${suffix}`))
379
- renameSync(`${path}${suffix}`, `${keptAt}${suffix}`);
380
- for (const suffix of STORE_PARTS)
381
- if (existsSync(`${target}${suffix}`))
382
- renameSync(`${target}${suffix}`, `${path}${suffix}`);
383
- const lost = Object.entries(rowsBefore)
384
- .map(([table, before]) => ({ table, before, read: read[table] ?? 0, kept: kept[table] ?? 0 }))
385
- .filter(({ before, read, kept }) => before === null || before > kept || read > kept);
386
- const seconds = (from, to) => Math.round((to - from) / 100) / 10;
387
- return {
388
- path,
389
- keptAt,
390
- sqlite3: program.version,
391
- lost,
392
- dangling,
393
- mailToFetch: fetch,
394
- rebuilt,
395
- copyErrors,
396
- health,
397
- seconds: {
398
- copy: seconds(started, copied),
399
- rebuild: seconds(copied, rebuiltAt),
400
- check: seconds(rebuiltAt, checkedAt),
401
- total: seconds(started, Date.now()),
402
- },
403
- };
404
488
  };
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError } from "@wirecat/cli-base";
3
- import { formatMeetingReference, parseMeetingQuery } from "../../meetings/index.js";
3
+ import { formatMeetingReference, MEETING_FIELD_NAMES, parseMeetingQuery } from "../../meetings/index.js";
4
+ import { plainQuery } from "../../search/lucene/plain.js";
4
5
  import { matchMeetingText, meetingQuerySql, resolveMeetingQuery } from "./meeting-hit-query.js";
5
6
  import { indexedText } from "./meeting-index-values.js";
6
7
  import { checkMeetingCancelled } from "./meeting-operation.js";
@@ -90,7 +91,7 @@ export function meetingHitSearchOver({ database }) {
90
91
  fail("Meeting search byte limit must be from 1 through 67108864");
91
92
  if (typeof rawQuery === "string" && Buffer.byteLength(rawQuery) > 65536)
92
93
  fail("Meeting search query must be a bounded string");
93
- const ast = typeof rawQuery === "string" ? parseMeetingQuery(rawQuery) : rawQuery;
94
+ const ast = typeof rawQuery === "string" ? parseMeetingQuery(plainQuery(rawQuery, MEETING_FIELD_NAMES)) : rawQuery;
94
95
  return read(database, () => {
95
96
  checkMeetingCancelled(input.signal);
96
97
  const state = meetingStemState(database, input.accountId);
@@ -122,7 +122,6 @@
122
122
  }
123
123
  ],
124
124
  "negative": [
125
- { "query": "foo:bar", "code": "validation_error", "reason": "query.unknown-field" },
126
125
  { "query": "tag:\"two words\"", "code": "validation_error", "reason": "query.invalid-tag" },
127
126
  { "query": "size>10TB", "code": "validation_error", "reason": "query.invalid-size" },
128
127
  { "query": "invoice~1", "code": "validation_error", "reason": "query.unsupported-operator" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.601.0",
3
+ "version": "0.602.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",