@git-stunts/git-cas 2.0.0 → 3.0.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.
package/CHANGELOG.md CHANGED
@@ -5,7 +5,48 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [Unreleased]
8
+ ## [3.0.0] — Vault (2026-02-08)
9
+
10
+ ### Added
11
+ - **Vault** — GC-safe ref-based storage via `refs/cas/vault`. A single Git ref pointing to a commit chain indexes all stored assets by slug. `git gc` can no longer silently discard stored data.
12
+ - `initVault()` — initialize the vault, optionally with passphrase-based encryption (vault-level KDF policy).
13
+ - `addToVault()` — add or update an entry by slug + tree OID, with `force` flag for overwrites.
14
+ - `listVault()` — list all entries sorted by slug.
15
+ - `removeFromVault()` — remove an entry by slug.
16
+ - `resolveVaultEntry()` — resolve a slug to its tree OID.
17
+ - `getVaultMetadata()` — inspect vault metadata (encryption config, version).
18
+ - Vault metadata (`.vault.json`) supports versioning and optional encryption configuration.
19
+ - CAS-safe writes with automatic retry (up to 3 attempts with exponential backoff) on concurrent update conflicts.
20
+ - Strict slug validation: rejects empty strings, `..` traversal, control characters, oversized segments.
21
+ - New CLI subcommands: `vault init`, `vault list`, `vault info <slug>`, `vault remove <slug>`, `vault history`.
22
+ - CLI `store --tree` now auto-vaults the entry (adds to vault after creating tree).
23
+ - CLI `restore` now supports `--slug` (resolve via vault) and `--oid` (direct tree OID) flags.
24
+ - CLI `--vault-passphrase` flag for vault-level encryption on `store`, `restore`, and `vault init`.
25
+ - New error codes: `INVALID_SLUG`, `VAULT_ENTRY_NOT_FOUND`, `VAULT_ENTRY_EXISTS`, `VAULT_CONFLICT`, `VAULT_METADATA_INVALID`, `VAULT_ENCRYPTION_ALREADY_CONFIGURED`.
26
+ - TypeScript declarations for `VaultEntry`, `VaultMetadata`, `VaultState`, `VaultService`, `GitRefPort` types.
27
+ - `VaultService` — first-class domain service with proper port/adapter separation (hexagonal architecture).
28
+ - `GitRefPort` and `GitRefAdapter` — new port/adapter for Git ref and commit operations.
29
+ - `getVaultService()` on facade exposes the underlying `VaultService` for advanced usage.
30
+ - Vault-specific integration tests (`test/integration/vault.test.js`).
31
+ - 46 vault unit tests + facade delegation smoke test.
32
+
33
+ ### Fixed
34
+ - `#validateMetadata` now requires `kdf.keyLength` in encryption metadata, preventing downstream KDF failures from manually edited `.vault.json` files.
35
+ - `#casUpdateRef` now preserves the original error in `VAULT_CONFLICT` meta for better diagnostics.
36
+ - CLI `--vault-passphrase` now emits a stderr warning when the vault is not encrypted, instead of silently ignoring the passphrase.
37
+ - `vault history` command now uses `VAULT_REF` constant instead of hardcoded string.
38
+ - API docs: fixed invalid import path `@git-stunts/cas/vault` → `@git-stunts/cas`.
39
+ - API docs: fixed `_readVaultState()` → `readState()` in error codes table.
40
+ - API docs and GUIDE: added `text` language identifier to fenced code blocks (markdownlint MD040).
41
+ - CLI version string updated from `2.0.0` to `3.0.0`.
42
+ - CLI `vault history --max-count` now validates input as a positive integer.
43
+ - Stale JSDoc in `GitPersistenceAdapter` corrected (removed mention of retries).
44
+ - CLI uses `program.parseAsync()` instead of `program.parse()` to prevent Bun from hanging on async action handlers.
45
+
46
+ ### Changed
47
+ - **Vault promoted to domain layer** — all vault logic extracted from facade (`index.js`) into `VaultService` (`src/domain/services/VaultService.js`) with `GitRefPort`/`GitRefAdapter` for ref operations. Facade now delegates to VaultService.
48
+ - CLI `restore` command no longer takes a positional `<tree-oid>` argument. Use `--oid <tree-oid>` or `--slug <slug>` instead.
49
+ - Purged completed milestones (M1–M7) and their task cards from ROADMAP.md, reducing it from 3,153 to 1,675 lines.
9
50
 
10
51
  ## [2.0.0] — M7 Horizon (2026-02-08)
11
52
 
package/README.md CHANGED
@@ -28,6 +28,7 @@ We use the object database.
28
28
  - **Tree output** generates standard Git trees so assets snap into commits cleanly.
29
29
  - **Full round-trip** store, tree, and restore — get your bytes back, verified.
30
30
  - **Lifecycle management** `readManifest`, `deleteAsset`, `findOrphanedChunks` — inspect trees, plan deletions, audit storage.
31
+ - **Vault** GC-safe ref-based storage. One ref (`refs/cas/vault`) indexes all assets by slug. No more silent data loss from `git gc`.
31
32
 
32
33
  **Use it for:** binary assets, build artifacts, model weights, data packs, secret bundles, weird experiments, etc.
33
34
 
@@ -41,6 +42,24 @@ We use the object database.
41
42
 
42
43
  See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
43
44
 
45
+ ## What's new in v3.0.0
46
+
47
+ **Vault** — GC-safe ref-based storage. A single Git ref (`refs/cas/vault`) indexes all stored assets by slug, so `git gc` can no longer silently discard your data. Initialize with `vault init`, store with `--tree`, restore by `--slug`.
48
+
49
+ **CLI breaking change** — `git cas restore` no longer takes a positional `<tree-oid>` argument. Use `--oid <tree-oid>` or `--slug <slug>` instead.
50
+
51
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
52
+
53
+ ## Install
54
+
55
+ ```bash
56
+ npm install @git-stunts/git-cas
57
+ ```
58
+
59
+ ```bash
60
+ npx jsr add @git-stunts/git-cas
61
+ ```
62
+
44
63
  ## Usage (Node API)
45
64
 
46
65
  ```js
@@ -87,18 +106,26 @@ const manifest2 = await cas.storeFile({
87
106
  # Store a file — prints manifest JSON
88
107
  git cas store ./image.png --slug my-image
89
108
 
90
- # Store and get a tree OID directly
109
+ # Store and vault the tree OID (GC-safe)
91
110
  git cas store ./image.png --slug my-image --tree
92
111
 
93
- # Create a tree from an existing manifest
94
- git cas tree --manifest manifest.json
112
+ # Restore from a vault slug
113
+ git cas restore --slug my-image --out ./restored.png
114
+
115
+ # Restore from a direct tree OID
116
+ git cas restore --oid <tree-oid> --out ./restored.png
95
117
 
96
- # Restore from a tree OID
97
- git cas restore <tree-oid> --out ./restored.png
118
+ # Vault management
119
+ git cas vault init
120
+ git cas vault list
121
+ git cas vault info my-image
122
+ git cas vault remove my-image
123
+ git cas vault history
98
124
 
99
- # Encrypted round-trip (32-byte raw key file)
100
- git cas store ./secret.bin --slug vault --key-file ./my.key --tree
101
- git cas restore <tree-oid> --out ./decrypted.bin --key-file ./my.key
125
+ # Encrypted vault round-trip
126
+ git cas vault init --vault-passphrase "secret"
127
+ git cas store ./secret.bin --slug vault-entry --tree --vault-passphrase "secret"
128
+ git cas restore --slug vault-entry --out ./decrypted.bin --vault-passphrase "secret"
102
129
  ```
