@git-stunts/git-cas 6.1.0 → 6.3.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 (69) hide show
  1. package/ARCHITECTURE.md +116 -3
  2. package/CHANGELOG.md +117 -2
  3. package/GUIDE.md +114 -13
  4. package/README.md +60 -4
  5. package/UPGRADING.md +75 -0
  6. package/build-info.json +2 -2
  7. package/docs/API.md +867 -16
  8. package/docs/releases/v6.2.0.md +131 -0
  9. package/docs/releases/v6.3.0.md +96 -0
  10. package/index.d.ts +972 -2
  11. package/index.js +326 -1
  12. package/package.json +4 -2
  13. package/src/domain/errors/Codes.js +39 -0
  14. package/src/domain/helpers/assertCanonicalTimestamp.js +15 -0
  15. package/src/domain/helpers/handleTarget.js +48 -0
  16. package/src/domain/helpers/isCanonicalCollectionKey.js +35 -0
  17. package/src/domain/services/AssetService.js +213 -0
  18. package/src/domain/services/BundleDescriptorCodec.js +286 -0
  19. package/src/domain/services/BundleFanoutBuilder.js +247 -0
  20. package/src/domain/services/BundleService.js +848 -0
  21. package/src/domain/services/CacheAcquisitionInventory.js +123 -0
  22. package/src/domain/services/CacheAcquisitionRegistry.js +188 -0
  23. package/src/domain/services/CacheCandidateHeap.js +71 -0
  24. package/src/domain/services/CacheIndex.js +362 -0
  25. package/src/domain/services/CacheMetadataCodec.js +164 -0
  26. package/src/domain/services/CachePolicyEnforcer.js +144 -0
  27. package/src/domain/services/CacheSet.js +754 -0
  28. package/src/domain/services/CacheSetRegistry.js +95 -0
  29. package/src/domain/services/CasService.d.ts +2 -1
  30. package/src/domain/services/ExpiringSet.js +496 -0
  31. package/src/domain/services/ExpiringSetIndex.js +254 -0
  32. package/src/domain/services/ExpiringSetMetadataCodec.js +160 -0
  33. package/src/domain/services/ExpiringSetRegistry.js +101 -0
  34. package/src/domain/services/PageService.js +175 -0
  35. package/src/domain/services/PublicationService.js +315 -0
  36. package/src/domain/services/RepositoryDoctor.js +676 -0
  37. package/src/domain/services/RetentionService.js +120 -0
  38. package/src/domain/services/RootSet.js +10 -6
  39. package/src/domain/services/RootSetMetadataCodec.js +8 -2
  40. package/src/domain/services/RootSetPersistence.js +3 -2
  41. package/src/domain/services/StagingEvidence.js +39 -0
  42. package/src/domain/value-objects/ApplicationHandle.js +40 -0
  43. package/src/domain/value-objects/AssetHandle.js +163 -0
  44. package/src/domain/value-objects/BundleHandle.js +32 -0
  45. package/src/domain/value-objects/BundleLimits.js +80 -0
  46. package/src/domain/value-objects/BundlePath.js +78 -0
  47. package/src/domain/value-objects/CacheAcquisition.js +88 -0
  48. package/src/domain/value-objects/CacheAcquisitionRef.js +129 -0
  49. package/src/domain/value-objects/CacheHit.js +93 -0
  50. package/src/domain/value-objects/CacheKey.js +32 -0
  51. package/src/domain/value-objects/CachePolicy.js +59 -0
  52. package/src/domain/value-objects/CacheSetRef.js +40 -0
  53. package/src/domain/value-objects/CollectionNamespace.js +54 -0
  54. package/src/domain/value-objects/ExpiringMarker.js +81 -0
  55. package/src/domain/value-objects/ExpiringSetKey.js +28 -0
  56. package/src/domain/value-objects/ExpiringSetRef.js +42 -0
  57. package/src/domain/value-objects/OpaqueHandle.js +171 -0
  58. package/src/domain/value-objects/PageHandle.js +34 -0
  59. package/src/domain/value-objects/RetentionWitness.js +106 -0
  60. package/src/domain/value-objects/StagedAsset.js +63 -0
  61. package/src/domain/value-objects/StagedBundle.js +66 -0
  62. package/src/domain/value-objects/StagedPage.js +47 -0
  63. package/src/infrastructure/adapters/GitPersistenceAdapter.js +48 -20
  64. package/src/infrastructure/adapters/GitRefAdapter.js +318 -7
  65. package/src/infrastructure/adapters/GitRepositoryInspectionAdapter.js +182 -0
  66. package/src/package-version.js +1 -1
  67. package/src/ports/GitPersistencePort.js +11 -1
  68. package/src/ports/GitRefPort.js +46 -0
  69. package/src/ports/RepositoryInspectionPort.js +36 -0
