@peac/capture-node 0.10.12

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,190 @@
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
+ Copyright 2025-2026 PEAC Protocol Contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,97 @@
1
+ # @peac/capture-node
2
+
3
+ Node.js durable storage for the PEAC capture pipeline. Provides filesystem-backed implementations of the `SpoolStore` and `DedupeIndex` interfaces from `@peac/capture-core`.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @peac/capture-node @peac/capture-core
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { createFsSpoolStore, createFsDedupeIndex } from '@peac/capture-node';
15
+ import { createCaptureSession, createHasher } from '@peac/capture-core';
16
+
17
+ const store = await createFsSpoolStore({
18
+ filePath: '/var/peac/spool.jsonl',
19
+ autoCommitIntervalMs: 5000,
20
+ });
21
+
22
+ const dedupe = await createFsDedupeIndex({
23
+ filePath: '/var/peac/dedupe.idx',
24
+ });
25
+
26
+ const session = createCaptureSession({
27
+ store,
28
+ dedupe,
29
+ hasher: createHasher(),
30
+ });
31
+ ```
32
+
33
+ ## Durability Contract
34
+
35
+ - **`append()`** writes to the OS page cache (no fsync). Fast, but not crash-safe on its own.
36
+ - **`commit()`** calls fsync -- the explicit durability point. Entries written before the last `commit()` survive crashes. Entries after may be lost.
37
+ - **Auto-commit timer** (default 5s) calls `commit()` periodically when dirty. Prevents long unflushed windows. Set `autoCommitIntervalMs: 0` to disable.
38
+
39
+ ### Commit Ordering
40
+
41
+ When used with a dedupe index:
42
+
43
+ 1. Spool `commit()` first (authoritative evidence log)
44
+ 2. Dedupe `commit()` second (best-effort optimization index)
45
+
46
+ If dedupe commit fails after spool commit, worst case is re-emitting some receipts after restart. No evidence is lost. The dedupe index is disposable -- it can be deleted and rebuilt from the spool.
47
+
48
+ ## Corruption Boundaries
49
+
50
+ - **Incomplete last line** (crash artifact): automatically truncated on startup. `onWarning` callback fired.
51
+ - **Malformed JSON mid-file**: spool marked corrupt. No auto-repair -- mid-file corruption could indicate tampering.
52
+ - **Chain linkage broken**: spool marked corrupt. `prev_entry_digest` chain failed verification.
53
+ - **Oversized line** (exceeds `maxLineBytes`): spool marked corrupt. Line was never materialized as a JS string.
54
+
55
+ When corrupt, the spool enters **read-only mode**: new captures are blocked, but export/verify/query tools still operate so the operator can recover salvageable data.
56
+
57
+ ### Pre-Materialization Line Guard
58
+
59
+ The streaming line parser enforces `maxLineBytes` (default 4MB) at the Buffer level, BEFORE converting to a JS string. A single giant line in a spool file cannot cause an OOM crash.
60
+
61
+ ## Diagnostics
62
+
63
+ ```typescript
64
+ import { getFsSpoolDiagnostics } from '@peac/capture-node';
65
+
66
+ const diag = getFsSpoolDiagnostics(store);
67
+ // {
68
+ // mode: 'active' | 'read_only',
69
+ // spoolFull: boolean,
70
+ // spoolCorrupt: boolean,
71
+ // corruptReason?: 'CHAIN_BROKEN' | 'MALFORMED_JSON' | 'LINE_TOO_LARGE',
72
+ // corruptAtSequence?: number,
73
+ // entryCount, fileBytes, maxEntries, maxFileBytes, filePath
74
+ // }
75
+ ```
76
+
77
+ ## Hard-Cap Limits
78
+
79
+ - `maxEntries` (default: 100,000)
80
+ - `maxFileBytes` (default: 100MB)
81
+
82
+ When exceeded, `append()` throws `SpoolFullError`. The session returns `E_CAPTURE_STORE_FAILED` with a clear message. The adapter stays running (hooks, tools) -- only new captures are blocked.
83
+
84
+ ## Reset Procedure
85
+
86
+ 1. Export the evidence bundle (if any salvageable data)
87
+ 2. Stop the plugin/adapter
88
+ 3. Delete: `spool.jsonl`, `spool.jsonl.meta.json`, `dedupe.idx`, `*.lock`
89
+ 4. Restart
90
+
91
+ ## Single-Writer Guard
92
+
93
+ A lockfile (`spool.jsonl.lock`) prevents concurrent writers. Default: fail loudly if lock exists. Stale lock break is opt-in via `lockOptions.allowStaleLockBreak`.
94
+
95
+ ## License
96
+
97
+ Apache-2.0
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @peac/capture-node - Error Types
3
+ */
4
+ /**
5
+ * Why the spool was marked corrupt. Exposed in SpoolDiagnostics.corruptReason.
6
+ */
7
+ export type CorruptReason = 'CHAIN_BROKEN' | 'MALFORMED_JSON' | 'LINE_TOO_LARGE';
8
+ /**
9
+ * Thrown when a spool reaches its hard-cap limits (maxEntries or maxFileBytes).
10
+ *
11
+ * CaptureSession catches this and returns E_CAPTURE_STORE_FAILED.
12
+ * The adapter stays running (hooks fire, tools work) -- only new captures are blocked.
13
+ */
14
+ export declare class SpoolFullError extends Error {
15
+ readonly current: number;
16
+ readonly max: number;
17
+ readonly unit: 'entries' | 'bytes';
18
+ readonly code: "E_SPOOL_FULL";
19
+ constructor(current: number, max: number, unit: 'entries' | 'bytes');
20
+ }
21
+ /**
22
+ * Thrown when spool corruption is detected (linkage, malformed JSON, oversized line).
23
+ *
24
+ * Blocks new appends. Tools still work so the user can export/inspect
25
+ * salvageable data. Operator must take explicit action to clear/reset.
26
+ */
27
+ export declare class SpoolCorruptError extends Error {
28
+ readonly reason: CorruptReason;
29
+ readonly corruptAtSequence?: number | undefined;
30
+ readonly details?: string | undefined;
31
+ readonly code: "E_SPOOL_CORRUPT";
32
+ constructor(reason: CorruptReason, corruptAtSequence?: number | undefined, details?: string | undefined);
33
+ }
34
+ /**
35
+ * Thrown when a lockfile cannot be acquired (another instance holds it).
36
+ */
37
+ export declare class LockfileError extends Error {
38
+ readonly lockPath: string;
39
+ readonly holderPid?: number | undefined;
40
+ readonly code: "E_LOCKFILE";
41
+ constructor(lockPath: string, holderPid?: number | undefined);
42
+ }
43
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;GAEG;AAMH;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,cAAc,GAAG,gBAAgB,GAAG,gBAAgB,CAAC;AAMjF;;;;;GAKG;AACH,qBAAa,cAAe,SAAQ,KAAK;IAIrC,QAAQ,CAAC,OAAO,EAAE,MAAM;IACxB,QAAQ,CAAC,GAAG,EAAE,MAAM;IACpB,QAAQ,CAAC,IAAI,EAAE,SAAS,GAAG,OAAO;IALpC,QAAQ,CAAC,IAAI,EAAG,cAAc,CAAU;gBAG7B,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,SAAS,GAAG,OAAO;CAKrC;AAED;;;;;GAKG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAIxC,QAAQ,CAAC,MAAM,EAAE,aAAa;IAC9B,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM;IACnC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM;IAL3B,QAAQ,CAAC,IAAI,EAAG,iBAAiB,CAAU;gBAGhC,MAAM,EAAE,aAAa,EACrB,iBAAiB,CAAC,EAAE,MAAM,YAAA,EAC1B,OAAO,CAAC,EAAE,MAAM,YAAA;CAS5B;AAED;;GAEG;AACH,qBAAa,aAAc,SAAQ,KAAK;IAIpC,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM;IAJ7B,QAAQ,CAAC,IAAI,EAAG,YAAY,CAAU;gBAG3B,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,YAAA;CAQ9B"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @peac/capture-node - Filesystem Dedupe Index
3
+ *
4
+ * Map-backed deduplication index with append-only file persistence.
5
+ * Last-write-wins on reload (tolerates duplicate lines from crash replay).
6
+ */
7
+ import type { DedupeIndex, DedupeEntry } from '@peac/capture-core';
8
+ export interface FsDedupeIndexOptions {
9
+ /** Path to dedupe.idx file. */
10
+ filePath: string;
11
+ }
12
+ /**
13
+ * Create a filesystem-backed dedupe index.
14
+ */
15
+ export declare function createFsDedupeIndex(options: FsDedupeIndexOptions): Promise<FsDedupeIndex>;
16
+ export declare class FsDedupeIndex implements DedupeIndex {
17
+ private readonly filePath;
18
+ private readonly entries;
19
+ private fd;
20
+ private closed;
21
+ private firstCreate;
22
+ constructor(options: FsDedupeIndexOptions);
23
+ /**
24
+ * Initialize: load existing entries from file.
25
+ */
26
+ init(): Promise<void>;
27
+ get(actionId: string): Promise<DedupeEntry | undefined>;
28
+ set(actionId: string, entry: DedupeEntry): Promise<void>;
29
+ has(actionId: string): Promise<boolean>;
30
+ markEmitted(actionId: string): Promise<boolean>;
31
+ delete(actionId: string): Promise<boolean>;
32
+ size(): Promise<number>;
33
+ clear(): Promise<void>;
34
+ /**
35
+ * Flush pending writes to durable storage.
36
+ *
37
+ * Not part of the DedupeIndex interface (capture-core stays stable).
38
+ * Callers use type guard to detect this method on the concrete type.
39
+ */
40
+ commit(): Promise<void>;
41
+ close(): Promise<void>;
42
+ /**
43
+ * Load entries from the dedupe file.
44
+ * Last-write-wins for duplicate actionIds (handles crash replay).
45
+ */
46
+ private loadFromFile;
47
+ /**
48
+ * Append an operation to the dedupe file (no fsync).
49
+ */
50
+ private appendOp;
51
+ /**
52
+ * fsync the parent directory for directory entry durability on first creation.
53
+ * Best-effort: not all platforms support this (e.g. Windows).
54
+ */
55
+ private fsyncDir;
56
+ private assertNotClosed;
57
+ }
58
+ //# sourceMappingURL=fs-dedupe-index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fs-dedupe-index.d.ts","sourceRoot":"","sources":["../src/fs-dedupe-index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAMnE,MAAM,WAAW,oBAAoB;IACnC,+BAA+B;IAC/B,QAAQ,EAAE,MAAM,CAAC;CAClB;AAeD;;GAEG;AACH,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,aAAa,CAAC,CAI/F;AAMD,qBAAa,aAAc,YAAW,WAAW;IAC/C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAuC;IAC/D,OAAO,CAAC,EAAE,CAA8B;IACxC,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,WAAW,CAAkB;gBAEzB,OAAO,EAAE,oBAAoB;IAIzC;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAuBrB,GAAG,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC;IAKvD,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAQxD,GAAG,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAKvC,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAa/C,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAW1C,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC;IAKvB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAoB5B;;;;;OAKG;IACG,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAoBvB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAmB5B;;;OAGG;YACW,YAAY;IAkD1B;;OAEG;YACW,QAAQ;IAMtB;;;OAGG;YACW,QAAQ;IAUtB,OAAO,CAAC,eAAe;CAKxB"}
@@ -0,0 +1,167 @@
1
+ /**
2
+ * @peac/capture-node - Filesystem Spool Store
3
+ *
4
+ * Append-only JSONL spool with tamper-evident chaining.
5
+ * Production-grade: crash recovery, hard-cap limits, streaming reads,
6
+ * single-writer lockfile, meta file for fast startup, max line guard.
7
+ *
8
+ * Durability model:
9
+ * append() writes without fsync (throughput).
10
+ * commit() fsyncs (durability).
11
+ * Auto-commit timer (default 5s) prevents unflushed windows.
12
+ *
13
+ * Commit ordering (when used with dedupe):
14
+ * Spool commit first, dedupe commit second (best-effort).
15
+ * Spool is the authoritative evidence log; dedupe is an optimization index.
16
+ * If dedupe.commit() fails after spool.commit(), worst case is re-emitting
17
+ * some receipts after restart -- no evidence is lost.
18
+ */
19
+ import type { SpoolStore, SpoolEntry } from '@peac/capture-core';
20
+ import type { CorruptReason } from './errors.js';
21
+ import { type LockOptions } from './lockfile.js';
22
+ export interface FsSpoolStoreOptions {
23
+ /** Path to spool.jsonl. */
24
+ filePath: string;
25
+ /** Maximum entries before spool is full. Default: 100_000. */
26
+ maxEntries?: number;
27
+ /** Maximum file size in bytes before spool is full. Default: 100MB. */
28
+ maxFileBytes?: number;
29
+ /** Maximum allowed line length in bytes during read(). Default: 4MB. */
30
+ maxLineBytes?: number;
31
+ /** Auto-commit interval in ms. Default: 5000 (5s). 0 = disabled. */
32
+ autoCommitIntervalMs?: number;
33
+ /** Lockfile options. */
34
+ lockOptions?: LockOptions;
35
+ /** Warning callback (crash recovery, stale lock, etc.). */
36
+ onWarning?: (msg: string) => void;
37
+ }
38
+ /**
39
+ * Diagnostic snapshot for operator tooling (e.g. /peac-status).
40
+ *
41
+ * Queryable without parsing error strings. Use `getFsSpoolDiagnostics()`
42
+ * or access `store.diagnostics()` on the concrete type.
43
+ */
44
+ export interface SpoolDiagnostics {
45
+ /** Operational mode: 'active' = capturing, 'read_only' = full/corrupt. */
46
+ mode: 'active' | 'read_only';
47
+ /** Whether the spool has reached its hard-cap limit. */
48
+ spoolFull: boolean;
49
+ /** Whether linkage corruption was detected on load. */
50
+ spoolCorrupt: boolean;
51
+ /** Why the spool was marked corrupt. Only set when spoolCorrupt is true. */
52
+ corruptReason?: CorruptReason;
53
+ /** Sequence number where corruption was detected. */
54
+ corruptAtSequence?: number;
55
+ /** Current entry count. */
56
+ entryCount: number;
57
+ /** Current file size in bytes. */
58
+ fileBytes: number;
59
+ /** Configured max entries. */
60
+ maxEntries: number;
61
+ /** Configured max file bytes. */
62
+ maxFileBytes: number;
63
+ /** Path to the spool file. */
64
+ filePath: string;
65
+ }
66
+ /**
67
+ * Create a filesystem-backed spool store.
68
+ *
69
+ * Acquires a single-writer lockfile, loads existing data (or recovers from
70
+ * crash), and returns a SpoolStore ready for use.
71
+ */
72
+ export declare function createFsSpoolStore(options: FsSpoolStoreOptions): Promise<FsSpoolStore>;
73
+ /**
74
+ * Get spool diagnostics from a SpoolStore via type guard.
75
+ *
76
+ * Usage:
77
+ * const diag = getFsSpoolDiagnostics(store);
78
+ * if (diag) { // store is FsSpoolStore }
79
+ */
80
+ export declare function getFsSpoolDiagnostics(store: SpoolStore): SpoolDiagnostics | undefined;
81
+ export declare class FsSpoolStore implements SpoolStore {
82
+ private readonly filePath;
83
+ private readonly metaPath;
84
+ private readonly maxEntries;
85
+ private readonly maxFileBytes;
86
+ private readonly maxLineBytes;
87
+ private readonly autoCommitIntervalMs;
88
+ private readonly lockOptions;
89
+ private readonly onWarning;
90
+ private sequence;
91
+ private headDigest;
92
+ private entryCount;
93
+ private fileBytes;
94
+ private fd;
95
+ private lock;
96
+ private closed;
97
+ private corrupt;
98
+ private corruptReason;
99
+ private corruptAtSequence;
100
+ private firstCreate;
101
+ private dirty;
102
+ private autoCommitTimer;
103
+ constructor(options: FsSpoolStoreOptions);
104
+ /**
105
+ * Initialize: acquire lock, load or recover state, open file handle.
106
+ */
107
+ init(): Promise<void>;
108
+ append(entry: SpoolEntry): Promise<number>;
109
+ commit(): Promise<void>;
110
+ read(fromSequence: number, limit?: number): Promise<SpoolEntry[]>;
111
+ getHeadDigest(): Promise<string>;
112
+ getSequence(): Promise<number>;
113
+ close(): Promise<void>;
114
+ /**
115
+ * Get a diagnostic snapshot for operator tooling.
116
+ *
117
+ * Use `getFsSpoolDiagnostics(store)` if you have a generic SpoolStore
118
+ * reference and need to probe for this method via type guard.
119
+ */
120
+ diagnostics(): SpoolDiagnostics;
121
+ /** Whether the spool has reached its hard-cap limit. */
122
+ get isFull(): boolean;
123
+ /** Whether linkage corruption was detected on load. */
124
+ get isCorrupt(): boolean;
125
+ /** Current entry count. */
126
+ get currentEntryCount(): number;
127
+ /** Current file size in bytes. */
128
+ get currentFileBytes(): number;
129
+ /** Configured max entries. */
130
+ get maxEntryLimit(): number;
131
+ /** Configured max file bytes. */
132
+ get maxBytesLimit(): number;
133
+ /**
134
+ * Try to load state from meta file (fast path).
135
+ * Returns true if meta was valid and loaded.
136
+ */
137
+ private tryLoadMeta;
138
+ /**
139
+ * Full JSONL scan: stream line by line, verify linkage, recover from crash.
140
+ *
141
+ * Uses the custom streaming line parser (streamLines) which enforces
142
+ * maxLineBytes BEFORE materializing the line as a JS string. This prevents
143
+ * memory blowup from a single giant line -- the primary "local file DoS" vector.
144
+ *
145
+ * Crash recovery rules:
146
+ * - Incomplete last line (no trailing newline + invalid JSON): truncate tail only.
147
+ * - Invalid JSON mid-file (before the last line): mark spool_corrupt, do NOT auto-repair.
148
+ * Auto-repair mid-file would mask real tampering.
149
+ */
150
+ private fullScan;
151
+ /**
152
+ * Write meta file for fast startup.
153
+ */
154
+ private writeMeta;
155
+ /**
156
+ * fsync the parent directory for directory entry durability on first creation.
157
+ * Best-effort: not all platforms support this (e.g. Windows).
158
+ */
159
+ private fsyncDir;
160
+ /**
161
+ * Mark the spool as corrupt with a specific reason.
162
+ */
163
+ private setCorrupt;
164
+ private assertNotClosed;
165
+ private assertWritable;
166
+ }
167
+ //# sourceMappingURL=fs-spool-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fs-spool-store.d.ts","sourceRoot":"","sources":["../src/fs-spool-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAe,KAAK,WAAW,EAAmB,MAAM,eAAe,CAAC;AAiB/E,MAAM,WAAW,mBAAmB;IAClC,2BAA2B;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,8DAA8D;IAC9D,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,uEAAuE;IACvE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,wEAAwE;IACxE,YAAY,CAAC,EAAE,MAAM,CAA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