@wirecat/cli-core 0.600.0 → 0.602.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 (80) hide show
  1. package/CHANGELOG.md +83 -1
  2. package/dist/calendar/cli/search-all.js +9 -2
  3. package/dist/cli/app-doctor-command.js +18 -10
  4. package/dist/cli/bot/api-input.js +8 -2
  5. package/dist/cli/context.d.ts +2 -0
  6. package/dist/cli/contract-templates.js +2 -1
  7. package/dist/cli/effects.d.ts +5 -0
  8. package/dist/cli/effects.js +5 -0
  9. package/dist/cli/index.d.ts +2 -1
  10. package/dist/cli/index.js +2 -1
  11. package/dist/cli/messenger/search-answers.d.ts +5 -1
  12. package/dist/cli/messenger/search-answers.js +4 -1
  13. package/dist/cli/messenger/store-maintenance-command.d.ts +2 -0
  14. package/dist/cli/messenger/store-maintenance-command.js +1 -0
  15. package/dist/cli/new-file.d.ts +2 -0
  16. package/dist/cli/new-file.js +13 -0
  17. package/dist/cli/program.js +3 -0
  18. package/dist/cli/search-left-out.d.ts +27 -0
  19. package/dist/cli/search-left-out.js +31 -0
  20. package/dist/cli/store-recover.d.ts +2 -0
  21. package/dist/cli/store-recover.js +2 -0
  22. package/dist/crm/cli/index.js +2 -7
  23. package/dist/crm/cli/search-all.js +17 -2
  24. package/dist/crm/index.d.ts +1 -1
  25. package/dist/crm/index.js +1 -1
  26. package/dist/crm/writes.d.ts +17 -0
  27. package/dist/crm/writes.js +31 -16
  28. package/dist/errors/reasons.js +16 -0
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.js +1 -1
  31. package/dist/meetings/cli/index.d.ts +14 -0
  32. package/dist/meetings/cli/index.js +18 -6
  33. package/dist/meetings/hit-query.d.ts +2 -0
  34. package/dist/meetings/hit-query.js +2 -0
  35. package/dist/meetings/index.d.ts +2 -2
  36. package/dist/meetings/index.js +1 -1
  37. package/dist/meetings/mcp/index.d.ts +15 -15
  38. package/dist/meetings/pull.d.ts +13 -1
  39. package/dist/meetings/pull.js +34 -8
  40. package/dist/meetings/source.d.ts +5 -0
  41. package/dist/resolve.d.ts +2 -2
  42. package/dist/resolve.js +4 -3
  43. package/dist/search/lucene/plain.d.ts +9 -0
  44. package/dist/search/lucene/plain.js +124 -0
  45. package/dist/services/events-search.js +2 -0
  46. package/dist/services/index.d.ts +1 -0
  47. package/dist/services/index.js +1 -0
  48. package/dist/services/meeting-hit-search.js +3 -2
  49. package/dist/services/messages-archive-search.js +3 -0
  50. package/dist/services/notes-search.js +3 -0
  51. package/dist/services/search-all.d.ts +4 -1
  52. package/dist/services/search-all.js +6 -3
  53. package/dist/speech/local.d.ts +2 -1
  54. package/dist/speech/local.js +12 -1
  55. package/dist/speech/recognize.d.ts +2 -0
  56. package/dist/speech/recognize.js +15 -0
  57. package/dist/store/damage.js +6 -1
  58. package/dist/store/decision-requests.d.ts +10 -0
  59. package/dist/store/decision-requests.js +16 -0
  60. package/dist/store/health.d.ts +15 -0
  61. package/dist/store/health.js +31 -1
  62. package/dist/store/index.d.ts +3 -1
  63. package/dist/store/index.js +1 -0
  64. package/dist/store/recover.d.ts +14 -2
  65. package/dist/store/recover.js +179 -95
  66. package/dist/store/sqlite/deals.d.ts +3 -1
  67. package/dist/store/sqlite/deals.js +2 -2
  68. package/dist/store/sqlite/decision-requests.d.ts +59 -0
  69. package/dist/store/sqlite/decision-requests.js +111 -0
  70. package/dist/store/sqlite/manifest.js +2 -0
  71. package/dist/store/sqlite/meeting-hit-search.js +3 -2
  72. package/dist/store/sqlite/migrations.generated.js +12 -0
  73. package/dist/store/sqlite/schema/decision-requests.d.ts +233 -0
  74. package/dist/store/sqlite/schema/decision-requests.js +20 -0
  75. package/dist/store/sqlite/schema.d.ts +1 -0
  76. package/dist/store/sqlite/schema.js +1 -0
  77. package/dist/store/store.d.ts +3 -0
  78. package/dist/store/store.js +5 -0
  79. package/docs/search/recipes.json +0 -1
  80. package/package.json +2 -2