103
130
 
104
131
  ## Why not Git LFS?
package/bin/git-cas.js CHANGED
@@ -2,31 +2,94 @@
2
2
 
3
3
  import { readFileSync } from 'node:fs';
4
4
  import { program } from 'commander';
5
- import GitPlumbing from '@git-stunts/plumbing';
5
+ import GitPlumbing, { ShellRunnerFactory } from '@git-stunts/plumbing';
6
6
  import ContentAddressableStore from '../index.js';
7
7
  import Manifest from '../src/domain/value-objects/Manifest.js';
8
8
 
9
9
  program
10
10
  .name('git-cas')
11
11
  .description('Content Addressable Storage backed by Git')
12
- .version('1.3.0');
12
+ .version('3.0.0');
13
13
 
14
14
  /**
15
15
  * Read a 32-byte raw encryption key from a file.
16
16
  */
17
17
  function readKeyFile(keyFilePath) {
18
- const key = readFileSync(keyFilePath);
19
- return key;
18
+ return readFileSync(keyFilePath);
20
19
  }
21
20
 
22
21
  /**
23
22
  * Create a CAS instance for the given working directory.
24
23
  */
25
24
  function createCas(cwd) {
26
- const plumbing = new GitPlumbing({ cwd });
25
+ const runner = ShellRunnerFactory.create();
26
+ const plumbing = new GitPlumbing({ runner, cwd });
27
27
  return new ContentAddressableStore({ plumbing });
28
28
  }
29
29
 
30
+ /**
31
+ * Derive the encryption key from vault metadata + passphrase.
32
+ */
33
+ async function deriveVaultKey(cas, metadata, passphrase) {
34
+ const { kdf } = metadata.encryption;
35
+ const { key } = await cas.deriveKey({
36
+ passphrase,
37
+ salt: Buffer.from(kdf.salt, 'base64'),
38
+ algorithm: kdf.algorithm,
39
+ iterations: kdf.iterations,
40
+ cost: kdf.cost,
41
+ blockSize: kdf.blockSize,
42
+ parallelization: kdf.parallelization,
43
+ });
44
+ return key;
45
+ }
46
+
47
+ /**
48
+ * Resolve encryption key from --key-file or --vault-passphrase.
49
+ */
50
+ async function resolveEncryptionKey(cas, opts) {
51
+ if (opts.keyFile) {
52
+ return readKeyFile(opts.keyFile);
53
+ }
54
+ if (!opts.vaultPassphrase) {
55
+ return undefined;
56
+ }
57
+ const metadata = await cas.getVaultMetadata();
58
+ if (metadata?.encryption) {
59
+ return deriveVaultKey(cas, metadata, opts.vaultPassphrase);
60
+ }
61
+ process.stderr.write('warning: --vault-passphrase ignored (vault is not encrypted)\n');
62
+ return undefined;
63
+ }
64
+
65
+ /**
66
+ * Read the manifest from a tree OID.
67
+ */
68
+ async function readManifestFromTree(service, treeOid) {
69
+ const entries = await service.persistence.readTree(treeOid);
70
+ const entry = entries.find((e) => e.name.startsWith('manifest.'));
71
+ if (!entry) {
72
+ process.stderr.write('error: No manifest found in tree\n');
73
+ process.exit(1);
74
+ }
75
+ const blob = await service.persistence.readBlob(entry.oid);
76
+ return new Manifest(service.codec.decode(blob));
77
+ }
78
+
79
+ /**
80
+ * Validate --slug / --oid flags (exactly one required).
81
+ */
82
+ function validateRestoreFlags(opts) {
83
+ if (opts.slug && opts.oid) {
84
+ process.stderr.write('error: Provide --slug or --oid, not both\n');
85
+ process.exit(1);
86
+ }
87
+ if (!opts.slug && !opts.oid) {
88
+ process.stderr.write('error: Provide --slug <slug> or --oid <tree-oid>\n');
89
+ process.exit(1);
90
+ }
91
+ }
92
+
30
93
  // ---------------------------------------------------------------------------
31
94
  // store
32
95
  // ---------------------------------------------------------------------------
@@ -36,26 +99,26 @@ program
36
99
  .requiredOption('--slug <slug>', 'Asset slug identifier')
37
100
  .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
38
101
  .option('--tree', 'Also create a Git tree and print its OID')
102
+ .option('--force', 'Overwrite existing vault entry')
103
+ .option('--vault-passphrase <pass>', 'Vault-level passphrase for encryption')
39
104
  .option('--cwd <dir>', 'Git working directory', '.')
