@wirecat/cli-core 1.0.0-rc.0 → 1.1.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 (96) hide show
  1. package/CHANGELOG.md +186 -0
  2. package/THIRD_PARTY_NOTICES +47 -0
  3. package/dist/cli/account-rename.js +1 -1
  4. package/dist/cli/bot/api-input.d.ts +5 -0
  5. package/dist/cli/bot/api-input.js +6 -1
  6. package/dist/cli/bot/api.js +7 -1
  7. package/dist/cli/domain-lists-command.d.ts +16 -0
  8. package/dist/cli/domain-lists-command.js +88 -0
  9. package/dist/cli/index.d.ts +4 -3
  10. package/dist/cli/index.js +3 -2
  11. package/dist/cli/model-catalogue-command.d.ts +6 -0
  12. package/dist/cli/model-catalogue-command.js +1 -1
  13. package/dist/cli/oauth-session.d.ts +38 -4
  14. package/dist/cli/oauth-session.js +66 -22
  15. package/dist/cli/service-api.js +3 -1
  16. package/dist/cli/shared-command-exports.d.ts +2 -0
  17. package/dist/cli/shared-command-exports.js +3 -0
  18. package/dist/cli/token-session.d.ts +9 -0
  19. package/dist/cli/token-session.js +29 -2
  20. package/dist/crm/manifest/map.d.ts +5 -2
  21. package/dist/crm/manifest/map.js +14 -2
  22. package/dist/domain/domain-lists.d.ts +86 -0
  23. package/dist/domain/domain-lists.js +110 -0
  24. package/dist/domain/free-mail-domains.generated.d.ts +1 -0
  25. package/dist/domain/free-mail-domains.generated.js +4 -0
  26. package/dist/domain/organization-sectors.d.ts +16 -0
  27. package/dist/domain/organization-sectors.generated.d.ts +12 -0
  28. package/dist/domain/organization-sectors.generated.js +15 -0
  29. package/dist/domain/organization-sectors.js +22 -0
  30. package/dist/domain/person-kinds.d.ts +5 -0
  31. package/dist/domain/person-kinds.js +5 -0
  32. package/dist/entities/domain-list.d.ts +27 -0
  33. package/dist/entities/domain-list.js +28 -0
  34. package/dist/entities/index.d.ts +20 -1
  35. package/dist/entities/index.js +3 -1
  36. package/dist/entities/knowledge-lists.d.ts +1 -0
  37. package/dist/entities/knowledge-lists.js +2 -0
  38. package/dist/errors/reasons.js +14 -3
  39. package/dist/mail/mail-types.d.ts +48 -0
  40. package/dist/mail/mail-types.js +218 -0
  41. package/dist/mail/score.d.ts +2 -0
  42. package/dist/mail/score.js +9 -2
  43. package/dist/oauth/index.d.ts +1 -1
  44. package/dist/oauth/storage.d.ts +10 -2
  45. package/dist/oauth/storage.js +23 -9
  46. package/dist/services/domain-lists-download.d.ts +26 -0
  47. package/dist/services/domain-lists-download.js +155 -0
  48. package/dist/services/search-all-rank.d.ts +44 -0
  49. package/dist/services/search-all-rank.js +112 -0
  50. package/dist/services/search-all-tracker.d.ts +58 -0
  51. package/dist/services/search-all-tracker.js +155 -0
  52. package/dist/services/search-all.d.ts +1 -8
  53. package/dist/services/search-all.js +18 -199
  54. package/dist/services/tracker-meaning.js +1 -1
  55. package/dist/store/areas.d.ts +1 -0
  56. package/dist/store/index.d.ts +2 -1
  57. package/dist/store/index.js +1 -1
  58. package/dist/store/people.d.ts +30 -0
  59. package/dist/store/people.js +16 -1
  60. package/dist/store/sqlite/accounts.js +3 -1
  61. package/dist/store/sqlite/domain-organizations.d.ts +36 -0
  62. package/dist/store/sqlite/domain-organizations.js +288 -0
  63. package/dist/store/sqlite/email-types.d.ts +79 -0
  64. package/dist/store/sqlite/email-types.js +261 -0
  65. package/dist/store/sqlite/emails.d.ts +11 -2
  66. package/dist/store/sqlite/emails.js +18 -7
  67. package/dist/store/sqlite/identities.d.ts +4 -1
  68. package/dist/store/sqlite/identities.js +11 -2
  69. package/dist/store/sqlite/identity-rekey.js +2 -0
  70. package/dist/store/sqlite/knowledge.d.ts +2 -9
  71. package/dist/store/sqlite/manifest.js +6 -0
  72. package/dist/store/sqlite/merged-persons.d.ts +3 -2
  73. package/dist/store/sqlite/merged-persons.js +5 -3
  74. package/dist/store/sqlite/migrations.generated.js +77 -0
  75. package/dist/store/sqlite/organizations.d.ts +12 -1
  76. package/dist/store/sqlite/organizations.js +9 -1
  77. package/dist/store/sqlite/people-list.js +69 -11
  78. package/dist/store/sqlite/person-links.js +13 -3
  79. package/dist/store/sqlite/person-match-scan.js +14 -1
  80. package/dist/store/sqlite/schema/sender-bots.d.ts +344 -0
  81. package/dist/store/sqlite/schema/sender-bots.js +30 -0
  82. package/dist/store/sqlite/schema.d.ts +49 -0
  83. package/dist/store/sqlite/schema.js +7 -0
  84. package/dist/store/sqlite/sender-bots.d.ts +108 -0
  85. package/dist/store/sqlite/sender-bots.js +431 -0
  86. package/dist/store/sqlite/sender-signals.d.ts +13 -3
  87. package/dist/store/sqlite/sender-signals.js +17 -13
  88. package/dist/store/sqlite/tracker.d.ts +11 -9
  89. package/dist/store/sqlite/tracker.js +27 -12
  90. package/dist/store/sqlite/work-tasks.js +2 -0
  91. package/dist/tracker/cli/index.d.ts +1 -1
  92. package/dist/tracker/cli/index.js +83 -24
  93. package/dist/tracker/sync.js +43 -20
  94. package/dist/tracker/writes.d.ts +28 -0
  95. package/dist/tracker/writes.js +141 -19
  96. package/package.json +3 -3
