@wirecat/cli-core 0.662.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 (173) hide show
  1. package/CHANGELOG.md +88 -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/call-stats-command.d.ts +18 -0
  8. package/dist/cli/call-stats-command.js +52 -0
  9. package/dist/cli/contract-templates.js +2 -0
  10. package/dist/cli/envelope.d.ts +0 -5
  11. package/dist/cli/envelope.js +25 -0
  12. package/dist/cli/index.d.ts +2 -1
  13. package/dist/cli/index.js +2 -1
  14. package/dist/cli/meeting-batch.d.ts +2 -1
  15. package/dist/cli/meeting-batch.js +7 -5
  16. package/dist/cli/meeting-preparation-command.js +5 -5
  17. package/dist/cli/meeting-preparation-read.d.ts +5 -5
  18. package/dist/cli/meeting-preparation-read.js +13 -21
  19. package/dist/cli/meeting-series-inventory-command.js +2 -2
  20. package/dist/cli/meeting-series-inventory-read.d.ts +2 -2
  21. package/dist/cli/meeting-series-inventory-read.js +7 -15
  22. package/dist/cli/messenger/admin-statistics-command.js +2 -2
  23. package/dist/cli/messenger/counters-command.js +2 -2
  24. package/dist/cli/messenger/media-archive-command.js +5 -4
  25. package/dist/cli/messenger/media-archive-move-command.js +1 -1
  26. package/dist/cli/messenger/media-archive-timer-command.js +5 -4
  27. package/dist/cli/messenger/metadata-command.js +3 -3
  28. package/dist/cli/messenger/rankings-command.js +3 -3
  29. package/dist/cli/messenger/tags-command.js +7 -2
  30. package/dist/cli/messenger/tasks-command.js +2 -2
  31. package/dist/cli/paging.d.ts +10 -0
  32. package/dist/cli/paging.js +29 -0
  33. package/dist/cli/runs/command.js +6 -4
  34. package/dist/cli/runs/search-command.js +9 -5
  35. package/dist/cli/schedule/schedule-command.js +1 -5
  36. package/dist/domain/moment.d.ts +29 -0
  37. package/dist/domain/moment.js +58 -0
  38. package/dist/domain/providers.d.ts +6 -4
  39. package/dist/domain/providers.js +10 -5
  40. package/dist/domain/send-time.d.ts +3 -4
  41. package/dist/domain/send-time.js +10 -24
  42. package/dist/entities/fields.d.ts +2 -2
  43. package/dist/entities/fields.js +2 -2
  44. package/dist/entities/index.d.ts +92 -1
  45. package/dist/entities/index.js +3 -2
  46. package/dist/entities/meeting.d.ts +1 -1
  47. package/dist/entities/meeting.js +1 -1
  48. package/dist/errors/reasons.js +0 -1
  49. package/dist/mail/cli/index.js +4 -2
  50. package/dist/mail/facts.d.ts +5 -2
  51. package/dist/mail/facts.js +6 -3
  52. package/dist/mail/index.d.ts +1 -1
  53. package/dist/mail/meeting-notes.js +1 -1
  54. package/dist/mail/probe.d.ts +5 -2
  55. package/dist/mail/probe.js +9 -5
  56. package/dist/mail/server-search.js +1 -1
  57. package/dist/mail/sync.js +1 -1
  58. package/dist/mcp/meeting-preparation.js +1 -1
  59. package/dist/mcp/meeting-series-inventory.js +1 -1
  60. package/dist/mcp/prompts.js +6 -9
  61. package/dist/meetings/call-answers.d.ts +106 -0
  62. package/dist/meetings/call-answers.js +171 -0
  63. package/dist/meetings/call-stats.d.ts +121 -0
  64. package/dist/meetings/call-stats.js +211 -0
  65. package/dist/meetings/calls.d.ts +76 -0
  66. package/dist/meetings/calls.js +78 -0
  67. package/dist/meetings/cli/index.d.ts +8 -0
  68. package/dist/meetings/cli/index.js +10 -22
  69. package/dist/meetings/cli/search.d.ts +9 -2
  70. package/dist/meetings/cli/search.js +16 -26
  71. package/dist/meetings/index.d.ts +3 -0
  72. package/dist/meetings/index.js +3 -0
  73. package/dist/meetings/mcp/index.d.ts +6 -3
  74. package/dist/meetings/mcp/index.js +2 -4
  75. package/dist/meetings/mcp/search.d.ts +6 -1
  76. package/dist/meetings/mcp/search.js +3 -3
  77. package/dist/meetings/read-through.d.ts +2 -1
  78. package/dist/meetings/read-through.js +10 -1
  79. package/dist/meetings/stats.d.ts +3 -0
  80. package/dist/meetings/stats.js +3 -3
  81. package/dist/meetings/testing/index.d.ts +1 -0
  82. package/dist/meetings/testing/index.js +1 -0
  83. package/dist/meetings/testing/paging.d.ts +6 -0
  84. package/dist/meetings/testing/paging.js +5 -0
  85. package/dist/moderation/rules.d.ts +2 -0
  86. package/dist/moderation/rules.js +16 -2
  87. package/dist/search/fusion.d.ts +17 -0
  88. package/dist/search/fusion.js +17 -0
  89. package/dist/search/lucene/resolved.d.ts +2 -0
  90. package/dist/search/question-plan.d.ts +2 -0
  91. package/dist/search/question-plan.js +5 -0
  92. package/dist/search/service-query.d.ts +6 -1
  93. package/dist/search/service-query.js +9 -1
  94. package/dist/services/agenda-mail.js +2 -1
  95. package/dist/services/agenda.js +5 -3
  96. package/dist/services/attachments.js +4 -2
  97. package/dist/services/call-stats.d.ts +17 -0
  98. package/dist/services/call-stats.js +41 -0
  99. package/dist/services/chats.js +4 -2
  100. package/dist/services/conversations.js +4 -2
  101. package/dist/services/deps.d.ts +1 -1
  102. package/dist/services/document-source.d.ts +1 -1
  103. package/dist/services/document-source.js +4 -3
  104. package/dist/services/documents/ingestion.js +11 -40
  105. package/dist/services/documents/plan.d.ts +1 -1
  106. package/dist/services/documents/plan.js +30 -17
  107. package/dist/services/documents/ports.d.ts +5 -0
  108. package/dist/services/documents/sync.js +1 -1
  109. package/dist/services/embeddings-search.js +20 -4
  110. package/dist/services/events-search.js +2 -1
  111. package/dist/services/index.d.ts +1 -0
  112. package/dist/services/index.js +1 -0
  113. package/dist/services/mail-search.d.ts +1 -1
  114. package/dist/services/mail-search.js +10 -11
  115. package/dist/services/media-archive-move.js +2 -4
  116. package/dist/services/media-archive.d.ts +0 -1
  117. package/dist/services/media-archive.js +2 -12
  118. package/dist/services/meeting-combined.js +1 -1
  119. package/dist/services/messages-combined.js +15 -4
  120. package/dist/services/moderation.js +10 -2
  121. package/dist/services/moment.d.ts +4 -10
  122. package/dist/services/moment.js +16 -44
  123. package/dist/services/notes-search.d.ts +0 -2
  124. package/dist/services/notes-search.js +1 -2
  125. package/dist/services/search-all.js +2 -1
  126. package/dist/services/tags.js +4 -2
  127. package/dist/services/task-stats.js +2 -2
  128. package/dist/services/tasks.js +2 -2
  129. package/dist/store/accounts.js +2 -1
  130. package/dist/store/sqlite/account-purge.d.ts +3 -0
  131. package/dist/store/sqlite/account-purge.js +143 -0
  132. package/dist/store/sqlite/accounts.d.ts +0 -2
  133. package/dist/store/sqlite/accounts.js +2 -134
  134. package/dist/store/sqlite/calendar.d.ts +1 -0
  135. package/dist/store/sqlite/calendar.js +5 -5
  136. package/dist/store/sqlite/catalog.js +2 -16
  137. package/dist/store/sqlite/chats.js +2 -1
  138. package/dist/store/sqlite/context-document-source.d.ts +3 -3
  139. package/dist/store/sqlite/context-document-source.js +9 -7
  140. package/dist/store/sqlite/context-evidence.js +9 -3
  141. package/dist/store/sqlite/document-listing.js +2 -1
  142. package/dist/store/sqlite/events.js +2 -1
  143. package/dist/store/sqlite/file-note.d.ts +6 -0
  144. package/dist/store/sqlite/file-note.js +15 -0
  145. package/dist/store/sqlite/files.d.ts +3 -2
  146. package/dist/store/sqlite/files.js +5 -3
  147. package/dist/store/sqlite/identities.js +2 -1
  148. package/dist/store/sqlite/imported-documents.js +2 -2
  149. package/dist/store/sqlite/knowledge.js +19 -19
  150. package/dist/store/sqlite/lucene-fields.js +8 -12
  151. package/dist/store/sqlite/mail-rules.js +2 -1
  152. package/dist/store/sqlite/meeting-calls.d.ts +4 -0
  153. package/dist/store/sqlite/meeting-calls.js +66 -0
  154. package/dist/store/sqlite/meetings.d.ts +2 -2
  155. package/dist/store/sqlite/meetings.js +4 -1
  156. package/dist/store/sqlite/mention-sources.js +2 -1
  157. package/dist/store/sqlite/mentions.js +2 -2
  158. package/dist/store/sqlite/messages.js +6 -1
  159. package/dist/store/sqlite/note-search.js +8 -11
  160. package/dist/store/sqlite/notes.d.ts +2 -0
  161. package/dist/store/sqlite/notes.js +24 -13
  162. package/dist/store/sqlite/organizations.js +2 -2
  163. package/dist/store/sqlite/people-list.js +3 -3
  164. package/dist/store/sqlite/query-filter.d.ts +3 -3
  165. package/dist/store/sqlite/query-filter.js +3 -3
  166. package/dist/store/sqlite/reads.d.ts +4 -4
  167. package/dist/store/sqlite/reads.js +4 -4
  168. package/dist/store/sqlite/search.js +11 -7
  169. package/dist/store/sqlite/test-accounts.js +1 -1
  170. package/dist/store/sqlite/trigram-match.d.ts +9 -0
  171. package/dist/store/sqlite/trigram-match.js +28 -0
  172. package/dist/store/sqlite/work-tasks.js +1 -1
  173. package/package.json +3 -3
