@git-stunts/git-cas 6.5.12 → 7.1.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 (57) hide show
  1. package/ARCHITECTURE.md +15 -0
  2. package/CHANGELOG.md +74 -0
  3. package/README.md +14 -4
  4. package/UPGRADING.md +90 -27
  5. package/build-info.json +2 -2
  6. package/docs/API.md +111 -0
  7. package/docs/releases/v7.0.0.md +27 -0
  8. package/docs/releases/v7.1.0.md +27 -0
  9. package/index.d.ts +15 -0
  10. package/index.js +30 -0
  11. package/package.json +7 -5
  12. package/src/domain/errors/Codes.js +1 -0
  13. package/src/domain/errors/ReservationStorageError.js +9 -0
  14. package/src/domain/schemas/ManifestSchema.d.ts +4 -4
  15. package/src/domain/services/ReservationCustodyObjects.js +171 -0
  16. package/src/domain/services/ReservationCustodyStore.js +149 -0
  17. package/src/domain/services/ReservationIndex.js +169 -0
  18. package/src/domain/services/ReservationIndexNode.js +75 -0
  19. package/src/domain/services/ReservationLedger.js +326 -0
  20. package/src/domain/services/ReservationLedgerStore.js +141 -0
  21. package/src/domain/services/ReservationListing.js +40 -0
  22. package/src/domain/services/ReservationNamespace.d.ts +135 -0
  23. package/src/domain/services/ReservationNamespace.js +51 -0
  24. package/src/domain/services/ReservationNamespaceRegistry.js +89 -0
  25. package/src/domain/services/ReservationRecord.js +166 -0
  26. package/src/domain/services/ReservationScan.js +49 -0
  27. package/src/domain/value-objects/ReservationCursor.d.ts +11 -0
  28. package/src/domain/value-objects/ReservationCursor.js +31 -0
  29. package/src/domain/value-objects/ReservationCustodyDescriptor.js +47 -0
  30. package/src/domain/value-objects/ReservationCustodySnapshot.js +16 -0
  31. package/src/domain/value-objects/ReservationEvidence.js +26 -0
  32. package/src/domain/value-objects/ReservationEvidenceRead.js +22 -0
  33. package/src/domain/value-objects/ReservationEvidenceRoots.js +72 -0
  34. package/src/domain/value-objects/ReservationIndeterminate.js +17 -0
  35. package/src/domain/value-objects/ReservationInspection.js +21 -0
  36. package/src/domain/value-objects/ReservationKey.js +26 -0
  37. package/src/domain/value-objects/ReservationLedgerHeader.js +15 -0
  38. package/src/domain/value-objects/ReservationLedgerRefusal.js +21 -0
  39. package/src/domain/value-objects/ReservationLedgerSnapshot.js +27 -0
  40. package/src/domain/value-objects/ReservationListRequest.js +35 -0
  41. package/src/domain/value-objects/ReservationListUnavailable.js +17 -0
  42. package/src/domain/value-objects/ReservationOpenIndeterminate.js +15 -0
  43. package/src/domain/value-objects/ReservationOpenRefusal.js +14 -0
  44. package/src/domain/value-objects/ReservationPage.js +27 -0
  45. package/src/domain/value-objects/ReservationPolicy.js +24 -0
  46. package/src/domain/value-objects/ReservationRefusal.js +23 -0
  47. package/src/domain/value-objects/ReservationResult.js +27 -0
  48. package/src/domain/value-objects/ReservationSupport.js +22 -0
  49. package/src/infrastructure/adapters/GitRefAdapter.js +7 -0
  50. package/src/infrastructure/codecs/ReservationCustodyCodec.js +54 -0
  51. package/src/infrastructure/codecs/ReservationLedgerCodec.js +48 -0
  52. package/src/infrastructure/codecs/ReservationRecordCodec.js +54 -0
  53. package/src/package-version.js +1 -1
  54. package/src/ports/GitRefPort.js +11 -0
  55. package/src/ports/ReservationCustodyCodecPort.js +14 -0
  56. package/src/ports/ReservationLedgerCodecPort.js +14 -0
  57. package/src/ports/ReservationRecordCodecPort.js +14 -0
package/index.js CHANGED
@@ -10,6 +10,12 @@ import CasService from './src/domain/services/CasService.js';
10
10
  import VaultService from './src/domain/services/VaultService.js';
11
11
  import RootSet from './src/domain/services/RootSet.js';
12
12
  import RootSetRegistry from './src/domain/services/RootSetRegistry.js';