@@ -4,8 +4,9 @@ import { clauseIn, probeOf, tokensOf, wordMatches, } from "../../search/word-mat
4
4
  import { fold, normalize } from "../normalize.js";
5
5
  import { accountPk, findAccountPk } from "./accounts.js";
6
6
  import { excerptOf } from "./crm-files.js";
7
+ import { writeState } from "./sync.js";
7
8
  import { dropTrackerChunks, isChunkedTrackerKind, nearestTrackerItems, refreshTrackerChunks, trackerChunksLeft, trackerChunksToEmbed, trackerChunkWriter, trackerEmbedded, } from "./tracker-chunks.js";
8
- import { write } from "./transaction.js";
9
+ import { read, write } from "./transaction.js";
9
10
  import { dropUnusedVectors } from "./vector-index.js";
10
11
  const MOST = 500;
11
12
  /** How many rows the index may offer one search; each is read and its words checked. */
@@ -88,7 +89,11 @@ const queryOf = (words, exact) => {
88
89
  };
89
90
  export const trackerStoreOver = (context) => {
90
91
  const { database } = context;
91
- const save = (key, kind, records, now) => write(database, () => {
92
+ const saveStates = (accountId, state = {}) => {
93
+ for (const [name, value] of Object.entries(state))
94
+ writeState(context, accountId, name, value);
95
+ };
96
+ const save = (key, kind, records, now, state) => write(database, () => {
92
97
  const accountId = accountPk(context, key);
93
98
  const stored = database.prepare("SELECT data, title, body, deleted_at FROM tracker_items WHERE account_id = ? AND kind = ? AND external_id = ?");
94
99
  const issueDeletedAt = database.prepare("SELECT deleted_at FROM tracker_items WHERE account_id = ? AND kind = 'issue' AND external_id = ?");
@@ -179,6 +184,7 @@ export const trackerStoreOver = (context) => {
179
184
  released.push(hash);
180
185
  }
181
186
  dropUnusedVectors(database, released);
187
+ saveStates(accountId, state);
182
188
  return changed;
183
189
  });
184
190
  /**
@@ -202,12 +208,13 @@ export const trackerStoreOver = (context) => {
202
208
  comments.run(accountId, String(row.external_id), Number(row.deleted_at));
203
209
  }
204
210
  };
205
- const removeUnlisted = (key, kind, listed, before, now, { dryRun = false } = {}) => {
206
- const accountId = findAccountPk(context, key);
207
- if (accountId === undefined)
211
+ const removeUnlisted = (key, kind, listed, before, now, { dryRun = false, state } = {}) => {
212
+ const found = findAccountPk(context, key);
213
+ if (found === undefined && (dryRun || !state))
208
214
  return 0;
209
215
  const keep = new Set(listed);
210
- return write(database, () => {
216
+ return (dryRun ? read : write)(database, () => {
217
+ const accountId = found ?? accountPk(context, key);
211
218
  const mark = database.prepare("UPDATE tracker_items SET deleted_at = ? WHERE id = ?");
212
219
  let removed = 0;
213
220
  const marked = [];
@@ -229,8 +236,10 @@ export const trackerStoreOver = (context) => {
229
236
  if (isChunkedTrackerKind(kind))
230
237
  dropTrackerChunks(database, marked);
231
238
  deleteComments(database, accountId, issues, now);
232
- if (!dryRun)
239
+ if (!dryRun) {
233
240
  restoreListed(accountId, kind, listed);
241
+ saveStates(accountId, state);
242
+ }
234
243
  return removed;
235
244
  });
236
245
  };
@@ -254,13 +263,19 @@ export const trackerStoreOver = (context) => {
254
263
  if (value === null)
255
264
  sql += ` AND json_extract(t.data, '$.${field}') IS NULL`;
256
265
  else {
257
- sql += ` AND json_extract(t.data, '$.${field}') = ?`;
258
- params.push(value);
266
+ const ids = typeof value === "string" ? [value] : value;
267
+ sql += ids.length ? ` AND json_extract(t.data, '$.${field}') IN (${ids.map(() => "?").join(", ")})` : " AND 0";
268
+ for (const id of ids)
269
+ params.push(id);
259
270
  }
260
271
  }
261
272
  if (filter.label !== undefined) {
262
- sql += " AND EXISTS (SELECT 1 FROM json_each(t.data, '$.labels') l WHERE l.value = ?)";
263
- params.push(filter.label);
273
+ const ids = typeof filter.label === "string" ? [filter.label] : filter.label;
274
+ sql += ids.length
275
+ ? ` AND EXISTS (SELECT 1 FROM json_each(t.data, '$.labels') l WHERE l.value IN (${ids.map(() => "?").join(", ")}))`
276
+ : " AND 0";
277
+ for (const id of ids)
278
+ params.push(id);
264
279
  }
265
280
  if (filter.stateTypes?.length) {
266
281
  sql +=
@@ -366,7 +381,7 @@ export const trackerStoreOver = (context) => {
366
381
  .slice(0, limit);
367
382
  };
368
383
  return {
369
- save: async (key, kind, records, now) => save(key, kind, records, now),
384
+ save: async (key, kind, records, now, state) => save(key, kind, records, now, state),
370
385
  removeUnlisted: async (key, kind, listed, before, now, options) => removeUnlisted(key, kind, listed, before, now, options),
371
386
  get: async (key, kind, externalId) => {
372
387
  const accountId = findAccountPk(context, key);
@@ -10,6 +10,7 @@ import { CORPORA, drainCorpus } from "./note-index.js";
10
10
  import { requiredThing } from "./notes.js";
11
11
  import { queryFilter } from "./query-filter.js";
12
12
  import { pageOfRows } from "./rows-page.js";
13
+ import { refuseBotAssignee } from "./sender-bots.js";
13
14
  import { stemmerCache } from "./stems.js";
14
15
  import { BOARD_SCOPE, boardOrder, dueGroups, mergedAssignees, projectTaskColumns, TASK_PEOPLE, withoutField, } from "./task-board.js";
15
16
  import { closeSuggestionOf, SUGGESTION_COLUMNS } from "./task-close.js";
@@ -441,6 +442,7 @@ export const workTaskOperationsOver = (context) => {
441
442
  write(database, () => {
442
443
  checkRevision(rowById(task), check.revision);
443
444
  const person = personOf(to);
445
+ refuseBotAssignee(database, person);
444
446
  const held = database
445
447
  .prepare("SELECT 1 FROM task_assignments WHERE task_id = ? AND assignee_type = 'person' " +
446
448
  "AND assignee_id IN (SELECT value FROM json_each(?)) AND role = ?")
@@ -5,7 +5,7 @@ import type { MessageStore } from "../../store/store.js";
5
5
  import type { AccountKey } from "../../store/types.js";
6
6
  import type { TrackerSource } from "../source.js";
7
7
  import type { TrackerWrite } from "../writer.js";
8
- import type { TrackerWrites } from "../writes.js";
8
+ import { type TrackerWrites } from "../writes.js";
9
9
  /** The selected profile's tracker account, opened for one command and closed before its answer is printed. */
10
10
  export interface TrackerRun {
11
11
  account: AccountKey;
@@ -8,12 +8,16 @@ import { honoursDryRun } from "../../cli/dry-run-guard.js";
8
8
  import { allowDeletionsOption, FETCH, LOCAL_READ, LOCAL_WRITE, NO_EFFECTS } from "../../cli/effects.js";
9
9
  import { itemOf, listOf, renderAnswer } from "../../cli/envelope.js";
10
10
  import { listQuery, nativeTermLists, queryTerms, termField, typedQuery, withQuery } from "../../cli/list-query.js";
11
+ import { commandAt, lineOf, nextStep, rootOf } from "../../cli/steps.js";
11
12
  import { aheadOf } from "../../domain/moment.js";
12
13
  import { STATE_TYPES, TRACKER_KINDS, TRACKER_PRIORITY_LABELS, } from "../../domain/tracker.js";
14
+ import { chosenTextModel } from "../../embeddings/models.js";
13
15
  import { count, text } from "../../entities/fields.js";
16
+ import { searchTracker } from "../../services/search-all-tracker.js";
14
17
  import { embedTracker } from "../../services/tracker-meaning.js";
15
18
  import { syncTracker } from "../sync.js";
16
19
  import { trackerIssueTask } from "../tasks.js";
20
+ import { ambiguousTrackerReference, trackerMatches, unknownTrackerReference, } from "../writes.js";
17
21
  import { addTrackerWriteCommands } from "./writes.js";
18
22
  const MOST = 500;
19
23
  // The documents' own answer has a `skipped` list of files; a part that did not run says why in a string.
@@ -34,18 +38,26 @@ const listQueryOf = (kind) => ({
34
38
  backend: "native",
35
39
  fields: [ARCHIVED],
36
40
  });
37
- /** What `issues list` narrows by: each by the tracker's id, as `issues show` and the lists name them. */
41
+ /** What `issues list` narrows by: each by its name or the tracker's id, as `issues show` and the lists name them. */
38
42
  const ISSUES_QUERY = {
39
43
  entity: "tracker_issue",
40
44
  backend: "native",
41
45
  fields: [
42
- termField("team", "kw", "team:team-1", { relation: "the team's id, as teams list shows it" }),
43
- termField("project", "kw", "project:project-1", { relation: "the project's id, as projects list shows it" }),
44
- termField("assignee", "kw", "assignee:none", { relation: "the user's id, as users list shows it, or none" }),
45
- termField("state", "kw", "state:state-1", { relation: "the state's id, as states list shows it" }),
46
+ termField("team", "kw", "team:ENG", { relation: "the team's name, key or id, as teams list shows it" }),
47
+ termField("project", "kw", 'project:"Billing revamp"', {
48
+ relation: "the project's name or id, as projects list shows it",
49
+ }),
50
+ termField("assignee", "kw", "assignee:none", {
51
+ relation: "the user's name, e-mail or id, as users list shows it, or none",
52
+ }),
53
+ termField("state", "kw", 'state:"In Progress"', {
54
+ relation: "the state's name or id, as states list shows it; with team:, that team's",
55
+ }),
46
56
  termField("type", "enum", "type:started", { values: [...STATE_TYPES], relation: "repeat for any of several" }),
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" }),
57
+ termField("label", "kw", "label:Bug", { relation: "the label's name or id, as labels list shows it" }),
58
+ termField("sprint", "kw", "sprint:12", {
59
+ relation: "the sprint's name, number or id, as sprints list shows it, or none",
60
+ }),
49
61
  ARCHIVED,
50
62
  ],
51
63
  };
@@ -153,7 +165,12 @@ const trackerNext = (report, opts) => report.state === "partial" && report.progr
153
165
  ? "a kind failed to sync; running sync again retries it"
154
166
  : "the sync stopped before its end; running it again goes on from there"),
155
167
  ]
156
- : [];
168
+ : report.embeddings?.left
169
+ ? [
170
+ resumeStep({ ...opts, embed: true }, `${report.embeddings.remaining ?? "some"} chunks of issues, projects and comments have no vectors yet, so ` +
171
+ "search all may miss them by meaning; running sync --embed again embeds the next ones"),
172
+ ]
173
+ : [];
157
174
  /** Why `--embed` failed after the sync saved its report: a model not downloaded. */
158
175
  const embeddingIssue = (error) => {
159
176
  const { code, reason } = errorOf(error);
@@ -412,24 +429,47 @@ const addTrackerCommandsDefinition = (program, options) => {
412
429
  outputFor(command).streams.diagnostic(line);
413
430
  });
414
431
  const issues = annotate(program.command("issues"), { effects: NO_EFFECTS }).description("the tracker's issues as last synced: state, team, project, assignee and labels");
415
- example(paging(withQuery(answerEntity(annotate(issues.command("list"), { effects: LOCAL_READ }), "tracker_issue", trackerView), ISSUES_QUERY).description("issues copied from the tracker, newest change first; run sync to bring them up to date")), "issues list type:started", "issues list assignee:none --json").action(async (words, opts, command) => {
432
+ example(paging(withQuery(answerEntity(annotate(issues.command("list"), { effects: LOCAL_READ }), "tracker_issue", trackerView), ISSUES_QUERY).description("issues copied from the tracker, newest change first; run sync to bring them up to date")), "issues list type:started", "issues list label:Bug assignee:none --json").action(async (words, opts, command) => {
416
433
  const lists = nativeTermLists(listQuery(typedQuery(words), ISSUES_QUERY, "issues list"), "issues list", ["type"]);
417
434
  if ([...lists.values()].flat().some((one) => one.operator !== "term" && one.operator !== "phrase"))
418
435
  throw new InvalidArgumentError("issues list takes field:value terms, each one whole value");
419
436
  const types = (lists.get("type") ?? []).map((one) => one.value.toLowerCase());
420
437
  const terms = new Map([...lists].filter(([field]) => field !== "type").map(([field, [one]]) => [field, one?.value]));
421
- const noneOr = (field) => (terms.get(field)?.toLowerCase() === "none" ? "none" : terms.get(field));
422
- const assignee = noneOr("assignee");
423
- const sprint = noneOr("sprint");
424
438
  await within(command, true, async (run) => {
439
+ const TEAMED = new Set(["state", "label", "sprint"]);
440
+ // A name every team's state or sprint has matches each of them; only the team itself must be one row.
441
+ const rowsOf = async (field, kind, team) => {
442
+ const given = terms.get(field);
443
+ if (given === undefined)
444
+ return undefined;
445
+ const scoped = team !== undefined && TEAMED.has(kind) ? " for that team" : "";
446
+ const found = await trackerMatches(run, kind, given, team);
447
+ if (found.length)
448
+ return found;
449
+ throw await unknownTrackerReference(run, kind, given, `${field}:`, {
450
+ ...(team === undefined ? {} : { team }),
451
+ scoped,
452
+ });
453
+ };
454
+ const idsOf = async (field, kind, team) => (await rowsOf(field, kind, team))?.map(({ record }) => record.externalId);
455
+ const teams = await rowsOf("team", "team");
456
+ if (teams && teams.length > 1)
457
+ throw ambiguousTrackerReference("team", terms.get("team"), teams.map(({ record }) => record), "team:");
458
+ const team = teams?.[0]?.record.externalId;
459
+ const noneOr = async (field, kind) => terms.get(field)?.toLowerCase() === "none" ? null : await idsOf(field, kind, team);
460
+ const project = await idsOf("project", "project");
461
+ const assignee = await noneOr("assignee", "user");
462
+ const state = await idsOf("state", "state", team);
463
+ const label = await idsOf("label", "label", team);
464
+ const sprint = await noneOr("sprint", "sprint");
425
465
  const filter = {
426
- ...(terms.has("team") ? { parent: terms.get("team") } : {}),
427
- ...(terms.has("project") ? { project: terms.get("project") } : {}),
428
- ...(assignee !== undefined ? { assignee: assignee === "none" ? null : assignee } : {}),
429
- ...(terms.has("state") ? { state: terms.get("state") } : {}),
466
+ ...(team !== undefined ? { parent: team } : {}),
467
+ ...(project ? { project } : {}),
468
+ ...(assignee !== undefined ? { assignee } : {}),
469
+ ...(state ? { state } : {}),
430
470
  ...(types.length ? { stateTypes: types } : {}),
431
- ...(terms.has("label") ? { label: terms.get("label") } : {}),
432
- ...(sprint !== undefined ? { sprint: sprint === "none" ? null : sprint } : {}),
471
+ ...(label ? { label } : {}),
472
+ ...(sprint !== undefined ? { sprint } : {}),
433
473
  ...(terms.has("archived") ? { archived: true } : {}),
434
474
  limit: opts.limit,
435
475
  offset: (opts.page - 1) * opts.limit,
@@ -458,22 +498,41 @@ const addTrackerCommandsDefinition = (program, options) => {
458
498
  });
459
499
  });
460
500
  example(paging(answerEntity(annotate(issues.command("search"), { effects: LOCAL_READ }), "tracker_hit", trackerView)
461
- .description("find issues, projects and comments in the copy by their words")
462
- .argument("<words...>", "every word must match, in any form; a word of four letters or more finds the words it begins")), 'issues search "invoice currency"').action(async (words, opts, command) => {
501
+ .description("find issues, projects and comments in the copy by their words, and by meaning once sync --embed built " +
502
+ "their vectors")
503
+ .argument("<words...>", 'every word must match, in any form and any order; a word of four letters or more finds the words it begins; "a phrase" in quote marks inside the query keeps its words together; a question finds what holds some of its words')), "issues search invoice currency", 'issues search "why do refunds round wrong?"').action(async (words, opts, command) => {
504
+ const { env } = environmentOf(command);
505
+ const download = commandAt(rootOf(command), "models download") !== undefined;
463
506
  await within(command, true, async (run) => {
464
- const found = await run.store.tracker.find({
465
- words,
507
+ const found = await searchTracker(run.store, {
508
+ text: words.join(" "),
466
509
  accounts: [run.account],
467
- kinds: ["issue", "project", "comment"],
468
510
  limit: opts.limit,
469
511
  offset: (opts.page - 1) * opts.limit,
512
+ now: now(),
513
+ ...(download ? { command: options.app.command } : {}),
514
+ ...(env ? { env } : {}),
470
515
  });
516
+ const noVectors = found.meaningReason === "tracker.no-vectors";
517
+ const why = found.meaningSkipped === undefined
518
+ ? undefined
519
+ : `found by words only: ${found.meaningSkipped}` +
520
+ (noVectors ? `; \`${lineOf(command, "sync --embed")}\` builds the vectors that find them by meaning` : "");
521
+ if (why)
522
+ outputFor(command).renderer.note(why);
523
+ const next = noVectors
524
+ ? [resumeStep({ embed: true }, "builds the vectors that find issues, projects and comments by meaning")]
525
+ : download && found.meaningReason === "model.not-downloaded"
526
+ ? [nextStep("models.download", { args: { model: chosenTextModel(env).id } })]
527
+ : [];
471
528
  return listOf("issues search", {
472
- items: found.items.map((hit) => viewOf(hit.item, { excerpt: hit.excerpt })),
529
+ items: found.items.map(({ hit, item }) => viewOf(item, { excerpt: hit.text, found_by: hit.foundBy })),
473
530
  limit: opts.limit,
474
531
  page: opts.page,
475
532
  has_more: found.hasMore,
476
533
  args: { words },
534
+ ...(why ? { missing: [{ field: "found_by", why }] } : {}),
535
+ ...(next.length ? { next } : {}),
477
536
  });
478
537
  });
479
538
  });
@@ -30,7 +30,10 @@ class BudgetSpent extends Error {
30
30
  this.why = why;
31
31
  }
32
32
  }
33
- /** Reads one kind's changes from where it stood, page by page, saving each page and the cursor after it. */
33
+ /**
34
+ * Reads one kind's changes from where it stood, page by page, saving each page and the cursor after it in one
35
+ * transaction: a page is saved with its cursor or not at all, and each commit waits for the disk.
36
+ */
34
37
  const syncChanges = async (run, kind, result, mode) => {
35
38
  const { source, store, account, budget } = run;
36
39
  const name = trackerCursorName(kind);
@@ -38,10 +41,11 @@ const syncChanges = async (run, kind, result, mode) => {
38
41
  let round = mode.drop
39
42
  ? { from: null, page: null }
40
43
  : (cursor.round ?? { from: mode.full ? null : cursor.token, page: null });
41
- const save = (patch) => {
44
+ const moved = (patch) => {
42
45
  cursor = { ...cursor, ...patch };
43
- return store.sync.setSyncState(account, name, JSON.stringify(cursor));
46
+ return { [name]: JSON.stringify(cursor) };
44
47
  };
48
+ const save = (patch) => store.sync.setSyncState(account, name, moved(patch)[name]);
45
49
  const pages = new Set();
46
50
  for (;;) {
47
51
  result.round = round.from === null ? "full" : "changes";
@@ -64,23 +68,34 @@ const syncChanges = async (run, kind, result, mode) => {
64
68
  pages.clear();
65
69
  continue;
66
70
  }
71
+ const broken = !page.hasMore
72
+ ? undefined
73
+ : page.nextCursor === undefined
74
+ ? `${source.provider} said there are more ${kind}s but gave no cursor`
75
+ : pages.has(page.nextCursor)
76
+ ? `${source.provider} gave the same page of ${kind}s twice`
77
+ : undefined;
78
+ // A cursor past a broken page would skip the rows the tracker failed to list.
79
+ let state;
80
+ if (!broken) {
81
+ if (page.hasMore) {
82
+ pages.add(page.nextCursor);
83
+ round = { ...round, page: page.nextCursor };
84
+ }
85
+ state = moved(page.hasMore ? { round } : { token: page.cursor ?? null, round: null });
86
+ }
67
87
  if (page.items.length) {
68
- const changed = await store.tracker.save(account, kind, page.items, run.now);
88
+ const changed = await store.tracker.save(account, kind, page.items, run.now, state);
69
89
  result.saved += changed;
70
90
  run.report.progress.saved += changed;
71
91
  }
92
+ else if (state)
93
+ await store.sync.setSyncState(account, name, state[name]);
72
94
  run.report.progress.steps += 1;
73
- if (!page.hasMore) {
74
- await save({ token: page.cursor ?? null, round: null });
95
+ if (broken)
96
+ throw new CliError("invalid_response", broken);
97
+ if (!page.hasMore)
75
98
  return null;
76
- }
77
- if (page.nextCursor === undefined)
78
- throw new CliError("invalid_response", `${source.provider} said there are more ${kind}s but gave no cursor`);
79
- if (pages.has(page.nextCursor))
80
- throw new CliError("invalid_response", `${source.provider} gave the same page of ${kind}s twice`);
81
- pages.add(page.nextCursor);
82
- round = { ...round, page: page.nextCursor };
83
- await save({ round });
84
99
  }
85
100
  };
86
101
  /**
@@ -122,6 +137,10 @@ const passIds = async (run, kind, result, mode) => {
122
137
  await store.sync.setSyncState(account, name, JSON.stringify(pass));
123
138
  continue;
124
139
  }
140
+ const cursorName = trackerCursorName(kind);
141
+ const cursor = parsed((await store.sync.syncState(account, cursorName))?.value) ?? fresh();
142
+ // Apart, a crash between them would run a pass again whose marks are saved, or drop one without its `passAt`.
143
+ const state = { [name]: "null", [cursorName]: JSON.stringify({ ...cursor, passAt: pass.started }) };
125
144
  const stored = await store.tracker.count(account, kind);
126
145
  const unlisted = await store.tracker.removeUnlisted(account, kind, pass.ids, pass.started, run.now, {
127
146
  dryRun: true,
@@ -138,14 +157,12 @@ const passIds = async (run, kind, result, mode) => {
138
157
  : `${source.provider} listed ${pass.ids.length} ${kind} ids, so ${unlisted} of the ${stored} stored would be ` +
139
158
  `marked deleted; nothing was. Check the sign-in's rights, then run sync --allow-deletions ${unlisted} to ` +
140
159
  "let them through";
160
+ await store.sync.applyDelta(account, { state });
141
161
  }
142
162
  else {
143
- result.unlisted += await store.tracker.removeUnlisted(account, kind, pass.ids, pass.started, run.now);
163
+ result.unlisted += await store.tracker.removeUnlisted(account, kind, pass.ids, pass.started, run.now, { state });
144
164
  result.pass = "complete";
145
165
  }
146
- await store.sync.setSyncState(account, name, "null");
147
- const cursor = parsed((await store.sync.syncState(account, trackerCursorName(kind)))?.value) ?? fresh();
148
- await store.sync.setSyncState(account, trackerCursorName(kind), JSON.stringify({ ...cursor, passAt: pass.started }));
149
166
  return null;
150
167
  }
151
168
  };
@@ -250,8 +267,14 @@ export const syncTracker = async (source, store, account, options = {}) => {
250
267
  result.state = "complete";
251
268
  done.add(kind);
252
269
  }
253
- await store.sync.setSyncState(account, RESUME, report.stopped ? JSON.stringify({ v: 1, done: [...done], ...(mode.full ? { rescan: true } : {}) }) : "null");
254
- await store.sync.setSyncState(account, GAPS, JSON.stringify(report.gaps));
270
+ await store.sync.applyDelta(account, {
271
+ state: {
272
+ [RESUME]: report.stopped
273
+ ? JSON.stringify({ v: 1, done: [...done], ...(mode.full ? { rescan: true } : {}) })
274
+ : "null",
275
+ [GAPS]: JSON.stringify(report.gaps),
276
+ },
277
+ });
255
278
  const passes = await Promise.all(kinds.map(async (kind) => parsed((await store.sync.syncState(account, trackerCursorName(kind)))?.value)?.passAt ?? 0));
256
279
  const checked = passes.reduce((least, one) => Math.min(least, one), passes[0] ?? 0);
257
280
  if (checked > 0)
@@ -1,3 +1,5 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { type TrackerRecords } from "../domain/tracker.js";
1
3
  import type { Asker } from "../sends/guard.js";
2
4
  import { type ProfileWrites } from "../sends/profile-writes.js";
3
5
  import type { TrackerItem } from "../store/sqlite/tracker.js";
@@ -43,6 +45,31 @@ export interface TrackerCommentWritten {
43
45
  operationId: string;
44
46
  comment: TrackerItem<"comment">;
45
47
  }
48
+ declare const PLURALS: {
49
+ readonly team: "teams";
50
+ readonly user: "users";
51
+ readonly state: "states";
52
+ readonly label: "labels";
53
+ readonly project: "projects";
54
+ readonly sprint: "sprints";
55
+ };
56
+ /** The kinds a command names by their id or name: an issue's fields and the `issues list` filters. */
57
+ export type TrackerNamed = keyof typeof PLURALS;
58
+ type Named = TrackerNamed;
59
+ type Copy = Pick<TrackerWriteContext, "store" | "account">;
60
+ /**
61
+ * The live rows of this account's copy a reference names: the one with that id, else every one with that name in any
62
+ * letter case. A state, a label or a sprint is looked for among `team`'s.
63
+ */
64
+ export declare const trackerMatches: (context: Copy, kind: Named, given: string, team?: string) => Promise<TrackerItem[]>;
65
+ /** A reference the copy holds none of: refused with the names nearest to it, never answered as an empty list. */
66
+ export declare const unknownTrackerReference: (context: Copy, kind: Named, given: string, param: string, { team, scoped, hint }?: {
67
+ team?: string;
68
+ scoped?: string;
69
+ hint?: string;
70
+ }) => Promise<CliError>;
71
+ /** Several rows of the copy share the name: refused with each, so the caller names one by its id. */
72
+ export declare const ambiguousTrackerReference: (kind: Named, given: string, found: readonly TrackerRecords[Named][], param: string, scoped?: string) => CliError;
46
73
  /** An issue of this account's copy by its key (`ENG-12`, any case) or id. */
47
74
  export declare const trackerIssueOf: (context: Pick<TrackerWriteContext, "store" | "account">, reference: string, param?: string) => Promise<TrackerItem<"issue">>;
48
75
  /** A new issue in the tracker, through the guarded path; the tracker's answer is stored as a sync stores it. */
@@ -51,3 +78,4 @@ export declare const createTrackerIssue: (context: TrackerWriteContext, input: T
51
78
  export declare const updateTrackerIssue: (context: TrackerWriteContext, reference: string, input: TrackerIssueInput) => Promise<TrackerIssueWritten>;
52
79
  /** A comment on an issue by its key or id, in the owner's words. */
53
80
  export declare const commentTrackerIssue: (context: TrackerWriteContext, reference: string, body: string) => Promise<TrackerCommentWritten>;
81
+ export {};