@wirecat/cli-core 0.606.0 → 0.607.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 +186 -1
  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 +61 -2
  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
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { walkQuery } from "@wirecat/cli-base/query";
3
3
  import { parseLocator } from "../../domain/locator.js";
4
+ import { isBusinessType } from "../../domain/record-types.js";
4
5
  import { formatReference, parseReference } from "../../domain/references.js";
5
6
  import { checkEnds, isSymmetric, notOverriddenSql } from "../../domain/relations.js";
6
7
  import { normalizeTag } from "../../domain/tags.js";
@@ -11,6 +12,8 @@ import { assertMayDecide } from "../decisions.js";
11
12
  import { fold } from "../normalize.js";
12
13
  import { ulid } from "../ulid.js";
13
14
  import { ownerPerson } from "./actors.js";
15
+ import { forgetEvidenceToRow } from "./evidence-signature.js";
16
+ import { LABELLED } from "./labelled.js";
14
17
  import { linkKind, RELATION_KINDS } from "./link-kinds.js";
15
18
  import { meetingProjectsStoreOver } from "./meeting-projects.js";
16
19
  import { holdingText } from "./note-index.js";
@@ -19,6 +22,7 @@ import { organizationOf, organizationsStoreOver } from "./organizations.js";
19
22
  import { queryFilter } from "./query-filter.js";
20
23
  import { relationOf as relationAt, relationProposalsOver, } from "./relation-proposals.js";
21
24
  import { checkStoredRole, relationReadsOver } from "./relation-reads.js";
25
+ import { sourceReviewStoreOver } from "./source-review.js";
22
26
  import { addTags as addThingTags, canonicalTagNamed, createTag, labelsOf, liveTagging, removeTags as removeThingTags, setMainTopic, } from "./tags.js";
23
27
  import { INBOX_KEY_LENGTH, TASK_KEY_PREFIXES } from "./task-keys.js";
24
28
  import { inboxKey, taskAccountOf, taskIdOf, taskRowOf } from "./tasks.js";
