@wirecat/cli-core 0.606.0 → 0.608.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 (209) hide show
  1. package/CHANGELOG.md +196 -0
  2. package/dist/calendar/index.d.ts +1 -0
  3. package/dist/calendar/index.js +1 -0
  4. package/dist/calendar/reads.js +5 -0
  5. package/dist/cli/app-mcp-command.d.ts +6 -2
  6. package/dist/cli/app-mcp-command.js +11 -2
  7. package/dist/cli/csv.d.ts +10 -0
  8. package/dist/cli/csv.js +22 -0
  9. package/dist/cli/early-refusal.d.ts +10 -0
  10. package/dist/cli/early-refusal.js +19 -0
  11. package/dist/cli/index.d.ts +3 -0
  12. package/dist/cli/index.js +3 -0
  13. package/dist/cli/profile-token.d.ts +29 -0
  14. package/dist/cli/profile-token.js +65 -0
  15. package/dist/cli/program.js +4 -2
  16. package/dist/crm/cli/csv.d.ts +23 -0
  17. package/dist/crm/cli/csv.js +135 -0
  18. package/dist/crm/cli/index.d.ts +1 -1
  19. package/dist/crm/cli/index.js +33 -21
  20. package/dist/crm/cli/pipeline-view.d.ts +3 -0
  21. package/dist/crm/cli/pipeline-view.js +36 -0
  22. package/dist/crm/writes.d.ts +6 -4
  23. package/dist/crm/writes.js +17 -13
  24. package/dist/documents.d.ts +2 -0
  25. package/dist/documents.js +2 -0
  26. package/dist/domain/business.d.ts +79 -0
  27. package/dist/domain/business.js +42 -0
  28. package/dist/domain/finance.d.ts +2 -0
  29. package/dist/domain/finance.js +2 -2
  30. package/dist/domain/google-documents.d.ts +2 -0
  31. package/dist/domain/google-documents.js +3 -1
  32. package/dist/domain/money.d.ts +2 -0
  33. package/dist/domain/money.js +11 -3
  34. package/dist/domain/providers.d.ts +36 -1
  35. package/dist/domain/providers.js +69 -7
  36. package/dist/domain/record-fields.d.ts +42 -0
  37. package/dist/domain/record-fields.js +122 -0
  38. package/dist/domain/record-types.d.ts +489 -16
  39. package/dist/domain/record-types.js +374 -7
  40. package/dist/domain/records.d.ts +96 -5
  41. package/dist/domain/records.js +178 -32
  42. package/dist/domain/ref-summaries.js +5 -0
  43. package/dist/domain/references.d.ts +1 -1
  44. package/dist/domain/references.js +5 -0
  45. package/dist/domain/vcard.d.ts +25 -0
  46. package/dist/domain/vcard.js +267 -0
  47. package/dist/entities/deal.d.ts +14 -0
  48. package/dist/entities/deal.js +3 -0
  49. package/dist/entities/index.d.ts +12 -0
  50. package/dist/errors/reasons.js +63 -4
  51. package/dist/fetch/addresses.d.ts +5 -0
  52. package/dist/fetch/addresses.js +76 -0
  53. package/dist/fetch/page.d.ts +64 -0
  54. package/dist/fetch/page.js +256 -0
  55. package/dist/index.d.ts +5 -3
  56. package/dist/index.js +5 -3
  57. package/dist/meetings/calendar-text.d.ts +1 -1
  58. package/dist/meetings/calendar-text.js +4 -0
  59. package/dist/meetings/event-store.d.ts +2 -2
  60. package/dist/search/account-list.d.ts +4 -0
  61. package/dist/search/account-list.js +19 -8
  62. package/dist/search/query.js +2 -2
  63. package/dist/services/events-search.js +2 -2
  64. package/dist/services/index.d.ts +1 -1
  65. package/dist/services/index.js +1 -1
  66. package/dist/services/ingest.d.ts +56 -8
  67. package/dist/services/ingest.js +95 -61
  68. package/dist/services/messages-search.js +3 -2
  69. package/dist/services/metadata.d.ts +1 -1
  70. package/dist/services/notes-search.js +1 -0
  71. package/dist/services/proposals/kinds/contracts.d.ts +4 -0
  72. package/dist/services/proposals/kinds/contracts.js +9 -0
  73. package/dist/services/proposals/kinds/finance.d.ts +4 -0
  74. package/dist/services/proposals/kinds/finance.js +14 -35
  75. package/dist/services/proposals/kinds/orders.js +7 -30
  76. package/dist/services/proposals/kinds/shared.d.ts +27 -1
  77. package/dist/services/proposals/kinds/shared.js +34 -0
  78. package/dist/services/proposals/kinds/source-review.d.ts +4 -0
  79. package/dist/services/proposals/kinds/source-review.js +45 -0
  80. package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
  81. package/dist/services/proposals/kinds/subscriptions.js +24 -0
  82. package/dist/services/proposals/kinds/transactions.d.ts +4 -0
  83. package/dist/services/proposals/kinds/transactions.js +10 -0
  84. package/dist/services/proposals/registry.js +9 -0
  85. package/dist/services/search-all-meetings.js +2 -2
  86. package/dist/services/search-all.js +4 -3
  87. package/dist/services/search-kind.js +3 -3
  88. package/dist/store/decisions.js +5 -1
  89. package/dist/store/index.d.ts +14 -3
  90. package/dist/store/index.js +3 -0
  91. package/dist/store/people.js +1 -1
  92. package/dist/store/source-review.d.ts +64 -0
  93. package/dist/store/source-review.js +7 -0
  94. package/dist/store/sqlite/accounts.d.ts +1 -1
  95. package/dist/store/sqlite/accounts.js +24 -1
  96. package/dist/store/sqlite/added-sources.d.ts +82 -0
  97. package/dist/store/sqlite/added-sources.js +237 -0
  98. package/dist/store/sqlite/business-contracts.d.ts +90 -0
  99. package/dist/store/sqlite/business-contracts.js +182 -0
  100. package/dist/store/sqlite/calendar-events.js +7 -3
  101. package/dist/store/sqlite/calendar-forget.js +3 -0
  102. package/dist/store/sqlite/calendar.d.ts +21 -1
  103. package/dist/store/sqlite/calendar.js +27 -7
  104. package/dist/store/sqlite/chat-rekey.js +7 -0
  105. package/dist/store/sqlite/chats.d.ts +3 -1
  106. package/dist/store/sqlite/chats.js +15 -1
  107. package/dist/store/sqlite/crm-rows.d.ts +44 -0
  108. package/dist/store/sqlite/crm-rows.js +195 -0
  109. package/dist/store/sqlite/crm.d.ts +2 -11
  110. package/dist/store/sqlite/crm.js +11 -166
  111. package/dist/store/sqlite/deals.d.ts +4 -8
  112. package/dist/store/sqlite/deals.js +5 -3
  113. package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
  114. package/dist/store/sqlite/emails.js +2 -0
  115. package/dist/store/sqlite/entity-types.d.ts +14 -9
  116. package/dist/store/sqlite/entity-types.js +4 -10
  117. package/dist/store/sqlite/evidence-signature.d.ts +114 -0
  118. package/dist/store/sqlite/evidence-signature.js +349 -0
  119. package/dist/store/sqlite/evidence-sources.d.ts +2 -1
  120. package/dist/store/sqlite/evidence-sources.js +7 -3
  121. package/dist/store/sqlite/facts.d.ts +7 -2
  122. package/dist/store/sqlite/facts.js +21 -5
  123. package/dist/store/sqlite/finance.d.ts +18 -105
  124. package/dist/store/sqlite/finance.js +100 -219
  125. package/dist/store/sqlite/knowledge.d.ts +8 -2
  126. package/dist/store/sqlite/knowledge.js +65 -71
  127. package/dist/store/sqlite/labelled.d.ts +3 -0
  128. package/dist/store/sqlite/labelled.js +11 -0
  129. package/dist/store/sqlite/link-kinds.d.ts +2 -0
  130. package/dist/store/sqlite/link-kinds.js +2 -0
  131. package/dist/store/sqlite/manifest.js +2 -0
  132. package/dist/store/sqlite/memories.d.ts +23 -9
  133. package/dist/store/sqlite/memories.js +41 -13
  134. package/dist/store/sqlite/messages.js +2 -0
  135. package/dist/store/sqlite/migrations.generated.js +103 -0
  136. package/dist/store/sqlite/money-lines.d.ts +48 -0
  137. package/dist/store/sqlite/money-lines.js +76 -0
  138. package/dist/store/sqlite/money-transactions.d.ts +132 -0
  139. package/dist/store/sqlite/money-transactions.js +295 -0
  140. package/dist/store/sqlite/notes.d.ts +11 -2
  141. package/dist/store/sqlite/notes.js +20 -25
  142. package/dist/store/sqlite/orders.d.ts +36 -6
  143. package/dist/store/sqlite/orders.js +126 -46
  144. package/dist/store/sqlite/payment-facts.js +1 -1
  145. package/dist/store/sqlite/private-people.js +2 -0
  146. package/dist/store/sqlite/products.d.ts +78 -0
  147. package/dist/store/sqlite/products.js +131 -0
  148. package/dist/store/sqlite/project-transfer/records.js +26 -1
  149. package/dist/store/sqlite/project-transfer/snapshot.js +5 -3
  150. package/dist/store/sqlite/proposed-actions.d.ts +1 -1
  151. package/dist/store/sqlite/proposed-actions.js +24 -7
  152. package/dist/store/sqlite/providers.d.ts +0 -4
  153. package/dist/store/sqlite/providers.js +20 -2
  154. package/dist/store/sqlite/record-matching.d.ts +80 -0
  155. package/dist/store/sqlite/record-matching.js +264 -0
  156. package/dist/store/sqlite/record-projection.d.ts +89 -0
  157. package/dist/store/sqlite/record-projection.js +50 -0
  158. package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
  159. package/dist/store/sqlite/record-projectors-direct.js +125 -0
  160. package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
  161. package/dist/store/sqlite/record-projectors-money.js +214 -0
  162. package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
  163. package/dist/store/sqlite/record-projectors-phone.js +212 -0
  164. package/dist/store/sqlite/record-projectors.d.ts +3 -44
  165. package/dist/store/sqlite/record-projectors.js +7 -67
  166. package/dist/store/sqlite/record-relations.d.ts +24 -0
  167. package/dist/store/sqlite/record-relations.js +92 -0
  168. package/dist/store/sqlite/record-remap.d.ts +12 -0
  169. package/dist/store/sqlite/record-remap.js +92 -0
  170. package/dist/store/sqlite/record-run.d.ts +71 -0
  171. package/dist/store/sqlite/record-run.js +179 -0
  172. package/dist/store/sqlite/record-settling.d.ts +9 -0
  173. package/dist/store/sqlite/record-settling.js +74 -0
  174. package/dist/store/sqlite/record-stamps.d.ts +13 -0
  175. package/dist/store/sqlite/record-stamps.js +30 -0
  176. package/dist/store/sqlite/record-writes.d.ts +43 -0
  177. package/dist/store/sqlite/record-writes.js +307 -0
  178. package/dist/store/sqlite/records.d.ts +52 -42
  179. package/dist/store/sqlite/records.js +123 -353
  180. package/dist/store/sqlite/ref-summaries.d.ts +6 -5
  181. package/dist/store/sqlite/ref-summaries.js +60 -8
  182. package/dist/store/sqlite/refunds.d.ts +31 -0
  183. package/dist/store/sqlite/refunds.js +112 -0
  184. package/dist/store/sqlite/reviewed.d.ts +109 -0
  185. package/dist/store/sqlite/reviewed.js +173 -0
  186. package/dist/store/sqlite/schema.d.ts +2840 -83
  187. package/dist/store/sqlite/schema.js +256 -1
  188. package/dist/store/sqlite/source-review-marks.d.ts +54 -0
  189. package/dist/store/sqlite/source-review-marks.js +143 -0
  190. package/dist/store/sqlite/source-review.d.ts +54 -0
  191. package/dist/store/sqlite/source-review.js +221 -0
  192. package/dist/store/sqlite/stage-amounts.d.ts +14 -0
  193. package/dist/store/sqlite/stage-amounts.js +23 -0
  194. package/dist/store/sqlite/subscriptions.d.ts +135 -0
  195. package/dist/store/sqlite/subscriptions.js +294 -0
  196. package/dist/store/sqlite/text-input.d.ts +3 -0
  197. package/dist/store/sqlite/text-input.js +13 -0
  198. package/dist/store/sqlite/things.js +2 -9
  199. package/dist/store/sqlite/transaction.d.ts +15 -0
  200. package/dist/store/sqlite/transaction.js +57 -0
  201. package/dist/store/sqlite/wallets.d.ts +88 -0
  202. package/dist/store/sqlite/wallets.js +143 -0
  203. package/dist/store/store-errors.d.ts +1 -0
  204. package/dist/store/store-errors.js +45 -0
  205. package/dist/store/store.d.ts +16 -1
  206. package/dist/store/store.js +30 -6
  207. package/package.json +5 -2
  208. package/schemas/examples/records-business.jsonl +11 -0
  209. package/schemas/records-envelope.v1.schema.json +1160 -5
