@wirecat/cli-core 0.619.0 → 0.621.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 (94) hide show
  1. package/CHANGELOG.md +144 -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 +21 -0
  22. package/dist/cli/search-harder-consents-command.js +112 -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/crm/source.d.ts +8 -0
  28. package/dist/crm/sync.d.ts +1 -1
  29. package/dist/crm/sync.js +13 -1
  30. package/dist/domain/models.d.ts +2 -0
  31. package/dist/domain/relations.d.ts +1 -0
  32. package/dist/domain/relations.js +5 -1
  33. package/dist/entities/contact-context.d.ts +3 -0
  34. package/dist/entities/contact-context.js +4 -0
  35. package/dist/entities/hit.d.ts +9 -2
  36. package/dist/entities/hit.js +6 -2
  37. package/dist/entities/index.d.ts +9 -1
  38. package/dist/errors/reasons.js +3 -0
  39. package/dist/meetings/hit-query.d.ts +1 -1
  40. package/dist/meetings/hit-query.js +2 -2
  41. package/dist/meetings/index.d.ts +1 -0
  42. package/dist/meetings/index.js +1 -0
  43. package/dist/meetings/store.d.ts +4 -0
  44. package/dist/meetings/store.js +2 -1
  45. package/dist/models/anthropic.js +5 -0
  46. package/dist/search/question-period.d.ts +10 -0
  47. package/dist/search/question-period.js +133 -0
  48. package/dist/sends/buttons.d.ts +2 -0
  49. package/dist/sends/buttons.js +6 -1
  50. package/dist/services/enrichment-setting.d.ts +6 -0
  51. package/dist/services/enrichment-setting.js +5 -1
  52. package/dist/services/enrichment.d.ts +5 -0
  53. package/dist/services/enrichment.js +1 -1
  54. package/dist/services/index.d.ts +4 -2
  55. package/dist/services/index.js +3 -1
  56. package/dist/services/messages.d.ts +1 -4
  57. package/dist/services/messages.js +0 -2
  58. package/dist/services/metadata.d.ts +1 -1
  59. package/dist/services/person-context.d.ts +3 -1
  60. package/dist/services/person-context.js +21 -8
  61. package/dist/services/person-preparation.d.ts +5 -1
  62. package/dist/services/person-preparation.js +10 -3
  63. package/dist/services/person-timeline.d.ts +6 -1
  64. package/dist/services/person-timeline.js +10 -2
  65. package/dist/services/search-all-deprecated.d.ts +40 -0
  66. package/dist/services/search-all-deprecated.js +10 -0
  67. package/dist/services/search-all-meetings.d.ts +50 -52
  68. package/dist/services/search-all-meetings.js +265 -272
  69. package/dist/services/search-all.d.ts +34 -6
  70. package/dist/services/search-all.js +119 -24
  71. package/dist/services/search-harder.d.ts +90 -0
  72. package/dist/services/search-harder.js +264 -0
  73. package/dist/store/chats.d.ts +3 -1
  74. package/dist/store/chats.js +6 -0
  75. package/dist/store/people.d.ts +6 -2
  76. package/dist/store/sqlite/added-sources.d.ts +15 -3
  77. package/dist/store/sqlite/added-sources.js +26 -5
  78. package/dist/store/sqlite/chats.d.ts +2 -0
  79. package/dist/store/sqlite/chats.js +6 -0
  80. package/dist/store/sqlite/involvements.d.ts +1 -1
  81. package/dist/store/sqlite/involvements.js +4 -2
  82. package/dist/store/sqlite/meeting-hit-query.d.ts +5 -0
  83. package/dist/store/sqlite/meeting-hit-query.js +33 -0
  84. package/dist/store/sqlite/meeting-hit-search.js +10 -8
  85. package/dist/store/sqlite/meetings.js +1 -1
  86. package/dist/store/sqlite/notes.d.ts +7 -0
  87. package/dist/store/sqlite/notes.js +23 -7
  88. package/dist/store/sqlite/person-preparation.d.ts +7 -3
  89. package/dist/store/sqlite/person-preparation.js +20 -6
  90. package/dist/store/sqlite/relation-list.js +4 -2
  91. package/dist/store/sqlite/reported-relations.d.ts +0 -1
  92. package/dist/store/sqlite/reported-relations.js +1 -4
  93. package/package.json +1 -1
  94. package/parity.json +26 -12
