@drakulavich/cogload 0.14.2 → 0.15.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 +8 -0
- package/README.md +2 -2
- package/package.json +31 -9
- package/src/cli/args.ts +87 -21
- package/src/cli/commands.io.ts +46 -11
- package/src/cli/index.ts +44 -14
- package/src/cli/timing.ts +17 -11
- package/src/lib/card/card.ts +22 -4
- package/src/lib/card/cardhtml.ts +5 -2
- package/src/lib/card/image.io.ts +32 -8
- package/src/lib/metrics/analyze.ts +1 -3
- package/src/lib/metrics/derive.ts +91 -21
- package/src/lib/metrics/score.ts +11 -7
- package/src/lib/report/report.io.ts +43 -6
- package/src/lib/status/statusfile.io.ts +5 -1
- package/src/lib/text/format.ts +5 -1
- package/src/lib/text/render.ts +35 -6
- package/src/lib/transcripts/cache.io.ts +70 -16
- package/src/lib/transcripts/parse.ts +5 -1
- package/src/lib/transcripts/scan.io.ts +6 -2
- package/src/lib/types.ts +46 -6
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,14 @@ All notable changes to this project are documented here. The format follows
|
|
|
5
5
|
|
|
6
6
|
## [Unreleased]
|
|
7
7
|
|
|
8
|
+
## [0.15.0] - 2026-10-29
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- You get five skips a calendar week, from Monday 00:00 local time. With
|
|
12
|
+
none left, a skip no longer lifts the rest. During a rest the band shows
|
|
13
|
+
how many are left, and `/cogload` counts the week from Monday. A session
|
|
14
|
+
started before the update ignores the limit until it is restarted. (#234)
|
|
15
|
+
|
|
8
16
|
## [0.14.2] - 2026-10-17
|
|
9
17
|
|
|
10
18
|
### Fixed
|
package/README.md
CHANGED
|
@@ -95,10 +95,10 @@ The `cognitive-load` plugin draws the last hour's level above the prompt, with t
|
|
|
95
95
|
|
|
96
96
|
```
|
|
97
97
|
Heating 80 this hour, at the cap: 16 decisions and 13 context switches, 32 prompts, a 57m streak.
|
|
98
|
-
This week: 1 rest taken, 1 skipped (last: "prod is down, fixing it").
|
|
98
|
+
This week: 1 rest taken, 1 skipped (last: "prod is down, fixing it"), 4 skips left.
|
|
99
99
|
```
|
|
100
100
|
|
|
101
|
-
It also makes you rest. After 40 minutes of work without a ten-minute gap, or in a Fried hour, it holds your prompts for ten minutes. Each held prompt gets the next short idea for the break, the minutes left and the way out: `Stand up and stretch. 7 min left. Your prompt is back in the box: to send it, add "skip: <reason>" as its last line.` A `skip: <reason>` line at the start or the end of the prompt, the reason three words or more, lifts the rest.
|
|
101
|
+
It also makes you rest. After 40 minutes of work without a ten-minute gap, or in a Fried hour, it holds your prompts for ten minutes. Each held prompt gets the next short idea for the break, the minutes left and the way out: `Stand up and stretch. 7 min left. Your prompt is back in the box: to send it, add "skip: <reason>" as its last line.` A `skip: <reason>` line at the start or the end of the prompt, the reason three words or more, lifts the rest. You get five skips a calendar week, from Monday 00:00 local time. With none left, a skip gets `The powerbank is empty until Monday: 5 skips this week.` and the rest runs out on its own.
|
|
102
102
|
|
|
103
103
|
## Privacy
|
|
104
104
|
|
package/package.json
CHANGED
|
@@ -1,28 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakulavich/cogload",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "Keep your head cold. A thermometer for your Claude Code days: every hour scored 0 to 100 from the transcripts already on your disk. Nothing leaves your machine.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Anton Yakutovich",
|
|
7
|
-
"repository": {
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/drakulavich/cogload.git"
|
|
10
|
+
},
|
|
8
11
|
"homepage": "https://github.com/drakulavich/cogload#readme",
|
|
9
12
|
"bugs": "https://github.com/drakulavich/cogload/issues",
|
|
10
|
-
"keywords": [
|
|
13
|
+
"keywords": [
|
|
14
|
+
"claude-code",
|
|
15
|
+
"cognitive-load",
|
|
16
|
+
"developer-experience",
|
|
17
|
+
"cli",
|
|
18
|
+
"bun"
|
|
19
|
+
],
|
|
11
20
|
"type": "module",
|
|
12
|
-
"bin": {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
"
|
|
21
|
+
"bin": {
|
|
22
|
+
"cogload": "src/cli/index.ts"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"src/",
|
|
26
|
+
"assets/fonts/",
|
|
27
|
+
"assets/characters.webp",
|
|
28
|
+
"CHANGELOG.md",
|
|
29
|
+
"!src/**/*.test.ts"
|
|
30
|
+
],
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"engines": {
|
|
35
|
+
"bun": ">=1.4.4"
|
|
36
|
+
},
|
|
16
37
|
"scripts": {
|
|
17
38
|
"dev": "bun run src/cli/index.ts",
|
|
18
39
|
"stats": "bun scripts/signal-stats.ts",
|
|
19
40
|
"test": "TZ=UTC bun test --randomize ./tests",
|
|
20
41
|
"typecheck": "bun --check && bun scripts/typecheck-plugin.ts",
|
|
21
|
-
"
|
|
42
|
+
"fmt": "bun fmt",
|
|
43
|
+
"lint": "bun fmt --check && biome ci && knip --include files,exports,types",
|
|
22
44
|
"check": "bun run typecheck && bun run lint && bun run test"
|
|
23
45
|
},
|
|
24
46
|
"devDependencies": {
|
|
25
|
-
"@biomejs/biome": "2.
|
|
47
|
+
"@biomejs/biome": "2.6.3",
|
|
26
48
|
"@types/bun": "^1.4.0",
|
|
27
49
|
"knip": "^6.38.0"
|
|
28
50
|
}
|
package/src/cli/args.ts
CHANGED
|
@@ -27,7 +27,18 @@ levels: calm 0-29 warming 30-59 heating 60-84 fried 85-100
|
|
|
27
27
|
bugs, ideas and a star: github.com/drakulavich/cogload`;
|
|
28
28
|
export const HINT = "run 'cogload --help' for usage";
|
|
29
29
|
|
|
30
|
-
export type Args = {
|
|
30
|
+
export type Args = {
|
|
31
|
+
command: "grid" | "day" | "card" | "status";
|
|
32
|
+
to: string;
|
|
33
|
+
days: number;
|
|
34
|
+
explain: boolean;
|
|
35
|
+
json: boolean;
|
|
36
|
+
out: string | null;
|
|
37
|
+
projects: string;
|
|
38
|
+
color: boolean;
|
|
39
|
+
verbose: boolean;
|
|
40
|
+
cache: boolean;
|
|
41
|
+
};
|
|
31
42
|
|
|
32
43
|
export class UsageError extends Error {}
|
|
33
44
|
// Thrown only at a flag position, never for a token consumed as another flag's
|
|
@@ -61,7 +72,10 @@ function resolveDate(what: string, s: string, now: Date): string {
|
|
|
61
72
|
|
|
62
73
|
// UTC arithmetic, so a DST day is still one day.
|
|
63
74
|
function spanDays(from: string, to: string): number {
|
|
64
|
-
const utc = (s: string): number => {
|
|
75
|
+
const utc = (s: string): number => {
|
|
76
|
+
const [y = 0, m = 0, d = 0] = s.split("-").map(Number);
|
|
77
|
+
return Date.UTC(y, m - 1, d);
|
|
78
|
+
};
|
|
65
79
|
return Math.round((utc(to) - utc(from)) / 86_400_000) + 1;
|
|
66
80
|
}
|
|
67
81
|
|
|
@@ -79,7 +93,18 @@ function windowOf(days: string | null, from: string | null, to: string | null, d
|
|
|
79
93
|
}
|
|
80
94
|
|
|
81
95
|
export function parseArgs(argv: string[], now: Date, env: Record<string, string | undefined>, isTTY: boolean, projects: string): Args {
|
|
82
|
-
const a: Args = {
|
|
96
|
+
const a: Args = {
|
|
97
|
+
command: "grid",
|
|
98
|
+
to: localDate(now),
|
|
99
|
+
days: 7,
|
|
100
|
+
explain: false,
|
|
101
|
+
json: false,
|
|
102
|
+
out: null,
|
|
103
|
+
projects,
|
|
104
|
+
color: isTTY && !env.NO_COLOR,
|
|
105
|
+
verbose: false,
|
|
106
|
+
cache: true,
|
|
107
|
+
};
|
|
83
108
|
let days: string | null = null;
|
|
84
109
|
let from: string | null = null;
|
|
85
110
|
let to: string | null = null;
|
|
@@ -91,8 +116,13 @@ export function parseArgs(argv: string[], now: Date, env: Record<string, string
|
|
|
91
116
|
let arg = argv[i]!;
|
|
92
117
|
let inline: string | null = null;
|
|
93
118
|
const eq = arg.startsWith("--") ? arg.indexOf("=") : -1;
|
|
94
|
-
if (eq > 0) {
|
|
95
|
-
|
|
119
|
+
if (eq > 0) {
|
|
120
|
+
inline = arg.slice(eq + 1);
|
|
121
|
+
arg = arg.slice(0, eq);
|
|
122
|
+
}
|
|
123
|
+
const bare = (): void => {
|
|
124
|
+
if (inline !== null) throw new UsageError(`unknown flag${named(argv[i]!)}`);
|
|
125
|
+
};
|
|
96
126
|
// A value that looks like another flag is a usage error (`--projects --json`),
|
|
97
127
|
// and so is an empty one (`--projects=`); only --days accepts a negative
|
|
98
128
|
// number, so `--days -1` reaches the range check.
|
|
@@ -111,19 +141,48 @@ export function parseArgs(argv: string[], now: Date, env: Record<string, string
|
|
|
111
141
|
};
|
|
112
142
|
switch (arg) {
|
|
113
143
|
case "--help":
|
|
114
|
-
case "-h":
|
|
144
|
+
case "-h":
|
|
145
|
+
bare();
|
|
146
|
+
throw new HelpRequested();
|
|
115
147
|
case "--version":
|
|
116
|
-
case "-V":
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
case "--
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
case "--
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
148
|
+
case "-V":
|
|
149
|
+
bare();
|
|
150
|
+
throw new VersionRequested();
|
|
151
|
+
case "--json":
|
|
152
|
+
bare();
|
|
153
|
+
jsonFlag = true;
|
|
154
|
+
break;
|
|
155
|
+
case "--explain":
|
|
156
|
+
bare();
|
|
157
|
+
a.explain = true;
|
|
158
|
+
break;
|
|
159
|
+
case "--no-color":
|
|
160
|
+
bare();
|
|
161
|
+
a.color = false;
|
|
162
|
+
break;
|
|
163
|
+
case "--verbose":
|
|
164
|
+
bare();
|
|
165
|
+
a.verbose = true;
|
|
166
|
+
break;
|
|
167
|
+
case "--no-cache":
|
|
168
|
+
bare();
|
|
169
|
+
a.cache = false;
|
|
170
|
+
break;
|
|
171
|
+
case "--projects":
|
|
172
|
+
a.projects = value();
|
|
173
|
+
break;
|
|
174
|
+
case "--from":
|
|
175
|
+
from = value();
|
|
176
|
+
break;
|
|
177
|
+
case "--to":
|
|
178
|
+
to = value();
|
|
179
|
+
break;
|
|
180
|
+
case "--days":
|
|
181
|
+
days = value(true);
|
|
182
|
+
break;
|
|
183
|
+
case "--out":
|
|
184
|
+
a.out = value();
|
|
185
|
+
break;
|
|
127
186
|
default:
|
|
128
187
|
if (arg.startsWith("-")) throw new UsageError(`unknown flag${named(arg)}`);
|
|
129
188
|
positional.push(arg);
|
|
@@ -133,12 +192,19 @@ export function parseArgs(argv: string[], now: Date, env: Record<string, string
|
|
|
133
192
|
const [word] = positional;
|
|
134
193
|
if (word === undefined) a.command = "grid";
|
|
135
194
|
else if (word === "card") a.command = "card";
|
|
136
|
-
else if (word === "status") {
|
|
137
|
-
|
|
138
|
-
|
|
195
|
+
else if (word === "status") {
|
|
196
|
+
a.command = "status";
|
|
197
|
+
a.to = localDate(now);
|
|
198
|
+
a.days = 1;
|
|
199
|
+
} else if (word === "today" || word === "yesterday" || DATE.test(word)) {
|
|
200
|
+
a.command = "day";
|
|
201
|
+
a.to = resolveDate("date", word, now);
|
|
202
|
+
a.days = 1;
|
|
203
|
+
} else throw new UsageError(`unknown command${named(word)} (try today, yesterday, a date, card or status)`);
|
|
139
204
|
|
|
140
205
|
if (a.command === "day" || a.command === "status") {
|
|
141
|
-
if (days !== null || from !== null || to !== null)
|
|
206
|
+
if (days !== null || from !== null || to !== null)
|
|
207
|
+
throw new UsageError(`--days, --from and --to do not apply to ${a.command === "day" ? "a named day" : "status"}`);
|
|
142
208
|
} else {
|
|
143
209
|
({ to: a.to, days: a.days } = windowOf(days, from, to, a.command === "card" ? 14 : 7, now));
|
|
144
210
|
}
|
package/src/cli/commands.io.ts
CHANGED
|
@@ -34,22 +34,35 @@ function cardTarget(out: string | null): { path: string; label: string; unwritab
|
|
|
34
34
|
if (out !== null) return { path: out, label: basename(out) };
|
|
35
35
|
const dir = join(homedir(), "Downloads");
|
|
36
36
|
let isDir = false;
|
|
37
|
-
try {
|
|
37
|
+
try {
|
|
38
|
+
isDir = statSync(dir).isDirectory();
|
|
39
|
+
} catch {}
|
|
38
40
|
if (!isDir) throw new Error("no Downloads folder: pass --out <path>");
|
|
39
|
-
return {
|
|
41
|
+
return {
|
|
42
|
+
path: join(dir, "cogload-card.png"),
|
|
43
|
+
label: "cogload-card.png to Downloads",
|
|
44
|
+
unwritable: "cannot write cogload-card.png to Downloads: pass --out <path>",
|
|
45
|
+
};
|
|
40
46
|
}
|
|
41
47
|
|
|
42
48
|
// Keys pressed while the card was drawn answer no question yet asked, so the
|
|
43
49
|
// terminal's pending input is dropped first: tcflush(0, TCIFLUSH). Best effort,
|
|
44
50
|
// where libc can be found; elsewhere the question reads as before.
|
|
45
|
-
const TCIFLUSH: Partial<Record<NodeJS.Platform, { lib: string; queue: number }>> = {
|
|
51
|
+
const TCIFLUSH: Partial<Record<NodeJS.Platform, { lib: string; queue: number }>> = {
|
|
52
|
+
darwin: { lib: "libSystem.B.dylib", queue: 1 },
|
|
53
|
+
linux: { lib: "libc.so.6", queue: 0 },
|
|
54
|
+
};
|
|
46
55
|
async function discardTypedInput(): Promise<void> {
|
|
47
56
|
const c = TCIFLUSH[process.platform];
|
|
48
57
|
if (!c) return;
|
|
49
58
|
try {
|
|
50
59
|
const { dlopen, FFIType } = await import("bun:ffi");
|
|
51
60
|
const libc = dlopen(c.lib, { tcflush: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } });
|
|
52
|
-
try {
|
|
61
|
+
try {
|
|
62
|
+
libc.symbols.tcflush(0, c.queue);
|
|
63
|
+
} finally {
|
|
64
|
+
libc.close();
|
|
65
|
+
}
|
|
53
66
|
} catch {}
|
|
54
67
|
}
|
|
55
68
|
|
|
@@ -57,17 +70,32 @@ export async function card(a: Args, now: Date, cache: TranscriptCache | null, ti
|
|
|
57
70
|
const days: Day[] = await report({ projects: a.projects, to: a.to, days: a.days, now }, timing, cache);
|
|
58
71
|
const data = cardData(days, { days: a.days });
|
|
59
72
|
// A script asking for the data gets a document either way; a picture of nothing is an error.
|
|
60
|
-
if (data === null && a.json) {
|
|
73
|
+
if (data === null && a.json) {
|
|
74
|
+
console.log("null");
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
61
77
|
const from = days[0]!.date;
|
|
62
78
|
const to = days[days.length - 1]!.date;
|
|
63
79
|
if (data === null) throw new Error(from === to ? `no activity on ${to}` : `no activity from ${from} to ${to}`);
|
|
64
80
|
if (a.json) {
|
|
65
81
|
const round2 = (x: number): number => Math.round(x * 100) / 100;
|
|
66
82
|
const json = {
|
|
67
|
-
from,
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
83
|
+
from,
|
|
84
|
+
to,
|
|
85
|
+
days: data.days,
|
|
86
|
+
character: data.character,
|
|
87
|
+
name: data.name,
|
|
88
|
+
sentence: sentenceText(data.sentence),
|
|
89
|
+
motto: data.motto,
|
|
90
|
+
shares: {
|
|
91
|
+
conductor: round2(data.shares.conductor),
|
|
92
|
+
supervisor: round2(data.shares.supervisor),
|
|
93
|
+
marathoner: round2(data.shares.marathoner),
|
|
94
|
+
nightOwl: round2(data.shares.nightOwl),
|
|
95
|
+
},
|
|
96
|
+
peak: data.peak,
|
|
97
|
+
spectrum: data.spectrum,
|
|
98
|
+
highlights: data.highlights,
|
|
71
99
|
};
|
|
72
100
|
console.log(JSON.stringify(json, null, 2));
|
|
73
101
|
return 0;
|
|
@@ -85,14 +113,21 @@ export async function card(a: Args, now: Date, cache: TranscriptCache | null, ti
|
|
|
85
113
|
} finally {
|
|
86
114
|
if (note) process.stderr.write("\r\x1b[K");
|
|
87
115
|
}
|
|
88
|
-
if (timing)
|
|
116
|
+
if (timing)
|
|
117
|
+
timing.render = {
|
|
118
|
+
format: target.path.slice(target.path.lastIndexOf(".") + 1).toLowerCase(),
|
|
119
|
+
ms: performance.now() - t,
|
|
120
|
+
};
|
|
89
121
|
console.log(`${data.name}: ${sentenceText(data.sentence)}\nwrote ${target.label}`);
|
|
90
122
|
if (timing) timing.totalMs = performance.now(); // the wait for an answer is not cogload's time
|
|
91
123
|
if (process.stdin.isTTY && process.stdout.isTTY && process.platform !== "win32") {
|
|
92
124
|
await discardTypedInput();
|
|
93
125
|
process.stdout.write("open it? [Y/n] ");
|
|
94
126
|
let answer: string | null = null;
|
|
95
|
-
for await (const line of console) {
|
|
127
|
+
for await (const line of console) {
|
|
128
|
+
answer = line;
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
96
131
|
if (answer !== null && /^(y|yes)?$/i.test(answer.trim())) openCard(target.path);
|
|
97
132
|
}
|
|
98
133
|
return 0;
|
package/src/cli/index.ts
CHANGED
|
@@ -20,8 +20,17 @@ function version(): string {
|
|
|
20
20
|
|
|
21
21
|
function runEnv() {
|
|
22
22
|
let ver = "?";
|
|
23
|
-
try {
|
|
24
|
-
|
|
23
|
+
try {
|
|
24
|
+
ver = version();
|
|
25
|
+
} catch {}
|
|
26
|
+
return {
|
|
27
|
+
version: ver,
|
|
28
|
+
bun: Bun.version,
|
|
29
|
+
platform: process.platform,
|
|
30
|
+
arch: process.arch,
|
|
31
|
+
cpus: cpus().length,
|
|
32
|
+
nowMs: performance.now(),
|
|
33
|
+
};
|
|
25
34
|
}
|
|
26
35
|
|
|
27
36
|
async function main(): Promise<number> {
|
|
@@ -33,7 +42,12 @@ async function main(): Promise<number> {
|
|
|
33
42
|
const cache = a.cache ? openCache(process.env) : null;
|
|
34
43
|
if (timing && a.cache) timing.openMs = performance.now() - t;
|
|
35
44
|
try {
|
|
36
|
-
const code =
|
|
45
|
+
const code =
|
|
46
|
+
a.command === "card"
|
|
47
|
+
? await card(a, now, cache, timing)
|
|
48
|
+
: a.command === "status"
|
|
49
|
+
? await status(a, now, cache, timing)
|
|
50
|
+
: await table(a, now, cache, timing);
|
|
37
51
|
if (timing) process.stderr.write(timingLines(timing, runEnv()));
|
|
38
52
|
return code;
|
|
39
53
|
} finally {
|
|
@@ -47,17 +61,33 @@ export function start(): void {
|
|
|
47
61
|
throw e;
|
|
48
62
|
});
|
|
49
63
|
// exitCode, not exit(): exit() drops output still queued for a pipe.
|
|
50
|
-
main().then(
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
64
|
+
main().then(
|
|
65
|
+
(code) => {
|
|
66
|
+
process.exitCode = code;
|
|
67
|
+
},
|
|
68
|
+
(e: unknown) => {
|
|
69
|
+
if (e instanceof HelpRequested) {
|
|
70
|
+
console.log(USAGE);
|
|
71
|
+
process.exit(0);
|
|
72
|
+
}
|
|
73
|
+
if (e instanceof VersionRequested) {
|
|
74
|
+
try {
|
|
75
|
+
console.log(version());
|
|
76
|
+
process.exit(0);
|
|
77
|
+
} catch (err) {
|
|
78
|
+
console.error(`cogload: ${err instanceof Error ? err.message : String(err)}`);
|
|
79
|
+
process.exit(1);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
83
|
+
if (e instanceof UsageError) {
|
|
84
|
+
console.error(`cogload: ${msg}\n${HINT}`);
|
|
85
|
+
process.exit(2);
|
|
86
|
+
}
|
|
87
|
+
console.error(`cogload: ${msg}`);
|
|
88
|
+
process.exit(1);
|
|
89
|
+
},
|
|
90
|
+
);
|
|
61
91
|
}
|
|
62
92
|
|
|
63
93
|
if (import.meta.main) start();
|
package/src/cli/timing.ts
CHANGED
|
@@ -4,15 +4,21 @@ import { READERS, type Timing } from "../lib/report/index.ts";
|
|
|
4
4
|
export function timingLines(t: Timing, env: { version: string; bun: string; platform: string; arch: string; cpus: number; nowMs: number }): string {
|
|
5
5
|
const row = (label: string, what: string, ms: number) => `${label.padEnd(8)}${what.padEnd(44)}${String(Math.round(ms)).padStart(7)} ms\n`;
|
|
6
6
|
const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
7
|
-
return
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
7
|
+
return (
|
|
8
|
+
`cogload ${env.version} · bun ${env.bun} · ${env.platform} ${env.arch} · ${env.cpus} cpus\n` +
|
|
9
|
+
row("start", "bun, modules, arguments", t.startMs ?? 0) +
|
|
10
|
+
(t.openMs !== undefined ? row("open", "cache", t.openMs) : "") +
|
|
11
|
+
row(
|
|
12
|
+
"scan",
|
|
13
|
+
`${plural(t.files, "file")}, ${t.inWindow} in window, ${plural(t.tailChecks, "tail check")}${t.skipped ? `, ${t.skipped} unreadable skipped` : ""}`,
|
|
14
|
+
t.scanMs,
|
|
15
|
+
) +
|
|
16
|
+
(t.cache ? row("cache", `${plural(t.cache.hits, "hit")}, ${plural(t.cache.misses, "miss", "misses")}`, t.lookupMs) : `${"cache".padEnd(8)}off\n`) +
|
|
17
|
+
row("read", `${plural(t.read, "file")}, ${(t.bytes / 1e6).toFixed(1)} MB, ${READERS} at a time`, t.readMs) +
|
|
18
|
+
row("analyze", "", t.analyzeMs) +
|
|
19
|
+
(t.cache ? row("save", "cache", t.saveMs) : "") +
|
|
20
|
+
(t.render ? row("render", t.render.format, t.render.ms) : "") +
|
|
21
|
+
(t.writeMs !== undefined ? row("write", "status file", t.writeMs) : "") +
|
|
22
|
+
row("total", "", t.totalMs ?? env.nowMs)
|
|
23
|
+
);
|
|
18
24
|
}
|
package/src/lib/card/card.ts
CHANGED
|
@@ -24,7 +24,10 @@ export type CardData = {
|
|
|
24
24
|
// Tie order: the first of equal shares wins.
|
|
25
25
|
const CHARACTERS: readonly Character[] = ["conductor", "supervisor", "marathoner", "nightOwl"];
|
|
26
26
|
const NAMES: Record<Character, string> = {
|
|
27
|
-
conductor: "The Conductor",
|
|
27
|
+
conductor: "The Conductor",
|
|
28
|
+
supervisor: "The Supervisor",
|
|
29
|
+
marathoner: "The Marathoner",
|
|
30
|
+
nightOwl: "The Night Owl",
|
|
28
31
|
};
|
|
29
32
|
const MOTTOS: Record<Character, string> = {
|
|
30
33
|
conductor: "You run agents like an orchestra.",
|
|
@@ -121,9 +124,20 @@ export function cardData(days: Day[], w: { days: number }): CardData | null {
|
|
|
121
124
|
const spectrum = spectrumOf([count("Calm"), count("Warming"), count("Heating"), count("Fried")], n);
|
|
122
125
|
|
|
123
126
|
const sentences: Record<Character, Segment[]> = {
|
|
124
|
-
conductor: [
|
|
127
|
+
conductor: [
|
|
128
|
+
strong(plural(maxSessions, "session")),
|
|
129
|
+
plain(" at once, "),
|
|
130
|
+
strong(plural(maxSwitches, "context switch", "context switches")),
|
|
131
|
+
plain(" in one hour."),
|
|
132
|
+
],
|
|
125
133
|
supervisor: [strong(plural(reports, "agent report")), plain(" and "), strong(plural(tokens, "token", "tokens", formatTokens)), plain(" of output read.")],
|
|
126
|
-
marathoner: [
|
|
134
|
+
marathoner: [
|
|
135
|
+
plain("Longest streak "),
|
|
136
|
+
strong(formatStreak(maxStreak)),
|
|
137
|
+
plain(" without a break, "),
|
|
138
|
+
strong(`${spectrum.calm}%`),
|
|
139
|
+
plain(" of your hours calm."),
|
|
140
|
+
],
|
|
127
141
|
nightOwl: [strong(`${late}%`), plain(" of your hours "), strong("late at night"), plain(".")],
|
|
128
142
|
};
|
|
129
143
|
|
|
@@ -156,7 +170,11 @@ export function cardData(days: Day[], w: { days: number }): CardData | null {
|
|
|
156
170
|
// character's own number and always shows, so the row is never empty.
|
|
157
171
|
const [first, second] = owned;
|
|
158
172
|
const keys = [first, ...[second, third].filter((k) => norms[k] > 0)];
|
|
159
|
-
const highlights = keys.map((key) => ({
|
|
173
|
+
const highlights = keys.map((key) => ({
|
|
174
|
+
key,
|
|
175
|
+
value: values[key],
|
|
176
|
+
caption: CAPTIONS[key][values[key] === "1" ? 0 : 1],
|
|
177
|
+
}));
|
|
160
178
|
|
|
161
179
|
return {
|
|
162
180
|
days: w.days,
|
package/src/lib/card/cardhtml.ts
CHANGED
|
@@ -14,7 +14,7 @@ export type CardAssets = {
|
|
|
14
14
|
const CHARACTER_RECTS: Record<Character, [number, number, number, number]> = {
|
|
15
15
|
conductor: [0.02, 0.01, 0.53, 0.543],
|
|
16
16
|
supervisor: [0.55, 0.07, 0.38, 0.505],
|
|
17
|
-
marathoner: [0.02, 0.553, 0.
|
|
17
|
+
marathoner: [0.02, 0.553, 0.5, 0.437],
|
|
18
18
|
nightOwl: [0.54, 0.585, 0.45, 0.41],
|
|
19
19
|
};
|
|
20
20
|
const BOX = 360;
|
|
@@ -51,7 +51,10 @@ export function cardHtml(card: CardData, assets: CardAssets): string {
|
|
|
51
51
|
["heat", card.spectrum.heating, "heating"],
|
|
52
52
|
["fried", card.spectrum.fried, "fried"],
|
|
53
53
|
] as const;
|
|
54
|
-
const bar = levels
|
|
54
|
+
const bar = levels
|
|
55
|
+
.filter(([, pct]) => pct > 0)
|
|
56
|
+
.map(([cls, pct]) => `<div class="${cls}" style="width:${pct}%"></div>`)
|
|
57
|
+
.join("");
|
|
55
58
|
const legend = levels.map(([cls, pct, name]) => `<span><i class="${cls}"></i><b>${pct}%</b> ${name}</span>`).join(" ");
|
|
56
59
|
const stats = card.highlights
|
|
57
60
|
.map((h) => `<div class="stat" data-key="${h.key}"><div class="v">${h.value}</div><div class="c mono">${h.caption}</div></div>`)
|
package/src/lib/card/image.io.ts
CHANGED
|
@@ -20,7 +20,10 @@ export async function loadAssets(): Promise<CardAssets> {
|
|
|
20
20
|
}
|
|
21
21
|
const [inter400, inter700, inter800, mono500, characters] = parts;
|
|
22
22
|
if (parts.some((p) => p.length === 0)) throw new Error("assets missing: reinstall cogload");
|
|
23
|
-
return {
|
|
23
|
+
return {
|
|
24
|
+
fonts: { inter400: inter400!, inter700: inter700!, inter800: inter800!, mono500: mono500! },
|
|
25
|
+
characters: characters!,
|
|
26
|
+
};
|
|
24
27
|
}
|
|
25
28
|
|
|
26
29
|
const BACKEND = process.platform === "darwin" ? "webkit" : "chrome";
|
|
@@ -28,7 +31,9 @@ const ENGINE_LINE = "card needs a browser engine: install a Chromium browser suc
|
|
|
28
31
|
// Thrown for a card that cannot be written, so the caller can name the place it
|
|
29
32
|
// chose; the message is the line for an --out the person gave.
|
|
30
33
|
export class CardWriteError extends Error {
|
|
31
|
-
constructor() {
|
|
34
|
+
constructor() {
|
|
35
|
+
super("cannot write the card: check the --out directory");
|
|
36
|
+
}
|
|
32
37
|
}
|
|
33
38
|
const TEMP_LINE = "cannot draw the card: the temporary directory is not writable";
|
|
34
39
|
const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"] as const;
|
|
@@ -46,7 +51,9 @@ export async function renderCard(html: string, out: string, timeoutMs = 15_000):
|
|
|
46
51
|
await write(out, html);
|
|
47
52
|
return;
|
|
48
53
|
}
|
|
49
|
-
const dir = await mkdtemp(join(tmpdir(), "cogload-card-")).catch(() => {
|
|
54
|
+
const dir = await mkdtemp(join(tmpdir(), "cogload-card-")).catch(() => {
|
|
55
|
+
throw new Error(TEMP_LINE);
|
|
56
|
+
});
|
|
50
57
|
// Ctrl-C (or a hangup, or kill) mid-render would skip the finally below and
|
|
51
58
|
// leave the page behind: remove it, then end as the signal would have.
|
|
52
59
|
const onSignal = (signal: NodeJS.Signals): void => {
|
|
@@ -57,8 +64,12 @@ export async function renderCard(html: string, out: string, timeoutMs = 15_000):
|
|
|
57
64
|
let bytes: Uint8Array | null;
|
|
58
65
|
try {
|
|
59
66
|
const page = join(dir, "card.html");
|
|
60
|
-
await writeFile(page, html, { mode: 0o600 }).catch(() => {
|
|
61
|
-
|
|
67
|
+
await writeFile(page, html, { mode: 0o600 }).catch(() => {
|
|
68
|
+
throw new Error(TEMP_LINE);
|
|
69
|
+
});
|
|
70
|
+
bytes = await shoot(pathToFileURL(page).href, lower.endsWith(".webp"), timeoutMs).catch(() => {
|
|
71
|
+
throw new Error(ENGINE_LINE);
|
|
72
|
+
});
|
|
62
73
|
} finally {
|
|
63
74
|
// The handlers stay until the page is gone: a signal during this rm still cleans up.
|
|
64
75
|
await rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
@@ -93,7 +104,12 @@ async function shoot(url: string, webp: boolean, ms: number): Promise<Uint8Array
|
|
|
93
104
|
// After the deadline closes the view, the calls still pending on it may reject.
|
|
94
105
|
work.catch(() => {});
|
|
95
106
|
try {
|
|
96
|
-
return await Promise.race([
|
|
107
|
+
return await Promise.race([
|
|
108
|
+
work,
|
|
109
|
+
new Promise<null>((done) => {
|
|
110
|
+
timer = setTimeout(() => done(null), ms);
|
|
111
|
+
}),
|
|
112
|
+
]);
|
|
97
113
|
} finally {
|
|
98
114
|
clearTimeout(timer);
|
|
99
115
|
view.close();
|
|
@@ -111,7 +127,11 @@ async function write(out: string, data: string | Uint8Array): Promise<void> {
|
|
|
111
127
|
try {
|
|
112
128
|
const handle = await open(tmp, "wx");
|
|
113
129
|
created = true;
|
|
114
|
-
try {
|
|
130
|
+
try {
|
|
131
|
+
await handle.writeFile(data);
|
|
132
|
+
} finally {
|
|
133
|
+
await handle.close();
|
|
134
|
+
}
|
|
115
135
|
await rename(tmp, out);
|
|
116
136
|
} catch {
|
|
117
137
|
if (created) await unlink(tmp).catch(() => {});
|
|
@@ -129,6 +149,10 @@ export function openCard(path: string): void {
|
|
|
129
149
|
// terminal cogload leads, dies with cogload. A program that fails to start is ignored.
|
|
130
150
|
function startInBackground(command: string[]): void {
|
|
131
151
|
try {
|
|
132
|
-
Bun.spawnSync(["sh", "-c", 'trap "" HUP; "$0" "$@" </dev/null >/dev/null 2>&1 &', ...command], {
|
|
152
|
+
Bun.spawnSync(["sh", "-c", 'trap "" HUP; "$0" "$@" </dev/null >/dev/null 2>&1 &', ...command], {
|
|
153
|
+
stdin: "ignore",
|
|
154
|
+
stdout: "ignore",
|
|
155
|
+
stderr: "ignore",
|
|
156
|
+
});
|
|
133
157
|
} catch {}
|
|
134
158
|
}
|
|
@@ -5,9 +5,7 @@ import type { Day, Event, Transcript, Window } from "../types.ts";
|
|
|
5
5
|
// Sorted by path so file discovery order cannot change a result.
|
|
6
6
|
export function analyze(transcripts: Transcript[], w: Window): Day[] {
|
|
7
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));
|
|
8
|
+
const events = [...transcripts].sort((a, b) => compareStrings(a.path, b.path)).flatMap((t) => parseTranscript(t.text, cutoffMs));
|
|
11
9
|
return analyzeEvents(events, w);
|
|
12
10
|
}
|
|
13
11
|
|
|
@@ -37,16 +37,42 @@ export function windowBounds(w: Window): { startMs: number; endMs: number; cutof
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
const emptyMetrics = (): Metrics => ({
|
|
40
|
-
sessions: 0,
|
|
41
|
-
|
|
40
|
+
sessions: 0,
|
|
41
|
+
prompts: 0,
|
|
42
|
+
reports: 0,
|
|
43
|
+
outputTokens: 0,
|
|
44
|
+
interrupts: 0,
|
|
45
|
+
rejects: 0,
|
|
46
|
+
questions: 0,
|
|
47
|
+
plans: 0,
|
|
48
|
+
modeSwitches: 0,
|
|
49
|
+
decisions: 0,
|
|
50
|
+
contextSwitches: 0,
|
|
51
|
+
activeMin: 0,
|
|
52
|
+
streakMin: 0,
|
|
53
|
+
lateNight: false,
|
|
42
54
|
});
|
|
43
55
|
|
|
44
56
|
// Presence is the human's own actions only: agent records and the agent's asks
|
|
45
57
|
// are never presence, because presence answers "is it time to rest?".
|
|
46
58
|
const PRESENCE: ReadonlySet<EventKind> = new Set<EventKind>(["prompt", "interrupt", "reject", "answer"]);
|
|
47
59
|
|
|
48
|
-
type Acc = {
|
|
49
|
-
|
|
60
|
+
type Acc = {
|
|
61
|
+
m: Metrics;
|
|
62
|
+
sessions: Set<string>;
|
|
63
|
+
slots: Set<number>;
|
|
64
|
+
lastPromptSession: string | null;
|
|
65
|
+
maxStreakMs: number;
|
|
66
|
+
lastPresence: { ts: number; streakStart: number } | null;
|
|
67
|
+
};
|
|
68
|
+
const newAcc = (): Acc => ({
|
|
69
|
+
m: emptyMetrics(),
|
|
70
|
+
sessions: new Set(),
|
|
71
|
+
slots: new Set(),
|
|
72
|
+
lastPromptSession: null,
|
|
73
|
+
maxStreakMs: 0,
|
|
74
|
+
lastPresence: null,
|
|
75
|
+
});
|
|
50
76
|
|
|
51
77
|
// Inside a streak the human sat through the gap, so a pair of actions covers
|
|
52
78
|
// every slot between them; an action that starts a streak covers only its own.
|
|
@@ -74,13 +100,27 @@ function accumulate(a: Acc, e: Event, streakStart: number): void {
|
|
|
74
100
|
if (a.lastPromptSession !== null && a.lastPromptSession !== e.sessionId) a.m.contextSwitches++;
|
|
75
101
|
a.lastPromptSession = e.sessionId;
|
|
76
102
|
break;
|
|
77
|
-
case "report":
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
case "
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
case "
|
|
103
|
+
case "report":
|
|
104
|
+
a.m.reports++;
|
|
105
|
+
break;
|
|
106
|
+
case "output":
|
|
107
|
+
a.m.outputTokens += e.tokens ?? 0;
|
|
108
|
+
break;
|
|
109
|
+
case "interrupt":
|
|
110
|
+
a.m.interrupts++;
|
|
111
|
+
break;
|
|
112
|
+
case "reject":
|
|
113
|
+
a.m.rejects++;
|
|
114
|
+
break;
|
|
115
|
+
case "question":
|
|
116
|
+
a.m.questions++;
|
|
117
|
+
break;
|
|
118
|
+
case "plan_review":
|
|
119
|
+
a.m.plans++;
|
|
120
|
+
break;
|
|
121
|
+
case "mode_change":
|
|
122
|
+
a.m.modeSwitches++;
|
|
123
|
+
break;
|
|
84
124
|
}
|
|
85
125
|
}
|
|
86
126
|
|
|
@@ -107,7 +147,10 @@ function foldEvents(sorted: Event[], startMs: number): { acc: Map<string, Acc>;
|
|
|
107
147
|
};
|
|
108
148
|
const get = (k: string): Acc => {
|
|
109
149
|
let a = acc.get(k);
|
|
110
|
-
if (!a) {
|
|
150
|
+
if (!a) {
|
|
151
|
+
a = newAcc();
|
|
152
|
+
acc.set(k, a);
|
|
153
|
+
}
|
|
111
154
|
return a;
|
|
112
155
|
};
|
|
113
156
|
|
|
@@ -184,19 +227,43 @@ function buildDay(date: string, acc: Map<string, Acc>): Day {
|
|
|
184
227
|
buckets.push({ ...finish(a ?? newAcc(), LATE_HOURS.has(hour)), hour });
|
|
185
228
|
}
|
|
186
229
|
const scored = buckets.filter((b) => b.score !== null);
|
|
187
|
-
const totals: Totals = buckets.reduce(
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
230
|
+
const totals: Totals = buckets.reduce(
|
|
231
|
+
(t, b) => ({
|
|
232
|
+
prompts: t.prompts + b.prompts,
|
|
233
|
+
reports: t.reports + b.reports,
|
|
234
|
+
outputTokens: t.outputTokens + b.outputTokens,
|
|
235
|
+
interrupts: t.interrupts + b.interrupts,
|
|
236
|
+
rejects: t.rejects + b.rejects,
|
|
237
|
+
questions: t.questions + b.questions,
|
|
238
|
+
plans: t.plans + b.plans,
|
|
239
|
+
modeSwitches: t.modeSwitches + b.modeSwitches,
|
|
240
|
+
decisions: t.decisions + b.decisions,
|
|
241
|
+
contextSwitches: t.contextSwitches + b.contextSwitches,
|
|
242
|
+
maxSessions: Math.max(t.maxSessions, b.sessions),
|
|
243
|
+
}),
|
|
244
|
+
{
|
|
245
|
+
prompts: 0,
|
|
246
|
+
reports: 0,
|
|
247
|
+
outputTokens: 0,
|
|
248
|
+
interrupts: 0,
|
|
249
|
+
rejects: 0,
|
|
250
|
+
questions: 0,
|
|
251
|
+
plans: 0,
|
|
252
|
+
modeSwitches: 0,
|
|
253
|
+
decisions: 0,
|
|
254
|
+
contextSwitches: 0,
|
|
255
|
+
maxSessions: 0,
|
|
256
|
+
},
|
|
257
|
+
);
|
|
194
258
|
return {
|
|
195
259
|
date,
|
|
196
260
|
peak: scored.length ? Math.max(...scored.map((b) => b.score!.index)) : null,
|
|
197
261
|
mean: scored.length ? Math.round(scored.reduce((s, b) => s + b.score!.index, 0) / scored.length) : null,
|
|
198
262
|
activeMin: buckets.reduce((s, b) => s + b.activeMin, 0),
|
|
199
|
-
presence: lastPresence && {
|
|
263
|
+
presence: lastPresence && {
|
|
264
|
+
lastAt: new Date(lastPresence.ts).toISOString(),
|
|
265
|
+
streakStartAt: new Date(lastPresence.streakStart).toISOString(),
|
|
266
|
+
},
|
|
200
267
|
totals,
|
|
201
268
|
buckets,
|
|
202
269
|
};
|
|
@@ -226,7 +293,10 @@ export function derive(events: Event[], w: Window): Day[] {
|
|
|
226
293
|
// and only into `presence`: no bucket, total or active minute crosses back.
|
|
227
294
|
const first = days[0];
|
|
228
295
|
if (first && first.presence === null && carried) {
|
|
229
|
-
first.presence = {
|
|
296
|
+
first.presence = {
|
|
297
|
+
lastAt: new Date(carried.ts).toISOString(),
|
|
298
|
+
streakStartAt: new Date(carried.streakStart).toISOString(),
|
|
299
|
+
};
|
|
230
300
|
}
|
|
231
301
|
for (const d of days) {
|
|
232
302
|
if (d.presence) d.presence.streakStartAt = new Date(traceBack(Date.parse(d.presence.streakStartAt), earlier)).toISOString();
|
package/src/lib/metrics/score.ts
CHANGED
|
@@ -3,7 +3,15 @@ import type { Level, Metrics, Part, Parts, Score } from "../types.ts";
|
|
|
3
3
|
// Calibration lives here and nowhere else. Integer points of 100, so 0.5 sums
|
|
4
4
|
// stay exact; norms are the p90 of two weeks on two machines (see CHANGELOG).
|
|
5
5
|
export const WEIGHTS = { parallel: 25, pace: 15, supervision: 30, reading: 10, streak: 10, late: 10 } as const;
|
|
6
|
-
export const NORMS = {
|
|
6
|
+
export const NORMS = {
|
|
7
|
+
parallelSpan: 4,
|
|
8
|
+
pacePerHour: 20,
|
|
9
|
+
supervisionPerHour: 45,
|
|
10
|
+
decisionWeight: 3,
|
|
11
|
+
readingTokens: 80_000,
|
|
12
|
+
streakMin: 40,
|
|
13
|
+
coolMin: 20,
|
|
14
|
+
} as const;
|
|
7
15
|
const LEVELS: readonly { max: number; level: Level }[] = [
|
|
8
16
|
{ max: 29, level: "Calm" },
|
|
9
17
|
{ max: 59, level: "Warming" },
|
|
@@ -30,9 +38,7 @@ export function fractionsOf(m: Metrics): Fractions {
|
|
|
30
38
|
const parallel = clamp01((m.sessions - 1) / NORMS.parallelSpan);
|
|
31
39
|
const pace = clamp01(m.prompts / NORMS.pacePerHour);
|
|
32
40
|
// A decision costs `decisionWeight` reports or session hops; the three share a norm.
|
|
33
|
-
const supervision = clamp01(
|
|
34
|
-
(NORMS.decisionWeight * m.decisions + m.reports + m.contextSwitches) / NORMS.supervisionPerHour,
|
|
35
|
-
);
|
|
41
|
+
const supervision = clamp01((NORMS.decisionWeight * m.decisions + m.reports + m.contextSwitches) / NORMS.supervisionPerHour);
|
|
36
42
|
const reading = clamp01(m.outputTokens / NORMS.readingTokens);
|
|
37
43
|
const streak = clamp01(m.streakMin / NORMS.streakMin);
|
|
38
44
|
const late = m.lateNight ? 1 : 0;
|
|
@@ -62,8 +68,6 @@ export function scoreOf(fractions: Fractions): Score {
|
|
|
62
68
|
late: Math.round(raw.late * 10) / 10,
|
|
63
69
|
};
|
|
64
70
|
// Rounded once from the raw points, so parts' rounding can never tip it across a boundary.
|
|
65
|
-
const index = Math.round(
|
|
66
|
-
raw.parallel + raw.pace + raw.supervision + raw.reading + raw.streak + raw.late,
|
|
67
|
-
);
|
|
71
|
+
const index = Math.round(raw.parallel + raw.pace + raw.supervision + raw.reading + raw.streak + raw.late);
|
|
68
72
|
return { index, level: levelOf(index), parts, capped, top };
|
|
69
73
|
}
|
|
@@ -6,7 +6,22 @@ import type { Day, Event } from "../types.ts";
|
|
|
6
6
|
|
|
7
7
|
export type ReportOptions = { projects: string; to: string; days: number; now?: Date; streakFrom?: Date };
|
|
8
8
|
// What --verbose prints about a run: counts and milliseconds, never a path.
|
|
9
|
-
export type Timing = ScanStats & {
|
|
9
|
+
export type Timing = ScanStats & {
|
|
10
|
+
inWindow: number;
|
|
11
|
+
read: number;
|
|
12
|
+
bytes: number;
|
|
13
|
+
cache: { hits: number; misses: number } | null;
|
|
14
|
+
startMs?: number;
|
|
15
|
+
openMs?: number;
|
|
16
|
+
scanMs: number;
|
|
17
|
+
lookupMs: number;
|
|
18
|
+
readMs: number;
|
|
19
|
+
analyzeMs: number;
|
|
20
|
+
saveMs: number;
|
|
21
|
+
render?: { format: string; ms: number };
|
|
22
|
+
writeMs?: number;
|
|
23
|
+
totalMs?: number;
|
|
24
|
+
};
|
|
10
25
|
|
|
11
26
|
// Reading one file at a time left the disk idle between files: 1.6 GB took 5.4 s
|
|
12
27
|
// sequentially and 0.9 s in parallel. The cap keeps open files well under the limit.
|
|
@@ -26,8 +41,12 @@ async function readWhole(entry: ScanEntry): Promise<Read> {
|
|
|
26
41
|
if (before.size > constants.MAX_STRING_LENGTH) throw new Error("longer than a string can hold");
|
|
27
42
|
const bytes = await fh.readFile();
|
|
28
43
|
const after = await fh.stat();
|
|
29
|
-
const same =
|
|
30
|
-
|
|
44
|
+
const same =
|
|
45
|
+
before.dev === after.dev && before.ino === after.ino && before.size === after.size && before.mtimeMs === after.mtimeMs && before.size === bytes.length;
|
|
46
|
+
return {
|
|
47
|
+
bytes,
|
|
48
|
+
stable: same ? { path: entry.path, dev: after.dev, ino: after.ino, size: after.size, mtimeMs: after.mtimeMs } : null,
|
|
49
|
+
};
|
|
31
50
|
} finally {
|
|
32
51
|
await fh.close();
|
|
33
52
|
}
|
|
@@ -56,7 +75,9 @@ export async function report(o: ReportOptions, timing?: Timing, cache?: Transcri
|
|
|
56
75
|
const r = await readWhole(entry);
|
|
57
76
|
bytes += r.bytes.length;
|
|
58
77
|
reads.set(entry.path, r);
|
|
59
|
-
} catch {
|
|
78
|
+
} catch {
|
|
79
|
+
stats.skipped++;
|
|
80
|
+
}
|
|
60
81
|
}
|
|
61
82
|
};
|
|
62
83
|
await Promise.all(Array.from({ length: Math.min(READERS, misses.length) }, reader));
|
|
@@ -75,8 +96,24 @@ export async function report(o: ReportOptions, timing?: Timing, cache?: Transcri
|
|
|
75
96
|
const days = analyzeEvents(events, window);
|
|
76
97
|
const analyzeMs = performance.now() - t;
|
|
77
98
|
t = performance.now();
|
|
78
|
-
cache?.save(
|
|
99
|
+
cache?.save(
|
|
100
|
+
entries.filter((e) => hits.has(e.path)),
|
|
101
|
+
fresh,
|
|
102
|
+
Date.now(),
|
|
103
|
+
);
|
|
79
104
|
const saveMs = performance.now() - t;
|
|
80
|
-
if (timing)
|
|
105
|
+
if (timing)
|
|
106
|
+
Object.assign(timing, {
|
|
107
|
+
...stats,
|
|
108
|
+
inWindow: entries.length,
|
|
109
|
+
read: reads.size,
|
|
110
|
+
bytes,
|
|
111
|
+
cache: found ? { hits: hits.size, misses: misses.length } : null,
|
|
112
|
+
scanMs,
|
|
113
|
+
lookupMs,
|
|
114
|
+
readMs,
|
|
115
|
+
analyzeMs,
|
|
116
|
+
saveMs,
|
|
117
|
+
});
|
|
81
118
|
return days;
|
|
82
119
|
}
|
|
@@ -28,7 +28,11 @@ export async function writeStatus(line: string, env: NodeJS.ProcessEnv): Promise
|
|
|
28
28
|
if ((await mkdir(dir, { recursive: true, mode: 0o700 })) !== undefined) await chmod(dir, 0o700);
|
|
29
29
|
const handle = await open(tmp, "wx", 0o600);
|
|
30
30
|
created = true;
|
|
31
|
-
try {
|
|
31
|
+
try {
|
|
32
|
+
await handle.writeFile(line);
|
|
33
|
+
} finally {
|
|
34
|
+
await handle.close();
|
|
35
|
+
}
|
|
32
36
|
await chmod(tmp, 0o600);
|
|
33
37
|
await rename(tmp, join(dir, "status.json"));
|
|
34
38
|
} catch {
|
package/src/lib/text/format.ts
CHANGED
|
@@ -2,7 +2,11 @@
|
|
|
2
2
|
// truncated, not rounded: 9.96M stays "9.9M".
|
|
3
3
|
function ladder(n: number): string {
|
|
4
4
|
if (n >= 1e12) return "999B+";
|
|
5
|
-
for (const [unit, size] of [
|
|
5
|
+
for (const [unit, size] of [
|
|
6
|
+
["B", 1e9],
|
|
7
|
+
["M", 1e6],
|
|
8
|
+
["k", 1e3],
|
|
9
|
+
] as const) {
|
|
6
10
|
if (n < size) continue;
|
|
7
11
|
const v = n / size;
|
|
8
12
|
if (unit !== "k" && v < 10) return `${(Math.floor(v * 10) / 10).toFixed(1)}${unit}`;
|
package/src/lib/text/render.ts
CHANGED
|
@@ -44,9 +44,22 @@ export function renderWeek(days: Day[], color: boolean): string {
|
|
|
44
44
|
const decisions = days.reduce((s, d) => s + d.totals.decisions, 0);
|
|
45
45
|
const maxSessions = Math.max(0, ...days.map((d) => d.totals.maxSessions));
|
|
46
46
|
// Compact counts keep a very active window inside the grid's 98 columns.
|
|
47
|
-
const totals = dim(
|
|
47
|
+
const totals = dim(
|
|
48
|
+
` ${hm(active)} active ${plural(prompts, "prompt")} ${plural(reports, "report")} ${plural(decisions, "decision")} ${plural(maxSessions, "session")} at once`,
|
|
49
|
+
color,
|
|
50
|
+
);
|
|
48
51
|
// Today need not be the last row: --to may name a later day.
|
|
49
|
-
return [
|
|
52
|
+
return [
|
|
53
|
+
header,
|
|
54
|
+
...rows,
|
|
55
|
+
"",
|
|
56
|
+
legend,
|
|
57
|
+
totals,
|
|
58
|
+
...snapshotLine(
|
|
59
|
+
days.find((d) => d.asOf),
|
|
60
|
+
color,
|
|
61
|
+
),
|
|
62
|
+
].join("\n");
|
|
50
63
|
}
|
|
51
64
|
|
|
52
65
|
const fmtTokens = (n: number): string => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
|
|
@@ -82,14 +95,27 @@ const EXPLAIN: Col[] = [
|
|
|
82
95
|
// other columns always show, so two days still line up.
|
|
83
96
|
const EVENT_COLS = new Set(["rep", "intr", "rej", "quest", "plan", "mode", "ctx-sw"]);
|
|
84
97
|
const FULL_NAME: Record<string, string> = {
|
|
85
|
-
rep: "reports",
|
|
86
|
-
|
|
98
|
+
rep: "reports",
|
|
99
|
+
intr: "interrupts",
|
|
100
|
+
rej: "rejects",
|
|
101
|
+
quest: "questions",
|
|
102
|
+
plan: "plans",
|
|
103
|
+
mode: "mode switches",
|
|
104
|
+
"ctx-sw": "context switches",
|
|
87
105
|
};
|
|
88
106
|
|
|
89
107
|
export function renderDay(day: Day, opts: { explain: boolean; color: boolean }): string {
|
|
90
108
|
const cols = opts.explain ? [...COLS, ...EXPLAIN] : COLS;
|
|
91
109
|
const line = (columns: Col[], cells: string[]) =>
|
|
92
|
-
cells
|
|
110
|
+
cells
|
|
111
|
+
.map((c, i) => {
|
|
112
|
+
const w = columns[i]![1];
|
|
113
|
+
if (i === 0) return c.padEnd(w);
|
|
114
|
+
if (columns[i]![0] === "level") return ` ${c.padEnd(w - 2)}`;
|
|
115
|
+
return c.padStart(w);
|
|
116
|
+
})
|
|
117
|
+
.join("")
|
|
118
|
+
.trimEnd();
|
|
93
119
|
|
|
94
120
|
const active = day.buckets.filter((b) => b.score !== null);
|
|
95
121
|
// The snapshot line still shows on an empty open day, or a run at 09:00 and
|
|
@@ -99,7 +125,10 @@ export function renderDay(day: Day, opts: { explain: boolean; color: boolean }):
|
|
|
99
125
|
const visible = cols.filter(([name, , f]) => !EVENT_COLS.has(name) || active.some((b) => f(b) !== "0"));
|
|
100
126
|
const leftOut = cols.filter((col) => EVENT_COLS.has(col[0]) && !visible.includes(col));
|
|
101
127
|
|
|
102
|
-
const header = line(
|
|
128
|
+
const header = line(
|
|
129
|
+
visible,
|
|
130
|
+
visible.map(([name]) => name),
|
|
131
|
+
);
|
|
103
132
|
const rows = active.map((b) => {
|
|
104
133
|
const cells = visible.map(([, , f]) => f(b));
|
|
105
134
|
const text = line(visible, cells);
|
|
@@ -21,10 +21,23 @@ const TAIL_BYTES = 4096;
|
|
|
21
21
|
const READERS = 16;
|
|
22
22
|
const KEEP_MS = 90 * 86_400_000;
|
|
23
23
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
24
|
-
const KINDS: Record<EventKind, true> = {
|
|
24
|
+
const KINDS: Record<EventKind, true> = {
|
|
25
|
+
prompt: true,
|
|
26
|
+
report: true,
|
|
27
|
+
output: true,
|
|
28
|
+
interrupt: true,
|
|
29
|
+
reject: true,
|
|
30
|
+
answer: true,
|
|
31
|
+
question: true,
|
|
32
|
+
plan_review: true,
|
|
33
|
+
mode_change: true,
|
|
34
|
+
activity: true,
|
|
35
|
+
};
|
|
25
36
|
|
|
26
37
|
export function tailHash(bytes: Uint8Array): Uint8Array {
|
|
27
|
-
return createHash("sha256")
|
|
38
|
+
return createHash("sha256")
|
|
39
|
+
.update(bytes.subarray(Math.max(0, bytes.length - TAIL_BYTES)))
|
|
40
|
+
.digest();
|
|
28
41
|
}
|
|
29
42
|
|
|
30
43
|
function fingerprint(): Uint8Array {
|
|
@@ -40,7 +53,11 @@ function encode(events: Event[]): Uint8Array {
|
|
|
40
53
|
const index = new Map<string, number>();
|
|
41
54
|
const rows = events.map((e) => {
|
|
42
55
|
let i = index.get(e.sessionId);
|
|
43
|
-
if (i === undefined) {
|
|
56
|
+
if (i === undefined) {
|
|
57
|
+
i = sessions.length;
|
|
58
|
+
index.set(e.sessionId, i);
|
|
59
|
+
sessions.push(e.sessionId);
|
|
60
|
+
}
|
|
44
61
|
if (e.bg) return [e.ts, e.kind, i, e.tokens ?? null, 1];
|
|
45
62
|
return e.tokens === undefined ? [e.ts, e.kind, i] : [e.ts, e.kind, i, e.tokens];
|
|
46
63
|
});
|
|
@@ -95,13 +112,20 @@ async function readTail(path: string, size: number): Promise<Uint8Array | null>
|
|
|
95
112
|
|
|
96
113
|
const equal = (a: Uint8Array, b: Uint8Array): boolean => a.length === b.length && a.every((x, i) => x === b[i]);
|
|
97
114
|
|
|
98
|
-
type Row = {
|
|
115
|
+
type Row = {
|
|
116
|
+
dev: number;
|
|
117
|
+
ino: number;
|
|
118
|
+
size: number;
|
|
119
|
+
mtime_ms: number;
|
|
120
|
+
tail: Uint8Array;
|
|
121
|
+
from_ms: number;
|
|
122
|
+
events: Uint8Array;
|
|
123
|
+
};
|
|
99
124
|
|
|
100
125
|
class Foreign extends Error {}
|
|
101
126
|
|
|
102
127
|
// Only a file that is not ours is replaced; a locked or unopenable one is left alone.
|
|
103
|
-
const replaceable = (e: unknown): boolean =>
|
|
104
|
-
e instanceof Foreign || /^SQLITE_(NOTADB|CORRUPT)/.test(String((e as { code?: unknown } | null)?.code));
|
|
128
|
+
const replaceable = (e: unknown): boolean => e instanceof Foreign || /^SQLITE_(NOTADB|CORRUPT)/.test(String((e as { code?: unknown } | null)?.code));
|
|
105
129
|
|
|
106
130
|
// Modes are set on what cogload creates; a mode the person set later is theirs.
|
|
107
131
|
function connect(path: string): Database {
|
|
@@ -131,7 +155,9 @@ function connect(path: string): Database {
|
|
|
131
155
|
}).immediate();
|
|
132
156
|
return db;
|
|
133
157
|
} catch (e) {
|
|
134
|
-
try {
|
|
158
|
+
try {
|
|
159
|
+
db.close();
|
|
160
|
+
} catch {}
|
|
135
161
|
throw e;
|
|
136
162
|
}
|
|
137
163
|
}
|
|
@@ -172,9 +198,18 @@ export function openCache(env: NodeJS.ProcessEnv): TranscriptCache | null {
|
|
|
172
198
|
}
|
|
173
199
|
}
|
|
174
200
|
|
|
175
|
-
const remove = (path: string): void => {
|
|
201
|
+
const remove = (path: string): void => {
|
|
202
|
+
for (const f of [path, `${path}-wal`, `${path}-shm`]) rmSync(f, { force: true });
|
|
203
|
+
};
|
|
176
204
|
|
|
177
|
-
const fileId = (path: string): string | null => {
|
|
205
|
+
const fileId = (path: string): string | null => {
|
|
206
|
+
try {
|
|
207
|
+
const s = statSync(path);
|
|
208
|
+
return `${s.dev}:${s.ino}`;
|
|
209
|
+
} catch {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
};
|
|
178
213
|
|
|
179
214
|
// A file found corrupt only once it is queried (the header was fine) is
|
|
180
215
|
// replaced like one that fails to open, once; this run then misses every file.
|
|
@@ -188,10 +223,12 @@ function cacheOn(db: Database, parser: Uint8Array, path: string): TranscriptCach
|
|
|
188
223
|
const found = new Map<string, Event[]>();
|
|
189
224
|
try {
|
|
190
225
|
const keyed = entries.filter((e) => e.ino !== 0);
|
|
191
|
-
const rows = db
|
|
192
|
-
|
|
226
|
+
const rows = db
|
|
227
|
+
.query<Row, [Uint8Array, string]>(
|
|
228
|
+
`SELECT dev, ino, size, mtime_ms, tail, from_ms, events FROM transcript
|
|
193
229
|
WHERE parser = ? AND (dev, ino) IN (SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]') FROM json_each(?))`,
|
|
194
|
-
|
|
230
|
+
)
|
|
231
|
+
.all(parser, JSON.stringify(keyed.map((e) => [e.dev, e.ino])));
|
|
195
232
|
const byKey = new Map(rows.map((r) => [`${r.dev}:${r.ino}`, r]));
|
|
196
233
|
const candidates = keyed.flatMap((entry) => {
|
|
197
234
|
const row = byKey.get(`${entry.dev}:${entry.ino}`);
|
|
@@ -212,8 +249,13 @@ function cacheOn(db: Database, parser: Uint8Array, path: string): TranscriptCach
|
|
|
212
249
|
} catch (e) {
|
|
213
250
|
found.clear();
|
|
214
251
|
broken.length = 0;
|
|
215
|
-
if (!replaceable(e)) {
|
|
216
|
-
|
|
252
|
+
if (!replaceable(e)) {
|
|
253
|
+
failed = true;
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
try {
|
|
257
|
+
db.close();
|
|
258
|
+
} catch {}
|
|
217
259
|
try {
|
|
218
260
|
// Only the file this run opened: a different one at the path is
|
|
219
261
|
// another run's fresh cache. Unlinking a file another run still has
|
|
@@ -246,7 +288,17 @@ function cacheOn(db: Database, parser: Uint8Array, path: string): TranscriptCach
|
|
|
246
288
|
for (const k of broken) drop.run(k);
|
|
247
289
|
for (const { entry: e, tail, fromMs, events } of fresh) {
|
|
248
290
|
if (e.ino === 0 || !events.every((ev) => UUID.test(ev.sessionId))) continue;
|
|
249
|
-
upsert.run({
|
|
291
|
+
upsert.run({
|
|
292
|
+
dev: e.dev,
|
|
293
|
+
ino: e.ino,
|
|
294
|
+
parser,
|
|
295
|
+
size: e.size,
|
|
296
|
+
mtime: e.mtimeMs,
|
|
297
|
+
tail,
|
|
298
|
+
from: fromMs,
|
|
299
|
+
now: nowMs,
|
|
300
|
+
events: encode(events),
|
|
301
|
+
});
|
|
250
302
|
}
|
|
251
303
|
for (const e of hit) if (e.ino !== 0) touch.run({ now: nowMs, dev: e.dev, ino: e.ino });
|
|
252
304
|
db.run("DELETE FROM transcript WHERE used_at < ?", [nowMs - KEEP_MS]);
|
|
@@ -255,7 +307,9 @@ function cacheOn(db: Database, parser: Uint8Array, path: string): TranscriptCach
|
|
|
255
307
|
},
|
|
256
308
|
|
|
257
309
|
close() {
|
|
258
|
-
try {
|
|
310
|
+
try {
|
|
311
|
+
db.close();
|
|
312
|
+
} catch {}
|
|
259
313
|
},
|
|
260
314
|
};
|
|
261
315
|
}
|
|
@@ -69,7 +69,11 @@ export function parseTranscript(text: string, cutoffMs = -Infinity): Event[] {
|
|
|
69
69
|
if (line.trim() === "") continue;
|
|
70
70
|
if (lastTs !== null && lastTs < cutoffMs && olderThan(line, cutoffMs)) continue;
|
|
71
71
|
let rec: unknown;
|
|
72
|
-
try {
|
|
72
|
+
try {
|
|
73
|
+
rec = JSON.parse(line);
|
|
74
|
+
} catch {
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
73
77
|
if (!isObj(rec)) continue;
|
|
74
78
|
const type = str(rec.type);
|
|
75
79
|
const sessionId = str(rec.sessionId);
|
|
@@ -37,7 +37,9 @@ async function collect(dir: string, entries: Dirent[], cutoffMs: number, out: Sc
|
|
|
37
37
|
if (entry.name === "subagents") continue;
|
|
38
38
|
try {
|
|
39
39
|
await collect(full, await readdir(full, { withFileTypes: true }), cutoffMs, out, stats);
|
|
40
|
-
} catch {
|
|
40
|
+
} catch {
|
|
41
|
+
stats.skipped++;
|
|
42
|
+
}
|
|
41
43
|
} else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
|
|
42
44
|
stats.files++;
|
|
43
45
|
try {
|
|
@@ -47,7 +49,9 @@ async function collect(dir: string, entries: Dirent[], cutoffMs: number, out: Sc
|
|
|
47
49
|
if ((await lastTimestampMs(full)) < cutoffMs) continue;
|
|
48
50
|
}
|
|
49
51
|
out.push({ path: full, dev: st.dev, ino: st.ino, size: st.size, mtimeMs: st.mtimeMs });
|
|
50
|
-
} catch {
|
|
52
|
+
} catch {
|
|
53
|
+
stats.skipped++;
|
|
54
|
+
}
|
|
51
55
|
}
|
|
52
56
|
}
|
|
53
57
|
}
|
package/src/lib/types.ts
CHANGED
|
@@ -5,19 +5,59 @@ export type Transcript = { path: string; text: string };
|
|
|
5
5
|
// for `presence` only: the live streak is traced to its first action, up to it.
|
|
6
6
|
export type Window = { to: string; days: number; now?: Date; streakFrom?: Date };
|
|
7
7
|
export type Metrics = {
|
|
8
|
-
sessions: number;
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
sessions: number;
|
|
9
|
+
prompts: number;
|
|
10
|
+
reports: number;
|
|
11
|
+
outputTokens: number;
|
|
12
|
+
interrupts: number;
|
|
13
|
+
rejects: number;
|
|
14
|
+
questions: number;
|
|
15
|
+
plans: number;
|
|
16
|
+
modeSwitches: number;
|
|
17
|
+
decisions: number;
|
|
18
|
+
contextSwitches: number;
|
|
19
|
+
activeMin: number;
|
|
20
|
+
streakMin: number;
|
|
21
|
+
lateNight: boolean;
|
|
11
22
|
};
|
|
12
23
|
export type Level = "Calm" | "Warming" | "Heating" | "Fried";
|
|
13
|
-
export type Parts = {
|
|
24
|
+
export type Parts = {
|
|
25
|
+
parallel: number;
|
|
26
|
+
pace: number;
|
|
27
|
+
supervision: number;
|
|
28
|
+
reading: number;
|
|
29
|
+
streak: number;
|
|
30
|
+
late: number;
|
|
31
|
+
}; // weighted points, sum ≈ index
|
|
14
32
|
export type Part = keyof Parts;
|
|
15
33
|
export type Score = { index: number; level: Level; parts: Parts; capped: Part[]; top: Part };
|
|
16
34
|
export type LiveBucket = Metrics & { score: Score | null };
|
|
17
35
|
export type HourBucket = LiveBucket & { hour: number };
|
|
18
|
-
export type Totals = {
|
|
36
|
+
export type Totals = {
|
|
37
|
+
prompts: number;
|
|
38
|
+
reports: number;
|
|
39
|
+
outputTokens: number;
|
|
40
|
+
interrupts: number;
|
|
41
|
+
rejects: number;
|
|
42
|
+
questions: number;
|
|
43
|
+
plans: number;
|
|
44
|
+
modeSwitches: number;
|
|
45
|
+
decisions: number;
|
|
46
|
+
contextSwitches: number;
|
|
47
|
+
maxSessions: number;
|
|
48
|
+
};
|
|
19
49
|
// `asOf` and `live` exist only on the day containing `now`: `live` is the sixty
|
|
20
50
|
// minutes `(asOf − 60 min, asOf]`, by the hour bucket's rule, look-back included.
|
|
21
51
|
// `presence` is the day's last human action and the start of its streak, which
|
|
22
52
|
// may lie on an earlier day; instants are ISO 8601 UTC.
|
|
23
|
-
export type Day = {
|
|
53
|
+
export type Day = {
|
|
54
|
+
date: string;
|
|
55
|
+
peak: number | null;
|
|
56
|
+
mean: number | null;
|
|
57
|
+
activeMin: number;
|
|
58
|
+
presence: { lastAt: string; streakStartAt: string } | null;
|
|
59
|
+
totals: Totals;
|
|
60
|
+
buckets: HourBucket[];
|
|
61
|
+
asOf?: string;
|
|
62
|
+
live?: LiveBucket;
|
|
63
|
+
};
|