@wirecat/cli-core 0.682.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,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.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
+
8
35
  ## 0.682.0 — 16.11.2026
9
36
 
10
37
  ### Added
@@ -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);
@@ -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));
@@ -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, Deal, MessageStore, Organization } from "../store/index.js";
3
4
  import { type Category, type Coverage, type Related, type Section } from "./business-context.js";
@@ -62,6 +63,11 @@ export interface OrganizationContextOptions {
62
63
  limit?: number;
63
64
  /** The kinds the profile denies: none of their rows, titles or counts is answered. */
64
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[];
65
71
  }
66
72
  export declare const dealLine: (deal: Deal) => DealLine;
67
73
  /** Open tasks of these projects, the soonest due first, and the command that lists them when it is one project's. */
@@ -79,4 +85,4 @@ export declare const openTasksOf: (store: MessageStore, projects: {
79
85
  * nobody confirmed is `reported`, one that stopped is `ended`, one waiting for the owner `proposed`. A CRM's rows
80
86
  * outside `accounts` are left out, and `coverage` names that CRM.
81
87
  */
82
- 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();
@@ -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));
@@ -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));
@@ -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.682.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",