@wirecat/cli-core 0.714.0 → 0.716.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 (54) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/dist/background/lock.d.ts +7 -0
  3. package/dist/background/lock.js +15 -0
  4. package/dist/cli/account-remove.d.ts +14 -0
  5. package/dist/cli/account-remove.js +2 -2
  6. package/dist/cli/account-rename.d.ts +15 -0
  7. package/dist/cli/account-rename.js +240 -0
  8. package/dist/cli/bot/api.js +2 -1
  9. package/dist/cli/documents/words.d.ts +1 -1
  10. package/dist/cli/index.d.ts +1 -0
  11. package/dist/cli/index.js +1 -0
  12. package/dist/cli/messenger/account-command.js +6 -0
  13. package/dist/cli/messenger/serve-command.js +16 -1
  14. package/dist/cli/messenger/server-command.js +4 -2
  15. package/dist/cli/profile-files.js +1 -0
  16. package/dist/cli/profile-store.d.ts +31 -0
  17. package/dist/cli/profile-store.js +64 -0
  18. package/dist/cli/service-api.js +31 -3
  19. package/dist/content/cli/store.d.ts +4 -0
  20. package/dist/content/cli/store.js +3 -0
  21. package/dist/content/index.d.ts +1 -0
  22. package/dist/content/index.js +1 -0
  23. package/dist/content/manifest/manifest.d.ts +34 -10
  24. package/dist/content/manifest/manifest.js +32 -15
  25. package/dist/content/manifest/source.js +44 -6
  26. package/dist/content/manifest/writer.js +64 -34
  27. package/dist/content/source.d.ts +5 -0
  28. package/dist/content/sync.js +31 -8
  29. package/dist/content/testing/manifest-fake.d.ts +6 -1
  30. package/dist/content/testing/manifest-fake.js +51 -23
  31. package/dist/content/writes.js +2 -1
  32. package/dist/crm/cli/store.d.ts +4 -30
  33. package/dist/crm/cli/store.js +3 -63
  34. package/dist/documents/html-markdown.js +2 -1
  35. package/dist/errors/reasons.js +8 -0
  36. package/dist/search/lucene/types.d.ts +2 -0
  37. package/dist/search/lucene/types.js +8 -0
  38. package/dist/store/sqlite/account-groups.js +18 -2
  39. package/dist/store/sqlite/admin-statistics.js +3 -2
  40. package/dist/store/sqlite/lucene.js +2 -2
  41. package/dist/store/sqlite/migrations.generated.js +2 -2
  42. package/dist/tracker/cli/index.js +9 -3
  43. package/dist/tracker/index.d.ts +1 -1
  44. package/dist/tracker/index.js +1 -1
  45. package/dist/tracker/sync.d.ts +8 -0
  46. package/dist/tracker/sync.js +29 -0
  47. package/dist/tracker/tasks.d.ts +24 -4
  48. package/dist/tracker/tasks.js +164 -18
  49. package/dist/tracker/testing/manifest-fake.js +13 -1
  50. package/dist/tracker/testing/source-contract.js +14 -0
  51. package/dist/tracker/testing/source.d.ts +2 -0
  52. package/dist/tracker/testing/source.js +2 -0
  53. package/package.json +1 -1
  54. package/parity.json +11 -0
@@ -1,13 +1,15 @@
1
+ import type { TrackerIssue } from "../domain/tracker.js";
1
2
  import type { MessageStore } from "../store/store.js";
2
3
  import type { AccountKey } from "../store/types.js";
3
4
  import { type Task } from "../tasks/index.js";
4
5
  export declare const TRACKER_ISSUE_TASK = "tracker_issue";
5
- /** The task's locator: the issue in the tracker's copy, resolved when the task is read. */
6
+ /** The task's locator: the issue in the tracker's copy. */
6
7
  export declare const trackerIssueSource: (externalId: string) => string;
