@git-stunts/git-cas 6.4.0 → 6.5.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.
package/ARCHITECTURE.md CHANGED
@@ -374,6 +374,8 @@ Pure utility functions with no domain or infrastructure coupling:
374
374
  - **`kdfPolicy.js`** — KDF parameter validation and sensible defaults.
375
375
  - **`aesGcmMeta.js`** — AES-GCM metadata validation (IV length, tag length).
376
376
  - **`canonicalBase64.js`** — base64 encoding round-trip integrity check.
377
+ - **`boundedPromiseCache.js`** — fixed-residency LRU coalescing for immutable
378
+ async reads; rejected work is never retained.
377
379
 
378
380
  ## Storage Model
379
381
 
package/CHANGELOG.md CHANGED
@@ -7,6 +7,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [6.5.1] — 2026-07-18
11
+
12
+ ### Performance
13
+
14
+ - **Bounded immutable page payload reuse** - repeated `pages.get()` calls now
15
+ share successful in-flight and completed payload reads through an LRU bounded
16
+ by both entry count and aggregate bytes. Callers receive copies, failures
17
+ remain retryable, oversized values do not displace unrelated residents, and
18
+ `pages.open()` remains uncached and streaming.
19
+
20
+ ## [6.5.0] — 2026-07-18
21
+
22
+ ### Added
23
+
24
+ - **Direct bundle references** - `bundles.getMemberReference()` and
25
+ `bundles.iterateMemberReferences()` validate bundle structure, canonical
26
+ descriptors, direct Git edges, and direct target object types without
27
+ recursively resolving each member's support graph. Existing member and root
28
+ methods retain complete-validation semantics.
29
+
30
+ ### Performance
31
+
32
+ - **Bounded immutable Git metadata coalescing** - repeated exact tree-entry and
33
+ object-info reads now share successful in-flight and completed work through a
34
+ fixed-residency LRU. BundleService separately retains only structural
35
+ descriptor bytes under both entry and byte bounds. Rejected work is evicted,
36
+ mutable records are cloned for callers, and no application payloads or ref
37
+ state enter either cache.
38
+
39
+ ### Fixed
40
+
41
+ - **Observed RootSet compare-and-swap races** - exact failed
42
+ `update-ref --no-deref` commands with an independently observed head advance
43
+ now normalize to `ROOT_SET_CONFLICT` even when Git emits no diagnostic text.
44
+ OIDs are compared canonically so case-only differences do not create false
45
+ conflicts.
46
+ - **Bounded cache settlement** - rejected work is removed before its returned
47
+ promise settles, and a resolved value larger than its weight budget is
48
+ discarded before eviction runs, preserving retryability and unrelated
49
+ residents.
50
+
10
51
  ## [6.4.0] — 2026-07-17
11
52
 
12
53
  ### Added
package/GUIDE.md CHANGED
@@ -163,6 +163,12 @@ lookup reads only the descriptor path and selected payload; retention and
163
163
  publication perform full bounded graph validation. Identical page bytes and
164
164
  identically constructed bundles produce identical handles.
165
165
 
166
+ Repeated `pages.get()` calls reuse immutable payload reads within the store's
167
+ bounded page cache. The defaults retain at most 128 payloads and 8 MiB; use
168
+ `pageCacheEntries` and `pageCacheBytes` to tune that ceiling. Every result is a
169
+ caller-owned copy. `pages.open()` remains uncached and streaming, and neither
170
+ form of access establishes retention.
171
+
166
172
  ### Generic Application Publication
167
173
 
168
174
  Publication is disabled until the facade receives an explicit application-ref
package/README.md CHANGED
@@ -44,7 +44,7 @@ Unlike traditional LFS which moves files to external servers, `git-cas` treats t
44
44
  Existing v5 users should read [UPGRADING.md](./UPGRADING.md) and run
45
45
  `npm run upgrade` in dry-run mode before restoring old encrypted vault entries.
46
46
  For the release overview, see the
47
- [v6.4.0 Release Notes](./docs/releases/v6.4.0.md).
47
+ [v6.5.1 Release Notes](./docs/releases/v6.5.1.md).
48
48
 
49
49
  ### 1. CLI Usage
50
50
 
@@ -94,21 +94,21 @@ the asset reachable.
94
94
 
95
95
  The README is the front door. Detailed mechanics live in the guide set:
96
96
 
