@wirecat/cli-core 0.749.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/attachments/tesseract.d.ts +4 -1
  3. package/dist/attachments/tesseract.js +13 -4
  4. package/dist/background/report/render.js +1 -1
  5. package/dist/cli/documents/library.js +2 -0
  6. package/dist/crm/cli/index.js +1 -1
  7. package/dist/crm/source.d.ts +5 -0
  8. package/dist/crm/sync.d.ts +3 -1
  9. package/dist/crm/sync.js +31 -3
  10. package/dist/crm/testing/files-contract.js +5 -2
  11. package/dist/domain/tracker.d.ts +27 -6
  12. package/dist/domain/tracker.js +13 -8
  13. package/dist/errors/reasons.js +11 -0
  14. package/dist/services/documents/scans.d.ts +2 -0
  15. package/dist/services/documents/scans.js +3 -0
  16. package/dist/store/sqlite/crm-activities.d.ts +14 -0
  17. package/dist/store/sqlite/crm-activities.js +25 -1
  18. package/dist/store/sqlite/crm.d.ts +3 -5
  19. package/dist/store/sqlite/crm.js +2 -2
  20. package/dist/store/sqlite/tracker.d.ts +6 -2
  21. package/dist/store/sqlite/tracker.js +72 -5
  22. package/dist/tracker/cli/index.js +21 -8
  23. package/dist/tracker/manifest/manifest.d.ts +4 -1
  24. package/dist/tracker/manifest/manifest.js +4 -1
  25. package/dist/tracker/manifest/map.js +19 -1
  26. package/dist/tracker/manifest/source.js +5 -1
  27. package/dist/tracker/sync.d.ts +9 -0
  28. package/dist/tracker/sync.js +8 -2
  29. package/dist/tracker/tasks.d.ts +4 -4
  30. package/dist/tracker/tasks.js +6 -5
  31. package/dist/tracker/testing/manifest-fake.d.ts +2 -0
  32. package/dist/tracker/testing/manifest-fake.js +20 -0
  33. package/dist/tracker/testing/source-contract.d.ts +8 -0
  34. package/dist/tracker/testing/source-contract.js +28 -2
  35. package/dist/tracker/testing/source.d.ts +9 -1
  36. package/dist/tracker/testing/source.js +25 -2
  37. package/package.json +1 -1
@@ -39,7 +39,21 @@ export const resetTrackerItemWords = (database) => {
39
39
  });
40
40
  };
41
41
  const keyOf = (data) => data == null ? undefined : JSON.parse(String(data)).key;
