@wirecat/cli-core 0.681.0 → 0.682.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,33 @@ 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.682.0 — 16.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`organizationContext` lists its people's history, not only counts.** `history` holds their messages, mail and
13
+ meetings, newest first, `limit` of them, each with the start of its text and, for a call, its direction, employee and
14
+ length, as a deal context's `communications` does. The `organization_context` schema gains `history`. See
15
+ [business contexts](docs/dev/BUSINESS-CONTEXT.md).
16
+ - **Enrichment takes the run's `deadline`** (`EnrichOptions.deadline`, and `batchMs` for the expected time of one
17
+ batch, 30 s by default). A batch starts only while it is expected to end before the deadline less its margin, so a
18
+ paid request is not cut and sent again at every sync. A batch cut all the same stops the run with the new
19
+ `enrichment.deadline` reason, not `failed`. `embedNotes` and `embedMail` pass their `deadline` on. A run that
20
+ enriched nothing for lack of time does not answer `left`, and the shared documents `sync` asks for a longer run
21
+ with a `sync.longer` step that is not safe to run unasked, so an agent does not repeat a run that cannot move. See
22
+ [the enrichment section](docs/search/ai-providers.md).
23
+ - **`DocumentSyncAnswer.embeddings`**: what `--embed` did, which the shared `sync` reads for that step.
24
+
25
+ ### Fixed
26
+
27
+ - **A documents sync asks its budget before each picture download**, as it does before a file read, so picture
28
+ search no longer runs a sync past its deadline. A refused download leaves the file for the next sync. See
29
+ [Walks over several syncs](docs/dev/DOCUMENTS.md#walks-over-several-syncs).
30
+ - **An embed whose last batch ends as the run is cut answers that it is done**, not `left: true` with
31
+ `remaining: 0`.
32
+ - **`remaining` after an embed stop counts only the chunks the embed would still be given**, in one query that shares
33
+ its conditions with the embed's own. It counted chunks of gone enrichments too, so it never reached 0.
34
+
8
35
  ## 0.681.0 — 16.11.2026
9
36
 
10
37
  ### Added
@@ -25,6 +25,8 @@ export interface DocumentSyncAnswer {
25
25
  names_only?: number;
26
26
  removed?: number;
27
27
  unchanged?: number;
28
+ /** What `--embed` did, as `embedNotes` answers it, or what the CLI says instead. */
29
+ embeddings?: unknown;
28
30
  }
29
31
  export interface DocumentSyncCommands {
30
32
  words: DocumentWords;
@@ -5,6 +5,13 @@ import { honoursDryRun } from "../dry-run-guard.js";
5
5
  import { FETCH, LOCAL_READ } from "../effects.js";
6
6
  import { itemOf } from "../envelope.js";
7
7
  import { examples, positive, wordsOf } from "./words.js";
8
+ /** `embedNotes`' answer says enrichment never had the time to send a batch. */
9
+ const enrichmentOutOfTime = (embeddings) => {
10
+ const enrichment = typeof embeddings === "object" && embeddings !== null && "enrichment" in embeddings
11
+ ? embeddings.enrichment
12
+ : undefined;
13
+ return enrichment?.reason_id === "enrichment.deadline" && enrichment.enriched === 0;
14
+ };
8
15
  const addDocumentSyncCommandsDefinition = (program, helpers) => {
9
16
  const { output } = helpers;
10
17
  const wording = wordsOf(helpers.words);
@@ -30,7 +37,7 @@ const addDocumentSyncCommandsDefinition = (program, helpers) => {
30
37
  const again = `${wording.app} ${helpers.profile()} sync`;
31
38
  const timeout = command.optsWithGlobals().timeout;
32
39
  // The same sync again, never --rescan, which would start the pass over; a run that moved nothing gets no step.
33
- const next = unfinished && !result.errors.length && moved
40
+ const resume = unfinished && !result.errors.length && moved
34
41
  ? [
35
42
  {
36
43
  kind: "command",
@@ -46,6 +53,22 @@ const addDocumentSyncCommandsDefinition = (program, helpers) => {
46
53
  },
47
54
  ]
48
55
  : [];
56
+ // Enrichment starts a batch only when it ends before the deadline; one that never had the time would not move in
57
+ // a run like this one either, so the step asks for a longer run and is not run unasked.
58
+ const longer = enrichmentOutOfTime(result.embeddings)
59
+ ? [
60
+ {
61
+ kind: "command",
62
+ step: "sync.longer",
63
+ command: "sync",
64
+ args: { limit: args.limit, embed: true, timeout: "15m" },
65
+ why: "enrichment needs more time than this run had left, so it sent nothing; run this in a terminal, " +
66
+ "where a sync may take 15 minutes",
67
+ safe_to_auto_execute: false,
68
+ },
69
+ ]
70
+ : [];
71
+ const next = [...resume, ...longer];
49
72
  output(itemOf(result, {
50
73
  meta: result.errors.length
51
74
  ? {
@@ -99,6 +99,17 @@ const taskLine = v.strictObject({
99
99
  due_at: v.nullable(time),
100
100
  });
101
101
  const counts = { messages: count, mail: count, meetings: count };
102
+ /** A message, mail or meeting with the people it involves; a call adds its fields and length. */
103
+ const touch = {
104
+ kind: v.picklist(["message", "mail", "meeting"]),
105
+ ref: reference,
106
+ title: nullableText,
107
+ at: v.nullable(time),
108
+ people: v.array(reference),
109
+ text: v.optional(nullableText),
110
+ call: v.optional(meetingCall),
111
+ duration_ms: v.optional(v.nullable(count)),
112
+ };
102
113
  /** What a person is in the owner's business: organizations, reporting lines, deals and projects, with standing. */
103
114
  export const personBusiness = v.strictObject({
104
115
  organizations: section(v.strictObject({ ...related.entries, categories })),
@@ -141,6 +152,8 @@ export const organizationContext = v.strictObject({
141
152
  money,
142
153
  /** Counts only, through its own people, in the accounts read. */
143
154
  communications: v.strictObject({ ...counts, has_more: v.boolean() }),
155
+ /** Its people's messages, mail and meetings, newest first. */
156
+ history: section(v.strictObject(touch)),
144
157
  tasks: section(taskLine),
145
158
  coverage,
146
159
  });
@@ -157,17 +170,7 @@ export const dealContext = v.strictObject({
157
170
  window: v.strictObject({ since: time, until: time }),
158
171
  /** Shared people within its lifetime: `proposed`, an overlap of people, never a link. */
159
172
  communications: v.strictObject({
160
- ...section(v.strictObject({
161
- kind: v.picklist(["message", "mail", "meeting"]),
162
- ref: reference,
163
- title: nullableText,
164
- at: v.nullable(time),
165
- people: v.array(reference),
166
- text: v.optional(nullableText),
167
- call: v.optional(meetingCall),
168
- duration_ms: v.optional(v.nullable(count)),
169
- standing: v.literal("proposed"),
170
- })).entries,
173
+ ...section(v.strictObject({ ...touch, standing: v.literal("proposed") })).entries,
171
174
  counts: v.strictObject(counts),
172
175
  }),
173
176
  tasks: section(taskLine),
@@ -100,15 +100,21 @@ export const syncDocuments = async (options) => {
100
100
  else
101
101
  result.names_only++;
102
102
  };
103
+ // A call that has listed nothing makes one request, or a short run never moves.
104
+ const ask = () => {
105
+ const taken = options.budget?.take() ?? null;
106
+ return taken === "deadline" && options.budget?.first?.() ? null : taken;
107
+ };
103
108
  let modelMissing = false;
109
+ /** A stop when the budget refuses the download: the file stays pending and the next call fetches it. */
104
110
  const savePictureOf = async (file) => {
105
111
  const entry = state.documents[file.id];
106
112
  if (!profile.picture_search || !isPicture(file) || modelMissing)
107
- return;
113
+ return null;
108
114
  if ((file.size ?? 0) > MAX_PICTURE_BYTES) {
109
115
  entry.picture = "too-large";
110
116
  result.pictures_too_large = (result.pictures_too_large ?? 0) + 1;
111
- return;
117
+ return null;
112
118
  }
113
119
  if (!source)
114
120
  throw new CliError("configuration_error", "a pending picture requires source sign-in");
@@ -121,18 +127,22 @@ export const syncDocuments = async (options) => {
121
127
  throw error;
122
128
  modelMissing = true;
123
129
  result.pictures_skipped = error.message;
124
- return;
130
+ return null;
125
131
  }
126
132
  }
133
+ const stop = ask();
134
+ if (stop)
135
+ return stop;
127
136
  const bytes = await source.bytes(file.id);
128
137
  if (bytes.length > MAX_PICTURE_BYTES) {
129
138
  entry.picture = "too-large";
130
139
  result.pictures_too_large = (result.pictures_too_large ?? 0) + 1;
131
- return;
140
+ return null;
132
141
  }
133
142
  if ((await writer.save(entry.reference, bytes)) === "saved")
134
143
  result.pictures = (result.pictures ?? 0) + 1;
135
144
  entry.picture = "saved";
145
+ return null;
136
146
  };
137
147
  // Saving the whole state after every file grows with the profile; a batch at a time keeps it bounded.
138
148
  let unsaved = 0;
@@ -161,14 +171,16 @@ export const syncDocuments = async (options) => {
161
171
  }
162
172
  else if (job.file && skipReason(job.file)) {
163
173
  await saveNamesOnly(job.file, skipReason(job.file));
164
- await savePictureOf(job.file);
174
+ const stop = await savePictureOf(job.file);
175
+ if (stop) {
176
+ result.stopped = stop;
177
+ break;
178
+ }
165
179
  }
166
180
  else {
167
181
  if (!source)
168
182
  throw new CliError("configuration_error", "a pending save requires source sign-in");
169
- const taken = options.budget?.take();
170
- // A call that has listed nothing reads one page, or a short run never saves one.
171
- const stop = taken === "deadline" && options.budget?.first?.() ? null : taken;
183
+ const stop = ask();
172
184
  if (stop) {
173
185
  result.stopped = stop;
174
186
  break;
@@ -1,10 +1,16 @@
1
1
  import { type KeyringStore } from "@wirecat/cli-base";
2
+ import { type Deadline } from "../background/budget.js";
2
3
  import { type ModelAdapter, type ModelUsage } from "../models/index.js";
3
4
  import type { AppIdentity } from "../ports/app.js";
4
5
  import type { EnrichmentNarrowing, EnrichmentStore } from "../store/store.js";
5
6
  import { type EnrichmentSetting, estimateEnrichment } from "./enrichment-setting.js";
6
7
  /** One sync's share, as embedding is bounded per run; the next sync goes on where it stopped. */
7
8
  export declare const ENRICH_PER_RUN = 600;
9
+ /**
10
+ * How long one batch is expected to take when the caller does not say: 20 records with up to 8 192 tokens out. A
11
+ * guess, not measured; the slowest batch of the run raises it.
12
+ */
13
+ export declare const ENRICH_BATCH_MS = 30000;
8
14
  /** The reply's rows by index; a reply that is not this JSON fails the whole batch. */
9
15
  export declare const parseEnrichmentReply: (text: string) => Map<number, string>;
10
16
  export interface EnrichOptions {
@@ -20,9 +26,16 @@ export interface EnrichOptions {
20
26
  fetch?: typeof fetch;
21
27
  key?: (provider: string) => string | undefined;
22
28
  signal?: AbortSignal;
29
+ /**
30
+ * The run's hard limit: a batch starts only while it is expected to end before the deadline less its margin, so a
31
+ * paid request is not cut and sent again next sync; one cut all the same stops the run as `enrichment.deadline`.
32
+ */
33
+ deadline?: Deadline;
34
+ /** How long one batch is expected to take; `ENRICH_BATCH_MS` when absent. */
35
+ batchMs?: number;
23
36
  }
24
37
  /** Why a run stopped or failed, from a fixed list, so a window can say it in its own words. */
25
- export declare const ENRICHMENT_REASON_IDS: readonly ["enrichment.no-key", "enrichment.key-rejected", "enrichment.unreachable", "enrichment.rate-limited", "enrichment.bad-replies", "enrichment.cancelled", "enrichment.local-only", "enrichment.address-refused", "enrichment.error"];
38
+ export declare const ENRICHMENT_REASON_IDS: readonly ["enrichment.no-key", "enrichment.key-rejected", "enrichment.unreachable", "enrichment.rate-limited", "enrichment.bad-replies", "enrichment.cancelled", "enrichment.deadline", "enrichment.local-only", "enrichment.address-refused", "enrichment.error"];
26
39
  export type EnrichmentReasonId = (typeof ENRICHMENT_REASON_IDS)[number];
27
40
  export type EnrichRun = {
28
41
  status: "off";
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import * as v from "valibot";
3
+ import { ANSWER_RESERVE_MS, deadlineMargin } from "../background/budget.js";
3
4
  import { embeddingKeys, endpointKeyName } from "../embeddings/keys.js";
4
5
  import { modelAddressAllowed, onThisComputer } from "../models/endpoint.js";
5
6
  import { modelGateway } from "../models/index.js";
@@ -16,6 +17,11 @@ const MAX_QUESTIONS = 3;
16
17
  const MAX_LINE = 400;
17
18
  /** After this many failed batches in one run the provider is not answering; the rest wait for the next sync. */
18
19
  const MAX_FAILED_BATCHES = 3;
20
+ /**
21
+ * How long one batch is expected to take when the caller does not say: 20 records with up to 8 192 tokens out. A
22
+ * guess, not measured; the slowest batch of the run raises it.
23
+ */
24
+ export const ENRICH_BATCH_MS = 30_000;
19
25
  const SYSTEM = `For each record, write what a memory system would store about it.
20
26
 
21
27
  For each record:
@@ -64,6 +70,7 @@ export const ENRICHMENT_REASON_IDS = [
64
70
  "enrichment.rate-limited",
65
71
  "enrichment.bad-replies",
66
72
  "enrichment.cancelled",
73
+ "enrichment.deadline",
67
74
  "enrichment.local-only",
68
75
  "enrichment.address-refused",
69
76
  "enrichment.error",
@@ -71,6 +78,7 @@ export const ENRICHMENT_REASON_IDS = [
71
78
  const REASON_TEXT = {
72
79
  "enrichment.key-rejected": "the provider refused the key; nothing more was sent",
73
80
  "enrichment.unreachable": "the provider could not be reached; nothing more was sent",
81
+ "enrichment.deadline": "out of time before the run's deadline; the next sync goes on",
74
82
  };
75
83
  const reasonIdOf = (error) => {
76
84
  // A reply that cannot be read throws a plain error: one more bad batch.
@@ -166,6 +174,10 @@ export const enrichRecords = async (store, options) => {
166
174
  reason: `no ${setting.provider} key: store one with \`models keys set ${setting.provider}\` or set ${keyVariable(setting.provider)}; nothing was sent`,
167
175
  reason_id: "enrichment.no-key",
168
176
  };
177
+ const until = options.deadline ? options.deadline.endsAt - deadlineMargin(options.deadline) : Number.POSITIVE_INFINITY;
178
+ const timeUp = Number.isFinite(until) ? AbortSignal.timeout(Math.max(0, until - Date.now())) : undefined;
179
+ const signals = [options.signal, timeUp].filter((one) => one !== undefined);
180
+ const signal = signals.length ? AbortSignal.any(signals) : undefined;
169
181
  const gateway = modelGateway({
170
182
  resolve: () => target,
171
183
  // The setting exists only with the owner's yes for this provider and endpoint; the endpoint is checked again.
@@ -174,7 +186,7 @@ export const enrichRecords = async (store, options) => {
174
186
  env: options.env,
175
187
  ...(options.adapters ? { adapters: options.adapters } : {}),
176
188
  ...(options.fetch ? { fetch: options.fetch } : {}),
177
- ...(options.signal ? { signal: options.signal } : {}),
189
+ ...(signal ? { signal } : {}),
178
190
  });
179
191
  const queue = await enrichment.pending(maxRecords, options.narrow);
180
192
  const batches = [];
@@ -224,13 +236,29 @@ export const enrichRecords = async (store, options) => {
224
236
  failed += batch.length - answered.length;
225
237
  };
226
238
  let next = 0;
239
+ let slowest = 0;
240
+ const outOfTime = () => {
241
+ reason = REASON_TEXT["enrichment.deadline"];
242
+ reasonId = "enrichment.deadline";
243
+ };
227
244
  const worker = async () => {
228
245
  while (reason === undefined && next < batches.length) {
246
+ if (Date.now() + Math.max(options.batchMs ?? ENRICH_BATCH_MS, slowest) + ANSWER_RESERVE_MS >= until) {
247
+ outOfTime();
248
+ break;
249
+ }
229
250
  const batch = batches[next++];
251
+ const started = Date.now();
230
252
  try {
231
253
  await ask(batch);
254
+ slowest = Math.max(slowest, Date.now() - started);
232
255
  }
233
256
  catch (error) {
257
+ // Cut by the deadline, not refused: the records were not judged, so they are not counted as failed.
258
+ if (timeUp?.aborted && !options.signal?.aborted) {
259
+ outOfTime();
260
+ break;
261
+ }
234
262
  failed += batch.length;
235
263
  const id = reasonIdOf(error);
236
264
  // A refused key or an unreachable provider fails every batch the same way; only a bad reply may be one-off.
@@ -54,7 +54,7 @@ export interface NotesEmbedOptions {
54
54
  app?: AppIdentity;
55
55
  keyring?: KeyringStore;
56
56
  /** Tests give a fake model here; nothing in the suite reaches a provider. */
57
- enrichWith?: Pick<EnrichOptions, "adapters" | "fetch" | "key">;
57
+ enrichWith?: Pick<EnrichOptions, "adapters" | "fetch" | "key" | "batchMs">;
58
58
  /** The run's hard limit: the run stops between batches before it, less its margin, as a sync's last step does. */
59
59
  deadline?: Deadline;
60
60
  signal?: AbortSignal;
@@ -123,16 +123,17 @@ const embedChunks = async (store, source, { model: choice, maxChunks = Number.PO
123
123
  let after;
124
124
  let slowest = 0;
125
125
  while (embedded < maxChunks) {
126
- const why = stopped(slowest);
127
- if (why)
128
- return stop(embedded, why);
129
126
  const started = Date.now();
130
127
  const batch = await source.chunksToEmbed(key, {
131
128
  limit: Math.min(NOTE_BATCH, maxChunks - embedded),
132
129
  ...(after === undefined ? {} : { after }),
133
130
  });
131
+ // Nothing left is done, even at the deadline.
134
132
  if (batch.length === 0)
135
133
  break;
134
+ const why = stopped(slowest);
135
+ if (why)
136
+ return stop(embedded, why);
136
137
  after = batch.at(-1)?.hash;
137
138
  const vectors = await embedder.embed(batch.map(({ text }) => text), "passage");
138
139
  await store.vectors.saveVectors(key, model.dims, batch.map(({ hash }, index) => ({ hash, vector: vectors[index] })));
@@ -149,14 +150,6 @@ const embedChunks = async (store, source, { model: choice, maxChunks = Number.PO
149
150
  */
150
151
  const enrichedFirst = async (store, types, options, embed) => {
151
152
  let enrichment;
152
- const time = stopsAt(options.deadline) - Date.now();
153
- // Out of time, the embed answers that it stopped; enrichment that runs into the deadline fails and is retried.
154
- if (time <= 0 || options.signal?.aborted)
155
- return embed();
156
- const signals = [
157
- ...(options.signal ? [options.signal] : []),
158
- ...(Number.isFinite(time) ? [AbortSignal.timeout(time)] : []),
159
- ];
160
153
  try {
161
154
  const run = await enrichRecords(store, {
162
155
  env: options.env ?? process.env,
@@ -164,7 +157,8 @@ const enrichedFirst = async (store, types, options, embed) => {
164
157
  ...(options.app ? { app: options.app } : {}),
165
158
  ...(options.keyring ? { keyring: options.keyring } : {}),
166
159
  ...options.enrichWith,
167
- ...(signals.length ? { signal: AbortSignal.any(signals) } : {}),
160
+ ...(options.deadline ? { deadline: options.deadline } : {}),
161
+ ...(options.signal ? { signal: options.signal } : {}),
168
162
  });
169
163
  if (run.status !== "off")
170
164
  enrichment = run;
@@ -188,6 +182,7 @@ const enrichedFirst = async (store, types, options, embed) => {
188
182
  }
189
183
  if (!enrichment)
190
184
  return embedded;
185
+ // A run that enriched nothing for lack of time would only repeat itself: it is not `left` to run again.
191
186
  const more = enrichment.status !== "failed" && enrichment.left > 0 && enrichment.enriched > 0;
192
187
  return { ...embedded, left: embedded.left || more, enrichment };
193
188
  };
@@ -1,7 +1,7 @@
1
1
  import { type DealKind } from "../domain/deals.js";
2
2
  import type { AccountKey, Deal, MessageStore, Organization } from "../store/index.js";
3
3
  import { type Category, type Coverage, type Related, type Section } from "./business-context.js";
4
- import { type Communications } from "./communications.js";
4
+ import { type Communications, type Touch } from "./communications.js";
5
5
  import { type MoneySection } from "./money-context.js";
6
6
  export interface DealLine {
7
7
  ref: string;
@@ -49,6 +49,8 @@ export interface OrganizationContext {
49
49
  communications: Communications["counts"] & {
50
50
  hasMore: boolean;
51
51
  };
52
+ /** Its people's messages, mail and meetings, newest first, `limit` of them. */
53
+ history: Section<Touch>;
52
54
  /** Open tasks of its projects. */
53
55
  tasks: Section<TaskLine>;
54
56
  coverage: Coverage;
@@ -125,7 +125,7 @@ export const organizationContext = async (store, reference, { accounts, limit =
125
125
  if (record)
126
126
  members.push(record);
127
127
  }
128
- const talks = await communicationsOf(store, members, scope);
128
+ const talks = await communicationsOf(store, members, scope, { limit });
129
129
  const categories = (await organizationCategories(store, scope)).get(ref) ?? [];
130
130
  const tasks = await openTasksOf(store, [...projects.keys()].flatMap((one) => {
131
131
  const project = catalog.get(one);
@@ -151,6 +151,10 @@ export const organizationContext = async (store, reference, { accounts, limit =
151
151
  orders: oneKind(orders, [[(order) => order.side === "customer", `orders list customer:"${ref}"`]]),
152
152
  }, financeComplete),
153
153
  communications: { ...talks.counts, hasMore: talks.hasMore },
154
+ history: sectionOf(talks.items, limit, null, {
155
+ more: talks.hasMore,
156
+ total: Math.max(talks.counts.messages + talks.counts.mail + talks.counts.meetings, talks.items.length),
157
+ }),
154
158
  tasks: sectionOf(tasks.tasks, limit, tasks.next, { more: tasks.full }),
155
159
  coverage: await coverageFor(store, talks.coverage, scope),
156
160
  };
@@ -66,7 +66,8 @@ export interface LinkFact {
66
66
  export type LinkHold = LinkWeakness | "nothing-shared" | "owner" | "rejected" | "propose-only";
67
67
  /**
68
68
  * What the store finds between two people, never what an agent says. Strong is one value that is a mobile number or a
69
- * personal address, that only these two people hold, from two different sources, and for a phone at least one that
69
+ * personal address, that no one else holds, or that each of its holders has from a different source (one person's
70
+ * CRM card, WhatsApp and call, whatever their names); from two different sources; and for a phone at least one that
70
71
  * keeps its user's own number: a messenger account or a call's number.
71
72
  */
72
73
  export interface LinkEvidence {
@@ -182,7 +183,7 @@ export interface IdentityLinkFilter {
182
183
  export interface MatchScan {
183
184
  /** Every identity was read, not only those changed since the last pass. */
184
185
  full: boolean;
185
- /** People joined without asking: the same personal address, or a phone exactly two people have. */
186
+ /** People joined without asking: the same personal address, or a phone two people have or each source has once. */
186
187
  merged: {
187
188
  into: string;
188
189
  from: string;
@@ -102,9 +102,10 @@ export interface PeopleStore extends AccountPeople {
102
102
  proposeLink(input: IdentityLinkInput): Promise<ProposedAction>;
103
103
  /**
104
104
  * An agent's link. It merges at once only on strong evidence the store finds itself, never on the agent's word:
105
- * one value only these two people hold, a mobile number or a personal address, from two different sources, and for a
106
- * phone at least one that keeps its user's own number (a messenger account or a call's number; NEED-2445, NEED-2600).
107
- * A landline, a value more people share, a company's line, a role address, a name or a CRM's word alone is weak. The
105
+ * one value, a mobile number or a personal address, that no one else holds or that each of its holders has from a
106
+ * different source, whatever their names; from two different sources; and for a phone at least one that keeps its
107
+ * user's own number (a messenger account or a call's number; NEED-2445, NEED-2600, NEED-2697). A landline, a value two
108
+ * records of one source share, a company's line, a role address, a name or a CRM's word alone is weak. The
108
109
  * merge is recorded as an `identity_link` the agent decided, with the evidence, the reason and the run, and the owner
109
110
  * undoes it with `undoMerge`. Weak evidence, the owner's person, a pair the owner rejected, or `apply: false` (the
110
111
  * owner's setting) open a proposal instead, which says why. Refused over the owner's separation.
@@ -129,8 +130,8 @@ export interface PeopleStore extends AccountPeople {
129
130
  */
130
131
  decideLink(id: string, decision: IdentityLinkDecision): Promise<ProposedAction>;
131
132
  /**
132
- * One pass of the people matcher: the same address joins people in every scope, a phone exactly two people have
133
- * joins them, a phone more people share, a role address such as `info@`, a meeting guest's typed address, and one
133
+ * One pass of the people matcher: the same address joins people in every scope, a phone two people have, or one each
134
+ * source has once whatever the names (NEED-2697), joins them, a phone more people of one source share, a role address such as `info@`, a meeting guest's typed address, and one
134
135
  * name with a shared phone, address, chat or company domain become proposals. Never over the owner's separation; a pair the owner rejected is proposed again only on new evidence.
135
136
  */
136
137
  scanMatches(options?: {
@@ -358,6 +358,55 @@ export const noteSearchOver = (context) => {
358
358
  params: [...types, folders, folders, withInternal ? null : folders],
359
359
  };
360
360
  };
361
+ /**
362
+ * Live chunks with no vector of `model` whose text can still be built: a chunk of the model's own words only while
363
+ * its enrichment is kept. `chunksToEmbed` gives these and `chunksLeft` counts them.
364
+ */
365
+ const unembedded = (model) => {
366
+ const scope = live(undefined, undefined);
367
+ return {
368
+ sql: `${scope.sql}
369
+ AND NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)
370
+ AND (k.position <> ${ENRICHMENT_POSITION} OR EXISTS (SELECT 1 FROM enrichments e
371
+ WHERE e.subject_type = k.chunkable_type AND e.subject_id = k.chunkable_id))`,
372
+ params: [...scope.params, model],
373
+ };
374
+ };
375
+ const pendingChunks = (model, after, limit) => {
376
+ drain();
377
+ const where = unembedded(model);
378
+ return database
379
+ .prepare(`SELECT k.content_hash AS hash, min(k.chunkable_type || ':' || k.chunkable_id) AS owner, k.start_offset AS start, k.end_offset AS end,
380
+ k.position
381
+ FROM chunks k
382
+ WHERE k.content_hash > ?${where.sql}
383
+ GROUP BY k.content_hash ORDER BY k.content_hash LIMIT ?`)
384
+ .all(after ?? "", ...where.params, limit);
385
+ };
386
+ // One long note fills a whole batch; build its text once, not once per chunk.
387
+ const textsOf = () => {
388
+ const texts = new Map();
389
+ return (owner) => {
390
+ if (!texts.has(owner)) {
391
+ const [type, id] = owner.split(":");
392
+ const note = read(String(type), Number(id));
393
+ texts.set(owner, note ? noteIndexText(note.title, note.text) : undefined);
394
+ }
395
+ return texts.get(owner);
396
+ };
397
+ };
398
+ /** The row as `chunksToEmbed` gives it, or `undefined` when its enrichment or its note is gone. */
399
+ const chunkOf = (row, textOf) => {
400
+ if (Number(row.position) === ENRICHMENT_POSITION) {
401
+ const [type, id] = String(row.owner).split(":");
402
+ const text = enrichmentText(database, String(type), Number(id));
403
+ return text === undefined ? undefined : { hash: String(row.hash), text };
404
+ }
405
+ const text = textOf(String(row.owner));
406
+ return text === undefined
407
+ ? undefined
408
+ : { hash: String(row.hash), text: text.slice(Number(row.start), Number(row.end)) };
409
+ };
361
410
  return {
362
411
  ...documentPicturesOver(context),
363
412
  search: async (query) => {
@@ -403,46 +452,15 @@ export const noteSearchOver = (context) => {
403
452
  },
404
453
  chunksLeft: async (model) => {
405
454
  drain();
406
- const scope = live(undefined, undefined);
455
+ const where = unembedded(model);
407
456
  const row = database
408
- .prepare(`SELECT count(DISTINCT k.content_hash) AS left FROM chunks k
409
- WHERE 1${scope.sql}
410
- AND NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)`)
411
- .get(...scope.params, model);
457
+ .prepare(`SELECT count(DISTINCT k.content_hash) AS left FROM chunks k WHERE 1${where.sql}`)
458
+ .get(...where.params);
412
459
  return Number(row?.left ?? 0);
413
460
  },
414
461
  chunksToEmbed: async (model, { after, limit }) => {
415
- drain();
416
- const scope = live(undefined, undefined);
417
- // One long note fills a whole batch; build its text once, not once per chunk.
418
- const texts = new Map();
419
- const textOf = (owner) => {
420
- if (!texts.has(owner)) {
421
- const [type, id] = owner.split(":");
422
- const note = read(String(type), Number(id));
423
- texts.set(owner, note ? noteIndexText(note.title, note.text) : undefined);
424
- }
425
- return texts.get(owner);
426
- };
427
- return database
428
- .prepare(`SELECT k.content_hash AS hash, min(k.chunkable_type || ':' || k.chunkable_id) AS owner, k.start_offset AS start, k.end_offset AS end,
429
- k.position
430
- FROM chunks k
431
- WHERE k.content_hash > ?${scope.sql}
432
- AND NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)
433
- GROUP BY k.content_hash ORDER BY k.content_hash LIMIT ?`)
434
- .all(after ?? "", ...scope.params, model, limit)
435
- .flatMap((row) => {
436
- if (Number(row.position) === ENRICHMENT_POSITION) {
437
- const [type, id] = String(row.owner).split(":");
438
- const text = enrichmentText(database, String(type), Number(id));
439
- return text === undefined ? [] : [{ hash: String(row.hash), text }];
440
- }
441
- const text = textOf(String(row.owner));
442
- return text === undefined
443
- ? []
444
- : [{ hash: String(row.hash), text: text.slice(Number(row.start), Number(row.end)) }];
445
- });
462
+ const textOf = textsOf();
463
+ return pendingChunks(model, after, limit).flatMap((row) => chunkOf(row, textOf) ?? []);
446
464
  },
447
465
  embedded: async (model, { folderIds, withInternal, source }) => {
448
466
  drain();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.681.0",
3
+ "version": "0.682.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",