@wirecat/cli-core 0.728.0 → 0.730.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.
@@ -2,7 +2,9 @@ import { trackerBodyOf, trackerParentOf, trackerTitleOf, } from "../../domain/tr
2
2
  import { fold, normalize } from "../normalize.js";
3
3
  import { accountPk, findAccountPk } from "./accounts.js";
4
4
  import { excerptOf, matchOf } from "./crm-files.js";
5
+ import { dropTrackerChunks, isChunkedTrackerKind, nearestTrackerItems, refreshTrackerChunks, trackerChunksLeft, trackerChunksToEmbed, trackerChunkWriter, trackerEmbedded, } from "./tracker-chunks.js";
5
6
  import { write } from "./transaction.js";
7
+ import { dropUnusedVectors } from "./vector-index.js";
6
8
  const MOST = 500;
7
9
  const itemOf = (row) => ({
8
10
  kind: String(row.kind),
@@ -36,7 +38,11 @@ export const trackerStoreOver = (context) => {
36
38
  const { database } = context;
37
39
  const save = (key, kind, records, now) => write(database, () => {
38
40
  const accountId = accountPk(context, key);
39
- const stored = database.prepare("SELECT data FROM tracker_items WHERE account_id = ? AND kind = ? AND external_id = ?");
41
+ const stored = database.prepare("SELECT data, title, body, deleted_at FROM tracker_items WHERE account_id = ? AND kind = ? AND external_id = ?");
42
+ const scope = database.prepare("SELECT scope FROM accounts WHERE id = ?").get(accountId)?.scope;
43
+ const chunked = isChunkedTrackerKind(kind);
44
+ const chunk = trackerChunkWriter(database);
45
+ const released = [];
40
46
  const upsert = database.prepare("INSERT INTO tracker_items (account_id, kind, external_id, parent_id, title, title_folded, body, " +
41
47
  "normalized_text, data, source_created_at, source_updated_at, archived_at, deleted_at, synced_at) " +
42
48
  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?) " +
@@ -44,7 +50,7 @@ export const trackerStoreOver = (context) => {
44
50
  "title = excluded.title, title_folded = excluded.title_folded, body = excluded.body, " +
45
51
  "normalized_text = excluded.normalized_text, data = excluded.data, " +
46
52
  "source_created_at = excluded.source_created_at, source_updated_at = excluded.source_updated_at, " +
47
- "archived_at = excluded.archived_at, deleted_at = NULL, synced_at = excluded.synced_at");
53
+ "archived_at = excluded.archived_at, deleted_at = NULL, synced_at = excluded.synced_at RETURNING id");
48
54
  for (const record of records) {
49
55
  const before = stored.get(accountId, kind, record.externalId);
50
56
  // A field the tracker left out of this read keeps what the store knew: a read never erases by omission.
@@ -54,8 +60,24 @@ export const trackerStoreOver = (context) => {
54
60
  };
55
61
  const title = trackerTitleOf(kind, merged);
56
62
  const body = trackerBodyOf(kind, merged) ?? null;
57
- upsert.run(accountId, kind, merged.externalId, trackerParentOf(kind, merged) ?? null, title, fold(title), body, normalize([title, body].filter(Boolean).join("\n")), JSON.stringify(merged), merged.createdAt ?? null, merged.updatedAt ?? null, merged.archivedAt ?? null, now);
63
+ const saved = upsert.get(accountId, kind, merged.externalId, trackerParentOf(kind, merged) ?? null, title, fold(title), body, normalize([title, body].filter(Boolean).join("\n")), JSON.stringify(merged), merged.createdAt ?? null, merged.updatedAt ?? null, merged.archivedAt ?? null, now);
64
+ // Most rows of a sync come back with the text they had; their chunks stay, and only a revived row needs new.
65
+ const same = before?.deleted_at == null && before?.title === title && (before?.body ?? null) === body;
66
+ if (!chunked || same)
67
+ continue;
68
+ const freed = chunk({
69
+ id: Number(saved?.id),
70
+ accountId,
71
+ kind,
72
+ title,
73
+ body,
74
+ occurredAt: merged.updatedAt ?? now,
75
+ scope: scope == null ? null : String(scope),
76
+ }, now);
77
+ for (const hash of freed ?? [])
78
+ released.push(hash);
58
79
  }
80
+ dropUnusedVectors(database, released);
59
81
  return records.length;
60
82
  });
61
83
  const removeUnlisted = (key, kind, listed, before, now, { dryRun = false } = {}) => {
@@ -66,16 +88,21 @@ export const trackerStoreOver = (context) => {
66
88
  return write(database, () => {
67
89
  const mark = database.prepare("UPDATE tracker_items SET deleted_at = ? WHERE id = ?");
68
90
  let removed = 0;
91
+ const marked = [];
69
92
  for (const row of database
70
93
  .prepare("SELECT id, external_id FROM tracker_items WHERE account_id = ? AND kind = ? AND deleted_at IS NULL " +
71
94
  "AND synced_at < ?")
72
95
  .all(accountId, kind, before)) {
73
96
  if (keep.has(String(row.external_id)))
74
97
  continue;
75
- if (!dryRun)
98
+ if (!dryRun) {
76
99
  mark.run(now, Number(row.id));
100
+ marked.push(Number(row.id));
101
+ }
77
102
  removed += 1;
78
103
  }
104
+ if (isChunkedTrackerKind(kind))
105
+ dropTrackerChunks(database, marked);
79
106
  return removed;
80
107
  });
81
108
  };
@@ -156,6 +183,20 @@ export const trackerStoreOver = (context) => {
156
183
  hasMore: rows.length > most,
157
184
  };
158
185
  };
186
+ const accountIdsOf = (accounts) => accounts.flatMap((one) => {
187
+ const id = findAccountPk(context, one);
188
+ return id === undefined ? [] : [{ id, key: { provider: one.provider, account: one.account } }];
189
+ });
190
+ const nearest = (model, query, limit, accounts) => {
191
+ const item = database.prepare(`SELECT ${COLUMNS} FROM tracker_items t WHERE t.id = ?`);
192
+ return accountIdsOf(accounts)
193
+ .flatMap(({ id, key }) => nearestTrackerItems(database, model, query, { accountId: id, limit }).flatMap(({ owner, score }) => {
194
+ const row = item.get(owner);
195
+ return row ? [{ account: key, item: itemOf(row), score }] : [];
196
+ }))
197
+ .sort((a, b) => b.score - a.score)
198
+ .slice(0, limit);
199
+ };
159
200
  return {
160
201
  save: async (key, kind, records, now) => save(key, kind, records, now),
161
202
  removeUnlisted: async (key, kind, listed, before, now, options) => removeUnlisted(key, kind, listed, before, now, options),
@@ -206,5 +247,10 @@ export const trackerStoreOver = (context) => {
206
247
  name: row.name == null ? null : String(row.name),
207
248
  }));
208
249
  },