42
- const ISSUE_FIELDS = { assignee: "assignee", project: "project", state: "state" };
42
+ const ISSUE_FIELDS = { assignee: "assignee", project: "project", state: "state", sprint: "sprint" };
43
+ /**
44
+ * Marks the live comments of these issues deleted with them; a comment of a trashed issue is only archived in Linear,
45
+ * and would stay found under an issue that is gone.
46
+ */
47
+ const deleteComments = (database, accountId, issues, now) => {
48
+ if (!issues.length)
49
+ return;
50
+ const ids = database
51
+ .prepare("UPDATE tracker_items SET deleted_at = ? WHERE account_id = ? AND kind = 'comment' AND deleted_at IS NULL " +
52
+ "AND parent_id IN (SELECT value FROM json_each(?)) RETURNING id")
53
+ .all(now, accountId, JSON.stringify(issues))
54
+ .map((row) => Number(row.id));
55
+ dropTrackerChunks(database, ids);
56
+ };
43
57
  /**
44
58
  * The words as clauses for `clauseIn`, and the index expression that finds the rows they could match: a word, a word
45
59
  * it begins, or a word that begins with its stem. A Snowball stem begins its word, but for the English `y` it turns to
@@ -77,6 +91,10 @@ export const trackerStoreOver = (context) => {
77
91
  const save = (key, kind, records, now) => write(database, () => {
78
92
  const accountId = accountPk(context, key);
79
93
  const stored = database.prepare("SELECT data, title, body, deleted_at FROM tracker_items WHERE account_id = ? AND kind = ? AND external_id = ?");
94
+ const issueDeletedAt = database.prepare("SELECT deleted_at FROM tracker_items WHERE account_id = ? AND kind = 'issue' AND external_id = ?");
95
+ const reviveComments = database.prepare("UPDATE tracker_items SET deleted_at = NULL WHERE account_id = ? AND kind = 'comment' AND parent_id = ? " +
96
+ "AND deleted_at = ?");
97
+ let changed = 0;
80
98
  const scope = database.prepare("SELECT scope FROM accounts WHERE id = ?").get(accountId)?.scope;
81
99
  const chunked = isChunkedTrackerKind(kind);
82
100
  const chunk = trackerChunkWriter(database);
@@ -85,12 +103,14 @@ export const trackerStoreOver = (context) => {
85
103
  "WHERE account_id = ? AND kind = 'comment' AND parent_id = ? AND deleted_at IS NULL");
86
104
  const upsert = database.prepare("INSERT INTO tracker_items (account_id, kind, external_id, parent_id, title, title_folded, body, " +
87
105
  "normalized_text, data, source_created_at, source_updated_at, archived_at, deleted_at, synced_at) " +
88
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?) " +
106
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
89
107
  "ON CONFLICT (account_id, kind, external_id) DO UPDATE SET parent_id = excluded.parent_id, " +
90
108
  "title = excluded.title, title_folded = excluded.title_folded, body = excluded.body, " +
91
109
  "normalized_text = excluded.normalized_text, data = excluded.data, " +
92
110
  "source_created_at = excluded.source_created_at, source_updated_at = excluded.source_updated_at, " +
93
- "archived_at = excluded.archived_at, deleted_at = NULL, synced_at = excluded.synced_at RETURNING id");
111
+ "archived_at = excluded.archived_at, deleted_at = CASE WHEN excluded.deleted_at IS NULL THEN NULL " +
112
+ "ELSE coalesce(tracker_items.deleted_at, excluded.deleted_at) END, synced_at = excluded.synced_at " +
113
+ "RETURNING id, deleted_at");
94
114
  for (const record of records) {
95
115
  const before = stored.get(accountId, kind, record.externalId);
96
116
  // A field the tracker left out of this read keeps what the store knew: a read never erases by omission.
@@ -100,7 +120,27 @@ export const trackerStoreOver = (context) => {
100
120
  };
101
121
  const title = trackerTitleOf(kind, merged);
102
122
  const body = trackerBodyOf(kind, merged) ?? null;
103
- const saved = upsert.get(accountId, kind, merged.externalId, trackerParentOf(kind, merged) ?? null, title, fold(title), body, normalize([title, body].filter(Boolean).join("\n")), JSON.stringify(merged), merged.createdAt ?? null, merged.updatedAt ?? null, merged.archivedAt ?? null, now);
123
+ const data = JSON.stringify(merged);
124
+ // A comment saved under a deleted issue goes with it: Linear lists it as archived, not deleted.
125
+ const parentGone = kind === "comment"
126
+ ? issueDeletedAt.get(accountId, merged.issue ?? null)?.deleted_at
127
+ : undefined;
128
+ const deletedAt = merged.deleted === true ? now : parentGone == null ? null : Number(parentGone);
129
+ const saved = upsert.get(accountId, kind, merged.externalId, trackerParentOf(kind, merged) ?? null, title, fold(title), body, normalize([title, body].filter(Boolean).join("\n")), data, merged.createdAt ?? null, merged.updatedAt ?? null, merged.archivedAt ?? null, deletedAt, now);
130
+ const gone = saved?.deleted_at != null;
131
+ if (!before || before.data !== data || (before.deleted_at != null) !== gone)
132
+ changed += 1;
133
+ if (gone) {
134
+ if (before?.deleted_at == null) {
135
+ if (chunked)
136
+ dropTrackerChunks(database, [Number(saved?.id)]);
137
+ if (kind === "issue")
138
+ deleteComments(database, accountId, [merged.externalId], Number(saved?.deleted_at));
139
+ }
140
+ continue;
141
+ }
142
+ if (kind === "issue" && before?.deleted_at != null)
143
+ reviveComments.run(accountId, merged.externalId, Number(before.deleted_at));
104
144
  // Most rows of a sync come back with the text they had; their chunks stay, and only a revived row needs new.
105
145
  const same = before?.deleted_at == null && before?.title === title && (before?.body ?? null) === body;
106
146
  // A comment is embedded after its issue's key and title, so a new, revived, renamed or moved issue cuts its
@@ -139,8 +179,29 @@ export const trackerStoreOver = (context) => {
139
179
  released.push(hash);
140
180
  }
141
181
  dropUnusedVectors(database, released);
142
- return records.length;
182
+ return changed;
143
183
  });
184
+ /**
185
+ * Linear moves no `updatedAt` when an issue leaves the trash, so the id pass listing a deleted row again is the
186
+ * only sign it is back. A comment stays deleted while its issue is: Linear lists a trashed issue's comments.
187
+ */
188
+ const restoreListed = (accountId, kind, listed) => {
189
+ const found = database
190
+ .prepare("SELECT t.id, t.external_id, t.deleted_at FROM tracker_items t WHERE t.account_id = ? AND t.kind = ? " +
191
+ "AND t.deleted_at IS NOT NULL AND t.external_id IN (SELECT value FROM json_each(?)) " +
192
+ "AND (t.kind <> 'comment' OR NOT EXISTS (SELECT 1 FROM tracker_items i WHERE i.account_id = t.account_id " +
193
+ "AND i.kind = 'issue' AND i.external_id = t.parent_id AND i.deleted_at IS NOT NULL))")
194
+ .all(accountId, kind, JSON.stringify(listed));
195
+ const restore = database.prepare("UPDATE tracker_items SET deleted_at = NULL, data = CASE WHEN json_extract(data, '$.deleted') IS NULL " +
196
+ "THEN data ELSE json_set(data, '$.deleted', json('false')) END WHERE id = ?");
197
+ const comments = database.prepare("UPDATE tracker_items SET deleted_at = NULL WHERE account_id = ? AND kind = 'comment' AND parent_id = ? " +
198
+ "AND deleted_at = ?");
199
+ for (const row of found) {
200
+ restore.run(Number(row.id));
201
+ if (kind === "issue")
202
+ comments.run(accountId, String(row.external_id), Number(row.deleted_at));
203
+ }
204
+ };
144
205
  const removeUnlisted = (key, kind, listed, before, now, { dryRun = false } = {}) => {
145
206
  const accountId = findAccountPk(context, key);
146
207
  if (accountId === undefined)
@@ -150,6 +211,7 @@ export const trackerStoreOver = (context) => {
150
211
  const mark = database.prepare("UPDATE tracker_items SET deleted_at = ? WHERE id = ?");
151
212
  let removed = 0;
152
213
  const marked = [];
214
+ const issues = [];
153
215
  for (const row of database
154
216
  .prepare("SELECT id, external_id FROM tracker_items WHERE account_id = ? AND kind = ? AND deleted_at IS NULL " +
155
217
  "AND synced_at < ?")
@@ -159,11 +221,16 @@ export const trackerStoreOver = (context) => {
159
221
  if (!dryRun) {
160
222
  mark.run(now, Number(row.id));
161
223
  marked.push(Number(row.id));
224
+ if (kind === "issue")
225
+ issues.push(String(row.external_id));
162
226
  }
163
227
  removed += 1;
164
228
  }
165
229
  if (isChunkedTrackerKind(kind))
166
230
  dropTrackerChunks(database, marked);
231
+ deleteComments(database, accountId, issues, now);
232
+ if (!dryRun)
233
+ restoreListed(accountId, kind, listed);
167
234
  return removed;
168
235
  });
169
236
  };
