@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,32 +1,9 @@
1
- import { kept, proposerOfAuthor, pushed } from "./shared.js";
2
- const rowOf = (order) => ({
3
- id: order.ref,
4
- kind: "order",
5
- status: order.review,
6
- project: order.project,
7
- subject: order.ref,
8
- object: order.supplier?.ref ?? null,
9
- summary: order.title,
10
- proposedBy: proposerOfAuthor(order.author),
11
- reason: order.reason,
12
- evidence: [],
13
- score: null,
14
- signals: null,
15
- parts: null,
16
- createdAt: order.createdAt,
17
- });
1
+ import { reviewedKind, reviewedRow } from "./shared.js";
18
2
  /** An agent's order, by its own ref (`order:12`) as invoices are; only the owner decides it. */
19
- export const orderKind = (store) => ({
20
- kind: "order",
21
- prefix: "order",
22
- list: async (filter) => {
23
- const status = filter.status ?? "proposed";
24
- const orders = await store.orders.list({ ...pushed(filter), ...(status === "all" ? {} : { review: status }) });
25
- return kept(orders.map(rowOf), filter);
26
- },
27
- get: async (id) => rowOf(await store.orders.get(id)),
28
- decide: async (id, { confirm, by, reason }) => {
29
- const order = confirm ? await store.orders.confirm(id, by, reason) : await store.orders.reject(id, by, reason);
30
- return { id, kind: "order", status: confirm ? "confirmed" : "rejected", made: confirm ? [order.ref] : [] };
31
- },
3
+ export const orderKind = (store) => reviewedKind({
4
+ type: "order",
5
+ list: (options) => store.orders.list(options),
6
+ get: (id) => store.orders.get(id),
7
+ row: (order) => reviewedRow("order", order, order.supplier?.ref ?? null),
8
+ decide: async (id, confirm, { by, reason }) => (confirm ? await store.orders.confirm(id, by, reason) : await store.orders.reject(id, by, reason)).ref,
32
9
  });
@@ -1,5 +1,6 @@
1
+ import type { DecidedType } from "../../../domain/record-types.js";
1
2
  import type { Proposer } from "../../../store/decisions.js";
2
- import type { ProposalFilter, ProposalRow } from "../types.js";
3
+ import type { Decision, ProposalFilter, ProposalKind, ProposalRow } from "../types.js";
3
4
  /** A stored author as a proposer, with the kind read from its bot row. */
4
5
  export declare const proposerOfAuthor: (author: {
5
6
  type: "person" | "bot";
@@ -23,3 +24,28 @@ export declare const projectOf: (...refs: (string | null | undefined)[]) => stri
23
24
  export declare const actionStatus: (status: string) => ProposalRow["status"];
24
25
  /** The stored statuses a filter's status reads, so the store does the filtering when it can. */
25
26
  export declare const storedStatus: (filter: ProposalFilter) => "proposed" | "rejected" | undefined;
27
+ /** What a reviewed store entry shows in the inbox: its own ref is the proposal's id. */
28
+ export interface ReviewedEntry {
29
+ ref: string;
30
+ review: "proposed" | "confirmed" | "rejected";
31
+ project: string | null;
32
+ title: string;
33
+ author: Parameters<typeof proposerOfAuthor>[0];
34
+ reason: string | null;
35
+ createdAt: string;
36
+ }
37
+ export declare const reviewedRow: (kind: string, entry: ReviewedEntry, object: string | null) => ProposalRow;
38
+ /**
39
+ * A kind over a store whose rows carry `review`, routed by its own prefix as invoices are. Only the owner decides
40
+ * money: the store refuses an agent whatever the policy says.
41
+ */
42
+ export declare const reviewedKind: <T>(spec: {
43
+ /** A type the record registry marks reviewed: its kind and its ref prefix both. */
44
+ type: DecidedType;
45
+ list: (options: ReturnType<typeof pushed> & {
46
+ review?: "proposed" | "confirmed" | "rejected";
47
+ }) => Promise<T[]>;
48
+ get: (id: string) => Promise<T>;
49
+ row: (entry: T) => ProposalRow;
50
+ decide: (id: string, confirm: boolean, decision: Pick<Decision, "by" | "reason">) => Promise<string>;
51
+ }) => ProposalKind;
@@ -47,3 +47,37 @@ export const storedStatus = (filter) => {
47
47
  const status = filter.status ?? "proposed";
48
48
  return status === "proposed" || status === "rejected" ? status : undefined;
49
49
  };
50
+ export const reviewedRow = (kind, entry, object) => ({
51
+ id: entry.ref,
52
+ kind,
53
+ status: entry.review,
54
+ project: entry.project,
55
+ subject: entry.ref,
56
+ object,
57
+ summary: entry.title,
58
+ proposedBy: proposerOfAuthor(entry.author),
59
+ reason: entry.reason,
60
+ evidence: [],
61
+ score: null,
62
+ signals: null,
63
+ parts: null,
64
+ createdAt: entry.createdAt,
65
+ });
66
+ /**
67
+ * A kind over a store whose rows carry `review`, routed by its own prefix as invoices are. Only the owner decides
68
+ * money: the store refuses an agent whatever the policy says.
69
+ */
70
+ export const reviewedKind = (spec) => ({
71
+ kind: spec.type,
72
+ prefix: spec.type,
73
+ list: async (filter) => {
74
+ const status = filter.status ?? "proposed";
75
+ const entries = await spec.list({ ...pushed(filter), ...(status === "all" ? {} : { review: status }) });
76
+ return kept(entries.map(spec.row), filter);
77
+ },
78
+ get: async (id) => spec.row(await spec.get(id)),
79
+ decide: async (id, { confirm, by, reason }) => {
80
+ const made = await spec.decide(id, confirm, { by, reason });
81
+ return { id, kind: spec.type, status: confirm ? "confirmed" : "rejected", made: confirm ? [made] : [] };
82
+ },
83
+ });
@@ -0,0 +1,4 @@
1
+ import type { MessageStore } from "../../../store/index.js";
2
+ import type { ProposalKind } from "../types.js";
3
+ /** A memory or fact whose sources changed, went or were contradicted; only the owner says whether it still holds. */
4
+ export declare const sourceReviewKind: (store: Pick<MessageStore, "knowledge" | "proposedActions">) => ProposalKind;
@@ -0,0 +1,45 @@
1
+ import { proposerOfAction } from "../../../store/index.js";
2
+ import { SOURCE_REVIEW_KIND } from "../../../store/source-review.js";
3
+ import { actionStatus, kept, pushed, storedStatus } from "./shared.js";
4
+ const rowOf = (action) => {
5
+ const payload = action.payload;
6
+ const sources = payload.sources.flatMap((source) => source.ref ?? []);
7
+ const contradicting = payload.challenges.flatMap((challenge) => challenge.evidence);
8
+ const replacement = payload.sources.find((source) => source.replacement !== undefined)?.replacement ?? null;
9
+ return {
10
+ id: action.id,
11
+ kind: SOURCE_REVIEW_KIND,
12
+ status: actionStatus(action.status),
13
+ project: null,
14
+ subject: action.target ?? payload.target,
15
+ object: replacement,
16
+ summary: `${payload.cause}: ${payload.sources.length} source(s), ${payload.challenges.length} challenge(s)`,
17
+ proposedBy: proposerOfAction(action),
18
+ reason: payload.challenges.at(-1)?.reason ?? action.reason,
19
+ evidence: [...new Set([...sources, ...contradicting])].slice(0, 5),
20
+ score: null,
21
+ signals: null,
22
+ parts: null,
23
+ createdAt: payload.raisedAt,
24
+ };
25
+ };
26
+ /** A memory or fact whose sources changed, went or were contradicted; only the owner says whether it still holds. */
27
+ export const sourceReviewKind = (store) => ({
28
+ kind: SOURCE_REVIEW_KIND,
29
+ stored: [SOURCE_REVIEW_KIND],
30
+ ownerOnly: true,
31
+ list: async (filter) => {
32
+ const status = storedStatus(filter);
33
+ const stored = await store.proposedActions.list({
34
+ kinds: [SOURCE_REVIEW_KIND],
35
+ ...(status === undefined ? {} : { status }),
36
+ ...pushed(filter),
37
+ });
38
+ return kept(stored.map(rowOf), filter);
39
+ },
40
+ get: async (id) => rowOf(await store.proposedActions.get(id)),
41
+ decide: async (id, { confirm, by, reason }) => {
42
+ await store.knowledge.decideSourceReview(id, { confirm, by, ...(reason === undefined ? {} : { reason }) });
43
+ return { id, kind: SOURCE_REVIEW_KIND, status: confirm ? "confirmed" : "rejected", made: [] };
44
+ },
45
+ });
@@ -0,0 +1,9 @@
1
+ import type { MessageStore } from "../../../store/index.js";
2
+ import type { ProposalKind } from "../types.js";
3
+ /** An agent's or an import's subscription, by its own ref (`subscription:12`); only the owner decides it. */
4
+ export declare const subscriptionKind: (store: Pick<MessageStore, "subscriptions">) => ProposalKind;
5
+ /**
6
+ * A new price of a subscription (`subscription_price:7`): a proposal of its own, so a confirmed subscription stays
7
+ * confirmed while its next price waits.
8
+ */
9
+ export declare const subscriptionPriceKind: (store: Pick<MessageStore, "subscriptions">) => ProposalKind;
@@ -0,0 +1,24 @@
1
+ import { reviewedKind, reviewedRow } from "./shared.js";
2
+ /** An agent's or an import's subscription, by its own ref (`subscription:12`); only the owner decides it. */
3
+ export const subscriptionKind = (store) => reviewedKind({
4
+ type: "subscription",
5
+ list: (options) => store.subscriptions.list(options),
6
+ get: (id) => store.subscriptions.get(id),
7
+ row: (subscription) => reviewedRow("subscription", subscription, (subscription.direction === "receivable" ? subscription.customer : subscription.supplier).ref),
8
+ decide: async (id, confirm, { by, reason }) => (confirm ? await store.subscriptions.confirm(id, by, reason) : await store.subscriptions.reject(id, by, reason))
9
+ .ref,
10
+ });
11
+ /**
12
+ * A new price of a subscription (`subscription_price:7`): a proposal of its own, so a confirmed subscription stays
13
+ * confirmed while its next price waits.
14
+ */
15
+ export const subscriptionPriceKind = (store) => reviewedKind({
16
+ type: "subscription_price",
17
+ list: ({ review, proposedBy, limit }) => store.subscriptions.prices({ review, proposedBy, limit }),
18
+ get: (id) => store.subscriptions.price(id),
19
+ row: (price) => reviewedRow("subscription_price", price, price.subscription),
20
+ decide: async (id, confirm, { by, reason }) => {
21
+ await (confirm ? store.subscriptions.confirm(id, by, reason) : store.subscriptions.reject(id, by, reason));
22
+ return id;
23
+ },
24
+ });
@@ -0,0 +1,4 @@
1
+ import type { MessageStore } from "../../../store/index.js";
2
+ import type { ProposalKind } from "../types.js";
3
+ /** An agent's or an import's bank transaction, by its own ref (`transaction:12`); only the owner decides it. */
4
+ export declare const transactionKind: (store: Pick<MessageStore, "transactions">) => ProposalKind;
@@ -0,0 +1,10 @@
1
+ import { reviewedKind, reviewedRow } from "./shared.js";
2
+ /** An agent's or an import's bank transaction, by its own ref (`transaction:12`); only the owner decides it. */
3
+ export const transactionKind = (store) => reviewedKind({
4
+ type: "transaction",
5
+ list: (options) => store.transactions.list(options),
6
+ get: (id) => store.transactions.get(id),
7
+ row: (transaction) => reviewedRow("transaction", transaction, transaction.counterparty?.ref ?? transaction.wallet),
8
+ decide: async (id, confirm, { by, reason }) => (confirm ? await store.transactions.confirm(id, by, reason) : await store.transactions.reject(id, by, reason))
9
+ .ref,
10
+ });
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { mayDecide } from "../../store/decisions.js";
3
3
  import { actionKind } from "./kinds/action.js";
4
+ import { contractKind } from "./kinds/contracts.js";
4
5
  import { factKind } from "./kinds/fact.js";
5
6
  import { invoiceKind, paymentKind } from "./kinds/finance.js";
6
7
  import { findingsKind } from "./kinds/findings.js";
@@ -12,7 +13,10 @@ import { orderKind } from "./kinds/orders.js";
12
13
  import { organizationKind } from "./kinds/organization.js";
13
14
  import { relationshipKind } from "./kinds/relationship.js";
14
15
  import { relationshipUpdateKind } from "./kinds/relationship-update.js";
16
+ import { sourceReviewKind } from "./kinds/source-review.js";
17
+ import { subscriptionKind, subscriptionPriceKind } from "./kinds/subscriptions.js";
15
18
  import { taskCloseKind } from "./kinds/task-close.js";
19
+ import { transactionKind } from "./kinds/transactions.js";
16
20
  const PREFIX = /^([a-z][a-z_]*):/;
17
21
  const marked = (kind, row) => kind.ownerOnly ? { ...row, ownerOnly: true } : row;
18
22
  const refusalOf = (id, error) => {
@@ -135,12 +139,17 @@ export const proposalRegistry = (store) => {
135
139
  invoiceKind(store),
136
140
  paymentKind(store),
137
141
  orderKind(store),
142
+ contractKind(store),
143
+ subscriptionKind(store),
144
+ subscriptionPriceKind(store),
145
+ transactionKind(store),
138
146
  organizationKind(store),
139
147
  memoryKind(store),
140
148
  findingsKind(store),
141
149
  mailFindingsKind(store),
142
150
  meetingFindingsKind(store),
143
151
  taskCloseKind(store),
152
+ sourceReviewKind(store),
144
153
  ])
145
154
  registry.register(kind);
146
155
  registry.register(actionKind(store, registry.claimed));
@@ -1,7 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { parseLucene } from "@wirecat/cli-base/query";
3
3
  import { formatMeetingReference } from "../meetings/index.js";
4
- import { entriesOfList, fitting } from "../search/account-list.js";
4
+ import { entriesOfList, fitting, listedHolds } from "../search/account-list.js";
5
5
  import { SEARCH_QUERY } from "../search/lucene/types.js";
6
6
  import { codeOf } from "../sends/guarded.js";
7
7
  import { MAX_SEARCH_OFFSET } from "./messages-archive-search.js";
@@ -250,7 +250,7 @@ const searchAllOfSource = async (store, account, source, request, messenger, sea
250
250
  const named = (resource) => [
251
251
  ...new Map(entries
252
252
  .flatMap(({ accounts }) => accounts)
253
- .filter(({ kind }) => kind === resource)
253
+ .filter((one) => listedHolds(one, resource))
254
254
  .map(({ provider, account }) => [`${provider}\u0000${account}`, { provider, account }])).values(),
255
255
  ];
256
256
  const meetings = await holdingMeetings(store, named("meetings"));
@@ -3,7 +3,7 @@ import { parseLucene } from "@wirecat/cli-base/query";
3
3
  import { hitFiles } from "../domain/attachments.js";
4
4
  import { parseLocator } from "../domain/locator.js";
5
5
  import { senderIsMe } from "../domain/models.js";
6
- import { INTERNAL_NOTES, kindIn } from "../domain/providers.js";
6
+ import { holdsKind, INTERNAL_NOTES } from "../domain/providers.js";
7
7
  import { runEmbedders } from "../embeddings/embed.js";
8
8
  import { DEFAULT_TEXT_MODEL } from "../embeddings/models.js";
9
9
  import { plainQuery } from "../search/lucene/plain.js";
@@ -58,7 +58,7 @@ export const titleWords = (text) => {
58
58
  return { words, anyWord: clauses.length > 1 && clauses.every(({ occur }) => occur === "should") };
59
59
  };
60
60
  /** The accounts of every CRM the store holds copies of. */
61
- export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => kindIn(provider) === "crm");
61
+ export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
62
62
  /**
63
63
  * `search all`: messages, mail, notes, calendar events and CRM deals and leads from the local store — messages also from the messenger's
64
64
  * server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
@@ -120,7 +120,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
120
120
  hasMore ||= found.hasMore;
121
121
  const read = found.coverage?.accounts ??
122
122
  given ??
123
- (await store.accounts.accounts()).filter(({ provider }) => kindIn(provider) === kind);
123
+ (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, kind));
124
124
  for (const one of found.skipped ?? [])
125
125
  if (!skipped.some(({ source }) => source === one.source))
126
126
  skipped.push(one);
@@ -222,6 +222,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
222
222
  INTERNAL_NOTES,
223
223
  ...(await store.notes.folders()).map(({ id }) => id),
224
224
  ...(await store.notes.documentsAccounts()).map(({ id }) => id),
225
+ ...[await store.notes.addedAccount()].flatMap((added) => (added ? [added.id] : [])),
225
226
  ];
226
227
  accounts.push(...read.map((account) => ({ resource, provider: "notes", account })));
227
228
  }
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { isKind, kindOf, providerNamed } from "../domain/providers.js";
2
+ import { holdsKindOf, isKind, providerNamed } from "../domain/providers.js";
3
3
  import { entriesOfList, fitting, isAccountList } from "../search/account-list.js";
4
4
  export const NO_MAIL = "no_mail";
5
5
  export const MAIL = "email";
@@ -44,11 +44,11 @@ export const accountsOfKind = (kind, chosen, held, explicit, command = undefined
44
44
  if (kind === "messages") {
45
45
  if (explicit === MAIL)
46
46
  throw new CliError("validation_error", "mail is searched with `memo search mail`, not search messages");
47
- return chosen.filter(({ provider }) => kindOf(provider) === "messages");
47
+ return chosen.filter(({ provider }) => holdsKindOf(provider, "messages"));
48
48
  }
49
49
  if (explicit !== undefined && explicit !== MAIL && explicit !== "all")
50
50
  throw new CliError("validation_error", `search mail reads mail only — \`${command === undefined ? "" : `${command} `}search messages\` searches ${explicit}`);
51
- const mail = (listed ? chosen : held).filter(({ provider }) => kindOf(provider) === "mail");
51
+ const mail = (listed ? chosen : held).filter(({ provider }) => holdsKindOf(provider, "mail"));
52
52
  if (mail.length === 0)
53
53
  throw new CliError("not_found", "no mail in the store yet — `memo sync --only mail --since-time <time>` imports it", {
54
54
  reason: NO_MAIL,
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { MEETING_FINDINGS_KIND } from "../meetings/index.js";
3
3
  import { MAIL_FINDINGS_KIND } from "./mail-findings.js";
4
+ import { SOURCE_REVIEW_KIND } from "./source-review.js";
4
5
  /** An agent's suggested close of a task: kept on the task, not in `proposed_actions`. */
5
6
  export const TASK_CLOSE_KIND = "task_close";
6
7
  export const DEFAULT_DECISION_POLICY = { agentDecisions: false, ruleProposalsOwnerOnly: true };
@@ -8,7 +9,10 @@ export const DEFAULT_DECISION_POLICY = { agentDecisions: false, ruleProposalsOwn
8
9
  * Proposal kinds only the owner decides, whatever `agent_decisions` says. Read from the row's kind, so a path that
9
10
  * sees the row as something else — a generic action, a host's own kind — still refuses an agent.
10
11
  */
11
- export const isOwnerOnlyKind = (kind) => kind === MAIL_FINDINGS_KIND || kind === MEETING_FINDINGS_KIND || kind === TASK_CLOSE_KIND;
12
+ export const isOwnerOnlyKind = (kind) => kind === MAIL_FINDINGS_KIND ||
13
+ kind === MEETING_FINDINGS_KIND ||
14
+ kind === TASK_CLOSE_KIND ||
15
+ kind === SOURCE_REVIEW_KIND;
12
16
  /**
13
17
  * The one check every decide path runs before it confirms or rejects a proposal. `null` means allowed. Every Claude
14
18
  * Code session is the bot `claude-code`, so comparing bot names keeps one session from deciding another's proposal.
@@ -31,10 +31,13 @@ export { type ProjectAnnotationPreview, type ProjectAnnotationPreviewOptions, pr
31
31
  export { decodeProjectAnnotationSnapshot, type ProjectAnnotationSnapshot, type ProjectAnnotationSnapshotOptions, type ProjectAnnotationSnapshotResult, projectAnnotationSnapshotFingerprint, projectAnnotationSnapshotSchema, snapshotProjectAnnotations, } from "./project-transfer/snapshot.js";
32
32
  export { planProjectAnnotationSnapshot } from "./project-transfer/snapshot-plan.js";
33
33
  export type { ProjectAnnotationRestoreReceipt, ProjectAnnotationRestoreRequest, ProjectAnnotationStore, ProjectAnnotationTargetRequest, } from "./project-transfer/store.js";
34
+ export { SOURCE_REVIEW_CAUSES, SOURCE_REVIEW_KIND, type SourceCheck, type SourceReviewCause, type SourceReviewChallenge, type SourceReviewMarker, type SourceReviewPayload, type SourceReviewSource, } from "./source-review.js";
35
+ export { ADDED_KINDS, type AddedSource, type AddedSourceContent, type AddedSourceInput, addedSourceKeyOf, } from "./sqlite/added-sources.js";
34
36
  export type { AgentAction, AgentActionInput, AgentActionsStore } from "./sqlite/agent-actions.js";
35
37
  export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
36
38
  export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
37
39
  export type { BotUpdate, BotUpdateStore } from "./sqlite/bot-updates.js";
40
+ export type { Contract, ContractFields, ContractFilter, ContractInput, ContractsStore, ContractUpdate, } from "./sqlite/business-contracts.js";
38
41
  export type { CatalogActor, CatalogEntry, CatalogInput, CatalogQuery, CatalogStore } from "./sqlite/catalog.js";
39
42
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
40
43
  export type { ChatMetadata } from "./sqlite/chats.js";
@@ -44,10 +47,11 @@ export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, Fu
44
47
  export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
45
48
  export type { Email, EmailAddress, EmailAttachment, EmailFacts, EmailFilter, EmailInput, EmailInThread, EmailLocationInput, EmailRecipient, EmailRef, EmailThread, EmailVectorHit, FolderEmail, Mailbox, MailboxInput, MailFilter, MailStore, PartialEmail, SenderScore, ThreadDetails, ThreadSave, } from "./sqlite/emails.js";
46
49
  export { EVENT_FIELDS, type EventChunkToEmbed, type EventHit, type EventQuery, type EventSearch, type NearestEvent, } from "./sqlite/event-search.js";
50
+ export type { EvidenceInput, EvidenceMetadata } from "./sqlite/evidence-signature.js";
47
51
  export type { EvidenceSource } from "./sqlite/evidence-sources.js";
48
52
  export type { Fact, FactInput, FactsStore } from "./sqlite/facts.js";
49
53
  export type { FileListQuery, FilesStore, StoredFile } from "./sqlite/files.js";
50
- export type { Allocation, FinanceStore, Invoice, InvoiceDetail, InvoiceInput, InvoiceLine, InvoiceLineInput, OpenTotal, Party, Payment as FinancePayment, PaymentDetail as FinancePaymentDetail, PaymentInput as FinancePaymentInput, } from "./sqlite/finance.js";
54
+ export type { Allocation, FinanceStore, Invoice, InvoiceDetail, InvoiceInput, InvoiceLine, InvoiceLineInput, OpenTotal, Payment as FinancePayment, PaymentDetail as FinancePaymentDetail, PaymentInput as FinancePaymentInput, } from "./sqlite/finance.js";
51
55
  export { IMPORTED_DOCUMENT_QUERY, type ImportedDocuments } from "./sqlite/imported-documents.js";
52
56
  export type { Involvement, InvolvementStore } from "./sqlite/involvements.js";
53
57
  export type { Annotation, KnowledgeRelation, KnowledgeStore, KnowledgeTarget, LabelledType, Organization, Project, Reminder, } from "./sqlite/knowledge.js";
@@ -58,19 +62,25 @@ export type { MeetingContextReadCapabilities, MeetingReadCapabilities, MeetingRe
58
62
  export type { MeetingVectorHit, MeetingVectors } from "./sqlite/meeting-vectors.js";
59
63
  export type { AttachmentInput } from "./sqlite/meetings.js";
60
64
  export type { Author, MemoriesStore, Memory, MemoryInput } from "./sqlite/memories.js";
65
+ export type { MoneyLine, MoneyLineInput } from "./sqlite/money-lines.js";
66
+ export type { CategoryTotal, MoneyTransaction, SplitInput, TransactionFilter, TransactionInput, TransactionSplit, TransactionsStore, TransactionUpdate, } from "./sqlite/money-transactions.js";
61
67
  export type { NoteIndexState } from "./sqlite/note-index.js";
62
68
  export { type NearestNote, NOTE_FIELDS, type NoteChunkToEmbed, type NoteHit, type NoteQuery, type NoteSearch, } from "./sqlite/note-search.js";
63
69
  export type { FileNoteInput, Link, LinkInput, LinkListFilter, Note, NoteFolder, NotesStore, NoteTag, } from "./sqlite/notes.js";
64
- export type { Order, OrderFilter, OrderInput, OrdersStore } from "./sqlite/orders.js";
70
+ export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from "./sqlite/orders.js";
65
71
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
72
+ export type { Product, ProductFilter, ProductInput, ProductsStore, ProductUpdate } from "./sqlite/products.js";
66
73
  export { assertGenericAction, PROPOSAL_STATUSES, type ProposalInput, type ProposedAction, type ProposedActionsStore, proposerOfAction, } from "./sqlite/proposed-actions.js";
67
- export type { RecordKey, RecordOutcome, RecordStore, RecordsWritten, SourceRecord, } from "./sqlite/records.js";
74
+ export { type FlaggedRecord, type MappedRecord, type MatchRun, type RecordKey, type RecordStore, type RecordsRun, type RunItem, type RunOptions, type SourceRecord, type SourceRecordRelation, type Unmatched, waitingPointer, } from "./sqlite/records.js";
68
75
  export type { RelationFilter, RelationList, RelationListItem } from "./sqlite/relation-list.js";
69
76
  export type { LinkDecision, RelationUpdate } from "./sqlite/relation-proposals.js";
70
77
  export type { RelationReads } from "./sqlite/relation-reads.js";
71
78
  export type { RelationRole, RelationRoles } from "./sqlite/relation-roles.js";
72
79
  export type { RelationsStore, ReportedIssue, ReportedRelation, ReportedScope, ReportedSync, } from "./sqlite/reported-relations.js";
80
+ export type { AuthorInfo, Party, Reviewed, Written } from "./sqlite/reviewed.js";
73
81
  export { fillSearchIndex, resetSearchIndex, type SearchIndexFill, type SearchIndexState, searchIndexState, } from "./sqlite/search-index.js";
82
+ export type { ChallengeInput, SourceReviewDecision } from "./sqlite/source-review.js";
83
+ export type { PriceFilter, PriceInput, Subscription, SubscriptionDetail, SubscriptionFields, SubscriptionFilter, SubscriptionInput, SubscriptionPrice, SubscriptionsStore, SubscriptionUpdate, } from "./sqlite/subscriptions.js";
74
84
  export type { SyncStateSave } from "./sqlite/sync.js";
75
85
  export type { TagCreationOptions, TagCreationReview } from "./sqlite/tag-creation.js";
76
86
  export type { TagKind, TagRow } from "./sqlite/tags.js";
@@ -86,6 +96,7 @@ export { TASK_RELATION_KINDS } from "./sqlite/task-relations.js";
86
96
  export type { TaskStatRow, TaskStatScope } from "./sqlite/task-stats.js";
87
97
  export type { StoreTaskStore } from "./sqlite/tasks.js";
88
98
  export type { TagPreflight, VocabularyAlias, VocabularyAliasReceipt, VocabularyAudit, VocabularyAuditOptions, VocabularyCatalog, VocabularyEntry, VocabularyKind, VocabularyOptions, VocabularyResolution, VocabularyStore, VocabularyTarget, } from "./sqlite/vocabulary.js";
99
+ export type { Wallet, WalletFilter, WalletInput, WalletsStore, WalletUpdate } from "./sqlite/wallets.js";
89
100
  export type { BoardCounts, BoardOptions, EditedTask, MovedSubtask, NewWorkTask, RevisionCheck, TaskAssignment, TaskDetails, TaskEvent, TaskFields, TaskMove, TaskMoved, TaskRole, TaskType, WorkTaskType, } from "./sqlite/work-tasks.js";
90
101
  export { TASK_EVENT_KINDS, TASK_ROLES } from "./sqlite/work-tasks.js";
91
102
  export { type AccountAccounts, type AccountAttachments, type AccountCounters, type AccountKey, type AccountMentions, type AccountMessageFilter, type AccountMessages, type AccountPeople, type AccountsStore, type AccountVectors, type AttachmentsStore, type AttachmentTextEntry, type AttachmentView, type ChatStats, type ChatsStore, type ConversationsStore, type CountersStore, type DeletionScope, type Delta, type FileAttachment, type IdentityRef, type IngestedVia, type LinkedIdentity, type LinkOptions, MENTION_QUERY, MENTION_STATUSES, type MentionsStore, type MessageFilter, type MessageStore, type MessagesStore, OTHER_SOURCES, openStore, type PeopleStore, type PersonFacts, type PersonRecord, type QueriesStore, type Range, type RankedEvidence, type RankedStoreFound, type RankedStoreRow, type RankingEvidenceItem, type RankingEvidenceRequest, type RankingRequest, type RosterStore, type SearchCommand, type SearchesStore, type SearchIndexStore, type SearchRecord, type StoredAccount, type StoredChatFilter, type StoredHit, type StoredSearch, type StoredTag, type StoreOptions, type SyncStore, type TagFilter, type TagsStore, type TagTarget, type TaskAnalysisMark, type TaskAnalysisMarkWrite, type TaskTagTarget, type TextOrigin, type VectorsStore, } from "./store.js";
@@ -21,6 +21,8 @@ export { planProjectAnnotations, } from "./project-transfer/plan.js";
21
21
  export { previewProjectAnnotationSnapshot, } from "./project-transfer/preview.js";
22
22
  export { decodeProjectAnnotationSnapshot, projectAnnotationSnapshotFingerprint, projectAnnotationSnapshotSchema, snapshotProjectAnnotations, } from "./project-transfer/snapshot.js";
23
23
  export { planProjectAnnotationSnapshot } from "./project-transfer/snapshot-plan.js";
24
+ export { SOURCE_REVIEW_CAUSES, SOURCE_REVIEW_KIND, } from "./source-review.js";
25
+ export { ADDED_KINDS, addedSourceKeyOf, } from "./sqlite/added-sources.js";
24
26
  export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
25
27
  export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
26
28
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
@@ -31,6 +33,7 @@ export { IMPORTED_DOCUMENT_QUERY } from "./sqlite/imported-documents.js";
31
33
  export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js";
32
34
  export { NOTE_FIELDS, } from "./sqlite/note-search.js";
33
35
  export { assertGenericAction, PROPOSAL_STATUSES, proposerOfAction, } from "./sqlite/proposed-actions.js";
36
+ export { waitingPointer, } from "./sqlite/records.js";
34
37
  export { fillSearchIndex, resetSearchIndex, searchIndexState, } from "./sqlite/search-index.js";
35
38
  export { PROJECT_TASK_FIELDS, TASK_SORTS, withoutField } from "./sqlite/task-board.js";
36
39
  export { certaintyOf } from "./sqlite/task-close.js";
@@ -51,7 +51,7 @@ export const accountPeopleOver = (context) => {
51
51
  editContactNote: async (key, person, id, text, revision) => {
52
52
  return write(database, () => privatePeople.editNote(context, key, person, id, text, revision));
53
53
  },
54
- removeContactNote: async (key, person, id) => privatePeople.removeNote(context, key, person, id),
54
+ removeContactNote: async (key, person, id) => write(database, () => privatePeople.removeNote(context, key, person, id)),
55
55
  };
56
56
  };
57
57
  export const peopleStoreOver = (context, keyed) => {
@@ -0,0 +1,64 @@
1
+ export declare const SOURCE_REVIEW_KIND = "memory_source_review";
2
+ /** Least severe first: a review moves forward in the queue only when its cause moves right. */
3
+ export declare const SOURCE_REVIEW_CAUSES: readonly ["changed", "outdated", "deleted", "contradicted"];
4
+ export type SourceReviewCause = (typeof SOURCE_REVIEW_CAUSES)[number];
5
+ /** The open review of a memory or fact, as its reads show it. */
6
+ export interface SourceReviewMarker {
7
+ id: string;
8
+ cause: SourceReviewCause;
9
+ }
10
+ /** One cited source that needs a look; it names the cited version and never copies its text. */
11
+ export interface SourceReviewSource {
12
+ /** The `evidence` link's id. */
13
+ link: number;
14
+ /** `null` when the store can no longer name the source, or it was erased. */
15
+ ref: string | null;
16
+ /** The kind of source an erased `ref` named. */
17
+ kind?: string;
18
+ cause: Exclude<SourceReviewCause, "contradicted">;
19
+ /** The version cited (`links.metadata.cited_rev`), to read its text back through `sourceTextAt`. */
20
+ citedRev: number | null;
21
+ /** For `outdated`: what replaced the cited fact or memory, following `supersedes`. */
22
+ replacement?: string;
23
+ }
24
+ export interface SourceReviewChallenge {
25
+ evidence: string[];
26
+ reason: string;
27
+ /** `owner`, or the bot's handle. */
28
+ by: string;
29
+ at: string;
30
+ }
31
+ /** What an author offers with a review, such as a corrected claim; it is the author's text, never the source's. */
32
+ export interface SourceReviewSuggestion {
33
+ /** `owner`, or the bot's handle. */
34
+ author: string;
35
+ body: string;
36
+ /** The references of the challenge it came with. */
37
+ evidence: string[];
38
+ at: string;
39
+ }
40
+ /** A `memory_source_review` proposal's payload. */
41
+ export interface SourceReviewPayload {
42
+ target: string;
43
+ cause: SourceReviewCause;
44
+ raisedAt: string;
45
+ sources: SourceReviewSource[];
46
+ challenges: SourceReviewChallenge[];
47
+ suggestions?: SourceReviewSuggestion[];
48
+ }
49
+ export interface SourceCheck {
50
+ /** Evidence links read. */
51
+ checked: number;
52
+ /** Links written before signatures, signed now with nothing to say. */
53
+ baselined: number;
54
+ /** Reviews opened, or open ones whose cause or sources grew. */
55
+ raised: number;
56
+ /** Sources that changed while still saying the quoted words, signed again in silence. */
57
+ refreshed: number;
58
+ /** Open reviews of a memory or fact met in this run that no longer holds, closed. */
59
+ closed: number;
60
+ }
61
+ /** What stands in a review for words about a source that was erased since. */
62
+ export declare const ERASED_TEXT = "[source erased]";
63
+ export declare const severity: (cause: SourceReviewCause) => number;
64
+ export declare const graver: (a: SourceReviewCause, b: SourceReviewCause) => SourceReviewCause;
@@ -0,0 +1,7 @@
1
+ export const SOURCE_REVIEW_KIND = "memory_source_review";
2
+ /** Least severe first: a review moves forward in the queue only when its cause moves right. */
3
+ export const SOURCE_REVIEW_CAUSES = ["changed", "outdated", "deleted", "contradicted"];
4
+ /** What stands in a review for words about a source that was erased since. */
5
+ export const ERASED_TEXT = "[source erased]";
6
+ export const severity = (cause) => SOURCE_REVIEW_CAUSES.indexOf(cause);
7
+ export const graver = (a, b) => severity(b) > severity(a) ? b : a;
@@ -10,7 +10,7 @@ export declare const storedAccounts: ({ orm }: StoreContext) => StoredAccount[];
10
10
  /** One account by provider and external id, never created; a missing one is `not_found`. */
11
11
  export declare const storedAccount: ({ orm }: StoreContext, { provider, account }: AccountKey) => StoredAccount;
12
12
  /** Everything the account holds, children before parents: the foreign keys are enforced. */
13
- export declare const purgeAccount: ({ orm, database }: StoreContext, accountKey: number) => void;
13
+ export declare const purgeAccount: ({ orm, database, now }: StoreContext, accountKey: number) => void;
14
14
  export declare const unreferenced: (database: CacheDatabase, table: "identities") => Set<number>;
15
15
  /**
16
16
  * People only the purged account had seen go with it. An identity stays while anything else points at it
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { and, asc, eq, inArray, sql } from "./drizzle/core.js";
3
3
  import { pointerPairs } from "./entity-types.js";
4
+ import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
4
5
  import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
5
6
  import { dropUnusedVectors } from "./vector-index.js";
6
7
  /** An account's row, made on first sight; a name only replaces what was known when there is one. */
@@ -53,8 +54,24 @@ export const storedAccount = ({ orm }, { provider, account }) => {
53
54
  return found;
54
55
  };
55
56
  /** Everything the account holds, children before parents: the foreign keys are enforced. */
56
- export const purgeAccount = ({ orm, database }, accountKey) => {
57
+ export const purgeAccount = ({ orm, database, now }, accountKey) => {
57
58
  const unseenBefore = unreferenced(database, "identities");
59
+ const at = now();
60
+ const meetingIds = "SELECT id FROM meetings WHERE account_id = ?";
61
+ const transcriptIds = `SELECT id FROM meeting_transcripts WHERE meeting_id IN (${meetingIds})`;
62
+ for (const [type, sql] of [
63
+ ["message", "SELECT id FROM messages WHERE account_id = ?"],
64
+ ["chat", "SELECT id FROM chats WHERE account_id = ?"],
65
+ ["email", "SELECT id FROM emails WHERE account_id = ?"],
66
+ ["email_thread", "SELECT id FROM email_threads WHERE account_id = ?"],
67
+ ["meeting", meetingIds],
68
+ ["meeting_transcript", transcriptIds],
69
+ [
70
+ "meeting_transcript_row",
71
+ `SELECT id FROM meeting_transcript_rows WHERE meeting_transcript_id IN (${transcriptIds})`,
72
+ ],
73
+ ])
74
+ forgetEvidenceTo(database, type, { sql, params: [accountKey] }, at);
58
75
  const chatsOf = orm.select({ pk: chats.id }).from(chats).where(eq(chats.accountId, accountKey));
59
76
  const messagesOf = orm.select({ pk: messages.id }).from(messages).where(eq(messages.accountId, accountKey));
60
77
  orm.delete(botUpdates).where(eq(botUpdates.accountId, accountKey)).run();
@@ -114,6 +131,11 @@ export const purgeAccount = ({ orm, database }, accountKey) => {
114
131
  // The inbox project and its tasks are the owner's; only the tie to the account goes.
115
132
  orm.update(projects).set({ accountId: null }).where(eq(projects.accountId, accountKey)).run();
116
133
  orm.run(sql `DELETE FROM files WHERE account_id = ${accountKey}`);
134
+ // Deleting a document clears its pieces, words, revisions, tags and own links (trigger document_bd).
135
+ const documentsOf = sql `(SELECT id FROM documents WHERE account_id = ${accountKey})`;
136
+ orm.run(sql `DELETE FROM links WHERE to_type = 'document' AND to_id IN ${documentsOf}`);
137
+ orm.run(sql `UPDATE files SET document_id = NULL WHERE document_id IN ${documentsOf}`);
138
+ orm.run(sql `DELETE FROM documents WHERE account_id = ${accountKey}`);
117
139
  orm.run(sql `DELETE FROM crm_fields WHERE account_id = ${accountKey}`);
118
140
  // An entity made from a record is the owner's and stays; only what the source said goes.
119
141
  const recordsOf = sql `(SELECT id FROM records WHERE account_id = ${accountKey})`;
@@ -121,6 +143,7 @@ export const purgeAccount = ({ orm, database }, accountKey) => {
121
143
  orm.run(sql `DELETE FROM records WHERE account_id = ${accountKey}`);
122
144
  orm.delete(accounts).where(eq(accounts.id, accountKey)).run();
123
145
  dropOrphanPeople(database, unseenBefore);
146
+ forgetDanglingEvidence(database, at);
124
147
  dropUnusedVectors(database, hashes);
125
148
  };
126
149
  /** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */