@wirecat/cli-core 0.611.0 → 0.613.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 (63) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/dist/background/report/render.d.ts +10 -1
  3. package/dist/background/report/render.js +20 -7
  4. package/dist/background/report/schema.d.ts +37 -0
  5. package/dist/background/report/schema.js +98 -4
  6. package/dist/background/report/templates/morning-digest.email.en.liquid +49 -8
  7. package/dist/background/report/templates/morning-digest.email.ru.liquid +49 -8
  8. package/dist/background/report/templates/morning-digest.telegram.en.liquid +49 -9
  9. package/dist/background/report/templates/morning-digest.telegram.ru.liquid +49 -9
  10. package/dist/background/report/templates/morning-digest.text.en.liquid +49 -9
  11. package/dist/background/report/templates/morning-digest.text.ru.liquid +49 -9
  12. package/dist/background/report/view.d.ts +34 -3
  13. package/dist/background/report/view.js +59 -5
  14. package/dist/background/schedules.js +19 -3
  15. package/dist/calendar/mcp/index.d.ts +12 -12
  16. package/dist/cli/enrichment-consents-command.d.ts +19 -0
  17. package/dist/cli/enrichment-consents-command.js +110 -0
  18. package/dist/cli/model-catalogue-command.d.ts +8 -0
  19. package/dist/cli/model-catalogue-command.js +4 -1
  20. package/dist/domain/links.d.ts +72 -0
  21. package/dist/domain/links.js +139 -0
  22. package/dist/embeddings/keys.d.ts +2 -0
  23. package/dist/embeddings/keys.js +2 -0
  24. package/dist/errors/reasons.js +1 -0
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.js +1 -0
  27. package/dist/meetings/mcp/index.d.ts +15 -15
  28. package/dist/models/anthropic.js +6 -0
  29. package/dist/models/index.d.ts +1 -1
  30. package/dist/models/openai.js +8 -1
  31. package/dist/models/types.d.ts +7 -0
  32. package/dist/services/enrichment-setting.d.ts +50 -0
  33. package/dist/services/enrichment-setting.js +84 -0
  34. package/dist/services/enrichment.d.ts +111 -0
  35. package/dist/services/enrichment.js +240 -0
  36. package/dist/services/index.d.ts +2 -0
  37. package/dist/services/index.js +2 -0
  38. package/dist/services/notes-search.d.ts +15 -1
  39. package/dist/services/notes-search.js +38 -2
  40. package/dist/store/exports.d.ts +1 -0
  41. package/dist/store/exports.js +1 -0
  42. package/dist/store/sqlite/email-index.d.ts +2 -2
  43. package/dist/store/sqlite/email-index.js +6 -4
  44. package/dist/store/sqlite/emails.js +5 -0
  45. package/dist/store/sqlite/enrichments.d.ts +60 -0
  46. package/dist/store/sqlite/enrichments.js +113 -0
  47. package/dist/store/sqlite/entity-types.d.ts +1 -0
  48. package/dist/store/sqlite/entity-types.js +1 -0
  49. package/dist/store/sqlite/index-text.d.ts +2 -0
  50. package/dist/store/sqlite/index-text.js +2 -0
  51. package/dist/store/sqlite/mail-nearest.js +1 -1
  52. package/dist/store/sqlite/manifest.js +2 -0
  53. package/dist/store/sqlite/migrations.generated.js +14 -0
  54. package/dist/store/sqlite/note-index.d.ts +1 -2
  55. package/dist/store/sqlite/note-index.js +25 -4
  56. package/dist/store/sqlite/note-search.js +8 -1
  57. package/dist/store/sqlite/schema/enrichments.d.ts +137 -0
  58. package/dist/store/sqlite/schema/enrichments.js +12 -0
  59. package/dist/store/sqlite/schema.d.ts +1 -0
  60. package/dist/store/sqlite/schema.js +1 -0
  61. package/dist/store/store.d.ts +3 -0
  62. package/dist/store/store.js +5 -0
  63. package/package.json +2 -2
@@ -3,10 +3,10 @@ import type { Stemmer, Stemmers } from "../../search/stem.js";
3
3
  import type { CacheDatabase } from "../driver.js";
4
4
  export declare const titleOf: (subject: string | null) => string | null;
5
5
  /**
6
- * Every piece of mail: a stretch of a thread, or of one email's attachment. A thread piece holds no email of its
6
+ * Every piece of mail: a stretch of a thread, one email's attachment, or the text a model wrote about one email. A thread piece holds no email of its
7
7
  * own; `threadPieces` cuts the thread again to find which emails it spans.
8
8
  */
