@wirecat/cli-core 0.604.0 → 0.606.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 (141) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/dist/calendar/prepare.d.ts +4 -2
  3. package/dist/calendar/prepare.js +8 -8
  4. package/dist/cli/index.d.ts +2 -2
  5. package/dist/cli/index.js +2 -1
  6. package/dist/cli/messenger/contacts-command.js +3 -2
  7. package/dist/cli/messenger/doctor-command.js +14 -7
  8. package/dist/cli/messenger/store-maintenance-command.d.ts +34 -2
  9. package/dist/cli/messenger/store-maintenance-command.js +31 -4
  10. package/dist/cli/program.js +11 -2
  11. package/dist/cli/steps.js +9 -1
  12. package/dist/cli/store-recover.d.ts +10 -2
  13. package/dist/cli/store-recover.js +18 -4
  14. package/dist/cli/store-settings.js +38 -4
  15. package/dist/crm/cli/index.js +3 -1
  16. package/dist/crm/index.d.ts +2 -2
  17. package/dist/crm/index.js +1 -1
  18. package/dist/crm/source.d.ts +35 -5
  19. package/dist/crm/sync.d.ts +15 -7
  20. package/dist/crm/sync.js +169 -11
  21. package/dist/domain/crm.d.ts +41 -2
  22. package/dist/domain/deals.d.ts +5 -2
  23. package/dist/domain/deals.js +5 -2
  24. package/dist/domain/record-types.d.ts +61 -0
  25. package/dist/domain/record-types.js +26 -0
  26. package/dist/domain/records.d.ts +3 -5
  27. package/dist/domain/records.js +10 -13
  28. package/dist/domain/relations.d.ts +125 -0
  29. package/dist/domain/relations.js +107 -0
  30. package/dist/entities/contact-activity.d.ts +4 -0
  31. package/dist/entities/contact-activity.js +1 -0
  32. package/dist/entities/contact-context.d.ts +20 -0
  33. package/dist/entities/contact-context.js +2 -0
  34. package/dist/entities/deal.d.ts +2 -2
  35. package/dist/entities/deal.js +2 -1
  36. package/dist/entities/index.d.ts +39 -13
  37. package/dist/entities/relationship.d.ts +8 -2
  38. package/dist/entities/relationship.js +8 -2
  39. package/dist/entities/task-results.d.ts +10 -10
  40. package/dist/errors/failures.d.ts +17 -1
  41. package/dist/errors/failures.js +57 -1
  42. package/dist/errors/reasons.js +28 -0
  43. package/dist/index.d.ts +2 -1
  44. package/dist/index.js +1 -0
  45. package/dist/mail/cli/review.js +20 -6
  46. package/dist/mail/index.d.ts +1 -1
  47. package/dist/mail/marks.d.ts +10 -5
  48. package/dist/mail/marks.js +16 -8
  49. package/dist/mail/review.d.ts +5 -0
  50. package/dist/mcp/tool.js +2 -1
  51. package/dist/runs/recording.js +13 -4
  52. package/dist/services/deps.js +4 -6
  53. package/dist/services/index.d.ts +1 -1
  54. package/dist/services/link-scorers/chat-senders.d.ts +3 -2
  55. package/dist/services/link-scorers/chat-senders.js +7 -4
  56. package/dist/services/link-scorers/mail-thread.js +1 -0
  57. package/dist/services/link-scorers/member-chats.js +1 -0
  58. package/dist/services/link-scorers/member-dialog.d.ts +1 -1
  59. package/dist/services/link-scorers/member-dialog.js +4 -3
  60. package/dist/services/link-scorers/scan.d.ts +5 -2
  61. package/dist/services/link-scorers/scan.js +100 -54
  62. package/dist/services/link-scorers/shared.d.ts +2 -2
  63. package/dist/services/link-scorers/shared.js +8 -4
  64. package/dist/services/link-scorers/types.d.ts +3 -0
  65. package/dist/services/metadata.d.ts +1 -1
  66. package/dist/services/person-context.d.ts +24 -7
  67. package/dist/services/person-context.js +45 -11
  68. package/dist/services/person-preparation.js +4 -5
  69. package/dist/services/project-status/index.js +2 -1
  70. package/dist/services/stored-project-gathering.js +4 -3
  71. package/dist/store/damage.d.ts +3 -1
  72. package/dist/store/damage.js +19 -12
  73. package/dist/store/document-transfer/index.js +7 -0
  74. package/dist/store/exports.d.ts +1 -0
  75. package/dist/store/exports.js +1 -0
  76. package/dist/store/index.d.ts +7 -1
  77. package/dist/store/index.js +2 -0
  78. package/dist/store/marks.d.ts +57 -0
  79. package/dist/store/marks.js +121 -0
  80. package/dist/store/project-transfer/preview.js +12 -7
  81. package/dist/store/project-transfer/request.d.ts +4 -1
  82. package/dist/store/project-transfer/schema.d.ts +9 -2
  83. package/dist/store/project-transfer/schema.js +4 -0
  84. package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
  85. package/dist/store/recover.js +16 -1
  86. package/dist/store/sqlite/crm-settings.d.ts +28 -0
  87. package/dist/store/sqlite/crm-settings.js +80 -0
  88. package/dist/store/sqlite/crm.d.ts +42 -2
  89. package/dist/store/sqlite/crm.js +397 -36
  90. package/dist/store/sqlite/deals.js +3 -2
  91. package/dist/store/sqlite/finance.d.ts +8 -1
  92. package/dist/store/sqlite/finance.js +10 -3
  93. package/dist/store/sqlite/involvement-queue.js +4 -3
  94. package/dist/store/sqlite/knowledge.d.ts +7 -3
  95. package/dist/store/sqlite/knowledge.js +43 -31
  96. package/dist/store/sqlite/link-kinds.d.ts +2 -3
  97. package/dist/store/sqlite/link-kinds.js +4 -2
  98. package/dist/store/sqlite/manifest.js +5 -0
  99. package/dist/store/sqlite/memories.d.ts +1 -1
  100. package/dist/store/sqlite/memories.js +33 -7
  101. package/dist/store/sqlite/migrations.generated.js +31 -0
  102. package/dist/store/sqlite/notes.d.ts +3 -2
  103. package/dist/store/sqlite/notes.js +23 -6
  104. package/dist/store/sqlite/open-store.js +4 -1
  105. package/dist/store/sqlite/organizations.d.ts +8 -0
  106. package/dist/store/sqlite/organizations.js +14 -0
  107. package/dist/store/sqlite/own-identities.d.ts +1 -1
  108. package/dist/store/sqlite/own-identities.js +7 -5
  109. package/dist/store/sqlite/person-links.d.ts +5 -2
  110. package/dist/store/sqlite/person-links.js +24 -18
  111. package/dist/store/sqlite/person-preparation.d.ts +1 -1
  112. package/dist/store/sqlite/person-preparation.js +3 -2
  113. package/dist/store/sqlite/person-separation.d.ts +5 -0
  114. package/dist/store/sqlite/person-separation.js +26 -0
  115. package/dist/store/sqlite/project-transfer/records.js +14 -3
  116. package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
  117. package/dist/store/sqlite/project-transfer/snapshot.js +6 -0
  118. package/dist/store/sqlite/record-projectors.d.ts +44 -0
  119. package/dist/store/sqlite/record-projectors.js +72 -0
  120. package/dist/store/sqlite/records.js +12 -70
  121. package/dist/store/sqlite/relation-list.d.ts +43 -0
  122. package/dist/store/sqlite/relation-list.js +133 -0
  123. package/dist/store/sqlite/relation-proposals.d.ts +28 -6
  124. package/dist/store/sqlite/relation-proposals.js +134 -10
  125. package/dist/store/sqlite/relation-reads.d.ts +8 -0
  126. package/dist/store/sqlite/relation-reads.js +7 -0
  127. package/dist/store/sqlite/relation-roles.d.ts +26 -0
  128. package/dist/store/sqlite/relation-roles.js +91 -0
  129. package/dist/store/sqlite/reported-relations.d.ts +63 -0
  130. package/dist/store/sqlite/reported-relations.js +132 -0
  131. package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
  132. package/dist/store/sqlite/schema/link-revisions.js +11 -0
  133. package/dist/store/sqlite/schema/links.d.ts +360 -0
  134. package/dist/store/sqlite/schema/links.js +32 -0
  135. package/dist/store/sqlite/schema.d.ts +2 -296
  136. package/dist/store/sqlite/schema.js +2 -24
  137. package/dist/store/sqlite/transaction.js +2 -5
  138. package/dist/store/store.d.ts +3 -0
  139. package/dist/store/store.js +5 -0
  140. package/dist/store/types.d.ts +5 -0
  141. package/package.json +5 -5
