@wirecat/cli-core 0.619.0 → 0.620.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 (85) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/cli/search-all.d.ts +1 -1
  4. package/dist/calendar/cli/search-all.js +9 -10
  5. package/dist/calendar/prepare.js +1 -0
  6. package/dist/cli/base-stages-command.d.ts +1 -1
  7. package/dist/cli/base-stages-command.js +1 -1
  8. package/dist/cli/bot/buttons.d.ts +3 -0
  9. package/dist/cli/bot/buttons.js +24 -0
  10. package/dist/cli/bot/messages.js +14 -1
  11. package/dist/cli/bot/port.d.ts +8 -0
  12. package/dist/cli/contract-templates.js +31 -2
  13. package/dist/cli/messenger/contacts-command.js +2 -1
  14. package/dist/cli/messenger/conversations-command.js +2 -1
  15. package/dist/cli/messenger/message-items.js +1 -1
  16. package/dist/cli/messenger/search-answers.d.ts +5 -5
  17. package/dist/cli/messenger/search-answers.js +9 -20
  18. package/dist/cli/messenger/search-command.d.ts +2 -2
  19. package/dist/cli/messenger/search-command.js +8 -18
  20. package/dist/cli/model-catalogue-command.js +3 -1
  21. package/dist/cli/search-harder-consents-command.d.ts +18 -0
  22. package/dist/cli/search-harder-consents-command.js +83 -0
  23. package/dist/cli/steps.js +0 -6
  24. package/dist/cli/templates-command.js +4 -4
  25. package/dist/crm/cli/index.js +2 -2
  26. package/dist/crm/cli/search-all.js +7 -6
  27. package/dist/domain/models.d.ts +2 -0
  28. package/dist/entities/contact-context.d.ts +3 -0
  29. package/dist/entities/contact-context.js +4 -0
  30. package/dist/entities/hit.d.ts +9 -2
  31. package/dist/entities/hit.js +6 -2
  32. package/dist/entities/index.d.ts +9 -1
  33. package/dist/errors/reasons.js +2 -0
  34. package/dist/meetings/hit-query.d.ts +1 -1
  35. package/dist/meetings/hit-query.js +2 -2
  36. package/dist/meetings/index.d.ts +1 -0
  37. package/dist/meetings/index.js +1 -0
  38. package/dist/meetings/store.d.ts +4 -0
  39. package/dist/meetings/store.js +2 -1
  40. package/dist/models/anthropic.js +5 -0
  41. package/dist/search/question-period.d.ts +10 -0
  42. package/dist/search/question-period.js +133 -0
  43. package/dist/sends/buttons.d.ts +2 -0
  44. package/dist/sends/buttons.js +6 -1
  45. package/dist/services/enrichment.d.ts +5 -0
  46. package/dist/services/enrichment.js +1 -1
  47. package/dist/services/index.d.ts +4 -2
  48. package/dist/services/index.js +3 -1
  49. package/dist/services/messages.d.ts +1 -4
  50. package/dist/services/messages.js +0 -2
  51. package/dist/services/metadata.d.ts +1 -1
  52. package/dist/services/person-context.d.ts +3 -1
  53. package/dist/services/person-context.js +21 -8
  54. package/dist/services/person-preparation.d.ts +5 -1
  55. package/dist/services/person-preparation.js +10 -3
  56. package/dist/services/person-timeline.d.ts +6 -1
  57. package/dist/services/person-timeline.js +10 -2
  58. package/dist/services/search-all-deprecated.d.ts +40 -0
  59. package/dist/services/search-all-deprecated.js +10 -0
  60. package/dist/services/search-all-meetings.d.ts +50 -52
  61. package/dist/services/search-all-meetings.js +265 -272
  62. package/dist/services/search-all.d.ts +34 -6
  63. package/dist/services/search-all.js +118 -24
  64. package/dist/services/search-harder.d.ts +64 -0
  65. package/dist/services/search-harder.js +194 -0
  66. package/dist/store/chats.d.ts +3 -1
  67. package/dist/store/chats.js +6 -0
  68. package/dist/store/people.d.ts +6 -2
  69. package/dist/store/sqlite/added-sources.d.ts +15 -3
  70. package/dist/store/sqlite/added-sources.js +26 -5
  71. package/dist/store/sqlite/chats.d.ts +2 -0
  72. package/dist/store/sqlite/chats.js +6 -0
  73. package/dist/store/sqlite/involvements.d.ts +1 -1
  74. package/dist/store/sqlite/involvements.js +4 -2
  75. package/dist/store/sqlite/meeting-hit-query.d.ts +5 -0
  76. package/dist/store/sqlite/meeting-hit-query.js +33 -0
  77. package/dist/store/sqlite/meeting-hit-search.js +10 -8
  78. package/dist/store/sqlite/meetings.js +1 -1
  79. package/dist/store/sqlite/notes.d.ts +7 -0
  80. package/dist/store/sqlite/notes.js +13 -5
  81. package/dist/store/sqlite/person-preparation.d.ts +7 -3
  82. package/dist/store/sqlite/person-preparation.js +20 -6
  83. package/dist/store/sqlite/relation-list.js +4 -2
  84. package/package.json +1 -1
  85. package/parity.json +26 -12
@@ -7,7 +7,7 @@ import type { PersonMerge } from "./sqlite/person-merges.js";
7
7
  import { type PersonPreparationRead } from "./sqlite/person-preparation.js";
8
8
  import type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
9
9
  import type { ProposedAction } from "./sqlite/proposed-actions.js";
