@wirecat/cli-core 0.651.0 → 0.653.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 (42) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/documents/catalog.d.ts +2 -1
  4. package/dist/documents/catalog.js +4 -3
  5. package/dist/documents/index.d.ts +1 -1
  6. package/dist/documents/index.js +1 -1
  7. package/dist/documents/model.d.ts +3 -0
  8. package/dist/documents/scope.d.ts +13 -0
  9. package/dist/documents/scope.js +7 -0
  10. package/dist/domain/providers.js +3 -0
  11. package/dist/entities/index.d.ts +10 -10
  12. package/dist/entities/task-results.d.ts +10 -10
  13. package/dist/mail/index.d.ts +1 -0
  14. package/dist/mail/index.js +1 -0
  15. package/dist/mail/meeting-notes.d.ts +50 -0
  16. package/dist/mail/meeting-notes.js +198 -0
  17. package/dist/mail/rule-input.d.ts +1 -0
  18. package/dist/mail/rule-input.js +1 -0
  19. package/dist/mail/rule-stored.js +2 -0
  20. package/dist/mail/rules.d.ts +2 -0
  21. package/dist/mail/sync-types.d.ts +3 -0
  22. package/dist/mail/sync.js +12 -0
  23. package/dist/meetings/events.d.ts +3 -1
  24. package/dist/meetings/events.js +3 -1
  25. package/dist/meetings/index.d.ts +1 -1
  26. package/dist/meetings/pull.js +1 -1
  27. package/dist/meetings/source.d.ts +5 -0
  28. package/dist/meetings/store.d.ts +5 -0
  29. package/dist/meetings/transcript-store.d.ts +4 -0
  30. package/dist/services/documents/plan.d.ts +2 -1
  31. package/dist/services/documents/plan.js +35 -10
  32. package/dist/services/documents/ports.d.ts +2 -0
  33. package/dist/services/documents/sync.js +17 -7
  34. package/dist/services/metadata.d.ts +1 -1
  35. package/dist/services/search-all.js +20 -1
  36. package/dist/store/sqlite/link-kinds.d.ts +2 -2
  37. package/dist/store/sqlite/link-kinds.js +2 -2
  38. package/dist/store/sqlite/meeting-transcript-documents.d.ts +10 -0
  39. package/dist/store/sqlite/meeting-transcript-documents.js +52 -0
  40. package/dist/store/sqlite/meetings.d.ts +2 -2
  41. package/dist/store/sqlite/meetings.js +7 -2
  42. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,35 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.653.0 — 13.11.2026
9
+
10
+ ### Added
11
+
12
+ - **Mail can be a meeting's notes.** A mail rule's `meeting_notes: "<provider>"` saves each email it matches as a
13
+ meeting of that provider too, in the account named by the mailbox's address, once at the end of every mail sync;
14
+ `saveMeetingNotes(store, address, rules, { since })` reads mail stored earlier the same way, and a provider that
15
+ fails is a warning, never a failed sync. The first provider is `telemost`: Yandex Telemost mails its notes from
16
+ `keeper@telemost.yandex.ru` (`MEETING_NOTES`). The notes give the day, not the hours, so the meeting takes its times
17
+ from the event it is linked to, or from the owner's one calendar entry in the same room that day (in Moscow's zone
18
+ or the computer's); otherwise it starts at the day's start with `metadata.time_precision: "day"`, and no event is
19
+ made for it. The saved notes are cleaned as calendar text is: links without their queries, passcode lines dropped.
20
+ - **`MeetingSource.createsEvents: false`** links a source's meetings to an event the owner already has and never
21
+ makes one; `linkEvent` takes `{ create: false }` for it.
22
+ - **`telemost` is a provider** (kind `meetings`).
23
+
24
+ ## 0.652.0 — 13.11.2026
25
+
26
+ ### Added
27
+
28
+ - **A document sync takes a saved query beside its selected folders** (`SyncOptions.query`, `SourceQuery`). `include`
29
+ imports every file the query lists wherever it sits, read again on each sync, and drops one that stops matching;
30
+ `exclude` keeps matching files out even inside a selected folder. A profile without a query keeps its checkpoint.
31
+ drive uses it for Google Meet transcripts and Gemini notes that live in organizers' Drives.
32
+ - **A meeting transcript can name the Drive file it was saved as** (`TranscriptInput.driveFileId`). The store links the
33
+ meeting to that file's document whichever arrives first, and `search all` then shows the meeting once instead of the
34
+ meeting and the same Google Doc. A document whose meeting is not among the hits still shows. A newer transcript
35
+ that names another file replaces the link.
36
+
8
37
  ## 0.651.0 — 13.11.2026
9
38
 
10
39
  ### Added
@@ -24,12 +24,12 @@ export interface DailyArchiveTimerInput {
24
24
  }
25
25
  export declare const dailyArchiveTimer: (input: DailyArchiveTimerInput) => DailyArchiveTimer;
