@wirecat/cli-core 0.701.0 → 0.703.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,6 +5,39 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.703.0 — 18.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`search conversations` shows the owner's own conversations nearest in meaning in a block of their own**, up to 5
13
+ that the hits left out: in JSON they follow the hits with `from_owner: true`, in text under «your own messages».
14
+ The hits keep their order. A question about what the owner said or advised is often answered by a message a busy
15
+ group ranks low; on a test store of 220,000 chunks the block showed the answer to 31 of 40 questions instead of
16
+ 24, for about 0.24 s more per query. Only the owner's chunks are scored, found by their messages.
17
+
18
+ ### Fixed
19
+
20
+ - **`crmManifestFake`'s deals name the fake's own contacts and companies**: deal n links organization n and person n,
21
+ so a source with `linked: true` copies them and `crmManifestContract` passes over it. A linked kind's read of changes
22
+ answers `reset` to a dead cursor, as every other kind does.
23
+ - **`sync`'s summary fits WireCat Desktop's 300 characters again.** cli-base 0.119.0 checks the limit, and every CRM
24
+ CLI's `contracts/wirecat.json` failed to build on a 452-character summary; the activities and stage-tasks part moved
25
+ to `help sync`.
26
+
27
+ ## 0.702.0 — 18.11.2026
28
+
29
+ ### Added
30
+
31
+ - **A source manifest's `linked: true` on contacts or companies copies only the ones a deal names**, each read by its
32
+ `get`, as bitrix24-cli's sync does; the rest stay in the service and are read live. Their ids are the deals' links,
33
+ so one no deal names any more leaves the copy at the next full round. Attio's contacts and companies grow from the
34
+ owner's mail, and a full copy held thousands nobody sells to.
35
+
36
+ ### Fixed
37
+
38
+ - **An optional kind the service answers with 404 is a gap too**, not only a 403. Attio's Deals object is off until an
39
+ admin turns it on, and its records query answers 404: the sync failed instead of naming the gap.
40
+
8
41
  ## 0.701.0 — 18.11.2026
9
42
 
10
43
  ### Added