@@ -1,5 +1,5 @@
1
1
  import type { ChatKind, Id, Message, Provider } from "../domain/models.js";
2
- import type { AccountKey, IdentityRef, LinkedIdentity, MessageStore, PersonRecord } from "../store/store.js";
2
+ import type { AccountKey, IdentityRef, LinkedIdentity, MessageStore, PersonRecord, StoredAccount } from "../store/store.js";
3
3
  export declare const CONTEXT_MESSAGES = 10;
4
4
  export declare const CONTEXT_BYTES: number;
5
5
  export interface ContextMessage {
@@ -37,11 +37,16 @@ export interface ContextEvent {
37
37
  }
38
38
  /** `not_fetched`: nothing of its history was ever read into the store; `partial`: only some of it was. */
39
39
  export type NotReadReason = "not_fetched" | "partial";
40
+ export type AccountScope = StoredAccount["scope"];
40
41
  export interface PersonContext {
41
42
  person: PersonRecord & {
42
43
  provider: Provider;
43
44
  id: Id;
44
45
  };
46
+ /** Every account read, with its scope: only accounts of the scopes the caller may read. */
47
+ accounts: (AccountKey & {
48
+ scope: AccountScope;
49
+ })[];
45
50
  shared: SharedChat[];
46
51
  /** Each way, the newest in a messenger dialog whatever `limits` says; mail only within them. */
47
52
  last: {
@@ -78,15 +83,23 @@ export interface ContextOptions {
78
83
  since?: number;
79
84
  /** ms: what splits upcoming events from past ones; the clock when absent. */
80
85
  now?: number;
86
+ /**
87
+ * The account scopes read; the asked account's own scope when absent. One exact email address joins a personal
88
+ * and a work contact into one person, so a personal account must not read that person's work mail by default.
89
+ */
90
+ scopes?: readonly AccountScope[];
81
91
  }
82
92
  export declare const toContext: (key: AccountKey, message: Message, chatTitle: string | null) => ContextMessage;
93
+ /** The stored accounts of `scopes`, or of the asked account's own scope; the asked account must be stored. */
94
+ export declare const readableAccounts: (store: MessageStore, asked: AccountKey, scopes?: readonly AccountScope[]) => Promise<StoredAccount[]>;
83
95
  /**
84
- * The accounts each identity is read in: for the messenger asked, only the account asked about — a
85
- * second account of the same messenger is somebody else's view; for a linked messenger, every account
86
- * of this store that saw that identity.
96
+ * The accounts each identity is read in, among `readable` only: for the messenger asked, only the account asked
97
+ * about — a second account of the same messenger is somebody else's view; for a linked messenger, every readable
98
+ * account of this store that saw that identity.
87
99
  */
88
- export declare const readsOf: (record: PersonRecord, asked: AccountKey) => {
100
+ export declare const readsOf: (record: PersonRecord, asked: AccountKey, readable: readonly StoredAccount[]) => {
89
101
  key: AccountKey;
102
+ scope: AccountScope;
90
103
  identity: LinkedIdentity;
91
104
  }[];
92
105
  /**
@@ -94,11 +107,15 @@ export declare const readsOf: (record: PersonRecord, asked: AccountKey) => {
94
107
  * only: nothing is fetched, nothing marked read. Identity is by id, never by name.
95
108
  */
96
109
  export declare const personContext: (store: MessageStore, asked: AccountKey, reference: string, options?: ContextOptions) => Promise<PersonContext>;
97
- /** `personContext` of a person already found, read in the identities and accounts `reads` names. */
110
+ /**
111
+ * `personContext` of a person already found, read in the identities and accounts `reads` names; their calendar
112
+ * events in every calendar account of `readable`.
113
+ */
98
114
  export declare const recordContext: (store: MessageStore, record: PersonRecord, reads: {
99
115
  key: AccountKey;
116
+ scope: AccountScope;
100
117
  identity: LinkedIdentity;
101
- }[], { messages, bytes, since, now }?: ContextOptions) => Promise<Omit<PersonContext, "person">>;
118
+ }[], readable: readonly StoredAccount[], { messages, bytes, since, now }?: ContextOptions) => Promise<Omit<PersonContext, "person">>;
102
119
  /** `max:Ana` names a person in another messenger of this store; a reference with no prefix, this one. */
103
120
  export declare const identityIn: (store: MessageStore, asked: AccountKey, reference: string) => Promise<IdentityRef>;
104
121
  export declare const CHAT_MESSAGES = 20;
@@ -80,14 +80,30 @@ const eventsOnce = async (store, filter, limit) => {
80
80
  }
81
81
  return { items, cut: true };
82
82
  };
83
+ const nameOf = ({ provider, account }) => `${provider}:${account}`;
84
+ /** The stored accounts of `scopes`, or of the asked account's own scope; the asked account must be stored. */
85
+ export const readableAccounts = async (store, asked, scopes) => {
86
+ const stored = await store.accounts.storedAccounts();
87
+ const own = stored.find((one) => nameOf(one) === nameOf(asked));
88
+ if (!own || (asked.scope !== undefined && asked.scope !== own.scope))
89
+ throw new CliError("not_found", `no ${asked.provider} account ${asked.account} in the store`);
90
+ const allowed = scopes ?? [own.scope];
91
+ return stored.filter((one) => allowed.includes(one.scope));
92
+ };
83
93
  /**
84
- * The accounts each identity is read in: for the messenger asked, only the account asked about — a
85
- * second account of the same messenger is somebody else's view; for a linked messenger, every account
86
- * of this store that saw that identity.
94
+ * The accounts each identity is read in, among `readable` only: for the messenger asked, only the account asked
95
+ * about — a second account of the same messenger is somebody else's view; for a linked messenger, every readable
96
+ * account of this store that saw that identity.
87
97
  */
88
- export const readsOf = (record, asked) => record.identities.flatMap((identity) => (identity.provider === asked.provider ? [asked.account] : identity.accounts)
89
- .filter((account) => identity.accounts.includes(account))
90
- .map((account) => ({ key: { provider: identity.provider, account }, identity })));
98
+ export const readsOf = (record, asked, readable) => {
99
+ const scopeOf = new Map(readable.map((one) => [nameOf(one), one.scope]));
100
+ return record.identities.flatMap((identity) => (identity.provider === asked.provider ? [asked.account] : identity.accounts).flatMap((account) => {
101
+ const scope = scopeOf.get(nameOf({ provider: identity.provider, account }));
102
+ return identity.accounts.includes(account) && scope !== undefined
103
+ ? [{ key: { provider: identity.provider, account }, scope, identity }]
104
+ : [];
105
+ }));
106
+ };
91
107
  /**
92
108
  * What the store knows about one person, across every identity linked to them. Reads the store
93
109
  * only: nothing is fetched, nothing marked read. Identity is by id, never by name.
@@ -97,13 +113,17 @@ export const personContext = async (store, asked, reference, options = {}) => {
97
113
  const record = await store.people.personOf({ provider: asked.provider, id: found.id });
98
114
  if (!record)
99
115
  throw new CliError("not_found", `no person ${found.id} in the store`);
116
+ const readable = await readableAccounts(store, asked, options.scopes);
100
117
  return {
101
118
  person: { ...record, provider: asked.provider, id: found.id },
102
- ...(await recordContext(store, record, readsOf(record, asked), options)),
119
+ ...(await recordContext(store, record, readsOf(record, asked, readable), readable, options)),
103
120
  };
104
121
  };
105
- /** `personContext` of a person already found, read in the identities and accounts `reads` names. */
106
- export const recordContext = async (store, record, reads, { messages = CONTEXT_MESSAGES, bytes = CONTEXT_BYTES, since, now = Date.now() } = {}) => {
122
+ /**
123
+ * `personContext` of a person already found, read in the identities and accounts `reads` names; their calendar
124
+ * events in every calendar account of `readable`.
125
+ */
126
+ export const recordContext = async (store, record, reads, readable, { messages = CONTEXT_MESSAGES, bytes = CONTEXT_BYTES, since, now = Date.now() } = {}) => {
107
127
  const recent = (message) => since === undefined || Date.parse(message.timestamp) >= since;
108
128
  const shared = [];
109
129
  const notRead = [];
@@ -165,9 +185,17 @@ export const recordContext = async (store, record, reads, { messages = CONTEXT_M
165
185
  cut ||= named.hasMore;
166
186
  }
167
187
  const personId = Number(record.uid);
168
- const upcoming = await eventsOnce(store, { personId, from: now }, messages);
188
+ const calendars = [];
189
+ for (const one of readable)
190
+ if ((await store.calendar.calendars(one.id)).length)
191
+ calendars.push(one);
192
+ const accountIds = calendars.map(({ id }) => id);
193
+ const nothing = { items: [], cut: false };
194
+ const upcoming = accountIds.length ? await eventsOnce(store, { personId, accountIds, from: now }, messages) : nothing;
169
195
  const upcomingIds = new Set(upcoming.items.map(({ id }) => id));
170
- const past = await eventsOnce(store, { personId, to: now, newest: true, ...(since === undefined ? {} : { from: since }) }, messages);
196
+ const past = accountIds.length
197
+ ? await eventsOnce(store, { personId, accountIds, to: now, newest: true, ...(since === undefined ? {} : { from: since }) }, messages)
198
+ : nothing;
171
199
  cut ||= upcoming.cut || past.cut;
172
200
  direct.sort(newestFirst);
173
201
  const each = [...direct, ...beyond].sort(newestFirst);
@@ -183,7 +211,13 @@ export const recordContext = async (store, record, reads, { messages = CONTEXT_M
183
211
  };
184
212
  cut ||= direct.length > messages || groups.length > messages || mentions.length > messages;
185
213
  const kept = withinBytes(lists, bytes);
214
+ const read = [
215
+ ...reads.map(({ key, scope }) => ({ ...key, scope })),
216
+ ...calendars.map(({ provider, account, scope }) => ({ provider, account, scope })),
217
+ ];
218
+ const accounts = [...new Map(read.map((one) => [nameOf(one), one])).values()].sort((a, b) => nameOf(a).localeCompare(nameOf(b)));
186
219
  return {
220
+ accounts,
187
221
  shared: shared.sort((a, b) => Date.parse(b.lastMessageAt ?? "") - Date.parse(a.lastMessageAt ?? "")),
188
222
  last: {
189
223
  fromThem: each.find((message) => !message.outgoing) ?? null,
@@ -1,6 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { parseMeetingReference } from "../meetings/index.js";
3
- import { CONTEXT_BYTES, CONTEXT_MESSAGES, personContext, readsOf, toContext, } from "./person-context.js";
3
+ import { CONTEXT_BYTES, CONTEXT_MESSAGES, personContext, readableAccounts, toContext, } from "./person-context.js";
4
4
  import { personMeetingContext } from "./person-meeting-context.js";
5
5
  export const PREPARE_BYTES = 96 * 1024;
6
6
  const MEETINGS = 5;
@@ -34,7 +34,6 @@ export const personPreparation = async (store, asked, reference, options = {}) =
34
34
  coverage: { included: items.length, hasMore: over || cut, cutBy: cut ? "bytes" : over ? "limit" : null },
35
35
  };
36
36
  };
37
- const reads = readsOf(context.person, asked);
38
37
  const partial = new Set(context.notRead.map((chat) => `${chat.provider}/${chat.account}/${chat.chatId}`));
39
38
  const waiting = [];
40
39
  for (const chat of context.shared.filter((one) => one.kind === "dialog")) {
@@ -51,10 +50,10 @@ export const personPreparation = async (store, asked, reference, options = {}) =
51
50
  });
52
51
  }
53
52
  waiting.sort((a, b) => Date.parse(b.message.timestamp) - Date.parse(a.message.timestamp));
54
- const accounts = [...new Map(reads.map(({ key }) => [accountName(key), key])).values()];
53
+ const accounts = context.accounts.map(({ provider, account }) => ({ provider, account }));
55
54
  const held = await store.people.preparation(context.person.uid, { accounts, limit });
56
- const stored = await store.accounts.storedAccounts();
57
- const meetings = await meetingsOf(store, context.person.uid, stored, options.since, () => left);
55
+ const readable = await readableAccounts(store, asked, options.scopes);
56
+ const meetings = await meetingsOf(store, context.person.uid, readable, options.since, () => left);
58
57
  const sections = {
59
58
  waiting: budgeted({ items: waiting, hasMore: false }),
60
59
  tasks: budgeted(held.tasks),
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { formatReference } from "../../domain/references.js";
3
+ import { isUsable } from "../../domain/relations.js";
3
4
  import { chatCoverage } from "../chat-coverage.js";
4
5
  import { LINK_PURPOSE, purposeRead, purposesOf } from "../project-purposes.js";
5
6
  import { canonicalProjectRef, linkedChatsOf, storedChatCount, } from "../stored-project-gathering.js";
@@ -24,7 +25,7 @@ const childrenOf = async (store, root, catalog) => {
24
25
  const below = [];
25
26
  for (const parent of level)
26
27
  for (const relation of await store.knowledge.relations(null, parent)) {
27
- if (!relation.confirmed || relation.kind !== "member-of" || relation.to !== parent)
28
+ if (!isUsable(relation.standing) || relation.kind !== "member-of" || relation.to !== parent)
28
29
  continue;
29
30
  if (!relation.from.startsWith("project:"))
30
31
  continue;
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { formatReference, parseReference } from "../domain/references.js";
3
+ import { isUsable } from "../domain/relations.js";
3
4
  import { chatCoverage } from "./chat-coverage.js";
4
5
  import { gatherProjectEvidence } from "./project-gathering.js";
5
6
  import { storedNeighbours } from "./project-gathering-around.js";
@@ -121,7 +122,7 @@ const proposedLinksOf = async (store, project) => {
121
122
  })
122
123
  .sort((a, b) => Number(a.id) - Number(b.id));
123
124
  const legacy = (await store.knowledge.relations(null, project))
124
- .filter((one) => !one.confirmed && one.kind === "member-of" && one.to === project)
125
+ .filter((one) => one.standing === "proposed" && one.kind === "member-of" && one.to === project)
125
126
  .map((one) => ({ from: one.from, id: `link:${one.id}`, role: one.role, purpose: one.purpose }));
126
127
  return [...proposals, ...legacy];
127
128
  };
@@ -131,7 +132,7 @@ const memberRefsOf = async (store, project, includeProposed) => {
131
132
  return [];
132
133
  const confirmed = new Set();
133
134
  for (const relation of await store.knowledge.relations(null, project))
134
- if (relation.confirmed &&
135
+ if (isUsable(relation.standing) &&
135
136
  relation.kind === "member-of" &&
136
137
  relation.to === project &&
137
138
  /^person:.+/.test(relation.from))
@@ -180,7 +181,7 @@ export const linkedChatsOf = async (store, project, options = {}) => {
180
181
  return [];
181
182
  const chats = [];
182
183
  for (const relation of await store.knowledge.relations(null, project)) {
183
- if (!relation.confirmed || relation.kind !== "member-of" || relation.to !== project)
184
+ if (!isUsable(relation.standing) || relation.kind !== "member-of" || relation.to !== project)
184
185
  continue;
185
186
  const reference = chatOf(relation.from);
186
187
  if (reference)
@@ -1,4 +1,5 @@
1
1
  import type { StoreHealth } from "./health.js";
2
+ import type { DamageMark } from "./marks.js";
2
3
  /**
3
4
  * What a damaged store means, in the owner's words: one structure the CLIs render and the desktop app can show as it
4
5
  * is. Built from a health check only, so it never reads the damaged file again.
@@ -16,4 +17,5 @@ export interface DamageExplanation {
16
17
  * vectors, which a search by meaning computes again for any text that has none.
17
18
  */
18
19
  export declare const isDerivedTable: (table: string, searchIndexes: readonly string[]) => boolean;
19
- export declare const explainDamage: (health: StoreHealth, command: string) => DamageExplanation | null;
20
+ /** `mark`: a run saw the damage; the quick check reads too little to see it, so it alone can make a store damaged. */
21
+ export declare const explainDamage: (health: StoreHealth, command: string, mark?: DamageMark | null) => DamageExplanation | null;
@@ -8,8 +8,10 @@ export const isDerivedTable = (table, searchIndexes) => DERIVED.has(table) ||
8
8
  table.startsWith("vector_index_") ||
9
9
  searchIndexes.some((index) => table === index || table.startsWith(`${index}_`));
10
10
  const WIRECAT_UNITS = ["memo-*", "mail-*", "tg-*", "max-*", "wirecat-*"];
11
- export const explainDamage = (health, command) => {
12
- if (health.ok)
11
+ const seen = (mark) => `\`${mark.command}\` found the store damaged at ${mark.at} (${mark.error})`;
12
+ /** `mark`: a run saw the damage; the quick check reads too little to see it, so it alone can make a store damaged. */
13
+ export const explainDamage = (health, command, mark = null) => {
14
+ if (health.ok && !mark)
13
15
  return null;
14
16
  const indexNames = (health.searchIndexes ?? []).map((index) => index.name);
15
17
  const badIndexes = (health.searchIndexes ?? []).filter((index) => !index.ok).map((index) => index.name);
@@ -18,14 +20,17 @@ export const explainDamage = (health, command) => {
18
20
  const derived = [...new Set([...tables.filter((table) => isDerivedTable(table, indexNames)), ...badIndexes])];
19
21
  const unopened = health.error !== undefined;
20
22
  const json = (health.invalidJson ?? []).map(({ table, column }) => `${table}.${column}`);
21
- const what = unopened
22
- ? `the store file cannot be opened: ${health.error}`
23
- : health.checked === "quick"
24
- ? "the store file's header or schema is damaged"
25
- : `the store file is damaged: ${health.problems ?? 0} problems` +
26
- (sources.length ? ` in the data of ${named(sources)}` : "") +
27
- (derived.length ? `${sources.length ? ", and" : " in"} the search data of ${named(derived)}` : "") +
28
- (json.length ? `; values that are not valid JSON in ${named(json)}` : "");
23
+ const checked = health.ok
24
+ ? `${seen(mark)}; the quick check reads too little to see it, and a deep check that passes clears it`
25
+ : unopened
26
+ ? `the store file cannot be opened: ${health.error}`
27
+ : health.checked === "quick"
28
+ ? "the store file's header or schema is damaged"
29
+ : `the store file is damaged: ${health.problems ?? 0} problems` +
30
+ (sources.length ? ` in the data of ${named(sources)}` : "") +
31
+ (derived.length ? `${sources.length ? ", and" : " in"} the search data of ${named(derived)}` : "") +
32
+ (json.length ? `; values that are not valid JSON in ${named(json)}` : "");
33
+ const what = mark && !health.ok ? `${checked}; ${seen(mark)}` : checked;
29
34
  const impact = [
30
35
  ...(sources.length
31
36
  ? [`some rows of ${named(sources)} cannot be read; a recovery keeps every row it can read and names the rest`]
@@ -36,7 +41,9 @@ export const explainDamage = (health, command) => {
36
41
  ...(json.length
37
42
  ? [`a read of a row with a broken JSON value fails ("malformed JSON"); a recovery clears those values`]
38
43
  : []),
39
- "reads that do not touch a damaged page work; a write that touches one fails until the store is recovered",
44
+ mark
45
+ ? "reads that do not touch a damaged page work; every command that writes the store refuses until it is recovered"
46
+ : "reads that do not touch a damaged page work; a write that touches one fails until the store is recovered",
40
47
  ];
41
48
  return {
42
49
  what,
@@ -49,7 +56,7 @@ export const explainDamage = (health, command) => {
49
56
  `journalctl --user ${WIRECAT_UNITS.map((unit) => `-u '${unit}'`).join(" ")} --since -14d | grep -i -e malformed -e corrupt -e 'disk full'`,
50
57
  "journalctl -k --since -14d | grep -i -e 'I/O error' -e nvme -e ata",
51
58
  `df -h ${health.path.replace(/\/[^/]*$/, "")}`,
52
- ...(health.checked === "quick" ? [`${command} store recover`] : []),
59
+ ...(health.checked === "quick" || health.ok ? [`${command} store recover`] : []),
53
60
  ],
54
61
  impact,
55
62
  externalUnaffected: "only this computer's copy is damaged: Telegram, MAX, the mail servers and Google Drive keep their own data, " +
@@ -1,6 +1,7 @@
1
1
  import { realpathSync, statSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
3
  import { CliError } from "@wirecat/cli-base";
4
+ import { damagedFile } from "../../errors/failures.js";
4
5
  import { MIGRATIONS, migrate } from "../migrations.js";
5
6
  import { applyTransfer } from "../sqlite/document-transfer/apply.js";
6
7
  import { planTransfer } from "../sqlite/document-transfer/plan.js";
@@ -75,6 +76,9 @@ const openPreviewTarget = async (path) => {
75
76
  };
76
77
  export const previewDocumentTransfer = async (options) => {
77
78
  const location = locations(options);
79
+ return damagedFile([location.source, location.destination], () => previewWith(location, options));
80
+ };
81
+ const previewWith = async (location, options) => {
78
82
  const source = await openSource(location.source);
79
83
  try {
80
84
  const target = await openPreviewTarget(location.destination);
@@ -93,6 +97,9 @@ export const applyDocumentTransfer = async (options) => {
93
97
  if (!/^[a-f0-9]{64}$/.test(options.expected_fingerprint))
94
98
  throw new CliError("validation_error", "apply requires the fingerprint returned by a transfer preview");
95
99
  const location = locations(options);
100
+ return damagedFile([location.source, location.destination], () => applyWith(location, options));
101
+ };
102
+ const applyWith = async (location, options) => {
96
103
  const source = await openSource(location.source);
97
104
  try {
98
105
  const snapshot = transferSnapshot(source.database, options.collection);
@@ -23,6 +23,7 @@ export { storeClients } from "./sqlite/clients.js";
23
23
  export { CHAT_LIST_KEY, type ChatCompleteness, type ChatCoverage, fetchedKey, historyStartKey, } from "./sqlite/completeness.js";
24
24
  export { CONVERSATION_COLUMNS } from "./sqlite/conversations.js";
25
25
  export type { CounterTarget } from "./sqlite/counters.js";
26
+ export { crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting } from "./sqlite/crm-settings.js";
26
27
  export { type EmailMarks, MAIL_AGENDA_COLUMNS, type MarkedEmail, type NewestEmail, type ThreadActivity, } from "./sqlite/email-activity.js";
27
28
  export { messageOfEmail, threadConversation } from "./sqlite/emails.js";
28
29
  export { orphanPointers } from "./sqlite/entity-types.js";
@@ -6,6 +6,7 @@ export { CHAT_COLUMNS, TRACKED_CHAT_COLUMNS, titlePart } from "./sqlite/chats.js
6
6
  export { storeClients } from "./sqlite/clients.js";
7
7
  export { CHAT_LIST_KEY, fetchedKey, historyStartKey, } from "./sqlite/completeness.js";
8
8
  export { CONVERSATION_COLUMNS } from "./sqlite/conversations.js";
9
+ export { crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting } from "./sqlite/crm-settings.js";
9
10
  export { MAIL_AGENDA_COLUMNS, } from "./sqlite/email-activity.js";
10
11
  export { messageOfEmail, threadConversation } from "./sqlite/emails.js";
11
12
  export { orphanPointers } from "./sqlite/entity-types.js";
@@ -20,6 +20,7 @@ export { EVIDENCE_FINDINGS_KIND, type EvidenceFindingsBatch, type EvidenceFindin
20
20
  export { type DamagedTable, type InvalidJson, QUICK_HEALTH_CHECKS, type SearchIndexHealth, type StoreHealth, storeHealth, } from "./health.js";
21
21
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
22
22
  export { MAIL_FINDINGS_KIND, type MailFindingsBatch, type MailFindingsCheck, type MailFindingsStore, } from "./mail-findings.js";
23
+ export { clearDamageMark, type DamageMark, damageMarkPath, type HealthMark, healthMarkPath, markStoreDamaged, readDamageMark, readHealthMark, recordDeepCheck, } from "./marks.js";
23
24
  export type { MeetingFindingsBatch, MeetingFindingsStore } from "./meeting-findings.js";
24
25
  export { MIGRATIONS, type Migration, migrate } from "./migrations.js";
25
26
  export { openCache } from "./open.js";
@@ -37,7 +38,8 @@ export type { BotUpdate, BotUpdateStore } from "./sqlite/bot-updates.js";
37
38
  export type { CatalogActor, CatalogEntry, CatalogInput, CatalogQuery, CatalogStore } from "./sqlite/catalog.js";
38
39
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
39
40
  export type { ChatMetadata } from "./sqlite/chats.js";
40
- export { type CrmCopies, type CrmSaved, type CrmSkipped, crmIdentityId } from "./sqlite/crm.js";
41
+ export { type CrmCopies, type CrmRelationIssue, type CrmSaved, type CrmSkipped, crmIdentityId } from "./sqlite/crm.js";
42
+ export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, crmSettingKey, } from "./sqlite/crm-settings.js";
41
43
  export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, } from "./sqlite/deals.js";
42
44
  export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
43
45
  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";
@@ -63,7 +65,11 @@ export type { Order, OrderFilter, OrderInput, OrdersStore } from "./sqlite/order
63
65
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
64
66
  export { assertGenericAction, PROPOSAL_STATUSES, type ProposalInput, type ProposedAction, type ProposedActionsStore, proposerOfAction, } from "./sqlite/proposed-actions.js";
65
67
  export type { RecordKey, RecordOutcome, RecordStore, RecordsWritten, SourceRecord, } from "./sqlite/records.js";
68
+ export type { RelationFilter, RelationList, RelationListItem } from "./sqlite/relation-list.js";
66
69
  export type { LinkDecision, RelationUpdate } from "./sqlite/relation-proposals.js";
70
+ export type { RelationReads } from "./sqlite/relation-reads.js";
71
+ export type { RelationRole, RelationRoles } from "./sqlite/relation-roles.js";
72
+ export type { RelationsStore, ReportedIssue, ReportedRelation, ReportedScope, ReportedSync, } from "./sqlite/reported-relations.js";
67
73
  export { fillSearchIndex, resetSearchIndex, type SearchIndexFill, type SearchIndexState, searchIndexState, } from "./sqlite/search-index.js";
68
74
  export type { SyncStateSave } from "./sqlite/sync.js";
69
75
  export type { TagCreationOptions, TagCreationReview } from "./sqlite/tag-creation.js";
@@ -12,6 +12,7 @@ export { EVIDENCE_FINDINGS_KIND, validateEvidenceFindings, } from "./evidence-fi
12
12
  export { QUICK_HEALTH_CHECKS, storeHealth, } from "./health.js";
13
13
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
14
14
  export { MAIL_FINDINGS_KIND, } from "./mail-findings.js";
15
+ export { clearDamageMark, damageMarkPath, healthMarkPath, markStoreDamaged, readDamageMark, readHealthMark, recordDeepCheck, } from "./marks.js";
15
16
  export { MIGRATIONS, migrate } from "./migrations.js";
16
17
  export { openCache } from "./open.js";
17
18
  export { storePath } from "./path.js";
@@ -24,6 +25,7 @@ export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
24
25
  export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
25
26
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
26
27
  export { crmIdentityId } from "./sqlite/crm.js";
28
+ export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
27
29
  export { EVENT_FIELDS, } from "./sqlite/event-search.js";
28
30
  export { IMPORTED_DOCUMENT_QUERY } from "./sqlite/imported-documents.js";
29
31
  export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js";
@@ -0,0 +1,57 @@
1
+ import type { StoreHealth } from "./health.js";
2
+ /**
3
+ * Both marks live beside the store, not in it: the store may be the file that cannot be read. Each holds no content,
4
+ * only times, command names and SQLite's own message.
5
+ */
6
+ export declare const damageMarkPath: (store: string) => string;
7
+ export declare const healthMarkPath: (store: string) => string;
8
+ /** A run saw SQLite say the store is damaged. Every writable open refuses while it names the file in place. */
9
+ export interface DamageMark {
10
+ at: string;
11
+ command: string;
12
+ cli_version?: string;
13
+ run_id?: string;
14
+ error: string;
15
+ /** The file it was seen in: a store restored, reset or recovered since is another file, and the mark is stale. */
16
+ inode: number;
17
+ }
18
+ /** The newest deep check of the store, and the time of the newest one that passed: the last known good. */
19
+ export interface HealthMark {
20
+ checked_at: string;
21
+ ok: boolean;
22
+ problems: number;
23
+ schema: number | null;
24
+ cli: string;
25
+ cli_version?: string;
26
+ last_ok_at: string | null;
27
+ }
28
+ /**
29
+ * Leaves the damage mark when `error` is SQLite saying the store is damaged; the first sighting is kept. Never
30
+ * throws: the failure being reported matters more than the mark.
31
+ */
32
+ export declare const markStoreDamaged: (error: unknown, { store, command, version, runId, now, }: {
33
+ store: string;
34
+ command: string;
35
+ version?: string;
36
+ runId?: string;
37
+ now?: () => number;
38
+ }) => boolean;
39
+ /** The mark, or null; a mark left by another file at this path is removed. An unreadable mark still counts. */
40
+ export declare const readDamageMark: (store: string) => DamageMark | null;
41
+ export declare const clearDamageMark: (store: string) => void;
42
+ /** Thrown by a writable open of a store a run found damaged, so timers fail fast instead of writing into it. */
43
+ export declare const refuseDamagedStore: (store: string, cli?: string) => void;
44
+ export declare const readHealthMark: (store: string) => HealthMark | null;
45
+ /**
46
+ * Records a deep check of the store. One that passed also removes the damage mark: the file reads whole. Returns the
47
+ * mark it replaced, whose `last_ok_at` is the last known good before this check, and the damage mark it removed.
48
+ */
49
+ export declare const recordDeepCheck: (store: string, health: Pick<StoreHealth, "ok" | "problems">, { cli, version, schema, now, }: {
50
+ cli: string;
51
+ version?: string;
52
+ schema: number | null;
53
+ now?: () => number;
54
+ }) => {
55
+ previous: HealthMark | null;
56
+ cleared: DamageMark | null;
57
+ };
@@ -0,0 +1,121 @@
1
+ import { readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { isCliFailure, isStoreDamage } from "../errors/failures.js";
4
+ import { refuseOwnerStoreInTests } from "./path.js";
5
+ /**
6
+ * Both marks live beside the store, not in it: the store may be the file that cannot be read. Each holds no content,
7
+ * only times, command names and SQLite's own message.
8
+ */
9
+ export const damageMarkPath = (store) => `${store}.damaged.json`;
10
+ export const healthMarkPath = (store) => `${store}.health.json`;
11
+ const inodeOf = (store) => statSync(store, { throwIfNoEntry: false })?.ino;
12
+ const readJson = (path) => {
13
+ try {
14
+ return JSON.parse(readFileSync(path, "utf8"));
15
+ }
16
+ catch (error) {
17
+ if (error.code === "ENOENT")
18
+ return null;
19
+ throw error;
20
+ }
21
+ };
22
+ const ownerStoreInTests = (store) => {
23
+ try {
24
+ refuseOwnerStoreInTests(store);
25
+ return false;
26
+ }
27
+ catch {
28
+ return true;
29
+ }
30
+ };
31
+ /** SQLite's own failure under a `store.damaged` CliError, or the error itself; the mark's own refusal has none. */
32
+ const sqliteFailure = (error) => isCliFailure(error) && error.details?.reason === "store.damaged" ? error.cause : error;
33
+ /**
34
+ * Leaves the damage mark when `error` is SQLite saying the store is damaged; the first sighting is kept. Never
35
+ * throws: the failure being reported matters more than the mark.
36
+ */
37
+ export const markStoreDamaged = (error, { store, command, version, runId, now = Date.now, }) => {
38
+ const failure = sqliteFailure(error);
39
+ if (!isStoreDamage(failure) || ownerStoreInTests(store))
40
+ return false;
41
+ const inode = inodeOf(store);
42
+ if (inode === undefined)
43
+ return false;
44
+ const mark = {
45
+ at: new Date(now()).toISOString(),
46
+ command,
47
+ ...(version ? { cli_version: version } : {}),
48
+ ...(runId ? { run_id: runId } : {}),
49
+ error: failure.message.slice(0, 500),
50
+ inode,
51
+ };
52
+ try {
53
+ writeFileSync(damageMarkPath(store), `${JSON.stringify(mark, null, 2)}\n`, { flag: "wx", mode: 0o600 });
54
+ return true;
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ };
60
+ /** The mark, or null; a mark left by another file at this path is removed. An unreadable mark still counts. */
61
+ export const readDamageMark = (store) => {
62
+ const path = damageMarkPath(store);
63
+ let mark;
64
+ try {
65
+ mark = readJson(path);
66
+ }
67
+ catch {
68
+ return { at: "unknown", command: "unknown", error: `${path} cannot be read`, inode: inodeOf(store) ?? 0 };
69
+ }
70
+ if (mark === null)
71
+ return null;
72
+ if (mark.inode !== inodeOf(store)) {
73
+ clearDamageMark(store);
74
+ return null;
75
+ }
76
+ return mark;
77
+ };
78
+ export const clearDamageMark = (store) => rmSync(damageMarkPath(store), { force: true });
79
+ /** Thrown by a writable open of a store a run found damaged, so timers fail fast instead of writing into it. */
80
+ export const refuseDamagedStore = (store, cli) => {
81
+ const mark = readDamageMark(store);
82
+ if (!mark)
83
+ return;
84
+ throw new CliError("configuration_error", `the store was found damaged at ${mark.at} by \`${mark.command}\` (${mark.error}), so nothing writes to it until ` +
85
+ `it is recovered; \`${cli ?? "<cli>"} store recover\` says what is damaged and what to do`, { reason: "store.damaged" });
86
+ };
87
+ export const readHealthMark = (store) => {
88
+ try {
89
+ return readJson(healthMarkPath(store));
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ };
95
+ /**
96
+ * Records a deep check of the store. One that passed also removes the damage mark: the file reads whole. Returns the
97
+ * mark it replaced, whose `last_ok_at` is the last known good before this check, and the damage mark it removed.
98
+ */
99
+ export const recordDeepCheck = (store, health, { cli, version, schema, now = Date.now, }) => {
100
+ const previous = readHealthMark(store);
101
+ if (ownerStoreInTests(store))
102
+ return { previous, cleared: null };
103
+ const checkedAt = new Date(now()).toISOString();
104
+ const mark = {
105
+ checked_at: checkedAt,
106
+ ok: health.ok,
107
+ problems: health.problems ?? 0,
108
+ schema,
109
+ cli,
110
+ ...(version ? { cli_version: version } : {}),
111
+ last_ok_at: health.ok ? checkedAt : (previous?.last_ok_at ?? null),
112
+ };
113
+ const cleared = health.ok ? readDamageMark(store) : null;
114
+ try {
115
+ writeFileSync(healthMarkPath(store), `${JSON.stringify(mark, null, 2)}\n`, { mode: 0o600 });
116
+ }
117
+ catch { }
118
+ if (cleared)
119
+ clearDamageMark(store);
120
+ return { previous, cleared };
121
+ };
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { damagedFile } from "../../errors/failures.js";
2
3
  import { openStoreContext } from "../sqlite/open-store.js";
3
4
  import { SnapshotBudget } from "../sqlite/project-transfer/budget.js";
4
5
  import { previewAnnotationSnapshot } from "../sqlite/project-transfer/preview.js";
@@ -19,11 +20,15 @@ export const previewProjectAnnotationSnapshot = async (options) => {
19
20
  !Number.isSafeInteger(Number(options.project.slice(8))))
20
21
  throw new CliError("validation_error", "project preview project is a project:<safe integer id> reference");
21
22
  const budget = new SnapshotBudget(options.maxReadBytes ?? 4 * 1024 * 1024);
22
- const context = await openStoreContext({ path: options.target, env: options.env, readOnly: true });
23
- try {
24
- return previewAnnotationSnapshot(context.database, Number(options.project.slice(8)), snapshot, options.bindings, budget);
25
- }
26
- finally {
27
- context.database.close();
28
- }
23
+ const target = options.target;
24
+ const project = options.project;
25
+ return damagedFile([target], async () => {
26
+ const context = await openStoreContext({ path: target, env: options.env, readOnly: true });
27
+ try {
28
+ return previewAnnotationSnapshot(context.database, Number(project.slice(8)), snapshot, options.bindings, budget);
29
+ }
30
+ finally {
31
+ context.database.close();
32
+ }
33
+ });
29
34
  };