@@ -4,7 +4,7 @@ import { basename, dirname, join } from "node:path";
4
4
  import { Transform } from "node:stream";
5
5
  import { CliError } from "@wirecat/cli-base";
6
6
  import { holdersOf } from "../background/processes.js";
7
- import { fts5Tables, storeHealth } from "./health.js";
7
+ import { fts5Tables, invalidJson, storeHealth } from "./health.js";
8
8
  import { migrate } from "./migrations.js";
9
9
  import { resetAttachmentWords } from "./sqlite/attachment-texts.js";
10
10
  import { involvementStoreOver } from "./sqlite/involvements.js";
@@ -19,6 +19,7 @@ import { fillVectorIndexes } from "./sqlite/vector-index.js";
19
19
  /** `contentless_delete`, which every word index uses, came in SQLite 3.43. */
20
20
  export const SQLITE3_MINIMUM = [3, 43, 0];
21
21
  const STORE_PARTS = ["", "-wal", "-shm"];
22
+ const RECOVER_LOCK = ".recover-lock";
22
23
  /** The start of a row `.recover` writes; a value's own lines cannot start a line with it, its quotes are doubled. */
23
24
  const INSERTED = /^INSERT OR IGNORE INTO '([^']+)'/;
24
25
  const LOST_AND_FOUND = "recover_lost_and_found";
@@ -65,13 +66,66 @@ export const activeTimers = () => {
65
66
  return undefined;
66
67
  }
67
68
  };
