@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.
@@ -0,0 +1,92 @@
1
+ Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+ -----------------------------------------------------------
8
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
9
+ -----------------------------------------------------------
10
+
11
+ PREAMBLE
12
+ The goals of the Open Font License (OFL) are to stimulate worldwide
13
+ development of collaborative font projects, to support the font creation
14
+ efforts of academic and linguistic communities, and to provide a free and
15
+ open framework in which fonts may be shared and improved in partnership
16
+ with others.
17
+
18
+ The OFL allows the licensed fonts to be used, studied, modified and
19
+ redistributed freely as long as they are not sold by themselves. The
20
+ fonts, including any derivative works, can be bundled, embedded,
21
+ redistributed and/or sold with any software provided that any reserved
22
+ names are not used by derivative works. The fonts and derivatives,
23
+ however, cannot be released under any other type of license. The
24
+ requirement for fonts to remain under this license does not apply
25
+ to any document created using the fonts or their derivatives.
26
+
27
+ DEFINITIONS
28
+ "Font Software" refers to the set of files released by the Copyright
29
+ Holder(s) under this license and clearly marked as such. This may
30
+ include source files, build scripts and documentation.
31
+
32
+ "Reserved Font Name" refers to any names specified as such after the
33
+ copyright statement(s).
34
+
35
+ "Original Version" refers to the collection of Font Software components as
36
+ distributed by the Copyright Holder(s).
37
+
38
+ "Modified Version" refers to any derivative made by adding to, deleting,
39
+ or substituting -- in part or in whole -- any of the components of the
40
+ Original Version, by changing formats or by porting the Font Software to a
41
+ new environment.
42
+
43
+ "Author" refers to any designer, engineer, programmer, technical
44
+ writer or other person who contributed to the Font Software.
45
+
46
+ PERMISSION AND CONDITIONS
47
+ Permission is hereby granted, free of charge, to any person obtaining
48
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
49
+ redistribute, and sell modified and unmodified copies of the Font
50
+ Software, subject to the following conditions:
51
+
52
+ 1) Neither the Font Software nor any of its individual components,
53
+ in Original or Modified Versions, may be sold by itself.
54
+
55
+ 2) Original or Modified Versions of the Font Software may be bundled,
56
+ redistributed and/or sold with any software, provided that each copy
57
+ contains the above copyright notice and this license. These can be
58
+ included either as stand-alone text files, human-readable headers or
59
+ in the appropriate machine-readable metadata fields within text or
60
+ binary files as long as those fields can be easily viewed by the user.
61
+
62
+ 3) No Modified Version of the Font Software may use the Reserved Font
63
+ Name(s) unless explicit written permission is granted by the corresponding
64
+ Copyright Holder. This restriction only applies to the primary font name as
65
+ presented to the users.
66
+
67
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
68
+ Software shall not be used to promote, endorse or advertise any
69
+ Modified Version, except to acknowledge the contribution(s) of the
70
+ Copyright Holder(s) and the Author(s) or with their explicit written
71
+ permission.
72
+
73
+ 5) The Font Software, modified or unmodified, in part or in whole,
74
+ must be distributed entirely under this license, and must not be
75
+ distributed under any other license. The requirement for fonts to
76
+ remain under this license does not apply to any document created
77
+ using the Font Software.
78
+
79
+ TERMINATION
80
+ This license becomes null and void if any of the above conditions are
81
+ not met.
82
+
83
+ DISCLAIMER
84
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
85
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
86
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
87
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
88
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
89
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
90
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
91
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
92
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ https://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file
Binary file
Binary file
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@drakulavich/cogload",
3
+ "version": "0.10.0",
4
+ "description": "Cognitive load index for people driving Claude Code, computed locally from transcripts",
5
+ "license": "MIT",
6
+ "author": "Anton Yakutovich",
7
+ "repository": { "type": "git", "url": "git+https://github.com/drakulavich/cogload.git" },
8
+ "homepage": "https://github.com/drakulavich/cogload#readme",
9
+ "bugs": "https://github.com/drakulavich/cogload/issues",
10
+ "keywords": ["claude-code", "cognitive-load", "developer-experience", "cli", "bun"],
11
+ "type": "module",
12
+ "bin": { "cogload": "src/cli/index.ts", "zapara": "src/cli/zapara.ts" },
13
+ "files": ["src/", "assets/fonts/", "assets/characters.webp", "CHANGELOG.md", "!src/**/*.test.ts"],
14
+ "publishConfig": { "access": "public" },
15
+ "engines": { "bun": ">=1.4.2" },
16
+ "scripts": {
17
+ "dev": "bun run src/cli/index.ts",
18
+ "stats": "bun scripts/signal-stats.ts",
19
+ "test": "TZ=UTC bun test ./tests",
20
+ "typecheck": "tsc --noEmit",
21
+ "lint": "biome ci && knip --include files,exports,types",
22
+ "check": "bun run typecheck && bun run lint && bun run test"
23
+ },
24
+ "devDependencies": {
25
+ "@biomejs/biome": "2.5.14",
26
+ "@types/bun": "^1.4.0",
27
+ "knip": "^6.38.0",
28
+ "typescript": "^7.0.2"
29
+ }
30
+ }
@@ -0,0 +1,155 @@
1
+ import { localDate } from "../lib/metrics/index.ts";
2
+
3
+ export const USAGE = `usage: cogload [window] the last 7 days, one cell per hour
4
+ cogload today|yesterday|<date> one day, one row per active hour
5
+ cogload card [window] [--out] the last 14 days as one picture
6
+ cogload status write today's load for a status line
7
+
8
+ window:
9
+ --days <N> the last N days, 1..90; with --to, N days ending there
10
+ --from <date> first day; --to <date> last day, default today
11
+ a date is YYYY-MM-DD, today or yesterday
12
+
13
+ options:
14
+ --explain with a day: the six weighted parts behind each index
15
+ --out <path> with card: .png, .webp or .html
16
+ (default ~/Downloads/cogload-card.png)
17
+ --json the same data as JSON; for the grid and a day,
18
+ a pipe gets JSON without asking
19
+ --projects <dir> read this directory instead of ~/.claude/projects
20
+ --no-color no ANSI colors; NO_COLOR does the same
21
+ --no-cache parse every transcript again
22
+ --verbose timings and counts on stderr, for a slow run
23
+ -h, --help -V, --version
24
+
25
+ levels: calm 0-29 warming 30-59 heating 60-84 fried 85-100
26
+
27
+ bugs, ideas and a star: github.com/drakulavich/cogload`;
28
+ export const HINT = "run 'cogload --help' for usage";
29
+
30
+ export type Args = { command: "grid" | "day" | "card" | "status"; to: string; days: number; explain: boolean; json: boolean; out: string | null; projects: string; color: boolean; verbose: boolean; cache: boolean };
31
+
32
+ export class UsageError extends Error {}
33
+ // Thrown only at a flag position, never for a token consumed as another flag's
34
+ // value (`--to --help`).
35
+ export class HelpRequested extends Error {}
36
+ export class VersionRequested extends Error {}
37
+
38
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
39
+
40
+ // A usage error quotes the value only when it is short, printable ASCII with no
41
+ // path separator: the CLI never prints a path or an escape, even one typed in.
42
+ const quotable = (v: string): boolean => /^[\x21-\x7e]{1,24}$/.test(v) && !/[\/\\]/.test(v);
43
+ const got = (v: string): string => (quotable(v) ? `, got ${v}` : "");
44
+ const named = (v: string): string => (quotable(v) ? ` ${v}` : "");
45
+
46
+ function validDate(s: string): boolean {
47
+ const m = DATE.exec(s);
48
+ if (!m) return false;
49
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
50
+ const dt = new Date(y, mo - 1, d);
51
+ return dt.getFullYear() === y && dt.getMonth() === mo - 1 && dt.getDate() === d;
52
+ }
53
+
54
+ function resolveDate(what: string, s: string, now: Date): string {
55
+ if (s === "today") return localDate(now);
56
+ if (s === "yesterday") return localDate(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1));
57
+ if (!validDate(s)) throw new UsageError(`${what} must be YYYY-MM-DD, today or yesterday${got(s)}`);
58
+ return s;
59
+ }
60
+
61
+ // UTC arithmetic, so a DST day is still one day.
62
+ function spanDays(from: string, to: string): number {
63
+ const utc = (s: string): number => { const [y = 0, m = 0, d = 0] = s.split("-").map(Number); return Date.UTC(y, m - 1, d); };
64
+ return Math.round((utc(to) - utc(from)) / 86_400_000) + 1;
65
+ }
66
+
67
+ // Checks run in the order a reader meets the flags in --help.
68
+ function windowOf(days: string | null, from: string | null, to: string | null, defaultDays: number, now: Date): { to: string; days: number } {
69
+ if (from !== null && days !== null) throw new UsageError("--from sets the length; drop --days");
70
+ if (days !== null && (!/^\d+$/.test(days) || Number(days) < 1 || Number(days) > 90)) throw new UsageError(`--days must be 1..90${got(days)}`);
71
+ const last = to === null ? localDate(now) : resolveDate("--to", to, now);
72
+ if (from === null) return { to: last, days: days === null ? defaultDays : Number(days) };
73
+ const first = resolveDate("--from", from, now);
74
+ const span = spanDays(first, last);
75
+ if (span < 1) throw new UsageError(`--from ${first} is after --to ${last}`);
76
+ if (span > 90) throw new UsageError(`--from ${first} to ${last} is ${span} days; the most is 90`);
77
+ return { to: last, days: span };
78
+ }
79
+
80
+ export function parseArgs(argv: string[], now: Date, env: Record<string, string | undefined>, isTTY: boolean, projects: string): Args {
81
+ const a: Args = { command: "grid", to: localDate(now), days: 7, explain: false, json: false, out: null, projects, color: isTTY && !env.NO_COLOR, verbose: false, cache: true };
82
+ let days: string | null = null;
83
+ let from: string | null = null;
84
+ let to: string | null = null;
85
+ let jsonFlag = false;
86
+ const positional: string[] = [];
87
+ // A value flag given twice is a usage error; bare flags are idempotent and untracked.
88
+ const seen = new Set<string>();
89
+ for (let i = 0; i < argv.length; i++) {
90
+ let arg = argv[i]!;
91
+ let inline: string | null = null;
92
+ const eq = arg.startsWith("--") ? arg.indexOf("=") : -1;
93
+ if (eq > 0) { inline = arg.slice(eq + 1); arg = arg.slice(0, eq); }
94
+ const bare = (): void => { if (inline !== null) throw new UsageError(`unknown flag${named(argv[i]!)}`); };
95
+ // A value that looks like another flag is a usage error (`--projects --json`),
96
+ // and so is an empty one (`--projects=`); only --days accepts a negative
97
+ // number, so `--days -1` reaches the range check.
98
+ const value = (negativeNumberIsValue = false): string => {
99
+ let v: string;
100
+ if (inline !== null) v = inline;
101
+ else {
102
+ const next = argv[++i];
103
+ if (next === undefined || (next.startsWith("-") && !(negativeNumberIsValue && /^-\d/.test(next)))) throw new UsageError(`${arg} needs a value`);
104
+ v = next;
105
+ }
106
+ if (v === "") throw new UsageError(`${arg} needs a value`);
107
+ if (seen.has(arg)) throw new UsageError(`${arg} given twice`);
108
+ seen.add(arg);
109
+ return v;
110
+ };
111
+ switch (arg) {
112
+ case "--help":
113
+ case "-h": bare(); throw new HelpRequested();
114
+ case "--version":
115
+ case "-V": bare(); throw new VersionRequested();
116
+ case "--json": bare(); jsonFlag = true; break;
117
+ case "--explain": bare(); a.explain = true; break;
118
+ case "--no-color": bare(); a.color = false; break;
119
+ case "--verbose": bare(); a.verbose = true; break;
120
+ case "--no-cache": bare(); a.cache = false; break;
121
+ case "--projects": a.projects = value(); break;
122
+ case "--from": from = value(); break;
123
+ case "--to": to = value(); break;
124
+ case "--days": days = value(true); break;
125
+ case "--out": a.out = value(); break;
126
+ default:
127
+ if (arg.startsWith("-")) throw new UsageError(`unknown flag${named(arg)}`);
128
+ positional.push(arg);
129
+ }
130
+ }
131
+ if (positional.length > 1) throw new UsageError(`unexpected argument${named(positional[1]!)}`);
132
+ const [word] = positional;
133
+ if (word === undefined) a.command = "grid";
134
+ else if (word === "card") a.command = "card";
135
+ else if (word === "status") { a.command = "status"; a.to = localDate(now); a.days = 1; }
136
+ else if (word === "today" || word === "yesterday" || DATE.test(word)) { a.command = "day"; a.to = resolveDate("date", word, now); a.days = 1; }
137
+ else throw new UsageError(`unknown command${named(word)} (try today, yesterday, a date, card or status)`);
138
+
139
+ if (a.command === "day" || a.command === "status") {
140
+ if (days !== null || from !== null || to !== null) throw new UsageError(`--days, --from and --to do not apply to ${a.command === "day" ? "a named day" : "status"}`);
141
+ } else {
142
+ ({ to: a.to, days: a.days } = windowOf(days, from, to, a.command === "card" ? 14 : 7, now));
143
+ }
144
+ // The card is a file either way, so only an explicit --json switches it.
145
+ a.json = a.command === "card" ? jsonFlag : jsonFlag || !isTTY;
146
+ if (a.command !== "day" && a.explain) throw new UsageError("--explain applies to a named day only");
147
+ if (a.command !== "card" && a.out !== null) throw new UsageError("--out applies to card only");
148
+ if (a.json && a.out !== null) throw new UsageError("--json writes no file; drop --out");
149
+ if (a.out !== null) {
150
+ // Printed back verbatim in `wrote \u2026`, so it must be one plain line.
151
+ if (/[\x00-\x1f\x7f]/.test(a.out)) throw new UsageError("--out must not contain control characters");
152
+ if (!/\.(png|webp|html)$/i.test(a.out)) throw new UsageError("--out must end in .png, .webp or .html");
153
+ }
154
+ return a;
155
+ }
@@ -0,0 +1,99 @@
1
+ import { statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { CardWriteError, cardData, cardHtml, loadAssets, openCard, renderCard, sentenceText } from "../lib/card/index.ts";
5
+ import { report, type Timing } from "../lib/report/index.ts";
6
+ import { renderStatus, statusOf, streakFrom, writeStatus } from "../lib/status/index.ts";
7
+ import { renderDay, renderJson, renderWeek } from "../lib/text/index.ts";
8
+ import type { TranscriptCache } from "../lib/transcripts/index.ts";
9
+ import type { Day } from "../lib/types.ts";
10
+ import type { Args } from "./args.ts";
11
+
12
+ export async function table(a: Args, now: Date, cache: TranscriptCache | null, timing?: Timing): Promise<number> {
13
+ const days: Day[] = await report({ projects: a.projects, to: a.to, days: a.days, now }, timing, cache);
14
+ const data = a.command === "day" ? days[0] : days;
15
+ if (a.json) console.log(renderJson(data!));
16
+ else if (a.command === "day") console.log(renderDay(days[0]!, { explain: a.explain, color: a.color }));
17
+ else console.log(renderWeek(days, a.color));
18
+ return 0;
19
+ }
20
+
21
+ // The write comes first: a caller never reads a line that was not saved.
22
+ export async function status(a: Args, now: Date, cache: TranscriptCache | null, timing?: Timing): Promise<number> {
23
+ const days: Day[] = await report({ projects: a.projects, to: a.to, days: a.days, now, streakFrom: streakFrom(now) }, timing, cache);
24
+ const line = renderStatus(statusOf(days[0]!, now));
25
+ const t = performance.now();
26
+ await writeStatus(line, process.env);
27
+ if (timing) timing.writeMs = performance.now() - t;
28
+ process.stdout.write(line);
29
+ return 0;
30
+ }
31
+
32
+ // The label names the folder, not the path: the CLI never prints a derived path.
33
+ function cardTarget(out: string | null): { path: string; label: string; unwritable?: string } {
34
+ if (out !== null) return { path: out, label: out };
35
+ const dir = join(homedir(), "Downloads");
36
+ let isDir = false;
37
+ try { isDir = statSync(dir).isDirectory(); } catch {}
38
+ if (!isDir) throw new Error("no Downloads folder: pass --out <path>");
39
+ return { path: join(dir, "cogload-card.png"), label: "cogload-card.png to Downloads", unwritable: "cannot write cogload-card.png to Downloads: pass --out <path>" };
40
+ }
41
+
42
+ // Keys pressed while the card was drawn answer no question yet asked, so the
43
+ // terminal's pending input is dropped first: tcflush(0, TCIFLUSH). Best effort,
44
+ // where libc can be found; elsewhere the question reads as before.
45
+ const TCIFLUSH: Partial<Record<NodeJS.Platform, { lib: string; queue: number }>> = { darwin: { lib: "libSystem.B.dylib", queue: 1 }, linux: { lib: "libc.so.6", queue: 0 } };
46
+ async function discardTypedInput(): Promise<void> {
47
+ const c = TCIFLUSH[process.platform];
48
+ if (!c) return;
49
+ try {
50
+ const { dlopen, FFIType } = await import("bun:ffi");
51
+ const libc = dlopen(c.lib, { tcflush: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } });
52
+ try { libc.symbols.tcflush(0, c.queue); } finally { libc.close(); }
53
+ } catch {}
54
+ }
55
+
56
+ export async function card(a: Args, now: Date, cache: TranscriptCache | null, timing?: Timing): Promise<number> {
57
+ const days: Day[] = await report({ projects: a.projects, to: a.to, days: a.days, now }, timing, cache);
58
+ const data = cardData(days, { days: a.days });
59
+ // A script asking for the data gets a document either way; a picture of nothing is an error.
60
+ if (data === null && a.json) { console.log("null"); return 0; }
61
+ const from = days[0]!.date;
62
+ const to = days[days.length - 1]!.date;
63
+ if (data === null) throw new Error(from === to ? `no activity on ${to}` : `no activity from ${from} to ${to}`);
64
+ if (a.json) {
65
+ const round2 = (x: number): number => Math.round(x * 100) / 100;
66
+ const json = {
67
+ from, to, days: data.days, character: data.character, name: data.name,
68
+ sentence: sentenceText(data.sentence), motto: data.motto,
69
+ shares: { conductor: round2(data.shares.conductor), supervisor: round2(data.shares.supervisor), marathoner: round2(data.shares.marathoner), nightOwl: round2(data.shares.nightOwl) },
70
+ peak: data.peak, spectrum: data.spectrum, highlights: data.highlights,
71
+ };
72
+ console.log(JSON.stringify(json, null, 2));
73
+ return 0;
74
+ }
75
+ const target = cardTarget(a.out);
76
+ // The browser engine takes seconds; a person at a terminal is told why it waits.
77
+ const note = process.stderr.isTTY && !/\.html$/i.test(target.path);
78
+ if (note) process.stderr.write("drawing the card…");
79
+ const t = performance.now();
80
+ try {
81
+ await renderCard(cardHtml(data, await loadAssets()), target.path);
82
+ } catch (e) {
83
+ // Without --out, "check the --out directory" points at a flag the person never used.
84
+ throw e instanceof CardWriteError && target.unwritable ? new Error(target.unwritable) : e;
85
+ } finally {
86
+ if (note) process.stderr.write("\r\x1b[K");
87
+ }
88
+ if (timing) timing.render = { format: target.path.slice(target.path.lastIndexOf(".") + 1).toLowerCase(), ms: performance.now() - t };
89
+ console.log(`${data.name}: ${sentenceText(data.sentence)}\nwrote ${target.label}`);
90
+ if (timing) timing.totalMs = performance.now(); // the wait for an answer is not cogload's time
91
+ if (process.stdin.isTTY && process.stdout.isTTY && process.platform !== "win32") {
92
+ await discardTypedInput();
93
+ process.stdout.write("open it? [Y/n] ");
94
+ let answer: string | null = null;
95
+ for await (const line of console) { answer = line; break; }
96
+ if (answer !== null && /^(y|yes)?$/i.test(answer.trim())) openCard(target.path);
97
+ }
98
+ return 0;
99
+ }
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env bun
2
+ import { readFileSync } from "node:fs";
3
+ import { cpus, homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { openCache } from "../lib/transcripts/index.ts";
6
+ import type { Timing } from "../lib/report/index.ts";
7
+ import { HelpRequested, HINT, parseArgs, USAGE, UsageError, VersionRequested } from "./args.ts";
8
+ import { card, status, table } from "./commands.io.ts";
9
+ import { timingLines } from "./timing.ts";
10
+
11
+ // Read only when --version is handled, so a broken package.json fails inside
12
+ // the guarded catch instead of at module load.
13
+ function version(): string {
14
+ const parsed: unknown = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
15
+ if (typeof parsed === "object" && parsed !== null && typeof (parsed as { version?: unknown }).version === "string") {
16
+ return (parsed as { version: string }).version;
17
+ }
18
+ throw new Error("package.json has no version");
19
+ }
20
+
21
+ function runEnv() {
22
+ let ver = "?";
23
+ try { ver = version(); } catch {}
24
+ return { version: ver, bun: Bun.version, platform: process.platform, arch: process.arch, cpus: cpus().length, nowMs: performance.now() };
25
+ }
26
+
27
+ async function main(): Promise<number> {
28
+ const argv = process.argv.slice(2);
29
+ const now = new Date();
30
+ const a = parseArgs(argv, now, process.env, process.stdout.isTTY === true, join(homedir(), ".claude", "projects"));
31
+ const timing = a.verbose ? ({ startMs: performance.now() } as Timing) : undefined;
32
+ const t = performance.now();
33
+ const cache = a.cache ? openCache(process.env) : null;
34
+ if (timing && a.cache) timing.openMs = performance.now() - t;
35
+ try {
36
+ const code = a.command === "card" ? await card(a, now, cache, timing) : a.command === "status" ? await status(a, now, cache, timing) : await table(a, now, cache, timing);
37
+ if (timing) process.stderr.write(timingLines(timing, runEnv()));
38
+ return code;
39
+ } finally {
40
+ cache?.close();
41
+ }
42
+ }
43
+
44
+ export function start(): void {
45
+ main().then((code) => process.exit(code), (e: unknown) => {
46
+ if (e instanceof HelpRequested) { console.log(USAGE); process.exit(0); }
47
+ if (e instanceof VersionRequested) {
48
+ try { console.log(version()); process.exit(0); }
49
+ catch (err) { console.error(`cogload: ${err instanceof Error ? err.message : String(err)}`); process.exit(1); }
50
+ }
51
+ const msg = e instanceof Error ? e.message : String(e);
52
+ if (e instanceof UsageError) { console.error(`cogload: ${msg}\n${HINT}`); process.exit(2); }
53
+ console.error(`cogload: ${msg}`);
54
+ process.exit(1);
55
+ });
56
+ }
57
+
58
+ if (import.meta.main) start();
@@ -0,0 +1,18 @@
1
+ import { READERS, type Timing } from "../lib/report/index.ts";
2
+
3
+ // Numbers only: someone pastes these from another machine, and no path may leave it.
4
+ export function timingLines(t: Timing, env: { version: string; bun: string; platform: string; arch: string; cpus: number; nowMs: number }): string {
5
+ const row = (label: string, what: string, ms: number) => `${label.padEnd(8)}${what.padEnd(44)}${String(Math.round(ms)).padStart(7)} ms\n`;
6
+ const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
7
+ return `cogload ${env.version} · bun ${env.bun} · ${env.platform} ${env.arch} · ${env.cpus} cpus\n`
8
+ + row("start", "bun, modules, arguments", t.startMs ?? 0)
9
+ + (t.openMs !== undefined ? row("open", "cache", t.openMs) : "")
10
+ + row("scan", `${plural(t.files, "file")}, ${t.inWindow} in window, ${plural(t.tailChecks, "tail check")}`, t.scanMs)
11
+ + (t.cache ? row("cache", `${plural(t.cache.hits, "hit")}, ${plural(t.cache.misses, "miss", "misses")}`, t.lookupMs) : `${"cache".padEnd(8)}off\n`)
12
+ + row("read", `${plural(t.read, "file")}, ${(t.bytes / 1e6).toFixed(1)} MB, ${READERS} at a time`, t.readMs)
13
+ + row("analyze", "", t.analyzeMs)
14
+ + (t.cache ? row("save", "cache", t.saveMs) : "")
15
+ + (t.render ? row("render", t.render.format, t.render.ms) : "")
16
+ + (t.writeMs !== undefined ? row("write", "status file", t.writeMs) : "")
17
+ + row("total", "", t.totalMs ?? env.nowMs);
18
+ }
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bun
2
+ import { start } from "./index.ts";
3
+
4
+ process.stderr.write("zapara is now cogload; the zapara command goes away in 1.0.0\n");
5
+ start();