26
26
  export declare const manageDailyArchiveTimer: (plan: DailyArchiveTimer, action: "install" | "start" | "stop" | "status" | "uninstall", system: Pick<ServerSystem, "platform" | "run">, env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<{
27
+ action?: undefined;
27
28
  name: string;
28
29
  installed: boolean;
29
30
  active: boolean;
30
31
  servicePath: string;
31
32
  timerPath: string;
32
- action?: undefined;
33
33
  } | {
34
34
  active?: undefined;
35
35
  name: string;
@@ -1,2 +1,3 @@
1
1
  import type { SourceFile, SourceState } from "./model.js";
2
- export declare const catalogFiles: <M extends SourceFile>(state: SourceState<M>, roots: string[]) => M[];
2
+ import { type SourceQuery } from "./scope.js";
3
+ export declare const catalogFiles: <M extends SourceFile>(state: SourceState<M>, roots: string[], query?: SourceQuery<M>) => M[];
@@ -1,6 +1,7 @@
1
- import { within } from "./scope.js";
2
- export const catalogFiles = (state, roots) => {
1
+ import { inScope } from "./scope.js";
2
+ export const catalogFiles = (state, roots, query) => {
3
3
  const folders = state.pending?.folders ?? state.folders;
4
+ const matched = new Set(state.pending?.matched ?? state.matched ?? []);
4
5
  const files = new Map(Object.values(state.documents).map((doc) => [doc.metadata.id, doc.metadata]));
5
6
  for (const skip of state.skipped)
6
7
  if (skip.file)
@@ -13,5 +14,5 @@ export const catalogFiles = (state, roots) => {
13
14
  else if (job.file)
14
15
  files.set(job.id, job.file);
15
16
  }
16
- return [...files.values()].filter((file) => within(file, roots, folders));
17
+ return [...files.values()].filter((file) => inScope(file, roots, folders, matched, query));
17
18
  };
@@ -14,4 +14,4 @@ export { catalogFiles } from "./catalog.js";
14
14
  export { markdownBlocks, type PlacedBlock, placedMarkdownBlocks } from "./markdown-blocks.js";
15
15
  export type { DocumentSource, IndexedSource, PictureWriter, SourceChange, SourceContent, SourceFile, SourceIndex, SourceSkip, SourceState, SourceStatePort, SourceWalk, SourceWork, TabText, } from "./model.js";
16
16
  export type { ConflictPart, DocumentTarget, Keep, LocalDocument, Prepared, PushEntry, Pushed, PushPlan, PushState, PushStatePort, RemoteChange, } from "./push-model.js";
17
- export { within } from "./scope.js";
17
+ export { inScope, type SourceQuery, within } from "./scope.js";
@@ -11,4 +11,4 @@ export { syncDocuments } from "../services/documents/sync.js";
11
11
  export { blockKey, blockShape, normalizeInlines } from "./blocks.js";
12
12
  export { catalogFiles } from "./catalog.js";
13
13
  export { markdownBlocks, placedMarkdownBlocks } from "./markdown-blocks.js";
14
- export { within } from "./scope.js";
14
+ export { inScope, within } from "./scope.js";
@@ -77,7 +77,10 @@ export interface SourceState<M extends SourceFile = SourceFile> {
77
77
  folders: Record<string, M>;
78
78
  jobs: SourceWork<M>[];
79
79
  skipped: SourceSkip<M>[];
80
+ /** Files a saved query found, in scope wherever they sit. */
81
+ matched?: string[];
80
82
  };
83
+ matched?: string[];
81
84
  lastSync?: string;
82
85
  }
83
86
  export interface PictureWriter {
@@ -1,2 +1,15 @@
1
1
  import type { SourceFile } from "./model.js";
2
2
  export declare const within: (file: SourceFile, roots: string[], folders: Record<string, SourceFile>, seen?: Set<string>) => boolean;
3
+ /**
4
+ * A saved query beside the selected folders: `include` adds the files it finds wherever they sit, `exclude` keeps the
5
+ * files it matches out even inside a selected folder.
6
+ */
7
+ export interface SourceQuery<M extends SourceFile = SourceFile> {
8
+ /** Part of the sync's scope: a changed query or mode plans the sync again from the start. */
9
+ key: string;
10
+ mode: "include" | "exclude";
11
+ matches(file: M): boolean;
12
+ /** Every file the query finds, read on each sync: a file shared by another owner may never reach the change feed. */
13
+ list?(): Promise<M[]>;
14
+ }
15
+ export declare const inScope: <M extends SourceFile>(file: M, roots: string[], folders: Record<string, SourceFile>, matched?: ReadonlySet<string>, query?: SourceQuery<M>) => boolean;
@@ -12,3 +12,10 @@ export const within = (file, roots, folders, seen = new Set()) => {
12
12
  return folder ? within(folder, roots, folders, next) : roots.includes(id);
13
13
  });
14
14
  };
15
+ export const inScope = (file, roots, folders, matched = new Set(), query) => {
16
+ if (file.trashed)
17
+ return false;
18
+ if (query?.mode === "exclude" && query.matches(file))
19
+ return false;
20
+ return matched.has(file.id) || within(file, roots, folders);
21
+ };
@@ -19,6 +19,8 @@ export const PROVIDERS = [
19
19
  { name: "obsidian", kind: "notes", aliases: [] },
20
20
  { name: "added", kind: "notes", aliases: [] },
21
21
  { name: "zoom", kind: "meetings", aliases: [] },
22
+ // Its meetings come from the notes Telemost mails (`keeper@telemost.yandex.ru`), read by a mail rule.
23
+ { name: "telemost", kind: "meetings", aliases: [] },
22
24
  // A phone export's records: its SMS and its calls in the one account the import names.
23
25
  { name: "phone", kind: "messages", kinds: ["messages", "events"], aliases: [], imported: true },
24
26
  // Any other import: a folder of notes, a CRM's export, a script's records, under `import:<what it is>`.
@@ -34,6 +36,7 @@ const LABELS = {
34
36
  "google-drive": "Google Drive",
35
37
  added: "added by hand",
36
38
  email: "mail",
39
+ telemost: "Telemost",
37
40
  };
38
41
  /** How a text names a provider to a person: `MAX`, not `max`. */
39
42
  export const providerLabel = (provider) => LABELS[provider] ?? provider;
@@ -4723,7 +4723,7 @@ export declare const ENTITIES: {
4723
4723
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
4724
4724
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
4725
4725
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4726
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
4726
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
4727
4727
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4728
4728
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4729
4729
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -4738,7 +4738,7 @@ export declare const ENTITIES: {
4738
4738
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
4739
4739
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
4740
4740
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4741
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
4741
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
4742
4742
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4743
4743
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4744
4744
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -4839,7 +4839,7 @@ export declare const ENTITIES: {
4839
4839
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
4840
4840
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
4841
4841
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4842
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
4842
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
4843
4843
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4844
4844
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4845
4845
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -4854,7 +4854,7 @@ export declare const ENTITIES: {
4854
4854
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
4855
4855
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
4856
4856
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4857
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
4857
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
4858
4858
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4859
4859
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4860
4860
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -4956,7 +4956,7 @@ export declare const ENTITIES: {
4956
4956
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
4957
4957
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
4958
4958
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4959
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
4959
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
4960
4960
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4961
4961
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4962
4962
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -4971,7 +4971,7 @@ export declare const ENTITIES: {
4971
4971
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
4972
4972
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
4973
4973
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4974
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
4974
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
4975
4975
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4976
4976
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4977
4977
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -5101,7 +5101,7 @@ export declare const ENTITIES: {
5101
5101
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
5102
5102
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
5103
5103
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5104
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
5104
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
5105
5105
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5106
5106
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5107
5107
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -5116,7 +5116,7 @@ export declare const ENTITIES: {
5116
5116
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
5117
5117
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
5118
5118
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5119
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
5119
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
5120
5120
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5121
5121
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5122
5122
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -5211,7 +5211,7 @@ export declare const ENTITIES: {
5211
5211
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
5212
5212
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
5213
5213
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5214
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
5214
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
5215
5215
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5216
5216
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5217
5217
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -5226,7 +5226,7 @@ export declare const ENTITIES: {
5226
5226
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
5227
5227
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
5228
5228
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5229
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
5229
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
5230
5230
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5231
5231
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
5232
5232
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -54,7 +54,7 @@ export declare const taskCard: v.StrictObjectSchema<{
54
54
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
55
55
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
56
56
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
57
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
57
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
58
58
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
59
59
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
60
60
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -69,7 +69,7 @@ export declare const taskCard: v.StrictObjectSchema<{
69
69
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
70
70
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
71
71
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
72
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
72
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
73
73
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
74
74
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
75
75
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -172,7 +172,7 @@ export declare const taskCreated: v.StrictObjectSchema<{
172
172
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
173
173
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
174
174
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
175
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
175
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
176
176
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
177
177
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
178
178
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -187,7 +187,7 @@ export declare const taskCreated: v.StrictObjectSchema<{
187
187
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
188
188
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
189
189
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
190
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
190
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
191
191
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
192
192
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
193
193
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -291,7 +291,7 @@ export declare const taskLinks: v.UnionSchema<[v.StrictObjectSchema<{
291
291
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
292
292
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
293
293
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
294
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
294
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
295
295
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
296
296
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
297
297
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -306,7 +306,7 @@ export declare const taskLinks: v.UnionSchema<[v.StrictObjectSchema<{
306
306
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
307
307
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
308
308
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
309
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
309
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
310
310
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
311
311
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
312
312
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -438,7 +438,7 @@ export declare const taskMerge: v.StrictObjectSchema<{
438
438
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
439
439
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
440
440
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
441
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
441
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
442
442
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
443
443
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
444
444
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -453,7 +453,7 @@ export declare const taskMerge: v.StrictObjectSchema<{
453
453
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
454
454
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
455
455
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
456
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
456
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
457
457
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
458
458
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
459
459
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -550,7 +550,7 @@ export declare const taskUnmerge: v.StrictObjectSchema<{
550
550
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
551
551
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
552
552
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
553
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
553
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
554
554
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
555
555
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
556
556
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -565,7 +565,7 @@ export declare const taskUnmerge: v.StrictObjectSchema<{
565
565
  readonly to: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
566
566
  readonly kind: v.PicklistSchema<readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"], undefined>;
567
567
  readonly anchor: v.NullableSchema<v.StringSchema<undefined>, undefined>;
568
- readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar"], undefined>;
568
+ readonly origin: v.PicklistSchema<readonly ["file", "owner", "suggested", "message", "calendar", "meeting"], undefined>;
569
569
  readonly target_text: v.NullableSchema<v.StringSchema<undefined>, undefined>;
570
570
  readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
571
571
  readonly purpose: v.NullableSchema<v.StringSchema<undefined>, undefined>;
@@ -10,6 +10,7 @@ export { type AuthVerdicts, HEADER_FIELDS, headersOf, type MailHeaders, mailHead
10
10
  export { type MailIdsInput, mailIds } from "./ids.js";
11
11
  export { decodedLabelName, decodeMailboxName, labelName, systemLabel } from "./labels.js";
12
12
  export { acknowledgeMark, advancePastSkipped, type BulkExcerpt, cursorOf, HOLD_PARTIAL_MS, HOLDER, MARK_BATCH, type MailMark, type MailWaiting, type MarkedHit, type MarkRead, type MarkRewind, mailWaiting, markOf, marksOf, type RewoundMark, readPastMark, rewindMark, type SkipReason, } from "./marks.js";
13
+ export { MEETING_NOTES, MEETING_NOTES_PROVIDERS, mailMeetingSource, notesOf, saveMeetingNotes, } from "./meeting-notes.js";
13
14
  export { BULK_TRIAGE_DEFAULTS, type BulkSorted, type BulkTriage, excerptOf, NEWSLETTER_DEFAULTS, NEWSLETTER_SENDERS, NEWSLETTER_WORDS, type NewsletterCues, newsletterSorter, ORDER_WORDS, } from "./newsletter.js";
14
15
  export { type MailTurn, mailTurn } from "./owed.js";
15
16
  export { type Address, htmlToText, looksLikeHtml, MAX_ATTACHMENTS, MAX_BODY_CHARS, type ParsedMail, parseMail, } from "./parse.js";
@@ -10,6 +10,7 @@ export { HEADER_FIELDS, headersOf, mailHeadersOf } from "./headers.js";
10
10
  export { mailIds } from "./ids.js";
11
11
  export { decodedLabelName, decodeMailboxName, labelName, systemLabel } from "./labels.js";
12
12
  export { acknowledgeMark, advancePastSkipped, cursorOf, HOLD_PARTIAL_MS, HOLDER, MARK_BATCH, mailWaiting, markOf, marksOf, readPastMark, rewindMark, } from "./marks.js";
13
+ export { MEETING_NOTES, MEETING_NOTES_PROVIDERS, mailMeetingSource, notesOf, saveMeetingNotes, } from "./meeting-notes.js";
13
14
  export { BULK_TRIAGE_DEFAULTS, excerptOf, NEWSLETTER_DEFAULTS, NEWSLETTER_SENDERS, NEWSLETTER_WORDS, newsletterSorter, ORDER_WORDS, } from "./newsletter.js";
14
15
  export { mailTurn } from "./owed.js";
15
16
  export { htmlToText, looksLikeHtml, MAX_ATTACHMENTS, MAX_BODY_CHARS, parseMail, } from "./parse.js";
@@ -0,0 +1,50 @@
1
+ import { type MeetingSource, type MeetingStore, type RunReport, type SummaryContent } from "../meetings/index.js";
2
+ import type { MessageStore } from "../store/index.js";
3
+ import { type MailRule } from "./rules.js";
4
+ interface NotesKind {
5
+ /** Who mails them: what `rules add --meeting-notes <provider>` matches when no sender is given. */
6
+ senders: readonly string[];
7
+ /** The meeting's day, from the subject; null when the subject does not say. */
8
+ day(subject: string): {
9
+ year: number;
10
+ month: number;
11
+ day: number;
12
+ } | null;
13
+ /**
14
+ * The UTC offsets, in hours, the subject's day may be written in. The day window spans all of them and the
15
+ * computer's own zone, so a meeting just after midnight in one is still found.
16
+ */
17
+ offsets: readonly number[];
18
+ /** The headings the notes are split under, in the case they are written. */
19
+ headings: readonly string[];
20
+ overview: string;
21
+ }
22
+ /** The meeting-notes mail each provider sends. A provider not here cannot be named by a rule. */
23
+ export declare const MEETING_NOTES: Readonly<Record<string, NotesKind>>;
24
+ export declare const MEETING_NOTES_PROVIDERS: string[];
25
+ /** The notes cut at their headings; text before the first heading stays only in `content`. */
26
+ export declare const notesOf: (text: string, kind: Pick<NotesKind, "headings" | "overview">) => SummaryContent;
27
+ /**
28
+ * Meetings read from stored mail a meeting-notes rule matches, for `pull`. The notes give the day, not the hours:
29
+ * the event the meeting is already linked to, or the one event in the same room that day, gives its times; otherwise
30
+ * it starts at the day's start, says so in `metadata.time_precision`, and no event is made for it.
31
+ */
32
+ export declare const mailMeetingSource: ({ store, meetings, address, rules, provider, accountId, }: {
33
+ store: MessageStore;
34
+ meetings: Pick<MeetingStore, "eventCandidates" | "meetings" | "events">;
35
+ address: string;
36
+ rules: readonly MailRule[];
37
+ provider: string;
38
+ /** The provider's account the meetings are saved in; absent before its first save. */
39
+ accountId?: number;
40
+ }) => MeetingSource;
41
+ /**
42
+ * Saves as meetings the stored mail each meeting-notes rule matches, from `since`, into the provider's account named
43
+ * by the mailbox's address. Mail stored before the rule was made is read the same way, with an early `since`. A
44
+ * provider that fails is a warning in its report: the mail it was read from is already saved.
45
+ */
46
+ export declare const saveMeetingNotes: (store: MessageStore, address: string, rules: readonly MailRule[], { since, now }: {
47
+ since: string;
48
+ now?: number;
49
+ }) => Promise<Record<string, RunReport>>;
50
+ export {};
@@ -0,0 +1,198 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { calendarText, joinKeyOf, pull, } from "../meetings/index.js";
3
+ import { mailAccountKey } from "./account-key.js";
4
+ import { factsOf } from "./facts.js";
5
+ import { matches } from "./rules.js";
6
+ import { listedOf } from "./stored.js";
7
+ const HOUR_MS = 3_600_000;
8
+ const DAY_MS = 24 * HOUR_MS;
9
+ /** The meeting-notes mail each provider sends. A provider not here cannot be named by a rule. */
10
+ export const MEETING_NOTES = {
11
+ telemost: {
12
+ senders: ["keeper@telemost.yandex.ru"],
13
+ day: (subject) => {
14
+ const found = /(\d{2})\.(\d{2})\.(\d{4})/u.exec(subject);
15
+ return found ? { day: Number(found[1]), month: Number(found[2]), year: Number(found[3]) } : null;
16
+ },
17
+ // Moscow, Yandex's default; the zone of the owner's Yandex account is not known here.
18
+ offsets: [3],
19
+ headings: ["Итоги", "Что обсудили", "Задачи", "Открытые вопросы", "Следующая встреча"],
20
+ overview: "Итоги",
21
+ },
22
+ };
23
+ export const MEETING_NOTES_PROVIDERS = Object.keys(MEETING_NOTES);
24
+ const LINK = /https?:\/\/[^\s<>"')\]]+/giu;
25
+ const textOf = (email) => calendarText(email.bodyText?.trim() ? email.bodyText : email.bodyHtml)?.replace(/\r\n?/gu, "\n") ?? "";
26
+ const headingOf = (line, headings) => {
27
+ const plain = line
28
+ .replace(/^(?:[\s#*>-]|\p{Extended_Pictographic}|️)+/u, "")
29
+ .replace(/[\s:*]+$/u, "")
30
+ .toLowerCase();
31
+ return headings.find((heading) => heading.toLowerCase() === plain);
32
+ };
33
+ /** The notes cut at their headings; text before the first heading stays only in `content`. */
34
+ export const notesOf = (text, kind) => {
35
+ const parts = [];
36
+ for (const line of text.split("\n")) {
37
+ const heading = headingOf(line, kind.headings);
38
+ if (heading !== undefined)
39
+ parts.push({ label: heading, lines: [] });
40
+ else
41
+ parts.at(-1)?.lines.push(line);
42
+ }
43
+ const sections = parts
44
+ .map(({ label, lines }) => ({ label, text: lines.join("\n").trim() }))
45
+ .filter(({ text }) => text !== "");
46
+ return {
47
+ title: null,
48
+ overview: sections.find(({ label }) => label === kind.overview)?.text ?? null,
49
+ sections: sections.filter(({ label }) => label !== kind.overview),
50
+ nextSteps: [],
51
+ content: text.trim() || null,
52
+ };
53
+ };
54
+ /** The first link in the notes that names a meeting room, as `joinKeyOf` reads it: never a plain page link. */
55
+ const roomOf = (text) => {
56
+ for (const [url] of text.matchAll(LINK))
57
+ if (/\/j\/[^/]+$/u.test(url) && joinKeyOf(url))
58
+ return url;
59
+ return null;
60
+ };
61
+ /** The day as a window: from its first midnight in any of the zones to its last. */
62
+ const dayWindow = (kind, date) => {
63
+ const local = new Date(date.year, date.month - 1, date.day).getTime();
64
+ const utc = Date.UTC(date.year, date.month - 1, date.day);
65
+ const starts = [local, ...kind.offsets.map((offset) => utc - offset * HOUR_MS)];
66
+ const start = starts.reduce((low, at) => Math.min(low, at));
67
+ const end = starts.reduce((high, at) => Math.max(high, at)) + DAY_MS;
68
+ return { start, end, local };
69
+ };
70
+ /** The stored mail the rules can be matching: by sender when every rule names one, else the whole window. */
71
+ const candidateFacts = async (store, accountId, since, rules) => {
72
+ const senders = rules.map(({ match }) => match.from);
73
+ if (senders.some((sender) => sender === undefined))
74
+ return store.mail.emailFacts({ accountId, since });
75
+ const found = new Map();
76
+ for (const sender of new Set(senders))
77
+ for (const facts of await store.mail.emailFacts({ accountId, since, participant: sender }))
78
+ found.set(facts.externalId, facts);
79
+ return [...found.values()];
80
+ };
81
+ /**
82
+ * Meetings read from stored mail a meeting-notes rule matches, for `pull`. The notes give the day, not the hours:
83
+ * the event the meeting is already linked to, or the one event in the same room that day, gives its times; otherwise
84
+ * it starts at the day's start, says so in `metadata.time_precision`, and no event is made for it.
85
+ */
86
+ export const mailMeetingSource = ({ store, meetings, address, rules, provider, accountId, }) => {
87
+ const kind = MEETING_NOTES[provider];
88
+ const ruling = rules.filter((rule) => rule.meeting_notes === provider);
89
+ const notes = new Map();
90
+ const none = async () => null;
91
+ return {
92
+ provider,
93
+ name: "mail",
94
+ createsEvents: false,
95
+ async meetings(since) {
96
+ if (kind === undefined || ruling.length === 0)
97
+ return [];
98
+ const stored = await store.accounts.storedAccount(mailAccountKey(address)).catch((error) => {
99
+ if (error instanceof CliError && error.code === "not_found")
100
+ return null;
101
+ throw error;
102
+ });
103
+ if (stored === null)
104
+ return [];
105
+ const listed = (await candidateFacts(store, stored.id, Date.parse(since), ruling)).map(listedOf);
106
+ const factsFor = factsOf(listed, ruling);
107
+ const saved = accountId === undefined ? [] : await meetings.meetings({ accountId, includeDeleted: true });
108
+ const linked = new Map(saved.flatMap(({ externalId, eventId }) => (eventId === null ? [] : [[externalId, eventId]])));
109
+ const events = new Map(linked.size ? (await meetings.events()).map((event) => [event.id, event]) : []);
110
+ const found = [];
111
+ for (const item of listed) {
112
+ if (!ruling.some((rule) => matches(rule.match, factsFor(item))))
113
+ continue;
114
+ const email = await store.mail.email(stored.id, item.messageId);
115
+ if (email === null || email.deletedAt !== null)
116
+ continue;
117
+ const subject = email.subject ?? "";
118
+ const sent = email.sentAt ?? email.receivedAt;
119
+ const date = kind.day(subject) ??
120
+ (sent === null
121
+ ? null
122
+ : {
123
+ year: new Date(sent).getFullYear(),
124
+ month: new Date(sent).getMonth() + 1,
125
+ day: new Date(sent).getDate(),
126
+ });
127
+ if (date === null)
128
+ continue;
129
+ const window = dayWindow(kind, date);
130
+ if (!Number.isFinite(window.local))
131
+ continue;
132
+ const text = textOf(email);
133
+ const joinUrl = roomOf(text);
134
+ const linkedId = linked.get(email.externalId);
135
+ const linkedEvent = linkedId === undefined ? undefined : events.get(linkedId);
136
+ const candidates = linkedEvent !== undefined || joinUrl === null
137
+ ? []
138
+ : await meetings.eventCandidates({
139
+ meetingSeriesId: null,
140
+ joinUrl,
141
+ startsAt: window.start,
142
+ endsAt: window.end,
143
+ });
144
+ const timed = linkedEvent ?? (candidates.length === 1 ? candidates[0] : undefined);
145
+ const startsAt = timed?.startsAt ?? null;
146
+ const meeting = {
147
+ joinUrl,
148
+ metadata: { email: email.externalId, time_precision: startsAt === null ? "day" : "event" },
149
+ series: null,
150
+ occurrence: {
151
+ id: email.externalId,
152
+ seriesId: email.externalId,
153
+ title: timed?.title ?? (subject || null),
154
+ startedAt: new Date(startsAt ?? window.local).toISOString(),
155
+ endedAt: startsAt === null || timed?.endsAt == null ? null : new Date(timed.endsAt).toISOString(),
156
+ },
157
+ };
158
+ notes.set(email.externalId, { meeting, summary: notesOf(text, kind) });
159
+ found.push(meeting);
160
+ }
161
+ return found;
162
+ },
163
+ participants: none,
164
+ transcript: none,
165
+ chat: none,
166
+ summary: async (id) => notes.get(id)?.summary ?? null,
167
+ files: none,
168
+ };
169
+ };
170
+ /**
171
+ * Saves as meetings the stored mail each meeting-notes rule matches, from `since`, into the provider's account named
172
+ * by the mailbox's address. Mail stored before the rule was made is read the same way, with an early `since`. A
173
+ * provider that fails is a warning in its report: the mail it was read from is already saved.
174
+ */
175
+ export const saveMeetingNotes = async (store, address, rules, { since, now = Date.now() }) => {
176
+ const reports = {};
177
+ for (const provider of new Set(rules.flatMap(({ meeting_notes }) => (meeting_notes ? [meeting_notes] : [])))) {
178
+ if (MEETING_NOTES[provider] === undefined)
179
+ continue;
180
+ try {
181
+ const key = { provider, account: address.toLowerCase() };
182
+ const accountId = await store.accounts.saveAccount(key, { name: address.toLowerCase() });
183
+ const source = mailMeetingSource({ store, meetings: store.meetings, address, rules, provider, accountId });
184
+ reports[provider] = await pull(source, store.meetings, { accountId, since, now });
185
+ }
186
+ catch (error) {
187
+ const message = error instanceof Error ? error.message : "meeting notes could not be saved";
188
+ reports[provider] = {
189
+ meetings: 0,
190
+ participants: 0,
191
+ transcriptRows: 0,
192
+ summaries: 0,
193
+ warnings: [{ externalId: "", message }],
194
+ };
195
+ }
196
+ }
197
+ return reports;
198
+ };
@@ -6,6 +6,7 @@ export declare const ruleInput: (rule: MailRule, source?: string) => {
6
6
  store: string;
7
7
  tags?: string[] | undefined;
8
8
  tags_skipped?: Record<string, string> | undefined;
9
+ meeting_notes?: string | undefined;
9
10
  };
10
11
  protected: boolean;
11
12
  source: string;
@@ -24,6 +24,7 @@ export const ruleInput = (rule, source = rule.source ?? "owner") => ({
24
24
  store: STORE_ACTION[rule.action],
25
25
  ...(rule.tags?.length ? { tags: rule.tags } : {}),
26
26
  ...(rule.tags_skipped && Object.keys(rule.tags_skipped).length ? { tags_skipped: rule.tags_skipped } : {}),
27
+ ...(rule.meeting_notes ? { meeting_notes: rule.meeting_notes } : {}),
27
28
  },
28
29
  protected: rule.protected === true,
29
30
  source,
@@ -41,11 +41,13 @@ export const storedMailRule = (stored) => {
41
41
  const tagsSkipped = skipped !== null && typeof skipped === "object" && !Array.isArray(skipped)
42
42
  ? Object.fromEntries(Object.entries(skipped).filter(([, why]) => typeof why === "string"))
43
43
  : {};
44
+ const meetingNotes = stored.actions.meeting_notes;
44
45
  return {
45
46
  id: stored.id,
46
47
  match: Object.fromEntries(entries),
47
48
  action,
48
49
  ...(tags.length ? { tags: tags } : {}),
50
+ ...(typeof meetingNotes === "string" && meetingNotes ? { meeting_notes: meetingNotes } : {}),
49
51
  ...(Object.keys(tagsSkipped).length ? { tags_skipped: tagsSkipped } : {}),
50
52
  ...(stored.reason === null ? {} : { reason: stored.reason }),
51
53
  ...(stored.protected ? { protected: true } : {}),
@@ -39,6 +39,8 @@ export interface MailRule {
39
39
  reason?: string;
40
40
  /** Stored in full, and no cleanup may cut, archive or trash it, whatever other rules or presets say. */
41
41
  protected?: boolean;
42
+ /** The mail is a meeting's notes from this provider (`telemost`): each email it matches is saved as a meeting too. */
43
+ meeting_notes?: string;
42
44
  /** owner, preset:<name>, probe or gmail-filter. */
43
45
  source?: string;
44
46
  decided_at: string;
@@ -1,4 +1,5 @@
1
1
  import type { BudgetStop, RunBudget } from "../background/budget.js";
2
+ import type { RunReport } from "../meetings/index.js";
2
3
  import type { LoadEngine } from "../readers/types.js";
3
4
  import type { AccountKey, MessageStore } from "../store/index.js";
4
5
  import type { MailAttachmentPolicy } from "./attachments.js";
@@ -78,6 +79,8 @@ export interface MailSyncResult {
78
79
  stillFailed: number;
79
80
  missing: number;
80
81
  };
82
+ /** Per provider, the meetings saved from mail a meeting-notes rule matches. */
83
+ meetingNotes?: Record<string, RunReport>;
81
84
  }
82
85
  export interface MailSyncOptions {
83
86
  account: MailAccount;
package/dist/mail/sync.js CHANGED
@@ -11,6 +11,7 @@ import { GMAIL_ALL_MAIL, mailFolders } from "./folders.js";
11
11
  import { dropMissing, tooManyGone } from "./gone.js";
12
12
  import { mailHeadersOf } from "./headers.js";
13
13
  import { flagsToRefresh, proveByLocation } from "./locations.js";
14
+ import { saveMeetingNotes } from "./meeting-notes.js";
14
15
  import { MAX_BODY_CHARS, parseMail } from "./parse.js";
15
16
  import { completePartial } from "./partial.js";
16
17
  import { FETCH_SLICE, keyOf, readQuick } from "./quick.js";
@@ -36,6 +37,17 @@ const LIST_SLICE = 200;
36
37
  const STORE_BUSY_TRIES = 5;
37
38
  const STORE_BUSY_WAIT_MS = 2_000;
38
39
  export const syncMail = async (source, store, options) => {
40
+ const result = await syncAndComplete(source, store, options);
41
+ const rules = options.account.rules ?? [];
42
+ if (!rules.some(({ meeting_notes }) => meeting_notes) || options.signal?.aborted)
43
+ return result;
44
+ const now = (options.now ?? Date.now)();
45
+ return {
46
+ ...result,
47
+ meetingNotes: await saveMeetingNotes(store, options.account.address, rules, { since: result.since, now }),
48
+ };
49
+ };
50
+ const syncAndComplete = async (source, store, options) => {
39
51
  const result = await syncRounds(source, store, options);
40
52
  if (options.completePartial === false || options.retryAttachments || options.account.mode === "mbox")
41
53
  return result;
@@ -1,3 +1,5 @@
1
1
  import type { Event } from "./model.js";
2
2
  import type { MeetingDetails, MeetingStore } from "./store.js";
3
- export declare const linkEvent: (store: MeetingStore, details: MeetingDetails, now?: number) => Promise<Event | null>;
3
+ export declare const linkEvent: (store: MeetingStore, details: MeetingDetails, now?: number, { create }?: {
4
+ create?: boolean;
5
+ }) => Promise<Event | null>;
@@ -1,4 +1,4 @@
1
- export const linkEvent = async (store, details, now = Date.now()) => {
1
+ export const linkEvent = async (store, details, now = Date.now(), { create = true } = {}) => {
2
2
  const current = await store.meeting(details.meeting.id);
3
3
  if (!current)
4
4
  return null;
@@ -18,6 +18,8 @@ export const linkEvent = async (store, details, now = Date.now()) => {
18
18
  return null;
19
19
  }
20
20
  let event = candidates[0];
21
+ if (!event && !create)
22
+ return null;
21
23
  if (!event) {
22
24
  let eventSeriesId = series?.eventSeriesId ?? null;
23
25
  if (series?.kind === "recurring" && eventSeriesId === null) {
@@ -55,7 +55,7 @@ export { aggregateMeetingCounts, aggregateMeetingStats, MEETING_COUNTS_GROUPINGS
55
55
  export type { ChatInput, ContractCase, EventCandidateFilter, IdentityInput, MeetingDetails, MeetingFilter, MeetingHitSource, MeetingInput, MeetingParticipant, MeetingSave, MeetingStore, NewRecord, ParticipantInput, SearchHit, TranscriptInput, TranscriptLanguageFill, TranscriptRowInput, } from "./store.js";
56
56
  export { READ_BUDGET_EXCEEDED } from "./store.js";
57
57
  export { meetingTimestamp } from "./timestamp.js";
58
- export type { MeetingTranscriptReceiptStore, MeetingTranscriptStore, TranscriptAppend, TranscriptAppendReceipt, UnlinkedTranscriptInput, } from "./transcript-store.js";
58
+ export type { MeetingTranscriptDocumentStore, MeetingTranscriptReceiptStore, MeetingTranscriptStore, TranscriptAppend, TranscriptAppendReceipt, UnlinkedTranscriptInput, } from "./transcript-store.js";
59
59
  export { parseTranscriptText, TranscriptTextError, type TranscriptTextHeader } from "./transcript-text.js";
60
60
  export { type MeetingMediaDescriptor, type MeetingRecognitionSegment, type MeetingTranscriptionContext, type MeetingTranscriptionOptions, type MeetingTranscriptionReceipt, type MeetingTranscriptionSource, transcribeMeeting, } from "./transcription.js";
61
61
  export { createUpcomingMeetingReader } from "./upcoming.js";
@@ -173,7 +173,7 @@ export const pull = async (source, store, options) => {
173
173
  transcripts: [await transcriptInput(lines, [], source.name, `${JSON.stringify(lines)}\nunlinked`, format)],
174
174
  now,
175
175
  });
176
- await linkEvent(store, details, now);
176
+ await linkEvent(store, details, now, { create: source.createsEvents !== false });
177
177
  for (const p of participants)
178
178
  if (p.identity.phone)
179
179
  callers.add(p.identity.externalId);
@@ -27,6 +27,11 @@ export interface MeetingSource {
27
27
  * meeting only once it has ended, or adds its recording later, sets it. 0 when absent; `--lookback-days` widens it.
28
28
  */
29
29
  readonly overlapMs?: number;
30
+ /**
31
+ * False for a source that knows a meeting's day but not its hours, such as meeting notes from mail: its meetings
32
+ * link to an event the owner already has and never make one. True when absent.
33
+ */
34
+ readonly createsEvents?: boolean;
30
35
  meetings(since: string): Promise<SourceMeeting[]>;
31
36
  participants(occurrenceId: string): Promise<SourceParticipant[] | null>;
32
37
  transcript(occurrenceId: string): Promise<TranscriptLine[] | null>;
@@ -22,6 +22,11 @@ export interface TranscriptRowInput extends Omit<NewRecord<TranscriptRow>, "meet
22
22
  }
23
23
  export interface TranscriptInput extends Omit<NewRecord<Transcript>, "meetingId" | "supersededAt"> {
24
24
  rows: TranscriptRowInput[];
25
+ /**
26
+ * The Drive file the meeting service saved this transcript as (Meet's `docsDestination.document`). Drive may import
27
+ * the same Google Doc, before or after; the store joins the two, so search shows the meeting once.
28
+ */
29
+ driveFileId?: string;
25
30
  }
26
31
  export interface ChatInput extends Omit<NewRecord<ChatLine>, "meetingId" | "senderParticipantId"> {
27
32
  senderParticipantPosition: number | null;
@@ -35,3 +35,7 @@ export interface TranscriptAppendReceipt {
35
35
  export interface MeetingTranscriptReceiptStore {
36
36
  appendTranscriptsWithReceipt(input: TranscriptAppend): Promise<TranscriptAppendReceipt>;
37
37
  }
38
+ /** The meeting whose transcript a Drive document is, by the `driveFileId` the meeting's transcript named. */
39
+ export interface MeetingTranscriptDocumentStore {
40
+ transcriptMeetings(documentIds: readonly number[]): Promise<Map<number, number>>;
41
+ }
@@ -1,6 +1,7 @@
1
1
  import type { DocumentSource, SourceFile, SourceState, SourceWalk } from "../../documents/model.js";
2
+ import { type SourceQuery } from "../../documents/scope.js";
2
3
  import type { SyncOptions } from "./ports.js";
3
- export declare const scopeHash: (roots: string[]) => string;
4
+ export declare const scopeHash: (roots: string[], query?: Pick<SourceQuery, "key" | "mode">) => string;
4
5
  export declare const changedSince: (previous: SourceFile, file: SourceFile) => boolean;
5
6
  interface WalkStore<M extends SourceFile> {
6
7
  read: (scope: string) => SourceWalk<M> | undefined;
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError } from "@wirecat/cli-base";
3
- import { within } from "../../documents/scope.js";
4
- export const scopeHash = (roots) => createHash("sha256")
5
- .update(JSON.stringify([...roots].sort()))
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()))
6
7
  .digest("hex");
7
8
  export const changedSince = (previous, file) => previous.version !== file.version ||
8
9
  previous.modifiedAt !== file.modifiedAt ||
@@ -11,10 +12,10 @@ export const changedSince = (previous, file) => previous.version !== file.versio
11
12
  JSON.stringify(previous.parents) !== JSON.stringify(file.parents);
12
13
  const SAVE_EVERY_MS = 2000;
13
14
  export const planDocuments = async (options, source, state, roots, limit, pictures, abandoned = [], walks) => {
14
- const { isFolder, skipReason, retryable, maxEntries: MAX_ENTRIES, errorOf } = options;
15
+ const { isFolder, skipReason, retryable, maxEntries: MAX_ENTRIES, errorOf, query } = options;
15
16
  const tooManyEntries = () => options.limitError?.() ?? new CliError("validation_error", `selected folders exceed the ${MAX_ENTRIES} entry limit`);
16
- const scope = scopeHash(roots);
17
- if (!roots.length)
17
+ const scope = scopeHash(roots, query);
18
+ if (!roots.length && query?.mode !== "include")
18
19
  return {
19
20
  scope,
20
21
  cursor: state.cursor ?? "",
@@ -23,7 +24,11 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
23
24
  jobs: [...new Set([...Object.keys(state.documents), ...abandoned])].map((id) => ({ id, kind: "remove" })),
24
25
  };
25
26
  if (!source)
26
- throw new CliError("configuration_error", "selected folders require an authenticated source");
27
+ throw new CliError("configuration_error", "selected folders or a saved query require an authenticated source");
28
+ if (query?.mode === "include" && !query.list)
29
+ throw new CliError("configuration_error", "a query that includes files must list them");
30
+ // Listed before the walk: a failure here then costs no folder already walked.
31
+ const found = query?.mode === "include" && query.list ? await query.list() : [];
27
32
  const initial = !state.cursor || scope !== state.scope;
28
33
  const resumed = initial ? walks?.read(scope) : undefined;
29
34
  const cursor = initial ? (resumed?.cursor ?? (await source.startToken())) : state.cursor;
@@ -160,13 +165,26 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
160
165
  if (!visited.has(folder.id) && within(folder, roots, folders))
161
166
  await crawl(folder);
162
167
  }
168
+ const matched = new Set();
169
+ for (const file of found) {
170
+ if (isFolder(file) || file.trashed || !query?.matches(file) || matched.has(file.id))
171
+ continue;
172
+ if (!files.has(file.id) && ++discovered > MAX_ENTRIES)
173
+ throw tooManyEntries();
174
+ // Listed again on every sync, so only a new or changed file is work; a skipped one keeps its skip.
175
+ const prior = state.documents[file.id]?.metadata ?? state.skipped.find((item) => item.id === file.id)?.file;
176
+ if (initial || !prior || changedSince(prior, file))
177
+ changed.add(file.id);
178
+ files.set(file.id, file);
179
+ matched.add(file.id);
180
+ }
163
181
  const jobs = [];
164
182
  const skipped = [];
165
183
  for (const root of roots)
166
184
  if (folders[root]?.trashed)
167
185
  skipped.push({ id: root, reason: "selected folder is unavailable" });
168
186
  for (const [id, file] of files) {
169
- if (!within(file, roots, folders))
187
+ if (!inScope(file, roots, folders, matched, query))
170
188
  continue;
171
189
  const previousSkip = state.skipped.find((item) => item.id === id);
172
190
  const reason = skipReason(file);
@@ -190,10 +208,17 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
190
208
  }
191
209
  for (const id of new Set([...Object.keys(state.documents), ...abandoned])) {
192
210
  const file = files.get(id);
193
- if (!file || !within(file, roots, folders))
211
+ if (!file || !inScope(file, roots, folders, matched, query))
194
212
  jobs.push({ id, kind: "remove" });
195
213
  }
196
214
  // Only retain metadata for selected ancestry; the account-wide feed includes unrelated folders.
197
215
  const scopedFolders = Object.fromEntries(Object.entries(folders).filter(([, file]) => within(file, roots, folders) || roots.includes(file.id)));
198
- return { scope, cursor: finalCursor, folders: scopedFolders, jobs, skipped };
216
+ return {
217
+ scope,
218
+ cursor: finalCursor,
219
+ folders: scopedFolders,
220
+ jobs,
221
+ skipped,
222
+ ...(query?.mode === "include" ? { matched: [...matched] } : {}),
223
+ };
199
224
  };
@@ -1,11 +1,13 @@
1
1
  import type { CliError } from "@wirecat/cli-base";
2
2
  import type { DocumentSource, SourceFile, SourceIndex, SourceSkip, SourceStatePort } from "../../documents/model.js";
3
+ import type { SourceQuery } from "../../documents/scope.js";
3
4
  export interface SyncOptions<M extends SourceFile> {
4
5
  source: DocumentSource<M> | undefined;
5
6
  index: SourceIndex<M>;
6
7
  state: SourceStatePort<M>;
7
8
  principal: string;
8
9
  roots: string[];
10
+ query?: SourceQuery<M>;
9
11
  textLimit: number;
10
12
  max: number;
11
13
  maxEntries: number;
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError, isCliError } from "@wirecat/cli-base";
3
3
  import { catalogFiles } from "../../documents/catalog.js";
4
- import { within } from "../../documents/scope.js";
4
+ import { inScope } from "../../documents/scope.js";
5
5
  import { changedSince, planDocuments, scopeHash } from "./plan.js";
6
6
  const MAX_PICTURE_BYTES = 25 * 1024 * 1024;
7
7
  const SAVE_EVERY_MS = 2000;
@@ -9,7 +9,7 @@ const SAVE_EVERY_ITEMS = 25;
9
9
  const isPicture = (file) => file.mime.startsWith("image/") && file.canDownload;
10
10
  const hashText = (text) => createHash("sha256").update(text).digest("hex");
11
11
  export const syncDocuments = async (options) => {
12
- const { source, index, state: statePort, principal, roots, textLimit: limit, max, signal, rescan = false, pictures = false, assertHeld, errorOf, skipReason, storeVersion: VERSION, } = options;
12
+ const { source, index, state: statePort, principal, roots, textLimit: limit, max, signal, rescan = false, pictures = false, assertHeld, errorOf, skipReason, storeVersion: VERSION, query, } = options;
13
13
  if (![max, limit, options.maxEntries].every((value) => Number.isSafeInteger(value) && value > 0))
14
14
  throw new CliError("validation_error", "sync limits must be positive whole numbers");
15
15
  const profile = { principal, roots, picture_search: pictures };
@@ -25,20 +25,25 @@ export const syncDocuments = async (options) => {
25
25
  pending: 0,
26
26
  skipped: [],
27
27
  errors: [],
28
- coverage: "selected folders only; unsupported files are reported",
28
+ coverage: query?.mode === "include"
29
+ ? "selected folders and the files a saved query finds; unsupported files are reported"
30
+ : query?.mode === "exclude"
31
+ ? "selected folders only, without the files a saved query keeps out; unsupported files are reported"
32
+ : "selected folders only; unsupported files are reported",
29
33
  ...(profile.picture_search ? { pictures: 0 } : {}),
30
34
  };
31
35
  let writer;
32
36
  let flush;
33
37
  try {
34
- if (profile.roots.length && (!source || (await source.identity()) !== profile.principal))
38
+ if ((profile.roots.length || query?.mode === "include") &&
39
+ (!source || (await source.identity()) !== profile.principal))
35
40
  throw new CliError("authentication_error", "signed-in source account does not match this profile", {
36
41
  reason: "profile.wrong-account",
37
42
  });
38
43
  const state = statePort.read();
39
44
  if (state.principal !== principal)
40
45
  throw new CliError("configuration_error", "sync state belongs to another source account");
41
- const currentScope = scopeHash(profile.roots);
46
+ const currentScope = scopeHash(profile.roots, query);
42
47
  const abandoned = state.pending && (state.pending.scope !== currentScope || rescan) ? state.pending.jobs.map((job) => job.id) : [];
43
48
  if (state.pending?.scope !== currentScope || rescan)
44
49
  delete state.pending;
@@ -59,7 +64,7 @@ export const syncDocuments = async (options) => {
59
64
  if (!pending)
60
65
  throw new CliError("invalid_response", "could not prepare a sync batch");
61
66
  if (index.catalog)
62
- await index.catalog.import(profile.principal, catalogFiles(state, profile.roots));
67
+ await index.catalog.import(profile.principal, catalogFiles(state, profile.roots, query));
63
68
  result.skipped = state.skipped.map(({ id, reason }) => ({ id, reason }));
64
69
  const saveNamesOnly = async (file, reason) => {
65
70
  const doc = { metadata: file, markdown: "", text: "", tabs: [], notRead: reason };
@@ -140,7 +145,8 @@ export const syncDocuments = async (options) => {
140
145
  if (!source)
141
146
  throw new CliError("configuration_error", "a pending save requires source sign-in");
142
147
  const content = await source.content(job.id, limit);
143
- if (!within(content.metadata, profile.roots, pending.folders)) {
148
+ const listed = query?.mode === "include" && (pending.matched?.includes(job.id) ?? query.matches(content.metadata));
149
+ if (!listed && !inScope(content.metadata, profile.roots, pending.folders, new Set(), query)) {
144
150
  await index.remove(profile.principal, job.id);
145
151
  statePort.removeSnapshot(job.id);
146
152
  delete state.documents[job.id];
@@ -203,6 +209,10 @@ export const syncDocuments = async (options) => {
203
209
  state.cursor = pending.cursor;
204
210
  state.scope = pending.scope;
205
211
  state.folders = pending.folders;
212
+ if (pending.matched)
213
+ state.matched = pending.matched;
214
+ else
215
+ delete state.matched;
206
216
  delete state.pending;
207
217
  state.lastSync = new Date(now()).toISOString();
208
218
  statePort.save(state);
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
+ error?: undefined;
17
18
  chatId: string;
18
19
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
19
20
  algorithm: string;
20
21
  fetchedAt: string | null;
21
22
  source: string;
22
- error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -400,7 +400,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
400
400
  finally {
401
401
  await embedders.close();
402
402
  }
403
- let ordered = insidePeriodFirst(oneList(lists, cosines), period);
403
+ let ordered = insidePeriodFirst(oneList(await withoutTranscriptCopies(store, lists), cosines), period);
404
404
  let harder;
405
405
  if (request.harder) {
406
406
  const asking = {
@@ -442,6 +442,25 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
442
442
  ...(harder === undefined ? {} : { harder }),
443
443
  };
444
444
  };
445
+ /**
446
+ * A meeting's transcript that Drive also imported as a document is one thing: when the meeting is among the hits, its
447
+ * document's hit is dropped. Alone, the document stays, so nothing found is lost.
448
+ */
449
+ const withoutTranscriptCopies = async (store, lists) => {
450
+ const meetings = new Set(lists.flat().flatMap((item) => (item.kind === "meeting" ? [item.meetingId] : [])));
451
+ if (!meetings.size)
452
+ return lists;
453
+ const documentOf = (item) => item.kind === "document" && /^document:\d+$/.test(item.ref) ? Number(item.ref.slice("document:".length)) : undefined;
454
+ const documents = lists.flat().flatMap((item) => documentOf(item) ?? []);
455
+ const transcripts = await store.meetings.transcriptMeetings(documents);
456
+ if (!transcripts.size)
457
+ return lists;
458
+ return lists.map((list) => list.filter((item) => {
459
+ const document = documentOf(item);
460
+ const meeting = document === undefined ? undefined : transcripts.get(document);
461
+ return meeting === undefined || !meetings.has(meeting);
462
+ }));
463
+ };
445
464
  /** Passages of one meeting share its `ref`, the reference evidence cites; each is still a hit of its own. */
446
465
  const hitKey = (item) => item.kind === "meeting" ? `${item.ref}\u0000${item.scope}\u0000${item.id}` : item.ref;
447
466
  /**
@@ -6,8 +6,8 @@ export declare const LINK_KINDS: readonly ["links-to", "blocked-by", "follow-up-
6
6
  export type LinkKind = (typeof LINK_KINDS)[number];
7
7
  /** Where a caller may say a link came from. */
8
8
  export declare const LINK_ORIGINS: readonly ["file", "owner", "suggested", "message"];
9
- /** Where a stored link came from: an origin a caller gives, or `calendar`, which only the store writes. */
10
- export declare const LINK_SOURCES: readonly ["file", "owner", "suggested", "message", "calendar"];
9
+ /** Where a stored link came from: an origin a caller gives, or `calendar` or `meeting`, which only the store writes. */
10
+ export declare const LINK_SOURCES: readonly ["file", "owner", "suggested", "message", "calendar", "meeting"];
11
11
  export { RELATION_KINDS } from "../../domain/relations.js";
12
12
  /** A kind as an SQL literal, so a kind written into a query is checked against the list. */
13
13
  export declare const linkKind: (kind: LinkKind) => string;
@@ -22,8 +22,8 @@ export const LINK_KINDS = [
22
22
  ];
23
23
  /** Where a caller may say a link came from. */
24
24
  export const LINK_ORIGINS = ["file", "owner", "suggested", "message"];
25
- /** Where a stored link came from: an origin a caller gives, or `calendar`, which only the store writes. */
26
- export const LINK_SOURCES = [...LINK_ORIGINS, "calendar"];
25
+ /** Where a stored link came from: an origin a caller gives, or `calendar` or `meeting`, which only the store writes. */
26
+ export const LINK_SOURCES = [...LINK_ORIGINS, "calendar", "meeting"];
27
27
  export { RELATION_KINDS } from "../../domain/relations.js";
28
28
  /** A kind as an SQL literal, so a kind written into a query is checked against the list. */
29
29
  export const linkKind = (kind) => `'${kind}'`;
@@ -0,0 +1,10 @@
1
+ import type { MeetingTranscriptDocumentStore } from "../../meetings/index.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ import type { StoreContext } from "./open.js";
4
+ /**
5
+ * The meeting's transcript is this Drive file: an `attached` link to the file's document, waiting by its Drive id when
6
+ * Drive has not stored it yet. Drive's later import resolves it (`linkAttached`), so either order ends in one link.
7
+ * A new transcript version that names another file replaces the old link; a replay of an old version keeps it.
8
+ */
9
+ export declare const attachTranscriptDocument: (database: CacheDatabase, meetingId: number, fileId: string, now: number, replaces: boolean) => void;
10
+ export declare const meetingTranscriptDocumentsOver: ({ database }: StoreContext) => MeetingTranscriptDocumentStore;
@@ -0,0 +1,52 @@
1
+ import { driveDocumentOf, driveFileTarget } from "./files.js";
2
+ import { read } from "./transaction.js";
3
+ const TRANSCRIPT_ROLE = "transcript";
4
+ /**
5
+ * The meeting's transcript is this Drive file: an `attached` link to the file's document, waiting by its Drive id when
6
+ * Drive has not stored it yet. Drive's later import resolves it (`linkAttached`), so either order ends in one link.
7
+ * A new transcript version that names another file replaces the old link; a replay of an old version keeps it.
8
+ */
9
+ export const attachTranscriptDocument = (database, meetingId, fileId, now, replaces) => {
10
+ const file = fileId.trim();
11
+ if (!file)
12
+ return;
13
+ const target = driveFileTarget(file);
14
+ if (replaces)
15
+ database
16
+ .prepare("DELETE FROM links WHERE from_type = 'meeting' AND from_id = ? AND kind = 'attached' AND role = ? " +
17
+ "AND target_text <> ?")
18
+ .run(meetingId, TRANSCRIPT_ROLE, target);
19
+ const held = database
20
+ .prepare("SELECT id, to_id FROM links WHERE from_type = 'meeting' AND from_id = ? AND kind = 'attached' AND target_text = ?")
21
+ .get(meetingId, target);
22
+ if (!held) {
23
+ database
24
+ .prepare(`INSERT INTO links (from_type, from_id, to_type, to_id, kind, source, target_text, role, confirmed, author,
25
+ created_at, updated_at) VALUES ('meeting', ?, 'document', ?, 'attached', 'meeting', ?, ?, 1, 'rule', ?, ?)`)
26
+ .run(meetingId, driveDocumentOf(database, file), target, TRANSCRIPT_ROLE, now, now);
27
+ return;
28
+ }
29
+ if (held.to_id != null)
30
+ return;
31
+ const document = driveDocumentOf(database, file);
32
+ if (document !== null)
33
+ database.prepare("UPDATE links SET to_id = ?, updated_at = ? WHERE id = ?").run(document, now, Number(held.id));
34
+ };
35
+ export const meetingTranscriptDocumentsOver = ({ database }) => ({
36
+ async transcriptMeetings(documentIds) {
37
+ if (!documentIds.length)
38
+ return new Map();
39
+ return read(database, () => {
40
+ const rows = database
41
+ .prepare(`SELECT l.to_id AS document_id, l.from_id AS meeting_id FROM links l JOIN meetings m ON m.id = l.from_id
42
+ WHERE l.kind = 'attached' AND l.from_type = 'meeting' AND l.to_type = 'document' AND l.role = ?
43
+ AND m.deleted_at IS NULL AND l.to_id IN (SELECT value FROM json_each(?)) ORDER BY l.id`)
44
+ .all(TRANSCRIPT_ROLE, JSON.stringify(documentIds));
45
+ const found = new Map();
46
+ for (const row of rows)
47
+ if (!found.has(Number(row.document_id)))
48
+ found.set(Number(row.document_id), Number(row.meeting_id));
49
+ return found;
50
+ });
51
+ },
52
+ });
@@ -1,4 +1,4 @@
1
- import type { Attachment, MeetingChatLinesStore, MeetingContextStore, MeetingParticipantSearchStore, MeetingPreparationContextStore, MeetingPreparationKnowledgeStore, MeetingPreparationNotesStore, MeetingRelatedHistoryStore, MeetingReviewStore, MeetingSearchIndexStore, MeetingSearchStore, MeetingSeriesHistoryStore, MeetingStatsStore, MeetingStore, MeetingTranscriptReceiptStore, MeetingTranscriptStore, NewRecord } from "../../meetings/index.js";
1
+ import type { Attachment, MeetingChatLinesStore, MeetingContextStore, MeetingParticipantSearchStore, MeetingPreparationContextStore, MeetingPreparationKnowledgeStore, MeetingPreparationNotesStore, MeetingRelatedHistoryStore, MeetingReviewStore, MeetingSearchIndexStore, MeetingSearchStore, MeetingSeriesHistoryStore, MeetingStatsStore, MeetingStore, MeetingTranscriptDocumentStore, MeetingTranscriptReceiptStore, MeetingTranscriptStore, NewRecord } from "../../meetings/index.js";
2
2
  import type { CacheDatabase } from "../driver.js";
3
3
  import { type MeetingLanguageStore } from "./meeting-languages.js";
4
4
  import { type MeetingContextReadCapabilities, type MeetingReadCapabilities } from "./meeting-reads.js";
@@ -12,7 +12,7 @@ export declare const saveAttachment: (database: CacheDatabase, type: string, par
12
12
  export declare const drainMeetingIndex: (database: CacheDatabase, batch?: number) => number;
13
13
  /** Each word of the query, as a prefix, all required. */
14
14
  export declare const wordsQuery: (query: string) => string | null;
15
- export type StoredMeetings = MeetingStore & MeetingPreparationContextStore & MeetingPreparationKnowledgeStore & MeetingPreparationNotesStore & MeetingRelatedHistoryStore & MeetingSeriesHistoryStore & MeetingTranscriptStore & MeetingReadCapabilities & MeetingContextReadCapabilities & MeetingParticipantSearchStore & MeetingSearchStore & MeetingTranscriptReceiptStore & MeetingContextStore & MeetingSearchIndexStore & MeetingStatsStore & MeetingReviewStore & MeetingChatLinesStore & MeetingLanguageStore;
15
+ export type StoredMeetings = MeetingStore & MeetingPreparationContextStore & MeetingPreparationKnowledgeStore & MeetingPreparationNotesStore & MeetingRelatedHistoryStore & MeetingSeriesHistoryStore & MeetingTranscriptStore & MeetingReadCapabilities & MeetingContextReadCapabilities & MeetingParticipantSearchStore & MeetingSearchStore & MeetingTranscriptReceiptStore & MeetingContextStore & MeetingSearchIndexStore & MeetingStatsStore & MeetingReviewStore & MeetingChatLinesStore & MeetingLanguageStore & MeetingTranscriptDocumentStore;
16
16
  /** The `MeetingStore` of `src/meetings/` over the shared store. */
17
17
  export declare const meetingStoreOver: (context: StoreContext) => StoredMeetings;
18
18
  export {};
@@ -22,6 +22,7 @@ import { meetingReviewOver } from "./meeting-review.js";
22
22
  import { meetingSeriesHistoryOver } from "./meeting-series-history.js";
23
23
  import { meetingStatsOver } from "./meeting-stats.js";
24
24
  import { invalidateMeetingStems } from "./meeting-stem-state.js";
25
+ import { attachTranscriptDocument, meetingTranscriptDocumentsOver } from "./meeting-transcript-documents.js";
25
26
  import { meetingOf, transcriptOf, transcriptRowOf } from "./meeting-values.js";
26
27
  import { linkPhones } from "./person-match-scan.js";
27
28
  import { queryFilter } from "./query-filter.js";
@@ -342,8 +343,11 @@ const saveTranscripts = (database, meetingId, transcripts, participantId, now) =
342
343
  metadata, created_at, updated_at, deleted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id`);
343
344
  const insertRow = database.prepare(`INSERT INTO meeting_transcript_rows (meeting_transcript_id, position, start_ms, end_ms, speaker_participant_id,
344
345
  speaker_name, text, normalized_text, metadata, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
345
- for (const { rows, ...t } of transcripts) {
346
- if (t.contentHash !== null && sameContent.get(meetingId, t.source, t.contentHash)) {
346
+ for (const { rows, driveFileId, ...t } of transcripts) {
347
+ const replayed = t.contentHash !== null && Boolean(sameContent.get(meetingId, t.source, t.contentHash));
348
+ if (driveFileId !== undefined)
349
+ attachTranscriptDocument(database, meetingId, driveFileId, now, !replayed);
350
+ if (replayed) {
347
351
  counts.replayedTranscripts++;
348
352
  continue;
349
353
  }
@@ -612,6 +616,7 @@ export const meetingStoreOver = (context) => {
612
616
  ...meetingHitIndexOver(context),
613
617
  ...meetingContextLinksOver(context),
614
618
  ...meetingLanguagesOver(context),
619
+ ...meetingTranscriptDocumentsOver(context),
615
620
  async linkCallers(provider, externalIds) {
616
621
  const marks = externalIds.map(() => "?").join(", ");
617
622
  const ids = database
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.651.0",
3
+ "version": "0.653.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",