@wirecat/cli-core 0.430.0 → 0.432.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 (46) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/dist/cli/config-issues.d.ts +30 -0
  3. package/dist/cli/config-issues.js +90 -12
  4. package/dist/cli/config-keys.js +6 -7
  5. package/dist/cli/index.d.ts +1 -1
  6. package/dist/cli/index.js +1 -1
  7. package/dist/cli/messenger/conversation-answers.d.ts +1 -0
  8. package/dist/cli/messenger/conversations-command.js +11 -3
  9. package/dist/cli/messenger/message-answers.d.ts +1 -0
  10. package/dist/cli/messenger/message-writes.d.ts +2 -0
  11. package/dist/cli/messenger/messages-search-command.js +11 -1
  12. package/dist/cli/messenger/private-files.js +8 -4
  13. package/dist/cli/messenger/search-answers.js +13 -0
  14. package/dist/cli/settings.js +12 -43
  15. package/dist/cli/steps.js +6 -0
  16. package/dist/entities/conversation-preparation.d.ts +10 -0
  17. package/dist/entities/conversation-preparation.js +2 -0
  18. package/dist/entities/conversation-results.d.ts +10 -0
  19. package/dist/entities/evidence.d.ts +8 -0
  20. package/dist/entities/index.d.ts +45 -0
  21. package/dist/entities/listener.d.ts +4 -0
  22. package/dist/entities/message-context.d.ts +3 -0
  23. package/dist/entities/message-transfer.d.ts +8 -0
  24. package/dist/entities/message-write.d.ts +4 -0
  25. package/dist/entities/message.d.ts +2 -0
  26. package/dist/entities/message.js +2 -0
  27. package/dist/entities/store-records.d.ts +5 -0
  28. package/dist/services/embeddings-maintenance.js +71 -2
  29. package/dist/services/embeddings-search.js +3 -1
  30. package/dist/services/embeddings.d.ts +7 -0
  31. package/dist/services/messages-archive-search.d.ts +2 -1
  32. package/dist/services/messages-archive-search.js +4 -4
  33. package/dist/services/messages-discovery.d.ts +24 -1
  34. package/dist/services/messages-discovery.js +61 -4
  35. package/dist/services/messages-meaning.d.ts +7 -0
  36. package/dist/services/messages-meaning.js +53 -0
  37. package/dist/services/messages-search.d.ts +5 -0
  38. package/dist/services/messages.d.ts +5 -0
  39. package/dist/services/messages.js +2 -1
  40. package/dist/services/search-catchup.js +1 -0
  41. package/dist/store/sqlite/message-chunks.d.ts +44 -0
  42. package/dist/store/sqlite/message-chunks.js +76 -0
  43. package/dist/store/sqlite/vectors.js +4 -1
  44. package/dist/store/vectors.d.ts +36 -0
  45. package/dist/store/vectors.js +54 -0
  46. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,7 +5,25 @@ 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.432.0 — 25.10.2026