@@ -0,0 +1,82 @@
1
+ import type { Section } from "../../readers/types.js";
2
+ import type { Decider } from "../decisions.js";
3
+ import { type DocumentMetadata } from "./document-metadata.js";
4
+ import { type Note, type NoteFolder } from "./notes.js";
5
+ import type { StoreContext } from "./open.js";
6
+ export declare const ADDED_KINDS: readonly ["text", "file", "page"];
7
+ /** A source the owner adds by hand: pasted text, a file, or a page read from a link. */
8
+ export interface AddedSourceInput {
9
+ kind: (typeof ADDED_KINDS)[number];
10
+ /** What a reader found; empty when it found none (`read: "no-text"`). */
11
+ text: string;
12
+ read: "extracted" | "no-text";
13
+ title?: string | null;
14
+ /** The page's address, or where a file came from. */
15
+ url?: string | null;
16
+ fileName?: string | null;
17
+ mime?: string | null;
18
+ size?: number | null;
19
+ /** A file's own bytes, which name it. Pasted text and a page are named by their normalized text. */
20
+ bytes?: Uint8Array;
21
+ /** People, organizations, projects, tasks or meetings it is about (`person:3`), linked `about`. */
22
+ subjects?: readonly string[];
23
+ /** The owner's subjects are his statement; an agent's wait unconfirmed, as its links always do. */
24
+ by: Decider;
25
+ /** Where the caller keeps a copy of the file. Without it only the text is kept, and nothing claims a copy. */
26
+ keepCopy?: {
27
+ path: string;
28
+ };
29
+ metadata?: DocumentMetadata;
30
+ sections?: Section[];
31
+ }
32
+ /** What names an added source: enough to find it before anything is written. */
33
+ export type AddedSourceContent = Pick<AddedSourceInput, "kind" | "text" | "url" | "bytes">;
34
+ /** The part of `store.notes` that keeps the sources added by hand. */
35
+ export interface AddedSources {
36
+ /**
37
+ * Saves a source the owner added by hand into the `added` account, named `sha256:<hash>`: a repeat is the same
38
+ * document, and a live folder or Drive document with the same content is answered as `duplicateOf`, given only the
39
+ * new subjects.
40
+ */
41
+ saveAddedSource(input: AddedSourceInput): Promise<AddedSource>;
42
+ /** The account of the sources added by hand, once one was saved. */
43
+ addedAccount(): Promise<NoteFolder | undefined>;
44
+ /**
45
+ * What saving this content would find, read only: the live added source it repeats, or the folder or Drive document
46
+ * it duplicates. A caller that keeps a copy of the file asks this first, and writes the copy only when both are null.
47
+ */
48
+ findAddedSource(content: AddedSourceContent): Promise<{
49
+ existing: string | null;
50
+ duplicateOf: string | null;
51
+ }>;
52
+ /**
53
+ * Removes an added source the way a folder file's removal does: its text goes, its row stays as deleted. The owner's
54
+ * alone. Answers the copy's path, for the caller to delete, when one was kept.
55
+ */
56
+ removeAddedSource(reference: string, by: Decider): Promise<{
57
+ ref: string;
58
+ removed: true;
59
+ copy: string | null;
60
+ }>;
61
+ }
62
+ export interface AddedSource {
63
+ /** The document holding it: the added one, or the live document of the same content it duplicates. */
64
+ note: Note;
65
+ created: boolean;
66
+ /** The folder or Drive document with the same content, when nothing new was stored. */
67
+ duplicateOf: string | null;
68
+ /** What is kept of the source: its text, or its text and a copy; `null` for a duplicate. */
69
+ kept: "text" | "copy" | null;
70
+ /** Every subject the document is about now, the ones linked before included. */
71
+ subjects: string[];
72
+ }
73
+ /**
74
+ * The key an added source is stored under, `sha256:<hash>` (a file's bytes; pasted text or a page by its normalized
75
+ * text, or its address when it has none), and every hash a folder or Drive document of the same content may carry.
76
+ */
77
+ export declare const addedSourceKeyOf: (content: AddedSourceContent) => {
78
+ externalId: string;
79
+ hash: string;
80
+ hashes: string[];
81
+ };
82
+ export declare const addedSourcesOver: (context: StoreContext) => AddedSources;
@@ -0,0 +1,237 @@
1
+ import { createHash } from "node:crypto";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { MAX_TEXT_CHARS } from "../../attachments/limits.js";
4
+ import { ADDED_ACCOUNT, ADDED_PROVIDER, notAdded } from "../../domain/providers.js";
5
+ import { fold } from "../normalize.js";
6
+ import { encodeDocumentMetadata, languageOf } from "./document-metadata.js";
7
+ import { syncFile } from "./files.js";
8
+ import { linkKind } from "./link-kinds.js";
9
+ import { documentOf, folderOf, insertLink, pathParts, requiredThing, thingRef, } from "./notes.js";
10
+ import { oneOf, textOf } from "./text-input.js";
11
+ import { write } from "./transaction.js";
12
+ export const ADDED_KINDS = ["text", "file", "page"];
13
+ const sha256 = (value) => createHash("sha256").update(value).digest("hex");
14
+ /**
15
+ * The key an added source is stored under, `sha256:<hash>` (a file's bytes; pasted text or a page by its normalized
16
+ * text, or its address when it has none), and every hash a folder or Drive document of the same content may carry.
17
+ */
18
+ export const addedSourceKeyOf = (content) => {
19
+ const kind = oneOf(content.kind, ADDED_KINDS, "an added source's kind");
20
+ if (kind === "file" && !content.bytes)
21
+ throw new CliError("validation_error", "an added file needs its bytes");
22
+ const text = content.text.trim();
23
+ const url = content.url?.trim() || null;
24
+ const normalized = text.normalize("NFC").replace(/\s+/gu, " ").trim();
25
+ if (kind !== "file" && !normalized && !url)
26
+ throw new CliError("validation_error", "an added source without text needs its address");
27
+ const hash = kind === "file" ? sha256(content.bytes) : sha256(normalized || url);
28
+ // Drive keeps the sha256 of the text it exported, as is: pasted text or a page with that text is that file.
29
+ const hashes = [...new Set(kind === "file" || !text ? [hash] : [hash, sha256(content.text)])];
30
+ return { externalId: `sha256:${hash}`, hash, hashes };
31
+ };
32
+ /** The input checked. */
33
+ const checked = (input) => {
34
+ const read = oneOf(input.read, ["extracted", "no-text"], "what was read");
35
+ const text = textOf(input.text, "an added source's text", MAX_TEXT_CHARS, read === "no-text");
36
+ if (read === "no-text" && text)
37
+ throw new CliError("validation_error", "a source read as no-text has no text");
38
+ if (input.kind === "text" && read === "no-text")
39
+ throw new CliError("validation_error", "pasted text cannot be empty");
40
+ const url = input.url == null ? null : textOf(input.url, "an added source's address", 4096);
41
+ if (input.kind === "page" && !url)
42
+ throw new CliError("validation_error", "an added page needs its address");
43
+ const copy = input.keepCopy === undefined ? null : textOf(input.keepCopy.path, "the copy's path", 4096);
44
+ if (copy !== null && input.kind !== "file")
45
+ throw new CliError("validation_error", "only a file is kept as a copy");
46
+ const fileName = input.fileName == null ? null : textOf(input.fileName, "a file's name", 500);
47
+ const title = input.title == null || !input.title.trim() ? null : textOf(input.title, "a title", 500);
48
+ return {
49
+ ...addedSourceKeyOf(input),
50
+ kind: input.kind,
51
+ read,
52
+ text,
53
+ url,
54
+ copy,
55
+ title,
56
+ fileName,
57
+ extension: fileName === null ? null : pathParts(fileName).extension,
58
+ };
59
+ };
60
+ export const addedSourcesOver = (context) => {
61
+ const { database, now } = context;
62
+ const accountRow = () => database.prepare("SELECT * FROM accounts WHERE provider = ? AND external_id = ?").get(ADDED_PROVIDER, ADDED_ACCOUNT);
63
+ const documentAt = (id) => documentOf(database.prepare("SELECT * FROM documents WHERE id = ?").get(id));
64
+ const ownRow = (externalId) => {
65
+ const account = accountRow();
66
+ return account
67
+ ? database
68
+ .prepare("SELECT * FROM documents WHERE account_id = ? AND external_id = ?")
69
+ .get(Number(account.id), externalId)
70
+ : undefined;
71
+ };
72
+ const about = (id, subjects, by) => {
73
+ const at = now();
74
+ for (const subject of subjects) {
75
+ if (by === "owner") {
76
+ const link = insertLink(context, { from: `document:${id}`, to: subject, kind: "about", origin: "owner" });
77
+ // An agent's proposal of the same subject is what the owner now states.
78
+ if (!link.confirmed)
79
+ database
80
+ .prepare("UPDATE links SET confirmed = 1, source = 'owner', author = 'owner', updated_at = ? WHERE id = ?")
81
+ .run(at, Number(link.id));
82
+ continue;
83
+ }
84
+ const thing = requiredThing(database, subject, "a subject");
85
+ const known = database
86
+ .prepare(`SELECT 1 FROM links WHERE from_type = 'document' AND from_id = ? AND to_type = ? AND to_id = ? AND kind = ${linkKind("about")} AND anchor IS NULL`)
87
+ .get(id, thing.type, thing.id);
88
+ const link = insertLink(context, {
89
+ from: `document:${id}`,
90
+ to: subject,
91
+ kind: "about",
92
+ origin: "suggested",
93
+ confirmed: false,
94
+ provenance: by.reason,
95
+ });
96
+ if (!known)
97
+ database
98
+ .prepare("UPDATE links SET author = ?, metadata = ? WHERE id = ?")
99
+ .run(by.bot, JSON.stringify({ provenance: by.reason, ...(by.model ? { model: by.model } : {}) }), Number(link.id));
100
+ }
101
+ return database
102
+ .prepare(`SELECT to_type, to_id FROM links WHERE from_type = 'document' AND from_id = ? AND kind = ${linkKind("about")} ` +
103
+ "AND to_id IS NOT NULL ORDER BY id")
104
+ .all(id)
105
+ .flatMap((row) => thingRef(database, row.to_type, row.to_id) ?? []);
106
+ };
107
+ /** A live folder or Drive document with this content; a document no reader could read matches nothing. */
108
+ const duplicateOf = (hashes) => {
109
+ const row = database
110
+ .prepare("SELECT d.id FROM documents d WHERE d.content_hash IN (SELECT value FROM json_each(?)) AND d.deleted_at IS NULL " +
111
+ `AND d.body <> '' AND ${notAdded} AND coalesce(json_extract(d.metadata, '$.catalog.active'), 1) = 1 ` +
112
+ "ORDER BY d.id LIMIT 1")
113
+ .get(JSON.stringify(hashes));
114
+ return row ? Number(row.id) : undefined;
115
+ };
116
+ /** Its `files` row is named as the owner named the source, not by its hash. */
117
+ const placeFile = (id, at, name) => {
118
+ syncFile(database, at, id);
119
+ database
120
+ .prepare("UPDATE files SET name = ?, path = ?, path_folded = ? WHERE document_id = ? AND kind <> 'folder'")
121
+ .run(name, name, fold(name), id);
122
+ };
123
+ return {
124
+ addedAccount: async () => {
125
+ const row = accountRow();
126
+ return row ? folderOf(row) : undefined;
127
+ },
128
+ findAddedSource: async (content) => {
129
+ const key = addedSourceKeyOf(content);
130
+ const own = ownRow(key.externalId);
131
+ if (own && own.deleted_at == null)
132
+ return { existing: `document:${own.id}`, duplicateOf: null };
133
+ const duplicate = duplicateOf(key.hashes);
134
+ return { existing: null, duplicateOf: duplicate === undefined ? null : `document:${duplicate}` };
135
+ },
136
+ removeAddedSource: async (reference, by) => {
137
+ if (by !== "owner")
138
+ throw new CliError("permission_error", "only the owner removes a source he added", {
139
+ reason: "proposal.owner-only",
140
+ });
141
+ return write(database, () => {
142
+ const id = /^document:\d+$/.test(reference) ? Number(reference.slice("document:".length)) : Number.NaN;
143
+ const row = database
144
+ .prepare("SELECT d.* FROM documents d JOIN accounts a ON a.id = d.account_id WHERE d.id = ? AND a.provider = ? " +
145
+ "AND d.deleted_at IS NULL")
146
+ .get(id, ADDED_PROVIDER);
147
+ if (!row)
148
+ throw new CliError("not_found", `no live added source ${reference} in the local store`);
149
+ const at = now();
150
+ database
151
+ .prepare("UPDATE files SET deleted_at = ?, updated_at = ? WHERE document_id = ? AND deleted_at IS NULL")
152
+ .run(at, at, id);
153
+ database.prepare("UPDATE documents SET deleted_at = ?, body = '' WHERE id = ?").run(at, id);
154
+ return {
155
+ ref: `document:${id}`,
156
+ removed: true,
157
+ copy: row.storage === "copy" ? String(row.local_path) : null,
158
+ };
159
+ });
160
+ },
161
+ saveAddedSource: async (input) => {
162
+ const source = checked(input);
163
+ const metadata = encodeDocumentMetadata(input.metadata, input.sections);
164
+ const subjects = input.subjects ?? [];
165
+ return write(database, () => {
166
+ const at = now();
167
+ const own = ownRow(source.externalId);
168
+ if (own !== undefined && own.deleted_at == null) {
169
+ const id = Number(own.id);
170
+ if (source.copy !== null && own.storage !== "copy")
171
+ database
172
+ .prepare("UPDATE documents SET storage = 'copy', local_path = ?, updated_at = ? WHERE id = ?")
173
+ .run(source.copy, at, id);
174
+ const kept = source.copy !== null || own.storage === "copy" ? "copy" : "text";
175
+ return {
176
+ note: documentAt(id),
177
+ created: false,
178
+ duplicateOf: null,
179
+ kept,
180
+ subjects: about(id, subjects, input.by),
181
+ };
182
+ }
183
+ const duplicate = duplicateOf(source.hashes);
184
+ if (duplicate !== undefined) {
185
+ const linked = about(duplicate, subjects, input.by);
186
+ const note = documentAt(duplicate);
187
+ return { note, created: false, duplicateOf: note.ref, kept: null, subjects: linked };
188
+ }
189
+ const values = [
190
+ source.kind,
191
+ source.title,
192
+ source.fileName,
193
+ source.extension,
194
+ source.url,
195
+ source.copy === null ? "text" : "copy",
196
+ source.copy,
197
+ input.mime ?? null,
198
+ input.size ?? input.bytes?.byteLength ?? null,
199
+ source.hash,
200
+ source.text,
201
+ source.read === "extracted" ? "text" : "none",
202
+ metadata,
203
+ languageOf(input.metadata),
204
+ ];
205
+ let id;
206
+ if (own) {
207
+ id = Number(own.id);
208
+ database
209
+ .prepare("UPDATE documents SET kind = ?, title = ?, file_name = ?, extension = ?, url = ?, storage = ?, local_path = ?, " +
210
+ "mime = ?, size = ?, content_hash = ?, body = ?, extraction = ?, metadata = ?, language = ?, " +
211
+ "updated_at = ?, deleted_at = NULL WHERE id = ?")
212
+ .run(...values, at, id);
213
+ }
214
+ else {
215
+ const holder = accountRow()?.id ??
216
+ database
217
+ .prepare("INSERT INTO accounts (provider, external_id, name, settings, created_at, updated_at) " +
218
+ "VALUES (?, ?, NULL, ?, ?, ?) RETURNING id")
219
+ .get(ADDED_PROVIDER, ADDED_ACCOUNT, JSON.stringify({ format: "markdown" }), at, at)?.id;
220
+ id = Number(database
221
+ .prepare("INSERT INTO documents (account_id, external_id, kind, title, file_name, extension, url, storage, local_path, " +
222
+ "mime, size, content_hash, body, extraction, metadata, language, revision, created_at, updated_at) " +
223
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?) RETURNING id")
224
+ .get(Number(holder), source.externalId, ...values, at, at)?.id);
225
+ }
226
+ placeFile(id, at, source.fileName ?? source.title ?? source.externalId);
227
+ return {
228
+ note: documentAt(id),
229
+ created: !own,
230
+ duplicateOf: null,
231
+ kept: source.copy === null ? "text" : "copy",
232
+ subjects: about(id, subjects, input.by),
233
+ };
234
+ });
235
+ },
236
+ };
237
+ };
@@ -0,0 +1,90 @@
1
+ import { type ContractKind, type ContractStatus, type Interval } from "../../domain/business.js";
2
+ import { type FinanceReview } from "../../domain/finance.js";
3
+ import type { Decider } from "../decisions.js";
4
+ import { type ProposedByFilter } from "./actors.js";
5
+ import { type Author } from "./memories.js";
6
+ import type { StoreContext } from "./open.js";
7
+ import { type Reviewed, type Written } from "./reviewed.js";
8
+ export interface Contract extends Reviewed {
9
+ id: string;
10
+ ref: string;
11
+ /** One line, as a list or the review inbox prints it. */
12
+ title: string;
13
+ name: string;
14
+ number: string | null;
15
+ kind: ContractKind;
16
+ status: ContractStatus;
17
+ /** `YYYY-MM-DD`. */
18
+ signedDate: string | null;
19
+ effectiveDate: string | null;
20
+ /** `null` when it runs until ended. */
21
+ expirationDate: string | null;
22
+ autoRenew: boolean;
23
+ /** What one renewal adds, such as 1-year. */
24
+ renewal: Interval | null;
25
+ noticeDays: number | null;
26
+ /** The last day to give notice: the expiration date less the notice days; computed, never stored. */
27
+ noticeDeadline: string | null;
28
+ terms: string | null;
29
+ /** Both `null` when it carries no value. */
30
+ value: string | null;
31
+ currency: string | null;
32
+ deal: string | null;
33
+ }
34
+ export interface ContractFields {
35
+ name?: string;
36
+ number?: string;
37
+ kind?: ContractKind;
38
+ /** `active` when left out. */
39
+ status?: ContractStatus;
40
+ signedDate?: string;
41
+ effectiveDate?: string;
42
+ expirationDate?: string;
43
+ autoRenew?: boolean;
44
+ /** A count and a unit, such as 1-year. */
45
+ renewal?: string;
46
+ noticeDays?: number;
47
+ terms?: string;
48
+ /** A decimal string in `currency`; give both or neither. */
49
+ value?: string;
50
+ currency?: string;
51
+ deal?: string;
52
+ }
53
+ export interface ContractInput extends Written, ContractFields {
54
+ name: string;
55
+ kind: ContractKind;
56
+ }
57
+ export interface ContractUpdate extends ContractFields {
58
+ by: Author;
59
+ }
60
+ export interface ContractFilter {
61
+ status?: ContractStatus;
62
+ kind?: ContractKind;
63
+ project?: string;
64
+ review?: FinanceReview;
65
+ proposedBy?: ProposedByFilter;
66
+ /** `YYYY-MM-DD`: only those that expire on or before it. */
67
+ expiresBy?: string;
68
+ /** 1–500, 100 by default; newest written first. */
69
+ limit?: number;
70
+ }
71
+ /**
72
+ * The contracts the owner works under. One without a value is written confirmed by anyone, as it feeds no total: its
73
+ * `confirmedBy` stays `null` and `author` says who wrote it. With a value an agent's waits as proposed. A confirmed
74
+ * contract is the owner's to change.
75
+ */
76
+ export interface ContractsStore {
77
+ add(input: ContractInput): Promise<Contract>;
78
+ get(reference: string): Promise<Contract>;
79
+ list(filter?: ContractFilter): Promise<Contract[]>;
80
+ /** The owner changes any; a bot only one it proposed that is still proposed. */
81
+ update(reference: string, input: ContractUpdate): Promise<Contract>;
82
+ confirm(reference: string, by: Decider, reason?: string): Promise<Contract>;
83
+ reject(reference: string, by: Decider, reason?: string): Promise<Contract>;
84
+ }
85
+ type ContractOperations = {
86
+ [K in keyof ContractsStore]: ContractsStore[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => R : never;
87
+ };
88
+ export declare const contractOperationsOver: (context: StoreContext) => ContractOperations;
89
+ export declare const contractsStoreOver: (context: StoreContext) => ContractsStore;
90
+ export {};
@@ -0,0 +1,182 @@
1
+ import { CONTRACT_KINDS, CONTRACT_STATUSES, contractLine, intervalOf, } from "../../domain/business.js";
2
+ import { FINANCE_REVIEWS } from "../../domain/finance.js";
3
+ import { currencyOf, formatDecimal, minorUnits, scaleOf } from "../../domain/money.js";
4
+ import { proposedBySql } from "./actors.js";
5
+ import { projectId } from "./memories.js";
6
+ import { requiredThing } from "./notes.js";
7
+ import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text } from "./reviewed.js";
8
+ import { write } from "./transaction.js";
9
+ const CONTRACTS = "SELECT k.*, b.name AS author_name, b.kind AS author_kind FROM contracts k " +
10
+ "LEFT JOIN bots b ON k.author_type = 'bot' AND b.id = k.author_id";
11
+ const DAY_MS = 86_400_000;
12
+ const deadlineOf = (expiration, days) => expiration === null || days === null
13
+ ? null
14
+ : new Date(Date.parse(`${expiration}T00:00:00Z`) - days * DAY_MS).toISOString().slice(0, 10);
15
+ /** The columns a contract's fields set, checked; a field left out keeps `base`'s value. */
16
+ const columnsOf = (fields, base) => {
17
+ const kept = (given, column, read) => given === undefined ? (base[column] ?? null) : read(given);
18
+ const name = kept(fields.name, "name", (value) => text(value, "a contract's name", 200));
19
+ if (name == null)
20
+ refuse("a contract needs a name", "contract.field");
21
+ const renewal = fields.renewal !== undefined
22
+ ? intervalOf(fields.renewal, "contract.field")
23
+ : base.renewal_count == null
24
+ ? null
25
+ : { count: Number(base.renewal_count), unit: base.renewal_unit };
26
+ const noticeDays = kept(fields.noticeDays, "notice_days", (value) => {
27
+ if (!Number.isSafeInteger(value) || value < 0 || value > 3650)
28
+ refuse("a contract's notice is 0–3650 days", "contract.field");
29
+ return value;
30
+ });
31
+ const dates = {
32
+ signed_date: kept(fields.signedDate, "signed_date", (value) => isoDate(value, "a contract's signing date")),
33
+ effective_date: kept(fields.effectiveDate, "effective_date", (value) => isoDate(value, "a contract's start date")),
34
+ expiration_date: kept(fields.expirationDate, "expiration_date", (value) => isoDate(value, "a contract's end date")),
35
+ };
36
+ if (dates.effective_date != null &&
37
+ dates.expiration_date != null &&
38
+ String(dates.effective_date) > String(dates.expiration_date))
39
+ refuse("a contract ends on or after the day it starts", "contract.field");
40
+ const valued = fields.value !== undefined || fields.currency !== undefined;
41
+ if (valued && (fields.value === undefined) !== (fields.currency === undefined))
42
+ refuse("a contract's value and currency come together", "contract.field");
43
+ const currency = valued ? currencyOf(fields.currency) : (base.currency ?? null);
44
+ const value = valued
45
+ ? minorUnits(fields.value, currency, "a contract's value")
46
+ : (base.value ?? null);
47
+ return {
48
+ name: name,
49
+ number: kept(fields.number, "number", (value) => text(value, "a contract's number", 80)),
50
+ kind: kept(fields.kind, "kind", (value) => oneOf(value, CONTRACT_KINDS, "a contract's kind")),
51
+ status: kept(fields.status, "status", (value) => oneOf(value, CONTRACT_STATUSES, "a contract's status")),
52
+ ...dates,
53
+ auto_renew: kept(fields.autoRenew, "auto_renew", (value) => {
54
+ if (typeof value !== "boolean")
55
+ refuse("a contract's renewal is on or off", "contract.field");
56
+ return value ? 1 : 0;
57
+ }),
58
+ renewal_count: renewal?.count ?? null,
59
+ renewal_unit: renewal?.unit ?? null,
60
+ notice_days: noticeDays,
61
+ terms: kept(fields.terms, "terms", (value) => text(value, "a contract's terms", 20_000)),
62
+ value,
63
+ currency,
64
+ };
65
+ };
66
+ export const contractOperationsOver = (context) => {
67
+ const { database, now } = context;
68
+ const { reviewedOf, written, keepEvidence, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
69
+ const contractOf = (row) => {
70
+ const currency = row.currency == null ? null : String(row.currency);
71
+ const value = row.value == null || currency === null ? null : Number(row.value);
72
+ const expirationDate = row.expiration_date == null ? null : String(row.expiration_date);
73
+ const noticeDays = row.notice_days == null ? null : Number(row.notice_days);
74
+ const fields = {
75
+ id: Number(row.id),
76
+ name: String(row.name),
77
+ number: row.number == null ? null : String(row.number),
78
+ value,
79
+ currency,
80
+ status: row.status,
81
+ review: row.review,
82
+ };
83
+ return {
84
+ id: String(row.id),
85
+ ref: `contract:${row.id}`,
86
+ title: `Contract ${contractLine(fields)}`,
87
+ name: fields.name,
88
+ number: fields.number,
89
+ kind: row.kind,
90
+ status: fields.status,
91
+ signedDate: row.signed_date == null ? null : String(row.signed_date),
92
+ effectiveDate: row.effective_date == null ? null : String(row.effective_date),
93
+ expirationDate,
94
+ autoRenew: row.auto_renew === 1,
95
+ renewal: row.renewal_count == null ? null : { count: Number(row.renewal_count), unit: row.renewal_unit },
96
+ noticeDays,
97
+ noticeDeadline: deadlineOf(expirationDate, noticeDays),
98
+ terms: row.terms == null ? null : String(row.terms),
99
+ value: value === null || currency === null ? null : formatDecimal(value, scaleOf(currency)),
100
+ currency,
101
+ deal: row.deal_id == null ? null : `deal:${row.deal_id}`,
102
+ ...reviewedOf(row, "contract"),
103
+ };
104
+ };
105
+ const rowOf = (reference) => {
106
+ const thing = requiredThing(database, reference.includes(":") ? reference : `contract:${reference}`, "the contract");
107
+ if (thing.type !== "contract")
108
+ return refuse(`${reference} is not a contract`, "contract.ref");
109
+ return database.prepare(`${CONTRACTS} WHERE k.id = ?`).get(thing.id);
110
+ };
111
+ const decide = (reference, by, reason, confirm) => {
112
+ const row = rowOf(reference);
113
+ decideRow("contract", row, { by, reason, confirm });
114
+ return contractOf(rowOf(`contract:${row.id}`));
115
+ };
116
+ return {
117
+ add: (input) => {
118
+ const columns = columnsOf({ ...input, status: input.status ?? "active", autoRenew: input.autoRenew ?? false }, {});
119
+ const id = write(database, () => {
120
+ const deal = linkedId(input.deal, "deal", "contract.ref");
121
+ const by = written(input);
122
+ // Without a value a contract feeds no total, so an agent's needs no decision.
123
+ const direct = !by.owner && columns.value === null;
124
+ const at = now();
125
+ const made = Number(database
126
+ .prepare("INSERT INTO contracts (name, number, kind, status, signed_date, effective_date, expiration_date, auto_renew, " +
127
+ "renewal_count, renewal_unit, notice_days, terms, value, currency, project_id, deal_id, review, author_type, " +
128
+ "author_id, model, confirmed_by_type, confirmed_by_id, source, metadata, created_at, updated_at) " +
129
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
130
+ .get(columns.name, columns.number, columns.kind, columns.status, columns.signed_date, columns.effective_date, columns.expiration_date, columns.auto_renew, columns.renewal_count, columns.renewal_unit, columns.notice_days, columns.terms, columns.value, columns.currency, by.project, deal, direct ? "confirmed" : by.review, by.actor.type, by.actor.id, by.model, by.confirmedType, by.confirmedId, by.source, by.metadata, at, at)?.id);
131
+ keepEvidence("contract", made, by);
132
+ return made;
133
+ });
134
+ return contractOf(rowOf(`contract:${id}`));
135
+ },
136
+ get: (reference) => contractOf(rowOf(reference)),
137
+ list: (filter = {}) => {
138
+ const project = filter.project === undefined ? null : projectId(database, filter.project);
139
+ const status = filter.status === undefined ? null : oneOf(filter.status, CONTRACT_STATUSES, "a status");
140
+ const kind = filter.kind === undefined ? null : oneOf(filter.kind, CONTRACT_KINDS, "a kind");
141
+ const review = filter.review === undefined ? null : oneOf(filter.review, FINANCE_REVIEWS, "a review");
142
+ const expires = isoDate(filter.expiresBy, "the last expiration day");
143
+ const by = proposedBySql("k.author_type", "k.author_id", filter.proposedBy);
144
+ return database
145
+ .prepare(`${CONTRACTS} WHERE k.deleted_at IS NULL AND (? IS NULL OR k.status = ?) AND (? IS NULL OR k.kind = ?) ` +
146
+ "AND (? IS NULL OR k.review = ?) AND (? IS NULL OR k.project_id = ?) " +
147
+ `AND (? IS NULL OR k.expiration_date <= ?) AND ${by.sql} ORDER BY k.created_at DESC, k.id DESC LIMIT ?`)
148
+ .all(status, status, kind, kind, review, review, project, project, expires, expires, ...by.params, limitOf(filter.limit))
149
+ .map((row) => contractOf(row));
150
+ },
151
+ update: (reference, { by, ...fields }) => {
152
+ const row = rowOf(reference);
153
+ const ref = `contract:${row.id}`;
154
+ if (row.review === "rejected" || row.deleted_at != null)
155
+ refuse(`${ref} is ${row.deleted_at != null ? "deleted" : "rejected"}`, "contract.ref");
156
+ mayChangeParts(row, by, `only the owner changes ${ref}; a bot changes only a contract it proposed that is still proposed`);
157
+ const columns = columnsOf(fields, row);
158
+ write(database, () => {
159
+ const deal = fields.deal === undefined ? row.deal_id : linkedId(fields.deal, "deal", "contract.ref");
160
+ database
161
+ .prepare("UPDATE contracts SET name = ?, number = ?, kind = ?, status = ?, signed_date = ?, effective_date = ?, " +
162
+ "expiration_date = ?, auto_renew = ?, renewal_count = ?, renewal_unit = ?, notice_days = ?, terms = ?, " +
163
+ "value = ?, currency = ?, deal_id = ?, updated_at = ? WHERE id = ?")
164
+ .run(columns.name, columns.number, columns.kind, columns.status, columns.signed_date, columns.effective_date, columns.expiration_date, columns.auto_renew, columns.renewal_count, columns.renewal_unit, columns.notice_days, columns.terms, columns.value, columns.currency, deal, now(), Number(row.id));
165
+ });
166
+ return contractOf(rowOf(ref));
167
+ },
168
+ confirm: (reference, by, reason) => decide(reference, by, reason, true),
169
+ reject: (reference, by, reason) => decide(reference, by, reason, false),
170
+ };
171
+ };
172
+ export const contractsStoreOver = (context) => {
173
+ const operations = contractOperationsOver(context);
174
+ return {
175
+ add: async (input) => operations.add(input),
176
+ get: async (reference) => operations.get(reference),
177
+ list: async (filter) => operations.list(filter),
178
+ update: async (reference, input) => operations.update(reference, input),
179
+ confirm: async (reference, by, reason) => operations.confirm(reference, by, reason),
180
+ reject: async (reference, by, reason) => operations.reject(reference, by, reason),
181
+ };
182
+ };
@@ -1,6 +1,9 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { eventOf } from "./events.js";
3
+ import { COUNTERPART_ROLE, linkKind } from "./link-kinds.js";
3
4
  const DAY = 86_400_000;
5
+ const COUNTERPART_LINK = "EXISTS (SELECT 1 FROM links l WHERE l.from_type = 'event' AND l.from_id = e.id AND l.to_type = 'person' " +
6
+ `AND l.to_id = ? AND l.kind = ${linkKind("related-to")} AND l.role = '${COUNTERPART_ROLE}')`;
4
7
  const accountsOf = (filter) => {
5
8
  if (filter.accountIds !== undefined && filter.accountId !== undefined)
6
9
  throw new CliError("validation_error", "an event filter takes accountId or accountIds, not both");
@@ -73,9 +76,10 @@ export const listEvents = (database, filter) => {
73
76
  if (filter.notEventTypes?.length)
74
77
  clauses.push(`NOT ${ofKind(filter.notEventTypes)}`);
75
78
  if (filter.personId !== undefined) {
76
- clauses.push(entries("EXISTS (SELECT 1 FROM calendar_entry_participants p JOIN identity_links il ON il.identity_id = p.identity_id " +
77
- "WHERE p.entry_id = ce.id AND il.person_id = ?)"));
78
- params.push(filter.personId);
79
+ // A phone call's other side is a number, which a participant (an address) cannot hold: the import links the person.
80
+ clauses.push(`(${entries("EXISTS (SELECT 1 FROM calendar_entry_participants p JOIN identity_links il ON il.identity_id = p.identity_id " +
81
+ "WHERE p.entry_id = ce.id AND il.person_id = ?)")} OR ${COUNTERPART_LINK})`);
82
+ params.push(filter.personId, filter.personId);
79
83
  }
80
84
  const account = (alias) => (accounts === undefined ? "" : ` AND ${inAccounts(`${alias}.account_id`)}`);
81
85
  if (filter.changedSince !== undefined) {
@@ -1,4 +1,5 @@
1
1
  import { dropOrphanPeople, unreferenced } from "./accounts.js";
2
+ import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
2
3
  import { dropUnusedVectors } from "./vector-index.js";
3
4
  const distinctIds = (rows) => [...new Set(rows.map((row) => Number(row.id)))];
4
5
  /**
@@ -46,6 +47,7 @@ export const forgetCalendarRows = (database, { calendarId, accountId, cursorKey,
46
47
  database
47
48
  .prepare("UPDATE meetings SET event_id = NULL, updated_at = ? WHERE event_id IN (SELECT value FROM json_each(?))")
48
49
  .run(now, gone(goneEvents));
50
+ forgetEvidenceTo(database, "event", { sql: "SELECT value FROM json_each(?)", params: [gone(goneEvents)] }, now);
49
51
  dropAround("event", goneEvents);
50
52
  database.prepare("DELETE FROM events WHERE id IN (SELECT value FROM json_each(?))").run(gone(goneEvents));
51
53
  for (const table of ["meeting_series", "events"])
@@ -63,6 +65,7 @@ export const forgetCalendarRows = (database, { calendarId, accountId, cursorKey,
63
65
  database.prepare("DELETE FROM sync_cursors WHERE account_id = ? AND key = ?").run(accountId, cursorKey);
64
66
  database.prepare("DELETE FROM calendars WHERE id = ?").run(calendarId);
65
67
  dropOrphanPeople(database, unseenBefore);
68
+ forgetDanglingEvidence(database, now);
66
69
  dropUnusedVectors(database, hashes);
67
70
  return { entries: entryIds.length, events: goneEvents.length };
68
71
  };