@@ -0,0 +1,264 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import * as v from "valibot";
3
+ import { modelGateway } from "../models/index.js";
4
+ import { readSharedSection, writeSharedSection } from "../store/shared-config.js";
5
+ import { keyLookup, keyVariable } from "./enrichment.js";
6
+ import { costOf, enrichmentEndpoint, enrichmentSettingPath, MODEL_CHOICE, } from "./enrichment-setting.js";
7
+ const SECTION = "search_harder";
8
+ /**
9
+ * Each provider's model when the owner names none: small and fast for a short answer. gpt-4o-mini, not a cheaper
10
+ * reasoning model, because the OpenAI adapter cannot turn reasoning down (pricing read 2026-11-09).
11
+ */
12
+ export const HARDER_MODELS = {
13
+ anthropic: "claude-haiku-5-5",
14
+ openai: "gpt-4o-mini",
15
+ };
16
+ /** The search lab's setup (cli-testing search-lab, "Haiku rerank"): the top 30, each cut to 400 characters. */
17
+ export const HARDER_CANDIDATES = 30;
18
+ export const HARDER_CHARS = 400;
19
+ const TIMEOUT_MS = 5_000;
20
+ const Setting = v.strictObject({
21
+ ...MODEL_CHOICE,
22
+ /** When the owner agreed that a `--harder` search sends its question and hits; the setting exists only with it. */
23
+ consented_at: v.pipe(v.string(), v.isoTimestamp()),
24
+ });
25
+ /** The owner's consent, or `undefined`: no section means `--harder` sends nothing. */
26
+ export const readHarderSetting = (env) => {
27
+ const path = enrichmentSettingPath(env);
28
+ const section = readSharedSection(path, SECTION);
29
+ if (section === undefined || section === null)
30
+ return undefined;
31
+ const checked = v.safeParse(Setting, section);
32
+ if (!checked.success)
33
+ throw new CliError("configuration_error", `${path}: ${SECTION}.${v.getDotPath(checked.issues[0]) ?? "settings"} is invalid — ${checked.issues[0].message}`);
34
+ return checked.output;
35
+ };
36
+ export const writeHarderSetting = (env, setting) => writeSharedSection(enrichmentSettingPath(env), SECTION, setting === undefined ? undefined : v.parse(Setting, setting));
37
+ export const HARDER_REASON_IDS = [
38
+ "harder.no-consent",
39
+ "harder.no-key",
40
+ "harder.bad-setting",
41
+ "harder.later-page",
42
+ "harder.too-few",
43
+ "harder.timeout",
44
+ "harder.key-rejected",
45
+ "harder.unreachable",
46
+ "harder.rate-limited",
47
+ "harder.bad-reply",
48
+ "harder.error",
49
+ ];
50
+ // The search lab's prompt, word for word, except that the records travel as the gateway's untrusted data.
51
+ const PROMPT = "Today is {as_of}. A person searches their own archive of messages, mails, notes, calendar entries and phone " +
52
+ "records with the question below. Here are {n} candidate records, numbered, in the data.\n\n" +
53
+ "Question: {question}\n\n" +
54
+ "Which records help answer the question? List their numbers, most useful first, at most ten; an empty list if " +
55
+ "none does.";
56
+ // Only Anthropic takes the schema; another provider is told the shape, and its answer is read leniently.
57
+ const JSON_SHAPE = '\n\nAnswer with JSON only, in the form {"records": [numbers]}.';
58
+ const FORMAT = {
59
+ type: "json_schema",
60
+ schema: {
61
+ type: "object",
62
+ properties: { records: { type: "array", items: { type: "integer" } } },
63
+ required: ["records"],
64
+ additionalProperties: false,
65
+ },
66
+ };
67
+ const Reply = v.object({ records: v.array(v.pipe(v.number(), v.integer())) });
68
+ /** The JSON in an answer, also when a model wraps it in a code block or a sentence. */
69
+ const jsonOf = (text) => {
70
+ try {
71
+ return JSON.parse(text);
72
+ }
73
+ catch {
74
+ const start = text.indexOf("{");
75
+ const end = text.lastIndexOf("}");
76
+ if (start < 0 || end <= start)
77
+ throw new Error("no JSON in the answer");
78
+ return JSON.parse(text.slice(start, end + 1));
79
+ }
80
+ };
81
+ const recordLine = (hit, i) => `[${i}] (${hit.timestamp?.slice(0, 10) ?? "undated"}) ${`${hit.title ? `${hit.title}\n` : ""}${hit.text.slice(0, HARDER_CHARS)}`.replace(/\s*\n\s*/g, " ")}`;
82
+ const REASON_TEXT = {
83
+ "harder.no-consent": "the owner has not agreed to send searches to a hosted model",
84
+ "harder.no-key": "no key for the provider",
85
+ "harder.bad-setting": "the search_harder setting cannot be read; nothing was sent",
86
+ "harder.later-page": "--harder reorders the first page only; nothing was sent",
87
+ "harder.too-few": "fewer than two hits to reorder; nothing was sent",
88
+ "harder.timeout": `the model did not answer within ${TIMEOUT_MS / 1000} s`,
89
+ "harder.key-rejected": "the provider refused the key",
90
+ "harder.unreachable": "the provider could not be reached",
91
+ "harder.rate-limited": "the provider's rate limit was reached",
92
+ "harder.bad-reply": "the model's answer could not be read",
93
+ "harder.error": "the provider failed",
94
+ };
95
+ const reasonOf = (error, timedOut) => {
96
+ if (timedOut)
97
+ return "harder.timeout";
98
+ if (!(error instanceof CliError))
99
+ return "harder.bad-reply";
100
+ if (error.details.reason === "model.key-rejected")
101
+ return "harder.key-rejected";
102
+ if (error.details.reason === "model.unreachable")
103
+ return "harder.unreachable";
104
+ if (error.code === "rate_limited")
105
+ return "harder.rate-limited";
106
+ return "harder.error";
107
+ };
108
+ const UNSET = {
109
+ provider: "anthropic",
110
+ model: HARDER_MODELS.anthropic,
111
+ endpoint: enrichmentEndpoint({ provider: "anthropic" }),
112
+ };
113
+ export const harderAccess = ({ env, command, ...options }) => {
114
+ let setting;
115
+ try {
116
+ setting = readHarderSetting(env);
117
+ }
118
+ catch (error) {
119
+ const unreadable = error instanceof CliError ? error.message : REASON_TEXT["harder.bad-setting"];
120
+ return { ready: false, ...UNSET, reason_id: "harder.bad-setting", reason: `${unreadable}; nothing was sent` };
121
+ }
122
+ const tool = command ?? "memo";
123
+ if (!setting)
124
+ return {
125
+ ready: false,
126
+ ...UNSET,
127
+ reason_id: "harder.no-consent",
128
+ reason: `${REASON_TEXT["harder.no-consent"]}: \`${tool} models search-consents set <provider> --yes\`; nothing was sent`,
129
+ };
130
+ const chosen = {
131
+ provider: setting.provider,
132
+ model: setting.model,
133
+ endpoint: enrichmentEndpoint(setting),
134
+ custom: setting.base_url !== undefined,
135
+ };
136
+ let key;
137
+ try {
138
+ key = keyLookup({ env, ...options }, setting)?.key;
139
+ }
140
+ catch {
141
+ return {
142
+ ready: false,
143
+ ...chosen,
144
+ reason_id: "harder.error",
145
+ reason: `the ${setting.provider} key could not be read; nothing was sent`,
146
+ };
147
+ }
148
+ // A server of the owner's own may need no key; the public API would answer 401 only after the question left.
149
+ if (key === undefined && !chosen.custom)
150
+ return {
151
+ ready: false,
152
+ ...chosen,
153
+ reason_id: "harder.no-key",
154
+ reason: `no ${setting.provider} key: \`${tool} models keys set ${setting.provider}\` or set ${keyVariable(setting.provider)}; nothing was sent`,
155
+ };
156
+ return { ready: true, ...chosen, ...(key === undefined ? {} : { key }) };
157
+ };
158
+ /** One call to the model under the 5 s limit; a failure comes back as its reason, never thrown. */
159
+ const ask = async (access, options, request) => {
160
+ const limit = new AbortController();
161
+ const timer = setTimeout(() => limit.abort(), options.timeoutMs ?? TIMEOUT_MS);
162
+ const gateway = modelGateway({
163
+ resolve: () => ({ provider: access.provider, model: access.model, baseUrl: access.endpoint }),
164
+ consent: (_request, chosen) => chosen.provider === access.provider && chosen.baseUrl === access.endpoint,
165
+ key: () => access.key,
166
+ signal: limit.signal,
167
+ ...(options.adapters ? { adapters: options.adapters } : {}),
168
+ ...(options.fetch ? { fetch: options.fetch } : {}),
169
+ });
170
+ const { format, ...rest } = request;
171
+ // Each adapter refuses options it does not know, so Anthropic's never reach another provider.
172
+ const settings = access.provider === "anthropic"
173
+ ? { thinking: { type: "disabled" }, output_config: { effort: "low", ...(format ? { format } : {}) } }
174
+ : access.custom
175
+ ? undefined
176
+ : { temperature: 0, ...(format ? { response_format: { type: "json_object" } } : {}) };
177
+ try {
178
+ const answer = await gateway.complete({
179
+ ...rest,
180
+ ...(format && access.provider !== "anthropic" ? { prompt: `${rest.prompt}${JSON_SHAPE}` } : {}),
181
+ ...(settings ? { options: settings } : {}),
182
+ });
183
+ const cost = costOf(answer.usage ?? { input: answer.tokens, output: 0 }, {
184
+ provider: access.provider,
185
+ model: access.model,
186
+ ...(access.custom ? { base_url: access.endpoint } : {}),
187
+ });
188
+ return { text: answer.text, cost };
189
+ }
190
+ catch (error) {
191
+ return { reason_id: reasonOf(error, limit.signal.aborted) };
192
+ }
193
+ finally {
194
+ clearTimeout(timer);
195
+ }
196
+ };
197
+ /**
198
+ * `search all --harder`: a hosted model reads the question with the first 30 hits and puts the ones that answer it
199
+ * first. Any failure keeps the plain order and says why; it never fails the search. Without the owner's consent or a
200
+ * key nothing is sent.
201
+ */
202
+ export const reorderHarder = async (question, hits, { laterPage, access: given, ...asking }) => {
203
+ const started = Date.now();
204
+ const access = laterPage ? undefined : (given ?? harderAccess(asking));
205
+ const plain = (reason_id, extra = {}, reason = REASON_TEXT[reason_id]) => ({
206
+ items: [...hits],
207
+ harder: {
208
+ applied: false,
209
+ provider: (access ?? UNSET).provider,
210
+ model: (access ?? UNSET).model,
211
+ endpoint: (access ?? UNSET).endpoint,
212
+ sent: 0,
213
+ cost_usd: 0,
214
+ ms: Date.now() - started,
215
+ ...extra,
216
+ reason,
217
+ reason_id,
218
+ },
219
+ });
220
+ if (!access)
221
+ return plain("harder.later-page");
222
+ if (!access.ready)
223
+ return plain(access.reason_id, {}, access.reason);
224
+ const candidates = hits.slice(0, HARDER_CANDIDATES);
225
+ if (candidates.length < 2)
226
+ return plain("harder.too-few");
227
+ const sent = { sent: candidates.length };
228
+ const answer = await ask(access, asking, {
229
+ purpose: "search-harder",
230
+ prompt: PROMPT.replace("{as_of}", new Date(asking.now).toISOString().slice(0, 10))
231
+ .replace("{n}", String(candidates.length))
232
+ .replace("{question}", () => question),
233
+ data: candidates.map(recordLine).join("\n"),
234
+ maxTokens: 300,
235
+ format: FORMAT,
236
+ });
237
+ if ("reason_id" in answer)
238
+ return plain(answer.reason_id, { ...sent, cost_usd: null });
239
+ let picked;
240
+ try {
241
+ picked = v.parse(Reply, jsonOf(answer.text)).records;
242
+ }
243
+ catch {
244
+ return plain("harder.bad-reply", { ...sent, cost_usd: answer.cost });
245
+ }
246
+ const first = [...new Set(picked.filter((i) => i >= 0 && i < candidates.length))];
247
+ const chosen = new Set(first);
248
+ return {
249
+ items: [
250
+ ...first.map((i) => candidates[i]),
251
+ ...candidates.filter((_, i) => !chosen.has(i)),
252
+ ...hits.slice(HARDER_CANDIDATES),
253
+ ],
254
+ harder: {
255
+ applied: true,
256
+ provider: access.provider,
257
+ model: access.model,
258
+ endpoint: access.endpoint,
259
+ ...sent,
260
+ cost_usd: answer.cost,
261
+ ms: Date.now() - started,
262
+ },
263
+ };
264
+ };
@@ -7,7 +7,7 @@ import type { ChatCompleteness, ChatCoverage } from "./sqlite/completeness.js";
7
7
  import type { ChatHistoryShape, StoredHistorySkip } from "./sqlite/history-skips.js";