@@ -1,7 +1,8 @@
1
1
  import { Policy } from '@git-stunts/alfred';
2
2
  import GitRefPort from '../../ports/GitRefPort.js';
3
3
  import { CasError, ErrorCodes } from '../../domain/errors/index.js';
4
- import { isGitMissingRefError } from '../../domain/helpers/gitRefErrors.js';
4
+ import { errorDetailsText, isGitMissingRefError } from '../../domain/helpers/gitRefErrors.js';
5
+ import Oid from '../../domain/value-objects/Oid.js';
5
6
 
6
7
  /**
7
8
  * Default resilience policy: 30 s timeout (no retry).
@@ -12,7 +13,8 @@ import { isGitMissingRefError } from '../../domain/helpers/gitRefErrors.js';
12
13
  * an unref'd timer that allows Node to exit before the next attempt starts.
13
14
  */
14
15
  const DEFAULT_POLICY = Policy.timeout(30_000);
15
- const GIT_NULL_OID = '0'.repeat(40);
16
+ const FORBIDDEN_REF_CHARACTERS = new Set(['~', '^', ':', '?', '*', '[', '\\']);
17
+ const MAX_REF_ITERATION_LIMIT = 1001;
16
18
 
17
19
  /**
18
20
  * {@link GitRefPort} implementation backed by `@git-stunts/plumbing`.
@@ -89,13 +91,15 @@ export default class GitRefAdapter extends GitRefPort {
89
91
  * @param {Object} options
90
92
  * @param {string} options.treeOid - Tree OID for the commit.
91
93
  * @param {string|null} [options.parentOid] - Parent commit OID.
94
+ * @param {string[]} [options.parentOids] - Ordered parent commit OIDs.
92
95
  * @param {string} options.message - Commit message.
93
96
  * @returns {Promise<string>} The new commit OID.
94
97
  */