68
- /** Processes that have any of the store's files open, by PID and program name, never their arguments. */
69
+ const alive = (pid) => {
70
+ try {
71
+ process.kill(pid, 0);
72
+ return true;
73
+ }
74
+ catch (error) {
75
+ return error.code === "EPERM";
76
+ }
77
+ };
78
+ /** The process recovering the store now, from the lock file it keeps beside it; a lock whose process ended is none. */
79
+ export const runningRecovery = (path) => {
80
+ let pid;
81
+ try {
82
+ pid = Number(readFileSync(`${path}${RECOVER_LOCK}`, "utf8").trim());
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ return Number.isInteger(pid) && pid > 0 && alive(pid) ? pid : null;
88
+ };
89
+ /** Between its copy and its swap a recovery holds none of the store's files, so only its lock shows it. */
90
+ const takeRecoverLock = (path) => {
91
+ const lock = `${path}${RECOVER_LOCK}`;
92
+ const take = () => writeFileSync(lock, String(process.pid), { flag: "wx", mode: 0o600 });
93
+ try {
94
+ take();
95
+ }
96
+ catch (error) {
97
+ if (error.code !== "EEXIST")
98
+ throw error;
99
+ const pid = runningRecovery(path);
100
+ if (pid === null) {
101
+ rmSync(lock, { force: true });
102
+ take();
103
+ }
104
+ else {
105
+ throw new CliError("validation_error", `the store is being recovered by process ${pid} — wait for it to finish`, {
106
+ reason: "store.recovering",
107
+ });
108
+ }
109
+ }
110
+ return () => rmSync(lock, { force: true });
111
+ };
112
+ /**
113
+ * Processes that have any of the store's files open, by PID and program name, never their arguments, and the one
114
+ * recovering it.
115
+ */
69
116
  export const storeHolders = (path) => {
70
117
  const folder = realpathSync(dirname(path));
71
118
  const files = STORE_PARTS.map((suffix) => join(folder, `${basename(path)}${suffix}`));
72
119
  // A process that kept writing after its log was deleted holds it as "<path> (deleted)" (BUG-557).
73
120
  const wanted = process.platform === "linux" ? files.flatMap((file) => [file, `${file} (deleted)`]) : files.filter(existsSync);
74
- return holdersOf(wanted)?.map((pid) => {
121
+ const recovering = runningRecovery(path);
122
+ const pids = holdersOf(wanted);
123
+ if (pids === undefined && recovering === null)
124
+ return undefined;
125
+ const all = [
126
+ ...new Set([...(pids ?? []), ...(recovering !== null && recovering !== process.pid ? [recovering] : [])]),
127
+ ];
128
+ return all.map((pid) => {
75
129
  let name = "?";
76
130
  try {
77
131
  name = readFileSync(`/proc/${pid}/comm`, "utf8").trim();
@@ -278,13 +332,20 @@ const mailToFetch = (database) => {
278
332
  return [];
279
333
  }
280
334
  };
281
- /** The file and its log; the shared-memory file changes on every read, so it says nothing. */
282
- const fingerprint = (path) => ["", "-wal"]
283
- .map((suffix) => {
284
- const stat = statSync(`${path}${suffix}`, { throwIfNoEntry: false });
285
- return stat ? `${stat.size}:${stat.mtimeMs}` : "-";
286
- })
287
- .join("|");
335
+ /**
336
+ * Sets each value the tools read as JSON that SQLite's JSON functions refuse to NULL, or drops its row where the
337
+ * column may not be NULL: `.recover` copies a damaged value that still reads, and a JSON read of it fails.
338
+ */
339
+ export const clearInvalidJson = (database) => {
340
+ const found = invalidJson(database);
341
+ for (const { table, column, required } of found) {
342
+ const invalid = `"${column}" IS NOT NULL AND NOT json_valid("${column}")`;
343
+ database.exec(required
344
+ ? `DELETE FROM "${table}" WHERE ${invalid}`
345
+ : `UPDATE "${table}" SET "${column}" = NULL WHERE ${invalid}`);
346
+ }
347
+ return found;
348
+ };
288
349
  const refuseInUse = (path) => {
289
350
  const holders = storeHolders(path);
290
351
  if (holders && holders.length > 0) {
@@ -307,98 +368,121 @@ export const recoverStore = async ({ path, command, version, sqlite3 = "sqlite3"
307
368
  ? `sqlite3 ${program.version} cannot recover: the recovery needs ${SQLITE3_MINIMUM.join(".")} or newer, built with .recover`
308
369
  : "the recovery needs the sqlite3 program with its .recover command: install it (apt install sqlite3, brew install sqlite)", { reason: "store.sqlite3-missing" });
309
370
  }
310
- refuseInUse(path);
311
- const bytes = STORE_PARTS.reduce((sum, suffix) => sum + (statSync(`${path}${suffix}`, { throwIfNoEntry: false })?.size ?? 0), 0);
312
- const { bavail, bsize } = statfsSync(dirname(path));
313
- if (Number(bavail) * Number(bsize) < bytes * 1.2)
314
- throw new CliError("validation_error", `the recovery needs about ${Math.ceil((bytes * 1.2) / 1e9)} GB free beside the store`);
315
- const old = await openSqlite(path, { readOnly: true });
316
- let rowsBefore;
371
+ const releaseLock = takeRecoverLock(path);
317
372
  try {
318
- rowsBefore = tableRows(old.database);
373
+ refuseInUse(path);
374
+ const bytes = STORE_PARTS.reduce((sum, suffix) => sum + (statSync(`${path}${suffix}`, { throwIfNoEntry: false })?.size ?? 0), 0);
375
+ const { bavail, bsize } = statfsSync(dirname(path));
376
+ if (Number(bavail) * Number(bsize) < bytes * 1.2)
377
+ throw new CliError("validation_error", `the recovery needs about ${Math.ceil((bytes * 1.2) / 1e9)} GB free beside the store`);
378
+ return await recoverLocked({ path, command, version, sqlite3, now, note, copy, started, program });
319
379
  }
320
380
  finally {
321
- old.database.close();
381
+ releaseLock();
322
382
  }
323
- const before = fingerprint(path);
324
- const stamp = new Date(now()).toISOString().replace(/[:.]/g, "-");
325
- const target = `${path}.recovering-${stamp}`;
326
- writeFileSync(target, "", { flag: "wx", mode: 0o600 });
327
- const dropTarget = () => {
328
- for (const suffix of [...STORE_PARTS, "-journal"])
329
- rmSync(`${target}${suffix}`, { force: true });
383
+ };
384
+ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy, started, program, }) => {
385
+ // Kept open to the swap: data_version moves only when another connection commits, never for a reader's
386
+ // checkpoint or a log reset, which change the files' times and sizes but not one row.
387
+ const watch = (await openSqlite(path, { readOnly: true })).database;
388
+ let watching = true;
389
+ const stopWatching = () => {
390
+ if (watching)
391
+ watch.close();
392
+ watching = false;
330
393
  };
331
- note(`copying the readable rows into ${target}`);
332
- let copied;
333
- let copyErrors;
334
- let read;
335
- let opened;
336
394
  try {
337
- ;
338
- ({ errors: copyErrors, read } = await (copy ?? ((from, to) => copyReadableRows(from, to, sqlite3)))(path, target));
339
- copied = Date.now();
340
- opened = await openSqlite(target);
341
- }
342
- catch (error) {
343
- dropTarget();
344
- throw error;
345
- }
346
- let rebuilt;
347
- let kept;
348
- let dangling;
349
- let fetch;
350
- try {
351
- kept = tableRows(opened.database);
352
- migrate(opened.database, { command, ...(version ? { version } : {}) });
353
- rebuilt = rebuildDerived(opened.database, { now, note });
354
- note("looking for rows that point at rows that were lost");
355
- dangling = danglingRows(opened.database);
356
- fetch = mailToFetch(opened.database);
357
- opened.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
358
- }
359
- catch (error) {
395
+ const dataVersion = () => Number(watch.prepare("PRAGMA data_version").get()?.data_version);
396
+ const rowsBefore = tableRows(watch);
397
+ const before = { data: dataVersion(), inode: statSync(path).ino };
398
+ const stamp = new Date(now()).toISOString().replace(/[:.]/g, "-");
399
+ const target = `${path}.recovering-${stamp}`;
400
+ writeFileSync(target, "", { flag: "wx", mode: 0o600 });
401
+ const dropTarget = () => {
402
+ for (const suffix of [...STORE_PARTS, "-journal"])
403
+ rmSync(`${target}${suffix}`, { force: true });
404
+ };
405
+ note(`copying the readable rows into ${target}`);
406
+ let copied;
407
+ let copyErrors;
408
+ let read;
409
+ let opened;
410
+ try {
411
+ ;
412
+ ({ errors: copyErrors, read } = await (copy ?? ((from, to) => copyReadableRows(from, to, sqlite3)))(path, target));
413
+ copied = Date.now();
414
+ opened = await openSqlite(target);
415
+ }
416
+ catch (error) {
417
+ dropTarget();
418
+ throw error;
419
+ }
420
+ let rebuilt;
421
+ let kept;
422
+ let dangling;
423
+ let json;
424
+ let fetch;
425
+ try {
426
+ kept = tableRows(opened.database);
427
+ migrate(opened.database, { command, ...(version ? { version } : {}) });
428
+ note("clearing values that are not valid JSON");
429
+ json = clearInvalidJson(opened.database);
430
+ rebuilt = rebuildDerived(opened.database, { now, note });
431
+ note("looking for rows that point at rows that were lost");
432
+ dangling = danglingRows(opened.database);
433
+ fetch = mailToFetch(opened.database);
434
+ opened.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
435
+ }
436
+ catch (error) {
437
+ opened.database.close();
438
+ dropTarget();
439
+ throw error;
440
+ }
360
441
  opened.database.close();
361
- dropTarget();
362
- throw error;
363
- }
364
- opened.database.close();
365
- const rebuiltAt = Date.now();
366
- note("checking the recovered file");
367
- const health = await storeHealth(target, { deep: true });
368
- const checkedAt = Date.now();
369
- if (!health.ok) {
370
- throw new CliError("validation_error", `the recovered file did not pass its check, so the store was left as it was; the file is kept at ${target}`, { reason: "store.recovery-failed" });
442
+ const rebuiltAt = Date.now();
443
+ note("checking the recovered file");
444
+ const health = await storeHealth(target, { deep: true });
445
+ const checkedAt = Date.now();
446
+ if (!health.ok) {
447
+ throw new CliError("validation_error", `the recovered file did not pass its check, so the store was left as it was; the file is kept at ${target}`, { reason: "store.recovery-failed" });
448
+ }
449
+ refuseInUse(path);
450
+ const changed = dataVersion() !== before.data || statSync(path, { throwIfNoEntry: false })?.ino !== before.inode;
451
+ stopWatching();
452
+ if (changed) {
453
+ throw new CliError("validation_error", `the store was written to during the recovery, so it was left as it was — stop every timer and run it again; ${target} can be deleted`, { reason: "store.changed-during-recovery" });
454
+ }
455
+ const keptAt = `${path}.before-recover-${stamp}`;
456
+ for (const suffix of STORE_PARTS)
457
+ if (existsSync(`${path}${suffix}`))
458
+ renameSync(`${path}${suffix}`, `${keptAt}${suffix}`);
459
+ for (const suffix of STORE_PARTS)
460
+ if (existsSync(`${target}${suffix}`))
461
+ renameSync(`${target}${suffix}`, `${path}${suffix}`);
462
+ const lost = Object.entries(rowsBefore)
463
+ .map(([table, before]) => ({ table, before, read: read[table] ?? 0, kept: kept[table] ?? 0 }))
464
+ .filter(({ before, read, kept }) => before === null || before > kept || read > kept);
465
+ const seconds = (from, to) => Math.round((to - from) / 100) / 10;
466
+ return {
467
+ path,
468
+ keptAt,
469
+ sqlite3: program.version,
470
+ lost,
471
+ dangling,
472
+ invalidJson: json,
473
+ mailToFetch: fetch,
474
+ rebuilt,
475
+ copyErrors,
476
+ health,
477
+ seconds: {
478
+ copy: seconds(started, copied),
479
+ rebuild: seconds(copied, rebuiltAt),
480
+ check: seconds(rebuiltAt, checkedAt),
481
+ total: seconds(started, Date.now()),
482
+ },
483
+ };
371
484
  }
372
- refuseInUse(path);
373
- if (fingerprint(path) !== before) {
374
- throw new CliError("validation_error", `the store was written to during the recovery, so it was left as it was — stop every timer and run it again; ${target} can be deleted`, { reason: "store.changed-during-recovery" });
485
+ finally {
486
+ stopWatching();
375
487
  }
376
- const keptAt = `${path}.before-recover-${stamp}`;
377
- for (const suffix of STORE_PARTS)
378
- if (existsSync(`${path}${suffix}`))
379
- renameSync(`${path}${suffix}`, `${keptAt}${suffix}`);
380
- for (const suffix of STORE_PARTS)
381
- if (existsSync(`${target}${suffix}`))
382
- renameSync(`${target}${suffix}`, `${path}${suffix}`);
383
- const lost = Object.entries(rowsBefore)
384
- .map(([table, before]) => ({ table, before, read: read[table] ?? 0, kept: kept[table] ?? 0 }))
385
- .filter(({ before, read, kept }) => before === null || before > kept || read > kept);
386
- const seconds = (from, to) => Math.round((to - from) / 100) / 10;
387
- return {
388
- path,
389
- keptAt,
390
- sqlite3: program.version,
391
- lost,
392
- dangling,
393
- mailToFetch: fetch,
394
- rebuilt,
395
- copyErrors,
396
- health,
397
- seconds: {
398
- copy: seconds(started, copied),
399
- rebuild: seconds(copied, rebuiltAt),
400
- check: seconds(rebuiltAt, checkedAt),
401
- total: seconds(started, Date.now()),
402
- },
403
- };
404
488
  };
@@ -153,6 +153,8 @@ export interface DealSearch {
153
153
  anyWord?: boolean;
154
154
  /** Only the copies of these CRM accounts; absent, every account's and the owner's own. */
155
155
  accounts?: AccountKey[];
156
+ /** Only these kinds; absent, deals and leads. */
157
+ kinds?: readonly DealKind[];
156
158
  /** 1–500, 100 by default. */
157
159
  limit?: number;
158
160
  }
@@ -217,7 +219,7 @@ export declare const dealOperationsOver: (context: StoreContext) => {
217
219
  add: (input: DealInput) => Deal;
218
220
  get: (reference: string) => Deal;
219
221
  list: (filter?: DealFilter) => Deal[];
220
- find: ({ words, anyWord, accounts, limit }: DealSearch) => Deal[];
222
+ find: ({ words, anyWord, accounts, kinds, limit }: DealSearch) => Deal[];
221
223
  move: (reference: string, { stage, by }: {
222
224
  stage: string;
223
225
  by: Author;
@@ -367,14 +367,14 @@ export const dealOperationsOver = (context) => {
367
367
  .all(status, status, project, project, stage, stage, pipeline, pipeline, organization?.id ?? null, organization?.id ?? null, own, provider, provider, account, ...by.params, limit, Math.max(0, Math.trunc(filter.offset ?? 0)))
368
368
  .map(itemOf(kind));
369
369
  },
370
- find: ({ words, anyWord, accounts, limit }) => {
370
+ find: ({ words, anyWord, accounts, kinds = DEAL_KINDS, limit }) => {
371
371
  const wanted = [...new Set(words.map((word) => fold(word).trim()).filter(Boolean))];
372
372
  if (!wanted.length)
373
373
  return [];
374
374
  const most = Math.min(Math.max(limit ?? 100, 1), 500);
375
375
  const within = accounts?.map(({ provider, account }) => `${provider}\u0000${account}`);
376
376
  // Titles are short and a CRM holds thousands, not millions: folding them here is cheaper than a word index.
377
- const found = DEAL_KINDS.flatMap((kind) => database
377
+ const found = kinds.flatMap((kind) => database
378
378
  .prepare(`SELECT d.id, d.title, d.updated_at, a.provider, a.external_id AS account FROM ${TABLES[kind]} d ` +
379
379
  "LEFT JOIN accounts a ON a.id = d.account_id WHERE d.deleted_at IS NULL")
380
380
  .all()
@@ -0,0 +1,59 @@
1
+ import { type DecisionAction } from "../decision-requests.js";
2
+ import type { StoreContext } from "./open.js";
3
+ /** The message a set of buttons is on. */
4
+ export interface DecisionMessage {
5
+ channel: string;
6
+ botProfile: string;
7
+ chatId: string;
8
+ messageId: string;
9
+ }
10
+ export interface DecisionRequestInput extends DecisionMessage {
11
+ proposalId: string;
12
+ batchDigest: string;
13
+ ownerUserId: string;
14
+ /** One button each, in this order; no action twice. */
15
+ actions: readonly DecisionAction[];
16
+ }
17
+ export interface DecisionRequest extends DecisionMessage {
18
+ proposalId: string;
19
+ action: DecisionAction;
20
+ batchDigest: string;
21
+ ownerUserId: string;
22
+ createdAt: number;
23
+ expiresAt: number;
24
+ }
25
+ /** Where and by whom the press came; every part must equal what the button was sent with. */
26
+ export interface DecisionPress {
27
+ botProfile: string;
28
+ chatId: string;
29
+ messageId: string;
30
+ ownerUserId: string;
31
+ }
32
+ export type DecisionRefusal = "decision.token-unknown" | "decision.token-used" | "decision.token-cancelled" | "decision.token-expired" | "decision.token-mismatch";
33
+ export type TakeResult = {
34
+ ok: true;
35
+ request: DecisionRequest;
36
+ cancelled: number;
37
+ } | {
38
+ ok: false;
39
+ reason: DecisionRefusal;
40
+ };
41
+ export interface DecisionRequestStore {
42
+ /** One token per action, for one message; the tokens are returned once and kept only as digests. */
43
+ create(input: DecisionRequestInput): {
44
+ action: DecisionAction;
45
+ token: string;
46
+ }[];
47
+ /**
48
+ * Uses a token once and cancels the message's other open tokens in the same transaction. A token for another
49
+ * bot, chat, message or owner is refused as a mismatch before its state is looked at, and stays open.
50
+ */
51
+ take(token: string, expect: DecisionPress): TakeResult;
52
+ /** Cancels every open token, of one bot when given; for turning the feature off. Returns how many. */
53
+ cancelOpen(scope?: Partial<Pick<DecisionMessage, "channel" | "botProfile">>): number;
54
+ /** Deletes rows that expired, were used or were cancelled more than 30 days before `at`; returns how many. */
55
+ prune(at?: number): number;
56
+ /** The open (unused, uncancelled, unexpired) buttons of a message, oldest first. */
57
+ open(message: DecisionMessage): DecisionRequest[];
58
+ }
59
+ export declare const decisionRequestStoreOver: ({ database, now }: StoreContext) => DecisionRequestStore;
@@ -0,0 +1,111 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { DECISION_ACTIONS, DECISION_TTL_MS, isDecisionToken } from "../decision-requests.js";
4
+ import { write } from "./transaction.js";
5
+ const digestOf = (token) => createHash("sha256").update(token).digest("hex");
6
+ const newToken = () => randomBytes(16).toString("base64url");
7
+ const requestOf = (row) => ({
8
+ proposalId: row.proposal_id,
9
+ action: row.action,
10
+ batchDigest: row.batch_digest,
11
+ channel: row.channel,
12
+ botProfile: row.bot_profile,
13
+ chatId: row.chat_id,
14
+ messageId: row.message_id,
15
+ ownerUserId: row.owner_user_id,
16
+ createdAt: row.created_at,
17
+ expiresAt: row.expires_at,
18
+ });
19
+ const PRUNE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;
20
+ const SAME_MESSAGE = "channel=? AND bot_profile=? AND chat_id=? AND message_id=?";
21
+ const OPEN = "used_at IS NULL AND cancelled_at IS NULL";
22
+ export const decisionRequestStoreOver = ({ database, now }) => {
23
+ const refusal = (row, at) => {
24
+ if (!row)
25
+ return "decision.token-unknown";
26
+ if (row.used_at !== null)
27
+ return "decision.token-used";
28
+ if (row.cancelled_at !== null)
29
+ return "decision.token-cancelled";
30
+ if (row.expires_at <= at)
31
+ return "decision.token-expired";
32
+ return undefined;
33
+ };
34
+ return {
35
+ create: (input) => {
36
+ const { actions, ...fields } = input;
37
+ const text = [
38
+ fields.proposalId,
39
+ fields.batchDigest,
40
+ fields.channel,
41
+ fields.botProfile,
42
+ fields.chatId,
43
+ fields.messageId,
44
+ fields.ownerUserId,
45
+ ];
46
+ if (text.some((value) => typeof value !== "string" || value === ""))
47
+ throw new CliError("validation_error", "a decision request needs its batch, message and owner", {
48
+ reason: "decision.request-invalid",
49
+ });
50
+ if (actions.length === 0 ||
51
+ new Set(actions).size !== actions.length ||
52
+ actions.some((action) => !DECISION_ACTIONS.includes(action)))
53
+ throw new CliError("validation_error", "a decision request needs distinct, known actions", {
54
+ reason: "decision.request-invalid",
55
+ });
56
+ const at = now();
57
+ return write(database, () => actions.map((action) => {
58
+ const token = newToken();
59
+ database
60
+ .prepare(`INSERT INTO decision_requests (token_digest, proposal_id, action, batch_digest, channel, bot_profile,
61
+ chat_id, message_id, owner_user_id, created_at, expires_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)`)
62
+ .run(digestOf(token), fields.proposalId, action, fields.batchDigest, fields.channel, fields.botProfile, fields.chatId, fields.messageId, fields.ownerUserId, at, at + DECISION_TTL_MS);
63
+ return { action, token };
64
+ }));
65
+ },
66
+ take: (token, expect) => {
67
+ if (!isDecisionToken(token))
68
+ return { ok: false, reason: "decision.token-unknown" };
69
+ const digest = digestOf(token);
70
+ return write(database, () => {
71
+ const at = now();
72
+ const row = database.prepare("SELECT * FROM decision_requests WHERE token_digest=?").get(digest);
73
+ if (!row)
74
+ return { ok: false, reason: "decision.token-unknown" };
75
+ if (expect.botProfile !== row.bot_profile ||
76
+ expect.chatId !== row.chat_id ||
77
+ expect.messageId !== row.message_id ||
78
+ expect.ownerUserId !== row.owner_user_id)
79
+ return { ok: false, reason: "decision.token-mismatch" };
80
+ const reason = refusal(row, at);
81
+ if (reason)
82
+ return { ok: false, reason };
83
+ database.prepare("UPDATE decision_requests SET used_at=? WHERE id=?").run(at, row.id);
84
+ const { changes } = database
85
+ .prepare(`UPDATE decision_requests SET cancelled_at=? WHERE ${SAME_MESSAGE} AND id<>? AND ${OPEN}`)
86
+ .run(at, row.channel, row.bot_profile, row.chat_id, row.message_id, row.id);
87
+ return { ok: true, request: requestOf(row), cancelled: Number(changes) };
88
+ });
89
+ },
90
+ cancelOpen: (scope = {}) => {
91
+ const filters = [];
92
+ const values = [];
93
+ if (scope.channel !== undefined) {
94
+ filters.push("channel=?");
95
+ values.push(scope.channel);
96
+ }
97
+ if (scope.botProfile !== undefined) {
98
+ filters.push("bot_profile=?");
99
+ values.push(scope.botProfile);
100
+ }
101
+ const where = [OPEN, ...filters].join(" AND ");
102
+ return write(database, () => Number(database.prepare(`UPDATE decision_requests SET cancelled_at=? WHERE ${where}`).run(now(), ...values).changes));
103
+ },
104
+ prune: (at = now()) => write(database, () => Number(database
105
+ .prepare(`DELETE FROM decision_requests WHERE expires_at < ?1 OR used_at < ?1 OR cancelled_at < ?1`)
106
+ .run(at - PRUNE_AFTER_MS).changes)),
107
+ open: (message) => database
108
+ .prepare(`SELECT * FROM decision_requests WHERE ${SAME_MESSAGE} AND ${OPEN} AND expires_at>? ORDER BY id`)
109
+ .all(message.channel, message.botProfile, message.chatId, message.messageId, now()).map(requestOf),
110
+ };
111
+ };
@@ -111,6 +111,8 @@ export const MANIFEST = [
111
111
  { name: "20261106010507_version-52-deals-rules", version: 52, minCompatible: 34 },
112
112
  { name: "20261106165009_version-53-crm-pipelines", version: 53, minCompatible: 34 },
113
113
  { name: "20261106225547_version-54-crm-fields", version: 54, minCompatible: 34 },
114
+ { name: "20261107032742_version-55-decision-requests", version: 55, minCompatible: 34 },
115
+ { name: "20261107043407_version-55-decision-requests-index", version: 55, minCompatible: 34 },
114
116
  ];
115
117
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
116
118
  const migrations = [];
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError } from "@wirecat/cli-base";
3
- import { formatMeetingReference, parseMeetingQuery } from "../../meetings/index.js";
3
+ import { formatMeetingReference, MEETING_FIELD_NAMES, parseMeetingQuery } from "../../meetings/index.js";
4
+ import { plainQuery } from "../../search/lucene/plain.js";
4
5
  import { matchMeetingText, meetingQuerySql, resolveMeetingQuery } from "./meeting-hit-query.js";
5
6
  import { indexedText } from "./meeting-index-values.js";
6
7
  import { checkMeetingCancelled } from "./meeting-operation.js";
@@ -90,7 +91,7 @@ export function meetingHitSearchOver({ database }) {
90
91
  fail("Meeting search byte limit must be from 1 through 67108864");
91
92
  if (typeof rawQuery === "string" && Buffer.byteLength(rawQuery) > 65536)
92
93
  fail("Meeting search query must be a bounded string");
93
- const ast = typeof rawQuery === "string" ? parseMeetingQuery(rawQuery) : rawQuery;
94
+ const ast = typeof rawQuery === "string" ? parseMeetingQuery(plainQuery(rawQuery, MEETING_FIELD_NAMES)) : rawQuery;
94
95
  return read(database, () => {
95
96
  checkMeetingCancelled(input.signal);
96
97
  const state = meetingStemState(database, input.accountId);
@@ -1048,5 +1048,17 @@ export const GENERATED = [
1048
1048
  "statements": [
1049
1049
  "CREATE TABLE `crm_fields` (\n\t`id` integer PRIMARY KEY,\n\t`account_id` integer NOT NULL,\n\t`kind` text NOT NULL,\n\t`code` text NOT NULL,\n\t`label` text,\n\t`type` text NOT NULL,\n\t`multiple` integer NOT NULL,\n\t`filterable` integer NOT NULL,\n\t`options` text,\n\t`position` integer NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\t`deleted_at` integer,\n\tCONSTRAINT `fk_crm_fields_account_id_accounts_id_fk` FOREIGN KEY (`account_id`) REFERENCES `accounts`(`id`),\n\tCONSTRAINT `crm_fields_account_id_kind_code_unique` UNIQUE(`account_id`,`kind`,`code`)\n);"
1050
1050
  ]
1051
+ },
1052
+ {
1053
+ "name": "20261107032742_version-55-decision-requests",
1054
+ "statements": [
1055
+ "CREATE TABLE `decision_requests` (\n\t`id` integer PRIMARY KEY,\n\t`token_digest` text NOT NULL UNIQUE,\n\t`proposal_id` text NOT NULL,\n\t`action` text NOT NULL,\n\t`batch_digest` text NOT NULL,\n\t`channel` text NOT NULL,\n\t`bot_profile` text NOT NULL,\n\t`chat_id` text NOT NULL,\n\t`message_id` text NOT NULL,\n\t`owner_user_id` text NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`expires_at` integer NOT NULL,\n\t`used_at` integer,\n\t`cancelled_at` integer\n);"
1056
+ ]
1057
+ },
1058
+ {
1059
+ "name": "20261107043407_version-55-decision-requests-index",
1060
+ "statements": [
1061
+ "CREATE INDEX `decision_requests_by_channel_bot_profile_chat_id_message_id` ON `decision_requests` (`channel`,`bot_profile`,`chat_id`,`message_id`);"
1062
+ ]
1051
1063
  }
1052
1064
  ];