@agencer/reverie-loop 0.1.0-alpha.0 → 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/CHANGELOG.md +148 -69
- package/LICENSE +8 -199
- package/README.md +118 -56
- package/dist/contracts.d.ts +161 -0
- package/dist/contracts.d.ts.map +1 -0
- package/dist/contracts.js +28 -0
- package/dist/contracts.js.map +1 -0
- package/dist/index.d.ts +12 -5
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +30 -4
- package/dist/index.js.map +1 -0
- package/dist/logger.d.ts +47 -21
- package/dist/logger.d.ts.map +1 -0
- package/dist/logger.js +44 -107
- package/dist/logger.js.map +1 -0
- package/dist/opus-client.d.ts +60 -0
- package/dist/opus-client.d.ts.map +1 -0
- package/dist/opus-client.js +301 -0
- package/dist/opus-client.js.map +1 -0
- package/dist/pair-sink.d.ts +36 -0
- package/dist/pair-sink.d.ts.map +1 -0
- package/dist/pair-sink.js +132 -0
- package/dist/pair-sink.js.map +1 -0
- package/dist/reverie-loop.d.ts +83 -0
- package/dist/reverie-loop.d.ts.map +1 -0
- package/dist/reverie-loop.js +216 -0
- package/dist/reverie-loop.js.map +1 -0
- package/dist/reverie-trigger.d.ts +67 -0
- package/dist/reverie-trigger.d.ts.map +1 -0
- package/dist/reverie-trigger.js +271 -0
- package/dist/reverie-trigger.js.map +1 -0
- package/package.json +43 -12
- package/dist/compat.d.ts +0 -22
- package/dist/compat.js +0 -81
- package/dist/types.d.ts +0 -34
- package/dist/types.js +0 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,71 +1,150 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
All notable changes to `@agencer/reverie-loop
|
|
4
|
-
|
|
5
|
-
## 0.1.0-
|
|
6
|
-
|
|
7
|
-
Initial
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
- `
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
-
|
|
28
|
-
|
|
29
|
-
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
3
|
+
All notable changes to `@agencer/reverie-loop` will be documented in this file.
|
|
4
|
+
|
|
5
|
+
## [0.1.0] - 2026-05-14
|
|
6
|
+
|
|
7
|
+
Initial release. Reverie Loop — Strange Loop training-signal capture for AI agents — extracted from agencer-ox into a portable Lego with zero `@agencer/*` runtime dependencies and zero `@anthropic-ai/sdk` runtime coupling on the public API.
|
|
8
|
+
|
|
9
|
+
### Public API
|
|
10
|
+
|
|
11
|
+
Six Layer-A interfaces in `contracts.ts`:
|
|
12
|
+
- `LoggerLike` (pino-compatible)
|
|
13
|
+
- `UsageMeter` (recordCall + getUserUsage)
|
|
14
|
+
- `ReverieUserContext` (userId + sessionId)
|
|
15
|
+
- `CostCalculator` (function signature)
|
|
16
|
+
- `ReverieInferenceRequest` + `ReverieInferenceResponse` + `ReverieInferenceProvider` (Anthropic-shaped but provider-agnostic)
|
|
17
|
+
|
|
18
|
+
Two factory + class entry points:
|
|
19
|
+
- `createReverieLogger({ reveriesPath, whisperResultsPath })` returns `{ logReverie, logWhisperResult }`. NEVER-throws disk writers.
|
|
20
|
+
- `new ReverieTrigger({ meter, logger, costCalculator, inferenceProvider?, reveriePairsPath, reverieSafetyFlagsPath, legacyReverieLogPath, idleMs?, dailyBudgetUsd?, forceMock? })`. Session-end orchestrator with `markActive`, `endCohort`, `cancelAll`.
|
|
21
|
+
|
|
22
|
+
Plus orchestrator entry points consumed by ReverieTrigger and exposed for tests:
|
|
23
|
+
- `triggerReverie(sessionId, getHistory, deps)`
|
|
24
|
+
- `executeReverie(sessionId, history, deps)` (branches on `deps.forceMock`)
|
|
25
|
+
- `executeReflection(args)` (single Opus reflection)
|
|
26
|
+
- `splitResultByCategory(result, reveriePairsPath)`
|
|
27
|
+
- `appendReverieResult(path, result, logger)`
|
|
28
|
+
- `appendSafetyFlag(path, result, logger)`
|
|
29
|
+
- `validateCorrectionPairs(raw)`
|
|
30
|
+
- `mapErrorKind(err)` (structural duck-typing on `.code`)
|
|
31
|
+
- `getLastReverie() / getLastReverieReal() / cancelAllReveries()` (state accessors + test teardown)
|
|
32
|
+
- `REVERIE_PAIR_SCHEMA_VERSION = "reverie-pair-v1"`
|
|
33
|
+
- `REVERIE_SAFETY_FLAG_SCHEMA_VERSION = "reverie-safety-flag-v1"`
|
|
34
|
+
- `_REFLECTION_SYSTEM_PROMPT_FOR_TEST` (verbatim equality test access)
|
|
35
|
+
|
|
36
|
+
### Package shape
|
|
37
|
+
|
|
38
|
+
- `dependencies`: `{}` (zero `@agencer/*`, zero `@anthropic-ai/sdk`)
|
|
39
|
+
- `peerDependencies`: `pino: ">=8.0.0"` (required), `@agencer/usage-accountant: "0.1.0"` (optional via `peerDependenciesMeta`)
|
|
40
|
+
- `devDependencies`: `@agencer/usage-accountant`, `@anthropic-ai/sdk`, `better-sqlite3` (for integration tests only)
|
|
41
|
+
|
|
42
|
+
The Greg test invariant — `dependencies: {}` plus `ls node_modules/@agencer/` showing only `reverie-loop` after a scratch-dir install — is codified in `PUBLISH.md`.
|
|
43
|
+
|
|
44
|
+
## Migration guide
|
|
45
|
+
|
|
46
|
+
For external consumers (currently only agencer-ox) integrating `@agencer/reverie-loop`:
|
|
47
|
+
|
|
48
|
+
### From pre-Leg-G agencer-ox internal paths
|
|
49
|
+
|
|
50
|
+
Pre-Leg-G call sites lived under `packages/server/src/{services,brain}/reverie-*.ts`. Post-Leg-G, the canonical home is `@agencer/reverie-loop`. The agencer-ox composition root (and any other consumer) imports from the Lego barrel.
|
|
51
|
+
|
|
52
|
+
| Pre-Leg-G path | Post-Leg-G import |
|
|
53
|
+
|---|---|
|
|
54
|
+
| `services/reverie-logger.ts: logReverie, logWhisperResult` | `@agencer/reverie-loop: createReverieLogger(opts).logReverie / .logWhisperResult` |
|
|
55
|
+
| `services/reverie-loop.ts: triggerReverie, executeReverie, ...` | `@agencer/reverie-loop: triggerReverie / executeReverie / ...` |
|
|
56
|
+
| `services/reverie-loop.ts: ReverieResult, ReverieObservation (legacy aliases)` | `@agencer/reverie-loop: ReverieResultLegacy / ReverieObservation` |
|
|
57
|
+
| `brain/reverie-pair-sink.ts: splitResultByCategory, appendReverieResult, appendSafetyFlag` | `@agencer/reverie-loop: splitResultByCategory / appendReverieResult / appendSafetyFlag` |
|
|
58
|
+
| `brain/reverie-opus-client.ts: executeReflection, schema versions, types` | `@agencer/reverie-loop: executeReflection / REVERIE_PAIR_SCHEMA_VERSION / ...` |
|
|
59
|
+
| `brain/reverie-trigger.ts: ReverieTrigger` | `@agencer/reverie-loop: ReverieTrigger` |
|
|
60
|
+
|
|
61
|
+
### Constructor field renames
|
|
62
|
+
|
|
63
|
+
Pre-Leg-G `ReverieTrigger`:
|
|
64
|
+
```ts
|
|
65
|
+
new ReverieTrigger({
|
|
66
|
+
accountant, // UsageAccountant
|
|
67
|
+
logger,
|
|
68
|
+
anthropic, // AnthropicProvider, optional
|
|
69
|
+
idleMs?,
|
|
70
|
+
dailyBudgetUsd?,
|
|
71
|
+
});
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Post-Leg-G:
|
|
75
|
+
```ts
|
|
76
|
+
new ReverieTrigger({
|
|
77
|
+
meter, // UsageMeter (structurally compat with UsageAccountant)
|
|
78
|
+
logger, // LoggerLike (structurally compat with pino.Logger)
|
|
79
|
+
costCalculator, // CostCalculator (calculateCost from @agencer/usage-accountant works)
|
|
80
|
+
inferenceProvider?, // ReverieInferenceProvider (structurally compat with AnthropicProvider)
|
|
81
|
+
reveriePairsPath, // absolute path (REQUIRED; composition root resolves from os.homedir())
|
|
82
|
+
reverieSafetyFlagsPath, // absolute path (REQUIRED)
|
|
83
|
+
legacyReverieLogPath, // absolute path (REQUIRED)
|
|
84
|
+
forceMock?: boolean, // replaces env-toggle MOCK_REVERIE
|
|
85
|
+
idleMs?,
|
|
86
|
+
dailyBudgetUsd?,
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Two structural-type widenings cross the Lego boundary (compile-time-only brands; runtime identical):
|
|
91
|
+
- `family: ModelFamily` (server) → `family: string` (Lego) — the Lego only emits `"opus"`
|
|
92
|
+
- `component: UsageComponentType` (server) → `component: string` (Lego) — the Lego only emits canonical `reverie.*` strings
|
|
93
|
+
|
|
94
|
+
Consumers passing concrete `UsageAccountant` / `AnthropicProvider` instances need `as unknown as` casts at the call site OR a small adapter at the composition root. The agencer-ox composition root uses the inline-cast pattern.
|
|
95
|
+
|
|
96
|
+
### Env-toggle removal: MOCK_REVERIE → forceMock
|
|
97
|
+
|
|
98
|
+
Pre-Leg-G code branched on `process.env["MOCK_REVERIE"] === "true"` inside `reverie-loop.ts:178`. The Lego no longer reads env. Consumers thread the equivalent via `deps.forceMock`:
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
const forceMock = process.env["MOCK_REVERIE"] === "true";
|
|
102
|
+
new ReverieTrigger({ ..., forceMock });
|
|
103
|
+
// or per-call:
|
|
104
|
+
executeReverie(sid, history, { ..., forceMock });
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
The composition root reads the env once at startup and threads `forceMock` into every deps object thereafter.
|
|
108
|
+
|
|
109
|
+
### OperativeError → structural duck-typing
|
|
110
|
+
|
|
111
|
+
Pre-Leg-G `mapErrorKind` used `if (err instanceof OperativeError) { switch (err.code) {...} }`. The Lego replaced this with structural duck-typing on `.code`:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
if (err && typeof err === "object" && "code" in err && typeof (err as { code?: unknown }).code === "string") {
|
|
115
|
+
switch ((err as { code: string }).code) { ... }
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Consumers' `OperativeError` instances (and any other `Error` subclass with a string `.code` field) classify identically. Plain `Error` instances with no `.code` fall through to `"unknown"`, same as the pre-Leg-G non-OperativeError throws.
|
|
120
|
+
|
|
121
|
+
### Path config: agencer-ox composition root pattern
|
|
122
|
+
|
|
123
|
+
The composition root resolves the three jsonl paths from `os.homedir()` and threads them into `ReverieTriggerOptions`:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const reverieLogDir = path.join(
|
|
127
|
+
process.env["HOME"] || os.homedir(),
|
|
128
|
+
".operative-x",
|
|
129
|
+
"logs",
|
|
130
|
+
);
|
|
131
|
+
const reverieTrainingDir = path.join(
|
|
132
|
+
process.env["HOME"] || os.homedir(),
|
|
133
|
+
".operative-x",
|
|
134
|
+
"training-data",
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
new ReverieTrigger({
|
|
138
|
+
...,
|
|
139
|
+
reveriePairsPath: path.join(reverieLogDir, "reverie-pairs.jsonl"),
|
|
140
|
+
reverieSafetyFlagsPath: path.join(reverieLogDir, "reverie-safety-flags.jsonl"),
|
|
141
|
+
legacyReverieLogPath: path.join(reverieLogDir, "reverie-log.jsonl"),
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
const { logReverie, logWhisperResult } = createReverieLogger({
|
|
145
|
+
reveriesPath: path.join(reverieTrainingDir, "reveries.jsonl"),
|
|
146
|
+
whisperResultsPath: path.join(reverieTrainingDir, "whisper-results.jsonl"),
|
|
147
|
+
});
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Tests that mutate `process.env["HOME"]` between calls (e.g., per-test tmpDir) must do so before invoking the composition root. The Lego itself never reads HOME, so post-construct mutation is invisible to it.
|
package/LICENSE
CHANGED
|
@@ -1,202 +1,11 @@
|
|
|
1
|
+
Copyright (c) 2026 Agencer, Inc. All rights reserved.
|
|
1
2
|
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
This software and associated documentation files (the "Software") are the
|
|
4
|
+
proprietary property of Agencer, Inc. and are licensed for use only under the
|
|
5
|
+
terms of a written license agreement between Agencer, Inc. and the licensee.
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
Unauthorized use, reproduction, modification, distribution, or disclosure of
|
|
8
|
+
the Software, in whole or in part, is strictly prohibited.
|
|
7
9
|
|
|
8
|
-
|
|
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.
|
|
10
|
+
This LICENSE applies to all files in this package directory unless explicitly
|
|
11
|
+
stated otherwise.
|
package/README.md
CHANGED
|
@@ -1,82 +1,144 @@
|
|
|
1
1
|
# @agencer/reverie-loop
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Reverie Loop. Strange Loop training-signal capture for AI agents. Post-session Opus reflection produces correction pairs, split into behavioral and safety JSONL files for fine-tune corpus generation. Portable Lego with zero `@agencer/*` runtime dependencies and zero `@anthropic-ai/sdk` runtime coupling on the public API.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
## Status
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
v0.1.0. Extraction arc complete (Leg G-1 through G-6). Published to npm under `@agencer/reverie-loop`; consumable by agencer-ox, future operatives, and external integrators.
|
|
8
8
|
|
|
9
|
-
|
|
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`.
|
|
9
|
+
## What it does
|
|
12
10
|
|
|
13
|
-
|
|
11
|
+
Reverie fires at session end (last WebSocket disconnect or 5-minute idle) and runs a single Anthropic Opus reflection over the conversation history. The reflection produces correction pairs across six categories (`factual_error | tone_miss | tool_misuse | verbosity | safety_concern | other`). Pairs split into a behavioral JSONL log (training corpus for the next fine-tune) and a safety JSONL log (constitutional corpus, never co-mingled per Day 159 Betley amendment).
|
|
14
12
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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.
|
|
13
|
+
```
|
|
14
|
+
Session ends (WS disconnect / idle)
|
|
15
|
+
-> ReverieTrigger.endCohort [debounced 10s; budget-guarded $1/day per user]
|
|
16
|
+
-> executeReflection [Opus inference via injected ReverieInferenceProvider]
|
|
17
|
+
-> splitResultByCategory [behavioral / safety / mixed partitions]
|
|
18
|
+
-> appendReverieResult -> ~/.operative-x/logs/reverie-pairs.jsonl
|
|
19
|
+
-> appendSafetyFlag -> ~/.operative-x/logs/reverie-safety-flags.jsonl
|
|
20
|
+
```
|
|
27
21
|
|
|
28
|
-
|
|
22
|
+
## Install
|
|
29
23
|
|
|
30
|
-
|
|
24
|
+
```bash
|
|
25
|
+
npm install @agencer/reverie-loop pino
|
|
26
|
+
```
|
|
31
27
|
|
|
32
|
-
|
|
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.
|
|
28
|
+
`pino` is a required peer. If you already use `UsageAccountant` from `@agencer/usage-accountant`, the optional `@agencer/usage-accountant` peer satisfies the `UsageMeter` interface with type alignment.
|
|
36
29
|
|
|
37
30
|
## Usage
|
|
38
31
|
|
|
39
|
-
### OX-style consumer (compat API)
|
|
40
|
-
|
|
41
32
|
```ts
|
|
42
|
-
import { homedir } from "node:os";
|
|
43
|
-
import path from "node:path";
|
|
44
33
|
import {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
logWhisperResult,
|
|
34
|
+
ReverieTrigger,
|
|
35
|
+
createReverieLogger,
|
|
48
36
|
} from "@agencer/reverie-loop";
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
37
|
+
import { calculateCost, UsageAccountant } from "@agencer/usage-accountant";
|
|
38
|
+
import os from "node:os";
|
|
39
|
+
import path from "node:path";
|
|
40
|
+
import pino from "pino";
|
|
41
|
+
|
|
42
|
+
const logger = pino();
|
|
43
|
+
const accountant = new UsageAccountant(db, logger);
|
|
44
|
+
|
|
45
|
+
const logDir = path.join(os.homedir(), ".operative-x", "logs");
|
|
46
|
+
const trainingDir = path.join(os.homedir(), ".operative-x", "training-data");
|
|
47
|
+
|
|
48
|
+
const reverieTrigger = new ReverieTrigger({
|
|
49
|
+
meter: accountant, // satisfies UsageMeter structurally
|
|
50
|
+
logger,
|
|
51
|
+
costCalculator: calculateCost, // signature-compatible
|
|
52
|
+
inferenceProvider: anthropicProvider, // your AnthropicProvider adapter
|
|
53
|
+
reveriePairsPath: path.join(logDir, "reverie-pairs.jsonl"),
|
|
54
|
+
reverieSafetyFlagsPath: path.join(logDir, "reverie-safety-flags.jsonl"),
|
|
55
|
+
legacyReverieLogPath: path.join(logDir, "reverie-log.jsonl"),
|
|
56
|
+
forceMock: process.env["MOCK_REVERIE"] === "true",
|
|
52
57
|
});
|
|
53
58
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
```
|
|
59
|
+
// On every routing decision:
|
|
60
|
+
reverieTrigger.markActive(userContext, () => conversationHistory);
|
|
57
61
|
|
|
58
|
-
|
|
62
|
+
// On last WebSocket disconnect:
|
|
63
|
+
reverieTrigger.endCohort();
|
|
59
64
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
logDir: path.join(process.cwd(), "data", "training"),
|
|
66
|
-
reverieFilename: "o2-reveries.jsonl",
|
|
67
|
-
whisperResultFilename: "o2-whisper-outcomes.jsonl",
|
|
65
|
+
// Separate from the orchestrator: factory-bound disk loggers for the
|
|
66
|
+
// whisper-failure -> Opus-takeover training-signal capture.
|
|
67
|
+
const { logReverie, logWhisperResult } = createReverieLogger({
|
|
68
|
+
reveriesPath: path.join(trainingDir, "reveries.jsonl"),
|
|
69
|
+
whisperResultsPath: path.join(trainingDir, "whisper-results.jsonl"),
|
|
68
70
|
});
|
|
69
|
-
|
|
70
|
-
logger.logReverie(u, m, o, "timeout", modelId);
|
|
71
71
|
```
|
|
72
72
|
|
|
73
|
-
##
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
73
|
+
## Public API
|
|
74
|
+
|
|
75
|
+
| Export | Kind | Description |
|
|
76
|
+
|---|---|---|
|
|
77
|
+
| `ReverieTrigger` | class | Session-end orchestrator. `markActive` + `endCohort` + `cancelAll`. |
|
|
78
|
+
| `createReverieLogger(opts)` | factory | Returns `{ logReverie, logWhisperResult }` bound to absolute paths. |
|
|
79
|
+
| `executeReflection(args)` | function | Single Opus reflection call. Returns `ReverieResult`. NEVER throws. |
|
|
80
|
+
| `validateCorrectionPairs(raw)` | function | Hand-rolled validator for the 6-category enum + pair shape. |
|
|
81
|
+
| `mapErrorKind(err)` | function | Structural duck-typing on `.code` for the auth/network/etc taxonomy. |
|
|
82
|
+
| `splitResultByCategory(result, reveriePairsPath)` | function | Behavioral vs safety partitioning. |
|
|
83
|
+
| `appendReverieResult(path, result, logger)` | function | JSONL writer for behavioral records. NEVER throws. |
|
|
84
|
+
| `appendSafetyFlag(path, result, logger)` | function | JSONL writer for safety records. NEVER throws. |
|
|
85
|
+
| `triggerReverie(sid, getHistory, deps)` | function | 10s-debounced trigger. |
|
|
86
|
+
| `executeReverie(sid, history, deps)` | function | Immediate execution; branches on `deps.forceMock`. |
|
|
87
|
+
| `getLastReverie() / getLastReverieReal()` | function | Test-scaffolding state accessors. |
|
|
88
|
+
| `cancelAllReveries()` | function | Clears all pending debounce timers. |
|
|
89
|
+
| `REVERIE_PAIR_SCHEMA_VERSION` | const | `"reverie-pair-v1"` |
|
|
90
|
+
| `REVERIE_SAFETY_FLAG_SCHEMA_VERSION` | const | `"reverie-safety-flag-v1"` |
|
|
91
|
+
| 6 contracts | types | `LoggerLike`, `UsageMeter`, `ReverieUserContext`, `CostCalculator`, `ReverieInferenceRequest`, `ReverieInferenceResponse`, `ReverieInferenceProvider` |
|
|
92
|
+
| `ReverieDeps`, `ReverieTriggerOptions` | types | Per-invocation deps + constructor opts |
|
|
93
|
+
| Plus types for `ReverieResult`, `CorrectionPair`, `ReverieCategory`, `ReverieErrorKind`, etc. |
|
|
94
|
+
|
|
95
|
+
## Sub-meter component vocabulary
|
|
96
|
+
|
|
97
|
+
The Lego emits six observable sub-meter strings via the injected `UsageMeter`. Downstream dashboards filter by these names:
|
|
98
|
+
|
|
99
|
+
| Component | When | Cost |
|
|
100
|
+
|---|---|---|
|
|
101
|
+
| `reverie.opus.reflection` | Real Opus call returns (Law 16 paid record) | injected `costCalculator` result |
|
|
102
|
+
| `reverie.trigger.opus.attempt` | A cohort fired and intended to invoke reflection | 0 |
|
|
103
|
+
| `reverie.trigger.disconnect` | Cohort fired from `endCohort` | 0 |
|
|
104
|
+
| `reverie.trigger.idle_timer` | Cohort fired from 5-minute idle | 0 |
|
|
105
|
+
| `reverie.skipped.budget_exceeded` | Daily $1.00 cost guard tripped | 0 |
|
|
106
|
+
| `reverie.skipped.deduped` | Same cohort fired twice (defensive) | 0 |
|
|
107
|
+
|
|
108
|
+
These strings are part of the public observable contract. They are preserved verbatim across leg refactors.
|
|
109
|
+
|
|
110
|
+
## Configuration
|
|
111
|
+
|
|
112
|
+
| Option | Required | Default | Purpose |
|
|
113
|
+
|---|---|---|---|
|
|
114
|
+
| `meter` | yes | — | Metered ledger (UsageMeter) |
|
|
115
|
+
| `logger` | yes | — | pino-compatible LoggerLike |
|
|
116
|
+
| `costCalculator` | yes | — | Cost USD calculator |
|
|
117
|
+
| `inferenceProvider` | no | none (forces mock path) | Anthropic adapter |
|
|
118
|
+
| `reveriePairsPath` | yes | — | Absolute path to behavioral JSONL |
|
|
119
|
+
| `reverieSafetyFlagsPath` | yes | — | Absolute path to safety JSONL |
|
|
120
|
+
| `legacyReverieLogPath` | yes | — | Absolute path to legacy mock JSONL |
|
|
121
|
+
| `idleMs` | no | 300_000 | Idle window |
|
|
122
|
+
| `dailyBudgetUsd` | no | 1.0 | Per-user daily cost ceiling |
|
|
123
|
+
| `forceMock` | no | false | Force legacy mock path |
|
|
124
|
+
|
|
125
|
+
## Sacred constraints
|
|
126
|
+
|
|
127
|
+
Per Canon Law 8, the following invariants are sacred. Changes require the explicit Reverie Loop change protocol (test harness run + verification + operator sign-off):
|
|
128
|
+
|
|
129
|
+
- **No `process.env` reads inside the Lego.** The Lego accepts resolved absolute paths via `ReverieDeps` / `ReverieTriggerOptions` / `createReverieLogger` options. The consumer composition root owns env parsing. Test scaffolding that mutates `process.env["HOME"]` resolves paths at the SHIM/composition root, never inside the Lego.
|
|
130
|
+
- **No `os.homedir()` reads inside the Lego.** Same rule, same reason. Path resolution is the consumer's job.
|
|
131
|
+
- **NEVER-throws on every public function.** Reverie is fire-and-forget session-end observability; a throw would surface as `uncaughtException` at the WebSocket teardown boundary or break the voice handler. Every public function wraps fallible work in try/catch and returns a safe default on error.
|
|
132
|
+
- **Sub-meter component name strings are observable contract.** The six `reverie.*` strings are emitted verbatim to the injected `UsageMeter`. Downstream dashboards filter on these exact names. Renames are breaking changes.
|
|
133
|
+
- **REFLECTION_SYSTEM_PROMPT is locked text.** The Day 159 Betley emergent-misalignment safety amendment defined the 6-category enum and the `safety_concern` definition verbatim. Any change to the system prompt requires re-running the eval suite + operator sign-off + a new schema version bump.
|
|
134
|
+
- **Schema version strings are immutable.** `reverie-pair-v1` and `reverie-safety-flag-v1` are inscribed on every JSONL row. `ox-data-factory` and the constitutional pipeline both filter by these strings. Bumping the schema is a breaking change to the data contract.
|
|
135
|
+
- **C-1 Option B cost attribution.** In mixed cohorts (safety + behavioral pairs in the same reflection), the behavioral record carries full `cost_usd` and the safety twin carries `cost_usd: 0` + `cost_attributed_to: reveriePairsPath`. Pure-safety cohorts keep cost on the safety record (no twin to attribute to).
|
|
136
|
+
|
|
137
|
+
## Operator-facing knobs
|
|
138
|
+
|
|
139
|
+
- `MOCK_REVERIE=true` env at the composition root forces the legacy mock path (test scaffolding only — produces the `observations[]` schema instead of the real `pairs[]` schema). The composition root reads this env and threads `forceMock: true` into deps. The Lego itself never reads `MOCK_REVERIE`.
|
|
140
|
+
- `dailyBudgetUsd` (constructor option) caps per-user paid Opus calls. The guard fires before `triggerReverie` schedules the reflection, so a budget-exceeded cohort never invokes the inference provider.
|
|
79
141
|
|
|
80
142
|
## License
|
|
81
143
|
|
|
82
|
-
|
|
144
|
+
Proprietary. See [LICENSE](./LICENSE).
|