@@ -45,10 +45,11 @@ const ISSUES_QUERY = {
45
45
  termField("state", "kw", "state:state-1", { relation: "the state's id, as states list shows it" }),
46
46
  termField("type", "enum", "type:started", { values: [...STATE_TYPES], relation: "repeat for any of several" }),
47
47
  termField("label", "kw", "label:label-1", { relation: "the label's id, as labels list shows it" }),
48
+ termField("sprint", "kw", "sprint:sprint-1", { relation: "the sprint's id, as sprints list shows it, or none" }),
48
49
  ARCHIVED,
49
50
  ],
50
51
  };
51
- const TIMES = new Set(["createdAt", "updatedAt", "archivedAt", "completedAt", "canceledAt"]);
52
+ const TIMES = new Set(["createdAt", "updatedAt", "archivedAt", "completedAt", "canceledAt", "startsAt", "endsAt"]);
52
53
  const snake = (name) => name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
53
54
  /** A tracker's text is someone else's: an agent reads these fields as data, never as instructions. */
54
55
  const UNTRUSTED = {
@@ -57,6 +58,7 @@ const UNTRUSTED = {
57
58
  state: ["name"],
58
59
  label: ["name"],
59
60
  project: ["name", "description", "status"],
61
+ sprint: ["name", "description"],
60
62
  issue: ["title", "description", "state_name", "labels_names"],
61
63
  comment: ["body"],
62
64
  };
@@ -90,6 +92,7 @@ const trackerSync = v.strictObject({
90
92
  })),
91
93
  gaps: v.array(v.strictObject({ kind: v.picklist(TRACKER_KINDS), message: text, scope: v.optional(text) })),
92
94
  progress: v.strictObject({ requests: count, saved: count, steps: count }),