40
105
  .action(async (file, opts) => {
41
106
  try {
42
107
  const cas = createCas(opts.cwd);
43
- const storeOpts = {
44
- filePath: file,
45
- slug: opts.slug,
46
- };
47
-
48
- if (opts.keyFile) {
49
- storeOpts.encryptionKey = readKeyFile(opts.keyFile);
108
+ const encryptionKey = await resolveEncryptionKey(cas, opts);
109
+ const storeOpts = { filePath: file, slug: opts.slug };
110
+ if (encryptionKey) {
111
+ storeOpts.encryptionKey = encryptionKey;
50
112
  }
51
113
 
52
114
  const manifest = await cas.storeFile(storeOpts);
53
115
 
54
116
  if (opts.tree) {
55
117
  const treeOid = await cas.createTree({ manifest });
56
- process.stdout.write(`${treeOid }\n`);
118
+ await cas.addToVault({ slug: opts.slug, treeOid, force: !!opts.force });
119
+ process.stdout.write(`${treeOid}\n`);
57
120
  } else {
58
- process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2) }\n`);
121
+ process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2)}\n`);
59
122
  }
60
123
  } catch (err) {
61
124
  process.stderr.write(`error: ${err.message}\n`);
@@ -77,7 +140,7 @@ program
77
140
  const raw = readFileSync(opts.manifest, 'utf8');
78
141
  const manifest = new Manifest(JSON.parse(raw));
79
142
  const treeOid = await cas.createTree({ manifest });
80
- process.stdout.write(`${treeOid }\n`);
143
+ process.stdout.write(`${treeOid}\n`);
81
144
  } catch (err) {
82
145
  process.stderr.write(`error: ${err.message}\n`);
83
146
  process.exit(1);
@@ -88,43 +151,32 @@ program
88
151
  // restore
89
152
  // ---------------------------------------------------------------------------
90
153
  program
91
- .command('restore <tree-oid>')
154
+ .command('restore')
92
155
  .description('Restore a file from a Git CAS tree')
93
156
  .requiredOption('--out <path>', 'Output file path')
157
+ .option('--slug <slug>', 'Resolve tree OID from vault slug')
158
+ .option('--oid <tree-oid>', 'Direct tree OID')
94
159
  .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
160
+ .option('--vault-passphrase <pass>', 'Vault-level passphrase for decryption')
95
161
  .option('--cwd <dir>', 'Git working directory', '.')
96
- .action(async (treeOid, opts) => {
162
+ .action(async (opts) => {
97
163
  try {
164
+ validateRestoreFlags(opts);
98
165
  const cas = createCas(opts.cwd);
166
+ const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
99
167
  const service = await cas.getService();
100
-
101
- // Read the tree to find the manifest
102
- const entries = await service.persistence.readTree(treeOid);
103
- const manifestEntry = entries.find(
104
- (e) => e.name.startsWith('manifest.'),
105
- );
106
- if (!manifestEntry) {
107
- process.stderr.write('error: No manifest found in tree\n');
108
- process.exit(1);
109
- }
110
-
111
- const manifestBlob = await service.persistence.readBlob(
112
- manifestEntry.oid,
113
- );
114
- const manifest = new Manifest(
115
- service.codec.decode(manifestBlob),
116
- );
168
+ const manifest = await readManifestFromTree(service, treeOid);
117
169
 
118
170
  const restoreOpts = { manifest };
119
- if (opts.keyFile) {
120
- restoreOpts.encryptionKey = readKeyFile(opts.keyFile);
171
+ const encryptionKey = await resolveEncryptionKey(cas, opts);
172
+ if (encryptionKey) {
173
+ restoreOpts.encryptionKey = encryptionKey;
121
174
  }
122
175
 
123
176
  const { bytesWritten } = await cas.restoreFile({
124
177
  ...restoreOpts,
125
178
  outputPath: opts.out,
126
179
  });
127
-
128
180
  process.stdout.write(`${bytesWritten}\n`);
129
181
  } catch (err) {
130
182
  process.stderr.write(`error: ${err.message}\n`);
@@ -132,4 +184,119 @@ program
132
184
  }
133
185
  });
134
186
 
135
- program.parse();
187
+ // ---------------------------------------------------------------------------
188
+ // vault init
189
+ // ---------------------------------------------------------------------------
190
+ const vault = program
191
+ .command('vault')
192
+ .description('Manage the CAS vault');
193
+
194
+ vault
195
+ .command('init')
196
+ .description('Initialize the vault')
197
+ .option('--vault-passphrase <pass>', 'Passphrase for vault-level encryption')
198
+ .option('--algorithm <alg>', 'KDF algorithm (pbkdf2 or scrypt)', 'pbkdf2')
199
+ .option('--cwd <dir>', 'Git working directory', '.')
200
+ .action(async (opts) => {
201
+ try {
202
+ const cas = createCas(opts.cwd);
203
+ const initOpts = {};
204
+ if (opts.vaultPassphrase) {
205
+ initOpts.passphrase = opts.vaultPassphrase;
206
+ initOpts.kdfOptions = { algorithm: opts.algorithm };
207
+ }
208
+ const { commitOid } = await cas.initVault(initOpts);
209
+ process.stdout.write(`${commitOid}\n`);
210
+ } catch (err) {
211
+ process.stderr.write(`error: ${err.message}\n`);
212
+ process.exit(1);
213
+ }
214
+ });
215
+
216
+ // ---------------------------------------------------------------------------
217
+ // vault list
218
+ // ---------------------------------------------------------------------------
219
+ vault
220
+ .command('list')
221
+ .description('List vault entries')
222
+ .option('--cwd <dir>', 'Git working directory', '.')
223
+ .action(async (opts) => {
224
+ try {
225
+ const cas = createCas(opts.cwd);
226
+ const entries = await cas.listVault();
227
+ for (const { slug, treeOid } of entries) {
228
+ process.stdout.write(`${slug}\t${treeOid}\n`);
229
+ }
230
+ } catch (err) {
231
+ process.stderr.write(`error: ${err.message}\n`);
232
+ process.exit(1);
233
+ }
234
+ });
235
+
236
+ // ---------------------------------------------------------------------------
237
+ // vault remove
238
+ // ---------------------------------------------------------------------------
239
+ vault
240
+ .command('remove <slug>')
241
+ .description('Remove an entry from the vault')
242
+ .option('--cwd <dir>', 'Git working directory', '.')
243
+ .action(async (slug, opts) => {
244
+ try {
245
+ const cas = createCas(opts.cwd);
246
+ const { removedTreeOid } = await cas.removeFromVault({ slug });
247
+ process.stdout.write(`${removedTreeOid}\n`);
248
+ } catch (err) {
249
+ process.stderr.write(`error: ${err.message}\n`);
250
+ process.exit(1);
251
+ }
252
+ });
253
+
254
+ // ---------------------------------------------------------------------------
255
+ // vault info
256
+ // ---------------------------------------------------------------------------
257
+ vault
258
+ .command('info <slug>')
259
+ .description('Show info for a vault entry')
260
+ .option('--cwd <dir>', 'Git working directory', '.')
261
+ .action(async (slug, opts) => {
262
+ try {
263
+ const cas = createCas(opts.cwd);
264
+ const treeOid = await cas.resolveVaultEntry({ slug });
265
+ process.stdout.write(`slug\t${slug}\n`);
266
+ process.stdout.write(`tree\t${treeOid}\n`);
267
+ } catch (err) {
268
+ process.stderr.write(`error: ${err.message}\n`);
269
+ process.exit(1);
270
+ }
271
+ });
272
+
273
+ // ---------------------------------------------------------------------------
274
+ // vault history
275
+ // ---------------------------------------------------------------------------
276
+ vault
277
+ .command('history')
278
+ .description('Show vault commit history')
279
+ .option('--cwd <dir>', 'Git working directory', '.')
280
+ .option('-n, --max-count <n>', 'Limit number of commits')
281
+ .action(async (opts) => {
282
+ try {
283
+ const runner = ShellRunnerFactory.create();
284
+ const plumbing = new GitPlumbing({ runner, cwd: opts.cwd || '.' });
285
+ const args = ['log', '--oneline', ContentAddressableStore.VAULT_REF];
286
+ if (opts.maxCount) {
287
+ const n = parseInt(opts.maxCount, 10);
288
+ if (Number.isNaN(n) || n <= 0) {
289
+ process.stderr.write('error: --max-count must be a positive integer\n');
290
+ process.exit(1);
291
+ }
292
+ args.push(`-${n}`);
293
+ }
294
+ const output = await plumbing.execute({ args });
295
+ process.stdout.write(`${output}\n`);
296
+ } catch (err) {
297
+ process.stderr.write(`error: ${err.message}\n`);
298
+ process.exit(1);
299
+ }
300
+ });
301
+
302
+ await program.parseAsync();
package/index.d.ts CHANGED
@@ -45,11 +45,32 @@ export declare class GitPersistencePortBase {
45
45
  ): Promise<Array<{ mode: string; type: string; oid: string; name: string }>>;
46
46
  }
47
47
 
48
+ /** Abstract port for Git ref and commit operations. */
49
+ export declare class GitRefPortBase {
50
+ resolveRef(ref: string): Promise<string>;
51
+ resolveTree(commitOid: string): Promise<string>;
52
+ createCommit(options: {
53
+ treeOid: string;
54
+ parentOid?: string | null;
55
+ message: string;
56
+ }): Promise<string>;
57
+ updateRef(options: {
58
+ ref: string;
59
+ newOid: string;
60
+ expectedOldOid?: string | null;
61
+ }): Promise<void>;
62
+ }
63
+
48
64
  /** Git-backed implementation of the persistence port. */
49
65
  export declare class GitPersistenceAdapter extends GitPersistencePortBase {
50
66
  constructor(options: { plumbing: unknown; policy?: unknown });
51
67
  }
52
68
 
69
+ /** Git-backed implementation of the ref port. */
70
+ export declare class GitRefAdapter extends GitRefPortBase {
71
+ constructor(options: { plumbing: unknown; policy?: unknown });
72
+ }
73
+
53
74
  /** Node.js crypto implementation of CryptoPort. */
54
75
  export declare class NodeCryptoAdapter extends CryptoPortBase {
55
76
  constructor();
@@ -82,11 +103,95 @@ export interface ContentAddressableStoreOptions {
82
103
  merkleThreshold?: number;
83
104
  }
84
105
 
106
+ /** A single vault entry. */
107
+ export interface VaultEntry {
108
+ slug: string;
109
+ treeOid: string;
110
+ }
111
+
112
+ /** Vault metadata stored in .vault.json. */
113
+ export interface VaultMetadata {
114
+ version: number;
115
+ encryption?: {
116
+ cipher: string;
117
+ kdf: {
118
+ algorithm: string;
119
+ salt: string;
120
+ iterations?: number;
121
+ cost?: number;
122
+ blockSize?: number;
123
+ parallelization?: number;
124
+ keyLength: number;
125
+ };
126
+ };
127
+ }
128
+
129
+ /** Internal vault state returned by VaultService.readState(). */
130
+ export interface VaultState {
131
+ entries: Map<string, string>;
132
+ parentCommitOid: string | null;
133
+ metadata: VaultMetadata | null;
134
+ }
135
+
136
+ /**
137
+ * Domain service for vault (GC-safe ref-based asset index) operations.
138
+ */
139
+ export declare class VaultService {
140
+ static VAULT_REF: string;
141
+
142
+ constructor(options: {
143
+ persistence: GitPersistencePortBase;
144
+ ref: GitRefPortBase;
145
+ crypto: CryptoPortBase;
146
+ });
147
+
148
+ /** Validates a vault slug. Throws CasError with code INVALID_SLUG on failure. */
149
+ validateSlug(slug: string): void;
150
+
151
+ /** Reads the current vault state from refs/cas/vault. */
152
+ readState(): Promise<VaultState>;
153
+
154
+ /** Writes a new vault commit and updates the ref atomically. */
155
+ writeCommit(options: {
156
+ entries: Map<string, string>;
157
+ metadata: VaultMetadata;
158
+ parentCommitOid: string | null;
159
+ message: string;
160
+ }): Promise<{ commitOid: string }>;
161
+
162
+ /** Initializes the vault, optionally with encryption. */
163
+ initVault(options?: {
164
+ passphrase?: string;
165
+ kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
166
+ }): Promise<{ commitOid: string }>;
167
+
168
+ /** Adds or updates an entry in the vault. */
169
+ addToVault(options: {
170
+ slug: string;
171
+ treeOid: string;
172
+ force?: boolean;
173
+ }): Promise<{ commitOid: string }>;
174
+
175
+ /** Lists all vault entries sorted by slug. */
176
+ listVault(): Promise<VaultEntry[]>;
177
+
178
+ /** Removes an entry from the vault. */
179
+ removeFromVault(options: {
180
+ slug: string;
181
+ }): Promise<{ commitOid: string; removedTreeOid: string }>;
182
+
183
+ /** Resolves a vault entry slug to its tree OID. */
184
+ resolveVaultEntry(options: { slug: string }): Promise<string>;
185
+
186
+ /** Returns the vault metadata, or null if no vault exists. */
187
+ getVaultMetadata(): Promise<VaultMetadata | null>;
188
+ }
189
+
85
190
  /**
86
191
  * High-level facade for the Content Addressable Store library.
87
192
  *
88
- * Wraps CasService with lazy initialization, runtime-adaptive crypto
89
- * selection, and convenience helpers for file I/O.
193
+ * Wraps CasService and VaultService with lazy initialization, runtime-adaptive
194
+ * crypto selection, and convenience helpers for file I/O.
90
195
  */
91
196
  export default class ContentAddressableStore {
92
197
  constructor(options: ContentAddressableStoreOptions);
@@ -94,6 +199,7 @@ export default class ContentAddressableStore {
94
199
  get chunkSize(): number;
95
200
 
96
201
  getService(): Promise<CasService>;
202
+ getVaultService(): Promise<VaultService>;
97
203
 
98
204
  static createJson(options: {
99
205
  plumbing: unknown;
@@ -166,4 +272,29 @@ export default class ContentAddressableStore {
166
272
  }): Promise<{ referenced: Set<string>; total: number }>;
167
273
 
168
274
  deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
275
+
276
+ // Vault — delegates to VaultService
277
+
278
+ static VAULT_REF: string;
279
+
280
+ initVault(options?: {
281
+ passphrase?: string;
282
+ kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
283
+ }): Promise<{ commitOid: string }>;
284
+
285
+ addToVault(options: {
286
+ slug: string;
287
+ treeOid: string;
288
+ force?: boolean;
289
+ }): Promise<{ commitOid: string }>;
290
+
291
+ listVault(): Promise<VaultEntry[]>;
292
+
293
+ removeFromVault(options: {
294
+ slug: string;
295
+ }): Promise<{ commitOid: string; removedTreeOid: string }>;
296
+
297
+ resolveVaultEntry(options: { slug: string }): Promise<string>;
298
+
299
+ getVaultMetadata(): Promise<VaultMetadata | null>;
169
300
  }
package/index.js CHANGED
@@ -6,7 +6,9 @@
6
6
  import { createReadStream, writeFileSync } from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import CasService from './src/domain/services/CasService.js';
9
+ import VaultService from './src/domain/services/VaultService.js';
9
10
  import GitPersistenceAdapter from './src/infrastructure/adapters/GitPersistenceAdapter.js';
11
+ import GitRefAdapter from './src/infrastructure/adapters/GitRefAdapter.js';
10
12
  import NodeCryptoAdapter from './src/infrastructure/adapters/NodeCryptoAdapter.js';
11
13
  import Manifest from './src/domain/value-objects/Manifest.js';
12
14
  import Chunk from './src/domain/value-objects/Chunk.js';
@@ -16,7 +18,9 @@ import CborCodec from './src/infrastructure/codecs/CborCodec.js';
16
18
 
17
19
  export {
18
20
  CasService,
21
+ VaultService,
19
22
  GitPersistenceAdapter,
23
+ GitRefAdapter,
20
24
  NodeCryptoAdapter,
21
25
  CryptoPort,
22
26
  Manifest,
@@ -44,8 +48,8 @@ async function getDefaultCryptoAdapter() {
44
48
  /**
45
49
  * High-level facade for the Content Addressable Store library.
46
50
  *
47
- * Wraps {@link CasService} with lazy initialization, runtime-adaptive crypto
48
- * selection, and convenience helpers for file I/O.
51
+ * Wraps {@link CasService} and {@link VaultService} with lazy initialization,
52
+ * runtime-adaptive crypto selection, and convenience helpers for file I/O.
49
53
  */
50
54
  export default class ContentAddressableStore {
51
55
  /**
@@ -68,6 +72,8 @@ export default class ContentAddressableStore {
68
72
  this.#servicePromise = null;
69
73
  }
70
74
 
75
+ /** @type {VaultService|null} */
76
+ #vault = null;
71
77
  #servicePromise = null;
72
78
 
73
79
  /**
@@ -83,7 +89,7 @@ export default class ContentAddressableStore {
83
89
  }
84
90
 
85
91
  /**
86
- * Constructs the persistence adapter, resolves crypto, and creates the CasService.
92
+ * Constructs adapters, resolves crypto, and creates CasService + VaultService.
87
93
  * @private
88
94
  * @returns {Promise<CasService>}
89
95
  */
@@ -100,9 +106,26 @@ export default class ContentAddressableStore {
100
106
  crypto,
101
107
  merkleThreshold: this.merkleThresholdConfig,
102
108
  });
109
+
110
+ const ref = new GitRefAdapter({
111
+ plumbing: this.plumbing,
112
+ policy: this.policyConfig,
113
+ });
114
+ this.#vault = new VaultService({ persistence, ref, crypto });
115
+
103
116
  return this.service;
104
117
  }
105
118
 
119
+ /**
120
+ * Lazily initializes and returns the underlying {@link VaultService}.
121
+ * @private
122
+ * @returns {Promise<VaultService>}
123
+ */
124
+ async #getVault() {
125
+ await this.#getService();
126
+ return this.#vault;
127
+ }
128
+
106
129
  /**
107
130
  * Lazily initializes and returns the underlying {@link CasService}.
108
131
  * @returns {Promise<CasService>}
@@ -111,6 +134,14 @@ export default class ContentAddressableStore {
111
134
  return await this.#getService();
112
135
  }
113
136
 
137
+ /**
138
+ * Lazily initializes and returns the underlying {@link VaultService}.
139
+ * @returns {Promise<VaultService>}
140
+ */
141
+ async getVaultService() {
142
+ return await this.#getVault();
143
+ }
144
+
114
145
  /**
115
146
  * Factory to create a CAS with JSON codec.
116
147
  * @param {Object} options
@@ -170,10 +201,6 @@ export default class ContentAddressableStore {
170
201
 
171
202
  /**
172
203
  * Reads a file from disk and stores it in Git as chunked blobs.
173
- *
174
- * Convenience wrapper that opens a read stream and delegates to
175
- * {@link CasService#store}.
176
- *
177
204
  * @param {Object} options
178
205
  * @param {string} options.filePath - Absolute or relative path to the file.
179
206
  * @param {string} options.slug - Logical identifier for the stored asset.
@@ -282,7 +309,6 @@ export default class ContentAddressableStore {
282
309
 
283
310
  /**
284
311
  * Returns deletion metadata for an asset stored in a Git tree.
285
- * Does not perform any destructive Git operations.
286
312
  * @param {Object} options
287
313
  * @param {string} options.treeOid - Git tree OID of the asset.
288
314
  * @returns {Promise<{ slug: string, chunksOrphaned: number }>}
@@ -294,7 +320,6 @@ export default class ContentAddressableStore {
294
320
 
295
321
  /**
296
322
  * Aggregates referenced chunk blob OIDs across multiple stored assets.
297
- * Analysis only — does not delete or modify anything.
298
323
  * @param {Object} options
299
324
  * @param {string[]} options.treeOids - Git tree OIDs to analyze.
300
325
  * @returns {Promise<{ referenced: Set<string>, total: number }>}
@@ -321,4 +346,46 @@ export default class ContentAddressableStore {
321
346
  const service = await this.#getService();
322
347
  return await service.deriveKey(options);
323
348
  }
349
+
350
+ // ---------------------------------------------------------------------------
351
+ // Vault — delegates to VaultService
352
+ // ---------------------------------------------------------------------------
353
+
354
+ static VAULT_REF = VaultService.VAULT_REF;
355
+
356
+ /** @see VaultService#initVault */
357
+ async initVault(options) {
358
+ const vault = await this.#getVault();
359
+ return vault.initVault(options);
360
+ }
361
+
362
+ /** @see VaultService#addToVault */
363
+ async addToVault(options) {
364
+ const vault = await this.#getVault();
365
+ return vault.addToVault(options);
366
+ }
367
+
368
+ /** @see VaultService#listVault */
369
+ async listVault() {
370
+ const vault = await this.#getVault();
371
+ return vault.listVault();
372
+ }
373
+
374
+ /** @see VaultService#removeFromVault */
375
+ async removeFromVault(options) {
376
+ const vault = await this.#getVault();
377
+ return vault.removeFromVault(options);
378
+ }
379
+
380
+ /** @see VaultService#resolveVaultEntry */
381
+ async resolveVaultEntry(options) {
382
+ const vault = await this.#getVault();
383
+ return vault.resolveVaultEntry(options);
384
+ }
385
+
386
+ /** @see VaultService#getVaultMetadata */
387
+ async getVaultMetadata() {
388
+ const vault = await this.#getVault();
389
+ return vault.getVaultMetadata();
390
+ }
324
391
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "2.0.0",
3
+ "version": "3.0.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",
@@ -0,0 +1,445 @@
1
+ /**
2
+ * @fileoverview Domain service for vault (GC-safe ref-based asset index) operations.
3
+ */
4
+ import CasError from '../errors/CasError.js';
5
+
6
+ const VAULT_REF = 'refs/cas/vault';
7
+ const MAX_CAS_RETRIES = 3;
8
+ const CAS_RETRY_BASE_MS = 50;
9
+
10
+ /**
11
+ * Percent-encodes a vault slug for use as a git tree entry name.
12
+ * Git tree entry names cannot contain '/'.
13
+ * @param {string} slug
14
+ * @returns {string}
15
+ */
16
+ function encodeSlug(slug) {
17
+ return slug.replaceAll('%', '%25').replaceAll('/', '%2F');
18
+ }
19
+
20
+ /**
21
+ * Decodes a percent-encoded tree entry name back to a vault slug.
22
+ * @param {string} name
23
+ * @returns {string}
24
+ */
25
+ function decodeSlug(name) {
26
+ return name.replaceAll('%2F', '/').replaceAll('%25', '%');
27
+ }
28
+
29
+ /**
30
+ * Returns true if the string contains ASCII control characters (0x00–0x1f, 0x7f).
31
+ * @param {string} str
32
+ * @returns {boolean}
33
+ */
34
+ function hasControlChars(str) {
35
+ for (let i = 0; i < str.length; i++) {
36
+ const code = str.charCodeAt(i);
37
+ if (code <= 0x1f || code === 0x7f) {
38
+ return true;
39
+ }
40
+ }
41
+ return false;
42
+ }
43
+
44
+ /**
45
+ * Domain service for vault operations.
46
+ *
47
+ * The vault is a GC-safe ref-based index that maps slugs to Git tree OIDs.
48
+ * It is backed by a single Git ref (`refs/cas/vault`) pointing to a commit
49
+ * chain. Each commit's tree contains one entry per stored asset plus a
50
+ * `.vault.json` metadata blob.
51
+ *
52
+ * Requires three ports:
53
+ * - `persistence` ({@link GitPersistencePort}) for blob/tree read/write
54
+ * - `ref` ({@link GitRefPort}) for ref resolution, commits, and atomic updates
55
+ * - `crypto` ({@link CryptoPort}) for KDF when vault-level encryption is enabled
56
+ */
57
+ export default class VaultService {
58
+ static VAULT_REF = VAULT_REF;
59
+
60
+ /**
61
+ * @param {Object} options
62
+ * @param {import('../../../src/ports/GitPersistencePort.js').default} options.persistence
63
+ * @param {import('../../../src/ports/GitRefPort.js').default} options.ref
64
+ * @param {import('../../../src/ports/CryptoPort.js').default} options.crypto
65
+ */
66
+ constructor({ persistence, ref, crypto }) {
67
+ this.persistence = persistence;
68
+ this.ref = ref;
69
+ this.crypto = crypto;
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // Slug validation
74
+ // ---------------------------------------------------------------------------
75
+
76
+ /**
77
+ * Validates a single slug segment.
78
+ * @private
79
+ */
80
+ static #validateSegment(seg, slug) {
81
+ if (seg.length === 0) {
82
+ throw new CasError('Slug contains empty segment', 'INVALID_SLUG', { slug });
83
+ }
84
+ if (seg === '.' || seg === '..') {
85
+ throw new CasError('Slug contains "." or ".." segment', 'INVALID_SLUG', { slug });
86
+ }
87
+ if (Buffer.byteLength(seg, 'utf8') > 255) {
88
+ throw new CasError('Slug segment exceeds 255 bytes', 'INVALID_SLUG', { slug });
89
+ }
90
+ if (hasControlChars(seg)) {
91
+ throw new CasError('Slug contains control characters', 'INVALID_SLUG', { slug });
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Validates a vault slug.
97
+ * @param {string} slug
98
+ * @throws {CasError} INVALID_SLUG if the slug is invalid.
99
+ */
100
+ validateSlug(slug) {
101
+ if (typeof slug !== 'string' || slug.length === 0) {
102
+ throw new CasError('Slug must be a non-empty string', 'INVALID_SLUG', { slug });
103
+ }
104
+ if (slug.startsWith('/') || slug.endsWith('/')) {
105
+ throw new CasError('Slug must not start or end with "/"', 'INVALID_SLUG', { slug });
106
+ }
107
+ if (Buffer.byteLength(slug, 'utf8') > 1024) {
108
+ throw new CasError('Slug exceeds 1024 bytes total', 'INVALID_SLUG', { slug });
109
+ }
110
+ for (const seg of slug.split('/')) {
111
+ VaultService.#validateSegment(seg, slug);
112
+ }
113
+ }
114
+
115
+ // ---------------------------------------------------------------------------
116
+ // Metadata validation
117
+ // ---------------------------------------------------------------------------
118
+
119
+ /**
120
+ * Validates encryption-specific metadata fields.
121
+ * @private
122
+ */
123
+ static #validateEncryption(encryption, metadata) {
124
+ const { cipher, kdf } = encryption;
125
+ if (!cipher || !kdf?.algorithm || !kdf?.salt || !kdf?.keyLength) {
126
+ throw new CasError(
127
+ 'Vault encryption metadata missing required fields',
128
+ 'VAULT_METADATA_INVALID',
129
+ { metadata },
130
+ );
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Validates vault metadata object structure.
136
+ * @private
137
+ */
138
+ static #validateMetadata(metadata) {
139
+ if (typeof metadata.version !== 'number' || metadata.version !== 1) {
140
+ throw new CasError(
141
+ `Unsupported vault metadata version: ${metadata.version}`,
142
+ 'VAULT_METADATA_INVALID',
143
+ { metadata },
144
+ );
145
+ }
146
+ if (metadata.encryption) {
147
+ VaultService.#validateEncryption(metadata.encryption, metadata);
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Reads and validates vault metadata from a blob OID.
153
+ * @private
154
+ */
155
+ async #readMetadataBlob(blobOid) {
156
+ try {
157
+ const blob = await this.persistence.readBlob(blobOid);
158
+ const metadata = JSON.parse(blob.toString());
159
+ VaultService.#validateMetadata(metadata);
160
+ return metadata;
161
+ } catch (err) {
162
+ if (err instanceof CasError) { throw err; }
163
+ throw new CasError(
164
+ `Failed to parse .vault.json: ${err.message}`,
165
+ 'VAULT_METADATA_INVALID',
166
+ { originalError: err },
167
+ );
168
+ }
169
+ }
170
+
171
+ // ---------------------------------------------------------------------------
172
+ // State read / write
173
+ // ---------------------------------------------------------------------------
174
+
175
+ /**
176
+ * Separates vault tree entries into slug→OID map and metadata blob OID.
177
+ * @private
178
+ * @param {Array<{ mode: string, type: string, oid: string, name: string }>} treeEntries
179
+ */
180
+ static #parseTreeEntries(treeEntries) {
181
+ const entries = new Map();
182
+ let metadataBlobOid = null;
183
+ for (const entry of treeEntries) {
184
+ if (entry.name === '.vault.json') {
185
+ metadataBlobOid = entry.oid;
186
+ } else {
187
+ entries.set(decodeSlug(entry.name), entry.oid);
188
+ }
189
+ }
190
+ return { entries, metadataBlobOid };
191
+ }
192
+
193
+ /**
194
+ * Reads the current vault state from refs/cas/vault.
195
+ * @returns {Promise<{ entries: Map<string, string>, parentCommitOid: string|null, metadata: object|null }>}
196
+ */
197
+ async readState() {
198
+ let commitOid;
199
+ try {
200
+ commitOid = await this.ref.resolveRef(VAULT_REF);
201
+ } catch {
202
+ return { entries: new Map(), parentCommitOid: null, metadata: null };
203
+ }
204
+
205
+ const treeOid = await this.ref.resolveTree(commitOid);
206
+ const rawEntries = await this.persistence.readTree(treeOid);
207
+ const { entries, metadataBlobOid } = VaultService.#parseTreeEntries(rawEntries);
208
+ const metadata = metadataBlobOid
209
+ ? await this.#readMetadataBlob(metadataBlobOid)
210
+ : null;
211
+
212
+ return { entries, parentCommitOid: commitOid, metadata };
213
+ }
214
+
215
+ /**
216
+ * Writes a new vault commit and updates the ref atomically.
217
+ * @param {Object} options
218
+ * @param {Map<string, string>} options.entries - Slug→treeOid map.
219
+ * @param {object} options.metadata - Vault metadata (.vault.json contents).
220
+ * @param {string|null} options.parentCommitOid - Parent commit OID (null for first commit).
221
+ * @param {string} options.message - Commit message.
222
+ * @returns {Promise<{ commitOid: string }>}
223
+ */
224
+ async writeCommit({ entries, metadata, parentCommitOid, message }) {
225
+ const metadataBlob = await this.persistence.writeBlob(
226
+ JSON.stringify(metadata, null, 2),
227
+ );
228
+
229
+ const treeLines = [`100644 blob ${metadataBlob}\t.vault.json`];
230
+ for (const [slug, treeOid] of entries) {
231
+ treeLines.push(`040000 tree ${treeOid}\t${encodeSlug(slug)}`);
232
+ }
233
+
234
+ const newTreeOid = await this.persistence.writeTree(treeLines);
235
+
236
+ const commitOid = await this.ref.createCommit({
237
+ treeOid: newTreeOid,
238
+ parentOid: parentCommitOid,
239
+ message,
240
+ });
241
+ await this.#casUpdateRef(commitOid, parentCommitOid);
242
+ return { commitOid };
243
+ }
244
+
245
+ /**
246
+ * Atomically updates the vault ref with CAS semantics.
247
+ * @private
248
+ */
249
+ async #casUpdateRef(newOid, expectedOldOid) {
250
+ try {
251
+ await this.ref.updateRef({
252
+ ref: VAULT_REF,
253
+ newOid,
254
+ expectedOldOid,
255
+ });
256
+ } catch (err) {
257
+ throw new CasError(
258
+ 'Concurrent vault update detected',
259
+ 'VAULT_CONFLICT',
260
+ { expectedParent: expectedOldOid, newCommit: newOid, originalError: err },
261
+ );
262
+ }
263
+ }
264
+
265
+ /**
266
+ * Wraps a vault mutation with CAS retry logic.
267
+ * @private
268
+ * @param {function} mutationFn - Async function(state) → { entries, metadata, message }
269
+ * @returns {Promise<{ commitOid: string }>}
270
+ */
271
+ async #retryMutation(mutationFn) {
272
+ for (let attempt = 0; attempt < MAX_CAS_RETRIES; attempt++) {
273
+ const state = await this.readState();
274
+ const { entries, metadata, message } = await mutationFn(state);
275
+ try {
276
+ return await this.writeCommit({
277
+ entries, metadata, parentCommitOid: state.parentCommitOid, message,
278
+ });
279
+ } catch (err) {
280
+ const isRetryable = err instanceof CasError && err.code === 'VAULT_CONFLICT';
281
+ if (!isRetryable || attempt >= MAX_CAS_RETRIES - 1) {
282
+ throw err;
283
+ }
284
+ const delay = CAS_RETRY_BASE_MS * (2 ** attempt);
285
+ await new Promise((r) => setTimeout(r, delay));
286
+ }
287
+ }
288
+ /* c8 ignore next 2 */
289
+ throw new CasError('Vault CAS retries exhausted', 'VAULT_CONFLICT');
290
+ }
291
+
292
+ // ---------------------------------------------------------------------------
293
+ // Encryption helpers
294
+ // ---------------------------------------------------------------------------
295
+
296
+ /**
297
+ * Builds vault encryption metadata from KDF result.
298
+ * @private
299
+ */
300
+ static #buildEncryptionMeta(salt, params) {
301
+ return {
302
+ cipher: 'aes-256-gcm',
303
+ kdf: {
304
+ algorithm: params.algorithm,
305
+ salt: salt.toString('base64'),
306
+ ...('iterations' in params && { iterations: params.iterations }),
307
+ ...('cost' in params && { cost: params.cost }),
308
+ ...('blockSize' in params && { blockSize: params.blockSize }),
309
+ ...('parallelization' in params && { parallelization: params.parallelization }),
310
+ keyLength: params.keyLength,
311
+ },
312
+ };
313
+ }
314
+
315
+ // ---------------------------------------------------------------------------
316
+ // Public API
317
+ // ---------------------------------------------------------------------------
318
+
319
+ /**
320
+ * Initializes the vault, optionally with encryption.
321
+ * @param {Object} [options]
322
+ * @param {string} [options.passphrase] - Passphrase for vault-level encryption.
323
+ * @param {Object} [options.kdfOptions] - KDF options (algorithm, iterations, etc.).
324
+ * @returns {Promise<{ commitOid: string }>}
325
+ */
326
+ async initVault({ passphrase, kdfOptions } = {}) {
327
+ const state = await this.readState();
328
+
329
+ if (state.metadata?.encryption) {
330
+ throw new CasError(
331
+ 'Vault encryption is already configured',
332
+ 'VAULT_ENCRYPTION_ALREADY_CONFIGURED',
333
+ );
334
+ }
335
+
336
+ const metadata = { version: 1 };
337
+ if (passphrase) {
338
+ const { salt, params } = await this.crypto.deriveKey({ passphrase, ...kdfOptions });
339
+ metadata.encryption = VaultService.#buildEncryptionMeta(salt, params);
340
+ }
341
+
342
+ return await this.writeCommit({
343
+ entries: state.entries,
344
+ metadata,
345
+ parentCommitOid: state.parentCommitOid,
346
+ message: 'vault: init',
347
+ });
348
+ }
349
+
350
+ /**
351
+ * Adds or updates an entry in the vault.
352
+ * @param {Object} options
353
+ * @param {string} options.slug - Entry slug.
354
+ * @param {string} options.treeOid - Git tree OID.
355
+ * @param {boolean} [options.force=false] - Overwrite existing entry.
356
+ * @returns {Promise<{ commitOid: string }>}
357
+ */
358
+ async addToVault({ slug, treeOid, force = false }) {
359
+ this.validateSlug(slug);
360
+
361
+ return await this.#retryMutation((state) => {
362
+ if (state.entries.has(slug) && !force) {
363
+ throw new CasError(
364
+ `Vault entry "${slug}" already exists (use force to overwrite)`,
365
+ 'VAULT_ENTRY_EXISTS',
366
+ { slug },
367
+ );
368
+ }
369
+ const isUpdate = state.entries.has(slug);
370
+ state.entries.set(slug, treeOid);
371
+ return {
372
+ entries: state.entries,
373
+ metadata: state.metadata || { version: 1 },
374
+ message: isUpdate ? `vault: update ${slug}` : `vault: add ${slug}`,
375
+ };
376
+ });
377
+ }
378
+
379
+ /**
380
+ * Lists all vault entries.
381
+ * @returns {Promise<Array<{ slug: string, treeOid: string }>>}
382
+ */
383
+ async listVault() {
384
+ const { entries } = await this.readState();
385
+ return [...entries.entries()]
386
+ .map(([slug, treeOid]) => ({ slug, treeOid }))
387
+ .sort((a, b) => a.slug.localeCompare(b.slug));
388
+ }
389
+
390
+ /**
391
+ * Removes an entry from the vault.
392
+ * @param {Object} options
393
+ * @param {string} options.slug - Entry slug to remove.
394
+ * @returns {Promise<{ commitOid: string, removedTreeOid: string }>}
395
+ */
396
+ async removeFromVault({ slug }) {
397
+ let removedTreeOid;
398
+
399
+ const result = await this.#retryMutation((state) => {
400
+ if (!state.entries.has(slug)) {
401
+ throw new CasError(
402
+ `Vault entry "${slug}" not found`,
403
+ 'VAULT_ENTRY_NOT_FOUND',
404
+ { slug },
405
+ );
406
+ }
407
+ removedTreeOid = state.entries.get(slug);
408
+ state.entries.delete(slug);
409
+ return {
410
+ entries: state.entries,
411
+ metadata: state.metadata || { version: 1 },
412
+ message: `vault: remove ${slug}`,
413
+ };
414
+ });
415
+
416
+ return { commitOid: result.commitOid, removedTreeOid };
417
+ }
418
+
419
+ /**
420
+ * Resolves a vault entry slug to its tree OID.
421
+ * @param {Object} options
422
+ * @param {string} options.slug - Entry slug.
423
+ * @returns {Promise<string>} The tree OID.
424
+ */
425
+ async resolveVaultEntry({ slug }) {
426
+ const { entries } = await this.readState();
427
+ if (!entries.has(slug)) {
428
+ throw new CasError(
429
+ `Vault entry "${slug}" not found`,
430
+ 'VAULT_ENTRY_NOT_FOUND',
431
+ { slug },
432
+ );
433
+ }
434
+ return entries.get(slug);
435
+ }
436
+
437
+ /**
438
+ * Returns the vault metadata, or null if no vault exists.
439
+ * @returns {Promise<object|null>}
440
+ */
441
+ async getVaultMetadata() {
442
+ const { metadata } = await this.readState();
443
+ return metadata;
444
+ }
445
+ }
@@ -2,27 +2,27 @@ import { Policy } from '@git-stunts/alfred';
2
2
  import GitPersistencePort from '../../ports/GitPersistencePort.js';
3
3
  import CasError from '../../domain/errors/CasError.js';
4
4
 
5
- /** Default resilience policy: 30 s timeout wrapping 2 retries with exponential backoff. */
6
- const DEFAULT_POLICY = Policy.timeout(30_000).wrap(
7
- Policy.retry({
8
- retries: 2,
9
- backoff: 'exponential',
10
- delay: 100,
11
- maxDelay: 2_000,
12
- }),
13
- );
5
+ /**
6
+ * Default resilience policy: 30 s timeout (no retry).
7
+ *
8
+ * Plumbing already retries lock-contention errors internally via
9
+ * {@link ExecutionOrchestrator}, so an additional alfred retry layer is
10
+ * unnecessary and causes premature process exit: alfred's retry sleep uses
11
+ * an unref'd timer that allows Node to exit before the next attempt starts.
12
+ */
13
+ const DEFAULT_POLICY = Policy.timeout(30_000);
14
14
 
15
15
  /**
16
16
  * {@link GitPersistencePort} implementation backed by `@git-stunts/plumbing`.
17
17
  *
18
18
  * All Git I/O is wrapped with a configurable resilience {@link Policy}
19
- * (timeout + retry by default).
19
+ * (30 s timeout by default).
20
20
  */
21
21
  export default class GitPersistenceAdapter extends GitPersistencePort {
22
22
  /**
23
23
  * @param {Object} options
24
24
  * @param {import('@git-stunts/plumbing').default} options.plumbing - GitPlumbing instance.
25
- * @param {import('@git-stunts/alfred').Policy} [options.policy] - Resilience policy (defaults to 30 s timeout + 2 retries).
25
+ * @param {import('@git-stunts/alfred').Policy} [options.policy] - Resilience policy (defaults to 30 s timeout, no retry).
26
26
  */
27
27
  constructor({ plumbing, policy }) {
28
28
  super();
@@ -0,0 +1,67 @@
1
+ import { Policy } from '@git-stunts/alfred';
2
+ import GitRefPort from '../../ports/GitRefPort.js';
3
+
4
+ /**
5
+ * Default resilience policy: 30 s timeout (no retry).
6
+ *
7
+ * Plumbing already retries lock-contention errors internally via
8
+ * {@link ExecutionOrchestrator}, so an additional alfred retry layer is
9
+ * unnecessary and causes premature process exit: alfred's retry sleep uses
10
+ * an unref'd timer that allows Node to exit before the next attempt starts.
11
+ */
12
+ const DEFAULT_POLICY = Policy.timeout(30_000);
13
+
14
+ /**
15
+ * {@link GitRefPort} implementation backed by `@git-stunts/plumbing`.
16
+ *
17
+ * All Git I/O is wrapped with a configurable resilience {@link Policy}
18
+ * (30 s timeout by default).
19
+ */
20
+ export default class GitRefAdapter extends GitRefPort {
21
+ /**
22
+ * @param {Object} options
23
+ * @param {import('@git-stunts/plumbing').default} options.plumbing - GitPlumbing instance.
24
+ * @param {import('@git-stunts/alfred').Policy} [options.policy] - Resilience policy.
25
+ */
26
+ constructor({ plumbing, policy }) {
27
+ super();
28
+ this.plumbing = plumbing;
29
+ this.policy = policy ?? DEFAULT_POLICY;
30
+ }
31
+
32
+ /** @override */
33
+ async resolveRef(ref) {
34
+ return this.policy.execute(() =>
35
+ this.plumbing.execute({ args: ['rev-parse', ref] }),
36
+ );
37
+ }
38
+
39
+ /** @override */
40
+ async resolveTree(commitOid) {
41
+ return this.policy.execute(() =>
42
+ this.plumbing.execute({ args: ['rev-parse', `${commitOid}^{tree}`] }),
43
+ );
44
+ }
45
+
46
+ /** @override */
47
+ async createCommit({ treeOid, parentOid, message }) {
48
+ const args = ['commit-tree', treeOid, '-m', message];
49
+ if (parentOid) {
50
+ args.push('-p', parentOid);
51
+ }
52
+ return this.policy.execute(() =>
53
+ this.plumbing.execute({ args }),
54
+ );
55
+ }
56
+
57
+ /** @override */
58
+ async updateRef({ ref, newOid, expectedOldOid }) {
59
+ const args = ['update-ref', ref, newOid];
60
+ if (expectedOldOid) {
61
+ args.push(expectedOldOid);
62
+ }
63
+ return this.policy.execute(() =>
64
+ this.plumbing.execute({ args }),
65
+ );
66
+ }
67
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Abstract port for Git ref and commit operations.
3
+ * @abstract
4
+ */
5
+ export default class GitRefPort {
6
+ /**
7
+ * Resolves a Git ref to its commit OID.
8
+ * @param {string} ref - Git ref (e.g. 'refs/cas/vault').
9
+ * @returns {Promise<string>} The commit OID.
10
+ * @throws If the ref does not exist.
11
+ */
12
+ async resolveRef(_ref) {
13
+ throw new Error('Not implemented');
14
+ }
15
+
16
+ /**
17
+ * Resolves the tree OID from a commit OID.
18
+ * @param {string} commitOid - Git commit OID.
19
+ * @returns {Promise<string>} The tree OID.
20
+ */
21
+ async resolveTree(_commitOid) {
22
+ throw new Error('Not implemented');
23
+ }
24
+
25
+ /**
26
+ * Creates a Git commit object.
27
+ * @param {Object} options
28
+ * @param {string} options.treeOid - Tree OID for the commit.
29
+ * @param {string|null} [options.parentOid] - Parent commit OID (null for root commit).
30
+ * @param {string} options.message - Commit message.
31
+ * @returns {Promise<string>} The new commit OID.
32
+ */
33
+ async createCommit(_options) {
34
+ throw new Error('Not implemented');
35
+ }
36
+
37
+ /**
38
+ * Atomically updates a Git ref with optional CAS (compare-and-swap) semantics.
39
+ * @param {Object} options
40
+ * @param {string} options.ref - Git ref to update.
41
+ * @param {string} options.newOid - New OID to set.
42
+ * @param {string|null} [options.expectedOldOid] - Expected current OID for CAS. If provided and mismatched, throws.
43
+ * @returns {Promise<void>}
44
+ */
45
+ async updateRef(_options) {
46
+ throw new Error('Not implemented');
47
+ }
48
+ }