@sawbuck/reins 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +2 -0
- package/README.md +81 -2
- package/bin/reins.mjs +182 -0
- package/judge.mjs +132 -0
- package/package.json +20 -4
- package/scan.mjs +126 -0
- package/wizard.mjs +62 -0
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/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,82 @@
|
|
|
1
|
-
#
|
|
1
|
+
# reins (engine)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The engine behind reins: measure how much you steer your AI coding agent. It reads
|
|
4
|
+
a Claude Code session transcript, scores each of your turns for **steering
|
|
5
|
+
pressure** (0 passive → 1 light refine → 2 redirect → 3 hard yank) with a small LLM,
|
|
6
|
+
and prints a seismograph of the session plus the distribution.
|
|
7
|
+
|
|
8
|
+
This is the LLM half of reins. The deterministic brake-slam counter (`sawbuck yank`)
|
|
9
|
+
lives in sawbuck's offline core; the continuous pressure judge needs a model, so it
|
|
10
|
+
lives here, keeping sawbuck's core model-free. (The reins *plugin*, the Claude Code
|
|
11
|
+
surface, lives alongside this in `plugins/sawbuck-reins/`.)
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
$ reins
|
|
15
|
+
reins · steering this session (judge: ollama:qwen2.5:7b)
|
|
16
|
+
..--+-+---+---.--.--..+--+.--
|
|
17
|
+
. passive - refine + redirect # yank
|
|
18
|
+
|
|
19
|
+
you steered 22 of 29 turns (76%) · mean pressure 0.93/3
|
|
20
|
+
17 light refine · 5 redirect · 0 hard yank · 7 passive
|
|
21
|
+
the check guards the 7 turns you didn't steer - a miss there is the risk.
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Backend (SAWBUCK_JUDGE)
|
|
25
|
+
|
|
26
|
+
The judge model is a socket. Set `SAWBUCK_JUDGE` (default `ollama:qwen2.5:7b`):
|
|
27
|
+
|
|
28
|
+
- `ollama:<model>`, local, free, private (nothing leaves your box). `OLLAMA_HOST`
|
|
29
|
+
overrides the endpoint. Benchmarked default `qwen2.5:7b`: fastest, smallest, and
|
|
30
|
+
tied-best accuracy against an opus-labeled gold, model size did not help.
|
|
31
|
+
- `haiku`, Anthropic `claude-haiku-5-5` (needs `ANTHROPIC_API_KEY`); zero VRAM,
|
|
32
|
+
about $0.00005 per turn.
|
|
33
|
+
- `anthropic:<model>`, any Anthropic model.
|
|
34
|
+
- `openai:<model>`, any OpenAI-compatible endpoint (`OPENAI_BASE_URL`,
|
|
35
|
+
`OPENAI_API_KEY`).
|
|
36
|
+
|
|
37
|
+
Output is constrained to a JSON schema where the backend supports it (ollama
|
|
38
|
+
structured outputs), so a thinking model can't break the parse.
|
|
39
|
+
|
|
40
|
+
## Live on the statusline
|
|
41
|
+
|
|
42
|
+
`--write [path]` writes the summary JSON (default `.sawbuck/steer.json`). The
|
|
43
|
+
offline `sawbuck statusline` reads that file and shows `🤠 steer 76%` next to its
|
|
44
|
+
own segment, the LLM work happens here, sawbuck's core stays model-free (it only
|
|
45
|
+
reads a file). Keep it fresh by running `reins --write` on a cadence (a `/loop`, a
|
|
46
|
+
watch, or a post-turn hook):
|
|
47
|
+
|
|
48
|
+
```
|
|
49
|
+
reins --write # writes .sawbuck/steer.json; the statusline picks it up
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Usage
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
reins [--session <path.jsonl>] [--judge <backend>] [-n N] [--json] [--write [path]]
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Defaults to your newest Claude Code session. `-n` scores only the most recent N
|
|
59
|
+
turns. `--json` is machine-readable. Zero-dep, Node 18+.
|
|
60
|
+
|
|
61
|
+
## The wizard: harvest your cues
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
reins wizard [--sessions N] [--max N] [--since DAYS] [--judge <backend>] [--json] [--write [path]] [--yes]
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Reads your old Claude Code chats, finds the steers you keep giving (a correction of HOW
|
|
68
|
+
the agent works, not a new task), and ranks them into a cue inventory, so a fresh saddle
|
|
69
|
+
already knows your style. It writes `.sawbuck/cues.json` and prints your top cues, ranked by
|
|
70
|
+
how many distinct sessions they span, then how generalizable they are.
|
|
71
|
+
|
|
72
|
+
It reads every turn-pair with a model, so on the default local ollama it is free (just
|
|
73
|
+
compute); a hosted backend (`haiku`, `openai:`) costs a little, and the command asks for
|
|
74
|
+
`--yes` before it spends. `--max` caps the pairs scored (default 400). The cues are LEADS,
|
|
75
|
+
candidates from your history to review, not rules it adopts for you.
|
|
76
|
+
|
|
77
|
+
## Honest limits
|
|
78
|
+
|
|
79
|
+
A single-turn judge: it sees the agent action and your reply, not the whole thread.
|
|
80
|
+
Models agree on the *shape* (pressure within one level ~95% of the time) more than
|
|
81
|
+
on exact per-turn scores, so read the seismograph and the distribution, not any one
|
|
82
|
+
cell.
|
package/bin/reins.mjs
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// reins: how much did you steer your agent this session? Reads your Claude Code
|
|
3
|
+
// transcript, scores each turn's steering pressure via SAWBUCK_JUDGE, and prints
|
|
4
|
+
// the seismograph + distribution. The check guards the turns you did not steer.
|
|
5
|
+
|
|
6
|
+
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
7
|
+
import { join, dirname } from "node:path";
|
|
8
|
+
import { scan, resolveSessionPath, pairs } from "../scan.mjs";
|
|
9
|
+
import { score, backend, harvestScore } from "../judge.mjs";
|
|
10
|
+
import { harvest, resolveSessions } from "../wizard.mjs";
|
|
11
|
+
|
|
12
|
+
const argv = process.argv.slice(2);
|
|
13
|
+
const flag = (n) => { const i = argv.indexOf(n); return i > -1 ? argv[i + 1] : null; };
|
|
14
|
+
const has = (n) => argv.includes(n);
|
|
15
|
+
|
|
16
|
+
// ---- `reins wizard` / `reins harvest`: read your old chats, rank the cues you keep giving ----
|
|
17
|
+
if (argv[0] === "wizard" || argv[0] === "harvest") {
|
|
18
|
+
if (has("--help") || has("-h")) {
|
|
19
|
+
process.stdout.write(`reins wizard: harvest your old Claude Code chats into a cue inventory
|
|
20
|
+
|
|
21
|
+
Usage: reins wizard [--judge <backend>] [--sessions N] [--max N] [--since DAYS] [--json] [--write [path]] [--yes]
|
|
22
|
+
|
|
23
|
+
--sessions N scan the N most recent sessions (default: all)
|
|
24
|
+
--max N cap the turn-pairs scored, for cost/time control (default 400)
|
|
25
|
+
--since DAYS only sessions touched in the last DAYS days
|
|
26
|
+
--judge <b> ollama:<model> (default, free, local) | haiku | anthropic:<model> | openai:<model>
|
|
27
|
+
--yes proceed without the confirm on a HOSTED (paid) backend
|
|
28
|
+
--write [path] write the cue inventory (default .sawbuck/cues.json)
|
|
29
|
+
--json machine-readable output
|
|
30
|
+
|
|
31
|
+
It reads every turn-pair with a model. On the local ollama default that is free; a hosted backend costs a little.
|
|
32
|
+
`);
|
|
33
|
+
process.exit(0);
|
|
34
|
+
}
|
|
35
|
+
if (flag("--judge")) process.env.SAWBUCK_JUDGE = flag("--judge");
|
|
36
|
+
const b = backend();
|
|
37
|
+
const sessionsN = parseInt(flag("--sessions"), 10) || 0;
|
|
38
|
+
const maxPairs = parseInt(flag("--max"), 10) || 400;
|
|
39
|
+
const sinceDays = parseInt(flag("--since"), 10) || 0;
|
|
40
|
+
const sinceMs = sinceDays > 0 ? Date.now() - sinceDays * 86400000 : 0;
|
|
41
|
+
const sessions = resolveSessions({ limit: sessionsN, sinceMs });
|
|
42
|
+
if (!sessions.length) { process.stderr.write("reins wizard: no Claude Code sessions found under ~/.claude/projects\n"); process.exit(2); }
|
|
43
|
+
const hosted = !b.startsWith("ollama:");
|
|
44
|
+
if (hosted && !has("--yes")) {
|
|
45
|
+
process.stderr.write(`reins wizard: ${b} is a HOSTED backend and will make up to ${maxPairs} calls (a small cost).\n re-run with --yes to proceed, or use the free local default (omit --judge).\n`);
|
|
46
|
+
process.exit(2);
|
|
47
|
+
}
|
|
48
|
+
process.stderr.write(`reins wizard: harvesting up to ${maxPairs} turn-pairs from ${sessions.length} session(s) via ${b}${hosted ? " (hosted, paid)" : " (local, free)"}...\n`);
|
|
49
|
+
const rw = await harvest(harvestScore, { sessions, maxPairs });
|
|
50
|
+
const wf = flag("--write");
|
|
51
|
+
const out = wf && !wf.startsWith("--") ? wf : join(process.cwd(), ".sawbuck", "cues.json");
|
|
52
|
+
if (has("--write") || !has("--json")) {
|
|
53
|
+
try { mkdirSync(dirname(out), { recursive: true }); writeFileSync(out, JSON.stringify({ at: new Date().toISOString(), backend: b, ...rw }, null, 2) + "\n"); }
|
|
54
|
+
catch { process.stderr.write("reins wizard: could not write " + out + "\n"); }
|
|
55
|
+
}
|
|
56
|
+
if (has("--json")) { process.stdout.write(JSON.stringify({ backend: b, ...rw }, null, 2) + "\n"); process.exit(0); }
|
|
57
|
+
const pct = rw.scored ? Math.round((rw.steers / rw.scored) * 100) : 0;
|
|
58
|
+
process.stdout.write(`\n reins · wizard (judge: ${b})\n`);
|
|
59
|
+
process.stdout.write(` read ${rw.pairs} turn-pairs from ${rw.sessionsRead} session(s) · ${rw.steers} steers (${pct}%)\n\n`);
|
|
60
|
+
const top = rw.cues.filter((c) => c.count >= 2 || c.gen > 0).slice(0, 12);
|
|
61
|
+
if (!top.length) { process.stdout.write(" no repeated cues surfaced yet - harvest more sessions (--sessions, --since).\n\n"); process.exit(0); }
|
|
62
|
+
process.stdout.write(" your top cues (candidates from your history, review before trusting):\n");
|
|
63
|
+
for (const c of top) {
|
|
64
|
+
process.stdout.write(` ${("[" + c.axis + "]").padEnd(13)} ${(c.cue || "(unnamed)").padEnd(34)} · ${c.sessions} sess · gen ${c.genShare} · ${c.count}x\n`);
|
|
65
|
+
}
|
|
66
|
+
process.stdout.write(`\n wrote ${out}\n these are LEADS. Promote the ones that are really you; the check still guards the rest.\n\n`);
|
|
67
|
+
process.exit(0);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (has("--help") || has("-h")) {
|
|
71
|
+
process.stdout.write(`reins: measure how much you steer your agent this session
|
|
72
|
+
|
|
73
|
+
Usage: reins [--session <path.jsonl>] [--judge <backend>] [-n N] [--json] [--write [path]] [--share [--label <term>]]
|
|
74
|
+
|
|
75
|
+
--session <path> a Claude Code transcript (default: your newest session)
|
|
76
|
+
--judge <backend> override SAWBUCK_JUDGE: ollama:<model> | haiku | anthropic:<model> | openai:<model>
|
|
77
|
+
-n <N> score only the most recent N turns
|
|
78
|
+
--json machine-readable output
|
|
79
|
+
--write [path] also write the summary JSON (default .sawbuck/steer.json) for the
|
|
80
|
+
offline sawbuck statusline to read - run it on a cadence for a live readout
|
|
81
|
+
--share print a paste-ready card for posting (LinkedIn / X / Reddit)
|
|
82
|
+
--label <term> the word for the stat on the share card (default "steer rate";
|
|
83
|
+
e.g. "yank rate" for a playful channel - keep it neutral for LinkedIn)
|
|
84
|
+
|
|
85
|
+
Backend is SAWBUCK_JUDGE (default ollama:qwen2.5:7b). Local = free + private.
|
|
86
|
+
`);
|
|
87
|
+
process.exit(0);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (flag("--judge")) process.env.SAWBUCK_JUDGE = flag("--judge");
|
|
91
|
+
const sess = resolveSessionPath(flag("--session"));
|
|
92
|
+
if (!sess) { process.stderr.write("reins: no session transcript found (pass --session <path.jsonl>)\n"); process.exit(2); }
|
|
93
|
+
|
|
94
|
+
let text = "";
|
|
95
|
+
try { text = readFileSync(sess, "utf8"); } catch { process.stderr.write("reins: cannot read " + sess + "\n"); process.exit(2); }
|
|
96
|
+
|
|
97
|
+
// --append: incremental, BOUNDED per-turn scoring for the live watcher. Reads the
|
|
98
|
+
// prior tally from .sawbuck/steer.json, scores only the NEW turn-pairs since the last
|
|
99
|
+
// run, merges, rewrites. One new pair per turn - not a full re-scan (which would be
|
|
100
|
+
// quadratic over a session). The sawbuck statusline reads the same steer.json offline.
|
|
101
|
+
if (has("--append")) {
|
|
102
|
+
const out = join(process.cwd(), ".sawbuck", "steer.json");
|
|
103
|
+
let prior = { lastPairs: 0, scored: 0, steering: 0, wsum: 0, distribution: { 0: 0, 1: 0, 2: 0, 3: 0 } };
|
|
104
|
+
try {
|
|
105
|
+
const p = JSON.parse(readFileSync(out, "utf8"));
|
|
106
|
+
if (p && p.lastPairs != null) prior = { lastPairs: p.lastPairs, scored: p.scored || 0, steering: p.steering || 0, wsum: p._wsum || 0, distribution: p.distribution || prior.distribution };
|
|
107
|
+
} catch { /* no prior tally = fresh */ }
|
|
108
|
+
const all = pairs(text);
|
|
109
|
+
let added = 0;
|
|
110
|
+
for (const { prior: a, user: u } of all.slice(prior.lastPairs)) {
|
|
111
|
+
let s = null; try { s = await score(a, u); } catch {}
|
|
112
|
+
if (!s) continue;
|
|
113
|
+
prior.distribution[s.pressure] = (prior.distribution[s.pressure] || 0) + 1;
|
|
114
|
+
prior.scored++; prior.wsum += s.pressure; added++;
|
|
115
|
+
if (s.pressure >= 1) prior.steering++;
|
|
116
|
+
}
|
|
117
|
+
const rate = prior.scored ? prior.steering / prior.scored : 0;
|
|
118
|
+
const rec = { at: new Date().toISOString(), backend: backend(), lastPairs: all.length, turns: all.length, scored: prior.scored, steering: prior.steering, steeringRate: rate, meanPressure: prior.scored ? prior.wsum / prior.scored : 0, distribution: prior.distribution, _wsum: prior.wsum };
|
|
119
|
+
try { mkdirSync(dirname(out), { recursive: true }); writeFileSync(out, JSON.stringify(rec) + "\n"); } catch { process.stderr.write("reins: could not write " + out + "\n"); }
|
|
120
|
+
if (has("--json")) process.stdout.write(JSON.stringify(rec) + "\n");
|
|
121
|
+
else process.stdout.write(`reins: +${added} new turn(s), steer rate ${Math.round(rate * 100)}% over ${prior.scored} turns\n`);
|
|
122
|
+
process.exit(0);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const n = parseInt(flag("-n"), 10) || 0;
|
|
126
|
+
const r = await scan(text, score, { limit: n });
|
|
127
|
+
|
|
128
|
+
// --write [path]: persist the summary so an OFFLINE reader (the sawbuck statusline)
|
|
129
|
+
// can display the live steering number without ever calling a model itself.
|
|
130
|
+
if (has("--write")) {
|
|
131
|
+
const wf = flag("--write");
|
|
132
|
+
const out = wf && !wf.startsWith("--") ? wf : join(process.cwd(), ".sawbuck", "steer.json");
|
|
133
|
+
try {
|
|
134
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
135
|
+
writeFileSync(out, JSON.stringify({ at: new Date().toISOString(), backend: backend(), turns: r.turns, scored: r.scored, steering: r.steering, steeringRate: r.steeringRate, meanPressure: r.meanPressure, distribution: r.distribution }) + "\n");
|
|
136
|
+
} catch { process.stderr.write("reins: could not write " + out + "\n"); }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (has("--json")) { process.stdout.write(JSON.stringify({ backend: backend(), ...r }) + "\n"); process.exit(0); }
|
|
140
|
+
|
|
141
|
+
// --share: a tasteful, paste-anywhere card (plain text works on LinkedIn / X / Reddit).
|
|
142
|
+
// --label swaps the stat's word; default stays neutral ("steer rate") so it's safe for a
|
|
143
|
+
// professional feed, e.g. --label "yank rate" for a playful channel.
|
|
144
|
+
if (has("--share")) {
|
|
145
|
+
if (r.scored === 0) { process.stdout.write("reins: nothing to share yet (no turns scored).\n"); process.exit(0); }
|
|
146
|
+
const lf = flag("--label");
|
|
147
|
+
const label = lf && !lf.startsWith("--") ? lf : "steer rate";
|
|
148
|
+
const pct = Math.round(r.steeringRate * 100);
|
|
149
|
+
const d = r.distribution;
|
|
150
|
+
const texture = d[1] >= d[2] + d[3] ? "mostly light refinements" : d[3] > 0 ? "a few hard pulls" : "real redirects";
|
|
151
|
+
const grip = pct >= 60 ? "hands-on" : pct >= 30 ? "a steady hand" : "a loose rein";
|
|
152
|
+
process.stdout.write(
|
|
153
|
+
`my ${label} this session 🐴
|
|
154
|
+
|
|
155
|
+
${r.seismograph}
|
|
156
|
+
· let it ride - nudge + redirect # hard pull
|
|
157
|
+
|
|
158
|
+
I steered ${r.steering} of ${r.scored} turns (${pct}%) — ${grip}, ${texture}.
|
|
159
|
+
The ${r.scored - r.steering} I let ride, the check had my back.
|
|
160
|
+
|
|
161
|
+
— measured with reins · sawbuck
|
|
162
|
+
`);
|
|
163
|
+
process.exit(0);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const pct = Math.round(r.steeringRate * 100);
|
|
167
|
+
const d = r.distribution;
|
|
168
|
+
process.stdout.write(`\n reins · steering this session (judge: ${backend()})\n`);
|
|
169
|
+
if (r.scored === 0) {
|
|
170
|
+
process.stdout.write(` no turns scored${r.fails ? ` (${r.fails} judge errors - is the backend reachable?)` : ""}.\n\n`);
|
|
171
|
+
process.exit(r.fails ? 2 : 0);
|
|
172
|
+
}
|
|
173
|
+
process.stdout.write(` ${r.seismograph}\n`);
|
|
174
|
+
process.stdout.write(` . passive - refine + redirect # yank\n\n`);
|
|
175
|
+
process.stdout.write(` you steered ${r.steering} of ${r.scored} turns (${pct}%) · mean pressure ${r.meanPressure.toFixed(2)}/3\n`);
|
|
176
|
+
process.stdout.write(` ${d[1]} light refine · ${d[2]} redirect · ${d[3]} hard yank · ${d[0]} passive${r.fails ? ` · ${r.fails} skipped` : ""}\n`);
|
|
177
|
+
process.stdout.write(` the check guards the ${r.scored - r.steering} turns you didn't steer - a miss there is the risk.\n`);
|
|
178
|
+
if (r.recent.length) {
|
|
179
|
+
process.stdout.write(`\n recent steers:\n`);
|
|
180
|
+
for (const s of r.recent) process.stdout.write(` ${["", "-", "+", "#"][s.pressure]}${s.pressure} ${(s.axis || "").padEnd(12)} ${s.nudge}\n`);
|
|
181
|
+
}
|
|
182
|
+
process.stdout.write("\n");
|
package/judge.mjs
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// judge.mjs - the steering judge's backend socket.
|
|
2
|
+
//
|
|
3
|
+
// score(prior, user) -> {pressure 0-3, axis, nudge} (the per-turn seismograph)
|
|
4
|
+
// harvestScore(prior, user) -> {steer, axis, magnitude, generalizable, cue} (the wizard's cue finder)
|
|
5
|
+
//
|
|
6
|
+
// Both run through the backend SAWBUCK_JUDGE selects. This file does network/LLM calls ON
|
|
7
|
+
// PURPOSE - it is a STANDALONE tool, never imported into sawbuck's offline core.
|
|
8
|
+
//
|
|
9
|
+
// Backends (SAWBUCK_JUDGE):
|
|
10
|
+
// ollama:<model> local, free, private - the default (ollama:qwen2.5:7b). OLLAMA_HOST overrides.
|
|
11
|
+
// haiku Anthropic claude-haiku-5-5 (needs ANTHROPIC_API_KEY); cheap hosted, zero VRAM.
|
|
12
|
+
// anthropic:<model> any Anthropic model.
|
|
13
|
+
// openai:<model> any OpenAI-compatible endpoint (OPENAI_BASE_URL + OPENAI_API_KEY).
|
|
14
|
+
//
|
|
15
|
+
// Benchmarked default = qwen2.5:7b: tied-best accuracy vs an opus gold, fastest, smallest.
|
|
16
|
+
|
|
17
|
+
// ---- schemas (ollama structured outputs: a grammar, not a prayer, so no parse-fails) ----
|
|
18
|
+
const PRESSURE_SCHEMA = {
|
|
19
|
+
type: "object",
|
|
20
|
+
properties: {
|
|
21
|
+
pressure: { type: "integer", enum: [0, 1, 2, 3] },
|
|
22
|
+
axis: { type: "string" },
|
|
23
|
+
nudge: { type: "string" },
|
|
24
|
+
},
|
|
25
|
+
required: ["pressure", "axis", "nudge"],
|
|
26
|
+
};
|
|
27
|
+
const HARVEST_SCHEMA = {
|
|
28
|
+
type: "object",
|
|
29
|
+
properties: {
|
|
30
|
+
steer: { type: "boolean" },
|
|
31
|
+
axis: { type: "string" },
|
|
32
|
+
magnitude: { type: "string", enum: ["refine", "redirect", "hard-stop"] },
|
|
33
|
+
generalizable: { type: "boolean" },
|
|
34
|
+
cue: { type: "string" },
|
|
35
|
+
},
|
|
36
|
+
required: ["steer", "axis", "magnitude", "generalizable", "cue"],
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const PROMPT = (a, u) =>
|
|
40
|
+
`You rate how much a developer's message STEERS an AI coding agent's current work.
|
|
41
|
+
Output ONLY one JSON object: {"pressure":0-3,"axis":"one-word","nudge":"<=8 words"}
|
|
42
|
+
pressure: 0 passive (approval like "yes/go/do it", a pure question, or a brand-new unrelated task; NOT steering current work). 1 light refine (small adjustment to the SAME work: tone, length, scope, emphasis, "a bit more X", "also Y"). 2 redirect (change the approach/direction of current work). 3 hard-stop ("no/stop/undo/revert", reject and restart).
|
|
43
|
+
AGENT just did: ${a}
|
|
44
|
+
USER replied: ${u}
|
|
45
|
+
JSON:`;
|
|
46
|
+
|
|
47
|
+
const HARVEST_PROMPT = (a, u) =>
|
|
48
|
+
`You analyze a developer's message to an AI coding agent to find a repeated STEER: a correction of HOW the agent works, not a new task.
|
|
49
|
+
Output ONLY one JSON object: {"steer":true|false,"axis":"one-word","magnitude":"refine|redirect|hard-stop","generalizable":true|false,"cue":"<=6 words"}
|
|
50
|
+
steer: true if the message corrects or redirects the current work; false for a brand-new task, a pure question, or plain approval.
|
|
51
|
+
axis: the dimension - rigor, scope, approach, correctness, format, process, tone, naming, or constraint.
|
|
52
|
+
magnitude: refine (small adjustment) | redirect (change the approach) | hard-stop (reject or undo).
|
|
53
|
+
generalizable: true if it is a STANDING preference that would apply to future work, false if specific to this one case.
|
|
54
|
+
cue: a short imperative naming the rule, e.g. "verify before claiming done".
|
|
55
|
+
AGENT just did: ${String(a).slice(0, 600)}
|
|
56
|
+
USER replied: ${String(u).replace(/\s+/g, " ").slice(0, 800)}
|
|
57
|
+
JSON:`;
|
|
58
|
+
|
|
59
|
+
// lenient parse: strip reasoning-model <think> blocks, take the last JSON object.
|
|
60
|
+
function lastJson(txt) {
|
|
61
|
+
txt = String(txt).replace(/<think>[\s\S]*?<\/think>/g, "");
|
|
62
|
+
const cands = txt.match(/\{[^{}]*\}/g) || [];
|
|
63
|
+
for (const c of cands.reverse()) { try { return JSON.parse(c); } catch { /* keep scanning */ } }
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
export function parse(txt) {
|
|
67
|
+
const j = lastJson(txt);
|
|
68
|
+
if (!j || j.pressure == null) return null;
|
|
69
|
+
return {
|
|
70
|
+
pressure: Math.max(0, Math.min(3, parseInt(j.pressure, 10) || 0)),
|
|
71
|
+
axis: String(j.axis || "").slice(0, 16),
|
|
72
|
+
nudge: String(j.nudge || "").slice(0, 48),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
export function parseHarvest(txt) {
|
|
76
|
+
const j = lastJson(txt);
|
|
77
|
+
if (!j || j.steer == null) return null;
|
|
78
|
+
const mags = ["refine", "redirect", "hard-stop"];
|
|
79
|
+
return {
|
|
80
|
+
steer: j.steer === true,
|
|
81
|
+
axis: String(j.axis || "other").toLowerCase().slice(0, 20),
|
|
82
|
+
magnitude: mags.includes(j.magnitude) ? j.magnitude : "refine",
|
|
83
|
+
generalizable: j.generalizable === true,
|
|
84
|
+
cue: String(j.cue || "").trim().slice(0, 60),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// one backend call -> RAW text (the caller parses). schema is used where the backend supports it (ollama).
|
|
89
|
+
async function complete(promptStr, schema) {
|
|
90
|
+
const b = backend();
|
|
91
|
+
if (b === "haiku") return anthropic("claude-haiku-5-5", promptStr);
|
|
92
|
+
if (b.startsWith("anthropic:")) return anthropic(b.slice(10), promptStr);
|
|
93
|
+
if (b.startsWith("ollama:")) return ollama(b.slice(7), promptStr, schema);
|
|
94
|
+
if (b.startsWith("openai:")) return openai(b.slice(7), promptStr);
|
|
95
|
+
throw new Error("unknown SAWBUCK_JUDGE backend: " + b + " (use ollama:<model> | haiku | anthropic:<model> | openai:<model>)");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function ollama(model, promptStr, schema) {
|
|
99
|
+
const host = process.env.OLLAMA_HOST || "http://localhost:11434";
|
|
100
|
+
const res = await fetch(host + "/api/generate", {
|
|
101
|
+
method: "POST", headers: { "Content-Type": "application/json" },
|
|
102
|
+
body: JSON.stringify({ model, prompt: promptStr, stream: false, format: schema, options: { temperature: 0, num_predict: 800 } }),
|
|
103
|
+
});
|
|
104
|
+
const j = await res.json();
|
|
105
|
+
return j.response || "";
|
|
106
|
+
}
|
|
107
|
+
async function anthropic(model, promptStr) {
|
|
108
|
+
const key = process.env.ANTHROPIC_API_KEY;
|
|
109
|
+
if (!key) throw new Error("ANTHROPIC_API_KEY not set (SAWBUCK_JUDGE=haiku needs it)");
|
|
110
|
+
const res = await fetch("https://api.anthropic.com/v1/messages", {
|
|
111
|
+
method: "POST", headers: { "Content-Type": "application/json", "x-api-key": key, "anthropic-version": "2023-06-01" },
|
|
112
|
+
body: JSON.stringify({ model, max_tokens: 200, messages: [{ role: "user", content: promptStr }] }),
|
|
113
|
+
});
|
|
114
|
+
const j = await res.json();
|
|
115
|
+
return (j.content || []).filter((x) => x.type === "text").map((x) => x.text).join("");
|
|
116
|
+
}
|
|
117
|
+
async function openai(model, promptStr) {
|
|
118
|
+
const base = process.env.OPENAI_BASE_URL || "https://api.openai.com/v1";
|
|
119
|
+
const key = process.env.OPENAI_API_KEY;
|
|
120
|
+
if (!key) throw new Error("OPENAI_API_KEY not set");
|
|
121
|
+
const res = await fetch(base.replace(/\/$/, "") + "/chat/completions", {
|
|
122
|
+
method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + key },
|
|
123
|
+
body: JSON.stringify({ model, temperature: 0, max_tokens: 200, response_format: { type: "json_object" }, messages: [{ role: "user", content: promptStr }] }),
|
|
124
|
+
});
|
|
125
|
+
const j = await res.json();
|
|
126
|
+
return j.choices?.[0]?.message?.content || "";
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function backend() { return process.env.SAWBUCK_JUDGE || "ollama:qwen2.5:7b"; }
|
|
130
|
+
|
|
131
|
+
export async function score(prior, user) { return parse(await complete(PROMPT(prior, user), PRESSURE_SCHEMA)); }
|
|
132
|
+
export async function harvestScore(prior, user) { return parseHarvest(await complete(HARVEST_PROMPT(prior, user), HARVEST_SCHEMA)); }
|
package/package.json
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sawbuck/reins",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Reins: measure how much you steer your AI coding agent. A per-turn steering-pressure judge over your session transcript, pluggable backend (Haiku / local ollama / any OpenAI-compatible). The LLM half of the reins steering layer; keeps sawbuck's core offline.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"bin": {
|
|
8
|
+
"reins": "bin/reins.mjs"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"test": "node --test"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"bin/reins.mjs",
|
|
15
|
+
"judge.mjs",
|
|
16
|
+
"scan.mjs",
|
|
17
|
+
"wizard.mjs",
|
|
18
|
+
"README.md",
|
|
19
|
+
"LICENSE",
|
|
20
|
+
"NOTICE"
|
|
21
|
+
]
|
|
22
|
+
}
|
package/scan.mjs
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// scan.mjs - turn a Claude Code session transcript into a steering-pressure
|
|
2
|
+
// reading: score each of your turns (given the agent action it followed) and
|
|
3
|
+
// aggregate into a distribution + a seismograph. The scorer is injected so the
|
|
4
|
+
// aggregation is testable without a live model.
|
|
5
|
+
|
|
6
|
+
import { readFileSync, readdirSync, statSync, existsSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
|
|
10
|
+
function humanText(o) {
|
|
11
|
+
if (!o || o.type !== "user" || o.isMeta) return null;
|
|
12
|
+
if (o.userType && o.userType !== "external") return null;
|
|
13
|
+
const c = o.message && o.message.content;
|
|
14
|
+
if (typeof c === "string") return c;
|
|
15
|
+
if (Array.isArray(c)) {
|
|
16
|
+
if (c.some((b) => b && b.type === "tool_result")) return null;
|
|
17
|
+
const t = c.filter((b) => b && b.type === "text").map((b) => b.text || "").join(" ");
|
|
18
|
+
return t || null;
|
|
19
|
+
}
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
function assistantText(o) {
|
|
23
|
+
const c = o.message && o.message.content;
|
|
24
|
+
if (Array.isArray(c)) return c.filter((b) => b && b.type === "text").map((b) => b.text || "").join(" ").trim();
|
|
25
|
+
if (typeof c === "string") return c.trim();
|
|
26
|
+
return "";
|
|
27
|
+
}
|
|
28
|
+
const noise = (t) => {
|
|
29
|
+
const s = t.trim();
|
|
30
|
+
if (s.includes("<task-notification>") || s.startsWith("<task-id>")) return true;
|
|
31
|
+
if (s.replace(/\[Image #\d+\]/g, "").trim().length < 3) return true;
|
|
32
|
+
return false;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
// Extract the (prior-agent, user-turn) pairs to score: every non-opener human turn
|
|
36
|
+
// that followed an agent action.
|
|
37
|
+
export function pairs(text) {
|
|
38
|
+
const out = [];
|
|
39
|
+
let prev = "", seen = false;
|
|
40
|
+
for (const line of String(text).split("\n")) {
|
|
41
|
+
if (!line.trim()) continue;
|
|
42
|
+
let o; try { o = JSON.parse(line); } catch { continue; }
|
|
43
|
+
if (o.type === "assistant") { prev = assistantText(o); continue; }
|
|
44
|
+
const t = humanText(o);
|
|
45
|
+
if (t === null || noise(t)) continue;
|
|
46
|
+
if (!seen) { seen = true; continue; } // opener = a request, not a steer
|
|
47
|
+
if (prev) out.push({ prior: prev.slice(0, 600), user: t.replace(/\s+/g, " ").slice(0, 800) });
|
|
48
|
+
prev = "";
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const GLYPH = { 0: ".", 1: "-", 2: "+", 3: "#" };
|
|
54
|
+
|
|
55
|
+
// scan(text, scoreFn) -> aggregate. scoreFn(prior, user) -> {pressure, axis, nudge} | null.
|
|
56
|
+
export async function scan(text, scoreFn, { limit = 0 } = {}) {
|
|
57
|
+
let ps = pairs(text);
|
|
58
|
+
if (limit > 0 && ps.length > limit) ps = ps.slice(-limit); // most recent N
|
|
59
|
+
const dist = { 0: 0, 1: 0, 2: 0, 3: 0 };
|
|
60
|
+
let scored = 0, fails = 0, wsum = 0, spark = "";
|
|
61
|
+
const recent = [];
|
|
62
|
+
for (const { prior, user } of ps) {
|
|
63
|
+
let r = null;
|
|
64
|
+
try { r = await scoreFn(prior, user); } catch { r = null; }
|
|
65
|
+
if (!r) { fails++; spark += "?"; continue; }
|
|
66
|
+
dist[r.pressure]++; scored++; wsum += r.pressure; spark += GLYPH[r.pressure];
|
|
67
|
+
if (r.pressure >= 1) recent.push({ pressure: r.pressure, axis: r.axis, nudge: r.nudge, user: user.slice(0, 60) });
|
|
68
|
+
}
|
|
69
|
+
const turns = ps.length;
|
|
70
|
+
const steering = dist[1] + dist[2] + dist[3];
|
|
71
|
+
return {
|
|
72
|
+
turns, scored, fails,
|
|
73
|
+
distribution: dist,
|
|
74
|
+
steering, steeringRate: scored ? steering / scored : 0,
|
|
75
|
+
meanPressure: scored ? wsum / scored : 0,
|
|
76
|
+
seismograph: spark,
|
|
77
|
+
recent: recent.slice(-6),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Resolve the newest session transcript for a cwd (Claude Code: ~/.claude/projects/
|
|
82
|
+
// <encoded-cwd>/<id>.jsonl). Best-effort; prefer the cwd's dir, else newest overall.
|
|
83
|
+
export function resolveSessionPath(explicit, cwd = process.cwd()) {
|
|
84
|
+
if (explicit) return existsSync(explicit) ? explicit : null;
|
|
85
|
+
const root = join(homedir(), ".claude", "projects");
|
|
86
|
+
if (!existsSync(root)) return null;
|
|
87
|
+
const key = cwd.replace(/[^A-Za-z0-9]/g, "-");
|
|
88
|
+
let dirs = [];
|
|
89
|
+
try { dirs = readdirSync(root).map((d) => join(root, d)).filter((p) => { try { return statSync(p).isDirectory(); } catch { return false; } }); }
|
|
90
|
+
catch { return null; }
|
|
91
|
+
const matched = dirs.filter((p) => p.endsWith("/" + key));
|
|
92
|
+
const pool = matched.length ? matched : dirs;
|
|
93
|
+
let best = null, bestT = 0;
|
|
94
|
+
for (const full of pool) {
|
|
95
|
+
let files = []; try { files = readdirSync(full); } catch { continue; }
|
|
96
|
+
for (const f of files) {
|
|
97
|
+
if (!f.endsWith(".jsonl")) continue;
|
|
98
|
+
const p = join(full, f);
|
|
99
|
+
try { const st = statSync(p); if (st.mtimeMs > bestT) { bestT = st.mtimeMs; best = p; } } catch {}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return best;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Enumerate recent Claude Code session transcripts across ALL projects, newest first.
|
|
106
|
+
// For the wizard's harvest ("read my old chats"). { limit } caps the count; { sinceMs }
|
|
107
|
+
// drops anything older. Best-effort; returns [] if the projects dir is missing.
|
|
108
|
+
export function resolveSessions({ limit = 0, sinceMs = 0 } = {}) {
|
|
109
|
+
const root = join(homedir(), ".claude", "projects");
|
|
110
|
+
if (!existsSync(root)) return [];
|
|
111
|
+
let dirs = [];
|
|
112
|
+
try { dirs = readdirSync(root).map((d) => join(root, d)).filter((p) => { try { return statSync(p).isDirectory(); } catch { return false; } }); }
|
|
113
|
+
catch { return []; }
|
|
114
|
+
const found = [];
|
|
115
|
+
for (const d of dirs) {
|
|
116
|
+
let files = []; try { files = readdirSync(d); } catch { continue; }
|
|
117
|
+
for (const f of files) {
|
|
118
|
+
if (!f.endsWith(".jsonl")) continue;
|
|
119
|
+
const p = join(d, f);
|
|
120
|
+
try { const st = statSync(p); if (sinceMs && st.mtimeMs < sinceMs) continue; found.push({ path: p, mtime: st.mtimeMs }); } catch {}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
found.sort((a, b) => b.mtime - a.mtime);
|
|
124
|
+
const sliced = limit > 0 ? found.slice(0, limit) : found;
|
|
125
|
+
return sliced.map((f) => f.path);
|
|
126
|
+
}
|
package/wizard.mjs
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// wizard.mjs - the harvest: read your old Claude Code chats, find the STEERS you keep
|
|
2
|
+
// giving, and rank them into a cue inventory, so a fresh saddle already knows your style.
|
|
3
|
+
//
|
|
4
|
+
// Token honesty: every turn-pair is read by a model. On the default local ollama that is
|
|
5
|
+
// free (just compute); on a hosted backend it costs a little. The CLI prints the count and
|
|
6
|
+
// the backend before it runs. The scorer is injected here so the aggregation is testable
|
|
7
|
+
// without a model.
|
|
8
|
+
|
|
9
|
+
import { readFileSync } from "node:fs";
|
|
10
|
+
import { pairs, resolveSessions } from "./scan.mjs";
|
|
11
|
+
|
|
12
|
+
// aggregateCues(items) -> ranked cue inventory. items = [{ session, result }], where
|
|
13
|
+
// result = { steer, axis, magnitude, generalizable, cue } | null. Pure + deterministic.
|
|
14
|
+
// Rank = distinct-session support, then generalizable count, then raw frequency (so a
|
|
15
|
+
// one-session spike never outranks a cue you give across many sessions - the study's lesson).
|
|
16
|
+
export function aggregateCues(items) {
|
|
17
|
+
const clusters = new Map();
|
|
18
|
+
let scored = 0, steers = 0, fails = 0;
|
|
19
|
+
for (const { session, result } of items) {
|
|
20
|
+
if (!result) { fails++; continue; }
|
|
21
|
+
scored++;
|
|
22
|
+
if (!result.steer) continue;
|
|
23
|
+
steers++;
|
|
24
|
+
const key = (result.axis || "other") + "|" + String(result.cue || "").toLowerCase().replace(/\s+/g, " ").trim().slice(0, 40);
|
|
25
|
+
const c = clusters.get(key) || { axis: result.axis || "other", cue: result.cue || "", count: 0, gen: 0, sessions: new Set(), mag: { refine: 0, redirect: 0, "hard-stop": 0 } };
|
|
26
|
+
c.count++;
|
|
27
|
+
if (result.generalizable) c.gen++;
|
|
28
|
+
if (result.magnitude && c.mag[result.magnitude] != null) c.mag[result.magnitude]++;
|
|
29
|
+
if (session) c.sessions.add(session);
|
|
30
|
+
// keep the most specific non-empty cue text seen for this cluster
|
|
31
|
+
if (!c.cue && result.cue) c.cue = result.cue;
|
|
32
|
+
clusters.set(key, c);
|
|
33
|
+
}
|
|
34
|
+
const cues = [...clusters.values()]
|
|
35
|
+
.map((c) => ({ axis: c.axis, cue: c.cue, count: c.count, gen: c.gen, genShare: c.count ? +(c.gen / c.count).toFixed(2) : 0, sessions: c.sessions.size, magnitude: c.mag }))
|
|
36
|
+
.sort((a, b) => (b.sessions - a.sessions) || (b.gen - a.gen) || (b.count - a.count));
|
|
37
|
+
return { scored, steers, fails, steerRate: scored ? +(steers / scored).toFixed(3) : 0, cues };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// harvest(scoreFn, { sessions, maxPairs }) -> aggregateCues over the pairs in those session
|
|
41
|
+
// files, newest first, capped at maxPairs (cost control). scoreFn(prior, user) -> result | null.
|
|
42
|
+
export async function harvest(scoreFn, { sessions = [], maxPairs = 400 } = {}) {
|
|
43
|
+
const items = [];
|
|
44
|
+
const gathered = [];
|
|
45
|
+
for (const path of sessions) {
|
|
46
|
+
let text = ""; try { text = readFileSync(path, "utf8"); } catch { continue; }
|
|
47
|
+
for (const p of pairs(text)) {
|
|
48
|
+
gathered.push({ ...p, session: path });
|
|
49
|
+
if (gathered.length >= maxPairs) break;
|
|
50
|
+
}
|
|
51
|
+
if (gathered.length >= maxPairs) break;
|
|
52
|
+
}
|
|
53
|
+
for (const { prior, user, session } of gathered) {
|
|
54
|
+
let result = null;
|
|
55
|
+
try { result = await scoreFn(prior, user); } catch { result = null; }
|
|
56
|
+
items.push({ session, result });
|
|
57
|
+
}
|
|
58
|
+
const agg = aggregateCues(items);
|
|
59
|
+
return { pairs: gathered.length, sessionsRead: sessions.length, ...agg };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export { resolveSessions };
|