@getengram/cli 0.6.0 → 0.7.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 (208) hide show
  1. package/LICENSE +112 -0
  2. package/README.md +1 -1
  3. package/dist/commands/auth.d.ts.map +1 -1
  4. package/dist/commands/auth.js +38 -11
  5. package/dist/commands/auth.js.map +1 -1
  6. package/dist/commands/conversations.d.ts.map +1 -1
  7. package/dist/commands/conversations.js +8 -2
  8. package/dist/commands/conversations.js.map +1 -1
  9. package/dist/commands/exclude.d.ts.map +1 -1
  10. package/dist/commands/exclude.js +73 -21
  11. package/dist/commands/exclude.js.map +1 -1
  12. package/dist/commands/import.d.ts +30 -3
  13. package/dist/commands/import.d.ts.map +1 -1
  14. package/dist/commands/import.js +374 -45
  15. package/dist/commands/import.js.map +1 -1
  16. package/dist/commands/login.d.ts.map +1 -1
  17. package/dist/commands/login.js +144 -29
  18. package/dist/commands/login.js.map +1 -1
  19. package/dist/commands/search.js +2 -2
  20. package/dist/commands/search.js.map +1 -1
  21. package/dist/commands/status.d.ts +16 -0
  22. package/dist/commands/status.d.ts.map +1 -0
  23. package/dist/commands/status.js +51 -0
  24. package/dist/commands/status.js.map +1 -0
  25. package/dist/commands/store.d.ts.map +1 -1
  26. package/dist/commands/store.js +19 -3
  27. package/dist/commands/store.js.map +1 -1
  28. package/dist/commands/upgrade.d.ts +24 -0
  29. package/dist/commands/upgrade.d.ts.map +1 -1
  30. package/dist/commands/upgrade.js +64 -15
  31. package/dist/commands/upgrade.js.map +1 -1
  32. package/dist/commands/usage.d.ts +44 -0
  33. package/dist/commands/usage.d.ts.map +1 -1
  34. package/dist/commands/usage.js +79 -19
  35. package/dist/commands/usage.js.map +1 -1
  36. package/dist/commands/vault.d.ts +11 -2
  37. package/dist/commands/vault.d.ts.map +1 -1
  38. package/dist/commands/vault.js +372 -53
  39. package/dist/commands/vault.js.map +1 -1
  40. package/dist/config-file.d.ts +74 -0
  41. package/dist/config-file.d.ts.map +1 -0
  42. package/dist/config-file.js +152 -0
  43. package/dist/config-file.js.map +1 -0
  44. package/dist/config-guard.d.ts +96 -0
  45. package/dist/config-guard.d.ts.map +1 -0
  46. package/dist/config-guard.js +184 -0
  47. package/dist/config-guard.js.map +1 -0
  48. package/dist/config.d.ts +48 -4
  49. package/dist/config.d.ts.map +1 -1
  50. package/dist/config.js +101 -12
  51. package/dist/config.js.map +1 -1
  52. package/dist/daemon/as-root.d.ts +46 -0
  53. package/dist/daemon/as-root.d.ts.map +1 -0
  54. package/dist/daemon/as-root.js +64 -0
  55. package/dist/daemon/as-root.js.map +1 -0
  56. package/dist/daemon/backoff.d.ts +26 -0
  57. package/dist/daemon/backoff.d.ts.map +1 -0
  58. package/dist/daemon/backoff.js +37 -0
  59. package/dist/daemon/backoff.js.map +1 -0
  60. package/dist/daemon/codex-parser.d.ts +38 -4
  61. package/dist/daemon/codex-parser.d.ts.map +1 -1
  62. package/dist/daemon/codex-parser.js +111 -23
  63. package/dist/daemon/codex-parser.js.map +1 -1
  64. package/dist/daemon/command-path.d.ts +13 -0
  65. package/dist/daemon/command-path.d.ts.map +1 -0
  66. package/dist/daemon/command-path.js +35 -0
  67. package/dist/daemon/command-path.js.map +1 -0
  68. package/dist/daemon/commands.d.ts +153 -3
  69. package/dist/daemon/commands.d.ts.map +1 -1
  70. package/dist/daemon/commands.js +2775 -235
  71. package/dist/daemon/commands.js.map +1 -1
  72. package/dist/daemon/db.d.ts +255 -27
  73. package/dist/daemon/db.d.ts.map +1 -1
  74. package/dist/daemon/db.js +749 -53
  75. package/dist/daemon/db.js.map +1 -1
  76. package/dist/daemon/exclusions.d.ts +23 -3
  77. package/dist/daemon/exclusions.d.ts.map +1 -1
  78. package/dist/daemon/exclusions.js +91 -21
  79. package/dist/daemon/exclusions.js.map +1 -1
  80. package/dist/daemon/homebrew.d.ts +26 -0
  81. package/dist/daemon/homebrew.d.ts.map +1 -0
  82. package/dist/daemon/homebrew.js +43 -0
  83. package/dist/daemon/homebrew.js.map +1 -0
  84. package/dist/daemon/instance.d.ts +427 -0
  85. package/dist/daemon/instance.d.ts.map +1 -0
  86. package/dist/daemon/instance.js +1201 -0
  87. package/dist/daemon/instance.js.map +1 -0
  88. package/dist/daemon/key-source.d.ts +41 -0
  89. package/dist/daemon/key-source.d.ts.map +1 -0
  90. package/dist/daemon/key-source.js +89 -0
  91. package/dist/daemon/key-source.js.map +1 -0
  92. package/dist/daemon/launch.d.ts +56 -0
  93. package/dist/daemon/launch.d.ts.map +1 -0
  94. package/dist/daemon/launch.js +153 -0
  95. package/dist/daemon/launch.js.map +1 -0
  96. package/dist/daemon/launchd.d.ts +215 -0
  97. package/dist/daemon/launchd.d.ts.map +1 -0
  98. package/dist/daemon/launchd.js +527 -0
  99. package/dist/daemon/launchd.js.map +1 -0
  100. package/dist/daemon/login-start.d.ts +2 -0
  101. package/dist/daemon/login-start.d.ts.map +1 -0
  102. package/dist/daemon/login-start.js +25 -0
  103. package/dist/daemon/login-start.js.map +1 -0
  104. package/dist/daemon/ownership.d.ts +123 -0
  105. package/dist/daemon/ownership.d.ts.map +1 -0
  106. package/dist/daemon/ownership.js +245 -0
  107. package/dist/daemon/ownership.js.map +1 -0
  108. package/dist/daemon/package-runner.d.ts +28 -0
  109. package/dist/daemon/package-runner.d.ts.map +1 -0
  110. package/dist/daemon/package-runner.js +113 -0
  111. package/dist/daemon/package-runner.js.map +1 -0
  112. package/dist/daemon/parser.d.ts +50 -5
  113. package/dist/daemon/parser.d.ts.map +1 -1
  114. package/dist/daemon/parser.js +224 -47
  115. package/dist/daemon/parser.js.map +1 -1
  116. package/dist/daemon/powershell.d.ts +25 -0
  117. package/dist/daemon/powershell.d.ts.map +1 -0
  118. package/dist/daemon/powershell.js +30 -0
  119. package/dist/daemon/powershell.js.map +1 -0
  120. package/dist/daemon/preflight.d.ts +0 -17
  121. package/dist/daemon/preflight.d.ts.map +1 -1
  122. package/dist/daemon/preflight.js +32 -6
  123. package/dist/daemon/preflight.js.map +1 -1
  124. package/dist/daemon/prune.d.ts +101 -0
  125. package/dist/daemon/prune.d.ts.map +1 -0
  126. package/dist/daemon/prune.js +287 -0
  127. package/dist/daemon/prune.js.map +1 -0
  128. package/dist/daemon/queue-error.d.ts +47 -0
  129. package/dist/daemon/queue-error.d.ts.map +1 -0
  130. package/dist/daemon/queue-error.js +59 -0
  131. package/dist/daemon/queue-error.js.map +1 -0
  132. package/dist/daemon/root-daemon.d.ts +60 -0
  133. package/dist/daemon/root-daemon.d.ts.map +1 -0
  134. package/dist/daemon/root-daemon.js +86 -0
  135. package/dist/daemon/root-daemon.js.map +1 -0
  136. package/dist/daemon/scoop.d.ts +52 -0
  137. package/dist/daemon/scoop.d.ts.map +1 -0
  138. package/dist/daemon/scoop.js +84 -0
  139. package/dist/daemon/scoop.js.map +1 -0
  140. package/dist/daemon/scrubber.d.ts +456 -0
  141. package/dist/daemon/scrubber.d.ts.map +1 -0
  142. package/dist/daemon/scrubber.js +994 -0
  143. package/dist/daemon/scrubber.js.map +1 -0
  144. package/dist/daemon/status.d.ts +306 -11
  145. package/dist/daemon/status.d.ts.map +1 -1
  146. package/dist/daemon/status.js +568 -43
  147. package/dist/daemon/status.js.map +1 -1
  148. package/dist/daemon/supervise.d.ts +78 -0
  149. package/dist/daemon/supervise.d.ts.map +1 -0
  150. package/dist/daemon/supervise.js +121 -0
  151. package/dist/daemon/supervise.js.map +1 -0
  152. package/dist/daemon/supervisor.d.ts +18 -0
  153. package/dist/daemon/supervisor.d.ts.map +1 -0
  154. package/dist/daemon/supervisor.js +56 -0
  155. package/dist/daemon/supervisor.js.map +1 -0
  156. package/dist/daemon/syncer.d.ts +382 -21
  157. package/dist/daemon/syncer.d.ts.map +1 -1
  158. package/dist/daemon/syncer.js +1448 -178
  159. package/dist/daemon/syncer.js.map +1 -1
  160. package/dist/daemon/systemd.d.ts +109 -0
  161. package/dist/daemon/systemd.d.ts.map +1 -0
  162. package/dist/daemon/systemd.js +363 -0
  163. package/dist/daemon/systemd.js.map +1 -0
  164. package/dist/daemon/types.d.ts +58 -6
  165. package/dist/daemon/types.d.ts.map +1 -1
  166. package/dist/daemon/vault-changed.d.ts +29 -0
  167. package/dist/daemon/vault-changed.d.ts.map +1 -0
  168. package/dist/daemon/vault-changed.js +47 -0
  169. package/dist/daemon/vault-changed.js.map +1 -0
  170. package/dist/daemon/vault-key-missing.d.ts +70 -0
  171. package/dist/daemon/vault-key-missing.d.ts.map +1 -0
  172. package/dist/daemon/vault-key-missing.js +125 -0
  173. package/dist/daemon/vault-key-missing.js.map +1 -0
  174. package/dist/daemon/watcher.d.ts +87 -4
  175. package/dist/daemon/watcher.d.ts.map +1 -1
  176. package/dist/daemon/watcher.js +286 -36
  177. package/dist/daemon/watcher.js.map +1 -1
  178. package/dist/daemon/worker-main.js +363 -51
  179. package/dist/daemon/worker-main.js.map +1 -1
  180. package/dist/daemon/worker.js +19 -1
  181. package/dist/daemon/worker.js.map +1 -1
  182. package/dist/import-resume.d.ts +163 -0
  183. package/dist/import-resume.d.ts.map +1 -0
  184. package/dist/import-resume.js +267 -0
  185. package/dist/import-resume.js.map +1 -0
  186. package/dist/index.js +242 -33
  187. package/dist/index.js.map +1 -1
  188. package/dist/message-bounds.d.ts +52 -0
  189. package/dist/message-bounds.d.ts.map +1 -0
  190. package/dist/message-bounds.js +157 -0
  191. package/dist/message-bounds.js.map +1 -0
  192. package/dist/output.d.ts +14 -0
  193. package/dist/output.d.ts.map +1 -1
  194. package/dist/output.js +33 -5
  195. package/dist/output.js.map +1 -1
  196. package/dist/private-files.d.ts +126 -0
  197. package/dist/private-files.d.ts.map +1 -0
  198. package/dist/private-files.js +372 -0
  199. package/dist/private-files.js.map +1 -0
  200. package/dist/server-url.d.ts +31 -0
  201. package/dist/server-url.d.ts.map +1 -0
  202. package/dist/server-url.js +47 -0
  203. package/dist/server-url.js.map +1 -0
  204. package/dist/vault-key.d.ts +122 -0
  205. package/dist/vault-key.d.ts.map +1 -0
  206. package/dist/vault-key.js +273 -0
  207. package/dist/vault-key.js.map +1 -0
  208. package/package.json +11 -12
