@git-stunts/git-cas 6.5.5 → 6.5.7

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.
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import { statSync } from 'node:fs';
7
- import { CLEAR_LINE_RETURN, progressBar } from '@flyingrobots/bijou';
7
+ import { CLEAR_LINE_RETURN, cursorGuard, progressBar } from '@flyingrobots/bijou';
8
8
  import { getCliContext } from './context.js';
9
9
 
10
10
  /**
@@ -43,7 +43,13 @@ function formatBytes(bytes) {
43
43
  * @param {import('@flyingrobots/bijou').BijouContext} [options.ctx] - Context override.
44
44
  * @returns {ProgressTracker}
45
45
  */
46
- export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize, ctx: providedCtx }) {
46
+ export function createStoreProgress({
47
+ filePath,
48
+ chunkSize,
49
+ quiet,
50
+ fileSize: providedSize,
51
+ ctx: providedCtx,
52
+ }) {
47
53
  if (quiet) {
48
54
  return { attach() {}, detach() {} };
49
55
  }
@@ -92,6 +98,7 @@ export function createRestoreProgress({ totalChunks, quiet, ctx: providedCtx })
92
98
  * @property {number | null} startTime
93
99
  * @property {Observer | null} service
94
100
  * @property {((evt: { size: number }) => void) | null} handler
101
+ * @property {import('@flyingrobots/bijou').CursorHideHandle | null} cursorHandle
95
102
  */
96
103
 
97
104
  /**
@@ -102,18 +109,77 @@ export function createRestoreProgress({ totalChunks, quiet, ctx: providedCtx })
102
109
  * @param {{ ctx: import('@flyingrobots/bijou').BijouContext, totalChunks: number, label: string, width: number }} deps
103
110
  */
104
111
  function handleChunkEvent({ size }, state, deps) {
105
- if (!state.startTime) { state.startTime = Date.now(); }
112
+ if (!state.startTime) {
113
+ state.startTime = Date.now();
114
+ }
106
115
  state.chunksProcessed++;
107
116
  state.bytesProcessed += size;
117
+ renderProgress(state, deps);
118
+ }
119
+
120
+ /**
121
+ * Render the current tracker state without mutating its counters.
122
+ *
123
+ * @param {TrackerState} state
124
+ * @param {{ ctx: import('@flyingrobots/bijou').BijouContext, totalChunks: number, label: string, width: number }} deps
125
+ */
126
+ function renderProgress(state, deps) {
108
127
  const pct = (state.chunksProcessed / deps.totalChunks) * 100;
109
- const elapsed = (Date.now() - state.startTime) / 1000;
128
+ const elapsed = state.startTime ? (Date.now() - state.startTime) / 1000 : 0;
110
129
  const throughput = elapsed > 0 ? state.bytesProcessed / elapsed : 0;
111
130
  if (deps.ctx.mode === 'interactive') {
112
131
  const status = ` ${deps.label} ${state.chunksProcessed}/${deps.totalChunks} ${formatBytes(throughput)}/s `;
113
132
  const barStr = progressBar(pct, { width: deps.width, showPercent: false, ctx: deps.ctx });
114
133
  deps.ctx.io.writeError(`${CLEAR_LINE_RETURN}${status}${barStr}`);
115
- } else if (state.chunksProcessed === 1 || state.chunksProcessed === deps.totalChunks || state.chunksProcessed % 10 === 0) {
116
- deps.ctx.io.writeError(`${deps.label} ${state.chunksProcessed}/${deps.totalChunks} ${Math.round(pct)}%\n`);
134
+ } else if (
135
+ state.chunksProcessed === 1 ||
136
+ state.chunksProcessed === deps.totalChunks ||
137
+ state.chunksProcessed % 10 === 0
138
+ ) {
139
+ deps.ctx.io.writeError(
140
+ `${deps.label} ${state.chunksProcessed}/${deps.totalChunks} ${Math.round(pct)}%\n`
141
+ );
142
+ }
143
+ }
144
+
145
+ function releaseTracker(state) {
146
+ state.cursorHandle?.dispose();
147
+ state.cursorHandle = null;
148
+ state.service = null;
149
+ state.handler = null;
150
+ }
151
+
152
+ function attachProgress(svc, state, deps) {
153
+ state.service = svc;
154
+ state.handler = (/** @type {{ size: number }} */ evt) => handleChunkEvent(evt, state, deps);
155
+ try {
156
+ if (deps.ctx.mode === 'interactive') {
157
+ state.cursorHandle = cursorGuard(deps.ctx.io).hide();
158
+ renderProgress(state, deps);
159
+ }
160
+ state.service.on(deps.event, state.handler);
161
+ } catch (error) {
162
+ releaseTracker(state);
163
+ throw error;
164
+ }
165
+ }
166
+
167
+ function detachProgress(state, deps) {
168
+ try {
169
+ if (state.service && state.handler) {
170
+ state.service.removeListener(deps.event, state.handler);
171
+ }
172
+ const elapsed = state.startTime ? (Date.now() - state.startTime) / 1000 : 0;
173
+ const throughput = elapsed > 0 ? state.bytesProcessed / elapsed : 0;
174
+ if (deps.ctx.mode === 'interactive') {
175
+ deps.ctx.io.writeError(
176
+ `${CLEAR_LINE_RETURN} ${deps.label} ${state.chunksProcessed}/${deps.totalChunks} done ${formatBytes(throughput)}/s\n`
177
+ );
178
+ } else {
179
+ deps.ctx.io.writeError(`${deps.label} ${state.chunksProcessed}/${deps.totalChunks} done\n`);
180
+ }
181
+ } finally {
182
+ releaseTracker(state);
117
183
  }
118
184
  }
119
185
 
@@ -126,29 +192,23 @@ function handleChunkEvent({ size }, state, deps) {
126
192
  function createProgressTracker({ ctx, totalChunks, event, label }) {
127
193
  const width = Math.min(40, (ctx.runtime.columns || 80) - 30);
128
194
  /** @type {TrackerState} */
129
- const state = { chunksProcessed: 0, bytesProcessed: 0, startTime: null, service: null, handler: null };
130
- const deps = { ctx, totalChunks, label, width };
195
+ const state = {
196
+ chunksProcessed: 0,
197
+ bytesProcessed: 0,
198
+ startTime: null,
199
+ service: null,
200
+ handler: null,
201
+ cursorHandle: null,
202
+ };
203
+ const deps = { ctx, totalChunks, event, label, width };
131
204
 
132
205
  return {
133
206
  /** @param {Observer} svc */
134
207
  attach(svc) {
135
- state.service = svc;
136
- state.handler = (/** @type {{ size: number }} */ evt) => handleChunkEvent(evt, state, deps);
137
- if (ctx.mode === 'interactive') {
138
- ctx.io.writeError('\x1b[?25l'); // hide cursor
139
- handleChunkEvent({ size: 0 }, state, deps);
140
- }
141
- state.service.on(event, state.handler);
208
+ attachProgress(svc, state, deps);
142
209
  },
143
210
  detach() {
144
- if (state.service && state.handler) { state.service.removeListener(event, state.handler); }
145
- const elapsed = state.startTime ? (Date.now() - state.startTime) / 1000 : 0;
146
- const throughput = elapsed > 0 ? state.bytesProcessed / elapsed : 0;
147
- if (ctx.mode === 'interactive') {
148
- ctx.io.writeError(`${CLEAR_LINE_RETURN} ${label} ${state.chunksProcessed}/${totalChunks} done ${formatBytes(throughput)}/s\n\x1b[?25h`); // show cursor
149
- } else {
150
- ctx.io.writeError(`${label} ${state.chunksProcessed}/${totalChunks} done\n`);
151
- }
211
+ detachProgress(state, deps);
152
212
  },
153
213
  };
154
214
  }
package/bin/ui/theme.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Shared visual language for git-cas terminal surfaces.
3
3
  */
4
4
 
5
- import { parseAnsiToSurface } from '@flyingrobots/bijou';
5
+ import { defineThemeSafePairs, parseAnsiToSurface } from '@flyingrobots/bijou';
6
6
 
7
7
  export const GIT_CAS_PALETTE = {
8
8
  ghost: [251, 252, 252],
@@ -31,16 +31,18 @@ function token(rgb, modifiers = [], bg) {
31
31
  };
32
32
  }
33
33
 
34
- const {
35
- ghost, pearl, slate, cyan, orange, midnight, ink, ruby, sky, violet, deepSlate,
36
- } = GIT_CAS_PALETTE;
34
+ const { ghost, slate, cyan, orange, midnight, ink, ruby, sky, violet, deepSlate } = GIT_CAS_PALETTE;
35
+
36
+ const secondaryBackground = [43, 58, 68];
37
+ const elevatedBackground = [51, 68, 78];
38
+ const mutedBackground = [31, 41, 49];
37
39
 
38
40
  /**
39
- * Bijou v5 theme for the git-cas cockpit.
41
+ * Bijou v7 theme for the git-cas cockpit.
40
42
  *
41
43
  * Keep this object aligned with Bijou's public Theme shape. App-specific
42
- * colors belong in local helpers, not in stray token groups that components
43
- * will never read.
44
+ * surface tokens are registered under `ui` so Bijou's theme doctor can verify
45
+ * every foreground/background relationship used by the cockpit.
44
46
  */
45
47
  export const GIT_CAS_THEME = {
46
48
  name: 'git-cas-cockpit',
@@ -51,7 +53,7 @@ export const GIT_CAS_THEME = {
51
53
  info: token(sky),
52
54
  pending: token(slate),
53
55
  active: token(cyan, ['bold']),
54
- muted: token(deepSlate),
56
+ muted: token(slate),
55
57
  },
56
58
  semantic: {
57
59
  success: token(cyan, ['bold']),
@@ -91,22 +93,47 @@ export const GIT_CAS_THEME = {
91
93
  logo: token(cyan, ['bold']),
92
94
  tableHeader: token(ghost, ['bold']),
93
95
  trackEmpty: token(deepSlate),
96
+ canvas: token(midnight),
97
+ secondaryCanvas: token(secondaryBackground),
98
+ elevatedCanvas: token(elevatedBackground),
99
+ overlayCanvas: token(ink),
100
+ mutedCanvas: token(mutedBackground),
94
101
  },
95
102
  surface: {
96
103
  primary: token(ghost, [], midnight),
97
- secondary: token(pearl, [], [43, 58, 68]),
98
- elevated: token(ghost, [], [51, 68, 78]),
104
+ secondary: token(ghost, [], secondaryBackground),
105
+ elevated: token(ghost, [], elevatedBackground),
99
106
  overlay: token(ghost, [], ink),
100
- muted: token(slate, [], [31, 41, 49]),
107
+ muted: token(ghost, [], mutedBackground),
101
108
  },
102
109
  };
103
110
 
111
+ /**
112
+ * High-contrast foreground/background contracts selected with Design Book and
113
+ * enforced by Bijou's theme doctor. Decorative track and border colors are not
114
+ * text pairs and are intentionally excluded.
115
+ */
116
+ export const GIT_CAS_THEME_SAFE_PAIRS = defineThemeSafePairs()
117
+ .readable('surface.primary', 'ui.canvas', { label: 'primary surface text' })
118
+ .readable('surface.secondary', 'ui.secondaryCanvas', { label: 'secondary surface text' })
119
+ .readable('surface.elevated', 'ui.elevatedCanvas', { label: 'elevated surface text' })
120
+ .readable('surface.overlay', 'ui.overlayCanvas', { label: 'overlay surface text' })
121
+ .readable('surface.muted', 'ui.mutedCanvas', { label: 'muted surface text' })
122
+ .readable('semantic.primary', 'ui.canvas', { label: 'primary cockpit text' })
123
+ .readable('semantic.muted', 'ui.canvas', { label: 'muted cockpit text' })
124
+ .status('semantic.success', 'ui.canvas', { label: 'success cockpit text' })
125
+ .status('semantic.error', 'ui.canvas', { label: 'error cockpit text' })
126
+ .status('semantic.warning', 'ui.canvas', { label: 'warning cockpit text' })
127
+ .status('semantic.info', 'ui.canvas', { label: 'informational cockpit text' })
128
+ .status('semantic.accent', 'ui.canvas', { label: 'accent cockpit text' })
129
+ .build();
130
+
104
131
  const TEXT_TONES = {
105
132
  brand: { fg: cyan, bold: true },
106
133
  accent: { fg: orange, bold: true },
107
134
  primary: { fg: ghost },
108
135
  secondary: { fg: slate },
109
- subdued: { fg: deepSlate },
136
+ subdued: { fg: slate },
110
137
  info: { fg: sky, bold: true },
111
138
  violet: { fg: violet, bold: true },
112
139
  success: { fg: cyan, bold: true },
package/build-info.json CHANGED
@@ -1,4 +1,4 @@
1
1
  {
2
- "sha": "9ea91a7",
3
- "timestamp": "2026-07-26T17:04:12.629Z"
2
+ "sha": "eebc6e3",
3
+ "timestamp": "2026-08-23T12:01:03.041Z"
4
4
  }
@@ -0,0 +1,55 @@
1
+ # git-cas v6.5.6 Release Notes
2
+
3
+ v6.5.6 moves the interactive cockpit onto Bijou 7.2's hosted application
4
+ boundary and makes checked Git ref conflicts independent of diagnostic prose.
5
+ It changes no public package API or stored-data schema.
6
+
7
+ ## Bijou 7 Hosted Cockpit
8
+
9
+ The interactive launcher now runs a `FramedApp`. Bijou owns terminal lifecycle,
10
+ outer chrome, help, command and asset-search palettes, settings, notifications,
11
+ performance telemetry, quit confirmation, and reference-counted cursor state.
12
+ The git-cas page continues to own vault authentication, storage state,
13
+ Explorer/Atlas/Operations navigation, filtering, and the Store Wizard.
14
+
15
+ Store and restore progress use Bijou's shared cursor guard and render the
16
+ initial `0/N` state without incrementing the processed count. Frame and page
17
+ tests preserve ordinary modal input, page-first key ownership, structured
18
+ stdout, and the static noninteractive fallback.
19
+
20
+ Design Book selected the high-contrast foregrounds for the dark cockpit
21
+ surfaces. Bijou's theme doctor and explicit text-tone tests enforce a minimum
22
+ 4.5:1 contrast ratio.
23
+
24
+ ## Deterministic Checked-Ref Conflicts
25
+
26
+ Failed checked updates, atomic anchors, and checked deletes no longer inspect
27
+ Git's human-readable diagnostics. The Git adapter reads structured post-failure
28
+ posture—direct OID, symbolic target, or absence—and normalizes only when that
29
+ posture disproves the attempted compare-and-swap precondition.
30
+
31
+ The existing contracts remain:
32
+
33
+ - checked updates and deletes reject with `GIT_REF_CONFLICT` plus structured
34
+ expected and observed posture;
35
+ - atomic anchors return `false` when their source changed or target appeared;
36
+ - operational failures remain the original error when the attempted ref
37
+ precondition still holds.
38
+
39
+ Diagnostic-free unit and real-Git tests cover changed, absent, and symbolic
40
+ posture across all three mutation paths.
41
+
42
+ ## Verification
43
+
44
+ The release candidate passed the repository's complete 14-step verifier with
45
+ 6,898 observed tests across Node, Bun, and Deno. The matrix includes public
46
+ type compatibility, executable examples, 199 real-Git integration tests on
47
+ each runtime, build stamping, and npm and JSR dry-runs.
48
+
49
+ ## Compatibility
50
+
51
+ This release requires no application or stored-data migration. Existing refs,
52
+ objects, handles, cockpit lower modes, machine-readable output, and package
53
+ exports remain valid. Interactive operators receive the hosted Bijou shell
54
+ automatically; callers receive more reliable existing conflict semantics
55
+ without changing method signatures.
@@ -0,0 +1,56 @@
1
+ # git-cas v6.5.7 Release Notes
2
+
3
+ v6.5.7 removes process-per-payload startup for small blobs requested through
4
+ the streaming persistence contract. It changes no public package API, object
5
+ identity, stored-data format, ref, or retention behavior.
6
+
7
+ ## Bounded Session-Backed Stream Reads
8
+
9
+ On plumbing that exposes a typed `cat-file --batch-command` session,
10
+ `GitPersistenceAdapter.readBlobStream()` now inspects immutable object type and
11
+ size before choosing a content route. A blob at or below the fixed 10 MiB
12
+ ceiling is read through the existing repository-scoped session and returned as
13
+ one `Buffer` chunk.
14
+
15
+ The ceiling is fixed independently of `maxBlobSize`; callers cannot configure
16
+ the optimization into unbounded allocation. Returning one chunk changes
17
+ backpressure granularity for admitted small objects, but the public
18
+ `AsyncIterable` method, byte sequence, object identity, and error surface remain
19
+ unchanged.
20
+
21
+ Objects above 10 MiB retain the genuine one-shot streaming path. Metadata is
22
+ inspected first, so oversized content is streamed exactly once and never read
23
+ and discarded through the bounded session. Plumbing without typed sessions,
24
+ unsupported object posture, and failed bounded reads retain the previous
25
+ one-shot fallback.
26
+
27
+ ## Process-Topology Witness
28
+
29
+ The committed diagnostic used 32 deterministic 4,096-byte objects. The legacy
30
+ fallback opened 32 one-shot `cat-file` children. The bounded session route
31
+ opened one persistent child, issued 32 metadata requests and 32 bounded reads,
32
+ returned the same semantic digest, and left zero active sessions after close.
33
+
34
+ A 10 MiB + 1 byte object opened one persistent child for metadata and one
35
+ one-shot content stream. It performed no session content read. Docker-backed
36
+ integration tests repeat the small-object law in SHA-1 and SHA-256 repositories
37
+ and verify exact bytes plus deterministic closure.
38
+
39
+ These are structural process-count and semantic-equality results. They are not
40
+ a wall-clock guarantee, a claim that every downstream Git child disappears, or
41
+ an aggregate caller-residency bound.
42
+
43
+ ## Verification
44
+
45
+ The release candidate passed the repository's complete 14-step verifier with
46
+ 6,922 observed tests across Node, Bun, and Deno. The matrix includes public
47
+ type compatibility, executable examples, 202 real-Git integration tests on
48
+ each runtime, build stamping, and npm and JSR dry-runs.
49
+
50
+ ## Compatibility
51
+
52
+ This release requires no application or stored-data migration. Existing
53
+ objects, manifests, handles, refs, retention evidence, package exports, and
54
+ custom persistence adapters remain valid. Consumers automatically receive the
55
+ bounded route when their injected Git plumbing supports typed sessions; large
56
+ payloads and fallback implementations keep the prior streaming behavior.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "6.5.5",
3
+ "version": "6.5.7",
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",
@@ -42,6 +42,8 @@
42
42
  "docs/releases/v6.5.3.md",
43
43
  "docs/releases/v6.5.4.md",
44
44
  "docs/releases/v6.5.5.md",
45
+ "docs/releases/v6.5.6.md",
46
+ "docs/releases/v6.5.7.md",
45
47
  "docs/THREAT_MODEL.md",
46
48
  "docs/VAULT_INTERNALS.md",
47
49
  "docs/WALKTHROUGH.md",
@@ -102,10 +104,10 @@
102
104
  "format": "prettier --write ."
103
105
  },
104
106
  "dependencies": {
105
- "@flyingrobots/bijou": "^5.0.0",
106
- "@flyingrobots/bijou-node": "^5.0.0",
107
- "@flyingrobots/bijou-tui": "^5.0.0",
108
- "@flyingrobots/bijou-tui-app": "^5.0.0",
107
+ "@flyingrobots/bijou": "^7.2.0",
108
+ "@flyingrobots/bijou-node": "^7.2.0",
109
+ "@flyingrobots/bijou-tui": "^7.2.0",
110
+ "@flyingrobots/bijou-tui-app": "^7.2.0",
109
111
  "@git-stunts/alfred": "^0.10.0",
110
112
  "@git-stunts/plumbing": "^3.2.0",
111
113
  "@git-stunts/vault": "^1.0.1",
@@ -19,6 +19,7 @@ import GitObjectSessionPool from './GitObjectSessionPool.js';
19
19
  */
20
20
  const DEFAULT_POLICY = Policy.timeout(30_000);
21
21
  export const DEFAULT_MAX_BLOB_SIZE = 10 * 1024 * 1024;
22
+ const MAX_SESSION_STREAM_BLOB_BYTES = DEFAULT_MAX_BLOB_SIZE;
22
23
  const DEFAULT_METADATA_CACHE_ENTRIES = 2_048;
23
24
  const DEFAULT_SESSION_IDLE_TIMEOUT_MS = 1_000;
24
25
  const DEFAULT_TREE_CACHE_BYTES = 8 * 1024 * 1024;
@@ -189,21 +190,7 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
189
190
  ? this.#maxBlobSize
190
191
  : GitPersistenceAdapter.#validatedReadBlobLimit(maxBytes);
191
192
  if (this.#sessions.supports('catFile')) {
192
- let object;
193
- try {
194
- object = await this.#sessions.read(oid, { maxBytes: limit }, (operation) =>
195
- this.policy.execute(operation)
196
- );
197
- } catch (error) {
198
- throw this.#normalizeObjectReadError(error, oid, limit);
199
- }
200
- if (object.type !== 'blob') {
201
- throw createCasError(`Git object is not a blob: ${oid}`, ErrorCodes.GIT_ERROR, {
202
- oid,
203
- actualType: object.type,
204
- });
205
- }
206
- return GitPersistenceAdapter.#toBuffer(object.content);
193
+ return await this.#readBlobFromSession(oid, limit);
207
194
  }
208
195
  const chunks = [];
209
196
  let bytesRead = 0;
@@ -241,7 +228,48 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
241
228
  * @returns {Promise<AsyncIterable<Buffer>>} The blob content stream.
242
229
  */
243
230
  async readBlobStream(oid) {
244
- return await this.#runOperation(() => this.#openBufferStream(['cat-file', 'blob', oid]));
231
+ return await this.#runOperation(async () => {
232
+ if (!this.#sessions.supports('catFile')) {
233
+ return await this.#openBlobStream(oid);
234
+ }
235
+ let info;
236
+ try {
237
+ info = await this.#readObjectInfo(oid);
238
+ } catch {
239
+ return await this.#openBlobStream(oid);
240
+ }
241
+ if (info.type !== 'blob' || info.size > MAX_SESSION_STREAM_BLOB_BYTES) {
242
+ return await this.#openBlobStream(oid);
243
+ }
244
+ try {
245
+ const content = await this.#readBlobFromSession(oid, MAX_SESSION_STREAM_BLOB_BYTES);
246
+ return GitPersistenceAdapter.#singleBufferStream(content);
247
+ } catch {
248
+ return await this.#openBlobStream(oid);
249
+ }
250
+ });
251
+ }
252
+
253
+ async #readBlobFromSession(oid, maxBytes) {
254
+ let object;
255
+ try {
256
+ object = await this.#sessions.read(oid, { maxBytes }, (operation) =>
257
+ this.policy.execute(operation)
258
+ );
259
+ } catch (error) {
260
+ throw this.#normalizeObjectReadError(error, oid, maxBytes);
261
+ }
262
+ if (object.type !== 'blob') {
263
+ throw createCasError(`Git object is not a blob: ${oid}`, ErrorCodes.GIT_ERROR, {
264
+ oid,
265
+ actualType: object.type,
266
+ });
267
+ }
268
+ return GitPersistenceAdapter.#toBuffer(object.content);
269
+ }
270
+
271
+ async #openBlobStream(oid) {
272
+ return await this.#openBufferStream(['cat-file', 'blob', oid]);
245
273
  }