@@ -11,7 +11,7 @@ export declare const readinessGaps: ({ meaning, model, readiness, refreshed, cov
11
11
  missing: Missing[];
12
12
  };
13
13
  /** `search conversations` and `conversations related`, CLI and MCP alike. */
14
- export declare const foundConversations: (command: string, found: Readiness & Pick<FoundConversations, "hits" | "accounts" | "words">, limit: number, messenger: Syncing, chat?: string, meta?: Partial<Meta>) => import("../envelope.js").ListBody<unknown>;
14
+ export declare const foundConversations: (command: string, found: Readiness & Pick<FoundConversations, "hits" | "accounts" | "words" | "own">, limit: number, messenger: Syncing, chat?: string, meta?: Partial<Meta>) => import("../envelope.js").ListBody<unknown>;
15
15
  /** `conversations status`: each built chat with the model it was measured by; group chats never built are missing. */
16
16
  export declare const readinessList: ({ model, chats, unbuiltGroups, }: {
17
17
  model: string;
@@ -54,7 +54,10 @@ export const readinessGaps = ({ meaning, model, readiness, refreshed, coverage }
54
54
  };
55
55
  /** `search conversations` and `conversations related`, CLI and MCP alike. */
56
56
  export const foundConversations = (command, found, limit, messenger, chat, meta = {}) => listOf(command, {
57
- items: found.hits.map((hit) => snakeKeys(hit)),
57
+ items: [
58
+ ...found.hits.map((hit) => snakeKeys(hit)),
59
+ ...(found.own ?? []).map((hit) => ({ ...snakeKeys(hit), from_owner: true })),
60
+ ],
58
61
  limit,
59
62
  has_more: false,
60
63
  ...readinessGaps(found, messenger, chat),
@@ -632,7 +632,8 @@ export const conversationsSearchCommand = (messenger) => syncOptions(boundOption
632
632
  context.renderer.note(`«${found.named.word}» is a name in chat ${found.named.title ?? found.named.chatId} (${found.named.chatId}): its hits come first`);
633
633
  if (found.words === "out-of-time")
634
634
  context.renderer.note("the word half ran out of time, so these are by meaning alone; --timeout gives it longer");
635
- renderAnswer(this, context, foundConversations("search conversations", found, limit, messenger, chat, window.meta), () => found.hits.map((hit) => `${hitLine(hit)}\n`).join(""));
635
+ renderAnswer(this, context, foundConversations("search conversations", found, limit, messenger, chat, window.meta), () => found.hits.map((hit) => `${hitLine(hit)}\n`).join("") +
636
+ (found.own?.length ? `your own messages:\n${found.own.map((hit) => `${hitLine(hit)}\n`).join("")}` : ""));
636
637
  if (found.hits.length === 0 && context.format === "pretty")
637
638
  context.renderer.note(found.meaning === "unavailable"
638
639
  ? "nothing matches in words"
@@ -211,11 +211,14 @@ const addCrmCommandsDefinition = (program, options) => {
211
211
  renderAnswer(command, outputFor(command), body, view);
212
212
  });
213
213
  const example = (command, ...lines) => annotate(command, { examples: lines.map((line) => `${options.app.command} work ${line}`) });
214
- example(answerEntity(annotate(program.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), "crm_sync", crmSync).description("bring the CRM's copy in the local store up to date: pipelines, companies, contacts, deals and leads that " +
215
- "changed since the last sync, or everything with --rescan; a run stops before its deadline or --max-pages " +
216
- "and the next one goes on from there. With the activities setting on, also the activities and tasks on the " +
217
- "deals and leads it keeps. Then each deal or lead that moved into a stage the stage-tasks setting names " +
218
- "opens a local task, once per move"), "sync", "sync --rescan", "sync --max-pages 20")
214
+ example(answerEntity(annotate(program.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), "crm_sync", crmSync)
215
+ .description("bring the CRM's copy in the local store up to date: pipelines, companies, contacts, deals and leads that " +
216
+ "changed since the last sync, or everything with --rescan; a run stops before its deadline or " +
217
+ "--max-pages and the next one goes on from there")
218
+ // WireCat Desktop takes a summary of 300 characters at most; the settings' part is help only.
219
+ .addHelpText("after", "\nWith the activities setting on, it also copies the activities and tasks on the deals and leads it keeps. " +
220
+ "Then each deal or lead that moved into a stage the stage-tasks setting names opens a local task, once " +
221
+ "per move."), "sync", "sync --rescan", "sync --max-pages 20")
219
222
  .option("--rescan", "list everything again, every id too, dropping a round in progress")
220
223
  .option("--max-pages <pages>", "at most this many requests to the CRM in this run", integer(100_000))
221
224
  .action(async (opts, command) => {
@@ -94,13 +94,19 @@ export interface CrmManifestEntity<K extends CrmKind = CrmKind> {
94
94
  typed?: CrmTypedValues;
95
95
  };
96
96
  /**
97
- * A kind the plan or the sign-in may not have (HubSpot's leads): the service refusing it is a gap with this text and
98
- * scope, and the other kinds still sync.
97
+ * A kind the plan or the sign-in may not have (HubSpot's leads, Attio's Deals object when it is off): the service
98
+ * refusing it, or answering that it is not there, is a gap with this text and scope, and the other kinds still sync.
99
99
  */
100
100
  optional?: {
101
101
  message: string;
102
102
  scope?: string;
103
103
  };
104
+ /**
105
+ * Contacts or companies: the sync copies only the ones a deal names, each read by `get`, as Bitrix24's does; the
106
+ * rest stay in the service and are read live. For a service whose own contacts and companies grow from mail
107
+ * (Attio), where a full copy would hold thousands nobody sells to.
108
+ */
109
+ linked?: true;
104
110
  }
105
111
  /**
106
112
  * Values kept as a list of typed entries, each naming its type (Attio's `values.<slug>`): the entry's type picks where
@@ -48,6 +48,7 @@ const entity = v.strictObject({
48
48
  typed: v.optional(v.strictObject({ by: path, current: v.optional(path), paths: v.optional(v.record(v.string(), path)) })),
49
49
  })),
50
50
  optional: v.optional(v.strictObject({ message: v.pipe(v.string(), v.minLength(1)), scope: v.optional(v.string()) })),
51
+ linked: v.optional(v.literal(true)),
51
52
  });
52
53
  const pipelines = v.strictObject({
53
54
  call,
@@ -159,6 +160,15 @@ export const parseCrmManifest = (input, api) => {
159
160
  if (!hasPlaceholder([one.search.path, one.search.query, one.search.body], "{query}"))
160
161
  throw invalid(`entities.${kind}.search`, 'no "{query}" in its path, query or body');
161
162
  }
163
+ if (one.linked) {
164
+ if (kind !== "person" && kind !== "organization")
165
+ throw invalid(`entities.${kind}.linked`, "only contacts and companies are copied as a deal names them");
166
+ if (!one.get)
167
+ throw invalid(`entities.${kind}.linked`, "each one is read by its get, and this kind has none");
168
+ const link = kind === "person" ? "people" : "organization";
169
+ if (!manifest.kinds.includes("deal") || manifest.entities.deal?.map[link] === undefined)
170
+ throw invalid(`entities.${kind}.linked`, `no deal entity maps ${link}`);
171
+ }
162
172
  if (one.map.externalId === undefined)
163
173
  throw invalid(`entities.${kind}.map.externalId`, "every kind maps its id");
164
174
  const fields = [...Object.keys(FIELDS[kind]), "amount", "currency"];
@@ -9,6 +9,8 @@ const OVERLAP_MS = 10 * 60_000;
9
9
  const MOST_LIVE = 100;
10
10
  /** How far one read of every page goes: a service that never stops paging must not hold a sync forever. */
11
11
  const MOST_PAGES = 500;
12
+ /** Contacts or companies a deal names, read one by one, per page of a sync round. */
13
+ const LINKED_PAGE = 50;
12
14
  const DROP = Symbol("drop");
13
15
  /** Fills `"{since}"`, `"{select}"`, `"{id}"` and `"{query}"`; an empty select drops the parameter it stands for. */
14
16
  const fill = (value, slots) => {
@@ -189,7 +191,7 @@ export const crmSourceFromManifest = (input, options) => {
189
191
  /** A refusal of a kind the manifest marks optional is a gap; the other kinds still sync. */
190
192
  const optionalRefused = (kind, error, context) => {
191
193
  const optional = manifest.entities[kind]?.optional;
192
- if (!optional || !isCliError(error) || error.code !== "permission_error")
194
+ if (!optional || !unseen(error))
193
195
  return false;
194
196
  gap(context, { kind, message: optional.message, ...(optional.scope ? { scope: optional.scope } : {}) });
195
197
  return true;
@@ -231,6 +233,8 @@ export const crmSourceFromManifest = (input, options) => {
231
233
  const since = cursor === null ? null : Date.parse(cursor);
232
234
  if (since !== null && Number.isNaN(since))
233
235
  return { reset: true };
236
+ if (entity.linked && (kind === "person" || kind === "organization"))
237
+ return (await readLinked(kind, page, context));
234
238
  const { token, started } = pageOf(page, now());
235
239
  const send = metered(context);
236
240
  const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
@@ -247,8 +251,80 @@ export const crmSourceFromManifest = (input, options) => {
247
251
  ? { items, hasMore: false, cursor: new Date(started).toISOString() }
248
252
  : { items, hasMore: true, nextCursor: `${next}@${started}` };
249
253
  };
254
+ const readOne = async (kind, externalId, send, context) => {
255
+ const entity = entityOf(kind);
256
+ if (!entity.get)
257
+ return null;
258
+ const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
259
+ let answer;
260
+ try {
261
+ answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId, select: selectOf(kind, defined, context) }));
262
+ }
263
+ catch (error) {
264
+ if (unseen(error))
265
+ return null;
266
+ throw error;
267
+ }
268
+ const raw = entity.get.items === undefined ? answer : at(answer, entity.get.items);
269
+ return isRaw(raw) ? ((await mapped(kind, [raw], defined, send))[0] ?? null) : null;
270
+ };
271
+ /** The contacts and companies the deals name, from one pass over the deals; deals the service refuses name none. */
272
+ const linkedOf = async (send, context) => {
273
+ const deal = entityOf("deal");
274
+ const found = { person: new Set(), organization: new Set() };
275
+ let rows;
276
+ try {
277
+ rows = await readAll(deal.list, send);
278
+ }
279
+ catch (error) {
280
+ if (!optionalRefused("deal", error, context))
281
+ throw error;
282
+ rows = [];
283
+ }
284
+ for (const raw of rows) {
285
+ const record = mapRecord("deal", deal, raw, []);
286
+ if (record?.organization)
287
+ found.organization.add(record.organization);
288
+ for (const one of record?.people ?? [])
289
+ found.person.add(one.externalId);
290
+ }
291
+ return { person: [...found.person].sort(), organization: [...found.organization].sort() };
292
+ };
293
+ /** One pass per round: every page of the round reads the same list, so no id is skipped or read twice. */
294
+ let round;
295
+ const linkedRound = (started, send, context) => {
296
+ if (round?.started !== started) {
297
+ const ids = linkedOf(send, context);
298
+ ids.catch(() => {
299
+ if (round?.ids === ids)
300
+ round = undefined;
301
+ });
302
+ round = { started, ids };
303
+ }
304
+ return round.ids;
305
+ };
306
+ const readLinked = async (kind, page, context) => {
307
+ const { token, started } = pageOf(page, now());
308
+ const from = token === undefined ? 0 : Number(token);
309
+ if (!Number.isSafeInteger(from) || from < 0)
310
+ return { reset: true };
311
+ const send = metered(context);
312
+ const ids = (await linkedRound(started, send, context))[kind];
313
+ const items = [];
314
+ for (const externalId of ids.slice(from, from + LINKED_PAGE)) {
315
+ const one = await readOne(kind, externalId, send, context);
316
+ if (one)
317
+ items.push(one);
318
+ }
319
+ const next = from + LINKED_PAGE;
320
+ return next < ids.length
321
+ ? { items, hasMore: true, nextCursor: `${next}@${started}` }
322
+ : { items, hasMore: false, cursor: new Date(started).toISOString() };
323
+ };
250
324
  const readIds = async (kind, page, context) => {
251
325
  const entity = entityOf(kind);
326
+ if (entity.linked && (kind === "person" || kind === "organization"))
327
+ return { items: (await linkedOf(metered(context), context))[kind], hasMore: false };
252
328
  const { rows, next } = await readPage(entity.ids ?? entity.list, {}, page, metered(context));
253
329
  const items = rows.flatMap((raw) => {
254
330
  const found = evaluate(entity.map.externalId, raw);
@@ -335,22 +411,7 @@ export const crmSourceFromManifest = (input, options) => {
335
411
  },
336
412
  ...(live.length ? { list: readLive } : {}),
337
413
  async get(kind, externalId, context) {
338
- const entity = entityOf(kind);
339
- if (!entity.get)
340
- return null;
341
- const send = metered(context);
342
- const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
343
- let answer;
344
- try {
345
- answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId, select: selectOf(kind, defined, context) }));
346
- }
347
- catch (error) {
348
- if (unseen(error))
349
- return null;
350
- throw error;
351
- }
352
- const raw = entity.get.items === undefined ? answer : at(answer, entity.get.items);
353
- return isRaw(raw) ? ((await mapped(kind, [raw], defined, send))[0] ?? null) : null;
414
+ return readOne(kind, externalId, metered(context), context);
354
415
  },
355
416
  ...(manifest.fields
356
417
  ? { fields: (kind, context) => fieldsOf(kind, metered(context), context) }
@@ -284,6 +284,20 @@ export const crmManifestFake = (input, options) => {
284
284
  putList(row, spec.stages.each, stages, node);
285
285
  pipelines.set(kind, { rows: [row], id, stages: ids });
286
286
  }
287
+ const idAt = (kind, n) => {
288
+ const index = manifest.kinds.indexOf(kind);
289
+ return index < 0 ? undefined : String((index + 1) * 1000 + n + 1);
290
+ };
291
+ /** A deal's people walk a list: its one entry names the contact the deal's row number holds. */
292
+ const linkPeople = (row, rule, node, person) => {
293
+ if (typeof rule !== "object" || !("each" in rule) || !("id" in rule))
294
+ return;
295
+ const entry = itemOf(nodeAt(node, rule.each), definitions);
296
+ const made = sample(entry && narrowed(entry, rule.id.split("."), person));
297
+ const item = isRaw(made) ? made : {};
298
+ put(item, rule.id, person, entry);
299
+ putList(row, rule.each, [item], node);
300
+ };
287
301
  const rows = {};
288
302
  const changeAt = {};
289
303
  for (const [index, kind] of manifest.kinds.entries()) {
@@ -303,7 +317,11 @@ export const crmManifestFake = (input, options) => {
303
317
  assignee: "7001",
304
318
  ...(pipeline ? { pipeline: pipeline.id, stage: pipeline.stages[n % pipeline.stages.length] } : {}),
305
319
  ...(money ? { amount: "100.50", currency: "EUR" } : { amount: undefined, currency: undefined }),
320
+ ...(pipeline && idAt("organization", n) ? { organization: idAt("organization", n) } : {}),
306
321
  });
322
+ const person = idAt("person", n);
323
+ if (pipeline && person)
324
+ linkPeople(row, map.people, node, person);
307
325
  if (keyset)
308
326
  put(row, keyset, time, node);
309
327
  return row;
@@ -15,6 +15,8 @@ import { refreshSearch } from "./search-refresh.js";
15
15
  const CANDIDATES = 50;
16
16
  /** Conversations the meaning half reads across chats before it gives each chat its share. */
17
17
  const ACROSS_CHATS = 500;
18
+ /** The owner's own chunks shown beside the hits: a result list ranks them low, and a question is often about them. */
19
+ const OWN_BLOCK = 5;
18
20
  /**
19
21
  * What one chat brings to each list when several are searched, so a large chat cannot fill them. Its meaning hits
20
22
  * count by how far they lead its 20th best: a large chat holds some text near any question, and a small chat's
@@ -190,6 +192,7 @@ export const embeddingsSearch = (deps) => {
190
192
  };
191
193
  });
192
194
  const meaning = [];
195
+ const own = [];
193
196
  const sources = words.sources;
194
197
  if (target.installed && prepared.scopeAccounts.length && eligibility?.conversations.length !== 0) {
195
198
  await withEmbedder(deps, target, choice, {}, async (embedder) => {
@@ -219,8 +222,21 @@ export const embeddingsSearch = (deps) => {
219
222
  ...hits,
220
223
  ...images.filter((hit) => !eligibility || eligibility.conversations.includes(hit.summary.id)),
221
224
  ].sort((a, b) => b.score - a.score);
225
+ const mine = await store.vectors.nearestConversations(one, {
226
+ ...scope,
227
+ ...(since === undefined ? {} : { since }),
228
+ model: target.key,
229
+ limit: OWN_BLOCK,
230
+ query: vector,
231
+ fromOwner: true,
232
+ ...(eligibility ? { conversations: eligibility.conversations } : {}),
233
+ });
222
234
  for (const hit of found)
223
235
  sources.set(hit.summary.id, one);
236
+ for (const hit of mine) {
237
+ sources.set(hit.summary.id, one);
238
+ own.push(hit);
239
+ }
224
240
  meaning.push(...(whole ? found.map((hit) => ({ hit, lead: hit.score })) : shared(found, limit)));
225
241
  }
226
242
  });
@@ -252,22 +268,31 @@ export const embeddingsSearch = (deps) => {
252
268
  ].sort();
253
269
  if (scoped.length > 1)
254
270
  readiness.scopes = scoped;
271
+ const located = (hit) => {
272
+ const source = sources.get(hit.summary.id);
273
+ return {
274
+ ...hit,
275
+ source,
276
+ locator: formatLocator({ ...source, chat: hit.summary.chatId, message: hit.chunk.firstMessageId }),
277
+ };
278
+ };
279
+ const hits = fused(meaning.map(({ hit }) => hit), words.hits, meaningFloor(target.key))
280
+ .slice(0, limit)
281
+ .map(located);
282
+ const shown = new Set(hits.map((hit) => hit.summary.id));
283
+ const ownHits = own
284
+ .filter((hit) => !shown.has(hit.summary.id))
285
+ .sort((a, b) => b.score - a.score)
286
+ .slice(0, OWN_BLOCK)
287
+ .map((hit) => located({ ...hit, by: ["meaning"] }));
255
288
  return {
256
289
  accounts: prepared.scopeAccounts,
257
290
  model: target.id,
258
291
  meaning: target.installed ? "searched" : "unavailable",
259
292
  ...(wordsOutOfTime ? { words: "out-of-time" } : {}),
260
293
  ...(words.respellings.size ? { respelled: Object.fromEntries(words.respellings) } : {}),
261
- hits: fused(meaning.map(({ hit }) => hit), words.hits, meaningFloor(target.key))
262
- .slice(0, limit)
263
- .map((hit) => {
264
- const source = sources.get(hit.summary.id);
265
- return {
266
- ...hit,
267
- source,
268
- locator: formatLocator({ ...source, chat: hit.summary.chatId, message: hit.chunk.firstMessageId }),
269
- };
270
- }),
294
+ hits,
295
+ ...(ownHits.length ? { own: ownHits } : {}),
271
296
  readiness,
272
297
  ...(locallyRefreshed ? { prepared: locallyRefreshed } : {}),
273
298
  ...(refreshed
@@ -148,6 +148,8 @@ export interface FoundConversations {
148
148
  title: string | null;
149
149
  };
150
150
  hits: FoundConversation[];
151
+ /** The owner's own conversations nearest in meaning that `hits` left out. */
152
+ own?: FoundConversation[];
151
153
  readiness: SearchReadiness;
152
154
  /** Kept for callers of 0.141.0 and before; `readiness.wordsOnly` says more. */
153
155
  embeddedOnlyElsewhere: Id[];
@@ -80,6 +80,7 @@ export declare const nearestChunks: (context: StoreContext, accountPk: number, f
80
80
  projectId?: number;
81
81
  before?: number;
82
82
  personId?: number;
83
+ fromOwner?: boolean;
83
84
  }) => NearestChunk[];
84
85
  /** Chats in scope whose current build has vectors of another model and none of `model`: a search with it skips them. */
85
86
  export declare const embeddedOnlyElsewhere: ({ orm }: StoreContext, accountPk: number, { chatKey, model }: {
@@ -181,7 +181,7 @@ export const dot = (query, blob) => {
181
181
  */
182
182
  export const nearestChunks = (context, accountPk, filter) => {
183
183
  const { orm } = context;
184
- const { chatKey, model, since, limit, query, exclude, conversations, scope, projectId, before, personId } = filter;
184
+ const { chatKey, model, since, limit, query, exclude, conversations, scope, projectId, before, personId, fromOwner } = filter;
185
185
  const rows = (page) => orm.all(
186
186
  // CROSS JOIN keeps the chunks first, so each page walks their key; led by the vectors, SQLite re-read and
187
187
  // sorted every one of them per page — 1.3 s against 140 ms at 42k chunks (bench/embeddings/README.md).
@@ -197,6 +197,7 @@ export const nearestChunks = (context, accountPk, filter) => {
197
197
  ${projectId === undefined ? sql `` : sql `AND k.project_id=${projectId}`}
198
198
  ${before === undefined ? sql `` : sql `AND k.occurred_at < ${before}`}
199
199
  ${personId === undefined ? sql `` : sql `AND EXISTS (SELECT 1 FROM conversation_messages pcm JOIN messages pm ON pm.id=pcm.message_id JOIN identity_links pil ON pil.identity_id=pm.sender_identity_id WHERE pcm.conversation_id=c.id AND pil.person_id=${personId})`}
200
+ ${fromOwner ? sql `AND EXISTS (SELECT 1 FROM conversation_messages om JOIN messages m ON m.id = om.message_id WHERE om.conversation_id = c.id AND m.outgoing = 1 AND m.id BETWEEN r.first_message_id AND r.last_message_id)` : sql ``}
200
201
  ${chatKey === undefined ? sql `AND ch.searchable = 1` : sql `AND c.chat_id = ${chatKey}`}
201
202
  ${since === undefined ? sql `` : sql `AND k.occurred_at >= ${since}`}
202
203
  ${exclude === undefined ? sql `` : sql `AND c.id <> ${exclude}`}
@@ -226,7 +227,11 @@ export const nearestChunks = (context, accountPk, filter) => {
226
227
  const ranked = (found) => found.sort((a, b) => b.score - a.score).slice(0, limit);
227
228
  const plain = (found) => found.map(({ id: _, ...chunk }) => chunk);
228
229
  // The index has no person, project, scope or conversation list; with one of those the scan stays.
229
- const indexable = personId === undefined && projectId === undefined && scope === undefined && conversations === undefined;
230
+ const indexable = personId === undefined &&
231
+ projectId === undefined &&
232
+ scope === undefined &&
233
+ conversations === undefined &&
234
+ !fromOwner;
230
235
  const indexed = indexable &&
231
236
  searchIndex(context.database, model, {
232
237
  kind: "conversation",
@@ -245,6 +250,24 @@ export const nearestChunks = (context, accountPk, filter) => {
245
250
  });
246
251
  if (indexed)
247
252
  return plain(indexed);
253
+ if (fromOwner) {
254
+ // The owner's chunks are few: find them by the owner's messages, then score only those.
255
+ const ids = orm
256
+ .all(sql `SELECT DISTINCT k.id FROM messages m
257
+ JOIN conversation_messages om ON om.message_id = m.id
258
+ JOIN conversations c ON c.id = om.conversation_id
259
+ JOIN conversation_state s ON s.chat_id = c.chat_id AND s.current_build = c.build
260
+ JOIN chats ch ON ch.id = c.chat_id
261
+ JOIN chunks k ON k.chunkable_type = 'conversation' AND k.chunkable_id = c.id
262
+ JOIN chunk_messages r ON r.chunk_id = k.id AND m.id BETWEEN r.first_message_id AND r.last_message_id
263
+ WHERE m.outgoing = 1 AND ch.account_id = ${accountPk}
264
+ ${chatKey === undefined ? sql `AND ch.searchable = 1` : sql `AND c.chat_id = ${chatKey}`}`)
265
+ .map(({ id }) => id);
266
+ const best = new Map();
267
+ for (const row of rows({ ids }))
268
+ keepBest(best, row);
269
+ return plain(ranked([...best.values()]));
270
+ }
248
271
  const best = new Map();
249
272
  let after = { conversation: 0, ordinal: -1 };
250
273
  for (;;) {
@@ -120,6 +120,8 @@ export interface AccountVectors {
120
120
  projectId?: string;
121
121
  personId?: string;
122
122
  before?: string;
123
+ /** Only chunks that hold one of the owner's own messages. */
124
+ fromOwner?: boolean;
123
125
  }): Promise<ConversationHit[]>;
124
126
  /**
125
127
  * A conversation of the current build: how many chunks it has, and the vectors of `model` of those whose
@@ -165,7 +165,7 @@ export const accountVectorsOver = (context, mail) => {
165
165
  });
166
166
  return cleared;
167
167
  },
168
- nearestConversations: async (key, { chatId, model, since, limit, query, exclude, conversations, scope, projectId, personId, before }) => {
168
+ nearestConversations: async (key, { chatId, model, since, limit, query, exclude, conversations, scope, projectId, personId, before, fromOwner }) => {
169
169
  const accountPk = findAccountPk(key);
170
170
  if (accountPk === undefined)
171
171
  return [];
@@ -175,7 +175,8 @@ export const accountVectorsOver = (context, mail) => {
175
175
  scope === undefined &&
176
176
  projectId === undefined &&
177
177
  personId === undefined &&
178
- before === undefined;
178
+ before === undefined &&
179
+ !fromOwner;
179
180
  const mailHits = async () => mailToo
180
181
  ? (await mail().nearest(model, query, {
181
182
  accountId: accountPk,
@@ -203,6 +204,7 @@ export const accountVectorsOver = (context, mail) => {
203
204
  ...(projectId === undefined ? {} : { projectId: Number(projectId) }),
204
205
  ...(personId === undefined ? {} : { personId: Number(personId) }),
205
206
  ...(before === undefined ? {} : { before: Date.parse(before) }),
207
+ ...(fromOwner ? { fromOwner } : {}),
206
208
  });
207
209
  const found = conversationQueries.summariesOf(context, accountPk, nearest.map(({ conversationPk }) => conversationPk));
208
210
  const ids = vectors.messageIds(context, nearest.flatMap(({ firstMessagePk, lastMessagePk }) => [firstMessagePk, lastMessagePk]));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.701.0",
3
+ "version": "0.703.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",