13
+ import ReservationNamespaceRegistry from './src/domain/services/ReservationNamespaceRegistry.js';
14
+ import ReservationIndex from './src/domain/services/ReservationIndex.js';
15
+ import ReservationLedgerStore from './src/domain/services/ReservationLedgerStore.js';
16
+ import ReservationRecordCodec from './src/infrastructure/codecs/ReservationRecordCodec.js';
17
+ import ReservationLedgerCodec from './src/infrastructure/codecs/ReservationLedgerCodec.js';
18
+ import ReservationCustodyCodec from './src/infrastructure/codecs/ReservationCustodyCodec.js';
13
19
  import AssetService from './src/domain/services/AssetService.js';
14
20
  import BundleService from './src/domain/services/BundleService.js';
15
21
  import CacheSet from './src/domain/services/CacheSet.js';
@@ -100,6 +106,8 @@ export { default as StagedPage } from './src/domain/value-objects/StagedPage.js'
100
106
  export { default as RetentionWitness } from './src/domain/value-objects/RetentionWitness.js';
101
107
  export { default as CacheHit } from './src/domain/value-objects/CacheHit.js';
102
108
  export { default as CachePolicy } from './src/domain/value-objects/CachePolicy.js';
109
+ export { default as ReservationNamespace } from './src/domain/services/ReservationNamespace.js';
110
+ export { default as ReservationCursor } from './src/domain/value-objects/ReservationCursor.js';
103
111
  export { default as ExpiringMarker } from './src/domain/value-objects/ExpiringMarker.js';
104
112
  export { default as EventEmitterObserver } from './src/infrastructure/adapters/EventEmitterObserver.js';
105
113
  export { default as StatsCollector } from './src/infrastructure/adapters/StatsCollector.js';
@@ -195,6 +203,14 @@ export default class ContentAddressableStore {
195
203
  }
196
204
 
197
205
  #installCapabilities() {