246
274
 
247
275
  /**
@@ -675,6 +703,10 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
675
703
  }
676
704
  }
677
705
 
706
+ static async *#singleBufferStream(content) {
707
+ yield content;
708
+ }
709
+
678
710
  /**
679
711
  * @param {Buffer|Uint8Array|string} chunk
680
712
  * @returns {Buffer}
@@ -1,7 +1,7 @@
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 { errorDetailsText, isGitMissingRefError } from '../../domain/helpers/gitRefErrors.js';
4
+ import { isGitMissingRefError } from '../../domain/helpers/gitRefErrors.js';
5
5
  import Oid from '../../domain/value-objects/Oid.js';
6
6
 
7
7
  /**
@@ -136,9 +136,22 @@ export default class GitRefAdapter extends GitRefPort {
136
136
  if (expectedOldOid !== undefined) {
137
137
  args.push(expectedOldOid ?? '0'.repeat(newOid.length));
138
138
  }
139
- await this.policy.execute(() =>
140
- this.plumbing.execute({ args }),
141
- );
139
+ try {
140
+ await this.policy.execute(() =>
141
+ this.plumbing.execute({ args }),
142
+ );
143
+ } catch (error) {
144
+ const actual = await this.#inspectRefPosture(ref);
145
+ if (postureDisprovesExpectedOid(actual, expectedOldOid)) {
146
+ throw refConflictFromPosture({
147
+ ref,
148
+ expectedOldOid: expectedOldOid ?? null,
149
+ actual,
150
+ originalError: error,
151
+ });
152
+ }
153
+ throw error;
154
+ }
142
155
  }
143
156
 
144
157
  /** @override */