@@ -59,17 +63,6 @@ const oneOf = (value, allowed, what) => {
59
63
  /** What a relationship may connect; a deal or a lead only as the end its people hang from. */
60
64
  const RELATED = ["person", "organization", "project", "task"];
61
65
  const DEALS = ["deal", "lead"];
62
- /** What a label without an account may sit on; a chat, contact or message is the messenger's tag. */
63
- const LABELLED = {
64
- note: "note",
65
- document: "document",
66
- person: "person",
67
- organization: "organization",
68
- project: "project",
69
- task: "task",
70
- meeting: "meeting",
71
- account: "folder",
72
- };
73
66
  export const knowledgeStoreOver = (context) => {
74
67
  const { database, now } = context;
75
68
  const account = (key) => {
@@ -153,12 +146,7 @@ export const knowledgeStoreOver = (context) => {
153
146
  parsed.type === "bot" ||
154
147
  parsed.type === "event" ||
155
148
  parsed.type === "meeting" ||
156
- parsed.type === "invoice" ||
157
- parsed.type === "payment" ||
158
- parsed.type === "order" ||
159
- parsed.type === "deal" ||
160
- parsed.type === "lead" ||
161
- parsed.type === "pipeline")
149
+ isBusinessType(parsed.type))
162
150
  return undefined;
163
151
  return { type: parsed.type, id: parsed.id };
164
152
  };
@@ -365,7 +353,10 @@ export const knowledgeStoreOver = (context) => {
365
353
  },
366
354
  removeAnnotation: async (key, id) => {
367
355
  annotation(key, id);
368
- database.prepare("DELETE FROM notes WHERE id=?").run(Number(id));
356
+ write(database, () => {
357
+ forgetEvidenceToRow(database, { type: "note", id: Number(id) }, now());
358
+ database.prepare("DELETE FROM notes WHERE id=?").run(Number(id));
359
+ });
369
360
  return { id, removed: true };
370
361
  },
371
362
  tags: async (key, target, tag) => {
@@ -454,59 +445,7 @@ export const knowledgeStoreOver = (context) => {
454
445
  .get(oneOf(kind, ORGANIZATION_KINDS, "an organization's kind"), textOf(name, 200), oneOf(scope, SCOPES, "a scope"), at, at);
455
446
  return organizationOf(row);
456
447
  },
457
- addProject: async ({ name, key, type = "other", organization, scope = "personal", description }) => write(database, () => {
458
- const title = textOf(name, 200);
459
- const organizationId = organization === undefined
460
- ? null
461
- : (() => {
462
- const thing = thingOf(database, organization);
463
- if (thing?.type !== "organization")
464
- throw new CliError("not_found", `no organization ${organization}`);
465
- return thing.id;
466
- })();
467
- const wanted = key === undefined ? projectKey(title) : key.trim().toUpperCase();
468
- if (!/^[A-Z][A-Z0-9]{2,3}$/.test(wanted))
469
- throw new CliError("validation_error", "a new project key is 3–4 letters and digits, starting with a letter");
470
- const aliasName = (() => {
471
- try {
472
- return normalizeVocabularyName(title);
473
- }
474
- catch {
475
- return null;
476
- }
477
- })();
478
- const alias = database
479
- .prepare("SELECT DISTINCT p.id,p.name FROM aliases a JOIN projects p ON p.id=a.aliasable_id " +
480
- "WHERE a.aliasable_type='project' AND a.account_id IS NULL AND p.account_id IS NULL AND p.deleted_at IS NULL " +
481
- "AND a.name_folded IN (?,?) LIMIT 2")
482
- .all(aliasName, normalizeVocabularyName(wanted));
483
- if (alias.length)
484
- throw new CliError("configuration_error", "the project name or key already aliases an existing project", {
485
- reason: "vocabulary.alias-conflict",
486
- candidates: alias.map((row) => ({ kind: "project", id: String(row.id), name: String(row.name) })),
487
- });
488
- if (key !== undefined && TYPED_KEY_PREFIXES.has(wanted))
489
- throw new CliError("validation_error", `the project key ${wanted} is kept for the keys of tasks found in messages`);
490
- let chosen = wanted;
491
- for (let n = 2; TYPED_KEY_PREFIXES.has(chosen) ||
492
- database.prepare("SELECT 1 FROM projects WHERE key = ?").get(chosen) ||
493
- database
494
- .prepare("SELECT 1 FROM aliases a JOIN projects p ON p.id=a.aliasable_id WHERE a.aliasable_type='project' AND a.account_id IS NULL AND p.account_id IS NULL AND p.deleted_at IS NULL AND a.name_folded=? LIMIT 1")
495
- .get(normalizeVocabularyName(chosen)); n++) {
496
- if (key !== undefined)
497
- throw new CliError("validation_error", `the project key ${wanted} is taken`);
498
- const suffix = String(n);
499
- if (suffix.length > 3)
500
- throw new CliError("validation_error", "no short project key is available; choose an explicit key");
501
- chosen = `${wanted.slice(0, 4 - suffix.length)}${suffix}`;
502
- }
503
- const at = now();
504
- const row = database
505
- .prepare("INSERT INTO projects (key, name, name_folded, description, type, organization_id, scope, tasks_count, status, created_at, updated_at) " +
506
- "VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'active', ?, ?) RETURNING *")
507
- .get(chosen, title, fold(title), description === undefined ? null : textOf(description, 2000), oneOf(type, PROJECT_TYPES, "a project's type"), organizationId, oneOf(scope, SCOPES, "a scope"), at, at);
508
- return projectOf(row);
509
- }),
448
+ addProject: async (input) => write(database, () => projectOf(insertProject(context, input))),
510
449
  projects: async (query) => {
511
450
  const asksKind = query !== undefined && walkQuery(query.root).some((node) => node.field === "kind");
512
451
  const where = query &&
@@ -571,6 +510,7 @@ export const knowledgeStoreOver = (context) => {
571
510
  return { proposal, relation: link && relationOf(link) };
572
511
  },
573
512
  decideLinkProposal: async (id, decision) => proposals.decideProposal(id, decision),
513
+ ...sourceReviewStoreOver(context),
574
514
  decideSuggestedLink: async (id, decision) => proposals.decideLink(id, decision),
575
515
  relations: async (key, reference) => {
576
516
  checked(key);
@@ -696,6 +636,60 @@ export const knowledgeStoreOver = (context) => {
696
636
  },
697
637
  };
698
638
  };
639
+ /** A new project row, its key made from the name when none is given; inside the caller's write. */
640
+ export const insertProject = ({ database, now }, { name, key, type = "other", organization, scope = "personal", description }) => {
641
+ const title = textOf(name, 200);
642
+ const organizationId = organization === undefined
643
+ ? null
644
+ : (() => {
645
+ const thing = thingOf(database, organization);
646
+ if (thing?.type !== "organization")
647
+ throw new CliError("not_found", `no organization ${organization}`);
648
+ return thing.id;
649
+ })();
650
+ const wanted = key === undefined ? projectKey(title) : key.trim().toUpperCase();
651
+ if (!/^[A-Z][A-Z0-9]{2,3}$/.test(wanted))
652
+ throw new CliError("validation_error", "a new project key is 3–4 letters and digits, starting with a letter");
653
+ const aliasName = (() => {
654
+ try {
655
+ return normalizeVocabularyName(title);
656
+ }
657
+ catch {
658
+ return null;
659
+ }
660
+ })();
661
+ const alias = database
662
+ .prepare("SELECT DISTINCT p.id,p.name FROM aliases a JOIN projects p ON p.id=a.aliasable_id " +
663
+ "WHERE a.aliasable_type='project' AND a.account_id IS NULL AND p.account_id IS NULL AND p.deleted_at IS NULL " +
664
+ "AND a.name_folded IN (?,?) LIMIT 2")
665
+ .all(aliasName, normalizeVocabularyName(wanted));
666
+ if (alias.length)
667
+ throw new CliError("configuration_error", "the project name or key already aliases an existing project", {
668
+ reason: "vocabulary.alias-conflict",
669
+ candidates: alias.map((row) => ({ kind: "project", id: String(row.id), name: String(row.name) })),
670
+ });
671
+ if (key !== undefined && TYPED_KEY_PREFIXES.has(wanted))
672
+ throw new CliError("validation_error", `the project key ${wanted} is kept for the keys of tasks found in messages`);
673
+ let chosen = wanted;
674
+ for (let n = 2; TYPED_KEY_PREFIXES.has(chosen) ||
675
+ database.prepare("SELECT 1 FROM projects WHERE key = ?").get(chosen) ||
676
+ database
677
+ .prepare("SELECT 1 FROM aliases a JOIN projects p ON p.id=a.aliasable_id WHERE a.aliasable_type='project' AND a.account_id IS NULL AND p.account_id IS NULL AND p.deleted_at IS NULL AND a.name_folded=? LIMIT 1")
678
+ .get(normalizeVocabularyName(chosen)); n++) {
679
+ if (key !== undefined)
680
+ throw new CliError("validation_error", `the project key ${wanted} is taken`);
681
+ const suffix = String(n);
682
+ if (suffix.length > 3)
683
+ throw new CliError("validation_error", "no short project key is available; choose an explicit key");
684
+ chosen = `${wanted.slice(0, 4 - suffix.length)}${suffix}`;
685
+ }
686
+ const at = now();
687
+ const row = database
688
+ .prepare("INSERT INTO projects (key, name, name_folded, description, type, organization_id, scope, tasks_count, status, created_at, updated_at) " +
689
+ "VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'active', ?, ?) RETURNING *")
690
+ .get(chosen, title, fold(title), description === undefined ? null : textOf(description, 2000), oneOf(type, PROJECT_TYPES, "a project's type"), organizationId, oneOf(scope, SCOPES, "a scope"), at, at);
691
+ return row;
692
+ };
699
693
  /** Existing project keys stay stable; only new projects receive the short-key convention. */
700
694
  const projectKey = (name) => {
701
695
  const letters = name
@@ -0,0 +1,3 @@
1
+ export type LabelledType = "note" | "document" | "person" | "organization" | "project" | "task" | "meeting" | "folder";
2
+ /** What a label without an account may sit on; a chat, contact or message is the messenger's tag. */
3
+ export declare const LABELLED: Record<string, LabelledType>;
@@ -0,0 +1,11 @@
1
+ /** What a label without an account may sit on; a chat, contact or message is the messenger's tag. */
2
+ export const LABELLED = {
3
+ note: "note",
4
+ document: "document",
5
+ person: "person",
6
+ organization: "organization",
7
+ project: "project",
8
+ task: "task",
9
+ meeting: "meeting",
10
+ account: "folder",
11
+ };
@@ -11,3 +11,5 @@ export declare const LINK_SOURCES: readonly ["file", "owner", "suggested", "mess
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;
14
+ /** The `role` of the `related-to` link from a phone call's event to the person on the other end. */
15
+ export declare const COUNTERPART_ROLE = "counterpart";
@@ -27,3 +27,5 @@ export const LINK_SOURCES = [...LINK_ORIGINS, "calendar"];
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}'`;
30
+ /** The `role` of the `related-to` link from a phone call's event to the person on the other end. */
31
+ export const COUNTERPART_ROLE = "counterpart";
@@ -118,6 +118,8 @@ export const MANIFEST = [
118
118
  { name: "20261107162427_version-56-relationship-links", version: 56, minCompatible: 56, tables: V56_TABLES },
119
119
  { name: "20261107162448_version-56-relationship-links-history", version: 56, minCompatible: 56, tables: V56_TABLES },
120
120
  { name: "20261107163245_version-56-relationship-links-key", version: 56, minCompatible: 56, tables: V56_TABLES },
121
+ { name: "20261108010753_version-57-business", version: 57, minCompatible: 56 },
122
+ { name: "20261108010754_version-57-business-rules", version: 57, minCompatible: 56 },
121
123
  ];
122
124
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
123
125
  const migrations = [];
@@ -1,6 +1,8 @@
1
1
  import { MEMORY_KINDS, MEMORY_SCOPES, type MEMORY_STATUSES } from "../../domain/knowledge.js";
2
2
  import { type Decider } from "../decisions.js";
3
+ import type { SourceReviewMarker } from "../source-review.js";
3
4
  import { type Actor, type ProposedByFilter } from "./actors.js";
5
+ import { type EvidenceInput } from "./evidence-signature.js";
4
6
  import { type EvidenceSource } from "./evidence-sources.js";
5
7
  import { type NoteIndexState } from "./note-index.js";
6
8
  import type { StoreContext } from "./open.js";
@@ -38,6 +40,8 @@ export interface Memory {
38
40
  supersedes: string | null;
39
41
  /** The references it rests on: `links` of kind `evidence`. */
40
42
  evidence: string[];
43
+ /** The open review of its sources (`memory_source_review`), when one waits for the owner. */
44
+ sourceReview: SourceReviewMarker | null;
41
45
  lastVerifiedAt: string | null;
42
46
  createdAt: string;
43
47
  updatedAt: string;
@@ -47,8 +51,8 @@ export interface MemoryInput {
47
51
  body: string;
48
52
  /** Required, with no default: a memory read for the wrong purpose leaks, so its writer says which. */
49
53
  scope: Memory["scope"];
50
- /** At least one reference the memory rests on. */
51
- evidence: string[];
54
+ /** At least one reference the memory rests on, each with the words of it the memory rests on if given. */
55
+ evidence: EvidenceInput[];
52
56
  author: Author;
53
57
  subject?: string;
54
58
  project?: string;
@@ -75,11 +79,15 @@ export interface MemoriesStore {
75
79
  }): Promise<Memory>;
76
80
  /** The owner, or an agent for the owner, stands behind it; its evidence was checked now. */
77
81
  confirm(reference: string, by: Decider): Promise<Memory>;
78
- /** Its evidence no longer holds; for an agent's memory this is how it is turned down, so `by` must be allowed. */
82
+ /**
83
+ * Its evidence no longer holds; for an agent's memory this is how it is turned down, so `by` must be allowed. A
84
+ * confirmed memory is the owner's to retire: an agent challenges it instead (`knowledge.challenge`).
85
+ */
79
86
  markStale(reference: string, by: Decider): Promise<Memory>;
80
87
  /**
81
- * Erases the memory: its row, its text in the search and meaning indexes, and every link from or to it. A memory
82
- * that replaced it no longer names it. A backup made before keeps it.
88
+ * Erases the memory: its row, its text in the search and meaning indexes, and every link from or to it, except the
89
+ * evidence of memories and facts that cited it, which stays with no pointer and shows as a missing source. A memory
90
+ * that replaced it no longer names it. `links` counts the links erased. A backup made before keeps it.
83
91
  */
84
92
  remove(reference: string, by: Decider): Promise<{
85
93
  ref: string;
@@ -102,11 +110,14 @@ export declare const authorActor: (context: StoreContext, author: Author) => {
102
110
  model: string | null;
103
111
  };
104
112
  export declare const authorOf: (row: Row) => Memory["author"];
105
- /** Writes `evidence` links from a row to each reference, refusing one the store does not hold. */
113
+ /**
114
+ * Writes `evidence` links from a row to each reference, refusing one the store does not hold. Each link keeps the
115
+ * source's signature and the quote it was given, so a later check sees whether the source still says it.
116
+ */
106
117
  export declare const linkEvidence: (context: StoreContext, from: {
107
118
  type: string;
108
119
  id: number;
109
- }, references: string[], author: "owner" | "agent") => void;
120
+ }, references: readonly EvidenceInput[], author: "owner" | "agent") => void;
110
121
  export declare const evidenceOf: (context: StoreContext, from: {
111
122
  type: string;
112
123
  id: number;
@@ -131,11 +142,14 @@ type Numbered = "memories" | "facts";
131
142
  export declare const nextId: (database: StoreContext["database"], table: Numbered) => number;
132
143
  /** Before a delete: remembers the highest id handed out, which the delete may be about to free. */
133
144
  export declare const keepHighestId: (database: StoreContext["database"], table: Numbered, at: number) => void;
134
- /** Counts every link from or to a row and drops the ones its delete trigger does not: those pointing at it. */
145
+ /**
146
+ * Counts every link from or to a row and drops the ones its delete trigger does not: those pointing at it. Evidence
147
+ * that cites it stays, with no pointer, so a memory or fact that rested on it still shows a source that went.
148
+ */
135
149
  export declare const dropLinksOf: (database: StoreContext["database"], thing: {
136
150
  type: string;
137
151
  id: number;
138
- }) => number;
152
+ }, at: number) => number;
139
153
  /**
140
154
  * Runs a delete so the text does not linger in the file: freed pages are zeroed, the words indexes merged so no
141
155
  * segment still holds the erased words, and the write-ahead log emptied when no reader holds it.
@@ -1,12 +1,14 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { MEMORY_KINDS, MEMORY_SCOPES } from "../../domain/knowledge.js";
3
- import { assertMayDecide, assertMayWithdraw } from "../decisions.js";
3
+ import { assertMayDecide, assertMayWithdraw, deciderAuthor } from "../decisions.js";
4
4
  import { normalize } from "../normalize.js";
5
5
  import { botNamed, ownerPerson, proposedBySql, proposerOf } from "./actors.js";
6
+ import { assertQuoted, evidenceInputOf, evidenceMetadata, evidenceSignature, forgetEvidenceToRow, } from "./evidence-signature.js";
6
7
  import { evidenceSourcesOf } from "./evidence-sources.js";
7
8
  import { linkKind } from "./link-kinds.js";
8
9
  import { CORPORA, corpusIndexState, drainCorpus } from "./note-index.js";
9
10
  import { requiredThing } from "./notes.js";
11
+ import { closeSourceReviews, eraseSourceReviews, sourceReviewOf } from "./source-review-marks.js";
10
12
  import { stemmerCache } from "./stems.js";
11
13
  import { referenceOfThing, storedThing } from "./things.js";
12
14
  import { write } from "./transaction.js";
@@ -31,14 +33,19 @@ export const authorOf = (row) => ({
31
33
  name: row.author_name == null ? null : String(row.author_name),
32
34
  kind: row.author_type !== "bot" ? null : row.author_kind === "rule" || row.author_name === "rule" ? "rule" : "agent",
33
35
  });
34
- /** Writes `evidence` links from a row to each reference, refusing one the store does not hold. */
36
+ /**
37
+ * Writes `evidence` links from a row to each reference, refusing one the store does not hold. Each link keeps the
38
+ * source's signature and the quote it was given, so a later check sees whether the source still says it.
39
+ */
35
40
  export const linkEvidence = (context, from, references, author) => {
36
41
  const at = context.now();
37
- const insert = context.database.prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, source, confirmed, created_at, author, updated_at) " +
38
- `VALUES (?, ?, ?, ?, ${linkKind("evidence")}, ?, 1, ?, ?, ?)`);
39
- for (const reference of references) {
40
- const thing = requiredThing(context.database, reference, "the evidence");
41
- insert.run(from.type, from.id, thing.type, thing.id, author === "owner" ? "owner" : "suggested", at, author, at);
42
+ const insert = context.database.prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, source, metadata, confirmed, created_at, author, updated_at) " +
43
+ `VALUES (?, ?, ?, ?, ${linkKind("evidence")}, ?, ?, 1, ?, ?, ?)`);
44
+ for (const { ref, quote } of references.map(evidenceInputOf)) {
45
+ const thing = requiredThing(context.database, ref, "the evidence");
46
+ assertQuoted(context.database, thing, ref, quote);
47
+ const metadata = evidenceMetadata(evidenceSignature(context.database, thing), at, quote);
48
+ insert.run(from.type, from.id, thing.type, thing.id, author === "owner" ? "owner" : "suggested", JSON.stringify(metadata), at, author, at);
42
49
  }
43
50
  };