8
8
  import type { StoreContext } from "./sqlite/open.js";
9
9
  import type { Where } from "./sqlite/query-filter.js";
10
- import type { AccountKey, ChatActivity, ChatStats, StoredChatFilter } from "./types.js";
10
+ import type { AccountKey, ChatActivity, ChatStats, StoredAccount, StoredChatFilter } from "./types.js";
11
11
  export type { LeftChat };
12
12
  /** The chats marked left: how many, the messages they hold, and each one. */
13
13
  export interface LeftChats {
@@ -25,6 +25,8 @@ export interface ChatsStore {
25
25
  countChats(key: AccountKey, filter?: StoredChatFilter): Promise<number>;
26
26
  /** The chats a person is in, newest first — as far as the saved member lists go. */
27
27
  chatsWith(key: AccountKey, memberId: Id): Promise<Chat[]>;
28
+ /** Each stored chat's scope, its own or else its account's; a chat the store lacks is left out. */
29
+ chatScopes(key: AccountKey, chatIds: readonly Id[]): Promise<Map<Id, StoredAccount["scope"]>>;
28
30
  /**
29
31
  * Given every chat the account is in, marks the rest `left`, takes the mark off those it names, and says how many
30
32
  * it marked. Only ever from a complete list: a page or a cut list says nothing about the chats it leaves out.
@@ -31,6 +31,12 @@ export const chatsStoreOver = (context) => {
31
31
  const accountKey = findAccountPk(key);
32
32
  return accountKey === undefined ? [] : chatQueries.chatsWith(context, accountKey, key, memberId);
33
33
  },
34
+ chatScopes: async (key, chatIds) => {
35
+ const accountKey = findAccountPk(key);
36
+ return accountKey === undefined
37
+ ? new Map()
38
+ : chatQueries.chatScopes(context, accountKey, chatIds);
39
+ },
34
40
  markChatsLeft: async (key, present) => {
35
41
  const accountKey = findAccountPk(key);
36
42
  if (accountKey === undefined)
@@ -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`. */