@@ -168,7 +181,12 @@ export default class GitRefAdapter extends GitRefPort {
168
181
  );
169
182
  return true;
170
183
  } catch (error) {
171
- if (isUpdateRefConflict(error, [sourceRef, targetRef])) {
184
+ const sourceActual = await this.#inspectRefPosture(sourceRef);
185
+ if (postureDisprovesExpectedOid(sourceActual, generation)) {
186
+ return false;
187
+ }
188
+ const targetActual = await this.#inspectRefPosture(targetRef);
189
+ if (postureDisprovesExpectedOid(targetActual, null)) {
172
190
  return false;
173
191
  }
174
192
  throw error;
@@ -197,27 +215,16 @@ export default class GitRefAdapter extends GitRefPort {
197
215
  }),
198
216
  );
199
217
  } catch (error) {
200
- if (!isUpdateRefConflict(error, [ref])) {
201
- throw error;
202
- }
203
- const racedSymbolicTarget = await this.#resolveSymbolicRef(ref);
204
- if (racedSymbolicTarget !== null) {
205
- throw refConflict({
218
+ const actual = await this.#inspectRefPosture(ref);
219
+ if (postureDisprovesExpectedOid(actual, expectedGeneration)) {
220
+ throw refConflictFromPosture({
206
221
  ref,
207
222
  expectedOldOid: expectedGeneration,
208
- actualOldOid: null,
209
- actualSymref: racedSymbolicTarget,
223
+ actual,
210
224
  originalError: error,
211
225
  });
212
226
  }
213
- const actual = await this.#inspectDirectRef(ref);
214
- throw refConflict({
215
- ref,
216
- expectedOldOid: expectedGeneration,
217
- actualOldOid: actual?.oid ?? null,
218
- actualSymref: actual?.symref ?? null,
219
- originalError: error,
220
- });
227
+ throw error;
221
228
  }
222
229
  return true;
223
230
  }
@@ -270,6 +277,18 @@ export default class GitRefAdapter extends GitRefPort {
270
277
  });
271
278
  }