44
51
  export const evidenceOf = (context, from) => context.database
@@ -97,13 +104,17 @@ export const keepHighestId = (database, table, at) => {
97
104
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
98
105
  .run(highestKey(table), String(highest), at);
99
106
  };
100
- /** Counts every link from or to a row and drops the ones its delete trigger does not: those pointing at it. */
101
- export const dropLinksOf = (database, thing) => {
107
+ /**
108
+ * Counts every link from or to a row and drops the ones its delete trigger does not: those pointing at it. Evidence
109
+ * that cites it stays, with no pointer, so a memory or fact that rested on it still shows a source that went.
110
+ */
111
+ export const dropLinksOf = (database, thing, at) => {
102
112
  const count = Number(database
103
113
  .prepare("SELECT count(*) AS n FROM links WHERE (from_type = ? AND from_id = ?) OR (to_type = ? AND to_id = ?)")
104
114
  .get(thing.type, thing.id, thing.type, thing.id)?.n);
115
+ const kept = forgetEvidenceToRow(database, storedThing(thing.type, thing.id), at).length;
105
116
  database.prepare("DELETE FROM links WHERE to_type = ? AND to_id = ?").run(thing.type, thing.id);
106
- return count;
117
+ return count - kept;
107
118
  };
108
119
  /**
109
120
  * Runs a delete so the text does not linger in the file: freed pages are zeroed, the words indexes merged so no
@@ -142,6 +153,7 @@ export const memoriesStoreOver = (context) => {
142
153
  scope: row.scope,
143
154
  supersedes: row.supersedes_id == null ? null : `memory:${row.supersedes_id}`,
144
155
  evidence: evidenceOf(context, { type: "memory", id: Number(row.id) }),
156
+ sourceReview: sourceReviewOf(database, { type: "memory", id: Number(row.id) }),
145
157
  lastVerifiedAt: row.last_verified_at == null ? null : iso(row.last_verified_at),
146
158
  createdAt: iso(row.created_at),
147
159
  updatedAt: iso(row.updated_at),
@@ -183,6 +195,11 @@ export const memoriesStoreOver = (context) => {
183
195
  .run(...(verified ? [status, at, at, Number(row.id)] : [status, at, Number(row.id)]));
184
196
  return memoryOf(rowOf(reference));
185
197
  };
198
+ const closing = (by, why) => ({
199
+ actor: authorActor(context, deciderAuthor(by)).actor,
200
+ at: now(),
201
+ why,
202
+ });
186
203
  /** `add` inside the caller's write, so a decision that adds a memory rolls back with it. */
187
204
  const addNow = (input) => {
188
205
  const kind = oneOf(input.kind, MEMORY_KINDS, "a memory's kind");
@@ -217,8 +234,10 @@ export const memoriesStoreOver = (context) => {
217
234
  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
218
235
  .get(nextId(database, "memories"), kind, body, subject?.type ?? null, subject?.id ?? null, actor.type, actor.id, model, input.confidence ?? null, status, status === "confirmed" ? at : null, replaced ?? null, scope, project, at, at)?.id);
219
236
  linkEvidence(context, { type: "memory", id: made }, input.evidence, input.author === "owner" ? "owner" : "agent");
220
- if (replaced !== undefined && status === "confirmed")
237
+ if (replaced !== undefined && status === "confirmed") {
221
238
  database.prepare("UPDATE memories SET status = 'superseded', updated_at = ? WHERE id = ?").run(at, replaced);
239
+ closeSourceReviews(database, { type: "memory", id: replaced }, { actor, at, why: "superseded" });
240
+ }
222
241
  return made;
223
242
  });
