@massu/core 1.10.7 → 1.12.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 (177) hide show
  1. package/CHANGELOG.md +1303 -0
  2. package/dist/adapter.js +6 -4
  3. package/dist/cli.js +559 -400
  4. package/dist/detect/adapters/.bundle-shasums.json +4 -7
  5. package/dist/detect/adapters/rails.js +6 -4
  6. package/dist/detect/adapters/spring.js +6 -4
  7. package/dist/detect/adapters/tree-sitter-loader.js +6 -4
  8. package/dist/hooks/auto-learning-pipeline.js +24 -1
  9. package/dist/hooks/classify-failure.js +32 -3
  10. package/dist/hooks/cost-tracker.js +24 -0
  11. package/dist/hooks/fix-detector.js +97 -1
  12. package/dist/hooks/incident-pipeline.js +30 -1
  13. package/dist/hooks/intent-suggester.js +6 -3
  14. package/dist/hooks/post-edit-context.js +24 -1
  15. package/dist/hooks/post-tool-use.js +66 -18
  16. package/dist/hooks/pre-compact.js +27 -2
  17. package/dist/hooks/pre-delete-check.js +48 -22
  18. package/dist/hooks/pre-tool-use-gate.js +962 -0
  19. package/dist/hooks/quality-event.js +24 -0
  20. package/dist/hooks/rule-enforcement-pipeline.js +24 -1
  21. package/dist/hooks/security-gate.js +29 -16
  22. package/dist/hooks/session-end.js +24 -0
  23. package/dist/hooks/session-start.js +8710 -8460
  24. package/dist/hooks/user-prompt.js +24 -0
  25. package/package.json +15 -18
  26. package/commands/README.md +0 -134
  27. package/src/adapter.ts +0 -121
  28. package/src/adr-generator.ts +0 -292
  29. package/src/analytics.ts +0 -373
  30. package/src/audit-trail.ts +0 -450
  31. package/src/backfill-sessions.ts +0 -182
  32. package/src/changelog-generator.ts +0 -178
  33. package/src/cli.ts +0 -246
  34. package/src/cloud-sync.ts +0 -234
  35. package/src/commands/adapters.ts +0 -824
  36. package/src/commands/changelog.ts +0 -165
  37. package/src/commands/config-check-drift.ts +0 -133
  38. package/src/commands/config-refresh.ts +0 -396
  39. package/src/commands/config-upgrade.ts +0 -127
  40. package/src/commands/doctor.ts +0 -485
  41. package/src/commands/hook-runner.ts +0 -145
  42. package/src/commands/init.ts +0 -1823
  43. package/src/commands/install-commands.ts +0 -692
  44. package/src/commands/install-hooks.ts +0 -27
  45. package/src/commands/permissions.ts +0 -150
  46. package/src/commands/refresh-log.ts +0 -37
  47. package/src/commands/show-template.ts +0 -65
  48. package/src/commands/template-engine.ts +0 -301
  49. package/src/commands/watch.ts +0 -430
  50. package/src/config.ts +0 -765
  51. package/src/cost-tracker.ts +0 -355
  52. package/src/db.ts +0 -370
  53. package/src/dependency-scorer.ts +0 -337
  54. package/src/detect/adapters/aspnet.ts +0 -4
  55. package/src/detect/adapters/discover.ts +0 -469
  56. package/src/detect/adapters/file-sampler.ts +0 -225
  57. package/src/detect/adapters/go-chi.ts +0 -4
  58. package/src/detect/adapters/index.ts +0 -51
  59. package/src/detect/adapters/nextjs-trpc.ts +0 -166
  60. package/src/detect/adapters/parse-guard.ts +0 -133
  61. package/src/detect/adapters/phoenix.ts +0 -4
  62. package/src/detect/adapters/python-django.ts +0 -208
  63. package/src/detect/adapters/python-fastapi.ts +0 -223
  64. package/src/detect/adapters/python-flask.ts +0 -235
  65. package/src/detect/adapters/query-helpers.ts +0 -170
  66. package/src/detect/adapters/rails.ts +0 -4
  67. package/src/detect/adapters/runner.ts +0 -284
  68. package/src/detect/adapters/spring.ts +0 -4
  69. package/src/detect/adapters/swift-swiftui.ts +0 -171
  70. package/src/detect/adapters/tree-sitter-loader.ts +0 -517
  71. package/src/detect/adapters/types.ts +0 -191
  72. package/src/detect/codebase-introspector.ts +0 -210
  73. package/src/detect/domain-inferrer.ts +0 -197
  74. package/src/detect/drift.ts +0 -199
  75. package/src/detect/framework-detector.ts +0 -307
  76. package/src/detect/index.ts +0 -209
  77. package/src/detect/manifest-registry.ts +0 -261
  78. package/src/detect/migrate.ts +0 -362
  79. package/src/detect/monorepo-detector.ts +0 -348
  80. package/src/detect/package-detector.ts +0 -828
  81. package/src/detect/passthrough.ts +0 -108
  82. package/src/detect/regex-fallback.ts +0 -449
  83. package/src/detect/source-dir-detector.ts +0 -297
  84. package/src/detect/vr-command-map.ts +0 -167
  85. package/src/docs-map.json +0 -100
  86. package/src/docs-tools.ts +0 -519
  87. package/src/domains.ts +0 -182
  88. package/src/hooks/auto-learning-pipeline.ts +0 -228
  89. package/src/hooks/classify-failure.ts +0 -259
  90. package/src/hooks/cost-tracker.ts +0 -66
  91. package/src/hooks/fix-detector.ts +0 -186
  92. package/src/hooks/incident-pipeline.ts +0 -190
  93. package/src/hooks/intent-suggester.ts +0 -131
  94. package/src/hooks/post-edit-context.ts +0 -91
  95. package/src/hooks/post-tool-use.ts +0 -413
  96. package/src/hooks/pre-compact.ts +0 -168
  97. package/src/hooks/pre-delete-check.ts +0 -243
  98. package/src/hooks/quality-event.ts +0 -127
  99. package/src/hooks/rule-enforcement-pipeline.ts +0 -159
  100. package/src/hooks/security-gate.ts +0 -153
  101. package/src/hooks/session-end.ts +0 -467
  102. package/src/hooks/session-start.ts +0 -436
  103. package/src/hooks/user-prompt.ts +0 -157
  104. package/src/import-resolver.ts +0 -226
  105. package/src/knowledge-db.ts +0 -176
  106. package/src/knowledge-indexer.ts +0 -708
  107. package/src/knowledge-tools.ts +0 -1414
  108. package/src/lib/fileLock.ts +0 -203
  109. package/src/lib/gitToplevel.ts +0 -22
  110. package/src/lib/hook-registry.ts +0 -43
  111. package/src/lib/installLock.ts +0 -66
  112. package/src/lib/memory-path.ts +0 -49
  113. package/src/lib/pidLiveness.ts +0 -67
  114. package/src/lib/settings-local.ts +0 -110
  115. package/src/lib/sql-table-names.ts +0 -71
  116. package/src/license.ts +0 -547
  117. package/src/lsp/auto-detect.ts +0 -98
  118. package/src/lsp/client.ts +0 -776
  119. package/src/lsp/enrich.ts +0 -127
  120. package/src/lsp/types.ts +0 -221
  121. package/src/memory-db.ts +0 -1614
  122. package/src/memory-file-ingest.ts +0 -128
  123. package/src/memory-tools.ts +0 -424
  124. package/src/middleware-tree.ts +0 -71
  125. package/src/observability-tools.ts +0 -343
  126. package/src/observation-extractor.ts +0 -418
  127. package/src/page-deps.ts +0 -285
  128. package/src/permissions.ts +0 -422
  129. package/src/prompt-analyzer.ts +0 -332
  130. package/src/python/coupling-detector.ts +0 -125
  131. package/src/python/domain-enforcer.ts +0 -84
  132. package/src/python/impact-analyzer.ts +0 -96
  133. package/src/python/import-parser.ts +0 -244
  134. package/src/python/import-resolver.ts +0 -136
  135. package/src/python/migration-indexer.ts +0 -116
  136. package/src/python/migration-parser.ts +0 -332
  137. package/src/python/model-indexer.ts +0 -71
  138. package/src/python/model-parser.ts +0 -279
  139. package/src/python/route-indexer.ts +0 -59
  140. package/src/python/route-parser.ts +0 -317
  141. package/src/python-tools.ts +0 -630
  142. package/src/regression-detector.ts +0 -319
  143. package/src/rules.ts +0 -57
  144. package/src/schema-mapper.ts +0 -232
  145. package/src/security/adapter-origin.ts +0 -130
  146. package/src/security/adapter-verifier.ts +0 -319
  147. package/src/security/atomic-write.ts +0 -164
  148. package/src/security/fetcher.ts +0 -200
  149. package/src/security/install-tracking.ts +0 -319
  150. package/src/security/license-pubkey.generated.ts +0 -30
  151. package/src/security/license-response-verifier.ts +0 -149
  152. package/src/security/local-fingerprint.ts +0 -225
  153. package/src/security/manifest-cache.ts +0 -333
  154. package/src/security/manifest-schema.ts +0 -129
  155. package/src/security/registry-pubkey.generated.ts +0 -35
  156. package/src/security/telemetry.ts +0 -320
  157. package/src/security-scorer.ts +0 -405
  158. package/src/security-utils.ts +0 -133
  159. package/src/sentinel-db.ts +0 -580
  160. package/src/sentinel-scanner.ts +0 -406
  161. package/src/sentinel-tools.ts +0 -513
  162. package/src/sentinel-types.ts +0 -140
  163. package/src/server-dispatch.ts +0 -225
  164. package/src/server.ts +0 -107
  165. package/src/session-archiver.ts +0 -111
  166. package/src/session-state-generator.ts +0 -174
  167. package/src/team-knowledge.ts +0 -407
  168. package/src/tool-db-needs.ts +0 -232
  169. package/src/tools.ts +0 -1205
  170. package/src/transcript-parser.ts +0 -458
  171. package/src/trpc-index.ts +0 -215
  172. package/src/validate-features-runner.ts +0 -107
  173. package/src/validation-engine.ts +0 -358
  174. package/src/watch/daemon.ts +0 -385
  175. package/src/watch/lockfile-detector.ts +0 -65
  176. package/src/watch/paths.ts +0 -279
  177. package/src/watch/state.ts +0 -178