250
+ refreshChunks: async ({ until } = {}) => refreshTrackerChunks(database, context.now(), until),
251
+ chunksToEmbed: async (model, options) => trackerChunksToEmbed(database, model, options),
252
+ chunksLeft: async (model) => trackerChunksLeft(database, model),
253
+ embedded: async (model, accounts) => trackerEmbedded(database, model, accountIdsOf(accounts).map(({ id }) => id)),
254
+ nearest: async (model, query, { limit, accounts }) => nearest(model, query, limit, accounts),
209
255
  };
210
256
  };
@@ -11,10 +11,14 @@ import { listQuery, nativeTermLists, queryTerms, termField, typedQuery, withQuer
11
11
  import { aheadOf } from "../../domain/moment.js";
12
12
  import { STATE_TYPES, TRACKER_KINDS, } from "../../domain/tracker.js";
13
13
  import { count, text } from "../../entities/fields.js";
14
+ import { embedTracker } from "../../services/tracker-meaning.js";
14
15
  import { syncTracker } from "../sync.js";
15
16
  import { trackerIssueTask } from "../tasks.js";
16
17
  import { addTrackerWriteCommands } from "./writes.js";
17
18
  const MOST = 500;
19
+ // The documents' own answer has a `skipped` list of files; a part that did not run says why in a string.
20
+ const isSkipped = (item) => typeof item.skipped === "string";
21
+ const EMBED_MAX = 600;
18
22
  const integer = (most) => (value) => {
19
23
  const number = Number(value);
20
24
  if (!Number.isSafeInteger(number) || number < 1 || number > most)
@@ -90,6 +94,14 @@ const trackerSync = v.strictObject({
90
94
  v.strictObject({ opened: count, closed: count, reopened: count, renamed: count }),
91
95
  v.strictObject({ skipped: text }),
92
96
  ])),
97
+ /** What `sync --embed` embedded of the issues, projects and comments: `embedTracker`'s answer. */
98
+ embeddings: v.optional(v.strictObject({
99
+ model: text,
100
+ embedded: count,
101
+ left: v.boolean(),
102
+ stopped: v.optional(v.picklist(["deadline", "cancelled"])),
103
+ remaining: v.optional(count),
104
+ })),
93
105
  });