224
243
  return memoryOf(rowOf(`memory:${id}`));
@@ -234,6 +253,7 @@ export const memoriesStoreOver = (context) => {
234
253
  database
235
254
  .prepare("UPDATE memories SET status = 'superseded', updated_at = ? WHERE id = ?")
236
255
  .run(now(), Number(replaced.id));
256
+ closeSourceReviews(database, { type: "memory", id: Number(replaced.id) }, closing(by, "superseded"));
237
257
  }
238
258
  return setStatus(reference, "confirmed", true);
239
259
  });
@@ -261,8 +281,15 @@ export const memoriesStoreOver = (context) => {
261
281
  }),
262
282
  confirm: async (reference, by) => confirmNow(reference, by),
263
283
  markStale: async (reference, by) => {
284
+ const row = rowOf(reference);
285
+ if (by !== "owner" && row.status === "confirmed")
286
+ throw new CliError("permission_error", `memory:${row.id} is confirmed; only the owner retires it. Challenge it with what contradicts it instead`, { reason: "proposal.owner-only" });
264
287
  decided(reference, by);
265
- return setStatus(reference, "stale", false);
288
+ return write(database, () => {
289
+ const memory = setStatus(reference, "stale", false);
290
+ closeSourceReviews(database, { type: "memory", id: Number(row.id) }, closing(by, "invalidated"));
291
+ return memoryOf(rowOf(memory.ref));
292
+ });
266
293
  },