@@ -1,6 +1,14 @@
1
- import { recordSuccess, recordFailure, classifyError } from "./status.js";
1
+ import { createHash } from "node:crypto";
2
+ import { recordSuccess, recordFailure, recordNextRetry, recordSignedIn, recordSignedOut, recordDeletesRefused, classifyError, isConversationGone, isNotFound, isScopeRefusal, } from "./status.js";
3
+ import { retryDelay, formatWait } from "./backoff.js";
2
4
  import { parseStorageFullError } from "../storage-error.js";
3
5
  import { isPathExcluded, detectOptOut } from "./exclusions.js";
6
+ import { queueing } from "./queue-error.js";
7
+ import { engramCommand } from "./package-runner.js";
8
+ import { plural } from "../output.js";
9
+ import { isDefaultServer, normalizeServer, sameServer } from "../server-url.js";
10
+ import { boundContent, stripBinaryPayloads } from "../message-bounds.js";
11
+ import { VaultKeyMismatch, VaultKeyUnreadable } from "../vault-key.js";
4
12
  // Claude Code transcript messages can be enormous (tool output dumps), and
5
13
  // the server does per-message work on append (R2 write, chunk, embed, index).
6
14
  // 200-message batches reliably exceeded the request timeout and wedged the
@@ -18,215 +26,1150 @@ const BILLING_BACKOFF_MS = [
18
26
  15 * 60_000, // 15 minutes
19
27
  60 * 60_000, // 1 hour (cap)
20
28
  ];
29
+ /**
30
+ * Backoff schedule for a full memory: 1min → 2min → 5min → 5min ... The user
31
+ * clears it, by upgrading or deleting conversations, and capture should
32
+ * resume within minutes of that, not an hour. Retrying is cheap: the server
33
+ * refuses the send before it writes anything.
34
+ */
35
+ const STORAGE_FULL_BACKOFF_MS = [60_000, 2 * 60_000, 5 * 60_000];
36
+ /**
37
+ * Pause schedule while the API key is rejected: 10min → 30min → 1hr → 1hr …
38
+ * (engram#587). A rejected key used to stop syncing until the daemon
39
+ * restarted, and nothing restarts it: `engram auth login` saves the new key
40
+ * and leaves this process running with the old one. Now the daemon reads
41
+ * the configured key every KEY_POLL_MS and switches to a new one at once;
42
+ * this schedule only paces retries of the same key, for a key that was
43
+ * refused for a while and accepted again.
44
+ */
45
+ const AUTH_RETRY_MS = [10 * 60_000, 30 * 60_000, 60 * 60_000];
46
+ /**
47
+ * How often the daemon reads the configured key (engram#594). A logout must
48
+ * stop sending within seconds, and a new key must be used without a
49
+ * restart. The read is of one small local file.
50
+ */
51
+ const KEY_POLL_MS = 2_000;
52
+ /**
53
+ * Retry schedule for asking the server which earlier keys are the current
54
+ * key's account's, when it can't answer (network, 5xx, rate limit).
55
+ */
56
+ const OWNERSHIP_RETRY_MS = [30_000, 2 * 60_000, 10 * 60_000];
57
+ /**
58
+ * How long a session that already has a conversation under an earlier key
59
+ * waits for that answer before it gets a conversation of its own under the
60
+ * current key. Without the wait, a rotated key would give every session it
61
+ * continues a second conversation in the same account. Past it, a server
62
+ * that can't answer mustn't hold captures back for good: the worst case is
63
+ * a session split across two conversations, never a lost message.
64
+ */
65
+ const OWNERSHIP_GATE_MS = 15 * 60_000;
66
+ /**
67
+ * The key fingerprint of a Syncer built with a fixed client and no
68
+ * KeySource (tests, and callers that manage the key themselves). Not a
69
+ * SHA-256, so the server is never asked about it.
70
+ */
71
+ export const FIXED_KEY_FP = "fixed";
72
+ /** What a real key's fingerprint looks like (keyFingerprint). */
73
+ const KEY_HASH = /^[0-9a-f]{64}$/;
74
+ /** An account on a server other than the default (accountFingerprint):
75
+ * its key's hash, then its server's tag. */
76
+ const SERVER_ACCOUNT = /^([0-9a-f]{64})@([0-9a-f]{32})$/;
77
+ /**
78
+ * The key's SHA-256 as lowercase hex (engram#594). It is the hash the server
79
+ * keeps of the key, so the server can say which earlier keys are the same
80
+ * account's. The key itself is never written to daemon.db.
81
+ */
82
+ export function keyFingerprint(key) {
83
+ return createHash("sha256").update(key).digest("hex");
84
+ }
85
+ /**
86
+ * What daemon.db records about the account a message was captured for
87
+ * (engram#594, engram#685). On the default server, the key's fingerprint
88
+ * (keyFingerprint), as before servers were recorded, so nothing recorded
89
+ * then changes. On any other server, the key's fingerprint followed by
90
+ * "@" and a tag of the server's address, so what is queued for one server
91
+ * is never sent to another. Neither the key nor the address is written.
92
+ */
93
+ export function accountFingerprint(account) {
94
+ const keyHash = keyFingerprint(account.key);
95
+ if (isDefaultServer(account.server))
96
+ return keyHash;
97
+ const tag = createHash("sha256").update(normalizeServer(account.server)).digest("hex").slice(0, 32);
98
+ return `${keyHash}@${tag}`;
99
+ }
100
+ /** Whether `a` and `b` are the same account: the same key, for the same
101
+ * server. */
102
+ export function sameAccount(a, b) {
103
+ if (!a || !b)
104
+ return a === b;
105
+ return a.key === b.key && sameServer(a.server, b.server);
106
+ }
107
+ /**
108
+ * Which of `others` (other account fingerprints in daemon.db) the server of
109
+ * the account `runFp` may be asked about, each with the key hash to ask
110
+ * with (checkOwnership). What it confirms is its account's is sent with
111
+ * that account (engram#685):
112
+ *
113
+ * - The default server: what was queued under another key for it, or
114
+ * before servers were recorded, as before. Never what was queued for
115
+ * another server.
116
+ * - Any other server: what was queued for that same server under another
117
+ * key. And, under any key in `unknownServer` (its own included), what
118
+ * was queued before servers were recorded (daemon.db version 4): then a
119
+ * key's fingerprint alone stood for whatever server was configured, so
120
+ * it may be this server's, and the server confirms the key is its
121
+ * account's before it moves. Never what was recorded for the default
122
+ * server: an answer from another server doesn't make it that server's.
123
+ */
124
+ export function ownershipCandidates(runFp, others, unknownServer) {
125
+ const run = SERVER_ACCOUNT.exec(runFp);
126
+ const candidates = [];
127
+ for (const fp of others) {
128
+ if (!run) {
129
+ if (KEY_HASH.test(fp))
130
+ candidates.push({ fp, keyHash: fp, unknownServerOnly: false });
131
+ continue;
132
+ }
133
+ const other = SERVER_ACCOUNT.exec(fp);
134
+ if (other) {
135
+ if (other[2] === run[2])
136
+ candidates.push({ fp, keyHash: other[1], unknownServerOnly: false });
137
+ }
138
+ else if (KEY_HASH.test(fp) && unknownServer.has(fp)) {
139
+ candidates.push({ fp, keyHash: fp, unknownServerOnly: true });
140
+ }
141
+ }
142
+ return candidates;
143
+ }
144
+ /** A settled promise, for the paths of onMessages that have nothing left to do. */
145
+ const DONE = Promise.resolve();
146
+ function freshOwnership() {
147
+ return { answered: false, firstAskedAt: 0, retryAt: 0, step: 0 };
148
+ }
149
+ /** Retry schedule for one session whose conversation create failed with an
150
+ * ordinary error (network, 5xx, rejected input). Its messages stay queued
151
+ * in daemon.db throughout — this only paces the retries. */
152
+ const CREATE_RETRY_MS = [30_000, 2 * 60_000, 10 * 60_000];
153
+ /**
154
+ * After Engram answers that it doesn't have a conversation (engram#593),
155
+ * when it is asked again: the n-th such answer in a row is followed by a
156
+ * check after the n-th wait here, and the answer after the last of them is
157
+ * final (about four days after the first). A check sends one message. If
158
+ * that goes through, Engram has the conversation after all (a restore, or
159
+ * an answer that was wrong) and the rest follows as usual.
160
+ *
161
+ * Until then the conversation's messages, and any captured for its session
162
+ * later, stay in daemon.db and aren't sent. The conversation is never
163
+ * created again: the user may have deleted it, and a deleted conversation
164
+ * must not come back. Kept in daemon.db, so a restart doesn't start the
165
+ * schedule over.
166
+ */
167
+ export const GONE_RECHECK_MS = [
168
+ 10 * 60_000,
169
+ 60 * 60_000,
170
+ 6 * 60 * 60_000,
171
+ 24 * 60 * 60_000,
172
+ 72 * 60 * 60_000,
173
+ ];
174
+ /** When a conversation Engram said `checks` times it doesn't have, last at
175
+ * `checkedAt`, is checked again; null: never. */
176
+ function goneRecheckAt(checkedAt, checks) {
177
+ const wait = GONE_RECHECK_MS[checks - 1];
178
+ return wait === undefined ? null : checkedAt + wait;
179
+ }
21
180
  /**
22
181
  * Batches parsed messages and sends them to the Engram API.
23
182
  * If offline, messages sit in the SQLite queue and are retried
24
183
  * on the next flush cycle.
184
+ *
185
+ * Every queued message records the key it was captured under (engram#594),
186
+ * as a fingerprint, and is sent only with that key or with a key the server
187
+ * confirmed is the same account's (a rotated or re-issued key). The
188
+ * configured key is read every KEY_POLL_MS. A new key is used from the next
189
+ * request on; no key, after `engram auth logout`, stops capture and sending
190
+ * at once. Nothing queued is deleted either way: it waits on this machine
191
+ * until its account signs in again.
192
+ *
193
+ * While signed out, capture stops and each transcript's read offset stays
194
+ * where it was, so what is written meanwhile is read, and queued, for the
195
+ * next account that signs in.
25
196
  */