95
+ deletions: v.strictObject({ checked: v.nullable(text), due: text }),
93
96
  tasks: v.optional(v.union([
94
97
  v.strictObject({ opened: count, closed: count, reopened: count, renamed: count }),
95
98
  v.strictObject({ skipped: text }),
@@ -129,7 +132,10 @@ const resumeStep = (opts, why, extra = {}) => ({
129
132
  why,
130
133
  safe_to_auto_execute: true,
131
134
  });
135
+ // Not a failure of the run: a key without the scope lacks it on every sync, so it must not mark the sync partial.
136
+ const UNREAD = "tracker.kind-unread";
132
137
  const trackerIssues = (report) => [
138
+ ...report.gaps.map((gap) => ({ code: "permission_error", reason: UNREAD, source: `tracker:${gap.kind}` })),
133
139
  ...report.synced
134
140
  .filter((one) => one.error !== undefined)
135
141
  .map((one) => ({ code: "provider_error", reason: "sync.partial", source: `tracker:${one.kind}` })),
@@ -194,7 +200,10 @@ const combinedAnswer = (tracker, documents, opts, embedError) => {
194
200
  ...(outcome?.meta.issues ?? []),
195
201
  ...(documentsError ? [failed("documents", documentsError)] : []),
196
202
  ];
197
- const complete = report?.state === "complete" && outcome !== undefined && outcome.meta.complete !== false && issues.length === 0;
203
+ const complete = report?.state === "complete" &&
204
+ outcome !== undefined &&
205
+ outcome.meta.complete !== false &&
206
+ issues.every((one) => one.reason === UNREAD);
198
207
  const [trackerStep] = report ? trackerNext(report, opts) : [];
199
208
  const resume = trackerStep !== undefined || outcome?.next.some(({ step }) => step === "sync.run");
200
209
  const next = [
@@ -212,7 +221,7 @@ const combinedAnswer = (tracker, documents, opts, embedError) => {
212
221
  ? { ...report, complete, documents: documentsPart }
213
222
  : { complete: false, synced: [], error: trackerError, documents: documentsPart };
214
223
  return itemOf(item, {
215
- ...(complete ? {} : { meta: { complete: false, ...(issues.length ? { issues } : {}) } }),
224
+ ...(complete && !issues.length ? {} : { meta: { complete: false, ...(issues.length ? { issues } : {}) } }),
216
225
  ...(next.length ? { next } : {}),
217
226
  });
218
227
  };
@@ -305,10 +314,10 @@ const addTrackerCommandsDefinition = (program, options) => {
305
314
  }
306
315
  });
307
316
  const { documents } = options;
308
- const sync = example(answerEntity(annotate(program.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), documents ? "tracker_documents_sync" : "tracker_sync", documents ? trackerDocumentsSync : trackerSync).description("bring the tracker's copy in the local store up to date: teams, users, states, labels, projects, issues and " +
309
- "comments that changed since the last sync, or everything with --rescan; once a day it also finds what the " +
310
- "tracker deleted. Open issues assigned to you become your tasks, and close when the issue is done, " +
311
- "canceled, deleted or goes to someone else. " +
317
+ const sync = example(answerEntity(annotate(program.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), documents ? "tracker_documents_sync" : "tracker_sync", documents ? trackerDocumentsSync : trackerSync).description("bring the tracker's copy in the local store up to date: teams, users, states, labels, projects, sprints, " +
318
+ "issues and comments that changed since the last sync, or everything with --rescan; once a day it also finds " +
319
+ "what the tracker deleted, and says when it next will. Open issues assigned to you become your tasks, " +
320
+ "and close when the issue is done, canceled, a duplicate, deleted or goes to someone else. " +
312
321
  (documents
313
322
  ? "It also imports what changed in the chosen document folders, answered under documents; a part that " +
314
323
  "fails leaves the other's answer. "
@@ -407,7 +416,9 @@ const addTrackerCommandsDefinition = (program, options) => {
407
416
  throw new InvalidArgumentError("issues list takes field:value terms, each one whole value");
408
417
  const types = (lists.get("type") ?? []).map((one) => one.value.toLowerCase());
409
418
  const terms = new Map([...lists].filter(([field]) => field !== "type").map(([field, [one]]) => [field, one?.value]));
410
- const assignee = terms.get("assignee")?.toLowerCase() === "none" ? "none" : terms.get("assignee");
419
+ const noneOr = (field) => (terms.get(field)?.toLowerCase() === "none" ? "none" : terms.get(field));
420
+ const assignee = noneOr("assignee");
421
+ const sprint = noneOr("sprint");
411
422
  await within(command, true, async (run) => {
412
423
  const filter = {
413
424
  ...(terms.has("team") ? { parent: terms.get("team") } : {}),
@@ -416,6 +427,7 @@ const addTrackerCommandsDefinition = (program, options) => {
416
427
  ...(terms.has("state") ? { state: terms.get("state") } : {}),
417
428
  ...(types.length ? { stateTypes: types } : {}),
418
429
  ...(terms.has("label") ? { label: terms.get("label") } : {}),
430
+ ...(sprint !== undefined ? { sprint: sprint === "none" ? null : sprint } : {}),
419
431
  ...(terms.has("archived") ? { archived: true } : {}),
420
432
  limit: opts.limit,
421
433
  offset: (opts.page - 1) * opts.limit,
@@ -487,6 +499,7 @@ const addTrackerCommandsDefinition = (program, options) => {
487
499
  });
488
500
  for (const [kind, plural, what] of [
489
501
  ["project", "projects", "the tracker's projects: status, lead, teams and target date"],
502
+ ["sprint", "sprints", "each team's sprints (Linear's cycles): number, start, end and when completed"],
490
503
  ["team", "teams", "the tracker's teams"],
491
504
  ["user", "users", "the tracker's users, each with the person the store knows by the same e-mail"],
492
505
  ["state", "states", "each team's workflow states and their type"],
@@ -26,7 +26,10 @@ export interface TrackerManifestEntity<K extends TrackerKind = TrackerKind> {
26
26
  list: TrackerOperationCall;
27
27
  /** Rows changed since `{since}`, the last cursor less the overlap; absent, every sync lists in full. */
28
28
  changes?: TrackerChangesCall;
29
- /** Every id, archived ones too, to find deletions; absent, `list`. Give one that selects only the id. */
29
+ /**
30
+ * Every id, archived ones too, to find deletions; absent, `list`. Give one that selects only the id, and what the
31
+ * map's `deleted` reads: a row the tracker lists but calls deleted is left out, so the pass marks it deleted.
32
+ */
30
33
  ids?: TrackerOperationCall;
31
34
  map: {
32
35
  readonly [F in keyof TrackerRecords[K]]?: CrmRule;
@@ -141,7 +141,10 @@ export const parseTrackerManifest = (input, api) => {
141
141
  throw invalid(`entities.${kind}.changes`, 'no "{since}" in its variables');
142
142
  }
143
143
  if (one.ids)
144
- checkCall(`entities.${kind}.ids`, one.ids, { externalId: one.map.externalId });
144
+ checkCall(`entities.${kind}.ids`, one.ids, {
145
+ externalId: one.map.externalId,
146
+ ...(one.map.deleted === undefined ? {} : { deleted: one.map.deleted }),
147
+ });
145
148
  }
146
149
  for (const [kind, one] of Object.entries(manifest.entities))
147
150
  if (one && !manifest.kinds.includes(kind))
@@ -1,7 +1,13 @@
1
1
  import { crmValues } from "../../crm/index.js";
2
2
  import { convert, mapFields, rulePaths } from "../../crm/manifest/map.js";
3
3
  import { STATE_TYPES } from "../../domain/tracker.js";
4
- const TIMES = { externalId: "id", createdAt: "epoch", updatedAt: "epoch", archivedAt: "epoch" };
4
+ const TIMES = {
5
+ externalId: "id",
6
+ createdAt: "epoch",
7
+ updatedAt: "epoch",
8
+ archivedAt: "epoch",
9
+ deleted: "bool",
10
+ };
5
11
  // A literal after `key:` reads as a permission key to src/cli/permission-keys.test.ts.
6
12
  const KEY = "text";
7
13
  /** Each of our fields and how a value the tracker sent becomes it. */
@@ -20,6 +26,16 @@ export const TRACKER_FIELDS = {
20
26
  targetDate: "day",
21
27
  url: "text",
22
28
  },
29
+ sprint: {
30
+ ...TIMES,
31
+ name: "text",
32
+ number: "number",
33
+ description: "text",
34
+ team: "id",
35
+ startsAt: "epoch",
36
+ endsAt: "epoch",
37
+ completedAt: "epoch",
38
+ },
23
39
  issue: {
24
40
  ...TIMES,
25
41
  title: "text",
@@ -28,6 +44,7 @@ export const TRACKER_FIELDS = {
28
44
  state: "id",
29
45
  team: "id",
30
46
  project: "id",
47
+ sprint: "id",
31
48
  assignee: "id",
32
49
  creator: "id",
33
50
  labels: "ids",
@@ -47,6 +64,7 @@ const REQUIRED = {
47
64
  state: { name: "" },
48
65
  label: { name: "" },
49
66
  project: { name: "" },
67
+ sprint: { name: "" },
50
68
  issue: { title: "" },
51
69
  comment: { body: "" },
52
70
  };
@@ -1,7 +1,7 @@
1
1
  import { CliError, isCliError } from "@wirecat/cli-base";
2
2
  import { nextPage, parameterValue, withValue } from "../../cli/service-api-manifest.js";
3
3
  import { crmValues } from "../../crm/index.js";
4
- import { at, evaluate, MISSING } from "../../crm/manifest/map.js";
4
+ import { at, convert, evaluate, MISSING } from "../../crm/manifest/map.js";
5
5
  import { parseTrackerManifest, } from "./manifest.js";
6
6
  import { mapTrackerRecord } from "./map.js";
7
7
  const OVERLAP_MS = 10 * 60_000;
@@ -130,7 +130,11 @@ export const trackerSourceFromManifest = (input, options) => {
130
130
  const entity = entityOf(kind);
131
131
  const { rows, next } = await readPage(entity.ids ?? entity.list, undefined, page, metered(context));
132
132
  const rule = entity.map.externalId;
133
+ const { deleted } = entity.map;
133
134
  const items = rows.flatMap((raw) => {
135
+ // Linear's trash moves no updatedAt, so only this pass sees a trashed row: leaving it out marks it deleted.
136
+ if (deleted !== undefined && convert("bool", evaluate(deleted, raw)) === true)
137
+ return [];
134
138
  const found = evaluate(rule, raw);
135
139
  const externalId = found === MISSING ? null : crmValues.id(found);
136
140
  return externalId === null ? [] : [externalId];
@@ -22,6 +22,7 @@ export interface TrackerSyncResult {
22
22
  /** The cursor was dead, so the round became a full one. */
23
23
  reset: boolean;
24
24
  state: "partial" | "complete";
25
+ /** Rows that changed in the copy: new, different, or deleted or back again. A row read again as it was is not. */
25
26
  saved: number;
26
27
  /** Rows a complete id pass did not list, now marked deleted. */
27
28
  unlisted: number;
@@ -50,6 +51,14 @@ export interface TrackerSyncReport {
50
51
  saved: number;
51
52
  steps: number;
52
53
  };
54
+ /**
55
+ * When the id pass that finds deleted rows last ran for every kind (`null` before the first) and when it is next due:
56
+ * a sync between them finds no deletion.
57
+ */
58
+ deletions: {
59
+ checked: string | null;
60
+ due: string;
61
+ };
53
62
  /**
54
63
  * The owner's tasks from issues assigned to the signed-in user, brought in line with the copy. Absent when the
55
64
  * tracker cannot name its user or the run was cancelled; `skipped` says why they were left as they were.
@@ -65,8 +65,9 @@ const syncChanges = async (run, kind, result, mode) => {
65
65
  continue;
66
66
  }
67
67
  if (page.items.length) {
68
- result.saved += await store.tracker.save(account, kind, page.items, run.now);
69
- run.report.progress.saved += page.items.length;
68
+ const changed = await store.tracker.save(account, kind, page.items, run.now);
69
+ result.saved += changed;
70
+ run.report.progress.saved += changed;
70
71
  }
71
72
  run.report.progress.steps += 1;
72
73
  if (!page.hasMore) {
@@ -172,6 +173,7 @@ export const syncTracker = async (source, store, account, options = {}) => {
172
173
  complete: true,
173
174
  state: "complete",
174
175
  progress: { requests: 0, saved: 0, steps: 0 },
176
+ deletions: { checked: null, due: new Date(now).toISOString() },
175
177
  };
176
178
  const said = new Set();
177
179
  const run = {
@@ -243,6 +245,10 @@ export const syncTracker = async (source, store, account, options = {}) => {
243
245
  }
244
246
  await store.sync.setSyncState(account, RESUME, report.stopped ? JSON.stringify({ v: 1, done: [...done], ...(mode.full ? { rescan: true } : {}) }) : "null");
245
247
  await store.sync.setSyncState(account, GAPS, JSON.stringify(report.gaps));
248
+ const passes = await Promise.all(kinds.map(async (kind) => parsed((await store.sync.syncState(account, trackerCursorName(kind)))?.value)?.passAt ?? 0));
249
+ const checked = passes.reduce((least, one) => Math.min(least, one), passes[0] ?? 0);
250
+ if (checked > 0)
251
+ report.deletions = { checked: new Date(checked).toISOString(), due: new Date(checked + passEvery).toISOString() };
246
252
  if (source.self && source.traits.kinds.includes("issue") && report.stopped !== "cancelled")
247
253
  report.tasks = await ownTasks(run, source.self.bind(source));
248
254
  return report;
@@ -28,10 +28,10 @@ export interface TrackerTaskChanges {
28
28
  /**
29
29
  * Brings the owner's tasks in line with the tracker's copy, after a sync: each live issue assigned to `self` whose
30
30
  * state is open work becomes a task, and every task from an issue takes the issue's current title. A task closes when
31
- * its issue is completed, canceled, archived or deleted, and a task the sync made also when the issue goes to someone
32
- * else; `issues assign` picks an issue whoever holds it. A task the sync closed opens again once its issue is open
33
- * work again (and, for one the sync made, assigned to `self` again); one the owner closed stays closed, as a dismissed
34
- * task does. Nothing is written to the tracker.
31
+ * its issue is completed, canceled, a duplicate, archived or deleted, and a task the sync made also when the issue goes
32
+ * to someone else; `issues assign` picks an issue whoever holds it. A task the sync closed opens again once its issue
33
+ * is open work again (and, for one the sync made, assigned to `self` again); one the owner closed stays closed, as a
34
+ * dismissed task does. Nothing is written to the tracker.
35
35
  */
36
36
  export declare const syncTrackerTasks: (store: MessageStore, account: AccountKey, self: string, { now }?: {
37
37
  now?: number;
@@ -54,6 +54,7 @@ export const trackerIssueTask = async (store, account, issue, { dueAt, now = Dat
54
54
  const closing = {
55
55
  completed: { as: "done", reason: (provider) => `the issue was completed in ${provider}` },
56
56
  canceled: { as: "dismissed", reason: (provider) => `the issue was canceled in ${provider}` },
57
+ duplicate: { as: "dismissed", reason: (provider) => `the issue was marked a duplicate in ${provider}` },
57
58
  deleted: { as: "dismissed", reason: (provider) => `the issue was deleted in ${provider}` },
58
59
  archived: { as: "dismissed", reason: (provider) => `the issue was archived in ${provider}` },
59
60
  reassigned: { as: "dismissed", reason: (provider) => `the issue was assigned to someone else in ${provider}` },
@@ -84,10 +85,10 @@ const lastClose = async (store, id) => {
84
85
  /**
85
86
  * Brings the owner's tasks in line with the tracker's copy, after a sync: each live issue assigned to `self` whose
86
87
  * state is open work becomes a task, and every task from an issue takes the issue's current title. A task closes when
87
- * its issue is completed, canceled, archived or deleted, and a task the sync made also when the issue goes to someone
88
- * else; `issues assign` picks an issue whoever holds it. A task the sync closed opens again once its issue is open
89
- * work again (and, for one the sync made, assigned to `self` again); one the owner closed stays closed, as a dismissed
90
- * task does. Nothing is written to the tracker.
88
+ * its issue is completed, canceled, a duplicate, archived or deleted, and a task the sync made also when the issue goes
89
+ * to someone else; `issues assign` picks an issue whoever holds it. A task the sync closed opens again once its issue
90
+ * is open work again (and, for one the sync made, assigned to `self` again); one the owner closed stays closed, as a
91
+ * dismissed task does. Nothing is written to the tracker.
91
92
  */
92
93
  export const syncTrackerTasks = async (store, account, self, { now = Date.now() } = {}) => {
93
94
  const changes = { opened: 0, closed: 0, reopened: 0, renamed: 0 };
@@ -132,7 +133,7 @@ export const syncTrackerTasks = async (store, account, self, { now = Date.now()
132
133
  ? "deleted"
133
134
  : issue?.archivedAt
134
135
  ? "archived"
135
- : type === "completed" || type === "canceled"
136
+ : type === "completed" || type === "canceled" || type === "duplicate"
136
137
  ? type
137
138
  : task.origin === "rule" && !picked.has(task.id) && issue?.assignee !== self
138
139
  ? issue?.assignee
@@ -23,6 +23,8 @@ export interface TrackerManifestFake extends GraphqlFake {
23
23
  archive(kind: TrackerKind, id: string): void;
24
24
  /** Deletes one row outright. */
25
25
  remove(kind: TrackerKind, id: string): void;
26
+ /** Moves one row to the trash, as Linear does: archived now and `deleted`, its change time as it was. */
27
+ trash(kind: TrackerKind, id: string): void;
26
28
  }
27
29
  /**
28
30
  * A GraphQL tracker in memory, built from a source manifest and the generated API it names: cli-base's strict
@@ -25,6 +25,7 @@ const TARGETS = {
25
25
  label: "label",
26
26
  labels: "label",
27
27
  project: "project",
28
+ sprint: "sprint",
28
29
  lead: "user",
29
30
  assignee: "user",
30
31
  creator: "user",
@@ -148,6 +149,8 @@ export const trackerManifestFake = (input, options) => {
148
149
  // A state of a type outside STATE_TYPES is dropped by the map, and its issues with it.
149
150
  if (kind === "state" && field === "type")
150
151
  return STATE_TYPES[n % STATE_TYPES.length];
152
+ if (field === "deleted")
153
+ return false;
151
154
  switch (type) {
152
155
  case "epoch":
153
156
  return field === "createdAt" || field === "updatedAt" ? { ms: SEEDED + n * 60_000 } : null;
@@ -451,6 +454,14 @@ export const trackerManifestFake = (input, options) => {
451
454
  const row = find(kind, id);
452
455
  rows[kind]?.splice(rows[kind].indexOf(row), 1);
453
456
  },
457
+ trash(kind, id) {
458
+ const row = find(kind, id);
459
+ const path = timePath(kind, "deleted");
460
+ if (path === undefined)
461
+ throw new Error(`${kind}: map deleted to a path, so the fake can trash a row`);
462
+ stamp(kind, row, "archivedAt");
463
+ write(row, items.get(kind), path, true);
464
+ },
454
465
  };
455
466
  };
456
467
  const externalIdOf = (manifest, kind, row) => {
@@ -484,6 +495,7 @@ export const trackerManifestFixture = (manifest, options) => {
484
495
  // no other row points at.
485
496
  const changed = ["issue", ...[...parsed.kinds].reverse()].find((kind) => parsed.kinds.includes(kind) && parsed.entities[kind]?.changes);
486
497
  const archivable = changed && parsed.entities[changed]?.map.archivedAt !== undefined;
498
+ const trashable = archivable && parsed.entities[changed]?.map.deleted !== undefined;
487
499
  const first = (kind) => held[kind]?.[0];
488
500
  const last = (kind) => held[kind]?.at(-1);
489
501
  return {
@@ -514,6 +526,14 @@ export const trackerManifestFixture = (manifest, options) => {
514
526
  },
515
527
  }
516
528
  : {}),
529
+ ...(changed && trashable
530
+ ? {
531
+ trash: () => {
532
+ fake.trash(changed, last(changed));
533
+ return { kind: changed, id: last(changed) };
534
+ },
535
+ }
536
+ : {}),
517
537
  },
518
538
  };
519
539
  };
@@ -29,6 +29,14 @@ export interface TrackerSourceFaults {
29
29
  kind: TrackerKind;
30
30
  id: string;
31
31
  }>;
32
+ /** Moves one row to the tracker's trash, where it is still listed but deleted, as Linear's trash keeps an issue. */
33
+ trash?(): {
34
+ kind: TrackerKind;
35
+ id: string;
36
+ } | Promise<{
37
+ kind: TrackerKind;
38
+ id: string;
39
+ }>;
32
40
  }
33
41
  /** One adapter over recorded or faked answers, fresh for each case. Every kind its traits name lists at least one row. */
34
42
  export interface TrackerSourceFixture {
@@ -49,7 +49,7 @@ const optionalTime = (value) => value === undefined || value === null || (typeof
49
49
  const checkShape = (kind, record) => {
50
50
  const at = `${kind} ${String(record.externalId)}`;
51
51
  assert.ok(typeof record.externalId === "string" && record.externalId.trim(), `${kind}: a record has an id`);
52
- for (const field of ["createdAt", "updatedAt", "archivedAt", "completedAt", "canceledAt"])
52
+ for (const field of ["createdAt", "updatedAt", "archivedAt", "completedAt", "canceledAt", "startsAt", "endsAt"])
53
53
  assert.ok(optionalTime(record[field]), `${at}: ${field} is epoch ms or null`);
54
54
  const named = kind === "issue" ? "title" : kind === "comment" ? "body" : "name";
55
55
  assert.ok(typeof record[named] === "string", `${at} has its ${named}`);
@@ -57,8 +57,22 @@ const checkShape = (kind, record) => {
57
57
  assert.ok(STATE_TYPES.includes(String(record.type)), `${at}: type is one of ${STATE_TYPES}`);
58
58
  if (kind === "comment")
59
59
  assert.ok(typeof record.issue === "string", `${at} names its issue`);
60
- for (const field of ["team", "state", "project", "assignee", "creator", "lead", "author", "parent", "key", "email"])
60
+ for (const field of [
61
+ "team",
62
+ "state",
63
+ "project",
64
+ "sprint",
65
+ "assignee",
66
+ "creator",
67
+ "lead",
68
+ "author",
69
+ "parent",
70
+ "key",
71
+ "email",
72
+ ])
61
73
  assert.ok(optionalText(record[field]), `${at}: ${field} is an id or text, or null`);
74
+ if (record.deleted !== undefined && record.deleted !== null)
75
+ assert.equal(typeof record.deleted, "boolean", `${at}: deleted is true, false or null`);
62
76
  for (const field of ["labels", "teams"])
63
77
  if (record[field] !== undefined)
64
78
  assert.ok(Array.isArray(record[field]) && record[field].every((one) => typeof one === "string"), `${at}: ${field} is a list of ids`);
@@ -205,6 +219,18 @@ export const trackerSourceContract = (make) => [
205
219
  assert.ok(!(await allIds(source, kind)).has(id), `${kind} ${id}: a deleted row is not in ids()`);
206
220
  },
207
221
  },
222
+ {
223
+ name: "faults: a trashed row is a deleted one: a full list calls it deleted, and ids() leaves it out",
224
+ async run() {
225
+ const { source, faults } = await make();
226
+ if (!faults?.trash)
227
+ return;
228
+ const { kind, id } = await faults.trash();
229
+ const found = (await listAll(source, kind, null)).items.find((one) => one.externalId === id);
230
+ assert.ok(found?.deleted === true, `${kind} ${id}: a full list carries deleted: true`);
231
+ assert.ok(!(await allIds(source, kind)).has(id), `${kind} ${id}: a trashed row is not in ids()`);
232
+ },
233
+ },
208
234
  {
209
235
  name: "faults: a full list cut after its first page goes on from that page in a new run, nothing lost or repeated",
210
236
  async run() {
@@ -28,6 +28,11 @@ export interface FakeTrackerSource extends TrackerSource, TrackerWriter {
28
28
  archive(kind: TrackerKind, externalId: string): void;
29
29
  /** Deletes one row outright, as only an id pass finds. */
30
30
  remove(kind: TrackerKind, externalId: string): void;
31
+ /**
32
+ * Moves one row to the trash, as Linear does: still listed, archived and `deleted`, with its `updatedAt` as it was,
33
+ * so a change read misses it and only a full list or an id pass, which leaves it out, finds it.
34
+ */
35
+ trash(kind: TrackerKind, externalId: string): void;
31
36
  /** The same tracker, read from a computer whose clock is `ms` off. */
32
37
  skewed(ms: number): FakeTrackerSource;
33
38
  }
@@ -37,5 +42,8 @@ export interface FakeTrackerSource extends TrackerSource, TrackerWriter {
37
42
  * page, so it never spends from the run's budget itself.
38
43
  */
39
44
  export declare const fakeTrackerSource: (options: FakeTrackerSourceOptions) => FakeTrackerSource;
40
- /** A small Linear-like workspace: one team, two users, the six state types, a label, a project, three issues. */
45
+ /**
46
+ * A small Linear-like workspace: one team, two users, the seven state types, a label, a project, a sprint, three
47
+ * issues.
48
+ */
41
49
  export declare const exampleTrackerRows: () => Required<FakeTrackerRows>;