* Drain in-memory state to the buffer, then send completed-day rollups and * lifecycle events. Bounded by `timeoutMs`; leftovers stay buffered for the * next process. Awaited only where latency is invisible (install/init).
(timeoutMs: number = DEFAULT_FLUSH_TIMEOUT_MS)
| 275 | * next process. Awaited only where latency is invisible (install/init). |
| 276 | */ |
| 277 | async flushNow(timeoutMs: number = DEFAULT_FLUSH_TIMEOUT_MS): Promise<void> { |
| 278 | if (!this.isEnabled()) return; |
| 279 | try { |
| 280 | this.persistSync(); |
| 281 | this.recoverStaleClaims(); |
| 282 | const claim = this.claimQueue(); |
| 283 | if (!claim) return; |
| 284 | const { claimPath, lines } = claim; |
| 285 | const today = this.utcDay(); |
| 286 | const sendable: BufferLine[] = []; |
| 287 | const keep: BufferLine[] = []; |
| 288 | for (const line of lines) { |
| 289 | if ('ev' in line) sendable.push(line); |
| 290 | else if (line.d < today) sendable.push(line); |
| 291 | else keep.push(line); |
| 292 | } |
| 293 | let failed: BufferLine[] = []; |
| 294 | if (sendable.length > 0) { |
| 295 | // Consent gate: the one-time notice precedes the FIRST bytes that |
| 296 | // ever leave the machine (and mints the machine id). Recording only |
| 297 | // buffers locally, so it stays silent — this lets the installer show |
| 298 | // its explicit consent toggle before any notice can fire, instead of |
| 299 | // the preAction usage count pre-empting it. An explicit installer/CLI |
| 300 | // choice sets first_run_notice_shown and suppresses this permanently. |
| 301 | this.firstRunNotice(); |
| 302 | failed = await this.send(sendable, timeoutMs); |
| 303 | } |
| 304 | // Whatever didn't go out returns to the queue (append — writers may |
| 305 | // have created a fresh queue file while we held the claim). |
| 306 | const back = [...failed, ...keep]; |
| 307 | if (back.length > 0) this.appendLines(back); |
| 308 | try { fs.rmSync(claimPath, { force: true }); } catch { /* fail silent */ } |
| 309 | } catch { |
| 310 | /* fail silent */ |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | /** |
| 315 | * Periodic flush for long-lived processes (MCP daemon / serve). Unref'd so |
no test coverage detected