97
- | Need | Start Here |
98
- | ------------------------------------------------------- | ------------------------------------------------------------ |
99
- | Productive library and CLI workflows | [Developer Guide](./GUIDE.md) |
100
- | Restore memory behavior | [Streaming and restore matrix](./GUIDE.md#streaming-surface) |
101
- | Encryption scheme selection | [Encryption Modes](./docs/ENCRYPTION_MODES.md) |
102
- | CDC internals, Merkle manifests, KDF policy, and tuning | [Advanced Guide](./ADVANCED_GUIDE.md) |
103
- | Ports, adapters, and collaborator boundaries | [Architecture](./ARCHITECTURE.md) |
104
- | Assets, pages, bundles, retention, and publication | [Application storage](./docs/API.md#application-storage) |
105
- | Temporary retention during multi-step composition | [Scoped staging workspaces](./docs/API.md#scoped-staging-workspaces) |
106
- | GC retention for caches and derived state | [Root Sets](./docs/API.md#root-sets) |
107
- | Managed TTL and capacity caches | [Cache Sets](./docs/API.md#cache-sets) |
108
- | Scoped protection while consuming a cache hit | [Cache acquisitions](./docs/API.md#acquire-and-release) |
109
- | Durable replay markers with expiry-only release | [Expiring Sets](./docs/API.md#expiring-sets) |
110
- | Repository reachability and git-cas usage evidence | [Repository Diagnostics](./docs/API.md#repository-diagnostics) |
111
- | v5 to v6 migration | [Upgrading](./UPGRADING.md) |
97
+ | Need | Start Here |
98
+ | ------------------------------------------------------- | -------------------------------------------------------------------- |
99
+ | Productive library and CLI workflows | [Developer Guide](./GUIDE.md) |
100
+ | Restore memory behavior | [Streaming and restore matrix](./GUIDE.md#streaming-surface) |
101
+ | Encryption scheme selection | [Encryption Modes](./docs/ENCRYPTION_MODES.md) |
102
+ | CDC internals, Merkle manifests, KDF policy, and tuning | [Advanced Guide](./ADVANCED_GUIDE.md) |
103
+ | Ports, adapters, and collaborator boundaries | [Architecture](./ARCHITECTURE.md) |
104
+ | Assets, pages, bundles, retention, and publication | [Application storage](./docs/API.md#application-storage) |
105
+ | Temporary retention during multi-step composition | [Scoped staging workspaces](./docs/API.md#scoped-staging-workspaces) |
106
+ | GC retention for caches and derived state | [Root Sets](./docs/API.md#root-sets) |
107
+ | Managed TTL and capacity caches | [Cache Sets](./docs/API.md#cache-sets) |
108
+ | Scoped protection while consuming a cache hit | [Cache acquisitions](./docs/API.md#acquire-and-release) |
109
+ | Durable replay markers with expiry-only release | [Expiring Sets](./docs/API.md#expiring-sets) |
110
+ | Repository reachability and git-cas usage evidence | [Repository Diagnostics](./docs/API.md#repository-diagnostics) |
111
+ | v5 to v6 migration | [Upgrading](./UPGRADING.md) |
112
112
 
113
113
  Core capabilities:
114
114
 
@@ -138,8 +138,8 @@ Core capabilities:
138
138
  read-only, and `sweep()` can release only markers whose expiry has passed.
139
139
  - **Application storage**: `assets`, `pages`, `bundles`, `retention`, and
140
140
  `publications` compose streaming CAS writes, bounded structured
141
- materializations, targeted member reads, reachability roots,
142
- compare-and-swap refs, and immutable lifecycle evidence.
141
+ materializations, direct-reference or complete-validation member reads,
142
+ reachability roots, compare-and-swap refs, and immutable lifecycle evidence.
143
143
  - **Scoped staging workspaces**: `workspaces.open()` mirrors application writes
144
144
  behind one renewable temporary RootSet, returns only after each handle is
145
145
  anchored, promotes destination-first, and exposes bounded age, expiry,
@@ -202,6 +202,10 @@ All three runtimes are tested in CI on every push. The hexagonal architecture is
202
202
  reference-only cache acquisitions with explicit release and doctor evidence.
203
203
  - **[v6.4.0 Release Notes](./docs/releases/v6.4.0.md)**: Scoped staging
204
204
  workspaces for temporary multi-object reachability, promotion, and cleanup.
205
+ - **[v6.5.0 Release Notes](./docs/releases/v6.5.0.md)**: Bounded direct bundle
206
+ references, immutable metadata reuse, and corrected concurrency settlement.
207
+ - **[v6.5.1 Release Notes](./docs/releases/v6.5.1.md)**: Bounded immutable page
208
+ payload reuse with zero-command warm reads.
205
209
  - **[Upgrading](./UPGRADING.md)**: Migration guide for v5 → v6.
206
210
  - **[Changelog](./CHANGELOG.md)**: Version history and migration notes.
207
211
 
package/UPGRADING.md CHANGED
@@ -2,6 +2,73 @@
2
2
 
3
3
  v6.0.0 is a major release that simplifies the encryption model, hardens security defaults, and cleans up the architecture. This guide covers every breaking change and what you need to do.
4
4
 
5
+ ## v6.5.0 To v6.5.1
6
+
7
+ v6.5.1 is API-additive and does not require stored-data migration. Repeated
8
+ `pages.get()` calls now reuse immutable payload bytes through a process-local
9
+ LRU bounded by entry count and aggregate bytes. Applications may tune the
10
+ defaults with `pageCacheEntries` and `pageCacheBytes` when constructing the
11
+ store.
12
+
13
+ Every caller still receives an independent `Uint8Array`, and each call's
14
+ `maxBytes` limit remains authoritative on cold, resident, and shared in-flight
15
+ reads. Rejected work remains retryable, and an individually oversized payload
16
+ does not displace unrelated residents.
17
+
18
+ `pages.open()` remains the streaming API and never enters the payload cache.
19
+ Cache residence is an optimization, not retention evidence; keep each handle
20
+ reachable through a workspace, RootSet, cache acquisition, publication, or
21
+ other documented lifetime while consuming it.
22
+
23
+ See [v6.5.1 Release Notes](./docs/releases/v6.5.1.md) and
24
+ [Application Storage](./docs/API.md#application-storage) for the complete
25
+ residency and lifetime contract.
26
+
27
+ ## v6.4.0 To v6.5.0
28
+
29
+ v6.5.0 is API-additive and does not require stored-data migration. It adds
30
+ bounded reference reads for callers that need a member handle without
31
+ recursively resolving that member's complete support graph.
32
+
33
+ Use `getMemberReference()` for one exact path:
34
+
35
+ ```javascript
36
+ const reference = await cas.bundles.getMemberReference({
37
+ handle: materializationBundle,
38
+ path: 'nodes/user-alice.cbor',
39
+ });
40
+
41
+ if (reference) {
42
+ await consumeRetainedHandle(reference.handle);
43
+ }
44
+ ```
45
+
46
+ Use `iterateMemberReferences()` for a streaming structural scan:
47
+
48
+ ```javascript
49
+ for await (const reference of cas.bundles.iterateMemberReferences({
50
+ handle: materializationBundle,
51
+ })) {
52
+ await indexReference(reference);
53
+ }
54
+ ```
55
+
56
+ These APIs validate the bundle root, every traversed descriptor summary, the
57
+ selected or enumerated Git tree edges, and each direct target object type. They
58
+ do not recursively validate nested page, asset, or bundle support graphs. Keep
59
+ using `getMember()` or `iterateMembers()` when the operation requires complete
60
+ recursive validation and computed `logicalBytes`.
61
+
62
+ Reference results are observations, not retention claims. Keep the containing
63
+ bundle reachable through a workspace, cache acquisition, RootSet, or other
64
+ documented lifetime while consuming them. The immutable metadata and
65
+ descriptor caches introduced in v6.5.0 are bounded internal implementation
66
+ details; callers do not manage or invalidate them.
67
+
68
+ See [v6.5.0 Release Notes](./docs/releases/v6.5.0.md) and
69
+ [Application Storage](./docs/API.md#application-storage) for the
70
+ complete integrity and lifetime contract.
71
+
5
72
  ## v6.3.0 To v6.4.0
6
73
 
7
74
  v6.4.0 is API-additive and does not require stored-data migration. It adds
@@ -198,13 +265,13 @@ for example a job workspace or tenant-scoped artifact directory.
198
265
 
199
266
  v5 had 5 encryption scheme identifiers. v6 has 3:
200
267
 
201
- | v5 Scheme | v6 Scheme | Migration |
202
- |---|---|---|
203
- | `whole-v1` | `whole` | **Re-encryption required** (v1 had no AAD) |
204
- | `whole-v2` | `whole` | Rename only (already had AAD) |
205
- | `framed-v1` | `framed` | **Re-encryption required** (v1 had no AAD) |
206
- | `framed-v2` | `framed` | Rename only (already had AAD) |
207
- | `convergent-v1` | `convergent` | Rename only |
268
+ | v5 Scheme | v6 Scheme | Migration |
269
+ | --------------- | ------------ | ------------------------------------------ |
270
+ | `whole-v1` | `whole` | **Re-encryption required** (v1 had no AAD) |
271
+ | `whole-v2` | `whole` | Rename only (already had AAD) |
272
+ | `framed-v1` | `framed` | **Re-encryption required** (v1 had no AAD) |
273
+ | `framed-v2` | `framed` | Rename only (already had AAD) |
274
+ | `convergent-v1` | `convergent` | Rename only |
208
275
 
209
276
  ### Why
210
277
 
@@ -285,11 +352,11 @@ verifier and the next keyed vault write will add it.
285
352
 
286
353
  ### What Changed
287
354
 
288
- | Scenario | v5 Default | v6 Default |
289
- |---|---|---|
290
- | CDC chunking + encryption | `framed-v1` | `convergent` |
291
- | Fixed chunking + encryption | `framed-v1` | `framed` |
292
- | Explicit `whole` | `whole-v1` | `whole` |
355
+ | Scenario | v5 Default | v6 Default |
356
+ | --------------------------- | ----------- | ------------ |
357
+ | CDC chunking + encryption | `framed-v1` | `convergent` |
358
+ | Fixed chunking + encryption | `framed-v1` | `framed` |
359
+ | Explicit `whole` | `whole-v1` | `whole` |
293
360
 
294
361
  ### What This Means
295
362
 
@@ -382,14 +449,14 @@ import { SCHEME_WHOLE, SCHEME_FRAMED, SCHEME_CONVERGENT } from '@git-stunts/git-
382
449
 
383
450
  ### Behavioral Changes
384
451
 
385
- | Change | Impact |
386
- |---|---|
387
- | Plaintext + gzip restore now streams | Lower memory usage. Should be transparent. |
388
- | AAD always on for `whole` and `framed` | Cannot opt out. v1-style no-AAD is gone. |
452
+ | Change | Impact |
453
+ | ---------------------------------------- | ------------------------------------------------------------------------------------- |
454
+ | Plaintext + gzip restore now streams | This lowers memory usage and should be transparent. |
455
+ | AAD always on for `whole` and `framed` | Cannot opt out. v1-style no-AAD is gone. |
389
456
  | Manifest integrity hash verified on read | Corrupted manifests that previously loaded will now throw `MANIFEST_INTEGRITY_ERROR`. |
390
- | KDF policy enforced in `deriveKey()` | Dangerously weak params (e.g., 1 PBKDF2 iteration) now throw `KDF_POLICY_VIOLATION`. |
391
- | Concurrency capped at 64 | Was unbounded. Unlikely to affect real usage. |
392
- | frameBytes capped at 64 MiB | Was unbounded. Unlikely to affect real usage. |
457
+ | KDF policy enforced in `deriveKey()` | Dangerously weak params (e.g., 1 PBKDF2 iteration) now throw `KDF_POLICY_VIOLATION`. |
458
+ | Concurrency capped at 64 | Was unbounded. Unlikely to affect real usage. |
459
+ | frameBytes capped at 64 MiB | Was unbounded. Unlikely to affect real usage. |
393
460
 
394
461
  ---
395
462
 
package/build-info.json CHANGED
@@ -1,4 +1,4 @@
1
1
  {
2
- "sha": "d47af74",
3
- "timestamp": "2026-07-18T02:58:21.403Z"
2
+ "sha": "49b7d5c",
3
+ "timestamp": "2026-07-19T00:14:16.713Z"
4
4
  }
package/docs/API.md CHANGED
@@ -80,6 +80,8 @@ new ContentAddressableStore(options);
80
80
  - `options.maxRestoreBufferSize` (optional): Max bytes for buffered encrypted/compressed restore (default: 536870912 / 512 MiB)
81
81
  - `options.maxBlobSize` (optional): Max bytes for metadata blob reads (default: 10485760 / 10 MiB)
82
82
  - `options.maxPageSize` (optional): Maximum immutable page bytes (default: 16777216 / 16 MiB)
83
+ - `options.pageCacheEntries` (optional): Maximum immutable page payloads retained in memory (default: 128)
84
+ - `options.pageCacheBytes` (optional): Maximum immutable page payload bytes retained in memory (default: 8388608 / 8 MiB)
83
85
  - `options.bundleLimits` (optional): Repository maximums for bundle members, path bytes, descriptor bytes, fanout entries, and fanout depth
84
86
  - `options.maxBundleNestingDepth` (optional): Maximum nested bundle depth (default: 32)
85
87
  - `options.compressionAdapter` (optional): CompressionPort implementation (default: NodeCompressionAdapter)
@@ -1025,6 +1027,19 @@ metadata before streaming it. `get()` additionally collects the page under its
1025
1027
  effective byte bound. An imported handle above the configured maximum fails
1026
1028
  with `PAGE_TOO_LARGE` without materializing the blob.
1027
1029
 
1030
+ Successful `get()` payloads share in-flight and completed immutable reads inside
1031
+ one store instance. The default LRU retains at most 128 payloads and 8 MiB of
1032
+ payload bytes; `pageCacheEntries` and `pageCacheBytes` may lower or raise those
1033
+ bounds. Every result is copied for its caller, failed reads remain retryable,
1034
+ and a payload larger than the byte budget is returned without remaining
1035
+ resident. Cold misses validate object type and size before reading. Resident or
1036
+ in-flight hits reuse that immutable OID validation and still enforce the current
1037
+ caller's `maxBytes`. In-flight work is coalesced separately from completed LRU
1038
+ residence, so its transient memory follows caller concurrency and the per-page
1039
+ size bound. `open()` remains streaming and does not enter the payload cache.
1040
+ This reuse is not retention evidence; callers must keep the page reachable for
1041
+ the duration of use.
1042
+
1028
1043
  The canonical page token is:
1029
1044
 
1030
1045
  ```text
@@ -1077,6 +1092,47 @@ The canonical bundle token is:
1077
1092
  git-cas:1:bundle:fanout-tree:<codec>:<sha1|sha256>:<oid>
1078
1093
  ```
1079
1094
 
1095
+ ### Direct bundle references
1096
+
1097
+ ```javascript
1098
+ const reference = await cas.bundles.getMemberReference({
1099
+ handle: materializationHandle,
1100
+ path: 'nodes/root',
1101
+ });
1102
+
1103
+ for await (const reference of cas.bundles.iterateMemberReferences({
1104
+ handle: materializationHandle,
1105
+ })) {
1106
+ indexHandle(reference.path, reference.handle);
1107
+ }
1108
+ ```
1109
+
1110
+ `getMemberReference()` and `iterateMemberReferences()` are the explicit lazy
1111
+ integrity surfaces. They validate the bundle root, persisted limits, fanout
1112
+ summaries, canonical member descriptor, direct Git tree edge, and direct target
1113
+ object type. They do not recursively resolve the referenced member's complete
1114
+ support graph. Use them for indexes and manifests that dereference only selected
1115
+ members.
1116
+
1117
+ Each immutable `BundleMemberReference` contains `version`, `path`, `handle`,
1118
+ `type`, and declared `size`. Missing paths return `null`; malformed bundle
1119
+ structure, mismatched edges, and missing or mistyped direct targets fail closed.
1120
+ Completing reference iteration still validates root and fanout summaries.
1121
+
1122
+ The Git persistence adapter coalesces successful exact tree-entry and
1123
+ object-info reads in one process-local LRU with a fixed 2,048-entry default.
1124
+ Bundle traversal separately retains immutable structural descriptor bytes under
1125
+ a 1,024-entry and 16 MiB total bound. Rejected work is removed, returned
1126
+ tree-entry records are cloned, and application payloads, refs, and collection
1127
+ state are never cached. Advanced direct adapter construction may set
1128
+ `metadataCacheEntries` to another positive safe integer.
1129
+
1130
+ Object identity is immutable, but external pruning can change whether an
1131
+ unretained object remains available. Keep roots retained for the adapter's
1132
+ operation lifetime and do not race active reads with destructive repository
1133
+ maintenance. Payload access performs authoritative Git I/O if availability
1134
+ changes despite that precondition.
1135
+
1080
1136
  ### `bundles.getMember()`, `bundles.iterateMembers()`, and `bundles.openMember()`
1081
1137
 
1082
1138
  ```javascript
@@ -0,0 +1,140 @@
1
+ # git-cas v6.5.0 Release Notes
2
+
3
+ v6.5.0 adds bounded direct bundle-reference reads for applications that need to
4
+ locate or enumerate retained materialization handles without recursively
5
+ hydrating every referenced support graph. It also adds bounded reuse for
6
+ immutable Git metadata and bundle descriptors, and repairs two concurrency
7
+ edge cases found while proving the new path under stress.
8
+
9
+ This release is API-additive. It does not change persisted bundle formats and
10
+ does not require stored-data migration.
11
+
12
+ ## Direct Bundle References
13
+
14
+ Read one exact member descriptor without opening its payload or recursively
15
+ resolving the member's complete support graph:
16
+
17
+ ```javascript
18
+ const reference = await cas.bundles.getMemberReference({
19
+ handle: materializationBundle,
20
+ path: 'nodes/user-alice.cbor',
21
+ });
22
+
23
+ if (reference) {
24
+ console.log(reference.handle);
25
+ console.log(reference.type);
26
+ console.log(reference.size);
27
+ }
28
+ ```
29
+
30
+ Stream canonical member descriptors without collecting the whole bundle:
31
+
32
+ ```javascript
33
+ for await (const reference of cas.bundles.iterateMemberReferences({
34
+ handle: materializationBundle,
35
+ })) {
36
+ await indexReference(reference);
37
+ }
38
+ ```
39
+
40
+ Each `BundleMemberReference` contains:
41
+
42
+ - `version: 1`;
43
+ - the canonical member `path`;
44
+ - the typed application `handle`;
45
+ - the direct Git object `type`; and
46
+ - the declared byte `size`, or `null` for structured tree members.
47
+
48
+ The existing `getMember()` and `iterateMembers()` APIs retain complete recursive
49
+ validation semantics and include computed `logicalBytes`.
50
+
51
+ ## Integrity Boundary
52
+
53
+ The direct path validates:
54
+
55
+ - the bundle handle codec and root tree type;
56
+ - the root descriptor and persisted read limits;
57
+ - every descriptor and summary along the selected path, or across the streamed
58
+ structural traversal;
59
+ - every traversed fanout tree edge;
60
+ - the selected or enumerated leaf edge; and
61
+ - each direct target Git object type.
62
+
63
+ It does not recursively validate a selected page, asset, or nested bundle's
64
+ complete support graph. Callers that require that stronger proof must continue
65
+ to use `getMember()` or `iterateMembers()`.
66
+
67
+ A reference is also not a retention witness. The containing bundle must remain
68
+ reachable through a workspace, RootSet, cache acquisition, publication, or
69
+ other documented lifetime while the reference is consumed.
70
+
71
+ ## Bounded Immutable Reuse
72
+
73
+ Repeated exact tree-entry and object-info reads now share successful in-flight
74
+ and completed work inside each Git persistence adapter. The default metadata
75
+ cache retains at most 2,048 immutable entries and can be lowered with the
76
+ `metadataCacheEntries` constructor option.
77
+
78
+ Bundle descriptors use a separate cache bounded by both 1,024 entries and 16
79
+ MiB. Returned byte arrays and mutable metadata records are copied for callers.
80
+ Rejected work removes itself so a later read can retry. Values larger than the
81
+ descriptor byte budget are returned to the current caller but are not retained
82
+ and do not evict unrelated residents.
83
+
84
+ These caches contain immutable Git metadata and structural descriptors only.
85
+ They do not retain application payload bytes, mutable refs, cache indexes, or
86
+ root-set state.
87
+
88
+ ## Concurrency Repairs
89
+
90
+ The RootSet compare-and-swap classifier now recovers exact failed
91
+ `git update-ref --no-deref` races when Git exits fatally without diagnostic
92
+ text, provided an independent ref read proves that the managed head advanced.
93
+ OID comparisons use canonical lowercase values, avoiding false conflicts from
94
+ case-only differences. A checked-in real-Git diagnostic passed 500/500
95
+ two-writer replacement races after the repair.
96
+
97
+ The bounded promise cache now removes rejected work before the returned promise
98
+ settles, preserving immediate retry semantics. Individually oversized resolved
99
+ values are discarded before weight-based eviction runs, preserving unrelated
100
+ residents.
101
+
102
+ ## Performance Evidence
103
+
104
+ The stable regression contract counts real Git commands rather than asserting
105
+ portable wall-clock latency:
106
+
107
+ - a cold direct read must perform metadata work;
108
+ - an identical warm direct read must perform zero additional Git metadata
109
+ commands; and
110
+ - direct reference iteration must issue fewer total and object-inspection
111
+ commands than complete recursive validation.
112
+
113
+ On the recorded four-node git-warp fixture, the final direct-reference and
114
+ descriptor-cache path reduced one selected read from 192 Git commands to 69,
115
+ approximately 64 percent. The same host sample reduced the observed wall time
116
+ from approximately 3-5 seconds to 1.291 seconds. These timings are diagnostic,
117
+ not cross-machine promises; command-count integration is the merge gate.
118
+
119
+ ## Verification
120
+
121
+ The final release candidate passed 14/14 verifier steps with 6,625 observed
122
+ tests:
123
+
124
+ - Node.js: 2,020 unit tests and 192 real-Git integration tests;
125
+ - Bun: 2,019 unit tests and 192 real-Git integration tests; and
126
+ - Deno: 2,010 unit tests and 192 real-Git integration tests.
127
+
128
+ The verifier also passed lint, examples, public type compatibility, build
129
+ stamping, npm package inspection, and the JSR publish dry-run. The checked-in
130
+ RootSet race diagnostic passed 500/500 two-writer replacement races.
131
+
132
+ ## Upgrade Notes
133
+
134
+ No stored-data migration is required. Existing complete-validation calls keep
135
+ their behavior. Applications may adopt the new reference APIs selectively where
136
+ their own retained lifetime already guarantees that recursive support remains
137
+ available.
138
+
139
+ See [UPGRADING.md](../../UPGRADING.md) for the adoption decision and
140
+ [Application Storage](../API.md#application-storage) for the full API contract.
@@ -0,0 +1,44 @@
1
+ # git-cas v6.5.1 Release Notes
2
+
3
+ v6.5.1 completes the bounded immutable read path introduced in v6.5.0 by
4
+ coalescing repeated `pages.get()` payload reads. Exact application reads no
5
+ longer start another Git blob process when the same retained page is already
6
+ resident in the store's bounded payload cache.
7
+
8
+ ## Bounded Payload Reuse
9
+
10
+ The page cache defaults to at most 128 entries and 8 MiB of payload bytes. It
11
+ allocates no fixed arena. Applications can configure the limits with
12
+ `pageCacheEntries` and `pageCacheBytes` when constructing the store.
13
+
14
+ Every `get()` result is a caller-owned copy. Concurrent reads share in-flight
15
+ work, rejected reads are immediately retryable, and values larger than the byte
16
+ budget are returned to the current caller without remaining resident or
17
+ evicting unrelated entries. In-flight work is tracked separately from completed
18
+ LRU residence, so capacity pressure cannot break coalescing; transient memory
19
+ still follows caller concurrency and the configured per-page size bound.
20
+
21
+ `pages.open()` is unchanged: it remains a streaming operation and never enters
22
+ the payload cache. Cache residence is not a retention witness, so applications
23
+ must continue to keep handles reachable through the documented lifecycle APIs.
24
+
25
+ ## Performance Evidence
26
+
27
+ The real-Git command-count integration contract proves that an identical warm
28
+ `pages.get()` performs zero additional Git commands. git-warp will publish its
29
+ end-to-end CPU, wall-clock, Git-command, and bounded-memory deltas after adopting
30
+ this release.
31
+
32
+ ## Verification
33
+
34
+ The versioned candidate passed all 14 release-verifier steps with 6,676 observed
35
+ tests: 2,036 Node unit tests, 2,035 Bun unit tests, 2,026 Deno unit tests, and
36
+ 193 real-Git integration tests on each runtime. Lint, examples, public type
37
+ compatibility, build stamping, npm packaging dry-run, and JSR publication
38
+ dry-run also passed.
39
+
40
+ ## Compatibility
41
+
42
+ This release does not require stored-data migration. It changes no persisted
43
+ formats, handles, refs, witnesses, or existing method signatures. The two
44
+ constructor options are additive and optional.
package/index.d.ts CHANGED
@@ -564,7 +564,11 @@ export declare class GitRefPortBase {
564
564
 
565
565
  /** Git-backed implementation of the persistence port. */
566
566
  export declare class GitPersistenceAdapter extends GitPersistencePortBase {
567
- constructor(options: { plumbing: unknown; policy?: unknown });
567
+ constructor(options: {
568
+ plumbing: unknown;
569
+ policy?: unknown;
570
+ metadataCacheEntries?: number;
571
+ });
568
572
  setMaxBlobSize(maxBlobSize: number): void;
569
573
  }
570
574
 
@@ -702,6 +706,10 @@ export interface ContentAddressableStoreOptions {
702
706
  maxBlobSize?: number;
703
707
  /** Maximum immutable page size in bytes. @default 16777216 (16 MiB) */
704
708
  maxPageSize?: number;
709
+ /** Maximum immutable page payloads retained in memory. @default 128 */
710
+ pageCacheEntries?: number;
711
+ /** Maximum immutable page payload bytes retained in memory. @default 8388608 (8 MiB) */
712
+ pageCacheBytes?: number;
705
713
  /** Repository-wide maximum bundle admission limits. */
706
714
  bundleLimits?: Partial<BundleLimits>;
707
715
  /** Maximum nested bundle depth. @default 32 */
@@ -1456,12 +1464,15 @@ export type BundleMemberInput =
1456
1464
  | PageSource
1457
1465
  | { source: PageSource; maxBytes?: number };
1458
1466
 
1459
- export interface BundleMember {
1467
+ export interface BundleMemberReference {
1460
1468
  readonly version: 1;
1461
1469
  readonly path: string;
1462
1470
  readonly handle: ApplicationHandle;
1463
1471
  readonly type: 'blob' | 'tree';
1464
1472
  readonly size: number | null;
1473
+ }
1474
+
1475
+ export interface BundleMember extends BundleMemberReference {
1465
1476
  readonly logicalBytes: number;
1466
1477
  }
1467
1478
 
@@ -1483,6 +1494,11 @@ export interface BundleCapability {
1483
1494
  handle: BundleHandleInput;
1484
1495
  path: string;
1485
1496
  }): Promise<BundleMember | null>;
1497
+ getMemberReference(options: {
1498
+ handle: BundleHandleInput;
1499
+ path: string;
1500
+ }): Promise<BundleMemberReference | null>;
1501
+ iterateMemberReferences(options: { handle: BundleHandleInput }): AsyncIterable<BundleMemberReference>;
1486
1502
  iterateMembers(options: { handle: BundleHandleInput }): AsyncIterable<BundleMember>;
1487
1503
  openMember(options: { handle: BundleHandleInput; path: string }): AsyncIterable<Uint8Array>;
1488
1504
  }
package/index.js CHANGED
@@ -133,6 +133,8 @@ export default class ContentAddressableStore {
133
133
  * @param {number} [options.maxRestoreBufferSize=536870912] - Max buffered restore size in bytes for encrypted/compressed restores (default 512 MiB).
134
134
  * @param {number} [options.maxBlobSize=10485760] - Safety limit for readBlob metadata in bytes (default 10 MiB).
135
135
  * @param {number} [options.maxPageSize=16777216] - Maximum immutable page size in bytes (default 16 MiB).
136
+ * @param {number} [options.pageCacheEntries=128] - Maximum immutable page payloads retained in memory.
137
+ * @param {number} [options.pageCacheBytes=8388608] - Maximum immutable page payload bytes retained in memory.
136
138
  * @param {object} [options.bundleLimits] - Repository-wide maximum bundle admission limits.
137
139
  * @param {number} [options.maxBundleNestingDepth=32] - Maximum nested bundle depth.
138
140
  * @param {import('./src/ports/CompressionPort.js').default} [options.compressionAdapter] - Compression adapter (default NodeCompressionAdapter).
@@ -153,6 +155,8 @@ export default class ContentAddressableStore {
153
155
  maxRestoreBufferSize,
154
156
  maxBlobSize,
155
157
  maxPageSize,
158
+ pageCacheEntries,
159
+ pageCacheBytes,
156
160
  bundleLimits,
157
161
  maxBundleNestingDepth,
158
162
  compressionAdapter,
@@ -173,6 +177,8 @@ export default class ContentAddressableStore {
173
177
  maxRestoreBufferSize,
174
178
  maxBlobSize,
175
179
  maxPageSize,
180
+ pageCacheEntries,
181
+ pageCacheBytes,
176
182
  bundleLimits,
177
183
  maxBundleNestingDepth,
178
184
  compressionAdapter,
@@ -216,7 +222,11 @@ export default class ContentAddressableStore {
216
222
  put: async (options) => (await this.#getBundleService()).put(options),
217
223
  putOrdered: async (options) => (await this.#getBundleService()).putOrdered(options),
218
224
  getMember: async (options) => (await this.#getBundleService()).getMember(options),
225
+ getMemberReference: async (options) => (
226
+ await this.#getBundleService()
227
+ ).getMemberReference(options),
219
228
  iterateMembers: (options) => this.#iterateBundleMembers(options),
229
+ iterateMemberReferences: (options) => this.#iterateBundleMemberReferences(options),
220
230
  openMember: (options) => this.#openBundleMember(options),
221
231
  });
222
232
  this.retention = Object.freeze({
@@ -227,7 +237,7 @@ export default class ContentAddressableStore {
227
237
  });
228
238
  }
229
239
 
230
- /** @type {{ plumbing: *, chunkSize?: number, codec?: *, policy?: *, crypto?: *, observability?: *, merkleThreshold?: number, concurrency?: number, chunking?: *, chunker?: *, maxRestoreBufferSize?: number, maxBlobSize?: number, maxPageSize?: number, bundleLimits?: object, maxBundleNestingDepth?: number, compressionAdapter?: *, applicationRefPrefixes?: string[], clock?: { now(): Date } }} */
240
+ /** @type {{ plumbing: *, chunkSize?: number, codec?: *, policy?: *, crypto?: *, observability?: *, merkleThreshold?: number, concurrency?: number, chunking?: *, chunker?: *, maxRestoreBufferSize?: number, maxBlobSize?: number, maxPageSize?: number, pageCacheEntries?: number, pageCacheBytes?: number, bundleLimits?: object, maxBundleNestingDepth?: number, compressionAdapter?: *, applicationRefPrefixes?: string[], clock?: { now(): Date } }} */
231
241
  #config;
232
242
  /** @type {AssetService|null} */
233
243
  #assetService = null;
@@ -365,6 +375,8 @@ export default class ContentAddressableStore {
365
375
  this.#pageService = new PageService({
366
376
  persistence: this.service.persistence,
367
377
  maxPageSize: cfg.maxPageSize,
378
+ pageCacheEntries: cfg.pageCacheEntries,
379
+ pageCacheBytes: cfg.pageCacheBytes,
368
380
  clock: cfg.clock,
369
381
  });
370
382
  this.#bundleService = new BundleService({
@@ -486,6 +498,12 @@ export default class ContentAddressableStore {
486
498
  yield* bundles.openMember(options);
487
499
  }
488
500
 
501
+ /** @returns {AsyncIterable<object>} */
502
+ async *#iterateBundleMemberReferences(options) {
503
+ const bundles = await this.#getBundleService();
504
+ yield* bundles.iterateMemberReferences(options);
505
+ }
506
+
489
507
  /** @returns {AsyncIterable<object>} */
490
508
  async *#iterateBundleMembers(options) {
491
509
  const bundles = await this.#getBundleService();
@@ -610,6 +628,9 @@ export default class ContentAddressableStore {
610
628
  * @param {import('./src/ports/ChunkingPort.js').default} [options.chunker] - Pre-built ChunkingPort instance.
611
629
  * @param {number} [options.maxRestoreBufferSize=536870912] - Max buffered restore size in bytes.
612
630
  * @param {number} [options.maxBlobSize=10485760] - Safety limit for readBlob metadata in bytes.
631
+ * @param {number} [options.maxPageSize=16777216] - Maximum immutable page size in bytes.
632
+ * @param {number} [options.pageCacheEntries=128] - Maximum immutable page payloads retained in memory.
633
+ * @param {number} [options.pageCacheBytes=8388608] - Maximum immutable page payload bytes retained in memory.
613
634
  * @param {import('./src/ports/CompressionPort.js').default} [options.compressionAdapter] - Compression adapter.
614
635
  * @returns {Promise<ContentAddressableStore>}
615
636
  */
@@ -634,6 +655,9 @@ export default class ContentAddressableStore {
634
655
  * @param {import('./src/ports/ChunkingPort.js').default} [options.chunker] - Pre-built ChunkingPort instance.
635
656
  * @param {number} [options.maxRestoreBufferSize=536870912] - Max buffered restore size in bytes.
636
657
  * @param {number} [options.maxBlobSize=10485760] - Safety limit for readBlob metadata in bytes.
658
+ * @param {number} [options.maxPageSize=16777216] - Maximum immutable page size in bytes.
659
+ * @param {number} [options.pageCacheEntries=128] - Maximum immutable page payloads retained in memory.
660
+ * @param {number} [options.pageCacheBytes=8388608] - Maximum immutable page payload bytes retained in memory.
637
661
  * @param {import('./src/ports/CompressionPort.js').default} [options.compressionAdapter] - Compression adapter.
638
662
  * @returns {ContentAddressableStore}
639
663
  */
@@ -655,6 +679,9 @@ export default class ContentAddressableStore {
655
679
  * @param {import('./src/ports/ChunkingPort.js').default} [options.chunker] - Pre-built ChunkingPort instance.
656
680
  * @param {number} [options.maxRestoreBufferSize=536870912] - Max buffered restore size in bytes.
657
681
  * @param {number} [options.maxBlobSize=10485760] - Safety limit for readBlob metadata in bytes.
682
+ * @param {number} [options.maxPageSize=16777216] - Maximum immutable page size in bytes.
683
+ * @param {number} [options.pageCacheEntries=128] - Maximum immutable page payloads retained in memory.
684
+ * @param {number} [options.pageCacheBytes=8388608] - Maximum immutable page payload bytes retained in memory.
658
685
  * @param {import('./src/ports/CompressionPort.js').default} [options.compressionAdapter] - Compression adapter.
659
686
  * @returns {ContentAddressableStore}
660
687
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "6.4.0",
3
+ "version": "6.5.1",
4
4
  "description": "Content-addressed storage backed by Git's object database, with optional encryption and pluggable codecs",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -36,6 +36,8 @@
36
36
  "docs/releases/v6.2.0.md",
37
37
  "docs/releases/v6.3.0.md",
38
38
  "docs/releases/v6.4.0.md",
39
+ "docs/releases/v6.5.0.md",
40
+ "docs/releases/v6.5.1.md",
39
41
  "docs/THREAT_MODEL.md",
40
42
  "docs/VAULT_INTERNALS.md",
41
43
  "docs/WALKTHROUGH.md",
@@ -7,12 +7,15 @@ import BundleHandle from '../value-objects/BundleHandle.js';
7
7
  import BundleLimits from '../value-objects/BundleLimits.js';
8
8
  import normalizeBundlePath from '../value-objects/BundlePath.js';
9
9
  import StagedBundle from '../value-objects/StagedBundle.js';
10
+ import BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
10
11
  import BundleDescriptorCodec, { BUNDLE_INDEX_ENTRY } from './BundleDescriptorCodec.js';
11
12
  import BundleFanoutBuilder from './BundleFanoutBuilder.js';
12
13
  import StagingEvidence from './StagingEvidence.js';
13
14
 
14
15
  const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
15
16
  const DEFAULT_MAX_NESTING_DEPTH = 32;
17
+ const DESCRIPTOR_CACHE_ENTRIES = 1_024;
18
+ const DESCRIPTOR_CACHE_BYTES = 16 * 1024 * 1024;
16
19
 
17
20
  /**
18
21
  * Builds and traverses deterministic, targeted structured bundle trees.
@@ -20,6 +23,10 @@ const DEFAULT_MAX_NESTING_DEPTH = 32;
20
23
  export default class BundleService {
21
24
  #clock;
22
25
  #codec;
26
+ #descriptorBlobs = new BoundedPromiseCache(DESCRIPTOR_CACHE_ENTRIES, {
27
+ maxWeight: DESCRIPTOR_CACHE_BYTES,
28
+ weightOf: (value) => value.byteLength,
29
+ });
23
30
  #limits;
24
31
  #maxNestingDepth;
25
32
  #openHandle;
@@ -104,14 +111,30 @@ export default class BundleService {
104
111
  return member === null ? null : await this.#resolveMemberReference(member, BundleHandle.from(value));
105
112
  }
106
113
 
107
- /** @internal Returns one descriptor after validating only its direct Git edge. */
114
+ /** Returns one descriptor after validating the bundle structure and direct Git edge. */
108
115
  async getMemberReference({ handle: value, path: rawPath }) {
109
116
  const handle = BundleHandle.from(value);
110
117
  const path = normalizeBundlePath(rawPath, this.#limits.maxMemberPathBytes);
111
118
  const root = await this.#readRoot(handle);
112
119
  let nodeOid = root.index.oid;
120
+ let expectedSummary = null;
121
+ let parentTreeOid = handle.oid;
122
+ let descriptorBytes = root.descriptorBytes;
113
123
  while (true) {
114
124
  const node = await this.#readNode(nodeOid, root.descriptor.limits);
125
+ descriptorBytes += node.descriptorBytes;
126
+ if (descriptorBytes > root.descriptor.limits.maxDescriptorBytes) {
127
+ throw corrupt('Bundle descriptors exceed their persisted byte limit', {
128
+ descriptorBytes,
129
+ maxDescriptorBytes: root.descriptor.limits.maxDescriptorBytes,
130
+ });
131
+ }
132
+ const actualSummary = summaryOf(node.descriptor, nodeOid);
133
+ if (expectedSummary === null) {
134
+ assertSummary(root.descriptor, actualSummary);
135
+ } else {
136
+ assertChildSummary(expectedSummary, actualSummary, parentTreeOid);
137
+ }
115
138
  if (node.descriptor.kind === 'leaf') {
116
139
  return await this.#referenceFromLeaf({
117
140
  bundleHandle: handle,
@@ -125,6 +148,8 @@ export default class BundleService {
125
148
  return null;
126
149
  }
127
150
  const edge = await this.#requiredEdge(nodeOid, child.slot, 'tree');
151
+ expectedSummary = child;
152
+ parentTreeOid = nodeOid;
128
153
  nodeOid = edge.oid;
129
154
  }
130
155
  }
@@ -206,7 +231,7 @@ export default class BundleService {
206
231
  yield* this.#iterateMemberReferences(value, { validateTargets: true });
207
232
  }
208
233
 
209
- /** @internal Streams descriptors after validating only their direct Git edges. */
234
+ /** Streams descriptors after validating bundle structure and direct Git edges. */
210
235
  async *iterateMemberReferences({ handle: value }) {
211
236
  yield* this.#iterateMemberReferences(value, { validateTargets: false });
212
237
  }
@@ -587,7 +612,11 @@ export default class BundleService {
587
612
 
588
613
  async #readDescriptorBlob(oid, meta, maxBytes) {
589
614
  try {
590
- return await this.#persistence.readBlob(oid, maxBytes);
615
+ const bytes = await this.#descriptorBlobs.getOrCreate(
616
+ `${oid}\0${maxBytes}`,
617
+ () => this.#persistence.readBlob(oid, maxBytes),
618
+ );
619
+ return Uint8Array.from(bytes);
591
620
  } catch (error) {
592
621
  throw corrupt('Bundle descriptor blob is missing or unreadable', { ...meta, oid, originalError: error });
593
622
  }
@@ -4,8 +4,11 @@ import { ErrorCodes } from '../errors/index.js';
4
4
  import { assertHandleObjectType, mapHandleTargetError } from '../helpers/handleTarget.js';
5
5
  import PageHandle from '../value-objects/PageHandle.js';
6
6
  import StagedPage from '../value-objects/StagedPage.js';
7
+ import BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
7
8
 
8
9
  export const DEFAULT_MAX_PAGE_SIZE = 16 * 1024 * 1024;
10
+ const DEFAULT_PAGE_CACHE_ENTRIES = 128;
11
+ const DEFAULT_PAGE_CACHE_BYTES = 8 * 1024 * 1024;
9
12
  const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
10
13
 
11
14
  /**
@@ -14,19 +17,34 @@ const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
14
17
  export default class PageService {
15
18
  #clock;
16
19
  #maxPageSize;
20
+ #payloads;
17
21
  #persistence;
18
22
 
19
23
  /**
20
24
  * @param {object} options
21
25
  * @param {import('../../ports/GitPersistencePort.js').default} options.persistence
22
26
  * @param {number} [options.maxPageSize]
27
+ * @param {number} [options.pageCacheEntries]
28
+ * @param {number} [options.pageCacheBytes]
23
29
  * @param {{ now(): Date }} [options.clock]
24
30
  */
25
- constructor({ persistence, maxPageSize = DEFAULT_MAX_PAGE_SIZE, clock = DEFAULT_CLOCK }) {
31
+ constructor({
32
+ persistence,
33
+ maxPageSize = DEFAULT_MAX_PAGE_SIZE,
34
+ pageCacheEntries = DEFAULT_PAGE_CACHE_ENTRIES,
35
+ pageCacheBytes = DEFAULT_PAGE_CACHE_BYTES,
36
+ clock = DEFAULT_CLOCK,
37
+ }) {
26
38
  PageService.#assertDependencies(persistence, clock);
27
39
  PageService.#assertLimit(maxPageSize, 'Configured max page size');
40
+ PageService.#assertPositiveLimit(pageCacheEntries, 'Page cache entries');
41
+ PageService.#assertLimit(pageCacheBytes, 'Page cache bytes');
28
42
  this.#persistence = persistence;
29
43
  this.#maxPageSize = maxPageSize;
44
+ this.#payloads = new BoundedPromiseCache(pageCacheEntries, {
45
+ maxWeight: pageCacheBytes,
46
+ weightOf: (value) => value.byteLength,
47
+ });
30
48
  this.#clock = clock;
31
49
  }
32
50
 
@@ -64,7 +82,24 @@ export default class PageService {
64
82
  * @returns {Promise<Uint8Array>}
65
83
  */
66
84
  async get({ handle, maxBytes }) {
67
- return await PageService.#collect(this.open({ handle }), this.#effectiveLimit(maxBytes));
85
+ const limit = this.#effectiveLimit(maxBytes);
86
+ const pageHandle = PageHandle.from(handle);
87
+ let payload = this.#payloads.get(pageHandle.oid);
88
+ if (payload === undefined) {
89
+ const root = await this.resolveRoot(pageHandle);
90
+ if (root.size > limit) {
91
+ throw PageService.#tooLarge(root.size, limit);
92
+ }
93
+ payload = this.#payloads.getOrCreate(
94
+ root.oid,
95
+ async () => await this.#readRoot(root),
96
+ );
97
+ }
98
+ const bytes = await payload;
99
+ if (bytes.byteLength > limit) {
100
+ throw PageService.#tooLarge(bytes.byteLength, limit);
101
+ }
102
+ return new Uint8Array(bytes);
68
103
  }
69
104
 
70
105
  /**
@@ -106,6 +141,17 @@ export default class PageService {
106
141
  return value;
107
142
  }
108
143
 
144
+ async #readRoot(root) {
145
+ try {
146
+ return await PageService.#collect(
147
+ await this.#persistence.readBlobStream(root.oid),
148
+ this.#maxPageSize,
149
+ );
150
+ } catch (error) {
151
+ throw mapHandleTargetError(error, root.handle);
152
+ }
153
+ }
154
+
109
155
  #observedAt() {
110
156
  const now = this.#clock.now();
111
157
  if (!(now instanceof Date) || Number.isNaN(now.getTime())) {
@@ -163,6 +209,14 @@ export default class PageService {
163
209
  }
164
210
  }
165
211
 
212
+ static #assertPositiveLimit(value, label) {
213
+ if (!Number.isSafeInteger(value) || value < 1) {
214
+ throw createCasError(`${label} must be a positive safe integer`, ErrorCodes.INVALID_OPTIONS, {
215
+ value,
216
+ });
217
+ }
218
+ }
219
+
166
220
  static #assertDependencies(persistence, clock) {
167
221
  const methods = ['writeBlob', 'readBlobStream', 'readObjectType', 'readObjectSize'];
168
222
  if (!persistence || methods.some((method) => typeof persistence[method] !== 'function')) {
@@ -1,6 +1,7 @@
1
1
  import CasError from '../errors/CasError.js';
2
2
  import { ErrorCodes } from '../errors/index.js';
3
3
  import { errorDetailsText, isGitMissingRefError } from '../helpers/gitRefErrors.js';
4
+ import Oid from '../value-objects/Oid.js';
4
5
  import RootSetRef from '../value-objects/RootSetRef.js';
5
6
  import RootSetMetadataCodec, { ROOT_SET_METADATA_ENTRY } from './RootSetMetadataCodec.js';
6
7
  import RootSetTreeCodec from './RootSetTreeCodec.js';
@@ -11,16 +12,14 @@ const UPDATE_REF_CONFLICT_MARKERS = Object.freeze({
11
12
  referenceAlreadyExists: 'reference already exists',
12
13
  });
13
14
  const GIT_REPOSITORY_LOCKED = 'GIT_REPOSITORY_LOCKED';
15
+ const GIT_FATAL_EXIT_CODE = 128;
14
16
 
15
- function classifyStructuredUpdateRefConflict(err, {
17
+ function hasExactUpdateRefArgs(err, {
16
18
  rootSetRef,
17
19
  newCommit,
18
20
  expectedHeadOid,
19
21
  }) {
20
22
  const details = err?.details && typeof err.details === 'object' ? err.details : {};
21
- if (details.code !== GIT_REPOSITORY_LOCKED) {
22
- return null;
23
- }
24
23
  if (!Array.isArray(details.args)) {
25
24
  return false;
26
25
  }
@@ -35,6 +34,48 @@ function classifyStructuredUpdateRefConflict(err, {
35
34
  expectedArgs.every((arg, index) => details.args[index] === arg);
36
35
  }
37
36
 
37
+ function classifyStructuredUpdateRefConflict(err, {
38
+ rootSetRef,
39
+ newCommit,
40
+ expectedHeadOid,
41
+ }) {
42
+ const details = err?.details && typeof err.details === 'object' ? err.details : {};
43
+ if (details.code !== GIT_REPOSITORY_LOCKED) {
44
+ return null;
45
+ }
46
+ return hasExactUpdateRefArgs(err, { rootSetRef, newCommit, expectedHeadOid });
47
+ }
48
+
49
+ function isObservedUpdateRefConflict(err, {
50
+ rootSetRef,
51
+ newCommit,
52
+ expectedHeadOid,
53
+ actualHeadOid,
54
+ }) {
55
+ const details = err?.details && typeof err.details === 'object' ? err.details : {};
56
+ if (!Oid.isValid(actualHeadOid)) {
57
+ return false;
58
+ }
59
+ const canonicalActualHeadOid = Oid.from(actualHeadOid).toString();
60
+ const canonicalExpectedHeadOid = Oid.isValid(expectedHeadOid)
61
+ ? Oid.from(expectedHeadOid).toString()
62
+ : expectedHeadOid;
63
+ return details.code === GIT_FATAL_EXIT_CODE &&
64
+ canonicalActualHeadOid !== canonicalExpectedHeadOid &&
65
+ hasExactUpdateRefArgs(err, { rootSetRef, newCommit, expectedHeadOid });
66
+ }
67
+
68
+ function hasTextualUpdateRefConflict(err, rootSetRef) {
69
+ const normalized = errorDetailsText(err).toLowerCase();
70
+ if (!normalized.includes(rootSetRef.toLowerCase())) {
71
+ return false;
72
+ }
73
+ return normalized.includes(UPDATE_REF_CONFLICT_MARKERS.cannotLockRef) && (
74
+ normalized.includes(UPDATE_REF_CONFLICT_MARKERS.butExpected) ||
75
+ normalized.includes(UPDATE_REF_CONFLICT_MARKERS.referenceAlreadyExists)
76
+ );
77
+ }
78
+
38
79
  /**
39
80
  * Stateless persistence boundary for one root-set ref and snapshot format.
40
81
  */
@@ -238,7 +279,11 @@ export default class RootSetPersistence {
238
279
  });
239
280
  } catch (err) {
240
281
  const meta = await this.#updateFailureMeta(err, commitOid, expectedHeadOid);
241
- if (this.#isConflict(err, commitOid, expectedHeadOid)) {
282
+ if (this.#isConflict(err, {
283
+ newCommit: commitOid,
284
+ expectedHeadOid,
285
+ actualHeadOid: meta.actualHeadOid,
286
+ })) {
242
287
  throw new CasError(
243
288
  'Concurrent root-set update detected',
244
289
  ErrorCodes.ROOT_SET_CONFLICT,
@@ -272,7 +317,7 @@ export default class RootSetPersistence {
272
317
  };
273
318
  }
274
319
 
275
- #isConflict(err, newCommit, expectedHeadOid) {
320
+ #isConflict(err, { newCommit, expectedHeadOid, actualHeadOid }) {
276
321
  const meta = err?.meta && typeof err.meta === 'object' ? err.meta : {};
277
322
  if (Object.hasOwn(meta, 'expectedOldOid') && Object.hasOwn(meta, 'actualOldOid')) {
278
323
  return true;
@@ -285,14 +330,17 @@ export default class RootSetPersistence {
285
330
  if (structuredConflict !== null) {
286
331
  return structuredConflict;
287
332
  }
288
- const normalized = errorDetailsText(err).toLowerCase();
289
- if (!normalized.includes(this.rootSetRef.toLowerCase())) {
290
- return false;
333
+ // A failed exact CAS command plus an independently observed head advance
334
+ // remains sufficient conflict evidence when Git emits no diagnostic text.
335
+ if (isObservedUpdateRefConflict(err, {
336
+ rootSetRef: this.rootSetRef,
337
+ newCommit,
338
+ expectedHeadOid,
339
+ actualHeadOid,
340
+ })) {
341
+ return true;
291
342
  }
292
- return normalized.includes(UPDATE_REF_CONFLICT_MARKERS.cannotLockRef) && (
293
- normalized.includes(UPDATE_REF_CONFLICT_MARKERS.butExpected) ||
294
- normalized.includes(UPDATE_REF_CONFLICT_MARKERS.referenceAlreadyExists)
295
- );
343
+ return hasTextualUpdateRefConflict(err, this.rootSetRef);
296
344
  }
297
345
 
298
346
  #isMissingRefError(err) {
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Fixed-residency LRU for in-flight and completed immutable reads.
3
+ * Rejected promises remove themselves so transient failures remain retryable.
4
+ */
5
+ export default class BoundedPromiseCache {
6
+ /** @type {Map<string, { promise: Promise<unknown>, weight: number }>} */
7
+ #completed = new Map();
8
+ /** @type {Map<string, Promise<unknown>>} */
9
+ #inFlight = new Map();
10
+ #maxEntries;
11
+ #maxWeight;
12
+ #totalWeight = 0;
13
+ #weightOf;
14
+
15
+ /**
16
+ * @param {number} maxEntries
17
+ * @param {object} [options]
18
+ * @param {number} [options.maxWeight=Infinity]
19
+ * @param {(value: unknown) => number} [options.weightOf]
20
+ */
21
+ constructor(maxEntries, { maxWeight = Number.POSITIVE_INFINITY, weightOf = () => 0 } = {}) {
22
+ if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) {
23
+ throw new TypeError('maxEntries must be a positive safe integer');
24
+ }
25
+ if (
26
+ maxWeight !== Number.POSITIVE_INFINITY &&
27
+ (!Number.isSafeInteger(maxWeight) || maxWeight < 0)
28
+ ) {
29
+ throw new TypeError('maxWeight must be a non-negative safe integer or Infinity');
30
+ }
31
+ if (typeof weightOf !== 'function') {
32
+ throw new TypeError('weightOf must be a function');
33
+ }
34
+ this.#maxEntries = maxEntries;
35
+ this.#maxWeight = maxWeight;
36
+ this.#weightOf = weightOf;
37
+ }
38
+
39
+ /**
40
+ * @template T
41
+ * @param {string} key
42
+ * @returns {Promise<T>|undefined}
43
+ */
44
+ get(key) {
45
+ const cached = this.#completed.get(key);
46
+ if (cached !== undefined) {
47
+ this.#completed.delete(key);
48
+ this.#completed.set(key, cached);
49
+ return cached.promise;
50
+ }
51
+ return this.#inFlight.get(key);
52
+ }
53
+
54
+ /**
55
+ * @template T
56
+ * @param {string} key
57
+ * @param {() => Promise<T>|T} factory
58
+ * @returns {Promise<T>}
59
+ */
60
+ getOrCreate(key, factory) {
61
+ const present = this.get(key);
62
+ if (present !== undefined) {
63
+ return present;
64
+ }
65
+
66
+ const source = Promise.resolve().then(factory);
67
+ const tracked = source.then(
68
+ (value) => {
69
+ this.#removeInFlight(key, tracked);
70
+ const weight = this.#resolvedWeight(value);
71
+ if (weight <= this.#maxWeight) {
72
+ const entry = { promise: Promise.resolve(value), weight };
73
+ this.#completed.set(key, entry);
74
+ this.#totalWeight += weight;
75
+ this.#evictCompleted();
76
+ }
77
+ return value;
78
+ },
79
+ (error) => {
80
+ this.#removeInFlight(key, tracked);
81
+ throw error;
82
+ },
83
+ );
84
+ this.#inFlight.set(key, tracked);
85
+ return tracked;
86
+ }
87
+
88
+ #resolvedWeight(value) {
89
+ const weight = this.#weightOf(value);
90
+ if (!Number.isSafeInteger(weight) || weight < 0) {
91
+ throw new TypeError('weightOf must return a non-negative safe integer');
92
+ }
93
+ return weight;
94
+ }
95
+
96
+ #evictCompleted() {
97
+ while (this.#completed.size > this.#maxEntries || this.#totalWeight > this.#maxWeight) {
98
+ const oldestKey = this.#completed.keys().next().value;
99
+ const oldest = this.#completed.get(oldestKey);
100
+ this.#removeCompleted(oldestKey, oldest);
101
+ }
102
+ }
103
+
104
+ #removeCompleted(key, entry) {
105
+ if (entry === undefined || !this.#completed.delete(key)) {
106
+ return;
107
+ }
108
+ this.#totalWeight -= entry.weight;
109
+ }
110
+
111
+ #removeInFlight(key, promise) {
112
+ if (this.#inFlight.get(key) === promise) {
113
+ this.#inFlight.delete(key);
114
+ }
115
+ }
116
+ }
@@ -4,6 +4,7 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import GitPersistencePort from '../../ports/GitPersistencePort.js';
6
6
  import { CasError, createCasError, ErrorCodes } from '../../domain/errors/index.js';
7
+ import BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
7
8
 
8
9
  /**
9
10
  * Default resilience policy: 30 s timeout (no retry).
@@ -15,8 +16,10 @@ import { CasError, createCasError, ErrorCodes } from '../../domain/errors/index.
15
16
  */
16
17
  const DEFAULT_POLICY = Policy.timeout(30_000);
17
18
  export const DEFAULT_MAX_BLOB_SIZE = 10 * 1024 * 1024;
19
+ const DEFAULT_METADATA_CACHE_ENTRIES = 2_048;
18
20
  const MIN_READ_BLOB_LIMIT = 1;
19
21
  const MIN_MAX_BLOB_SIZE = 1024;
22
+ const MIN_METADATA_CACHE_ENTRIES = 1;
20
23
  const MAX_BLOB_SIZE_LIMIT = Number.MAX_SAFE_INTEGER;
21
24
  const OBJECT_INFO_ARGUMENT = '--batch-check=%(objectname) %(objecttype) %(objectsize)';
22
25
  const GIT_OBJECT_TYPES = new Set(['blob', 'tree', 'commit', 'tag']);
@@ -25,19 +28,25 @@ const GIT_OBJECT_TYPES = new Set(['blob', 'tree', 'commit', 'tag']);
25
28
  * {@link GitPersistencePort} implementation backed by `@git-stunts/plumbing`.
26
29
  *
27
30
  * All Git I/O is wrapped with a configurable resilience {@link Policy}
28
- * (30 s timeout by default).
31
+ * (30 s timeout by default). Successful metadata reads assume referenced roots
32
+ * remain retained while this adapter is in use; destructive external pruning
33
+ * must not race active operations.
29
34
  */
30
35
  export default class GitPersistenceAdapter extends GitPersistencePort {
31
36
  #maxBlobSize = DEFAULT_MAX_BLOB_SIZE;
37
+ #metadataCache;
32
38
  /**
33
39
  * @param {Object} options
34
40
  * @param {import('@git-stunts/plumbing').default} options.plumbing - GitPlumbing instance.
35
41
  * @param {import('@git-stunts/alfred').Policy} [options.policy] - Resilience policy (defaults to 30 s timeout, no retry).
42
+ * @param {number} [options.metadataCacheEntries=2048] - Maximum immutable metadata entries retained by this adapter.
36
43
  */
37
- constructor({ plumbing, policy }) {
44
+ constructor({ plumbing, policy, metadataCacheEntries = DEFAULT_METADATA_CACHE_ENTRIES }) {
38
45
  super();
46
+ GitPersistenceAdapter.#assertMetadataCacheEntries(metadataCacheEntries);
39
47
  this.plumbing = plumbing;
40
48
  this.policy = policy ?? DEFAULT_POLICY;
49
+ this.#metadataCache = new BoundedPromiseCache(metadataCacheEntries);
41
50
  }
42
51
 
43
52
  /**
@@ -145,12 +154,15 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
145
154
  * @returns {Promise<{ mode: string, type: string, oid: string, name: string }|null>}
146
155
  */
147
156
  async readTreeEntry(treeOid, treePath) {
148
- return this.policy.execute(async () => {
157
+ const key = `tree\0${treeOid}\0${treePath}`;
158
+ const entry = await this.#metadataCache.getOrCreate(key, () => this.policy.execute(async () => {
149
159
  const output = await this.plumbing.execute({
150
160
  args: ['ls-tree', '-z', treeOid, '--', treePath],
151
161
  });
152
- return GitPersistenceAdapter.#parseTreeOutput(output)[0] || null;
153
- });
162
+ const found = GitPersistenceAdapter.#parseTreeOutput(output)[0] || null;
163
+ return found === null ? null : Object.freeze(found);
164
+ }));
165
+ return entry === null ? null : { ...entry };
154
166
  }
155
167
 
156
168
  /**
@@ -209,32 +221,51 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
209
221
  * @returns {Promise<{ oid: string, type: string, size: number }>} Object metadata.
210
222
  */
211
223
  async #readObjectInfo(oid) {
212
- const rawOutput = await this.policy.execute(() => this.plumbing.execute({
213
- args: ['cat-file', OBJECT_INFO_ARGUMENT],
214
- input: `${oid}\n`,
215
- }));
216
- const output = typeof rawOutput === 'string' ? rawOutput.trim() : '';
217
- if (output === `${oid} missing`) {
218
- throw new CasError(`Git object not found: ${oid}`, ErrorCodes.GIT_OBJECT_NOT_FOUND, {
219
- oid,
220
- });
221
- }
224
+ return this.#metadataCache.getOrCreate(`object\0${oid}`, async () => {
225
+ const rawOutput = await this.policy.execute(() => this.plumbing.execute({
226
+ args: ['cat-file', OBJECT_INFO_ARGUMENT],
227
+ input: `${oid}\n`,
228
+ }));
229
+ const output = typeof rawOutput === 'string' ? rawOutput.trim() : '';
230
+ if (output === `${oid} missing`) {
231
+ throw new CasError(`Git object not found: ${oid}`, ErrorCodes.GIT_OBJECT_NOT_FOUND, {
232
+ oid,
233
+ });
234
+ }
222
235
 
223
- const fields = output.split(' ');
224
- const size = Number(fields[2]);
236
+ const fields = output.split(' ');
237
+ const size = Number(fields[2]);
238
+ if (
239
+ fields.length !== 3 ||
240
+ fields[0] !== oid ||
241
+ !GIT_OBJECT_TYPES.has(fields[1]) ||
242
+ !Number.isSafeInteger(size) ||
243
+ size < 0
244
+ ) {
245
+ throw new CasError(`Git object has invalid metadata: ${oid}`, ErrorCodes.GIT_ERROR, {
246
+ oid,
247
+ output: rawOutput,
248
+ });
249
+ }
250
+ return Object.freeze({ oid: fields[0], type: fields[1], size });
251
+ });
252
+ }
253
+
254
+ /**
255
+ * @param {number} metadataCacheEntries
256
+ */
257
+ static #assertMetadataCacheEntries(metadataCacheEntries) {
225
258
  if (
226
- fields.length !== 3 ||
227
- fields[0] !== oid ||
228
- !GIT_OBJECT_TYPES.has(fields[1]) ||
229
- !Number.isSafeInteger(size) ||
230
- size < 0
259
+ Number.isSafeInteger(metadataCacheEntries) &&
260
+ metadataCacheEntries >= MIN_METADATA_CACHE_ENTRIES
231
261
  ) {
232
- throw new CasError(`Git object has invalid metadata: ${oid}`, ErrorCodes.GIT_ERROR, {
233
- oid,
234
- output: rawOutput,
235
- });
262
+ return;
236
263
  }
237
- return Object.freeze({ oid: fields[0], type: fields[1], size });
264
+ throw createCasError(
265
+ 'Git metadata cache entries must be a positive safe integer',
266
+ ErrorCodes.INVALID_OPTIONS,
267
+ { option: 'metadataCacheEntries', metadataCacheEntries },
268
+ );
238
269
  }
239
270
 
240
271
  /**
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '6.4.0';
1
+ export const PACKAGE_VERSION = '6.5.1';