10
- import type { AccountKey, IdentityRef, LinkOptions, PersonFacts, PersonRecord } from "./types.js";
10
+ import type { AccountKey, IdentityRef, LinkOptions, PersonFacts, PersonRecord, StoredAccount } from "./types.js";
11
11
  export interface AccountPeople {
12
12
  savePeople(key: AccountKey, people: PersonFacts[]): Promise<void>;
13
13
  /**
@@ -52,9 +52,13 @@ export interface PeopleStore extends AccountPeople {
52
52
  personByUid(uid: string): Promise<PersonRecord | undefined>;
53
53
  /** The person marked as the owner, with every identity linked to them; `undefined` when none is. */
54
54
  owner(): Promise<PersonRecord | undefined>;
55
- /** Accepted facts, the owner's notes and open tasks about them; tasks of an account only if `accounts` holds it. */
55
+ /**
56
+ * Accepted facts, the owner's notes and open tasks about them; tasks of an account only if `accounts` holds it,
57
+ * and what belongs to no account only in `scopes`.
58
+ */
56
59
  preparation(uid: string, options: {
57
60
  accounts: readonly AccountKey[];
61
+ scopes: readonly StoredAccount["scope"][];
58
62
  limit: number;
59
63
  }): Promise<PersonPreparationRead>;
60
64
  /** Records the decision in `identity_link_events`; `unlinkIdentity` undoes it. */
@@ -28,9 +28,15 @@ export interface AddedSourceInput {
28
28
  };
29
29
  metadata?: DocumentMetadata;
30
30
  sections?: Section[];
31
+ /**
32
+ * What names it where it came from, `<namespace>:<id>` (`google-drive:<fileId>`). A source saved again under the
33
+ * same key is that source: changed text becomes its next revision, so what cites it is reviewed, never a second
34
+ * copy. Without a key a source is named by its content.
35
+ */
36
+ sourceKey?: string;
31
37
  }
32
38
  /** What names an added source: enough to find it before anything is written. */
33
- export type AddedSourceContent = Pick<AddedSourceInput, "kind" | "text" | "url" | "bytes">;
39
+ export type AddedSourceContent = Pick<AddedSourceInput, "kind" | "text" | "url" | "bytes" | "sourceKey">;
34
40
  /** The part of `store.notes` that keeps the sources added by hand. */
35
41
  export interface AddedSources {
36
42
  /**
@@ -69,6 +75,11 @@ export interface AddedSource {
69
75
  duplicateOf: string | null;
70
76
  /** What is kept of the source: its text, or its text and a copy; `null` for a duplicate. */
71
77
  kept: "text" | "copy" | null;
78
+ /**
79
+ * Whether its text was written now: a new source, a revived one, or a new revision under its source key. Optional
80
+ * because a host store that wraps this one (drive-cli) may not report it; absent means not reported.
81
+ */
82
+ changed?: boolean;
72
83
  /** Every subject the document is about now, the ones linked before included. */
73
84
  subjects: string[];
74
85
  }
@@ -87,8 +98,9 @@ export interface AddedSourceDetails {
87
98
  copy: string | null;
88
99
  }
89
100
  /**
90
- * The key an added source is stored under, `sha256:<hash>` (a file's bytes; pasted text or a page by its normalized
91
- * text, or its address when it has none), and every hash a folder or Drive document of the same content may carry.
101
+ * The key an added source is stored under: its source key, else `sha256:<hash>` (a file's bytes; pasted text or a page
102
+ * by its normalized text, or its address when it has none), and every hash a folder or Drive document of the same
103
+ * content may carry.
92
104
  */
