@devicerail/recorder 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 DeviceRail contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,111 @@
1
+ # `@devicerail/recorder`
2
+
3
+ `@devicerail/recorder` records the public DeviceRail Session event stream into
4
+ a durable, resumable checkpoint. It orders exclusively by `TestEvent.sequence`,
5
+ preserves event and Action correlation, and stores typed Evidence references
6
+ rather than screenshot or video bytes.
7
+
8
+ The package sits above `@devicerail/client` and `@devicerail/protocol`. It has
9
+ no Driver, ADB, AI SDK, prompt, YAML, visualizer, or product UI dependency.
10
+
11
+ ## Completion boundary
12
+
13
+ A checkpoint is an internal recovery artifact, not a second archive format and
14
+ not proof that recording completed. Completion requires an ended Session, an
15
+ exact `session.export` match, and successful export and independent validation
16
+ through the local Rust `devicerail-bundle` CLI. The CLI remains the sole Session
17
+ Bundle writer and validator; this package does not reimplement its manifest or
18
+ Evidence integrity rules.
19
+
20
+ The daemon must be stopped before Bundle export so the CLI can acquire the
21
+ filesystem Evidence Store's exclusive lock. Until export atomically publishes
22
+ the Bundle, callers must not clear the Session or its Evidence and must not
23
+ restart the daemon: startup reconciliation may release the stopped process's
24
+ orphaned Evidence pins. Once export succeeds, independent validation reads only
25
+ the Bundle and may run after a daemon restart. Retain the checkpoint until that
26
+ validation succeeds.
27
+
28
+ The intended lifecycle is `ExecutionRecorder.open` → `captureOnce` or
29
+ `captureUntilSealed` → `publishSource` → close the client/daemon → `finalize`.
30
+ `ExecutionRecorder.openOffline` resumes a sealed or completed checkpoint after
31
+ shutdown without pretending an active in-memory daemon Session can be restored.
32
+ Finalization takes an explicit absolute path to the `devicerail-bundle` binary
33
+ and invokes it with fixed arguments and `shell: false`; package import never
34
+ probes for or starts that binary.
35
+
36
+ ## Recovery limits
37
+
38
+ Duplicate delivery is idempotent only when the complete event value matches.
39
+ Sequence gaps, out-of-order events, cross-Session events, lifecycle violations,
40
+ and incomplete Action pairs fail explicitly. Cancellation may retain a durable
41
+ checkpoint but never publishes a completed recording.
42
+
43
+ Protocol 1.4 media start/frame/end events are checkpointed as typed Evidence
44
+ references. Stream IDs remain lifetime-unique for the whole Session, including
45
+ after a stream has ended; reuse fails before a checkpoint can advance.
46
+
47
+ The current `events.list` and `session.export` RPC methods do not accept
48
+ request-control options. Recorder cancellation is therefore observed before
49
+ and after each call and during polling/checkpoint/CLI work; interrupting a
50
+ stuck stdio call requires the host to close the client connection.
51
+
52
+ The current stdio transport limits each `events.list` and `session.export`
53
+ response to 1 MiB. Recorder starts at 1000 events per page and, on the typed
54
+ `response_frame_too_large` failure, halves that limit until the page fits. The
55
+ successful smaller limit is reused for later pages; if one event still cannot
56
+ fit, recording fails explicitly as `event_too_large`. Recorder advances
57
+ `afterSequence` and durably commits each accepted event page before requesting
58
+ the next, so a missed suffix does not need to fit in one response.
59
+
60
+ When `session.export.page.v1` was negotiated and the configured event source
61
+ implements `exportSessionPage`, sealing applies the same bounded retry policy to
62
+ the authoritative export. Every page must repeat one stable ended `SessionInfo`
63
+ and must exactly match the corresponding durable checkpoint events. Reading
64
+ pages never advances the checkpoint; only the fully verified export performs
65
+ the single `recording` to `sealed` revision CAS. Without that negotiated
66
+ capability Recorder retains the legacy complete `session.export` behavior.
67
+ Concurrent seal callers share one in-flight verification and successful CAS,
68
+ but keep independent cancellation: an aborted waiter returns immediately
69
+ without cancelling the owner, while a non-cancelled waiter may retry after an
70
+ owner cancellation leaves the checkpoint recording.
71
+ Concurrent seal attempts on one Recorder share a successful verification and
72
+ CAS, while each caller retains independent cancellation: aborting a waiter does
73
+ not cancel the owner, and a non-cancelled waiter retries after a cancelled
74
+ owner operation.
75
+
76
+ Pagination removes the RPC single-frame bottleneck; it does not remove the
77
+ local snapshot limit. The complete Bundle Source must still fit its explicit
78
+ 8 MiB bound, below the Session Bundle's default 16 MiB manifest budget. The
79
+ checkpoint permits a separate fixed 64 KiB envelope/phase headroom so a valid
80
+ near-limit Source can advance through sealed and completed without losing room
81
+ for its checksum and receipt metadata. Sessions whose Source exceeds 8 MiB
82
+ require a future segmented checkpoint and streaming Bundle Source contract. The
83
+ current daemon also uses a process-local Event Store, so recovery of an active
84
+ Session requires the same daemon and connection to remain alive. A sealed,
85
+ terminal checkpoint can be finalized offline before restarting the daemon.
86
+
87
+ Recording pages are persisted in an explicitly versioned, checksummed sidecar
88
+ journal. Each commit appends only the accepted page and atomically advances a
89
+ small journal head, so `P` fixed-size pages write `O(N + P)` bytes instead of
90
+ rewriting `P` growing prefixes. A checksum chain binds every committed page;
91
+ bytes written before a head publication are ignored and truncated on the next
92
+ append. Recovery validates the complete chain once, and the `recording` to
93
+ `sealed` transition compacts it into one canonical checkpoint snapshot. The
94
+ 8 MiB Source and checkpoint bounds, per-page fsync, revision CAS, owner-only
95
+ metadata checks, and fail-closed corruption behavior remain unchanged.
96
+
97
+ The in-memory `EventLog` follows the same boundary: batch preparation validates
98
+ against overlay indexes without copying the confirmed prefix, and the prefix is
99
+ materialized only when a snapshot is requested or sealing begins. Public
100
+ speculative `fork()` calls still copy identity indexes to preserve independent
101
+ branch mutation and are not used by Recorder page capture.
102
+
103
+ On Unix, checkpoint and Source files must be owned by the current user with no
104
+ group/world permission bits, and directory fsync closes the normal power-loss
105
+ window. Node.js exposes neither portable Windows owner-only ACL verification
106
+ nor directory fsync. Recorder therefore does not claim or enforce owner-only
107
+ access on Windows; deployments must provide a suitably ACL-restricted parent
108
+ directory. It still checks regular-file identity and retains file flush plus
109
+ atomic replace/no-clobber semantics, with final directory durability left to
110
+ the filesystem. Stale writer locks are reclaimed only when the OS confirms
111
+ their PID no longer exists; ambiguous or reused PIDs fail closed.
@@ -0,0 +1,13 @@
1
+ import { type BundleSourceFile } from "./source-file.js";
2
+ import type { RecorderBundleReceipt } from "./types.js";
3
+ export type BundleSource = BundleSourceFile;
4
+ export interface BundleFinalizeOptions {
5
+ readonly executable: string;
6
+ readonly sourcePath: string;
7
+ readonly evidenceDirectory: string;
8
+ readonly outputDirectory: string;
9
+ readonly source: BundleSource;
10
+ readonly signal?: AbortSignal;
11
+ }
12
+ /** Runs the existing Rust Bundle writer and validator without a shell. */
13
+ export declare function exportAndValidateBundle(options: BundleFinalizeOptions): Promise<RecorderBundleReceipt>;
@@ -0,0 +1,311 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open } from "node:fs/promises";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { dirname, isAbsolute, join } from "node:path";
6
+ import { RecorderError } from "./errors.js";
7
+ import { validateBundleSourceFile, } from "./source-file.js";
8
+ const COMMAND_OUTPUT_MAX_BYTES = 64 * 1024;
9
+ const MANIFEST_MAX_BYTES = 16 * 1024 * 1024;
10
+ function cancelled() {
11
+ throw new RecorderError("operation_cancelled", "Recorder operation was cancelled");
12
+ }
13
+ function appendBounded(chunks, chunk, total) {
14
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
15
+ total.value += bytes.length;
16
+ if (total.value > COMMAND_OUTPUT_MAX_BYTES) {
17
+ return false;
18
+ }
19
+ chunks.push(bytes);
20
+ return true;
21
+ }
22
+ async function runCommand(executable, arguments_, signal) {
23
+ if (signal?.aborted) {
24
+ cancelled();
25
+ }
26
+ if (typeof executable !== "string" || !isAbsolute(executable)) {
27
+ throw new RecorderError("bundle_cli_failed", "Bundle CLI executable must be an absolute path");
28
+ }
29
+ return await new Promise((resolve, reject) => {
30
+ const child = spawn(executable, [...arguments_], {
31
+ shell: false,
32
+ stdio: ["ignore", "pipe", "pipe"],
33
+ windowsHide: true,
34
+ });
35
+ const stdout = [];
36
+ const stderr = [];
37
+ const stdoutBytes = { value: 0 };
38
+ const stderrBytes = { value: 0 };
39
+ let overflow = false;
40
+ let aborted = false;
41
+ let spawnError;
42
+ let forceKillTimer;
43
+ const terminate = () => {
44
+ child.kill(process.platform === "win32" ? undefined : "SIGINT");
45
+ forceKillTimer ??= setTimeout(() => child.kill("SIGKILL"), 2_000);
46
+ forceKillTimer.unref();
47
+ };
48
+ const abortListener = () => {
49
+ aborted = true;
50
+ terminate();
51
+ };
52
+ signal?.addEventListener("abort", abortListener, { once: true });
53
+ child.stdout.on("data", (chunk) => {
54
+ if (!appendBounded(stdout, chunk, stdoutBytes)) {
55
+ overflow = true;
56
+ terminate();
57
+ }
58
+ });
59
+ child.stderr.on("data", (chunk) => {
60
+ if (!appendBounded(stderr, chunk, stderrBytes)) {
61
+ overflow = true;
62
+ terminate();
63
+ }
64
+ });
65
+ child.once("error", (error) => {
66
+ spawnError = error;
67
+ });
68
+ child.once("close", (code) => {
69
+ if (forceKillTimer) {
70
+ clearTimeout(forceKillTimer);
71
+ }
72
+ signal?.removeEventListener("abort", abortListener);
73
+ if (aborted || signal?.aborted) {
74
+ reject(new RecorderError("operation_cancelled", "Bundle CLI operation was cancelled"));
75
+ return;
76
+ }
77
+ if (overflow) {
78
+ reject(new RecorderError("bundle_cli_failed", "Bundle CLI output exceeded the bounded diagnostic limit"));
79
+ return;
80
+ }
81
+ if (spawnError) {
82
+ reject(new RecorderError("bundle_cli_failed", "Bundle CLI could not be started", {
83
+ cause: spawnError,
84
+ }));
85
+ return;
86
+ }
87
+ resolve({
88
+ exitCode: code ?? 1,
89
+ stdout: Buffer.concat(stdout),
90
+ stderr: Buffer.concat(stderr),
91
+ });
92
+ });
93
+ });
94
+ }
95
+ function parseSummary(bytes, operation) {
96
+ let value;
97
+ try {
98
+ const text = bytes.toString("utf8");
99
+ if (!text.endsWith("\n") || text.indexOf("\n") !== text.length - 1) {
100
+ throw new Error("summary must be exactly one newline-terminated JSON value");
101
+ }
102
+ value = JSON.parse(text.slice(0, -1));
103
+ }
104
+ catch (cause) {
105
+ throw new RecorderError("bundle_summary_invalid", "Bundle CLI returned invalid JSON", {
106
+ cause,
107
+ });
108
+ }
109
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
110
+ throw new RecorderError("bundle_summary_invalid", "Bundle CLI summary must be an object");
111
+ }
112
+ const summary = value;
113
+ const keys = Object.keys(summary).sort();
114
+ const expectedKeys = [
115
+ "assetBytes",
116
+ "assetCount",
117
+ "eventCount",
118
+ "ok",
119
+ "operation",
120
+ "sessionId",
121
+ ];
122
+ if (!isDeepStrictEqual(keys, expectedKeys)) {
123
+ throw new RecorderError("bundle_summary_invalid", "Bundle CLI summary fields are invalid");
124
+ }
125
+ if (summary.ok !== true || summary.operation !== operation) {
126
+ throw new RecorderError("bundle_summary_invalid", "Bundle CLI summary operation is invalid");
127
+ }
128
+ if (typeof summary.sessionId !== "string" || summary.sessionId.length === 0) {
129
+ throw new RecorderError("bundle_summary_invalid", "Bundle CLI sessionId is invalid");
130
+ }
131
+ for (const field of ["eventCount", "assetCount", "assetBytes"]) {
132
+ if (!Number.isSafeInteger(summary[field]) ||
133
+ Object.is(summary[field], -0) ||
134
+ summary[field] < 0) {
135
+ throw new RecorderError("bundle_summary_invalid", `Bundle CLI ${field} must be a non-negative safe integer`);
136
+ }
137
+ }
138
+ return summary;
139
+ }
140
+ async function executeCli(executable, arguments_, operation, signal) {
141
+ const result = await runCommand(executable, arguments_, signal);
142
+ if (result.exitCode !== 0) {
143
+ const diagnostic = result.stderr.toString("utf8").trim();
144
+ throw new RecorderError("bundle_cli_failed", `Bundle CLI ${operation} failed`, {
145
+ details: {
146
+ exitCode: result.exitCode,
147
+ ...(diagnostic ? { diagnostic } : {}),
148
+ },
149
+ });
150
+ }
151
+ return parseSummary(result.stdout, operation);
152
+ }
153
+ async function pathExists(path) {
154
+ try {
155
+ await lstat(path);
156
+ return true;
157
+ }
158
+ catch (cause) {
159
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
160
+ return false;
161
+ }
162
+ throw new RecorderError("bundle_cli_failed", "Bundle output metadata is inaccessible", {
163
+ cause,
164
+ });
165
+ }
166
+ }
167
+ function expectedReceipt(source) {
168
+ return {
169
+ sessionId: source.sessionExport.session.id,
170
+ eventCount: source.sessionExport.events.length,
171
+ };
172
+ }
173
+ function verifySummary(summary, source) {
174
+ const expected = expectedReceipt(source);
175
+ if (summary.sessionId !== expected.sessionId || summary.eventCount !== expected.eventCount) {
176
+ throw new RecorderError("bundle_summary_mismatch", "Bundle CLI summary does not identify the sealed recording", { details: { expected, actual: summary } });
177
+ }
178
+ }
179
+ async function verifyManifestIdentity(outputDirectory, source) {
180
+ let bytes;
181
+ try {
182
+ const path = join(outputDirectory, "manifest.json");
183
+ const pathMetadata = await lstat(path);
184
+ if (!pathMetadata.isFile() ||
185
+ pathMetadata.isSymbolicLink() ||
186
+ pathMetadata.size > MANIFEST_MAX_BYTES) {
187
+ throw new Error("manifest is not a bounded regular file");
188
+ }
189
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
190
+ try {
191
+ const opened = await handle.stat();
192
+ if (!opened.isFile() ||
193
+ opened.dev !== pathMetadata.dev ||
194
+ opened.ino !== pathMetadata.ino) {
195
+ throw new Error("manifest changed while it was opened");
196
+ }
197
+ const buffer = Buffer.allocUnsafe(MANIFEST_MAX_BYTES + 1);
198
+ let offset = 0;
199
+ while (offset < buffer.length) {
200
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, null);
201
+ if (bytesRead === 0) {
202
+ break;
203
+ }
204
+ offset += bytesRead;
205
+ }
206
+ if (offset > MANIFEST_MAX_BYTES) {
207
+ throw new Error("manifest exceeds its bounded read limit");
208
+ }
209
+ bytes = buffer.subarray(0, offset);
210
+ }
211
+ finally {
212
+ await handle.close().catch(() => { });
213
+ }
214
+ }
215
+ catch (cause) {
216
+ throw new RecorderError("bundle_summary_mismatch", "Validated Bundle manifest is unreadable", {
217
+ cause,
218
+ });
219
+ }
220
+ let manifest;
221
+ try {
222
+ manifest = JSON.parse(bytes.toString("utf8"));
223
+ }
224
+ catch (cause) {
225
+ throw new RecorderError("bundle_summary_mismatch", "Validated Bundle manifest is invalid", {
226
+ cause,
227
+ });
228
+ }
229
+ if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest)) {
230
+ throw new RecorderError("bundle_summary_mismatch", "Validated Bundle manifest is invalid");
231
+ }
232
+ const record = manifest;
233
+ if (!isDeepStrictEqual(record.eventProtocolVersion, source.eventProtocolVersion) ||
234
+ !isDeepStrictEqual(record.session, source.sessionExport.session) ||
235
+ !isDeepStrictEqual(record.events, source.sessionExport.events)) {
236
+ throw new RecorderError("bundle_summary_mismatch", "Validated Bundle content does not match the sealed recording");
237
+ }
238
+ }
239
+ async function syncOutputParent(outputDirectory) {
240
+ // Rust publication uses MoveFileExW(MOVEFILE_WRITE_THROUGH) on Windows.
241
+ // On Unix this closes the durability-unknown recovery case before the
242
+ // Recorder marks a previously published target complete.
243
+ if (process.platform === "win32") {
244
+ return;
245
+ }
246
+ try {
247
+ const handle = await open(dirname(outputDirectory), "r");
248
+ try {
249
+ await handle.sync();
250
+ }
251
+ finally {
252
+ await handle.close().catch(() => { });
253
+ }
254
+ }
255
+ catch (cause) {
256
+ throw new RecorderError("bundle_cli_failed", "validated Bundle parent-directory durability could not be confirmed", { cause });
257
+ }
258
+ }
259
+ /** Runs the existing Rust Bundle writer and validator without a shell. */
260
+ export async function exportAndValidateBundle(options) {
261
+ // The generated DTO types contain serde-default optionals that are wider
262
+ // than the daemon's canonical output. Reject that lossy shape before the
263
+ // Rust CLI can publish a target that would compare differently afterward.
264
+ const source = validateBundleSourceFile(options.source);
265
+ let exportSummary;
266
+ if (!(await pathExists(options.outputDirectory))) {
267
+ try {
268
+ exportSummary = await executeCli(options.executable, [
269
+ "export",
270
+ "--source",
271
+ options.sourcePath,
272
+ "--evidence-dir",
273
+ options.evidenceDirectory,
274
+ "--output",
275
+ options.outputDirectory,
276
+ ], "export", options.signal);
277
+ verifySummary(exportSummary, source);
278
+ }
279
+ catch (error) {
280
+ // Publication is the Rust writer's linearization point. If it raced the
281
+ // process failure, converge through the independent validator below.
282
+ if (!(await pathExists(options.outputDirectory))) {
283
+ throw error;
284
+ }
285
+ }
286
+ }
287
+ const validateSummary = await executeCli(options.executable, ["validate", options.outputDirectory], "validate", options.signal);
288
+ verifySummary(validateSummary, source);
289
+ if (exportSummary &&
290
+ !isDeepStrictEqual({
291
+ sessionId: exportSummary.sessionId,
292
+ eventCount: exportSummary.eventCount,
293
+ assetCount: exportSummary.assetCount,
294
+ assetBytes: exportSummary.assetBytes,
295
+ }, {
296
+ sessionId: validateSummary.sessionId,
297
+ eventCount: validateSummary.eventCount,
298
+ assetCount: validateSummary.assetCount,
299
+ assetBytes: validateSummary.assetBytes,
300
+ })) {
301
+ throw new RecorderError("bundle_summary_mismatch", "Bundle export and validation summaries disagree");
302
+ }
303
+ await verifyManifestIdentity(options.outputDirectory, source);
304
+ await syncOutputParent(options.outputDirectory);
305
+ return {
306
+ sessionId: validateSummary.sessionId,
307
+ eventCount: validateSummary.eventCount,
308
+ assetCount: validateSummary.assetCount,
309
+ assetBytes: validateSummary.assetBytes,
310
+ };
311
+ }
@@ -0,0 +1,22 @@
1
+ export declare const DEFAULT_CANONICAL_JSON_MAX_BYTES: number;
2
+ export interface CanonicalJsonOptions {
3
+ readonly maxBytes?: number;
4
+ readonly maxDepth?: number;
5
+ readonly maxNodes?: number;
6
+ }
7
+ export declare class CanonicalJsonError extends Error {
8
+ constructor(message: string, options?: ErrorOptions);
9
+ }
10
+ /** Encode one value as compact recursively key-sorted UTF-8 JSON plus one LF. */
11
+ export declare function toCanonicalJson(value: unknown, options?: CanonicalJsonOptions): Buffer;
12
+ /**
13
+ * Encode `{ checkpoint, sha256 }` while visiting the checkpoint value once.
14
+ * The checksum covers the checkpoint's standalone canonical bytes, including
15
+ * its LF, while depth/node limits still apply to the complete envelope.
16
+ */
17
+ export declare function toCanonicalJsonChecksumEnvelope(checkpoint: unknown, options?: CanonicalJsonOptions): Buffer;
18
+ /** Parse JSON only when its bytes are already in the canonical representation. */
19
+ export declare function fromCanonicalJson(bytes: Uint8Array, options?: CanonicalJsonOptions): unknown;
20
+ export declare function sha256Hex(bytes: Uint8Array): string;
21
+ export declare function canonicalSha256(value: unknown, options?: CanonicalJsonOptions): string;
22
+ export declare function sha256Matches(actualBytes: Uint8Array, expectedHex: string): boolean;