94
106
  const partError = v.strictObject({ code: text, reason: v.optional(text), message: text });
95
107
  /** The tracker's answer as `tracker_sync` has it, or the error it failed with, and the documents' answer or error. */
@@ -109,7 +121,11 @@ const resumeStep = (opts, why, extra = {}) => ({
109
121
  kind: "command",
110
122
  step: "tracker.sync",
111
123
  command: "sync",
112
- args: { ...(opts.maxPages === undefined ? {} : { max_pages: opts.maxPages }), ...extra },
124
+ args: {
125
+ ...(opts.maxPages === undefined ? {} : { max_pages: opts.maxPages }),
126
+ ...(opts.embed ? { embed: true } : {}),
127
+ ...extra,
128
+ },
113
129
  why,
114
130
  safe_to_auto_execute: true,
115
131
  });
@@ -132,8 +148,13 @@ const trackerNext = (report, opts) => report.state === "partial" && report.progr
132
148
  : "the sync stopped before its end; running it again goes on from there"),
133
149
  ]
134
150
  : [];
135
- const trackerAnswer = (report, opts) => {
136
- const issues = trackerIssues(report);
151
+ /** Why `--embed` failed after the sync saved its report: a model not downloaded. */
152
+ const embeddingIssue = (error) => {
153
+ const { code, reason } = errorOf(error);
154
+ return { code, reason: reason ?? "sync.failed", source: "tracker:embeddings" };
155
+ };
156
+ const trackerAnswer = (report, opts, embedError) => {
157
+ const issues = [...trackerIssues(report), ...(embedError === undefined ? [] : [embeddingIssue(embedError)])];
137
158
  const next = trackerNext(report, opts);
138
159
  return itemOf(report, {
139
160
  ...(report.state === "partial" || issues.length
@@ -156,7 +177,7 @@ const errorOf = (error) => {
156
177
  * Both parts in one answer: the tracker's report as `tracker_sync` has it, the documents' under `documents`. A part
157
178
  * that fails is named in its place and in `meta.issues`, so the other's answer still shows; `complete` is both parts'.
158
179
  */
159
- const combinedAnswer = (tracker, documents, opts) => {
180
+ const combinedAnswer = (tracker, documents, opts, embedError) => {
160
181
  const failed = (part, error) => ({
161
182
  code: error.code,
162
183
  reason: error.reason ?? "sync.failed",
@@ -169,6 +190,7 @@ const combinedAnswer = (tracker, documents, opts) => {
169
190
  const issues = [
170
191
  ...(report ? trackerIssues(report) : []),
171
192
  ...(trackerError ? [failed("tracker", trackerError)] : []),
193
+ ...(embedError === undefined ? [] : [embeddingIssue(embedError)]),
172
194
  ...(outcome?.meta.issues ?? []),
173
195
  ...(documentsError ? [failed("documents", documentsError)] : []),
174
196
  ];
@@ -180,7 +202,6 @@ const combinedAnswer = (tracker, documents, opts) => {
180
202
  ? [
181
203
  resumeStep(opts, trackerStep?.why ?? "the sync stopped before its end; running it again goes on from there", {
182
204
  ...(opts.timeout === undefined ? {} : { timeout: opts.timeout }),
183
- ...(opts.embed ? { embed: true } : {}),
184
205
  }),
185
206
  ]
186
207
  : []),
@@ -255,6 +276,21 @@ const addTrackerCommandsDefinition = (program, options) => {
255
276
  ...(opts.rescan ? { rescan: true } : {}),
256
277
  });
257
278
  };
279
+ // A run its budget stopped has no time left for the model; the run that finishes the round embeds.
280
+ const embedOf = async (command, run, report) => {
281
+ if (report.stopped)
282
+ return report;
283
+ const { signal, env } = environmentOf(command);
284
+ const deadline = environmentOf(command).deadline?.();
285
+ const embeddings = await embedTracker(run.store, {
286
+ maxChunks: EMBED_MAX,
287
+ ...(deadline ? { deadline } : {}),
288
+ ...(signal ? { signal } : {}),
289
+ ...(env ? { env } : {}),
290
+ command: options.app.command,
291
+ });
292
+ return { ...report, embeddings };
293
+ };
258
294
  const trackerPart = (command, opts, opened = () => { }) => inCommandRun(command, async () => {
259
295
  const run = await options.open(command, { readOnly: false });
260
296
  opened(run.account);
@@ -283,12 +319,28 @@ const addTrackerCommandsDefinition = (program, options) => {
283
319
  ? "at most this many requests for the issues in this run, and as many for the documents"
284
320
  : "at most this many requests to the tracker in this run", integer(100_000));
285
321
  if (!documents)
286
- sync.action(async (opts, command) => {
287
- await within(command, false, async (run) => trackerAnswer(await syncOf(command, opts)(run), opts));
322
+ sync
323
+ .option("--embed", "also index new issues, projects and comments for meaning search, with a model already downloaded")
324
+ .action(async (opts, command) => {
325
+ await within(command, false, async (run) => {
326
+ const report = await syncOf(command, opts)(run);
327
+ if (!opts.embed)
328
+ return trackerAnswer(report, opts);
329
+ try {
330
+ return trackerAnswer(await embedOf(command, run, report), opts);
331
+ }
332
+ catch (error) {
333
+ // What the sync saved is answered; a cancel still ends the command.
334
+ if (environmentOf(command).signal?.aborted)
335
+ throw error;
336
+ return trackerAnswer(report, opts, error);
337
+ }
338
+ });
288
339
  });
289
340
  else
290
341
  sync
291
- .option("--embed", "also index the documents' pending text for meaning search, with a model already downloaded")
342
+ .option("--embed", "also index new issues, projects and comments and the documents' pending text for meaning search, with a " +
343
+ "model already downloaded")
292
344
  .addOption(new Option("--limit <n>", "refused: it would count documents only").hideHelp().argParser(() => {
293
345
  throw new InvalidArgumentError("--limit counts documents only, and this sync brings the issues too; --max-pages bounds both parts");
294
346
  }))
@@ -314,6 +366,21 @@ const addTrackerCommandsDefinition = (program, options) => {
314
366
  ...(opts.embed ? { embed: true } : {}),
315
367
  ...(deadline ? { deadline } : {}),
316
368
  }));
369
+ // A skipped documents part did not run, so a failed tracker part is the whole answer, as without documents.
370
+ if ("error" in tracker && "value" in docs && isSkipped(docs.value.item))
371
+ throw tracker.error;
372
+ // After both parts, so the documents get their sync's time first; outside the tracker's run, which has ended.
373
+ const embedded = opts.embed && "value" in tracker
374
+ ? await settled(async () => {
375
+ const run = await options.open(command, { readOnly: false });
376
+ try {
377
+ return await embedOf(command, run, tracker.value);
378
+ }
379
+ finally {
380
+ await run.close?.();
381
+ }
382
+ })
383
+ : undefined;
317
384
  if ("error" in tracker && "error" in docs) {
318
385
  const failed = errorOf(docs.error);
319
386
  // An error envelope has no meta and keeps only the details its reason registers, so the documents'
@@ -324,7 +391,7 @@ const addTrackerCommandsDefinition = (program, options) => {
324
391
  : tracker.error;
325
392
  }
326
393
  const timeout = command.optsWithGlobals().timeout;
327
- const answer = combinedAnswer(tracker, docs, { ...opts, ...(timeout === undefined ? {} : { timeout }) });
394
+ const answer = combinedAnswer(embedded && "value" in embedded ? embedded : tracker, docs, { ...opts, ...(timeout === undefined ? {} : { timeout }) }, embedded && "error" in embedded ? embedded.error : undefined);
328
395
  renderAnswer(command, outputFor(command), answer);
329
396
  if ("value" in docs)
330
397
  for (const line of docs.value.diagnostics)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.728.0",
3
+ "version": "0.730.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",
@@ -334,7 +334,7 @@
334
334
  "@types/pngjs": "6.0.5",
335
335
  "@types/ssh2": "1.15.5",
336
336
  "@vitest/coverage-v8": "^5.0.5",
337
- "@wirecat/cli-base": "0.130.0",
337
+ "@wirecat/cli-base": "0.131.0",
338
338
  "@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
339
339
  "ajv": "8.17.1",
340
340
  "commander": "15.0.0",