@wirecat/cli-core 0.713.0 → 0.715.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 (39) hide show
  1. package/CHANGELOG.md +71 -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-token.js +6 -3
  17. package/dist/cli/service-api.js +31 -3
  18. package/dist/errors/reasons.js +8 -0
  19. package/dist/search/lucene/types.d.ts +2 -0
  20. package/dist/search/lucene/types.js +8 -0
  21. package/dist/services/files/mirror.d.ts +2 -2
  22. package/dist/services/files/mirror.js +2 -2
  23. package/dist/store/sqlite/account-groups.js +18 -2
  24. package/dist/store/sqlite/admin-statistics.js +3 -2
  25. package/dist/store/sqlite/lucene.js +2 -2
  26. package/dist/store/sqlite/migrations.generated.js +2 -2
  27. package/dist/tracker/cli/index.js +9 -3
  28. package/dist/tracker/index.d.ts +1 -1
  29. package/dist/tracker/index.js +1 -1
  30. package/dist/tracker/sync.d.ts +8 -0
  31. package/dist/tracker/sync.js +29 -0
  32. package/dist/tracker/tasks.d.ts +24 -4
  33. package/dist/tracker/tasks.js +164 -18
  34. package/dist/tracker/testing/manifest-fake.js +13 -1
  35. package/dist/tracker/testing/source-contract.js +14 -0
  36. package/dist/tracker/testing/source.d.ts +2 -0
  37. package/dist/tracker/testing/source.js +2 -0
  38. package/package.json +1 -1
  39. package/parity.json +11 -0
@@ -263,11 +263,36 @@ const serviceApiCore = (options) => {
263
263
  renderer.warn(`permissions name ${former}, the old key of api ${pathOf(operation)}: rename it to ${keyOf(operation)}`);
264
264
  return operation.effect === "read" && level !== "deny" && level !== "ask" ? [] : [former];
265
265
  };
266
- return { operations, left, baseUrlOf, defaults, exchange, formerKeys, operationOf, readsFreely, signed, write };
266
+ /**
267
+ * The refusal `execute` would give, before the body is read: a `deny` stops a call whatever its input, and a missing
268
+ * body must not answer `validation_error` in its place. Only the keys known without the body; the rest, and an old
269
+ * flat key (which warns), wait for `execute`.
270
+ */
271
+ const refuseBeforeBody = (command, operation) => {
272
+ const extra = permissionsOf(operation)
273
+ .filter((permission) => whenOf(permission) === undefined)
274
+ .map(({ key }) => key);
275
+ if (operation.effect === "read" && extra.length === 0)
276
+ return;
277
+ guardOf(command, extra).refuse({ chatId: null, kind: "edit", key: keyOf(operation), operationId: newOperationId() });
278
+ };
279
+ return {
280
+ operations,
281
+ left,
282
+ baseUrlOf,
283
+ defaults,
284
+ exchange,
285
+ formerKeys,
286
+ operationOf,
287
+ readsFreely,
288
+ refuseBeforeBody,
289
+ signed,
290
+ write,
291
+ };
267
292
  };