9
- export declare const MAIL_PIECES = "(SELECT k.id, k.content_hash, k.chunkable_type AS type, k.chunkable_id AS owner, k.position,\n k.start_offset, k.end_offset, k.account_id, k.occurred_at, a.attachable_id AS email_id,\n CASE k.chunkable_type WHEN 'email_thread' THEN k.chunkable_id\n ELSE (SELECT email_thread_id FROM emails WHERE id = a.attachable_id) END AS thread_id\n FROM chunks k LEFT JOIN attachments a ON k.chunkable_type = 'attachment' AND a.id = k.chunkable_id\n AND a.attachable_type = 'email'\n WHERE k.chunkable_type = 'email_thread' OR a.id IS NOT NULL) p";
9
+ export declare const MAIL_PIECES = "(SELECT k.id, k.content_hash, k.chunkable_type AS type, k.chunkable_id AS owner, k.position,\n k.start_offset, k.end_offset, k.account_id, k.occurred_at,\n CASE k.chunkable_type WHEN 'email_enrichment' THEN k.chunkable_id ELSE a.attachable_id END AS email_id,\n CASE k.chunkable_type WHEN 'email_thread' THEN k.chunkable_id\n ELSE (SELECT email_thread_id FROM emails\n WHERE id = CASE k.chunkable_type WHEN 'email_enrichment' THEN k.chunkable_id ELSE a.attachable_id END) END AS thread_id\n FROM chunks k LEFT JOIN attachments a ON k.chunkable_type = 'attachment' AND a.id = k.chunkable_id\n AND a.attachable_type = 'email'\n WHERE k.chunkable_type IN ('email_thread', 'email_enrichment') OR a.id IS NOT NULL) p";
10
10
  /**
11
11
  * A thread's pieces, email by email: a piece never spans two emails, so a hit names the email that holds it
12
12
  * (bench/mail-quality). A new reply adds its own pieces; every earlier one keeps its hash and so its vector.
@@ -6,16 +6,18 @@ import { write } from "./transaction.js";
6
6
  import { dropUnusedVectors } from "./vector-index.js";
7
7
  export const titleOf = (subject) => subject?.replace(/^\s*((re|fwd?|aw|wg)\s*:\s*)+/i, "").trim() || null;
8
8
  /**
9
- * Every piece of mail: a stretch of a thread, or of one email's attachment. A thread piece holds no email of its
9
+ * Every piece of mail: a stretch of a thread, one email's attachment, or the text a model wrote about one email. A thread piece holds no email of its
10
10
  * own; `threadPieces` cuts the thread again to find which emails it spans.
11
11
  */