93
105
  export declare const addedSourceKeyOf: (content: AddedSourceContent) => {
94
106
  externalId: string;
@@ -6,14 +6,22 @@ import { fold } from "../normalize.js";
6
6
  import { encodeDocumentMetadata, languageOf } from "./document-metadata.js";
7
7
  import { syncFile } from "./files.js";
8
8
  import { linkKind } from "./link-kinds.js";
9
- import { documentOf, folderOf, insertLink, pathParts, requiredThing, thingRef, } from "./notes.js";
9
+ import { documentOf, folderOf, insertLink, keepRevision, pathParts, requiredThing, thingRef, } from "./notes.js";
10
10
  import { oneOf, textOf } from "./text-input.js";
11
11
  import { write } from "./transaction.js";
12
12
  export const ADDED_KINDS = ["text", "file", "page"];
13
13
  const sha256 = (value) => createHash("sha256").update(value).digest("hex");
14
+ // `sha256:` is the content's own name, so no key may take it.
15
+ const SOURCE_KEY = /^(?!sha256:)[a-z][a-z0-9-]{0,39}:[A-Za-z0-9._~-]{1,200}$/;
16
+ const sourceKeyOf = (key) => {
17
+ if (!SOURCE_KEY.test(key))
18
+ throw new CliError("validation_error", "a source key is <namespace>:<id>: a lower-case namespace other than sha256, then letters, digits, . _ ~ or -", { param: "sourceKey" });
19
+ return key;
20
+ };
14
21
  /**
15
- * The key an added source is stored under, `sha256:<hash>` (a file's bytes; pasted text or a page by its normalized
16
- * text, or its address when it has none), and every hash a folder or Drive document of the same content may carry.
22
+ * The key an added source is stored under: its source key, else `sha256:<hash>` (a file's bytes; pasted text or a page
23
+ * by its normalized text, or its address when it has none), and every hash a folder or Drive document of the same
24
+ * content may carry.
17
25
  */
18
26
  export const addedSourceKeyOf = (content) => {
19
27
  const kind = oneOf(content.kind, ADDED_KINDS, "an added source's kind");
@@ -27,7 +35,8 @@ export const addedSourceKeyOf = (content) => {
27
35
  const hash = kind === "file" ? sha256(content.bytes) : sha256(normalized || url);
28
36
  // Drive keeps the sha256 of the text it exported, as is: pasted text or a page with that text is that file.
29
37
  const hashes = [...new Set(kind === "file" || !text ? [hash] : [hash, sha256(content.text)])];
30
- return { externalId: `sha256:${hash}`, hash, hashes };
38
+ const externalId = content.sourceKey === undefined ? `sha256:${hash}` : sourceKeyOf(content.sourceKey);
39
+ return { externalId, hash, hashes };
31
40
  };
32
41
  /** The input checked. */
33
42
  const checked = (input) => {
@@ -189,6 +198,16 @@ export const addedSourcesOver = (context) => {
189
198
  const own = ownRow(source.externalId);
190
199
  if (own !== undefined && own.deleted_at == null) {
191
200
  const id = Number(own.id);
201
+ const revised = input.sourceKey !== undefined && own.content_hash !== source.hash;
202
+ if (revised) {
203
+ keepRevision(database, own, at);
204
+ database
205
+ .prepare("UPDATE documents SET kind = ?, title = ?, file_name = ?, extension = ?, url = ?, mime = ?, size = ?, " +
206
+ "content_hash = ?, body = ?, extraction = ?, metadata = ?, language = ?, revision = revision + 1, " +
207
+ "updated_at = ? WHERE id = ?")
208
+ .run(source.kind, source.title, source.fileName, source.extension, source.url, input.mime ?? null, input.size ?? input.bytes?.byteLength ?? null, source.hash, source.text, source.read === "extracted" ? "text" : "none", metadata, languageOf(input.metadata), at, id);
209
+ placeFile(id, at, source.fileName ?? source.title ?? source.externalId);
210
+ }
192
211
  if (source.copy !== null && own.storage !== "copy")
193
212
  database
194
213
  .prepare("UPDATE documents SET storage = 'copy', local_path = ?, updated_at = ? WHERE id = ?")
@@ -199,6 +218,7 @@ export const addedSourcesOver = (context) => {
199
218
  created: false,
200
219
  duplicateOf: null,
201
220
  kept,
221
+ changed: revised,
202
222
  subjects: about(id, subjects, input.by),
203
223
  };
204
224
  }
@@ -206,7 +226,7 @@ export const addedSourcesOver = (context) => {
206
226
  if (duplicate !== undefined) {
207
227
  const linked = about(duplicate, subjects, input.by);
208
228
  const note = documentAt(duplicate);
209
- return { note, created: false, duplicateOf: note.ref, kept: null, subjects: linked };
229
+ return { note, created: false, duplicateOf: note.ref, kept: null, changed: false, subjects: linked };
210
230
  }
211
231
  const values = [
212
232
  source.kind,
@@ -251,6 +271,7 @@ export const addedSourcesOver = (context) => {
251
271
  created: !own,
252
272
  duplicateOf: null,
253
273
  kept: source.copy === null ? "text" : "copy",
274
+ changed: true,
254
275
  subjects: about(id, subjects, input.by),
255
276
  };
256
277
  });
@@ -63,6 +63,8 @@ export declare const leftChats: ({ orm }: StoreContext, accountKey: number) => {
63
63
  };
64
64
  /** These chats and everything under them, children before parents: the foreign keys are enforced. */
65
65
  export declare const purgeChats: ({ orm, database, now }: StoreContext, pks: number[]) => void;
66
+ /** Each chat's scope as every reader applies it: the chat's own, or else its account's. */
67
+ export declare const chatScopes: ({ database }: StoreContext, accountKey: number, chatIds: readonly Id[]) => Map<Id, string>;
66
68
  export declare const chatsWith: ({ orm, now }: StoreContext, accountKey: number, key: AccountKey, memberId: Id) => Chat[];
67
69
  /**
68
70
  * How the store answers a chat list's query. `title:` goes through the trigram index, so it matches part of a
@@ -337,6 +337,12 @@ export const purgeChats = ({ orm, database, now }, pks) => {
337
337
  forgetDanglingEvidence(database, at);
338
338
  dropUnusedVectors(database, released.map(({ hash }) => hash));
339
339
  };
340
+ /** Each chat's scope as every reader applies it: the chat's own, or else its account's. */
341
+ export const chatScopes = ({ database }, accountKey, chatIds) => new Map(database
342
+ .prepare("SELECT c.external_id AS id, coalesce(c.scope, a.scope) AS scope FROM chats c JOIN accounts a ON a.id = c.account_id " +
343
+ "WHERE c.account_id = ? AND c.external_id IN (SELECT value FROM json_each(?))")
344
+ .all(accountKey, JSON.stringify(chatIds))
345
+ .map((row) => [String(row.id), String(row.scope)]));
340
346
  export const chatsWith = ({ orm, now }, accountKey, key, memberId) => {
341
347
  const rows = orm
342
348
  .select({ chat: chats })
@@ -31,7 +31,7 @@ export interface InvolvementStore {
31
31
  * another account of the same messenger is somebody else's view; other providers and rows of no account stay.
32
32
  */
33
33
  forPerson(personId: number, options?: {
34
- scope?: string;
34
+ scopes?: readonly string[];
35
35
  since?: number;
36
36
  until?: number;
37
37
  only?: {
@@ -21,11 +21,13 @@ export const involvementStoreOver = ({ database, now }) => ({
21
21
  return { recomputed, pending: pendingInvolvements(database) };
22
22
  },
23
23
  pending: () => pendingInvolvements(database),
24
- forPerson: (personId, { scope, since, until, only, before, limit = 100 } = {}) => {
24
+ forPerson: (personId, { scopes, since, until, only, before, limit = 100 } = {}) => {
25
25
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
26
26
  throw new CliError("validation_error", "involvement limit takes 1–1000");
27
27
  const filters = [
28
- ...(scope === undefined ? [] : [["AND i.scope=?", scope]]),
28
+ ...(scopes === undefined
29
+ ? []
30
+ : [["AND i.scope IN (SELECT value FROM json_each(?))", JSON.stringify(scopes)]]),
29
31
  ...(since === undefined ? [] : [["AND i.occurred_at>=?", since]]),
30
32
  ...(until === undefined ? [] : [["AND i.occurred_at<=?", until]]),
31
33
  ];
@@ -57,4 +57,9 @@ export declare const matchMeetingText: (tree: Resolved, text: string, stemmer: S
57
57
  from: string;
58
58
  to: string[];
59
59
  }[] | null;
60
+ /**
61
+ * The words of `text` the query's positive terms matched, as the text spells them: by the typed beginning, by stem or
62
+ * as a garbled spelling. A word only under NOT is never one, so an excerpt centred on these shows why it is a hit.
63
+ */
64
+ export declare const matchedMeetingWords: (tree: Resolved, text: string, stemmer: Stemmer | null) => string[];
60
65
  export {};
@@ -275,3 +275,36 @@ export const matchMeetingText = (tree, text, stemmer) => {
275
275
  };
276
276
  return check(tree);
277
277
  };
278
+ /**
279
+ * The words of `text` the query's positive terms matched, as the text spells them: by the typed beginning, by stem or
280
+ * as a garbled spelling. A word only under NOT is never one, so an excerpt centred on these shows why it is a hit.
281
+ */
282
+ export const matchedMeetingWords = (tree, text, stemmer) => {
283
+ const tokens = normalize(text).match(/[\p{L}\p{N}]+/gu) ?? [];
284
+ let stemmed;
285
+ const stemsOf = () => (stemmed ??= stemmer ? stemmer.explain(meetingStemmableText(text)) : []);
286
+ const found = new Set();
287
+ const word = (term) => {
288
+ for (const token of tokens)
289
+ if (term.whole ? token === term.literal : token.startsWith(term.literal))
290
+ found.add(token);
291
+ for (const { word, stem } of stemsOf())
292
+ if (term.stems.includes(stem))
293
+ found.add(word);
294
+ for (const widened of term.widened)
295
+ if (tokens.includes(widened))
296
+ found.add(widened);
297
+ };
298
+ const visit = (node) => {
299
+ if (node.kind === "speaker")
300
+ return;
301
+ if (node.kind === "boolean")
302
+ for (const part of [...node.must, ...node.should])
303
+ visit(part);
304
+ else
305
+ for (const term of node.words)
306
+ word(term);
307
+ };
308
+ visit(tree);
309
+ return [...found];
310
+ };
@@ -1,8 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError } from "@wirecat/cli-base";
3
- import { formatMeetingReference, MEETING_FIELD_NAMES, parseMeetingQuery } from "../../meetings/index.js";
3
+ import { formatMeetingReference, MEETING_FIELD_NAMES, parseMeetingQuery, READ_BUDGET_EXCEEDED, } from "../../meetings/index.js";
4
4
  import { plainQuery } from "../../search/lucene/plain.js";
5
- import { matchMeetingText, meetingQuerySql, resolveMeetingQuery } from "./meeting-hit-query.js";
5
+ import { matchedMeetingWords, matchMeetingText, meetingQuerySql, resolveMeetingQuery } from "./meeting-hit-query.js";
6
6
  import { indexedText } from "./meeting-index-values.js";
7
7
  import { checkMeetingCancelled } from "./meeting-operation.js";
8
8
  import { positiveReadInteger } from "./meeting-reads.js";
@@ -122,9 +122,9 @@ export function meetingHitSearchOver({ database }) {
122
122
  if (after)
123
123
  params.push(after.tier, after.tier, after.started, after.started, after.meeting, after.meeting, after.kind, after.kind, after.id);
124
124
  const sql = `WITH matches AS (${matching}), matching AS (SELECT rid,tier FROM matches h WHERE NOT EXISTS(SELECT 1 FROM meeting_index_pending p WHERE p.id=h.rid/4 AND p.indexable_type=CASE h.rid%4 WHEN 1 THEN 'meeting_transcript_row' WHEN 2 THEN 'meeting_chat_message' ELSE 'meeting_summary' END)), selected AS (SELECT m.id,coalesce(m.started_at,0) AS started FROM meetings m WHERE ${clauses.join(" AND ")}), hits AS (
125
- SELECT h.tier,m.started,m.id AS meeting_id,0 AS kind,r.id,r.start_ms,${bytes("r", ["text"])} AS bytes,t.id AS transcript_id,r.position,t.language,(SELECT count(*) FROM meeting_transcript_rows n WHERE n.meeting_transcript_id=t.id) AS lines_total FROM matching h JOIN meeting_transcript_rows r ON h.rid%4=1 AND r.id=h.rid/4 JOIN meeting_transcripts t ON t.id=r.meeting_transcript_id AND t.superseded_at IS NULL AND t.deleted_at IS NULL JOIN selected m ON m.id=t.meeting_id
126
- UNION ALL SELECT h.tier,m.started,m.id,1,c.id,NULL,${bytes("c", ["text"])},NULL,NULL,NULL,NULL FROM matching h JOIN meeting_chat_messages c ON h.rid%4=2 AND c.id=h.rid/4 JOIN selected m ON m.id=c.meeting_id
127
- UNION ALL SELECT h.tier,m.started,m.id,2,s.id,NULL,${bytes("s", fields)},NULL,NULL,NULL,NULL FROM matching h JOIN meeting_summaries s ON h.rid%4=3 AND s.id=h.rid/4 JOIN selected m ON m.id=s.meeting_id)
125
+ SELECT h.tier,m.started,m.id AS meeting_id,0 AS kind,r.id,r.start_ms,${bytes("r", ["text", "speaker_name"])} AS bytes,t.id AS transcript_id,r.position,t.language,(SELECT count(*) FROM meeting_transcript_rows n WHERE n.meeting_transcript_id=t.id) AS lines_total,r.speaker_name AS speaker FROM matching h JOIN meeting_transcript_rows r ON h.rid%4=1 AND r.id=h.rid/4 JOIN meeting_transcripts t ON t.id=r.meeting_transcript_id AND t.superseded_at IS NULL AND t.deleted_at IS NULL JOIN selected m ON m.id=t.meeting_id
126
+ UNION ALL SELECT h.tier,m.started,m.id,1,c.id,NULL,${bytes("c", ["text"])},NULL,NULL,NULL,NULL,NULL FROM matching h JOIN meeting_chat_messages c ON h.rid%4=2 AND c.id=h.rid/4 JOIN selected m ON m.id=c.meeting_id
127
+ UNION ALL SELECT h.tier,m.started,m.id,2,s.id,NULL,${bytes("s", fields)},NULL,NULL,NULL,NULL,NULL FROM matching h JOIN meeting_summaries s ON h.rid%4=3 AND s.id=h.rid/4 JOIN selected m ON m.id=s.meeting_id)
128
128
  SELECT h.*,${bytes("m", ["title"])}+${bytes("s", ["doc_url"])} AS context_bytes FROM hits h
129
129
  JOIN meetings m ON m.id=h.meeting_id LEFT JOIN meeting_summaries s ON h.kind=2 AND s.id=h.id
130
130
  ${seek} ORDER BY h.tier,h.started DESC,h.meeting_id,h.kind,h.id LIMIT ?`;
@@ -138,7 +138,7 @@ export function meetingHitSearchOver({ database }) {
138
138
  fail("Invalid stored meeting search text size");
139
139
  total += size;
140
140
  if (total > maxReadBytes)
141
- fail("Meeting search exceeds its stored text byte budget");
141
+ fail(READ_BUDGET_EXCEEDED);
142
142
  }
143
143
  checkMeetingCancelled(input.signal);
144
144
  const items = rows.slice(0, limit).map((row) => {
@@ -179,6 +179,7 @@ export function meetingHitSearchOver({ database }) {
179
179
  startMs: row.start_ms === null ? null : Number(row.start_ms),
180
180
  ...(kind === 0
181
181
  ? {
182
+ speakerName: row.speaker === null ? null : String(row.speaker),
182
183
  language: row.language === null ? null : String(row.language),
183
184
  line: Number(row.position) + 1,
184
185
  linesTotal: Number(row.lines_total),
@@ -190,10 +191,11 @@ export function meetingHitSearchOver({ database }) {
190
191
  const corrections = matchMeetingText(tree, item.text, state.stemmer);
191
192
  if (!corrections)
192
193
  return [];
194
+ const matchedWords = matchedMeetingWords(tree, item.text, state.stemmer);
193
195
  return [
194
196
  corrections.length
195
- ? { ...item, match: "corrected", corrections }
196
- : { ...item, match: "words" },
197
+ ? { ...item, match: "corrected", corrections, matchedWords }
198
+ : { ...item, match: "words", matchedWords },
197
199
  ];
198
200
  });
199
201
  if (fresh.length !== items.length)
@@ -447,7 +447,7 @@ const filtered = (filter = {}) => {
447
447
  const [limit, offset] = page(filter);
448
448
  return {
449
449
  sql: `SELECT * FROM meetings${where.length ? ` WHERE ${where.join(" AND ")}` : ""}
450
- ORDER BY coalesce(started_at, 0) DESC, id LIMIT ? OFFSET ?`,
450
+ ORDER BY started_at DESC, id LIMIT ? OFFSET ?`,
451
451
  params: [...params, limit, offset],
452
452
  };
453
453
  };
@@ -201,6 +201,13 @@ export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources
201
201
  type Row = Record<string, unknown>;
202
202
  /** What a link's written target is matched by: case, accents and a leading `@` do not count. */
203
203
  export declare const targetKey: (text: string) => string;
204
+ /**
205
+ * Keeps a document's text under its current revision before the caller writes the new text with `revision + 1`, so
206
+ * a citation reads back the words it cited and the source check sees the change.
207
+ */
208
+ export declare const keepRevision: (database: CacheDatabase, row: Row, at: number) => {
209
+ changes: number;
210
+ };
204
211
  export declare const documentOf: (row: Row) => Note;
205
212
  export declare const noteOf: (row: Row) => Note;
206
213
  /** A document or note row by its typed reference, or `undefined`. */
@@ -30,6 +30,13 @@ const iso = (value) => new Date(Number(value)).toISOString();
30
30
  const optionalIso = (value) => (value == null ? null : iso(value));
31
31
  /** What a link's written target is matched by: case, accents and a leading `@` do not count. */
32
32
  export const targetKey = (text) => fold(text).trim().replace(/^@/, "");
33
+ /**
34
+ * Keeps a document's text under its current revision before the caller writes the new text with `revision + 1`, so
35
+ * a citation reads back the words it cited and the source check sees the change.
36
+ */
37
+ export const keepRevision = (database, row, at) => database
38
+ .prepare("INSERT INTO document_revisions (document_id, body, revision, created_at) VALUES (?, ?, ?, ?)")
39
+ .run(Number(row.id), String(row.body ?? ""), Number(row.revision), at);
33
40
  export const documentOf = (row) => ({
34
41
  id: String(row.id),
35
42
  ref: `document:${row.id}`,
@@ -417,9 +424,7 @@ export const notesStoreOver = (context) => {
417
424
  found.deleted_at == null;
418
425
  if (!same) {
419
426
  if ((found.body ?? "") !== text)
420
- database
421
- .prepare("INSERT INTO document_revisions (document_id, body, revision, created_at) VALUES (?, ?, ?, ?)")
422
- .run(id, String(found.body ?? ""), Number(found.revision), at);
427
+ keepRevision(database, found, at);
423
428
  database
424
429
  .prepare("UPDATE documents SET title = ?, body = ?, front_matter = ?, content_hash = ?, metadata = ?, language = ?, " +
425
430
  "revision = revision + ?, updated_at = ?, deleted_at = NULL WHERE id = ?")
@@ -612,7 +617,9 @@ export const notesStoreOver = (context) => {
612
617
  if (reference === undefined)
613
618
  return { known: true, type: null, id: null };
614
619
  const thing = thingOf(database, reference);
615
- return thing ? { known: true, type: thing.type, id: thing.id } : { known: false, type: null, id: null };
620
+ return thing
621
+ ? { known: true, type: thing.type, id: idsOf(database, thing.type, thing.id) }
622
+ : { known: false, type: null, id: null };
616
623
  };
617
624
  const from = pair(options.from);
618
625
  const to = pair(options.to);
@@ -626,7 +633,8 @@ export const notesStoreOver = (context) => {
626
633
  ...(options.confirmed === undefined ? [] : [{ sql: "confirmed = ?", value: options.confirmed ? 1 : 0 }]),
627
634
  ];
628
635
  return database
629
- .prepare("SELECT * FROM links WHERE (? IS NULL OR (from_type = ? AND from_id = ?)) AND (? IS NULL OR (to_type = ? AND to_id = ?)) " +
636
+ .prepare("SELECT * FROM links WHERE (? IS NULL OR (from_type = ? AND from_id IN (SELECT value FROM json_each(?)))) " +
637
+ "AND (? IS NULL OR (to_type = ? AND to_id IN (SELECT value FROM json_each(?)))) " +
630
638
  `AND (? = 0 OR to_id IS NULL)${filters.map(({ sql }) => ` AND (${sql})`).join("")} ORDER BY created_at, id LIMIT 5000`)
631
639
  .all(from.type, from.type, from.id, to.type, to.type, to.id, options.unresolved ? 1 : 0, ...filters.map(({ value }) => value))
632
640
  .map((row) => linkOf(database, row));
@@ -1,4 +1,4 @@
1
- import type { AccountKey } from "../types.js";
1
+ import type { AccountKey, StoredAccount } from "../types.js";
2
2
  import type { StoreContext } from "./open.js";
3
3
  export interface PreparationFact {
4
4
  ref: string;
@@ -40,9 +40,13 @@ export interface PersonPreparationRead {
40
40
  }
41
41
  /**
42
42
  * The accepted facts, the owner's notes and the open tasks about one person. A project bound to an account is that
43
- * account's: its facts never come along, and its tasks only when `accounts` holds it.
43
+ * account's: its facts never come along, and its tasks only when `accounts` holds it. What belongs to no account
44
+ * comes only in `scopes`: a fact in its own scope, else its project's, a note only when every scope it touches is
45
+ * read, a global project's task in that project's. Anything else unscoped is personal, the side a work view never
46
+ * reads.
44
47
  */
45
- export declare const personPreparation: ({ database, now }: Pick<StoreContext, "database" | "now">, uid: string, { accounts, limit }: {
48
+ export declare const personPreparation: ({ database, now }: Pick<StoreContext, "database" | "now">, uid: string, { accounts, scopes, limit, }: {
46
49
  accounts: readonly AccountKey[];
50
+ scopes: readonly StoredAccount["scope"][];
47
51
  limit: number;
48
52
  }) => PersonPreparationRead;
@@ -5,16 +5,28 @@ import { samePersons } from "./merged-persons.js";
5
5
  import { taskIdOf } from "./things.js";
6
6
  import { read } from "./transaction.js";
7
7
  const GLOBAL_PROJECT = "SELECT id FROM main.projects WHERE account_id IS NULL AND deleted_at IS NULL";
8
+ const IN_SCOPES = "IN (SELECT value FROM json_each(?))";
9
+ const projectScope = (id) => `(SELECT p.scope FROM main.projects p WHERE p.id=${id})`;
10
+ const NOTE_PROJECTS = `SELECT l.to_id FROM links l WHERE l.from_type='note' AND l.from_id=n.id AND l.to_type='project'
11
+ AND l.kind=${linkKind("about")}`;
12
+ /** A note is in its project's scope, or in those of the projects it is about; with no project, personal. */
13
+ const NOTE_SCOPES = `SELECT p.scope FROM main.projects p WHERE (n.notable_type='project' AND p.id=n.notable_id)
14
+ OR p.id IN (${NOTE_PROJECTS})
15
+ UNION SELECT 'personal' WHERE n.notable_type<>'project' AND NOT EXISTS(${NOTE_PROJECTS})`;
8
16
  const iso = (value) => (value == null ? null : new Date(Number(value)).toISOString());
9
17
  /**
10
18
  * The accepted facts, the owner's notes and the open tasks about one person. A project bound to an account is that
11
- * account's: its facts never come along, and its tasks only when `accounts` holds it.
19
+ * account's: its facts never come along, and its tasks only when `accounts` holds it. What belongs to no account
20
+ * comes only in `scopes`: a fact in its own scope, else its project's, a note only when every scope it touches is
21
+ * read, a global project's task in that project's. Anything else unscoped is personal, the side a work view never
22
+ * reads.
12
23
  */
13
- export const personPreparation = ({ database, now }, uid, { accounts, limit }) => {
24
+ export const personPreparation = ({ database, now }, uid, { accounts, scopes, limit, }) => {
14
25
  const asked = Number(uid);
15
26
  if (!/^[1-9]\d*$/.test(uid) || !Number.isSafeInteger(asked) || !Number.isSafeInteger(limit) || limit < 1)
16
27
  throw new CliError("validation_error", "person preparation takes a person id and a positive limit");
17
28
  const page = (rows) => ({ items: rows.slice(0, limit), hasMore: rows.length > limit });
29
+ const inScopes = JSON.stringify(scopes);
18
30
  return read(database, () => {
19
31
  const person = JSON.stringify(samePersons(database, asked));
20
32
  const projects = `SELECT l.to_id FROM links l WHERE l.from_type='person' AND l.from_id IN (SELECT value FROM json_each(?))
@@ -27,8 +39,9 @@ export const personPreparation = ({ database, now }, uid, { accounts, limit }) =
27
39
  OR f.project_id IN (${projects}))
28
40
  AND (f.subject_type IS NOT 'project' OR f.subject_id IN (${GLOBAL_PROJECT}))
29
41
  AND (f.project_id IS NULL OR f.project_id IN (${GLOBAL_PROJECT}))
42
+ AND coalesce(f.scope,${projectScope("coalesce(f.project_id,CASE WHEN f.subject_type='project' THEN f.subject_id END)")},'personal') ${IN_SCOPES}
30
43
  ORDER BY f.updated_at DESC, f.id DESC LIMIT ?`)
31
- .all(person, person, person, limit + 1)
44
+ .all(person, person, person, inScopes, limit + 1)
32
45
  .map((row) => ({
33
46
  ref: `fact:${row.id}`,
34
47
  type: String(row.type),
@@ -44,8 +57,9 @@ export const personPreparation = ({ database, now }, uid, { accounts, limit }) =
44
57
  AND ((n.notable_type='person' AND n.notable_id IN (SELECT value FROM json_each(?))) OR EXISTS(SELECT 1 FROM links l WHERE l.from_type='note'
45
58
  AND l.from_id=n.id AND l.to_type='person' AND l.to_id IN (SELECT value FROM json_each(?)) AND l.kind=${linkKind("about")} AND l.confirmed=1))
46
59
  AND (n.notable_type='person' OR (n.notable_type='project' AND n.notable_id IN (${GLOBAL_PROJECT})))
60
+ AND NOT EXISTS(SELECT 1 FROM (${NOTE_SCOPES}) WHERE scope NOT ${IN_SCOPES})
47
61
  ORDER BY n.updated_at DESC, n.id DESC LIMIT ?`)
48
- .all(person, person, limit + 1)
62
+ .all(person, person, inScopes, limit + 1)
49
63
  .map((row) => ({
50
64
  ref: `note:${row.id}`,
51
65
  title: row.title == null ? null : String(row.title),
@@ -57,11 +71,11 @@ export const personPreparation = ({ database, now }, uid, { accounts, limit }) =
57
71
  .prepare(`SELECT t.id,t.title,t.due_at,t.project_id,t.source_locator,t.created_at,group_concat(DISTINCT ta.role) AS role
58
72
  FROM task_assignments ta JOIN tasks t ON t.id=ta.task_id JOIN main.projects p ON p.id=t.project_id
59
73
  WHERE ta.assignee_type='person' AND ta.assignee_id IN (SELECT value FROM json_each(?)) AND t.deleted_at IS NULL AND t.status NOT IN ('done','dismissed')
60
- AND p.deleted_at IS NULL AND (p.account_id IS NULL OR p.account_id IN (SELECT a.id FROM accounts a
74
+ AND p.deleted_at IS NULL AND ((p.account_id IS NULL AND p.scope ${IN_SCOPES}) OR p.account_id IN (SELECT a.id FROM accounts a
61
75
  JOIN json_each(?) k ON a.provider=json_extract(k.value,'$.provider')
62
76
  AND a.external_id=json_extract(k.value,'$.account')))
63
77
  GROUP BY t.id ORDER BY t.due_at IS NULL, t.due_at, t.created_at, t.id LIMIT ?`)
64
- .all(person, JSON.stringify(accounts.map(({ provider, account }) => ({ provider, account }))), limit + 1)
78
+ .all(person, inScopes, JSON.stringify(accounts.map(({ provider, account }) => ({ provider, account }))), limit + 1)
65
79
  .map((row) => ({
66
80
  ref: `task:${taskIdOf(database, Number(row.id))}`,
67
81
  title: String(row.title),
@@ -54,8 +54,10 @@ export const relationListOver = (context) => {
54
54
  if (filter.to !== undefined)
55
55
  end("to", filter.to);
56
56
  const about = filter.about === undefined ? undefined : thing(filter.about, "the reference");
57
+ const aboutIds = about ? idsOf(database, about.type, about.id) : "[]";
57
58
  if (about)
58
- add(`((r.from_type = ? AND r.from_id IN (SELECT value FROM json_each(?))) OR (r.to_type = ? AND r.to_id IN (SELECT value FROM json_each(?))))`, about.type, idsOf(database, about.type, about.id), about.type, idsOf(database, about.type, about.id));
59
+ add(`((r.from_type = ? AND r.from_id IN (SELECT value FROM json_each(?))) OR (r.to_type = ? AND r.to_id IN (SELECT value FROM json_each(?))))`, about.type, aboutIds, about.type, aboutIds);
60
+ const aboutSame = new Set(JSON.parse(aboutIds));
59
61
  if (filter.at !== undefined)
60
62
  add("(r.starts_at IS NULL OR r.starts_at <= ?) AND (r.ends_at IS NULL OR ? < r.ends_at)", filter.at, filter.at);
61
63
  if (filter.standing !== undefined)
@@ -103,7 +105,7 @@ export const relationListOver = (context) => {
103
105
  if (!about)
104
106
  return item;
105
107
  const from = thingOf(database, item.from);
106
- const outgoing = from?.type === about.type && from.id === about.id;
108
+ const outgoing = from?.type === about.type && aboutSame.has(from.id);
107
109
  return outgoing
108
110
  ? { ...item, direction: "outgoing" }
109
111
  : { ...item, direction: "incoming", inverse: inverseOf(item.kind) };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.619.0",
3
+ "version": "0.620.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
package/parity.json CHANGED
@@ -157,6 +157,10 @@
157
157
  "--brief": {
158
158
  "meaning": "found messages as reference, title, time, sender and excerpt only"
159
159
  },
160
+ "--button": {
161
+ "value": "<text=data>",
162
+ "meaning": "an inline button as <text>=<data>; repeat for more in one row"
163
+ },
160
164
  "--by": {
161
165
  "value": "<grouping>",
162
166
  "meaning": "what to count by",
@@ -588,10 +592,6 @@
588
592
  "meaning": "at most this many bytes of buffered stdin",
589
593
  "default": "16777216"
590
594
  },
591
- "--max-meetings": {
592
- "value": "<n>",
593
- "meaning": "how many of the meeting account's meetings to look through, newest first, or all for every one (default 100)"
594
- },
595
595
  "--max-messages": {
596
596
  "value": "<n>",
597
597
  "meaning": "fetch at most this many messages total (default: 500)"
@@ -669,6 +669,9 @@
669
669
  "--no-block": {
670
670
  "meaning": "remove without banning; by default a removed person cannot come back by the link"
671
671
  },
672
+ "--no-buttons": {
673
+ "meaning": "take the buttons off the message"
674
+ },
672
675
  "--no-catch-up": {
673
676
  "meaning": "skip local preparation after this run"
674
677
  },
@@ -728,7 +731,7 @@
728
731
  },
729
732
  "--only": {
730
733
  "value": "<resources>",
731
- "meaning": "only these resources, separated by commas: messages, notes; meetings when --source names a meeting account"
734
+ "meaning": "only these resources, separated by commas: messages, notes, events, meetings"
732
735
  },
733
736
  "--only-admins-add": {
734
737
  "value": "<on|off>",
@@ -1888,6 +1891,12 @@
1888
1891
  "bot messages edit": {
1889
1892
  "in": ["max", "tg"],
1890
1893
  "options": {
1894
+ "--button": {
1895
+ "in": ["max", "tg"],
1896
+ "planned": {
1897
+ "wa": "whatsapp-cli: wa bot API, plans/2026-10-22-wa-bot-api"
1898
+ }
1899
+ },
1891
1900
  "--html": {
1892
1901
  "in": ["max", "tg"],
1893
1902
  "planned": {
@@ -1899,6 +1908,12 @@
1899
1908
  "planned": {
1900
1909
  "wa": "whatsapp-cli: wa bot API, plans/2026-10-22-wa-bot-api"
1901
1910
  }
1911
+ },
1912
+ "--no-buttons": {
1913
+ "in": ["max", "tg"],
1914
+ "planned": {
1915
+ "wa": "whatsapp-cli: wa bot API, plans/2026-10-22-wa-bot-api"
1916
+ }
1902
1917
  }
1903
1918
  },
1904
1919
  "planned": {
@@ -1948,6 +1963,12 @@
1948
1963
  "wa": "whatsapp-cli: wa bot API, plans/2026-10-22-wa-bot-api"
1949
1964
  }
1950
1965
  },
1966
+ "--button": {
1967
+ "in": ["max", "tg"],
1968
+ "planned": {
1969
+ "wa": "whatsapp-cli: wa bot API, plans/2026-10-22-wa-bot-api"
1970
+ }
1971
+ },
1951
1972
  "--file": {
1952
1973
  "in": ["max", "tg"],
1953
1974
  "planned": {
@@ -4118,13 +4139,6 @@
4118
4139
  },
4119
4140
  "--exact": "all",
4120
4141
  "--limit": "all",
4121
- "--max-meetings": {
4122
- "in": ["wa"],
4123
- "planned": {
4124
- "max": "each CLI’s next cli-core bump",
4125
- "tg": "each CLI’s next cli-core bump"
4126
- }
4127
- },
4128
4142
  "--only": "all",
4129
4143
  "--page": "all",
4130
4144
  "--server-time": {