-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathstorage.ts
More file actions
2656 lines (2445 loc) · 71.6 KB
/
storage.ts
File metadata and controls
2656 lines (2445 loc) · 71.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AsyncLocalStorage } from "node:async_hooks";
import { createHash } from "node:crypto";
import { existsSync, promises as fs } from "node:fs";
import { basename, dirname, isAbsolute, join, relative } from "node:path";
import { ACCOUNT_LIMITS } from "./constants.js";
import { createLogger } from "./logger.js";
import {
exportNamedBackupFile,
getNamedBackupRoot,
resolveNamedBackupPath,
} from "./named-backup-export.js";
import { MODEL_FAMILIES, type ModelFamily } from "./prompts/codex.js";
import { AnyAccountStorageSchema, getValidationErrors } from "./schemas.js";
import {
type AccountMetadataV1,
type AccountMetadataV3,
type AccountStorageV1,
type AccountStorageV3,
type CooldownReason,
migrateV1ToV3,
type RateLimitStateV3,
} from "./storage/migrations.js";
import {
findProjectRoot,
getConfigDir,
getProjectConfigDir,
getProjectGlobalConfigDir,
resolvePath,
resolveProjectStorageIdentityRoot,
} from "./storage/paths.js";
export type {
CooldownReason,
RateLimitStateV3,
AccountMetadataV1,
AccountStorageV1,
AccountMetadataV3,
AccountStorageV3,
};
const log = createLogger("storage");
const ACCOUNTS_FILE_NAME = "openai-codex-accounts.json";
const FLAGGED_ACCOUNTS_FILE_NAME = "openai-codex-flagged-accounts.json";
const LEGACY_FLAGGED_ACCOUNTS_FILE_NAME = "openai-codex-blocked-accounts.json";
const ACCOUNTS_BACKUP_SUFFIX = ".bak";
const ACCOUNTS_WAL_SUFFIX = ".wal";
const ACCOUNTS_BACKUP_HISTORY_DEPTH = 3;
const BACKUP_COPY_MAX_ATTEMPTS = 5;
const BACKUP_COPY_BASE_DELAY_MS = 10;
const RESET_MARKER_SUFFIX = ".reset-intent";
let storageBackupEnabled = true;
let lastAccountsSaveTimestamp = 0;
export interface FlaggedAccountMetadataV1 extends AccountMetadataV3 {
flaggedAt: number;
flaggedReason?: string;
lastError?: string;
}
export interface FlaggedAccountStorageV1 {
version: 1;
accounts: FlaggedAccountMetadataV1[];
}
type RestoreReason = "empty-storage" | "intentional-reset" | "missing-storage";
type AccountStorageWithMetadata = AccountStorageV3 & {
restoreEligible?: boolean;
restoreReason?: RestoreReason;
};
type BackupSnapshotKind =
| "accounts-primary"
| "accounts-wal"
| "accounts-backup"
| "accounts-backup-history"
| "accounts-discovered-backup"
| "flagged-primary"
| "flagged-backup"
| "flagged-backup-history"
| "flagged-discovered-backup";
type BackupSnapshotMetadata = {
kind: BackupSnapshotKind;
path: string;
index?: number;
exists: boolean;
valid: boolean;
bytes?: number;
mtimeMs?: number;
version?: number;
accountCount?: number;
flaggedCount?: number;
schemaErrors?: string[];
};
type BackupMetadataSection = {
storagePath: string;
latestValidPath?: string;
snapshotCount: number;
validSnapshotCount: number;
snapshots: BackupSnapshotMetadata[];
};
export type BackupMetadata = {
accounts: BackupMetadataSection;
flaggedAccounts: BackupMetadataSection;
};
export type RestoreAssessment = {
storagePath: string;
restoreEligible: boolean;
restoreReason?: RestoreReason;
latestSnapshot?: BackupSnapshotMetadata;
backupMetadata: BackupMetadata;
};
export interface NamedBackupSummary {
path: string;
fileName: string;
accountCount: number;
mtimeMs: number;
}
async function collectNamedBackups(storagePath: string): Promise<NamedBackupSummary[]> {
const backupRoot = getNamedBackupRoot(storagePath);
let entries: Array<{ isFile(): boolean; name: string }>;
try {
entries = await fs.readdir(backupRoot, {
withFileTypes: true,
encoding: "utf8",
});
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") return [];
throw error;
}
const candidates: NamedBackupSummary[] = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
if (!entry.name.toLowerCase().endsWith(".json")) continue;
const candidatePath = join(backupRoot, entry.name);
try {
const statsBefore = await fs.stat(candidatePath);
const { normalized } = await loadAccountsFromPath(candidatePath);
if (!normalized || normalized.accounts.length === 0) continue;
const statsAfter = await fs.stat(candidatePath).catch(() => null);
if (statsAfter && statsAfter.mtimeMs !== statsBefore.mtimeMs) {
log.debug("backup file changed between stat and load, mtime may be stale", {
candidatePath,
fileName: entry.name,
beforeMtimeMs: statsBefore.mtimeMs,
afterMtimeMs: statsAfter.mtimeMs,
});
}
candidates.push({
path: candidatePath,
fileName: entry.name,
accountCount: normalized.accounts.length,
mtimeMs: statsBefore.mtimeMs,
});
} catch (error) {
log.debug("Skipping named backup candidate after loadAccountsFromPath/fs.stat failure", {
candidatePath,
fileName: entry.name,
error: error instanceof Error
? {
message: error.message,
stack: error.stack,
}
: String(error),
});
continue;
}
}
candidates.sort((left, right) => {
const mtimeDelta = right.mtimeMs - left.mtimeMs;
if (mtimeDelta !== 0) return mtimeDelta;
return left.fileName.localeCompare(right.fileName);
});
return candidates;
}
/**
* Custom error class for storage operations with platform-aware hints.
*/
export class StorageError extends Error {
readonly code: string;
readonly path: string;
readonly hint: string;
constructor(
message: string,
code: string,
path: string,
hint: string,
cause?: Error,
) {
super(message, { cause });
this.name = "StorageError";
this.code = code;
this.path = path;
this.hint = hint;
}
}
/**
* Generate platform-aware troubleshooting hint based on error code.
*/
export function formatStorageErrorHint(error: unknown, path: string): string {
const err = error as NodeJS.ErrnoException;
const code = err?.code || "UNKNOWN";
const isWindows = process.platform === "win32";
switch (code) {
case "EACCES":
case "EPERM":
return isWindows
? `Permission denied writing to ${path}. Check antivirus exclusions for this folder. Ensure you have write permissions.`
: `Permission denied writing to ${path}. Check folder permissions. Try: chmod 755 ~/.codex`;
case "EBUSY":
return `File is locked at ${path}. The file may be open in another program. Close any editors or processes accessing it.`;
case "ENOSPC":
return `Disk is full. Free up space and try again. Path: ${path}`;
case "EEMPTY":
return `File written but is empty. This may indicate a disk or filesystem issue. Path: ${path}`;
default:
return isWindows
? `Failed to write to ${path}. Check folder permissions and ensure path contains no special characters.`
: `Failed to write to ${path}. Check folder permissions and disk space.`;
}
}
let storageMutex: Promise<void> = Promise.resolve();
const transactionSnapshotContext = new AsyncLocalStorage<{
snapshot: AccountStorageV3 | null;
storagePath: string;
active: boolean;
}>();
function withStorageLock<T>(fn: () => Promise<T>): Promise<T> {
const previousMutex = storageMutex;
let releaseLock: () => void;
storageMutex = new Promise<void>((resolve) => {
releaseLock = resolve;
});
return previousMutex.then(fn).finally(() => releaseLock());
}
type AnyAccountStorage = AccountStorageV1 | AccountStorageV3;
type AccountLike = {
accountId?: string;
email?: string;
refreshToken?: string;
addedAt?: number;
lastUsed?: number;
};
function looksLikeSyntheticFixtureAccount(account: AccountMetadataV3): boolean {
const email =
typeof account.email === "string" ? account.email.trim().toLowerCase() : "";
const refreshToken =
typeof account.refreshToken === "string"
? account.refreshToken.trim().toLowerCase()
: "";
const accountId =
typeof account.accountId === "string"
? account.accountId.trim().toLowerCase()
: "";
if (!/^account\d+@example\.com$/.test(email)) {
return false;
}
const hasSyntheticRefreshToken =
refreshToken.startsWith("fake_refresh") ||
/^fake_refresh_token_\d+(_for_testing_only)?$/.test(refreshToken);
if (!hasSyntheticRefreshToken) {
return false;
}
if (accountId.length === 0) {
return true;
}
return /^acc(_|-)?\d+$/.test(accountId);
}
function looksLikeSyntheticFixtureStorage(
storage: AccountStorageV3 | null,
): boolean {
if (!storage || storage.accounts.length === 0) return false;
return storage.accounts.every((account) =>
looksLikeSyntheticFixtureAccount(account),
);
}
async function ensureGitignore(storagePath: string): Promise<void> {
const state = getStoragePathState();
if (!state.currentStoragePath) return;
const configDir = dirname(storagePath);
const inferredProjectRoot = dirname(configDir);
const candidateRoots = [state.currentProjectRoot, inferredProjectRoot].filter(
(root): root is string => typeof root === "string" && root.length > 0,
);
const projectRoot = candidateRoots.find((root) =>
existsSync(join(root, ".git")),
);
if (!projectRoot) return;
const gitignorePath = join(projectRoot, ".gitignore");
try {
let content = "";
if (existsSync(gitignorePath)) {
content = await fs.readFile(gitignorePath, "utf-8");
const lines = content.split("\n").map((l) => l.trim());
if (
lines.includes(".codex") ||
lines.includes(".codex/") ||
lines.includes("/.codex") ||
lines.includes("/.codex/")
) {
return;
}
}
const newContent =
content.endsWith("\n") || content === "" ? content : content + "\n";
await fs.writeFile(gitignorePath, newContent + ".codex/\n", "utf-8");
log.debug("Added .codex to .gitignore", { path: gitignorePath });
} catch (error) {
log.warn("Failed to update .gitignore", { error: String(error) });
}
}
type StoragePathState = {
currentStoragePath: string | null;
currentLegacyProjectStoragePath: string | null;
currentLegacyWorktreeStoragePath: string | null;
currentProjectRoot: string | null;
};
let currentStorageState: StoragePathState = {
currentStoragePath: null,
currentLegacyProjectStoragePath: null,
currentLegacyWorktreeStoragePath: null,
currentProjectRoot: null,
};
const storagePathStateContext = new AsyncLocalStorage<StoragePathState>();
function getStoragePathState(): StoragePathState {
return storagePathStateContext.getStore() ?? currentStorageState;
}
function setStoragePathState(state: StoragePathState): void {
currentStorageState = state;
storagePathStateContext.enterWith(state);
}
export function setStorageBackupEnabled(enabled: boolean): void {
storageBackupEnabled = enabled;
}
function getAccountsBackupPath(path: string): string {
return `${path}${ACCOUNTS_BACKUP_SUFFIX}`;
}
function getAccountsBackupPathAtIndex(path: string, index: number): string {
if (index <= 0) {
return getAccountsBackupPath(path);
}
return `${path}${ACCOUNTS_BACKUP_SUFFIX}.${index}`;
}
function getAccountsBackupRecoveryCandidates(path: string): string[] {
const candidates: string[] = [];
for (let i = 0; i < ACCOUNTS_BACKUP_HISTORY_DEPTH; i += 1) {
candidates.push(getAccountsBackupPathAtIndex(path, i));
}
return candidates;
}
async function getAccountsBackupRecoveryCandidatesWithDiscovery(
path: string,
): Promise<string[]> {
const knownCandidates = getAccountsBackupRecoveryCandidates(path);
const discoveredCandidates = new Set<string>();
const candidatePrefix = `${basename(path)}.`;
const knownCandidateSet = new Set(knownCandidates);
const directoryPath = dirname(path);
try {
const entries = await fs.readdir(directoryPath, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isFile()) continue;
if (!entry.name.startsWith(candidatePrefix)) continue;
if (isCacheLikeBackupArtifactName(entry.name)) continue;
if (entry.name.endsWith(RESET_MARKER_SUFFIX)) continue;
if (entry.name.endsWith(".tmp")) continue;
if (entry.name.includes(".rotate.")) continue;
if (entry.name.endsWith(ACCOUNTS_WAL_SUFFIX)) continue;
const candidatePath = join(directoryPath, entry.name);
if (knownCandidateSet.has(candidatePath)) continue;
discoveredCandidates.add(candidatePath);
}
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT") {
log.warn("Failed to discover account backup candidates", {
path,
error: String(error),
});
}
}
const discoveredOrdered = Array.from(discoveredCandidates).sort((a, b) =>
a.localeCompare(b, undefined, { sensitivity: "base" }),
);
return [...knownCandidates, ...discoveredOrdered];
}
function getAccountsWalPath(path: string): string {
return `${path}${ACCOUNTS_WAL_SUFFIX}`;
}
async function copyFileWithRetry(
sourcePath: string,
destinationPath: string,
options?: { allowMissingSource?: boolean },
): Promise<void> {
const allowMissingSource = options?.allowMissingSource ?? false;
for (let attempt = 0; attempt < BACKUP_COPY_MAX_ATTEMPTS; attempt += 1) {
try {
await fs.copyFile(sourcePath, destinationPath);
return;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (allowMissingSource && code === "ENOENT") {
return;
}
const canRetry =
(code === "EPERM" || code === "EBUSY") &&
attempt + 1 < BACKUP_COPY_MAX_ATTEMPTS;
if (canRetry) {
await new Promise((resolve) =>
setTimeout(resolve, BACKUP_COPY_BASE_DELAY_MS * 2 ** attempt),
);
continue;
}
throw error;
}
}
}
async function renameFileWithRetry(
sourcePath: string,
destinationPath: string,
): Promise<void> {
for (let attempt = 0; attempt < BACKUP_COPY_MAX_ATTEMPTS; attempt += 1) {
try {
await fs.rename(sourcePath, destinationPath);
return;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
const canRetry =
(code === "EPERM" || code === "EBUSY" || code === "EAGAIN") &&
attempt + 1 < BACKUP_COPY_MAX_ATTEMPTS;
if (!canRetry) {
throw error;
}
const jitterMs = Math.floor(Math.random() * BACKUP_COPY_BASE_DELAY_MS);
await new Promise((resolve) =>
setTimeout(
resolve,
BACKUP_COPY_BASE_DELAY_MS * 2 ** attempt + jitterMs,
),
);
}
}
}
async function createRotatingAccountsBackup(path: string): Promise<void> {
const candidates = getAccountsBackupRecoveryCandidates(path);
const rotationNonce = `${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
const stagedWrites: Array<{ targetPath: string; stagedPath: string }> = [];
const buildStagedPath = (targetPath: string, label: string): string =>
`${targetPath}.rotate.${rotationNonce}.${label}.tmp`;
try {
for (let i = candidates.length - 1; i > 0; i -= 1) {
const previousPath = candidates[i - 1];
const currentPath = candidates[i];
if (!previousPath || !currentPath || !existsSync(previousPath)) {
continue;
}
const stagedPath = buildStagedPath(currentPath, `slot-${i}`);
await copyFileWithRetry(previousPath, stagedPath, {
allowMissingSource: true,
});
if (existsSync(stagedPath)) {
stagedWrites.push({ targetPath: currentPath, stagedPath });
}
}
const latestBackupPath = candidates[0];
if (!latestBackupPath) {
return;
}
const latestStagedPath = buildStagedPath(latestBackupPath, "latest");
await copyFileWithRetry(path, latestStagedPath);
if (existsSync(latestStagedPath)) {
stagedWrites.push({
targetPath: latestBackupPath,
stagedPath: latestStagedPath,
});
}
for (const stagedWrite of stagedWrites) {
await renameFileWithRetry(stagedWrite.stagedPath, stagedWrite.targetPath);
}
} finally {
for (const stagedWrite of stagedWrites) {
if (!existsSync(stagedWrite.stagedPath)) {
continue;
}
try {
await fs.unlink(stagedWrite.stagedPath);
} catch {
// Best effort cleanup for staged rotation artifacts.
}
}
}
}
function isRotatingBackupTempArtifact(
storagePath: string,
candidatePath: string,
): boolean {
const backupPrefix = `${storagePath}${ACCOUNTS_BACKUP_SUFFIX}`;
if (
!candidatePath.startsWith(backupPrefix) ||
!candidatePath.endsWith(".tmp")
) {
return false;
}
const suffix = candidatePath.slice(backupPrefix.length);
const rotateSeparatorIndex = suffix.indexOf(".rotate.");
if (rotateSeparatorIndex === -1) {
return false;
}
const backupIndexSuffix = suffix.slice(0, rotateSeparatorIndex);
if (backupIndexSuffix.length > 0 && !/^\.\d+$/.test(backupIndexSuffix)) {
return false;
}
return true;
}
async function cleanupStaleRotatingBackupArtifacts(
path: string,
): Promise<void> {
const directoryPath = dirname(path);
try {
const directoryEntries = await fs.readdir(directoryPath, {
withFileTypes: true,
});
const staleArtifacts = directoryEntries
.filter((entry) => entry.isFile())
.map((entry) => join(directoryPath, entry.name))
.filter((entryPath) => isRotatingBackupTempArtifact(path, entryPath));
for (const staleArtifactPath of staleArtifacts) {
try {
await fs.unlink(staleArtifactPath);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT") {
log.warn("Failed to remove stale rotating backup artifact", {
path: staleArtifactPath,
error: String(error),
});
}
}
}
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT") {
log.warn("Failed to scan for stale rotating backup artifacts", {
path,
error: String(error),
});
}
}
}
function computeSha256(value: string): string {
return createHash("sha256").update(value).digest("hex");
}
function getIntentionalResetMarkerPath(path: string): string {
return `${path}${RESET_MARKER_SUFFIX}`;
}
function createEmptyStorageWithMetadata(
restoreEligible: boolean,
restoreReason: RestoreReason,
): AccountStorageWithMetadata {
return {
version: 3,
accounts: [],
activeIndex: 0,
activeIndexByFamily: {},
restoreEligible,
restoreReason,
};
}
function withRestoreMetadata(
storage: AccountStorageV3,
restoreEligible: boolean,
restoreReason: RestoreReason,
): AccountStorageWithMetadata {
return {
...storage,
restoreEligible,
restoreReason,
};
}
function isCacheLikeBackupArtifactName(entryName: string): boolean {
return entryName.toLowerCase().includes(".cache");
}
async function statSnapshot(path: string): Promise<{
exists: boolean;
bytes?: number;
mtimeMs?: number;
}> {
try {
const stats = await fs.stat(path);
return { exists: true, bytes: stats.size, mtimeMs: stats.mtimeMs };
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT") {
log.warn("Failed to stat backup candidate", {
path,
error: String(error),
});
}
return { exists: false };
}
}
async function describeAccountSnapshot(
path: string,
kind: BackupSnapshotKind,
index?: number,
): Promise<BackupSnapshotMetadata> {
const stats = await statSnapshot(path);
if (!stats.exists) {
return { kind, path, index, exists: false, valid: false };
}
try {
const { normalized, schemaErrors, storedVersion } =
await loadAccountsFromPath(path);
return {
kind,
path,
index,
exists: true,
valid: !!normalized,
bytes: stats.bytes,
mtimeMs: stats.mtimeMs,
version: typeof storedVersion === "number" ? storedVersion : undefined,
accountCount: normalized?.accounts.length,
schemaErrors: schemaErrors.length > 0 ? schemaErrors : undefined,
};
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT") {
log.warn("Failed to inspect account snapshot", {
path,
error: String(error),
});
}
return {
kind,
path,
index,
exists: true,
valid: false,
bytes: stats.bytes,
mtimeMs: stats.mtimeMs,
};
}
}
async function describeAccountsWalSnapshot(
path: string,
): Promise<BackupSnapshotMetadata> {
const stats = await statSnapshot(path);
if (!stats.exists) {
return { kind: "accounts-wal", path, exists: false, valid: false };
}
try {
const raw = await fs.readFile(path, "utf-8");
const parsed = JSON.parse(raw) as unknown;
if (!isRecord(parsed)) {
return {
kind: "accounts-wal",
path,
exists: true,
valid: false,
bytes: stats.bytes,
mtimeMs: stats.mtimeMs,
};
}
const entry = parsed as Partial<AccountsJournalEntry>;
if (
entry.version !== 1 ||
typeof entry.content !== "string" ||
typeof entry.checksum !== "string" ||
computeSha256(entry.content) !== entry.checksum
) {
return {
kind: "accounts-wal",
path,
exists: true,
valid: false,
bytes: stats.bytes,
mtimeMs: stats.mtimeMs,
};
}
const { normalized, storedVersion, schemaErrors } =
parseAndNormalizeStorage(JSON.parse(entry.content) as unknown);
return {
kind: "accounts-wal",
path,
exists: true,
valid: !!normalized,
bytes: stats.bytes,
mtimeMs: stats.mtimeMs,
version: typeof storedVersion === "number" ? storedVersion : undefined,
accountCount: normalized?.accounts.length,
schemaErrors: schemaErrors.length > 0 ? schemaErrors : undefined,
};
} catch {
return {
kind: "accounts-wal",
path,
exists: true,
valid: false,
bytes: stats.bytes,
mtimeMs: stats.mtimeMs,
};
}
}
async function loadFlaggedAccountsFromPath(
path: string,
): Promise<FlaggedAccountStorageV1> {
const content = await fs.readFile(path, "utf-8");
const data = JSON.parse(content) as unknown;
return normalizeFlaggedStorage(data);
}
async function describeFlaggedSnapshot(
path: string,
kind: BackupSnapshotKind,
index?: number,
): Promise<BackupSnapshotMetadata> {
const stats = await statSnapshot(path);
if (!stats.exists) {
return { kind, path, index, exists: false, valid: false };
}
try {
const storage = await loadFlaggedAccountsFromPath(path);
return {
kind,
path,
index,
exists: true,
valid: true,
bytes: stats.bytes,
mtimeMs: stats.mtimeMs,
version: storage.version,
flaggedCount: storage.accounts.length,
};
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT") {
log.warn("Failed to inspect flagged snapshot", {
path,
error: String(error),
});
}
return {
kind,
path,
index,
exists: true,
valid: false,
bytes: stats.bytes,
mtimeMs: stats.mtimeMs,
};
}
}
function latestValidSnapshot(
snapshots: BackupSnapshotMetadata[],
): BackupSnapshotMetadata | undefined {
return snapshots
.filter((snapshot) => snapshot.valid)
.sort((left, right) => (right.mtimeMs ?? 0) - (left.mtimeMs ?? 0))[0];
}
function buildMetadataSection(
storagePath: string,
snapshots: BackupSnapshotMetadata[],
): BackupMetadataSection {
const latestValid = latestValidSnapshot(snapshots);
return {
storagePath,
latestValidPath: latestValid?.path,
snapshotCount: snapshots.length,
validSnapshotCount: snapshots.filter((snapshot) => snapshot.valid).length,
snapshots,
};
}
type AccountsJournalEntry = {
version: 1;
createdAt: number;
path: string;
checksum: string;
content: string;
};
export function getLastAccountsSaveTimestamp(): number {
return lastAccountsSaveTimestamp;
}
export function setStoragePath(projectPath: string | null): void {
if (!projectPath) {
setStoragePathState({
currentStoragePath: null,
currentLegacyProjectStoragePath: null,
currentLegacyWorktreeStoragePath: null,
currentProjectRoot: null,
});
return;
}
const projectRoot = findProjectRoot(projectPath);
if (projectRoot) {
const identityRoot = resolveProjectStorageIdentityRoot(projectRoot);
const currentStoragePath = join(
getProjectGlobalConfigDir(identityRoot),
ACCOUNTS_FILE_NAME,
);
const currentLegacyProjectStoragePath = join(
getProjectConfigDir(projectRoot),
ACCOUNTS_FILE_NAME,
);
const previousWorktreeScopedPath = join(
getProjectGlobalConfigDir(projectRoot),
ACCOUNTS_FILE_NAME,
);
const currentLegacyWorktreeStoragePath =
previousWorktreeScopedPath !== currentStoragePath
? previousWorktreeScopedPath
: null;
setStoragePathState({
currentStoragePath,
currentLegacyProjectStoragePath,
currentLegacyWorktreeStoragePath,
currentProjectRoot: projectRoot,
});
} else {
setStoragePathState({
currentStoragePath: null,
currentLegacyProjectStoragePath: null,
currentLegacyWorktreeStoragePath: null,
currentProjectRoot: null,
});
}
}
export function setStoragePathDirect(path: string | null): void {
setStoragePathState({
currentStoragePath: path,
currentLegacyProjectStoragePath: null,
currentLegacyWorktreeStoragePath: null,
currentProjectRoot: null,
});
}
/**
* Returns the file path for the account storage JSON file.
* @returns Absolute path to the accounts.json file
*/
export function getStoragePath(): string {
const state = getStoragePathState();
if (state.currentStoragePath) {
return state.currentStoragePath;
}
return join(getConfigDir(), ACCOUNTS_FILE_NAME);
}
export function buildNamedBackupPath(name: string): string {
return resolveNamedBackupPath(name, getStoragePath());
}
export async function getNamedBackups(): Promise<NamedBackupSummary[]> {
return collectNamedBackups(getStoragePath());
}
export async function restoreAccountsFromBackup(
path: string,
options?: { persist?: boolean },
): Promise<AccountStorageV3> {
const backupRoot = getNamedBackupRoot(getStoragePath());
let resolvedBackupRoot: string;
try {
resolvedBackupRoot = await fs.realpath(backupRoot);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") {
throw new Error(`Backup root does not exist: ${backupRoot}`);
}
throw error;
}
let resolvedBackupPath: string;
try {
resolvedBackupPath = await fs.realpath(path);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") {
throw new Error(`Backup file no longer exists: ${path}`);
}
throw error;
}
const relativePath = relative(resolvedBackupRoot, resolvedBackupPath);
const isInsideBackupRoot =
relativePath.length > 0 &&
!relativePath.startsWith("..") &&
!isAbsolute(relativePath);
if (!isInsideBackupRoot) {
throw new Error(`Backup path must stay inside ${resolvedBackupRoot}: ${path}`);
}
const { normalized } = await (async () => {
try {
return await loadAccountsFromPath(resolvedBackupPath);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") {
throw new Error(
`Backup file no longer exists: ${path}`,
);
}
throw error;
}
})();
if (!normalized || normalized.accounts.length === 0) {
throw new Error(`Backup does not contain any accounts: ${resolvedBackupPath}`);
}
if (options?.persist !== false) {
await saveAccounts(normalized);
}
return normalized;
}
export async function exportNamedBackup(
name: string,
options?: { force?: boolean },
): Promise<string> {
return exportNamedBackupFile(
name,
{
getStoragePath,
exportAccounts,
},
options,
);
}
export function getFlaggedAccountsPath(): string {
return join(dirname(getStoragePath()), FLAGGED_ACCOUNTS_FILE_NAME);
}
function getLegacyFlaggedAccountsPath(): string {
return join(dirname(getStoragePath()), LEGACY_FLAGGED_ACCOUNTS_FILE_NAME);
}
async function migrateLegacyProjectStorageIfNeeded(
persist: (storage: AccountStorageV3) => Promise<void> = saveAccounts,