chompyy 0.1.0 → 0.4.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/README.md +82 -8
- package/THIRD_PARTY_NOTICES.md +29 -1
- package/dist/appstate.js +121 -4
- package/dist/away.js +191 -25
- package/dist/blueprint.js +102 -7
- package/dist/board.js +143 -15
- package/dist/catalog.js +81 -0
- package/dist/claudesettings.js +23 -0
- package/dist/cli.js +804 -55
- package/dist/coldstart.js +208 -0
- package/dist/config.js +43 -8
- package/dist/costs.js +162 -0
- package/dist/deps.js +124 -0
- package/dist/dream.js +422 -0
- package/dist/duration.js +3 -3
- package/dist/gate.js +40 -5
- package/dist/history.js +308 -0
- package/dist/live.js +255 -0
- package/dist/livequota.js +42 -5
- package/dist/macapp.js +25 -2
- package/dist/pacing.js +189 -0
- package/dist/permissions.js +106 -0
- package/dist/picture.js +124 -0
- package/dist/picturetype.js +208 -0
- package/dist/preflight.js +168 -0
- package/dist/projects.js +5 -4
- package/dist/quota.js +31 -5
- package/dist/refresh.js +290 -0
- package/dist/report.js +41 -21
- package/dist/review.js +111 -11
- package/dist/runner.js +318 -10
- package/dist/taste.js +528 -0
- package/dist/tokens.js +75 -0
- package/dist/tokenstore.js +61 -0
- package/dist/trace.js +284 -0
- package/dist/triggers.js +193 -0
- package/dist/usage.js +467 -0
- package/dist/vendor/codeburn/prices.js +45 -0
- package/dist/verify.js +150 -0
- package/dist/verifycard.js +146 -0
- package/dist/workspace.js +132 -18
- package/package.json +4 -2
- package/skills/taste/SKILL.md +4 -1
- package/vendor/diagram-design/LICENSE +21 -0
- package/vendor/diagram-design/SKILL.md +399 -0
- package/vendor/diagram-design/UPSTREAM.md +18 -0
- package/vendor/diagram-design/assets/example-arc-diagram.html +111 -0
- package/vendor/diagram-design/assets/example-architecture-containment.html +205 -0
- package/vendor/diagram-design/assets/example-architecture-delta.html +193 -0
- package/vendor/diagram-design/assets/example-architecture.html +183 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-campus.html +108 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-coffee-shop.html +121 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-warehouse.html +127 -0
- package/vendor/diagram-design/assets/example-axonometric-plan.html +114 -0
- package/vendor/diagram-design/assets/example-bar.html +129 -0
- package/vendor/diagram-design/assets/example-beeswarm.html +384 -0
- package/vendor/diagram-design/assets/example-box-plot.html +127 -0
- package/vendor/diagram-design/assets/example-bubble.html +147 -0
- package/vendor/diagram-design/assets/example-bump.html +142 -0
- package/vendor/diagram-design/assets/example-data-flow.html +143 -0
- package/vendor/diagram-design/assets/example-datalake.html +269 -0
- package/vendor/diagram-design/assets/example-db-schema.html +302 -0
- package/vendor/diagram-design/assets/example-dependency.html +224 -0
- package/vendor/diagram-design/assets/example-deployment.html +190 -0
- package/vendor/diagram-design/assets/example-dp-integration.html +81 -0
- package/vendor/diagram-design/assets/example-dp-security-matrix.html +88 -0
- package/vendor/diagram-design/assets/example-er.html +202 -0
- package/vendor/diagram-design/assets/example-event-modeling.html +64 -0
- package/vendor/diagram-design/assets/example-exploded-ai-stack.html +85 -0
- package/vendor/diagram-design/assets/example-exploded-keyboard.html +84 -0
- package/vendor/diagram-design/assets/example-exploded-phone.html +83 -0
- package/vendor/diagram-design/assets/example-exploded-unboxing.html +84 -0
- package/vendor/diagram-design/assets/example-exploded.html +83 -0
- package/vendor/diagram-design/assets/example-fishbone.html +152 -0
- package/vendor/diagram-design/assets/example-flowchart.html +163 -0
- package/vendor/diagram-design/assets/example-gantt.html +137 -0
- package/vendor/diagram-design/assets/example-heatmap.html +224 -0
- package/vendor/diagram-design/assets/example-high-level-vertical.html +325 -0
- package/vendor/diagram-design/assets/example-high-level.html +301 -0
- package/vendor/diagram-design/assets/example-import-drawio.html +185 -0
- package/vendor/diagram-design/assets/example-import-excalidraw.html +70 -0
- package/vendor/diagram-design/assets/example-import-mermaid.html +70 -0
- package/vendor/diagram-design/assets/example-import-plantuml.html +107 -0
- package/vendor/diagram-design/assets/example-it-state.html +128 -0
- package/vendor/diagram-design/assets/example-journey.html +148 -0
- package/vendor/diagram-design/assets/example-kanban.html +174 -0
- package/vendor/diagram-design/assets/example-layers.html +123 -0
- package/vendor/diagram-design/assets/example-line.html +111 -0
- package/vendor/diagram-design/assets/example-loop.html +100 -0
- package/vendor/diagram-design/assets/example-marimekko.html +148 -0
- package/vendor/diagram-design/assets/example-medallion.html +159 -0
- package/vendor/diagram-design/assets/example-nested.html +136 -0
- package/vendor/diagram-design/assets/example-org-chart.html +45 -0
- package/vendor/diagram-design/assets/example-polar.html +116 -0
- package/vendor/diagram-design/assets/example-process.html +64 -0
- package/vendor/diagram-design/assets/example-pyramid.html +119 -0
- package/vendor/diagram-design/assets/example-quadrant-consultant.html +166 -0
- package/vendor/diagram-design/assets/example-quadrant.html +135 -0
- package/vendor/diagram-design/assets/example-radar.html +139 -0
- package/vendor/diagram-design/assets/example-requirement-traceability.html +122 -0
- package/vendor/diagram-design/assets/example-ridgeline.html +104 -0
- package/vendor/diagram-design/assets/example-sankey.html +150 -0
- package/vendor/diagram-design/assets/example-sbgn.html +213 -0
- package/vendor/diagram-design/assets/example-scatter.html +141 -0
- package/vendor/diagram-design/assets/example-sequence-oauth.html +227 -0
- package/vendor/diagram-design/assets/example-sequence.html +222 -0
- package/vendor/diagram-design/assets/example-service-blueprint.html +185 -0
- package/vendor/diagram-design/assets/example-slopegraph.html +119 -0
- package/vendor/diagram-design/assets/example-state-lifecycle.html +92 -0
- package/vendor/diagram-design/assets/example-state.html +147 -0
- package/vendor/diagram-design/assets/example-steps.html +78 -0
- package/vendor/diagram-design/assets/example-story-map.html +184 -0
- package/vendor/diagram-design/assets/example-streamgraph.html +99 -0
- package/vendor/diagram-design/assets/example-swimlane.html +172 -0
- package/vendor/diagram-design/assets/example-timeline.html +135 -0
- package/vendor/diagram-design/assets/example-tree-block-decomposition.html +151 -0
- package/vendor/diagram-design/assets/example-tree.html +173 -0
- package/vendor/diagram-design/assets/example-treemap.html +107 -0
- package/vendor/diagram-design/assets/example-uml-class.html +188 -0
- package/vendor/diagram-design/assets/example-unit-grid.html +141 -0
- package/vendor/diagram-design/assets/example-venn.html +110 -0
- package/vendor/diagram-design/assets/example-wardley.html +153 -0
- package/vendor/diagram-design/assets/example-waterfall.html +129 -0
- package/vendor/diagram-design/assets/template-dark.html +99 -0
- package/vendor/diagram-design/assets/template.html +100 -0
- package/vendor/diagram-design/references/layout-budget.md +103 -0
- package/vendor/diagram-design/references/output-spec.md +277 -0
- package/vendor/diagram-design/references/primitive-annotation.md +36 -0
- package/vendor/diagram-design/references/primitive-sketchy.md +43 -0
- package/vendor/diagram-design/references/primitives-core.md +146 -0
- package/vendor/diagram-design/references/semantic-patterns.md +154 -0
- package/vendor/diagram-design/references/style-guide.md +234 -0
- package/vendor/diagram-design/references/type-architecture-delta.md +143 -0
- package/vendor/diagram-design/references/type-architecture.md +117 -0
- package/vendor/diagram-design/references/type-axonometric-plan.md +83 -0
- package/vendor/diagram-design/references/type-bar.md +108 -0
- package/vendor/diagram-design/references/type-data-flow.md +371 -0
- package/vendor/diagram-design/references/type-db-schema.md +48 -0
- package/vendor/diagram-design/references/type-dependency.md +113 -0
- package/vendor/diagram-design/references/type-deployment.md +45 -0
- package/vendor/diagram-design/references/type-dp-integration.md +407 -0
- package/vendor/diagram-design/references/type-dp-security-matrix.md +379 -0
- package/vendor/diagram-design/references/type-er.md +25 -0
- package/vendor/diagram-design/references/type-event-modeling.md +36 -0
- package/vendor/diagram-design/references/type-exploded.md +115 -0
- package/vendor/diagram-design/references/type-fishbone.md +75 -0
- package/vendor/diagram-design/references/type-flowchart.md +23 -0
- package/vendor/diagram-design/references/type-gantt.md +45 -0
- package/vendor/diagram-design/references/type-heatmap.md +80 -0
- package/vendor/diagram-design/references/type-high-level.md +470 -0
- package/vendor/diagram-design/references/type-it-state.md +468 -0
- package/vendor/diagram-design/references/type-journey.md +55 -0
- package/vendor/diagram-design/references/type-kanban.md +49 -0
- package/vendor/diagram-design/references/type-layers.md +26 -0
- package/vendor/diagram-design/references/type-line.md +337 -0
- package/vendor/diagram-design/references/type-loop.md +223 -0
- package/vendor/diagram-design/references/type-medallion.md +356 -0
- package/vendor/diagram-design/references/type-nested.md +22 -0
- package/vendor/diagram-design/references/type-org-chart.md +44 -0
- package/vendor/diagram-design/references/type-polar.md +136 -0
- package/vendor/diagram-design/references/type-process.md +490 -0
- package/vendor/diagram-design/references/type-pyramid.md +33 -0
- package/vendor/diagram-design/references/type-quadrant.md +81 -0
- package/vendor/diagram-design/references/type-radar.md +82 -0
- package/vendor/diagram-design/references/type-requirement-traceability.md +45 -0
- package/vendor/diagram-design/references/type-sankey.md +75 -0
- package/vendor/diagram-design/references/type-sbgn.md +80 -0
- package/vendor/diagram-design/references/type-scatter.md +276 -0
- package/vendor/diagram-design/references/type-sequence.md +130 -0
- package/vendor/diagram-design/references/type-service-blueprint.md +103 -0
- package/vendor/diagram-design/references/type-state.md +30 -0
- package/vendor/diagram-design/references/type-steps.md +180 -0
- package/vendor/diagram-design/references/type-story-map.md +46 -0
- package/vendor/diagram-design/references/type-swimlane.md +22 -0
- package/vendor/diagram-design/references/type-timeline.md +20 -0
- package/vendor/diagram-design/references/type-tree.md +24 -0
- package/vendor/diagram-design/references/type-treemap.md +137 -0
- package/vendor/diagram-design/references/type-uml-class.md +65 -0
- package/vendor/diagram-design/references/type-unit-grid.md +63 -0
- package/vendor/diagram-design/references/type-venn.md +26 -0
- package/vendor/diagram-design/references/type-wardley.md +39 -0
- package/vendor/diagram-design/references/type-waterfall.md +75 -0
- package/vendor/diagram-design/scripts/self_check.py +1177 -0
- package/vendor/diagram-design/scripts/verify_geometry.py +696 -0
package/dist/taste.js
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
// Taste distiller (spec §5.8, FEATURES §7): signals → candidate preferences → one-tap questions → taste.md.
|
|
2
|
+
//
|
|
3
|
+
// - Evidence first: every preference cites signals (ratings, "what would have made it a 5?" picks, blueprint
|
|
4
|
+
// edits, keep/undo, answers). Citations are checked against signals.jsonl, so the model can't invent any.
|
|
5
|
+
// - Learn only from governed work: signals of cards you approved, ran or rated. Drafts you dropped don't count.
|
|
6
|
+
// - Asked, not assumed: a candidate becomes a question after 3 separate cards (or right away when you stated
|
|
7
|
+
// it yourself in a rating). Only a "yes" writes it to taste.md, with a valid-from date.
|
|
8
|
+
// - Never silently deleted: contradicted or removed preferences are retired with the reason and evidence.
|
|
9
|
+
// - Your edits win: delete a learned line from taste.md and the preference is retired.
|
|
10
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { appendJsonl, homePath, readJson, writeJson } from './home.js';
|
|
12
|
+
// ---------- taste.md ----------
|
|
13
|
+
export const TASTE_STUB = `# taste.md
|
|
14
|
+
|
|
15
|
+
What Chompyy has learned about how you like work done. Plain text: edit it freely, your edits win.
|
|
16
|
+
Learned lines end with an id like "p3"; delete the line and Chompyy retires that preference.
|
|
17
|
+
|
|
18
|
+
## Everywhere
|
|
19
|
+
`;
|
|
20
|
+
export function tastePath() {
|
|
21
|
+
return homePath('taste.md');
|
|
22
|
+
}
|
|
23
|
+
export function readTaste() {
|
|
24
|
+
const path = tastePath();
|
|
25
|
+
if (existsSync(path))
|
|
26
|
+
return { path, text: readFileSync(path, 'utf8'), created: false };
|
|
27
|
+
writeFileSync(path, TASTE_STUB);
|
|
28
|
+
return { path, text: TASTE_STUB, created: true };
|
|
29
|
+
}
|
|
30
|
+
/** Insert a line at the end of a "## <scope>" section, creating the section if needed. */
|
|
31
|
+
export function insertUnderHeading(text, scope, line) {
|
|
32
|
+
const out = text.endsWith('\n') ? text : `${text}\n`;
|
|
33
|
+
const heading = `## ${scope}`;
|
|
34
|
+
const rows = out.split('\n');
|
|
35
|
+
const at = rows.findIndex((l) => l.trim() === heading);
|
|
36
|
+
if (at < 0)
|
|
37
|
+
return `${out.trimEnd()}\n\n${heading}\n${line}\n`;
|
|
38
|
+
let end = at + 1;
|
|
39
|
+
while (end < rows.length && !rows[end].startsWith('## '))
|
|
40
|
+
end++;
|
|
41
|
+
while (end > at + 1 && rows[end - 1].trim() === '')
|
|
42
|
+
end--; // after the section's last line
|
|
43
|
+
rows.splice(end, 0, line);
|
|
44
|
+
return rows.join('\n');
|
|
45
|
+
}
|
|
46
|
+
/** taste.md for agents: drop the header comment so prompts carry only the preferences. Empty when nothing learned. */
|
|
47
|
+
export function tasteForPrompt() {
|
|
48
|
+
const path = tastePath();
|
|
49
|
+
if (!existsSync(path))
|
|
50
|
+
return '';
|
|
51
|
+
const lines = readFileSync(path, 'utf8')
|
|
52
|
+
.split('\n')
|
|
53
|
+
.map((l) => l.replace(/\s+\((learned|from your history)[^)]*\)\s*$/, ''));
|
|
54
|
+
const kept = lines.filter((l) => /^\s*[-*]\s+\S/.test(l) || l.startsWith('## '));
|
|
55
|
+
// Only headings, no preferences: nothing to say.
|
|
56
|
+
if (!kept.some((l) => !l.startsWith('## ')))
|
|
57
|
+
return '';
|
|
58
|
+
return kept.join('\n').replace(/(## [^\n]+\n)(?=## |$)/g, '').trim();
|
|
59
|
+
}
|
|
60
|
+
export function signalsPath() {
|
|
61
|
+
return homePath('signals.jsonl');
|
|
62
|
+
}
|
|
63
|
+
export function readSignals() {
|
|
64
|
+
const path = signalsPath();
|
|
65
|
+
if (!existsSync(path))
|
|
66
|
+
return [];
|
|
67
|
+
const out = [];
|
|
68
|
+
readFileSync(path, 'utf8')
|
|
69
|
+
.split('\n')
|
|
70
|
+
.forEach((line, i) => {
|
|
71
|
+
if (!line.trim())
|
|
72
|
+
return;
|
|
73
|
+
try {
|
|
74
|
+
const raw = JSON.parse(line);
|
|
75
|
+
out.push({
|
|
76
|
+
id: `s${i + 1}`,
|
|
77
|
+
kind: raw.kind ?? 'rating',
|
|
78
|
+
at: String(raw.at ?? ''),
|
|
79
|
+
...(raw.card != null ? { card: String(raw.card) } : {}),
|
|
80
|
+
...(raw.title ? { title: String(raw.title) } : {}),
|
|
81
|
+
raw,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
catch { }
|
|
85
|
+
});
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
export function recordOutcome(card, outcome, now) {
|
|
89
|
+
appendJsonl(signalsPath(), { at: now.toISOString(), card: card.id, title: card.title, kind: 'outcome', outcome, checks: card.run?.checks?.result ?? null });
|
|
90
|
+
}
|
|
91
|
+
/** Cards whose signals may teach taste: approved, ran or rated (spec: learn only from approved or rated work). */
|
|
92
|
+
export function governedCards(cards) {
|
|
93
|
+
const archive = homePath('archive.jsonl');
|
|
94
|
+
const dropped = existsSync(archive)
|
|
95
|
+
? readFileSync(archive, 'utf8')
|
|
96
|
+
.split('\n')
|
|
97
|
+
.flatMap((l) => {
|
|
98
|
+
try {
|
|
99
|
+
return l.trim() ? [JSON.parse(l)] : [];
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return [];
|
|
103
|
+
}
|
|
104
|
+
})
|
|
105
|
+
: [];
|
|
106
|
+
return new Set([...cards, ...dropped].filter((c) => c.approvedAt || c.run || c.rating || c.outcome).map((c) => c.id));
|
|
107
|
+
}
|
|
108
|
+
/** How strong a signal is as evidence. Concrete changes you made beat feelings. */
|
|
109
|
+
export function signalWeight(s) {
|
|
110
|
+
if (s.kind === 'blueprint-edit')
|
|
111
|
+
return 3;
|
|
112
|
+
if (s.kind === 'outcome')
|
|
113
|
+
return s.raw.outcome === 'undone' ? 3 : 1;
|
|
114
|
+
if (s.kind === 'rating')
|
|
115
|
+
return Array.isArray(s.raw.toFive) && s.raw.toFive.length ? 3 : s.raw.reason ? 2 : 1;
|
|
116
|
+
if (s.kind === 'answer')
|
|
117
|
+
return 1;
|
|
118
|
+
if (s.kind === 'chat')
|
|
119
|
+
return 2;
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
/** One line per signal, for the distiller prompt and for "why do you think that?". */
|
|
123
|
+
export function describeSignal(s, max = 400) {
|
|
124
|
+
const cut = (v, n = max) => {
|
|
125
|
+
const t = String(v ?? '').replace(/\s+/g, ' ').trim();
|
|
126
|
+
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
|
|
127
|
+
};
|
|
128
|
+
const card = s.card ? `card #${s.card} "${s.title ?? ''}"` : '';
|
|
129
|
+
switch (s.kind) {
|
|
130
|
+
case 'rating': {
|
|
131
|
+
const toFive = Array.isArray(s.raw.toFive) && s.raw.toFive.length ? ` · to make it a 5: ${s.raw.toFive.join('; ')}` : '';
|
|
132
|
+
return `rated ${card} ${s.raw.rating}/5${s.raw.reason ? ` "${cut(s.raw.reason)}"` : ''}${toFive}`;
|
|
133
|
+
}
|
|
134
|
+
case 'blueprint-edit':
|
|
135
|
+
return `edited the blueprint of ${card}\n before: ${cut(s.raw.before)}\n after: ${cut(s.raw.after)}`;
|
|
136
|
+
case 'outcome':
|
|
137
|
+
return `${s.raw.outcome === 'undone' ? 'undid' : 'kept'} the result of ${card}`;
|
|
138
|
+
case 'answer':
|
|
139
|
+
return `answered the questions of ${card}: "${cut(s.raw.text)}"`;
|
|
140
|
+
case 'chat': {
|
|
141
|
+
const where = String(s.raw.workspace ?? '').split('/').pop() || 'a session';
|
|
142
|
+
return `said in a session in ${where} on ${s.at.slice(0, 10)}: "${cut(s.raw.quote)}"${s.raw.why ? ` (${cut(s.raw.why, 200)})` : ''}`;
|
|
143
|
+
}
|
|
144
|
+
default:
|
|
145
|
+
return `${s.kind} ${card}`;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** Short receipts for the report: "undid #3, #5 · edited blueprint of #7". */
|
|
149
|
+
export function receipts(signals) {
|
|
150
|
+
const groups = new Map();
|
|
151
|
+
for (const s of signals) {
|
|
152
|
+
const verb = s.kind === 'outcome' ? (s.raw.outcome === 'undone' ? 'undid' : 'kept')
|
|
153
|
+
: s.kind === 'blueprint-edit' ? 'edited the blueprint of'
|
|
154
|
+
: s.kind === 'rating' ? (Array.isArray(s.raw.toFive) && s.raw.toFive.length ? 'asked for a change on' : 'rated')
|
|
155
|
+
: s.kind === 'answer' ? 'answered' : s.kind === 'chat' ? 'said it in sessions on' : s.kind;
|
|
156
|
+
const ids = groups.get(verb) ?? [];
|
|
157
|
+
const label = s.card ? `#${s.card}` : s.kind === 'chat' ? s.at.slice(5, 10) : '';
|
|
158
|
+
if (label && !ids.includes(label))
|
|
159
|
+
ids.push(label);
|
|
160
|
+
groups.set(verb, ids);
|
|
161
|
+
}
|
|
162
|
+
return [...groups].map(([verb, ids]) => `${verb} ${ids.join(', ')}`).join(' · ');
|
|
163
|
+
}
|
|
164
|
+
/** A preference needs this many separate cards before Chompyy asks (FEATURES §7: 3 confirmations). */
|
|
165
|
+
export const MIN_CARDS = 3;
|
|
166
|
+
/** …or this many separate everyday sessions where you said it (the nightly read; "a mistake made a second time"). */
|
|
167
|
+
export const MIN_SESSIONS = 2;
|
|
168
|
+
export function storePath() {
|
|
169
|
+
return homePath('preferences.json');
|
|
170
|
+
}
|
|
171
|
+
export function loadStore() {
|
|
172
|
+
return readJson(storePath(), { nextId: 1, prefs: [] });
|
|
173
|
+
}
|
|
174
|
+
export function saveStore(store) {
|
|
175
|
+
writeJson(storePath(), store);
|
|
176
|
+
}
|
|
177
|
+
export function getPref(store, id) {
|
|
178
|
+
const p = store.prefs.find((x) => x.id === id.trim().toLowerCase());
|
|
179
|
+
if (!p)
|
|
180
|
+
throw new Error(`No preference "${id}". See \`chompyy taste list\`.`);
|
|
181
|
+
return p;
|
|
182
|
+
}
|
|
183
|
+
export function distinctCards(evidence, byId) {
|
|
184
|
+
return new Set(evidence.map((id) => byId.get(id)?.card).filter(Boolean)).size;
|
|
185
|
+
}
|
|
186
|
+
/** Separate everyday sessions behind it (chat signals from the nightly read). */
|
|
187
|
+
export function distinctSessions(evidence, byId) {
|
|
188
|
+
return new Set(evidence.map((id) => byId.get(id)).filter((s) => s?.kind === 'chat').map((s) => String(s.raw.session))).size;
|
|
189
|
+
}
|
|
190
|
+
/** Separate places it was seen: cards plus sessions. */
|
|
191
|
+
export function sightings(evidence, byId) {
|
|
192
|
+
return distinctCards(evidence, byId) + distinctSessions(evidence, byId);
|
|
193
|
+
}
|
|
194
|
+
/** Strength for ordering questions: separate cards first, then how concrete the signals are. */
|
|
195
|
+
export function strength(p, byId) {
|
|
196
|
+
const weight = p.evidence.reduce((sum, id) => sum + (byId.get(id) ? signalWeight(byId.get(id)) : 0), 0);
|
|
197
|
+
return sightings(p.evidence, byId) * 10 + weight + (p.stated ? 5 : 0);
|
|
198
|
+
}
|
|
199
|
+
/** Promote candidates with enough evidence; wake snoozed ones that gained a card. */
|
|
200
|
+
export function promote(p, byId) {
|
|
201
|
+
const cards = distinctCards(p.evidence, byId);
|
|
202
|
+
const sessions = distinctSessions(p.evidence, byId);
|
|
203
|
+
const enough = cards >= MIN_CARDS || sessions >= MIN_SESSIONS || cards + sessions >= MIN_CARDS || (p.stated && cards >= 1);
|
|
204
|
+
if (p.status === 'candidate' && enough)
|
|
205
|
+
p.status = 'ready';
|
|
206
|
+
if (p.status === 'snoozed' && cards + sessions > (p.snoozedAtCards ?? 0))
|
|
207
|
+
p.status = 'ready';
|
|
208
|
+
}
|
|
209
|
+
// ---------- the distiller ----------
|
|
210
|
+
export function distillPrompt(signals, prefs) {
|
|
211
|
+
const open = prefs.filter((p) => ['candidate', 'ready', 'active', 'snoozed'].includes(p.status));
|
|
212
|
+
const muted = prefs.filter((p) => p.status === 'muted' || (p.status === 'retired' && !p.validFrom));
|
|
213
|
+
return `You learn one developer's taste: how they like an agent to do work. Below are signals from cards an agent
|
|
214
|
+
ran for them unattended: their ratings and reasons, "what would have made it a 5?" picks, edits they made to a
|
|
215
|
+
blueprint before approving it, results they kept or undid, and answers to the agent's questions. Also things
|
|
216
|
+
they said to their AI in everyday coding sessions ("said in a session"), in their exact words, each with what
|
|
217
|
+
the nightly read thought it showed. The same point said in different sessions is one preference: cite them all.
|
|
218
|
+
|
|
219
|
+
Find preferences that would change what an agent does in a DIFFERENT task next week. A preference must be
|
|
220
|
+
supported by the signals you cite. Prefer patterns across separate cards or sessions. A reason the person wrote or a
|
|
221
|
+
change they picked counts as "stated". Write each as an instruction to an agent, at most 20 words, e.g.
|
|
222
|
+
"Don't add tests unless the blueprint asks for them". Write "noticed" as one sentence to the person saying
|
|
223
|
+
"you", with the receipts, e.g. "You undid 3 cards that added tests you didn't ask for."
|
|
224
|
+
|
|
225
|
+
Not preferences: one-off details of a single task, moods, anything true only for one card, secrets, and
|
|
226
|
+
anything about their health, relationships, money, identity or private life.
|
|
227
|
+
|
|
228
|
+
Scope is "Everywhere", or a project folder name if it only applies there.
|
|
229
|
+
${open.length ? `
|
|
230
|
+
Preferences already known (extend one by giving its id, instead of creating a duplicate):
|
|
231
|
+
${open.map((p) => `- ${p.id} [${p.status}] ${p.text}`).join('\n')}
|
|
232
|
+
` : ''}${muted.length ? `
|
|
233
|
+
The person declined these; never propose them again, nor the same thing in other words:
|
|
234
|
+
${muted.map((p) => `- ${p.text}`).join('\n')}
|
|
235
|
+
` : ''}
|
|
236
|
+
If a signal clearly goes against a known preference (they undid work that followed it, or rated it down
|
|
237
|
+
because of it), list it under "contradicted".
|
|
238
|
+
|
|
239
|
+
Reply with ONLY this JSON, no prose; empty lists are fine and fewer, stronger items beat many weak ones:
|
|
240
|
+
{"candidates":[{"id":null,"scope":"Everywhere","text":"...","noticed":"...","signals":["s3","s9"],"stated":false}],
|
|
241
|
+
"contradicted":[{"id":"p2","signals":["s14"],"why":"one sentence"}]}
|
|
242
|
+
|
|
243
|
+
Signals:
|
|
244
|
+
${signals.map((s) => `${s.id} (${s.at.slice(0, 10)}) ${describeSignal(s)}`).join('\n')}`;
|
|
245
|
+
}
|
|
246
|
+
function parseJson(output) {
|
|
247
|
+
const start = output.indexOf('{');
|
|
248
|
+
const end = output.lastIndexOf('}');
|
|
249
|
+
if (start < 0 || end <= start)
|
|
250
|
+
throw new Error('The model did not reply with JSON.');
|
|
251
|
+
return JSON.parse(output.slice(start, end + 1));
|
|
252
|
+
}
|
|
253
|
+
const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
|
|
254
|
+
const sigIds = (v, valid) => Array.isArray(v) ? [...new Set(v.filter((x) => typeof x === 'string').map((x) => x.trim().toLowerCase()))].filter((x) => valid.has(x)) : [];
|
|
255
|
+
/** Apply the model's reply to the store. Only evidence that exists and is governed is kept. */
|
|
256
|
+
export function applyDistill(store, raw, signals, now) {
|
|
257
|
+
const at = now.toISOString();
|
|
258
|
+
const byId = new Map(signals.map((s) => [s.id, s]));
|
|
259
|
+
const valid = new Set(signals.map((s) => s.id));
|
|
260
|
+
const changes = { added: [], extended: [], ready: [], retired: [], dropped: 0 };
|
|
261
|
+
const muted = new Set(store.prefs.filter((p) => p.status === 'muted').map((p) => p.text.toLowerCase()));
|
|
262
|
+
for (const item of raw.candidates ?? []) {
|
|
263
|
+
const o = (item ?? {});
|
|
264
|
+
const evidence = sigIds(o.signals, valid);
|
|
265
|
+
const text = str(o.text, 200);
|
|
266
|
+
const oid = typeof o.id === 'string' ? o.id.trim().toLowerCase() : '';
|
|
267
|
+
const existing = oid ? store.prefs.find((p) => p.id === oid) : undefined;
|
|
268
|
+
if (!evidence.length || (!existing && (!text || muted.has(text.toLowerCase())))) {
|
|
269
|
+
changes.dropped++;
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
if (existing) {
|
|
273
|
+
if (existing.status === 'muted' || existing.status === 'retired')
|
|
274
|
+
continue;
|
|
275
|
+
const fresh = evidence.filter((e) => !existing.evidence.includes(e));
|
|
276
|
+
if (!fresh.length)
|
|
277
|
+
continue;
|
|
278
|
+
existing.evidence.push(...fresh);
|
|
279
|
+
existing.stated ||= o.stated === true;
|
|
280
|
+
const noticed = str(o.noticed, 300);
|
|
281
|
+
if (noticed)
|
|
282
|
+
existing.noticed = noticed;
|
|
283
|
+
existing.updatedAt = at;
|
|
284
|
+
changes.extended.push(existing.id);
|
|
285
|
+
const before = existing.status;
|
|
286
|
+
promote(existing, byId);
|
|
287
|
+
if (before !== 'ready' && existing.status === 'ready')
|
|
288
|
+
changes.ready.push(existing.id);
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
const p = {
|
|
292
|
+
id: `p${store.nextId++}`,
|
|
293
|
+
scope: str(o.scope, 60) || 'Everywhere',
|
|
294
|
+
text,
|
|
295
|
+
noticed: str(o.noticed, 300) || text,
|
|
296
|
+
status: 'candidate',
|
|
297
|
+
evidence,
|
|
298
|
+
stated: o.stated === true && evidence.some((e) => byId.get(e)?.kind === 'rating'),
|
|
299
|
+
createdAt: at,
|
|
300
|
+
updatedAt: at,
|
|
301
|
+
};
|
|
302
|
+
promote(p, byId);
|
|
303
|
+
store.prefs.push(p);
|
|
304
|
+
changes.added.push(p.id);
|
|
305
|
+
if (p.status === 'ready')
|
|
306
|
+
changes.ready.push(p.id);
|
|
307
|
+
}
|
|
308
|
+
for (const item of raw.contradicted ?? []) {
|
|
309
|
+
const o = (item ?? {});
|
|
310
|
+
const oid = typeof o.id === 'string' ? o.id.trim().toLowerCase() : '';
|
|
311
|
+
const p = oid ? store.prefs.find((x) => x.id === oid) : undefined;
|
|
312
|
+
const against = sigIds(o.signals, valid).filter((e) => !p?.evidence.includes(e));
|
|
313
|
+
if (!p || !against.length || p.status === 'retired' || p.status === 'muted') {
|
|
314
|
+
changes.dropped++;
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
retire(p, str(o.why, 300) || 'later signals went against it', now, against);
|
|
318
|
+
changes.retired.push(p.id);
|
|
319
|
+
}
|
|
320
|
+
return changes;
|
|
321
|
+
}
|
|
322
|
+
export function retire(p, because, now, against = []) {
|
|
323
|
+
p.status = 'retired';
|
|
324
|
+
p.retiredAt = now.toISOString();
|
|
325
|
+
p.retiredBecause = because;
|
|
326
|
+
if (against.length)
|
|
327
|
+
p.against = [...(p.against ?? []), ...against];
|
|
328
|
+
p.updatedAt = p.retiredAt;
|
|
329
|
+
}
|
|
330
|
+
/** Signals the distiller should read: governed, about cards, not yet seen. */
|
|
331
|
+
export function newSignals(store, signals, governed) {
|
|
332
|
+
const seen = store.seenThrough ?? 0;
|
|
333
|
+
return signals.filter((s) => Number(s.id.slice(1)) > seen && signalWeight(s) > 0 && (s.kind === 'chat' || (s.card && governed.has(s.card))));
|
|
334
|
+
}
|
|
335
|
+
/** Read new signals with the model and update preferences.json. Runs at most once per call; nothing to read = no model call. */
|
|
336
|
+
export async function distill(board, runner, opts) {
|
|
337
|
+
const store = loadStore();
|
|
338
|
+
const signals = readSignals();
|
|
339
|
+
const fresh = newSignals(store, signals, governedCards(board.cards));
|
|
340
|
+
const empty = { added: [], extended: [], ready: [], retired: [], dropped: 0 };
|
|
341
|
+
if (!fresh.length)
|
|
342
|
+
return { changes: empty, read: 0 };
|
|
343
|
+
// Context: the evidence behind open preferences, so the model can extend or contradict them.
|
|
344
|
+
const byId = new Map(signals.map((s) => [s.id, s]));
|
|
345
|
+
const context = store.prefs
|
|
346
|
+
.filter((p) => ['candidate', 'ready', 'active', 'snoozed'].includes(p.status))
|
|
347
|
+
.flatMap((p) => p.evidence.map((e) => byId.get(e)).filter(Boolean));
|
|
348
|
+
const shown = [...new Map([...context, ...fresh].map((s) => [s.id, s])).values()].sort((a, b) => Number(a.id.slice(1)) - Number(b.id.slice(1)));
|
|
349
|
+
const result = await runner.run({ prompt: distillPrompt(shown, store.prefs), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 180_000 });
|
|
350
|
+
if (result.timedOut)
|
|
351
|
+
throw new Error('The distiller timed out.');
|
|
352
|
+
if (result.exitCode !== 0)
|
|
353
|
+
throw new Error(`claude exited with ${result.exitCode}: ${result.stderr.trim().slice(0, 300)}`);
|
|
354
|
+
const changes = applyDistill(store, parseJson(result.output), shown, opts.now);
|
|
355
|
+
store.seenThrough = Math.max(store.seenThrough ?? 0, ...signals.map((s) => Number(s.id.slice(1))));
|
|
356
|
+
store.lastDistillAt = opts.now.toISOString();
|
|
357
|
+
saveStore(store);
|
|
358
|
+
syncTasteFile(opts.now);
|
|
359
|
+
return { changes, read: fresh.length };
|
|
360
|
+
}
|
|
361
|
+
// ---------- asking ----------
|
|
362
|
+
/** The one question for the next report: the ready preference with the strongest evidence. */
|
|
363
|
+
export function nextQuestion(store, signals) {
|
|
364
|
+
const byId = new Map(signals.map((s) => [s.id, s]));
|
|
365
|
+
const ready = store.prefs.filter((p) => p.status === 'ready');
|
|
366
|
+
ready.sort((a, b) => strength(b, byId) - strength(a, byId));
|
|
367
|
+
return ready[0] ?? null;
|
|
368
|
+
}
|
|
369
|
+
export function formatQuestion(p, signals) {
|
|
370
|
+
const byId = new Map(signals.map((s) => [s.id, s]));
|
|
371
|
+
const ev = p.evidence.map((e) => byId.get(e)).filter((s) => Boolean(s));
|
|
372
|
+
return [
|
|
373
|
+
`💭 ${p.noticed}`,
|
|
374
|
+
` From now on: "${p.text}"?`,
|
|
375
|
+
` Evidence: ${receipts(ev)} (chompyy taste why ${p.id})`,
|
|
376
|
+
` chompyy taste yes ${p.id} · not-now ${p.id} · never ${p.id}`,
|
|
377
|
+
];
|
|
378
|
+
}
|
|
379
|
+
/** Your one-tap answer. Yes writes it to taste.md; the others are signals too, and Chompyy asks less after them. */
|
|
380
|
+
export function answerPreference(id, answer, now) {
|
|
381
|
+
const store = loadStore();
|
|
382
|
+
const p = getPref(store, id);
|
|
383
|
+
if (p.status === 'retired')
|
|
384
|
+
throw new Error(`${p.id} was retired: ${p.retiredBecause ?? ''}`);
|
|
385
|
+
const at = now.toISOString();
|
|
386
|
+
const byId = new Map(readSignals().map((s) => [s.id, s]));
|
|
387
|
+
if (answer === 'yes') {
|
|
388
|
+
p.status = 'active';
|
|
389
|
+
p.validFrom = at;
|
|
390
|
+
}
|
|
391
|
+
else if (answer === 'not-now') {
|
|
392
|
+
p.status = 'snoozed';
|
|
393
|
+
p.snoozedAtCards = sightings(p.evidence, byId);
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
p.status = 'muted';
|
|
397
|
+
}
|
|
398
|
+
p.updatedAt = at;
|
|
399
|
+
saveStore(store);
|
|
400
|
+
appendJsonl(signalsPath(), { at, kind: 'taste-answer', pref: p.id, text: p.text, answer });
|
|
401
|
+
syncTasteFile(now);
|
|
402
|
+
return p;
|
|
403
|
+
}
|
|
404
|
+
/** You retire a preference yourself. */
|
|
405
|
+
export function retirePreference(id, now) {
|
|
406
|
+
const store = loadStore();
|
|
407
|
+
const p = getPref(store, id);
|
|
408
|
+
retire(p, 'you retired it', now);
|
|
409
|
+
saveStore(store);
|
|
410
|
+
syncTasteFile(now);
|
|
411
|
+
return p;
|
|
412
|
+
}
|
|
413
|
+
// ---------- taste.md stays in step ----------
|
|
414
|
+
const MARK = /\s+·\s+(p\d+)\)\s*$/;
|
|
415
|
+
export function learnedLine(p, signals) {
|
|
416
|
+
const byId = new Map(signals.map((s) => [s.id, s]));
|
|
417
|
+
const cards = [...new Set(p.evidence.map((e) => byId.get(e)?.card).filter(Boolean))].map((c) => `#${c}`);
|
|
418
|
+
return `- ${p.text} (learned ${(p.validFrom ?? '').slice(0, 10)}${cards.length ? ` · from cards ${cards.join(', ')}` : ''} · ${p.id})`;
|
|
419
|
+
}
|
|
420
|
+
/** Ids of learned lines present in taste.md. */
|
|
421
|
+
export function learnedIds(text) {
|
|
422
|
+
return new Set(text.split('\n').map((l) => l.match(MARK)?.[1]).filter((x) => Boolean(x)));
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Bring taste.md and preferences.json in step. Your edits win: a learned line you deleted retires that
|
|
426
|
+
* preference. Active preferences not written yet are added; retired ones are taken out. Returns ids retired.
|
|
427
|
+
*/
|
|
428
|
+
export function syncTasteFile(now) {
|
|
429
|
+
const store = loadStore();
|
|
430
|
+
const signals = readSignals();
|
|
431
|
+
const { path, text } = readTaste();
|
|
432
|
+
const present = learnedIds(text);
|
|
433
|
+
const retiredByYou = [];
|
|
434
|
+
for (const p of store.prefs) {
|
|
435
|
+
if (p.status === 'active' && p.rendered && !present.has(p.id)) {
|
|
436
|
+
retire(p, 'you removed it from taste.md', now);
|
|
437
|
+
retiredByYou.push(p.id);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
let out = text
|
|
441
|
+
.split('\n')
|
|
442
|
+
.filter((l) => {
|
|
443
|
+
const id = l.match(MARK)?.[1];
|
|
444
|
+
if (!id)
|
|
445
|
+
return true;
|
|
446
|
+
const p = store.prefs.find((x) => x.id === id);
|
|
447
|
+
return !p || p.status === 'active';
|
|
448
|
+
})
|
|
449
|
+
.join('\n');
|
|
450
|
+
for (const p of store.prefs) {
|
|
451
|
+
if (p.status === 'active' && !present.has(p.id))
|
|
452
|
+
out = insertUnderHeading(out, p.scope, learnedLine(p, signals));
|
|
453
|
+
if (p.status === 'active')
|
|
454
|
+
p.rendered = true;
|
|
455
|
+
else
|
|
456
|
+
delete p.rendered;
|
|
457
|
+
}
|
|
458
|
+
if (out !== text)
|
|
459
|
+
writeFileSync(path, out);
|
|
460
|
+
saveStore(store);
|
|
461
|
+
return retiredByYou;
|
|
462
|
+
}
|
|
463
|
+
// ---------- views ----------
|
|
464
|
+
const STATUS_LABEL = {
|
|
465
|
+
candidate: '… candidate',
|
|
466
|
+
ready: '💭 to ask',
|
|
467
|
+
active: '✓ in taste.md',
|
|
468
|
+
snoozed: '⏸ not now',
|
|
469
|
+
muted: '🔕 never',
|
|
470
|
+
retired: '✗ retired',
|
|
471
|
+
};
|
|
472
|
+
export function formatPrefs(store, signals) {
|
|
473
|
+
if (!store.prefs.length)
|
|
474
|
+
return 'No preferences yet. They come from your ratings, blueprint edits and keep/undo; run `chompyy distill`.';
|
|
475
|
+
const byId = new Map(signals.map((s) => [s.id, s]));
|
|
476
|
+
const order = ['ready', 'active', 'candidate', 'snoozed', 'muted', 'retired'];
|
|
477
|
+
const out = [];
|
|
478
|
+
for (const status of order) {
|
|
479
|
+
for (const p of store.prefs.filter((x) => x.status === status)) {
|
|
480
|
+
out.push(`${p.id.padEnd(4)} ${STATUS_LABEL[status].padEnd(15)} [${p.scope}] ${p.text} (${distinctCards(p.evidence, byId)} cards, ${distinctSessions(p.evidence, byId)} sessions)`);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
out.push('', `Why: chompyy taste why <id> · answer: taste yes|not-now|never <id> · retire: taste retire <id>`);
|
|
484
|
+
if (store.lastDistillAt)
|
|
485
|
+
out.push(`Last distilled ${store.lastDistillAt.slice(0, 16).replace('T', ' ')}.`);
|
|
486
|
+
return out.join('\n');
|
|
487
|
+
}
|
|
488
|
+
/** "Why do you think that?": every card, edit and quote behind a preference. */
|
|
489
|
+
export function formatWhy(p, signals) {
|
|
490
|
+
const byId = new Map(signals.map((s) => [s.id, s]));
|
|
491
|
+
const out = [`${p.id} · ${STATUS_LABEL[p.status]} · [${p.scope}]`, `"${p.text}"`, '', p.noticed, ''];
|
|
492
|
+
out.push('Evidence:');
|
|
493
|
+
for (const e of p.evidence) {
|
|
494
|
+
const s = byId.get(e);
|
|
495
|
+
out.push(s ? ` ${s.at.slice(0, 10)} ${describeSignal(s, 300)}` : ` ${e} (no longer in signals.jsonl)`);
|
|
496
|
+
}
|
|
497
|
+
if (p.against?.length) {
|
|
498
|
+
out.push('', 'Against it:');
|
|
499
|
+
for (const e of p.against) {
|
|
500
|
+
const s = byId.get(e);
|
|
501
|
+
if (s)
|
|
502
|
+
out.push(` ${s.at.slice(0, 10)} ${describeSignal(s, 300)}`);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
if (p.stated)
|
|
506
|
+
out.push('', 'You said this yourself in a rating, so it can be asked before 3 cards.');
|
|
507
|
+
if (p.validFrom)
|
|
508
|
+
out.push(`In force from ${p.validFrom.slice(0, 10)}.`);
|
|
509
|
+
if (p.retiredAt)
|
|
510
|
+
out.push(`Retired ${p.retiredAt.slice(0, 10)}: ${p.retiredBecause}.`);
|
|
511
|
+
return out.join('\n');
|
|
512
|
+
}
|
|
513
|
+
/** What changed in taste since a moment, for the morning report. */
|
|
514
|
+
export function tasteChangesSince(store, since) {
|
|
515
|
+
const after = (t) => Boolean(t && (!since || t > since));
|
|
516
|
+
return {
|
|
517
|
+
learned: store.prefs.filter((p) => p.status === 'active' && after(p.validFrom)).length,
|
|
518
|
+
retired: store.prefs.filter((p) => p.status === 'retired' && after(p.retiredAt)).length,
|
|
519
|
+
toAsk: store.prefs.filter((p) => p.status === 'ready').length,
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
/** Distill only when there is something new and it hasn't run in a while. */
|
|
523
|
+
export function distillDue(board, now, minGapMs = 6 * 3600_000) {
|
|
524
|
+
const store = loadStore();
|
|
525
|
+
if (store.lastDistillAt && now.getTime() - Date.parse(store.lastDistillAt) < minGapMs)
|
|
526
|
+
return false;
|
|
527
|
+
return newSignals(store, readSignals(), governedCards(board.cards)).length > 0;
|
|
528
|
+
}
|
package/dist/tokens.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Exact tokens per run (2026-11-19): what a card really used, from the run's own stream (the `result` event
|
|
2
|
+
// Claude Code prints at the end), instead of "5-hour % before vs after", which is whole points only, mixes in
|
|
3
|
+
// your own use at the same time, and goes blank when the window resets mid-run. Tagged per run, the way
|
|
4
|
+
// Langfuse tags each interaction; the base for honest cost estimates later.
|
|
5
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
6
|
+
/** Adds up every `result` event in a stream (a resumed or multi-result run has more than one). */
|
|
7
|
+
export class TokenTally {
|
|
8
|
+
t = null;
|
|
9
|
+
cost = 0;
|
|
10
|
+
feed(event) {
|
|
11
|
+
const e = event;
|
|
12
|
+
if (e?.type !== 'result' || !e.usage)
|
|
13
|
+
return;
|
|
14
|
+
const t = (this.t ??= { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, thinking: 0, costUsd: 0, turns: 0, models: [] });
|
|
15
|
+
const u = e.usage;
|
|
16
|
+
t.input += u.input_tokens ?? 0;
|
|
17
|
+
t.output += u.output_tokens ?? 0;
|
|
18
|
+
t.cacheRead += u.cache_read_input_tokens ?? 0;
|
|
19
|
+
t.cacheWrite += u.cache_creation_input_tokens ?? 0;
|
|
20
|
+
t.thinking += u.output_tokens_details?.thinking_tokens ?? 0;
|
|
21
|
+
this.cost += e.total_cost_usd ?? 0; // rounded once, at the end
|
|
22
|
+
t.costUsd = Math.round(this.cost * 10_000) / 10_000;
|
|
23
|
+
t.turns += e.num_turns ?? 0;
|
|
24
|
+
for (const m of Object.keys(e.modelUsage ?? {}))
|
|
25
|
+
if (!t.models.includes(m))
|
|
26
|
+
t.models.push(m);
|
|
27
|
+
}
|
|
28
|
+
total() {
|
|
29
|
+
return this.t ?? undefined;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Tokens from a saved stream log (`<run>.stream.jsonl`), e.g. for runs recorded before this existed. */
|
|
33
|
+
export function tokensFromStream(path) {
|
|
34
|
+
if (!existsSync(path))
|
|
35
|
+
return undefined;
|
|
36
|
+
const tally = new TokenTally();
|
|
37
|
+
for (const line of readFileSync(path, 'utf8').split('\n')) {
|
|
38
|
+
if (!line.includes('"type":"result"'))
|
|
39
|
+
continue;
|
|
40
|
+
try {
|
|
41
|
+
tally.feed(JSON.parse(line));
|
|
42
|
+
}
|
|
43
|
+
catch { }
|
|
44
|
+
}
|
|
45
|
+
return tally.total();
|
|
46
|
+
}
|
|
47
|
+
export const totalTokens = (t) => t.input + t.output + t.cacheRead + t.cacheWrite;
|
|
48
|
+
/** 1234 → "1.2k", 670000 → "670k", 1_500_000 → "1.5M". */
|
|
49
|
+
export function compact(n) {
|
|
50
|
+
if (n < 1000)
|
|
51
|
+
return String(n);
|
|
52
|
+
if (n < 1_000_000)
|
|
53
|
+
return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0).replace(/\.0$/, '')}k`;
|
|
54
|
+
return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`;
|
|
55
|
+
}
|
|
56
|
+
/** "670k tokens (7.2k out · 609k cache read · 54k cache write · 26 in) · $0.70 at API prices · 14 turns" */
|
|
57
|
+
export function formatTokens(t) {
|
|
58
|
+
const parts = [`${compact(t.output)} out`, `${compact(t.cacheRead)} cache read`, `${compact(t.cacheWrite)} cache write`, `${compact(t.input)} in`];
|
|
59
|
+
return `${compact(totalTokens(t))} tokens (${parts.join(' · ')}) · $${t.costUsd.toFixed(2)} at API prices · ${t.turns} turn${t.turns === 1 ? '' : 's'}`;
|
|
60
|
+
}
|
|
61
|
+
/** The stream log next to a run's text log. */
|
|
62
|
+
export const streamPathFor = (logPath) => logPath.replace(/\.log$/, '.stream.jsonl');
|
|
63
|
+
/** Two runs' tokens added up (several calls in one nightly read). */
|
|
64
|
+
export function addTokens(a, b) {
|
|
65
|
+
return {
|
|
66
|
+
input: a.input + b.input,
|
|
67
|
+
output: a.output + b.output,
|
|
68
|
+
cacheRead: a.cacheRead + b.cacheRead,
|
|
69
|
+
cacheWrite: a.cacheWrite + b.cacheWrite,
|
|
70
|
+
thinking: a.thinking + b.thinking,
|
|
71
|
+
costUsd: Math.round((a.costUsd + b.costUsd) * 10000) / 10000,
|
|
72
|
+
turns: a.turns + b.turns,
|
|
73
|
+
models: [...new Set([...a.models, ...b.models])],
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Filling in exact tokens for runs recorded before tokens.ts existed: every away run since 2026-11-17 saved its
|
|
2
|
+
// whole stream (`<started>.stream.jsonl`), and the stream's result event has the exact counts.
|
|
3
|
+
import { existsSync, renameSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { cardDir, loadBoard, updateBoard } from './board.js';
|
|
6
|
+
import { readRuns, runsPath } from './costs.js';
|
|
7
|
+
import { homePath } from './home.js';
|
|
8
|
+
import { streamPathFor, tokensFromStream } from './tokens.js';
|
|
9
|
+
const stamp = (ms) => new Date(ms).toISOString().replace(/[:.]/g, '-');
|
|
10
|
+
/** Where a run's stream log is: next to its log, in the old runs/<id>/ folder, or in the card's own folder. */
|
|
11
|
+
function streamFor(r, workspace) {
|
|
12
|
+
const name = `${stamp(Date.parse(r.at) - r.durationMs)}.stream.jsonl`;
|
|
13
|
+
for (const dir of [homePath('runs', r.card), cardDir({ id: r.card, workspace })]) {
|
|
14
|
+
const p = join(dir, name);
|
|
15
|
+
if (existsSync(p))
|
|
16
|
+
return p;
|
|
17
|
+
}
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
/** Fill in `tokens` on board runs and runs.jsonl records that lack it. Returns how many runs.jsonl records got them. */
|
|
21
|
+
export function backfillTokens() {
|
|
22
|
+
const board = loadBoard();
|
|
23
|
+
const ws = new Map(board.cards.map((c) => [c.id, c.workspace]));
|
|
24
|
+
if (board.cards.some((c) => c.run && !c.run.tokens && c.logPath)) {
|
|
25
|
+
updateBoard((b) => {
|
|
26
|
+
for (const c of b.cards) {
|
|
27
|
+
if (!c.run || c.run.tokens || !c.logPath)
|
|
28
|
+
continue;
|
|
29
|
+
const t = tokensFromStream(streamPathFor(c.logPath));
|
|
30
|
+
if (t)
|
|
31
|
+
c.run.tokens = t;
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
const runs = readRuns();
|
|
36
|
+
let filled = 0;
|
|
37
|
+
for (const r of runs) {
|
|
38
|
+
if (r.tokens)
|
|
39
|
+
continue;
|
|
40
|
+
const p = streamFor(r, ws.get(r.card));
|
|
41
|
+
const t = p ? tokensFromStream(p) : undefined;
|
|
42
|
+
if (t) {
|
|
43
|
+
r.tokens = t;
|
|
44
|
+
filled++;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (filled) {
|
|
48
|
+
const path = runsPath();
|
|
49
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
50
|
+
writeFileSync(tmp, runs.map((r) => JSON.stringify(r)).join('\n') + '\n');
|
|
51
|
+
renameSync(tmp, path);
|
|
52
|
+
}
|
|
53
|
+
return filled;
|
|
54
|
+
}
|
|
55
|
+
export function median(xs) {
|
|
56
|
+
if (!xs.length)
|
|
57
|
+
return 0;
|
|
58
|
+
const s = [...xs].sort((a, b) => a - b);
|
|
59
|
+
const m = Math.floor(s.length / 2);
|
|
60
|
+
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
|
61
|
+
}
|