267
294
  remove: async (reference, by) => {
268
295
  const row = rowOf(reference);
@@ -275,7 +302,8 @@ export const memoriesStoreOver = (context) => {
275
302
  const links = erase(database, () => {
276
303
  keepHighestId(database, "memories", now());
277
304
  database.prepare("UPDATE memories SET supersedes_id = NULL WHERE supersedes_id = ?").run(id);
278
- const count = dropLinksOf(database, { type: "memory", id });
305
+ eraseSourceReviews(database, { type: "memory", id });
306
+ const count = dropLinksOf(database, { type: "memory", id }, now());
279
307
  database.prepare("DELETE FROM memories WHERE id = ?").run(id);
280
308
  return count;
281
309
  });
@@ -3,6 +3,7 @@ import { NORMALIZER_VERSION, normalize } from "../normalize.js";
3
3
  import { findChatPk } from "./chats.js";
4
4
  import { applyCounterObservations } from "./counters.js";
5
5
  import { and, eq, isNull, sql } from "./drizzle/core.js";
6
+ import { forgetEvidenceToRow } from "./evidence-signature.js";
6
7
  import { folded } from "./folded.js";
7
8
  import { identityPk } from "./identities.js";
8
9
  import { attachments, chats, messageRevisions, messages, messageTranscripts } from "./schema.js";
@@ -264,6 +265,7 @@ export const tombstone = (context, pk) => {
264
265
  .prepare("UPDATE attachments SET extraction=NULL, extractor=NULL, extraction_error=NULL, content_sha256=NULL, extracted_at=NULL, updated_at=? WHERE attachable_type='message' AND attachable_id=?")
265
266
  .run(now(), pk);
266
267
  orm.delete(messageRevisions).where(eq(messageRevisions.messageId, pk)).run();
268
+ forgetEvidenceToRow(context.database, { type: "message", id: pk }, now(), { keepPointer: true });
267
269
  context.database
268
270
  .prepare("DELETE FROM poll_votes WHERE chat_id=? AND message_external_id=?")
269
271
  .run(row.chatId, row.externalId);