@wirecat/cli-core 0.661.0 → 0.663.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 (201) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/cli/bodies.js +2 -1
  4. package/dist/calendar/cli/index.js +13 -10
  5. package/dist/calendar/mcp/index.d.ts +3 -1
  6. package/dist/calendar/mcp/index.js +4 -4
  7. package/dist/cli/ai-model-command.js +3 -3
  8. package/dist/cli/call-stats-command.d.ts +18 -0
  9. package/dist/cli/call-stats-command.js +52 -0
  10. package/dist/cli/command-availability.d.ts +1 -1
  11. package/dist/cli/command-availability.js +4 -4
  12. package/dist/cli/contract-templates.js +2 -0
  13. package/dist/cli/dry-run-guard.js +7 -5
  14. package/dist/cli/early-refusal.d.ts +1 -1
  15. package/dist/cli/early-refusal.js +2 -2
  16. package/dist/cli/effects.d.ts +9 -2
  17. package/dist/cli/effects.js +16 -4
  18. package/dist/cli/envelope.d.ts +0 -5
  19. package/dist/cli/envelope.js +25 -0
  20. package/dist/cli/index.d.ts +3 -2
  21. package/dist/cli/index.js +3 -2
  22. package/dist/cli/meeting-batch.d.ts +2 -1
  23. package/dist/cli/meeting-batch.js +7 -5
  24. package/dist/cli/meeting-preparation-command.js +5 -5
  25. package/dist/cli/meeting-preparation-read.d.ts +5 -5
  26. package/dist/cli/meeting-preparation-read.js +13 -21
  27. package/dist/cli/meeting-series-inventory-command.js +2 -2
  28. package/dist/cli/meeting-series-inventory-read.d.ts +2 -2
  29. package/dist/cli/meeting-series-inventory-read.js +7 -15
  30. package/dist/cli/messenger/admin-moderation-command.js +2 -2
  31. package/dist/cli/messenger/admin-statistics-command.js +2 -2
  32. package/dist/cli/messenger/archive-commands.js +2 -2
  33. package/dist/cli/messenger/context.d.ts +2 -2
  34. package/dist/cli/messenger/context.js +5 -3
  35. package/dist/cli/messenger/counters-command.js +2 -2
  36. package/dist/cli/messenger/media-archive-command.js +5 -4
  37. package/dist/cli/messenger/media-archive-move-command.js +1 -1
  38. package/dist/cli/messenger/media-archive-timer-command.js +5 -4
  39. package/dist/cli/messenger/metadata-command.js +3 -3
  40. package/dist/cli/messenger/rankings-command.js +3 -3
  41. package/dist/cli/messenger/tags-command.js +7 -2
  42. package/dist/cli/messenger/tasks-command.js +4 -3
  43. package/dist/cli/paging.d.ts +10 -0
  44. package/dist/cli/paging.js +29 -0
  45. package/dist/cli/preview.js +3 -5
  46. package/dist/cli/program.js +2 -2
  47. package/dist/cli/runs/command.js +6 -4
  48. package/dist/cli/runs/search-command.js +9 -5
  49. package/dist/cli/schedule/schedule-command.js +1 -5
  50. package/dist/cli/shadowed-options.d.ts +7 -0
  51. package/dist/cli/shadowed-options.js +26 -0
  52. package/dist/crm/cli/index.js +4 -2
  53. package/dist/domain/moment.d.ts +29 -0
  54. package/dist/domain/moment.js +58 -0
  55. package/dist/domain/providers.d.ts +6 -4
  56. package/dist/domain/providers.js +10 -5
  57. package/dist/domain/send-time.d.ts +3 -4
  58. package/dist/domain/send-time.js +10 -24
  59. package/dist/entities/fields.d.ts +2 -2
  60. package/dist/entities/fields.js +2 -2
  61. package/dist/entities/index.d.ts +92 -1
  62. package/dist/entities/index.js +3 -2
  63. package/dist/entities/meeting.d.ts +1 -1
  64. package/dist/entities/meeting.js +1 -1
  65. package/dist/errors/reasons.js +0 -1
  66. package/dist/kit/sync-after-install.d.ts +10 -1
  67. package/dist/kit/sync-after-install.js +35 -11
  68. package/dist/mail/cli/index.js +4 -2
  69. package/dist/mail/facts.d.ts +5 -2
  70. package/dist/mail/facts.js +6 -3
  71. package/dist/mail/index.d.ts +1 -1
  72. package/dist/mail/meeting-notes.js +1 -1
  73. package/dist/mail/probe.d.ts +5 -2
  74. package/dist/mail/probe.js +9 -5
  75. package/dist/mail/server-search.js +4 -4
  76. package/dist/mail/sync.js +1 -1
  77. package/dist/mcp/meeting-preparation.js +1 -1
  78. package/dist/mcp/meeting-series-inventory.js +1 -1
  79. package/dist/mcp/prompts.js +6 -9
  80. package/dist/mcp/server.js +4 -4
  81. package/dist/mcp/tool.js +3 -3
  82. package/dist/meetings/call-answers.d.ts +106 -0
  83. package/dist/meetings/call-answers.js +171 -0
  84. package/dist/meetings/call-stats.d.ts +121 -0
  85. package/dist/meetings/call-stats.js +211 -0
  86. package/dist/meetings/calls.d.ts +76 -0
  87. package/dist/meetings/calls.js +78 -0
  88. package/dist/meetings/cli/index.d.ts +8 -0
  89. package/dist/meetings/cli/index.js +10 -22
  90. package/dist/meetings/cli/search.d.ts +9 -2
  91. package/dist/meetings/cli/search.js +16 -26
  92. package/dist/meetings/index.d.ts +3 -0
  93. package/dist/meetings/index.js +3 -0
  94. package/dist/meetings/mcp/index.d.ts +21 -18
  95. package/dist/meetings/mcp/index.js +2 -4
  96. package/dist/meetings/mcp/search.d.ts +6 -1
  97. package/dist/meetings/mcp/search.js +3 -3
  98. package/dist/meetings/read-through.d.ts +2 -1
  99. package/dist/meetings/read-through.js +10 -1
  100. package/dist/meetings/stats.d.ts +3 -0
  101. package/dist/meetings/stats.js +3 -3
  102. package/dist/meetings/testing/index.d.ts +1 -0
  103. package/dist/meetings/testing/index.js +1 -0
  104. package/dist/meetings/testing/paging.d.ts +6 -0
  105. package/dist/meetings/testing/paging.js +5 -0
  106. package/dist/moderation/rules.d.ts +2 -0
  107. package/dist/moderation/rules.js +16 -2
  108. package/dist/search/fusion.d.ts +17 -0
  109. package/dist/search/fusion.js +17 -0
  110. package/dist/search/lucene/resolved.d.ts +2 -0
  111. package/dist/search/question-plan.d.ts +2 -0
  112. package/dist/search/question-plan.js +5 -0
  113. package/dist/search/service-query.d.ts +6 -1
  114. package/dist/search/service-query.js +9 -1
  115. package/dist/sends/guard.js +4 -20
  116. package/dist/sends/keyed-guard.d.ts +1 -1
  117. package/dist/sends/keyed-guard.js +2 -1
  118. package/dist/sends/permissions.d.ts +14 -0
  119. package/dist/sends/permissions.js +32 -0
  120. package/dist/services/agenda-mail.js +2 -1
  121. package/dist/services/agenda.js +5 -3
  122. package/dist/services/attachments.js +4 -2
  123. package/dist/services/call-stats.d.ts +17 -0
  124. package/dist/services/call-stats.js +41 -0
  125. package/dist/services/chats.js +4 -2
  126. package/dist/services/conversations.js +4 -2
  127. package/dist/services/deps.d.ts +1 -1
  128. package/dist/services/document-source.d.ts +1 -1
  129. package/dist/services/document-source.js +4 -3
  130. package/dist/services/documents/ingestion.js +11 -40
  131. package/dist/services/documents/plan.d.ts +1 -1
  132. package/dist/services/documents/plan.js +30 -17
  133. package/dist/services/documents/ports.d.ts +5 -0
  134. package/dist/services/documents/sync.js +1 -1
  135. package/dist/services/embeddings-search.js +20 -4
  136. package/dist/services/events-search.js +2 -1
  137. package/dist/services/index.d.ts +1 -0
  138. package/dist/services/index.js +1 -0
  139. package/dist/services/mail-search.d.ts +1 -1
  140. package/dist/services/mail-search.js +10 -11
  141. package/dist/services/media-archive-move.js +2 -4
  142. package/dist/services/media-archive.d.ts +0 -1
  143. package/dist/services/media-archive.js +2 -12
  144. package/dist/services/meeting-combined.js +1 -1
  145. package/dist/services/messages-combined.js +15 -4
  146. package/dist/services/moderation.js +10 -2
  147. package/dist/services/moment.d.ts +4 -10
  148. package/dist/services/moment.js +16 -44
  149. package/dist/services/notes-search.d.ts +0 -2
  150. package/dist/services/notes-search.js +1 -2
  151. package/dist/services/search-all.js +2 -1
  152. package/dist/services/server-search.js +1 -1
  153. package/dist/services/tags.js +4 -2
  154. package/dist/services/task-stats.js +2 -2
  155. package/dist/services/tasks.js +2 -2
  156. package/dist/store/accounts.js +2 -1
  157. package/dist/store/sqlite/account-purge.d.ts +3 -0
  158. package/dist/store/sqlite/account-purge.js +143 -0
  159. package/dist/store/sqlite/accounts.d.ts +0 -2
  160. package/dist/store/sqlite/accounts.js +2 -134
  161. package/dist/store/sqlite/calendar.d.ts +1 -0
  162. package/dist/store/sqlite/calendar.js +5 -5
  163. package/dist/store/sqlite/catalog.js +2 -16
  164. package/dist/store/sqlite/chats.js +2 -1
  165. package/dist/store/sqlite/context-document-source.d.ts +3 -3
  166. package/dist/store/sqlite/context-document-source.js +9 -7
  167. package/dist/store/sqlite/context-evidence.js +9 -3
  168. package/dist/store/sqlite/document-listing.js +2 -1
  169. package/dist/store/sqlite/events.js +2 -1
  170. package/dist/store/sqlite/file-note.d.ts +6 -0
  171. package/dist/store/sqlite/file-note.js +15 -0
  172. package/dist/store/sqlite/files.d.ts +3 -2
  173. package/dist/store/sqlite/files.js +5 -3
  174. package/dist/store/sqlite/identities.js +2 -1
  175. package/dist/store/sqlite/imported-documents.js +2 -2
  176. package/dist/store/sqlite/knowledge.js +19 -19
  177. package/dist/store/sqlite/lucene-fields.js +8 -12
  178. package/dist/store/sqlite/mail-rules.js +2 -1
  179. package/dist/store/sqlite/meeting-calls.d.ts +4 -0
  180. package/dist/store/sqlite/meeting-calls.js +66 -0
  181. package/dist/store/sqlite/meetings.d.ts +2 -2
  182. package/dist/store/sqlite/meetings.js +4 -1
  183. package/dist/store/sqlite/mention-sources.js +2 -1
  184. package/dist/store/sqlite/mentions.js +2 -2
  185. package/dist/store/sqlite/messages.js +6 -1
  186. package/dist/store/sqlite/note-search.js +8 -11
  187. package/dist/store/sqlite/notes.d.ts +2 -0
  188. package/dist/store/sqlite/notes.js +24 -13
  189. package/dist/store/sqlite/organizations.js +2 -2
  190. package/dist/store/sqlite/people-list.js +3 -3
  191. package/dist/store/sqlite/query-filter.d.ts +3 -3
  192. package/dist/store/sqlite/query-filter.js +3 -3
  193. package/dist/store/sqlite/reads.d.ts +4 -4
  194. package/dist/store/sqlite/reads.js +4 -4
  195. package/dist/store/sqlite/search.js +11 -7
  196. package/dist/store/sqlite/test-accounts.js +1 -1
  197. package/dist/store/sqlite/trigram-match.d.ts +9 -0
  198. package/dist/store/sqlite/trigram-match.js +28 -0
  199. package/dist/store/sqlite/work-tasks.js +1 -1
  200. package/package.json +3 -3
  201. package/parity.json +2 -1
