@wirecat/cli-core 0.750.0 → 0.751.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,17 @@ 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.751.0 — 25.11.2026
9
+
10
+ ### Fixed
11
+
12
+ - **A note or task deleted in the CRM leaves the copy.** The sync kept every activity it had once stored. It now marks
13
+ deleted the ones a source's page names in `removed`. A source that lists every activity on each run sets
14
+ `listedAll` on its last page, and then a stored activity it did not list is marked deleted too, when the round was
15
+ read whole and no list was refused. A list that would mark most of ten or more is held with
16
+ `crm.activities-unlisted-held` until `sync --rescan`. `sync` counts them in `activities.removed`
17
+ ([CRM](docs/dev/CRM.md#activities-changes-and-the-digest)).
18
+
8
19
  ## 0.750.0 — 24.11.2026
9
20
 
10
21
  ### Added
@@ -107,7 +107,7 @@ const crmSync = v.strictObject({
107
107
  skipped_owner_rejected: count,
108
108
  contacts_removed: v.optional(crmContactsRemoved),
109
109
  stage_tasks: count,
110
- activities: v.optional(v.strictObject({ saved: count, out_of_scope: count, state: v.picklist(["partial", "complete"]) })),
110
+ activities: v.optional(v.strictObject({ saved: count, out_of_scope: count, removed: count, state: v.picklist(["partial", "complete"]) })),
111
111
  synced: v.array(v.strictObject({
112
112
  kind: v.picklist(CRM_KINDS),
113
113
  round: v.picklist(["full", "changes"]),
@@ -20,6 +20,11 @@ export interface CrmPage<T> {
20
20
  nextCursor?: string;
21
21
  /** On the last page: the cursor the next run reads changes after; `null` when the CRM keeps none. */
22
22
  cursor?: string | null;
23
+ /**
24
+ * On the last page of activities: the round listed every one the CRM holds, whatever `since` asked (Attio's notes
25
+ * take no time filter), so one stored that it did not list was deleted.
26
+ */
27
+ listedAll?: boolean;
23
28
  }
24
29
  /** `reset`: the cursor is dead, and the CRM must be listed in full again. */
25
30
  export type CrmChanges<T> = CrmPage<T> | {
@@ -50,7 +50,7 @@ export interface CrmSyncOptions {
50
50
  export interface CrmSyncIssue {
51
51
  /** `user`: the account's users and departments. */
52
52
  kind: CrmKind | "user";
53
- reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.unassigned-dropped" | "crm.not-reported" | "crm.pending-dropped" | "crm.activities-failed" | "crm.stage-history-failed";
53
+ reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.unassigned-dropped" | "crm.not-reported" | "crm.pending-dropped" | "crm.activities-failed" | "crm.activities-unlisted-held" | "crm.stage-history-failed";
54
54
  message: string;
55
55
  externalId?: string;
56
56
  }
@@ -107,6 +107,8 @@ export interface CrmSyncReport {
107
107
  activities?: {
108
108
  saved: number;
109
109
  outOfScope: number;
110
+ /** Ones the CRM said it deleted, or a full list no longer named, now marked deleted. */
111
+ removed: number;
110
112
  state: "partial" | "complete";
111
113
  };
112
114
  hint?: string;
package/dist/crm/sync.js CHANGED
@@ -169,18 +169,40 @@ const activityCursor = (value) => {
169
169
  return undefined;
170
170
  }
171
171
  };
172
+ /** As the id pass of a kind does, a list that would mark most of the stored activities deleted is held. */
173
+ const removeUnlistedActivities = async (run, options, seen) => {
174
+ const { store, account, source } = run;
175
+ const { stored, unlisted } = await store.crm.removeUnlistedActivities(account, seen, { dryRun: true });
176
+ if (unlisted === 0)
177
+ return;
178
+ if (!options.rescan && (seen.length === 0 || (stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED))) {
179
+ run.report.issues.push({
180
+ kind: "deal",
181
+ reason: "crm.activities-unlisted-held",
182
+ message: `${source.provider} listed ${seen.length} activities, so ${unlisted} of the ${stored} stored would be marked ` +
183
+ "deleted; nothing was — check the sign-in's rights, then run sync --rescan to let it through",
184
+ });
185
+ return;
186
+ }
187
+ const done = await store.crm.removeUnlistedActivities(account, seen);
188
+ if (run.report.activities)
189
+ run.report.activities.removed += done.unlisted;
190
+ };
172
191
  /**
173
192
  * Activities and tasks changed since the last read, after every deal and lead of the run is stored: each is kept only
174
193
  * on the deals and leads this copy holds. Pages go on from where a stopped run left them.
175
194
  */
176
- const readActivities = async (run) => {
195
+ const readActivities = async (run, options) => {
177
196
  const { source, store, account } = run;
178
197
  if (!source.activities || !(await store.crm.activitiesOn(account)))
179
198
  return null;
180
- const read = { saved: 0, outOfScope: 0, state: "partial" };
199
+ const read = { saved: 0, outOfScope: 0, removed: 0, state: "partial" };
181
200
  run.report.activities = read;
182
201
  const saved = activityCursor((await store.sync.syncState(account, ACTIVITIES))?.value);
183
202
  const cursor = saved ?? { since: run.now - ACTIVITY_DAYS * DAY, newest: 0 };
203
+ // Only a round read whole in this run, with no list refused, may show what was deleted: a resumed one lost its start.
204
+ const seen = cursor.page === undefined ? new Set() : undefined;
205
+ const gaps = run.gaps.length;
184
206
  for (;;) {
185
207
  const why = run.budget.take();
186
208
  if (why)
@@ -200,6 +222,10 @@ const readActivities = async (run) => {
200
222
  const done = await store.crm.saveActivities(account, page.items);
201
223
  read.saved += done.saved;
202
224
  read.outOfScope += done.outOfScope;
225
+ if (page.removed?.length)
226
+ read.removed += await store.crm.removeActivities(account, page.removed);
227
+ for (const one of page.items)
228
+ seen?.add(one.externalId);
203
229
  cursor.newest = Math.max(cursor.newest, ...page.items.map((one) => one.updatedAt));
204
230
  run.moved();
205
231
  if (page.hasMore && page.nextCursor !== undefined) {
@@ -209,6 +235,8 @@ const readActivities = async (run) => {
209
235
  return "cancelled";
210
236
  continue;
211
237
  }
238
+ if (page.listedAll && seen && run.gaps.length === gaps)
239
+ await removeUnlistedActivities(run, options, [...seen]);
212
240
  const next = page.cursor != null ? Number(page.cursor) : cursor.newest || cursor.since;
213
241
  await store.sync.setSyncState(account, ACTIVITIES, JSON.stringify({ since: next, newest: 0 }));
214
242
  read.state = "complete";
@@ -635,7 +663,7 @@ export const syncCrm = async (source, store, account, options = {}) => {
635
663
  const rowsStopped = stopped;
636
664
  if (!stopped && kinds.some(isItemKind)) {
637
665
  try {
638
- stopped = await stopping(() => readActivities(run));
666
+ stopped = await stopping(() => readActivities(run, options));
639
667
  }
640
668
  catch (error) {
641
669
  if (options.signal?.aborted)
@@ -599,6 +599,7 @@ const OTHERS = [
599
599
  validation("crm.reference-unknown", "a CRM row names a contact, company or user the store does not hold; that link was not made"),
600
600
  validation("crm.pending-dropped", "relationships waited too long for an end that never came; they were dropped"),
601
601
  validation("crm.activities-failed", "the activities and tasks could not be read; the deals and leads were synced"),
602
+ validation("crm.activities-unlisted-held", "a full list would mark most activities deleted; held until --rescan"),
602
603
  validation("crm.stage-history-failed", "the CRM's stage history could not be read; stage tasks wait for the next sync"),
603
604
  validation("crm.email-ambiguous", "a CRM contact's email belongs to more than one person; the owner decides"),
604
605
  validation("crm.own-unknown", "no own company of the CRM account is stored, so its users are no one's employees yet"),
@@ -60,6 +60,19 @@ export interface ListedActivity extends StoredActivity {
60
60
  }
61
61
  /** The subjects and texts of the activities on each deal or lead of a kind, by `<account id>\u0000<external id>`. */
62
62
  export declare const activityTexts: (database: StoreContext["database"], kind: DealKind) => Map<string, string[]>;
63
+ export interface CrmActivityWrites {
64
+ /** Activities and tasks, each on the kept deals and leads it names; one on none of them is not stored. */
65
+ saveActivities(key: AccountKey, activities: readonly CrmActivity[]): Promise<CrmActivitiesSaved>;
66
+ /** Marks deleted the stored activities the CRM says it deleted; answers how many. */
67
+ removeActivities(key: AccountKey, externalIds: readonly string[]): Promise<number>;
68
+ /** The stored ones a list of every activity did not name, marked deleted; `dryRun` only counts them. */
69
+ removeUnlistedActivities(key: AccountKey, seen: readonly string[], options?: {
70
+ dryRun?: boolean;
71
+ }): Promise<{
72
+ stored: number;
73
+ unlisted: number;
74
+ }>;
75
+ }
63
76
  export interface CrmActivitiesSaved {
64
77
  saved: number;
65
78
  /** On no deal, lead, contact or company this copy keeps, so not stored. */
@@ -67,6 +80,7 @@ export interface CrmActivitiesSaved {
67
80
  }
68
81
  export declare const crmActivitiesOver: (context: StoreContext) => {
69
82
  save: (key: AccountKey, activities: readonly CrmActivity[]) => CrmActivitiesSaved;
83
+ writes: CrmActivityWrites;
70
84
  of: (key: AccountKey, kind: DealKind, externalId: string, limit: number) => StoredActivity[];
71
85
  list: (key: AccountKey, filter: ActivityFilter) => {
72
86
  items: ListedActivity[];
@@ -143,6 +143,25 @@ export const crmActivitiesOver = (context) => {
143
143
  }
144
144
  return { saved, outOfScope };
145
145
  });
146
+ const remove = (key, externalIds) => write(database, () => {
147
+ const forgotten = database
148
+ .prepare("UPDATE records SET deleted_at = ? WHERE account_id = ? AND type = ? AND deleted_at IS NULL " +
149
+ "AND external_id IN (SELECT value FROM json_each(?)) RETURNING id")
150
+ .all(now(), accountPk(context, key), ACTIVITY_RECORD, JSON.stringify(externalIds))
151
+ .map(({ id }) => Number(id));
152
+ dropCrmActivityChunks(database, forgotten);
153
+ return forgotten.length;
154
+ });
155
+ const removeUnlisted = (key, seen, { dryRun = false } = {}) => {
156
+ const accountId = accountPk(context, key);
157
+ const live = "account_id = ? AND type = ? AND deleted_at IS NULL";
158
+ const stored = Number(database.prepare(`SELECT count(*) AS n FROM records WHERE ${live}`).get(accountId, ACTIVITY_RECORD)?.n ?? 0);
159
+ const ids = database
160
+ .prepare(`SELECT external_id FROM records WHERE ${live} AND external_id NOT IN (SELECT value FROM json_each(?))`)
161
+ .all(accountId, ACTIVITY_RECORD, JSON.stringify(seen))
162
+ .map(({ external_id }) => String(external_id));
163
+ return { stored, unlisted: dryRun || ids.length === 0 ? ids.length : remove(key, ids) };
164
+ };
146
165
  /** The activities on one deal or lead: open ones first by due time, then the rest, newest first. */
147
166
  const of = (key, kind, externalId, limit) => {
148
167
  const accountId = findAccountPk(context, key);
@@ -282,7 +301,12 @@ export const crmActivitiesOver = (context) => {
282
301
  where.map(({ sql }) => `AND ${sql}`).join(" "))
283
302
  .get(accountId, ACTIVITY_RECORD, ...where.flatMap(({ params }) => params))?.n ?? 0);
284
303
  };
285
- return { save, of, list, count };
304
+ const writes = {
305
+ saveActivities: async (key, activities) => save(key, activities),
306
+ removeActivities: async (key, externalIds) => remove(key, externalIds),
307
+ removeUnlistedActivities: async (key, seen, options) => removeUnlisted(key, seen, options),
308
+ };
309
+ return { save, writes, of, list, count };
286
310
  };
287
311
  /** An activity a viewer may read: on one of its deals or leads, or on contacts alone and assigned to it. */
288
312
  const seenSql = (viewer) => {
@@ -1,8 +1,8 @@
1
- import { type CrmActivity, type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmScopeSetting, type CrmStageEntry, type CrmUser } from "../../domain/crm.js";
1
+ import { type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmScopeSetting, type CrmStageEntry, type CrmUser } from "../../domain/crm.js";
2
2
  import { type DealKind } from "../../domain/deals.js";
3
3
  import type { AccountPeople } from "../people.js";
4
4
  import type { AccountKey } from "../types.js";
5
- import { type CrmActivitiesSaved, type StoredActivity } from "./crm-activities.js";
5
+ import { type CrmActivityWrites, type StoredActivity } from "./crm-activities.js";
6
6
  import { type CrmActivityChunks } from "./crm-activity-chunks.js";
7
7
  import { type CrmReads } from "./crm-changes.js";
8
8
  import { type CrmContactsRemoved } from "./crm-contacts.js";
@@ -37,7 +37,7 @@ export interface CrmSaved {
37
37
  * nothing is ever matched by name (WC-DATA-6). Rows the CRM no longer has are marked deleted, never removed
38
38
  * (WC-DATA-7). Every write is one transaction per call.
39
39
  */
40
- export interface CrmCopies extends CrmReads {
40
+ export interface CrmCopies extends CrmReads, CrmActivityWrites {
41
41
  /** One kind's pipelines and their stages, by the CRM's ids. A stage the CRM dropped stays: deals may stand in it. */
42
42
  savePipelines(key: AccountKey, kind: DealKind, pipelines: CrmPipeline[]): Promise<CrmSaved>;
43
43
  /** Deals or leads; one whose stage is not stored, or whose fields the store refuses, is skipped and named. */
@@ -113,8 +113,6 @@ export interface CrmCopies extends CrmReads {
113
113
  expireStageEntries(key: AccountKey): Promise<number>;
114
114
  /** Whether the owner turned on reading activities and tasks (`activities` setting). */
115
115
  activitiesOn(key: AccountKey): Promise<boolean>;
116
- /** Activities and tasks, each on the kept deals and leads it names; one on none of them is not stored. */
117
- saveActivities(key: AccountKey, activities: readonly CrmActivity[]): Promise<CrmActivitiesSaved>;
118
116
  /** One deal's or lead's activities, open ones first. */
119
117
  activitiesOf(key: AccountKey, kind: DealKind, externalId: string, limit: number): Promise<StoredActivity[]>;
120
118
  /** The activities' pieces searched by meaning, as `embedCrmActivities` and `search all` read them. */
@@ -4,7 +4,7 @@ import { DEAL_ROLES } from "../../domain/deals.js";
4
4
  import { recordFingerprint } from "../../domain/records.js";
5
5
  import { accountPk, findAccountPk } from "./accounts.js";
6
6
  import { suggestBaseStages } from "./base-suggest.js";
7
- import { crmActivitiesOver, forgetActivitiesOn, } from "./crm-activities.js";
7
+ import { crmActivitiesOver, forgetActivitiesOn } from "./crm-activities.js";
8
8
  import { crmActivityChunksOver } from "./crm-activity-chunks.js";
9
9
  import { crmReadsOver } from "./crm-changes.js";
10
10
  import { removeCrmContacts } from "./crm-contacts.js";
@@ -670,7 +670,7 @@ export const crmCopiesOver = (context, people) => {
670
670
  handleStageEntries: async (ids) => stageEntryStore.handled(ids),
671
671
  expireStageEntries: async (key) => stageEntryStore.expire(key),
672
672
  activitiesOn: async (key) => crmActivitiesOn(database, key),
673
- saveActivities: async (key, activities) => activityStore.save(key, activities),
673
+ ...activityStore.writes,
674
674
  activitiesOf: async (key, kind, externalId, limit) => activityStore.of(key, kind, externalId, limit),
675
675
  activityChunks: crmActivityChunksOver(context),
676
676
  ...crmReadsOver(context),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.750.0",
3
+ "version": "0.751.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",