@wirecat/cli-core 0.681.0 → 0.683.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,60 @@ 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.683.0 — 16.11.2026
9
+
10
+ ### Changed — may break callers
11
+
12
+ - **`config set crm.<provider>:<account>.self` is refused** (`crm.self-from-sync`, also from
13
+ `parseCrmSettingValue`). Only a sync records whose copy it is; `config unset` still gives the copy to the next
14
+ sign-in's sync. A typed id could name the CRM's administrator, and offline reads of the copy by its owner's rule
15
+ (`search all` of another account, memo) then showed the whole copy.
16
+
17
+ ### Fixed
18
+
19
+ - **`changes list` and its `--format report` digest run on Node 22.16.** Their SQL numbered its values (`?13`) and
20
+ bound them from a list, which node:sqlite before Node 22.23 refuses ("column index out of range"); each value is
21
+ now a plain `?` bound in order. The old-Node CI job runs `scripts/node22-crm-changes.mjs` on 22.16.0.
22
+ - **`changes list` lists an activity that arrives done with no due date once**, as `activity_added`: an amoCRM or
23
+ Bitrix24 note or logged call was also listed as `activity_done` at the same time. Such an activity's `done_at` is
24
+ now when it was made. Rows synced before keep both lines.
25
+
26
+ ### Security
27
+
28
+ - **Business contexts and relationships follow the copy's viewer rule.** `organizationContext`,
29
+ `canonicalPersonContext` and `dealContext` take `viewing` (one `CrmViewing` per CRM account, from `crmViewerOf`):
30
+ a deal or lead the profile may not read is not listed or named, `dealContext` of one is `not_found`, and each
31
+ rule's note goes to `coverage.notRead`. `listRelations` takes `viewers` (`CopyViewer[]`) and leaves out, in its
32
+ query, every relationship with a deal or lead end a viewer may not read, so a caller titling relationship ends never
33
+ sees one. Without the options nothing changes.
34
+
35
+ ## 0.682.0 — 16.11.2026
36
+
37
+ ### Added
38
+
39
+ - **`organizationContext` lists its people's history, not only counts.** `history` holds their messages, mail and
40
+ meetings, newest first, `limit` of them, each with the start of its text and, for a call, its direction, employee and
41
+ length, as a deal context's `communications` does. The `organization_context` schema gains `history`. See
42
+ [business contexts](docs/dev/BUSINESS-CONTEXT.md).
43
+ - **Enrichment takes the run's `deadline`** (`EnrichOptions.deadline`, and `batchMs` for the expected time of one
44
+ batch, 30 s by default). A batch starts only while it is expected to end before the deadline less its margin, so a
45
+ paid request is not cut and sent again at every sync. A batch cut all the same stops the run with the new
46
+ `enrichment.deadline` reason, not `failed`. `embedNotes` and `embedMail` pass their `deadline` on. A run that
47
+ enriched nothing for lack of time does not answer `left`, and the shared documents `sync` asks for a longer run
48
+ with a `sync.longer` step that is not safe to run unasked, so an agent does not repeat a run that cannot move. See
49
+ [the enrichment section](docs/search/ai-providers.md).
50
+ - **`DocumentSyncAnswer.embeddings`**: what `--embed` did, which the shared `sync` reads for that step.
51
+
52
+ ### Fixed
53
+
54
+ - **A documents sync asks its budget before each picture download**, as it does before a file read, so picture
55
+ search no longer runs a sync past its deadline. A refused download leaves the file for the next sync. See
56
+ [Walks over several syncs](docs/dev/DOCUMENTS.md#walks-over-several-syncs).
57
+ - **An embed whose last batch ends as the run is cut answers that it is done**, not `left: true` with
58
+ `remaining: 0`.
59
+ - **`remaining` after an embed stop counts only the chunks the embed would still be given**, in one query that shares
60
+ its conditions with the embed's own. It counted chunks of gone enrichments too, so it never reached 0.
61
+
8
62
  ## 0.681.0 — 16.11.2026
9
63
 
10
64
  ### 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
  ? {
@@ -302,9 +302,7 @@ const crmNote = (name, now) => {
302
302
  ? "store-wide — no stage opens a task"
303
303
  : "store-wide — from now on, each sync opens a local task for every deal or lead that moved into one of these " +
304
304
  "stages since the last sync; moves made before the rules were first set open none";
305
- return now === ""
306
- ? "store-wide — the next sync gives the account's copy to its sign-in's user, and narrows it to that user's deals"
307
- : "store-wide — the account's copy holds this user's deals; a sync signed in as another user is refused";
305
+ return "store-wide — the next sync gives the account's copy to its sign-in's user, and narrows it to that user's deals";
308
306
  };
309
307
  const changeCrm = async (env, setting, value) => {
310
308
  const { name } = parseCrmSetting(setting);
@@ -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),
@@ -417,6 +417,7 @@ const OTHERS = [
417
417
  validation("deal.field", "a field of the deal or lead is not valid"),
418
418
  ["deal.denied", "permission_error", "the profile denies listing deals or leads, so none is answered"],
419
419
  ["deal.out-of-scope", "not_found", "the deal or lead is a copy from an account outside the accounts asked for"],
420
+ ["deal.not-readable", "not_found", "the deal or lead is a copy the profile's CRM sign-in may not read"],
420
421
  validation("deal.ref", "the reference names no deal or lead"),
421
422
  validation("deal.stage", "no stage of that name, or a stage name more than one pipeline has"),
422
423
  validation("stage.base-field", "a base stage needs a name its set has once and a position within the set"),
@@ -438,6 +439,7 @@ const OTHERS = [
438
439
  validation("pipeline.duplicate", "a pipeline of that name and kind is already stored"),
439
440
  validation("pipeline.field", "a pipeline needs a name and at least one stage, each named once"),
440
441
  ["pipeline.not-found", "not_found", "no stored pipeline has that name or reference"],
442
+ validation("crm.self-from-sync", "only a sync records whose CRM copy it is; config unset hands the copy to the next sync"),
441
443
  validation("crm.stage-unknown", "a CRM item stands in a stage the store does not hold; it was not kept"),
442
444
  validation("crm.item-invalid", "a CRM item has a field the store refuses, such as a status it does not know"),
443
445
  validation("crm.amount-unkept", "a CRM deal's amount is in a currency or with decimals the store cannot hold: the deal is kept without it"),
@@ -1,7 +1,9 @@
1
+ import { type CrmViewing } from "../crm/index.js";
1
2
  import { CATEGORIES, type Category } from "../domain/categories.js";
2
3
  import type { DealKind } from "../domain/deals.js";
3
4
  import { type Standing } from "../domain/relations.js";
4
5
  import type { AccountKey, KnowledgeRelation, MessageStore } from "../store/index.js";
6
+ import { type CopyViewer } from "../store/store.js";
5
7
  /** Items a context section lists before it says `hasMore`. */
6
8
  export declare const SECTION_LIMIT = 20;
7
9
  /** What one store list answers at most: a read that fills it may hold more. */
@@ -26,7 +28,9 @@ export declare const keyOf: ({ provider, account }: AccountKey) => string;
26
28
  * The accounts a context reads, the caller's `--source` or group already resolved; every account when none is
27
29
  * given. A row no account reported — the owner's, an agent's — is always in it. `left` collects every account whose
28
30
  * rows were kept out, so `coverage` can say so. `denied` holds the kinds the profile denies (`deals.list`,
29
- * `leads.list`): no row, title or count of them is answered, and `coverage` says they were denied.
31
+ * `leads.list`): no row, title or count of them is answered, and `coverage` says they were denied. `viewers` are the
32
+ * CRM copies' rules for the profile (SEC-197, `crmViewerOf`): a deal or lead one may not read is never named, and each
33
+ * note on why a copy shows less goes to `coverage`.
30
34
  */
31
35
  export interface Scope {
32
36
  accounts: AccountKey[] | undefined;
@@ -35,8 +39,18 @@ export interface Scope {
35
39
  denied: ReadonlySet<DealKind>;
36
40
  /** A ref the answer may name: none of a denied kind. */
37
41
  allows(ref: string): boolean;
42
+ viewers: CopyViewer[];
43
+ viewerNotes: {
44
+ source: string;
45
+ reason: string;
46
+ }[];
47
+ /** A deal or lead row every viewer may read. */
48
+ sees(deal: {
49
+ account: AccountKey | null;
50
+ assignee: string | null;
51
+ }): boolean;
38
52
  }
39
- export declare const scopeOf: (accounts: AccountKey[] | undefined, denied?: readonly DealKind[]) => Scope;
53
+ export declare const scopeOf: (accounts: AccountKey[] | undefined, denied?: readonly DealKind[], viewing?: readonly CrmViewing[]) => Scope;
40
54
  export declare const notRejected: <T extends {
41
55
  review: string;
42
56
  }>(rows: T[]) => T[];
@@ -1,6 +1,7 @@
1
1
  import { crmGapsOf } from "../crm/index.js";
2
2
  import { CATEGORIES } from "../domain/categories.js";
3
3
  import { isUsable } from "../domain/relations.js";
4
+ import { seenBy } from "../store/store.js";
4
5
  /** Items a context section lists before it says `hasMore`. */
5
6
  export const SECTION_LIMIT = 20;
6
7
  /** What one store list answers at most: a read that fills it may hold more. */
@@ -15,14 +16,18 @@ export const sectionOf = (all, limit, next, { more = false, total = all.length,
15
16
  };
16
17
  };
17
18
  export const keyOf = ({ provider, account }) => `${provider}:${account}`;
18
- export const scopeOf = (accounts, denied = []) => {
19
+ export const scopeOf = (accounts, denied = [], viewing = []) => {
19
20
  const asked = accounts && new Set(accounts.map(keyOf));
20
21
  const left = new Set();
21
22
  const kinds = new Set(denied);
23
+ const viewers = viewing.flatMap(({ viewer }) => (viewer ? [viewer] : []));
22
24
  return {
23
25
  accounts,
24
26
  left,
25
27
  denied: kinds,
28
+ viewers,
29
+ viewerNotes: viewing.flatMap(({ viewer, note }) => viewer && note ? [{ source: keyOf(viewer.account), reason: note }] : []),
30
+ sees: ({ account, assignee }) => viewers.every((viewer) => seenBy(viewer, { provider: account?.provider, account: account?.account, assignee })),
26
31
  has: (account) => {
27
32
  if (account == null)
28
33
  return true;
@@ -57,6 +62,7 @@ export const edgesOf = async (store, ref, scope) => {
57
62
  about: ref,
58
63
  includeEnded: true,
59
64
  deniedKinds: [...scope.denied],
65
+ ...(scope.viewers.length ? { viewers: scope.viewers } : {}),
60
66
  limit: STORE_PAGE,
61
67
  ...(scope.accounts === undefined ? {} : { accounts: scope.accounts }),
62
68
  });
@@ -139,6 +145,8 @@ export const coverageFor = async (store, base, scope) => {
139
145
  const named = new Set(notRead.map((one) => one.source));
140
146
  for (const kind of scope.denied)
141
147
  notRead.push({ source: `${kind}s`, reason: "denied" });
148
+ for (const note of scope.viewerNotes)
149
+ notRead.push(note);
142
150
  if (scope.accounts !== undefined)
143
151
  for (const key of await store.accounts.accounts())
144
152
  if (!scope.has(key))
@@ -1,3 +1,4 @@
1
+ import type { CrmViewing } from "../crm/index.js";
1
2
  import type { DealKind } from "../domain/deals.js";
2
3
  import { type Standing } from "../domain/relations.js";
3
4
  import type { AccountKey, Deal, MessageStore, StageChange } from "../store/index.js";
@@ -48,13 +49,17 @@ export interface DealContextOptions {
48
49
  now?: number;
49
50
  /** The kinds the profile denies: a deal or lead of one is not answered. */
50
51
  deniedKinds?: readonly DealKind[];
52
+ /**
53
+ * Each CRM copy's rule for the profile (`crmViewerOf`, SEC-197): a deal or lead it may not read is not found.
54
+ */
55
+ viewing?: readonly CrmViewing[];
51
56
  }
52
57
  /**
53
58
  * One answer about a deal or a lead from the store: the row, how it moved, its client, people, project, money and
54
59
  * what its people said within its lifetime. Nothing is inferred from a stage's name. A CRM's copy outside
55
60
  * `accounts` is not answered, and a CRM's relationships outside it are left out.
56
61
  */
57
- export declare const dealContext: (store: MessageStore, reference: string, { accounts, limit, now, deniedKinds }?: DealContextOptions) => Promise<DealContext>;
62
+ export declare const dealContext: (store: MessageStore, reference: string, { accounts, limit, now, deniedKinds, viewing }?: DealContextOptions) => Promise<DealContext>;
58
63
  /** The compact form for a model's context: names, roles and standings, totals and counts, no row detail. */
59
64
  export interface DealBrief {
60
65
  ref: string;
@@ -11,8 +11,8 @@ const DAY = 86_400_000;
11
11
  * what its people said within its lifetime. Nothing is inferred from a stage's name. A CRM's copy outside
12
12
  * `accounts` is not answered, and a CRM's relationships outside it are left out.
13
13
  */
14
- export const dealContext = async (store, reference, { accounts, limit = SECTION_LIMIT, now = Date.now(), deniedKinds = [] } = {}) => {
15
- const scope = scopeOf(accounts, deniedKinds);
14
+ export const dealContext = async (store, reference, { accounts, limit = SECTION_LIMIT, now = Date.now(), deniedKinds = [], viewing = [] } = {}) => {
15
+ const scope = scopeOf(accounts, deniedKinds, viewing);
16
16
  const kind = /^lead:/.test(reference.trim()) ? "lead" : "deal";
17
17
  if (scope.denied.has(kind))
18
18
  throw new CliError("permission_error", `the profile denies ${kind}s.list, so no ${kind} is answered`, {
@@ -24,6 +24,10 @@ export const dealContext = async (store, reference, { accounts, limit = SECTION_
24
24
  throw new CliError("not_found", `${deal.ref} is a copy from an account outside the accounts asked for`, {
25
25
  reason: "deal.out-of-scope",
26
26
  });
27
+ if (!scope.sees(deal))
28
+ throw new CliError("not_found", `${deal.ref} is not a copy this profile's CRM sign-in may read`, {
29
+ reason: "deal.not-readable",
30
+ });
27
31
  const { edges, full } = await edgesOf(store, deal.ref, scope);
28
32
  const people = edges.filter((edge) => edge.role.kind === "related-to" && edge.from === deal.ref && edge.to.startsWith("person:"));
29
33
  const names = await namesOf(store, people.map(({ to }) => to));
@@ -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,8 @@
1
+ import type { CrmViewing } from "../crm/index.js";
1
2
  import { type DealKind } from "../domain/deals.js";
2
3
  import type { AccountKey, Deal, MessageStore, Organization } from "../store/index.js";
3
4
  import { type Category, type Coverage, type Related, type Section } from "./business-context.js";
4
- import { type Communications } from "./communications.js";
5
+ import { type Communications, type Touch } from "./communications.js";
5
6
  import { type MoneySection } from "./money-context.js";
6
7
  export interface DealLine {
7
8
  ref: string;
@@ -49,6 +50,8 @@ export interface OrganizationContext {
49
50
  communications: Communications["counts"] & {
50
51
  hasMore: boolean;
51
52
  };
53
+ /** Its people's messages, mail and meetings, newest first, `limit` of them. */
54
+ history: Section<Touch>;
52
55
  /** Open tasks of its projects. */
53
56
  tasks: Section<TaskLine>;
54
57
  coverage: Coverage;
@@ -60,6 +63,11 @@ export interface OrganizationContextOptions {
60
63
  limit?: number;
61
64
  /** The kinds the profile denies: none of their rows, titles or counts is answered. */
62
65
  deniedKinds?: readonly DealKind[];
66
+ /**
67
+ * Each CRM copy's rule for the profile (`crmViewerOf`, SEC-197): a deal or lead it may not read is left out, and
68
+ * `coverage.notRead` carries the rule's note.
69
+ */
70
+ viewing?: readonly CrmViewing[];
63
71
  }
64
72
  export declare const dealLine: (deal: Deal) => DealLine;
65
73
  /** Open tasks of these projects, the soonest due first, and the command that lists them when it is one project's. */
@@ -77,4 +85,4 @@ export declare const openTasksOf: (store: MessageStore, projects: {
77
85
  * nobody confirmed is `reported`, one that stopped is `ended`, one waiting for the owner `proposed`. A CRM's rows
78
86
  * outside `accounts` are left out, and `coverage` names that CRM.
79
87
  */
80
- export declare const organizationContext: (store: MessageStore, reference: string, { accounts, limit, deniedKinds }?: OrganizationContextOptions) => Promise<OrganizationContext>;
88
+ export declare const organizationContext: (store: MessageStore, reference: string, { accounts, limit, deniedKinds, viewing }?: OrganizationContextOptions) => Promise<OrganizationContext>;
@@ -51,7 +51,7 @@ const oneKind = (rows, commands) => commands.find(([fits]) => rows.every(fits))?
51
51
  * nobody confirmed is `reported`, one that stopped is `ended`, one waiting for the owner `proposed`. A CRM's rows
52
52
  * outside `accounts` are left out, and `coverage` names that CRM.
53
53
  */
54
- export const organizationContext = async (store, reference, { accounts, limit = SECTION_LIMIT, deniedKinds = [] } = {}) => {
54
+ export const organizationContext = async (store, reference, { accounts, limit = SECTION_LIMIT, deniedKinds = [], viewing = [] } = {}) => {
55
55
  const id = /^(?:organization:)?(\d+)$/.exec(reference.trim())?.[1];
56
56
  if (id === undefined)
57
57
  throw new CliError("validation_error", "an organization is organization:<id>");
@@ -59,7 +59,7 @@ export const organizationContext = async (store, reference, { accounts, limit =
59
59
  const [organization] = await store.knowledge.organizations(parseLucene(`id:${id}`));
60
60
  if (!organization)
61
61
  throw new CliError("not_found", `no ${ref} in the store`);
62
- const scope = scopeOf(accounts, deniedKinds);
62
+ const scope = scopeOf(accounts, deniedKinds, viewing);
63
63
  const own = (await store.knowledge.ownOrganizations()).some((one) => one.ref === ref);
64
64
  const { edges, full } = await edgesOf(store, ref, scope);
65
65
  const names = await namesOf(store, edges.flatMap(({ from, to }) => [from, to]));
@@ -80,7 +80,8 @@ export const organizationContext = async (store, reference, { accounts, limit =
80
80
  });
81
81
  dealsFull ||= found.hasMore;
82
82
  for (const deal of found.items)
83
- deals.push(deal);
83
+ if (scope.sees(deal))
84
+ deals.push(deal);
84
85
  }
85
86
  const catalog = new Map((await store.knowledge.projects()).map((project) => [project.ref, project]));
86
87
  const projects = new Map();
@@ -125,7 +126,7 @@ export const organizationContext = async (store, reference, { accounts, limit =
125
126
  if (record)
126
127
  members.push(record);
127
128
  }
128
- const talks = await communicationsOf(store, members, scope);
129
+ const talks = await communicationsOf(store, members, scope, { limit });
129
130
  const categories = (await organizationCategories(store, scope)).get(ref) ?? [];
130
131
  const tasks = await openTasksOf(store, [...projects.keys()].flatMap((one) => {
131
132
  const project = catalog.get(one);
@@ -151,6 +152,10 @@ export const organizationContext = async (store, reference, { accounts, limit =
151
152
  orders: oneKind(orders, [[(order) => order.side === "customer", `orders list customer:"${ref}"`]]),
152
153
  }, financeComplete),
153
154
  communications: { ...talks.counts, hasMore: talks.hasMore },
155
+ history: sectionOf(talks.items, limit, null, {
156
+ more: talks.hasMore,
157
+ total: Math.max(talks.counts.messages + talks.counts.mail + talks.counts.meetings, talks.items.length),
158
+ }),
154
159
  tasks: sectionOf(tasks.tasks, limit, tasks.next, { more: tasks.full }),
155
160
  coverage: await coverageFor(store, talks.coverage, scope),
156
161
  };
@@ -1,3 +1,4 @@
1
+ import type { CrmViewing } from "../crm/index.js";
1
2
  import type { DealKind } from "../domain/deals.js";
2
3
  import type { AccountKey, MessageStore, PersonRecord } from "../store/store.js";
3
4
  import { type Category, type Coverage, type Related, type Scope, type Section } from "./business-context.js";
@@ -30,6 +31,11 @@ export interface CanonicalContextOptions extends ContextOptions {
30
31
  limit?: number;
31
32
  /** The kinds the profile denies: no deal or lead of theirs is named. */
32
33
  deniedKinds?: readonly DealKind[];
34
+ /**
35
+ * Each CRM copy's rule for the profile (`crmViewerOf`, SEC-197): a deal or lead it may not read is not named, and
36
+ * `coverage.notRead` carries the rule's note.
37
+ */
38
+ viewing?: readonly CrmViewing[];
33
39
  }
34
40
  export declare const personBusiness: (store: MessageStore, uid: string, { limit, scope }?: {
35
41
  limit?: number;
@@ -40,4 +46,4 @@ export declare const personBusiness: (store: MessageStore, uid: string, { limit,
40
46
  * someone seen by several accounts alike. Every identity is read in every account in scope that saw it — never one
41
47
  * picked for them (WC-ACCT-9) — and `coverage` says what was read and what was not.
42
48
  */
43
- export declare const canonicalPersonContext: (store: MessageStore, reference: string, { accounts, limit, deniedKinds, ...options }?: CanonicalContextOptions) => Promise<CanonicalPersonContext>;
49
+ export declare const canonicalPersonContext: (store: MessageStore, reference: string, { accounts, limit, deniedKinds, viewing, ...options }?: CanonicalContextOptions) => Promise<CanonicalPersonContext>;
@@ -37,14 +37,14 @@ export const personBusiness = async (store, uid, { limit = SECTION_LIMIT, scope
37
37
  * someone seen by several accounts alike. Every identity is read in every account in scope that saw it — never one
38
38
  * picked for them (WC-ACCT-9) — and `coverage` says what was read and what was not.
39
39
  */
40
- export const canonicalPersonContext = async (store, reference, { accounts, limit, deniedKinds, ...options } = {}) => {
40
+ export const canonicalPersonContext = async (store, reference, { accounts, limit, deniedKinds, viewing, ...options } = {}) => {
41
41
  const uid = /^person:(\d+)$/.exec(reference.trim())?.[1];
42
42
  if (uid === undefined)
43
43
  throw new CliError("validation_error", "a person is person:<id>");
44
44
  const record = await store.people.personByUid(uid);
45
45
  if (!record)
46
46
  throw new CliError("not_found", `no person:${uid} in the store`);
47
- const scope = scopeOf(accounts, deniedKinds);
47
+ const scope = scopeOf(accounts, deniedKinds, viewing);
48
48
  const stored = await store.accounts.storedAccounts();
49
49
  // The scope is the caller's: every stored account it holds is readable, whatever its personal or work scope.
50
50
  const readable = stored.filter((one) => scope.has(one));
@@ -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?: {
@@ -64,6 +64,17 @@ export const crmActivitiesOver = (context) => {
64
64
  : database
65
65
  .prepare(`SELECT 1 FROM ${TABLES[kind]} WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL`)
66
66
  .get(accountId, externalId)) !== undefined;
67
+ /**
68
+ * When it was done, as near as the copy can tell: the CRM's change that closed it, kept once seen. One that arrives
69
+ * done with no due date, as a note or a logged call, was done when it was made, and `changes list` lists it once.
70
+ */
71
+ const doneAt = (activity, held) => {
72
+ if (!activity.done)
73
+ return null;
74
+ if (held?.done)
75
+ return held.done_at ?? null;
76
+ return held === undefined && activity.dueAt == null ? activity.createdAt : activity.updatedAt;
77
+ };
67
78
  const save = (key, activities) => write(database, () => {
68
79
  const accountId = accountPk(context, key);
69
80
  const at = now();
@@ -88,8 +99,7 @@ export const crmActivitiesOver = (context) => {
88
99
  body: textOf(activity.body, MOST_BODY),
89
100
  due_at: activity.dueAt ?? null,
90
101
  done: activity.done,
91
- // When it was done, as near as the copy can tell: the CRM's change that closed it, kept once seen.
92
- done_at: activity.done ? (held?.done ? (held.done_at ?? null) : activity.updatedAt) : null,
102
+ done_at: doneAt(activity, held),
93
103
  assignee: activity.assignee ? crmIdentityId(key, activity.assignee, "user") : null,
94
104
  created_at: activity.createdAt,
95
105
  updated_at: activity.updatedAt,
@@ -52,6 +52,14 @@ export interface ChangeFilter {
52
52
  limit: number;
53
53
  offset: number;
54
54
  }
55
+ /**
56
+ * `sql` with each `?N` as a plain `?`, and its values in the order they appear. node:sqlite before Node 22.23 binds
57
+ * no `?N` from a list of values ("column index out of range"), and every version refuses a value the SQL never uses.
58
+ */
59
+ export declare const usedParams: <T>(sql: string, params: readonly T[]) => {
60
+ sql: string;
61
+ params: T[];
62
+ };
55
63
  /** How many changes of each kind `filter`'s window holds, every page together. */
56
64
  export declare const crmChangeCounts: (context: StoreContext, key: AccountKey, filter: Omit<ChangeFilter, "limit" | "offset">) => Record<CrmChangeKind, number>;
57
65
  /**
@@ -16,6 +16,14 @@ export const CRM_CHANGES = [
16
16
  const HALF_DAY = 43_200_000;
17
17
  const DAY = 86_400_000;
18
18
  const utcDay = (at) => new Date(at).toISOString().slice(0, 10);
19
+ /**
20
+ * `sql` with each `?N` as a plain `?`, and its values in the order they appear. node:sqlite before Node 22.23 binds
21
+ * no `?N` from a list of values ("column index out of range"), and every version refuses a value the SQL never uses.
22
+ */
23
+ export const usedParams = (sql, params) => ({
24
+ sql: sql.replace(/\?\d+/g, "?"),
25
+ params: [...sql.matchAll(/\?(\d+)/g)].map((one) => params[Number(one[1]) - 1]),
26
+ });
19
27
  /** The SQL of every change in `filter`'s window, unordered, and its numbered parameters (`?13`, `?14` page it). */
20
28
  const changesQuery = (context, key, filter) => {
21
29
  const accountId = findAccountPk(context, key);
@@ -73,7 +81,13 @@ const changesQuery = (context, key, filter) => {
73
81
  `FROM (SELECT r.id, r.fields, ${itemOf("r.id")} AS item, (SELECT target_type FROM record_relations ` +
74
82
  "WHERE record_id = r.id AND role = 'on' LIMIT 1) AS target FROM records r WHERE r.account_id = ?1 " +
75
83
  `AND r.type = ?4 AND r.deleted_at IS NULL AND json_extract(r.fields, '$.${field}') ` +
76
- "BETWEEN ?6 AND ?7) a " +
84
+ "BETWEEN ?6 AND ?7" +
85
+ // One that arrived done with no due date was done as it was made: its `activity_added` says it.
86
+ (field === "done_at"
87
+ ? " AND NOT (json_extract(r.fields, '$.due_at') IS NULL AND " +
88
+ "json_extract(r.fields, '$.done_at') = json_extract(r.fields, '$.created_at'))"
89
+ : "") +
90
+ ") a " +
77
91
  // A viewer reads an activity on its own deal or lead, or one on contacts alone that is assigned to it.
78
92
  `WHERE ?15 IS NULL OR a.item IS NOT NULL OR (NOT ${onDealOrLead} AND json_extract(a.fields, '$.assignee') = ?16)`),
79
93
  "SELECT 'person_added', CAST(json_extract(r.fields, '$.created_at') AS INTEGER), 'person', NULL, r.id, NULL, " +
@@ -119,9 +133,8 @@ export const crmChangeCounts = (context, key, filter) => {
119
133
  const query = changesQuery(context, key, { ...filter, limit: 0, offset: 0 });
120
134
  if (!query)
121
135
  return counts;
122
- for (const row of context.database
123
- .prepare(`SELECT change, count(*) AS n FROM (${query.sql}) GROUP BY change`)
124
- .all(...query.params))
136
+ const counted = usedParams(`SELECT change, count(*) AS n FROM (${query.sql}) GROUP BY change`, query.params);
137
+ for (const row of context.database.prepare(counted.sql).all(...counted.params))
125
138
  counts[row.change] = Number(row.n);
126
139
  return counts;
127
140
  };
@@ -136,9 +149,8 @@ export const crmChanges = (context, key, filter) => {
136
149
  const query = changesQuery(context, key, filter);
137
150
  if (!query)
138
151
  return { items: [], hasMore: false };
139
- const rows = database
140
- .prepare(`${query.sql} ORDER BY at DESC, change, kind, item DESC, record DESC LIMIT ?13 OFFSET ?14`)
141
- .all(...query.params);
152
+ const paged = usedParams(`${query.sql} ORDER BY at DESC, change, kind, item DESC, record DESC LIMIT ?13 OFFSET ?14`, query.params);
153
+ const rows = database.prepare(paged.sql).all(...paged.params);
142
154
  const stageName = database.prepare("SELECT name FROM pipeline_stages WHERE id = ?");
143
155
  const nameOf = (id) => id == null ? null : (stageName.get(Number(id))?.name ?? null);
144
156
  const itemStatements = Object.fromEntries(["deal", "lead"].map((kind) => [
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { isCrmUserId, normalCrmUserId } from "../../domain/crm.js";
2
+ import { isCrmUserId } from "../../domain/crm.js";
3
3
  /** `reported`: what a CRM account says is a relationship nobody confirmed; `review`: it waits as a proposal. */
4
4
  export const CRM_LINK_MODES = ["reported", "review"];
5
5
  /** What a CRM company type may mean: the company buys from the own company, sells to it, or partners with it. */
@@ -179,11 +179,10 @@ export const parseCrmSettingValue = (name, value) => {
179
179
  return picked(name, text, CRM_SCOPES);
180
180
  if (name === "activities")
181
181
  return picked(name, text, CRM_ACTIVITIES);
182
- if (name === "self") {
183
- if (!isCrmUserId(text))
184
- throw new CliError("validation_error", `self takes the CRM's numeric user id: not "${text}"`);
185
- return normalCrmUserId(text);
186
- }
182
+ // The copy's viewers read their rule by it (SEC-201): a typed id could name the administrator.
183
+ if (name === "self")
184
+ throw new CliError("validation_error", "self is whose copy it is, and only the copy's first sync records it: unset it to give the copy to the next " +
185
+ "sign-in's sync", { reason: "crm.self-from-sync" });
187
186
  if (name === "unassigned") {
188
187
  const ids = [...new Set(text.split(",").map((one) => one.trim()))];
189
188
  const bad = ids.find((one) => !isCrmUserId(one));
@@ -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();
@@ -1,5 +1,6 @@
1
1
  import { type RelationKind, type RoleList, type Standing } from "../../domain/relations.js";
2
2
  import type { AccountKey } from "../types.js";
3
+ import type { CopyViewer } from "./copy-viewer.js";
3
4
  import type { StoreContext } from "./open.js";
4
5
  import { type KnowledgeRelation } from "./relation-proposals.js";
5
6
  export interface RelationFilter {
@@ -22,6 +23,8 @@ export interface RelationFilter {
22
23
  accounts?: AccountKey[];
23
24
  /** No row with an end of these types, such as `deal` and `lead` a profile denies. */
24
25
  deniedKinds?: string[];
26
+ /** No row with a deal or lead end that one of these may not read (SEC-197); each limits only its own account. */
27
+ viewers?: readonly CopyViewer[];
25
28
  limit?: number;
26
29
  /** 1-based. */
27
30
  page?: number;
@@ -83,6 +83,22 @@ export const relationListOver = (context) => {
83
83
  const list = filter.deniedKinds.map(() => "?").join(", ");
84
84
  add(`r.from_type NOT IN (${list}) AND r.to_type NOT IN (${list})`, ...filter.deniedKinds, ...filter.deniedKinds);
85
85
  }
86
+ for (const viewer of filter.viewers ?? []) {
87
+ const account = database
88
+ .prepare("SELECT id FROM accounts WHERE provider = ? AND external_id = ?")
89
+ .get(viewer.account.provider, viewer.account.account);
90
+ if (!account)
91
+ continue;
92
+ // `IS NOT` keeps an unassigned row hidden: `<>` would compare with null and let it through.
93
+ const other = viewer.assignee === null ? "" : " AND json_extract(e.metadata, '$.assignee') IS NOT ?";
94
+ for (const side of ["from", "to"])
95
+ for (const [type, table] of [
96
+ ["deal", "deals"],
97
+ ["lead", "leads"],
98
+ ])
99
+ add(`NOT (r.${side}_type = '${type}' AND EXISTS (SELECT 1 FROM ${table} e WHERE e.id = r.${side}_id ` +
100
+ `AND e.account_id = ?${other}))`, Number(account.id), ...(viewer.assignee === null ? [] : [viewer.assignee]));
101
+ }
86
102
  const rows = database
87
103
  .prepare(`SELECT r.source, r.id FROM (
88
104
  SELECT 'link' AS source, id, from_type, from_id, to_type, to_id, kind, role, account_id, starts_at, ends_at,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.681.0",
3
+ "version": "0.683.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",