chompyy 0.1.0 → 0.3.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 +79 -6
- package/THIRD_PARTY_NOTICES.md +28 -0
- package/dist/appstate.js +43 -2
- package/dist/away.js +104 -15
- package/dist/board.js +33 -3
- package/dist/claudesettings.js +23 -0
- package/dist/cli.js +409 -27
- package/dist/coldstart.js +207 -0
- package/dist/config.js +36 -1
- package/dist/costs.js +162 -0
- package/dist/gate.js +29 -0
- package/dist/history.js +308 -0
- package/dist/livequota.js +15 -1
- package/dist/pacing.js +189 -0
- package/dist/picture.js +117 -0
- package/dist/projects.js +2 -2
- package/dist/quota.js +31 -5
- package/dist/report.js +38 -21
- package/dist/review.js +47 -4
- package/dist/runner.js +268 -8
- package/dist/taste.js +507 -0
- package/dist/triggers.js +182 -0
- package/dist/verify.js +131 -0
- package/package.json +2 -1
- 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/history.js
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
// Reads your Claude Code history for the cold start (spec §5.9). Runs locally and changes nothing.
|
|
2
|
+
// From each interactive session it keeps only: the folder, the dates, what you typed (cleaned, secrets
|
|
3
|
+
// removed) and the last thing Claude said. Headless runs (Chompyy's own, benchmarks, scripts) are skipped.
|
|
4
|
+
import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { basename, join } from 'node:path';
|
|
7
|
+
import { findGitRoot, isTemp } from './projects.js';
|
|
8
|
+
// ---------- redaction ----------
|
|
9
|
+
const SECRET_PATTERNS = [
|
|
10
|
+
[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g, '[secret]'],
|
|
11
|
+
[/\bsk-(ant-)?[A-Za-z0-9_-]{16,}/g, '[secret]'],
|
|
12
|
+
[/\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g, '[secret]'],
|
|
13
|
+
[/\bgithub_pat_[A-Za-z0-9_]{20,}/g, '[secret]'],
|
|
14
|
+
[/\bnpm_[A-Za-z0-9]{30,}/g, '[secret]'],
|
|
15
|
+
[/\bAKIA[0-9A-Z]{16}\b/g, '[secret]'],
|
|
16
|
+
[/\bAIza[0-9A-Za-z_-]{35}\b/g, '[secret]'],
|
|
17
|
+
[/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, '[secret]'],
|
|
18
|
+
[/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, '[secret]'], // JWT
|
|
19
|
+
[/\b(sk|rk|pk)_(live|test)_[A-Za-z0-9]{16,}/g, '[secret]'], // Stripe
|
|
20
|
+
[/\bglpat-[A-Za-z0-9_-]{20,}/g, '[secret]'], // GitLab
|
|
21
|
+
[/\bhf_[A-Za-z0-9]{30,}/g, '[secret]'], // Hugging Face
|
|
22
|
+
[/\bya29\.[A-Za-z0-9_-]{20,}/g, '[secret]'], // Google OAuth access token
|
|
23
|
+
[/\b(AccountKey|SharedAccessSignature|sig)=[A-Za-z0-9%+/=]{20,}/g, '[secret]'], // Azure
|
|
24
|
+
[/https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9/]+/g, '[secret]'],
|
|
25
|
+
[/https:\/\/(discord(app)?\.com)\/api\/webhooks\/[A-Za-z0-9/_-]+/g, '[secret]'],
|
|
26
|
+
// user:password@ in a URL: keep the scheme and host so the sentence still reads
|
|
27
|
+
[/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/:@]+:[^\s/@]+@/gi, (_m, scheme) => `${scheme}[secret]@`],
|
|
28
|
+
[/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{16,}/g, (_m, kind) => `${kind} [secret]`],
|
|
29
|
+
// keep "password=" so the sentence still reads
|
|
30
|
+
[/\b(password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key)(\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, (_m, name, sep) => `${name}${sep}[secret]`],
|
|
31
|
+
// long random-looking strings (mixed case and digits), not paths or slugs
|
|
32
|
+
[/[A-Za-z0-9+_=-]{32,}/g, (m) => (/[a-z]/.test(m) && /[A-Z]/.test(m) && /\d/.test(m) && (m.match(/-/g)?.length ?? 0) < 3 ? '[secret]' : m)],
|
|
33
|
+
[/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, '[email]'],
|
|
34
|
+
// phone numbers: +44 20 7946 0958, (415) 555-0132, 415-555-0132
|
|
35
|
+
[/(\+\d{1,3}[\s.-]?)?(\(\d{2,4}\)[\s.-]?|\b\d{2,4}[\s.-])\d{3,4}[\s.-]\d{3,4}\b/g, '[phone]'],
|
|
36
|
+
];
|
|
37
|
+
// ---------- pastes without markers ----------
|
|
38
|
+
/** How much a line looks machine-made (log, stack trace, code, diff, JSON) rather than typed by a person. */
|
|
39
|
+
function machineLine(line) {
|
|
40
|
+
const t = line.trim();
|
|
41
|
+
if (!t)
|
|
42
|
+
return false;
|
|
43
|
+
return (/^\s*at\s+\S.*(\(|:\d+)/.test(line) || // JS/Java stack frame
|
|
44
|
+
/^\s*File ".*", line \d+/.test(line) || /^Traceback \(most recent call last\)/.test(t) ||
|
|
45
|
+
/^\d{4}-\d\d-\d\d[T ]\d\d:\d\d/.test(t) || /^\[?\d\d:\d\d:\d\d/.test(t) || // timestamped log
|
|
46
|
+
/^\[?(INFO|WARN|WARNING|ERROR|DEBUG|TRACE|FATAL)\b/.test(t) ||
|
|
47
|
+
/^(\+\+\+|---|@@|diff --git|index [0-9a-f]+)/.test(t) || /^[+-](?![+-])\S/.test(t) || // diff
|
|
48
|
+
/^[{}\[\]],?$/.test(t) || /^"[^"]+":\s/.test(t) || // JSON
|
|
49
|
+
/[;{}]$/.test(t) || /^(import|export|from|def|class|function|const|let|var|return|if|for|while|#include|package|func|fn|pub|use)\b.*[({:=;]/.test(t) ||
|
|
50
|
+
/^(\$|>>>|PS [A-Z]:\\|❯)\s/.test(t) || // shell or REPL prompt
|
|
51
|
+
/^\s{4,}\S/.test(line) || /^\t+\S/.test(line) || // indented block
|
|
52
|
+
/^[\w.-]+:\d+(:\d+)?\b/.test(t) // file:line
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Replace pasted material that came in without Claude Code's paste markers: fenced code blocks, runs of 3+
|
|
57
|
+
* machine-made lines (logs, stack traces, code, diffs, JSON), and very long unbroken lines. Must run before
|
|
58
|
+
* whitespace is collapsed, because line breaks are what give a paste away.
|
|
59
|
+
*/
|
|
60
|
+
export function stripUnmarkedPastes(text) {
|
|
61
|
+
let out = text.replace(/```[\s\S]*?(```|$)/g, '\n[pasted text]\n');
|
|
62
|
+
const lines = out.split('\n');
|
|
63
|
+
const kept = [];
|
|
64
|
+
for (let i = 0; i < lines.length;) {
|
|
65
|
+
// Grow a block while most of its lines look machine-made (a blank or odd line inside is allowed).
|
|
66
|
+
let j = i;
|
|
67
|
+
let machine = 0;
|
|
68
|
+
while (j < lines.length) {
|
|
69
|
+
const isMachine = machineLine(lines[j]);
|
|
70
|
+
const blank = !lines[j].trim();
|
|
71
|
+
if (!isMachine && !blank && (j - i < 1 || machine / (j - i + 1) < 0.6))
|
|
72
|
+
break;
|
|
73
|
+
if (isMachine)
|
|
74
|
+
machine++;
|
|
75
|
+
j++;
|
|
76
|
+
}
|
|
77
|
+
// Don't end a block on a typed line: give trailing non-machine lines back.
|
|
78
|
+
while (j > i && !machineLine(lines[j - 1]))
|
|
79
|
+
j--;
|
|
80
|
+
if (machine >= 3) {
|
|
81
|
+
if (kept.at(-1) !== '[pasted text]')
|
|
82
|
+
kept.push('[pasted text]');
|
|
83
|
+
i = j;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const line = lines[i];
|
|
87
|
+
// One long line with few spaces: minified code, base64, a URL dump, a log line.
|
|
88
|
+
const spaces = (line.match(/\s/g) ?? []).length;
|
|
89
|
+
kept.push(line.length > 400 && spaces / line.length < 0.08 ? '[pasted text]' : line);
|
|
90
|
+
i++;
|
|
91
|
+
}
|
|
92
|
+
return kept.join('\n');
|
|
93
|
+
}
|
|
94
|
+
/** Remove things that look like secrets or personal contact details. */
|
|
95
|
+
export function redact(text) {
|
|
96
|
+
let out = text;
|
|
97
|
+
for (const [re, to] of SECRET_PATTERNS)
|
|
98
|
+
out = typeof to === 'string' ? out.replace(re, to) : out.replace(re, to);
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
// ---------- reading one transcript ----------
|
|
102
|
+
/** Turn a user message into what you actually typed, or null if it isn't something you typed. */
|
|
103
|
+
export function cleanPrompt(content) {
|
|
104
|
+
let text;
|
|
105
|
+
if (typeof content === 'string')
|
|
106
|
+
text = content;
|
|
107
|
+
else if (Array.isArray(content)) {
|
|
108
|
+
// Arrays hold tool results or text blocks; only plain text blocks are typed words.
|
|
109
|
+
if (content.some((b) => b && typeof b === 'object' && b.type === 'tool_result'))
|
|
110
|
+
return null;
|
|
111
|
+
text = content
|
|
112
|
+
.filter((b) => b && typeof b === 'object' && b.type === 'text')
|
|
113
|
+
.map((b) => b.text ?? '')
|
|
114
|
+
.join('\n');
|
|
115
|
+
}
|
|
116
|
+
else
|
|
117
|
+
return null;
|
|
118
|
+
// A slash command arrives as tags: keep it as "/name args".
|
|
119
|
+
const cmd = text.match(/<command-name>([^<]*)<\/command-name>/);
|
|
120
|
+
if (cmd) {
|
|
121
|
+
const args = text.match(/<command-args>([\s\S]*?)<\/command-args>/)?.[1]?.trim() ?? '';
|
|
122
|
+
const name = cmd[1].trim();
|
|
123
|
+
return name ? `${name.startsWith('/') ? name : `/${name}`}${args ? ` ${args}` : ''}` : null;
|
|
124
|
+
}
|
|
125
|
+
if (/^\s*<(local-command|bash-|system-reminder|task-notification|user-prompt-submit-hook)/.test(text))
|
|
126
|
+
return null;
|
|
127
|
+
if (/^\s*(Caveat:|\[Request interrupted|This session is being continued from a previous conversation)/.test(text))
|
|
128
|
+
return null;
|
|
129
|
+
text = text
|
|
130
|
+
.replace(/<pasted_content[^>]*>[\s\S]*?<\/pasted_content[^>]*>/g, '[pasted text]')
|
|
131
|
+
.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '');
|
|
132
|
+
text = stripUnmarkedPastes(text)
|
|
133
|
+
.replace(/\[Image[^\]]*\]/g, '[image]')
|
|
134
|
+
.replace(/\s+/g, ' ')
|
|
135
|
+
.trim();
|
|
136
|
+
return text ? text : null;
|
|
137
|
+
}
|
|
138
|
+
function textOf(content) {
|
|
139
|
+
if (typeof content === 'string')
|
|
140
|
+
return content;
|
|
141
|
+
if (!Array.isArray(content))
|
|
142
|
+
return '';
|
|
143
|
+
return content
|
|
144
|
+
.filter((b) => b && typeof b === 'object' && b.type === 'text')
|
|
145
|
+
.map((b) => b.text ?? '')
|
|
146
|
+
.join('\n');
|
|
147
|
+
}
|
|
148
|
+
export function parseTranscript(raw) {
|
|
149
|
+
const p = { entrypoint: null, cwd: null, started: null, ended: null, prompts: [], lastReply: null };
|
|
150
|
+
for (const line of raw.split('\n')) {
|
|
151
|
+
if (!line.trim())
|
|
152
|
+
continue;
|
|
153
|
+
let o;
|
|
154
|
+
try {
|
|
155
|
+
o = JSON.parse(line);
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (!p.entrypoint && typeof o.entrypoint === 'string')
|
|
161
|
+
p.entrypoint = o.entrypoint;
|
|
162
|
+
if (!p.cwd && typeof o.cwd === 'string')
|
|
163
|
+
p.cwd = o.cwd;
|
|
164
|
+
if (typeof o.timestamp === 'string') {
|
|
165
|
+
p.started ??= o.timestamp;
|
|
166
|
+
p.ended = o.timestamp;
|
|
167
|
+
}
|
|
168
|
+
if (o.isSidechain || o.isMeta || o.isCompactSummary)
|
|
169
|
+
continue;
|
|
170
|
+
const message = o.message;
|
|
171
|
+
if (o.type === 'user') {
|
|
172
|
+
const typed = cleanPrompt(message?.content);
|
|
173
|
+
if (typed)
|
|
174
|
+
p.prompts.push(typed);
|
|
175
|
+
}
|
|
176
|
+
else if (o.type === 'assistant') {
|
|
177
|
+
const t = textOf(message?.content).trim();
|
|
178
|
+
if (t)
|
|
179
|
+
p.lastReply = t;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return p;
|
|
183
|
+
}
|
|
184
|
+
// ---------- scanning all of it ----------
|
|
185
|
+
/** Read every interactive Claude Code session on this Mac, newest first. */
|
|
186
|
+
export function scanHistory(opts = {}) {
|
|
187
|
+
const temp = opts.isTemp ?? isTemp;
|
|
188
|
+
const claudeDir = opts.claudeDir ?? join(homedir(), '.claude', 'projects');
|
|
189
|
+
const scan = { sessions: [], skipped: { headless: 0, temp: 0, empty: 0, unreadable: 0 }, from: null, to: null };
|
|
190
|
+
if (!existsSync(claudeDir))
|
|
191
|
+
return scan;
|
|
192
|
+
const files = [];
|
|
193
|
+
for (const dir of readdirSync(claudeDir, { withFileTypes: true })) {
|
|
194
|
+
if (!dir.isDirectory())
|
|
195
|
+
continue;
|
|
196
|
+
const folder = join(claudeDir, dir.name);
|
|
197
|
+
for (const f of readdirSync(folder)) {
|
|
198
|
+
if (!f.endsWith('.jsonl'))
|
|
199
|
+
continue;
|
|
200
|
+
try {
|
|
201
|
+
files.push({ file: join(folder, f), mtime: statSync(join(folder, f)).mtimeMs });
|
|
202
|
+
}
|
|
203
|
+
catch { }
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
files.sort((a, b) => b.mtime - a.mtime);
|
|
207
|
+
const found = [];
|
|
208
|
+
for (const { file } of files) {
|
|
209
|
+
if (opts.maxSessions && found.length >= opts.maxSessions)
|
|
210
|
+
break;
|
|
211
|
+
let parsed;
|
|
212
|
+
try {
|
|
213
|
+
parsed = parseTranscript(readFileSync(file, 'utf8'));
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
scan.skipped.unreadable++;
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
// Headless runs (`claude -p`, SDK) are agents talking, not you.
|
|
220
|
+
if (parsed.entrypoint === 'sdk-cli' || parsed.entrypoint === 'sdk-ts' || parsed.entrypoint === 'sdk-py') {
|
|
221
|
+
scan.skipped.headless++;
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (!parsed.cwd || temp(parsed.cwd) || parsed.cwd.includes('/.branchwork/')) {
|
|
225
|
+
scan.skipped.temp++;
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (parsed.prompts.length === 0) {
|
|
229
|
+
scan.skipped.empty++;
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
let project = parsed.cwd;
|
|
233
|
+
const root = existsSync(parsed.cwd) ? findGitRoot(parsed.cwd) : null;
|
|
234
|
+
if (root && root !== homedir()) {
|
|
235
|
+
try {
|
|
236
|
+
project = realpathSync.native(root);
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
project = root;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
found.push({
|
|
243
|
+
file,
|
|
244
|
+
cwd: parsed.cwd,
|
|
245
|
+
project,
|
|
246
|
+
projectName: basename(project),
|
|
247
|
+
started: parsed.started ?? '',
|
|
248
|
+
ended: parsed.ended ?? '',
|
|
249
|
+
prompts: parsed.prompts.map(redact),
|
|
250
|
+
lastReply: parsed.lastReply ? redact(parsed.lastReply) : null,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
found.sort((a, b) => b.ended.localeCompare(a.ended));
|
|
254
|
+
scan.sessions = found.map((s, i) => ({ id: `S${i + 1}`, ...s }));
|
|
255
|
+
const times = found.flatMap((s) => [s.started, s.ended]).filter(Boolean).sort();
|
|
256
|
+
scan.from = times[0] ?? null;
|
|
257
|
+
scan.to = times[times.length - 1] ?? null;
|
|
258
|
+
return scan;
|
|
259
|
+
}
|
|
260
|
+
// ---------- the digest sent to the model ----------
|
|
261
|
+
/** Words that mark an idea for later, in English and Chinese. */
|
|
262
|
+
const LATER = /\b(later|todo|to-do|next time|someday|some day|remind me|come back|eventually|follow[- ]up|not now|backlog|park|wishlist|nice to have)\b|之後|以後|下次|有空|待辦|晚點|再來|改天/i;
|
|
263
|
+
/** Words that mark a correction: the clearest taste evidence. */
|
|
264
|
+
const CORRECTION = /^(no\b|nope|don'?t|do not|stop|instead|actually|wrong|that'?s not|not what|please don'?t|never)|不要|不是|別|改成|太長|太多/i;
|
|
265
|
+
const clip = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
|
|
266
|
+
/** Which prompts of a session go in the digest: the start, ideas for later, corrections, and the end. */
|
|
267
|
+
export function pickPrompts(prompts, max = 14) {
|
|
268
|
+
const keep = new Set();
|
|
269
|
+
const add = (i) => {
|
|
270
|
+
if (i >= 0 && i < prompts.length && keep.size < max)
|
|
271
|
+
keep.add(i);
|
|
272
|
+
};
|
|
273
|
+
[0, 1, 2].forEach(add);
|
|
274
|
+
prompts.forEach((p, i) => LATER.test(p) && add(i));
|
|
275
|
+
prompts.forEach((p, i) => CORRECTION.test(p) && add(i));
|
|
276
|
+
[prompts.length - 3, prompts.length - 2, prompts.length - 1].forEach(add);
|
|
277
|
+
return [...keep].sort((a, b) => a - b).map((i) => prompts[i]);
|
|
278
|
+
}
|
|
279
|
+
/** The digest: one block per session, newest first, until the size cap. */
|
|
280
|
+
export function buildDigest(sessions, maxChars = 60_000) {
|
|
281
|
+
const blocks = [];
|
|
282
|
+
const included = [];
|
|
283
|
+
let size = 0;
|
|
284
|
+
for (const s of sessions) {
|
|
285
|
+
const lines = [
|
|
286
|
+
`### ${s.id} · ${s.projectName} (${s.project}) · ${s.ended.slice(0, 10)} · ${s.prompts.length} prompts`,
|
|
287
|
+
...pickPrompts(s.prompts).map((p) => `> ${clip(p, 300)}`),
|
|
288
|
+
...(s.lastReply ? [`Claude ended with: ${clip(s.lastReply.replace(/\s+/g, ' '), 450)}`] : []),
|
|
289
|
+
];
|
|
290
|
+
const block = lines.join('\n');
|
|
291
|
+
if (size + block.length > maxChars && included.length > 0)
|
|
292
|
+
break;
|
|
293
|
+
blocks.push(block);
|
|
294
|
+
included.push(s);
|
|
295
|
+
size += block.length + 2;
|
|
296
|
+
}
|
|
297
|
+
return { text: blocks.join('\n\n'), included };
|
|
298
|
+
}
|
|
299
|
+
/** How long Claude Code keeps transcripts (`cleanupPeriodDays`, default 30). */
|
|
300
|
+
export function historyRetention(settingsPath = join(homedir(), '.claude', 'settings.json')) {
|
|
301
|
+
try {
|
|
302
|
+
const s = JSON.parse(readFileSync(settingsPath, 'utf8'));
|
|
303
|
+
if (typeof s.cleanupPeriodDays === 'number')
|
|
304
|
+
return { days: s.cleanupPeriodDays, isDefault: false };
|
|
305
|
+
}
|
|
306
|
+
catch { }
|
|
307
|
+
return { days: 30, isDefault: true };
|
|
308
|
+
}
|
package/dist/livequota.js
CHANGED
|
@@ -26,6 +26,16 @@ export function snapshotFromProvider(provider, now) {
|
|
|
26
26
|
snap.fiveHour = five;
|
|
27
27
|
if (week)
|
|
28
28
|
snap.sevenDay = week;
|
|
29
|
+
// Per-model weekly windows ("Weekly · Opus", "Weekly · Sonnet", …).
|
|
30
|
+
const models = {};
|
|
31
|
+
for (const row of provider.details) {
|
|
32
|
+
const name = row.label.startsWith('Weekly · ') ? row.label.slice('Weekly · '.length) : '';
|
|
33
|
+
const w = name ? windowFrom(provider, row.label) : undefined;
|
|
34
|
+
if (w)
|
|
35
|
+
models[name] = w;
|
|
36
|
+
}
|
|
37
|
+
if (Object.keys(models).length)
|
|
38
|
+
snap.models = models;
|
|
29
39
|
return snap;
|
|
30
40
|
}
|
|
31
41
|
/**
|
|
@@ -37,7 +47,7 @@ export async function refreshLiveQuota(opts = {}) {
|
|
|
37
47
|
const state = loadLiveState();
|
|
38
48
|
const current = loadSnapshot();
|
|
39
49
|
if (state.retryAfterAt && Date.parse(state.retryAfterAt) > now.getTime()) {
|
|
40
|
-
return { ok: false, snapshot: current, message: `Anthropic
|
|
50
|
+
return { ok: false, snapshot: current, message: `Anthropic limits how often quota can be checked; next check after ${hhmm(state.retryAfterAt)}.` };
|
|
41
51
|
}
|
|
42
52
|
if (!opts.force && state.lastTryAt && now.getTime() - Date.parse(state.lastTryAt) < MIN_INTERVAL_MS && current?.source === 'api') {
|
|
43
53
|
return { ok: true, snapshot: current, message: 'Fresh enough.' };
|
|
@@ -55,6 +65,9 @@ export async function refreshLiveQuota(opts = {}) {
|
|
|
55
65
|
if (!snap) {
|
|
56
66
|
next.note = result.quota.footerLines.join(' ') || result.quota.connection;
|
|
57
67
|
writeJson(statePath(), next);
|
|
68
|
+
// A 429: other tools signed in with the same Claude login (or a recent check) used up the allowance.
|
|
69
|
+
if (next.retryAfterAt)
|
|
70
|
+
return { ok: false, snapshot: current, message: `Anthropic limits how often quota can be checked; next check after ${hhmm(next.retryAfterAt)}.` };
|
|
58
71
|
return { ok: false, snapshot: current, message: explain(result.quota) };
|
|
59
72
|
}
|
|
60
73
|
const merged = mergeSnapshot(current, snap);
|
|
@@ -62,6 +75,7 @@ export async function refreshLiveQuota(opts = {}) {
|
|
|
62
75
|
writeJson(statePath(), next);
|
|
63
76
|
return { ok: true, snapshot: merged, message: `Updated from Anthropic${result.quota.planLabel ? ` (${result.quota.planLabel})` : ''}.` };
|
|
64
77
|
}
|
|
78
|
+
const hhmm = (iso) => new Date(iso).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
|
|
65
79
|
function explain(p) {
|
|
66
80
|
const extra = p.footerLines.length ? ` ${p.footerLines.join(' ')}` : '';
|
|
67
81
|
switch (p.connection) {
|
package/dist/pacing.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// Pacing (FEATURES §2): how you're spending your windows, at a glance.
|
|
2
|
+
//
|
|
3
|
+
// - Signed pace delta (claude-pace): used % minus the % of the window that has passed. ⇣15% = headroom,
|
|
4
|
+
// ⇡15% = burning faster than an even pace.
|
|
5
|
+
// - Forecast unused at reset (Claude-Code-Usage-Monitor forecasts run-out; we flip it): "~40% resets unused at
|
|
6
|
+
// 18:20" is the moment to offer cards. Frozen once a limit is hit: no projections past 100%.
|
|
7
|
+
// - Rolling daily allowance: today = what's left of the week ÷ days left, where your day ends at bedtime.
|
|
8
|
+
//
|
|
9
|
+
// The burn rate comes from a small history of quota readings (quota-history.json), saved whenever the snapshot
|
|
10
|
+
// changes, so no extra calls are made.
|
|
11
|
+
import { homePath, readJson, writeJson } from './home.js';
|
|
12
|
+
import { windowView } from './quota.js';
|
|
13
|
+
export const FIVE_HOURS = 5 * 3600_000;
|
|
14
|
+
export const WEEK = 7 * 24 * 3600_000;
|
|
15
|
+
const DAY = 24 * 3600_000;
|
|
16
|
+
const historyPath = () => homePath('quota-history.json');
|
|
17
|
+
/** Keep 8 days: enough for a weekly window and the day before it. */
|
|
18
|
+
const KEEP_MS = 8 * DAY;
|
|
19
|
+
/** Save a reading at most this often unless the numbers changed. */
|
|
20
|
+
const MIN_GAP_MS = 5 * 60_000;
|
|
21
|
+
export function loadSamples() {
|
|
22
|
+
return readJson(historyPath(), { samples: [] }).samples;
|
|
23
|
+
}
|
|
24
|
+
const same = (a, b) => a?.usedPct === b?.usedPct && a?.resetsAt === b?.resetsAt;
|
|
25
|
+
/** Add a reading when it says something new. Returns true when saved. */
|
|
26
|
+
export function recordSample(snap, nowMs = Date.parse(snap.capturedAt)) {
|
|
27
|
+
if (!snap.fiveHour && !snap.sevenDay)
|
|
28
|
+
return false;
|
|
29
|
+
const samples = loadSamples();
|
|
30
|
+
const last = samples.at(-1);
|
|
31
|
+
if (last && same(last.five, snap.fiveHour) && same(last.week, snap.sevenDay) && nowMs - last.at < MIN_GAP_MS)
|
|
32
|
+
return false;
|
|
33
|
+
if (last && nowMs < last.at)
|
|
34
|
+
return false; // out of order
|
|
35
|
+
samples.push({ at: nowMs, ...(snap.fiveHour ? { five: snap.fiveHour } : {}), ...(snap.sevenDay ? { week: snap.sevenDay } : {}) });
|
|
36
|
+
writeJson(historyPath(), { samples: samples.filter((s) => s.at > nowMs - KEEP_MS) });
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
// ---------- pace delta ----------
|
|
40
|
+
/** Used % minus elapsed % of the window. Negative = headroom. Null when the window is unknown or reset. */
|
|
41
|
+
export function paceDelta(w, lengthMs, now) {
|
|
42
|
+
const v = windowView(w, now);
|
|
43
|
+
if (!v.known)
|
|
44
|
+
return null;
|
|
45
|
+
const elapsedPct = Math.min(100, Math.max(0, (1 - v.msLeft / lengthMs) * 100));
|
|
46
|
+
return v.usedPct - elapsedPct;
|
|
47
|
+
}
|
|
48
|
+
const GREEN = '\u001b[32m';
|
|
49
|
+
const RED = '\u001b[31m';
|
|
50
|
+
const RESET = '\u001b[0m';
|
|
51
|
+
/** "⇣15%" (headroom, green) or "⇡15%" (burning fast, red); "±0%" when within a point. */
|
|
52
|
+
export function formatDelta(delta, color = false) {
|
|
53
|
+
if (delta === null)
|
|
54
|
+
return '';
|
|
55
|
+
const n = Math.round(Math.abs(delta));
|
|
56
|
+
if (n < 1)
|
|
57
|
+
return '±0%';
|
|
58
|
+
const text = delta < 0 ? `⇣${n}%` : `⇡${n}%`;
|
|
59
|
+
return color ? `${delta < 0 ? GREEN : RED}${text}${RESET}` : text;
|
|
60
|
+
}
|
|
61
|
+
const RECENT_MS = 60 * 60_000;
|
|
62
|
+
const MIN_SPAN_MS = 10 * 60_000;
|
|
63
|
+
/** % per ms over the last hour of readings in this same window, or null if there aren't enough. */
|
|
64
|
+
export function recentRate(samples, pick, resetsAt, nowMs) {
|
|
65
|
+
const pts = samples.filter((s) => pick(s)?.resetsAt === resetsAt && s.at >= nowMs - RECENT_MS && s.at <= nowMs);
|
|
66
|
+
if (pts.length < 2)
|
|
67
|
+
return null;
|
|
68
|
+
const first = pts[0];
|
|
69
|
+
const last = pts.at(-1);
|
|
70
|
+
if (last.at - first.at < MIN_SPAN_MS)
|
|
71
|
+
return null;
|
|
72
|
+
return Math.max(0, (pick(last).usedPct - pick(first).usedPct) / (last.at - first.at));
|
|
73
|
+
}
|
|
74
|
+
export function forecastWindow(w, lengthMs, samples, pick, now) {
|
|
75
|
+
const v = windowView(w, now);
|
|
76
|
+
if (!v.known)
|
|
77
|
+
return { kind: 'unknown' };
|
|
78
|
+
if (v.usedPct >= 100)
|
|
79
|
+
return { kind: 'limit', resetsAt: v.resetsAt };
|
|
80
|
+
const nowMs = now.getTime();
|
|
81
|
+
let rate = recentRate(samples, pick, v.resetsAt, nowMs);
|
|
82
|
+
let basis = 'recent';
|
|
83
|
+
if (rate === null) {
|
|
84
|
+
const elapsed = lengthMs - v.msLeft;
|
|
85
|
+
if (elapsed < 15 * 60_000)
|
|
86
|
+
return { kind: 'unknown' };
|
|
87
|
+
rate = v.usedPct / elapsed;
|
|
88
|
+
basis = 'average';
|
|
89
|
+
}
|
|
90
|
+
const projected = v.usedPct + rate * v.msLeft;
|
|
91
|
+
if (projected >= 100 && rate > 0)
|
|
92
|
+
return { kind: 'limit-ahead', atMs: nowMs + (100 - v.usedPct) / rate, resetsAt: v.resetsAt };
|
|
93
|
+
return { kind: 'unused', unusedPct: Math.max(0, 100 - projected), resetsAt: v.resetsAt, basis };
|
|
94
|
+
}
|
|
95
|
+
const clock = (ms) => new Date(ms).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
|
|
96
|
+
/** Short, for the status line: "~40% unused at 18:20" · "limit ~17:05" · "limit hit, resets 18:20". */
|
|
97
|
+
export function formatForecastShort(f) {
|
|
98
|
+
switch (f.kind) {
|
|
99
|
+
case 'unused':
|
|
100
|
+
return `~${Math.round(f.unusedPct)}% unused at ${clock(f.resetsAt * 1000)}`;
|
|
101
|
+
case 'limit-ahead':
|
|
102
|
+
return `limit ~${clock(f.atMs)}`;
|
|
103
|
+
case 'limit':
|
|
104
|
+
return `limit hit, resets ${clock(f.resetsAt * 1000)}`;
|
|
105
|
+
default:
|
|
106
|
+
return '';
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export function formatForecast(f) {
|
|
110
|
+
switch (f.kind) {
|
|
111
|
+
case 'unused':
|
|
112
|
+
return `at ${f.basis === 'recent' ? 'your pace over the last hour' : 'your average pace this window'}, ~${Math.round(f.unusedPct)}% of this window resets unused at ${clock(f.resetsAt * 1000)}${f.unusedPct >= 20 ? ' (room for an away card: chompyy eat-tokens)' : ''}`;
|
|
113
|
+
case 'limit-ahead':
|
|
114
|
+
return `at this pace you hit the limit at ~${clock(f.atMs)}, before the reset at ${clock(f.resetsAt * 1000)}`;
|
|
115
|
+
case 'limit':
|
|
116
|
+
return `limit hit; no forecast until it resets at ${clock(f.resetsAt * 1000)}`;
|
|
117
|
+
default:
|
|
118
|
+
return 'not enough readings yet to forecast';
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
// ---------- rolling daily allowance ----------
|
|
122
|
+
/** The day you're in: from your last bedtime (or midnight) to the next. */
|
|
123
|
+
export function dayBounds(now, bedtime) {
|
|
124
|
+
const [h, m] = bedtime ? bedtime.split(':').map(Number) : [0, 0];
|
|
125
|
+
const start = new Date(now);
|
|
126
|
+
start.setHours(h, m, 0, 0);
|
|
127
|
+
if (start.getTime() > now.getTime())
|
|
128
|
+
start.setDate(start.getDate() - 1);
|
|
129
|
+
const end = new Date(start);
|
|
130
|
+
end.setDate(end.getDate() + 1); // calendar day, so DST shifts don't move bedtime
|
|
131
|
+
return { start: start.getTime(), end: end.getTime() };
|
|
132
|
+
}
|
|
133
|
+
export function dailyAllowance(w, samples, now, bedtime) {
|
|
134
|
+
const v = windowView(w, now);
|
|
135
|
+
if (!v.known)
|
|
136
|
+
return null;
|
|
137
|
+
const { start, end } = dayBounds(now, bedtime);
|
|
138
|
+
const weekEnd = v.resetsAt * 1000;
|
|
139
|
+
// The weekly window may have started today: then today starts there.
|
|
140
|
+
const dayStart = Math.max(start, weekEnd - WEEK);
|
|
141
|
+
const inWindow = samples.filter((s) => s.week?.resetsAt === v.resetsAt);
|
|
142
|
+
const before = inWindow.filter((s) => s.at <= dayStart).at(-1);
|
|
143
|
+
const after = inWindow.find((s) => s.at > dayStart);
|
|
144
|
+
const approx = !before && !(dayStart > start); // a window that began today started at 0
|
|
145
|
+
const usedAtStart = dayStart > start ? 0 : (before ?? after)?.week?.usedPct ?? v.usedPct;
|
|
146
|
+
const daysLeft = Math.max(1, Math.ceil((weekEnd - dayStart) / DAY - 0.01));
|
|
147
|
+
const allowance = Math.max(0, 100 - usedAtStart) / daysLeft;
|
|
148
|
+
const usedToday = Math.max(0, v.usedPct - usedAtStart);
|
|
149
|
+
const dayEnds = Math.min(end, weekEnd);
|
|
150
|
+
const frac = Math.min(1, Math.max(0, (now.getTime() - dayStart) / Math.max(1, dayEnds - dayStart)));
|
|
151
|
+
const expectedByNow = allowance * frac;
|
|
152
|
+
const slack = Math.max(1, allowance * 0.1);
|
|
153
|
+
const status = usedToday > allowance ? 'over' : usedToday > expectedByNow + slack ? 'ahead' : usedToday < expectedByNow - slack ? 'behind' : 'on pace';
|
|
154
|
+
const since = approx ? (after?.at ?? now.getTime()) : dayStart;
|
|
155
|
+
const tooEarly = approx && now.getTime() - since < 2 * 3600_000;
|
|
156
|
+
return { allowance, usedToday, expectedByNow, status, daysLeft, dayEnds, approx, since, tooEarly };
|
|
157
|
+
}
|
|
158
|
+
const r1 = (n) => (n < 10 ? (Math.round(n * 10) / 10).toString() : Math.round(n).toString());
|
|
159
|
+
/** "today 4% of 12% ▓▓▓░░░░░░░ behind: 3% unspent so far, it funds the night · day ends 23:30". */
|
|
160
|
+
export function formatAllowance(a) {
|
|
161
|
+
if (!a)
|
|
162
|
+
return 'today unknown (weekly window not known)';
|
|
163
|
+
if (a.tooEarly)
|
|
164
|
+
return `today ${r1(a.allowance)}% a day for the ${a.daysLeft} day${a.daysLeft === 1 ? '' : 's'} left · tracking today since ${clock(a.since)}, so no verdict yet · day ends ${clock(a.dayEnds)}`;
|
|
165
|
+
const filled = Math.min(10, Math.round((a.usedToday / Math.max(a.allowance, 0.01)) * 10));
|
|
166
|
+
const bar = '▓'.repeat(filled) + '░'.repeat(10 - filled);
|
|
167
|
+
const say = {
|
|
168
|
+
'on pace': 'on pace',
|
|
169
|
+
ahead: `ahead: ${r1(a.usedToday - a.expectedByNow)}% more than an even day by now`,
|
|
170
|
+
behind: `behind: ${r1(a.expectedByNow - a.usedToday)}% unspent so far, it funds the night`,
|
|
171
|
+
over: `over today's share by ${r1(a.usedToday - a.allowance)}%`,
|
|
172
|
+
};
|
|
173
|
+
return `today ${r1(a.usedToday)}% of ${r1(a.allowance)}% ${bar} ${say[a.status]} · day ends ${clock(a.dayEnds)}${a.approx ? ' (counted from the first reading today)' : ''}`;
|
|
174
|
+
}
|
|
175
|
+
export function pacing(snap, samples, now, bedtime) {
|
|
176
|
+
const models = {};
|
|
177
|
+
for (const [name, w] of Object.entries(snap?.models ?? {})) {
|
|
178
|
+
const v = windowView(w, now);
|
|
179
|
+
if (v.known)
|
|
180
|
+
models[name] = { usedPct: v.usedPct, delta: paceDelta(w, WEEK, now), resetsAt: v.resetsAt };
|
|
181
|
+
}
|
|
182
|
+
return {
|
|
183
|
+
fiveHourDelta: paceDelta(snap?.fiveHour, FIVE_HOURS, now),
|
|
184
|
+
weekDelta: paceDelta(snap?.sevenDay, WEEK, now),
|
|
185
|
+
fiveHourForecast: forecastWindow(snap?.fiveHour, FIVE_HOURS, samples, (s) => s.five, now),
|
|
186
|
+
today: dailyAllowance(snap?.sevenDay, samples, now, bedtime),
|
|
187
|
+
models,
|
|
188
|
+
};
|
|
189
|
+
}
|
package/dist/picture.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Picture first: every card opens with a diagram of what the task will do, drawn by an agent following
|
|
2
|
+
// the diagram-design skill (vendored in cli/vendor/diagram-design, MIT). One HTML + SVG file per card,
|
|
3
|
+
// in Chompyy's skin; the dark copy is made by swapping tokens (the skill's inversion rule), no second call.
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { existsSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { dirname, join } from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { homePath } from './home.js';
|
|
10
|
+
export function skillDir() {
|
|
11
|
+
return join(dirname(fileURLToPath(import.meta.url)), '..', 'vendor', 'diagram-design');
|
|
12
|
+
}
|
|
13
|
+
export const blueprintHash = (text) => createHash('sha256').update(text ?? '').digest('hex').slice(0, 16);
|
|
14
|
+
export function picturePrompt(card) {
|
|
15
|
+
return `You are drawing the picture for a task card in Chompyy, unattended. Nobody can answer questions,
|
|
16
|
+
so don't ask any: decide and draw.
|
|
17
|
+
|
|
18
|
+
Use the diagram-design skill in this folder. Read SKILL.md first. The style guide
|
|
19
|
+
(references/style-guide.md) is already customized for Chompyy, so skip the first-time style gate and
|
|
20
|
+
onboarding, and take every color from it (never the colors in the example files). Then pick ONE visual
|
|
21
|
+
type and read only that type's reference, plus references/primitives-core.md or
|
|
22
|
+
references/layout-budget.md if you need exact markup. Start from assets/template.html.
|
|
23
|
+
|
|
24
|
+
Who looks at it: the person deciding in ten seconds whether to approve this task. The picture must show
|
|
25
|
+
what the task will DO and WHY it helps: the thing it produces or changes and how it fits, not the
|
|
26
|
+
blueprint's headings. Don't draw four boxes called Goal / Changes / Won't touch / Done when. Good picks
|
|
27
|
+
are usually Steps, Flowchart, Data flow, Architecture or Before/After (Architecture delta), but choose
|
|
28
|
+
what fits. Put the accent on the 1 or 2 things this task actually creates or changes. Keep it small:
|
|
29
|
+
at most 7 nodes. Title (h1): the task in plain words. Eyebrow: "<Type> · Card #${card.id}".
|
|
30
|
+
|
|
31
|
+
Rendering rules for Chompyy:
|
|
32
|
+
- Remove the Google Fonts <link>; keep the font stacks (Chompyy renders offline).
|
|
33
|
+
- Static only: no <script>, no motion.
|
|
34
|
+
- Use viewBox width 960 and the matching min-width, as the template does.
|
|
35
|
+
- Follow the taste gate (SKILL.md §9) before you answer.
|
|
36
|
+
|
|
37
|
+
Reply with ONLY the complete HTML document, from <!DOCTYPE html> to </html>. No commentary.
|
|
38
|
+
|
|
39
|
+
The task:
|
|
40
|
+
Title: ${card.title}
|
|
41
|
+
Idea: ${card.idea}
|
|
42
|
+
|
|
43
|
+
Blueprint (agreed scope):
|
|
44
|
+
${card.blueprint ?? '(none yet)'}`;
|
|
45
|
+
}
|
|
46
|
+
/** The HTML document in the model's reply. */
|
|
47
|
+
export function extractHtml(output) {
|
|
48
|
+
const start = output.search(/<!DOCTYPE html>|<html[\s>]/i);
|
|
49
|
+
const end = output.toLowerCase().lastIndexOf('</html>');
|
|
50
|
+
if (start < 0 || end < start)
|
|
51
|
+
throw new Error('The picture model did not reply with an HTML document.');
|
|
52
|
+
return output.slice(start, end + '</html>'.length);
|
|
53
|
+
}
|
|
54
|
+
// Colors from the skill's default skin (examples) → Chompyy light, then Chompyy light → dark.
|
|
55
|
+
const TO_CHOMPYY = [
|
|
56
|
+
[/#f5f5f5\b/gi, '#faf3e8'],
|
|
57
|
+
[/#ececec\b/gi, '#f2e8d9'],
|
|
58
|
+
[/#2d3142\b/gi, '#3a2a1f'],
|
|
59
|
+
[/#4f5d75\b/gi, '#6b5141'],
|
|
60
|
+
[/#5a6580\b/gi, '#735a48'],
|
|
61
|
+
[/#bfc0c0\b/gi, '#ddd0bd'],
|
|
62
|
+
[/#bf4520\b/gi, '#a8481c'],
|
|
63
|
+
[/rgba\(\s*45\s*,\s*49\s*,\s*66\s*,/gi, 'rgba(58,42,31,'],
|
|
64
|
+
[/rgba\(\s*191\s*,\s*69\s*,\s*32\s*,/gi, 'rgba(168,72,28,'],
|
|
65
|
+
];
|
|
66
|
+
const TO_DARK = [
|
|
67
|
+
[/#faf3e8\b/gi, '#1e1915'],
|
|
68
|
+
[/#f2e8d9\b/gi, '#2a231d'],
|
|
69
|
+
[/#ffffff\b|#fff\b(?![0-9a-f])/gi, '#26201b'],
|
|
70
|
+
[/(fill|background(?:-color)?)(=|:\s*)"?white\b/gi, '$1$2"#26201b'],
|
|
71
|
+
[/#3a2a1f\b/gi, '#f6eee3'],
|
|
72
|
+
[/#6b5141\b/gi, '#d0c1af'],
|
|
73
|
+
[/#735a48\b/gi, '#b5a28f'],
|
|
74
|
+
[/#ddd0bd\b/gi, 'rgba(208,193,175,0.25)'],
|
|
75
|
+
[/#a8481c\b/gi, '#f0a066'],
|
|
76
|
+
[/#2e5aa8\b/gi, '#86aee6'],
|
|
77
|
+
[/rgba\(\s*58\s*,\s*42\s*,\s*31\s*,/gi, 'rgba(246,238,227,'],
|
|
78
|
+
[/rgba\(\s*168\s*,\s*72\s*,\s*28\s*,/gi, 'rgba(240,160,102,'],
|
|
79
|
+
];
|
|
80
|
+
const apply = (html, map) => map.reduce((s, [re, to]) => s.replace(re, to), html);
|
|
81
|
+
/** Make it safe and offline: no scripts, no remote fonts or images; Chompyy colors. */
|
|
82
|
+
export function cleanPicture(html) {
|
|
83
|
+
const out = html
|
|
84
|
+
.replace(/<link[^>]+fonts\.(googleapis|gstatic)\.com[^>]*>/gi, '')
|
|
85
|
+
.replace(/<script[\s\S]*?<\/script>/gi, '')
|
|
86
|
+
.replace(/\son[a-z]+\s*=\s*("[^"]*"|'[^']*')/gi, '');
|
|
87
|
+
if (!/<svg[\s>]/i.test(out))
|
|
88
|
+
throw new Error('The picture has no diagram (<svg>) in it.');
|
|
89
|
+
if (/(src|href)\s*=\s*["']https?:/i.test(out.replace(/xmlns(:\w+)?="[^"]*"/g, '')))
|
|
90
|
+
throw new Error('The picture loads something from the internet.');
|
|
91
|
+
return apply(out, TO_CHOMPYY);
|
|
92
|
+
}
|
|
93
|
+
export const darkPicture = (html) => apply(html, TO_DARK);
|
|
94
|
+
/** The skill's own self-check (accessibility contract, single-file safety, content inside the viewBox). */
|
|
95
|
+
function selfCheck(file) {
|
|
96
|
+
const r = spawnSync('python3', [join(skillDir(), 'scripts', 'self_check.py'), file], { encoding: 'utf8', timeout: 20_000 });
|
|
97
|
+
if (r.error)
|
|
98
|
+
return null;
|
|
99
|
+
return (r.stdout + r.stderr).trim().split('\n').slice(0, 12).join('\n') || (r.status === 0 ? 'OK' : `exit ${r.status}`);
|
|
100
|
+
}
|
|
101
|
+
export async function drawPicture(card, runner, opts) {
|
|
102
|
+
if (!card.blueprint)
|
|
103
|
+
throw new Error(`Card #${card.id} has no blueprint to draw yet.`);
|
|
104
|
+
if (!existsSync(join(skillDir(), 'SKILL.md')))
|
|
105
|
+
throw new Error('The diagram-design skill is missing from this install.');
|
|
106
|
+
const result = await runner.run({ prompt: picturePrompt(card), cwd: skillDir(), model: opts.model, tools: 'Read,Glob,Grep', timeoutMs: opts.timeoutMs ?? 300_000 });
|
|
107
|
+
if (result.timedOut)
|
|
108
|
+
throw new Error('Drawing the picture timed out.');
|
|
109
|
+
if (result.exitCode !== 0)
|
|
110
|
+
throw new Error(`claude exited with ${result.exitCode}: ${result.stderr.trim().slice(0, 300)}`);
|
|
111
|
+
const html = cleanPicture(extractHtml(result.output));
|
|
112
|
+
const path = homePath('pictures', `${card.id}.html`);
|
|
113
|
+
const darkPath = homePath('pictures', `${card.id}-dark.html`);
|
|
114
|
+
writeFileSync(path, html);
|
|
115
|
+
writeFileSync(darkPath, darkPicture(html));
|
|
116
|
+
return { path, darkPath, at: opts.now.toISOString(), blueprintHash: blueprintHash(card.blueprint), check: selfCheck(path) };
|
|
117
|
+
}
|