forked from Yeachan-Heo/gajae-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession-storage.ts
More file actions
3677 lines (3460 loc) · 132 KB
/
Copy pathsession-storage.ts
File metadata and controls
3677 lines (3460 loc) · 132 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 { createHash, randomUUID } from "node:crypto";
import * as fs from "node:fs";
import * as path from "node:path";
import type * as native from "@gajae-code/natives";
let nativeSessionStorageBindings: typeof import("@gajae-code/natives") | undefined;
function nativeSessionStorage(): typeof import("@gajae-code/natives") {
if (!nativeSessionStorageBindings) {
nativeSessionStorageBindings = require("@gajae-code/natives") as typeof import("@gajae-code/natives");
}
return nativeSessionStorageBindings;
}
import { isEnoent, pathIsWithin, peekFile, toError } from "@gajae-code/utils";
import {
assertManagedDirectoryRoot,
type ManagedDirectoryRoot,
renameFlagsUnsupported,
shouldFsyncManagedDirectory,
validateNativeSecurityResult,
} from "./internal/managed-session-storage";
import {
classifyNativePublishOutcome,
mayCleanCurrentStaging,
type NativePublishOutcome,
} from "./internal/native-publish-outcome";
import { isDerivedSessionMemoryFile } from "./internal/session-memory-sidecar";
const utf8Decoder = new TextDecoder("utf-8");
const newlineBuffer = Buffer.from("\n", "utf8");
function canonicalPathSync(value: string): string {
try {
return fs.realpathSync.native(value);
} catch {
return path.resolve(value);
}
}
export interface SessionStorageStat {
dev: bigint;
ino: bigint;
nlink?: bigint;
size: number;
mtimeMs: number;
mtimeNs: bigint;
ctimeNs: bigint;
mtime: Date;
isFile: boolean;
}
/** Exact bytes and identity captured from one opened regular-file descriptor. */
export interface SessionStorageSnapshot {
bytes: Uint8Array;
stat: SessionStorageStat;
}
export interface SessionStorageExactReplacementExpectation {
readonly stat: SessionStorageStat;
readonly sha256: string;
}
/** Upper bound for one descriptor-validated recorded range read. */
export const SESSION_RANGE_READ_MAX_BYTES = 64 * 1024 * 1024;
/**
* One bounded recorded-length read validated against a single opened descriptor.
* `bytes` is exactly `length` bytes from `[start, start + length)` of the same
* regular-file object; `stat` is the fresh post-read descriptor snapshot so the
* caller can compare dev/ino/nlink against the pathname before committing an index.
*/
export interface SessionStorageRangeSnapshot {
stat: SessionStorageStat;
bytes: Uint8Array;
}
function validateRangeReadBounds(start: number, length: number): void {
if (!Number.isSafeInteger(start) || start < 0 || !Number.isSafeInteger(length) || length < 0)
throw new RangeError("Invalid session range read bounds");
if (start > Number.MAX_SAFE_INTEGER - length) throw new RangeError("Session range read start overflows");
if (length > SESSION_RANGE_READ_MAX_BYTES) throw new RangeError("Session range read exceeds the bounded maximum");
}
function normalizeBufferedWriterCapacity(value: number | undefined): number {
const capacity = value ?? SESSION_STORAGE_BUFFERED_WRITER_DEFAULT_BYTES;
if (
!Number.isSafeInteger(capacity) ||
capacity < SESSION_STORAGE_BUFFERED_WRITER_MIN_BYTES ||
capacity > SESSION_STORAGE_BUFFERED_WRITER_MAX_BYTES
)
throw new RangeError(
`Buffered writer capacity must be between ${SESSION_STORAGE_BUFFERED_WRITER_MIN_BYTES} and ${SESSION_STORAGE_BUFFERED_WRITER_MAX_BYTES} bytes`,
);
return capacity;
}
function statFromNode(stats: fs.BigIntStats): SessionStorageStat {
return {
dev: stats.dev,
ino: stats.ino,
nlink: stats.nlink,
size: Number(stats.size),
mtimeMs: Number(stats.mtimeMs),
mtimeNs: stats.mtimeNs,
ctimeNs: stats.ctimeNs,
mtime: stats.mtime,
isFile: stats.isFile(),
};
}
// =============================================================================
// Certainty-aware writer close contract (ACP fail-closed deletion foundation)
// =============================================================================
/**
* Four-state writer close lifecycle. Only a successful underlying close confirms
* `closed`. A failure certified to have happened BEFORE the OS close was dispatched
* is `close_failed_retryable` (ownership of the numeric fd is still proven, so a
* later retry/finalizer close is safe). Any exception from an actually dispatched
* close call is terminal `close_unknown`: the numeric fd cannot be safely retried
* or finalizer-closed, and the writer blocks strict deletion.
*/
export type SessionStorageWriterCloseState = "open" | "close_failed_retryable" | "close_unknown" | "closed";
/**
* Thrown by a {@link SessionStorageWriterCloseAdapter} to certify that a close
* failure occurred BEFORE the real OS close (`fs.closeSync`-equivalent) was ever
* dispatched. Because no OS close ran, the numeric fd is still owned and a retry
* is safe. Any other thrown value is treated as a dispatched close failure
* (`close_unknown`) and forbids retry/finalizer close of that fd.
*/
export class SessionStorageWriterRetryableCloseError extends Error {
override readonly name = "SessionStorageWriterRetryableCloseError";
constructor(message?: string, options?: ErrorOptions) {
super(message ?? "Certified pre-dispatch writer close failure", options);
}
}
/**
* Injectable dispatcher for the numeric-fd OS close. The default implementation
* calls `fs.closeSync(fd)`. Tests inject adapters that throw
* {@link SessionStorageWriterRetryableCloseError} to certify a pre-dispatch
* failure, or that call the real close and throw to simulate a dispatched
* failure (`close_unknown`).
*/
export interface SessionStorageWriterCloseAdapter {
close(fd: number): void;
}
/** Bounded buffered-writer capacity limits. */
export const SESSION_STORAGE_BUFFERED_WRITER_MIN_BYTES = 64 * 1024;
export const SESSION_STORAGE_BUFFERED_WRITER_MAX_BYTES = 512 * 1024;
export const SESSION_STORAGE_BUFFERED_WRITER_DEFAULT_BYTES = 256 * 1024;
/**
* Counters for a synchronous buffered sidecar writer. `bytesWritten` and
* `writeCalls` count operations against the backend, not calls accepted into
* the in-process buffer.
*/
export interface SessionStorageBufferedWriterInstrumentation {
readonly bytesSubmitted: number;
readonly bytesWritten: number;
readonly writeCalls: number;
readonly flushCalls: number;
readonly bufferedBytes: number;
}
/** Options for opening a {@link SessionStorageWriter}. */
export interface SessionStorageWriterOpenOptions {
flags?: "a" | "w";
onError?: (err: Error) => void;
/** Injectable OS-close dispatcher; defaults to `fs.closeSync`. */
closeAdapter?: SessionStorageWriterCloseAdapter;
/** Opaque authority for default-computed managed destinations only. */
securityContext?: SessionStorageSecurityContext;
/** Enable bounded synchronous buffering for disposable sidecar writes. */
bufferSize?: number;
}
/**
* Immutable authority attached only to a computed managed session destination.
* A caller-supplied pathname never receives this capability, even when it
* happens to equal the current default session directory.
*/
export interface ManagedSessionSecurityContext {
readonly kind: "managed";
readonly agentDir: string;
/** Logical profile root for process-local caches; distinct from managed pathname authority. */
readonly profileAgentDir: string;
readonly sessionsRoot: string;
readonly sessionDir: string;
readonly rootAuthority: ManagedDirectoryRoot;
readonly retainedAuthority?: native.RecoveryFsRoot;
}
const managedSecurityContexts = new WeakSet<ManagedSessionSecurityContext>();
/** @internal Create the only accepted managed writer authority object. */
export function createManagedSessionSecurityContext(input: {
agentDir: string;
/** Optional for compatibility with existing authority-only callers. */
profileAgentDir?: string;
sessionsRoot: string;
sessionDir: string;
rootAuthority: ManagedDirectoryRoot;
retainedAuthority?: native.RecoveryFsRoot;
}): ManagedSessionSecurityContext {
const context = Object.freeze({
kind: "managed" as const,
...input,
profileAgentDir: input.profileAgentDir ?? input.agentDir,
});
managedSecurityContexts.add(context);
return context;
}
export type SessionStorageSecurityContext = ManagedSessionSecurityContext | undefined;
export interface SessionStorageWriter {
writeLine(line: string): Promise<void>;
/**
* Synchronously append a single line. Returns once the bytes are handed to the kernel
* (page cache), so the data survives a non-graceful process death (OOM, SIGKILL, etc.)
* even though it has not yet been fsynced to the underlying disk.
*
* `line` MUST already include the trailing newline. Throws synchronously on I/O error.
*/
writeLineSync(line: string): void;
flush(): Promise<void>;
fsync(): Promise<void>;
/** Synchronously fsync all prior writes when the backend supports durable sidecar publication. */
fsyncSync?(): void;
/** Descriptor-bound identity captured from the still-open writer after fsync. */
statSync?(): SessionStorageStat;
close(): Promise<void>;
/**
* Synchronously close the underlying descriptor. The certainty-aware close
* state is updated synchronously and any close failure throws before this
* returns, so sync callers (atomic rewrite) can observe a close failure
* before proceeding to rename. Mirrors {@link close} semantics exactly.
*/
closeSync(): void;
getError(): Error | undefined;
/** Current certainty-aware close lifecycle state. */
getCloseState(): SessionStorageWriterCloseState;
/** Stored error for non-success close states (`close_failed_retryable`/`close_unknown`). */
getCloseError(): Error | undefined;
}
/** Synchronous byte-oriented writer with bounded buffering for disposable sidecars. */
export interface SessionStorageBufferedWriter extends SessionStorageWriter {
/** Append already-serialized bytes; the caller's view may be reused on return. */
writeBytesSync(bytes: Uint8Array): void;
/** Flush pending bytes to the backend without synchronizing them to stable storage. */
flushSync(): void;
/** Flush pending bytes, then synchronize the backend. */
fsyncSync(): void;
/** Flush pending bytes, then close the backend descriptor. */
closeSync(): void;
/** Snapshot backend-write counters and current pending capacity. */
getInstrumentation(): SessionStorageBufferedWriterInstrumentation;
}
// =============================================================================
// Staged streaming writer contract (two-pass fork publication, immutable destinations)
// =============================================================================
/** Upper bound for one staged line (excluding the trailing newline). */
export const STAGED_WRITER_LINE_MAX_BYTES = 64 * 1024 * 1024;
/** Upper bound for aggregated different-length patches buffered for the publish-time overlay pass. */
export const STAGED_WRITER_PATCH_LIMIT_BYTES = 8 * 1024 * 1024;
export const STAGED_WRITER_PATCH_MAX_COUNT = 65_536;
export const STAGED_MEMORY_WRITER_MAX_BYTES = 20 * 1024 * 1024;
export const STAGED_MEMORY_WRITER_MAX_LINES = STAGED_WRITER_PATCH_MAX_COUNT + 1;
const STAGED_WRITER_COPY_CHUNK_BYTES = 64 * 1024;
/**
* Bounded staged streaming writer for one immutable one-shot destination (fork /
* capture). Lines are streamed to a sibling staging file; {@link publishNoReplace}
* atomically publishes the staged file only while the destination is still absent,
* so publication never materializes the whole file in memory. Different-length
* {@link patchLine} replacements are buffered (bounded) and applied by a second
* bounded streaming pass at publish time.
*
* `publishNoReplace` is reserved for immutable one-shot destinations and must never
* be used for the mutable `.spill.commit` marker (checked create/replace helpers
* exist for that path).
*/
export interface StagedStreamingWriter {
/** Append one complete line; the writer adds the trailing newline. */
writeLine(bytes: Uint8Array): void;
/** Move the line cursor to `ordinal` (0-based) so a later patchLine targets it. */
seekToLine(ordinal: number): void;
/**
* Replace the line at `ordinal` with `bytes`. Same-length replacements are
* applied in place; different-length replacements are buffered (bounded) and
* applied by the publish-time overlay pass.
*/
patchLine(ordinal: number, bytes: Uint8Array): void;
/** Hand buffered writes to the kernel (the staged descriptor is unbuffered). */
flush(): void;
/** Synchronize the staged file. */
fsync(): void;
/** Close the staged descriptor; required before {@link publishNoReplace}. */
closeSync(): void;
/** Atomically publish the staged file at the destination only while it is absent. */
publishNoReplace(): void;
}
export interface SessionStorageExclusiveLock {
releaseSync(): void;
}
export interface SessionStorage {
ensureDirSync(dir: string): void;
existsSync(path: string): boolean;
writeTextSync(path: string, content: string): void;
readTextSync(path: string): string;
/** Exact on-disk bytes for strict read-only session inspection. */
readBytesSync?(path: string): Uint8Array;
/** Exact bytes and descriptor-bound identity captured from one opened regular file. */
readSnapshotSync?(path: string): SessionStorageSnapshot;
statSync(path: string): SessionStorageStat;
listFilesSync(dir: string, pattern: string): string[];
/** List matching files with mtimes without issuing one JavaScript stat call per path. */
listFilesByMtime?(dir: string, pattern: string): Promise<Array<{ path: string; mtimeMs: number }>>;
/**
* Strict directory scan that never suppresses scan/root errors. Used by strict
* authorization inventory; the forgiving {@link listFilesSync} stays display-only.
*/
listFilesStrictSync?(dir: string, pattern: string): string[];
exists(path: string): Promise<boolean>;
readText(path: string): Promise<string>;
readTextPrefix(path: string, maxBytes: number): Promise<string>;
writeText(path: string, content: string): Promise<void>;
rename(path: string, nextPath: string): Promise<void>;
renameSync(path: string, nextPath: string): void;
/** Replace only while the destination still has the expected exact identity and bytes. */
replaceExactSync?(
sourcePath: string,
destinationPath: string,
expected: SessionStorageExactReplacementExpectation,
): boolean;
unlink(path: string): Promise<void>;
unlinkSync(path: string): void;
deleteSessionWithArtifacts(sessionPath: string): Promise<void>;
/**
* Verified hard delete bound to exact identity evidence. Removes the verified
* artifact directory first, revalidates, and unlinks the transcript last. Returns
* typed partial-cleanup evidence for exact-identity retry; never returns success
* for a partial deletion.
*/
deleteSessionVerified?(target: VerifiedSessionDeleteTarget): Promise<VerifiedSessionDeleteResult>;
openWriter(path: string, options?: SessionStorageWriterOpenOptions): SessionStorageWriter;
/** Open a bounded synchronous byte-oriented writer for disposable sidecars. */
openBufferedWriter?(path: string, options?: SessionStorageWriterOpenOptions): SessionStorageBufferedWriter;
/** Bounded recorded-length read with descriptor identity validation (additive). */
readRangeSync?(path: string, start: number, length: number): SessionStorageRangeSnapshot;
/** Async bounded recorded-length read with descriptor identity validation (additive). */
readRange?(path: string, start: number, length: number): Promise<SessionStorageRangeSnapshot>;
/** Open a staged streaming writer for one immutable one-shot destination (additive). */
openStagedWriter?(path: string, options?: SessionStorageWriterOpenOptions): StagedStreamingWriter;
/** Acquire an owner-bound exclusive lock; returns undefined while another owner holds it. */
acquireExclusiveLockSync?(
path: string,
options?: { securityContext?: SessionStorageSecurityContext },
): SessionStorageExclusiveLock | undefined;
}
// =============================================================================
// Verified hard-delete identity + typed partial-cleanup evidence
// =============================================================================
/** Exact authorization evidence for a transcript or artifact path. */
export interface SessionStorageFileIdentity {
dev: bigint;
ino: bigint;
nlink?: bigint;
size: number;
mtimeNs: bigint;
sha256: string;
}
/** Kind of verification failure surfaced by {@link deleteSessionVerified}. */
export type VerifiedDeleteFailureKind =
| "containment"
| "symlink"
| "stat"
| "identity"
| "header"
| "cwd"
| "artifacts";
/**
* Thrown by {@link deleteSessionVerified} when canonical containment, transcript
* non-symlink/identity, header id/cwd, parent identity, or artifact identity
* verification fails. These are visible, sanitized failures: they never mutate
* the transcript or artifacts and grant zero authority.
*/
export class SessionDeleteVerificationError extends Error {
readonly kind: VerifiedDeleteFailureKind;
constructor(kind: VerifiedDeleteFailureKind, message: string, options?: ErrorOptions) {
super(message, options);
this.name = "SessionDeleteVerificationError";
this.kind = kind;
}
}
/**
* Exact identity evidence a verified hard delete binds to. All fields are captured
* at authorization time; delete revalidates each one before any mutation. Retry
* after a partial cleanup supplies the recorded artifact identity via
* {@link expectedArtifactsIdentity}.
*/
export interface VerifiedSessionDeleteTarget {
/** Canonical sessions root; the transcript must be contained within it. */
sessionsRoot: string;
/** Canonical transcript path (absolute `*.jsonl`). */
transcriptPath: string;
/** Expected session id parsed from the header. */
sessionId: string;
/** Expected canonical cwd parsed from the header. */
cwd: string;
/** Expected transcript file `(dev, ino)` captured at authorization. */
transcriptIdentity: SessionStorageFileIdentity;
transcriptParentIdentity?: { dev: bigint; ino: bigint };
/**
* For retry after an `artifacts` `cleanup_pending`: the recorded artifact
* directory identity to re-accept. A replacement/different artifact directory
* fails closed. Omit on first attempt or to accept recorded absence.
*/
expectedArtifactsIdentity?: SessionStorageFileIdentity;
artifactsAbsentAtAuthorization?: true;
/** Stable native recursive-tree evidence captured before artifact detachment. */
expectedArtifactsTree?: NativeDirectoryTreeSnapshot;
/** Identity-bound quarantine path retained when recursive artifact cleanup failed. */
detachedArtifactsPath?: string;
/** Identity-bound quarantine path retained when transcript unlink deferred cleanup. */
detachedTranscriptPath?: string;
/** Native-retained publisher successor observed during transcript cleanup. */
retainedTranscriptSuccessorPath?: string;
/** Native-retained exchange placeholder observed during transcript cleanup. */
retainedTranscriptPlaceholderPath?: string;
/** Native-retained transcript entry whose identity could not be verified. */
retainedTranscriptUnknownPath?: string;
/** Native-retained publisher successor observed during cleanup. */
retainedArtifactsSuccessorPath?: string;
/** Native-retained exchange placeholder observed during cleanup. */
retainedArtifactsPlaceholderPath?: string;
/** Native-retained entry whose identity could not be verified. */
retainedArtifactsUnknownPath?: string;
/** Caller-published, no-replace quarantine pathname for the next artifact detach. */
plannedArtifactsPath?: string;
/** Caller-published, no-replace quarantine pathname for the next transcript detach. */
plannedTranscriptPath?: string;
/** Set only after a durable caller receipt records successful artifact removal. */
artifactsRemoved?: true;
}
/**
* Outcome of a verified hard delete. Artifact removal happens first; only after
* revalidation is the transcript unlinked last. A partial deletion returns
* `cleanup_pending` with exact evidence for same-connection retry — never
* `deleted` and never `{}`.
*/
export type VerifiedSessionDeleteResult =
| { kind: "artifacts_removed"; phase: "artifacts"; transcriptIdentity: SessionStorageFileIdentity }
| { kind: "deleted" }
| {
kind: "cleanup_pending";
phase: "artifacts";
error: Error;
/** Artifact directory identity at failure time; undefined when absent. */
artifactsIdentity: SessionStorageFileIdentity | undefined;
/** Identity-bound quarantine path retained when recursive cleanup failed. */
detachedArtifactsPath: string;
artifactsPayloadDurable?: true;
/** Native snapshot required for an identity-bound recursive retry. */
artifactsTree: NativeDirectoryTreeSnapshot;
/** Transcript identity (unchanged) for retry binding. */
transcriptIdentity: SessionStorageFileIdentity;
retainedSuccessorPath?: string;
retainedPlaceholderPath?: string;
retainedUnknownPath?: string;
}
| {
kind: "cleanup_pending";
phase: "transcript";
error: Error;
/** Transcript identity at failure time for retry binding. */
transcriptIdentity: SessionStorageFileIdentity;
/** Optional identity-bound transcript quarantine path for restart cleanup. */
detachedTranscriptPath?: string;
transcriptPayloadDurable?: true;
retainedSuccessorPath?: string;
retainedPlaceholderPath?: string;
retainedUnknownPath?: string;
};
/** Default OS-close dispatcher: a direct `fs.closeSync`. */
const defaultCloseAdapter: SessionStorageWriterCloseAdapter = {
close(fd: number): void {
fs.closeSync(fd);
},
};
type NativeExactUnlinkResult =
| {
ok: true;
detachedPath?: string;
retainedSuccessorPath?: string;
retainedPlaceholderPath?: string;
retainedUnknownPath?: string;
}
| {
ok: false;
code: string;
detachedPath?: string;
retainedSuccessorPath?: string;
retainedPlaceholderPath?: string;
retainedUnknownPath?: string;
};
type NativeExactUnlink = (
path: string,
identity: {
dev: bigint;
ino: bigint;
nlink?: bigint;
size: bigint;
mtimeNs: bigint;
parentDev?: bigint;
parentIno?: bigint;
/** Required for regular-file deletion; directories are identity-bound only. */
sha256?: string;
directory?: boolean;
/** Optional caller-planned no-replace quarantine destination component. */
quarantineName?: string;
},
) => NativeExactUnlinkResult;
function nativeExactUnlink(
pathname: string,
identity: {
dev: bigint;
ino: bigint;
nlink?: bigint;
size: bigint;
mtimeNs: bigint;
/** Required for regular-file deletion; directories are identity-bound only. */
sha256?: string;
parentDev?: bigint;
parentIno?: bigint;
directory?: boolean;
quarantineName?: string;
},
): NativeExactUnlinkResult {
return (nativeSessionStorage().exactUnlink as unknown as NativeExactUnlink)(pathname, identity);
}
type NativeDirectoryTreeEntry = {
relativePath: string;
kind: string;
dev: string;
ino: string;
nlink: string;
size: string;
mtimeNs: string;
ctimeNs: string;
sha256?: string;
};
export type NativeDirectoryTreeSnapshot = {
rootDev: string;
rootIno: string;
entries: NativeDirectoryTreeEntry[];
};
type NativeDirectoryTreeResult =
| { ok: true; snapshot: NativeDirectoryTreeSnapshot }
| { ok: false; code: string; snapshot?: undefined };
type NativeDirectoryTreeApi = {
snapshotDirectoryTree(pathname: string): NativeDirectoryTreeResult;
exactRemoveDirectoryTree(
pathname: string,
snapshot: NativeDirectoryTreeSnapshot,
parentIdentity: { dev: bigint; ino: bigint },
): NativeExactUnlinkResult;
};
function nativeDirectoryTreeApi(): NativeDirectoryTreeApi {
return nativeSessionStorage() as unknown as NativeDirectoryTreeApi;
}
function snapshotDirectoryTree(pathname: string): NativeDirectoryTreeSnapshot {
const result = nativeDirectoryTreeApi().snapshotDirectoryTree(pathname);
if (!result.ok || !result.snapshot)
throw new SessionDeleteVerificationError(
"artifacts",
`Native artifact snapshot rejected: ${result.ok ? "missing_snapshot" : result.code}`,
);
return result.snapshot;
}
function retainedTreeDoesNotExpandAuthority(
expected: NativeDirectoryTreeSnapshot,
retained: NativeDirectoryTreeSnapshot,
): boolean {
if (expected.rootDev !== retained.rootDev || expected.rootIno !== retained.rootIno) return false;
const expectedEntries = new Map(expected.entries.map(entry => [entry.relativePath, entry]));
if (retained.entries.length > expected.entries.length) return false;
return retained.entries.every(entry => {
if (entry.relativePath === "") return entry.kind === "directory";
const authorized = expectedEntries.get(entry.relativePath);
if (
authorized === undefined ||
authorized.kind !== entry.kind ||
authorized.dev !== entry.dev ||
authorized.ino !== entry.ino ||
authorized.nlink !== entry.nlink
)
return false;
if (entry.kind !== "file") return entry.size === authorized.size;
const scrubbed = entry.size === "0" && entry.sha256 === createHash("sha256").update("").digest("hex");
return scrubbed || (entry.size === authorized.size && entry.sha256 === authorized.sha256);
});
}
function removeDirectoryTreeExact(
pathname: string,
snapshot: NativeDirectoryTreeSnapshot,
parentIdentity: { dev: bigint; ino: bigint },
): NativeExactUnlinkResult {
return nativeDirectoryTreeApi().exactRemoveDirectoryTree(pathname, snapshot, parentIdentity);
}
function exactUnlinkFailure(result: NativeExactUnlinkResult): SessionDeleteVerificationError {
if (result.ok) throw new Error("Expected exact unlink failure");
const kind: VerifiedDeleteFailureKind =
result.code === "reparse_point" || result.code === "not_regular_file"
? "symlink"
: result.code === "identity_mismatch"
? "identity"
: "stat";
return new SessionDeleteVerificationError(kind, `Exact transcript deletion rejected: ${result.code}`);
}
/**
* A transcript-phase exact unlink is terminal when no live bytes survive. The
* native exchange-placeholder protocol on POSIX always retains a zero-length,
* descriptor-scrubbed, fsync'd internal recovery entry after scrubbing the
* detached transcript; `payloadDurable` proves the payload was destroyed before
* that entry was retained, so a placeholder alone never keeps transcript bytes
* alive. A retained successor or unknown path is genuine uncertainty and must
* stay `cleanup_pending`.
*/
function transcriptDeletionTerminal(result: NativeExactUnlinkResult): boolean {
if (result.ok) return true;
return (
result.code === "cleanup_pending" &&
(result as typeof result & { payloadDurable?: boolean }).payloadDurable === true &&
result.retainedSuccessorPath === undefined &&
result.retainedUnknownPath === undefined
);
}
function isValidManagedSecurityContext(value: SessionStorageSecurityContext): value is ManagedSessionSecurityContext {
if (
value?.kind !== "managed" ||
!Object.isFrozen(value) ||
!managedSecurityContexts.has(value) ||
!pathIsWithin(value.agentDir, value.sessionsRoot) ||
!pathIsWithin(value.sessionsRoot, value.sessionDir)
) {
return false;
}
assertManagedDirectoryRoot(value.rootAuthority);
if (!pathIsWithin(value.rootAuthority.canonicalPath, value.agentDir)) return false;
return true;
}
function secureOwnerOnlyFileDescriptor(
pathname: string,
fd: number,
operation: "apply" | "verify",
securityContext: SessionStorageSecurityContext,
): void {
if (securityContext && !isValidManagedSecurityContext(securityContext))
throw new Error("Invalid managed session security context");
if (securityContext) {
const root = fs.lstatSync(securityContext.rootAuthority.canonicalPath, { bigint: true });
if (
!root.isDirectory() ||
root.isSymbolicLink() ||
root.dev !== securityContext.rootAuthority.dev ||
root.ino !== securityContext.rootAuthority.ino
)
throw new Error("Managed writer root authority changed");
if (securityContext.retainedAuthority) {
const relative = path.relative(securityContext.sessionDir, pathname).split(path.sep).join("/");
const retained = securityContext.retainedAuthority.stat(relative);
const opened = fs.fstatSync(fd, { bigint: true });
if (
!retained.ok ||
!retained.identity ||
retained.identity.dev !== opened.dev.toString() ||
retained.identity.ino !== opened.ino.toString() ||
retained.identity.nlink !== opened.nlink.toString()
)
throw new Error("Managed writer descriptor escaped retained authority");
}
}
if (process.platform !== "linux" || !securityContext) {
if (operation === "apply") {
const applied = validateNativeSecurityResult(
nativeSessionStorage().applyOwnerOnlyPathSecurity(pathname, "file"),
"apply",
"file",
);
if (!applied.ok) throw new Error(`Owner-only security rejected ${pathname}: ${applied.code}`);
}
const verified = validateNativeSecurityResult(
nativeSessionStorage().verifyOwnerOnlyPathSecurity(pathname, "file"),
"verify",
"file",
);
if (!verified.ok) throw new Error(`Owner-only security rejected ${pathname}: ${verified.code}`);
return;
}
if (!pathIsWithin(securityContext.sessionDir, pathname))
throw new Error(`Managed writer escaped its session directory: ${pathname}`);
const result = validateNativeSecurityResult(
operation === "apply"
? nativeSessionStorage().applyOwnerOnlyFdSecurity(pathname, "file", fd)
: nativeSessionStorage().verifyOwnerOnlyFdSecurity(pathname, "file", fd),
operation,
"file",
);
if (!result.ok) throw new Error(`Owner-only security rejected ${pathname}: ${result.code}`);
}
/** Reject a symlink/junction/reparse component before a storage path is created or opened. */
function assertNoReparsePath(pathname: string): void {
const resolved = path.resolve(pathname);
const parsed = path.parse(resolved);
let current = parsed.root;
for (const part of resolved.slice(parsed.root.length).split(path.sep)) {
if (!part) continue;
current = path.join(current, part);
try {
if (fs.lstatSync(current).isSymbolicLink()) throw new Error(`Unsafe reparse storage path: ${current}`);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
}
}
}
// =============================================================================
// Commit-marker checked create/replace (mutable `.spill.commit` publication)
// =============================================================================
function fsyncDirectorySync(pathname: string): void {
if (!shouldFsyncManagedDirectory()) return;
const fd = fs.openSync(pathname, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY);
try {
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
}
/** Best-effort identity-checked removal of one of our own staged temp names. */
function unlinkOwnedStagedSync(stagingPath: string, expected: { dev: bigint; ino: bigint }): void {
let fd: number | undefined;
try {
const named = fs.lstatSync(stagingPath, { bigint: true });
if (!named.isFile() || named.isSymbolicLink() || named.dev !== expected.dev || named.ino !== expected.ino) return;
fd = fs.openSync(stagingPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
const opened = fs.fstatSync(fd, { bigint: true });
if (
!opened.isFile() ||
opened.dev !== named.dev ||
opened.ino !== named.ino ||
opened.nlink !== named.nlink ||
opened.size !== named.size ||
opened.mtimeNs !== named.mtimeNs ||
opened.ctimeNs !== named.ctimeNs
)
return;
const hash = createHash("sha256");
const buffer = Buffer.allocUnsafe(64 * 1024);
let offset = 0;
while (offset < Number(opened.size)) {
const length = Math.min(buffer.byteLength, Number(opened.size) - offset);
const count = fs.readSync(fd, buffer, 0, length, offset);
if (count === 0) return;
hash.update(buffer.subarray(0, count));
offset += count;
}
const after = fs.fstatSync(fd, { bigint: true });
if (
after.dev !== opened.dev ||
after.ino !== opened.ino ||
after.nlink !== opened.nlink ||
after.size !== opened.size ||
after.mtimeNs !== opened.mtimeNs ||
after.ctimeNs !== opened.ctimeNs
)
return;
exactRemoveSessionStorageLockPath(stagingPath, after, hash.digest("hex"), after.nlink > 1n);
} catch {
// ENOENT means the name was already consumed or removed; cleanup is best-effort.
} finally {
if (fd !== undefined) fs.closeSync(fd);
}
}
function sameDescriptorIdentity(left: SessionStorageStat, right: SessionStorageStat): boolean {
return (
left.dev === right.dev &&
left.ino === right.ino &&
left.nlink === right.nlink &&
left.size === right.size &&
left.mtimeNs === right.mtimeNs &&
left.ctimeNs === right.ctimeNs
);
}
/** Physically observed commit-marker state; corrupt JSON is still `present`. */
export type SessionCommitMarkerState =
| { kind: "missing" }
| { kind: "present"; rawBytesSha256: string; stat: SessionStorageStat };
/** Exact `present` expectation for one checked commit-marker replacement. */
export interface SessionCommitMarkerPresentExpectation {
/** SHA-256 of the exact raw marker bytes physically on disk (corrupt JSON included). */
rawBytesSha256: string;
/** Descriptor snapshot of the marker object expected to be replaced. */
descriptorIdentity: SessionStorageStat;
}
/** Snapshot one commit marker's physical state without granting write authority. */
export function readSessionCommitMarkerSync(storage: SessionStorage, markerPath: string): SessionCommitMarkerState {
if (!storage.existsSync(markerPath)) return { kind: "missing" };
if (!storage.readBytesSync) throw new Error("Commit marker reads require exact-bytes storage");
const bytes = storage.readBytesSync(markerPath);
const stat = storage.statSync(markerPath);
return { kind: "present", rawBytesSha256: createHash("sha256").update(bytes).digest("hex"), stat };
}
/**
* Checked commit-marker create: publishes only while the marker is still `missing`.
* Temp + fsync + atomic create-if-absent + directory fsync (file backend); the
* in-memory backend mirrors the same missing-expectation abort. Leftover temps are
* removed on any failure. Runs inside the caller's persistence fence.
*/
export function createSessionCommitMarkerCheckedSync(
storage: SessionStorage,
markerPath: string,
bytes: Uint8Array,
options?: { securityContext?: SessionStorageSecurityContext },
): void {
if (storage instanceof FileSessionStorage) {
createFileCommitMarkerCheckedSync(storage, markerPath, bytes, options?.securityContext);
return;
}
if (storage instanceof MemorySessionStorage) {
if (storage.existsSync(markerPath)) throw new Error("commit_marker_expected_missing");
storage.writeTextSync(markerPath, Buffer.from(bytes).toString("utf8"));
return;
}
throw new Error("Commit marker checked publication requires a file or memory storage backend");
}
/**
* Checked commit-marker replace: replaces only on an exact `present` raw/hash +
* descriptor identity match (corrupt-present included). Temp + fsync + checked
* atomic rename + directory fsync (file backend); any mismatch aborts with the
* current marker untouched. The in-memory backend mirrors the same aborts. Runs
* inside the caller's persistence fence.
*/
export function replaceSessionCommitMarkerCheckedSync(
storage: SessionStorage,
markerPath: string,
bytes: Uint8Array,
expected: SessionCommitMarkerPresentExpectation,
options?: { securityContext?: SessionStorageSecurityContext },
): void {
if (storage instanceof FileSessionStorage) {
replaceFileCommitMarkerCheckedSync(storage, markerPath, bytes, expected, options?.securityContext);
return;
}
if (storage instanceof MemorySessionStorage) {
replaceMemoryCommitMarkerCheckedSync(storage, markerPath, bytes, expected);
return;
}
throw new Error("Commit marker checked publication requires a file or memory storage backend");
}
function createFileCommitMarkerCheckedSync(
_storage: FileSessionStorage,
markerPath: string,
bytes: Uint8Array,
securityContext: SessionStorageSecurityContext,
): void {
const dir = path.dirname(markerPath);
assertNoReparsePath(dir);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
assertNoReparsePath(markerPath);
const tempPath = path.join(dir, `.${path.basename(markerPath)}.${randomUUID()}.tmp`);
let fd: number | undefined;
let stagedIdentity: { dev: bigint; ino: bigint } | undefined;
let failure: unknown;
let outcome: NativePublishOutcome | undefined;
let linkPublished = false;
try {
fd = fs.openSync(
tempPath,
fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | (fs.constants.O_NOFOLLOW ?? 0),
0o600,
);
secureOwnerOnlyFileDescriptor(tempPath, fd, "apply", securityContext);
const opened = fs.fstatSync(fd, { bigint: true });
stagedIdentity = { dev: opened.dev, ino: opened.ino };
let offset = 0;
while (offset < bytes.byteLength) {
const written = fs.writeSync(fd, bytes, offset, bytes.byteLength - offset);
if (written === 0) throw new Error("Short write");
offset += written;
}
fs.fsyncSync(fd);
secureOwnerOnlyFileDescriptor(tempPath, fd, "verify", securityContext);
const staged = fs.fstatSync(fd, { bigint: true });
stagedIdentity = { dev: staged.dev, ino: staged.ino };
fs.closeSync(fd);
fd = undefined;
outcome = classifyNativePublishOutcome(nativeSessionStorage().renameNoReplacePath(tempPath, markerPath));
if (renameFlagsUnsupported(outcome)) {
outcome = classifyNativePublishOutcome(nativeSessionStorage().linkNoReplacePath(tempPath, markerPath));
linkPublished = outcome.ok;
}
if (!outcome.ok) {
if (outcome.reason === "destination_exists") throw new Error("commit_marker_expected_missing");
throw new Error(`commit_marker_create_rejected:${outcome.reason}`);
}
const named = fs.lstatSync(markerPath, { bigint: true });
if (
!named.isFile() ||
named.isSymbolicLink() ||
named.dev !== stagedIdentity.dev ||
named.ino !== stagedIdentity.ino
)
throw new Error("destination_identity_changed");
fsyncDirectorySync(dir);
} catch (error) {
failure = error;
} finally {
if (fd !== undefined) fs.closeSync(fd);
if (stagedIdentity && (outcome === undefined || linkPublished || mayCleanCurrentStaging(outcome))) {
unlinkOwnedStagedSync(tempPath, stagedIdentity);
}
}
if (failure !== undefined) throw failure;
}
function replaceFileCommitMarkerCheckedSync(
storage: FileSessionStorage,
markerPath: string,
bytes: Uint8Array,
expected: SessionCommitMarkerPresentExpectation,
securityContext: SessionStorageSecurityContext,
): void {
// Expected-state check runs before any mutation (inside the caller's fence).
const current = readSessionCommitMarkerSync(storage, markerPath);
if (current.kind !== "present") throw new Error("commit_marker_expected_present");
if (current.rawBytesSha256 !== expected.rawBytesSha256) throw new Error("commit_marker_raw_hash_mismatch");
if (!sameDescriptorIdentity(current.stat, expected.descriptorIdentity))
throw new Error("commit_marker_identity_mismatch");
const dir = path.dirname(markerPath);
const parentIdentity = fs.statSync(dir, { bigint: true });
const tempPath = path.join(dir, `.${path.basename(markerPath)}.${randomUUID()}.tmp`);
let fd: number | undefined;
let staged: fs.BigIntStats | undefined;
let stagedIdentity: { dev: bigint; ino: bigint } | undefined;
const stagedSha256 = createHash("sha256").update(bytes).digest("hex");
let failure: unknown;
try {
fd = fs.openSync(
tempPath,
fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | (fs.constants.O_NOFOLLOW ?? 0),
0o600,
);
secureOwnerOnlyFileDescriptor(tempPath, fd, "apply", securityContext);
const opened = fs.fstatSync(fd, { bigint: true });
stagedIdentity = { dev: opened.dev, ino: opened.ino };
let offset = 0;
while (offset < bytes.byteLength) {
const written = fs.writeSync(fd, bytes, offset, bytes.byteLength - offset);
if (written === 0) throw new Error("Short write");
offset += written;
}
fs.fsyncSync(fd);
secureOwnerOnlyFileDescriptor(tempPath, fd, "verify", securityContext);