@@ -1,9 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError } from "@wirecat/cli-base";
3
3
  import { inScope, within } from "../../documents/scope.js";
4
- // Without a query the hash stays what it was, so a profile that never set one keeps its checkpoint.
5
- export const scopeHash = (roots, query) => createHash("sha256")
6
- .update(JSON.stringify(query ? [[...roots].sort(), query.mode, query.key] : [...roots].sort()))
4
+ // Without a query or pages the hash stays what it was, so a profile that never set them keeps its checkpoint. Turning
5
+ // pages on changes it, so the next sync walks again and imports the pages an incremental one would never revisit.
6
+ export const scopeHash = (roots, query, pages = false) => createHash("sha256")
7
+ .update(JSON.stringify(query || pages ? [[...roots].sort(), query?.mode, query?.key, ...(pages ? ["pages"] : [])] : [...roots].sort()))
7
8
  .digest("hex");
8
9
  export const changedSince = (previous, file) => previous.version !== file.version ||
9
10
  previous.modifiedAt !== file.modifiedAt ||
@@ -14,7 +15,7 @@ const SAVE_EVERY_MS = 2000;
14
15
  export const planDocuments = async (options, source, state, roots, limit, pictures, abandoned = [], walks) => {
15
16
  const { isFolder, skipReason, retryable, maxEntries: MAX_ENTRIES, errorOf, query } = options;
16
17
  const tooManyEntries = () => options.limitError?.() ?? new CliError("validation_error", `selected folders exceed the ${MAX_ENTRIES} entry limit`);
17
- const scope = scopeHash(roots, query);
18
+ const scope = scopeHash(roots, query, options.isDocument !== undefined);
18
19
  if (!roots.length && query?.mode !== "include")
19
20
  return {
20
21
  scope,
@@ -38,6 +39,14 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
38
39
  for (const skipped of state.skipped)
39
40
  if (skipped.file)
40
41
  files.set(skipped.id, skipped.file);
42
+ const keep = (file) => {
43
+ files.set(file.id, file);
44
+ changed.add(file.id);
45
+ };
46
+ const container = (file) => {
47
+ if (options.isDocument?.(file))
48
+ keep(file);
49
+ };
41
50
  const visited = new Set();
42
51
  let discovered = 0;
43
52
  const crawl = async (folder, ancestry = new Set()) => {
@@ -50,12 +59,12 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
50
59
  for (const file of await source.children(folder.id)) {
51
60
  if (++discovered > MAX_ENTRIES)
52
61
  throw tooManyEntries();
53
- if (isFolder(file))
62
+ if (isFolder(file)) {
63
+ container(file);
54
64
  await crawl(file, new Set([...ancestry, folder.id]));
55
- else {
56
- files.set(file.id, file);
57
- changed.add(file.id);
58
65
  }
66
+ else
67
+ keep(file);
59
68
  }
60
69
  };
61
70
  let finalCursor = cursor;
@@ -94,6 +103,8 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
94
103
  const folder = step.folder ?? (await source.metadata(step.id));
95
104
  if (!step.folder && (!isFolder(folder) || folder.trashed))
96
105
  throw new CliError("validation_error", "configured root is not an accessible folder");
106
+ if (!step.folder)
107
+ container(folder);
97
108
  const children = await source.children(folder.id);
98
109
  if (discovered + children.length > MAX_ENTRIES)
99
110
  throw tooManyEntries();
@@ -103,12 +114,12 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
103
114
  folders[folder.id] = folder;
104
115
  const nested = [];
105
116
  for (const file of children)
106
- if (isFolder(file))
117
+ if (isFolder(file)) {
118
+ container(file);
107
119
  nested.push({ id: file.id, ancestry: [...step.ancestry, folder.id], folder: file });
108
- else {
109
- files.set(file.id, file);
110
- changed.add(file.id);
111
120
  }
121
+ else
122
+ keep(file);
112
123
  for (const entry of nested.reverse())
113
124
  walk.stack.push(entry);
114
125
  if ((options.now ?? Date.now)() - savedAt > SAVE_EVERY_MS)
@@ -135,11 +146,10 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
135
146
  else if (change.file && isFolder(change.file)) {
136
147
  folders[change.id] = change.file;
137
148
  entering.push(change.file);
149
+ container(change.file);
138
150
  }
139
- else if (change.file) {
140
- files.set(change.id, change.file);
141
- changed.add(change.id);
142
- }
151
+ else if (change.file)
152
+ keep(change.file);
143
153
  else if (state.documents[change.id] || folders[change.id])
144
154
  throw new CliError("invalid_response", "known source changed without metadata; checkpoint preserved");
145
155
  }
@@ -167,7 +177,10 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
167
177
  }
168
178
  const matched = new Set();
169
179
  for (const file of found) {
170
- if (isFolder(file) || file.trashed || !query?.matches(file) || matched.has(file.id))
180
+ if ((isFolder(file) && !options.isDocument?.(file)) ||
181
+ file.trashed ||
182
+ !query?.matches(file) ||
183
+ matched.has(file.id))
171
184
  continue;
172
185
  if (!files.has(file.id) && ++discovered > MAX_ENTRIES)
173
186
  throw tooManyEntries();
@@ -13,6 +13,11 @@ export interface SyncOptions<M extends SourceFile> {
13
13
  maxEntries: number;
14
14
  limitError?(): CliError;
15
15
  isFolder(file: M): boolean;
16
+ /**
17
+ * A folder that is a document too, such as a wiki page with sub-pages: walked for its children and imported
18
+ * itself. Left out, no folder is imported.
19
+ */
20
+ isDocument?(file: M): boolean;
16
21
  skipReason(file: M): string | undefined;
17
22
  retryable(skip: SourceSkip<M>, limit: number): boolean;
18
23
  errorOf(error: unknown): CliError;
@@ -43,7 +43,7 @@ export const syncDocuments = async (options) => {
43
43
  const state = statePort.read();
44
44
  if (state.principal !== principal)
45
45
  throw new CliError("configuration_error", "sync state belongs to another source account");
46
- const currentScope = scopeHash(profile.roots, query);
46
+ const currentScope = scopeHash(profile.roots, query, options.isDocument !== undefined);
47
47
  const abandoned = state.pending && (state.pending.scope !== currentScope || rescan) ? state.pending.jobs.map((job) => job.id) : [];
48
48
  if (state.pending?.scope !== currentScope || rescan)
49
49
  delete state.pending;
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { formatLocator, parseLocator } from "../domain/locator.js";
3
3
  import { meaningFloor } from "../embeddings/models.js";
4
+ import { fuseRanked } from "../search/fusion.js";
4
5
  import { QUERY_LIMITS, searchError } from "../search/lucene/types.js";
5
6
  import { threadConversation } from "../store/store.js";
6
7
  import { embeddingsMaintenance, embeddingTarget, isStale, notBuiltError, readinessOf, shaped, withEmbedder, } from "./embeddings-maintenance.js";
@@ -59,9 +60,18 @@ export const embeddingsSearch = (deps) => {
59
60
  });
60
61
  outside.set(JSON.stringify(account), { account, chats });
61
62
  }
62
- const ranked = items.flatMap(({ id, score }, index) => {
63
+ let ranked = items.flatMap(({ id, score, timestamp }, index) => {
63
64
  const summary = summaries.get(index);
64
- return summary ? [{ summary, chunk: { firstMessageId: id, lastMessageId: id }, score }] : [];
65
+ return summary
66
+ ? [
67
+ {
68
+ summary,
69
+ chunk: { firstMessageId: id, lastMessageId: id },
70
+ ranked: score !== null,
71
+ at: Date.parse(timestamp),
72
+ },
73
+ ]
74
+ : [];
65
75
  });
66
76
  // Mail in its own tables has no conversations: each email answers as its thread, ranked with the messages.
67
77
  const mailAccounts = prepared.scopeAccounts.filter(({ provider }) => provider === MAIL);
@@ -78,6 +88,7 @@ export const embeddingsSearch = (deps) => {
78
88
  return { items: [] };
79
89
  throw error;
80
90
  });
91
+ const emails = [];
81
92
  for (const account of mailAccounts) {
82
93
  const found = mail.items.filter((hit) => {
83
94
  const at = parseLocator(hit.locator);
@@ -93,10 +104,15 @@ export const embeddingsSearch = (deps) => {
93
104
  continue;
94
105
  const summary = threadConversation(place, Date.now());
95
106
  sources.set(summary.id, account);
96
- ranked.push({ summary, chunk: { firstMessageId: hit.id, lastMessageId: hit.id }, score: hit.score });
107
+ emails.push({
108
+ summary,
109
+ chunk: { firstMessageId: hit.id, lastMessageId: hit.id },
110
+ ranked: hit.score !== null,
111
+ at: Date.parse(hit.timestamp),
112
+ });
97
113
  }
98
114
  }
99
- ranked.sort((a, b) => (b.score ?? Number.NEGATIVE_INFINITY) - (a.score ?? Number.NEGATIVE_INFINITY));
115
+ ranked = fuseRanked([ranked, emails], (one) => one);
100
116
  }
101
117
  const seen = new Set();
102
118
  const hits = ranked.flatMap(({ summary, chunk }) => {
@@ -1,11 +1,12 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { holdsKind } from "../domain/providers.js";
3
3
  import { meaningFloor } from "../embeddings/models.js";
4
+ import { RRF_K } from "../search/fusion.js";
4
5
  import { plainQuery } from "../search/lucene/plain.js";
5
6
  import { questionLookup, questionText } from "../search/question-plan.js";
6
7
  import { excerpt } from "./excerpt.js";
7
8
  import { meaningModel } from "./meaning-model.js";
8
- import { localModel, RRF_K, storeQuery, withLocal } from "./notes-search.js";
9
+ import { localModel, storeQuery, withLocal } from "./notes-search.js";
9
10
  import { plainQueryWords } from "./notes-title-tier.js";
10
11
  const MAX_EVENTS_OFFSET = 1000;
11
12
  const iso = (at) => (at === null ? null : new Date(at).toISOString());
@@ -68,6 +68,7 @@ export type { AttachmentItem, AttachmentsService, AttachmentTextSet, ExtractItem
68
68
  export { attachmentsService } from "./attachments.js";
69
69
  export type { Category, Coverage, Related, RelationRole, Section } from "./business-context.js";
70
70
  export { CATEGORIES, organizationCategories, SECTION_LIMIT } from "./business-context.js";
71
+ export { type CallStatsAnswer, type CallStatsRequest, readCallStats } from "./call-stats.js";
71
72
  export type { ChatsService, MarkedRead, PageWindow } from "./chats.js";
72
73
  export { chatsService, EVENTS_DAYS } from "./chats.js";
73
74
  export type { Communications, Touch } from "./communications.js";
@@ -53,6 +53,7 @@ export { adminService } from "./admin.js";
53
53
  export { archiveService } from "./archive.js";
54
54
  export { attachmentsService } from "./attachments.js";
55
55
  export { CATEGORIES, organizationCategories, SECTION_LIMIT } from "./business-context.js";
56
+ export { readCallStats } from "./call-stats.js";
56
57
  export { chatsService, EVENTS_DAYS } from "./chats.js";
57
58
  export { BATCH_SIZE, conversationsService } from "./conversations.js";
58
59
  export { dealBrief, dealContext } from "./deal-context.js";
@@ -6,7 +6,7 @@ import type { MessageStore, ScoredHit, StoredHit } from "../store/store.js";
6
6
  */
7
7
  export declare const withMailThreads: (store: MessageStore) => MessageStore;
8
8
  /**
9
- * One page from mail stored as messages and mail in its own tables, in the order one search gives. An email
9
+ * One page from mail stored as messages and mail in its own tables, two word indexes fused by rank (`fuseRanked`). An email
10
10
  * imported again into the mail tables keeps its locator, so its older message copy is dropped.
11
11
  */
12
12
  export declare const mergeMail: (messages: Page<ScoredHit>, mail: Page<ScoredHit>, limit: number, newest?: boolean) => Page<ScoredHit>;
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { parseLocator } from "../domain/locator.js";
3
+ import { fuseRanked } from "../search/fusion.js";
3
4
  import { messageOfEmail } from "../store/store.js";
4
5
  const THREADS_PAGE = 500;
5
6
  const threadsOf = async (store, key) => {
@@ -41,22 +42,20 @@ export const withMailThreads = (store) => {
41
42
  get: (target, key, receiver) => (key === "chats" ? chats : Reflect.get(target, key, receiver)),
42
43
  });
43
44
  };
44
- const before = (newest) => (a, b) => {
45
- if (!newest) {
46
- if ((a.exact ?? false) !== (b.exact ?? false))
47
- return a.exact ? -1 : 1;
48
- if (a.score !== b.score)
49
- return a.score === null ? 1 : b.score === null ? -1 : b.score - a.score;
50
- }
51
- return b.timestamp.localeCompare(a.timestamp);
52
- };
53
45
  /**
54
- * One page from mail stored as messages and mail in its own tables, in the order one search gives. An email
46
+ * One page from mail stored as messages and mail in its own tables, two word indexes fused by rank (`fuseRanked`). An email
55
47
  * imported again into the mail tables keeps its locator, so its older message copy is dropped.
56
48
  */
57
49
  export const mergeMail = (messages, mail, limit, newest = false) => {
58
50
  const moved = new Set(mail.items.map(({ locator }) => locator));
59
- const items = [...messages.items.filter(({ locator }) => !moved.has(locator)), ...mail.items].sort(before(newest));
51
+ const kept = messages.items.filter(({ locator }) => !moved.has(locator));
52
+ const items = newest
53
+ ? [...kept, ...mail.items].sort((a, b) => b.timestamp.localeCompare(a.timestamp))
54
+ : fuseRanked([kept, mail.items], (hit) => ({
55
+ exact: hit.exact,
56
+ ranked: hit.score !== null,
57
+ at: Date.parse(hit.timestamp),
58
+ }));
60
59
  return {
61
60
  items: items.slice(0, limit),
62
61
  hasMore: messages.hasMore || mail.hasMore || items.length > limit,
@@ -2,10 +2,10 @@ import { realpath, unlink } from "node:fs/promises";
2
2
  import { basename, dirname, join, resolve } from "node:path";
3
3
  import { CliError } from "@wirecat/cli-base";
4
4
  import { openOrdinaryFile, sameOrdinaryFile, syncDirectory, writeFileAtomic } from "../files/index.js";
5
- import { validateMediaSince } from "./media-archive.js";
6
5
  import { archiveMediaFile } from "./media-archive-files.js";
7
6
  import { withMediaArchiveLocks } from "./media-archive-locks.js";
8
7
  import { mediaFingerprint, mediaKey, mediaManifestName, missingMediaFile, parseMediaEntry, readMediaManifests, sameMediaCopy, verifyMediaEntry, } from "./media-archive-manifest.js";
8
+ import { momentOf } from "./moment.js";
9
9
  const canonicalDestination = async (directory) => {
10
10
  const path = resolve(directory);
11
11
  try {
@@ -48,9 +48,7 @@ const removeLocalCopy = async (root, entry, beforeWrite, signal) => {
48
48
  };
49
49
  /** The destination is durable before a source relocation record is published, then the verified local copy is removed. */
50
50
  export const moveMediaArchive = async (options) => {
51
- const cutoff = validateMediaSince(options.beforeTime, "--before-time");
52
- if (cutoff === undefined)
53
- throw new CliError("validation_error", "--before-time is required");
51
+ const cutoff = momentOf(options.beforeTime, "--before-time");
54
52
  const target = await canonicalDestination(options.archiveDirectory);
55
53
  const source = await realpath(options.directory);
56
54
  if (source === target)
@@ -15,7 +15,6 @@ export interface MediaArchiveOptions {
15
15
  signal?: AbortSignal;
16
16
  onSaved?: (entry: MediaArchiveEntry) => void;
17
17
  }
18
- export declare const validateMediaSince: (value?: string, flag?: string) => number | undefined;
19
18
  export declare const checkMediaArchive: (directory: string, signal?: AbortSignal) => Promise<{
20
19
  valid: boolean;
21
20
  checked: number;
@@ -4,17 +4,7 @@ import { matchDownloads, NOT_FILES } from "../domain/attachments.js";
4
4
  import { archiveMediaFile } from "./media-archive-files.js";
5
5
  import { withMediaArchiveLocks } from "./media-archive-locks.js";
6
6
  import { mediaKey, readMediaManifests, verifyMediaEntry } from "./media-archive-manifest.js";
7
- export const validateMediaSince = (value, flag = "--since-time") => {
8
- if (value === undefined)
9
- return undefined;
10
- if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?(?:Z|[+-]\d\d:\d\d)$/.test(value) ||
11
- !Number.isFinite(Date.parse(value)))
12
- throw new CliError("validation_error", `${flag} needs an ISO timestamp with a time zone`);
13
- const date = value.slice(0, 10);
14
- if (new Date(`${date}T00:00:00Z`).toISOString().slice(0, 10) !== date)
15
- throw new CliError("validation_error", `${flag} has an invalid calendar date`);
16
- return Date.parse(value);
17
- };
7
+ import { momentOf } from "./moment.js";
18
8
  export const checkMediaArchive = (directory, signal) => withMediaArchiveLocks(directory, signal, async (root) => {
19
9
  const entries = await readMediaManifests(root, signal);
20
10
  if (!entries.length)
@@ -66,7 +56,7 @@ const saveMessage = async (root, account, message, ports, known, beforeWrite, op
66
56
  return { saved, existing };
67
57
  };
68
58
  export const archiveMedia = async (ports, options) => {
69
- const since = validateMediaSince(options.sinceTime);
59
+ const since = options.sinceTime === undefined ? undefined : momentOf(options.sinceTime, "--since-time");
70
60
  const pageSize = options.pageSize ?? 100;
71
61
  const pauseMs = options.pauseMs ?? 1000;
72
62
  if (!Number.isSafeInteger(pageSize) ||
@@ -2,10 +2,10 @@ import { createHash } from "node:crypto";
2
2
  import { CliError } from "@wirecat/cli-base";
3
3
  import { meaningFloor } from "../embeddings/models.js";
4
4
  import { formatMeetingReference, liftMeetingFields, parseMeetingReference, } from "../meetings/index.js";
5
+ import { RRF_K } from "../search/fusion.js";
5
6
  import { questionTerms } from "../search/question-plan.js";
6
7
  import { refreshMeetingIndex, resolveMeetingSelection } from "./meeting-hit-search.js";
7
8
  import { validateVector } from "./meeting-semantic.js";
8
- import { RRF_K } from "./notes-search.js";
9
9
  /** How many hits each side ranks before they are merged; a page past it has nothing more to show. */
10
10
  const DEPTH = 200;
11
11
  const cursorOf = (value, key) => {
@@ -5,6 +5,7 @@ import { correctWords } from "../search/correct.js";
5
5
  import { PRESET_VERSION } from "../search/lucene/presets.js";
6
6
  import { FIELD_VERSION } from "../search/lucene/registry.js";
7
7
  import { exhausted, outOfTime, QUERY_LIMITS } from "../search/lucene/types.js";
8
+ import { isFunctionWord } from "../search/question-plan.js";
8
9
  import { normalize } from "../store/normalize.js";
9
10
  import { withExcerpt } from "./excerpt.js";
10
11
  import { coverageOf, prepareLucene } from "./messages-search.js";
@@ -53,6 +54,16 @@ export const searchCombined = async (store, account, request, messenger = {}, op
53
54
  : new Map();
54
55
  check();
55
56
  const bySpan = new Map(eligible.map((leaf) => [leaf.span.start, leaf]));
57
+ const widenable = (node) => node.kind === "predicate" &&
58
+ bySpan.has(node.span.start) &&
59
+ [...normalize(node.value)].length >= 3 &&
60
+ !isFunctionWord(normalize(node.value));
61
+ const beginning = (node) => ({
62
+ ...node,
63
+ operator: "wildcard",
64
+ value: `${normalize(node.value)}*`,
65
+ widened: true,
66
+ });
56
67
  const transform = (node, source, exact = false) => {
57
68
  if (node.kind === "boolean")
58
69
  return {
@@ -63,8 +74,8 @@ export const searchCombined = async (store, account, request, messenger = {}, op
63
74
  return { ...node, field: "exact" };
64
75
  if (!bySpan.has(node.span.start))
65
76
  return node;
66
- if (source === "beginnings" && [...normalize(node.value)].length >= 3)
67
- return { ...node, operator: "wildcard", value: `${normalize(node.value)}*` };
77
+ if (source === "beginnings" && widenable(node))
78
+ return beginning(node);
68
79
  if (source !== "corrected")
69
80
  return node;
70
81
  const fixes = corrections.get(normalize(node.value));
@@ -98,8 +109,8 @@ export const searchCombined = async (store, account, request, messenger = {}, op
98
109
  const fixedPrefixRoot = transform(execution.root, "corrected");
99
110
  const correctedBeginnings = (node) => node.kind === "boolean"
100
111
  ? { ...node, clauses: node.clauses.map((clause) => ({ ...clause, node: correctedBeginnings(clause.node) })) }
101
- : bySpan.has(node.span.start) && [...normalize(node.value)].length >= 3
102
- ? { ...node, field: "exact", operator: "wildcard", value: `${normalize(node.value)}*` }
112
+ : widenable(node)
113
+ ? { ...beginning(node), field: "exact" }
103
114
  : node;
104
115
  const fixedPrefix = corrections.size
105
116
  ? await read(correctedBeginnings(fixedPrefixRoot), depth)
@@ -1,12 +1,20 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { gather, MAX_ACTIONS } from "../moderation/check.js";
3
- import { defaultRules, ModerationRules, moderationPathFor } from "../moderation/rules.js";
3
+ import { defaultRules, ModerationRules, moderationPathFor, moderationProfiles, } from "../moderation/rules.js";
4
4
  import { moderateWith } from "../moderation/run.js";
5
5
  import { capability } from "../ports/messenger.js";
6
6
  import { guardedWrite } from "../sends/guarded.js";
7
7
  import { newOperationId } from "../sends/send-id.js";
8
8
  export const moderationService = (deps) => {
9
- const file = () => new ModerationRules(moderationPathFor(deps.messenger.app, deps.profile ?? "default", deps.env ?? process.env));
9
+ // Checked at first use, not here: every service is built for every command, most of them without a profile.
10
+ const file = () => {
11
+ const env = deps.env ?? process.env;
12
+ if (deps.profile === undefined) {
13
+ const choices = moderationProfiles(deps.messenger.app, env);
14
+ throw new CliError("validation_error", `name a profile: moderation rules are kept per profile — ${choices.length ? `profiles here: ${choices.join(", ")}` : "there is none on this computer yet"}`, { profiles: choices });
15
+ }
16
+ return new ModerationRules(moderationPathFor(deps.messenger.app, deps.profile, env));
17
+ };
10
18
  const group = async (chat) => {
11
19
  if (deps.offline)
12
20
  throw new CliError("validation_error", "a group's rules are kept by its id, which the messenger gives");
@@ -1,17 +1,11 @@
1
- import { type MomentZone } from "../domain/moment.js";
1
+ import { aheadOf, type MomentZone } from "../domain/moment.js";
2
2
  export type { MomentZone };
3
- /** Shaped like a moment `momentOf` reads, whether or not it is a valid one. */
4
- export declare const isMoment: (reference: string) => boolean;
3
+ export { aheadOf };
5
4
  /**
6
- * `--since` as a moment: ISO 8601, or `30m`, `2h`, `1d` ago. Unlike max-cli, never a message id —
7
- * a MAX id carries its time, and a Telegram id is only a counter within one chat.
5
+ * `--since` as a moment, in the shared time grammar (`readMoment`). Unlike max-cli, never a message id — a MAX id
6
+ * carries its time, and a Telegram id is only a counter within one chat.
8
7
  */
9
8
  export declare const momentOf: (reference: string, flag?: string, now?: number, at?: MomentZone) => number;
10
- /**
11
- * A time ahead, for a due date or the next check: ISO 8601, or `30m`, `2h`, `3d` from now. `none`
12
- * is not a time; a caller that clears a date checks for it first.
13
- */
14
- export declare const aheadOf: (reference: string, flag: string, now?: number, at?: MomentZone) => number;
15
9
  export interface DateWindow {
16
10
  since?: number;
17
11
  until?: number;
@@ -1,54 +1,26 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { timezoneOf } from "@wirecat/cli-base/query";
3
- import { calendarMoment } from "../domain/moment.js";
4
- const AGO = /^(\d+)(m|h|d)$/;
5
- const AGO_MS = { m: 60_000, h: 3_600_000, d: 86_400_000 };
6
- const DATE = /^\d{4}-\d{2}-\d{2}/;
7
- /** Shaped like a moment `momentOf` reads, whether or not it is a valid one. */
8
- export const isMoment = (reference) => {
9
- const wanted = reference.trim();
10
- return AGO.test(wanted) || DATE.test(wanted);
3
+ import { aheadOf, readMoment } from "../domain/moment.js";
4
+ export { aheadOf };
5
+ const read = (reference, flag, now, at) => {
6
+ const found = readMoment(reference, flag, { ...at, now });
7
+ if (found === undefined)
8
+ throw new CliError("validation_error", `${flag} takes an ISO 8601 time, today, yesterday, or 30m, 2h, 1d ago — not "${reference.trim()}"`);
9
+ return found;
11
10
  };
12
11
  /**
13
- * `--since` as a moment: ISO 8601, or `30m`, `2h`, `1d` ago. Unlike max-cli, never a message id —
14
- * a MAX id carries its time, and a Telegram id is only a counter within one chat.
12
+ * `--since` as a moment, in the shared time grammar (`readMoment`). Unlike max-cli, never a message id — a MAX id
13
+ * carries its time, and a Telegram id is only a counter within one chat.
15
14
  */
16
- export const momentOf = (reference, flag = "--since", now = Date.now(), at = {}) => {
17
- const wanted = reference.trim();
18
- const [, amount, unit] = AGO.exec(wanted) ?? [];
19
- // By shape: `Date.parse("12345")` is the year 12345, so a message id would pass as a date.
20
- const time = amount && unit
21
- ? now - Number(amount) * (AGO_MS[unit] ?? 0)
22
- : DATE.test(wanted)
23
- ? calendarMoment(wanted, flag, at)
24
- : Number.NaN;
25
- if (Number.isNaN(time)) {
26
- throw new CliError("validation_error", `${flag} takes an ISO 8601 time or 30m, 2h, 1d ago — not "${wanted}"`);
27
- }
28
- return time;
29
- };
30
- /**
31
- * A time ahead, for a due date or the next check: ISO 8601, or `30m`, `2h`, `3d` from now. `none`
32
- * is not a time; a caller that clears a date checks for it first.
33
- */
34
- export const aheadOf = (reference, flag, now = Date.now(), at = {}) => {
35
- const wanted = reference.trim();
36
- const [, amount, unit] = AGO.exec(wanted) ?? [];
37
- const time = amount && unit
38
- ? now + Number(amount) * (AGO_MS[unit] ?? 0)
39
- : DATE.test(wanted)
40
- ? calendarMoment(wanted, flag, at)
41
- : Number.NaN;
42
- if (Number.isNaN(time)) {
43
- throw new CliError("validation_error", `${flag} takes an ISO 8601 time or 30m, 2h, 3d from now — not "${wanted}"`);
44
- }
45
- return time;
46
- };
15
+ export const momentOf = (reference, flag = "--since", now = Date.now(), at = {}) => read(reference, flag, now, at).time;
47
16
  /** `--since-time` and `--until-time` together, as the filter and the `meta` an answer reports it by. */
48
17
  export const dateWindow = ({ sinceTime, untilTime, zone, now = Date.now(), names = ["--since-time", "--until-time"], }) => {
49
- const since = sinceTime === undefined ? undefined : momentOf(sinceTime, names[0], now, { zone });
50
- const until = untilTime === undefined ? undefined : momentOf(untilTime, names[1], now, { zone, end: true });
51
- const readInZone = [sinceTime, untilTime].some((value) => value !== undefined && DATE.test(value.trim()) && !/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value.trim()));
18
+ const at = zone === undefined ? {} : { zone };
19
+ const lower = sinceTime === undefined ? undefined : read(sinceTime, names[0], now, at);
20
+ const upper = untilTime === undefined ? undefined : read(untilTime, names[1], now, { ...at, end: true });
21
+ const since = lower?.time;
22
+ const until = upper?.time;
23
+ const readInZone = lower?.local === true || upper?.local === true;
52
24
  const window = {
53
25
  ...(since === undefined ? {} : { since: new Date(since).toISOString() }),
54
26
  ...(until === undefined ? {} : { until: new Date(until).toISOString() }),
@@ -179,8 +179,6 @@ export interface NotesQuery {
179
179
  /** An open picture embedder, for tests and callers that keep one; opened and closed here when absent. */
180
180
  pictureEmbedder?: PictureEmbedder;
181
181
  }
182
- /** Reciprocal rank fusion's usual constant, as conversations use. */
183
- export declare const RRF_K = 60;
184
182
  /**
185
183
  * A `source:` every hit must match, and the query without it. The meaning half and the picture lane cannot read a
186
184
  * field, so they get the source and the rest of the words; the words half still compiles the field itself.
@@ -6,6 +6,7 @@ import { defaultThreads, isTextModelInstalled, openEmbedder, textModelsDirectory
6
6
  import { chosenTextModel, meaningFloor, textModel, vectorModelKey } from "../embeddings/models.js";
7
7
  import { DEFAULT_IMAGE_MODEL, imageModel } from "../images/picture/models.js";
8
8
  import { entriesOfList, fitting, sourceOf } from "../search/account-list.js";
9
+ import { RRF_K } from "../search/fusion.js";
9
10
  import { OWNER_NOTES } from "../search/groups.js";
10
11
  import { fieldsOfQuery as fieldsOf, meaningWords } from "../search/lucene/meaning-parts.js";
11
12
  import { plainQuery } from "../search/lucene/plain.js";
@@ -201,8 +202,6 @@ const MAX_LINE = 200;
201
202
  const MAX_NOTES_OFFSET = 1000;
202
203
  /** How deep each half is read before the two are merged. */
203
204
  const CANDIDATES = 50;
204
- /** Reciprocal rank fusion's usual constant, as conversations use. */
205
- export const RRF_K = 60;
206
205
  const firstLine = (text, query) => {
207
206
  const words = query
208
207
  .toLowerCase()
@@ -8,6 +8,7 @@ import { runEmbedders } from "../embeddings/embed.js";
8
8
  import { chosenTextModel } from "../embeddings/models.js";
9
9
  import { formatMeetingReference } from "../meetings/index.js";
10
10
  import { entriesOfList, fitting, listedHolds } from "../search/account-list.js";
11
+ import { RRF_K } from "../search/fusion.js";
11
12
  import { plainQuery } from "../search/lucene/plain.js";
12
13
  import { MESSAGE_PARSING, SEARCH_QUERY } from "../search/lucene/types.js";
13
14
  import { questionPeriod } from "../search/question-period.js";
@@ -16,7 +17,7 @@ import { calendarAccounts, searchEvents } from "./events-search.js";
16
17
  import { excerpt } from "./excerpt.js";
17
18
  import { MAX_SEARCH_OFFSET, searchStore } from "./messages-archive-search.js";
18
19
  import { nearEligible } from "./messages-discovery.js";
19
- import { importAccounts, notesScopeOf, RRF_K, searchNotes } from "./notes-search.js";
20
+ import { importAccounts, notesScopeOf, searchNotes } from "./notes-search.js";
20
21
  import { BUSINESS_WORDS_ONLY, searchBusiness } from "./search-all-business.js";
21
22
  import { meetingLane } from "./search-all-meetings.js";
22
23
  import { HARDER_CANDIDATES, reorderHarder } from "./search-harder.js";
@@ -110,7 +110,7 @@ export const searchServer = async (deps, request) => {
110
110
  if (deps.offline)
111
111
  return skip("offline");
112
112
  const guardRequest = { chatId: null, kind: "reaction", key: SERVER_SEARCH_KEY };
113
- // Never asked, as sync-first: over MCP an `ask` goes ahead, and the server search needs `allow`.
113
+ // Never asked, as sync-first: over MCP an `ask` goes ahead, and the server search needs `allow` or `readonly`.
114
114
  try {
115
115
  deps.guard.check(guardRequest, { reserve: false });
116
116
  }
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { queryFieldsOf } from "@wirecat/cli-base/query";
2
+ import { queryFieldsOf, timezoneOf } from "@wirecat/cli-base/query";
3
3
  import { formatLocator, isLocator, parseLocator } from "../domain/locator.js";
4
4
  import { formatReference } from "../domain/references.js";
5
5
  import { normalizeTag } from "../domain/tags.js";
@@ -93,7 +93,9 @@ export const tagsService = (deps) => {
93
93
  return { target: viewOf(account, target), removed, unchanged: tags.filter((tag) => !removed.includes(tag)) };
94
94
  }),
95
95
  list: ({ query, limit, offset }) => inStore(async (store, account) => {
96
- const where = query ? queryFilter(query, TAGGING_COLUMNS, { command: "tags list" }) : undefined;
96
+ const where = query
97
+ ? queryFilter(query, TAGGING_COLUMNS, { command: "tags list", zone: timezoneOf() })
98
+ : undefined;
97
99
  const rows = await store.tags.tags(account, {
98
100
  ...(where ? { where } : {}),
99
101
  window: { limit: limit + 1, offset },
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { walkQuery } from "@wirecat/cli-base/query";
2
+ import { timezoneOf, walkQuery } from "@wirecat/cli-base/query";
3
3
  import { parseMeetingReference } from "../meetings/index.js";
4
4
  import { withoutField } from "../store/index.js";
5
5
  import { queryFilter } from "../store/store.js";
@@ -59,7 +59,7 @@ export const taskStatsOf = async (store, accounts, { by = "chat", query, timezon
59
59
  ...(kind === undefined ? [] : [{ sql: "t.type = ?", params: [kind] }]),
60
60
  ...(by === "meeting" ? [{ sql: "t.source_kind = 'meeting'", params: [] }] : []),
61
61
  ];
62
- const options = { command: "stats tasks show", now, ...(timezone === undefined ? {} : { zone: timezone }) };
62
+ const options = { command: "stats tasks show", now, zone: timezoneOf(timezone) };
63
63
  const where = (ast, more = []) => and([...fixed, ...more, ...(ast ? [queryFilter(ast, read, options)] : [])]);
64
64
  // Project tasks belong to no account: one board read, whatever the accounts.
65
65
  const scopes = by === "project"
@@ -1,5 +1,5 @@
1
1
  import { CliError, isCliError, singleLine } from "@wirecat/cli-base";
2
- import { OPERATORS_BY_TYPE, queryFieldsOf, walkQuery } from "@wirecat/cli-base/query";
2
+ import { OPERATORS_BY_TYPE, queryFieldsOf, timezoneOf, walkQuery, } from "@wirecat/cli-base/query";
3
3
  import { isLocator, parseLocator } from "../domain/locator.js";
4
4
  import { formatReference } from "../domain/references.js";
5
5
  import { task as taskEntity } from "../entities/task.js";
@@ -230,7 +230,7 @@ export const tasksService = (deps, categories) => {
230
230
  return {
231
231
  list: ({ query, limit, offset, previews }) => inStore(async (store, account) => {
232
232
  const where = query
233
- ? queryFilter(query, await queryColumns(store, account, query), { command: "tasks list" })
233
+ ? queryFilter(query, await queryColumns(store, account, query), { command: "tasks list", zone: timezoneOf() })
234
234
  : undefined;
235
235
  const rows = await store.tasks.query(taskAccount(account), where, { limit: limit + 1, offset });
236
236
  const shown = rows.slice(0, limit);