12
12
  export const MAIL_PIECES = `(SELECT k.id, k.content_hash, k.chunkable_type AS type, k.chunkable_id AS owner, k.position,
13
- k.start_offset, k.end_offset, k.account_id, k.occurred_at, a.attachable_id AS email_id,
13
+ k.start_offset, k.end_offset, k.account_id, k.occurred_at,
14
+ CASE k.chunkable_type WHEN 'email_enrichment' THEN k.chunkable_id ELSE a.attachable_id END AS email_id,
14
15
  CASE k.chunkable_type WHEN 'email_thread' THEN k.chunkable_id
15
- ELSE (SELECT email_thread_id FROM emails WHERE id = a.attachable_id) END AS thread_id
16
+ ELSE (SELECT email_thread_id FROM emails
17
+ WHERE id = CASE k.chunkable_type WHEN 'email_enrichment' THEN k.chunkable_id ELSE a.attachable_id END) END AS thread_id
16
18
  FROM chunks k LEFT JOIN attachments a ON k.chunkable_type = 'attachment' AND a.id = k.chunkable_id
17
19
  AND a.attachable_type = 'email'
18
- WHERE k.chunkable_type = 'email_thread' OR a.id IS NOT NULL) p`;
20
+ WHERE k.chunkable_type IN ('email_thread', 'email_enrichment') OR a.id IS NOT NULL) p`;
19
21
  /** A thread's live emails, oldest first, each as what it adds: its subject, then its own text. */
20
22
  const threadText = (database, threadId) => {
21
23
  const rows = database
@@ -5,6 +5,7 @@ import { mailActivity, threadEmailIds } from "./email-activity.js";
5
5
  import { chunkAttachments, drainEmailIndex, dropAttachmentChunks, MAIL_PIECES, queueThreads, threadPieces, titleOf, } from "./email-index.js";
6
6
  import { backfillSentAt, folderEmails, forgetLocations, locate, partialMail, setLocations, storedWhole, } from "./email-locations.js";
7
7
  import { markEmailsDeleted, markEmailsRestored, recountEmailThread as recount, setEmailFlags } from "./email-state.js";
8
+ import { EMAIL_ENRICHMENT, enrichmentText } from "./enrichments.js";
8
9
  import { bool, flag, fromJson, int, page, str, toJson } from "./events.js";
9
10
  import { folded } from "./folded.js";
10
11
  import { ensurePerson } from "./identities.js";
@@ -586,6 +587,10 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
586
587
  const piece = threads.get(owner)?.[Number(row.position)];
587
588
  return piece && piece.hash === row.hash ? [{ hash: piece.hash, text: piece.text }] : [];
588
589
  }
590
+ if (type === EMAIL_ENRICHMENT) {
591
+ const text = enrichmentText(database, type, owner);
592
+ return text === undefined ? [] : [{ hash: String(row.hash), text }];
593
+ }
589
594
  const text = str(file.get(owner)?.text);
590
595
  return text == null ? [] : [{ hash: String(row.hash), text: text.slice(Number(row.start), Number(row.end)) }];
591
596
  });
@@ -0,0 +1,60 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import type { StoreContext } from "./open.js";
3
+ export type EnrichmentSubject = "document" | "note" | "email";
4
+ export declare const ENRICHMENT_SUBJECTS: readonly EnrichmentSubject[];
5
+ /**
6
+ * A note's or document's enrichment chunk sits at this position under the record's own chunks, so a hit by meaning
7
+ * still names the record. Its offsets are 0: its text is the enrichment's, never a stretch of the record's.
8
+ */
9
+ export declare const ENRICHMENT_POSITION = 1000000;
10
+ /** An email's enrichment chunk: thread pieces are cut again by position, so a reserved position there would break. */
11
+ export declare const EMAIL_ENRICHMENT = "email_enrichment";
12
+ export interface EnrichmentCandidate {
13
+ type: EnrichmentSubject;
14
+ id: number;
15
+ /** The record's indexed text, title first: what the hash covers. */
16
+ text: string;
17
+ at: number | null;
18
+ hash: string;
19
+ }
20
+ export interface SavedEnrichment {
21
+ type: EnrichmentSubject;
22
+ id: number;
23
+ hash: string;
24
+ provider: string;
25
+ model: string;
26
+ text: string;
27
+ tokens: number;
28
+ }
29
+ export interface EnrichmentNarrowing {
30
+ types?: readonly EnrichmentSubject[];
31
+ only?: readonly {
32
+ type: EnrichmentSubject;
33
+ id: number;
34
+ }[];
35
+ }
36
+ export interface EnrichmentCounts {
37
+ /** Live records search reads: documents, notes and emails. */
38
+ records: number;
39
+ /** Of those, the ones whose current text has an enrichment. */
40
+ enriched: number;
41
+ /** Characters of the records still to enrich, for a cost estimate. */
42
+ pendingChars: number;
43
+ pendingByType: Record<EnrichmentSubject, number>;
44
+ }
45
+ export interface EnrichmentStore {
46
+ /** Up to `limit` live records with no enrichment of their current text, by type then id; `only` narrows them. */
47
+ pending(limit: number, narrow?: EnrichmentNarrowing): Promise<EnrichmentCandidate[]>;
48
+ counts(): Promise<EnrichmentCounts>;
49
+ /** Keeps each text and queues its record, so the next index drain adds it to the record's stems and chunks. */
50
+ save(rows: readonly SavedEnrichment[]): Promise<void>;
51
+ /** Deletes every enrichment and queues its record: the drain then indexes the record's own text alone. */
52
+ clear(): Promise<number>;
53
+ }
54
+ /** The hash an enrichment is kept under: of the text the corpus indexes, so an edit makes it stale. */
55
+ export declare const enrichmentHash: (title: string | null, body: string) => string;
56
+ /** The record's enrichment text when it was written for its current text; a stale one is never indexed. */
57
+ export declare const currentEnrichment: (database: CacheDatabase, type: string, id: number, indexed: string) => string | undefined;
58
+ /** An enrichment's text by its chunk's owner, for the embed pass. */
59
+ export declare const enrichmentText: (database: CacheDatabase, type: string, id: number) => string | undefined;
60
+ export declare const enrichmentsOver: ({ database, now }: StoreContext) => EnrichmentStore;
@@ -0,0 +1,113 @@
1
+ import { chunkHash } from "../../conversations/chunks.js";
2
+ import { noteIndexText } from "./index-text.js";
3
+ import { write } from "./transaction.js";
4
+ export const ENRICHMENT_SUBJECTS = ["document", "note", "email"];
5
+ /**
6
+ * A note's or document's enrichment chunk sits at this position under the record's own chunks, so a hit by meaning
7
+ * still names the record. Its offsets are 0: its text is the enrichment's, never a stretch of the record's.
8
+ */
9
+ export const ENRICHMENT_POSITION = 1_000_000;
10
+ /** An email's enrichment chunk: thread pieces are cut again by position, so a reserved position there would break. */
11
+ export const EMAIL_ENRICHMENT = "email_enrichment";
12
+ const LIVE = {
13
+ document: "SELECT d.id, d.title, coalesce(d.body, '') AS body, coalesce(d.external_updated_at, d.updated_at) AS at FROM documents d " +
14
+ "WHERE d.deleted_at IS NULL AND coalesce(json_extract(d.metadata, '$.catalog.active'), 1) = 1",
15
+ note: "SELECT n.id, n.title, coalesce(n.body, '') AS body, n.updated_at AS at FROM notes n WHERE n.deleted_at IS NULL",
16
+ email: "SELECT e.id, e.subject AS title, coalesce(e.body_text, '') AS body, coalesce(e.sent_at, e.received_at) AS at " +
17
+ "FROM emails e WHERE e.deleted_at IS NULL",
18
+ };
19
+ const QUEUES = {
20
+ document: "INSERT OR IGNORE INTO document_index_pending (indexable_type, id) VALUES ('document', ?)",
21
+ note: "INSERT OR IGNORE INTO note_index_pending (indexable_type, id) VALUES ('note', ?)",
22
+ email: "INSERT OR IGNORE INTO email_index_pending (indexable_type, id) VALUES ('email', ?)",
23
+ };
24
+ /** The hash an enrichment is kept under: of the text the corpus indexes, so an edit makes it stale. */
25
+ export const enrichmentHash = (title, body) => chunkHash(noteIndexText(title, body));
26
+ /** The record's enrichment text when it was written for its current text; a stale one is never indexed. */
27
+ export const currentEnrichment = (database, type, id, indexed) => {
28
+ if (!ENRICHMENT_SUBJECTS.includes(type))
29
+ return undefined;
30
+ const row = database
31
+ .prepare("SELECT text, source_hash FROM enrichments WHERE subject_type = ? AND subject_id = ?")
32
+ .get(type, id);
33
+ return row && String(row.source_hash) === chunkHash(indexed) ? String(row.text) : undefined;
34
+ };
35
+ /** An enrichment's text by its chunk's owner, for the embed pass. */
36
+ export const enrichmentText = (database, type, id) => {
37
+ const row = database
38
+ .prepare("SELECT text FROM enrichments WHERE subject_type = ? AND subject_id = ?")
39
+ .get(type === EMAIL_ENRICHMENT ? "email" : type, id);
40
+ return row === undefined ? undefined : String(row.text);
41
+ };
42
+ const scan = function* (database, type, only) {
43
+ const held = new Map(database
44
+ .prepare("SELECT subject_id AS id, source_hash AS hash FROM enrichments WHERE subject_type = ?")
45
+ .all(type)
46
+ .map((row) => [Number(row.id), String(row.hash)]));
47
+ for (const row of database.prepare(`${LIVE[type]} ORDER BY 1`).all()) {
48
+ const id = Number(row.id);
49
+ if (only && !only.has(id))
50
+ continue;
51
+ const title = row.title == null ? null : String(row.title);
52
+ const text = noteIndexText(title, String(row.body));
53
+ if (!text.trim())
54
+ continue;
55
+ const hash = chunkHash(text);
56
+ yield { type, id, text, at: row.at == null ? null : Number(row.at), hash, enriched: held.get(id) === hash };
57
+ }
58
+ };
59
+ export const enrichmentsOver = ({ database, now }) => ({
60
+ pending: async (limit, { types = ENRICHMENT_SUBJECTS, only } = {}) => {
61
+ const found = [];
62
+ for (const type of types) {
63
+ const ids = only ? new Set(only.filter((one) => one.type === type).map((one) => one.id)) : undefined;
64
+ if (ids?.size === 0)
65
+ continue;
66
+ for (const { enriched, ...candidate } of scan(database, type, ids)) {
67
+ if (found.length >= limit)
68
+ return found;
69
+ if (!enriched)
70
+ found.push(candidate);
71
+ }
72
+ }
73
+ return found;
74
+ },
75
+ counts: async () => {
76
+ const counts = {
77
+ records: 0,
78
+ enriched: 0,
79
+ pendingChars: 0,
80
+ pendingByType: { document: 0, note: 0, email: 0 },
81
+ };
82
+ for (const type of ENRICHMENT_SUBJECTS)
83
+ for (const one of scan(database, type)) {
84
+ counts.records += 1;
85
+ if (one.enriched)
86
+ counts.enriched += 1;
87
+ else {
88
+ counts.pendingChars += one.text.length;
89
+ counts.pendingByType[type] += 1;
90
+ }
91
+ }
92
+ return counts;
93
+ },
94
+ save: async (rows) => write(database, () => {
95
+ const upsert = database.prepare(`INSERT INTO enrichments (subject_type, subject_id, source_hash, provider, model, text, tokens, created_at)
96
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
97
+ ON CONFLICT (subject_type, subject_id) DO UPDATE SET source_hash = excluded.source_hash,
98
+ provider = excluded.provider, model = excluded.model, text = excluded.text, tokens = excluded.tokens,
99
+ created_at = excluded.created_at`);
100
+ const at = now();
101
+ for (const row of rows) {
102
+ upsert.run(row.type, row.id, row.hash, row.provider, row.model, row.text, row.tokens, at);
103
+ database.prepare(QUEUES[row.type]).run(row.id);
104
+ }
105
+ }),
106
+ clear: async () => write(database, () => {
107
+ const rows = database.prepare("SELECT subject_type AS type, subject_id AS id FROM enrichments").all();
108
+ for (const row of rows)
109
+ database.prepare(QUEUES[row.type]).run(Number(row.id));
110
+ database.prepare("DELETE FROM enrichments").run();
111
+ return rows.length;
112
+ }),
113
+ });
@@ -27,6 +27,7 @@ export declare const ENTITY_TABLES: {
27
27
  readonly document: "documents";
28
28
  readonly document_picture: "documents";
29
29
  readonly email: "emails";
30
+ readonly email_enrichment: "emails";
30
31
  readonly email_thread: "email_threads";
31
32
  readonly event: "events";
32
33
  readonly event_series: "event_series";
@@ -14,6 +14,7 @@ export const ENTITY_TABLES = {
14
14
  document: "documents",
15
15
  document_picture: "documents",
16
16
  email: "emails",
17
+ email_enrichment: "emails",
17
18
  email_thread: "email_threads",
18
19
  event: "events",
19
20
  event_series: "event_series",
@@ -0,0 +1,2 @@
1
+ /** What a row is indexed as: its title, then its text. Chunk offsets point into this. */
2
+ export declare const noteIndexText: (title: string | null, text: string) => string;
@@ -0,0 +1,2 @@
1
+ /** What a row is indexed as: its title, then its text. Chunk offsets point into this. */
2
+ export const noteIndexText = (title, text) => (title ? `${title}\n\n${text}` : text);
@@ -41,7 +41,7 @@ const scannedMailPieces = (database, model, query, filter) => {
41
41
  const indexedMailPieces = (database, model, query, filter, depth) => {
42
42
  const candidates = database.prepare(`${MAIL_PIECE_ROWS} AND p.id IN (SELECT value FROM json_each(?)) ORDER BY p.id`);
43
43
  const merged = new Map();
44
- for (const kind of ["email_thread", "attachment"]) {
44
+ for (const kind of ["email_thread", "attachment", "email_enrichment"]) {
45
45
  const found = searchIndex(database, model, { kind, account: filter.accountId, ...(filter.since === undefined ? {} : { since: filter.since }) }, query, depth, (near) => {
46
46
  const hashes = new Map(near.map(({ id, hash }) => [id, hash]));
47
47
  const best = new Map();
@@ -120,6 +120,8 @@ export const MANIFEST = [
120
120
  { name: "20261107163245_version-56-relationship-links-key", version: 56, minCompatible: 56, tables: V56_TABLES },
121
121
  { name: "20261108010753_version-57-business", version: 57, minCompatible: 56 },
122
122
  { name: "20261108010754_version-57-business-rules", version: 57, minCompatible: 56 },
123
+ { name: "20261108104659_version-58-enrichments", version: 58, minCompatible: 56 },
124
+ { name: "20261108104701_version-58-enrichments-deletes", version: 58, minCompatible: 56 },
123
125
  ];
124
126
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
125
127
  const migrations = [];
@@ -1194,5 +1194,19 @@ export const GENERATED = [
1194
1194
  "CREATE TRIGGER payment_allocations_refund_bd BEFORE DELETE ON payment_allocations\n WHEN (SELECT refund_of IS NOT NULL AND review = 'confirmed' AND deleted_at IS NULL FROM payments WHERE id = old.payment_id)\n AND (SELECT review FROM invoices WHERE id = old.invoice_id) <> 'rejected'\n AND (SELECT coalesce(sum(CASE WHEN np.refund_of IS NULL THEN na.amount ELSE -na.amount END), 0) FROM payment_allocations na JOIN payments np ON np.id = na.payment_id WHERE na.invoice_id = old.invoice_id AND np.review = 'confirmed' AND np.deleted_at IS NULL) + old.amount\n > (SELECT total FROM invoices WHERE id = old.invoice_id) BEGIN\n SELECT RAISE(ABORT, 'payment_allocations: taking a refund''s share back would pay the invoice beyond its total');\nEND;",
1195
1195
  "-- A void invoice keeps what was settled on it; a rejected one lets its allocations go, as reject sets review first.\nCREATE TRIGGER payment_allocations_void_bd BEFORE DELETE ON payment_allocations\n WHEN (SELECT status = 'void' AND review <> 'rejected' FROM invoices WHERE id = old.invoice_id) BEGIN\n SELECT RAISE(ABORT, 'payment_allocations: a void invoice keeps its allocations');\nEND;"
1196
1196
  ]
1197
+ },
1198
+ {
1199
+ "name": "20261108104659_version-58-enrichments",
1200
+ "statements": [
1201
+ "CREATE TABLE `enrichments` (\n\t`subject_type` text NOT NULL,\n\t`subject_id` integer NOT NULL,\n\t`source_hash` text NOT NULL,\n\t`provider` text NOT NULL,\n\t`model` text NOT NULL,\n\t`text` text NOT NULL,\n\t`tokens` integer NOT NULL,\n\t`created_at` integer NOT NULL,\n\tCONSTRAINT `enrichments_pk` PRIMARY KEY(`subject_type`, `subject_id`)\n);"
1202
+ ]
1203
+ },
1204
+ {
1205
+ "name": "20261108104701_version-58-enrichments-deletes",
1206
+ "statements": [
1207
+ "CREATE TRIGGER enrichments_document_gone AFTER DELETE ON documents BEGIN\n DELETE FROM enrichments WHERE subject_type = 'document' AND subject_id = OLD.id;\nEND;",
1208
+ "CREATE TRIGGER enrichments_note_gone AFTER DELETE ON notes BEGIN\n DELETE FROM enrichments WHERE subject_type = 'note' AND subject_id = OLD.id;\nEND;",
1209
+ "CREATE TRIGGER enrichments_email_gone AFTER DELETE ON emails BEGIN\n DELETE FROM enrichments WHERE subject_type = 'email' AND subject_id = OLD.id;\n DELETE FROM chunks WHERE chunkable_type = 'email_enrichment' AND chunkable_id = OLD.id;\nEND;"
1210
+ ]
1197
1211
  }
1198
1212
  ];
@@ -101,8 +101,7 @@ export declare const CORPORA: {
101
101
  readonly read: string;
102
102
  };
103
103
  };
104
- /** What a row is indexed as: its title, then its text. Chunk offsets point into this. */
105
- export declare const noteIndexText: (title: string | null, text: string) => string;
104
+ export { noteIndexText } from "./index-text.js";
106
105
  /**
107
106
  * `column` (a note's or document's id) is a row whose title or text holds `search` anywhere, in any letter case;
108
107
  * no condition for an empty `search`. A row the trigrams do not hold yet — waiting in its queue, or stored before
@@ -5,8 +5,10 @@ import { taskStemsOf, taskWordsOf } from "../../search/task-similarity.js";
5
5
  import { isQueryOnly } from "../driver.js";
6
6
  import { normalize } from "../normalize.js";
7
7
  import { dropDocumentPicture } from "./document-pictures.js";
8
+ import { currentEnrichment, EMAIL_ENRICHMENT, ENRICHMENT_POSITION } from "./enrichments.js";
8
9
  import { int } from "./events.js";
9
10
  import { indexRow } from "./index-state.js";
11
+ import { noteIndexText } from "./index-text.js";
10
12
  import { speech } from "./lucene-fields.js";
11
13
  import { savedStemmers } from "./stems.js";
12
14
  import { write } from "./transaction.js";
@@ -102,8 +104,7 @@ export const CORPORA = {
102
104
  "WHERE ce.event_id = e.id AND ce.deleted_at IS NULL ORDER BY ce.id LIMIT 1) AS account_id FROM events e WHERE e.id = ?",
103
105
  },
104
106
  };
105
- /** What a row is indexed as: its title, then its text. Chunk offsets point into this. */
106
- export const noteIndexText = (title, text) => (title ? `${title}\n\n${text}` : text);
107
+ export { noteIndexText } from "./index-text.js";
107
108
  const queuedAs = (corpus) => corpus.queued ?? corpus.type;
108
109
  const hasTrigrams = (corpus) => corpus.type === "note" || corpus.type === "document";
109
110
  /**
@@ -207,26 +208,46 @@ const writer = (database, corpus, stemmer) => {
207
208
  chunk: database.prepare("INSERT INTO chunks (chunkable_type, chunkable_id, position, start_offset, end_offset, content_hash, scope, account_id, created_at, updated_at) " +
208
209
  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),
209
210
  dequeue: database.prepare(`DELETE FROM ${corpus.type}_index_pending WHERE indexable_type = ? AND id = ?`),
211
+ emailAt: database.prepare("SELECT coalesce(received_at, sent_at) AS at FROM emails WHERE id = ?"),
210
212
  };
213
+ const enrichedType = corpus.type === "email" ? EMAIL_ENRICHMENT : corpus.type;
211
214
  return (id) => {
212
215
  const row = read.get(id);
213
- const before = oldHashes.all(corpus.type, id).map((hash) => String(hash.hash));
216
+ const before = [
217
+ ...oldHashes.all(corpus.type, id).map((hash) => String(hash.hash)),
218
+ ...(corpus.type === "email" ? oldHashes.all(EMAIL_ENRICHMENT, id).map((hash) => String(hash.hash)) : []),
219
+ ];
214
220
  statements.dropWords.run(id);
215
221
  statements.dropStems.run(id);
216
222
  statements.dropTrigrams?.run(id);
217
223
  statements.dropChunks.run(corpus.type, id);
224
+ if (corpus.type === "email")
225
+ statements.dropChunks.run(EMAIL_ENRICHMENT, id);
218
226
  const live = row !== undefined && Number(row.live) === 1;
219
227
  const text = live ? noteIndexText(row.title == null ? null : String(row.title), String(row.body)) : "";
220
228
  const scope = live ? String(row.scope ?? "personal") : "";
229
+ // Only the stems see it: words, trigrams and --exact stay the record's own text.
230
+ const enrichment = text.trim() ? currentEnrichment(database, corpus.type, id, text) : undefined;
221
231
  const terms = corpus.terms && text ? corpus.terms(text, stemmer) : undefined;
222
232
  const words = terms ? terms.words : normalize(text);
223
233
  if (words !== "") {
224
234
  statements.words.run(id, words, scope);
225
235
  statements.trigrams?.run(id, words);
226
236
  }
227
- const stems = terms ? terms.stems : text ? stemmer.indexText(text) : "";
237
+ const stems = terms ? terms.stems : text ? stemmer.indexText(enrichment ? `${text}\n\n${enrichment}` : text) : "";
228
238
  if (stems !== "")
229
239
  statements.stems.run(id, stems, scope);
240
+ // A chunk of its own, never appended to the record's: appended text diluted the record's vector (cli-testing
241
+ // knowledge-graph-memory, 0.71 to 0.67 by meaning).
242
+ if (enrichment) {
243
+ const at = Date.now();
244
+ const occurred = corpus.type === "email" ? int(statements.emailAt.get(id)?.at) : null;
245
+ statements.chunk.run(enrichedType, id, corpus.type === "email" ? 0 : ENRICHMENT_POSITION, 0, 0, chunkHash(enrichment), scope, int(row?.account_id), at, at);
246
+ if (occurred !== null && occurred !== undefined)
247
+ database
248
+ .prepare("UPDATE chunks SET occurred_at = ? WHERE chunkable_type = ? AND chunkable_id = ?")
249
+ .run(occurred, EMAIL_ENRICHMENT, id);
250
+ }
230
251
  if (text.trim() && corpus.pieces !== false) {
231
252
  const at = Date.now();
232
253
  const sections = row?.metadata == null ? [] : storedSections(String(row.metadata));
@@ -6,6 +6,7 @@ import { exhausted, outOfTime, QUERY_LIMITS, searchError } from "../../search/lu
6
6
  import { normalize } from "../normalize.js";
7
7
  import { contextDocumentTime } from "./context-document-source.js";
8
8
  import { documentPicturesOver } from "./document-pictures.js";
9
+ import { ENRICHMENT_POSITION, enrichmentText } from "./enrichments.js";
9
10
  import { linkKind } from "./link-kinds.js";
10
11
  import { prefixOf } from "./lucene.js";
11
12
  import { drainNoteIndex, noteIndexState, noteIndexText } from "./note-index.js";
@@ -374,13 +375,19 @@ export const noteSearchOver = (context) => {
374
375
  return texts.get(owner);
375
376
  };
376
377
  return database
377
- .prepare(`SELECT k.content_hash AS hash, min(k.chunkable_type || ':' || k.chunkable_id) AS owner, k.start_offset AS start, k.end_offset AS end
378
+ .prepare(`SELECT k.content_hash AS hash, min(k.chunkable_type || ':' || k.chunkable_id) AS owner, k.start_offset AS start, k.end_offset AS end,
379
+ k.position
378
380
  FROM chunks k
379
381
  WHERE k.content_hash > ?${scope.sql}
380
382
  AND NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)
381
383
  GROUP BY k.content_hash ORDER BY k.content_hash LIMIT ?`)