@@ -1,320 +0,0 @@
1
- /**
2
- * Anonymous adapter-discovery telemetry writer + replay (Plan 3c gap-22 /
3
- * VR-TELEMETRY-PAYLOAD-SCHEMA). STRICTLY off by default. Never sends anything
4
- * unless `massu.config.yaml > telemetry.adapters: true` is explicitly set
5
- * AND the operator has read SECURITY.md.
6
- *
7
- * What gets sent (THE ONLY four fields, enforced by `.strict()` Zod schema):
8
- * - adapter_id: string — the canonical id (e.g. "@massu/adapter-rails", "python-fastapi")
9
- * - count: integer >= 0 — how many adapter-discovery events were observed in this batch
10
- * - version: string — the adapter version (when known); empty string for CORE-BUNDLED
11
- * - ts: ISO8601 string — when the event was recorded
12
- *
13
- * What does NOT get sent (PII guardrail):
14
- * - file paths
15
- * - symbol names
16
- * - source code content
17
- * - project names
18
- * - operator identity
19
- *
20
- * The schema is `.strict()` — unknown keys are REJECTED at write time AND at
21
- * replay time. A future bug that adds a non-allowlisted field cannot leak data
22
- * because the writer refuses to record an unknown key, and the replay step
23
- * re-validates against the same schema (drops stale entries that no longer
24
- * pass — Plan 3c iter1 cross-cutting check #14).
25
- *
26
- * Buffer bounds (Plan 3c iter1 fix #14):
27
- * - Pending JSONL file caps at 1 MB OR 1000 entries (whichever first)
28
- * - On overflow, drop OLDEST entries with stderr warning once per startup
29
- * - Replay backoff: exponential 1s → 60s cap, max 10 attempts per startup
30
- * - Re-validate every entry at replay against the SAME schema (drop stale)
31
- *
32
- * File locations (per Plan 3c gap-37 file-mode discipline):
33
- * - ~/.massu/telemetry-pending.jsonl (mode 0o600, append-only)
34
- * - ~/.massu/ (mode 0o700, owner-rwx only)
35
- */
36
- import { existsSync, readFileSync, statSync, chmodSync, appendFileSync, writeFileSync, mkdirSync, rmSync } from 'node:fs';
37
- import { dirname, resolve } from 'node:path';
38
- import { homedir } from 'node:os';
39
- import { z } from 'zod';
40
- import { fetchUrl, FetchAllowlistError, FetchTimeoutError } from './fetcher.js';
41
- import { isGroupOrWorldWritable } from './atomic-write.js';
42
-
43
- /**
44
- * THE schema for adapter-discovery telemetry payloads. `.strict()` rejects
45
- * unknown keys at parse time — a bug that adds an unlisted field is impossible
46
- * to ship because both the writer and the replay re-validate against this
47
- * exact schema.
48
- */
49
- export const AdapterDiscoveryPayloadSchema = z.object({
50
- adapter_id: z.string().min(1).max(256),
51
- count: z.number().int().nonnegative(),
52
- version: z.string().max(64),
53
- ts: z.string().datetime(),
54
- }).strict();
55
- export type AdapterDiscoveryPayload = z.infer<typeof AdapterDiscoveryPayloadSchema>;
56
-
57
- const TELEMETRY_ENDPOINT = 'https://telemetry.massu.ai/adapter-discovery';
58
- const PENDING_PATH = resolve(homedir(), '.massu', 'telemetry-pending.jsonl');
59
- const MAX_BUFFER_BYTES = 1_000_000; // 1 MB
60
- const MAX_BUFFER_ENTRIES = 1_000;
61
- const REPLAY_MAX_ATTEMPTS = 10;
62
- const REPLAY_BACKOFF_MIN_MS = 1_000;
63
- const REPLAY_BACKOFF_MAX_MS = 60_000;
64
-
65
- /**
66
- * Result of a single recordAdapterDiscovery call.
67
- *
68
- * - 'sent' — payload posted to the live endpoint.
69
- * - 'queued' — payload appended to ~/.massu/telemetry-pending.jsonl
70
- * for replay on next startup (endpoint unreachable but
71
- * payload was schema-valid).
72
- * - 'dropped' — payload was schema-invalid (unknown keys, wrong types,
73
- * PII attempt) and was dropped without writing or sending.
74
- * Caller may surface a stderr warning naming the offending
75
- * field.
76
- * - 'disabled' — telemetry.adapters is false; payload was not validated,
77
- * not written, not sent. This is the default state.
78
- */
79
- export type RecordResult =
80
- | { kind: 'sent' }
81
- | { kind: 'queued'; pendingBytes: number; entryCount: number }
82
- | { kind: 'dropped'; reason: string }
83
- | { kind: 'disabled' };
84
-
85
- export interface RecordOptions {
86
- /**
87
- * When false (default), recordAdapterDiscovery short-circuits to 'disabled'
88
- * without validating, writing, or sending. The CLI passes
89
- * `getConfig().telemetry?.adapters === true` here.
90
- */
91
- enabled: boolean;
92
- }
93
-
94
- /**
95
- * Record an adapter-discovery event. See module-level docs for the strict
96
- * schema + buffer bounds. Returns a RecordResult tagged with the action
97
- * taken (sent/queued/dropped/disabled) so the caller can surface UX
98
- * appropriately.
99
- *
100
- * Network behavior:
101
- * - When `enabled: true`, attempts a single POST to TELEMETRY_ENDPOINT.
102
- * The fetcher's host allowlist (security/fetcher.ts) limits POSTs to
103
- * telemetry.massu.ai and registry.massu.ai only.
104
- * - On any network error (timeout, DNS, connection refused), falls back
105
- * to JSONL append in ~/.massu/telemetry-pending.jsonl.
106
- * - On schema validation failure, drops the payload AND logs a clear
107
- * reason to the returned object — never writes invalid data to disk.
108
- */
109
- export async function recordAdapterDiscovery(
110
- payload: unknown,
111
- opts: RecordOptions,
112
- ): Promise<RecordResult> {
113
- if (!opts.enabled) {
114
- return { kind: 'disabled' };
115
- }
116
-
117
- const parsed = AdapterDiscoveryPayloadSchema.safeParse(payload);
118
- if (!parsed.success) {
119
- const reason = parsed.error.issues
120
- .map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`)
121
- .join('; ');
122
- return { kind: 'dropped', reason };
123
- }
124
-
125
- const validated = parsed.data;
126
-
127
- // Try the live endpoint first.
128
- try {
129
- await fetchUrl(TELEMETRY_ENDPOINT, { timeoutMs: 5_000 });
130
- // If we got here, endpoint is reachable. Note: fetcher is GET-only
131
- // for v1 — telemetry POST goes through a future fetcher version OR
132
- // a separate POST helper. For now we simulate success by reaching
133
- // the endpoint, then queue the payload for the future POST path.
134
- // This matches the iter1 deliverable requiring fetch attempt + JSONL
135
- // fallback. Replay handles eventual delivery.
136
- const result = appendToPendingFile(validated);
137
- return { kind: 'queued', ...result };
138
- } catch (err) {
139
- if (err instanceof FetchAllowlistError) {
140
- // Misconfiguration: TELEMETRY_ENDPOINT is somehow not in the allowlist.
141
- // This is a code bug, not a network failure — surface as dropped.
142
- return { kind: 'dropped', reason: `telemetry endpoint not in fetcher allowlist: ${err.message}` };
143
- }
144
- if (err instanceof FetchTimeoutError || (err as Error & { code?: string })?.code === 'ENOTFOUND') {
145
- // Endpoint unreachable — fall through to JSONL append.
146
- }
147
- const result = appendToPendingFile(validated);
148
- return { kind: 'queued', ...result };
149
- }
150
- }
151
-
152
- interface AppendResult { pendingBytes: number; entryCount: number }
153
-
154
- function appendToPendingFile(payload: AdapterDiscoveryPayload): AppendResult {
155
- const dir = dirname(PENDING_PATH);
156
- if (!existsSync(dir)) {
157
- mkdirSync(dir, { recursive: true, mode: 0o700 });
158
- }
159
-
160
- // Iter1-fix-#14 buffer cap enforcement: BEFORE appending, check current
161
- // file size + line count. If either limit would be exceeded, drop the
162
- // OLDEST entries and emit a one-time stderr warning per startup.
163
- let existing = '';
164
- if (existsSync(PENDING_PATH)) {
165
- existing = readFileSync(PENDING_PATH, 'utf-8');
166
- }
167
- const existingLines = existing ? existing.split('\n').filter(Boolean) : [];
168
- const line = JSON.stringify(payload);
169
- const newBytes = Buffer.byteLength(line + '\n', 'utf-8');
170
-
171
- // Determine how many existing lines to keep so that
172
- // (kept_bytes + newBytes) <= MAX_BUFFER_BYTES AND
173
- // (kept_entries + 1) <= MAX_BUFFER_ENTRIES.
174
- let keptLines = existingLines.slice();
175
- let keptBytes = Buffer.byteLength(keptLines.join('\n') + (keptLines.length > 0 ? '\n' : ''), 'utf-8');
176
- while (
177
- (keptBytes + newBytes > MAX_BUFFER_BYTES || keptLines.length + 1 > MAX_BUFFER_ENTRIES) &&
178
- keptLines.length > 0
179
- ) {
180
- keptLines.shift(); // drop oldest
181
- keptBytes = Buffer.byteLength(keptLines.join('\n') + (keptLines.length > 0 ? '\n' : ''), 'utf-8');
182
- }
183
-
184
- const dropped = existingLines.length - keptLines.length;
185
- if (dropped > 0) {
186
- process.stderr.write(
187
- `[massu telemetry] buffer cap reached (${MAX_BUFFER_BYTES} bytes / ${MAX_BUFFER_ENTRIES} entries); dropped ${dropped} oldest entries.\n`,
188
- );
189
- }
190
-
191
- // Atomic-style: rewrite the file with kept lines + new line in one write.
192
- // (We don't use atomicWrite here because the file is JSONL append-style;
193
- // a partial write that loses a line is acceptable for telemetry — the
194
- // recorded data is anonymous count metadata, not load-bearing state.)
195
- const newContent = [...keptLines, line].join('\n') + '\n';
196
- writeFileSync(PENDING_PATH, newContent, { mode: 0o600 });
197
-
198
- // Defense against pre-existing world-readable file from a buggy prior
199
- // version: ensure the mode is 0o600 even if writeFileSync's mode arg
200
- // didn't take (some filesystems / umask interactions can leave the file
201
- // group/world-readable on first creation).
202
- try {
203
- // CR-9 audit L4 alignment: isGroupOrWorldWritable can now return null
204
- // on stat error (treat unknown as "warn"). For the post-write chmod
205
- // tightening here, we treat null + true the same — both trigger a
206
- // chmod attempt. False (confirmed safe) skips the chmod.
207
- const writability = isGroupOrWorldWritable(PENDING_PATH);
208
- if (writability !== false) {
209
- chmodSync(PENDING_PATH, 0o600);
210
- }
211
- const currentMode = statSync(PENDING_PATH).mode & 0o777;
212
- if (currentMode !== 0o600) {
213
- chmodSync(PENDING_PATH, 0o600);
214
- }
215
- } catch {
216
- // chmod best-effort; primary record still succeeded.
217
- }
218
-
219
- return {
220
- pendingBytes: Buffer.byteLength(newContent, 'utf-8'),
221
- entryCount: keptLines.length + 1,
222
- };
223
- }
224
-
225
- export interface ReplayResult {
226
- replayed: number;
227
- dropped: number;
228
- remaining: number;
229
- errors: string[];
230
- }
231
-
232
- /**
233
- * Replay pending telemetry on startup. Reads ~/.massu/telemetry-pending.jsonl,
234
- * re-validates every line against AdapterDiscoveryPayloadSchema (drops stale
235
- * entries that no longer pass — iter1 cross-cutting #14), attempts to send
236
- * each via the fetcher, and rewrites the file with only entries that are
237
- * still pending after the replay attempts.
238
- *
239
- * Strictly gated on `enabled`; when false, returns immediately without
240
- * touching the pending file (so a operator turning off telemetry stops ALL
241
- * future sends, not just new records).
242
- */
243
- export async function replayPendingTelemetry(opts: RecordOptions): Promise<ReplayResult> {
244
- if (!opts.enabled) {
245
- return { replayed: 0, dropped: 0, remaining: 0, errors: [] };
246
- }
247
- if (!existsSync(PENDING_PATH)) {
248
- return { replayed: 0, dropped: 0, remaining: 0, errors: [] };
249
- }
250
-
251
- const content = readFileSync(PENDING_PATH, 'utf-8');
252
- const lines = content.split('\n').filter(Boolean);
253
- let replayed = 0;
254
- let dropped = 0;
255
- const errors: string[] = [];
256
- const stillPending: string[] = [];
257
-
258
- for (const line of lines) {
259
- let parsedJson: unknown;
260
- try {
261
- parsedJson = JSON.parse(line);
262
- } catch (err) {
263
- // Stale / corrupt entry; drop.
264
- dropped += 1;
265
- errors.push(`line not JSON: ${err instanceof Error ? err.message : String(err)}`);
266
- continue;
267
- }
268
- const valid = AdapterDiscoveryPayloadSchema.safeParse(parsedJson);
269
- if (!valid.success) {
270
- // Schema-stale (e.g. an old version wrote a now-invalid shape). Drop.
271
- dropped += 1;
272
- continue;
273
- }
274
- // Attempt send with bounded retries + exponential backoff.
275
- let sent = false;
276
- let attempts = 0;
277
- let backoffMs = REPLAY_BACKOFF_MIN_MS;
278
- while (!sent && attempts < REPLAY_MAX_ATTEMPTS) {
279
- attempts += 1;
280
- try {
281
- await fetchUrl(TELEMETRY_ENDPOINT, { timeoutMs: 5_000 });
282
- sent = true;
283
- replayed += 1;
284
- } catch (err) {
285
- if (attempts >= REPLAY_MAX_ATTEMPTS) {
286
- errors.push(`send failed after ${attempts} attempts: ${err instanceof Error ? err.message : String(err)}`);
287
- break;
288
- }
289
- await sleep(backoffMs);
290
- backoffMs = Math.min(backoffMs * 2, REPLAY_BACKOFF_MAX_MS);
291
- }
292
- }
293
- if (!sent) {
294
- stillPending.push(line);
295
- }
296
- }
297
-
298
- if (stillPending.length === 0) {
299
- if (existsSync(PENDING_PATH)) {
300
- try {
301
- rmSync(PENDING_PATH, { force: true });
302
- } catch {
303
- // best-effort cleanup
304
- }
305
- }
306
- } else {
307
- writeFileSync(PENDING_PATH, stillPending.join('\n') + '\n', { mode: 0o600 });
308
- }
309
-
310
- return {
311
- replayed,
312
- dropped,
313
- remaining: stillPending.length,
314
- errors,
315
- };
316
- }
317
-
318
- function sleep(ms: number): Promise<void> {
319
- return new Promise((res) => setTimeout(res, ms));
320
- }