95
- async createCommit({ treeOid, parentOid, message }) {
98
+ async createCommit({ treeOid, parentOid, parentOids, message }) {
96
99
  const args = ['commit-tree', treeOid, '-m', message];
97
- if (parentOid) {
98
- args.push('-p', parentOid);
100
+ const parents = parentOids ?? (parentOid ? [parentOid] : []);
101
+ for (const parent of parents) {
102
+ args.push('-p', parent);
99
103
  }
100
104
  return this.policy.execute(() =>
101
105
  this.plumbing.execute({ args }),
@@ -111,12 +115,319 @@ export default class GitRefAdapter extends GitRefPort {
111
115
  * @returns {Promise<void>}
112
116
  */
113
117
  async updateRef({ ref, newOid, expectedOldOid }) {
114
- const args = ['update-ref', ref, newOid];
118
+ assertRefName(ref);
119
+ const symbolicTarget = await this.#resolveSymbolicRef(ref);
120
+ if (symbolicTarget !== null) {
121
+ throw refConflict({
122
+ ref,
123
+ expectedOldOid: expectedOldOid ?? null,
124
+ actualOldOid: null,
125
+ actualSymref: symbolicTarget,
126
+ });
127
+ }
128
+ const args = ['update-ref', '--no-deref', ref, newOid];
115
129
  if (expectedOldOid !== undefined) {
116
- args.push(expectedOldOid ?? GIT_NULL_OID);
130
+ args.push(expectedOldOid ?? '0'.repeat(newOid.length));
117
131
  }
118
132
  await this.policy.execute(() =>
119
133
  this.plumbing.execute({ args }),
120
134
  );
121
135
  }
136
+
137
+ /** @override */
138
+ async anchorRef({ sourceRef, expectedSourceOid, targetRef }) {
139
+ assertRefName(sourceRef);
140
+ assertRefName(targetRef);
141
+ const generation = Oid.from(expectedSourceOid).toString();
142
+ // Git 2.43 cannot atomically assert ref type. Preflight rejects observed
143
+ // symrefs; --no-deref contains any subsequent race to the managed names.
144
+ if (
145
+ await this.#resolveSymbolicRef(sourceRef) !== null ||
146
+ await this.#resolveSymbolicRef(targetRef) !== null
147
+ ) {
148
+ return false;
149
+ }
150
+ const input = [
151
+ 'start',
152
+ `verify ${sourceRef} ${generation}`,
153
+ `create ${targetRef} ${generation}`,
154
+ 'prepare',
155
+ 'commit',
156
+ '',
157
+ ].join('\n');
158
+ try {
159
+ await this.policy.execute(() =>
160
+ this.plumbing.execute({ args: ['update-ref', '--no-deref', '--stdin'], input }),
161
+ );
162
+ return true;
163
+ } catch (error) {
164
+ if (isUpdateRefConflict(error, [sourceRef, targetRef])) {
165
+ return false;
166
+ }
167
+ throw error;
168
+ }
169
+ }
170
+
171
+ /** @override */
172
+ async deleteRef({ ref, expectedOldOid }) {
173
+ assertRefName(ref);
174
+ const expectedGeneration = Oid.from(expectedOldOid).toString();
175
+ // A post-probe type race may delete this managed symref name, never its
176
+ // referent. The expected OID still gates the no-dereference mutation.
177
+ const symbolicTarget = await this.#resolveSymbolicRef(ref);
178
+ if (symbolicTarget !== null) {
179
+ throw refConflict({
180
+ ref,
181
+ expectedOldOid: expectedGeneration,
182
+ actualOldOid: null,
183
+ actualSymref: symbolicTarget,
184
+ });
185
+ }
186
+ try {
187
+ await this.policy.execute(() =>
188
+ this.plumbing.execute({
189
+ args: ['update-ref', '--no-deref', '-d', ref, expectedGeneration],
190
+ }),
191
+ );
192
+ } catch (error) {
193
+ if (!isUpdateRefConflict(error, [ref])) {
194
+ throw error;
195
+ }
196
+ const racedSymbolicTarget = await this.#resolveSymbolicRef(ref);
197
+ if (racedSymbolicTarget !== null) {
198
+ throw refConflict({
199
+ ref,
200
+ expectedOldOid: expectedGeneration,
201
+ actualOldOid: null,
202
+ actualSymref: racedSymbolicTarget,
203
+ originalError: error,
204
+ });
205
+ }
206
+ const actual = await this.#inspectDirectRef(ref);
207
+ throw refConflict({
208
+ ref,
209
+ expectedOldOid: expectedGeneration,
210
+ actualOldOid: actual?.oid ?? null,
211
+ actualSymref: actual?.symref ?? null,
212
+ originalError: error,
213
+ });
214
+ }
215
+ return true;
216
+ }
217
+
218
+ /** @override */
219
+ async *iterateRefs({ prefix = 'refs/', limit } = {}) {
220
+ assertRefPrefix(prefix);
221
+ assertRefIterationLimit(limit);
222
+ if (typeof this.plumbing?.executeStream !== 'function') {
223
+ throw new CasError(
224
+ 'Git ref inventory requires streaming plumbing',
225
+ ErrorCodes.GIT_ERROR,
226
+ { prefix },
227
+ );
228
+ }
229
+ const stream = await this.policy.execute(() =>
230
+ this.plumbing.executeStream({
231
+ args: [
232
+ 'for-each-ref',
233
+ '--format=%(refname)%09%(objectname)%09%(symref)',
234
+ `--count=${limit}`,
235
+ prefix,
236
+ ],
237
+ }),
238
+ );
239
+ for await (const line of consumeRefLines(stream)) {
240
+ yield parseIteratedRef(prefix, line);
241
+ }
242
+ }
243
+
244
+ async #inspectDirectRef(ref) {
245
+ const output = await this.policy.execute(() =>
246
+ this.plumbing.execute({
247
+ args: [
248
+ 'for-each-ref',
249
+ '--format=%(refname)%09%(objectname)%09%(symref)',
250
+ '--count=1',
251
+ ref,
252
+ ],
253
+ }),
254
+ );
255
+ const line = String(output).replace(/\r?\n$/u, '');
256
+ if (line.length === 0) {
257
+ return null;
258
+ }
259
+ const fields = line.split('\t');
260
+ if (
261
+ (fields.length !== 2 && fields.length !== 3) ||
262
+ fields[0] !== ref ||
263
+ !Oid.isValid(fields[1]) ||
264
+ (fields[2] !== undefined && fields[2] !== '' && !isValidRefSyntax(fields[2], false))
265
+ ) {
266
+ throw invalidRefInventory(ref, line);
267
+ }
268
+ return Object.freeze({
269
+ ref,
270
+ oid: Oid.from(fields[1]).toString(),
271
+ symref: fields[2] || null,
272
+ });
273
+ }
274
+
275
+ async #resolveSymbolicRef(ref) {
276
+ try {
277
+ const output = await this.policy.execute(() =>
278
+ this.plumbing.execute({ args: ['symbolic-ref', '--quiet', ref] }),
279
+ );
280
+ const target = String(output).trim();
281
+ return target.length > 0 ? target : null;
282
+ } catch (error) {
283
+ if (isQuietSymbolicRefMiss(error, ref)) {
284
+ return null;
285
+ }
286
+ throw error;
287
+ }
288
+ }
289
+ }
290
+
291
+ function assertRefPrefix(prefix) {
292
+ assertRefSyntax(prefix, { allowTrailingSlash: true });
293
+ }
294
+
295
+ function assertRefName(ref) {
296
+ assertRefSyntax(ref, { allowTrailingSlash: false });
297
+ }
298
+
299
+ function assertRefIterationLimit(limit) {
300
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_REF_ITERATION_LIMIT) {
301
+ throw new CasError(
302
+ `Git ref inventory limit must be between 1 and ${MAX_REF_ITERATION_LIMIT}`,
303
+ ErrorCodes.GIT_ERROR,
304
+ { limit },
305
+ );
306
+ }
307
+ }
308
+
309
+ function assertRefSyntax(value, { allowTrailingSlash }) {
310
+ if (typeof value !== 'string' || !isValidRefSyntax(value, allowTrailingSlash)) {
311
+ throw invalidRefName(value);
312
+ }
313
+ }
314
+
315
+ function isValidRefSyntax(value, allowTrailingSlash) {
316
+ if (!value.startsWith('refs/') || (!allowTrailingSlash && value.endsWith('/'))) {
317
+ return false;
318
+ }
319
+ if (['//', '..', '@{'].some((pattern) => value.includes(pattern))) {
320
+ return false;
321
+ }
322
+ if (value.endsWith('.') || hasForbiddenRefCharacter(value)) {
323
+ return false;
324
+ }
325
+ const trimmed = allowTrailingSlash && value.endsWith('/') ? value.slice(0, -1) : value;
326
+ return !trimmed.split('/').some(isInvalidRefSegment);
327
+ }
328
+
329
+ function isInvalidRefSegment(part) {
330
+ return part.length === 0 || part.startsWith('.') || part.endsWith('.lock');
331
+ }
332
+
333
+ function hasForbiddenRefCharacter(value) {
334
+ return typeof value === 'string' && [...value].some((character) => {
335
+ const code = character.codePointAt(0);
336
+ return code <= 0x20 || code === 0x7f || FORBIDDEN_REF_CHARACTERS.has(character);
337
+ });
338
+ }
339
+
340
+ async function* consumeRefLines(stream) {
341
+ const decoder = new globalThis.TextDecoder();
342
+ let pending = '';
343
+ for await (const chunk of stream) {
344
+ pending += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
345
+ let newline = pending.indexOf('\n');
346
+ while (newline !== -1) {
347
+ const line = pending.slice(0, newline).replace(/\r$/u, '');
348
+ pending = pending.slice(newline + 1);
349
+ if (line.length > 0) {
350
+ yield line;
351
+ }
352
+ newline = pending.indexOf('\n');
353
+ }
354
+ }
355
+ pending += decoder.decode();
356
+ if (pending.length > 0) {
357
+ yield pending.replace(/\r$/u, '');
358
+ }
359
+ const result = await stream.finished;
360
+ if (result?.code !== 0) {
361
+ throw new CasError('Git ref inventory failed', ErrorCodes.GIT_ERROR, {
362
+ stderr: result?.stderr,
363
+ });
364
+ }
365
+ }
366
+
367
+ function invalidRefInventory(prefix, output) {
368
+ return new CasError(
369
+ 'Git ref inventory returned invalid structured output',
370
+ ErrorCodes.GIT_ERROR,
371
+ { prefix, output: String(output) },
372
+ );
373
+ }
374
+
375
+ function parseIteratedRef(prefix, line) {
376
+ const fields = line.split('\t');
377
+ if (!isValidIteratedRef(fields, prefix)) {
378
+ throw invalidRefInventory(prefix, line);
379
+ }
380
+ return Object.freeze({
381
+ ref: fields[0],
382
+ oid: Oid.from(fields[1]).toString(),
383
+ symref: fields[2] || null,
384
+ });
385
+ }
386
+
387
+ function isValidIteratedRef(fields, prefix) {
388
+ return fields.length === 3
389
+ && fields[0].startsWith(prefix)
390
+ && Oid.isValid(fields[1])
391
+ && (fields[2] === '' || isValidRefSyntax(fields[2], false));
392
+ }
393
+
394
+ function invalidRefName(ref) {
395
+ return new CasError('Git ref name or prefix is invalid', ErrorCodes.GIT_ERROR, { ref });
396
+ }
397
+
398
+ function isUpdateRefConflict(error, refs) {
399
+ const text = errorDetailsText(error).toLowerCase();
400
+ return refs.some((ref) => text.includes(ref.toLowerCase()))
401
+ && (
402
+ text.includes('cannot lock ref') ||
403
+ text.includes('but expected') ||
404
+ text.includes('reference already exists') ||
405
+ text.includes('unable to resolve reference') ||
406
+ text.includes('zero <oldvalue>') ||
407
+ text.includes('is a symref')
408
+ );
409
+ }
410
+
411
+ function isQuietSymbolicRefMiss(error, ref) {
412
+ const details = error instanceof Error && error.details && typeof error.details === 'object'
413
+ ? error.details
414
+ : {};
415
+ return details.code === 1
416
+ && Array.isArray(details.args)
417
+ && details.args[0] === 'symbolic-ref'
418
+ && details.args.at(-1) === ref;
419
+ }
420
+
421
+ function refConflict({
422
+ ref,
423
+ expectedOldOid,
424
+ actualOldOid,
425
+ actualSymref = null,
426
+ originalError,
427
+ }) {
428
+ return new CasError(
429
+ `Git ref changed before checked mutation: ${ref}`,
430
+ ErrorCodes.GIT_REF_CONFLICT,
431
+ { ref, expectedOldOid, actualOldOid, actualSymref, originalError },
432
+ );
122
433
  }
@@ -0,0 +1,182 @@
1
+ import { Policy } from '@git-stunts/alfred';
2
+ import { CasError, ErrorCodes } from '../../domain/errors/index.js';
3
+ import Oid from '../../domain/value-objects/Oid.js';
4
+ import RepositoryInspectionPort from '../../ports/RepositoryInspectionPort.js';
5
+
6
+ const DEFAULT_POLICY = Policy.timeout(30_000);
7
+ const DEFAULT_FULL_SCAN_POLICY = Policy.timeout(5 * 60_000);
8
+ const OBJECT_TYPES = new Set(['blob', 'tree', 'commit', 'tag']);
9
+ const OBJECT_FORMAT = '--batch-check=%(objectname) %(objecttype) %(objectsize) %(objectsize:disk)';
10
+
11
+ /** Non-mutating repository inspection backed by safe Git plumbing commands. */
12
+ export default class GitRepositoryInspectionAdapter extends RepositoryInspectionPort {
13
+ constructor({ plumbing, policy }) {
14
+ super();
15
+ if (
16
+ typeof plumbing?.execute !== 'function' ||
17
+ typeof plumbing?.executeStream !== 'function' ||
18
+ typeof plumbing?.inspectPrunableObjects !== 'function'
19
+ ) {
20
+ throw new CasError(
21
+ 'Repository inspection requires GitPlumbing 3.1.0 or newer',
22
+ ErrorCodes.REPOSITORY_INSPECTION_INVALID
23
+ );
24
+ }
25
+ this.plumbing = plumbing;
26
+ this.policy = policy ?? DEFAULT_POLICY;
27
+ this.fullScanPolicy = policy ?? DEFAULT_FULL_SCAN_POLICY;
28
+ Object.freeze(this);
29
+ }
30
+
31
+ async *iterateObjects() {
32
+ const stream = await this.#stream({
33
+ args: ['cat-file', '--batch-all-objects', OBJECT_FORMAT],
34
+ });
35
+ for await (const line of consumeLines(stream, 'object inventory')) {
36
+ const fields = line.split(' ');
37
+ if (fields.length !== 4) {
38
+ throw invalidOutput('object inventory', line);
39
+ }
40
+ const [oid, type] = fields;
41
+ yield Object.freeze({
42
+ oid: parseOid(oid, 'object inventory', line),
43
+ type: parseType(type, 'object inventory', line),
44
+ logicalBytes: parseBytes(fields[2], 'object inventory', line),
45
+ physicalBytes: parseBytes(fields[3], 'object inventory', line),
46
+ });
47
+ }
48
+ }
49
+
50
+ async *iterateReachableObjectIds() {
51
+ const stream = await this.#stream({
52
+ args: ['rev-list', '--all', '--reflog', '--objects', '--no-object-names'],
53
+ });
54
+ for await (const line of consumeLines(stream, 'reachable object inventory')) {
55
+ yield parseOid(line, 'reachable object inventory', line);
56
+ }
57
+ }
58
+
59
+ async *iteratePrunableObjects({ expiresBefore }) {
60
+ const stream = await this.policy.execute(() =>
61
+ this.plumbing.inspectPrunableObjects({ expiresBefore })
62
+ );
63
+ for await (const line of consumeLines(stream, 'prunable object inspection')) {
64
+ const fields = line.trim().split(/\s+/u);
65
+ if (fields.length !== 2) {
66
+ throw invalidOutput('prunable object inspection', line);
67
+ }
68
+ yield Object.freeze({
69
+ oid: parseOid(fields[0], 'prunable object inspection', line),
70
+ type: parseType(fields[1], 'prunable object inspection', line),
71
+ });
72
+ }
73
+ }
74
+
75
+ async *iterateRefs({ prefix = 'refs/' } = {}) {
76
+ if (typeof prefix !== 'string' || !prefix.startsWith('refs/') || prefix.includes('..')) {
77
+ throw new CasError(
78
+ 'Git ref inventory prefix is invalid',
79
+ ErrorCodes.REPOSITORY_INSPECTION_INVALID,
80
+ { prefix },
81
+ );
82
+ }
83
+ const stream = await this.#stream({
84
+ args: ['for-each-ref', '--format=%(refname)%09%(objectname)%09%(symref)', prefix],
85
+ });
86
+ for await (const line of consumeLines(stream, 'ref inventory')) {
87
+ yield parseRefRecord(line);
88
+ }
89
+ }
90
+
91
+ async reachablePhysicalBytes() {
92
+ const output = await this.fullScanPolicy.execute(() =>
93
+ this.plumbing.execute({
94
+ args: ['rev-list', '--all', '--reflog', '--objects', '--disk-usage'],
95
+ })
96
+ );
97
+ return parseBytes(String(output).trim(), 'reachable disk usage', output);
98
+ }
99
+
100
+ async #stream(options) {
101
+ return await this.policy.execute(() => this.plumbing.executeStream(options));
102
+ }
103
+ }
104
+
105
+ async function* consumeLines(stream, operation) {
106
+ const decoder = new globalThis.TextDecoder();
107
+ let pending = '';
108
+ for await (const chunk of stream) {
109
+ pending += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
110
+ let newline = pending.indexOf('\n');
111
+ while (newline !== -1) {
112
+ const line = pending.slice(0, newline).replace(/\r$/u, '');
113
+ pending = pending.slice(newline + 1);
114
+ if (line.length > 0) {
115
+ yield line;
116
+ }
117
+ newline = pending.indexOf('\n');
118
+ }
119
+ }
120
+ pending += decoder.decode();
121
+ if (pending.length > 0) {
122
+ yield pending.replace(/\r$/u, '');
123
+ }
124
+ const result = await stream.finished;
125
+ if (result?.code !== 0) {
126
+ throw new CasError(`Git ${operation} failed`, ErrorCodes.REPOSITORY_INSPECTION_INVALID, {
127
+ operation,
128
+ stderr: result?.stderr,
129
+ });
130
+ }
131
+ }
132
+
133
+ function parseOid(value, operation, output) {
134
+ if (!Oid.isValid(value)) {
135
+ throw invalidOutput(operation, output);
136
+ }
137
+ return Oid.from(value).toString();
138
+ }
139
+
140
+ function parseRefRecord(line) {
141
+ const fields = line.split('\t');
142
+ if (!isValidRefRecord(fields)) {
143
+ throw invalidOutput('ref inventory', line);
144
+ }
145
+ return Object.freeze({
146
+ ref: fields[0],
147
+ oid: parseOid(fields[1], 'ref inventory', line),
148
+ symref: fields[2] || null,
149
+ });
150
+ }
151
+
152
+ function isValidRefRecord(fields) {
153
+ return fields.length === 3
154
+ && fields[0].startsWith('refs/')
155
+ && (fields[2] === '' || fields[2].startsWith('refs/'));
156
+ }
157
+
158
+ function parseType(value, operation, output) {
159
+ if (!OBJECT_TYPES.has(value)) {
160
+ throw invalidOutput(operation, output);
161
+ }
162
+ return value;
163
+ }
164
+
165
+ function parseBytes(value, operation, output) {
166
+ if (!/^\d+$/u.test(String(value))) {
167
+ throw invalidOutput(operation, output);
168
+ }
169
+ const bytes = Number(value);
170
+ if (!Number.isSafeInteger(bytes)) {
171
+ throw invalidOutput(operation, output);
172
+ }
173
+ return bytes;
174
+ }
175
+
176
+ function invalidOutput(operation, output) {
177
+ return new CasError(
178
+ `Git ${operation} returned invalid structured output`,
179
+ ErrorCodes.REPOSITORY_INSPECTION_INVALID,
180
+ { operation, output: String(output) }
181
+ );
182
+ }
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '6.1.0';
1
+ export const PACKAGE_VERSION = '6.3.0';
@@ -24,9 +24,10 @@ export default class GitPersistencePort {
24
24
  /**
25
25
  * Reads a Git blob by its OID.
26
26
  * @param {string} _oid - Git object ID.
27
+ * @param {number} [_maxBytes] - Maximum bytes the adapter may materialize.
27
28
  * @returns {Promise<Uint8Array>} The blob content.
28
29
  */
29
- async readBlob(_oid) {
30
+ async readBlob(_oid, _maxBytes) {
30
31
  throw new Error('Not implemented');
31
32
  }
32
33
 
@@ -77,4 +78,13 @@ export default class GitPersistencePort {
77
78
  async readObjectType(_oid) {
78
79
  throw new Error('Not implemented');
79
80
  }
81
+
82
+ /**
83
+ * Reads the Git object size without materializing object content.
84
+ * @param {string} _oid - Git object ID.
85
+ * @returns {Promise<number>} Object size in bytes.
86
+ */
87
+ async readObjectSize(_oid) {
88
+ throw new Error('Not implemented');
89
+ }
80
90
  }
@@ -1,3 +1,6 @@
1
+ import createCasError from '../domain/errors/createCasError.js';
2
+ import { ErrorCodes } from '../domain/errors/index.js';
3
+
1
4
  /**
2
5
  * Abstract port for Git ref and commit operations.
3
6
  * @abstract
@@ -36,6 +39,7 @@ export default class GitRefPort {
36
39
  * @param {Object} _options
37
40
  * @param {string} _options.treeOid - Tree OID for the commit.
38
41
  * @param {string|null} [_options.parentOid] - Parent commit OID (null for root commit).
42
+ * @param {string[]} [_options.parentOids] - Ordered parent commit OIDs.
39
43
  * @param {string} _options.message - Commit message.
40
44
  * @returns {Promise<string>} The new commit OID.
41
45
  */
@@ -54,4 +58,46 @@ export default class GitRefPort {
54
58
  async updateRef(_options) {
55
59
  throw new Error('Not implemented');
56
60
  }
61
+
62
+ /**
63
+ * Atomically verifies one source ref and creates a new ref to its generation.
64
+ * @param {Object} _options
65
+ * @param {string} _options.sourceRef
66
+ * @param {string} _options.expectedSourceOid
67
+ * @param {string} _options.targetRef
68
+ * @returns {Promise<boolean>} Whether the source generation was anchored.
69
+ */
70
+ async anchorRef(_options) {
71
+ throw unsupportedAcquisitionCapability('anchorRef');
72
+ }
73
+
74
+ /**
75
+ * Deletes a ref only when it still names the expected object.
76
+ * @param {Object} _options
77
+ * @param {string} _options.ref
78
+ * @param {string} _options.expectedOldOid
79
+ * @returns {Promise<boolean>} Whether the ref existed and was deleted.
80
+ */
81
+ async deleteRef(_options) {
82
+ throw unsupportedAcquisitionCapability('deleteRef');
83
+ }
84
+
85
+ /**
86
+ * Streams refs below a canonical Git ref prefix.
87
+ * @param {Object} _options
88
+ * @param {string} [_options.prefix]
89
+ * @param {number} _options.limit Maximum records to request from Git.
90
+ * @returns {AsyncIterable<{ref: string, oid: string, symref: string|null}>}
91
+ */
92
+ iterateRefs(_options) {
93
+ throw unsupportedAcquisitionCapability('iterateRefs');
94
+ }
95
+ }
96
+
97
+ function unsupportedAcquisitionCapability(capability) {
98
+ return createCasError(
99
+ `Git ref adapter does not implement cache acquisition capability: ${capability}`,
100
+ ErrorCodes.CACHE_ACQUISITION_INVALID,
101
+ { capability },
102
+ );
57
103
  }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Abstract port for non-mutating, repository-wide Git object inspection.
3
+ * @abstract
4
+ */
5
+ export default class RepositoryInspectionPort {
6
+ /** @returns {AsyncIterable<{ oid: string, type: string, logicalBytes: number, physicalBytes: number }>} */
7
+ iterateObjects() {
8
+ throw new Error('Not implemented');
9
+ }
10
+
11
+ /** @returns {AsyncIterable<string>} */
12
+ iterateReachableObjectIds() {
13
+ throw new Error('Not implemented');
14
+ }
15
+
16
+ /**
17
+ * @param {{ expiresBefore: string }} _options
18
+ * @returns {AsyncIterable<{ oid: string, type: string }>}
19
+ */
20
+ iteratePrunableObjects(_options) {
21
+ throw new Error('Not implemented');
22
+ }
23
+
24
+ /**
25
+ * @param {{ prefix?: string }} [_options]
26
+ * @returns {AsyncIterable<{ ref: string, oid: string, symref: string|null }>}
27
+ */
28
+ iterateRefs(_options) {
29
+ throw new Error('Not implemented');
30
+ }
31
+
32
+ /** @returns {Promise<number>} */
33
+ async reachablePhysicalBytes() {
34
+ throw new Error('Not implemented');
35
+ }
36
+ }