9
+
10
+ ### Added
11
+
12
+ - **`search messages --discover` also searches by meaning, on its own, once it can.** When e5-small is downloaded and messages have their own vectors, discovery adds the 100 messages nearest in meaning to its word matches and merges the two lists by reciprocal rank fusion (k = 60), as arm A2 of the [evidence-pipeline benchmark](https://github.com/WireCatLabs/cli-testing/tree/main/performance/search/evidence-pipeline) did. The question's filters apply to both. Each hit's `discovery.found_by` says which list found it, and `score` is then the fused score. Otherwise discovery searches by words exactly as before and says why meaning was not used: a `meaning search not used: …` note in the terminal, and `missing`/`next` (`models.download` or `conversations.rebuild`) in `--json` and MCP. A search never downloads a model and never sends text anywhere. `--exact`, `--newest` and strict queries are untouched.
13
+ - **`conversations rebuild`, and `conversations embed` without `--chat`, give each message its own vector** with the default local model, within the same `--max-chunks` bound; the answer's `messages` says how many were embedded and how many are left. Messages edited since are embedded again, and deleted ones lose their vectors. A search's catch-up never does this.
14
+
15
+ ## 0.431.0 — 25.10.2026
16
+
17
+ ### Added
18
+
19
+ - **`readConfigText(path)`, `readConfigFile(path)`, `withoutSetting(raw, setting)` and `settingPathOf(setting)` from `/cli`**, for a tool with its own config file and `config unset`. `readConfigText` gives the text, `undefined` for no file, or an issue for a folder at the path or a file that cannot be read. `readConfigFile` adds the JSON parse. `withoutSetting` removes one setting at any depth, list items included (`mail.accounts.0.colour`, `permissions.messages.send`), and any object the removal leaves empty, but keeps a list item so the items after it keep their numbers.
20
+
21
+ ### Fixed
22
+
23
+ - **A bad setting inside a list item is removed alone.** Before, `checkConfigText` could not reach into a list. It reported `mail.accounts.0.colour`, then loaded the rest of the file as empty, and missed issues elsewhere (an unknown permission key) until the next run. Now everything else loads, and every issue is found in one pass, in nested lists too. An item of the wrong type is dropped, and the items after it are still named by their place in the file. `config unset` with no profile reaches a path through a list.
24
+ - **A config file that cannot be read is reported, not taken for no file.** A folder at the path gives `invalid_value` "the path is a folder, not a file"; a file this user may not read gives "the file could not be read". Neither has a `fix`. `loadSnakeCaseConfig` refuses both instead of using its fallback.
25
+ - **A file holding a list, a string, a number or `null` is refused as a whole**: `invalid_value` "the file must hold a JSON object", with no `key` and no `fix`. Before, valibot read `[]` as `{}`.
26
+ - **`privateFiles` suggests no file mode for a folder where a file should be**, or for a file where a folder should be: the config issue says what is wrong.
9
27
 
10
28
  ## 0.430.0 — 25.10.2026
11
29
 
@@ -46,6 +46,21 @@ export declare const permissionIssues: (saved: readonly {
46
46
  }) => LocatedIssue[];
47
47
  /** The file without the settings the issues name: what still loads, and what `config unset` would leave. */
48
48
  export declare const withoutIssues: (raw: unknown, issues: readonly LocatedIssue[]) => unknown;
49
+ /** The path `config unset <setting>` names: a permission key keeps its dots; a number is a list item. */
50
+ export declare const settingPathOf: (setting: string) => string[];
51
+ /**
52
+ * The file without one setting, at any depth and inside list items, and without any object the removal left empty
53
+ * — a list item stays, so the items after it keep their numbers. `removed` is false when nothing was there.
54
+ */
55
+ export declare const withoutPath: (raw: unknown, at: readonly string[]) => {
56
+ config: unknown;
57
+ removed: boolean;
58
+ };
59
+ /** `withoutPath` for a setting as `config unset` takes it: `mail.accounts.0.colour`, `permissions.messages.send`. */
60
+ export declare const withoutSetting: (raw: unknown, setting: string) => {
61
+ config: unknown;
62
+ removed: boolean;
63
+ };
49
64
  /** The public shape: where in the file is the loader's own business. */
50
65
  export declare const publicIssue: ({ at: _, ...issue }: LocatedIssue) => ConfigIssue;
51
66
  /**
@@ -68,3 +83,18 @@ export declare const checkConfigText: <T extends v.GenericSchema>(text: string,
68
83
  issues: ConfigIssue[];
69
84
  config: v.InferOutput<T> | undefined;
70
85
  };
86
+ /**
87
+ * A config file's text, `undefined` when there is no file, or the issue when one is there and cannot be read: a
88
+ * folder at the path, or a file this user may not read. Neither has a fix `config` could run.
89
+ */
90
+ export declare const readConfigText: (path: string) => {
91
+ text: string | undefined;
92
+ } | {
93
+ issue: ConfigIssue;
94
+ };
95
+ /** A config file as written, `raw: undefined` when there is none, or the one issue that stops it being read. */
96
+ export declare const readConfigFile: (path: string) => {
97
+ raw: unknown;
98
+ } | {
99
+ issue: ConfigIssue;
100
+ };
@@ -1,3 +1,4 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import * as v from "valibot";
2
3
  const isNode = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
4
  const SECTIONS = ["personal", "bot"];
@@ -171,12 +172,12 @@ const ruleOf = (issue) => {
171
172
  return issue.expected === null ? "has a value it does not take" : `has to be ${issue.expected}`;
172
173
  };
173
174
  /** One pass of the schema: valibot names only the first unknown key of each object. */
174
- const onePass = (raw, schema, context) => {
175
+ const onePass = (raw, schema, context, original) => {
175
176
  const result = v.safeParse(schema, raw);
176
177
  if (result.success)
177
178
  return [];
178
179
  return result.issues.map((issue) => {
179
- const at = keyOfPath(issue);
180
+ const at = original(keyOfPath(issue));
180
181
  const located = isPermissionKey(issue, at)
181
182
  ? locate("unknown_permission", at, context, (key) => `${key} names no command`)
182
183
  : isUnknownKey(issue)
@@ -186,6 +187,8 @@ const onePass = (raw, schema, context) => {
186
187
  : locate("invalid_value", at, context, (key) => at.length === 0 ? "the file has to be an object, in braces" : `setting ${key} ${ruleOf(issue)}`);
187
188
  if (located.kind === "missing_setting" || at.length === 0)
188
189
  delete located.fix;
190
+ if (at.length === 0)
191
+ delete located.key;
189
192
  return located;
190
193
  });
191
194
  };
@@ -193,7 +196,8 @@ const onePass = (raw, schema, context) => {
193
196
  export const schemaIssues = (raw, schema, context) => {
194
197
  const found = new Map();
195
198
  for (;;) {
196
- const fresh = onePass(withoutIssues(raw, [...found.values()]), schema, context).filter((issue) => !found.has(issue.at.join("\u0000")));
199
+ const { pruned, original } = prune(raw, [...found.values()].map(({ at }) => at));
200
+ const fresh = onePass(pruned, schema, context, original).filter((issue) => !found.has(issue.at.join("\u0000")));
197
201
  if (fresh.length === 0)
198
202
  return [...found.values()];
199
203
  for (const issue of fresh)
@@ -235,18 +239,60 @@ export const savedPermissionKeys = (raw) => scopes(raw).flatMap(([path, scope])
235
239
  export const permissionIssues = (saved, known, context) => saved
236
240
  .filter(({ key }) => !known.has(key))
237
241
  .map(({ at }) => locate("unknown_permission", at, context, (key) => `${key} names no command`));
242
+ const pathId = (path) => path.join("\u0000");
243
+ /**
244
+ * The file without the parts at `paths`, through objects and lists alike, and a map from a path in what is left
245
+ * back to the file: a list that lost an item numbers the rest differently.
246
+ */
247
+ const prune = (raw, paths) => {
248
+ const drop = new Set(paths.map(pathId));
249
+ const kept = new Map();
250
+ const walk = (node, at) => {
251
+ if (Array.isArray(node)) {
252
+ const indices = node.flatMap((_, index) => (drop.has(pathId([...at, String(index)])) ? [] : [index]));
253
+ kept.set(pathId(at), indices);
254
+ return indices.map((index) => walk(node[index], [...at, String(index)]));
255
+ }
256
+ if (!isNode(node))
257
+ return node;
258
+ return Object.fromEntries(Object.entries(node).flatMap(([key, item]) => drop.has(pathId([...at, key])) ? [] : [[key, walk(item, [...at, key])]]));
259
+ };
260
+ const pruned = drop.has("") ? {} : walk(raw, []);
261
+ const original = (path) => {
262
+ const at = [];
263
+ for (const part of path) {
264
+ const indices = kept.get(pathId(at));
265
+ at.push(indices ? String(indices[Number(part)] ?? part) : part);
266
+ }
267
+ return at;
268
+ };
269
+ return { pruned, original };
270
+ };
238
271
  /** The file without the settings the issues name: what still loads, and what `config unset` would leave. */
239
- export const withoutIssues = (raw, issues) => {
240
- if (issues.some((issue) => issue.at.length === 0))
241
- return {};
242
- const copy = structuredClone(raw);
243
- for (const { at } of issues) {
244
- const parent = at.slice(0, -1).reduce((node, key) => (isNode(node) ? node[key] : undefined), copy);
245
- if (isNode(parent))
246
- delete parent[at.at(-1)];
272
+ export const withoutIssues = (raw, issues) => prune(raw, issues.map(({ at }) => at)).pruned;
273
+ /** The path `config unset <setting>` names: a permission key keeps its dots; a number is a list item. */
274
+ export const settingPathOf = (setting) => setting.startsWith("permissions.") ? ["permissions", setting.slice("permissions.".length)] : setting.split(".");
275
+ /**
276
+ * The file without one setting, at any depth and inside list items, and without any object the removal left empty
277
+ * — a list item stays, so the items after it keep their numbers. `removed` is false when nothing was there.
278
+ */
279
+ export const withoutPath = (raw, at) => {
280
+ const valueAt = (path) => path.reduce((node, key) => (isNode(node) || Array.isArray(node) ? node[key] : undefined), raw);
281
+ if (at.length === 0 || valueAt(at) === undefined)
282
+ return { config: raw, removed: false };
283
+ let gone = [...at];
284
+ for (let parent = at.slice(0, -1); parent.length > 0; parent = parent.slice(0, -1)) {
285
+ if (Array.isArray(valueAt(parent.slice(0, -1))))
286
+ break;
287
+ const node = valueAt(parent);
288
+ if (!isNode(node) || Object.keys(node).some((key) => pathId([...parent, key]) !== pathId(gone)))
289
+ break;
290
+ gone = parent;
247
291
  }
248
- return copy;
292
+ return { config: prune(raw, [gone]).pruned, removed: true };
249
293
  };
294
+ /** `withoutPath` for a setting as `config unset` takes it: `mail.accounts.0.colour`, `permissions.messages.send`. */
295
+ export const withoutSetting = (raw, setting) => withoutPath(raw, settingPathOf(setting));
250
296
  /** The public shape: where in the file is the loader's own business. */
251
297
  export const publicIssue = ({ at: _, ...issue }) => issue;
252
298
  /**
@@ -272,6 +318,9 @@ export const checkConfigText = (text, { file, tool, schema, knownPermissions, })
272
318
  const parsed = parseConfigText(text, file);
273
319
  if ("issue" in parsed)
274
320
  return { issues: [publicIssue(parsed.issue)], config: undefined };
321
+ // valibot reads a list as an object, so `[]` would pass for `{}`.
322
+ if (!isNode(parsed.raw))
323
+ return { issues: [wholeFile(file, "the file must hold a JSON object")], config: undefined };
275
324
  const context = { file, tool };
276
325
  const located = schemaIssues(parsed.raw, schema, context);
277
326
  const loaded = v.safeParse(schema, withoutIssues(parsed.raw, located));
@@ -279,3 +328,32 @@ export const checkConfigText = (text, { file, tool, schema, knownPermissions, })
279
328
  const unknown = knownPermissions ? permissionIssues(savedPermissionKeys(config), knownPermissions, context) : [];
280
329
  return { issues: [...located, ...unknown].map(publicIssue), config };
281
330
  };
331
+ /** A problem with the file as a whole: no setting to name, and no `config unset` to remove it. */
332
+ const wholeFile = (file, what) => ({ kind: "invalid_value", file, what });
333
+ /**
334
+ * A config file's text, `undefined` when there is no file, or the issue when one is there and cannot be read: a
335
+ * folder at the path, or a file this user may not read. Neither has a fix `config` could run.
336
+ */
337
+ export const readConfigText = (path) => {
338
+ try {
339
+ return { text: readFileSync(path, "utf8") };
340
+ }
341
+ catch (error) {
342
+ const code = error.code;
343
+ if (code === "ENOENT")
344
+ return { text: undefined };
345
+ return {
346
+ issue: wholeFile(path, code === "EISDIR" ? "the path is a folder, not a file" : "the file could not be read"),
347
+ };
348
+ }
349
+ };
350
+ /** A config file as written, `raw: undefined` when there is none, or the one issue that stops it being read. */
351
+ export const readConfigFile = (path) => {
352
+ const read = readConfigText(path);
353
+ if ("issue" in read)
354
+ return read;
355
+ if (read.text === undefined)
356
+ return { raw: undefined };
357
+ const parsed = parseConfigText(read.text, path);
358
+ return "issue" in parsed ? { issue: publicIssue(parsed.issue) } : parsed;
359
+ };
@@ -1,6 +1,6 @@
1
- import { readFileSync } from "node:fs";
2
1
  import { CliError } from "@wirecat/cli-base";
3
2
  import * as v from "valibot";
3
+ import { readConfigText } from "./config-issues.js";
4
4
  const reasonOf = (issue) => {
5
5
  if (issue.expected === "never")
6
6
  return "is an unknown setting";
@@ -23,13 +23,12 @@ const problemOf = (issues) => {
23
23
  };
24
24
  /** Reads and checks a config file; a missing one is the fallback, a broken one an error naming its first problem. */
25
25
  export const loadSnakeCaseConfig = (path, schema, fallback) => {
26
- let text;
27
- try {
28
- text = readFileSync(path, "utf8");
29
- }
30
- catch {
26
+ const read = readConfigText(path);
27
+ if ("issue" in read)
28
+ throw new CliError("configuration_error", `${path}: ${read.issue.what}`);
29
+ if (read.text === undefined)
31
30
  return fallback();
32
- }
31
+ const text = read.text;
33
32
  let parsed;
34
33
  try {
35
34
  parsed = JSON.parse(text);
@@ -53,7 +53,7 @@ export { commandContract, type JsonSchema, SCHEMA_DIALECT } from "./command-cont
53
53
  export { type CommandRunOptions, type CommandRuns, commandRuns, providerEvent, providerRequest, type RunSettings, recordRuns, runSettings, type SavedRunSettings, } from "./command-runs.js";
54
54
  export { CONTRACT } from "./commands-command.js";
55
55
  export { refuseUnknownKey } from "./config-command.js";
56
- export { type ConfigIssue, type ConfigIssueKind, checkConfigText, issueMessage } from "./config-issues.js";
56
+ export { type ConfigIssue, type ConfigIssueKind, checkConfigText, issueMessage, readConfigFile, readConfigText, settingPathOf, withoutSetting, } from "./config-issues.js";
57
57
  export { loadSnakeCaseConfig } from "./config-keys.js";
58
58
  export { type AgentRun, type BaseContext, type BaseEnvironment, baseContext, environmentOf, outputFor, provide, secretInputOf, } from "./context.js";
59
59
  export { addContractInfo, type ContractEvidenceOptions, contractEvidence } from "./contract-evidence.js";
package/dist/cli/index.js CHANGED
@@ -46,7 +46,7 @@ export { commandContract, SCHEMA_DIALECT } from "./command-contract.js";
46
46
  export { commandRuns, providerEvent, providerRequest, recordRuns, runSettings, } from "./command-runs.js";
47
47
  export { CONTRACT } from "./commands-command.js";
48
48
  export { refuseUnknownKey } from "./config-command.js";
49
- export { checkConfigText, issueMessage } from "./config-issues.js";
49
+ export { checkConfigText, issueMessage, readConfigFile, readConfigText, settingPathOf, withoutSetting, } from "./config-issues.js";
50
50
  export { loadSnakeCaseConfig } from "./config-keys.js";
51
51
  export { baseContext, environmentOf, outputFor, provide, secretInputOf, } from "./context.js";
52
52
  export { addContractInfo, contractEvidence } from "./contract-evidence.js";
@@ -65,6 +65,7 @@ export declare const conversationShown: (account: AccountKey, { summary, message
65
65
  matched_terms: string[];
66
66
  missing_terms: string[];
67
67
  parent?: string | undefined;
68
+ found_by?: ("meaning" | "words")[] | undefined;
68
69
  } | undefined;
69
70
  context?: {
70
71
  ref: string;
@@ -339,7 +339,8 @@ export const conversationsCommand = (messenger) => {
339
339
  }))
340
340
  .summary("build and embed the chats that changed, on this machine only")
341
341
  .description("build, then embed with the model on this machine, the chats that changed since their build and the group " +
342
- "chats never built — or only --chat; bounded per run, so run it again for the rest; never asks the " +
342
+ "chats never built — or only --chat; with the default model, also each message on its own, which " +
343
+ "`search messages --discover` reads; bounded per run, so run it again for the rest; never asks the " +
343
344
  "messenger, downloads no model and sends no text anywhere")
344
345
  .option("--chat <chat>", messenger.chatArgument)).action(async function () {
345
346
  const options = this.optsWithGlobals();
@@ -429,8 +430,14 @@ const renderRefreshed = (command, context, refreshed) => {
429
430
  context.streams.data([
430
431
  ...refreshed.built.map((one) => `${one.chat} built: ${one.messages} messages → ${one.conversations} conversations\n`),
431
432
  ...refreshed.embedded.map((one) => `${one.chat} ${one.embedded} chunks embedded with ${one.model}\n`),
433
+ refreshed.messages?.embedded
434
+ ? `${refreshed.messages.embedded} messages embedded with ${refreshed.model}\n`
435
+ : "",
432
436
  ].join(""));
433
- if (refreshed.built.length + refreshed.embedded.length === 0 && refreshed.left.length === 0) {
437
+ if (refreshed.built.length + refreshed.embedded.length === 0 &&
438
+ refreshed.left.length === 0 &&
439
+ !refreshed.messages?.embedded &&
440
+ !refreshed.messages?.left) {
434
441
  context.renderer.note("every chat is up to date");
435
442
  }
436
443
  }
@@ -444,7 +451,7 @@ const notDownloaded = (root, model, lead) => {
444
451
  const [step] = runnable(root, [nextStep("models.download", { args: { model } })]);
445
452
  return `${lead}: ${model} is not downloaded${step?.kind === "command" ? ` — \`${stepLine(root, step)}\`` : ""}`;
446
453
  };
447
- const leftNotes = ({ model, modelAvailable, embedded, left }, root) => {
454
+ const leftNotes = ({ model, modelAvailable, embedded, left, messages }, root) => {
448
455
  const of = (needs) => left.filter((one) => one.needs === needs).map(({ chat }) => chat);
449
456
  const build = of("build");
450
457
  const embed = of("embed");
@@ -454,6 +461,7 @@ const leftNotes = ({ model, modelAvailable, embedded, left }, root) => {
454
461
  ? `still to embed: chat ${embed.join(", ")} — run it again, or raise --max-chats and --max-chunks`
455
462
  : "",
456
463
  embed.length > 0 && !modelAvailable && embedded.length === 0 ? notDownloaded(root, model, "nothing embedded") : "",
464
+ messages?.left ? `still to embed: ${messages.left} messages — run it again, or raise --max-chunks` : "",
457
465
  ].filter(Boolean);
458
466
  };
459
467
  const choiceOf = (options, messenger, context, extra) => embeddingChoice(options, messenger.app, context.settings, context.env, { ...extra, keyring: context.keyring });
@@ -42,6 +42,7 @@ export declare const threadAnswer: ({ items, ...thread }: ThreadContext, reader:
42
42
  matched_terms: string[];
43
43
  missing_terms: string[];
44
44
  parent?: string | undefined;
45
+ found_by?: ("meaning" | "words")[] | undefined;
45
46
  } | undefined;
46
47
  context?: {
47
48
  ref: string;
@@ -46,6 +46,7 @@ export declare const writtenAnswer: ({ operationId, sendId, message, messages, s
46
46
  matched_terms: string[];
47
47
  missing_terms: string[];
48
48
  parent?: string | undefined;
49
+ found_by?: ("meaning" | "words")[] | undefined;
49
50
  } | undefined;
50
51
  context?: {
51
52
  ref: string;
@@ -234,6 +235,7 @@ export declare const writtenAnswer: ({ operationId, sendId, message, messages, s
234
235
  matched_terms: string[];
235
236
  missing_terms: string[];
236
237
  parent?: string | undefined;
238
+ found_by?: ("meaning" | "words")[] | undefined;
237
239
  } | undefined;
238
240
  context?: {
239
241
  ref: string;
@@ -38,7 +38,8 @@ export const messagesSearchCommand = (messenger) => {
38
38
  .option("--newest", "newest first instead of best first")
39
39
  .option("--exact", "bare words and quotes match their exact form only, as exact:word does; text: still matches every form")
40
40
  .option("--context <n>", "messages before and after each hit; 2 in the terminal, 0 otherwise", wholeCount)
41
- .option("--discover", "find partial lexical matches and eligible replies in the local archive; results are evidence, not confirmed answers")
41
+ .option("--discover", "find partial word matches, eligible replies and, once messages have vectors, messages close in meaning in the " +
42
+ "local archive; results are evidence, not confirmed answers")
42
43
  .option("--timezone <zone>", "the IANA timezone for calendar date boundaries")
43
44
  .addHelpText("after", SAVE_HELP)
44
45
  .addHelpText("after", `${syncsFirst(messenger)
@@ -129,6 +130,15 @@ const searchAction = (messenger) => async function (given) {
129
130
  context.renderer.note(`${from} → ${to.join(", ")}`);
130
131
  for (const { source, reason } of found.skipped ?? [])
131
132
  context.renderer.note(`${source} not searched: ${reason}`);
133
+ const meaning = found.meaningSkipped;
134
+ if (meaning) {
135
+ const step = meaning.step === "models.download"
136
+ ? ` — \`${command} models download ${meaning.model}\`, then \`${command} conversations rebuild\` gives messages their vectors`
137
+ : meaning.step === "conversations.rebuild"
138
+ ? ` — \`${command} conversations rebuild\` gives messages their vectors, a batch a run`
139
+ : "";
140
+ context.renderer.note(`meaning search not used: ${meaning.reason}${step}`);
141
+ }
132
142
  if (found.picturesSkipped && found.picturesModel === undefined)
133
143
  context.renderer.note(`pictures not searched: ${found.picturesSkipped}`);
134
144
  const stemming = found.query?.stemming;
@@ -8,19 +8,23 @@ export const privateFiles = ({ files, dirs }, platform = process.platform) => {
8
8
  if (platform === "win32")
9
9
  return { checked: false, reason: "Windows has no Unix file modes" };
10
10
  const problems = [];
11
- const check = (path, want) => {
11
+ // A folder where a file should be, or the reverse, is a problem of its own; a mode is no fix for it.
12
+ const check = (path, want, folder) => {
12
13
  if (!existsSync(path))
13
14
  return;
14
- const mode = statSync(path).mode & 0o777;
15
+ const stat = statSync(path);
16
+ if (stat.isDirectory() !== folder)
17
+ return;
18
+ const mode = stat.mode & 0o777;
15
19
  if ((mode & 0o077) === 0)
16
20
  return;
17
21
  const octal = (value) => `0${value.toString(8)}`;
18
22
  problems.push({ path, mode: octal(mode), want: octal(want), fix: `chmod ${want.toString(8)} ${shellQuoted(path)}` });
19
23
  };
20
24
  for (const file of files)
21
- check(file, 0o600);
25
+ check(file, 0o600, false);
22
26
  for (const dir of dirs)
23
- check(dir, 0o700);
27
+ check(dir, 0o700, true);
24
28
  return { checked: true, ok: problems.length === 0, problems };
25
29
  };
26
30
  /** A SQLite database in write-ahead mode keeps its newest pages beside it. */
@@ -30,6 +30,7 @@ export const messageHitItem = (hit, query = "") => {
30
30
  matched_terms: hit.discovery.matchedTerms,
31
31
  missing_terms: hit.discovery.missingTerms,
32
32
  parent: hit.discovery.parent,
33
+ found_by: hit.discovery.foundBy,
33
34
  })
34
35
  : undefined,
35
36
  email: hit.email
@@ -100,6 +101,18 @@ const gapsOf = (found) => {
100
101
  step: "store.migrate",
101
102
  });
102
103
  }
104
+ const meaning = found.meaningSkipped;
105
+ if (meaning) {
106
+ if (meaning.step === "models.download")
107
+ next.push(nextStep("models.download", { args: { model: meaning.model } }));
108
+ if (meaning.step === "conversations.rebuild")
109
+ next.push(nextStep("conversations.rebuild", { args: {} }));
110
+ missing.push({
111
+ field: "discovery",
112
+ why: `searched by words only: ${meaning.reason}`,
113
+ ...(meaning.step ? { step: meaning.step } : {}),
114
+ });
115
+ }
103
116
  if (found.picturesModel !== undefined) {
104
117
  next.push(nextStep("models.download-image", { args: { model: found.picturesModel } }));
105
118
  missing.push({
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { existsSync } from "node:fs";
2
2
  import { CliError, configFilePath, resolvePaths, saveConfigFile } from "@wirecat/cli-base";
3
3
  import * as v from "valibot";
4
4
  import { AI_ENTRIES, resolveAISettings } from "../analysis/settings.js";
@@ -7,7 +7,7 @@ import { envName, readOnlyLockOf } from "../ports/app.js";
7
7
  import { assertOverridesTighten, CEILING_KEY, LEVELS, layerPermissions, permissionOverrides, RESOURCES, } from "../sends/permissions.js";
8
8
  import { storePath } from "../store/path.js";
9
9
  import { sharedConfigPath } from "../store/shared-config.js";
10
- import { checkConfigText, issueMessage, parseConfigText, publicIssue, savedPermissionKeys, schemaIssues, } from "./config-issues.js";
10
+ import { checkConfigText, issueMessage, readConfigFile, readConfigText, savedPermissionKeys, schemaIssues, settingPathOf, withoutPath, } from "./config-issues.js";
11
11
  import { DEFAULT_CONFIG, ensureDefaultConfig } from "./default-config.js";
12
12
  import { profilesHere } from "./messenger/accounts.js";
13
13
  import { usableProfileName } from "./profile.js";
@@ -144,27 +144,14 @@ export const settingsFor = (app, extension = {}) => {
144
144
  const configPathFor = ({ env = process.env, configDir }) => configFilePath(configDir ?? resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config);
145
145
  const readSchema = extension.schema ?? schema;
146
146
  const context = (file) => ({ file, tool: app.command });
147
- /** The file as written, `undefined` when there is none, or the issue that says it is not JSON. */
148
- const readRaw = (path) => {
149
- let text;
150
- try {
151
- text = readFileSync(path, "utf8");
152
- }
153
- catch {
154
- return { raw: undefined };
155
- }
156
- return parseConfigText(text, path);
157
- };
158
147
  /** The file with every problem found; what loads is the file without the settings they name. */
159
148
  const loadConfig = (path) => {
160
- let text;
161
- try {
162
- text = readFileSync(path, "utf8");
163
- }
164
- catch {
149
+ const read = readConfigText(path);
150
+ if ("issue" in read)
151
+ return { config: { profiles: {} }, issues: [read.issue] };
152
+ if (read.text === undefined)
165
153
  return { config: { profiles: {} }, issues: [] };
166
- }
167
- const { config, issues } = checkConfigText(text, { file: path, tool: app.command, schema: readSchema });
154
+ const { config, issues } = checkConfigText(read.text, { file: path, tool: app.command, schema: readSchema });
168
155
  return { config: (config ?? { profiles: {} }), issues };
169
156
  };
170
157
  /**
@@ -365,9 +352,9 @@ export const settingsFor = (app, extension = {}) => {
365
352
  const level = name === "permissions" && rest.length > 0 ? rest.join(".") : undefined;
366
353
  const modelField = /^models\.([a-z][a-z0-9-]*)\.(provider|model|base_url)$/.exec(setting);
367
354
  const known = allSettings.includes(setting) || level !== undefined || modelField !== null;
368
- const read = readRaw(path);
355
+ const read = readConfigFile(path);
369
356
  if ("issue" in read)
370
- throw new CliError("configuration_error", issueMessage([publicIssue(read.issue)]));
357
+ throw new CliError("configuration_error", issueMessage([read.issue]));
371
358
  const raw = read.raw === undefined ? {} : read.raw;
372
359
  if (!isScope(raw))
373
360
  throw new CliError("configuration_error", `${path}: the file has to be an object, in braces`);
@@ -375,7 +362,7 @@ export const settingsFor = (app, extension = {}) => {
375
362
  ? []
376
363
  : [...(kind === undefined ? [] : [kind]), ...(profile === undefined ? ["defaults"] : ["profiles", profile])];
377
364
  const keyPath = root
378
- ? setting.split(".")
365
+ ? settingPathOf(setting)
379
366
  : level !== undefined
380
367
  ? ["permissions", level]
381
368
  : modelField
@@ -388,9 +375,7 @@ export const settingsFor = (app, extension = {}) => {
388
375
  throw new CliError("validation_error", `${setting} has no problem to remove — name the profile, or add --defaults, to unset a setting`);
389
376
  if (!known && valueAt(raw, at) === undefined)
390
377
  throw new CliError("validation_error", `no setting called "${setting}" — one of: ${allSettings.join(", ")}`);
391
- const changed = structuredClone(raw);
392
- removeAt(changed, at);
393
- saveConfigFile(path, changed);
378
+ saveConfigFile(path, withoutPath(raw, at).config);
394
379
  return null;
395
380
  }
396
381
  if (!known)
@@ -417,7 +402,7 @@ export const settingsFor = (app, extension = {}) => {
417
402
  return { resolveSettings, configuredProfiles, changeSetting, allSettings, defaultsOnlyKeys, schema };
418
403
  };
419
404
  const isScope = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
420
- const valueAt = (node, path) => path.reduce((at, key) => (isScope(at) ? at[key] : undefined), node);
405
+ const valueAt = (node, path) => path.reduce((at, key) => (isScope(at) || Array.isArray(at) ? at[key] : undefined), node);
421
406
  const setAt = (node, path, value) => {
422
407
  let at = node;
423
408
  for (const key of path.slice(0, -1)) {
@@ -427,22 +412,6 @@ const setAt = (node, path, value) => {
427
412
  }
428
413
  at[path.at(-1)] = value;
429
414
  };
430
- /** Removes the value and every section it leaves empty, so an unset leaves no `{}` behind. */
431
- const removeAt = (node, path) => {
432
- const [key, ...rest] = path;
433
- if (key === undefined)
434
- return;
435
- if (rest.length === 0) {
436
- delete node[key];
437
- return;
438
- }
439
- const child = node[key];
440
- if (!isScope(child))
441
- return;
442
- removeAt(child, rest);
443
- if (Object.keys(child).length === 0)
444
- delete node[key];
445
- };
446
415
  /** Every profile the file names, in any section. */
447
416
  const namedProfiles = (config) => [
448
417
  ...new Set([
package/dist/cli/steps.js CHANGED
@@ -144,6 +144,12 @@ export const STEPS = defineSteps([
144
144
  args: [{ name: "chat", required: true }],
145
145
  why: "the chat's conversations are not searchable by meaning yet; this embeds them",
146
146
  },
147
+ {
148
+ id: "conversations.rebuild",
149
+ command: "conversations rebuild",
150
+ args: [],
151
+ why: "messages have no vectors yet, so discovery searched by words alone; this embeds them, a bounded batch a run",
152
+ },
147
153
  {
148
154
  id: "stats.evidence",
149
155
  command: "*",
@@ -34,6 +34,11 @@ export declare const conversationPreparation: v.StrictObjectSchema<{
34
34
  readonly chat: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
35
35
  readonly needs: v.PicklistSchema<["build", "embed"], undefined>;
36
36
  }, undefined>, undefined>;
37
+ /** Messages given their own vector, which `search messages --discover` reads, and how many still lack one. */
38
+ readonly messages: v.OptionalSchema<v.StrictObjectSchema<{
39
+ readonly embedded: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
40
+ readonly left: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
41
+ }, undefined>, undefined>;
37
42
  }, undefined>;
38
43
  export declare const catchUpPreparation: v.StrictObjectSchema<{
39
44
  readonly complete: v.BooleanSchema<undefined>;
@@ -59,5 +64,10 @@ export declare const catchUpPreparation: v.StrictObjectSchema<{
59
64
  readonly chat: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
60
65
  readonly needs: v.PicklistSchema<["build", "embed"], undefined>;
61
66
  }, undefined>, undefined>;
67
+ /** Messages given their own vector, which `search messages --discover` reads, and how many still lack one. */
68
+ readonly messages: v.OptionalSchema<v.StrictObjectSchema<{
69
+ readonly embedded: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
70
+ readonly left: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
71
+ }, undefined>, undefined>;
62
72
  }, undefined>, undefined>;
63
73
  }, undefined>;
@@ -15,6 +15,8 @@ export const conversationPreparation = v.strictObject({
15
15
  built: v.array(conversationBuild),
16
16
  embedded: v.array(chatEmbedding),
17
17
  left: v.array(v.strictObject({ chat: id, needs: v.picklist(["build", "embed"]) })),
18
+ /** Messages given their own vector, which `search messages --discover` reads, and how many still lack one. */
19
+ messages: v.optional(v.strictObject({ embedded: count, left: count })),
18
20
  });
19
21
  export const catchUpPreparation = v.strictObject({
20
22
  complete: v.boolean(),
@@ -41,6 +41,7 @@ export declare const conversationDetails: v.UnionSchema<[v.StrictObjectSchema<{
41
41
  readonly matched_terms: v.ArraySchema<v.StringSchema<undefined>, undefined>;
42
42
  readonly missing_terms: v.ArraySchema<v.StringSchema<undefined>, undefined>;
43
43
  readonly parent: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
44
+ readonly found_by: v.OptionalSchema<v.ArraySchema<v.PicklistSchema<["words", "meaning"], undefined>, undefined>, undefined>;
44
45
  }, undefined>, undefined>;
45
46
  readonly context: v.OptionalSchema<v.ArraySchema<v.StrictObjectSchema<{
46
47
  readonly ref: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>;
@@ -227,6 +228,7 @@ export declare const conversationDetails: v.UnionSchema<[v.StrictObjectSchema<{
227
228
  readonly matched_terms: v.ArraySchema<v.StringSchema<undefined>, undefined>;
228
229
  readonly missing_terms: v.ArraySchema<v.StringSchema<undefined>, undefined>;
229
230
  readonly parent: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
231
+ readonly found_by: v.OptionalSchema<v.ArraySchema<v.PicklistSchema<["words", "meaning"], undefined>, undefined>, undefined>;
230
232
  }, undefined>, undefined>;
231
233
  readonly context: v.OptionalSchema<v.ArraySchema<v.StrictObjectSchema<{
232
234
  readonly ref: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>;
@@ -446,6 +448,10 @@ export declare const conversationBuildResult: v.UnionSchema<[v.StrictObjectSchem
446
448
  readonly chat: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
447
449
  readonly needs: v.PicklistSchema<["build", "embed"], undefined>;
448
450
  }, undefined>, undefined>;
451
+ readonly messages: v.OptionalSchema<v.StrictObjectSchema<{
452
+ readonly embedded: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
453
+ readonly left: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
454
+ }, undefined>, undefined>;
449
455
  }, undefined>, v.StrictObjectSchema<{
450
456
  readonly chat: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
451
457
  readonly model: v.StringSchema<undefined>;
@@ -497,6 +503,10 @@ export declare const conversationEmbedding: v.UnionSchema<[v.StrictObjectSchema<
497
503
  readonly chat: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
498
504
  readonly needs: v.PicklistSchema<["build", "embed"], undefined>;
499
505
  }, undefined>, undefined>;
506
+ readonly messages: v.OptionalSchema<v.StrictObjectSchema<{
507
+ readonly embedded: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
508
+ readonly left: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
509
+ }, undefined>, undefined>;
500
510
  }, undefined>], undefined>;
501
511
  export declare const conversationChange: v.UnionSchema<[v.StrictObjectSchema<{
502
512
  readonly chat: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;