@git-stunts/git-cas 6.1.0 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/ARCHITECTURE.md +108 -3
  2. package/CHANGELOG.md +80 -2
  3. package/GUIDE.md +114 -13
  4. package/README.md +51 -4
  5. package/UPGRADING.md +43 -0
  6. package/build-info.json +2 -2
  7. package/docs/API.md +751 -16
  8. package/docs/releases/v6.2.0.md +131 -0
  9. package/index.d.ts +879 -2
  10. package/index.js +326 -1
  11. package/package.json +3 -2
  12. package/src/domain/errors/Codes.js +35 -0
  13. package/src/domain/helpers/assertCanonicalTimestamp.js +15 -0
  14. package/src/domain/helpers/handleTarget.js +48 -0
  15. package/src/domain/helpers/isCanonicalCollectionKey.js +35 -0
  16. package/src/domain/services/AssetService.js +213 -0
  17. package/src/domain/services/BundleDescriptorCodec.js +286 -0
  18. package/src/domain/services/BundleFanoutBuilder.js +247 -0
  19. package/src/domain/services/BundleService.js +848 -0
  20. package/src/domain/services/CacheCandidateHeap.js +71 -0
  21. package/src/domain/services/CacheIndex.js +362 -0
  22. package/src/domain/services/CacheMetadataCodec.js +164 -0
  23. package/src/domain/services/CachePolicyEnforcer.js +144 -0
  24. package/src/domain/services/CacheSet.js +703 -0
  25. package/src/domain/services/CacheSetRegistry.js +88 -0
  26. package/src/domain/services/CasService.d.ts +2 -1
  27. package/src/domain/services/ExpiringSet.js +496 -0
  28. package/src/domain/services/ExpiringSetIndex.js +254 -0
  29. package/src/domain/services/ExpiringSetMetadataCodec.js +160 -0
  30. package/src/domain/services/ExpiringSetRegistry.js +101 -0
  31. package/src/domain/services/PageService.js +175 -0
  32. package/src/domain/services/PublicationService.js +315 -0
  33. package/src/domain/services/RepositoryDoctor.js +649 -0
  34. package/src/domain/services/RetentionService.js +120 -0
  35. package/src/domain/services/RootSet.js +10 -6
  36. package/src/domain/services/RootSetMetadataCodec.js +8 -2
  37. package/src/domain/services/RootSetPersistence.js +3 -2
  38. package/src/domain/services/StagingEvidence.js +39 -0
  39. package/src/domain/value-objects/ApplicationHandle.js +40 -0
  40. package/src/domain/value-objects/AssetHandle.js +163 -0
  41. package/src/domain/value-objects/BundleHandle.js +32 -0
  42. package/src/domain/value-objects/BundleLimits.js +80 -0
  43. package/src/domain/value-objects/BundlePath.js +78 -0
  44. package/src/domain/value-objects/CacheHit.js +93 -0
  45. package/src/domain/value-objects/CacheKey.js +32 -0
  46. package/src/domain/value-objects/CachePolicy.js +59 -0
  47. package/src/domain/value-objects/CacheSetRef.js +40 -0
  48. package/src/domain/value-objects/CollectionNamespace.js +54 -0
  49. package/src/domain/value-objects/ExpiringMarker.js +81 -0
  50. package/src/domain/value-objects/ExpiringSetKey.js +28 -0
  51. package/src/domain/value-objects/ExpiringSetRef.js +42 -0
  52. package/src/domain/value-objects/OpaqueHandle.js +171 -0
  53. package/src/domain/value-objects/PageHandle.js +34 -0
  54. package/src/domain/value-objects/RetentionWitness.js +101 -0
  55. package/src/domain/value-objects/StagedAsset.js +63 -0
  56. package/src/domain/value-objects/StagedBundle.js +66 -0
  57. package/src/domain/value-objects/StagedPage.js +47 -0
  58. package/src/infrastructure/adapters/GitPersistenceAdapter.js +48 -20
  59. package/src/infrastructure/adapters/GitRefAdapter.js +6 -5
  60. package/src/infrastructure/adapters/GitRepositoryInspectionAdapter.js +164 -0
  61. package/src/package-version.js +1 -1
  62. package/src/ports/GitPersistencePort.js +11 -1
  63. package/src/ports/GitRefPort.js +1 -0
  64. package/src/ports/RepositoryInspectionPort.js +33 -0
package/docs/API.md CHANGED
@@ -15,14 +15,18 @@ should treat restored data, chunker output, codec output, and keys as
15
15
  ## Table of Contents
16
16
 