@@ -0,0 +1,41 @@
1
+ import { aggregateCallStats, CALLBACK_WITHIN_MS, callOf, } from "../meetings/index.js";
2
+ const callsOf = (stored) => stored.map(callOf).filter((one) => one !== null);
3
+ /**
4
+ * The call numbers of one account over the selected meetings. A callback may come after `until` or from an employee
5
+ * the selection leaves out, so the account's calls up to `callbackWithinMs` after the selection are read too.
6
+ */
7
+ export const readCallStats = async (store, request) => {
8
+ const { timeZone, callbackWithinMs, missedLimit, ...selection } = request;
9
+ const within = callbackWithinMs ?? CALLBACK_WITHIN_MS;
10
+ const stored = await store.meetings.meetingCalls(selection);
11
+ const calls = callsOf(stored);
12
+ const narrowed = Object.keys(selection).some((key) => !["accountId", "since", "until", "maxRows", "signal"].includes(key));
13
+ const end = selection.until === undefined ? undefined : selection.until + within;
14
+ // Narrowed to a person, a colleague's callback is outside the selection; otherwise only the time after it is.
15
+ const window = narrowed
16
+ ? {
17
+ ...(selection.since === undefined ? {} : { since: selection.since }),
18
+ ...(end === undefined ? {} : { until: end }),
19
+ }
20
+ : selection.until === undefined
21
+ ? null
22
+ : { since: selection.until + 1, until: end };
23
+ const later = calls.length > 0 && window !== null && Number.isSafeInteger(within)
24
+ ? callsOf(await store.meetings.meetingCalls({
25
+ accountId: selection.accountId,
26
+ ...window,
27
+ ...(selection.maxRows === undefined ? {} : { maxRows: selection.maxRows }),
28
+ ...(selection.signal ? { signal: selection.signal } : {}),
29
+ }))
30
+ : [];
31
+ return {
32
+ ...aggregateCallStats(calls, {
33
+ ...(timeZone === undefined ? {} : { timeZone }),
34
+ callbackWithinMs: within,
35
+ ...(missedLimit === undefined ? {} : { missedLimit }),
36
+ later,
37
+ }),
38
+ accountId: selection.accountId,
39
+ notCalls: stored.length - calls.length,
40
+ };
41
+ };
@@ -54,7 +54,7 @@ const deepChecks = async (deps, items, deep, pauseMs, registry) => {
54
54
  export const chatsService = (deps) => ({
55
55
  list: async (window, query) => {
56
56
  if (fromStore(deps)) {
57
- const where = query ? queryFilter(query, CHAT_COLUMNS, { command: "chats list" }) : undefined;
57
+ const where = query ? queryFilter(query, CHAT_COLUMNS, { command: "chats list", zone: timezoneOf() }) : undefined;
58
58
  return (await accountStore(deps)).chats.chats({ ...window, ...(where ? { where } : {}) });
59
59
  }
60
60
  const [term] = query ? walkQuery(query.root) : [];
@@ -211,7 +211,9 @@ export const chatsService = (deps) => ({
211
211
  return { chatId, read: members.length, participants, complete, more, ...change, tracked };
212
212
  },
213
213
  tracked: async (query) => {
214
- const where = query ? queryFilter(query, TRACKED_CHAT_COLUMNS, { command: "chats tracking list" }) : undefined;
214
+ const where = query
215
+ ? queryFilter(query, TRACKED_CHAT_COLUMNS, { command: "chats tracking list", zone: timezoneOf() })
216
+ : undefined;
215
217
  return (await accountStore(deps)).roster.trackedChats(where ? { where } : {});
216
218
  },
217
219
  memberHistory: async (chat, { since }) => {
@@ -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 { cutChunks } from "../conversations/chunks.js";
4
4
  import { linkMessages, RULES_VERSION } from "../conversations/link.js";
5
5
  import { formatLocator } from "../domain/locator.js";
@@ -92,7 +92,9 @@ export const conversationsService = (deps) => {
92
92
  const { store, chatId } = await found(chat);
93
93
  if (!(await store.conversations.conversationState(chatId))?.builtAt)
94
94
  throw notBuilt(chatId);
95
- const where = query ? queryFilter(query, CONVERSATION_COLUMNS, { command: "conversations list" }) : undefined;
95
+ const where = query
96
+ ? queryFilter(query, CONVERSATION_COLUMNS, { command: "conversations list", zone: timezoneOf() })
97
+ : undefined;
96
98
  const page = await store.conversations.conversations(chatId, { limit, offset, ...(where ? { where } : {}) });
97
99
  const account = await deps.account();
98
100
  return { items: page.items.map((one) => conversationItem(account, one)), hasMore: page.hasMore };
@@ -32,7 +32,7 @@ export interface ServiceDeps {
32
32
  */
33
33
  store: () => Promise<MessageStore>;
34
34
  guard: SendGuard;
35
- /** For the profile's own files — a group's moderation rules. `default` and `process.env` when unset. */
35
+ /** For the profile's own files — a group's moderation rules, which refuse to guess one when unset. */
36
36
  profile?: string;
37
37
  env?: NodeJS.ProcessEnv;
38
38
  /** A long-running process's open models, so a search does not load one each time. */
@@ -2,7 +2,7 @@ import type { Profiles } from "../search/account-list.js";
2
2
  import type { Note, StoredAccount, StoredFile } from "../store/index.js";
3
3
  /**
4
4
  * Where a hit came from. The document's preferred file says it: its account's provider and its link.
5
- * A Drive document under a notes folder (before version 31 moves it) is still known by its front matter.
5
+ * A documents provider's document under a notes folder is still known by its front matter's `source`.
6
6
  * The hit's time is the store search's: the one `date:` reads.
7
7
  */
8
8
  export declare const documentSource: (note: Note, accounts: readonly StoredAccount[], profiles: Profiles, file?: StoredFile) => {
@@ -1,7 +1,7 @@
1
- import { isFolderProvider, isImportedProvider, kindIn } from "../domain/providers.js";
1
+ import { isDocumentAccountProvider, isFolderProvider, isImportedProvider } from "../domain/providers.js";
2
2
  /**
3
3
  * Where a hit came from. The document's preferred file says it: its account's provider and its link.
4
- * A Drive document under a notes folder (before version 31 moves it) is still known by its front matter.
4
+ * A documents provider's document under a notes folder is still known by its front matter's `source`.
5
5
  * The hit's time is the store search's: the one `date:` reads.
6
6
  */
7
7
  export const documentSource = (note, accounts, profiles, file) => {
@@ -16,7 +16,8 @@ export const documentSource = (note, accounts, profiles, file) => {
16
16
  ...(file?.url ? { url: file.url } : {}),
17
17
  };
18
18
  const remote = note.source === "file" &&
19
- ((account !== undefined && kindIn(account.provider) === "documents") || metadata?.source === "google-drive");
19
+ ((account !== undefined && isDocumentAccountProvider(account.provider)) ||
20
+ isDocumentAccountProvider(metadata?.source));
20
21
  const profile = remote && account
21
22
  ? Object.entries(profiles)
22
23
  .flatMap(([command, named]) => Object.entries(named).map(([name, key]) => ({ command, name, key })))
@@ -10,28 +10,6 @@ export const documentIngestion = (store, options) => {
10
10
  const found = (await store.notes.folders()).find((item) => item.name === name);
11
11
  return found ?? (create ? await store.notes.addFolder({ name, format: "markdown" }) : undefined);
12
12
  };
13
- const documents = new Map();
14
- const cached = async (principal) => {
15
- const known = documents.get(principal);
16
- if (known)
17
- return known;
18
- const notes = new Map();
19
- const selected = await folder(principal, false);
20
- if (selected) {
21
- for (let offset = 0;; offset += 500) {
22
- const page = await store.notes.notes({ folderId: selected.id, source: "file", limit: 500, offset });
23
- for (const note of page.items)
24
- if (note.path)
25
- notes.set(note.path, note);
26
- if (!page.hasMore)
27
- break;
28
- if (offset >= 10000)
29
- throw new CliError("provider_error", "local document listing exceeded its bound");
30
- }
31
- }
32
- documents.set(principal, notes);
33
- return notes;
34
- };
35
13
  const stale = async (ref) => {
36
14
  for (const status of ["proposed", "confirmed"]) {
37
15
  for (let batch = 0;; batch++) {
@@ -48,23 +26,20 @@ export const documentIngestion = (store, options) => {
48
26
  return {
49
27
  catalog: {
50
28
  import: async (principal, files) => {
51
- if (files.length > 10000)
52
- throw new CliError("validation_error", "catalog scope exceeds 10000 entries", {
53
- reason: "catalog.scope-limit",
54
- });
55
29
  const selected = await folder(principal, true);
56
30
  if (!selected)
57
31
  throw new CliError("configuration_error", "catalog collection could not be registered");
58
32
  for (let start = 0; start < files.length; start += 200) {
59
- await store.catalog.upsert(selected.id, files.slice(start, start + 200).map(options.catalogInput));
60
- }
61
- for (const file of files) {
62
- const entry = await store.catalog.get(selected.id, options.externalId(file.id));
63
- if (entry)
64
- await options.observed?.(principal, file, entry.ref.slice("document:".length));
33
+ const chunk = files.slice(start, start + 200);
34
+ await store.catalog.upsert(selected.id, chunk.map(options.catalogInput));
35
+ if (options.observed)
36
+ for (const file of chunk) {
37
+ const entry = await store.catalog.get(selected.id, options.externalId(file.id));
38
+ if (entry)
39
+ await options.observed(principal, file, entry.ref.slice("document:".length));
40
+ }
65
41
  }
66
42
  const retired = await store.catalog.reconcile(selected.id, files.map((file) => options.externalId(file.id)));
67
- documents.delete(principal);
68
43
  return { entries: files.length, retired };
69
44
  },
70
45
  get: async (principal, id) => {
@@ -92,14 +67,13 @@ export const documentIngestion = (store, options) => {
92
67
  const selected = await folder(principal, true);
93
68
  if (!selected)
94
69
  throw new Error("folder registration failed");
95
- const notes = await cached(principal);
96
70
  const path = options.externalId(content.metadata.id);
97
- const before = notes.get(path);
71
+ const before = await store.notes.fileNote(selected.id, path);
98
72
  if (before && before.contentHash !== hash)
99
73
  await stale(before.ref);
100
74
  const { note } = await store.notes.saveFileNote({
101
75
  folderId: selected.id,
102
- path: options.externalId(content.metadata.id),
76
+ path,
103
77
  title: content.metadata.name,
104
78
  text: content.text,
105
79
  contentHash: hash,
@@ -107,21 +81,18 @@ export const documentIngestion = (store, options) => {
107
81
  });
108
82
  await store.catalog.upsert(selected.id, [options.catalogInput(content.metadata)]);
109
83
  await options.observed?.(principal, content.metadata, note.id);
110
- notes.set(path, note);
111
84
  return note.ref;
112
85
  },
113
86
  remove: async (principal, id) => {
114
87
  const selected = await folder(principal, false);
115
88
  if (selected) {
116
- const notes = await cached(principal);
117
89
  const path = options.externalId(id);
118
- const note = notes.get(path);
90
+ const note = await store.notes.fileNote(selected.id, path);
119
91
  const retired = note ? undefined : await store.catalog.get(selected.id, path, true);
120
92
  const ref = note?.ref ?? retired?.ref;
121
93
  if (ref)
122
94
  await stale(ref);
123
95
  await store.notes.deleteFileNotes(selected.id, [path]);
124
- notes.delete(path);
125
96
  }
126
97
  },
127
98
  };
@@ -1,7 +1,7 @@
1
1
  import type { DocumentSource, SourceFile, SourceState, SourceWalk } from "../../documents/model.js";
2
2
  import { type SourceQuery } from "../../documents/scope.js";
3
3
  import type { SyncOptions } from "./ports.js";
4
- export declare const scopeHash: (roots: string[], query?: Pick<SourceQuery, "key" | "mode">) => string;
4
+ export declare const scopeHash: (roots: string[], query?: Pick<SourceQuery, "key" | "mode">, pages?: boolean) => string;
5
5
  export declare const changedSince: (previous: SourceFile, file: SourceFile) => boolean;
6
6
  interface WalkStore<M extends SourceFile> {
7
7
  read: (scope: string) => SourceWalk<M> | undefined;
@@ -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)