@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
@@ -0,0 +1,17 @@
1
+ /** Reciprocal rank fusion's usual constant, as conversations use. */
2
+ export declare const RRF_K = 60;
3
+ export interface FusedFacts {
4
+ /** The hit holds the exact forms of the words, when the search was stemmed. */
5
+ exact?: boolean | undefined;
6
+ /** Its index ranked it by relevance; an unranked hit came by a field, a transcript or a file. */
7
+ ranked: boolean;
8
+ /** Milliseconds: what breaks a tie, newest first. */
9
+ at: number;
10
+ }
11
+ /**
12
+ * Lists, each best first from its own index, as one list best first. Raw scores of two word indexes never compare
13
+ * (each BM25 depends on its own corpus), so a hit's place in its own list votes instead, by reciprocal rank fusion;
14
+ * that place also carries the transcript and file tiers the list was sorted by. Exact hits stay first and ranked
15
+ * ones before unranked, as within one list. With nothing ranked, newest first.
16
+ */
17
+ export declare const fuseRanked: <T>(lists: readonly (readonly T[])[], facts: (item: T) => FusedFacts) => T[];
@@ -0,0 +1,17 @@
1
+ /** Reciprocal rank fusion's usual constant, as conversations use. */
2
+ export const RRF_K = 60;
3
+ /**
4
+ * Lists, each best first from its own index, as one list best first. Raw scores of two word indexes never compare
5
+ * (each BM25 depends on its own corpus), so a hit's place in its own list votes instead, by reciprocal rank fusion;
6
+ * that place also carries the transcript and file tiers the list was sorted by. Exact hits stay first and ranked
7
+ * ones before unranked, as within one list. With nothing ranked, newest first.
8
+ */
9
+ export const fuseRanked = (lists, facts) => {
10
+ const rows = lists.flatMap((list) => list.map((item, rank) => ({ item, vote: 1 / (RRF_K + rank + 1), ...facts(item) })));
11
+ const ranking = rows.some(({ ranked }) => ranked);
12
+ return rows
13
+ .sort((a, b) => Number(b.exact === true) - Number(a.exact === true) ||
14
+ (ranking ? Number(b.ranked) - Number(a.ranked) || b.vote - a.vote : 0) ||
15
+ b.at - a.at)
16
+ .map(({ item }) => item);
17
+ };
@@ -2,6 +2,8 @@ import type { DateRange, Occur, Predicate, QueryNode, Span } from "@wirecat/cli-
2
2
  import type { AccountKey } from "../../store/store.js";
3
3
  import type { Stemmer } from "../stem.js";