382
384
  .all(after ?? "", ...scope.params, model, limit)
383
385
  .flatMap((row) => {
386
+ if (Number(row.position) === ENRICHMENT_POSITION) {
387
+ const [type, id] = String(row.owner).split(":");
388
+ const text = enrichmentText(database, String(type), Number(id));
389
+ return text === undefined ? [] : [{ hash: String(row.hash), text }];
390
+ }
384
391
  const text = textOf(String(row.owner));
385
392
  return text === undefined
386
393
  ? []
@@ -0,0 +1,137 @@
1
+ /** What a hosted model wrote about one record, read by search beside it; only with the owner's consent. */
2
+ export declare const enrichments: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
3
+ name: "enrichments";
4
+ schema: undefined;
5
+ columns: {
6
+ subjectType: import("drizzle-orm/sqlite-core").SQLiteColumn<{
7
+ name: string;
8
+ tableName: "enrichments";
9
+ dataType: "string";
10
+ data: string;
11
+ driverParam: string;
12
+ notNull: true;
13
+ hasDefault: false;
14
+ isPrimaryKey: false;
15
+ isAutoincrement: false;
16
+ hasRuntimeDefault: false;
17
+ enumValues: [string, ...string[]];
18
+ baseColumn: never;
19
+ identity: undefined;
20
+ generated: undefined;
21
+ }, {}>;
22
+ subjectId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
23
+ name: string;
24
+ tableName: "enrichments";
25
+ dataType: "number int53";
26
+ data: number;
27
+ driverParam: number;
28
+ notNull: true;
29
+ hasDefault: false;
30
+ isPrimaryKey: false;
31
+ isAutoincrement: false;
32
+ hasRuntimeDefault: false;
33
+ enumValues: undefined;
34
+ baseColumn: never;
35
+ identity: undefined;
36
+ generated: undefined;
37
+ }, {}>;
38
+ sourceHash: import("drizzle-orm/sqlite-core").SQLiteColumn<{
39
+ name: string;
40
+ tableName: "enrichments";
41
+ dataType: "string";
42
+ data: string;
43
+ driverParam: string;
44
+ notNull: true;
45
+ hasDefault: false;
46
+ isPrimaryKey: false;
47
+ isAutoincrement: false;
48
+ hasRuntimeDefault: false;
49
+ enumValues: [string, ...string[]];
50
+ baseColumn: never;
51
+ identity: undefined;
52
+ generated: undefined;
53
+ }, {}>;
54
+ provider: import("drizzle-orm/sqlite-core").SQLiteColumn<{
55
+ name: string;
56
+ tableName: "enrichments";
57
+ dataType: "string";
58
+ data: string;
59
+ driverParam: string;
60
+ notNull: true;
61
+ hasDefault: false;
62
+ isPrimaryKey: false;
63
+ isAutoincrement: false;
64
+ hasRuntimeDefault: false;
65
+ enumValues: [string, ...string[]];
66
+ baseColumn: never;
67
+ identity: undefined;
68
+ generated: undefined;
69
+ }, {}>;
70
+ model: import("drizzle-orm/sqlite-core").SQLiteColumn<{
71
+ name: string;
72
+ tableName: "enrichments";
73
+ dataType: "string";
74
+ data: string;
75
+ driverParam: string;
76
+ notNull: true;
77
+ hasDefault: false;
78
+ isPrimaryKey: false;
79
+ isAutoincrement: false;
80
+ hasRuntimeDefault: false;
81
+ enumValues: [string, ...string[]];
82
+ baseColumn: never;
83
+ identity: undefined;
84
+ generated: undefined;
85
+ }, {}>;
86
+ text: import("drizzle-orm/sqlite-core").SQLiteColumn<{
87
+ name: string;
88
+ tableName: "enrichments";
89
+ dataType: "string";
90
+ data: string;
91
+ driverParam: string;
92
+ notNull: true;
93
+ hasDefault: false;
94
+ isPrimaryKey: false;
95
+ isAutoincrement: false;
96
+ hasRuntimeDefault: false;
97
+ enumValues: [string, ...string[]];
98
+ baseColumn: never;
99
+ identity: undefined;
100
+ generated: undefined;
101
+ }, {}>;
102
+ tokens: import("drizzle-orm/sqlite-core").SQLiteColumn<{
103
+ name: string;
104
+ tableName: "enrichments";
105
+ dataType: "number int53";
106
+ data: number;
107
+ driverParam: number;
108
+ notNull: true;
109
+ hasDefault: false;
110
+ isPrimaryKey: false;
111
+ isAutoincrement: false;
112
+ hasRuntimeDefault: false;
113
+ enumValues: undefined;
114
+ baseColumn: never;
115
+ identity: undefined;
116
+ generated: undefined;
117
+ }, {}>;
118
+ createdAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
119
+ name: string;
120
+ tableName: "enrichments";
121
+ dataType: "number int53";
122
+ data: number;
123
+ driverParam: number;
124
+ notNull: true;
125
+ hasDefault: false;
126
+ isPrimaryKey: false;
127
+ isAutoincrement: false;
128
+ hasRuntimeDefault: false;
129
+ enumValues: undefined;
130
+ baseColumn: never;
131
+ identity: undefined;
132
+ generated: undefined;
133
+ }, {}>;
134
+ };
135
+ dialect: 'sqlite';
136
+ isAlias: false;
137
+ }>;
@@ -0,0 +1,12 @@
1
+ import { integer, primaryKey, sqliteTable, text } from "../drizzle/core.js";
2
+ /** What a hosted model wrote about one record, read by search beside it; only with the owner's consent. */
3
+ export const enrichments = sqliteTable("enrichments", {
4
+ subjectType: text("subject_type").notNull(),
5
+ subjectId: integer("subject_id").notNull(),
6
+ sourceHash: text("source_hash").notNull(),
7
+ provider: text("provider").notNull(),
8
+ model: text("model").notNull(),
9
+ text: text("text").notNull(),
10
+ tokens: integer("tokens").notNull(),
11
+ createdAt: integer("created_at").notNull(),
12
+ }, (table) => [primaryKey({ columns: [table.subjectType, table.subjectId] })]);
@@ -19486,6 +19486,7 @@ export declare const transactionSplits: import("drizzle-orm/sqlite-core").SQLite
19486
19486
  isAlias: false;
