@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
@@ -10,6 +10,10 @@ const GUARDED_FROM = 10;
10
10
  const MOST_DUE = 50;
11
11
  /** The sign-in may not read it, which proves nothing about the row; WordPress also refuses with 400 and 403 inside. */
12
12
  const refusedRead = (error) => isCliError(error) && (error.code === "permission_error" || error.details.inner_status === 403);
13
+ const lackOf = (gap) => gap.scope ?? gap.message;
14
+ /** A refusal of this kind in this run, which proves nothing about the rows it left out; a right the role lacks does. */
15
+ const refusedIn = (run, kind) => run.report.gaps.some((gap) => gap.kind === kind && !gap.lasting);
16
+ const lackedIn = (run, kind) => run.report.gaps.flatMap((gap) => (gap.kind === kind && gap.lasting ? [lackOf(gap)] : []));
13
17
  const fresh = () => ({ v: 1, token: null, round: null, passAt: 0 });
14
18
  const parsed = (value) => {
15
19
  try {
@@ -39,7 +43,13 @@ const syncChanges = async (run, kind, result, mode) => {
39
43
  let round = mode.drop
40
44
  ? { from: null, page: null }
41
45
  : (cursor.round ?? { from: mode.full ? null : cursor.token, page: null });
42
- const gapped = () => run.report.gaps.some((gap) => gap.kind === kind);
46
+ const noted = () => {
47
+ if (refusedIn(run, kind))
48
+ round = { ...round, gapped: true };
49
+ const lacks = [...new Set([...(round.lacks ?? []), ...lackedIn(run, kind)])].sort();
50
+ if (lacks.length)
51
+ round = { ...round, lacks };
52
+ };
43
53
  const save = (patch) => {
44
54
  cursor = { ...cursor, ...patch };
45
55
  return store.sync.setSyncState(account, name, JSON.stringify(cursor));
@@ -54,8 +64,7 @@ const syncChanges = async (run, kind, result, mode) => {
54
64
  }
55
65
  run.report.progress.requests += 1;
56
66
  const page = await source.changes(kind, round.from, round.page ?? undefined, run.context);
57
- if (gapped())
58
- round = { ...round, gapped: true };
67
+ noted();
59
68
  if (run.signal?.aborted) {
60
69
  await save({ round });
61
70
  return "cancelled";
@@ -74,8 +83,20 @@ const syncChanges = async (run, kind, result, mode) => {
74
83
  }
75
84
  run.report.progress.steps += 1;
76
85
  if (!page.hasMore) {
86
+ const lacks = round.lacks ?? [];
87
+ // A right gained shows rows changed before the cursor, which a read of changes never reaches: list them all.
88
+ if (round.from !== null && (cursor.lacks ?? []).some((one) => !lacks.includes(one))) {
89
+ result.reset = true;
90
+ round = { from: null, page: null };
91
+ pages.clear();
92
+ continue;
93
+ }
77
94
  // Changes made while a read was refused would be past a new cursor: the next run reads from the old one again.
78
- await save({ token: round.gapped ? round.from : (page.cursor ?? null), round: null });
95
+ await save({
96
+ token: round.gapped ? round.from : (page.cursor ?? null),
97
+ round: null,
98
+ lacks: lacks.length ? lacks : undefined,
99
+ });
79
100
  return null;
80
101
  }
81
102
  if (page.nextCursor === undefined)
@@ -112,7 +133,7 @@ const passIds = async (run, kind, result, mode) => {
112
133
  return "cancelled";
113
134
  }
114
135
  pass = { ...pass, ids: [...pass.ids, ...page.items] };
115
- if (run.report.gaps.some((gap) => gap.kind === kind))
136
+ if (refusedIn(run, kind))
116
137
  pass = { ...pass, gapped: true };
117
138
  if (page.hasMore) {
118
139
  if (page.nextCursor === undefined || page.nextCursor === pass.page)
@@ -124,7 +145,8 @@ const passIds = async (run, kind, result, mode) => {
124
145
  const stored = await store.content.count(account, kind);
125
146
  const missing = await store.content.unlisted(account, kind, pass.ids, pass.started);
126
147
  const unlisted = missing.length;
127
- const unread = pass.gapped === true || run.report.gaps.some((gap) => gap.kind === kind);
148
+ // A role that sees only part lists less, the same each run: each row its list lacks is read once more below.
149
+ const unread = pass.gapped === true || refusedIn(run, kind);
128
150
  const moved = (run.report.moved?.length ?? 0) > 0;
129
151
  const emptied = pass.ids.length === 0 && unlisted > 0;
130
152
  const many = emptied || (stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED);
@@ -309,7 +331,8 @@ export const syncContent = async (source, store, account, options = {}) => {
309
331
  report.progress.requests += 1;
310
332
  },
311
333
  gap: (gap) => {
312
- const key = `${gap.kind} ${gap.message}`;
334
+ // A refusal with the same words as a right the role lacks still holds the cursor and the pass.
335
+ const key = `${gap.kind} ${gap.message}${gap.lasting ? " lasting" : ""}`;
313
336
  if (said.has(key))
314
337
  return;
315
338
  said.add(key);
@@ -340,7 +363,7 @@ export const syncContent = async (source, store, account, options = {}) => {
340
363
  if (resumed)
341
364
  for (const gap of await contentGapsOf(store, account))
342
365
  if (done.has(gap.kind)) {
343
- said.add(`${gap.kind} ${gap.message}`);
366
+ said.add(`${gap.kind} ${gap.message}${gap.lasting ? " lasting" : ""}`);
344
367
  report.gaps.push(gap);
345
368
  }
346
369
  for (const kind of kinds.filter((one) => !done.has(one))) {
@@ -19,8 +19,13 @@ export interface ContentManifestFakeOptions {
19
19
  * `refusals`.
20
20
  */
21
21
  lacks?: readonly string[];
22
- /** Operations refused with 403 to this sign-in, as WordPress refuses an author the users list. */
22
+ /**
23
+ * Operations refused with 403 to this sign-in, as WordPress refuses an author the users list with `context=edit`. A
24
+ * kind's `optional.fallback` form of the same call is answered.
25
+ */
23
26
  denied?: readonly string[];
27
+ /** Rows this sign-in may not see, by kind: left out of every list, and a read of one refused with 403. */
28
+ hidden?: Partial<Record<ContentKind, readonly string[]>>;
24
29
  }
25
30
  export interface ContentManifestFake {
26
31
  /** Reads as `serviceApiCall` sends them, with the answer's headers through `withHeaders`. */
@@ -164,13 +164,27 @@ export const contentManifestFake = (input, options) => {
164
164
  if (path)
165
165
  put(row, path, stamp(clock()));
166
166
  };
167
- const routes = manifest.kinds.flatMap((kind) => entities(kind).flatMap((entity, index) => [
168
- ...(entity.changes ? [{ kind, index, role: "changes", call: entity.changes }] : []),
169
- ...(entity.get ? [{ kind, index, role: "get", call: entity.get }] : []),
170
- { kind, index, role: "list", call: entity.list },
171
- ...(entity.ids ? [{ kind, index, role: "list", call: entity.ids }] : []),
172
- ...[entity.optional?.requires, entity.optional?.needs].flatMap((call) => call ? [{ kind, index, role: "rights", call }] : []),
173
- ]));
167
+ const routes = manifest.kinds.flatMap((kind) => entities(kind).flatMap((entity, index) => {
168
+ const own = [
169
+ ...(entity.changes ? [{ kind, index, role: "changes", call: entity.changes }] : []),
170
+ ...(entity.get ? [{ kind, index, role: "get", call: entity.get }] : []),
171
+ { kind, index, role: "list", call: entity.list },
172
+ ...(entity.ids ? [{ kind, index, role: "list", call: entity.ids }] : []),
173
+ ];
174
+ const fallback = entity.optional?.fallback;
175
+ return [
176
+ ...own,
177
+ ...(fallback
178
+ ? own.map((route) => ({
179
+ ...route,
180
+ call: { ...route.call, query: { ...route.call.query, ...fallback.query } },
181
+ simpler: true,
182
+ }))
183
+ : []),
184
+ ...[entity.optional?.requires, entity.optional?.needs].flatMap((call) => call ? [{ kind, index, role: "rights", call }] : []),
185
+ ];
186
+ }));
187
+ const hidden = (kind, id) => options.hidden?.[kind]?.includes(id) === true;
174
188
  const lacks = new Set(options.lacks ?? []);
175
189
  const checks = manifest.kinds.flatMap((kind) => entities(kind).flatMap((entity) => [entity.optional?.requires, entity.optional?.needs].flatMap((call) => (call ? [call] : []))));
176
190
  const carries = (route, request) => {
@@ -241,7 +255,7 @@ export const contentManifestFake = (input, options) => {
241
255
  refusals.push(operation);
242
256
  throw new CliError("configuration_error", `the content fake answers no ${operation} call like this`);
243
257
  }
244
- if (options.denied?.includes(operation))
258
+ if (options.denied?.includes(operation) && !route.simpler)
245
259
  throw new CliError("permission_error", `the content fake denies ${operation} to this sign-in`);
246
260
  const entity = entities(route.kind)[route.index];
247
261
  const held = rows[route.kind]?.[route.index] ?? [];
@@ -254,24 +268,31 @@ export const contentManifestFake = (input, options) => {
254
268
  return { body, headers: new Headers() };
255
269
  }
256
270
  const needs = entity.optional?.needs;
257
- if (needs && lacks.has(needs.check)) {
258
- refusals.push(operation);
259
- if (route.role === "get")
260
- throw new CliError("permission_error", `the content fake denies ${operation} to this sign-in`);
261
- throw new CliError("validation_error", `the content fake refuses ${operation} to this sign-in`, {
262
- status: 400,
263
- inner_status: 403,
264
- });
265
- }
271
+ const lacked = needs !== undefined && lacks.has(needs.check);
266
272
  if (route.role === "get") {
267
273
  const place = placeOf(route.call, "{id}");
268
274
  const id = place ? request[place.in][place.name] : undefined;
269
275
  const row = held.find((one) => idOf(entity, one) === String(id));
276
+ // A missing row is a 404 whoever asks; only a row that is there is refused to a role.
270
277
  if (!row)
271
278
  throw new CliError("not_found", `no ${route.kind} ${id}`);
279
+ if (lacked || hidden(route.kind, String(id))) {
280
+ if (lacked)
281
+ refusals.push(operation);
282
+ throw new CliError("permission_error", `the content fake denies ${operation} to this sign-in`);
283
+ }
272
284
  return { body: wrapped(route.call.items, structuredClone(row)), headers: new Headers() };
273
285
  }
274
- let list = [...held].sort((a, b) => Number(digits(idOf(entity, a))) - Number(digits(idOf(entity, b))));
286
+ if (lacked) {
287
+ refusals.push(operation);
288
+ throw new CliError("validation_error", `the content fake refuses ${operation} to this sign-in`, {
289
+ status: 400,
290
+ inner_status: 403,
291
+ });
292
+ }
293
+ let list = [...held]
294
+ .filter((row) => !hidden(route.kind, idOf(entity, row)))
295
+ .sort((a, b) => Number(digits(idOf(entity, a))) - Number(digits(idOf(entity, b))));
275
296
  if (route.role === "changes" && entity.changes) {
276
297
  const place = placeOf(entity.changes, "{since}");
277
298
  const raw = String(request[place.in][place.name]);
@@ -279,17 +300,24 @@ export const contentManifestFake = (input, options) => {
279
300
  if (Number.isNaN(since))
280
301
  throw new CliError("validation_error", `${raw} is not a time`);
281
302
  list = held
282
- .filter((row) => changedOf(entity, row) > since)
303
+ .filter((row) => changedOf(entity, row) > since && !hidden(route.kind, idOf(entity, row)))
283
304
  .sort((a, b) => changedOf(entity, a) - changedOf(entity, b));
284
305
  }
285
306
  return page(found, route.call, structuredClone(list), request);
286
307
  };
287
308
  const write = (operation, request) => {
288
- const ours = manifest.writes;
289
- const [entity] = entities("post");
290
- const held = rows.post?.[0];
291
- if (!ours || !entity || !held)
309
+ const writes_ = manifest.writes;
310
+ if (!writes_)
292
311
  throw new CliError("configuration_error", "the source manifest writes no posts");
312
+ const touches = (calls) => calls !== undefined &&
313
+ [calls.create, calls.update, calls.trash, calls.delete].some((call) => call?.operation === operation);
314
+ const type = touches(writes_.page) && !touches(writes_) ? "page" : "post";
315
+ const ours = type === "page" && writes_.page ? writes_.page : writes_;
316
+ const index = entityIndex("post", { type });
317
+ const entity = entities("post")[index];
318
+ const held = rows.post?.[index];
319
+ if (!entity || !held)
320
+ throw new CliError("configuration_error", `the source manifest reads no ${type}s`);
293
321
  const matches = (call) => call?.operation === operation &&
294
322
  fixedOf(call.query ?? {}).every(([key, value]) => String(request.query[key]) === value);
295
323
  const body = request.body ? JSON.parse(request.body) : {};
@@ -100,7 +100,8 @@ export const publishPost = async (context, externalId) => {
100
100
  export const schedulePost = async (context, externalId, at) => {
101
101
  const now = context.now?.() ?? Date.now();
102
102
  if (!Number.isFinite(at) || at <= now)
103
- throw new CliError("validation_error", "--at is in the past, and the source would publish the post at once; give a later time, or use posts publish", { reason: "content.schedule-past", param: "--at" });
103
+ throw new CliError("validation_error", "--at-time is in the past, and the source would publish the post at once; give a later time, or leave " +
104
+ "--at-time out to publish now", { reason: "content.schedule-past", param: "--at-time" });
104
105
  const copy = await copyOf(context, externalId);
105
106
  if (copy.record.status === "published")
106
107
  throw new CliError("validation_error", `post ${externalId} is already published`, {
@@ -1,30 +1,4 @@
1
- import { type AppIdentity } from "../../ports/app.js";
2
- import type { MessageStore } from "../../store/store.js";
3
- import type { AccountKey } from "../../store/types.js";
4
- export interface CrmStoreOptions {
5
- app: AppIdentity;
6
- env: NodeJS.ProcessEnv;
7
- profile: string;
8
- /** The command only reads the store: `CrmCommandOptions.open`'s `readOnly`. */
9
- readOnly: boolean;
10
- /** The CRM's provider, as the store names it: the empty store's account under the read-only lock. */
11
- provider: string;
12
- /** Opens the shared store as the CLI does; a writable open also registers its provider. */
13
- open: (env: NodeJS.ProcessEnv, options?: {
14
- readOnly?: boolean;
15
- }) => Promise<MessageStore>;
16
- /** The profile's account from its sign-in; asked only when no earlier run saved it. */
17
- account: () => AccountKey;
18
- }
19
- /**
20
- * The store a CRM command reads, and the profile's account in it. A read takes the account an earlier run saved, so it
21
- * never reads the sign-in; the first read of a profile, a store that is missing or needs a migration, and every sync
22
- * and write open it for writing and save the account (scope work: a CRM is the owner's work) and the profile.
23
- *
24
- * Under `<PREFIX>_READ_ONLY` a read with no store or no saved profile reads an empty store in a temporary folder, so
25
- * the lock creates no `wirecat.db`; the folder goes when the store closes. A sync still writes, as a fetch may.
26
- */
27
- export declare const openCrmStore: (options: CrmStoreOptions) => Promise<{
28
- store: MessageStore;
29
- account: AccountKey;
30
- }>;
1
+ import { openProfileStore, type ProfileStoreOptions } from "../../cli/profile-store.js";
2
+ export type CrmStoreOptions = ProfileStoreOptions;
3
+ /** The store a CRM command reads, and the profile's account in it (`openProfileStore`): a CRM is the owner's work. */
4
+ export declare const openCrmStore: typeof openProfileStore;
@@ -1,63 +1,3 @@
1
- import { mkdtempSync, rmSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
- import { isCliError } from "@wirecat/cli-base";
5
- import { readOnlyLockOf } from "../../ports/app.js";
6
- /**
7
- * The store a CRM command reads, and the profile's account in it. A read takes the account an earlier run saved, so it
8
- * never reads the sign-in; the first read of a profile, a store that is missing or needs a migration, and every sync
9
- * and write open it for writing and save the account (scope work: a CRM is the owner's work) and the profile.
10
- *
11
- * Under `<PREFIX>_READ_ONLY` a read with no store or no saved profile reads an empty store in a temporary folder, so
12
- * the lock creates no `wirecat.db`; the folder goes when the store closes. A sync still writes, as a fetch may.
13
- */
14
- export const openCrmStore = async (options) => {
15
- const { app, env, profile, readOnly, open } = options;
16
- const locked = readOnly && readOnlyLockOf(app, env) !== undefined;
17
- if (readOnly) {
18
- const store = await open(env, { readOnly: true }).catch((error) => {
19
- if (locked && !(isCliError(error) && error.code === "not_found"))
20
- throw error;
21
- return undefined;
22
- });
23
- if (store) {
24
- const saved = await store.accounts
25
- .profiles()
26
- .then((all) => all[app.command]?.[profile])
27
- .catch(() => undefined);
28
- if (saved)
29
- return { store, account: { provider: saved.provider, account: saved.account } };
30
- await store.close();
31
- }
32
- }
33
- if (!locked)
34
- return withProfile(options, env, options.account());
35
- const folder = mkdtempSync(join(tmpdir(), `${app.command}-empty-`));
36
- const removing = () => rmSync(folder, { recursive: true, force: true });
37
- try {
38
- const empty = await withProfile(options, { ...env, MESSAGING_STORE: join(folder, "wirecat.db") }, {
39
- provider: options.provider,
40
- account: profile,
41
- });
42
- const close = empty.store.close.bind(empty.store);
43
- empty.store.close = () => close().finally(removing);
44
- return empty;
45
- }
46
- catch (error) {
47
- removing();
48
- throw error;
49
- }
50
- };
51
- const withProfile = async ({ app, profile, open }, env, account) => {
52
- const store = await open(env);
53
- try {
54
- // An account already stored keeps the scope the owner gave it.
55
- await store.accounts.saveAccount(account, { name: null, scope: "work" });
56
- await store.accounts.saveProfile(app.command, profile, account);
57
- return { store, account };
58
- }
59
- catch (error) {
60
- await store.close();
61
- throw error;
62
- }
63
- };
1
+ import { openProfileStore } from "../../cli/profile-store.js";
2
+ /** The store a CRM command reads, and the profile's account in it (`openProfileStore`): a CRM is the owner's work. */
3
+ export const openCrmStore = openProfileStore;
@@ -68,7 +68,8 @@ const makeSafe = (tree) => {
68
68
  export const htmlToMarkdown = async (html) => {
69
69
  const { fromHtml, toMdast, toMarkdown, gfmToMarkdown } = await loaded();
70
70
  const tree = makeSafe(toMdast(fromHtml(html, { fragment: true })));
71
- return toMarkdown(tree, { extensions: [gfmToMarkdown()] });
71
+ // `-` as most Markdown is written: a body read back then compares equal to the file it was written from.
72
+ return toMarkdown(tree, { bullet: "-", extensions: [gfmToMarkdown()] });
72
73
  };
73
74
  /**
74
75
  * Markdown (CommonMark + GFM) as HTML for a service that stores HTML, such as WordPress or Ghost. Raw HTML in the
@@ -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",
@@ -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 {