206
+ this.#installCollectionCapabilities();
207
+ this.#installApplicationCapabilities();
208
+ }
209
+
210
+ #installCollectionCapabilities() {
211
+ this.reservations = Object.freeze({
212
+ open: async (options) => (await this.#getReservationRegistry()).open(options),
213
+ });
198
214
  this.rootSets = Object.freeze({
199
215
  open: async (options) => (await this.#getRootSetRegistry()).open(options),
200
216
  });
@@ -212,6 +228,9 @@ export default class ContentAddressableStore {
212
228
  this.diagnostics = Object.freeze({
213
229
  doctor: async (options) => (await this.#getRepositoryDoctor()).doctor(options),
214
230
  });
231
+ }
232
+
233
+ #installApplicationCapabilities() {
215
234
  this.assets = Object.freeze({
216
235
  put: async (options) => (await this.#getAssetService()).put(options),
217
236
  putBatch: async (options) => (await this.#getAssetService()).putBatch(options),
@@ -260,6 +279,7 @@ export default class ContentAddressableStore {
260
279
  #vault = null;
261
280
  /** @type {RootSetRegistry|null} */
262
281
  #rootSetRegistry = null;
282
+ #reservationRegistry = null;
263
283
  /** @type {CacheSetRegistry|null} */
264
284
  #cacheSetRegistry = null;
265
285
  /** @type {ExpiringSetRegistry|null} */
@@ -436,6 +456,16 @@ export default class ContentAddressableStore {
436
456
  return this.#rootSetRegistry;
437
457
  }
438
458
 
459
+ async #getReservationRegistry() {
460
+ const { persistence, crypto } = await this.#getService();
461
+ this.#reservationRegistry ??= new ReservationNamespaceRegistry({
462
+ persistence, refs: this.#ref, crypto, custodyCodec: new ReservationCustodyCodec(),
463
+ index: new ReservationIndex({ persistence, crypto, codec: new ReservationRecordCodec() }),
464
+ store: new ReservationLedgerStore({ persistence, refs: this.#ref, codec: new ReservationLedgerCodec() }),
465
+ });
466
+ return this.#reservationRegistry;
467
+ }
468
+
439
469
  /** @returns {Promise<CacheSetRegistry>} */
440
470
  async #getCacheSetRegistry() {
441
471
  await this.#getService();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "6.5.12",
3
+ "version": "7.1.0",
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",
@@ -57,7 +57,9 @@
57
57
  "LICENSE",
58
58
  "CHANGELOG.md",
59
59
  "docs/releases/v6.5.11.md",
60
- "docs/releases/v6.5.12.md"
60
+ "docs/releases/v6.5.12.md",
61
+ "docs/releases/v7.0.0.md",
62
+ "docs/releases/v7.1.0.md"
61
63
  ],
62
64
  "engines": {
63
65
  "node": ">=22.0.0"
@@ -96,7 +98,7 @@
96
98
  "test:integration": "docker compose run --build --rm test-node pnpm vitest run test/integration --no-file-parallelism",
97
99
  "test:integration:node": "docker compose run --build --rm test-node npx vitest run test/integration --no-file-parallelism",
98
100
  "test:integration:bun": "docker compose run --build --rm test-bun bunx vitest run test/integration --no-file-parallelism",
99
- "test:integration:deno": "docker compose run --build --rm test-deno deno run -A npm:vitest run test/integration --no-file-parallelism",
101
+ "test:integration:deno": "docker compose run --build --rm test-deno deno run --node-modules-dir=manual -A npm:vitest run test/integration --no-file-parallelism",
100
102
  "test:platforms": "docker compose run --build --rm test-node && docker compose run --build --rm test-bun && docker compose run --build --rm test-deno",
101
103
  "benchmark": "docker compose run --build --rm test-node pnpm vitest bench test/benchmark",
102
104
  "benchmark:local": "vitest bench test/benchmark",
@@ -114,11 +116,11 @@
114
116
  "@flyingrobots/bijou-tui": "^7.2.0",
115
117
  "@flyingrobots/bijou-tui-app": "^7.2.0",
116
118
  "@git-stunts/alfred": "^0.10.0",
117
- "@git-stunts/plumbing": "^3.3.2",
119
+ "@git-stunts/plumbing": "^3.3.3",
118
120
  "@git-stunts/vault": "^1.0.1",
119
121
  "cbor-x": "^1.6.0",
120
122
  "commander": "14.0.3",
121
- "zod": "^3.24.1"
123
+ "zod": "^4.6.7"
122
124
  },
123
125
  "pnpm": {
124
126
  "onlyBuiltDependencies": [
@@ -67,6 +67,7 @@ const ErrorCodes = Object.freeze({
67
67
  RECIPIENT_NOT_FOUND: 'RECIPIENT_NOT_FOUND',
68
68
  REPOSITORY_INSPECTION_INVALID: 'REPOSITORY_INSPECTION_INVALID',
69
69
  RESOURCE_CLOSED: 'RESOURCE_CLOSED',
70
+ RESERVATION_CORRUPT: 'RESERVATION_CORRUPT',
70
71
  RESTORE_TOO_LARGE: 'RESTORE_TOO_LARGE',
71
72
  RETENTION_WITNESS_INVALID: 'RETENTION_WITNESS_INVALID',
72
73
  ROOT_SET_CONFLICT: 'ROOT_SET_CONFLICT',
@@ -0,0 +1,9 @@
1
+ import CasError from './CasError.js';
2
+ import { ErrorCodes } from './Codes.js';
3
+
4
+ /** Invalid reservation storage evidence; never a known absence or a refund. */
5
+ export default class ReservationStorageError extends CasError {
6
+ constructor(message, meta = {}) {
7
+ super(message, ErrorCodes.RESERVATION_CORRUPT, meta);
8
+ }
9
+ }
@@ -15,7 +15,7 @@ export declare const ChunkSchema: z.ZodObject<{
15
15
 
16
16
  /** Validates KDF parameters stored alongside encryption metadata. */
17
17
  export declare const KdfSchema: z.ZodObject<{
18
- algorithm: z.ZodEnum<["pbkdf2", "scrypt"]>;
18
+ algorithm: z.ZodEnum<{ pbkdf2: "pbkdf2"; scrypt: "scrypt" }>;
19
19
  salt: z.ZodString;
20
20
  iterations: z.ZodOptional<z.ZodNumber>;
21
21
  cost: z.ZodOptional<z.ZodNumber>;
@@ -75,7 +75,7 @@ export declare const EncryptionSchema: z.ZodUnion<
75
75
 
76
76
  /** Validates compression metadata. */
77
77
  export declare const CompressionSchema: z.ZodObject<{
78
- algorithm: z.ZodEnum<["gzip"]>;
78
+ algorithm: z.ZodEnum<{ gzip: "gzip" }>;
79
79
  }>;
80
80
 
81
81
  /** Validates fixed-size chunking parameters. */
@@ -99,8 +99,8 @@ export declare const CdcChunkingSchema: z.ZodObject<{
99
99
 
100
100
  /** Validates chunking metadata (fixed or CDC). */
101
101
  export declare const ChunkingSchema: z.ZodDiscriminatedUnion<
102
- "strategy",
103
- [typeof FixedChunkingSchema, typeof CdcChunkingSchema]
102
+ [typeof FixedChunkingSchema, typeof CdcChunkingSchema],
103
+ "strategy"
104
104
  >;
105
105
 
106
106
  /** Validates a sub-manifest reference in a v2 Merkle manifest. */
@@ -0,0 +1,171 @@
1
+ import GitPersistencePort from '../../ports/GitPersistencePort.js';
2
+ import GitRefPort from '../../ports/GitRefPort.js';
3
+ import ReservationCustodyCodecPort, { RESERVATION_CUSTODY_MAX_BYTES } from '../../ports/ReservationCustodyCodecPort.js';
4
+ import ReservationEvidence, { RESERVATION_PAGE_MAX_BYTES } from '../value-objects/ReservationEvidence.js';
5
+ import ReservationCustodyDescriptor from '../value-objects/ReservationCustodyDescriptor.js';
6
+ import ReservationCustodySnapshot from '../value-objects/ReservationCustodySnapshot.js';
7
+ import ReservationRecord from './ReservationRecord.js';
8
+ import CollectionNamespace from '../value-objects/CollectionNamespace.js';
9
+ import Oid from '../value-objects/Oid.js';
10
+ import InvalidOptionsError from '../errors/InvalidOptionsError.js';
11
+ import ReservationStorageError from '../errors/ReservationStorageError.js';
12
+
13
+ const COMMIT_MAX_BYTES = 16 * 1024;
14
+ const ROOT_MAX_BYTES = 2 * 1024;
15
+ const SUPPORT_TREE_MAX_BYTES = 8 * 1024;
16
+
17
+ /** Bounded immutable custody objects. This class never creates or deletes refs. */
18
+ export default class ReservationCustodyObjects {
19
+ #persistence;
20
+ #refs;
21
+ #codec;
22
+
23
+ constructor({ namespace, persistence, refs, codec }) {
24
+ if (!(persistence instanceof GitPersistencePort) || !(refs instanceof GitRefPort) ||
25
+ !(codec instanceof ReservationCustodyCodecPort)) {
26
+ throw new InvalidOptionsError('Custody objects require persistence, ref and descriptor codec ports');
27
+ }
28
+ this.namespace = CollectionNamespace.from(namespace).toString();
29
+ this.#persistence = persistence;
30
+ this.#refs = refs;
31
+ this.#codec = codec;
32
+ Object.freeze(this);
33
+ }
34
+
35
+ async describe({ attempt, evidence, preparation = null }) {
36
+ if (!(attempt instanceof ReservationRecord) || !(evidence instanceof ReservationEvidence)) {
37
+ throw new InvalidOptionsError('Custody description requires an attempt and validated evidence');
38
+ }
39
+ await this.#assertRoots(evidence.roots);
40
+ const recordOid = await this.#persistence.writeBlob(evidence.record);
41
+ return new ReservationCustodyDescriptor({
42
+ namespace: this.namespace, key: attempt.key, binding: attempt.binding,
43
+ stage: preparation === null ? 'preparation' : 'settlement', preparation,
44
+ recordOid, roots: evidence.roots,
45
+ });
46
+ }
47
+
48
+ async write(descriptor) {
49
+ this.#assertDescriptor(descriptor);
50
+ await this.#assertPayload(descriptor);
51
+ const bytes = this.#codec.encode(descriptor);
52
+ if (!(bytes instanceof Uint8Array) || bytes.length > RESERVATION_CUSTODY_MAX_BYTES) {
53
+ throw new ReservationStorageError('Encoded custody descriptor exceeds its bound');
54
+ }
55
+ const metadata = await this.#persistence.writeBlob(bytes);
56
+ const support = await this.#persistence.writeTree(descriptor.roots.toTreeLines());
57
+ const treeOid = await this.#persistence.writeTree([
58
+ `100644 blob ${metadata}\tdescriptor`, `100644 blob ${descriptor.recordOid}\trecord`, `040000 tree ${support}\tsupport`,
59
+ ]);
60
+ for (const oid of [metadata, support, treeOid]) {
61
+ assertSameFormat(oid, descriptor.recordOid);
62
+ }
63
+ const revision = await this.#refs.createCommit({
64
+ treeOid, parentOids: descriptor.parents, message: `git-cas reservation ${descriptor.stage} v1`,
65
+ });
66
+ return new ReservationCustodySnapshot({ descriptor, revision });
67
+ }
68
+
69
+ async read(revision) {
70
+ await this.#assertObject(revision, { type: 'commit', maxBytes: COMMIT_MAX_BYTES });
71
+ const root = await this.#refs.resolveTree(revision);
72
+ assertSameFormat(root, revision);
73
+ await this.#assertObject(root, { type: 'tree', maxBytes: ROOT_MAX_BYTES });
74
+ const entries = await this.#persistence.readTree(root);
75
+ const { metadata, record, support } = rootEntries(entries, revision);
76
+ await this.#assertObject(metadata, { type: 'blob', maxBytes: RESERVATION_CUSTODY_MAX_BYTES });
77
+ const descriptor = this.#codec.decode(await this.#persistence.readBlob(metadata, RESERVATION_CUSTODY_MAX_BYTES));
78
+ this.#assertDescriptor(descriptor);
79
+ if (descriptor.recordOid !== record) {
80
+ throw new ReservationStorageError('Custody record edge disagrees with its descriptor');
81
+ }
82
+ const parents = await this.#refs.resolveParents(revision);
83
+ assertParents(parents, descriptor.parents);
84
+ await this.#assertObject(support, { type: 'tree', maxBytes: SUPPORT_TREE_MAX_BYTES });
85
+ descriptor.roots.assertTree(await this.#persistence.readTree(support));
86
+ await this.#assertPayload(descriptor);
87
+ return new ReservationCustodySnapshot({ descriptor, revision });
88
+ }
89
+
90
+ async readEvidence(revision) {
91
+ const { descriptor } = await this.read(revision);
92
+ return new ReservationEvidence({
93
+ record: await this.#persistence.readBlob(descriptor.recordOid, RESERVATION_PAGE_MAX_BYTES),
94
+ supports: descriptor.roots.supports, parents: descriptor.roots.parents,
95
+ });
96
+ }
97
+
98
+ #assertDescriptor(descriptor) {
99
+ if (!(descriptor instanceof ReservationCustodyDescriptor) || descriptor.namespace !== this.namespace) {
100
+ throw new ReservationStorageError('Custody descriptor does not belong to this namespace');
101
+ }
102
+ }
103
+
104
+ async #assertPayload(descriptor) {
105
+ await this.#assertObject(descriptor.recordOid, { type: 'blob', maxBytes: RESERVATION_PAGE_MAX_BYTES });
106
+ await this.#assertRoots(descriptor.roots);
107
+ if (descriptor.preparation !== null) {
108
+ await this.#assertObject(descriptor.preparation, { type: 'commit', maxBytes: COMMIT_MAX_BYTES });
109
+ }
110
+ }
111
+
112
+ async #assertRoots(roots) {
113
+ for (const item of roots.supports) {
114
+ await this.#assertObject(item.oid, { type: item.type, maxBytes: Number.MAX_SAFE_INTEGER });
115
+ }
116
+ for (const parent of roots.parents) {
117
+ await this.#assertObject(parent, { type: 'commit', maxBytes: Number.MAX_SAFE_INTEGER });
118
+ }
119
+ }
120
+
121
+ async #assertObject(oid, { type, maxBytes }) {
122
+ assertOid(oid);
123
+ const [actualType, size] = await Promise.all([
124
+ this.#persistence.readObjectType(oid), this.#persistence.readObjectSize(oid),
125
+ ]);
126
+ if (actualType !== type || !Number.isSafeInteger(size) || size < 0 || size > maxBytes) {
127
+ throw new ReservationStorageError('Custody object type or byte bound is invalid', { oid, type, size });
128
+ }
129
+ }
130
+ }
131
+
132
+ function rootEntries(entries, revision) {
133
+ if (!Array.isArray(entries) || entries.length !== 3) {
134
+ throw new ReservationStorageError('Custody root must have exactly three entries');
135
+ }
136
+ const metadata = rootEntry(entries, { name: 'descriptor', type: 'blob', mode: '100644' });
137
+ const record = rootEntry(entries, { name: 'record', type: 'blob', mode: '100644' });
138
+ const support = rootEntry(entries, { name: 'support', type: 'tree', mode: '040000' });
139
+ for (const oid of [metadata, record, support]) {
140
+ assertSameFormat(oid, revision);
141
+ }
142
+ return { metadata, record, support };
143
+ }
144
+
145
+ function rootEntry(entries, { name, type, mode }) {
146
+ const entry = entries.find((item) => item.name === name);
147
+ if (!entry || entry.type !== type || entry.mode !== mode) {
148
+ throw new ReservationStorageError('Custody root entry is invalid', { name });
149
+ }
150
+ return entry.oid;
151
+ }
152
+
153
+ function assertParents(actual, expected) {
154
+ if (!Array.isArray(actual) || actual.length !== expected.length || actual.some((oid, i) => oid !== expected[i])) {
155
+ throw new ReservationStorageError('Custody commit parents disagree with its descriptor');
156
+ }
157
+ }
158
+
159
+ function assertSameFormat(left, right) {
160
+ assertOid(left);
161
+ assertOid(right);
162
+ if (left.length !== right.length) {
163
+ throw new ReservationStorageError('Custody changed Git object format');
164
+ }
165
+ }
166
+
167
+ function assertOid(value) {
168
+ if (!Oid.isValid(value) || value !== value.toLowerCase()) {
169
+ throw new ReservationStorageError('Custody requires canonical Git OIDs');
170
+ }
171
+ }
@@ -0,0 +1,149 @@
1
+ import GitRefPort from '../../ports/GitRefPort.js';
2
+ import CryptoPort from '../../ports/CryptoPort.js';
3
+ import ReservationCustodyObjects from './ReservationCustodyObjects.js';
4
+ import ReservationRecord from './ReservationRecord.js';
5
+ import ReservationKey from '../value-objects/ReservationKey.js';
6
+ import ReservationRefusal from '../value-objects/ReservationRefusal.js';
7
+ import InvalidOptionsError from '../errors/InvalidOptionsError.js';
8
+ import ReservationStorageError from '../errors/ReservationStorageError.js';
9
+ import { CasError, ErrorCodes } from '../errors/index.js';
10
+
11
+ /** Per-attempt pins; the ledger owner alone decides when a phase may be issued. */
12
+ export default class ReservationCustodyStore {
13
+ #objects;
14
+ #refs;
15
+ #crypto;
16
+
17
+ constructor({ objects, refs, crypto }) {
18
+ if (!(objects instanceof ReservationCustodyObjects) || !(refs instanceof GitRefPort) || !(crypto instanceof CryptoPort)) {
19
+ throw new InvalidOptionsError('Custody store requires immutable objects, refs and crypto');
20
+ }
21
+ this.namespace = objects.namespace;
22
+ this.#objects = objects;
23
+ this.#refs = refs;
24
+ this.#crypto = crypto;
25
+ Object.freeze(this);
26
+ }
27
+
28
+ async read(attempt) {
29
+ const posture = await this.#refs.inspectRef(await this.#ref(attempt));
30
+ if (posture?.symref !== null) {
31
+ throw new ReservationStorageError('Custody must use a direct ref');
32
+ }
33
+ if (posture.oid === null) {
34
+ return null;
35
+ }
36
+ const current = await this.#objects.read(posture.oid);
37
+ assertIdentity(attempt, current);
38
+ const original = current.descriptor.stage === 'preparation' ? current : await this.#original(attempt, current);
39
+ if (attempt.preparation !== null && original.revision !== attempt.preparation) {
40
+ throw new ReservationStorageError('Custody pin does not retain the original preparation');
41
+ }
42
+ return current;
43
+ }
44
+
45
+ async verify(attempt) {
46
+ if (attempt.preparation === null) {
47
+ throw new ReservationStorageError('This attempt has no prepared custody to verify');
48
+ }
49
+ const current = await this.read(attempt);
50
+ if (current === null || (attempt.settlement !== null && current.revision !== attempt.settlement)) {
51
+ throw new ReservationStorageError('Required reservation custody is missing or replaced');
52
+ }
53
+ return current;
54
+ }
55
+
56
+ async readEvidence(attempt, stage) {
57
+ await this.verify(attempt);
58
+ const revision = stage === 'preparation' ? attempt.preparation : attempt.settlement;
59
+ return await this.#objects.readEvidence(revision);
60
+ }
61
+
62
+ async prepare(attempt, evidence) {
63
+ const descriptor = await this.#objects.describe({ attempt, evidence });
64
+ let current = await this.read(attempt);
65
+ if (current === null) {
66
+ if (attempt.preparation !== null) {
67
+ throw new ReservationStorageError('Cannot recreate missing prepared custody');
68
+ }
69
+ const candidate = await this.#objects.write(descriptor);
70
+ current = await this.#install(attempt, { expected: null, candidate });
71
+ }
72
+ const original = current.descriptor.stage === 'preparation' ? current : await this.#original(attempt, current);
73
+ return original.descriptor.equals(descriptor) ? original : new ReservationRefusal('preparation-mismatch');
74
+ }
75
+
76
+ async settle(attempt, evidence) {
77
+ if (attempt.preparation === null) {
78
+ return new ReservationRefusal('not-prepared');
79
+ }
80
+ const descriptor = await this.#objects.describe({ attempt, evidence, preparation: attempt.preparation });
81
+ let current = await this.verify(attempt);
82
+ if (current.descriptor.stage === 'preparation') {
83
+ const candidate = await this.#objects.write(descriptor);
84
+ current = await this.#install(attempt, { expected: current.revision, candidate });
85
+ }
86
+ return current.descriptor.equals(descriptor) ? current : new ReservationRefusal('settlement-mismatch');
87
+ }
88
+
89
+ async discardCancelled(attempt) {
90
+ if (!(attempt instanceof ReservationRecord) || attempt.phase !== 'cancelled') {
91
+ throw new InvalidOptionsError('Only a persisted cancelled attempt may have its pin removed');
92
+ }
93
+ const current = await this.read(attempt);
94
+ if (current === null) {
95
+ return;
96
+ }
97
+ try {
98
+ await this.#refs.deleteRef({ ref: await this.#ref(attempt), expectedOldOid: current.revision });
99
+ } catch (writeError) {
100
+ if (await this.#recover(attempt, writeError) !== null) {
101
+ throw writeError;
102
+ }
103
+ }
104
+ }
105
+
106
+ async #install(attempt, { expected, candidate }) {
107
+ try {
108
+ await this.#refs.updateRef({ ref: await this.#ref(attempt), newOid: candidate.revision, expectedOldOid: expected });
109
+ return candidate;
110
+ } catch (writeError) {
111
+ const current = await this.#recover(attempt, writeError);
112
+ if (current === null || current.revision === expected) {
113
+ throw writeError;
114
+ }
115
+ return current;
116
+ }
117
+ }
118
+
119
+ async #recover(attempt, writeError) {
120
+ try {
121
+ return await this.read(attempt);
122
+ } catch (inspectionError) {
123
+ throw new CasError('Custody mutation and inspection failed', ErrorCodes.GIT_ERROR, { writeError, inspectionError });
124
+ }
125
+ }
126
+
127
+ async #original(attempt, settlement) {
128
+ const original = await this.#objects.read(settlement.descriptor.preparation);
129
+ assertIdentity(attempt, original);
130
+ if (original.descriptor.stage !== 'preparation') {
131
+ throw new ReservationStorageError('Settlement must retain a preparation, not another settlement');
132
+ }
133
+ return original;
134
+ }
135
+
136
+ async #ref(attempt) {
137
+ if (!(attempt instanceof ReservationRecord)) {
138
+ throw new InvalidOptionsError('Custody operations require a validated attempt');
139
+ }
140
+ const route = await new ReservationKey(attempt.key).route(this.#crypto);
141
+ return `refs/cas/reservation-custody/${this.namespace}/${route}`;
142
+ }
143
+ }
144
+
145
+ function assertIdentity(attempt, generation) {
146
+ if (generation.descriptor.key !== attempt.key || generation.descriptor.binding !== attempt.binding) {
147
+ throw new ReservationStorageError('Custody pin belongs to another attempt identity');
148
+ }
149
+ }
@@ -0,0 +1,169 @@
1
+ import GitPersistencePort from '../../ports/GitPersistencePort.js';
2
+ import CryptoPort from '../../ports/CryptoPort.js';
3
+ import ReservationRecordCodecPort, { RESERVATION_RECORD_MAX_BYTES } from '../../ports/ReservationRecordCodecPort.js';
4
+ import InvalidOptionsError from '../errors/InvalidOptionsError.js';
5
+ import ReservationStorageError from '../errors/ReservationStorageError.js';
6
+ import Oid from '../value-objects/Oid.js';
7
+ import ReservationKey, { RESERVATION_ROUTE_DIGITS } from '../value-objects/ReservationKey.js';
8
+ import ReservationRecord from './ReservationRecord.js';
9
+ import ReservationIndexNode from './ReservationIndexNode.js';
10
+ import ReservationScan from './ReservationScan.js';
11
+
12
+ const NODE_BYTES = 2 * 1024;
13
+
14
+ /**
15
+ * Private immutable point index. It produces candidate trees, never publishes
16
+ * refs or admits capacity. The ledger owner enforces lifecycle and binding.
17
+ * Reads validate only the selected path, not every unvisited subtree.
18
+ */
19
+ export default class ReservationIndex {
20
+ #persistence;
21
+ #codec;
22
+ #crypto;
23
+
24
+ constructor({ persistence, codec, crypto }) {
25
+ if (!(persistence instanceof GitPersistencePort) || !(codec instanceof ReservationRecordCodecPort) ||
26
+ !(crypto instanceof CryptoPort)) {
27
+ throw new InvalidOptionsError('Reservation index requires persistence, record codec and crypto ports');
28
+ }
29
+ this.#persistence = persistence;
30
+ this.#codec = codec;
31
+ this.#crypto = crypto;
32
+ Object.freeze(this);
33
+ }
34
+
35
+ async get(root, key) {
36
+ const identity = new ReservationKey(key);
37
+ const route = await identity.route(this.#crypto);
38
+ const { leaf } = await this.#walk(root, route);
39
+ return leaf === null ? null : await this.#record(leaf, identity.value);
40
+ }
41
+
42
+ async empty() {
43
+ return checkedOid(await this.#persistence.writeTree([]));
44
+ }
45
+
46
+ async scan(root, request) {
47
+ const scan = new ReservationScan(request);
48
+ const complete = await this.#scanNode(checkedOid(root), '', scan);
49
+ if (!complete && scan.after === (request.cursor?.after ?? null)) {
50
+ throw new ReservationStorageError('Reservation traversal made no progress within its budget');
51
+ }
52
+ return scan.finish(complete);
53
+ }
54
+
55
+ async #scanNode(oid, prefix, scan) {
56
+ if (scan.skip(prefix)) {
57
+ return true;
58
+ }
59
+ if (!scan.visit()) {
60
+ return false;
61
+ }
62
+ if (prefix.length === RESERVATION_ROUTE_DIGITS) {
63
+ const record = await this.#readRecord(oid);
64
+ if (await new ReservationKey(record.key).route(this.#crypto) !== prefix) {
65
+ throw new ReservationStorageError('Reservation record does not belong at its indexed route');
66
+ }
67
+ scan.accept(record, prefix);
68
+ return true;
69
+ }
70
+ const node = await this.#node(oid, prefix.length);
71
+ if (prefix.length > 0 && node.entries.length === 0) {
72
+ throw new ReservationStorageError('Reservation index contains an empty internal branch');
73
+ }
74
+ for (const entry of node.entries) {
75
+ if (!await this.#scanNode(entry.oid, prefix + entry.name, scan)) {
76
+ return false;
77
+ }
78
+ }
79
+ return true;
80
+ }
81
+
82
+ async put(root, record) {
83
+ if (!(record instanceof ReservationRecord)) {
84
+ throw new InvalidOptionsError('Reservation index writes require a validated record');
85
+ }
86
+ const route = await new ReservationKey(record.key).route(this.#crypto);
87
+ const { nodes, leaf } = await this.#walk(root, route);
88
+ if (leaf !== null) {
89
+ await this.#record(leaf, record.key);
90
+ }
91
+ const bytes = this.#codec.encode(record);
92
+ if (!(bytes instanceof Uint8Array) || bytes.length > RESERVATION_RECORD_MAX_BYTES) {
93
+ throw new ReservationStorageError('Encoded reservation record exceeds its byte limit');
94
+ }
95
+ let oid = checkedOid(await this.#persistence.writeBlob(bytes));
96
+ assertFormat(record, oid.length);
97
+ if (root !== null && root.length !== oid.length) {
98
+ throw new ReservationStorageError('Reservation update changed Git object format');
99
+ }
100
+ for (let depth = RESERVATION_ROUTE_DIGITS - 1; depth >= 0; depth--) {
101
+ const node = nodes[depth] ?? new ReservationIndexNode({ entries: [], depth, oidLength: oid.length });
102
+ const updated = node.withChild(route[depth], oid);
103
+ const next = checkedOid(await this.#persistence.writeTree(updated.toTreeLines()));
104
+ if (next.length !== oid.length) {
105
+ throw new ReservationStorageError('Reservation tree writer changed Git object format');
106
+ }
107
+ oid = next;
108
+ }
109
+ return oid;
110
+ }
111
+
112
+ async #walk(root, route) {
113
+ let oid = root === null ? null : checkedOid(root);
114
+ const nodes = [];
115
+ for (let depth = 0; depth < RESERVATION_ROUTE_DIGITS && oid !== null; depth++) {
116
+ const node = await this.#node(oid, depth);
117
+ nodes.push(node);
118
+ oid = node.child(route[depth]);
119
+ }
120
+ return { nodes, leaf: nodes.length === RESERVATION_ROUTE_DIGITS ? oid : null };
121
+ }
122
+
123
+ async #record(oid, key) {
124
+ const record = await this.#readRecord(oid);
125
+ if (record.key !== key) {
126
+ throw new ReservationStorageError('Reservation route resolves to another key');
127
+ }
128
+ return record;
129
+ }
130
+
131
+ async #node(oid, depth) {
132
+ await this.#assertObject(oid, { type: 'tree', maxBytes: NODE_BYTES });
133
+ return new ReservationIndexNode({ entries: await this.#persistence.readTree(oid), depth, oidLength: oid.length });
134
+ }
135
+
136
+ async #readRecord(oid) {
137
+ await this.#assertObject(oid, { type: 'blob', maxBytes: RESERVATION_RECORD_MAX_BYTES });
138
+ const record = this.#codec.decode(await this.#persistence.readBlob(oid, RESERVATION_RECORD_MAX_BYTES));
139
+ if (!(record instanceof ReservationRecord)) {
140
+ throw new ReservationStorageError('Reservation route resolves to an invalid record');
141
+ }
142
+ assertFormat(record, oid.length);
143
+ return record;
144
+ }
145
+
146
+ async #assertObject(oid, { type, maxBytes }) {
147
+ const [actualType, size] = await Promise.all([
148
+ this.#persistence.readObjectType(oid), this.#persistence.readObjectSize(oid),
149
+ ]);
150
+ if (actualType !== type || !Number.isSafeInteger(size) || size < 0 || size > maxBytes) {
151
+ throw new ReservationStorageError('Reservation object type or byte bound is invalid', { oid, type, size });
152
+ }
153
+ }
154
+ }
155
+
156
+ function checkedOid(value) {
157
+ if (!Oid.isValid(value) || Oid.from(value).toString() !== value) {
158
+ throw new ReservationStorageError('Reservation index requires a canonical Git OID');
159
+ }
160
+ return value;
161
+ }
162
+
163
+ function assertFormat(record, oidLength) {
164
+ for (const oid of [record.preparation, record.settlement]) {
165
+ if (oid !== null && oid.length !== oidLength) {
166
+ throw new ReservationStorageError('Reservation evidence and index use different Git object formats');
167
+ }
168
+ }
169
+ }