4
4
  export type ResolvedPredicate = Predicate & {
5
+ /** A prefix the search made of a word typed whole: past the expansions budget it reads as that word instead. */
6
+ widened?: true;
5
7
  resolution?: {
6
8
  chat?: {
7
9
  account: AccountKey;
@@ -1,4 +1,6 @@
1
1
  export declare const words: (text: string) => RegExpMatchArray | [];
2
+ /** Words that carry no topic of their own: widening one to a prefix (`про*`) finds only noise. */
3
+ export declare const isFunctionWord: (word: string) => boolean;
2
4
  /**
3
5
  * A question's content words — «что решили по цене?» → решили, цене — or null when the text is not a question: it
4
6
  * ends with «?» or starts with a question word.
@@ -9,6 +9,11 @@ const QUESTION_STARTS = new Set(words("what which how who whom whose where when
9
9
  "что кто кого кому кем где когда как какой какая какое какие какую каким какого каких почему зачем откуда " +
10
10
  "куда сколько ли можно разве чей чья чьё чьи"));
11
11
  const QUESTION_FILLER = new Set(words("about any did does why whom whose would will это мы вы я они он она о об про ли"));
12
+ const LINKING = new Set(words("and or but not nor with without this that these those there their they them you your our its his her all any " +
13
+ "and for into onto over then than also just and при для без над под или либо его её их все всё уже ещё так " +
14
+ "тоже также был была были было будет это эта этот эти там тут"));
15
+ /** Words that carry no topic of their own: widening one to a prefix (`про*`) finds only noise. */
16
+ export const isFunctionWord = (word) => scaffolding.has(word) || QUESTION_STARTS.has(word) || QUESTION_FILLER.has(word) || LINKING.has(word);
12
17
  /**
13
18
  * A question's content words — «что решили по цене?» → решили, цене — or null when the text is not a question: it
14
19
  * ends with «?» or starts with a question word.
@@ -1,4 +1,4 @@
1
- import { type DateRange, type Occur, type Predicate, type Span } from "@wirecat/cli-base/query";
1
+ import { type DateRange, type Occur, type Predicate, type QueryAst, type Span } from "@wirecat/cli-base/query";
2
2
  /**
3
3
  * Where a read looks, the one vocabulary of messages, mail, calendar and meetings: the store (`archive`), the
4
4
  * service's own search (`server`), or both, with what the service returns kept in the store.
@@ -61,3 +61,8 @@ export declare const windowOf: ({ lower, upper, lower_inclusive, upper_inclusive
61
61
  from?: number;
62
62
  to?: number;
63
63
  };
64
+ /**
65
+ * Whether a query reads one of `times` in a zone — a date, `today`, a time without an offset — so the answer names
66
+ * that zone in `meta.timezone`. A time counted back from now or carrying its offset needs none.
67
+ */
68
+ export declare const readsZone: (ast: QueryAst, times: ReadonlySet<string>) => boolean;
@@ -1,4 +1,4 @@
1
- import { dateRange } from "@wirecat/cli-base/query";
1
+ import { dateRange, walkQuery, } from "@wirecat/cli-base/query";
2
2
  /**
3
3
  * Where a read looks, the one vocabulary of messages, mail, calendar and meetings: the store (`archive`), the
4
4
  * service's own search (`server`), or both, with what the service returns kept in the store.
@@ -55,3 +55,11 @@ export const windowOf = ({ lower, upper, lower_inclusive, upper_inclusive, }) =>
55
55
  ...(lower === undefined ? {} : { from: lower_inclusive ? lower : lower + 1 }),
56
56
  ...(upper === undefined ? {} : { to: upper_inclusive ? upper : upper - 1 }),
57
57
  });
58
+ const RELATIVE_TIME = /^\d+[mhd]$/i;
59
+ const OFFSET = /(?:Z|[+-]\d{2}:?\d{2})$/i;
60
+ /**
61
+ * Whether a query reads one of `times` in a zone — a date, `today`, a time without an offset — so the answer names
62
+ * that zone in `meta.timezone`. A time counted back from now or carrying its offset needs none.
63
+ */
64
+ export const readsZone = (ast, times) => walkQuery(ast.root).some((term) => times.has(term.field) &&
65
+ [term.value, term.upper].some((value) => value !== undefined && value !== "*" && !RELATIVE_TIME.test(value) && !OFFSET.test(value)));
@@ -3,25 +3,9 @@ import { CliError } from "@wirecat/cli-base";
3
3
  import { MESSENGER_CHANGE_REFUSAL, readOnlyRefusal } from "../ports/app.js";
4
4
  import { FloodMemory, floodPathFor, holdEnd } from "./flood.js";
5
5
  import { SendJournal, sendsPathFor, } from "./journal.js";
6
- import { CEILING_KEY, keyForWrite, levelFor, skipFlagFor } from "./permissions.js";
6
+ import { CEILING_KEY, keyForWrite, levelFor, STORE_ONLY_KEYS, skipFlagFor, stops, } from "./permissions.js";
7
7
  import { RecipientList, recipientsPathFor } from "./recipients.js";
8
8
  const HOUR_MS = 60 * 60 * 1000;
9
- /**
10
- * Asked of the guard for their permission level, yet they only read from the messenger or work here: reads go on
11
- * during a hold and under the read-only lock, which promises reads and syncs.
12
- */
13
- const READS = new Set([
14
- "attachments.extract",
15
- "conversations.embeddings",
16
- "conversations.links",
17
- "messages.server-search",
18
- "messages.sync-first",
19
- "stats.contacts.top.sync-first",
20
- "stats.messages.counters.sync",
21
- "stats.messages.show.sync-first",
22
- "stats.messages.top.sync-first",
23
- "store.gaps.repair",
24
- ]);
25
9
  /**
26
10
  * What puts something in front of somebody (max-cli `NEED-168`, widened by `NEED-282`). A message, a
27
11
  * forward, an edit, a pin that notifies, a new group and people added to one all do. A reaction,
@@ -72,14 +56,14 @@ export const sendGuard = ({ profile, recipients, command = recipients.command, r
72
56
  let reservation;
73
57
  const answered = new WeakSet();
74
58
  const refuseReadOnly = ({ key }) => {
75
- if (key !== undefined && READS.has(key))
59
+ if (key !== undefined && STORE_ONLY_KEYS.has(key))
76
60
  return;
77
61
  if (readOnlyLock)
78
62
  throw readOnlyRefusal(readOnlyLock, MESSENGER_CHANGE_REFUSAL);
79
63
  };
80
64
  // Every write, counted or not: a reaction or a read receipt sent through a ban is what makes the ban stick.
81
65
  const refuseHeld = ({ key }) => {
82
- if (key !== undefined && READS.has(key))
66
+ if (key !== undefined && STORE_ONLY_KEYS.has(key))
83
67
  return;
84
68
  const block = flood?.sendBlock();
85
69
  if (!block)
@@ -95,7 +79,7 @@ export const sendGuard = ({ profile, recipients, command = recipients.command, r
95
79
  if (levels !== undefined) {
96
80
  const key = request.key ?? keyForWrite(kind, action);
97
81
  const { level, key: named } = levelFor(levels, key, permissionDefaults);
98
- if (level === "deny" || level === "readonly")
82
+ if (stops(level, key))
99
83
  throw levelRefusal({ profile, command, key, level, named, permissionSources }, permissionFix?.(request, key));
100
84
  if (level === "ask" && !answered.has(request)) {
101
85
  throw new CliError("confirmation_required", `${key} asks before it acts, and it was not asked`);
@@ -1,5 +1,5 @@
1
1
  import type { Asker, GuardRequest, SendGuard } from "./guard.js";
2
- import type { Level, PermissionKey } from "./permissions.js";
2
+ import { type Level, type PermissionKey } from "./permissions.js";
3
3
  export type KeyedGuard = SendGuard & {
4
4
  /** Refuses the write when one of its keys denies it or is read-only; asks nothing. */
5
5
  refuse(request: GuardRequest): void;
@@ -1,3 +1,4 @@
1
+ import { stops } from "./permissions.js";
1
2
  /**
2
3
  * A guard over a write's main key and its extra keys. A key that refuses refuses before anything is asked, so nobody
3
4
  * answers yes to a write that a stricter key then stops, and one question names every key at `ask`. The extra keys are
@@ -23,7 +24,7 @@ export const keyedGuard = (build, ask, levelOf, extra) => {
23
24
  };
24
25
  const levelOfRequest = ({ key }) => levelOf(key ?? "");
25
26
  const refuse = (request) => {
26
- const refused = all(request).find((one) => ["deny", "readonly"].includes(levelOfRequest(one)));
27
+ const refused = all(request).find((one) => stops(levelOfRequest(one), one.key ?? ""));
27
28
  if (refused)
28
29
  guard.check(refused, { reserve: false });
29
30
  };
@@ -39,6 +39,20 @@ export declare const layerPermissions: (layers: readonly [string, Readonly<Recor
39
39
  * at a terminal writes it, so an agent cannot lift it with `config set`.
40
40
  */
41
41
  export declare const CEILING_KEY = "*";
42
+ /**
43
+ * Asked of the guard for their permission level, yet they only read from the messenger or work here: reads go on
44
+ * during a hold and under the read-only lock, which promises reads and syncs.
45
+ */
46
+ export declare const STORE_ONLY_KEYS: Set<string>;
47
+ /** Whether `level` lets a key that only fetches into the store run: `readonly` does, `deny` and `ask` decide alone. */
48
+ export declare const fetchesUnder: (level: Level, key: PermissionKey) => boolean;
49
+ /**
50
+ * Whether a fetch a read adds on its own (a sync first, a server search) runs at `level`: it is never asked, so `ask`
51
+ * does not, and `readonly` still fetches.
52
+ */
53
+ export declare const fetchesAt: (level: Level) => boolean;
54
+ /** Whether `level` stops a write under `key` outright: `deny` always, `readonly` unless the key only fetches. */
55
+ export declare const stops: (level: Level, key: PermissionKey) => boolean;
42
56
  /**
43
57
  * The most specific key the owner set wins. A built-in default (`DEFAULT_PERMISSIONS`) only ever
44
58
  * tightens: against a broader key of the owner's, the stricter of the two holds — so
@@ -121,6 +121,38 @@ export const layerPermissions = (layers) => {
121
121
  * at a terminal writes it, so an agent cannot lift it with `config set`.
122
122
  */
123
123
  export const CEILING_KEY = "*";
124
+ /**
125
+ * Asked of the guard for their permission level, yet they only read from the messenger or work here: reads go on
126
+ * during a hold and under the read-only lock, which promises reads and syncs.
127
+ */
128
+ export const STORE_ONLY_KEYS = new Set([
129
+ "attachments.extract",
130
+ "conversations.embeddings",
131
+ "conversations.links",
132
+ "messages.server-search",
133
+ "messages.sync-first",
134
+ "metadata.sync",
135
+ "stats.contacts.top.sync-first",
136
+ "stats.messages.counters.sync",
137
+ "stats.messages.show.sync-first",
138
+ "stats.messages.top.sync-first",
139
+ "store.gaps.repair",
140
+ ]);
141
+ /**
142
+ * Those of `STORE_ONLY_KEYS` that only fetch from the messenger into the store: a `readonly` level lets them run, as it
143
+ * lets a sync (owner ruling, 2026-11-14). Work done here on what is stored, such as a file's text or a link between
144
+ * conversations, stays a write that `readonly` stops.
145
+ */
146
+ const FETCH_KEYS = new Set([...STORE_ONLY_KEYS].filter((key) => !["attachments.extract", "conversations.embeddings", "conversations.links"].includes(key)));
147
+ /** Whether `level` lets a key that only fetches into the store run: `readonly` does, `deny` and `ask` decide alone. */
148
+ export const fetchesUnder = (level, key) => level === "readonly" && FETCH_KEYS.has(key);
149
+ /**
150
+ * Whether a fetch a read adds on its own (a sync first, a server search) runs at `level`: it is never asked, so `ask`
151
+ * does not, and `readonly` still fetches.
152
+ */
153
+ export const fetchesAt = (level) => level === "allow" || level === "readonly";
154
+ /** Whether `level` stops a write under `key` outright: `deny` always, `readonly` unless the key only fetches. */
155
+ export const stops = (level, key) => level === "deny" || (level === "readonly" && !FETCH_KEYS.has(key));
124
156
  const ALLOWED = { level: "allow", key: null };
125
157
  const ORDER = { deny: 0, readonly: 1, ask: 2, allow: 3 };
126
158
  const nearest = (levels, key) => {
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { timezoneOf } from "@wirecat/cli-base/query";
2
3
  import { mailTurn } from "../mail/owed.js";
3
4
  import { MAIL_AGENDA_COLUMNS, queryFilter, } from "../store/store.js";
4
5
  const absent = (error) => {
@@ -15,7 +16,7 @@ export const mailActivity = async (store, account, since, chats) => {
15
16
  if (!stored)
16
17
  return { chats: [], storedAt: null, coverage: () => [] };
17
18
  const where = chats
18
- ? queryFilter(chats, MAIL_AGENDA_COLUMNS, { command: "tasks agenda" })
19
+ ? queryFilter(chats, MAIL_AGENDA_COLUMNS, { command: "tasks agenda", zone: timezoneOf() })
19
20
  : undefined;
20
21
  const threads = await store.mail.threadActivity(stored.id, since, where);
21
22
  const synced = await store.sync.syncState(account, "mail_coverage");
@@ -1,4 +1,4 @@
1
- import { queryError, queryFieldsOf, walkQuery, } from "@wirecat/cli-base/query";
1
+ import { queryError, queryFieldsOf, timezoneOf, walkQuery, } from "@wirecat/cli-base/query";
2
2
  import { formatLocator, isLocator, parseLocator } from "../domain/locator.js";
3
3
  import { formatReference } from "../domain/references.js";
4
4
  import { agenda } from "../entities/agenda.js";
@@ -65,7 +65,7 @@ export const agendaService = (deps, now = Date.now) => ({
65
65
  const open = await find();
66
66
  const tags = await taskTagFilters(store, parts.tasks);
67
67
  const listed = parts.tasks
68
- ? await find(queryFilter(parts.tasks, taskColumns(holder, at, tags), { command: "tasks agenda" }))
68
+ ? await find(queryFilter(parts.tasks, taskColumns(holder, at, tags), { command: "tasks agenda", zone: timezoneOf() }))
69
69
  : open;
70
70
  const tasks = listed
71
71
  .map((task) => ({ task, reasons: reasonsOf(task, at, dueWithin) }))
@@ -106,7 +106,9 @@ export const agendaService = (deps, now = Date.now) => ({
106
106
  }));
107
107
  const mail = account.provider === "email" ? await mailActivity(store, account, at - within, parts.chats) : undefined;
108
108
  const activity = mail ??
109
- (await store.chats.chatActivity(account, at - within, parts.chats ? queryFilter(parts.chats, AGENDA_COLUMNS, { command: "tasks agenda" }) : undefined));
109
+ (await store.chats.chatActivity(account, at - within, parts.chats
110
+ ? queryFilter(parts.chats, AGENDA_COLUMNS, { command: "tasks agenda", zone: timezoneOf() })
111
+ : undefined));
110
112
  const turnOf = (chat) => "turn" in chat ? chat.turn : chat.lastFromOwner === null ? null : chat.lastFromOwner ? "waiting" : "owed";
111
113
  const chats = activity.chats.map(({ lastMessageId, ...chat }) => ({
112
114
  turn: turnOf({ lastMessageId, ...chat }),
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { constants, mkdirSync } from "node:fs";
3
3
  import { lstat, open, readFile, stat } from "node:fs/promises";
4
4
  import { CliError } from "@wirecat/cli-base";
5
- import { queryFieldsOf, walkQuery } from "@wirecat/cli-base/query";
5
+ import { queryFieldsOf, timezoneOf, walkQuery } from "@wirecat/cli-base/query";
6
6
  import { directoryPaths } from "../attachments/directory.js";
7
7
  import { documentExtractor, documentKind } from "../attachments/documents.js";
8
8
  import { classify, engineMissing, extractText, importEngine, MAX_TEXT_CHARS, } from "../attachments/extract.js";
@@ -367,7 +367,9 @@ export const attachmentsService = (deps) => ({
367
367
  for (const node of walkQuery(query.root))
368
368
  if (node.field === "chat" && node.operator !== "wildcard" && !chats.has(node.value))
369
369
  chats.set(node.value, await chatIdIn(deps.messenger, node.value, store, { includeLeft: true }));
370
- const where = query ? queryFilter(query, attachmentColumns(chats), { command: "attachments list" }) : undefined;
370
+ const where = query
371
+ ? queryFilter(query, attachmentColumns(chats), { command: "attachments list", zone: timezoneOf() })
372
+ : undefined;
371
373
  const views = await store.attachments.attachments({ ...(where ? { where } : {}), offset, limit: limit + 1 });
372
374
  return { items: views.slice(0, limit).map((view) => itemOf(account, view)), hasMore: views.length > limit };
373
375
  },
@@ -0,0 +1,17 @@
1
+ import { type CallStats, type MeetingCallsInput } from "../meetings/index.js";
2
+ import type { MessageStore } from "../store/store.js";
3
+ export type CallStatsRequest = MeetingCallsInput & {
4
+ timeZone?: string;
5
+ callbackWithinMs?: number;
6
+ missedLimit?: number;
7
+ };
8
+ export type CallStatsAnswer = CallStats & {
9
+ accountId: number;
10
+ /** Selected meetings that are not calls: no direction or outcome a phone system writes, and no client. */
11
+ notCalls: number;
12
+ };
13
+ /**
14
+ * The call numbers of one account over the selected meetings. A callback may come after `until` or from an employee
15
+ * the selection leaves out, so the account's calls up to `callbackWithinMs` after the selection are read too.
16
+ */
17
+ export declare const readCallStats: (store: Pick<MessageStore, "meetings">, request: CallStatsRequest) => Promise<CallStatsAnswer>;
@@ -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;