19487
19487
  }>;
19488
19488
  export { decisionRequests } from "./schema/decision-requests.js";
19489
+ export { enrichments } from "./schema/enrichments.js";
19489
19490
  /** What a source said about one of its records, as it said it: the layer under the entity an import makes. */
19490
19491
  export declare const records: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
19491
19492
  name: "records";
@@ -1933,6 +1933,7 @@ export const transactionSplits = sqliteTable("transaction_splits", {
1933
1933
  index("transaction_splits_by_project_id").on(table.projectId),
1934
1934
  ]);
1935
1935
  export { decisionRequests } from "./schema/decision-requests.js";
1936
+ export { enrichments } from "./schema/enrichments.js";
1936
1937
  /** What a source said about one of its records, as it said it: the layer under the entity an import makes. */
1937
1938
  export const records = sqliteTable("records", {
1938
1939
  id: integer("id").primaryKey(),
@@ -28,6 +28,7 @@ import { type CrmCopies } from "./sqlite/crm.js";
28
28
  import { type DealsStore } from "./sqlite/deals.js";
29
29
  import { type DecisionRequestStore } from "./sqlite/decision-requests.js";
30
30
  import { type MailStore } from "./sqlite/emails.js";
31
+ import { type EnrichmentStore } from "./sqlite/enrichments.js";
31
32
  import { type EventSearch } from "./sqlite/event-search.js";
32
33
  import { type FactsStore } from "./sqlite/facts.js";
33
34
  import { type FilesStore } from "./sqlite/files.js";
@@ -149,6 +150,8 @@ export interface MessageStore {
149
150
  readonly meetings: StoredMeetings;
150
151
  /** Email threads, emails, recipients and mailboxes. */
151
152
  readonly mail: MailStore;
153
+ /** What a hosted model wrote about notes, documents and mail, with the owner's consent; off by default. */
154
+ readonly enrichment?: EnrichmentStore;
152
155
  /** The same store with this account bound — what a service of one account reads and writes through. */
153
156
  forAccount(key: AccountKey): AccountStore;
154
157
  close(): Promise<void>;
@@ -26,6 +26,7 @@ import { crmCopiesOver } from "./sqlite/crm.js";
26
26
  import { dealsStoreOver } from "./sqlite/deals.js";
27
27
  import { decisionRequestStoreOver } from "./sqlite/decision-requests.js";
28
28
  import { mailStoreOver } from "./sqlite/emails.js";
29
+ import { enrichmentsOver } from "./sqlite/enrichments.js";
29
30
  import { eventSearchOver } from "./sqlite/event-search.js";
30
31
  import { evidenceFindingsStoreOver } from "./sqlite/evidence-findings.js";
31
32
  import { factsStoreOver } from "./sqlite/facts.js";
@@ -139,7 +140,11 @@ const storeOver = (context) => {
139
140
  const proposedActions = once(() => proposedActionsStoreOver(context));
140
141
  const agentActions = once(() => agentActionsStoreOver(context, pruneLogsWhenDue));
141
142
  const meetings = once(() => meetingStoreOver(context));
143
+ const enrichment = once(() => enrichmentsOver(context));
142
144
  const store = {
145
+ get enrichment() {
146
+ return enrichment();
147
+ },
143
148
  get projectAnnotations() {
144
149
  return projectAnnotations();
145
150
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.611.0",
3
+ "version": "0.613.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",
@@ -15,7 +15,7 @@
15
15
  "type": "module",
16
16
  "wirecat": {
17
17
  "store": {
18
- "speaks": 57,
18
+ "speaks": 58,
19
19
  "minCompatible": 56
20
20
  }
21
21
  },