268
293
  export const serviceApiCommand = (options) => {
269
294
  const { app, configuration } = options;
270
- const { operations, baseUrlOf, exchange, formerKeys, operationOf, readsFreely, signed, write } = serviceApiCore(options);
295
+ const { operations, baseUrlOf, exchange, formerKeys, operationOf, readsFreely, refuseBeforeBody, signed, write } = serviceApiCore(options);
271
296
  const send = async (command, operation, request) => (await exchange(command, operation, request)).answer;
272
297
  let schemas;
273
298
  const loaded = () => {
@@ -331,6 +356,7 @@ export const serviceApiCommand = (options) => {
331
356
  const generated = generatedApiCommand({
332
357
  operations,
333
358
  checkParameter: (name, schema, raw) => checkApiParameter(name, schema, raw, loaded()),
359
+ before: refuseBeforeBody,
334
360
  checkBody: (operation, text) => checkApiBody(operation, text, loaded()),
335
361
  readBody: (command, body) => {
336
362
  if (body.bodyFile !== undefined)
@@ -389,7 +415,9 @@ export const serviceApiCommand = (options) => {
389
415
  const schema = operation.request?.schema ? definitions[operation.request.schema] : undefined;
390
416
  renderAnswer(this, outputFor(this), itemOf({ operation, ...options.shown, ...(schema ? { request_schema: schema } : {}) }));
391
417
  });
392
- const group = annotate(new Command("api"), { effects: NO_EFFECTS }).description(`the raw ${options.service} API, one command per operation of its OpenAPI document`);
418
+ const graphql = operations.length > 0 && operations.every((one) => one.binding.kind === "graphql");
419
+ const described = graphql ? "GraphQL schema" : "OpenAPI document";
420
+ const group = annotate(new Command("api"), { effects: NO_EFFECTS }).description(`the raw ${options.service} API, one command per operation of its ${described}`);
393
421
  group.addCommand(list).addCommand(show);
394
422
  for (const child of [...generated.commands])
395
423
  group.addCommand(child);
@@ -57,6 +57,14 @@ const SIGN_IN = [
57
57
  "configuration_error",
58
58
  "the tool named a folder of its own outside the home folder",
59
59
  ],
60
+ ["account-rename.unknown-profile", "not_found", "no profile by this name on this computer"],
61
+ ["account-rename.taken", "conflict", "the new name, or a file or keyring entry under it, already exists"],
62
+ ["account-rename.busy", "conflict", "a serve, a background service, a schedule or a sync uses this profile"],
63
+ ["account-rename.bot", "conflict", "the profile is also a bot profile, which keeps its name"],
64
+ ["account-rename.unconfirmed", "confirmation_required", "renaming a profile asks first; add --yes"],
65
+ ["account-rename.moved-run", "permission_error", "a run with moved folders never renames a profile"],
66
+ ["account-rename.unpaired", "configuration_error", "the tool named different paths for the old and new name"],
67
+ ["account-rename.config", "configuration_error", "the config file cannot be read"],
60
68
  ];
61
69
  /** Reasons every CLI over a provider's API raises alike: gcal and drive today. */
62
70
  const PROVIDER_API = [
@@ -37,6 +37,8 @@ export declare const searchTimeLimit: (deadline: {
37
37
  export declare function outOfTime(limitMs?: number): never;
38
38
  /** A search limit that leaves the answer without a part, such as its total, rather than failing it. */
39
39
  export declare const isQueryLimit: (error: unknown) => boolean;
40
+ /** The error to throw on: a statement SQLite refused for its size is the search's own query.too-large. */
41
+ export declare const sqliteLimit: (error: unknown) => unknown;
40
42
  export declare function exhausted(budget: string): never;
41
43
  /** A pattern checked word by word over more messages than a search may read: what to write instead. */
42
44
  export declare function tooWideTerm([term]: string[], budget: string): never;
@@ -39,6 +39,14 @@ export function outOfTime(limitMs = QUERY_LIMITS.milliseconds) {
39
39
  }
40
40
  /** A search limit that leaves the answer without a part, such as its total, rather than failing it. */
41
41
  export const isQueryLimit = (error) => isCliError(error) && (error.details.reason === "query.too-large" || error.details.reason === "query.time-limit");
42
+ // SQLite's own size limits on one statement; SQLite 3.54 (Node 24.22) reaches its nesting limit at about 53 words.
43
+ const SQLITE_TOO_LARGE = /nested too deep|too many terms in compound SELECT|Expression tree is too large|parser stack overflow/;
44
+ /** The error to throw on: a statement SQLite refused for its size is the search's own query.too-large. */
45
+ export const sqliteLimit = (error) => {
46
+ if (error instanceof Error && SQLITE_TOO_LARGE.test(error.message))
47
+ exhausted("nodes");
48
+ return error;
49
+ };
42
50
  export function exhausted(budget) {
43
51
  throw new CliError("validation_error", `search exceeded its ${budget} budget — narrow the chat or date range`, {
44
52
  reason: "query.too-large",
@@ -69,9 +69,9 @@ export interface MirrorHints {
69
69
  sync: string;
70
70
  /** How a sync allows deletions: `--allow-deletions <count>`. */
71
71
  allowDeletions: string;
72
- /** How a sync allows replacements: `--allow-replacements <count>`. */
72
+ /** How a sync allows replacements: `--replace`, the vocabulary's overwrite switch. */
73
73
  allowReplacements: string;
74
- /** How to exclude a folder: `ydisk work mirrors exclude <id> <glob>`. */
74
+ /** How to leave a folder out: `ydisk work mirrors update <id> --ignore <path>`. */
75
75
  exclude: string;
76
76
  }
77
77
  export interface FileStep {
@@ -11,8 +11,8 @@ const HINTS = {
11
11
  repin: "--repin",
12
12
  sync: "sync",
13
13
  allowDeletions: "--allow-deletions <count>",
14
- allowReplacements: "--allow-replacements <count>",
15
- exclude: "--exclude <glob>",
14
+ allowReplacements: "--replace",
15
+ exclude: "--ignore <path>",
16
16
  };
17
17
  /**
18
18
  * A run that would delete more than `MAX_DELETIONS` files, or replace more than `MAX_REPLACEMENTS` existing files on
@@ -1,4 +1,16 @@
1
1
  import { ACCOUNT_GROUPS } from "../../search/account-list.js";
2
+ // Store version 31 run on SQLite 3.54 (Node 24.22) wrote each app's profiles and each group as a JSON string inside
3
+ // the setting; read back, the next save writes them whole again.
4
+ const unquoted = (value) => {
5
+ if (typeof value !== "string")
6
+ return value;
7
+ try {
8
+ return JSON.parse(value);
9
+ }
10
+ catch {
11
+ return value;
12
+ }
13
+ };
2
14
  /** None saved, or a value this build cannot read, is no groups: a search naming one then says it does not exist. */
3
15
  export const accountGroupsOf = (database) => {
4
16
  const row = database.prepare("SELECT value FROM store_settings WHERE key = ?").get(ACCOUNT_GROUPS);
@@ -8,7 +20,9 @@ export const accountGroupsOf = (database) => {
8
20
  const value = JSON.parse(String(row.value));
9
21
  if (typeof value !== "object" || value === null || Array.isArray(value))
10
22
  return {};
11
- return Object.fromEntries(Object.entries(value).filter((entry) => Array.isArray(entry[1]) && entry[1].every((member) => typeof member === "string")));
23
+ return Object.fromEntries(Object.entries(value)
24
+ .map(([name, members]) => [name, unquoted(members)])
25
+ .filter((entry) => Array.isArray(entry[1]) && entry[1].every((member) => typeof member === "string")));
12
26
  }
13
27
  catch {
14
28
  return {};
@@ -21,7 +35,9 @@ export const profilesOf = (database) => {
21
35
  return {};
22
36
  try {
23
37
  const value = JSON.parse(String(row.value));
24
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
38
+ if (typeof value !== "object" || value === null || Array.isArray(value))
39
+ return {};
40
+ return Object.fromEntries(Object.entries(value).map(([app, own]) => [app, unquoted(own)]));
25
41
  }
26
42
  catch {
27
43
  return {};
@@ -12,8 +12,9 @@ function fail(message, reason = "query.too-large") {
12
12
  throw new CliError("validation_error", message, { reason, complete: false });
13
13
  }
14
14
  const joined = "FROM messages m JOIN chats c ON c.id=m.chat_id JOIN accounts ac ON ac.id=m.account_id LEFT JOIN identities i ON i.id=m.sender_identity_id";
15
- const attachmentSnapshot = `(SELECT json_group_array(json_object('position',position,'kind',kind,'mime',mime,'name',name,'title',title,'url',url,'size',size,'width',width,'height',height,'duration',duration,'localPath',local_path)) FROM attachments WHERE attachable_type='message' AND attachable_id=m.id)`;
16
- const snapshot = `json_object('edited',m.edited_at,'senderName',m.sender_name,'reply',m.reply_to,'forward',m.forward,'reactions',m.reactions,'outgoing',m.outgoing,'thread',m.thread_external_id,'attachments',${attachmentSnapshot},'counterObservations',(SELECT json_group_array(json_object('counter',counter,'value',value,'at',created_at,'source',source)) FROM message_counter_observations WHERE message_id=m.id))`;
15
+ // json() keeps a subquery's array an array: SQLite 3.54 (Node 24.22) no longer passes its JSON subtype up.
16
+ const attachmentSnapshot = `json((SELECT json_group_array(json_object('position',position,'kind',kind,'mime',mime,'name',name,'title',title,'url',url,'size',size,'width',width,'height',height,'duration',duration,'localPath',local_path)) FROM attachments WHERE attachable_type='message' AND attachable_id=m.id))`;
17
+ const snapshot = `json_object('edited',m.edited_at,'senderName',m.sender_name,'reply',m.reply_to,'forward',m.forward,'reactions',m.reactions,'outgoing',m.outgoing,'thread',m.thread_external_id,'attachments',${attachmentSnapshot},'counterObservations',json((SELECT json_group_array(json_object('counter',counter,'value',value,'at',created_at,'source',source)) FROM message_counter_observations WHERE message_id=m.id)))`;
17
18
  export const adminStatisticsQuery = (context, execution, request) => withQuerySelection(context, execution, (selection, check) => {
18
19
  const { database } = context, { options } = request;
19
20
  const prefix = `WITH selected AS (${selection.sql}) `;
@@ -2,7 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { compileAutomaton } from "../../search/lucene/automaton.js";
3
3
  import { isPresence, PRESENCE } from "../../search/lucene/registry.js";
4
4
  import { isStemmed } from "../../search/lucene/resolved.js";
5
- import { exhausted, outOfTime, QUERY_LIMITS, searchError, tooWideTerm } from "../../search/lucene/types.js";
5
+ import { exhausted, outOfTime, QUERY_LIMITS, searchError, sqliteLimit, tooWideTerm } from "../../search/lucene/types.js";
6
6
  import { TIME_LIMIT_FUNCTION, TimeLimitReached } from "../driver.js";
7
7
  import { emailHitsByPk } from "./emails.js";
8
8
  import { placeHits } from "./hit-places.js";
@@ -61,7 +61,7 @@ export const matchingPks = (context, execution, cap) => inTime(() => {
61
61
  const timeLimited = (limitMs) => (error) => {
62
62
  if (error instanceof TimeLimitReached)
63
63
  outOfTime(limitMs);
64
- throw error;
64
+ throw sqliteLimit(error);
65
65
  };
66
66
  const inTime = (work, limitMs) => {
67
67
  try {
@@ -661,8 +661,8 @@ export const GENERATED = [
661
661
  "UPDATE mention_pending SET source_id = (SELECT account_id FROM temp.drive_moves WHERE folder_id = mention_pending.source_id)\nWHERE source_type = 'account' AND source_id IN (SELECT folder_id FROM temp.drive_moves);",
662
662
  "UPDATE mentions SET source_id = (SELECT account_id FROM temp.drive_moves WHERE folder_id = mentions.source_id)\nWHERE source_type = 'account' AND source_id IN (SELECT folder_id FROM temp.drive_moves);",
663
663
  "UPDATE mentions SET target_id = (SELECT account_id FROM temp.drive_moves WHERE folder_id = mentions.target_id)\nWHERE target_type = 'account' AND target_id IN (SELECT folder_id FROM temp.drive_moves);",
664
- "-- A profile that named the folder names the account: `{ provider: \"google-drive\", account: <principal> }`.\nUPDATE store_settings SET value = (\n SELECT json_group_object(app.key, CASE WHEN app.type = 'object' THEN (\n SELECT json_group_object(profile.key, CASE\n WHEN profile.type = 'object' AND json_extract(profile.value, '$.provider') = 'folder'\n AND json_extract(profile.value, '$.account') IN (SELECT 'google-drive:' || principal FROM temp.drive_moves)\n THEN json_set(profile.value, '$.provider', 'google-drive', '$.account', substr(json_extract(profile.value, '$.account'), 14))\n WHEN profile.type IN ('object', 'array') THEN json(profile.value)\n ELSE profile.value END)\n FROM json_each(app.value) profile\n ) WHEN app.type = 'array' THEN json(app.value) ELSE app.value END)\n FROM json_each(store_settings.value) app\n)\nWHERE key = 'profiles' AND json_valid(value) AND json_type(value) = 'object'\n AND EXISTS (SELECT 1 FROM temp.drive_moves);",
665
- "-- A group member `notes:<folder id>` follows the documents to `notes:<account id>`.\nUPDATE store_settings SET value = (\n SELECT json_group_object(grp.key, CASE WHEN grp.type = 'array' THEN (\n SELECT json_group_array(coalesce(\n (SELECT 'notes:' || m.account_id FROM temp.drive_moves m WHERE 'notes:' || m.folder_id = member.value),\n member.value))\n FROM json_each(grp.value) member\n ) WHEN grp.type = 'object' THEN json(grp.value) ELSE grp.value END)\n FROM json_each(store_settings.value) grp\n)\nWHERE key = 'accountGroups' AND json_valid(value) AND json_type(value) = 'object'\n AND EXISTS (SELECT 1 FROM temp.drive_moves);",
664
+ "-- A profile that named the folder names the account: `{ provider: \"google-drive\", account: <principal> }`.\n-- json() keeps the inner object an object: SQLite 3.54 (Node 24.22) no longer passes a subquery's JSON subtype up.\nUPDATE store_settings SET value = (\n SELECT json_group_object(app.key, CASE WHEN app.type = 'object' THEN json((\n SELECT json_group_object(profile.key, CASE\n WHEN profile.type = 'object' AND json_extract(profile.value, '$.provider') = 'folder'\n AND json_extract(profile.value, '$.account') IN (SELECT 'google-drive:' || principal FROM temp.drive_moves)\n THEN json_set(profile.value, '$.provider', 'google-drive', '$.account', substr(json_extract(profile.value, '$.account'), 14))\n WHEN profile.type IN ('object', 'array') THEN json(profile.value)\n ELSE profile.value END)\n FROM json_each(app.value) profile\n )) WHEN app.type = 'array' THEN json(app.value) ELSE app.value END)\n FROM json_each(store_settings.value) app\n)\nWHERE key = 'profiles' AND json_valid(value) AND json_type(value) = 'object'\n AND EXISTS (SELECT 1 FROM temp.drive_moves);",
665
+ "-- A group member `notes:<folder id>` follows the documents to `notes:<account id>`.\nUPDATE store_settings SET value = (\n SELECT json_group_object(grp.key, CASE WHEN grp.type = 'array' THEN json((\n SELECT json_group_array(coalesce(\n (SELECT 'notes:' || m.account_id FROM temp.drive_moves m WHERE 'notes:' || m.folder_id = member.value),\n member.value))\n FROM json_each(grp.value) member\n )) WHEN grp.type = 'object' THEN json(grp.value) ELSE grp.value END)\n FROM json_each(store_settings.value) grp\n)\nWHERE key = 'accountGroups' AND json_valid(value) AND json_type(value) = 'object'\n AND EXISTS (SELECT 1 FROM temp.drive_moves);",
666
666
  "DELETE FROM accounts WHERE id IN (SELECT folder_id FROM temp.drive_moves);",
667
667
  "DROP TABLE temp.drive_moves;"
668
668
  ]
@@ -84,6 +84,10 @@ const trackerSync = v.strictObject({
84
84
  })),
85
85
  gaps: v.array(v.strictObject({ kind: v.picklist(TRACKER_KINDS), message: text, scope: v.optional(text) })),
86
86
  progress: v.strictObject({ requests: count, saved: count, steps: count }),
87
+ tasks: v.optional(v.union([
88
+ v.strictObject({ opened: count, closed: count, reopened: count, renamed: count }),
89
+ v.strictObject({ skipped: text }),
90
+ ])),
87
91
  });
88
92
  const trackerTask = v.strictObject({ task_id: text, key: v.optional(text), issue: text, created: v.boolean() });
89
93
  /** Each issue with its state's name and type, and its assignee's name and person, read from the same copy. */
@@ -132,7 +136,9 @@ const addTrackerCommandsDefinition = (program, options) => {
132
136
  .option("--page <n>", "which page, starting at 1", integer(1_000_000), 1);
133
137
  example(answerEntity(annotate(program.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), "tracker_sync", trackerSync).description("bring the tracker's copy in the local store up to date: teams, users, states, labels, projects, issues and " +
134
138
  "comments that changed since the last sync, or everything with --rescan; once a day it also finds what the " +
135
- "tracker deleted. A run stops before its deadline or --max-pages and the next one goes on from there"), "sync", "sync --rescan")
139
+ "tracker deleted. Open issues assigned to you become your tasks, and close when the issue is done, " +
140
+ "canceled, deleted or goes to someone else. A run stops before its deadline or --max-pages and the next " +
141
+ "one goes on from there"), "sync", "sync --rescan")
136
142
  .option("--rescan", "list everything again, every id too, dropping a round in progress")
137
143
  .option("--max-pages <pages>", "at most this many requests to the tracker in this run", integer(100_000))
138
144
  .action(async (opts, command) => {
@@ -245,8 +251,8 @@ const addTrackerCommandsDefinition = (program, options) => {
245
251
  });
246
252
  });
247
253
  example(answerEntity(annotate(issues.command("assign"), { effects: LOCAL_WRITE }), "tracker_issue_task", trackerTask)
248
- .description("make an issue the owner's task: the task points at the issue and copies none of its text; the same issue " +
249
- "again answers its existing task")
254
+ .description("make an issue the owner's task, whoever it is assigned to: the task points at the issue and shows its key and " +
255
+ "title, which each sync keeps current; the same issue again answers its existing task")
250
256
  .argument("<issue>", "the issue's key (ENG-12) or id")
251
257
  .option("--due <time>", "when it is due: an ISO 8601 time, a day, today, or 3d from now", (typed) => new Date(aheadOf(typed, "--due", Date.now(), { end: true }))), "issues assign ENG-12 --due 2026-12-01").action(async (reference, opts, command) => {
252
258
  await within(command, false, async (run) => {
@@ -5,4 +5,4 @@ export { TRACKER_FIELDS } from "./manifest/map.js";
5
5
  export { type TrackerManifestSourceOptions, trackerSourceFromManifest, } from "./manifest/source.js";
6
6
  export type { TrackerCallContext, TrackerChanges, TrackerGap, TrackerIdPage, TrackerPage, TrackerSource, TrackerSourceTraits, } from "./source.js";
7
7
  export { syncTracker, type TrackerSyncOptions, type TrackerSyncReport, type TrackerSyncResult, trackerCursorName, trackerGapsOf, } from "./sync.js";
8
- export { TRACKER_ISSUE_TASK, trackerIssueSource, trackerIssueTask } from "./tasks.js";
8
+ export { syncTrackerTasks, TRACKER_ISSUE_TASK, type TrackerTaskChanges, trackerIssueSource, trackerIssueTask, trackerIssueTitle, } from "./tasks.js";
@@ -4,4 +4,4 @@ export { parseTrackerManifest, } from "./manifest/manifest.js";
4
4
  export { TRACKER_FIELDS } from "./manifest/map.js";
5
5
  export { trackerSourceFromManifest, } from "./manifest/source.js";
6
6
  export { syncTracker, trackerCursorName, trackerGapsOf, } from "./sync.js";
7
- export { TRACKER_ISSUE_TASK, trackerIssueSource, trackerIssueTask } from "./tasks.js";
7
+ export { syncTrackerTasks, TRACKER_ISSUE_TASK, trackerIssueSource, trackerIssueTask, trackerIssueTitle, } from "./tasks.js";
@@ -3,6 +3,7 @@ import { type TrackerKind } from "../domain/tracker.js";
3
3
  import type { MessageStore } from "../store/store.js";
4
4
  import type { AccountKey } from "../store/types.js";
5
5
  import type { TrackerGap, TrackerSource } from "./source.js";
6
+ import { type TrackerTaskChanges } from "./tasks.js";
6
7
  export declare const trackerCursorName: (kind: TrackerKind) => string;
7
8
  export interface TrackerSyncOptions {
8
9
  now?: number;
@@ -49,6 +50,13 @@ export interface TrackerSyncReport {
49
50
  saved: number;
50
51
  steps: number;
51
52
  };
53
+ /**
54
+ * The owner's tasks from issues assigned to the signed-in user, brought in line with the copy. Absent when the
55
+ * tracker cannot name its user or the run was cancelled; `skipped` says why they were left as they were.
56
+ */
57
+ tasks?: TrackerTaskChanges | {
58
+ skipped: string;
59
+ };
52
60
  }
53
61
  /**
54
62
  * Brings one tracker account's copy up to date: each kind's changes since its cursor, then, once a day, a pass over
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { runBudget } from "../background/budget.js";
3
3
  import { TRACKER_KINDS } from "../domain/tracker.js";
4
+ import { syncTrackerTasks } from "./tasks.js";
4
5
  const DAY = 86_400_000;
5
6
  /** An id pass that would mark more than this share of a kind deleted is held: a tracker that lost rights lists none. */
6
7
  const MOST_UNLISTED = 0.5;
@@ -19,6 +20,8 @@ export const trackerCursorName = (kind) => `tracker:${kind}`;
19
20
  const passName = (kind) => `tracker:${kind}:pass`;
20
21
  const GAPS = "tracker:gaps";
21
22
  const RESUME = "tracker:resume";
23
+ /** The signed-in user's id: an account is one sign-in, so it never changes once read. */
24
+ const SELF = "tracker:self";
22
25
  /** Thrown by `TrackerCallContext.spend` when the budget is spent; the engine turns it into a `partial` stop. */
23
26
  class BudgetSpent extends Error {
24
27
  why;
@@ -240,8 +243,34 @@ export const syncTracker = async (source, store, account, options = {}) => {
240
243
  }
241
244
  await store.sync.setSyncState(account, RESUME, report.stopped ? JSON.stringify({ v: 1, done: [...done], ...(mode.full ? { rescan: true } : {}) }) : "null");
242
245
  await store.sync.setSyncState(account, GAPS, JSON.stringify(report.gaps));
246
+ if (source.self && source.traits.kinds.includes("issue") && report.stopped !== "cancelled")
247
+ report.tasks = await ownTasks(run, source.self.bind(source));
243
248
  return report;
244
249
  };
250
+ const ownTasks = async (run, self) => {
251
+ const { store, account, budget, report } = run;
252
+ let id = (await store.sync.syncState(account, SELF))?.value;
253
+ if (!id) {
254
+ const spent = `the run's budget was spent before ${run.source.provider} named the signed-in user`;
255
+ if (budget.take())
256
+ return { skipped: spent };
257
+ report.progress.requests += 1;
258
+ try {
259
+ id = await self(run.context);
260
+ }
261
+ catch (error) {
262
+ return { skipped: error instanceof BudgetSpent ? spent : error instanceof Error ? error.message : String(error) };
263
+ }
264
+ await store.sync.setSyncState(account, SELF, id);
265
+ }
266
+ try {
267
+ return await syncTrackerTasks(store, account, id, { now: run.now });
268
+ }
269
+ catch (error) {
270
+ // The copy is saved by now: a task that cannot be written must not fail the sync that saved it.
271
+ return { skipped: error instanceof Error ? error.message : String(error) };
272
+ }
273
+ };
245
274
  /** The gaps the account's last sync recorded; none before its first. */
246
275
  export const trackerGapsOf = async (store, account) => {
247
276
  try {
@@ -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() {