@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
package/CHANGELOG.md CHANGED
@@ -7,6 +7,165 @@ shape of this file.
7
7
 
8
8
  ## Unreleased
9
9
 
10
+ ## 0.606.0 — 08.11.2026
11
+
12
+ ### Added
13
+
14
+ - **Business relationships: `reports-to`, `customer-of` and `partner-of`, role lists, and a `standing` on every
15
+ relationship.** `knowledge.relate` takes a person reporting to a person, a person or organization buying from an
16
+ organization, and two partner organizations (stored once, the lower id first, whichever way they are named). A deal
17
+ or a lead may be a relationship's `from`, so its people are relationships too, and `influencer` joins the deal roles.
18
+ Each relationship answers `standing`: `confirmed`, `reported` (a source's, nobody confirmed it), `proposed` or
19
+ `ended`. The kinds, their ends and roles are one registry, `RELATIONS` (`src/domain/relations.ts`), exported with
20
+ `ORGANIZATION_ROLES`, `PROJECT_ROLES`, `standingOf` and `usableLink`.
21
+ - **`review --holder` gives each email the cursor and findings key that end the batch at it** (`email.cursor`,
22
+ `email.findings_key`). A reader that cuts the batch to fit, such as an agent's input, acknowledges the last email it
23
+ showed instead of the batch's end, so the mark never moves past mail it did not show. Held emails, older than
24
+ the mark, end the batch at the mark with a key of their own (`<holder>:<mark>-h<highest held id>`).
25
+ - **`@wirecat/cli-core/cli` exports `AGENT_INPUT_MAX_CHARS`**, the 60,000-character cut of an agent's input, so a
26
+ host that builds the input can stay under it and cut at its own boundaries.
27
+
28
+ - **Relationship links know the account that reported them, when they held, and their history (store version 56).**
29
+ `links` gains `account_id`, `starts_at`, `ends_at` and `deleted_at`; `link_revisions` keeps one row per change of a
30
+ relationship link (`added`, `changed`, `ended`, `confirmed`, `withdrawn`, `restored`, `rejected`, `removed`),
31
+ written by triggers, never for a change of `updated_at` alone and never for links of other kinds. A unique key on
32
+ relationship links (kind, ends, anchor, role, account) lets one pair hold several roles and keeps a source's claim
33
+ apart from the owner's; the migration folds duplicates onto the owner's row, keeps their metadata and re-points the
34
+ proposals that named a dropped row.
35
+
36
+ - **A CRM sync keeps the relationships the CRM reports, as a diff.** Contacts become `member-of` their companies (role
37
+ `contact`, the job title beside it), a deal's contacts keep their deal roles and its `assignee` is its `owner`, the
38
+ account's users are `member-of` its own companies as `employee` and, from the departments, `reports-to` their head.
39
+ What the CRM stops reporting is withdrawn, not deleted; a link the owner confirmed is never withdrawn, and one the
40
+ owner removed or rejected, role included, is not written again (`skipped_owner_rejected`). A deal that names a
41
+ contact not synced yet gets it on a later run. `CrmPerson.organizations`/`position`, `CrmItem.people[].primary`,
42
+ `CrmOrganization.own`/`type`, `CrmUser`, `CrmDepartment` and `CrmSource.users()`/`departments()` carry them, all
43
+ optional. The same diff is `store.relations.syncReported` for any source. The store settings
44
+ `crm.<provider>:<account>.links` (`reported` or `review`: new relationships wait as proposals) and
45
+ `crm.<provider>:<account>.company-types` (a company type means `customer-of`, `supplier` or `partner-of` the own
46
+ company) are offered by every CLI's `config`. `knowledge.setOwnOrganization` records the owner's own-company
47
+ mark, which no sync changes; `crmGapsOf` reads what the account's last sync could not list (`{ kind, reason, code?, scope?, message }`).
48
+ Every `CrmSource` call takes an optional `CrmCallContext`: `spend()` takes one budget unit per extra request and
49
+ stops the run as `partial` when it is spent; `gap()` reports what a call could not read without failing it.
50
+ - **A relationship keeps a job title and when it held.** `relate` and `updateRelation` take `position`, `startsAt`
51
+ and `endsAt` (UTC ms, the end after the start); relationships answer `position`, `startsAt` and `endsAt`.
52
+ `knowledge.endRelation(key, id, at, by)` ends one without removing it (standing `ended` from then); an agent's end
53
+ is a `relationship_update` proposal.
54
+ - **The owner adds his own roles to the organization, project and deal role lists.** `knowledge.roles(list)`,
55
+ `addRole(list, id, label?)` and `removeRole(list, id)`, kept in the store setting `relationships.roles.<list>`; a
56
+ role id is lowercase letters, digits and `-`. Built-in roles stay; a role a relationship still holds is not removed
57
+ (`relationship.role-in-use` with the count).
58
+ - **`knowledge.listRelations(filter)` filters and pages relationships and pending relationship proposals in SQL.**
59
+ By `kind`, `role`, `standing`, `from`, `to`, `about` (both ways, each row with `direction` and the inverse label),
60
+ `at`, `includeEnded`, `accounts` (a source's rows only from these; the owner's always) and `deniedKinds`; `limit`
61
+ and `page` with `hasMore`. Each row says its `source` (`link` or `proposal`) and `custom` for a stored role off its
62
+ list.
63
+
64
+ ### Changed — may break callers
65
+
66
+ - **Store version 56 raises `minCompatible` to 56: a build from before it refuses the store and asks to be upgraded.**
67
+ A build that knows no account on a link would write a CRM's people as the owner's again, or fail on the new unique
68
+ key. Bump every CLI the same day as this release.
69
+
70
+ - **A person's role on an organization, a project, a deal or a lead must be one of that relationship's roles.**
71
+ `relate` and `updateRelation` refuse any other with `relationship.role-unknown`, naming the roles it takes; a role
72
+ between other ends stays free text, and roles already stored are read as they are. `member-of` now joins only to an
73
+ organization or a project. What to do: map a free-text role to the closest listed one (a job title goes in
74
+ `metadata.position`, never in the role); memo's `author`, `lead` and `cto` examples and tests need it.
75
+ - **`KnowledgeRelation.standing` and the `relationship` entity's `standing` are required.** A caller that builds one
76
+ by hand adds it; `standingOf` derives it from the link.
77
+ - **A CRM's deal and lead people are `confirmed: false`, `standing: reported` (store version 56).** They were stored
78
+ confirmed, as if the owner had said so. They still count wherever confirmed relationships count (`usableLink`), and
79
+ a deal still lists them; a view that reads `confirmed: false` as "proposed" (memo's relationships list) should read
80
+ `standing` instead.
81
+ - **The owner's change to a relationship a CRM reported overrides it.** The first `updateRelation`, `endRelation` or
82
+ confirmed `relationship_update` on a reported link makes one owner link that overrides it (`metadata.overrides`);
83
+ later changes change that link in place. Reads show the override instead of the CRM's row, which its sync keeps
84
+ diffing; removing the override shows the CRM's row again. A role is checked against the current role lists when a
85
+ proposal is approved, and a role a pending proposal holds counts as in use.
86
+ - **`relate` with a role the pair does not hold yet makes a second relationship**, since one pair may hold several
87
+ roles; without a role it answers the pair's link as before. `updateRelation` to a role the pair already holds is
88
+ refused with `relationship.exists`.
89
+ - **Removing any relationship leaves a rejected proposal**, so neither a scan nor a source's sync brings it back; it
90
+ was so only for a link to a project or a suggestion.
91
+ - **A memory written as `proposed` with `supersedes` no longer retires the old one until it is confirmed**, the
92
+ owner's included. `store.memories.add` and `confirm` refuse superseding a memory that is already superseded
93
+ (`memory.already-superseded`), so two corrections of one memory cannot both stand. drive-cli writes every memory
94
+ `proposed`, so its `memories add --supersedes` now retires the old memory only when that memory's correction is
95
+ confirmed.
96
+
97
+ ### Fixed
98
+
99
+ - **The person a CRM contact or user makes takes its name.** Joined to the mail contact of its address first, it was
100
+ left with no name.
101
+ - **A holder's batch of held emails only no longer reuses the findings key of the run that set the mark**, which
102
+ refused its staging (`key-used`): it takes `-h<highest held id>`.
103
+ - **An agent's correction no longer retires the memory it corrects.** `store.memories.add({ supersedes })` marked the
104
+ old memory `superseded` as soon as the new one was written, even while the new one only waited as proposed. Now
105
+ `confirm` of the correction retires it; rejecting or removing the correction leaves it as it was. Retiring a
106
+ confirmed memory is the owner's alone, whatever `agent_decisions` says.
107
+
108
+ ## 0.605.0 — 07.11.2026
109
+
110
+ ### Added
111
+
112
+ - **A run that finds the store damaged stops every later write.** When a command fails with SQLite's "database disk
113
+ image is malformed", "file is not a database" or an fts5 corruption, the run leaves `<store>.damaged.json` beside
114
+ the store (when, which command and version, the run's id, SQLite's message). While it is there, every command that
115
+ opens the store to write refuses with `store.damaged` and names `<cli> store recover`, so scheduled syncs fail at
116
+ once instead of writing into a damaged file; reads still work. `doctor` and `store recover` show it. A deep check
117
+ that passes (`doctor --deep`, `store recover`), `store recover run`, `store restore` and `store reset` lift it.
118
+ `markStoreDamaged` from `@wirecat/cli-core/store` leaves it for a CLI that reports such a failure itself.
119
+ - **Every deep check is recorded beside the store as its last known good.** `doctor --deep`, `store recover` and the
120
+ check after `store recover run` write `<store>.health.json` (when, the result, the schema, the CLI and its version,
121
+ and `last_ok_at`, the newest check that passed); `doctor` and `store recover` answer `last_known_good` from it.
122
+ `storeSummary` takes the CLI's `version` for it.
123
+
124
+ ### Changed — may break callers
125
+
126
+ - **`personContext`, `contacts context`, `contacts prepare` and `events prepare` read only accounts of the asked
127
+ account's scope.** A personal account no longer reads a linked person's mail, messages, calendar events or recorded
128
+ meetings in work accounts, and a work account none in personal ones. To read both, pass
129
+ `scopes: ["personal", "work"]` in the options of `personContext`, or of `eventPreparation`. The answer's new
130
+ `accounts` lists every account read with its scope. The asked account must be in the store: a missing one, or an
131
+ `AccountKey.scope` that differs from the stored scope, is `not_found`.
132
+
133
+ ### Fixed
134
+
135
+ - **`scanProjectLinks` spreads from what it finds within one run.** A chat or person that scores the threshold or more
136
+ is used like a confirmed link for the `spreads` scorers (`member-chats`, `member-dialog`, `chat-senders`,
137
+ `mail-thread`), up to `MAX_HOPS` (4) times. One scan now reaches a member's dialogs and groups in every messenger
138
+ their identities name, where before it took one owner confirmation per step and never left the first messenger.
139
+ On a synthetic project shaped like the PMED run, recall after two rounds rose from 27 % to 93 % (all findable
140
+ links), precision from 100 % to 74 %, 5 false proposals, none by name only. A rejected pair is never spread from.
141
+ - **`chat-senders` (version 2) counts any message in a dialog or a chat of 10 people or fewer;** a bigger chat still
142
+ needs 5 in the window.
143
+ - **`member-dialog` (version 2) counts the scanned project in the member's projects** whether the member is confirmed
144
+ or only found, so a found member who is in another project weighs the same as a confirmed one.
145
+ - **A damaged store file is `configuration_error` (`store.damaged`), not a crash.** SQLite's "database disk image is
146
+ malformed" or "file is not a database", raised anywhere in a command or behind a wrapper's `cause`, was
147
+ `internal_error` (`command.crashed`), "this is a bug". It now says the store file is damaged and names
148
+ `<cli> store recover` where the CLI has it, else `<cli> doctor --deep`, else no command, on the CLI, over MCP and in
149
+ the run kept of it, whose frames stay SQLite's own; a scheduled run's failure banner shows the reason.
150
+ `storeDamaged(error, next?)` from `@wirecat/cli-core/cli` does the same for a CLI with its own failure handling. A
151
+ damaged file named for a document or project transfer is `validation_error` (`store.file-damaged`) naming that
152
+ file, and `store recover run` on a store whose header is damaged says it cannot recover it (`store.unreadable`).
153
+ - **A filesystem error is no longer read as a SQLite one.** `errno` counts as SQLite's code only on bun:sqlite's
154
+ `SQLiteError`: Windows' EIO (-4070) has SQLITE_NOTADB's low byte, and a busy check took a filesystem errno with
155
+ BUSY's low byte for a lock.
156
+ - **cli-core accepts cli-base 0.81 and 0.82** (peer range `>=0.80.7 <0.83.0`, developed against 0.82.0). memo moved to
157
+ cli-base 0.82.0, and the downstream parity check downgraded it to 0.80.7, whose option vocabulary lacks memo's
158
+ `--from-app` and `tasks --status`, so every cli-core pull request failed parity.
159
+ - **People the owner separated stay apart.** An owner's unlink was checked only for the two identities being joined,
160
+ but a join moves whole people: a third identity with the same email address, linked to one of them, carried both
161
+ back together. Now no automatic join — the same email address, an account's own identity joining the owner — merges
162
+ two people when the owner once moved anyone of one away from anyone of the other. An agent's link of one identity
163
+ (a confirmed mention, a meeting participant) back over such a separation is refused with the reason
164
+ `identity.separated`; the owner's own link still goes through. The exact-email join stays automatic otherwise.
165
+ - **A personal account's `contacts context` no longer shows a person's work mail.** One exact email address joins a
166
+ personal and a work contact into one person, and the context then read every account that had seen any of that
167
+ person's identities. Each linked identity now also lists `seenIn`, its accounts with their scope.
168
+
10
169
  ## 0.604.0 — 07.11.2026
11
170
 
12
171
  ### Added
@@ -1,5 +1,5 @@
1
1
  import type { EventDetails, EventStore } from "../meetings/index.js";
2
- import { type ContextEvent, type ContextMessage } from "../services/person-context.js";
2
+ import { type AccountScope, type ContextEvent, type ContextMessage } from "../services/person-context.js";
3
3
  import { type PersonMeetingContextItem } from "../services/person-meeting-context.js";
4
4
  import type { MessageStore } from "../store/store.js";
5
5
  import { type PersonOfEmail, type ReadAccount } from "./reads.js";
@@ -24,11 +24,13 @@ export interface PreparationOptions {
24
24
  limit?: number;
25
25
  /** ms: no message or meeting older. */
26
26
  since?: number;
27
+ /** The account scopes read; the calendar account's own scope when absent. */
28
+ scopes?: readonly AccountScope[];
27
29
  }
28
30
  /**
29
31
  * The stored evidence for one meeting: the event, and for each attendee other than the owner, their linked identities,
30
32
  * their latest messages and mail, the events and recorded meetings they shared with the owner. Reads the store only,
31
- * every account that saw each person (WC-ACCT-9), and writes nothing; the brief is the agent's.
33
+ * every account of the allowed scopes that saw each person (WC-ACCT-9), and writes nothing; the brief is the agent's.
32
34
  */
33
35
  export declare const eventPreparation: (details: EventDetails, options: PreparationOptions) => Promise<{
34
36
  event: {
@@ -1,6 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { parseMeetingReference } from "../meetings/index.js";
3
- import { readsOf, recordContext } from "../services/person-context.js";
3
+ import { readableAccounts, readsOf, recordContext, } from "../services/person-context.js";
4
4
  import { personMeetingContext } from "../services/person-meeting-context.js";
5
5
  import { accountsMeta, CALENDAR_UNTRUSTED_FIELDS, eventAnswer, eventOf, } from "./reads.js";
6
6
  export const PREPARE_MESSAGES = 5;
@@ -59,7 +59,7 @@ const UNTRUSTED = [
59
59
  /**
60
60
  * The stored evidence for one meeting: the event, and for each attendee other than the owner, their linked identities,
61
61
  * their latest messages and mail, the events and recorded meetings they shared with the owner. Reads the store only,
62
- * every account that saw each person (WC-ACCT-9), and writes nothing; the brief is the agent's.
62
+ * every account of the allowed scopes that saw each person (WC-ACCT-9), and writes nothing; the brief is the agent's.
63
63
  */
64
64
  export const eventPreparation = async (details, options) => {
65
65
  const { messages: store, account, personOf, now, since } = options;
@@ -70,7 +70,7 @@ export const eventPreparation = async (details, options) => {
70
70
  .sort((a, b) => Number(b.organizer) - Number(a.organizer));
71
71
  const read = new Map([[nameOf(account.key), account.key]]);
72
72
  const issues = [];
73
- const stored = await store.accounts.storedAccounts();
73
+ const readable = await readableAccounts(store, account.key, options.scopes);
74
74
  let left = PREPARE_BYTES - size(shown);
75
75
  let truncated = others.length > PREPARE_PEOPLE;
76
76
  let pending = 0;
@@ -100,10 +100,10 @@ export const eventPreparation = async (details, options) => {
100
100
  people.push(nothing);
101
101
  continue;
102
102
  }
103
- const reads = readsOf(record, account.key);
103
+ const reads = readsOf(record, account.key, readable);
104
104
  for (const { key } of reads)
105
105
  read.set(nameOf(key), key);
106
- const context = await recordContext(store, record, reads, {
106
+ const context = await recordContext(store, record, reads, readable, {
107
107
  messages: limit,
108
108
  bytes: Math.min(left, PERSON_BYTES),
109
109
  now,
@@ -115,10 +115,10 @@ export const eventPreparation = async (details, options) => {
115
115
  reason: "chat.not-read",
116
116
  source: `${chat.provider}:${chat.account}/${chat.chatId}`,
117
117
  });
118
- const meetings = await meetingsWith(store, record.uid, stored, since);
118
+ const meetings = await meetingsWith(store, record.uid, readable, since);
119
119
  pending = Math.max(pending, meetings.pending);
120
120
  for (const id of meetings.accounts) {
121
- const one = stored.find((held) => held.id === id);
121
+ const one = readable.find((held) => held.id === id);
122
122
  if (one)
123
123
  read.set(nameOf(one), { provider: one.provider, account: one.account });
124
124
  }
@@ -151,7 +151,7 @@ export const eventPreparation = async (details, options) => {
151
151
  meta,
152
152
  };
153
153
  };
154
- /** Their latest recorded meetings in every stored account that saw them; none is not an error. */
154
+ /** Their latest recorded meetings in every account given that saw them; none is not an error. */
155
155
  const meetingsWith = async (store, uid, stored, since) => {
156
156
  const none = { items: [], hasMore: false, accounts: [], pending: 0 };
157
157
  if (!stored.length)
@@ -1,10 +1,10 @@
1
1
  export { AI_ENTRIES, AI_SETTING_KEYS, type AISettings, resolveAISettings } from "../analysis/settings.js";
2
- export type { AgentCli, AgentInput } from "../background/schedules.js";
2
+ export { AGENT_INPUT_MAX_CHARS, type AgentCli, type AgentInput } from "../background/schedules.js";
3
3
  export { parseDuration } from "../domain/duration.js";
4
4
  export { openOf, PROFILE_PLACEHOLDER, type ProfilesFor, type RefOpen, type RefSummary, refLabel, } from "../domain/ref-summaries.js";
5
5
  export { botTemplate } from "../entities/list-results.js";
6
6
  export { syncProgress } from "../entities/store-records.js";
7
- export { isCliFailure, isCommanderFailure } from "../errors/failures.js";
7
+ export { isCliFailure, isCommanderFailure, storeDamaged } from "../errors/failures.js";
8
8
  export { type AppErrors, failureContext } from "../errors/reasons.js";
9
9
  export { mailFindingFieldsHelp } from "../mail/findings.js";
10
10
  export { botInstructions } from "../mcp/bot/instructions.js";
package/dist/cli/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  export { AI_ENTRIES, AI_SETTING_KEYS, resolveAISettings } from "../analysis/settings.js";
2
+ export { AGENT_INPUT_MAX_CHARS } from "../background/schedules.js";
2
3
  export { parseDuration } from "../domain/duration.js";
3
4
  export { openOf, PROFILE_PLACEHOLDER, refLabel, } from "../domain/ref-summaries.js";
4
5
  export { botTemplate } from "../entities/list-results.js";
5
6
  export { syncProgress } from "../entities/store-records.js";
6
- export { isCliFailure, isCommanderFailure } from "../errors/failures.js";
7
+ export { isCliFailure, isCommanderFailure, storeDamaged } from "../errors/failures.js";
7
8
  export { failureContext } from "../errors/reasons.js";
8
9
  export { mailFindingFieldsHelp } from "../mail/findings.js";
9
10
  export { botInstructions } from "../mcp/bot/instructions.js";
@@ -102,8 +102,9 @@ export const contactsCommand = (messenger) => {
102
102
  output: { entity: "contact_context" },
103
103
  })
104
104
  .summary("what the local archive knows about a person")
105
- .description("what the store holds about one person, in every messenger linked to them: shared chats, the last " +
106
- "messages each way, their recent messages, where others mentioned them — never connects")
105
+ .description("what the store holds about one person, in every messenger linked to them, read only in accounts of this " +
106
+ "account's scope (personal or work): shared chats, the last messages each way, their recent messages, " +
107
+ "where others mentioned them — never connects")
107
108
  .argument("<person>", "their id, @username, or part of their name")
108
109
  .option("--limit <n>", `at most this many messages in each list; ${CONTEXT_MESSAGES} if not given`, positiveCount("--limit"))
109
110
  .option("--since-time <time>", "nothing older than this ISO 8601 time, or 2h / 1d ago")
@@ -59,13 +59,20 @@ export const DOCTOR_DEEP_OPTION = "also read every page of the store and check e
59
59
  /** The shared doctor stays quick; `store recover` is its deep check, and a CLI may add `--deep` to its own doctor. */
60
60
  const summaryOptions = (command, app) => ({
61
61
  deep: command.opts().deep === true,
62
- command: app,
62
+ command: app.command,
63
+ version: app.version,
63
64
  });
64
65
  /** The plain-words account of a damaged store, under the answer. */
65
66
  export const damageNotes = (store) => {
66
- const damage = store
67
- ?.damage;
68
- return damage ? [damage.what, damage.external_unaffected, ...damage.steps.map((step) => `next: ${step}`)] : [];
67
+ const { damage, damage_mark_cleared: cleared } = store ?? {};
68
+ return [
69
+ ...(cleared
70
+ ? [
71
+ `the deep check passed, so writes are allowed again: \`${cleared.command}\` had found the store damaged at ${cleared.at}`,
72
+ ]
73
+ : []),
74
+ ...(damage ? [damage.what, damage.external_unaffected, ...damage.steps.map((step) => `next: ${step}`)] : []),
75
+ ];
69
76
  };
70
77
  const INCLUDES = [
71
78
  "the version, the runtime and the operating system",
@@ -163,7 +170,7 @@ const diagnose = async (command, messenger) => {
163
170
  cli,
164
171
  config: { path, found: existsSync(path), issues: [] },
165
172
  settings: { error: messageOf(error) },
166
- store: snakeKeys(await storeSummary(env, summaryOptions(command, app.command))),
173
+ store: snakeKeys(await storeSummary(env, summaryOptions(command, app))),
167
174
  runs: { directory: runsDirFor(app, env), kept: listRuns(runsDirFor(app, env)).length },
168
175
  files: filesReport(files),
169
176
  },
@@ -188,7 +195,7 @@ const diagnose = async (command, messenger) => {
188
195
  cli,
189
196
  profile: null,
190
197
  config,
191
- store: snakeKeys(await storeSummary(env, summaryOptions(command, app.command))),
198
+ store: snakeKeys(await storeSummary(env, summaryOptions(command, app))),
192
199
  readers: engineStates(),
193
200
  runs: { directory: runsDirFor(app, env), kept: listRuns(runsDirFor(app, env)).length },
194
201
  files: filesReport(files),
@@ -224,7 +231,7 @@ const diagnose = async (command, messenger) => {
224
231
  account: { remembered: account?.account ?? null },
225
232
  // A session file on disk says nothing about whether the messenger still accepts it.
226
233
  login: { state: "not checked" },
227
- store: snakeKeys(await storeSummary(env, summaryOptions(command, app.command))),
234
+ store: snakeKeys(await storeSummary(env, summaryOptions(command, app))),
228
235
  readers: engineStates(),
229
236
  sends: sendsState(new SendJournal(sendsPathFor(app, profile, env))),
230
237
  flood: floodState(new FloodMemory(flood)),
@@ -3,11 +3,13 @@ import type { CacheDatabase } from "../../store/driver.js";
3
3
  import type { Messenger } from "./context.js";
4
4
  /**
5
5
  * `doctor`'s short summary of the store. Must answer for a broken file, so an error is a field. `health` is the quick
6
- * check unless `deep`; `damage` says in plain words what a failed one means and what to run.
6
+ * check unless `deep`; `damage` says in plain words what a failed one means, or what a run that found the store
7
+ * damaged saw, and what to run. A deep check is recorded beside the store as the last known good.
7
8
  */
8
- export declare const storeSummary: (env: NodeJS.ProcessEnv, { deep, command }?: {
9
+ export declare const storeSummary: (env: NodeJS.ProcessEnv, { deep, command, version }?: {
9
10
  deep?: boolean;
10
11
  command?: string;
12
+ version?: string;
11
13
  }) => Promise<{
12
14
  path: string;
13
15
  exists: boolean;
@@ -22,6 +24,21 @@ export declare const storeSummary: (env: NodeJS.ProcessEnv, { deep, command }?:
22
24
  invalidJson?: import("../../store/health.js").InvalidJson[] | undefined;
23
25
  damagedSearchIndexes?: string[] | undefined;
24
26
  };
27
+ lastKnownGood: string | null;
28
+ damageMark?: {
29
+ at: string;
30
+ command: string;
31
+ cli_version?: string;
32
+ run_id?: string;
33
+ error: string;
34
+ } | undefined;
35
+ damageMarkCleared?: {
36
+ at: string;
37
+ command: string;
38
+ cli_version?: string;
39
+ run_id?: string;
40
+ error: string;
41
+ } | undefined;
25
42
  damage?: import("../../store/damage.js").DamageExplanation | undefined;
26
43
  path: string;
27
44
  exists: boolean;
@@ -41,6 +58,21 @@ export declare const storeSummary: (env: NodeJS.ProcessEnv, { deep, command }?:
41
58
  invalidJson?: import("../../store/health.js").InvalidJson[] | undefined;
42
59
  damagedSearchIndexes?: string[] | undefined;
43
60
  };
61
+ lastKnownGood: string | null;
62
+ damageMark?: {
63
+ at: string;
64
+ command: string;
65
+ cli_version?: string;
66
+ run_id?: string;
67
+ error: string;
68
+ } | undefined;
69
+ damageMarkCleared?: {
70
+ at: string;
71
+ command: string;
72
+ cli_version?: string;
73
+ run_id?: string;
74
+ error: string;
75
+ } | undefined;
44
76
  damage?: import("../../store/damage.js").DamageExplanation | undefined;
45
77
  path: string;
46
78
  exists: boolean;
@@ -10,6 +10,7 @@ import { isSealed, sealFile, unsealFile } from "../../sealed.js";
10
10
  import { fileSchemaOf, SPEAKS, writableBy } from "../../store/compatibility.js";
11
11
  import { explainDamage } from "../../store/damage.js";
12
12
  import { QUICK_HEALTH_CHECKS, storeHealth } from "../../store/health.js";
13
+ import { readDamageMark, readHealthMark, recordDeepCheck } from "../../store/marks.js";
13
14
  import { migrate } from "../../store/migrations.js";
14
15
  import { openCache } from "../../store/open.js";
15
16
  import { storePath } from "../../store/path.js";
@@ -58,15 +59,35 @@ const readingOnly = async (path, read) => {
58
59
  database.close();
59
60
  }
60
61
  };
62
+ const withoutInode = ({ inode: _, ...mark }) => mark;
63
+ /** The schema version, or null when the file cannot say. */
64
+ const fileSchema = async (path) => {
65
+ try {
66
+ return await readingOnly(path, (database) => fileSchemaOf(database).version);
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ };
61
72
  /**
62
73
  * `doctor`'s short summary of the store. Must answer for a broken file, so an error is a field. `health` is the quick
63
- * check unless `deep`; `damage` says in plain words what a failed one means and what to run.
74
+ * check unless `deep`; `damage` says in plain words what a failed one means, or what a run that found the store
75
+ * damaged saw, and what to run. A deep check is recorded beside the store as the last known good.
64
76
  */
65
- export const storeSummary = async (env, { deep = false, command } = {}) => {
77
+ export const storeSummary = async (env, { deep = false, command, version } = {}) => {
66
78
  const path = storePath(env);
67
79
  if (!existsSync(path))
68
80
  return { path, exists: false };
69
81
  const checked = await storeHealth(path, { deep });
82
+ const recorded = deep
83
+ ? recordDeepCheck(path, checked, {
84
+ cli: command ?? "unknown",
85
+ ...(version ? { version } : {}),
86
+ schema: await fileSchema(path),
87
+ })
88
+ : null;
89
+ const mark = readDamageMark(path);
90
+ const lastKnownGood = readHealthMark(path)?.last_ok_at ?? null;
70
91
  const health = {
71
92
  checked: checked.checked,
72
93
  covers: deep ? "every page and every search index" : QUICK_HEALTH_CHECKS,
@@ -79,8 +100,14 @@ export const storeSummary = async (env, { deep = false, command } = {}) => {
79
100
  ? { damagedSearchIndexes: checked.searchIndexes.filter((index) => !index.ok).map((index) => index.name) }
80
101
  : {}),
81
102
  };
82
- const damage = command ? explainDamage(checked, command) : null;
83
- const healthOf = { health, ...(damage ? { damage } : {}) };
103
+ const damage = command ? explainDamage(checked, command, mark) : null;
104
+ const healthOf = {
105
+ health,
106
+ lastKnownGood,
107
+ ...(mark ? { damageMark: withoutInode(mark) } : {}),
108
+ ...(recorded?.cleared ? { damageMarkCleared: withoutInode(recorded.cleared) } : {}),
109
+ ...(damage ? { damage } : {}),
110
+ };
84
111
  try {
85
112
  return await reading(path, (database) => {
86
113
  const { version, writable } = schemaOf(database);
@@ -7,7 +7,7 @@ import { Command, Help } from "commander";
7
7
  import { relayCommand } from "../background/relay.js";
8
8
  import { failingNotice, scheduledRuns } from "../background/schedules.js";
9
9
  import { parseDuration } from "../domain/duration.js";
10
- import { isCliFailure, isCommanderFailure } from "../errors/failures.js";
10
+ import { isCliFailure, isCommanderFailure, storeDamaged } from "../errors/failures.js";
11
11
  import { failureContext } from "../errors/reasons.js";
12
12
  import { envName, readOnlyLockOf, readOnlyRefusal } from "../ports/app.js";
13
13
  import { recorded, wasSettled } from "../runs/recording.js";
@@ -721,9 +721,18 @@ const budgetSteps = (program, path, failure) => {
721
721
  ? tooLargeSteps(command, { maxBytes, neededBytes })
722
722
  : [];
723
723
  };
724
+ /** What a damaged store's message names: `store recover` where the CLI has it, else `doctor --deep`, else nothing. */
725
+ const damageStep = (program, cli) => {
726
+ if (commandAt(program, "store recover"))
727
+ return `${cli} store recover`;
728
+ const doctor = commandAt(program, "doctor");
729
+ return doctor?.options.some((option) => option.long === "--deep") ? `${cli} doctor --deep` : undefined;
730
+ };
724
731
  const failed = ({ app }, program, rest, error, settled, debug) => {
725
732
  const path = commandPath(program, program.args.length > 0 ? program.args : rest);
726
- const told = error instanceof NoProfileHere && !commandAt(program, "setup") ? error.withoutSetup(path) : error;
733
+ const told = error instanceof NoProfileHere && !commandAt(program, "setup")
734
+ ? error.withoutSetup(path)
735
+ : storeDamaged(error, damageStep(program, app.command));
727
736
  const failure = settled.settlementFailed && isCliFailure(told)
728
737
  ? new CliError(told.code, told.message, { ...told.details, settlement_failed: true })
729
738
  : told;
package/dist/cli/steps.js CHANGED
@@ -219,6 +219,12 @@ export const STEPS = defineSteps([
219
219
  ],
220
220
  why: "once the tasks these {shown} messages hold are opened, updated or closed, so the next review starts after them",
221
221
  },
222
+ {
223
+ id: "store.recover",
224
+ command: "store recover",
225
+ args: [],
226
+ why: "the store file is damaged; this says what is lost and the commands that recover it",
227
+ },
222
228
  {
223
229
  id: "search.meetings",
224
230
  command: "*",
@@ -273,7 +279,9 @@ export const failureSteps = (root, error) => {
273
279
  args: { model },
274
280
  }),
275
281
  ]
276
- : [];
282
+ : error.reason === "store.damaged"
283
+ ? [nextStep("store.recover", {})]
284
+ : [];
277
285
  return runnable(root, [...(error.next ?? []), ...own]);
278
286
  };
279
287
  /** Each command step judged by its command's effects: safe to run unasked only when it writes nothing remotely. */
@@ -1,6 +1,7 @@
1
1
  import { Command } from "commander";
2
2
  import { type DamageExplanation } from "../store/damage.js";
3
3
  import { type InvalidJson } from "../store/health.js";
4
+ import { type DamageMark } from "../store/marks.js";
4
5
  import { type RecoverOptions, type Recovery } from "../store/recover.js";
5
6
  export interface RecoveryCheck {
6
7
  path: string;
@@ -20,6 +21,10 @@ export interface RecoveryCheck {
20
21
  invalidJson?: InvalidJson[];
21
22
  rows?: Record<string, number | null>;
22
23
  explanation?: DamageExplanation | null;
24
+ /** What the run that found the store damaged saw; writes are refused while it stands. */
25
+ damageMark?: Omit<DamageMark, "inode"> | null;
26
+ /** When a deep check of the store last passed, as far as this computer recorded. */
27
+ lastKnownGood?: string | null;
23
28
  inUse?: {
24
29
  pid: number;
25
30
  name: string;
@@ -32,8 +37,11 @@ export interface RecoveryCheck {
32
37
  /** The commands to run, in order. */
33
38
  next: string[];
34
39
  }
35
- /** `store recover`: what is wrong with the store and what to run, reading every page; changes nothing. */
36
- export declare const storeRecoveryCheck: (env: NodeJS.ProcessEnv, command: string) => Promise<RecoveryCheck>;
40
+ /**
41
+ * `store recover`: what is wrong with the store and what to run, reading every page. Changes nothing in the store; it
42
+ * records the check beside it, and one that passes lifts the damage mark.
43
+ */
44
+ export declare const storeRecoveryCheck: (env: NodeJS.ProcessEnv, command: string, version?: string) => Promise<RecoveryCheck>;
37
45
  export type RecoveryRun = Omit<Recovery, "health" | "copyErrors"> & {
38
46
  /** `sqlite3` reported these while copying; most are rows that broke a constraint and were skipped. */
39
47
  copyErrors: number;
@@ -2,8 +2,10 @@ import { existsSync } from "node:fs";
2
2
  import { CliError } from "@wirecat/cli-base";
3
3
  import { annotate } from "@wirecat/cli-base/commands";
4
4
  import { Command } from "commander";
5
+ import { fileSchemaOf } from "../store/compatibility.js";
5
6
  import { explainDamage } from "../store/damage.js";
6
7
  import { storeHealth } from "../store/health.js";
8
+ import { readDamageMark, readHealthMark, recordDeepCheck } from "../store/marks.js";
7
9
  import { storePath } from "../store/path.js";
8
10
  import { activeTimers, recoverStore, sqlite3Program, storeHolders, tableRows, } from "../store/recover.js";
9
11
  import { openSqlite } from "../store/store.js";
@@ -25,16 +27,21 @@ const COUNTED = [
25
27
  "mentions",
26
28
  ];
27
29
  const stopTimers = (timers) => `systemctl --user stop ${timers.join(" ")}`;
28
- /** `store recover`: what is wrong with the store and what to run, reading every page; changes nothing. */
29
- export const storeRecoveryCheck = async (env, command) => {
30
+ /**
31
+ * `store recover`: what is wrong with the store and what to run, reading every page. Changes nothing in the store; it
32
+ * records the check beside it, and one that passes lifts the damage mark.
33
+ */
34
+ export const storeRecoveryCheck = async (env, command, version) => {
30
35
  const path = storePath(env);
31
36
  if (!existsSync(path))
32
37
  return { path, exists: false, ok: true, next: [] };
33
38
  const health = await storeHealth(path, { deep: true });
34
39
  let rows = {};
40
+ let schema = null;
35
41
  try {
36
42
  const { database } = await openSqlite(path, { readOnly: true });
37
43
  try {
44
+ schema = fileSchemaOf(database).version;
38
45
  const all = tableRows(database);
39
46
  rows = Object.fromEntries(COUNTED.filter((table) => table in all).map((table) => [table, all[table] ?? null]));
40
47
  }
@@ -43,7 +50,9 @@ export const storeRecoveryCheck = async (env, command) => {
43
50
  }
44
51
  }
45
52
  catch { }
46
- const explanation = explainDamage(health, command);
53
+ recordDeepCheck(path, health, { cli: command, ...(version ? { version } : {}), schema });
54
+ const mark = readDamageMark(path);
55
+ const explanation = explainDamage(health, command, mark);
47
56
  const inUse = storeHolders(path) ?? null;
48
57
  const timers = activeTimers() ?? null;
49
58
  const sqlite3 = sqlite3Program();
@@ -68,6 +77,8 @@ export const storeRecoveryCheck = async (env, command) => {
68
77
  invalidJson: health.invalidJson ?? [],
69
78
  rows,
70
79
  explanation,
80
+ damageMark: mark ? (({ inode: _, ...seen }) => seen)(mark) : null,
81
+ lastKnownGood: readHealthMark(path)?.last_ok_at ?? null,
71
82
  inUse,
72
83
  timers,
73
84
  sqlite3: { version: sqlite3.version, usable: sqlite3.usable },
@@ -119,6 +130,9 @@ export const recoveryNotes = (answer) => {
119
130
  const why = answer.explanation;
120
131
  return [
121
132
  ...(why ? [why.what, ...why.impact, why.externalUnaffected] : []),
133
+ answer.lastKnownGood
134
+ ? `the store last passed a deep check at ${answer.lastKnownGood}`
135
+ : "no deep check that passed is on record for this store",
122
136
  ...answer.next.map((line) => `next: ${line}`),
123
137
  ];
124
138
  };
@@ -129,7 +143,7 @@ export const storeRecoverCommand = ({ command, version }) => {
129
143
  .description("check every page and search index of the store, say what is damaged, what it means and the commands that recover it; changes nothing")
130
144
  .action(async function () {
131
145
  const output = outputFor(this);
132
- const answer = await storeRecoveryCheck(environmentOf(this).env ?? process.env, command);
146
+ const answer = await storeRecoveryCheck(environmentOf(this).env ?? process.env, command, version);
133
147
  renderAnswer(this, output, itemOf(snakeKeys(answer)));
134
148
  if (output.format === "pretty")
135
149
  for (const line of recoveryNotes(answer))