8
+ /** `ENG-12 Fix login`: the key people say, then the issue's title as the last sync copied it. */
9
+ export declare const trackerIssueTitle: (issue: TrackerIssue) => string;
7
10
  /**
8
- * Makes an issue the owner's task: the task points at the issue and keeps only its readable key as a title, so the
9
- * issue's text stays in the tracker's copy and a sync that changes it changes what the task shows. The same issue
10
- * twice answers the task it already has.
11
+ * Makes an issue the owner's task: the task points at the issue and carries its key and title, which each sync keeps
12
+ * current. The same issue twice, or one a sync already made a task of, answers the task it already has.
11
13
  */
12
14
  export declare const trackerIssueTask: (store: MessageStore, account: AccountKey, issue: string, { dueAt, now }?: {
13
15
  dueAt?: Date;
@@ -16,3 +18,21 @@ export declare const trackerIssueTask: (store: MessageStore, account: AccountKey
16
18
  task: Task;
17
19
  created: boolean;
18
20
  }>;
21
+ /** What a sync did to the owner's tasks from issues assigned to the signed-in user. */
22
+ export interface TrackerTaskChanges {
23
+ opened: number;
24
+ closed: number;
25
+ reopened: number;
26
+ renamed: number;
27
+ }
28
+ /**
29
+ * Brings the owner's tasks in line with the tracker's copy, after a sync: each live issue assigned to `self` whose
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.
35
+ */
36
+ export declare const syncTrackerTasks: (store: MessageStore, account: AccountKey, self: string, { now }?: {
37
+ now?: number;
38
+ }) => Promise<TrackerTaskChanges>;
@@ -1,29 +1,175 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { taskAccount } from "../services/task-rules.js";
3
- import { createTaskService } from "../tasks/index.js";
3
+ import { createTaskService, isClosedState } from "../tasks/index.js";
4
4
  export const TRACKER_ISSUE_TASK = "tracker_issue";
5
- /** The task's locator: the issue in the tracker's copy, resolved when the task is read. */
5
+ /** The task's locator: the issue in the tracker's copy. */
6
6
  export const trackerIssueSource = (externalId) => `tracker:issue/${externalId}`;
7
+ /** A task's title is at most this long; the store refuses a longer one on edit. */
8
+ const MOST_TITLE = 300;
9
+ const OPEN_TYPES = ["triage", "backlog", "unstarted", "started"];
10
+ const PAGE = 500;
11
+ const SYNC = { bot: "rule", kind: "rule" };
12
+ /** `ENG-12 Fix login`: the key people say, then the issue's title as the last sync copied it. */
13
+ export const trackerIssueTitle = (issue) => [issue.key, issue.title]
14
+ .map((part) => part?.replace(/\s+/g, " ").trim())
15
+ .filter(Boolean)
16
+ .join(" ")
17
+ .slice(0, MOST_TITLE)
18
+ .trim() || issue.externalId;
19
+ const serviceOf = (store, now) => {
20
+ const { reviewDuplicates: _review, ...tasks } = store.tasks;
21
+ return createTaskService({ store: tasks, now: () => new Date(now) });
22
+ };
23
+ const addIssueTask = (store, account, issue, origin, now, dueAt) => serviceOf(store, now).add({
24
+ source: trackerIssueSource(issue.externalId),
25
+ sourceKind: TRACKER_ISSUE_TASK,
26
+ account: taskAccount(account),
27
+ group: trackerIssueSource(issue.externalId),
28
+ kind: "request",
29
+ origin,
30
+ title: trackerIssueTitle(issue),
31
+ ...(dueAt ? { dueAt } : {}),
32
+ });
7
33
  /**
8
- * Makes an issue the owner's task: the task points at the issue and keeps only its readable key as a title, so the
9
- * issue's text stays in the tracker's copy and a sync that changes it changes what the task shows. The same issue
10
- * twice answers the task it already has.
34
+ * Makes an issue the owner's task: the task points at the issue and carries its key and title, which each sync keeps
35
+ * current. The same issue twice, or one a sync already made a task of, answers the task it already has.
11
36
  */
12
37
  export const trackerIssueTask = async (store, account, issue, { dueAt, now = Date.now() } = {}) => {
13
38
  const found = (await store.tracker.get(account, "issue", issue)) ?? (await store.tracker.issueByKey(account, issue));
14
39
  if (!found || found.deletedAt !== null)
15
40
  throw new CliError("not_found", `no issue ${issue} in the copy of ${account.provider}; run sync, then try again`);
16
- const { externalId, key } = found.record;
17
- const { reviewDuplicates: _review, ...tasks } = store.tasks;
18
- const { task, created } = await createTaskService({ store: tasks, now: () => new Date(now) }).add({
19
- source: trackerIssueSource(externalId),
20
- sourceKind: TRACKER_ISSUE_TASK,
21
- account: taskAccount(account),
22
- group: trackerIssueSource(externalId),
23
- kind: "request",
24
- origin: "owner",
25
- title: key ?? externalId,
26
- ...(dueAt ? { dueAt } : {}),
27
- });
28
- return { task, created };
41
+ const { task, created } = await addIssueTask(store, account, found.record, "owner", now, dueAt);
42
+ if (created)
43
+ return { task, created };
44
+ // A task the sync made, picked by hand, is the owner's whoever holds the issue: the sync no longer closes it when
45
+ // the issue goes to someone else, and opens it again if it had closed it.
46
+ const picked = new Set(JSON.parse((await store.sync.syncState(account, PICKED))?.value ?? "[]"));
47
+ if (task.origin === "rule" && !picked.has(task.id))
48
+ await store.sync.setSyncState(account, PICKED, JSON.stringify([...picked, task.id]));
49
+ if (!isClosedState(task.state))
50
+ return { task, created };
51
+ await store.tasks.edit(task.id, { status: "open" }, "owner");
52
+ return { task: (await store.tasks.get(task.id)) ?? task, created };
53
+ };
54
+ const closing = {
55
+ completed: { as: "done", reason: (provider) => `the issue was completed in ${provider}` },
56
+ canceled: { as: "dismissed", reason: (provider) => `the issue was canceled in ${provider}` },
57
+ deleted: { as: "dismissed", reason: (provider) => `the issue was deleted in ${provider}` },
58
+ archived: { as: "dismissed", reason: (provider) => `the issue was archived in ${provider}` },
59
+ reassigned: { as: "dismissed", reason: (provider) => `the issue was assigned to someone else in ${provider}` },
60
+ unassigned: { as: "dismissed", reason: (provider) => `the issue was unassigned in ${provider}` },
61
+ };
62
+ /**
63
+ * The owner's reopens the sync has seen end: a task id and the time of its reopen, recorded once the issue was open work
64
+ * again, after which the issue's next close closes the task again.
65
+ */
66
+ const RELEASED = "tracker:owner-reopens-released";
67
+ /** Tasks the sync made that the owner then picked with `issues assign`: theirs whoever holds the issue. */
68
+ const PICKED = "tracker:owner-picks";
69
+ /**
70
+ * What the task's events say of the sync's last close: the status it closed from, and the time of the owner's first
71
+ * status change after it, when there is one.
72
+ */
73
+ const lastClose = async (store, id) => {
74
+ const statuses = (await store.tasks.events(id)).filter((event) => event.kind === "status");
75
+ const at = statuses.findLastIndex((event) => event.actor?.type === "bot" && event.actor.name === SYNC.bot && isClosedState(String(event.changes?.status?.[1])));
76
+ if (at < 0)
77
+ return undefined;
78
+ const from = statuses[at]?.changes?.status?.[0];
79
+ return {
80
+ from: typeof from === "string" && !isClosedState(from) ? from : "open",
81
+ owner: statuses.slice(at + 1).find((event) => event.actor?.type !== "bot")?.at,
82
+ };
83
+ };
84
+ /**
85
+ * Brings the owner's tasks in line with the tracker's copy, after a sync: each live issue assigned to `self` whose
86
+ * 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.
91
+ */
92
+ export const syncTrackerTasks = async (store, account, self, { now = Date.now() } = {}) => {
93
+ const changes = { opened: 0, closed: 0, reopened: 0, renamed: 0 };
94
+ for (let offset = 0;; offset += PAGE) {
95
+ const { items, hasMore } = await store.tracker.list(account, "issue", {
96
+ assignee: self,
97
+ stateTypes: OPEN_TYPES,
98
+ limit: PAGE,
99
+ offset,
100
+ });
101
+ for (const { record } of items)
102
+ if ((await addIssueTask(store, account, record, "rule", now)).created)
103
+ changes.opened += 1;
104
+ if (!hasMore)
105
+ break;
106
+ }
107
+ const reasons = new Set(Object.values(closing).map(({ reason }) => reason(account.provider)));
108
+ const where = { sql: "t.source_kind = ?", params: [TRACKER_ISSUE_TASK] };
109
+ let tasks = [];
110
+ for (let offset = 0;; offset += PAGE) {
111
+ const page = await store.tasks.query(taskAccount(account), where, { limit: PAGE, offset });
112
+ tasks = tasks.concat(page);
113
+ if (page.length < PAGE)
114
+ break;
115
+ }
116
+ const before = JSON.parse((await store.sync.syncState(account, RELEASED))?.value ?? "{}");
117
+ const released = {};
118
+ const picked = new Set(JSON.parse((await store.sync.syncState(account, PICKED))?.value ?? "[]"));
119
+ const states = new Map();
120
+ const typeOf = async (state) => {
121
+ if (!state)
122
+ return undefined;
123
+ if (!states.has(state))
124
+ states.set(state, (await store.tracker.get(account, "state", state))?.record.type);
125
+ return states.get(state);
126
+ };
127
+ for (const { task, title } of tasks) {
128
+ const found = await store.tracker.get(account, "issue", task.source.slice("tracker:issue/".length));
129
+ const issue = found?.record;
130
+ const type = await typeOf(issue?.state);
131
+ const why = !found || found.deletedAt !== null
132
+ ? "deleted"
133
+ : issue?.archivedAt
134
+ ? "archived"
135
+ : type === "completed" || type === "canceled"
136
+ ? type
137
+ : task.origin === "rule" && !picked.has(task.id) && issue?.assignee !== self
138
+ ? issue?.assignee
139
+ ? "reassigned"
140
+ : "unassigned"
141
+ : undefined;
142
+ const closed = isClosedState(task.state);
143
+ const reopen = closed &&
144
+ why === undefined &&
145
+ type !== undefined &&
146
+ OPEN_TYPES.includes(type) &&
147
+ task.closedBy === "rule" &&
148
+ reasons.has(task.reason ?? "");
149
+ const named = issue ? trackerIssueTitle(issue) : title;
150
+ const last = reopen || !closed ? await lastClose(store, task.id) : undefined;
151
+ // The owner's reopen after a close of the sync holds against the issue going to someone else for good, and
152
+ // against any other close until the issue is open work again.
153
+ const owner = !closed ? last?.owner : undefined;
154
+ // A release stays while the same reopen applies, whatever the issue did since.
155
+ if (owner && (why === undefined || before[task.id] === owner))
156
+ released[task.id] = owner;
157
+ const ownerHolds = owner !== undefined && (why === "reassigned" || why === "unassigned" || before[task.id] !== owner);
158
+ if (!closed && why !== undefined && !ownerHolds) {
159
+ const { as, reason } = closing[why];
160
+ await serviceOf(store, now).close(task.id, { as, by: "rule", reason: reason(account.provider) });
161
+ changes.closed += 1;
162
+ }
163
+ if (reopen || named !== title)
164
+ await store.tasks.edit(task.id, {
165
+ ...(named === title ? {} : { title: named }),
166
+ ...(reopen ? { status: last?.from ?? "open" } : {}),
167
+ }, SYNC);
168
+ if (reopen)
169
+ changes.reopened += 1;
170
+ if (named !== title)
171
+ changes.renamed += 1;
172
+ }
173
+ await store.sync.setSyncState(account, RELEASED, JSON.stringify(released));
174
+ return changes;
29
175
  };
@@ -322,6 +322,15 @@ export const trackerManifestFake = (input, options) => {
322
322
  put(body, pagination.hasMore, more);
323
323
  return { data: project(body, selection) };
324
324
  };
325
+ /** The signed-in user is the first user, whom every row that points at a user names. */
326
+ const answerSelf = (call) => {
327
+ const self = manifest.self;
328
+ const selection = call.selection ?? {};
329
+ const made = sampled(responseOf(self.call), selection);
330
+ const body = crmValues.isRaw(made) ? made : {};
331
+ put(body, self.path, pointed("assignee"));
332
+ return { data: project(body, selection) };
333
+ };
325
334
  const scheme = Object.values(api.securitySchemes ?? {})[0];
326
335
  const fake = graphqlFake({
327
336
  operations: api.operations,
@@ -334,7 +343,10 @@ export const trackerManifestFake = (input, options) => {
334
343
  : { header: "Authorization", value: `Bearer ${FAKE_MANIFEST_TOKEN}` },
335
344
  }
336
345
  : {}),
337
- answers: Object.fromEntries(routes.map((route) => [route.call.operation, answer])),
346
+ answers: {
347
+ ...Object.fromEntries(routes.map((route) => [route.call.operation, answer])),
348
+ ...(manifest.self ? { [manifest.self.call.operation]: answerSelf } : {}),
349
+ },
338
350
  });
339
351
  return {
340
352
  // An answer of the fake's own that breaks the schema throws inside fetch, which the source reports as a network
@@ -133,6 +133,20 @@ export const trackerSourceContract = (make) => [
133
133
  }
134
134
  },
135
135
  },