17
17
  1. [ContentAddressableStore](#contentaddressablestore)
18
- 2. [Root Sets](#root-sets)
19
- 3. [Vault](#vault)
20
- 4. [CasService](#casservice)
21
- 5. [Events](#events)
22
- 6. [Value Objects](#value-objects)
23
- 7. [Ports](#ports)
24
- 8. [Codecs](#codecs)
25
- 9. [Error Codes](#error-codes)
18
+ 2. [Application Storage](#application-storage)
19
+ 3. [Root Sets](#root-sets)
20
+ 4. [Cache Sets](#cache-sets)
21
+ 5. [Expiring Sets](#expiring-sets)
22
+ 6. [Repository Diagnostics](#repository-diagnostics)
23
+ 7. [Vault](#vault)
24
+ 8. [CasService](#casservice)
25
+ 9. [Events](#events)
26
+ 10. [Value Objects](#value-objects)
27
+ 11. [Ports](#ports)
28
+ 12. [Codecs](#codecs)
29
+ 13. [Error Codes](#error-codes)
26
30
 
27
31
  ## ContentAddressableStore
28
32
 
@@ -74,7 +78,12 @@ new ContentAddressableStore(options);
74
78
  - `options.chunker` (optional): Pre-built ChunkingPort instance (advanced; overrides `chunking`)
75
79
  - `options.maxRestoreBufferSize` (optional): Max bytes for buffered encrypted/compressed restore (default: 536870912 / 512 MiB)
76
80
  - `options.maxBlobSize` (optional): Max bytes for metadata blob reads (default: 10485760 / 10 MiB)
81
+ - `options.maxPageSize` (optional): Maximum immutable page bytes (default: 16777216 / 16 MiB)
82
+ - `options.bundleLimits` (optional): Repository maximums for bundle members, path bytes, descriptor bytes, fanout entries, and fanout depth
83
+ - `options.maxBundleNestingDepth` (optional): Maximum nested bundle depth (default: 32)
77
84
  - `options.compressionAdapter` (optional): CompressionPort implementation (default: NodeCompressionAdapter)
85
+ - `options.applicationRefPrefixes` (optional): Explicit application-owned ref prefixes allowed for generic publication; publication is disabled when omitted, and Git/CAS-managed namespaces are always reserved
86
+ - `options.clock` (optional): `{ now(): Date }` clock used for deterministic staged results and retention witnesses
78
87
 
79
88
  **Example:**
80
89
 
@@ -905,6 +914,331 @@ Returns the configured chunk size in bytes.
905
914
  console.log(cas.chunkSize); // 262144
906
915
  ```
907
916
 
917
+ ## Application Storage
918
+
919
+ The high-level application boundary exposes immutable content handles and
920
+ explicit lifecycle operations. It composes the lower-level store, manifest,
921
+ tree, RootSet, commit, and ref operations without requiring callers to manage
922
+ payload OIDs.
923
+
924
+ ### `assets.put()`
925
+
926
+ ```javascript
927
+ const staged = await cas.assets.put({
928
+ source,
929
+ slug,
930
+ filename,
931
+ encryptionKey,
932
+ passphrase,
933
+ encryption,
934
+ kdfOptions,
935
+ compression,
936
+ recipients,
937
+ merkleThreshold,
938
+ chunking,
939
+ });
940
+ ```
941
+
942
+ Streams an `AsyncIterable<Uint8Array>` through the existing CAS pipeline,
943
+ creates its manifest tree, and returns an immutable `StagedAsset`. Payload
944
+ bytes are consumed through the configured chunker and are not returned in the
945
+ result. Manifest metadata remains subject to the existing manifest and Merkle
946
+ limits documented in the streaming matrix.
947
+
948
+ `filename` defaults to `slug`. All other storage options have the same meaning
949
+ as `store()`.
950
+
951
+ **Returns:** `Promise<StagedAsset>`
952
+
953
+ ```javascript
954
+ {
955
+ version: 1,
956
+ state: 'staged',
957
+ handle: AssetHandle,
958
+ asset: { slug, filename, size },
959
+ retention: {
960
+ policy: null,
961
+ reachability: 'unanchored',
962
+ protection: 'not-established',
963
+ },
964
+ observedAt: '2026-07-13T10:00:00.000Z',
965
+ }
966
+ ```
967
+
968
+ `unanchored` means this operation created no reachability root. It is not a
969
+ global assertion that a deduplicated object graph is unreachable through every
970
+ other Git ref. `not-established` likewise means this operation made no
971
+ protection claim. Call `retention.retain()` or `publications.commit()` before
972
+ relying on a new handle beyond Git's unreachable-object grace period.
973
+
974
+ ### `assets.open()`
975
+
976
+ ```javascript
977
+ for await (const chunk of cas.assets.open({
978
+ handle,
979
+ encryptionKey,
980
+ passphrase,
981
+ })) {
982
+ consume(chunk);
983
+ }
984
+ ```
985
+
986
+ Validates the canonical handle, codec, root tree, manifest, and referenced
987
+ chunk graph, then returns restored bytes as an `AsyncIterable<Uint8Array>`.
988
+ Encrypted restore behavior follows the existing streaming matrix; explicit
989
+ `whole` encryption may use its documented bounded compatibility buffer.
990
+
991
+ Missing transferred objects fail with `HANDLE_TARGET_MISSING`. A handle created
992
+ for a different manifest codec fails with `HANDLE_CODEC_MISMATCH`.
993
+
994
+ ### `assets.adopt()`
995
+
996
+ ```javascript
997
+ const staged = await cas.assets.adopt({ treeOid });
998
+ ```
999
+
1000
+ Validates an existing git-cas manifest tree and wraps it in the same staged
1001
+ result returned by `assets.put()`. This is a migration bridge for callers that
1002
+ already persisted raw tree OIDs; new application code should exchange handles.
1003
+
1004
+ ### `pages.put()`, `pages.open()`, and `pages.get()`
1005
+
1006
+ ```javascript
1007
+ const staged = await cas.pages.put({ source, maxBytes });
1008
+
1009
+ for await (const chunk of cas.pages.open({ handle: staged.handle })) {
1010
+ consume(chunk);
1011
+ }
1012
+
1013
+ const bytes = await cas.pages.get({ handle: staged.handle, maxBytes });
1014
+ ```
1015
+
1016
+ A page is one immutable raw Git blob intended for a bounded trie, index, or
1017
+ materialization node. `source` may be a `Uint8Array`, `Iterable<Uint8Array>`, or
1018
+ `AsyncIterable<Uint8Array>`. The facade default `maxPageSize` is 16 MiB; an
1019
+ operation may lower that bound with `maxBytes` but cannot raise it.
1020
+
1021
+ `put()` returns an immutable `StagedPage` and identical bytes deduplicate to the
1022
+ same `PageHandle`. `open()` validates the blob type and size through Git object
1023
+ metadata before streaming it. `get()` additionally collects the page under its
1024
+ effective byte bound. An imported handle above the configured maximum fails
1025
+ with `PAGE_TOO_LARGE` without materializing the blob.
1026
+
1027
+ The canonical page token is:
1028
+
1029
+ ```text
1030
+ git-cas:1:page:blob:raw:<sha1|sha256>:<oid>
1031
+ ```
1032
+
1033
+ ### `bundles.put()` and `bundles.putOrdered()`
1034
+
1035
+ ```javascript
1036
+ const staged = await cas.bundles.put({
1037
+ members: {
1038
+ 'nodes/root': nodePageHandle,
1039
+ 'edges/root': edgePageHandle,
1040
+ 'state/frontier': frontierBytes,
1041
+ },
1042
+ limits: { maxFanoutEntries: 256 },
1043
+ });
1044
+
1045
+ const streamed = await cas.bundles.putOrdered({
1046
+ members: orderedAsyncMemberPairs,
1047
+ });
1048
+ ```
1049
+
1050
+ Members are named application handles, byte sources, or `{ source, maxBytes }`
1051
+ page inputs. Inline bytes are staged as pages. Existing assets, pages, and
1052
+ bundles remain immutable; a bundle tree creates direct Git reachability edges
1053
+ to every member handle. `put()` sorts an in-memory object, `Map`, or pair array.
1054
+ `putOrdered()` consumes an already sorted iterable and rejects duplicate or
1055
+ out-of-order canonical paths, enabling construction with bounded resident
1056
+ state.
1057
+
1058
+ Repository defaults, which an operation may only lower, are:
1059
+
1060
+ | Limit | Default |
1061
+ | --- | ---: |
1062
+ | `maxMembers` | 100,000 |
1063
+ | `maxMemberPathBytes` | 512 bytes |
1064
+ | `maxDescriptorBytes` | 64 MiB |
1065
+ | `maxFanoutEntries` | 1,024 Git entries per node |
1066
+ | `maxFanoutDepth` | 8 levels |
1067
+
1068
+ Paths must be non-empty NFC text, use `/` separators, and cannot contain empty,
1069
+ `.` or `..` segments, backslashes, NULs, or control characters. Construction
1070
+ is deterministic across input chunking and in-memory member order. A staged
1071
+ bundle remains unanchored until retention or publication succeeds.
1072
+
1073
+ The canonical bundle token is:
1074
+
1075
+ ```text
1076
+ git-cas:1:bundle:fanout-tree:<codec>:<sha1|sha256>:<oid>
1077
+ ```
1078
+
1079
+ ### `bundles.getMember()`, `bundles.iterateMembers()`, and `bundles.openMember()`
1080
+
1081
+ ```javascript
1082
+ const member = await cas.bundles.getMember({
1083
+ handle: materializationHandle,
1084
+ path: 'nodes/root',
1085
+ });
1086
+
1087
+ for await (const member of cas.bundles.iterateMembers({
1088
+ handle: materializationHandle,
1089
+ })) {
1090
+ consumeDescriptor(member);
1091
+ }
1092
+
1093
+ for await (const chunk of cas.bundles.openMember({
1094
+ handle: materializationHandle,
1095
+ path: 'nodes/root',
1096
+ })) {
1097
+ consume(chunk);
1098
+ }
1099
+ ```
1100
+
1101
+ `getMember()` returns the selected member descriptor or `null`. `openMember()`
1102
+ streams one selected page or asset and fails with `BUNDLE_MEMBER_NOT_FOUND` for
1103
+ an absent path. A nested bundle is a structured handle rather than a byte
1104
+ stream and fails with `BUNDLE_MEMBER_NOT_STREAMABLE` when opened directly.
1105
+
1106
+ `iterateMembers()` validates each member support graph before yielding its
1107
+ immutable descriptor in canonical path order. Completing the iteration also
1108
+ validates the root and fanout summaries. It does not allocate an array or other
1109
+ cardinality-sized inventory for the member set. Bundle root resolution reports deterministic
1110
+ `logicalBytes`: descriptor bytes plus each distinct immediate member handle's
1111
+ transitive logical bytes. Repeating one handle within a bundle charges it once;
1112
+ using the same handle in two independent cache entries charges each entry.
1113
+
1114
+ `getMember()` and `openMember()` traverse only the bounded fanout path needed
1115
+ for the selected member. `iterateMembers()` is the explicit full-index
1116
+ streaming surface; retention, publication, and bundle-root resolution also
1117
+ validate the complete graph.
1118
+
1119
+ ### Application Handles
1120
+
1121
+ `AssetHandle`, `PageHandle`, and `BundleHandle` are immutable, versioned content
1122
+ locators. The asset token has this shape:
1123
+
1124
+ ```text
1125
+ git-cas:1:asset:manifest-tree:<codec>:<sha1|sha256>:<oid>
1126
+ ```
1127
+
1128
+ ```javascript
1129
+ import { AssetHandle } from '@git-stunts/git-cas';
1130
+
1131
+ const token = staged.handle.toString();
1132
+ const parsed = AssetHandle.parse(token);
1133
+ const data = parsed.toJSON();
1134
+ ```
1135
+
1136
+ The token contains no filesystem or repository location. It works in another
1137
+ clone or mirror only after the referenced Git object graph has been transferred.
1138
+ "Opaque" is an ownership boundary, not encryption: callers may serialize and
1139
+ compare the token, while `git-cas` owns interpretation and object traversal.
1140
+
1141
+ ### `retention.retain()`
1142
+
1143
+ ```javascript
1144
+ const result = await cas.retention.retain({
1145
+ handle,
1146
+ root: {
1147
+ ref: 'refs/cas/rootsets/my-app-cache',
1148
+ name: 'coordinate-184',
1149
+ },
1150
+ policy: 'evictable',
1151
+ });
1152
+ ```
1153
+
1154
+ Validates an asset, page, or bundle handle graph, installs its root in the named
1155
+ current-generation RootSet, and returns:
1156
+
1157
+ ```javascript
1158
+ {
1159
+ changed: true,
1160
+ witness: RetentionWitness,
1161
+ }
1162
+ ```
1163
+
1164
+ The witness records `policy`, observed `reachability`, timestamp, RootSet ref,
1165
+ generation commit, and the exact tree path that retained the handle. The
1166
+ default policy is `pinned`; `evictable` allows higher-level cache policy to
1167
+ release the entry. Neither policy creates a Git pack `.keep` file.
1168
+
1169
+ ### `publications.commit()`
1170
+
1171
+ ```javascript
1172
+ const result = await cas.publications.commit({
1173
+ root: handle,
1174
+ commit: {
1175
+ message: 'Publish application state',
1176
+ parents: previous === null ? [] : [previous],
1177
+ },
1178
+ ref: {
1179
+ name: 'refs/my-app/state',
1180
+ expected: previous,
1181
+ },
1182
+ });
1183
+ ```
1184
+
1185
+ Generic publication is available only below a constructor-configured
1186
+ `applicationRefPrefixes` allowlist. Even a broad allowlist cannot publish below
1187
+ `refs/bisect/*`, `refs/cas/*`, `refs/heads/*`, `refs/notes/*`,
1188
+ `refs/remotes/*`, `refs/replace/*`, `refs/rewritten/*`, `refs/stash`,
1189
+ `refs/tags/*`, or `refs/worktree/*`. The method:
1190
+
1191
+ 1. validates the complete supported handle graph;
1192
+ 2. validates at most 64 ordered parent commit IDs and a commit message of at
1193
+ most 1 MiB;
1194
+ 3. creates a commit whose tree is the validated handle root; blob-backed pages
1195
+ use a deterministic single-entry wrapper tree; and
1196
+ 4. updates the application ref with compare-and-swap semantics.
1197
+
1198
+ `ref.expected` is mandatory. Use `null` to require that the ref not exist.
1199
+ A stale expectation fails with `PUBLICATION_CONFLICT`; error metadata includes
1200
+ `expected`, `observed`, and `attemptedCommitId`. Because Git objects are
1201
+ immutable, a failed ref update can leave the attempted commit unreachable until
1202
+ normal Git pruning; it cannot publish a partial ref state.
1203
+
1204
+ **Returns:**
1205
+
1206
+ ```javascript
1207
+ {
1208
+ operation: 'publication',
1209
+ commitId,
1210
+ ref,
1211
+ root: AssetHandle | PageHandle | BundleHandle,
1212
+ witness: RetentionWitness,
1213
+ }
1214
+ ```
1215
+
1216
+ ### `RetentionWitness`
1217
+
1218
+ A `RetentionWitness` is immutable evidence for one observed retaining
1219
+ generation. It does not promise that a mutable ref still points to that
1220
+ generation later.
1221
+
1222
+ ```javascript
1223
+ {
1224
+ version: 1,
1225
+ handle: AssetHandle | PageHandle | BundleHandle,
1226
+ policy: 'pinned' | 'evictable',
1227
+ reachability: 'anchored' | 'orphaned' | 'volatile',
1228
+ root: {
1229
+ kind: 'root-set' | 'publication' | 'cache-set' | 'expiring-set',
1230
+ namespace: string,
1231
+ ref: string,
1232
+ generation: string,
1233
+ path: string,
1234
+ },
1235
+ observedAt: string,
1236
+ }
1237
+ ```
1238
+
1239
+ `toJSON()` serializes `handle` to its canonical token and copies the root
1240
+ evidence fields.
1241
+
908
1242
  ## Root Sets
909
1243
 
910
1244
  Root sets retain a mutable current set of Git blobs or trees. They are intended
@@ -1016,7 +1350,8 @@ await rootSet.mutate(
1016
1350
  ```
1017
1351
 
1018
1352
  Runs a compare-and-swap read/modify/write operation. The callback receives a
1019
- frozen snapshot and returns the next iterable of entries. Without
1353
+ frozen entry snapshot plus the observed `{ ref, headOid, treeOid }` generation
1354
+ context, and returns the next iterable of entries. Without
1020
1355
  `expectedHeadOid`, conflicts are retried against a fresh snapshot. With an
1021
1356
  expected head, the callback is guarded to that generation and any stale read
1022
1357
  or write conflict is returned to the caller without retrying.
@@ -1037,8 +1372,9 @@ Returns a non-mutating report with:
1037
1372
  - stable issue codes for missing or mismatched targets
1038
1373
 
1039
1374
  Current members are `anchored`. `orphaned` and `volatile` describe objects
1040
- outside the current root set and are reported as zero by a single-set doctor;
1041
- repository-wide classification remains a Git maintenance concern.
1375
+ outside the current root set and are reported as zero by a single-set doctor.
1376
+ Use [`cas.diagnostics.doctor()`](#repository-diagnostics) for repository-wide
1377
+ classification across refs and reflogs.
1042
1378
 
1043
1379
  ### repair
1044
1380
 
@@ -1064,11 +1400,354 @@ shared registry for advanced composition.
1064
1400
 
1065
1401
  Custom persistence implementations that support root sets must implement
1066
1402
  `readObjectType(oid)`, and custom ref adapters must implement
1067
- `resolveParents(commitOid)`. The default Git adapters use `git cat-file -t`
1068
- and `git rev-list --parents` so missing targets, repository read failures, and
1069
- parentful heads remain distinct doctor findings. Existing store, restore, and
1403
+ `resolveParents(commitOid)`. The default Git adapters use structured
1404
+ `git cat-file --batch-check` output and `git rev-list --parents` so missing
1405
+ targets, repository read failures, and parentful heads remain distinct doctor
1406
+ findings without parsing runtime-specific stderr. Existing store, restore, and
1070
1407
  vault paths do not call these methods.
1071
1408
 
1409
+ ## Cache Sets
1410
+
1411
+ Cache sets are the managed application cache surface. A caller supplies cache
1412
+ keys and application handles; git-cas owns the immutable index objects, Git
1413
+ reachability, compare-and-swap replacement, expiry, capacity policy,
1414
+ diagnostics, and repair.
1415
+
1416
+ ```javascript
1417
+ const cache = await cas.caches.open({
1418
+ namespace: 'git-warp/materializations',
1419
+ policy: {
1420
+ maxEntries: 128,
1421
+ maxBytes: 2 * 1024 * 1024 * 1024,
1422
+ accessResolutionMs: 60 * 60 * 1000,
1423
+ },
1424
+ });
1425
+ ```
1426
+
1427
+ The namespace maps to
1428
+ `refs/cas/caches/git-warp/materializations`. Namespaces contain 1 to 16
1429
+ slash-separated lowercase ASCII components and at most 240 bytes. Components
1430
+ start and end with an ASCII letter or digit, may contain `.` and `-`, and
1431
+ cannot contain `..`, end in `.lock`, or start with the reserved `git-cas-`
1432
+ prefix. Invalid namespaces fail with `COLLECTION_NAMESPACE_INVALID`.
1433
+
1434
+ Cache keys are non-empty, well-formed Unicode in NFC form, contain no C0 or C1
1435
+ control characters, and encode to at most 1024 UTF-8 bytes. Keys are rejected
1436
+ rather than normalized. Their lowercase SHA-256 digest is the canonical index
1437
+ path; the original key remains in metadata and is checked on every read so a
1438
+ digest collision fails closed with `CACHE_ENTRY_INVALID`.
1439
+
1440
+ The default cache policy is `maxEntries: 10000`, `maxBytes: null`, and
1441
+ `accessResolutionMs: 3600000` (one hour). `maxEntries` is bounded from 1 to
1442
+ 99999. `maxBytes` is either `null` or a non-negative safe integer, and
1443
+ `accessResolutionMs` is a non-negative safe integer.
1444
+
1445
+ ### Storage And Reachability
1446
+
1447
+ ```text
1448
+ refs/cas/caches/<namespace> -> parentless generation commit
1449
+ `-- root-00000000 -> structured bundle index
1450
+ |-- .cache/state -> immutable page
1451
+ `-- entries/<sha256-key> -> entry bundle
1452
+ |-- meta -> immutable page
1453
+ `-- target -> asset/page/bundle handle
1454
+ ```
1455
+
1456
+ Every successful mutation builds and validates immutable pages and bundles
1457
+ before publishing one new generation with a guarded ref update. The generation
1458
+ commit is parentless, so the previous index and evicted targets become
1459
+ collectible when no other ref reaches them. A failed concurrent attempt may
1460
+ leave harmless unanchored objects; it cannot remove or overwrite the winning
1461
+ generation. CacheSet never runs Git garbage collection and never directly
1462
+ deletes an object.
1463
+
1464
+ The ref is mutable because it names the current generation. Its metadata,
1465
+ entry records, indexes, and targets are immutable CAS objects. CacheSet does
1466
+ not maintain a second filesystem or process-memory cache.
1467
+
1468
+ ### put And replace
1469
+
1470
+ ```javascript
1471
+ const stored = await cache.put('optic:user:alice', materializationHandle, {
1472
+ retention: 'evictable',
1473
+ expiresAt: new Date(Date.now() + 15 * 60 * 1000),
1474
+ });
1475
+
1476
+ const replaced = await cache.replace('optic:user:alice', nextHandle, {
1477
+ expectedHandle: materializationHandle,
1478
+ });
1479
+ ```
1480
+
1481
+ `put()` is an upsert unless `expectedHandle` is supplied; a guarded put requires
1482
+ that current target to exist and match. `replace()` always requires the key to
1483
+ already exist. On either operation, `expectedHandle` guards replacement to a
1484
+ particular current target.
1485
+ The result includes `changed`, `accepted`, `hit`, `previous`, `generation`, a
1486
+ capacity-policy report, and a `RetentionWitness` for the accepted target.
1487
+
1488
+ Writes reject already-expired timestamps. `pinned` and `evictable` entries are
1489
+ both Git-reachable while present. Capacity sweeps may remove only `evictable`
1490
+ entries; explicit expiry applies to either policy. When pinned entries or the
1491
+ newly written entry alone exceed capacity, the write remains successful and
1492
+ returns `policy.satisfied: false` instead of silently dropping protected data.
1493
+
1494
+ ### get And touch
1495
+
1496
+ ```javascript
1497
+ const hit = await cache.get('optic:user:alice');
1498
+ if (hit) {
1499
+ use(hit.handle);
1500
+ await cache.touch(hit.key);
1501
+ }
1502
+ ```
1503
+
1504
+ `get(key)` returns an immutable `CacheHit` or `null`. Expired entries are cache
1505
+ misses. A hit contains the key, parsed application handle, retention policy,
1506
+ expiry, deterministic logical bytes, creation and access timestamps, current
1507
+ generation, and immutable retention evidence.
1508
+
1509
+ `get()` never performs a durable write, including for an expired entry.
1510
+ `touch(key)` is the explicit access update. It writes only when the persisted
1511
+ `accessedAt` is at least `accessResolutionMs` old, coalescing approximate-LRU
1512
+ updates without turning every read into a Git ref mutation.
1513
+
1514
+ ### remove And sweep
1515
+
1516
+ ```javascript
1517
+ const removed = await cache.remove('optic:user:alice');
1518
+ const swept = await cache.sweep();
1519
+ ```
1520
+
1521
+ `remove()` releases one key. `sweep()` first releases expired entries, then
1522
+ evicts the oldest eligible entries until `maxEntries` and `maxBytes` are met.
1523
+ Eviction selection uses a fixed-size oldest-candidate heap and repeats bounded
1524
+ streaming passes when more candidates are needed; resident memory does not
1525
+ scale with cache cardinality.
1526
+
1527
+ Logical-byte accounting is versioned and deterministic:
1528
+
1529
+ - assets charge manifest logical size;
1530
+ - pages charge exact blob bytes;
1531
+ - bundles charge descriptor bytes plus transitive distinct child logical
1532
+ bytes;
1533
+ - one repeated child handle in a bundle is charged once;
1534
+ - the same target under two cache keys is charged to both entries.
1535
+
1536
+ ### inspect And doctor
1537
+
1538
+ ```javascript
1539
+ const first = await cache.inspect({ limit: 100 });
1540
+ const next = await cache.inspect({ limit: 100, cursor: first.nextCursor });
1541
+ const report = await cache.doctor();
1542
+ ```
1543
+
1544
+ `inspect()` streams the index to compute exact aggregate counts and returns at
1545
+ most 1,000 entry records per call. Its cursor is the last returned SHA-256 key
1546
+ digest. `doctor()` does not mutate the repository. It validates the cache ref,
1547
+ parentless generation, RootSet edge, structured bundle support graph, key
1548
+ digests, target handles, canonical metadata, accounting version, persisted
1549
+ summary, and capacity posture.
1550
+
1551
+ ### repair
1552
+
1553
+ ```javascript
1554
+ await cache.repair({
1555
+ entries: authoritativeEntries,
1556
+ policy: { maxEntries: 128, maxBytes: 2 * 1024 * 1024 * 1024 },
1557
+ });
1558
+ ```
1559
+
1560
+ `repair()` rebuilds a missing or malformed generation from an authoritative
1561
+ bounded entry list without trusting current cache metadata. It validates every
1562
+ target before publishing the replacement generation and returns a retention
1563
+ witness for the repaired index. Run `doctor()` again and require
1564
+ `healthy: true` before any destructive repository maintenance.
1565
+
1566
+ ## Expiring Sets
1567
+
1568
+ Expiring sets are the durable replay-marker surface. They are stricter than
1569
+ cache sets: a live marker is pinned through its declared acceptance window and
1570
+ cannot be removed for capacity, recency, repair, or caller convenience.
1571
+
1572
+ ```javascript
1573
+ const replay = await cas.expiringSets.open({
1574
+ namespace: 'git-warp/admission-replay',
1575
+ });
1576
+
1577
+ const result = await replay.addIfAbsent(requestNonce, {
1578
+ expiresAt: new Date(Date.now() + 15 * 60 * 1000),
1579
+ });
1580
+
1581
+ if (!result.admitted) {
1582
+ throw new Error('Replay rejected');
1583
+ }
1584
+ ```
1585
+
1586
+ The namespace uses the same canonical grammar as CacheSet and maps to
1587
+ `refs/cas/expiring/git-warp/admission-replay`. Open options accept only
1588
+ `namespace` and an optional RootSet conflict `retry` policy. Capacity and
1589
+ eviction options fail with `INVALID_OPTIONS` rather than being ignored.
1590
+
1591
+ ### Key Privacy And Collision Detection
1592
+
1593
+ Keys use the same non-empty, NFC, control-free, 1,024-byte input boundary as
1594
+ cache keys, but plaintext keys are never persisted. ExpiringSet computes two
1595
+ domain-separated SHA-256 values:
1596
+
1597
+ - the primary digest is the deterministic marker path;
1598
+ - the verification digest detects a primary-digest collision when that key is
1599
+ checked or admitted.
1600
+
1601
+ Both digests are lowercase canonical hex. A crypto adapter that returns an
1602
+ invalid digest or collapses both domains is rejected. Deterministic digests can
1603
+ still reveal low-entropy input through offline guessing, so callers should use
1604
+ high-entropy nonces or hash a suitably secret protocol value before admission.
1605
+
1606
+ ### Storage And Reachability
1607
+
1608
+ ```text
1609
+ refs/cas/expiring/<namespace> -> parentless generation commit
1610
+ `-- root-00000000 -> structured bundle index
1611
+ |-- .expiring/state -> immutable page
1612
+ `-- markers/<sha256-key> -> immutable page
1613
+ ```
1614
+
1615
+ Marker pages contain only the metadata version, primary and verification
1616
+ digests, `createdAt`, and `expiresAt`. Every current marker is a real transitive
1617
+ Git tree edge below the one RootSet slot. The returned `RetentionWitness` names
1618
+ that physical slot and the immutable marker page it supports; it does not
1619
+ pretend that a structured bundle's logical member name is a physical path in
1620
+ the generation tree.
1621
+
1622
+ Every generation commit is parentless. Replacing the same expired key or
1623
+ sweeping expired markers releases old support without preserving it through a
1624
+ commit-parent chain. ExpiringSet never deletes Git objects and never invokes
1625
+ garbage collection.
1626
+
1627
+ ### addIfAbsent And contains
1628
+
1629
+ `addIfAbsent(key, { expiresAt })` requires a future canonical UTC timestamp or
1630
+ a valid `Date`. It performs a compare-and-swap RootSet mutation. Concurrent
1631
+ duplicate calls produce exactly one `admitted: true` winner; a loser returns
1632
+ the winning immutable `ExpiringMarker` and its generation-scoped witness.
1633
+
1634
+ The operation rechecks the expiry on every conflict retry, clears all
1635
+ attempt-local result state, and validates the persisted state page against a
1636
+ streamed historical marker scan before staging a write. Missing, malformed, or
1637
+ inconsistent marker support fails closed instead of being silently healed.
1638
+
1639
+ `contains(key)` is a targeted, non-mutating membership check. It returns `true`
1640
+ only while the matching marker is unexpired. Callers that need atomic replay
1641
+ admission must use `addIfAbsent()` rather than composing `contains()` with a
1642
+ later write.
1643
+
1644
+ ### sweep
1645
+
1646
+ ```javascript
1647
+ const swept = await replay.sweep();
1648
+ ```
1649
+
1650
+ `sweep()` validates current state and then releases only markers whose
1651
+ `expiresAt` is less than or equal to the injected clock. There is no public
1652
+ `remove()` or `repair()` method and no capacity or LRU policy. The implementation
1653
+ uses bounded streaming validation, classification, and rewrite passes without
1654
+ retaining an array proportional to set cardinality.
1655
+
1656
+ An expired marker remains anchored until `sweep()` or admission of that same
1657
+ expired key publishes a replacement generation. `contains()` never performs
1658
+ that cleanup as a side effect.
1659
+
1660
+ ### inspect And doctor
1661
+
1662
+ ```javascript
1663
+ const page = await replay.inspect({ limit: 100 });
1664
+ const report = await replay.doctor();
1665
+ ```
1666
+
1667
+ `inspect()` returns digest-only marker records, live/expired classification,
1668
+ current aggregate counts, retention evidence, and a digest cursor. It returns
1669
+ at most 1,000 records per call. `doctor()` is non-mutating and validates the
1670
+ ref, parentless RootSet generation, structured index, canonical state and
1671
+ marker pages, nested object existence, and persisted count/expiry summary.
1672
+ Expired markers are reported as an operational classification, not corruption.
1673
+
1674
+ Malformed or missing state has no automatic repair path because an
1675
+ authoritative-but-incomplete replacement could weaken replay protection.
1676
+ Reconstruction requires a trusted external ledger and a separately reviewed
1677
+ operator procedure.
1678
+
1679
+ ### Clock Trust
1680
+
1681
+ The constructor-level `clock` option controls deterministic evaluation in
1682
+ tests and host integrations. Clock rollback extends protection because markers
1683
+ remain live longer. A forward jump can shorten a window, so security callers
1684
+ must validate request timestamps and choose `expiresAt` from the same trusted
1685
+ clock. Marker state survives process restart because the Git ref, not process
1686
+ memory, is authoritative.
1687
+
1688
+ ## Repository Diagnostics
1689
+
1690
+ `cas.diagnostics.doctor()` returns immutable, machine-readable evidence about
1691
+ the complete Git object store and the managed git-cas refs without running
1692
+ garbage collection or destructive prune.
1693
+
1694
+ ```javascript
1695
+ const report = await cas.diagnostics.doctor({
1696
+ gracePeriodMs: 14 * 24 * 60 * 60 * 1000,
1697
+ maxCollectionsPerKind: 100,
1698
+ });
1699
+
1700
+ console.log(report.repository.objects);
1701
+ console.log(report.usage.caches);
1702
+ console.log(report.limitations);
1703
+ ```
1704
+
1705
+ Pass either `gracePeriodMs` or an exact canonical `expiresBefore` UTC timestamp,
1706
+ not both. The default grace period is 14 days. `maxCollectionsPerKind` bounds
1707
+ detailed CacheSet, RootSet, and ExpiringSet rows from 1 through 1000; its default
1708
+ is 100. Every managed collection is still inspected sequentially and included
1709
+ in `totals`. Coverage reports `observed`, `inspected`, `detailed`, and
1710
+ `complete`, so detail truncation is visible instead of silently dropping
1711
+ managed refs or undercounting repository usage.
1712
+
1713
+ The reachability classes have precise operational meanings:
1714
+
1715
+ - `anchored` is the object set reached by all refs and all reflog entries.
1716
+ - `volatile` is the loose unreachable set reported by
1717
+ `git prune --dry-run --verbose --no-progress --expire=<cutoff>`.
1718
+ - `orphaned` is the remaining unreachable set not targeted by that exact dry
1719
+ run.
1720
+
1721
+ The volatile inventory always goes through
1722
+ `GitPlumbing.inspectPrunableObjects()` from `@git-stunts/plumbing`; git-cas does
1723
+ not construct or expose a mutating prune path. If independent writers change
1724
+ the object store while the streamed inventories run, arithmetic invariants
1725
+ fail closed: `healthy` becomes false, derived counts become `null`, and the
1726
+ report includes `REPOSITORY_CHANGED_DURING_INSPECTION`.
1727
+
1728
+ Repository-wide physical bytes are reported where Git provides compatible
1729
+ evidence: total object bytes, anchored bytes, and their combined unreachable
1730
+ difference. Physical bytes for an individual cache, root set, vault, orphaned
1731
+ class, or volatile class are `null`; shared objects and pack deltas cannot be
1732
+ assigned honestly to one owner. A dry prune also cannot expose the age of
1733
+ packed unreachable objects. Git may include configured alternate object stores
1734
+ in its inventory, while object disk sizes exclude pack indexes, bitmaps, and
1735
+ other repository metadata. These facts appear in `limitations` rather than
1736
+ being estimated.
1737
+
1738
+ Cache summaries report entry count, deterministic logical bytes, age, expiry,
1739
+ capacity policy, and pinned/evictable counts. RootSet policy counts and Vault
1740
+ entry counts are reported independently from reachability. A privacy-mode
1741
+ vault remains healthy but reports `entryCount: null` because repository doctor
1742
+ does not request or retain vault key material.
1743
+
1744
+ Object and ref inventories are consumed as streams, and managed collections are
1745
+ inspected one at a time. Runtime memory is bounded by stream windows,
1746
+ `maxCollectionsPerKind`, and existing per-collection/blob safety limits;
1747
+ runtime is linear in repository object and managed-collection count. Doctor
1748
+ never updates a ref, writes an object, runs `git gc`, or runs a destructive
1749
+ `git prune`.
1750
+
1072
1751
  ## Vault
1073
1752
 
1074
1753
  The vault provides GC-safe storage by maintaining a single Git ref (`refs/cas/vault`) pointing to a commit chain. The commit's tree indexes all stored assets by slug. This prevents `git gc` from garbage-collecting stored data.
@@ -1959,6 +2638,31 @@ class CustomGitAdapter {
1959
2638
  }
1960
2639
  ```
1961
2640
 
2641
+ ### RepositoryInspectionPort
2642
+
2643
+ The domain-facing, non-mutating port behind repository doctor. Its Git adapter
2644
+ streams all-object metadata, reachable OIDs, dry-run-prunable loose objects,
2645
+ and refs, and obtains the aggregate reachable object disk usage. Application
2646
+ code normally uses `cas.diagnostics.doctor()` instead of this low-level port.
2647
+
2648
+ ```javascript
2649
+ for await (const object of port.iterateObjects()) {
2650
+ console.log(object.oid, object.type, object.logicalBytes, object.physicalBytes);
2651
+ }
2652
+
2653
+ for await (const oid of port.iterateReachableObjectIds()) {
2654
+ // refs and reflogs both contribute
2655
+ }
2656
+
2657
+ for await (const object of port.iteratePrunableObjects({ expiresBefore })) {
2658
+ // safe dry-run evidence only
2659
+ }
2660
+ ```
2661
+
2662
+ `GitRepositoryInspectionAdapter` requires `@git-stunts/plumbing` 3.1.0 or
2663
+ newer. Structured Git output is validated strictly; malformed records or a
2664
+ non-zero stream status fail with `REPOSITORY_INSPECTION_INVALID`.
2665
+
1962
2666
  ### CodecPort
1963
2667
 
1964
2668
  Interface for encoding/decoding manifest data.
@@ -2334,17 +3038,48 @@ new CasError({ message, code, meta, documentationUrl });
2334
3038
  | `GIT_ERROR` | Underlying Git plumbing command failed | `readManifest()`, `inspectAsset()`, `collectReferencedChunks()` |
2335
3039
  | `GIT_REF_NOT_FOUND` | Git ref lookup found no ref; vault reads normalize this to empty state | `GitRefAdapter`, `VaultPersistence` |
2336
3040
  | `INVALID_OPTIONS` | Mutually exclusive options provided or unsupported option value | `store()`, `restore()` |
3041
+ | `HANDLE_INVALID` | Handle object, canonical token, or staged result is malformed or unsupported | Application handles and staged results |
3042
+ | `HANDLE_KIND_MISMATCH` | A handle has a valid envelope but the wrong content kind | Handle parsing and application storage |
3043
+ | `HANDLE_CODEC_MISMATCH` | Handle manifest codec differs from the active CAS codec | `assets.open()`, `assets.adopt()`, retention, publication |
3044
+ | `HANDLE_TARGET_MISSING` | The repository does not contain the complete object graph referenced by a handle | `assets.open()`, `assets.adopt()`, retention, publication |
3045
+ | `HANDLE_TARGET_TYPE_MISMATCH` | A handle root or referenced object has the wrong Git object type | Application storage validation |
3046
+ | `PAGE_TOO_LARGE` | Page input or imported page blob exceeds the effective byte bound | `pages.put()`, `pages.get()`, `pages.open()` |
3047
+ | `BUNDLE_CORRUPT` | Persisted bundle descriptors, edges, ranges, or target summaries disagree | Bundle reads, retention, publication |
3048
+ | `BUNDLE_DESCRIPTOR_LIMIT` | Bundle descriptor bytes exceed admission or repository read policy | Bundle construction and validation |
3049
+ | `BUNDLE_DUPLICATE_PATH` | Two ordered bundle members use the same canonical path | `bundles.putOrdered()` |
3050
+ | `BUNDLE_FANOUT_LIMIT` | Bundle tree width, depth, or nesting exceeds policy | Bundle construction and validation |
3051
+ | `BUNDLE_LIMIT_INVALID` | Configured or per-operation bundle limits are malformed or attempt to raise repository policy | Facade construction, bundle writes |
3052
+ | `BUNDLE_MEMBER_INVALID` | Bundle member input or resolved handle target is invalid | Bundle construction |
3053
+ | `BUNDLE_MEMBER_LIMIT` | Bundle member count exceeds admission or repository read policy | Bundle construction and validation |
3054
+ | `BUNDLE_MEMBER_NOT_FOUND` | Requested bundle member path is absent | `bundles.openMember()` |
3055
+ | `BUNDLE_MEMBER_NOT_STREAMABLE` | Requested member is a nested structured bundle rather than bytes | `bundles.openMember()` |
3056
+ | `BUNDLE_MEMBER_ORDER` | Ordered bundle input is not strictly increasing by canonical path | `bundles.putOrdered()` |
3057
+ | `BUNDLE_PATH_INVALID` | Bundle member path is empty, unsafe, or non-canonical | Bundle writes and reads |
3058
+ | `BUNDLE_PATH_LIMIT` | Bundle member path exceeds its UTF-8 byte bound | Bundle construction and validation |
3059
+ | `COLLECTION_NAMESPACE_INVALID` | Managed collection namespace or cache ref is not canonical | `caches.open()` |
3060
+ | `CACHE_KEY_INVALID` | Cache key is empty, non-canonical, too large, or contains controls | CacheSet key operations |
3061
+ | `CACHE_ENTRY_INVALID` | Entry metadata, retention, expiry, handle identity, or key digest is invalid | CacheSet writes and reads |
3062
+ | `CACHE_STATE_INVALID` | Cache state, structured index, counts, or namespace is inconsistent | CacheSet reads, `doctor()`, and `repair()` |
3063
+ | `CACHE_POLICY_INVALID` | Cache entry, byte, access-resolution, or repair bound is invalid | `caches.open()`, CacheSet policy operations |
3064
+ | `CACHE_LOGICAL_SIZE_UNKNOWN` | A target has no deterministic safe-integer logical size | `put()`, `replace()`, accounting, and repair |
3065
+ | `CACHE_CONFLICT` | Concurrent cache update exhausted bounded compare-and-swap retries | CacheSet mutations and repair |
3066
+ | `RETENTION_WITNESS_INVALID` | Witness policy, reachability, root evidence, generation, or timestamp is invalid | `RetentionWitness` |
3067
+ | `PUBLICATION_INVALID` | Publication message, parent list, expected head, dependency, or clock input is invalid | `publications.commit()` |
3068
+ | `PUBLICATION_REF_FORBIDDEN` | Target ref is invalid, reserved, or outside configured application namespaces | `publications.commit()` |
3069
+ | `PUBLICATION_CONFLICT` | Application ref head differs from the explicit expected head | `publications.commit()` |
3070
+ | `PUBLICATION_REF_UPDATE_FAILED` | Application ref update or post-failure head observation failed for a non-conflict reason | `publications.commit()` |
2337
3071
  | `INVALID_SLUG` | Slug fails validation (empty, control chars, `..` segments, etc.) | `addToVault()` |
2338
3072
  | `ROOT_SET_REF_INVALID` | Ref is outside `refs/cas/rootsets/*` or is not a safe Git ref | `rootSets.open()` |
2339
3073
  | `ROOT_SET_ENTRY_INVALID` | Entry name, OID, type, retention, or duplicate-name validation failed | `put()`, `replace()`, `mutate()`, `repair()` |
2340
3074
  | `ROOT_SET_TARGET_MISSING` | A requested target OID does not exist | `put()`, `replace()`, `mutate()`, `repair()` |
2341
- | `ROOT_SET_TARGET_UNREADABLE` | Git could not inspect a target, but did not prove that it was missing | Root-set mutation and doctor |
3075
+ | `ROOT_SET_TARGET_UNREADABLE` | Git could not inspect a target, but did not prove that it was missing | Root-set mutation and doctor |
2342
3076
  | `ROOT_SET_TARGET_TYPE_MISMATCH` | Declared blob/tree type does not match the Git object | `put()`, `replace()`, `mutate()`, `repair()` |
2343
3077
  | `ROOT_SET_CONFLICT` | Concurrent root-set update exhausted bounded compare-and-swap retries | Root-set mutations and repair |
2344
3078
  | `ROOT_SET_HEAD_INVALID` | Root-set ref cannot resolve to a readable commit tree | `read()`, `list()`, `doctor()` |
2345
- | `ROOT_SET_METADATA_INVALID` | `.rootset.json` is malformed, non-canonical, or belongs to another ref | `read()`, `list()`, `doctor()` |
3079
+ | `ROOT_SET_METADATA_INVALID` | `.rootset.json` is malformed, non-canonical, or belongs to another ref | `read()`, `list()`, `doctor()` |
2346
3080
  | `ROOT_SET_TREE_INVALID` | Metadata and the Git tree's actual reachability edges disagree | `read()`, `list()`, `doctor()` |
2347
3081
  | `ROOT_SET_REF_UPDATE_FAILED` | Root-set ref update failed for a non-conflict reason | Root-set mutations and repair |
3082
+ | `REPOSITORY_INSPECTION_INVALID` | Repository doctor options, Git output, dependencies, or safe-integer totals are invalid | `cas.diagnostics.doctor()`, repository inspection adapter |
2348
3083
  | `VAULT_ENTRY_NOT_FOUND` | Slug does not exist in vault | `removeFromVault()`, `resolveVaultEntry()` |
2349
3084
  | `VAULT_ENTRY_EXISTS` | Slug already exists (use `force` to overwrite) | `addToVault()` |
2350
3085
  | `VAULT_CONFLICT` | Concurrent vault update detected (CAS failure after retries) | `addToVault()`, `removeFromVault()`, `initVault()`, `rotateVaultPassphrase()` |