@agencer/reverie-loop 0.1.0-alpha.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,71 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@agencer/reverie-loop`.
4
+
5
+ ## 0.1.0-alpha.0
6
+
7
+ Initial alpha release. Extracted from the agencer-ox
8
+ `packages/server/src/services/reverie-logger.ts` source.
9
+
10
+ Shipped:
11
+
12
+ - `ReverieLogger` class: synchronous, append-only JSONL writer with a
13
+ single `logDir` and two output files (`reveries.jsonl`,
14
+ `whisper-results.jsonl`), both filenames overridable.
15
+ Constructor validates `logDir` (required, non-empty) and both
16
+ filenames (plain basename, no path separators). Methods:
17
+ `logReverie`, `logWhisperResult`, `readReverieLog`,
18
+ `readWhisperResultLog`, `close`.
19
+ - Module-level compat API: `initReverieLogger`, `logReverie`,
20
+ `logWhisperResult`, `readReverieLog`, `readWhisperResultLog`,
21
+ `resetReverieLoggerSingletonForTests`. Function signatures match
22
+ the extracted source so callsite migration in agencer-ox is a
23
+ one-line import change. Pre-init calls are silent no-ops.
24
+ `read*Log(logDir)` with an explicit directory honors the active
25
+ singleton's custom filenames when set (internal consistency with
26
+ writes).
27
+ - Types: `ReverieEntry`, `WhisperResultEntry`, `ReverieFailureReason`,
28
+ `ReverieLoggerConfig`.
29
+ - Constants: `DEFAULT_REVERIE_FILENAME`,
30
+ `DEFAULT_WHISPER_RESULT_FILENAME`,
31
+ `WHISPER_RESULT_USER_MESSAGE_MAX_LENGTH` (200).
32
+ - 24 unit tests (logger / compat) covering JSONL format for both
33
+ files, append semantics, dual-file separation, 200-char
34
+ user_message truncation for whisper results, custom filenames,
35
+ nested-dir auto-create, torn-line resilience, both-filename path
36
+ traversal guards, init-time validation, and the NEVER-throws
37
+ runtime discipline for unwritable disks. First tests this code
38
+ has ever shipped with: the extracted source had zero coverage.
39
+
40
+ Hardened vs the extracted source:
41
+
42
+ - **Lenient `read*Log`.** One bad line no longer erases the entire
43
+ diagnostic view. Per-line `JSON.parse` with torn-line skip.
44
+ - **Init-time config validation.** Missing/empty `logDir` and
45
+ path-traversal filenames throw at construction instead of being
46
+ silently swallowed by the runtime catch-all. The NEVER-throws
47
+ discipline is intentionally scoped to the runtime path, not the
48
+ config path.
49
+ - **Filename path-traversal guards.** Both `reverieFilename` and
50
+ `whisperResultFilename` must be plain basenames so env-driven or
51
+ attacker-influenced config cannot redirect writes outside `logDir`.
52
+
53
+ Breaking changes vs the extracted source:
54
+
55
+ - The `~/.operative-x/training-data` default path is removed.
56
+ `logDir` is now a required config field. OX, O2, and future
57
+ consumers each wire their own path at startup (Hot-Swappable
58
+ Providers principle).
59
+
60
+ Known limitations (tracked for alpha.1):
61
+
62
+ - Single-process write safety. `appendFileSync` relies on `O_APPEND`
63
+ atomicity, which only guarantees atomic writes under `PIPE_BUF`
64
+ (~4 KB). Large exchanges from concurrent writers may interleave.
65
+ - Synchronous I/O on the caller's thread. A wedged disk or slow
66
+ network mount blocks the event loop. Async variant tracked for
67
+ alpha.1.
68
+ - `read*Log` reads the whole file — diagnostic only, not for large
69
+ production logs.
70
+
71
+ Apache-2.0 license.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
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 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 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 those 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. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # @agencer/reverie-loop
2
+
3
+ Append-only JSONL writer for reverie training signals. One of three signal sources for the Agencer Learning Loop (alongside `session-logger` and `whisper-router`).
4
+
5
+ Extracted from agencer-ox. Path-configurable so every consumer (OX, O2, future Agencer master) owns its own filesystem namespace without forking.
6
+
7
+ ## What ships
8
+
9
+ - **`ReverieLogger`** class: `logReverie`, `logWhisperResult`, `readReverieLog`, `readWhisperResultLog`, `close`.
10
+ - **Module compat API**: `initReverieLogger`, `logReverie`, `logWhisperResult`, `readReverieLog`, `readWhisperResultLog`, `resetReverieLoggerSingletonForTests` — drop-in for the legacy `services/reverie-logger.ts` callsites.
11
+ - **Types**: `ReverieEntry`, `WhisperResultEntry`, `ReverieFailureReason`, `ReverieLoggerConfig`.
12
+
13
+ ## Two files, one logger
14
+
15
+ Writes are split across two JSONL files inside the configured `logDir`:
16
+
17
+ - `reveries.jsonl` — whisper-failure deltas. Each entry captures `user_message`, `mini_response` (whisper output), `opus_response` (the rescue), `failure_reason` (`weak_response | user_corrected | timeout | error`), `whisper_model_id`, ISO-8601 `timestamp`. This is the training signal for whisper-model fine-tuning.
18
+ - `whisper-results.jsonl` — whisper model outcomes for monitoring. Each entry captures `outcome` (`success | failure`), `model_id`, `user_message` (truncated to 200 chars), `response_length`, `timestamp`.
19
+
20
+ Both filenames are overridable via `reverieFilename` / `whisperResultFilename`.
21
+
22
+ ## NEVER-throws discipline (runtime only)
23
+
24
+ Runtime methods swallow write and parse errors internally — failed `mkdir`, read-only disk, corrupt line, none propagate into the voice pipeline.
25
+
26
+ The **constructor is the exception**: invalid config (`logDir` empty/missing, either filename containing a path separator or `..`) throws synchronously. Misconfiguration is a programmer bug, silencing it hides deploy problems.
27
+
28
+ `readReverieLog` / `readWhisperResultLog` are lenient: torn/corrupt lines are skipped, valid records around them are returned. One bad tail line after a crash does not erase the log.
29
+
30
+ ## Known limitations (alpha.0)
31
+
32
+ - **Single-process, single-writer.** `appendFileSync` relies on POSIX `O_APPEND` atomicity, which only guarantees atomic writes under `PIPE_BUF` (~4 KB). Multi-process writers on the same file may interleave on larger exchanges.
33
+ - **Synchronous I/O.** `log*` blocks the event loop for the duration of the syscalls. Sub-millisecond on local disk, dangerous on a wedged network mount. Async variant tracked for alpha.1.
34
+ - **`read*Log` reads the whole file.** Tests and diagnostics only. For large logs, stream-read the JSONL directly.
35
+ - **`user_message` truncation for whisper results is pre-write.** Matches the extracted source semantics so the learning-loop `sync.py` ingestion shape stays stable.
36
+
37
+ ## Usage
38
+
39
+ ### OX-style consumer (compat API)
40
+
41
+ ```ts
42
+ import { homedir } from "node:os";
43
+ import path from "node:path";
44
+ import {
45
+ initReverieLogger,
46
+ logReverie,
47
+ logWhisperResult,
48
+ } from "@agencer/reverie-loop";
49
+
50
+ initReverieLogger({
51
+ logDir: path.join(homedir(), ".operative-x", "training-data"),
52
+ });
53
+
54
+ logReverie(userText, miniResponse, opusResponse, "weak_response", modelId);
55
+ logWhisperResult("success", modelId, userText, assistantResponse);
56
+ ```
57
+
58
+ ### O2-style consumer (class API, custom filenames)
59
+
60
+ ```ts
61
+ import path from "node:path";
62
+ import { ReverieLogger } from "@agencer/reverie-loop";
63
+
64
+ const logger = new ReverieLogger({
65
+ logDir: path.join(process.cwd(), "data", "training"),
66
+ reverieFilename: "o2-reveries.jsonl",
67
+ whisperResultFilename: "o2-whisper-outcomes.jsonl",
68
+ });
69
+
70
+ logger.logReverie(u, m, o, "timeout", modelId);
71
+ ```
72
+
73
+ ## What this Lego deliberately does NOT do
74
+
75
+ - **No rescue-decision logic.** *When* to fire a reverie — weak-response thresholds, timeouts, user-correction detection — lives in the caller. This Lego is an append-only writer.
76
+ - **No anonymization.** PII stripping belongs downstream in sync, not at write time.
77
+ - **No hardcoded path.** `config.logDir` is required; the legacy `~/.operative-x/training-data` default is removed.
78
+ - **No buffering.** `close()` is a no-op today, reserved for future fd pooling.
79
+
80
+ ## License
81
+
82
+ Apache-2.0. See `LICENSE`.
@@ -0,0 +1,22 @@
1
+ import { type ReverieEntry, type ReverieFailureReason, type ReverieLoggerConfig, type WhisperResultEntry } from "./types.js";
2
+ export declare function initReverieLogger(config: ReverieLoggerConfig): void;
3
+ export declare function logReverie(userMessage: string, miniResponse: string, opusResponse: string, failureReason: ReverieFailureReason, whisperModelId: string): void;
4
+ export declare function logWhisperResult(outcome: "success" | "failure", modelId: string, userMessage: string, response: string): void;
5
+ /**
6
+ * Read the reverie log.
7
+ *
8
+ * Callers may pass an explicit directory (used in tests and diagnostic tools),
9
+ * or rely on the directory set by {@link initReverieLogger}. With no init and
10
+ * no argument, returns `[]`.
11
+ *
12
+ * When an explicit `logDir` is given AND a singleton has been initialized with
13
+ * a custom `reverieFilename`, the singleton's filename is honored. This keeps
14
+ * the compat API internally consistent: writes and reads target the same file.
15
+ */
16
+ export declare function readReverieLog(logDir?: string): ReverieEntry[];
17
+ /**
18
+ * Read the whisper-result log. Same explicit-dir / singleton-filename semantics
19
+ * as {@link readReverieLog}.
20
+ */
21
+ export declare function readWhisperResultLog(logDir?: string): WhisperResultEntry[];
22
+ export declare function resetReverieLoggerSingletonForTests(): void;
package/dist/compat.js ADDED
@@ -0,0 +1,81 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { ReverieLogger } from "./logger.js";
4
+ import { DEFAULT_REVERIE_FILENAME, DEFAULT_WHISPER_RESULT_FILENAME, } from "./types.js";
5
+ // Module-level singleton. Mirrors the dual-API shape of @agencer/session-logger.
6
+ // Calls without a prior `initReverieLogger` are silent no-ops (preserves the
7
+ // "NEVER break caller" discipline even when init is forgotten).
8
+ let singleton = null;
9
+ export function initReverieLogger(config) {
10
+ singleton = new ReverieLogger(config);
11
+ }
12
+ export function logReverie(userMessage, miniResponse, opusResponse, failureReason, whisperModelId) {
13
+ if (!singleton)
14
+ return;
15
+ singleton.logReverie(userMessage, miniResponse, opusResponse, failureReason, whisperModelId);
16
+ }
17
+ export function logWhisperResult(outcome, modelId, userMessage, response) {
18
+ if (!singleton)
19
+ return;
20
+ singleton.logWhisperResult(outcome, modelId, userMessage, response);
21
+ }
22
+ function readJsonlLenient(logPath) {
23
+ try {
24
+ if (!fs.existsSync(logPath))
25
+ return [];
26
+ const raw = fs.readFileSync(logPath, "utf-8");
27
+ const out = [];
28
+ for (const line of raw.split("\n")) {
29
+ if (line.length === 0)
30
+ continue;
31
+ try {
32
+ out.push(JSON.parse(line));
33
+ }
34
+ catch {
35
+ // Skip torn/corrupt lines, keep valid records.
36
+ }
37
+ }
38
+ return out;
39
+ }
40
+ catch {
41
+ return [];
42
+ }
43
+ }
44
+ /**
45
+ * Read the reverie log.
46
+ *
47
+ * Callers may pass an explicit directory (used in tests and diagnostic tools),
48
+ * or rely on the directory set by {@link initReverieLogger}. With no init and
49
+ * no argument, returns `[]`.
50
+ *
51
+ * When an explicit `logDir` is given AND a singleton has been initialized with
52
+ * a custom `reverieFilename`, the singleton's filename is honored. This keeps
53
+ * the compat API internally consistent: writes and reads target the same file.
54
+ */
55
+ export function readReverieLog(logDir) {
56
+ if (logDir !== undefined) {
57
+ const filename = singleton ? singleton.reverieFilename : DEFAULT_REVERIE_FILENAME;
58
+ return readJsonlLenient(path.join(logDir, filename));
59
+ }
60
+ if (!singleton)
61
+ return [];
62
+ return singleton.readReverieLog();
63
+ }
64
+ /**
65
+ * Read the whisper-result log. Same explicit-dir / singleton-filename semantics
66
+ * as {@link readReverieLog}.
67
+ */
68
+ export function readWhisperResultLog(logDir) {
69
+ if (logDir !== undefined) {
70
+ const filename = singleton
71
+ ? singleton.whisperResultFilename
72
+ : DEFAULT_WHISPER_RESULT_FILENAME;
73
+ return readJsonlLenient(path.join(logDir, filename));
74
+ }
75
+ if (!singleton)
76
+ return [];
77
+ return singleton.readWhisperResultLog();
78
+ }
79
+ export function resetReverieLoggerSingletonForTests() {
80
+ singleton = null;
81
+ }
@@ -0,0 +1,5 @@
1
+ export declare const VERSION = "0.1.0-alpha.0";
2
+ export type { ReverieEntry, ReverieFailureReason, ReverieLoggerConfig, WhisperResultEntry, } from "./types.js";
3
+ export { DEFAULT_REVERIE_FILENAME, DEFAULT_WHISPER_RESULT_FILENAME, WHISPER_RESULT_USER_MESSAGE_MAX_LENGTH, } from "./types.js";
4
+ export { ReverieLogger } from "./logger.js";
5
+ export { initReverieLogger, logReverie, logWhisperResult, readReverieLog, readWhisperResultLog, resetReverieLoggerSingletonForTests, } from "./compat.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export const VERSION = "0.1.0-alpha.0";
2
+ export { DEFAULT_REVERIE_FILENAME, DEFAULT_WHISPER_RESULT_FILENAME, WHISPER_RESULT_USER_MESSAGE_MAX_LENGTH, } from "./types.js";
3
+ export { ReverieLogger } from "./logger.js";
4
+ export { initReverieLogger, logReverie, logWhisperResult, readReverieLog, readWhisperResultLog, resetReverieLoggerSingletonForTests, } from "./compat.js";
@@ -0,0 +1,22 @@
1
+ import { type ReverieEntry, type ReverieFailureReason, type ReverieLoggerConfig, type WhisperResultEntry } from "./types.js";
2
+ export declare class ReverieLogger {
3
+ #private;
4
+ constructor(config: ReverieLoggerConfig);
5
+ /** Package-private: used by the compat API to honor custom filenames on explicit-dir reads. */
6
+ get reverieFilename(): string;
7
+ /** Package-private: used by the compat API to honor custom filenames on explicit-dir reads. */
8
+ get whisperResultFilename(): string;
9
+ /**
10
+ * Log a reverie: the whisper model failed, Opus took over.
11
+ * The delta between the two responses is a training signal.
12
+ */
13
+ logReverie(userMessage: string, miniResponse: string, opusResponse: string, failureReason: ReverieFailureReason, whisperModelId: string): void;
14
+ /**
15
+ * Log a whisper model result (success or failure) for monitoring.
16
+ */
17
+ logWhisperResult(outcome: "success" | "failure", modelId: string, userMessage: string, response: string): void;
18
+ readReverieLog(): ReverieEntry[];
19
+ readWhisperResultLog(): WhisperResultEntry[];
20
+ /** Reserved for future fd pooling. No-op today; safe to call repeatedly. */
21
+ close(): void;
22
+ }
package/dist/logger.js ADDED
@@ -0,0 +1,134 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { DEFAULT_REVERIE_FILENAME, DEFAULT_WHISPER_RESULT_FILENAME, WHISPER_RESULT_USER_MESSAGE_MAX_LENGTH, } from "./types.js";
4
+ // NEVER let log{Reverie,WhisperResult} break the caller. Constructor-time
5
+ // errors (invalid config) throw — those are programmer bugs, not runtime
6
+ // failures, and silencing them hides misconfiguration. Runtime write/parse
7
+ // errors swallow so the voice pipeline never fails because of logging.
8
+ function validateFilename(name, field) {
9
+ // Prevent path-traversal via filename config. Must be a plain basename
10
+ // inside the configured logDir, not a relative path.
11
+ if (name.length === 0 ||
12
+ name.includes("/") ||
13
+ name.includes("\\") ||
14
+ name === "." ||
15
+ name === "..") {
16
+ throw new Error(`ReverieLogger: invalid ${field} "${name}" — must be a plain basename with no path separators`);
17
+ }
18
+ }
19
+ function parseLinesLenient(raw) {
20
+ // Per-line try/catch: one torn tail line must not erase the whole log.
21
+ // This matters after crashes, ENOSPC, or power loss — the very situations
22
+ // where diagnostic tools most need to read the log.
23
+ const out = [];
24
+ for (const line of raw.split("\n")) {
25
+ if (line.length === 0)
26
+ continue;
27
+ try {
28
+ out.push(JSON.parse(line));
29
+ }
30
+ catch {
31
+ // Skip the malformed line, keep the rest.
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+ export class ReverieLogger {
37
+ #logDir;
38
+ #reverieFilename;
39
+ #whisperResultFilename;
40
+ constructor(config) {
41
+ if (typeof config.logDir !== "string" || config.logDir.length === 0) {
42
+ throw new Error("ReverieLogger: config.logDir is required and must be a non-empty string");
43
+ }
44
+ const reverieFilename = config.reverieFilename ?? DEFAULT_REVERIE_FILENAME;
45
+ const whisperResultFilename = config.whisperResultFilename ?? DEFAULT_WHISPER_RESULT_FILENAME;
46
+ validateFilename(reverieFilename, "reverieFilename");
47
+ validateFilename(whisperResultFilename, "whisperResultFilename");
48
+ if (reverieFilename === whisperResultFilename) {
49
+ // Mixing both schemas into one file would silently poison both reads:
50
+ // readers type-cast every line to the requested type without filtering
51
+ // by the `type` discriminator. Catch the env-var typo at init.
52
+ throw new Error(`ReverieLogger: reverieFilename and whisperResultFilename must differ (both were "${reverieFilename}")`);
53
+ }
54
+ this.#logDir = config.logDir;
55
+ this.#reverieFilename = reverieFilename;
56
+ this.#whisperResultFilename = whisperResultFilename;
57
+ }
58
+ /** Package-private: used by the compat API to honor custom filenames on explicit-dir reads. */
59
+ get reverieFilename() {
60
+ return this.#reverieFilename;
61
+ }
62
+ /** Package-private: used by the compat API to honor custom filenames on explicit-dir reads. */
63
+ get whisperResultFilename() {
64
+ return this.#whisperResultFilename;
65
+ }
66
+ /**
67
+ * Log a reverie: the whisper model failed, Opus took over.
68
+ * The delta between the two responses is a training signal.
69
+ */
70
+ logReverie(userMessage, miniResponse, opusResponse, failureReason, whisperModelId) {
71
+ try {
72
+ fs.mkdirSync(this.#logDir, { recursive: true });
73
+ const entry = {
74
+ type: "reverie",
75
+ user_message: userMessage,
76
+ mini_response: miniResponse,
77
+ opus_response: opusResponse,
78
+ failure_reason: failureReason,
79
+ whisper_model_id: whisperModelId,
80
+ timestamp: new Date().toISOString(),
81
+ };
82
+ fs.appendFileSync(path.join(this.#logDir, this.#reverieFilename), JSON.stringify(entry) + "\n");
83
+ }
84
+ catch {
85
+ // swallow — logging must never break the voice pipeline
86
+ }
87
+ }
88
+ /**
89
+ * Log a whisper model result (success or failure) for monitoring.
90
+ */
91
+ logWhisperResult(outcome, modelId, userMessage, response) {
92
+ try {
93
+ fs.mkdirSync(this.#logDir, { recursive: true });
94
+ const entry = {
95
+ type: "whisper_result",
96
+ outcome,
97
+ model_id: modelId,
98
+ user_message: userMessage.slice(0, WHISPER_RESULT_USER_MESSAGE_MAX_LENGTH),
99
+ response_length: response.length,
100
+ timestamp: new Date().toISOString(),
101
+ };
102
+ fs.appendFileSync(path.join(this.#logDir, this.#whisperResultFilename), JSON.stringify(entry) + "\n");
103
+ }
104
+ catch {
105
+ // swallow — logging must never break the voice pipeline
106
+ }
107
+ }
108
+ readReverieLog() {
109
+ try {
110
+ const logPath = path.join(this.#logDir, this.#reverieFilename);
111
+ if (!fs.existsSync(logPath))
112
+ return [];
113
+ return parseLinesLenient(fs.readFileSync(logPath, "utf-8"));
114
+ }
115
+ catch {
116
+ return [];
117
+ }
118
+ }
119
+ readWhisperResultLog() {
120
+ try {
121
+ const logPath = path.join(this.#logDir, this.#whisperResultFilename);
122
+ if (!fs.existsSync(logPath))
123
+ return [];
124
+ return parseLinesLenient(fs.readFileSync(logPath, "utf-8"));
125
+ }
126
+ catch {
127
+ return [];
128
+ }
129
+ }
130
+ /** Reserved for future fd pooling. No-op today; safe to call repeatedly. */
131
+ close() {
132
+ // no-op
133
+ }
134
+ }
@@ -0,0 +1,34 @@
1
+ export type ReverieFailureReason = "weak_response" | "user_corrected" | "timeout" | "error";
2
+ export interface ReverieEntry {
3
+ type: "reverie";
4
+ user_message: string;
5
+ mini_response: string;
6
+ opus_response: string;
7
+ failure_reason: ReverieFailureReason;
8
+ whisper_model_id: string;
9
+ timestamp: string;
10
+ }
11
+ export interface WhisperResultEntry {
12
+ type: "whisper_result";
13
+ outcome: "success" | "failure";
14
+ model_id: string;
15
+ user_message: string;
16
+ response_length: number;
17
+ timestamp: string;
18
+ }
19
+ export interface ReverieLoggerConfig {
20
+ /** Absolute directory to write the JSONL files into. Required. */
21
+ readonly logDir: string;
22
+ /** Filename inside {@link logDir} for reverie entries. Default: "reveries.jsonl". */
23
+ readonly reverieFilename?: string;
24
+ /** Filename inside {@link logDir} for whisper-result entries. Default: "whisper-results.jsonl". */
25
+ readonly whisperResultFilename?: string;
26
+ }
27
+ export declare const DEFAULT_REVERIE_FILENAME = "reveries.jsonl";
28
+ export declare const DEFAULT_WHISPER_RESULT_FILENAME = "whisper-results.jsonl";
29
+ /**
30
+ * Max stored length for `WhisperResultEntry.user_message`. The legacy
31
+ * source truncated to 200 chars; the Lego preserves that to keep the
32
+ * ingestion shape stable for the learning-loop `sync.py` pipeline.
33
+ */
34
+ export declare const WHISPER_RESULT_USER_MESSAGE_MAX_LENGTH = 200;
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ export const DEFAULT_REVERIE_FILENAME = "reveries.jsonl";
2
+ export const DEFAULT_WHISPER_RESULT_FILENAME = "whisper-results.jsonl";
3
+ /**
4
+ * Max stored length for `WhisperResultEntry.user_message`. The legacy
5
+ * source truncated to 200 chars; the Lego preserves that to keep the
6
+ * ingestion shape stable for the learning-loop `sync.py` pipeline.
7
+ */
8
+ export const WHISPER_RESULT_USER_MESSAGE_MAX_LENGTH = 200;
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@agencer/reverie-loop",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "Append-only JSONL writer for reverie training signals (whisper-failure deltas + whisper model outcomes). One of three signal sources for the Agencer Learning Loop (alongside session-logger and whisper-router). Path-configurable, NEVER-throws discipline.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "CHANGELOG.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsc",
22
+ "prepack": "tsc",
23
+ "test": "vitest run --passWithNoTests",
24
+ "typecheck": "tsc --noEmit"
25
+ },
26
+ "publishConfig": {
27
+ "registry": "https://registry.npmjs.org"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^20.0.0",
31
+ "typescript": "^5.5.0",
32
+ "vitest": "^1.4.0"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/Agencer-Inc/operative-shared.git"
37
+ },
38
+ "license": "Apache-2.0"
39
+ }