272
279
 
280
+ async #inspectRefPosture(ref) {
281
+ const symbolicTarget = await this.#resolveSymbolicRef(ref);
282
+ if (symbolicTarget !== null) {
283
+ return Object.freeze({ oid: null, symref: symbolicTarget });
284
+ }
285
+ const direct = await this.#inspectDirectRef(ref);
286
+ if (direct?.symref) {
287
+ return Object.freeze({ oid: null, symref: direct.symref });
288
+ }
289
+ return Object.freeze({ oid: direct?.oid ?? null, symref: null });
290
+ }
291
+
273
292
  async #resolveSymbolicRef(ref) {
274
293
  try {
275
294
  const output = await this.policy.execute(() =>
@@ -443,17 +462,18 @@ function invalidRefName(ref) {
443
462
  return new CasError('Git ref name or prefix is invalid', ErrorCodes.GIT_ERROR, { ref });
444
463
  }
445
464
 
446
- function isUpdateRefConflict(error, refs) {
447
- const text = errorDetailsText(error).toLowerCase();
448
- return refs.some((ref) => text.includes(ref.toLowerCase()))
449
- && (
450
- text.includes('cannot lock ref') ||
451
- text.includes('but expected') ||
452
- text.includes('reference already exists') ||
453
- text.includes('unable to resolve reference') ||
454
- text.includes('zero <oldvalue>') ||
455
- text.includes('is a symref')
456
- );
465
+ function postureDisprovesExpectedOid(actual, expectedOldOid) {
466
+ if (actual.symref !== null) {
467
+ return true;
468
+ }
469
+ if (expectedOldOid === undefined) {
470
+ return false;
471
+ }
472
+ if (expectedOldOid === null) {
473
+ return actual.oid !== null;
474
+ }
475
+ return actual.oid === null
476
+ || Oid.from(actual.oid).toString() !== Oid.from(expectedOldOid).toString();
457
477
  }
458
478
 
459
479
  function isQuietSymbolicRefMiss(error, ref) {
@@ -479,3 +499,13 @@ function refConflict({
479
499
  { ref, expectedOldOid, actualOldOid, actualSymref, originalError },
480
500
  );
481
501
  }
502
+
503
+ function refConflictFromPosture({ ref, expectedOldOid, actual, originalError }) {
504
+ return refConflict({
505
+ ref,
506
+ expectedOldOid,
507
+ actualOldOid: actual.oid,
508
+ actualSymref: actual.symref,
509
+ originalError,
510
+ });
511
+ }
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '6.5.5';
1
+ export const PACKAGE_VERSION = '6.5.7';
@@ -54,6 +54,8 @@ export default class GitRefPort {
54
54
  * @param {string} _options.newOid - New OID to set.
55
55
  * @param {string|null} [_options.expectedOldOid] - Expected current OID for CAS; `null` means the ref must not exist.
56
56
  * @returns {Promise<void>}
57
+ * @throws A `GIT_REF_CONFLICT` error when observed ref posture disproves the
58
+ * checked mutation precondition.
57
59
  */
58
60
  async updateRef(_options) {
59
61
  throw new Error('Not implemented');
@@ -66,6 +68,8 @@ export default class GitRefPort {
66
68
  * @param {string} _options.expectedSourceOid
67
69
  * @param {string} _options.targetRef
68
70
  * @returns {Promise<boolean>} Whether the source generation was anchored.
71
+ * `false` means observed ref posture disproved the atomic verify/create
72
+ * preconditions.
69
73
  */
70
74
  async anchorRef(_options) {
71
75
  throw unsupportedAcquisitionCapability('anchorRef');
@@ -77,6 +81,8 @@ export default class GitRefPort {
77
81
  * @param {string} _options.ref
78
82
  * @param {string} _options.expectedOldOid
79
83
  * @returns {Promise<boolean>} Whether the ref existed and was deleted.
84
+ * @throws A `GIT_REF_CONFLICT` error when observed ref posture disproves the
85
+ * checked delete precondition.
80
86
  */
81
87
  async deleteRef(_options) {
82
88
  throw unsupportedAcquisitionCapability('deleteRef');