@drakulavich/cogload 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +303 -0
- package/LICENSE +21 -0
- package/README.md +301 -0
- package/assets/characters.webp +0 -0
- package/assets/fonts/LICENSE-inter.txt +92 -0
- package/assets/fonts/LICENSE-jetbrains-mono.txt +93 -0
- package/assets/fonts/inter-400.woff2 +0 -0
- package/assets/fonts/inter-700.woff2 +0 -0
- package/assets/fonts/inter-800.woff2 +0 -0
- package/assets/fonts/jetbrains-mono-500.woff2 +0 -0
- package/package.json +30 -0
- package/src/cli/args.ts +155 -0
- package/src/cli/commands.io.ts +99 -0
- package/src/cli/index.ts +58 -0
- package/src/cli/timing.ts +18 -0
- package/src/cli/zapara.ts +5 -0
- package/src/lib/card/card.ts +172 -0
- package/src/lib/card/cardhtml.ts +130 -0
- package/src/lib/card/image.io.ts +134 -0
- package/src/lib/card/index.ts +3 -0
- package/src/lib/metrics/analyze.ts +17 -0
- package/src/lib/metrics/derive.ts +221 -0
- package/src/lib/metrics/index.ts +3 -0
- package/src/lib/metrics/score.ts +55 -0
- package/src/lib/report/index.ts +1 -0
- package/src/lib/report/report.io.ts +82 -0
- package/src/lib/status/index.ts +2 -0
- package/src/lib/status/status.ts +52 -0
- package/src/lib/status/statusfile.io.ts +38 -0
- package/src/lib/text/format.ts +16 -0
- package/src/lib/text/index.ts +2 -0
- package/src/lib/text/render.ts +120 -0
- package/src/lib/transcripts/cache.io.ts +256 -0
- package/src/lib/transcripts/index.ts +3 -0
- package/src/lib/transcripts/parse.ts +138 -0
- package/src/lib/transcripts/scan.io.ts +75 -0
- package/src/lib/types.ts +22 -0
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Pure: Day[] in, CardData out, every value already formatted for the page.
|
|
2
|
+
// Nothing here knows a date, a path or a file, so nothing here can leak one.
|
|
3
|
+
import { formatCount, formatTokens, plural } from "../text/index.ts";
|
|
4
|
+
import { NORMS, WEIGHTS } from "../metrics/index.ts";
|
|
5
|
+
import type { Day, HourBucket, Level, Score } from "../types.ts";
|
|
6
|
+
|
|
7
|
+
export type Character = "conductor" | "supervisor" | "marathoner" | "nightOwl";
|
|
8
|
+
export type Segment = { text: string; strong: boolean };
|
|
9
|
+
type HighlightKey = "peakSessions" | "contextSwitches" | "longestStreak" | "reportsRead" | "tokensRead" | "interrupts" | "lateShare";
|
|
10
|
+
type Highlight = { key: HighlightKey; value: string; caption: string };
|
|
11
|
+
type Spectrum = { calm: number; warming: number; heating: number; fried: number };
|
|
12
|
+
export type CardData = {
|
|
13
|
+
days: number;
|
|
14
|
+
character: Character;
|
|
15
|
+
name: string;
|
|
16
|
+
sentence: Segment[];
|
|
17
|
+
motto: string;
|
|
18
|
+
shares: Record<Character, number>;
|
|
19
|
+
peak: { index: number; level: Level };
|
|
20
|
+
spectrum: Spectrum;
|
|
21
|
+
highlights: Highlight[];
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// Tie order: the first of equal shares wins.
|
|
25
|
+
const CHARACTERS: readonly Character[] = ["conductor", "supervisor", "marathoner", "nightOwl"];
|
|
26
|
+
const NAMES: Record<Character, string> = {
|
|
27
|
+
conductor: "The Conductor", supervisor: "The Supervisor", marathoner: "The Marathoner", nightOwl: "The Night Owl",
|
|
28
|
+
};
|
|
29
|
+
const MOTTOS: Record<Character, string> = {
|
|
30
|
+
conductor: "You run agents like an orchestra.",
|
|
31
|
+
supervisor: "Nothing ships without your eyes on it.",
|
|
32
|
+
marathoner: "You do not stop while it compiles.",
|
|
33
|
+
nightOwl: "The best commits happen after dark.",
|
|
34
|
+
};
|
|
35
|
+
// Rank the third highlight, per active hour. They never touch the index, whose
|
|
36
|
+
// norms stay in score.ts.
|
|
37
|
+
const CARD_NORMS = { reportsPerHour: 12, tokensPerHour: 65_000, interruptsPerHour: 3, latePercent: 25 } as const;
|
|
38
|
+
const OWNED: Record<Character, [HighlightKey, HighlightKey]> = {
|
|
39
|
+
conductor: ["peakSessions", "contextSwitches"],
|
|
40
|
+
supervisor: ["reportsRead", "tokensRead"],
|
|
41
|
+
marathoner: ["longestStreak", "interrupts"],
|
|
42
|
+
nightOwl: ["lateShare", "longestStreak"],
|
|
43
|
+
};
|
|
44
|
+
const POOL: readonly HighlightKey[] = ["peakSessions", "contextSwitches", "longestStreak", "reportsRead", "tokensRead", "interrupts", "lateShare"];
|
|
45
|
+
// [for the value "1", for any other]
|
|
46
|
+
const CAPTIONS: Record<HighlightKey, [string, string]> = {
|
|
47
|
+
peakSessions: ["session at once", "sessions at once"],
|
|
48
|
+
contextSwitches: ["switch in one hour", "switches in one hour"],
|
|
49
|
+
longestStreak: ["longest streak", "longest streak"],
|
|
50
|
+
reportsRead: ["agent report read", "agent reports read"],
|
|
51
|
+
tokensRead: ["token of output read", "tokens of output read"],
|
|
52
|
+
interrupts: ["time you stopped Claude", "times you stopped Claude"],
|
|
53
|
+
// Late is hours 23 and 0-5, so not "after midnight": 23:00 is before it.
|
|
54
|
+
lateShare: ["of hours late at night", "of hours late at night"],
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
function formatStreak(min: number): string {
|
|
58
|
+
if (min < 60) return `${min}m`;
|
|
59
|
+
const h = Math.floor(min / 60);
|
|
60
|
+
if (h < 10) return `${h}h${String(min % 60).padStart(2, "0")}m`;
|
|
61
|
+
if (h < 1000) return `${h}h`;
|
|
62
|
+
return "999h+";
|
|
63
|
+
}
|
|
64
|
+
const percent = (part: number, whole: number): number => Math.round((100 * part) / whole);
|
|
65
|
+
|
|
66
|
+
// Whole percents that sum to 100: floors first, then one more to the largest
|
|
67
|
+
// remainders, ties resolved in the given order. A level with any hours never
|
|
68
|
+
// reads 0%: it takes its 1 from the largest level, which holds 25 or more.
|
|
69
|
+
function spectrumOf(counts: [number, number, number, number], total: number): Spectrum {
|
|
70
|
+
const raw = counts.map((c) => (100 * c) / total);
|
|
71
|
+
const pct = raw.map((r) => Math.floor(r)) as [number, number, number, number];
|
|
72
|
+
let left = 100 - pct.reduce((a, b) => a + b, 0);
|
|
73
|
+
const byRemainder = raw.map((r, i) => ({ i, rem: r - Math.floor(r) })).sort((a, b) => b.rem - a.rem || a.i - b.i);
|
|
74
|
+
for (const { i } of byRemainder) {
|
|
75
|
+
if (left === 0) break;
|
|
76
|
+
pct[i]! += 1;
|
|
77
|
+
left -= 1;
|
|
78
|
+
}
|
|
79
|
+
for (const [i, c] of counts.entries()) {
|
|
80
|
+
if (c === 0 || pct[i] !== 0) continue;
|
|
81
|
+
pct[pct.indexOf(Math.max(...pct))]! -= 1;
|
|
82
|
+
pct[i] = 1;
|
|
83
|
+
}
|
|
84
|
+
const [calm, warming, heating, fried] = pct;
|
|
85
|
+
return { calm, warming, heating, fried };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const strong = (text: string): Segment => ({ text, strong: true });
|
|
89
|
+
const plain = (text: string): Segment => ({ text, strong: false });
|
|
90
|
+
export const sentenceText = (segments: Segment[]): string => segments.map((s) => s.text).join("");
|
|
91
|
+
|
|
92
|
+
type Active = HourBucket & { score: Score };
|
|
93
|
+
|
|
94
|
+
export function cardData(days: Day[], w: { days: number }): CardData | null {
|
|
95
|
+
const active = days.flatMap((d) => d.buckets).filter((b): b is Active => b.score !== null);
|
|
96
|
+
const n = active.length;
|
|
97
|
+
if (n === 0) return null;
|
|
98
|
+
const sum = (f: (b: Active) => number): number => active.reduce((a, b) => a + f(b), 0);
|
|
99
|
+
const max = (f: (b: Active) => number): number => active.reduce((a, b) => Math.max(a, f(b)), 0);
|
|
100
|
+
const count = (level: Level): number => active.filter((b) => b.score.level === level).length;
|
|
101
|
+
|
|
102
|
+
// A share is the fraction of the character's maximum points, so a 10-point
|
|
103
|
+
// component competes fairly with a 40-point one.
|
|
104
|
+
const shares: Record<Character, number> = {
|
|
105
|
+
conductor: sum((b) => b.score.parts.parallel + b.score.parts.pace) / ((WEIGHTS.parallel + WEIGHTS.pace) * n),
|
|
106
|
+
supervisor: sum((b) => b.score.parts.supervision + b.score.parts.reading) / ((WEIGHTS.supervision + WEIGHTS.reading) * n),
|
|
107
|
+
marathoner: sum((b) => b.score.parts.streak) / (WEIGHTS.streak * n),
|
|
108
|
+
nightOwl: sum((b) => b.score.parts.late) / (WEIGHTS.late * n),
|
|
109
|
+
};
|
|
110
|
+
// Strict >: CHARACTERS is the tie order.
|
|
111
|
+
const character = CHARACTERS.reduce((best, c) => (shares[c] > shares[best] ? c : best));
|
|
112
|
+
|
|
113
|
+
const maxSessions = max((b) => b.sessions);
|
|
114
|
+
const maxSwitches = max((b) => b.contextSwitches);
|
|
115
|
+
const maxStreak = max((b) => b.streakMin);
|
|
116
|
+
const reports = sum((b) => b.reports);
|
|
117
|
+
const tokens = sum((b) => b.outputTokens);
|
|
118
|
+
const interrupts = sum((b) => b.interrupts);
|
|
119
|
+
const late = percent(active.filter((b) => b.lateNight).length, n);
|
|
120
|
+
// One figure for one fact: the sentence's calm share is the legend's.
|
|
121
|
+
const spectrum = spectrumOf([count("Calm"), count("Warming"), count("Heating"), count("Fried")], n);
|
|
122
|
+
|
|
123
|
+
const sentences: Record<Character, Segment[]> = {
|
|
124
|
+
conductor: [strong(plural(maxSessions, "session")), plain(" at once, "), strong(plural(maxSwitches, "context switch", "context switches")), plain(" in one hour.")],
|
|
125
|
+
supervisor: [strong(plural(reports, "agent report")), plain(" and "), strong(plural(tokens, "token", "tokens", formatTokens)), plain(" of output read.")],
|
|
126
|
+
marathoner: [plain("Longest streak "), strong(formatStreak(maxStreak)), plain(" without a break, "), strong(`${spectrum.calm}%`), plain(" of your hours calm.")],
|
|
127
|
+
nightOwl: [strong(`${late}%`), plain(" of your hours "), strong("late at night"), plain(".")],
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const peakBucket = active.reduce((a, b) => (b.score.index > a.score.index ? b : a));
|
|
131
|
+
|
|
132
|
+
const values: Record<HighlightKey, string> = {
|
|
133
|
+
peakSessions: formatCount(maxSessions),
|
|
134
|
+
contextSwitches: formatCount(maxSwitches),
|
|
135
|
+
longestStreak: formatStreak(maxStreak),
|
|
136
|
+
reportsRead: formatCount(reports),
|
|
137
|
+
tokensRead: formatTokens(tokens),
|
|
138
|
+
interrupts: formatCount(interrupts),
|
|
139
|
+
lateShare: `${late}%`,
|
|
140
|
+
};
|
|
141
|
+
const norms: Record<HighlightKey, number> = {
|
|
142
|
+
peakSessions: (maxSessions - 1) / NORMS.parallelSpan,
|
|
143
|
+
contextSwitches: maxSwitches / NORMS.supervisionPerHour,
|
|
144
|
+
longestStreak: maxStreak / NORMS.streakMin,
|
|
145
|
+
reportsRead: reports / (CARD_NORMS.reportsPerHour * n),
|
|
146
|
+
tokensRead: tokens / (CARD_NORMS.tokensPerHour * n),
|
|
147
|
+
interrupts: interrupts / (CARD_NORMS.interruptsPerHour * n),
|
|
148
|
+
lateShare: late / CARD_NORMS.latePercent,
|
|
149
|
+
};
|
|
150
|
+
const owned = OWNED[character];
|
|
151
|
+
// A late-night number belongs to the Night Owl alone.
|
|
152
|
+
const rest = POOL.filter((k) => !owned.includes(k) && (k !== "lateShare" || character === "nightOwl"));
|
|
153
|
+
const third = rest.reduce((best, k) => (norms[k] > norms[best] ? k : best));
|
|
154
|
+
// A panel that scores nothing ("0m longest streak", "1 session at once") is
|
|
155
|
+
// no achievement and is left out; the rest share the row. The first is the
|
|
156
|
+
// character's own number and always shows, so the row is never empty.
|
|
157
|
+
const [first, second] = owned;
|
|
158
|
+
const keys = [first, ...[second, third].filter((k) => norms[k] > 0)];
|
|
159
|
+
const highlights = keys.map((key) => ({ key, value: values[key], caption: CAPTIONS[key][values[key] === "1" ? 0 : 1] }));
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
days: w.days,
|
|
163
|
+
character,
|
|
164
|
+
name: NAMES[character],
|
|
165
|
+
sentence: sentences[character],
|
|
166
|
+
motto: MOTTOS[character],
|
|
167
|
+
shares,
|
|
168
|
+
peak: { index: peakBucket.score.index, level: peakBucket.score.level },
|
|
169
|
+
spectrum,
|
|
170
|
+
highlights,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Nothing is escaped because nothing from a transcript reaches this file: only
|
|
2
|
+
// CardData's fixed strings and formatted numbers. The look is the table in
|
|
3
|
+
// docs/superpowers/specs/2026-09-18-zapara-card-design.md.
|
|
4
|
+
import type { CardData, Character, Segment } from "./card.ts";
|
|
5
|
+
import type { Level } from "../types.ts";
|
|
6
|
+
|
|
7
|
+
export type CardAssets = {
|
|
8
|
+
fonts: { inter400: string; inter700: string; inter800: string; mono500: string };
|
|
9
|
+
characters: string;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
// Fractions [x, y, w, h] of the sheet's side, measured on assets/characters.webp.
|
|
13
|
+
// Scaled so the longer side is BOX px, centred at CENTRE; nothing is cropped.
|
|
14
|
+
const CHARACTER_RECTS: Record<Character, [number, number, number, number]> = {
|
|
15
|
+
conductor: [0.02, 0.01, 0.53, 0.543],
|
|
16
|
+
supervisor: [0.55, 0.07, 0.38, 0.505],
|
|
17
|
+
marathoner: [0.02, 0.553, 0.50, 0.437],
|
|
18
|
+
nightOwl: [0.54, 0.585, 0.45, 0.41],
|
|
19
|
+
};
|
|
20
|
+
const BOX = 360;
|
|
21
|
+
const CENTRE = { x: 195, y: 300 };
|
|
22
|
+
|
|
23
|
+
// main, its rgb for alpha gradients, and the light shade for the repo link.
|
|
24
|
+
const ACCENT: Record<Character, { main: string; rgb: string; light: string }> = {
|
|
25
|
+
conductor: { main: "#8b5cf6", rgb: "139,92,246", light: "#c4b5fd" },
|
|
26
|
+
supervisor: { main: "#22d3ee", rgb: "34,211,238", light: "#a5f3fc" },
|
|
27
|
+
marathoner: { main: "#f59e0b", rgb: "245,158,11", light: "#fde68a" },
|
|
28
|
+
nightOwl: { main: "#60a5fa", rgb: "96,165,250", light: "#bfdbfe" },
|
|
29
|
+
};
|
|
30
|
+
const LEVEL_CLASS: Record<Level, string> = { Calm: "calm", Warming: "warm", Heating: "heat", Fried: "fried" };
|
|
31
|
+
|
|
32
|
+
function spriteStyle(c: Character): string {
|
|
33
|
+
const [x, y, w, h] = CHARACTER_RECTS[c];
|
|
34
|
+
const size = BOX / Math.max(w, h);
|
|
35
|
+
const bw = w * size;
|
|
36
|
+
const bh = h * size;
|
|
37
|
+
const px = (v: number): string => `${v.toFixed(1)}px`;
|
|
38
|
+
return `background-size:${px(size)} ${px(size)};background-position:${px(-x * size)} ${px(-y * size)};width:${px(bw)};height:${px(bh)};left:${px(CENTRE.x - bw / 2)};top:${px(CENTRE.y - bh / 2)}`;
|
|
39
|
+
}
|
|
40
|
+
const sentenceHtml = (segments: Segment[]): string => segments.map((s) => (s.strong ? `<b>${s.text}</b>` : s.text)).join("");
|
|
41
|
+
const fontFace = (family: string, weight: number, data: string): string =>
|
|
42
|
+
`@font-face{font-family:"${family}";font-weight:${weight};font-style:normal;src:url("data:font/woff2;base64,${data}") format("woff2")}`;
|
|
43
|
+
|
|
44
|
+
const GRAIN = `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='300' height='300'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 .6 0'/></filter><rect width='300' height='300' filter='url(%23n)'/></svg>")`;
|
|
45
|
+
|
|
46
|
+
export function cardHtml(card: CardData, assets: CardAssets): string {
|
|
47
|
+
const accent = ACCENT[card.character];
|
|
48
|
+
const levels = [
|
|
49
|
+
["calm", card.spectrum.calm, "calm"],
|
|
50
|
+
["warm", card.spectrum.warming, "warming"],
|
|
51
|
+
["heat", card.spectrum.heating, "heating"],
|
|
52
|
+
["fried", card.spectrum.fried, "fried"],
|
|
53
|
+
] as const;
|
|
54
|
+
const bar = levels.filter(([, pct]) => pct > 0).map(([cls, pct]) => `<div class="${cls}" style="width:${pct}%"></div>`).join("");
|
|
55
|
+
const legend = levels.map(([cls, pct, name]) => `<span><i class="${cls}"></i><b>${pct}%</b> ${name}</span>`).join(" ");
|
|
56
|
+
const stats = card.highlights
|
|
57
|
+
.map((h) => `<div class="stat" data-key="${h.key}"><div class="v">${h.value}</div><div class="c mono">${h.caption}</div></div>`)
|
|
58
|
+
.join("");
|
|
59
|
+
const label = card.days === 1 ? "Last 1 day" : `Last ${card.days} days`;
|
|
60
|
+
|
|
61
|
+
return `<!doctype html>
|
|
62
|
+
<html><head><meta charset="utf-8"><title>cogload card</title>
|
|
63
|
+
<style>
|
|
64
|
+
${fontFace("Inter", 400, assets.fonts.inter400)}
|
|
65
|
+
${fontFace("Inter", 700, assets.fonts.inter700)}
|
|
66
|
+
${fontFace("Inter", 800, assets.fonts.inter800)}
|
|
67
|
+
${fontFace("JetBrains Mono", 500, assets.fonts.mono500)}
|
|
68
|
+
:root{--ink:#f5f5f7;--muted:#a1a1aa;--dim:#6b6b76;--line:rgba(255,255,255,.10);--accent:${accent.main};--accent2:${accent.light};--accent-rgb:${accent.rgb};--calm:#7ee2a3;--warm:#fbd77a;--heat:#c4a0ff;--fried:#ff6b8f}
|
|
69
|
+
html{zoom:2}
|
|
70
|
+
html,body{margin:0;background:#000}
|
|
71
|
+
.card{position:relative;width:1200px;height:630px;overflow:hidden;font-family:Inter,-apple-system,system-ui,sans-serif;color:var(--ink);-webkit-font-smoothing:antialiased;background:#07070a}
|
|
72
|
+
.mono{font-family:"JetBrains Mono",ui-monospace,monospace}
|
|
73
|
+
.streaks{position:absolute;left:-200px;top:-260px;width:900px;height:1100px;transform:rotate(38deg);filter:blur(22px);opacity:.9}
|
|
74
|
+
.streaks div{position:absolute;top:0;height:100%;border-radius:40px}
|
|
75
|
+
.s1{left:120px;width:150px;background:linear-gradient(180deg,transparent 0%,rgba(var(--accent-rgb),.55) 35%,rgba(var(--accent-rgb),.9) 50%,rgba(var(--accent-rgb),.45) 70%,transparent 100%)}
|
|
76
|
+
.s2{left:320px;width:70px;background:linear-gradient(180deg,transparent 10%,rgba(255,255,255,.35) 45%,rgba(var(--accent-rgb),.7) 55%,transparent 90%)}
|
|
77
|
+
.s3{left:440px;width:200px;background:linear-gradient(180deg,transparent 0%,rgba(var(--accent-rgb),.35) 40%,rgba(34,211,238,.35) 58%,transparent 100%)}
|
|
78
|
+
.s4{left:700px;width:90px;background:linear-gradient(180deg,transparent 15%,rgba(var(--accent-rgb),.5) 50%,transparent 85%)}
|
|
79
|
+
.vignette{position:absolute;inset:0;background:radial-gradient(900px 600px at 30% 40%,transparent 30%,rgba(7,7,10,.85) 75%,#07070a 100%)}
|
|
80
|
+
.grain{position:absolute;inset:0;opacity:.35;mix-blend-mode:overlay;background-image:${GRAIN}}
|
|
81
|
+
.char{position:absolute;background-image:url("data:image/webp;base64,${assets.characters}");background-repeat:no-repeat;filter:drop-shadow(0 30px 40px rgba(0,0,0,.7))}
|
|
82
|
+
.panel{position:absolute;left:380px;top:56px;width:760px;height:518px;box-sizing:border-box;border-radius:20px;border:1px solid var(--line);background:linear-gradient(180deg,rgba(255,255,255,.045),rgba(255,255,255,.02));box-shadow:inset 0 1px 0 rgba(255,255,255,.08),0 30px 80px rgba(0,0,0,.5);padding:36px 40px}
|
|
83
|
+
.row{display:flex;justify-content:space-between;align-items:center}
|
|
84
|
+
.label{font-size:13px;color:var(--dim);letter-spacing:.5px;text-transform:uppercase}
|
|
85
|
+
.peak{display:inline-flex;align-items:center;gap:10px;padding:6px 12px;border-radius:8px;border:1px solid var(--line);background:rgba(255,255,255,.03);font-size:12px;color:var(--dim);letter-spacing:.5px;text-transform:uppercase;white-space:nowrap}
|
|
86
|
+
.peak b{font-weight:500}
|
|
87
|
+
.peak b.calm{color:var(--calm)}.peak b.warm{color:var(--warm)}.peak b.heat{color:var(--heat)}.peak b.fried{color:var(--fried)}
|
|
88
|
+
.name{margin-top:18px;font-size:76px;font-weight:700;line-height:1;letter-spacing:-3px;color:#fff;text-shadow:0 0 40px rgba(255,255,255,.18);white-space:nowrap}
|
|
89
|
+
.sentence{margin-top:22px;font-size:22px;line-height:31px;color:var(--muted);letter-spacing:-.2px;max-width:660px}
|
|
90
|
+
.sentence b{color:#fff;font-weight:600}
|
|
91
|
+
.divider{height:1px;background:var(--line);margin:30px 0 26px}
|
|
92
|
+
.bar{height:8px;border-radius:4px;overflow:hidden;display:flex;gap:2px}
|
|
93
|
+
.bar div{height:100%}
|
|
94
|
+
.bar .calm{background:var(--calm)}.bar .warm{background:var(--warm)}.bar .heat{background:var(--heat)}.bar .fried{background:var(--fried)}
|
|
95
|
+
.legend{margin-top:14px;font-size:12.5px;color:var(--dim);letter-spacing:.2px;white-space:nowrap}
|
|
96
|
+
.legend b{color:var(--muted);font-weight:500}
|
|
97
|
+
.legend i{display:inline-block;width:6px;height:6px;border-radius:50%;margin:0 7px 1px 0}
|
|
98
|
+
.legend i.calm{background:var(--calm)}.legend i.warm{background:var(--warm)}.legend i.heat{background:var(--heat)}.legend i.fried{background:var(--fried)}
|
|
99
|
+
.stats{display:flex;gap:16px;margin-top:30px}
|
|
100
|
+
.stat{flex:1;min-width:0;box-sizing:border-box;padding:18px 16px;border-radius:12px;border:1px solid var(--line);background:rgba(255,255,255,.025);box-shadow:inset 0 1px 0 rgba(255,255,255,.06)}
|
|
101
|
+
.stat .v{font-size:38px;font-weight:700;letter-spacing:-1.6px;line-height:1;color:#fff;font-variant-numeric:tabular-nums;white-space:nowrap}
|
|
102
|
+
.stat .c{margin-top:8px;font-size:12px;color:var(--dim);letter-spacing:0;white-space:nowrap}
|
|
103
|
+
.repo{position:absolute;left:60px;top:566px;line-height:1;white-space:nowrap}
|
|
104
|
+
.repo small{display:block;font-size:11px;letter-spacing:1.5px;text-transform:uppercase;color:var(--dim);margin-bottom:8px}
|
|
105
|
+
.repo span{font-size:17px;font-weight:500;color:var(--accent2);letter-spacing:-.2px}
|
|
106
|
+
.source{position:absolute;right:60px;top:588px;font-size:12px;color:var(--muted);letter-spacing:.2px;white-space:nowrap}
|
|
107
|
+
</style></head><body>
|
|
108
|
+
<div class="card">
|
|
109
|
+
<div class="streaks"><div class="s1"></div><div class="s2"></div><div class="s3"></div><div class="s4"></div></div>
|
|
110
|
+
<div class="vignette"></div>
|
|
111
|
+
<div class="grain"></div>
|
|
112
|
+
<div class="char ${card.character}" style="${spriteStyle(card.character)}"></div>
|
|
113
|
+
<div class="panel">
|
|
114
|
+
<div class="row">
|
|
115
|
+
<div class="label mono">${label}</div>
|
|
116
|
+
<div class="peak mono">Peak hour <b class="${LEVEL_CLASS[card.peak.level]}">${card.peak.index} · ${card.peak.level}</b></div>
|
|
117
|
+
</div>
|
|
118
|
+
<div class="name">${card.name}</div>
|
|
119
|
+
<div class="sentence">${sentenceHtml(card.sentence)} ${card.motto}</div>
|
|
120
|
+
<div class="divider"></div>
|
|
121
|
+
<div class="bar">${bar}</div>
|
|
122
|
+
<div class="legend mono">${legend}</div>
|
|
123
|
+
<div class="stats">${stats}</div>
|
|
124
|
+
</div>
|
|
125
|
+
<div class="repo mono"><small>Get yours</small><span>github.com/drakulavich/cogload</span></div>
|
|
126
|
+
<div class="source mono">computed locally from your Claude Code transcripts · nothing leaves your machine</div>
|
|
127
|
+
</div>
|
|
128
|
+
</body></html>
|
|
129
|
+
`;
|
|
130
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// The only module that reads the card assets, opens a Bun.WebView or Bun.Image,
|
|
2
|
+
// writes the card, and starts another program: the opener that shows it.
|
|
3
|
+
import { rmSync } from "node:fs";
|
|
4
|
+
import { mkdtemp, open, readFile, rename, rm, unlink, writeFile } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import type { CardAssets } from "./cardhtml.ts";
|
|
9
|
+
|
|
10
|
+
const ASSETS = new URL("../../../assets/", import.meta.url);
|
|
11
|
+
const FILES = ["fonts/inter-400.woff2", "fonts/inter-700.woff2", "fonts/inter-800.woff2", "fonts/jetbrains-mono-500.woff2", "characters.webp"] as const;
|
|
12
|
+
|
|
13
|
+
// A missing or empty asset is a broken install, reported without a path.
|
|
14
|
+
export async function loadAssets(): Promise<CardAssets> {
|
|
15
|
+
let parts: string[];
|
|
16
|
+
try {
|
|
17
|
+
parts = await Promise.all(FILES.map(async (name) => (await readFile(new URL(name, ASSETS))).toString("base64")));
|
|
18
|
+
} catch {
|
|
19
|
+
throw new Error("assets missing: reinstall cogload");
|
|
20
|
+
}
|
|
21
|
+
const [inter400, inter700, inter800, mono500, characters] = parts;
|
|
22
|
+
if (parts.some((p) => p.length === 0)) throw new Error("assets missing: reinstall cogload");
|
|
23
|
+
return { fonts: { inter400: inter400!, inter700: inter700!, inter800: inter800!, mono500: mono500! }, characters: characters! };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const BACKEND = process.platform === "darwin" ? "webkit" : "chrome";
|
|
27
|
+
const ENGINE_LINE = "card needs a browser engine: install a Chromium browser such as Chrome or Edge, or write --out card.html";
|
|
28
|
+
// Thrown for a card that cannot be written, so the caller can name the place it
|
|
29
|
+
// chose; the message is the line for an --out the person gave.
|
|
30
|
+
export class CardWriteError extends Error {
|
|
31
|
+
constructor() { super("cannot write the card: check the --out directory"); }
|
|
32
|
+
}
|
|
33
|
+
const TEMP_LINE = "cannot draw the card: the temporary directory is not writable";
|
|
34
|
+
const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"] as const;
|
|
35
|
+
const WIDTH = 2400;
|
|
36
|
+
const HEIGHT = 1260;
|
|
37
|
+
const READY = 'document.fonts.ready.then(() => document.fonts.status === "loaded" && Array.from(document.images).every((i) => i.complete))';
|
|
38
|
+
|
|
39
|
+
// The budget bounds the whole render, and the view closes the moment it runs
|
|
40
|
+
// out. The page loads from a file because a data: URL this size sometimes
|
|
41
|
+
// never finishes loading while other WebKit views are open. An engine failure
|
|
42
|
+
// becomes one line that never quotes the engine's text.
|
|
43
|
+
export async function renderCard(html: string, out: string, timeoutMs = 15_000): Promise<void> {
|
|
44
|
+
const lower = out.toLowerCase();
|
|
45
|
+
if (lower.endsWith(".html")) {
|
|
46
|
+
await write(out, html);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const dir = await mkdtemp(join(tmpdir(), "cogload-card-")).catch(() => { throw new Error(TEMP_LINE); });
|
|
50
|
+
// Ctrl-C (or a hangup, or kill) mid-render would skip the finally below and
|
|
51
|
+
// leave the page behind: remove it, then end as the signal would have.
|
|
52
|
+
const onSignal = (signal: NodeJS.Signals): void => {
|
|
53
|
+
rmSync(dir, { recursive: true, force: true });
|
|
54
|
+
process.exit(128 + ({ SIGHUP: 1, SIGINT: 2, SIGTERM: 15 } as Record<string, number>)[signal]!);
|
|
55
|
+
};
|
|
56
|
+
for (const s of SIGNALS) process.once(s, onSignal);
|
|
57
|
+
let bytes: Uint8Array | null;
|
|
58
|
+
try {
|
|
59
|
+
const page = join(dir, "card.html");
|
|
60
|
+
await writeFile(page, html, { mode: 0o600 }).catch(() => { throw new Error(TEMP_LINE); });
|
|
61
|
+
bytes = await shoot(pathToFileURL(page).href, lower.endsWith(".webp"), timeoutMs).catch(() => { throw new Error(ENGINE_LINE); });
|
|
62
|
+
} finally {
|
|
63
|
+
// The handlers stay until the page is gone: a signal during this rm still cleans up.
|
|
64
|
+
await rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
65
|
+
for (const s of SIGNALS) process.off(s, onSignal);
|
|
66
|
+
}
|
|
67
|
+
if (bytes === null) throw new Error("render timed out");
|
|
68
|
+
await write(out, bytes);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// The picture, or null when the view did not finish within `ms`.
|
|
72
|
+
async function shoot(url: string, webp: boolean, ms: number): Promise<Uint8Array | null> {
|
|
73
|
+
const view = new Bun.WebView({ width: WIDTH, height: HEIGHT, backend: BACKEND });
|
|
74
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
75
|
+
const work = (async () => {
|
|
76
|
+
// WebKit draws at the screen's density: at 2x, a 2400-wide viewport made a
|
|
77
|
+
// 4800-wide shot, 2.2 s of a 3 s render. The viewport and the page's zoom
|
|
78
|
+
// (2 in cardHtml) shrink by the density, so the shot is 2400 wide already.
|
|
79
|
+
// Headless Chrome (or Edge) shoots at 1x and cannot evaluate before a navigate.
|
|
80
|
+
const dpr = BACKEND === "webkit" ? await view.evaluate<number>("devicePixelRatio") : 1;
|
|
81
|
+
if (dpr !== 1) await view.resize(Math.round(WIDTH / dpr), Math.round(HEIGHT / dpr));
|
|
82
|
+
await view.navigate(url);
|
|
83
|
+
await view.evaluate(`document.documentElement.style.zoom = "${2 / dpr}"`);
|
|
84
|
+
while (!(await view.evaluate<boolean>(READY))) await Bun.sleep(50);
|
|
85
|
+
const shot = await view.screenshot({ encoding: "buffer", format: "png" });
|
|
86
|
+
const image = new Bun.Image(shot);
|
|
87
|
+
const meta = await image.metadata();
|
|
88
|
+
const sized = meta.width === WIDTH && meta.height === HEIGHT;
|
|
89
|
+
if (sized && !webp) return shot;
|
|
90
|
+
if (!sized) image.resize(WIDTH, HEIGHT, { fit: "fill" });
|
|
91
|
+
return webp ? await image.webp({ quality: 90 }).bytes() : await image.png().bytes();
|
|
92
|
+
})();
|
|
93
|
+
// After the deadline closes the view, the calls still pending on it may reject.
|
|
94
|
+
work.catch(() => {});
|
|
95
|
+
try {
|
|
96
|
+
return await Promise.race([work, new Promise<null>((done) => { timer = setTimeout(() => done(null), ms); })]);
|
|
97
|
+
} finally {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
view.close();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// The status file's way: a temporary file created exclusively next to the
|
|
104
|
+
// target, then a rename over it, so a symlink at the target (an unpacked
|
|
105
|
+
// archive can leave one in Downloads) is replaced, never written through. The
|
|
106
|
+
// mode is the umask's, as for any file the person makes. One line for every
|
|
107
|
+
// failure: node's error quotes the path, and the CLI never prints one.
|
|
108
|
+
async function write(out: string, data: string | Uint8Array): Promise<void> {
|
|
109
|
+
const tmp = join(dirname(out), `.${basename(out)}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`);
|
|
110
|
+
let created = false;
|
|
111
|
+
try {
|
|
112
|
+
const handle = await open(tmp, "wx");
|
|
113
|
+
created = true;
|
|
114
|
+
try { await handle.writeFile(data); } finally { await handle.close(); }
|
|
115
|
+
await rename(tmp, out);
|
|
116
|
+
} catch {
|
|
117
|
+
if (created) await unlink(tmp).catch(() => {});
|
|
118
|
+
throw new CardWriteError();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Absolute, so `-card.html` is never an option.
|
|
123
|
+
export function openCard(path: string): void {
|
|
124
|
+
startInBackground([process.platform === "darwin" ? "open" : "xdg-open", resolve(path)]);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// The only place src/ starts another program; lint/no-bun-spawn.grit bans Bun.spawn
|
|
128
|
+
// elsewhere. `sh … &` with SIGHUP ignored: a detached Bun.spawn child, or one in a
|
|
129
|
+
// terminal cogload leads, dies with cogload. A program that fails to start is ignored.
|
|
130
|
+
function startInBackground(command: string[]): void {
|
|
131
|
+
try {
|
|
132
|
+
Bun.spawnSync(["sh", "-c", 'trap "" HUP; "$0" "$@" </dev/null >/dev/null 2>&1 &', ...command], { stdin: "ignore", stdout: "ignore", stderr: "ignore" });
|
|
133
|
+
} catch {}
|
|
134
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { compareStrings, derive, windowBounds } from "./derive.ts";
|
|
2
|
+
import { parseTranscript } from "../transcripts/index.ts";
|
|
3
|
+
import type { Day, Event, Transcript, Window } from "../types.ts";
|
|
4
|
+
|
|
5
|
+
// Sorted by path so file discovery order cannot change a result.
|
|
6
|
+
export function analyze(transcripts: Transcript[], w: Window): Day[] {
|
|
7
|
+
const { cutoffMs } = windowBounds(w);
|
|
8
|
+
const events = [...transcripts]
|
|
9
|
+
.sort((a, b) => compareStrings(a.path, b.path))
|
|
10
|
+
.flatMap((t) => parseTranscript(t.text, cutoffMs));
|
|
11
|
+
return analyzeEvents(events, w);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Events already parsed, concatenated in path order as `analyze` does.
|
|
15
|
+
export function analyzeEvents(events: Event[], w: Window): Day[] {
|
|
16
|
+
return derive(events, w);
|
|
17
|
+
}
|