136
+ {
137
+ name: "self: names the signed-in user as an id among the tracker's users, the id an issue's assignee holds",
138
+ async run() {
139
+ const { source, held } = await make();
140
+ if (!source.self)
141
+ return;
142
+ const self = await source.self();
143
+ assert.ok(typeof self === "string" && self.trim(), "self() answers an id");
144
+ if (!source.traits.kinds.includes("user"))
145
+ return;
146
+ const users = held?.user ?? idsOf((await listAll(source, "user", null)).items);
147
+ assert.ok(users.includes(self), `self() answers ${self}, which no user of the tracker holds`);
148
+ },
149
+ },
136
150
  {
137
151
  name: "changes: a dead cursor answers reset",
138
152
  async run() {
@@ -11,6 +11,8 @@ export interface FakeTrackerSourceOptions {
11
11
  /** Rows on one page. */
12
12
  pageSize?: number;
13
13
  provider?: string;
14
+ /** The signed-in user's id, which `self()` answers; absent, the tracker cannot say. */
15
+ self?: string;
14
16
  }
15
17
  export interface FakeTrackerSource extends TrackerSource {
16
18
  /** Changes one row on the tracker's side: it gets a new `updatedAt`. */
@@ -17,9 +17,11 @@ export const fakeTrackerSource = (options) => {
17
17
  throw new Error(`the fake tracker has no ${kind} ${externalId}`);
18
18
  return found;
19
19
  };
20
+ const self = options.self;
20
21
  const make = (skew) => ({
21
22
  provider: options.provider ?? "fake-tracker",
22
23
  traits: { kinds: Object.keys(rows).filter((kind) => listOf(kind).length > 0) },
24
+ ...(self === undefined ? {} : { self: async () => self }),
23
25
  async changes(kind, cursor, page, _context) {
24
26
  const since = cursor === null ? null : Date.parse(cursor);
25
27
  if (since !== null && Number.isNaN(since))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.714.0",
3
+ "version": "0.716.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",
package/parity.json CHANGED
@@ -1324,6 +1324,17 @@
1324
1324
  "wa": "account remove: adopt Messenger.accountRemoval (WireCat Desktop removal)"
1325
1325
  }
1326
1326
  },
1327
+ "account rename": {
1328
+ "in": [],
1329
+ "options": {
1330
+ "--dry-run": "all"
1331
+ },
1332
+ "planned": {
1333
+ "max": "account rename: set accountRemoval.signIn (WireCat Desktop account edit)",
1334
+ "tg": "account rename: set accountRemoval.signIn (WireCat Desktop account edit)",
1335
+ "wa": "account rename: set accountRemoval.signIn (WireCat Desktop account edit)"
1336
+ }
1337
+ },
1327
1338
  "account sessions": {
1328
1339
  "in": "all"
1329
1340
  },