@git-stunts/git-cas 1.6.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 ADDED
@@ -0,0 +1,105 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [1.6.0] — M4 Compass + M5 Sonar + M6 Cartographer (2026-02-06)
11
+
12
+ ### Added
13
+ - `CasService.readManifest({ treeOid })` — reads a Git tree, locates and decodes the manifest, returns a validated `Manifest` value object.
14
+ - `CasService.deleteAsset({ treeOid })` — returns logical deletion metadata (`{ slug, chunksOrphaned }`) without performing destructive Git operations.
15
+ - `CasService.findOrphanedChunks({ treeOids })` — aggregates referenced chunk blob OIDs across multiple assets, returning `{ referenced: Set<string>, total: number }`.
16
+ - Facade pass-throughs for `readManifest`, `deleteAsset`, and `findOrphanedChunks` on `ContentAddressableStore`.
17
+ - New error codes: `MANIFEST_NOT_FOUND`, `GIT_ERROR`.
18
+ - 42 new unit tests across three new test suites.
19
+ - `CasService` now extends `EventEmitter` with lifecycle events:
20
+ `chunk:stored`, `chunk:restored`, `file:stored`, `file:restored`,
21
+ `integrity:pass`, `integrity:fail`, and `error` (guarded).
22
+ - Comprehensive benchmark suite (`test/benchmark/cas.bench.js`) covering
23
+ store, restore, encrypt/decrypt, createTree, verifyIntegrity, and
24
+ JsonCodec vs CborCodec at multiple data sizes.
25
+ - 14 new unit tests for EventEmitter integration.
26
+ - `docs/API.md` — full API reference for all public methods, events, value objects, ports, and error codes.
27
+ - `docs/SECURITY.md` — threat model, AES-256-GCM design, key handling, limitations.
28
+ - `GUIDE.md` — progressive-disclosure guide from zero knowledge to mastery.
29
+ - `examples/` directory with runnable scripts: `store-and-restore.js`, `encrypted-workflow.js`, `progress-tracking.js`.
30
+ - ESLint config now ignores `examples/` directory (runnable scripts use `console.log`).
31
+
32
+ ## [1.3.0] — M3 Launchpad (2026-02-06)
33
+
34
+ ### Added
35
+ - Native Bun support via `BunCryptoAdapter` (uses `Bun.CryptoHasher`).
36
+ - Native Deno/Web standard support via `WebCryptoAdapter` (uses `crypto.subtle`).
37
+ - Automated, secure release workflow (`.github/workflows/release.yml`) with:
38
+ - **NPM OIDC support** including build provenance.
39
+ - **JSR support** via `jsr.json` and automated publishing.
40
+ - **GitHub Releases** with automated release notes.
41
+ - **Idempotency & Version Checks** to prevent failed partial releases.
42
+ - Dynamic runtime detection in `ContentAddressableStore` to pick the best adapter automatically.
43
+ - Hardened `package.json` with repository metadata, engine constraints, and explicit file inclusion.
44
+ - Local quality gates via `pre-push` git hook and `scripts/install-hooks.sh`.
45
+
46
+ ### Changed
47
+ - **Breaking Change:** `CasService` cryptographic methods (`sha256`, `encrypt`, `decrypt`, `verifyIntegrity`) are now asynchronous to support Web Crypto and native optimizations.
48
+ - `ContentAddressableStore` facade methods are now asynchronous to accommodate lazy service initialization and async crypto.
49
+ - Project migrated from `npm` to `pnpm` for faster, more reliable dependency management.
50
+ - CI workflow (`.github/workflows/ci.yml`) now runs on all branches but prevents duplicate runs on PRs.
51
+ - `Dockerfile` now uses `corepack` for pnpm management.
52
+
53
+ ### Fixed
54
+ - Fixed recursion bug in `BunCryptoAdapter` where `randomBytes` shadowed the imported function.
55
+ - Resolved lazy-initialization race condition in `ContentAddressableStore` via promise caching.
56
+ - Fixed state leak in `WebCryptoAdapter` streaming encryption.
57
+ - Consolidated double decrypt calls in integrity tests for better performance.
58
+ - Hardened adapter-level key validation with type checks.
59
+
60
+ ## [1.2.0] — M2 Boomerang (v1.2.0)
61
+
62
+ ### Added
63
+ - `CryptoPort` interface and `NodeCryptoAdapter` — extracted all `node:crypto` usage from the domain layer.
64
+ - `CasService.store()` — accepts `AsyncIterable<Buffer>` sources (renamed from `storeFile`).
65
+ - Multi-stage Dockerfile (Node 22, Bun, Deno) with `docker-compose.yml` for per-runtime testing.
66
+ - BATS parallel test runner (`test/platform/runtimes.bats`).
67
+ - Devcontainer setup (`.devcontainer/`) with all three runtimes + BATS.
68
+ - Encryption key validation (`INVALID_KEY_TYPE`, `INVALID_KEY_LENGTH` error codes).
69
+ - Encryption round-trip unit tests (110 tests including fuzz).
70
+ - Empty file (0-byte) edge case tests.
71
+ - Error-path unit tests for constructors and core failures.
72
+ - Deterministic test digest helper (`digestOf`).
73
+
74
+ ### Changed
75
+ - `CasService` domain layer has zero `node:*` imports — all platform dependencies injected via ports.
76
+ - Constructor requires `crypto` and `codec` params (no defaults); facade supplies them.
77
+ - Facade `storeFile()` now opens the file and delegates to `CasService.store()`.
78
+
79
+ ### Fixed
80
+ - None.
81
+
82
+ ### Security
83
+ - None.
84
+
85
+ ## [1.0.0] - 2025-05-30
86
+
87
+ ### Added
88
+
89
+ - `ContentAddressableStore` facade with `createJson` and `createCbor` factory methods.
90
+ - `CasService` core with `storeFile`, `createTree`, `encrypt`, `decrypt`, and `verifyIntegrity` operations.
91
+ - Hexagonal architecture via `GitPersistencePort` interface and `GitPersistenceAdapter` backed by Git's object database.
92
+ - Pluggable codec system with `JsonCodec` and `CborCodec` implementations.
93
+ - `Manifest` and `Chunk` Zod-validated, frozen value objects.
94
+ - `CasError` custom error class for structured error handling.
95
+ - Streaming AES-256-GCM encryption and decryption.
96
+ - Docker-based test runner for reproducible CI builds.
97
+
98
+ ### Changed
99
+ - None.
100
+
101
+ ### Fixed
102
+ - None.
103
+
104
+ ### Security
105
+ - None.
package/LICENSE ADDED
@@ -0,0 +1,200 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. Please do not remove or change
186
+ the license header template below.
187
+
188
+ Copyright 2026 James Ross <james@flyingrobots.dev>
189
+
190
+ Licensed under the Apache License, Version 2.0 (the "License");
191
+ you may not use this file except in compliance with the License.
192
+ You may obtain a copy of the License at
193
+
194
+ http://www.apache.org/licenses/LICENSE-2.0
195
+
196
+ Unless required by applicable law or agreed to in writing, software
197
+ distributed under the License is distributed on an "AS IS" BASIS,
198
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
199
+ See the License for the specific language governing permissions and
200
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,111 @@
1
+ # @git-stunts/git-cas
2
+
3
+ <img width="420" alt="git-cas" src="https://github.com/user-attachments/assets/e7cb63b9-25b7-4369-b053-4a35962ccee4" />
4
+
5
+ ## JESSIE, STOP—
6
+
7
+ > Hold on. He’s turning Git into a blob store. Let him cook.
8
+
9
+ **Most potent clone available on GitHub (legally).**
10
+
11
+ ### Git, freebased: pure CAS that’ll knock your SHAs off. LFS hates this repo.
12
+
13
+ Git isn’t source control.
14
+ Git is a content-addressed object database.
15
+ We use the object database.
16
+
17
+ `git-cas` chunks files into Git blobs (dedupe for free), optionally encrypts them, and emits a manifest + a real Git tree so you can commit/tag/ref it like any other artifact.
18
+
19
+ ## What you get
20
+
21
+ - **Dedupe for free** Git already hashes objects. We just lean into it.
22
+ - **Chunked storage** big files become stable, reusable blobs.
23
+ - **Optional AES-256-GCM encryption** store secrets without leaking plaintext into the ODB.
24
+ - **Manifests** a tiny explicit index of chunks + metadata (JSON/CBOR).
25
+ - **Tree output** generates standard Git trees so assets snap into commits cleanly.
26
+ - **Full round-trip** store, tree, and restore — get your bytes back, verified.
27
+ - **Lifecycle management** `readManifest`, `deleteAsset`, `findOrphanedChunks` — inspect trees, plan deletions, audit storage.
28
+
29
+ **Use it for:** binary assets, build artifacts, model weights, data packs, secret bundles, weird experiments, etc.
30
+
31
+ ## Usage (Node API)
32
+
33
+ ```js
34
+ import GitPlumbing from '@git-stunts/plumbing';
35
+ import ContentAddressableStore from '@git-stunts/cas';
36
+
37
+ const git = new GitPlumbing({ cwd: './assets-repo' });
38
+ const cas = new ContentAddressableStore({ plumbing: git });
39
+
40
+ // Store a file -> returns a manifest (chunk list + metadata)
41
+ const manifest = await cas.storeFile({
42
+ filePath: './image.png',
43
+ slug: 'my-image',
44
+ encryptionKey: myKeyBuffer, // optional (32 bytes)
45
+ });
46
+
47
+ // Turn the manifest into a Git tree OID
48
+ const treeOid = await cas.createTree({ manifest });
49
+
50
+ // Restore later — get your bytes back, integrity-verified
51
+ await cas.restoreFile({ manifest, outputPath: './restored.png' });
52
+
53
+ // Read the manifest back from a tree OID
54
+ const m = await cas.readManifest({ treeOid });
55
+
56
+ // Lifecycle: inspect deletion impact, find orphaned chunks
57
+ const { slug, chunksOrphaned } = await cas.deleteAsset({ treeOid });
58
+ const { referenced, total } = await cas.findOrphanedChunks({ treeOids: [treeOid] });
59
+ ```
60
+
61
+ ## CLI (git plugin)
62
+
63
+ `git-cas` installs as a Git subcommand:
64
+
65
+ ```bash
66
+ # Store a file — prints manifest JSON
67
+ git cas store ./image.png --slug my-image
68
+
69
+ # Store and get a tree OID directly
70
+ git cas store ./image.png --slug my-image --tree
71
+
72
+ # Create a tree from an existing manifest
73
+ git cas tree --manifest manifest.json
74
+
75
+ # Restore from a tree OID
76
+ git cas restore <tree-oid> --out ./restored.png
77
+
78
+ # Encrypted round-trip (32-byte raw key file)
79
+ git cas store ./secret.bin --slug vault --key-file ./my.key --tree
80
+ git cas restore <tree-oid> --out ./decrypted.bin --key-file ./my.key
81
+ ```
82
+
83
+ ## Why not Git LFS?
84
+
85
+ Because sometimes you want the Git object database to be the store:
86
+
87
+ - deterministic
88
+ - content-addressed
89
+ - locally replicable
90
+ - commit-addressable
91
+
92
+ Also because LFS is, well... LFS.
93
+
94
+ ---
95
+
96
+ > _THIS HASH’LL KNOCK YOUR SHAs OFF! FIRST COMMIT’S FREE, MAN._
97
+
98
+ <img width="420" alt="dhtux" src="https://github.com/user-attachments/assets/f2c13357-22c7-4685-83ce-7eccd747e2fe" />
99
+
100
+ ---
101
+
102
+ ## License
103
+
104
+ Apache-2.0
105
+ Copyright © 2026 [James Ross](https://github.com/flyingrobots)
106
+
107
+ ---
108
+
109
+ <p align="center">
110
+ <sub>Built by <a href="https://github.com/flyingrobots">FLYING ROBOTS</a></sub>
111
+ </p>
package/bin/git-cas.js ADDED
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFileSync } from 'node:fs';
4
+ import { program } from 'commander';
5
+ import GitPlumbing from '@git-stunts/plumbing';
6
+ import ContentAddressableStore from '../index.js';
7
+ import Manifest from '../src/domain/value-objects/Manifest.js';
8
+
9
+ program
10
+ .name('git-cas')
11
+ .description('Content Addressable Storage backed by Git')
12
+ .version('1.3.0');
13
+
14
+ /**
15
+ * Read a 32-byte raw encryption key from a file.
16
+ */
17
+ function readKeyFile(keyFilePath) {
18
+ const key = readFileSync(keyFilePath);
19
+ return key;
20
+ }
21
+
22
+ /**
23
+ * Create a CAS instance for the given working directory.
24
+ */
25
+ function createCas(cwd) {
26
+ const plumbing = new GitPlumbing({ cwd });
27
+ return new ContentAddressableStore({ plumbing });
28
+ }
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // store
32
+ // ---------------------------------------------------------------------------
33
+ program
34
+ .command('store <file>')
35
+ .description('Store a file into Git CAS')
36
+ .requiredOption('--slug <slug>', 'Asset slug identifier')
37
+ .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
38
+ .option('--tree', 'Also create a Git tree and print its OID')
39
+ .option('--cwd <dir>', 'Git working directory', '.')
40
+ .action(async (file, opts) => {
41
+ try {
42
+ 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);
50
+ }
51
+
52
+ const manifest = await cas.storeFile(storeOpts);
53
+
54
+ if (opts.tree) {
55
+ const treeOid = await cas.createTree({ manifest });
56
+ process.stdout.write(`${treeOid }\n`);
57
+ } else {
58
+ process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2) }\n`);
59
+ }
60
+ } catch (err) {
61
+ process.stderr.write(`error: ${err.message}\n`);
62
+ process.exit(1);
63
+ }
64
+ });
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // tree
68
+ // ---------------------------------------------------------------------------
69
+ program
70
+ .command('tree')
71
+ .description('Create a Git tree from a manifest')
72
+ .requiredOption('--manifest <path>', 'Path to manifest JSON file')
73
+ .option('--cwd <dir>', 'Git working directory', '.')
74
+ .action(async (opts) => {
75
+ try {
76
+ const cas = createCas(opts.cwd);
77
+ const raw = readFileSync(opts.manifest, 'utf8');
78
+ const manifest = new Manifest(JSON.parse(raw));
79
+ const treeOid = await cas.createTree({ manifest });
80
+ process.stdout.write(`${treeOid }\n`);
81
+ } catch (err) {
82
+ process.stderr.write(`error: ${err.message}\n`);
83
+ process.exit(1);
84
+ }
85
+ });
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // restore
89
+ // ---------------------------------------------------------------------------
90
+ program
91
+ .command('restore <tree-oid>')
92
+ .description('Restore a file from a Git CAS tree')
93
+ .requiredOption('--out <path>', 'Output file path')
94
+ .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
95
+ .option('--cwd <dir>', 'Git working directory', '.')
96
+ .action(async (treeOid, opts) => {
97
+ try {
98
+ const cas = createCas(opts.cwd);
99
+ 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
+ );
117
+
118
+ const restoreOpts = { manifest };
119
+ if (opts.keyFile) {
120
+ restoreOpts.encryptionKey = readKeyFile(opts.keyFile);
121
+ }
122
+
123
+ const { bytesWritten } = await cas.restoreFile({
124
+ ...restoreOpts,
125
+ outputPath: opts.out,
126
+ });
127
+
128
+ process.stdout.write(`${bytesWritten}\n`);
129
+ } catch (err) {
130
+ process.stderr.write(`error: ${err.message}\n`);
131
+ process.exit(1);
132
+ }
133
+ });
134
+
135
+ program.parse();