26
197
  export class Syncer {
198
+ scrubber;
199
+ keys;
27
200
  db;
28
- client;
201
+ /** The key in use; null while signed out. */
202
+ active;
203
+ /** The key captures are queued under (null: signed out). */
204
+ captureFp;
29
205
  timer = null;
30
- flushing = false;
31
- authFailed = false;
206
+ keyTimer = null;
207
+ running = null;
208
+ /** A read of the configured key in progress, shared by its callers. */
209
+ keyCheck = null;
210
+ /** stop() was called: capture doesn't start again, and a key change only
211
+ * stops sending. */
212
+ stopped = false;
213
+ capture = null;
214
+ capturing = false;
215
+ /** Paused because the API key was rejected: until when, and how many
216
+ * pauses in a row without a request going through. */
217
+ authHeldUntil = 0;
218
+ authHoldStep = 0;
219
+ /** The account configured when it was last read (undefined: none). */
220
+ currentAccount;
221
+ /** config.json hasn't been read since start (KeySource.unread): which
222
+ * account is configured isn't known yet. */
223
+ unread = false;
224
+ /** The fingerprint rows that belonged to no key were last handed to. */
225
+ claimedFor = null;
226
+ ownership = freshOwnership();
227
+ /** The sessions the ownership gate holds were logged, under this key. */
228
+ gateLogged = false;
229
+ /** The last message logged for each lasting problem, so a problem that
230
+ * lasts is logged once, not on every poll. */
231
+ problems = new Map();
32
232
  /** Billing backoff state */
33
233
  billingBackoffUntil = 0;
34
234
  billingBackoffStep = 0;
35
- /** Sessions awaiting conversation creation (deferred from parse time). */
36
- pendingSessions = new Map();
37
- constructor(db, client) {
235
+ /** Sessions whose conversation create failed: when to try again. The
236
+ * sessions themselves live in daemon.db (engram#370) — losing this map
237
+ * on a restart only means an earlier retry. */
238
+ createRetry = new Map();
239
+ /**
240
+ * Nothing is sent from this account until this time, after the server
241
+ * refused a request for when it came rather than for what it carried: a
242
+ * rate limit, or a pause for maintenance (engram#596). `throttleStep`
243
+ * counts such pauses in a row without a request going through.
244
+ */
245
+ throttledUntil = 0;
246
+ throttleStep = 0;
247
+ /** A maintenance pause is among those pauses. It holds only sends, so a
248
+ * create or a delete going through doesn't show it's over. */
249
+ throttlePaused = false;
250
+ /**
251
+ * Conversations whose last send failed in a way that passes on its own
252
+ * (the server out of reach, a timeout, an error on the server's side):
253
+ * when each is tried again (engram#596). Like createRetry, a restart only
254
+ * means an earlier retry; the rows themselves stay queued in daemon.db.
255
+ */
256
+ sendRetry = new Map();
257
+ /** Opt-out deletes that failed the same way: when each is tried again. */
258
+ deleteRetry = new Map();
259
+ /**
260
+ * The key in use may not delete conversations: the server refused an
261
+ * opt-out's delete for want of the 'delete' permission (engram#597). A
262
+ * key's permissions don't change, so its deletes are kept and not tried
263
+ * again with it: they used to be retried, and logged, for as long as the
264
+ * key was in use. A different key tries again, and so does a restart.
265
+ */
266
+ deletesRefused = false;
267
+ /** Rows orphaned by a pre-#370 daemon are adopted once per process. */
268
+ orphansAdopted = false;
269
+ /**
270
+ * Sends are waiting for the vault (engram#588), and why, as last said: the
271
+ * key can't be read (engram#677), it decrypts none of the vault's secrets
272
+ * (engram#694), or the vault isn't read yet. A new why is said too.
273
+ */
274
+ vaultHeld = null;
275
+ /** Per-conversation reduced batch size after a failed send (halves down to
276
+ * 1 so even a single pathological message eventually goes alone; restored
277
+ * to the full batch on the next success). */
278
+ batchOverride = new Map();
279
+ /**
280
+ * With `keys`, `client` is the client for `keys.current` (built from it
281
+ * when null), and no `keys.current` starts the Syncer signed out, or
282
+ * waiting for config.json (`keys.unread`). Without `keys`, `client`
283
+ * sends everything, under FIXED_KEY_FP.
284
+ */
285
+ constructor(db, client, scrubber = null, keys = null) {
286
+ this.scrubber = scrubber;
287
+ this.keys = keys;
38
288
  this.db = db;
39
- this.client = client;
289
+ if (!keys) {
290
+ if (!client)
291
+ throw new Error("Syncer needs a client or a KeySource");
292
+ this.active = { fp: FIXED_KEY_FP, client };
293
+ }
294
+ else if (keys.current) {
295
+ const account = keys.current;
296
+ this.active = {
297
+ fp: accountFingerprint(account),
298
+ client: client ?? keys.connect(account),
299
+ account,
300
+ };
301
+ this.currentAccount = account;
302
+ }
303
+ else {
304
+ this.active = null;
305
+ this.unread = keys.unread === true;
306
+ }
307
+ this.captureFp = this.active?.fp ?? null;
308
+ if (this.active)
309
+ this.claim(this.active);
310
+ }
311
+ /** Hand capture to the Syncer (engram#594), which runs it while a key is
312
+ * configured. Set before start(). */
313
+ setCaptureControl(control) {
314
+ this.capture = control;
315
+ }
316
+ /** Start syncing, and capturing while a key is configured. */
317
+ start() {
318
+ this.stopped = false;
319
+ if (this.active) {
320
+ if (this.keys)
321
+ recordSignedIn();
322
+ this.startCapture();
323
+ }
324
+ else {
325
+ recordSignedOut();
326
+ // Waiting for config.json was said when it couldn't be read.
327
+ if (!this.unread)
328
+ this.logSignedOut();
329
+ }
330
+ // flush() and checkKey() handle their own errors; the catch only keeps
331
+ // a failure in that handling from becoming an unhandled rejection.
332
+ this.timer ??= setInterval(() => {
333
+ this.flush().catch(() => { });
334
+ }, FLUSH_INTERVAL_MS);
335
+ if (this.keys) {
336
+ this.keyTimer ??= setInterval(() => {
337
+ this.checkKey().catch(() => { });
338
+ }, KEY_POLL_MS);
339
+ }
340
+ }
341
+ /**
342
+ * Stop capturing and syncing. Queued messages stay in daemon.db. A final
343
+ * flush() may follow; it sends only with the key still configured.
344
+ */
345
+ stop() {
346
+ this.stopped = true;
347
+ this.stopCapture(false);
348
+ if (this.timer) {
349
+ clearInterval(this.timer);
350
+ this.timer = null;
351
+ }
352
+ if (this.keyTimer) {
353
+ clearInterval(this.keyTimer);
354
+ this.keyTimer = null;
355
+ }
356
+ }
357
+ startCapture() {
358
+ if (this.capturing || this.stopped || !this.capture)
359
+ return;
360
+ this.capturing = true;
361
+ try {
362
+ this.capture.start();
363
+ }
364
+ catch (err) {
365
+ console.error(`[engram] starting capture failed: ${errorText(err)}`);
366
+ }
367
+ }
368
+ stopCapture(drain) {
369
+ if (!this.capturing || !this.capture)
370
+ return;
371
+ this.capturing = false;
372
+ try {
373
+ this.capture.stop(drain);
374
+ }
375
+ catch (err) {
376
+ console.error(`[engram] stopping capture failed: ${errorText(err)}`);
377
+ }
378
+ }
379
+ /**
380
+ * Read the configured account and act on a change (engram#594,
381
+ * engram#685): no key stops capture and sending at once, and a new key or
382
+ * server is used from the next request on. Calls made while a read is in
383
+ * progress share it.
384
+ */
385
+ checkKey() {
386
+ const keys = this.keys;
387
+ if (!keys)
388
+ return DONE;
389
+ this.keyCheck ??= this.readKey(keys).finally(() => {
390
+ this.keyCheck = null;
391
+ });
392
+ return this.keyCheck;
393
+ }
394
+ async readKey(keys) {
395
+ let account;
396
+ try {
397
+ account = (await keys.read()) ?? undefined;
398
+ }
399
+ catch (err) {
400
+ this.logProblem("key", `[engram] reading the API key failed (will retry): ${errorText(err)}`);
401
+ return;
402
+ }
403
+ if (account && !account.key)
404
+ account = undefined;
405
+ // config.json has been read: from now on no key is a signed-out daemon.
406
+ const firstRead = this.unread;
407
+ this.unread = false;
408
+ if (sameAccount(account, this.currentAccount)) {
409
+ this.problems.delete("key");
410
+ if (firstRead && !this.stopped)
411
+ this.logSignedOut();
412
+ return;
413
+ }
414
+ if (this.stopped) {
415
+ // Shutting down, and the account changed since it was last read:
416
+ // nothing more is sent for an account that is no longer configured,
417
+ // and capture doesn't start again.
418
+ this.active = null;
419
+ this.captureFp = null;
420
+ this.currentAccount = undefined;
421
+ return;
422
+ }
423
+ if (account === undefined)
424
+ this.signOut();
425
+ else
426
+ this.signIn(keys, account);
427
+ }
428
+ /** An account is configured that isn't the one in use: a sign-in, or a
429
+ * change of key, server or account. */
430
+ signIn(keys, account) {
431
+ const previous = this.active ? this.currentAccount : undefined;
432
+ // What was written for the account in use is read and queued for it
433
+ // first, scrubbed against the vault read through it.
434
+ this.stopCapture(true);
435
+ let run;
436
+ try {
437
+ run = { fp: accountFingerprint(account), client: keys.connect(account), account };
438
+ }
439
+ catch (err) {
440
+ // Another account is configured: nothing more is captured or sent
441
+ // for the one in use.
442
+ if (this.active)
443
+ this.deactivate();
444
+ this.logProblem("key", `[engram] the new API key can't be used yet (will retry): ${errorText(err)}`);
445
+ return;
446
+ }
447
+ this.active = run;
448
+ this.captureFp = run.fp;
449
+ this.currentAccount = account;
450
+ this.resetForNewKey();
451
+ this.problems.delete("key");
452
+ this.claim(run);
453
+ recordSignedIn();
454
+ this.startCapture();
455
+ // Never the server's address, which can carry credentials. What was
456
+ // queued for the previous account is said once the server has been
457
+ // asked about it (checkOwnership, logHeld).
458
+ console.log(!previous
459
+ ? "[engram] signed in — capture and sync resumed"
460
+ : previous.key === account.key
461
+ ? "[engram] the server in ~/.engram/config.json changed — capturing and sending to the new one from now on"
462
+ : sameServer(previous.server, account.server)
463
+ ? "[engram] new API key found — capturing and sending with it (messages queued under the previous key are sent only if it's the same account's)"
464
+ : "[engram] new API key and server found — capturing and sending with them from now on");
465
+ }
466
+ /** Stop capturing and sending under the key in use. Nothing queued is
467
+ * touched. */
468
+ deactivate() {
469
+ // What was written under the key is read and queued under it first,
470
+ // scrubbed against the vault read through it — so the vault is let go
471
+ // of only after.
472
+ this.stopCapture(true);
473
+ this.active = null;
474
+ this.captureFp = null;
475
+ this.currentAccount = undefined;
476
+ this.resetForNewKey();
477
+ try {
478
+ this.keys?.disconnect?.();
479
+ }
480
+ catch (err) {
481
+ console.error(`[engram] letting go of the previous API key failed: ${errorText(err)}`);
482
+ }
483
+ recordSignedOut();
484
+ }
485
+ /** No key is configured any more (`engram auth logout`). */
486
+ signOut() {
487
+ this.deactivate();
488
+ this.problems.delete("key");
489
+ this.logSignedOut();
490
+ }
491
+ logSignedOut() {
492
+ let queued = 0;
493
+ try {
494
+ queued = this.db.getHeldCount(null);
495
+ }
496
+ catch {
497
+ // The count only informs the line below.
498
+ }
499
+ console.log(`[engram] signed out — capture paused and nothing is sent; ${queued} queued message(s) ` +
500
+ `stay on this machine, to be sent only with their account's key. ` +
501
+ `Capture resumes when '${engramCommand("auth login")}' saves a key.`);
502
+ }
503
+ /** Forget what was learned under the previous key: its pauses, retry
504
+ * timers and batch sizes say nothing about the next one. */
505
+ resetForNewKey() {
506
+ this.authHeldUntil = 0;
507
+ this.authHoldStep = 0;
508
+ // The new key may belong to an account with room, and a held billing
509
+ // backoff would only delay finding out.
510
+ this.billingBackoffUntil = 0;
511
+ this.billingBackoffStep = 0;
512
+ // A rate limit is the account's, and the next key may be another's.
513
+ this.throttledUntil = 0;
514
+ this.throttleStep = 0;
515
+ this.throttlePaused = false;
516
+ this.createRetry.clear();
517
+ this.sendRetry.clear();
518
+ this.deleteRetry.clear();
519
+ // Another key's permissions are its own.
520
+ this.deletesRefused = false;
521
+ this.batchOverride.clear();
522
+ this.vaultHeld = null;
523
+ this.ownership = freshOwnership();
524
+ this.gateLogged = false;
525
+ // What was queued while no key was in use goes to the next key.
526
+ this.claimedFor = null;
527
+ }
528
+ /**
529
+ * Hand what belongs to no key to the key in use: rows queued before
530
+ * daemon.db recorded keys, or while no key was in use. Once per key; a
531
+ * failure is retried on the next flush.
532
+ */
533
+ claim(run) {
534
+ if (this.claimedFor === run.fp)
535
+ return true;
536
+ try {
537
+ this.db.claimLegacy(run.fp);
538
+ this.claimedFor = run.fp;
539
+ this.problems.delete("claim");
540
+ return true;
541
+ }
542
+ catch (err) {
543
+ this.logProblem("claim", `[engram] couldn't assign queued messages to this API key (will retry): ${errorText(err)}`);
544
+ return false;
545
+ }
546
+ }
547
+ logProblem(kind, msg) {
548
+ if (this.problems.get(kind) === msg)
549
+ return;
550
+ this.problems.set(kind, msg);
551
+ console.error(msg);
40
552
  }
41
553
  /**
42
554
  * Called by the parser when new messages are ready for a session.
43
- * Queues messages locally; conversation creation is deferred to flush time
44
- * to avoid blocking the parser on network calls.
555
+ * Queues them in daemon.db before it returns; creating the conversation
556
+ * is deferred to flush time, so the parser never waits on the network.
557
+ *
558
+ * A failure to queue throws a QueueWriteError, synchronously (engram#584):
559
+ * the watcher stops at the line and reads it again later, instead of
560
+ * saving its resume offset past a message that was never queued. The
561
+ * returned promise covers only the server-side delete an in-chat opt-out
562
+ * starts, which retries on its own.
45
563
  */
46
- async onMessages(sessionId, meta, messages) {
564
+ onMessages(sessionId, meta, messages) {
47
565
  // Capture exclusions (engram#462) — checked here, the single funnel, so
48
566
  // an excluded session never touches the queue or the network.
49
567
  // A session the user already opted out of stays out.
50
- if (this.db.isSessionExcluded(sessionId))
51
- return;
568
+ if (queueing(() => this.db.isSessionExcluded(sessionId)))
569
+ return DONE;
52
570
  // Repo/directory exclusions: `engram exclude add <path>` or a
53
571
  // .engramignore marker at the repo root. Checked per batch (cheap,
54
572
  // cached) so a freshly added exclusion applies without a restart.
55
573
  if (isPathExcluded(meta.cwd))
56
- return;
574
+ return DONE;
57
575
  // In-chat opt-out: a USER message saying "don't save this to engram"
58
576
  // (or `engram:ignore`) excludes the whole session — including what was
59
577
  // already captured.
60
578
  if (messages.some((m) => m.role === "user" && detectOptOut(m.content))) {
61
- await this.excludeSession(sessionId, "in-chat opt-out");
62
- return;
579
+ return this.excludeSession(sessionId, "in-chat opt-out");
63
580
  }
64
- // Check if we already have a mapping
65
- let conversationId = this.db.getConversationId(sessionId);
66
- if (!conversationId) {
67
- // Defer creation — store messages under the sessionId temporarily.
68
- // The flush loop will create the conversation and re-map them.
69
- this.pendingSessions.set(sessionId, meta);
70
- conversationId = `pending:${sessionId}`;
581
+ // Queued under the key signed in now (engram#594), so only that key's
582
+ // account receives them; onto the session's conversation in that
583
+ // account, if it has one there.
584
+ const keyFp = this.captureFp;
585
+ const conversationId = keyFp === null ? null : queueing(() => this.db.getConversationId(sessionId, keyFp));
586
+ // Value-exact scrubbing of known vault secrets, applied to every role
587
+ // (tool output is where `engram vault get` lands), before the messages
588
+ // are queued. A message queued before the vault has been read isn't
589
+ // covered (its text is in the source transcript on this same disk
590
+ // anyway), so each batch is scrubbed again just before it's sent, and
591
+ // nothing is sent until the vault has been read (engram#588).
592
+ if (this.scrubber?.active) {
593
+ let hits = 0;
594
+ for (const m of messages) {
595
+ const r = this.scrubber.scrub(m.content);
596
+ if (r.replaced.length > 0) {
597
+ m.content = r.text;
598
+ hits += r.replaced.reduce((n, x) => n + x.count, 0);
599
+ }
600
+ }
601
+ if (hits > 0) {
602
+ // Names would be fine to log; counts are enough and give nothing away.
603
+ console.error(`[engram] scrubbed ${hits} vault value occurrence(s) from captured transcript`);
604
+ }
605
+ }
606
+ // File payloads (a screenshot in a tool result, a PDF) become a short
607
+ // note before they are queued (engram#750): Engram never stores them
608
+ // (engram#386), and queued as base64 they filled daemon.db and every
609
+ // upload. Only that here: the clip waits for the send, after the scrub
610
+ // there, so daemon.db keeps the whole text for a vault value saved
611
+ // later to be found in.
612
+ for (const m of messages)
613
+ m.content = stripBinaryPayloads(m.content);
614
+ if (conversationId) {
615
+ queueing(() => this.db.enqueue(conversationId, messages, keyFp));
71
616
  }
72
- this.db.enqueue(conversationId, messages);
617
+ else {
618
+ // No conversation yet. Creating it is deferred to the flush loop so
619
+ // the parser never waits on the network; until then the messages wait
620
+ // under pending:<sessionId>, recorded together with the session in
621
+ // daemon.db (engram#370) so a restart or a failed create can't strand
622
+ // them.
623
+ queueing(() => this.db.enqueuePendingSession(sessionId, meta, messages, keyFp));
624
+ }
625
+ return DONE;
73
626
  }
74
627
  /**
75
628
  * The user said not to save this session. Semantics are "this session was
76
629
  * never captured": stop future capture, wipe the local queue, and delete
77
630
  * whatever already reached the server. The remote delete is persisted in
78
- * excluded_sessions.delete_pending and retried from the flush loop until
79
- * it succeeds — offline opt-out must still stick.
631
+ * remote_deletes and retried from the flush loop until it succeeds —
632
+ * offline opt-out must still stick. A copy synced under another key is
633
+ * deleted with that key's account's key (engram#594), once it signs in
634
+ * again.
635
+ *
636
+ * The local part happens before this returns, in one transaction; if it
637
+ * fails, the QueueWriteError stops the watcher at the opt-out line, so
638
+ * nothing after it is read until the opt-out has taken (engram#584).
80
639
  */
81
- async excludeSession(sessionId, reason) {
82
- const conversationId = this.db.getConversationId(sessionId);
83
- this.db.markSessionExcluded(sessionId, reason, conversationId ?? undefined);
84
- this.pendingSessions.delete(sessionId);
85
- const dropped = this.db.deleteAllForConversation(`pending:${sessionId}`) +
86
- (conversationId ? this.db.deleteAllForConversation(conversationId) : 0);
640
+ excludeSession(sessionId, reason) {
641
+ const { conversations, dropped } = queueing(() => this.db.excludeSession(sessionId, reason));
642
+ this.createRetry.delete(sessionId);
643
+ const run = this.active;
644
+ const here = run ? conversations.filter((c) => c.keyFp === run.fp).length : 0;
645
+ const elsewhere = conversations.length - here;
87
646
  console.log(`[engram] session ${sessionId} excluded (${reason}) — ` +
88
- `${dropped} queued message(s) dropped` +
89
- (conversationId ? ", deleting synced copy" : ""));
90
- if (conversationId) {
91
- await this.retryRemoteDeletes();
92
- }
647
+ `${plural(dropped, "queued message")} dropped` +
648
+ (here > 0
649
+ ? this.deletesRefused
650
+ ? "; the synced copy waits to be deleted: this API key can't delete conversations"
651
+ : ", deleting synced copy"
652
+ : "") +
653
+ (elsewhere > 0
654
+ ? `; ${plural(elsewhere, "copy", "copies")} synced under another account ` +
655
+ `(another API key, or another server) will be deleted when it signs in again`
656
+ : ""));
657
+ return run && here > 0 ? this.retryRemoteDeletes(run) : DONE;
93
658
  }
94
- /** Delete server-side conversations for opted-out sessions; keeps
95
- * delete_pending until the server confirms. */
96
- async retryRemoteDeletes() {
97
- for (const row of this.db.getPendingRemoteDeletes()) {
659
+ /** Delete server-side conversations for opted-out sessions, each with the
660
+ * key of the account it is in; a delete is kept until the server
661
+ * confirms. */
662
+ async retryRemoteDeletes(run) {
663
+ // A rejected key can't delete either, and a rate limit or a maintenance
664
+ // pause holds deletes like any other request; they keep until then.
665
+ if (this.authHeld() || this.throttled())
666
+ return;
667
+ const rows = this.db.getPendingRemoteDeletes(run.fp);
668
+ forgetDone(this.deleteRetry, rows.map((r) => r.conversation_id));
669
+ // This key may not delete (engram#597): they wait for one that can.
670
+ // The status counts them, an opt-out made since included.
671
+ if (this.deletesRefused) {
672
+ recordDeletesRefused(rows.length);
673
+ return;
674
+ }
675
+ const now = Date.now();
676
+ for (const row of rows) {
677
+ // The key changed: the rest wait for their account to sign in again.
678
+ if (this.active !== run)
679
+ return;
680
+ // Refused meanwhile, in another pass over these deletes (engram#597).
681
+ if (this.deletesRefused)
682
+ return;
683
+ // A delete that failed waits its turn (engram#596).
684
+ if ((this.deleteRetry.get(row.conversation_id)?.until ?? 0) > now)
685
+ continue;
98
686
  try {
99
- await this.client.deleteConversation(row.delete_pending);
100
- this.db.clearPendingRemoteDelete(row.session_id);
101
- console.log(`[engram] deleted synced conversation ${row.delete_pending} for opted-out session`);
687
+ await run.client.deleteConversation(row.conversation_id);
688
+ this.requestWentThrough(run, false);
689
+ this.deleteRetry.delete(row.conversation_id);
690
+ this.db.clearPendingRemoteDelete(row.conversation_id);
691
+ console.log(`[engram] deleted synced conversation ${row.conversation_id} for opted-out session`);
102
692
  }
103
693
  catch (err) {
104
- const msg = err instanceof Error ? err.message : String(err);
105
- // "Not found" means it's already gone (or was never fully created) —
106
- // the promise is kept either way.
107
- if (msg.includes("404") || /not.?found/i.test(msg)) {
108
- this.db.clearPendingRemoteDelete(row.session_id);
694
+ const msg = errorText(err);
695
+ // Engram saying "not found" means it's already gone (or was never
696
+ // fully created) — the promise is kept either way. Only Engram's
697
+ // own answer counts (engram#587): this used to accept any text
698
+ // matching /not.?found/ or "404", and a DNS failure (ENOTFOUND)
699
+ // matches that. The delete was dropped while the copy stayed.
700
+ if (isNotFound(err)) {
701
+ this.requestWentThrough(run, false);
702
+ this.deleteRetry.delete(row.conversation_id);
703
+ this.db.clearPendingRemoteDelete(row.conversation_id);
109
704
  continue;
110
705
  }
111
- console.error(`[engram] opt-out delete failed for ${row.delete_pending} (will retry): ${msg}`);
706
+ // Refused under a key no longer in use: that says nothing about the
707
+ // key in use now, and the delete waits for its account.
708
+ if (this.active !== run)
709
+ return;
710
+ // The key works but may not delete (engram#597). It can still save,
711
+ // so nothing else pauses; every delete waits for a key that can.
712
+ if (isScopeRefusal(err)) {
713
+ this.requestWentThrough(run, false);
714
+ // Counted from daemon.db: an opt-out made since is waiting too.
715
+ const waiting = this.db.getPendingRemoteDeletes(run.fp).length;
716
+ // Said once, though two passes over the deletes may both be refused.
717
+ if (!this.deletesRefused) {
718
+ this.deletesRefused = true;
719
+ console.error(`[engram] opt-out delete refused for ${row.conversation_id}: this API key can't ` +
720
+ `delete conversations. ${plural(waiting, "opt-out delete")} kept on this ` +
721
+ `machine, waiting for a key that can; not retried with this one. ` +
722
+ `Run '${engramCommand("status")}' for details.`);
723
+ }
724
+ recordDeletesRefused(waiting);
725
+ return;
726
+ }
727
+ const errType = classifyError(err);
728
+ // Only a key refused outright pauses everything.
729
+ if (errType === "auth") {
730
+ console.error(`[engram] opt-out delete failed for ${row.conversation_id} (will retry): ${msg}`);
731
+ this.enterAuthHold(msg);
732
+ return;
733
+ }
734
+ if (errType === "rate_limit" || errType === "paused") {
735
+ console.error(`[engram] opt-out delete failed for ${row.conversation_id} (will retry): ${msg}`);
736
+ this.enterThrottle(msg, errType);
737
+ return;
738
+ }
739
+ const wait = waitAgain(this.deleteRetry, row.conversation_id);
740
+ console.error(`[engram] opt-out delete failed for ${row.conversation_id} ` +
741
+ `(will retry in ${formatWait(wait)}): ${msg}`);
112
742
  }
113
743
  }
114
744
  }
115
- startFlushLoop() {
116
- this.timer = setInterval(() => this.flush(), FLUSH_INTERVAL_MS);
745
+ /**
746
+ * Flush all pending messages to the API, with the key configured now. A
747
+ * call while a flush is in progress returns at once.
748
+ */
749
+ flush() {
750
+ if (this.running)
751
+ return DONE;
752
+ const flushing = this.runFlush().finally(() => {
753
+ this.running = null;
754
+ });
755
+ this.running = flushing;
756
+ return flushing;
117
757
  }
118
- stopFlushLoop() {
119
- if (this.timer) {
120
- clearInterval(this.timer);
121
- this.timer = null;
758
+ /** Settles once no flush is in progress: shutdown waits for it before
759
+ * closing daemon.db, so a send that went through is recorded as sent. */
760
+ idle() {
761
+ return this.running ?? DONE;
762
+ }
763
+ async runFlush() {
764
+ let run = null;
765
+ try {
766
+ // A logout or a new key takes effect before anything is sent
767
+ // (engram#594).
768
+ await this.checkKey();
769
+ run = this.active;
770
+ if (!run)
771
+ return; // signed out: nothing is sent
772
+ await this.flushWith(run);
773
+ }
774
+ catch (err) {
775
+ const msg = errorText(err);
776
+ console.error(`[engram] flush error: ${msg}`);
777
+ // After a logout or a new key, the error belongs to a key no longer
778
+ // in use; the status speaks for the one configured now.
779
+ if (this.active !== null && (run === null || this.active === run)) {
780
+ recordFailure(msg, classifyError(err), this.pendingCount());
781
+ }
122
782
  }
123
783
  }
124
- /** Flush all pending messages to the API. */
125
- async flush() {
126
- if (this.flushing || this.authFailed)
784
+ async flushWith(run) {
785
+ // What was queued before daemon.db recorded keys is this key's (see
786
+ // claim). Nothing is sent until that is recorded: a session mapped
787
+ // before then would otherwise get a second conversation.
788
+ if (!this.claim(run))
789
+ return;
790
+ // Nothing can send while the key is rejected, a billing backoff holds,
791
+ // or the account waits out a rate limit or a maintenance pause.
792
+ if (this.halted(run))
793
+ return;
794
+ // What an earlier key of this account queued is sent with this one.
795
+ await this.checkOwnership(run);
796
+ if (this.halted(run))
797
+ return; // the key was rejected, or changed, there
798
+ // Step 0: Honor opt-outs whose server-side delete hasn't landed yet
799
+ // (e.g. the machine was offline when the user said "don't save this").
800
+ await this.retryRemoteDeletes(run);
801
+ if (this.halted(run))
802
+ return; // the key was rejected, or changed, there
803
+ // Step 1: Create any pending conversations. A create carries no
804
+ // message content, so it doesn't wait for the vault.
805
+ const createsOk = await this.createPendingConversations(run);
806
+ if (this.halted(run))
807
+ return; // the key was rejected, or a limit hit, there
808
+ // Step 2: Flush messages for all conversations (with concurrency).
809
+ // Not those Engram said it doesn't have (engram#593), but for the ones
810
+ // due to be checked again.
811
+ const rechecks = this.dueRechecks(run);
812
+ const convIds = [
813
+ ...this.db.getPendingConversationIds(run.fp).filter((id) => !id.startsWith("pending:")),
814
+ ...rechecks,
815
+ ];
816
+ // A conversation whose last send failed waits its turn (engram#596).
817
+ // It used to be tried again at every flush, every 2 s, for as long as
818
+ // the failure lasted, and by every daemon at once.
819
+ forgetDone(this.sendRetry, convIds);
820
+ const now = Date.now();
821
+ const due = convIds.filter((id) => (this.sendRetry.get(id)?.until ?? 0) <= now);
822
+ // Nothing is sent before the vault has been read: a message queued
823
+ // before then wasn't scrubbed against it (engram#588).
824
+ if (due.length > 0 && !(await this.vaultReady(run)))
127
825
  return;
128
- // Skip if in billing backoff window
129
- if (Date.now() < this.billingBackoffUntil)
826
+ // Process conversations in parallel, up to CONCURRENCY at a time
827
+ const chunks = [];
828
+ for (let i = 0; i < due.length; i += CONCURRENCY) {
829
+ chunks.push(due.slice(i, i + CONCURRENCY));
830
+ }
831
+ // A conversation waiting its turn hasn't synced. One that Engram
832
+ // doesn't have is done: nothing more can be sent to it.
833
+ let allSent = due.length === convIds.length;
834
+ for (const chunk of chunks) {
835
+ const results = await Promise.allSettled(chunk.map((id) => this.flushConversation(run, id, rechecks.has(id))));
836
+ if (results.some((r) => r.status === "rejected" || (r.value !== "sent" && r.value !== "gone"))) {
837
+ allSent = false;
838
+ }
839
+ }
840
+ // The key changed during the flush: what this flush did says nothing
841
+ // about the key in use now.
842
+ if (this.active !== run)
130
843
  return;
131
- this.flushing = true;
844
+ // Report sync health. Only a flush in which every create and every
845
+ // send went through is a successful sync: a session still waiting on
846
+ // its create, or a conversation whose send failed, is not synced.
847
+ // A failed send used to count as a success (engram#580): status read
848
+ // "healthy" while nothing synced, and the billing backoff a full
849
+ // memory had just entered was cleared again, so the account was
850
+ // retried every 2 s instead of backing off.
851
+ //
852
+ // After a pause for a rejected key, a flush with nothing to send
853
+ // proves nothing about the key: status keeps saying it was rejected
854
+ // until a request goes through (requestWentThrough) or a new key is
855
+ // saved.
856
+ const pending = this.db.getPendingCount(run.fp);
857
+ if (createsOk && allSent && this.authHoldStep === 0) {
858
+ this.resetBillingBackoff();
859
+ recordSuccess(pending);
860
+ }
861
+ else {
862
+ // A wait can end, and another go on, with no failure in between.
863
+ recordNextRetry(this.nextRetryAt());
864
+ }
865
+ }
866
+ /**
867
+ * Ask the server, once per account, which of the other keys something
868
+ * here is queued or mapped under are keys of this account (engram#594): a
869
+ * rotated or re-issued key. Theirs is handed to this account, so it is
870
+ * sent with this key, and a session continues in the conversation it
871
+ * already has. The rest keep waiting for their own account. Only what was
872
+ * queued for this account's server is asked about (ownershipCandidates,
873
+ * engram#685), and only key fingerprints go to the server, never a key.
874
+ * When the server can't answer, it is asked again on OWNERSHIP_RETRY_MS.
875
+ */
876
+ async checkOwnership(run) {
877
+ const own = this.ownership;
878
+ if (own.answered || Date.now() < own.retryAt)
879
+ return;
880
+ const others = this.db.otherKeyFps(run.fp);
881
+ // Only a server other than the default is asked about what doesn't
882
+ // record its server; the default server's own key hashes cover it.
883
+ const unknownServer = SERVER_ACCOUNT.test(run.fp)
884
+ ? new Set(this.db.unknownServerFps())
885
+ : new Set();
886
+ const candidates = ownershipCandidates(run.fp, others, unknownServer);
887
+ if (candidates.length === 0) {
888
+ own.answered = true;
889
+ // What another server's account queued waits for it.
890
+ if (others.length > 0)
891
+ this.logHeld(run);
892
+ return;
893
+ }
894
+ const keys = this.keys;
895
+ if (!keys?.ownedKeys || !run.account) {
896
+ own.answered = true;
897
+ this.logHeld(run);
898
+ return;
899
+ }
900
+ if (own.firstAskedAt === 0)
901
+ own.firstAskedAt = Date.now();
902
+ let owned;
132
903
  try {
133
- // Step 0: Honor opt-outs whose server-side delete hasn't landed yet
134
- // (e.g. the machine was offline when the user said "don't save this").
135
- await this.retryRemoteDeletes();
136
- // Step 1: Create any pending conversations
137
- await this.createPendingConversations();
138
- // Step 2: Flush messages for all conversations (with concurrency)
139
- const convIds = this.db.getPendingConversationIds().filter((id) => !id.startsWith("pending:"));
140
- // Process conversations in parallel, up to CONCURRENCY at a time
141
- const chunks = [];
142
- for (let i = 0; i < convIds.length; i += CONCURRENCY) {
143
- chunks.push(convIds.slice(i, i + CONCURRENCY));
904
+ owned = await keys.ownedKeys(run.account, [...new Set(candidates.map((c) => c.keyHash))]);
905
+ }
906
+ catch (err) {
907
+ // The key changed while the server was asked: the answer is about a
908
+ // key no longer in use.
909
+ if (this.active !== run || this.ownership !== own)
910
+ return;
911
+ const msg = errorText(err);
912
+ const status = err?.status;
913
+ if (status === 401) {
914
+ this.enterAuthHold(msg);
915
+ return;
916
+ }
917
+ if (status === 400 || status === 403 || status === 404) {
918
+ // Asking again would get the same answer. What another key queued
919
+ // keeps waiting for that key's account.
920
+ own.answered = true;
921
+ console.error(`[engram] couldn't check which earlier API keys are this account's: ${msg}`);
922
+ this.logHeld(run);
923
+ return;
144
924
  }
145
- let hadError = false;
146
- for (const chunk of chunks) {
147
- const results = await Promise.allSettled(chunk.map((id) => this.flushConversation(id)));
148
- if (results.some((r) => r.status === "rejected"))
149
- hadError = true;
925
+ this.retryOwnership(own, msg);
926
+ return;
927
+ }
928
+ if (this.active !== run || this.ownership !== own)
929
+ return;
930
+ const mine = new Set(owned);
931
+ const adopted = candidates.filter((c) => mine.has(c.keyHash));
932
+ // The key in use, queued before servers were recorded (see
933
+ // ownershipCandidates), apart from the earlier keys.
934
+ const runKeyHash = run.fp.split("@")[0];
935
+ const earlier = adopted.filter((c) => c.keyHash !== runKeyHash);
936
+ const sameKey = adopted.filter((c) => c.keyHash === runKeyHash);
937
+ try {
938
+ // Each its own transaction: one that moved stays moved, and the
939
+ // next check no longer finds it.
940
+ if (earlier.length > 0) {
941
+ const moved = this.db.adoptKeys(earlier, run.fp);
942
+ console.log(`[engram] ${new Set(earlier.map((c) => c.keyHash)).size} earlier API key(s) are this ` +
943
+ `account's — sending their ${moved.messages} queued message(s) with this key`);
150
944
  }
151
- // Report sync health
152
- const pending = this.db.getPendingCount();
153
- if (!hadError && !this.authFailed) {
154
- this.resetBillingBackoff();
155
- recordSuccess(pending);
945
+ if (sameKey.length > 0) {
946
+ const moved = this.db.adoptKeys(sameKey, run.fp);
947
+ if (moved.messages > 0) {
948
+ console.log(`[engram] the server confirmed this API key — sending it the ${moved.messages} ` +
949
+ `message(s) an earlier version of Engram queued with the key`);
950
+ }
156
951
  }
157
952
  }
158
953
  catch (err) {
159
- const msg = err instanceof Error ? err.message : String(err);
160
- console.error(`[engram] flush error: ${msg}`);
161
- recordFailure(msg, classifyError(msg), this.db.getPendingCount());
954
+ this.retryOwnership(own, errorText(err));
955
+ return;
162
956
  }
163
- finally {
164
- this.flushing = false;
957
+ own.answered = true;
958
+ this.logHeld(run);
959
+ }
960
+ retryOwnership(own, msg) {
961
+ const delay = OWNERSHIP_RETRY_MS[Math.min(own.step, OWNERSHIP_RETRY_MS.length - 1)];
962
+ own.step++;
963
+ own.retryAt = Date.now() + delay;
964
+ console.error(`[engram] couldn't check which earlier API keys are this account's ` +
965
+ `(will retry in ${Math.round(delay / 1000)}s): ${msg}`);
966
+ }
967
+ /** While a session with a conversation under an earlier key waits for the
968
+ * server to say whether that key is this account's (OWNERSHIP_GATE_MS). */
969
+ awaitingOwnership(now) {
970
+ const own = this.ownership;
971
+ return !own.answered && (own.firstAskedAt === 0 || now - own.firstAskedAt < OWNERSHIP_GATE_MS);
972
+ }
973
+ /** Say how many queued messages wait for another account: another API
974
+ * key's, or the same key's on another server (engram#685). */
975
+ logHeld(run) {
976
+ let held = 0;
977
+ try {
978
+ held = this.db.getHeldCount(run.fp);
979
+ }
980
+ catch {
981
+ return; // the count only informs the line below
982
+ }
983
+ if (held > 0) {
984
+ console.log(`[engram] ${held} queued message(s) wait for another account (another API key, or ` +
985
+ `another server) — they stay on this machine and are sent only to that account`);
165
986
  }
166
987
  }
167
- /** Create conversations for sessions that were deferred during parsing. */
168
- async createPendingConversations() {
169
- if (this.pendingSessions.size === 0)
170
- return;
171
- const entries = [...this.pendingSessions.entries()];
172
- this.pendingSessions.clear();
988
+ /**
989
+ * Create conversations for sessions that were deferred during parsing.
990
+ * Every session stays in daemon.db until its conversation exists and its
991
+ * messages have moved onto it — a failure here only means "try again".
992
+ * Returns false while any session is still waiting on a failed create.
993
+ */
994
+ async createPendingConversations(run) {
995
+ let ok = true;
996
+ if (!this.orphansAdopted) {
997
+ try {
998
+ const adopted = this.db.adoptOrphanedPendingRows();
999
+ this.orphansAdopted = true;
1000
+ if (adopted.length > 0) {
1001
+ console.log(`[engram] recovered ${adopted.length} session(s) queued by an earlier daemon — creating their conversations`);
1002
+ }
1003
+ }
1004
+ catch (err) {
1005
+ // Not fatal: the orphans keep, and this runs again next flush.
1006
+ const msg = errorText(err);
1007
+ console.error(`[engram] orphaned-queue check failed (will retry): ${msg}`);
1008
+ ok = false;
1009
+ }
1010
+ }
1011
+ const now = Date.now();
1012
+ const pending = this.db.getPendingSessions(run.fp);
1013
+ forgetDone(this.createRetry, pending.map((s) => s.sessionId));
1014
+ let sessions = pending.filter((s) => (this.createRetry.get(s.sessionId)?.until ?? 0) <= now);
1015
+ // A session sitting out a retry delay hasn't synced.
1016
+ if (sessions.length < pending.length)
1017
+ ok = false;
1018
+ // A session with a conversation under an earlier key waits to learn
1019
+ // whether that key is this account's: if it is, the session continues
1020
+ // in that conversation instead of starting a second one
1021
+ // (checkOwnership).
1022
+ if (this.awaitingOwnership(now)) {
1023
+ const waiting = new Set(sessions
1024
+ .filter((s) => this.db.mappedUnderOtherKey(s.sessionId, run.fp))
1025
+ .map((s) => s.sessionId));
1026
+ if (waiting.size > 0) {
1027
+ ok = false;
1028
+ sessions = sessions.filter((s) => !waiting.has(s.sessionId));
1029
+ if (!this.gateLogged) {
1030
+ this.gateLogged = true;
1031
+ console.log(`[engram] ${waiting.size} session(s) synced under an earlier API key wait to learn ` +
1032
+ `whether it is this account's before they continue`);
1033
+ }
1034
+ }
1035
+ }
173
1036
  // Create conversations in parallel batches
174
- const batches = [];
175
- for (let i = 0; i < entries.length; i += CONCURRENCY) {
176
- batches.push(entries.slice(i, i + CONCURRENCY));
177
- }
178
- for (const batch of batches) {
179
- const results = await Promise.allSettled(batch.map(async ([sessionId, meta]) => {
180
- // Double-check (another flush may have created it)
181
- if (this.db.getConversationId(sessionId))
182
- return;
183
- const conversationId = await this.createConversation(sessionId, meta);
184
- // Opt-out race (engram#462): the user may have said "don't save
185
- // this" while the create was in flight — excludeSession saw no
186
- // conversation id yet, so it couldn't schedule the remote delete.
187
- // Schedule it now; the flush loop's retryRemoteDeletes handles it.
188
- if (this.db.isSessionExcluded(sessionId)) {
189
- this.db.markSessionExcluded(sessionId, "in-chat opt-out", conversationId);
190
- this.db.deleteAllForConversation(`pending:${sessionId}`);
191
- this.db.deleteAllForConversation(conversationId);
192
- return;
1037
+ for (let i = 0; i < sessions.length; i += CONCURRENCY) {
1038
+ // The key changed: the rest wait for the next flush.
1039
+ if (this.active !== run)
1040
+ return false;
1041
+ const batch = sessions.slice(i, i + CONCURRENCY);
1042
+ const results = await Promise.allSettled(batch.map((s) => this.createPendingConversation(run, s.sessionId, s.meta)));
1043
+ for (let j = 0; j < results.length; j++) {
1044
+ const r = results[j];
1045
+ const sessionId = batch[j].sessionId;
1046
+ if (r.status === "fulfilled") {
1047
+ this.createRetry.delete(sessionId);
1048
+ continue;
193
1049
  }
194
- // Migrate pending messages from pending:sessionId → real conversationId
195
- this.db.remapPending(`pending:${sessionId}`, conversationId);
196
- }));
197
- for (const r of results) {
198
- if (r.status === "rejected") {
199
- const msg = r.reason instanceof Error ? r.reason.message : String(r.reason);
200
- if (msg.includes("401") || msg.includes("403")) {
201
- this.authFailed = true;
202
- console.error(`[engram] auth error, stopping: ${msg}`);
203
- recordFailure(msg, "auth", this.db.getPendingCount());
204
- return;
205
- }
206
- const errType = classifyError(msg);
207
- if (errType === "billing" || errType === "storage_full") {
208
- this.enterBillingBackoff(msg);
209
- return;
210
- }
211
- console.error(`[engram] create error (will retry): ${msg}`);
212
- recordFailure(msg, errType, this.db.getPendingCount());
1050
+ ok = false;
1051
+ // Refused under a key no longer in use: that says nothing about the
1052
+ // key in use now.
1053
+ if (this.active !== run)
1054
+ continue;
1055
+ const msg = errorText(r.reason);
1056
+ const errType = classifyError(r.reason);
1057
+ if (errType === "auth") {
1058
+ this.enterAuthHold(msg);
1059
+ return false;
1060
+ }
1061
+ if (errType === "billing" || errType === "storage_full") {
1062
+ this.enterBillingBackoff(msg);
1063
+ return false;
1064
+ }
1065
+ if (errType === "rate_limit" || errType === "paused") {
1066
+ this.enterThrottle(msg, errType);
1067
+ return false;
213
1068
  }
1069
+ const wait = this.deferCreate(sessionId);
1070
+ console.error(`[engram] create error (will retry in ${formatWait(wait)}): ${msg}`);
1071
+ recordFailure(msg, errType, this.pendingCount(), { retryAt: this.nextRetryAt() });
214
1072
  }
215
1073
  }
1074
+ return ok;
216
1075
  }
217
- /** Per-conversation reduced batch size after a failed send (halves down to
218
- * 1 so even a single pathological message eventually goes alone; restored
219
- * to the full batch on the next success). */
220
- batchOverride = new Map();
221
- async flushConversation(conversationId) {
1076
+ async createPendingConversation(run, sessionId, meta) {
1077
+ // Opted out while it waited: nothing of this session may sync.
1078
+ if (this.db.isSessionExcluded(sessionId)) {
1079
+ this.db.dropPendingSession(sessionId);
1080
+ return;
1081
+ }
1082
+ // Already mapped in this key's account (rows an older daemon left under
1083
+ // the temporary id after the conversation was created, or rows queued
1084
+ // before the server said an earlier key is this account's) — move them;
1085
+ // never create a second conversation for the session.
1086
+ const existing = this.db.getConversationId(sessionId, run.fp);
1087
+ if (existing) {
1088
+ this.db.completePendingSession(sessionId, existing, run.fp);
1089
+ return;
1090
+ }
1091
+ // The key changed: the session waits for the next flush.
1092
+ if (this.active !== run)
1093
+ return;
1094
+ const conversationId = await this.createConversation(run, sessionId, meta);
1095
+ this.requestWentThrough(run, false);
1096
+ // Opt-out race (engram#462): the user may have said "don't save
1097
+ // this" while the create was in flight — excludeSession saw no
1098
+ // conversation id yet, so it couldn't schedule the remote delete.
1099
+ // Schedule it now, for the key that created it; the flush loop's
1100
+ // retryRemoteDeletes handles it.
1101
+ if (this.db.isSessionExcluded(sessionId)) {
1102
+ this.db.excludeCreatedConversation(sessionId, conversationId, run.fp);
1103
+ return;
1104
+ }
1105
+ // Map the session and move its messages onto the conversation (one
1106
+ // transaction — see DaemonDb.completePendingSession). Done even if the
1107
+ // key changed meanwhile: the conversation exists in this key's account,
1108
+ // and only what was queued under this key moves onto it.
1109
+ this.db.completePendingSession(sessionId, conversationId, run.fp, {
1110
+ projectDir: meta.projectDir,
1111
+ cwd: meta.cwd,
1112
+ gitBranch: meta.gitBranch,
1113
+ });
1114
+ }
1115
+ /** Pace retries for a session whose create failed: 30s → 2m → 10m …
1116
+ * Returns the wait. */
1117
+ deferCreate(sessionId) {
1118
+ const prev = this.createRetry.get(sessionId);
1119
+ const step = prev ? prev.step + 1 : 0;
1120
+ const delay = CREATE_RETRY_MS[Math.min(step, CREATE_RETRY_MS.length - 1)];
1121
+ this.createRetry.set(sessionId, { until: Date.now() + delay, step });
1122
+ return delay;
1123
+ }
1124
+ /**
1125
+ * Send what is queued for one conversation, batch by batch. `recheck`:
1126
+ * Engram said it doesn't have the conversation (engram#593), and this
1127
+ * checks again with one message before anything more is sent.
1128
+ */
1129
+ async flushConversation(run, conversationId, recheck = false) {
1130
+ let checking = recheck;
222
1131
  while (true) {
223
- const limit = this.batchOverride.get(conversationId) ?? BATCH_SIZE;
224
- let rows = this.db.dequeue(conversationId, limit);
1132
+ // Each batch waits for the vault to be read, not only the flush
1133
+ // (engram#701): `engram vault set` may save a secret while a long
1134
+ // flush is under way, and the batch after it may hold a row captured
1135
+ // since. ready() reads the vault again first. It answers at once
1136
+ // when nothing changed.
1137
+ if (!(await this.vaultReady(run)))
1138
+ return "retry";
1139
+ // The key changed or was removed (engram#594): no new batch goes out
1140
+ // with this one. What is left stays queued for its account.
1141
+ if (this.active !== run)
1142
+ return "retry";
1143
+ // An auth failure or a billing limit applies to the whole account.
1144
+ // Once any conversation in this flush has hit one, no new batch is
1145
+ // started: it could only fail the same way.
1146
+ if (this.authHeld())
1147
+ return "auth";
1148
+ if (Date.now() < this.billingBackoffUntil)
1149
+ return "backoff";
1150
+ if (this.throttled())
1151
+ return "wait";
1152
+ const limit = checking ? 1 : (this.batchOverride.get(conversationId) ?? BATCH_SIZE);
1153
+ let rows = this.db.dequeue(conversationId, limit, run.fp);
225
1154
  if (rows.length === 0)
226
- break;
1155
+ return "sent";
1156
+ // Scrubbed again against the set held now (engram#588): a row queued
1157
+ // before the vault was read wasn't scrubbed against it.
1158
+ rows = this.rescrub(rows);
1159
+ // Bounded the way Engram bounds them on arrival (engram#750): file
1160
+ // payloads become a note, then the text is clipped with a visible
1161
+ // marker. Engram stores the same text, or in one case less (see
1162
+ // message-bounds.ts), and no single message can outgrow its request
1163
+ // limit. Clipped only after the scrub above, so a vault value at the
1164
+ // cut is replaced whole, never half sent; daemon.db keeps the whole
1165
+ // text.
1166
+ rows = rows.map((r) => {
1167
+ const content = boundContent(r.content);
1168
+ return content === r.content ? r : { ...r, content };
1169
+ });
227
1170
  // Byte budget: transcript messages vary wildly in size — trim the batch
228
1171
  // so its total content stays inside the budget. Always send at least
229
- // one row, however large (the server accepts it; it just needs time).
1172
+ // one row (bounded above, it is far inside the server's limit).
230
1173
  let bytes = 0;
231
1174
  let take = 0;
232
1175
  for (const r of rows) {
@@ -240,43 +1183,227 @@ export class Syncer {
240
1183
  rows = rows.slice(0, take);
241
1184
  const messages = rows.map(rowToMessage);
242
1185
  try {
243
- await this.client.store({ conversationId, messages });
1186
+ await run.client.store({ conversationId, messages });
1187
+ this.requestWentThrough(run, true);
244
1188
  this.db.markSent(rows.map((r) => r.id));
245
- this.batchOverride.delete(conversationId);
1189
+ if (checking) {
1190
+ // Engram has the conversation after all: the rest follows.
1191
+ this.db.clearGone(conversationId);
1192
+ checking = false;
1193
+ console.log(`[engram] conversation ${conversationId} is on Engram again — sending its queued messages`);
1194
+ }
1195
+ if (this.active === run) {
1196
+ this.batchOverride.delete(conversationId);
1197
+ this.sendRetry.delete(conversationId);
1198
+ }
246
1199
  }
247
1200
  catch (err) {
248
- const msg = err instanceof Error ? err.message : String(err);
249
- if (msg.includes("401") || msg.includes("403") || msg.includes("Authentication")) {
250
- this.authFailed = true;
251
- console.error(`[engram] auth error, stopping flush: ${msg}`);
252
- recordFailure(msg, "auth", this.db.getPendingCount());
253
- this.stopFlushLoop();
254
- return;
1201
+ // Failed under a key no longer in use: that says nothing about the
1202
+ // key in use now. The rows stay queued for their account.
1203
+ if (this.active !== run)
1204
+ return "retry";
1205
+ // Engram doesn't have the conversation (engram#593): deleted there,
1206
+ // or not this account's. Sending again can't change that, so its
1207
+ // messages stay here instead of being retried forever, and the
1208
+ // conversation isn't created again. Engram answered, after checking
1209
+ // that writes aren't paused: the key works and the account can
1210
+ // write, so this is no failure of the account's.
1211
+ if (isConversationGone(err)) {
1212
+ this.requestWentThrough(run, true);
1213
+ this.setAside(conversationId);
1214
+ return "gone";
1215
+ }
1216
+ const msg = errorText(err);
1217
+ const errType = classifyError(err);
1218
+ // The key was rejected: pause, and recover without a restart. This
1219
+ // used to stop the flush loop for good (engram#587).
1220
+ if (errType === "auth") {
1221
+ this.enterAuthHold(msg);
1222
+ return "auth";
255
1223
  }
256
1224
  // Billing / limit errors — exponential backoff
257
- const errType = classifyError(msg);
258
1225
  if (errType === "billing" || errType === "storage_full") {
259
1226
  this.enterBillingBackoff(msg);
260
- return;
1227
+ return "backoff";
1228
+ }
1229
+ // A rate limit or a maintenance pause: nothing is sent from this
1230
+ // account for a while (engram#596). It refuses the request for when
1231
+ // it came, not for its size, so the batch keeps its size: halving
1232
+ // it would only multiply the requests.
1233
+ if (errType === "rate_limit" || errType === "paused") {
1234
+ this.enterThrottle(msg, errType);
1235
+ return "wait";
261
1236
  }
262
- // Rate limit or network/timeout — leave in queue for next cycle, but
263
- // halve this conversation's batch so an oversized batch self-resolves
264
- // instead of retrying the identical payload forever.
1237
+ // Refused as too large (engram#750). Every message is bounded far
1238
+ // inside Engram's limit, so this is a batch that still adds up to
1239
+ // more than something on the way accepts (a proxy with a smaller
1240
+ // limit): send half of it at once. Waiting would change nothing,
1241
+ // and the same batch would only be refused again. A single message
1242
+ // that is still refused stays queued, in its place, and is tried
1243
+ // again after a wait like any other failure: sending the ones after
1244
+ // it first would store the conversation out of order.
1245
+ if (errType === "too_large" && rows.length > 1) {
1246
+ const next = Math.max(1, Math.floor(rows.length / 2));
1247
+ this.batchOverride.set(conversationId, next);
1248
+ console.error(`[engram] send refused as too large — sending it again in batches of ${next}`);
1249
+ continue;
1250
+ }
1251
+ // Network/timeout/server — leave in queue, and try this conversation
1252
+ // again after a wait that doubles with each failure in a row
1253
+ // (engram#596). Halve its batch too, so an oversized batch
1254
+ // self-resolves instead of retrying the identical payload forever.
1255
+ // One conversation's failure doesn't hold the others: what fails for
1256
+ // one batch (a payload a proxy refuses) may not fail for the rest.
1257
+ const wait = waitAgain(this.sendRetry, conversationId);
265
1258
  if (rows.length > 1) {
266
1259
  const next = Math.max(1, Math.floor(rows.length / 2));
267
1260
  this.batchOverride.set(conversationId, next);
268
- console.error(`[engram] send failed (will retry with batch ${next}): ${msg}`);
1261
+ console.error(`[engram] send failed (will retry in ${formatWait(wait)} with batch ${next}): ${msg}`);
269
1262
  }
270
1263
  else {
271
- console.error(`[engram] send failed (will retry): ${msg}`);
1264
+ console.error(`[engram] send failed (will retry in ${formatWait(wait)}): ${msg}`);
272
1265
  }
273
- recordFailure(msg, errType, this.db.getPendingCount());
274
- return;
1266
+ recordFailure(msg, errType, this.pendingCount(), { retryAt: this.nextRetryAt() });
1267
+ return "retry";
1268
+ }
1269
+ }
1270
+ }
1271
+ /**
1272
+ * Stop sending a conversation Engram said it doesn't have (engram#593).
1273
+ * Its messages stay in daemon.db; the flush loop leaves it out until it
1274
+ * is due to be checked again (GONE_RECHECK_MS).
1275
+ */
1276
+ setAside(conversationId) {
1277
+ this.sendRetry.delete(conversationId);
1278
+ this.batchOverride.delete(conversationId);
1279
+ const now = Date.now();
1280
+ const checks = this.db.markGone(conversationId, now);
1281
+ const next = goneRecheckAt(now, checks);
1282
+ const kept = plural(this.db.getUnsentCount(conversationId), "queued message");
1283
+ console.log(`[engram] conversation ${conversationId} ${checks === 1 ? "isn't" : "still isn't"} on Engram ` +
1284
+ `(deleted there, or not this account's) — keeping its ${kept} on this machine, not sent; ` +
1285
+ (next === null ? "not checking again" : `checking again in ${waitInWords(next - now)}`));
1286
+ }
1287
+ /** The conversations Engram said it doesn't have that are due to be
1288
+ * checked again, with messages queued under `run`'s key (engram#593). */
1289
+ dueRechecks(run) {
1290
+ const now = Date.now();
1291
+ const due = new Set();
1292
+ for (const g of this.db.getGoneConversations(run.fp)) {
1293
+ const at = goneRecheckAt(g.checkedAt, g.checks);
1294
+ if (at !== null && at <= now)
1295
+ due.add(g.conversationId);
1296
+ }
1297
+ return due;
1298
+ }
1299
+ /**
1300
+ * Whether queued messages may be sent: the vault has been read through the
1301
+ * current key, so the scrub before each send covers it (engram#588). Until
1302
+ * then nothing is sent — captures keep queueing in daemon.db — and the
1303
+ * status says why.
1304
+ */
1305
+ async vaultReady(run) {
1306
+ if (!this.scrubber)
1307
+ return true;
1308
+ const ready = await this.scrubber.ready();
1309
+ // The key changed while the vault was read: the next flush starts over.
1310
+ if (this.active !== run)
1311
+ return false;
1312
+ if (ready) {
1313
+ if (this.vaultHeld) {
1314
+ this.vaultHeld = null;
1315
+ console.log("[engram] vault read — sending the messages held for it");
275
1316
  }
1317
+ return true;
276
1318
  }
1319
+ this.holdForVault(this.scrubber.failure);
1320
+ return false;
1321
+ }
1322
+ holdForVault(err) {
1323
+ // The vault key can't be read (engram#677): there is nothing to scrub
1324
+ // the vault's secrets with, for as long as it lasts. Something for the
1325
+ // user to fix, unlike the waits below: an error, in status.json and on
1326
+ // the desktop.
1327
+ if (err instanceof VaultKeyUnreadable) {
1328
+ if (this.vaultHeld !== "key") {
1329
+ this.vaultHeld = "key";
1330
+ console.error(`[engram] holding queued messages until the vault key can be read, so a vault ` +
1331
+ `secret in them can't be sent unredacted: ${err.message}`);
1332
+ }
1333
+ recordFailure(`holding messages until the vault key can be read: ${err.message}`, "vault_key", this.pendingCount());
1334
+ return;
1335
+ }
1336
+ // The key reads, but the vault holds secrets it doesn't decrypt
1337
+ // (engram#694): they can't be scrubbed, and they would go out as they
1338
+ // are. As above, the user's to fix, and nothing passes meanwhile.
1339
+ if (err instanceof VaultKeyMismatch) {
1340
+ if (this.vaultHeld !== "mismatch") {
1341
+ this.vaultHeld = "mismatch";
1342
+ console.error(`[engram] holding queued messages until each of the vault's secrets decrypts, or is ` +
1343
+ `deleted, so none of them is sent unredacted: ${err.message}`);
1344
+ }
1345
+ recordFailure(`holding messages until the vault's secrets can be scrubbed: ${err.message}`, "vault_mismatch", this.pendingCount());
1346
+ return;
1347
+ }
1348
+ const reason = err === undefined
1349
+ ? "the vault hasn't been read yet"
1350
+ : err instanceof Error
1351
+ ? err.message
1352
+ : String(err);
1353
+ const errType = err === undefined ? "network" : classifyError(err);
1354
+ // The key was rejected: the pause a rejected send enters, which picks up
1355
+ // a new key without a restart (engram#587). The vault is read through
1356
+ // the new key, and sends wait for that read.
1357
+ if (errType === "auth") {
1358
+ this.enterAuthHold(reason);
1359
+ return;
1360
+ }
1361
+ if (this.vaultHeld !== "read") {
1362
+ this.vaultHeld = "read";
1363
+ console.error(`[engram] holding queued messages until the vault is read, so a secret in them ` +
1364
+ `can't be sent unredacted: ${reason}`);
1365
+ }
1366
+ // A plan or storage refusal of the read doesn't hold sends (the
1367
+ // scrubber treats it as final), so what holds is the server or the
1368
+ // network.
1369
+ const kind = errType === "billing" || errType === "storage_full" ? "server" : errType;
1370
+ recordFailure(`holding messages until the vault is read: ${reason}`, kind, this.pendingCount());
277
1371
  }
278
1372
  /**
279
- * Enter billing backoff — escalates each time: 5min → 15min → 1hr.
1373
+ * Scrub queued rows against the set held now, and write the scrubbed text
1374
+ * back so the queue stops holding the value too. A failed write-back
1375
+ * doesn't stop the send: what's sent is scrubbed either way.
1376
+ */
1377
+ rescrub(rows) {
1378
+ const scrubber = this.scrubber;
1379
+ if (!scrubber?.active)
1380
+ return rows;
1381
+ let hits = 0;
1382
+ const changed = [];
1383
+ const out = rows.map((row) => {
1384
+ const r = scrubber.scrub(row.content);
1385
+ if (r.replaced.length === 0)
1386
+ return row;
1387
+ hits += r.replaced.reduce((n, x) => n + x.count, 0);
1388
+ changed.push({ id: row.id, content: r.text });
1389
+ return { ...row, content: r.text };
1390
+ });
1391
+ if (changed.length === 0)
1392
+ return rows;
1393
+ try {
1394
+ this.db.updateContents(changed);
1395
+ }
1396
+ catch (err) {
1397
+ const msg = errorText(err);
1398
+ console.error(`[engram] rewriting scrubbed queued messages failed (sending them scrubbed): ${msg}`);
1399
+ }
1400
+ console.error(`[engram] scrubbed ${hits} vault value occurrence(s) from queued messages before sending`);
1401
+ return out;
1402
+ }
1403
+ /**
1404
+ * Enter billing backoff — escalates each time it is entered:
1405
+ * 5min → 15min → 1hr for a plan limit, 1min → 2min → 5min for a full
1406
+ * memory (see STORAGE_FULL_BACKOFF_MS).
280
1407
  *
281
1408
  * A full memory is separated out here. It arrives as a 402 like any other
282
1409
  * billing error, but retrying can never clear it on its own: it needs an
@@ -286,22 +1413,130 @@ export class Syncer {
286
1413
  * even when the machine is offline.
287
1414
  */
288
1415
  enterBillingBackoff(msg) {
289
- const delay = BILLING_BACKOFF_MS[Math.min(this.billingBackoffStep, BILLING_BACKOFF_MS.length - 1)];
290
- this.billingBackoffUntil = Date.now() + delay;
291
- this.billingBackoffStep++;
292
1416
  const storageFull = parseStorageFullError(msg);
293
- const mins = Math.round(delay / 60_000);
1417
+ // Sends running in parallel hit the limit together. Only the first in a
1418
+ // flush escalates (engram#580): five at once would otherwise go
1419
+ // straight to the cap. No flush starts inside the window, so the next
1420
+ // flush that hits the limit escalates again.
1421
+ if (Date.now() >= this.billingBackoffUntil) {
1422
+ const schedule = storageFull ? STORAGE_FULL_BACKOFF_MS : BILLING_BACKOFF_MS;
1423
+ const delay = schedule[Math.min(this.billingBackoffStep, schedule.length - 1)];
1424
+ this.billingBackoffUntil = Date.now() + delay;
1425
+ this.billingBackoffStep++;
1426
+ const mins = Math.round(delay / 60_000);
1427
+ console.error(storageFull
1428
+ ? `[engram] memory full (${storageFull.used ?? "?"}/${storageFull.limit ?? "?"}), ` +
1429
+ `pausing sync ${mins}m — new captures stay queued until space is freed`
1430
+ : `[engram] billing limit hit, backing off ${mins}m (attempt ${this.billingBackoffStep}): ${msg}`);
1431
+ }
294
1432
  if (storageFull) {
295
- console.error(`[engram] memory full (${storageFull.used ?? "?"}/${storageFull.limit ?? "?"}), ` +
296
- `pausing sync ${mins}m — new captures stay queued until space is freed`);
297
- recordFailure(msg, "storage_full", this.db.getPendingCount(), {
298
- used: storageFull.used,
299
- limit: storageFull.limit,
1433
+ recordFailure(msg, "storage_full", this.pendingCount(), {
1434
+ storage: { used: storageFull.used, limit: storageFull.limit },
1435
+ retryAt: this.nextRetryAt(),
300
1436
  });
1437
+ }
1438
+ else {
1439
+ recordFailure(msg, "billing", this.pendingCount(), { retryAt: this.nextRetryAt() });
1440
+ }
1441
+ }
1442
+ /**
1443
+ * The API key was rejected: pause sending on AUTH_RETRY_MS. Escalates once
1444
+ * per pause, like the billing backoff: sends rejected together are one
1445
+ * rejection. Captures keep queueing in daemon.db meanwhile.
1446
+ */
1447
+ enterAuthHold(msg) {
1448
+ if (!this.authHeld()) {
1449
+ const delay = AUTH_RETRY_MS[Math.min(this.authHoldStep, AUTH_RETRY_MS.length - 1)];
1450
+ this.authHeldUntil = Date.now() + delay;
1451
+ this.authHoldStep++;
1452
+ console.error(`[engram] API key rejected — sync paused. Retrying in ${Math.round(delay / 60_000)}m, ` +
1453
+ `or as soon as a new key is saved ('${engramCommand("auth login")}'): ${msg}`);
1454
+ }
1455
+ recordFailure(msg, "auth", this.pendingCount(), { retryAt: this.nextRetryAt() });
1456
+ }
1457
+ authHeld() {
1458
+ return Date.now() < this.authHeldUntil;
1459
+ }
1460
+ /**
1461
+ * The server refused a request for when it came, not for what it carried:
1462
+ * a rate limit, or a pause for maintenance (engram#596). Nothing is sent
1463
+ * from this account until the wait is over, and each pause in a row
1464
+ * without a request going through waits longer (retryDelay), up to a few
1465
+ * minutes. Escalates once per pause, like the other holds: requests
1466
+ * refused together are one refusal. The wait is drawn at random within
1467
+ * its range, so daemons refused together don't all come back together.
1468
+ */
1469
+ enterThrottle(msg, errType) {
1470
+ if (errType === "paused")
1471
+ this.throttlePaused = true;
1472
+ if (!this.throttled()) {
1473
+ this.throttleStep++;
1474
+ const delay = retryDelay(this.throttleStep);
1475
+ this.throttledUntil = Date.now() + delay;
1476
+ console.error(`[engram] ${errType === "paused" ? "Engram is paused for maintenance" : "rate limited"} — ` +
1477
+ `sending nothing for ${formatWait(delay)}, messages stay queued: ${msg}`);
1478
+ }
1479
+ recordFailure(msg, errType, this.pendingCount(), { retryAt: this.nextRetryAt() });
1480
+ }
1481
+ throttled() {
1482
+ return Date.now() < this.throttledUntil;
1483
+ }
1484
+ /**
1485
+ * A request with `run`'s key went through: the key works, and the server
1486
+ * takes requests again. A maintenance pause holds only sends, so only a
1487
+ * send (`sent`) shows one is over. Lifts no pause early; the next one
1488
+ * only starts over at the shortest wait.
1489
+ */
1490
+ requestWentThrough(run, sent) {
1491
+ if (this.active !== run)
301
1492
  return;
1493
+ this.authHoldStep = 0;
1494
+ if (sent || !this.throttlePaused) {
1495
+ this.throttleStep = 0;
1496
+ this.throttlePaused = false;
1497
+ }
1498
+ }
1499
+ /** True while sending with `run` must not or can only fail: its key is
1500
+ * no longer the one configured, the key was rejected, the account is
1501
+ * inside a billing backoff, or it waits out a rate limit or a pause. */
1502
+ halted(run) {
1503
+ return (this.active !== run ||
1504
+ this.authHeld() ||
1505
+ Date.now() < this.billingBackoffUntil ||
1506
+ this.throttled());
1507
+ }
1508
+ /**
1509
+ * When the daemon next tries what failed, for the status (engram#596):
1510
+ * the end of a pause that holds every send, else the earliest turn of a
1511
+ * conversation or a session waiting after a failure of its own. Null when
1512
+ * nothing waits for a set time.
1513
+ */
1514
+ nextRetryAt() {
1515
+ const now = Date.now();
1516
+ const hold = Math.max(this.authHeldUntil, this.billingBackoffUntil, this.throttledUntil);
1517
+ if (hold > now)
1518
+ return hold;
1519
+ let next = null;
1520
+ for (const waits of [this.sendRetry, this.createRetry]) {
1521
+ for (const { until } of waits.values()) {
1522
+ if (until > now && (next === null || until < next))
1523
+ next = until;
1524
+ }
1525
+ }
1526
+ return next;
1527
+ }
1528
+ /** Unsent messages the key in use will send, for the status: 0 while
1529
+ * signed out, and when daemon.db can't be read. */
1530
+ pendingCount() {
1531
+ const run = this.active;
1532
+ if (!run)
1533
+ return 0;
1534
+ try {
1535
+ return this.db.getPendingCount(run.fp);
1536
+ }
1537
+ catch {
1538
+ return 0;
302
1539
  }
303
- console.error(`[engram] billing limit hit, backing off ${mins}m (attempt ${this.billingBackoffStep}): ${msg}`);
304
- recordFailure(msg, "billing", this.db.getPendingCount());
305
1540
  }
306
1541
  /** Reset billing backoff after a successful sync. */
307
1542
  resetBillingBackoff() {
@@ -311,10 +1546,10 @@ export class Syncer {
311
1546
  this.billingBackoffUntil = 0;
312
1547
  this.billingBackoffStep = 0;
313
1548
  }
314
- async createConversation(sessionId, meta) {
1549
+ async createConversation(run, sessionId, meta) {
315
1550
  const host = meta.host ?? "claude-code";
316
1551
  const title = `${meta.projectDir || host} (${new Date().toISOString().slice(0, 16).replace("T", " ")})`;
317
- const { conversationId } = await this.client.createConversation({
1552
+ const { conversationId } = await run.client.createConversation({
318
1553
  title,
319
1554
  // Per-host tagging (engram#261) so captures are attributable and
320
1555
  // filterable by source tool.
@@ -327,16 +1562,51 @@ export class Syncer {
327
1562
  cwd: meta.cwd,
328
1563
  gitBranch: meta.gitBranch,
329
1564
  capturedBy: "engram-daemon",
1565
+ // Metadata rebuilt after the session's own was lost (engram#370).
1566
+ ...(meta.recovered ? { recovered: true } : {}),
330
1567
  },
331
1568
  });
332
- this.db.setSessionMap(sessionId, conversationId, {
333
- projectDir: meta.projectDir,
334
- cwd: meta.cwd,
335
- gitBranch: meta.gitBranch,
336
- });
337
1569
  return conversationId;
338
1570
  }
339
1571
  }
1572
+ function errorText(err) {
1573
+ const text = err instanceof Error ? err.message : String(err);
1574
+ if (text)
1575
+ return text;
1576
+ // The SDK gives no text for an error body it doesn't read (a 429 says why
1577
+ // in a field it doesn't look at); the status at least names it.
1578
+ const status = err?.status;
1579
+ return typeof status === "number" ? `HTTP ${status}` : "unknown error";
1580
+ }
1581
+ /** A wait of whole minutes, hours or days, in words: "10 minutes", "1 hour",
1582
+ * "3 days". */
1583
+ function waitInWords(ms) {
1584
+ const minutes = Math.round(ms / 60_000);
1585
+ if (minutes < 60)
1586
+ return plural(minutes, "minute");
1587
+ const hours = Math.round(minutes / 60);
1588
+ if (hours < 24)
1589
+ return plural(hours, "hour");
1590
+ return plural(Math.round(hours / 24), "day");
1591
+ }
1592
+ /** Wait before trying one thing again that failed again: the wait doubles
1593
+ * with each failure in a row (retryDelay). Returns it. */
1594
+ function waitAgain(waits, id) {
1595
+ const step = (waits.get(id)?.step ?? 0) + 1;
1596
+ const delay = retryDelay(step);
1597
+ waits.set(id, { until: Date.now() + delay, step });
1598
+ return delay;
1599
+ }
1600
+ /** Forget the waits of what no longer waits to go out. */
1601
+ function forgetDone(waits, still) {
1602
+ if (waits.size === 0)
1603
+ return;
1604
+ const keep = new Set(still);
1605
+ for (const id of waits.keys()) {
1606
+ if (!keep.has(id))
1607
+ waits.delete(id);
1608
+ }
1609
+ }
340
1610
  function rowToMessage(row) {
341
1611
  const msg = {
342
1612
  role: row.role,