magpie-multi-usage 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,670 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { isValidCalendarMonth, normalizeFeedRow } from "./aggregator.mjs";
6
+ import {
7
+ assertContainedPath,
8
+ ensureDir,
9
+ readJsonStrict,
10
+ withFileLock,
11
+ writeJsonAtomic,
12
+ } from "./atomic-fs.mjs";
13
+ import { getConfigPaths, normalizeDeviceName, resolveMagpieConfigDir } from "./config.mjs";
14
+
15
+ export const DEFAULT_MAGPIE_PORT = 3425;
16
+ export const DEVICE_ID_PATTERN = /^[0-9a-f]{8,64}$/;
17
+ const MAX_FEED_RESPONSE_BYTES = 32 * 1024 * 1024;
18
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
19
+ const WILDCARD_HOSTS = new Set(["0.0.0.0", "::", "[::]", "*"]);
20
+ const CURSOR_RESET_CODES = new Set([
21
+ "cursor_expired",
22
+ "cursor_reset",
23
+ "cursor_filter_changed",
24
+ "cursor_invalid",
25
+ ]);
26
+
27
+ export class MagpieClientError extends Error {
28
+ constructor(code, message, options) {
29
+ super(message, options);
30
+ this.name = "MagpieClientError";
31
+ this.code = code;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Resolve Magpie's local loopback gateway base URL.
37
+ */
38
+ export async function resolveGatewayBaseUrl({
39
+ env = process.env,
40
+ magpieConfigDir,
41
+ homeDir = os.homedir(),
42
+ } = {}) {
43
+ const rawAddr = typeof env.MAGPIE_ADDR === "string" ? env.MAGPIE_ADDR.trim() : "";
44
+ if (rawAddr) {
45
+ const withScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(rawAddr)
46
+ ? rawAddr
47
+ : `http://${rawAddr}`;
48
+ let parsed;
49
+ try {
50
+ parsed = new URL(withScheme);
51
+ } catch (error) {
52
+ throw new MagpieClientError("INVALID_GATEWAY_ADDR", `Invalid MAGPIE_ADDR: ${rawAddr}`, { cause: error });
53
+ }
54
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
55
+ throw new MagpieClientError("INVALID_GATEWAY_ADDR", "MAGPIE_ADDR must use http or https.");
56
+ }
57
+ if (WILDCARD_HOSTS.has(parsed.hostname)) {
58
+ parsed.hostname = "127.0.0.1";
59
+ }
60
+ if (!LOOPBACK_HOSTS.has(parsed.hostname)) {
61
+ throw new MagpieClientError("NON_LOOPBACK_GATEWAY", "MAGPIE_ADDR must resolve to a loopback host.");
62
+ }
63
+ return parsed.origin;
64
+ }
65
+
66
+ const configDir = magpieConfigDir ? path.resolve(magpieConfigDir) : resolveMagpieConfigDir({ env, homeDir });
67
+ const settingsFile = path.join(configDir, "settings.json");
68
+ const settings = await readJsonStrict(settingsFile);
69
+
70
+ if (settings.status === "error") {
71
+ throw new MagpieClientError(
72
+ "MAGPIE_SETTINGS_READ_ERROR",
73
+ `Failed to read Magpie settings at ${settingsFile}: ${settings.code}`,
74
+ { cause: settings.error },
75
+ );
76
+ }
77
+ if (settings.status === "ok" && settings.value && typeof settings.value === "object") {
78
+ const port = Number(settings.value.port);
79
+ if (Number.isInteger(port) && port >= 1 && port <= 65535) {
80
+ return `http://127.0.0.1:${port}`;
81
+ }
82
+ }
83
+
84
+ return `http://127.0.0.1:${DEFAULT_MAGPIE_PORT}`;
85
+ }
86
+
87
+ async function readPluginStateStrict(stateFile) {
88
+ const result = await readJsonStrict(stateFile);
89
+ if (result.status === "missing") {
90
+ return {};
91
+ }
92
+ if (result.status === "error") {
93
+ throw new MagpieClientError(
94
+ "STATE_READ_ERROR",
95
+ `Failed to read plugin state at ${stateFile}: ${result.code}`,
96
+ { cause: result.error },
97
+ );
98
+ }
99
+ if (result.value === null || typeof result.value !== "object" || Array.isArray(result.value)) {
100
+ throw new MagpieClientError("STATE_INVALID", `Plugin state at ${stateFile} must be a JSON object.`);
101
+ }
102
+ return result.value;
103
+ }
104
+
105
+ /**
106
+ * Resolve this machine's persistent device ID and display name.
107
+ *
108
+ * Reads <magpieConfigDir>/usage-computer.json read-only. If absent or unparseable,
109
+ * generates and persists a stable 16-char lowercase hex ID under <dataDir>/state.json
110
+ * without ever writing to Magpie's config directory.
111
+ */
112
+ export async function resolveDeviceIdentity({
113
+ dataDir,
114
+ magpieConfigDir,
115
+ deviceNameOverride = "",
116
+ hostname = os.hostname(),
117
+ env = process.env,
118
+ homeDir = os.homedir(),
119
+ } = {}) {
120
+ if (!dataDir) {
121
+ throw new MagpieClientError("MISSING_DATA_DIR", "dataDir is required to resolve device identity.");
122
+ }
123
+
124
+ const configDir = magpieConfigDir ? path.resolve(magpieConfigDir) : resolveMagpieConfigDir({ env, homeDir });
125
+ const computerFile = path.join(configDir, "usage-computer.json");
126
+ const computer = await readJsonStrict(computerFile);
127
+
128
+ let deviceId = "";
129
+ let magpieName = "";
130
+ let source = "fallback";
131
+
132
+ if (computer.status === "ok" && computer.value && typeof computer.value === "object") {
133
+ const candidateId = typeof computer.value.id === "string" ? computer.value.id.trim().toLowerCase() : "";
134
+ if (DEVICE_ID_PATTERN.test(candidateId)) {
135
+ deviceId = candidateId;
136
+ source = "magpie";
137
+ if (typeof computer.value.name === "string") {
138
+ magpieName = computer.value.name.trim();
139
+ }
140
+ }
141
+ }
142
+
143
+ if (!deviceId) {
144
+ const paths = getConfigPaths(dataDir);
145
+ await withFileLock(paths.syncLockFile, async () => {
146
+ const state = await readPluginStateStrict(paths.stateFile);
147
+ const existing = typeof state.fallbackDeviceId === "string" ? state.fallbackDeviceId.trim().toLowerCase() : "";
148
+
149
+ if (DEVICE_ID_PATTERN.test(existing)) {
150
+ deviceId = existing;
151
+ } else {
152
+ deviceId = crypto.randomBytes(8).toString("hex");
153
+ await ensureDir(paths.root, 0o700);
154
+ await writeJsonAtomic(
155
+ paths.stateFile,
156
+ {
157
+ ...state,
158
+ fallbackDeviceId: deviceId,
159
+ },
160
+ { mode: 0o600 },
161
+ );
162
+ }
163
+ });
164
+ }
165
+
166
+ const cleanHost = typeof hostname === "string" ? hostname.replace(/\.local$/i, "") : "";
167
+ const displayName =
168
+ normalizeDeviceName(deviceNameOverride) ||
169
+ normalizeDeviceName(magpieName) ||
170
+ normalizeDeviceName(cleanHost) ||
171
+ deviceId;
172
+
173
+ return {
174
+ deviceId,
175
+ displayName,
176
+ source,
177
+ };
178
+ }
179
+
180
+ function parseErrorCodeFromBody(bodyText) {
181
+ if (!bodyText) {
182
+ return "";
183
+ }
184
+ try {
185
+ const parsed = JSON.parse(bodyText);
186
+ if (typeof parsed?.error?.code === "string") {
187
+ return parsed.error.code;
188
+ }
189
+ if (typeof parsed?.code === "string") {
190
+ return parsed.code;
191
+ }
192
+ if (typeof parsed?.error === "string") {
193
+ return parsed.error;
194
+ }
195
+ } catch {
196
+ // Non-JSON error body.
197
+ }
198
+ return "";
199
+ }
200
+
201
+ function shouldResetCursor(status, errorCode) {
202
+ if (status === 410) {
203
+ return true;
204
+ }
205
+ if (status === 400 && (!errorCode || CURSOR_RESET_CODES.has(errorCode))) {
206
+ return true;
207
+ }
208
+ return false;
209
+ }
210
+
211
+ async function readBoundedText(response, maxBytes = MAX_FEED_RESPONSE_BYTES) {
212
+ const contentLength = Number(response.headers?.get?.("content-length") || 0);
213
+ if (contentLength > maxBytes) {
214
+ throw new MagpieClientError("MAGPIE_FEED_TOO_LARGE", `Feed response exceeded ${maxBytes} bytes.`);
215
+ }
216
+ const text = await response.text();
217
+ if (Buffer.byteLength(text, "utf8") > maxBytes) {
218
+ throw new MagpieClientError("MAGPIE_FEED_TOO_LARGE", `Feed response exceeded ${maxBytes} bytes.`);
219
+ }
220
+ return text;
221
+ }
222
+
223
+ /**
224
+ * Pull pages from Magpie's local incremental usage feed:
225
+ * GET /v1/magpie/usage/requests?computer=this&cursor=<cursor>&limit=<limit>
226
+ *
227
+ * Rejects redirects (redirect: "error") so requests can never leave loopback,
228
+ * and returns hasMore: true when a non-reset incremental pull hits maxPages so
229
+ * progress can be checkpointed across runs.
230
+ */
231
+ export async function pullLocalUsageFeed({
232
+ baseUrl,
233
+ cursor = "start",
234
+ limit = 500,
235
+ maxPages = 200,
236
+ fetchImpl = globalThis.fetch,
237
+ timeoutMs = 15000,
238
+ } = {}) {
239
+ if (!baseUrl) {
240
+ throw new MagpieClientError("MISSING_GATEWAY_URL", "baseUrl is required.");
241
+ }
242
+ if (typeof fetchImpl !== "function") {
243
+ throw new MagpieClientError("MISSING_FETCH", "A fetch implementation is required.");
244
+ }
245
+
246
+ const normalizedBase = baseUrl.replace(/\/+$/, "");
247
+ let currentCursor = typeof cursor === "string" && cursor.trim() ? cursor.trim() : "start";
248
+ let resetRequired = false;
249
+ let didReset = false;
250
+ let pagesFetched = 0;
251
+ let events = [];
252
+
253
+ while (true) {
254
+ if (pagesFetched >= maxPages) {
255
+ if (resetRequired) {
256
+ throw new MagpieClientError(
257
+ "FEED_PAGE_LIMIT_EXCEEDED",
258
+ `Exceeded maximum feed page count (${maxPages}) during full reset.`,
259
+ );
260
+ }
261
+ return {
262
+ events,
263
+ nextCursor: currentCursor,
264
+ resetRequired,
265
+ pagesFetched,
266
+ hasMore: true,
267
+ };
268
+ }
269
+
270
+ const url = `${normalizedBase}/v1/magpie/usage/requests?computer=this&cursor=${encodeURIComponent(currentCursor)}&limit=${encodeURIComponent(String(limit))}`;
271
+ const controller = new AbortController();
272
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
273
+
274
+ let response;
275
+ let bodyText;
276
+ try {
277
+ response = await fetchImpl(url, {
278
+ method: "GET",
279
+ headers: { Accept: "application/json" },
280
+ redirect: "error",
281
+ signal: controller.signal,
282
+ });
283
+ bodyText = await readBoundedText(response);
284
+ } catch (error) {
285
+ if (error instanceof MagpieClientError) {
286
+ throw error;
287
+ }
288
+ throw new MagpieClientError(
289
+ error?.name === "AbortError" ? "MAGPIE_FEED_TIMEOUT" : "MAGPIE_FEED_NETWORK_ERROR",
290
+ `Failed to query Magpie usage feed: ${error?.message || String(error)}`,
291
+ { cause: error },
292
+ );
293
+ } finally {
294
+ clearTimeout(timer);
295
+ }
296
+
297
+ if (!response.ok) {
298
+ const errorCode = parseErrorCodeFromBody(bodyText);
299
+ if (!didReset && currentCursor !== "start" && shouldResetCursor(response.status, errorCode)) {
300
+ didReset = true;
301
+ resetRequired = true;
302
+ currentCursor = "start";
303
+ pagesFetched = 0;
304
+ events = [];
305
+ continue;
306
+ }
307
+ throw new MagpieClientError(
308
+ "MAGPIE_FEED_HTTP_ERROR",
309
+ `Magpie usage feed returned HTTP ${response.status}${errorCode ? ` (${errorCode})` : ""}.`,
310
+ );
311
+ }
312
+
313
+ let payload;
314
+ try {
315
+ payload = JSON.parse(bodyText);
316
+ } catch (error) {
317
+ throw new MagpieClientError("MAGPIE_FEED_PARSE_ERROR", "Magpie usage feed returned invalid JSON.", {
318
+ cause: error,
319
+ });
320
+ }
321
+
322
+ if (
323
+ payload === null ||
324
+ typeof payload !== "object" ||
325
+ !Array.isArray(payload.rows) ||
326
+ (payload.deleted !== undefined && !Array.isArray(payload.deleted)) ||
327
+ typeof payload.next_cursor !== "string" ||
328
+ typeof payload.has_more !== "boolean"
329
+ ) {
330
+ throw new MagpieClientError("MAGPIE_FEED_SCHEMA_ERROR", "Magpie usage feed returned an unexpected payload shape.");
331
+ }
332
+
333
+ pagesFetched += 1;
334
+
335
+ // Interleave page rows and tombstones in seq order when seq is present so a
336
+ // delete followed by a re-insert at a higher seq never loses the newer row.
337
+ const pageEvents = [];
338
+ let order = 0;
339
+ for (const row of payload.rows) {
340
+ pageEvents.push({
341
+ type: "upsert",
342
+ seq: Number.isInteger(row?.seq) ? row.seq : null,
343
+ order: order++,
344
+ row,
345
+ });
346
+ }
347
+ for (const tombstone of payload.deleted || []) {
348
+ pageEvents.push({
349
+ type: "delete",
350
+ seq: Number.isInteger(tombstone?.seq) ? tombstone.seq : null,
351
+ order: order++,
352
+ tombstone,
353
+ });
354
+ }
355
+ pageEvents.sort((a, b) => {
356
+ if (a.seq !== null && b.seq !== null && a.seq !== b.seq) {
357
+ return a.seq - b.seq;
358
+ }
359
+ return a.order - b.order;
360
+ });
361
+ events.push(...pageEvents);
362
+
363
+ const nextCursor = payload.next_cursor;
364
+ if (!payload.has_more) {
365
+ return {
366
+ events,
367
+ nextCursor,
368
+ resetRequired,
369
+ pagesFetched,
370
+ hasMore: false,
371
+ };
372
+ }
373
+
374
+ if (!nextCursor || nextCursor === currentCursor) {
375
+ throw new MagpieClientError("MAGPIE_FEED_CURSOR_STALLED", "Magpie usage feed cursor did not advance while has_more is true.");
376
+ }
377
+ currentCursor = nextCursor;
378
+ }
379
+ }
380
+
381
+ function resolveContainedMonthFile(localMonthsDir, month) {
382
+ if (!isValidCalendarMonth(month)) {
383
+ throw new MagpieClientError("INVALID_MONTH_KEY", `Invalid ledger month key: ${String(month)}`);
384
+ }
385
+ return assertContainedPath(localMonthsDir, path.join(localMonthsDir, `${month}.json`));
386
+ }
387
+
388
+ async function readLocalMonthRows(localMonthsDir, month) {
389
+ const monthFile = resolveContainedMonthFile(localMonthsDir, month);
390
+ const result = await readJsonStrict(monthFile);
391
+ if (result.status === "missing") {
392
+ return Object.create(null);
393
+ }
394
+ if (result.status === "error") {
395
+ throw new MagpieClientError(
396
+ "LOCAL_LEDGER_READ_ERROR",
397
+ `Failed to read local monthly ledger at ${monthFile}: ${result.code}`,
398
+ { cause: result.error },
399
+ );
400
+ }
401
+ if (
402
+ result.value === null ||
403
+ typeof result.value !== "object" ||
404
+ result.value.rows === null ||
405
+ typeof result.value.rows !== "object" ||
406
+ Array.isArray(result.value.rows)
407
+ ) {
408
+ throw new MagpieClientError("LOCAL_LEDGER_INVALID", `Local monthly ledger at ${monthFile} has an invalid structure.`);
409
+ }
410
+ const out = Object.create(null);
411
+ for (const key of Object.keys(result.value.rows)) {
412
+ Object.defineProperty(out, key, {
413
+ value: result.value.rows[key],
414
+ enumerable: true,
415
+ configurable: true,
416
+ writable: true,
417
+ });
418
+ }
419
+ return out;
420
+ }
421
+
422
+ async function rebuildRowIndexFromMonths(localMonthsDir, months) {
423
+ const rebuilt = Object.create(null);
424
+ for (const month of months) {
425
+ const rows = await readLocalMonthRows(localMonthsDir, month);
426
+ for (const id of Object.keys(rows)) {
427
+ Object.defineProperty(rebuilt, id, {
428
+ value: month,
429
+ enumerable: true,
430
+ configurable: true,
431
+ writable: true,
432
+ });
433
+ }
434
+ }
435
+ return rebuilt;
436
+ }
437
+
438
+ async function readRowIndex(indexFile, { localMonthsDir, existingMonths, cursorStarted }) {
439
+ const result = await readJsonStrict(indexFile);
440
+ if (result.status === "missing") {
441
+ // If local months exist while index was lost, rebuild the index from ledger
442
+ // files rather than silently disabling tombstone deletions.
443
+ if (cursorStarted && existingMonths.length > 0) {
444
+ return rebuildRowIndexFromMonths(localMonthsDir, existingMonths);
445
+ }
446
+ return Object.create(null);
447
+ }
448
+ if (result.status === "error") {
449
+ throw new MagpieClientError(
450
+ "ROW_INDEX_READ_ERROR",
451
+ `Failed to read local row index at ${indexFile}: ${result.code}`,
452
+ { cause: result.error },
453
+ );
454
+ }
455
+ if (result.value === null || typeof result.value !== "object" || Array.isArray(result.value)) {
456
+ throw new MagpieClientError("ROW_INDEX_INVALID", `Local row index at ${indexFile} must be a JSON object.`);
457
+ }
458
+
459
+ const out = Object.create(null);
460
+ for (const id of Object.keys(result.value)) {
461
+ const month = result.value[id];
462
+ if (!isValidCalendarMonth(month)) {
463
+ throw new MagpieClientError("ROW_INDEX_INVALID", `Invalid month "${String(month)}" in row index for ${id}.`);
464
+ }
465
+ Object.defineProperty(out, id, {
466
+ value: month,
467
+ enumerable: true,
468
+ configurable: true,
469
+ writable: true,
470
+ });
471
+ }
472
+ return out;
473
+ }
474
+
475
+ /**
476
+ * Load all persisted normalized local rows for a specific YYYY-MM month.
477
+ */
478
+ export async function loadLocalMonthRows(dataDir, month) {
479
+ const { localMonthsDir } = getConfigPaths(dataDir);
480
+ const rowsById = await readLocalMonthRows(localMonthsDir, month);
481
+ return Object.values(rowsById);
482
+ }
483
+
484
+ /**
485
+ * List all locally stored YYYY-MM month keys in ascending order.
486
+ */
487
+ export async function listLocalMonths(dataDir) {
488
+ const { localMonthsDir } = getConfigPaths(dataDir);
489
+ let entries;
490
+ try {
491
+ entries = await fs.readdir(localMonthsDir);
492
+ } catch (error) {
493
+ if (error && error.code === "ENOENT") {
494
+ return [];
495
+ }
496
+ throw error;
497
+ }
498
+
499
+ return entries
500
+ .filter((name) => /^\d{4}-\d{2}\.json$/.test(name) && isValidCalendarMonth(name.slice(0, 7)))
501
+ .map((name) => name.slice(0, 7))
502
+ .sort();
503
+ }
504
+
505
+ /**
506
+ * Incrementally sync Magpie's local usage feed into partitioned JSON monthly
507
+ * ledgers under <dataDir>/local-months/<YYYY-MM>.json, serialized across
508
+ * processes via <dataDir>/.sync.lock.
509
+ */
510
+ export async function syncLocalLedger({
511
+ dataDir,
512
+ baseUrl,
513
+ fetchImpl = globalThis.fetch,
514
+ limit = 500,
515
+ maxPages = 200,
516
+ timeoutMs = 15000,
517
+ timeZone,
518
+ } = {}) {
519
+ if (!dataDir) {
520
+ throw new MagpieClientError("MISSING_DATA_DIR", "dataDir is required.");
521
+ }
522
+
523
+ const paths = getConfigPaths(dataDir);
524
+
525
+ return withFileLock(paths.syncLockFile, async () => {
526
+ const state = await readPluginStateStrict(paths.stateFile);
527
+ const startCursor = typeof state.feedCursor === "string" && state.feedCursor.trim()
528
+ ? state.feedCursor.trim()
529
+ : "start";
530
+
531
+ const feed = await pullLocalUsageFeed({
532
+ baseUrl,
533
+ cursor: startCursor,
534
+ limit,
535
+ maxPages,
536
+ fetchImpl,
537
+ timeoutMs,
538
+ });
539
+
540
+ const existingMonths = await listLocalMonths(dataDir);
541
+ const rowIndex = feed.resetRequired
542
+ ? Object.create(null)
543
+ : await readRowIndex(paths.localRowIndexFile, {
544
+ localMonthsDir: paths.localMonthsDir,
545
+ existingMonths,
546
+ cursorStarted: startCursor !== "start",
547
+ });
548
+
549
+ const loadedMonths = new Map();
550
+ const dirtyMonths = new Set();
551
+
552
+ if (feed.resetRequired) {
553
+ for (const month of existingMonths) {
554
+ loadedMonths.set(month, Object.create(null));
555
+ dirtyMonths.add(month);
556
+ }
557
+ }
558
+
559
+ async function getMonthMap(month) {
560
+ if (!loadedMonths.has(month)) {
561
+ loadedMonths.set(month, await readLocalMonthRows(paths.localMonthsDir, month));
562
+ }
563
+ return loadedMonths.get(month);
564
+ }
565
+
566
+ let rowsIngested = 0;
567
+ let rowsDeleted = 0;
568
+
569
+ for (const event of feed.events) {
570
+ if (event.type === "upsert") {
571
+ const normalized = normalizeFeedRow(event.row, { timeZone });
572
+ const previousMonth = Object.prototype.hasOwnProperty.call(rowIndex, normalized.id)
573
+ ? rowIndex[normalized.id]
574
+ : null;
575
+ if (previousMonth && previousMonth !== normalized.month) {
576
+ const oldMap = await getMonthMap(previousMonth);
577
+ if (Object.prototype.hasOwnProperty.call(oldMap, normalized.id)) {
578
+ delete oldMap[normalized.id];
579
+ dirtyMonths.add(previousMonth);
580
+ }
581
+ }
582
+
583
+ const monthMap = await getMonthMap(normalized.month);
584
+ Object.defineProperty(monthMap, normalized.id, {
585
+ value: normalized,
586
+ enumerable: true,
587
+ configurable: true,
588
+ writable: true,
589
+ });
590
+ Object.defineProperty(rowIndex, normalized.id, {
591
+ value: normalized.month,
592
+ enumerable: true,
593
+ configurable: true,
594
+ writable: true,
595
+ });
596
+ dirtyMonths.add(normalized.month);
597
+ rowsIngested += 1;
598
+ } else if (event.type === "delete") {
599
+ const id = typeof event.tombstone?.id === "string" ? event.tombstone.id.trim() : "";
600
+ if (!id) {
601
+ continue;
602
+ }
603
+ const targetMonth = Object.prototype.hasOwnProperty.call(rowIndex, id) ? rowIndex[id] : null;
604
+ if (targetMonth) {
605
+ const monthMap = await getMonthMap(targetMonth);
606
+ if (Object.prototype.hasOwnProperty.call(monthMap, id)) {
607
+ delete monthMap[id];
608
+ dirtyMonths.add(targetMonth);
609
+ rowsDeleted += 1;
610
+ }
611
+ delete rowIndex[id];
612
+ }
613
+ }
614
+ }
615
+
616
+ await ensureDir(paths.localMonthsDir, 0o700);
617
+
618
+ const sortedDirtyMonths = Array.from(dirtyMonths).sort();
619
+ const monthsToDelete = [];
620
+
621
+ // Write all populated months first before removing empty/obsolete months so
622
+ // an interrupted 410 rebuild never leaves populated data deleted early.
623
+ for (const month of sortedDirtyMonths) {
624
+ const monthFile = resolveContainedMonthFile(paths.localMonthsDir, month);
625
+ const rowsMap = loadedMonths.get(month) || Object.create(null);
626
+ if (Object.keys(rowsMap).length === 0) {
627
+ monthsToDelete.push(monthFile);
628
+ } else {
629
+ await writeJsonAtomic(
630
+ monthFile,
631
+ {
632
+ schemaVersion: 1,
633
+ month,
634
+ rows: rowsMap,
635
+ },
636
+ { mode: 0o600 },
637
+ );
638
+ }
639
+ }
640
+
641
+ for (const monthFile of monthsToDelete) {
642
+ try {
643
+ await fs.unlink(monthFile);
644
+ } catch (error) {
645
+ if (!error || error.code !== "ENOENT") {
646
+ throw error;
647
+ }
648
+ }
649
+ }
650
+
651
+ await writeJsonAtomic(paths.localRowIndexFile, rowIndex, { mode: 0o600, pretty: false });
652
+
653
+ const nextState = {
654
+ ...state,
655
+ feedCursor: feed.nextCursor,
656
+ lastLocalSyncAt: new Date().toISOString(),
657
+ };
658
+ await writeJsonAtomic(paths.stateFile, nextState, { mode: 0o600 });
659
+
660
+ return {
661
+ resetRequired: feed.resetRequired,
662
+ rowsIngested,
663
+ rowsDeleted,
664
+ dirtyMonths: sortedDirtyMonths,
665
+ nextCursor: feed.nextCursor,
666
+ pagesFetched: feed.pagesFetched,
667
+ hasMore: feed.hasMore,
668
+ };
669
+ });
670
+ }