slopcard 0.0.0-stage → 1.0.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/LICENSE +23 -0
- package/README.md +71 -2
- package/package.json +10 -4
- package/slopcard.mjs +502 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Taylor McKnight
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
The images in site/public (taylor.webp, og.png) are not covered by this license.
|
package/README.md
CHANGED
|
@@ -1,3 +1,72 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Slopcard
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://taylor.fyi/slopcard/r/taylor-fyi-slopcard)
|
|
4
|
+
|
|
5
|
+
Proof of slop. A badge for sites built with AI agents that shows how much work went into them: the prompts, agent hours and days, counted from the agents' own logs.
|
|
6
|
+
|
|
7
|
+
The badge opens the site's card. Sites with a badge are listed at [taylor.fyi/slopcard/directory](https://taylor.fyi/slopcard/directory).
|
|
8
|
+
|
|
9
|
+
## Get one
|
|
10
|
+
|
|
11
|
+
Paste this to your coding agent, in the site's folder:
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
Read and follow taylor.fyi/slopcard/skill.md to put a slopcard on this site.
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
It counts the work, shows you exactly what it will send, sends it when you say yes, and adds the badge. Say yes once more and it keeps the numbers current: a git pre-push hook sends them every time you push.
|
|
18
|
+
|
|
19
|
+
Or by hand, in the site's folder:
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
npx slopcard submit --url https://yoursite.com
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Node 18 or newer. With Bun, `bunx slopcard`; with Deno, `deno run -A npm:slopcard`.
|
|
26
|
+
|
|
27
|
+
It prints the badge:
|
|
28
|
+
|
|
29
|
+
```html
|
|
30
|
+
<a href="https://taylor.fyi/slopcard/r/yoursite-com"><img src="https://taylor.fyi/slopcard/badge/yoursite-com.svg" alt="Slopcard: 169 prompts, 7 days" height="24"></a>
|
|
31
|
+
<script async src="https://taylor.fyi/slopcard/embed.js"></script>
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The first line works anywhere, READMEs included. The second makes the badge open the card in place. For a dark site, add `?theme=dark` to the image address.
|
|
35
|
+
|
|
36
|
+
Your site joins the directory the first time its badge loads on the live site.
|
|
37
|
+
|
|
38
|
+
## What it counts
|
|
39
|
+
|
|
40
|
+
- **Where:** Claude Code logs (`~/.claude/projects`) and Codex logs (`~/.codex/sessions`) on your computer.
|
|
41
|
+
- **Which work:** every turn that ran in the site's folder, plus turns from its parent folder that touched this folder more than any other.
|
|
42
|
+
- **Prompts:** the messages you typed.
|
|
43
|
+
- **Agent hours:** the time the agents were working, with pauses over 30 minutes left out.
|
|
44
|
+
- **Tokens written:** the agents' output tokens.
|
|
45
|
+
|
|
46
|
+
Claude Code deletes old logs, so every run saves its counts in `~/.slopcard` first, and the total never drops.
|
|
47
|
+
|
|
48
|
+
## What it sends
|
|
49
|
+
|
|
50
|
+
Counts per day, the site's address and its name. Never your prompts, code or file names. The counter prints the exact message before sending.
|
|
51
|
+
|
|
52
|
+
The numbers are self-reported: anyone could change them before sending. A site is listed only once its badge is live on it.
|
|
53
|
+
|
|
54
|
+
## What's here
|
|
55
|
+
|
|
56
|
+
- `slopcard.mjs`: the counter, published to npm as `slopcard`. One file, no dependencies. Runs on Node 18 or newer, Bun or Deno.
|
|
57
|
+
- `skill.md`: the instructions any coding agent can follow.
|
|
58
|
+
- `site/`: the Cloudflare Worker behind taylor.fyi/slopcard. It serves the pages, the badges, `embed.js` and the API, with the cards in D1.
|
|
59
|
+
|
|
60
|
+
## Run your own
|
|
61
|
+
|
|
62
|
+
```
|
|
63
|
+
cd site
|
|
64
|
+
npx wrangler d1 create slopcard # put the id in wrangler.jsonc
|
|
65
|
+
npx wrangler deploy # set BASE in wrangler.jsonc to where it lives
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Point the counter at it with `SLOPCARD_BASE=https://your.site/slopcard`.
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
|
|
72
|
+
The code is MIT. The art (`site/public/taylor.webp`, `site/public/og.png`) isn't covered.
|
package/package.json
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "slopcard",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Proof of slop. A badge for sites built with AI agents: the prompts, agent hours and days behind the site, counted from Claude Code and Codex logs.",
|
|
5
|
+
"keywords": ["claude-code", "codex", "ai", "badge", "vibe-coding"],
|
|
6
|
+
"homepage": "https://taylor.fyi/slopcard",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"bin": { "slopcard": "slopcard.mjs" },
|
|
10
|
+
"files": ["slopcard.mjs"],
|
|
11
|
+
"engines": { "node": ">=18" }
|
|
12
|
+
}
|
package/slopcard.mjs
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Slopcard: count the work behind a site from your coding agents' own logs. Proof of slop.
|
|
3
|
+
//
|
|
4
|
+
// npx slopcard measure this repo, write slopcard.json
|
|
5
|
+
// npx slopcard submit measure, show what will be sent, send it, print the badge
|
|
6
|
+
// npx slopcard badge print the badge snippet again
|
|
7
|
+
//
|
|
8
|
+
// Reads Claude Code logs (~/.claude/projects) and Codex logs (~/.codex/sessions) on this machine.
|
|
9
|
+
// Keeps counts only. No prompt text, file names or code ever leave this machine.
|
|
10
|
+
// Claude Code deletes old logs, so every run banks per-session counts in ~/.slopcard first.
|
|
11
|
+
// Every run also leaves a copy of this file at ~/.slopcard/slopcard.mjs: the git hook and the AGENTS.md note run that
|
|
12
|
+
// fixed copy, never whatever is newest on npm.
|
|
13
|
+
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import os from 'node:os';
|
|
17
|
+
import readline from 'node:readline';
|
|
18
|
+
import { execFileSync } from 'node:child_process';
|
|
19
|
+
import { fileURLToPath } from 'node:url';
|
|
20
|
+
|
|
21
|
+
const NAME = 'Slopcard';
|
|
22
|
+
const BASE = (process.env.SLOPCARD_BASE || 'https://taylor.fyi/slopcard').replace(/\/$/, '');
|
|
23
|
+
const HOME = os.homedir();
|
|
24
|
+
const STORE = process.env.SLOPCARD_DIR || path.join(HOME, '.slopcard');
|
|
25
|
+
const GAP = 30 * 60; // a pause longer than this is waiting, not working
|
|
26
|
+
const VERSION = 1;
|
|
27
|
+
const BANK_VERSION = 2; // 2: a turn counts only for the folder it touched most
|
|
28
|
+
|
|
29
|
+
// ---------- where ----------
|
|
30
|
+
// The repo's top folder. But a folder the repo around it doesn't track (a project kept inside a bigger repo, never
|
|
31
|
+
// added to it) is its own project: measure that folder, not the whole repo.
|
|
32
|
+
function repoRoot() {
|
|
33
|
+
const git = (...a) => execFileSync('git', a, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
34
|
+
try {
|
|
35
|
+
const top = git('rev-parse', '--show-toplevel');
|
|
36
|
+
const first = path.relative(fs.realpathSync(top), fs.realpathSync(process.cwd())).split(path.sep)[0];
|
|
37
|
+
if (!first || first.startsWith('..')) return top;
|
|
38
|
+
let tracked = true;
|
|
39
|
+
try { tracked = !!git('-C', top, 'ls-tree', '--name-only', 'HEAD', '--', first); } catch { /* no commits yet */ }
|
|
40
|
+
return tracked ? top : path.join(top, first);
|
|
41
|
+
} catch {
|
|
42
|
+
return process.cwd();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function listFiles(dir, test, depth) {
|
|
47
|
+
const out = [];
|
|
48
|
+
const walk = (d, n) => {
|
|
49
|
+
let ents;
|
|
50
|
+
try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
|
|
51
|
+
for (const e of ents) {
|
|
52
|
+
const p = path.join(d, e.name);
|
|
53
|
+
if (e.isDirectory() && n > 0) walk(p, n - 1);
|
|
54
|
+
else if (e.isFile() && test(p)) out.push(p);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
walk(dir, depth);
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ---------- does this text touch the repo? ----------
|
|
62
|
+
function makeMatcher(root) {
|
|
63
|
+
const name = path.basename(root);
|
|
64
|
+
const parent = path.dirname(root);
|
|
65
|
+
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
66
|
+
// --also: folders beside this one that belong to it, or names it had before a rename
|
|
67
|
+
const alsoNames = ALSO;
|
|
68
|
+
const names = [name, ...alsoNames];
|
|
69
|
+
const roots = names.map((n) => path.join(parent, n));
|
|
70
|
+
// the repo's path as agents write it: /Users/me/x, ~/x, $HOME/x
|
|
71
|
+
const forms = [];
|
|
72
|
+
for (const r of roots) {
|
|
73
|
+
forms.push(r);
|
|
74
|
+
if (r.startsWith(HOME + path.sep)) {
|
|
75
|
+
const rest = r.slice(HOME.length);
|
|
76
|
+
forms.push('~' + rest, '$HOME' + rest, '${HOME}' + rest);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const any = names.map(esc).join('|');
|
|
80
|
+
const abs = new RegExp('(?:' + forms.map(esc).join('|') + ')(?![\\w.-])');
|
|
81
|
+
const rel = new RegExp('(?:^|[\\s"\'(=:;&|`])(?:\\./)?(?:' + any + ')/');
|
|
82
|
+
const cd = new RegExp('\\bcd\\s+(?:\\./)?(?:' + any + ')(?![\\w.-])');
|
|
83
|
+
const inside = (cwd) => !!cwd && roots.some((r) => cwd === r || cwd.startsWith(r + path.sep));
|
|
84
|
+
// Every folder beside this one (when agents work from the parent folder, a turn can touch several):
|
|
85
|
+
// a turn counts for this site only when this is the folder it touched most.
|
|
86
|
+
const SKIP = new Set(['node_modules', 'dist', 'build', 'tmp', 'public', 'src', 'docs', 'tools', 'data', 'scripts', 'test', 'tests']);
|
|
87
|
+
let siblings = new Set();
|
|
88
|
+
try { siblings = new Set(fs.readdirSync(parent, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith('.') && !SKIP.has(e.name)).map((e) => e.name)); } catch {}
|
|
89
|
+
const mine = (f) => names.includes(f);
|
|
90
|
+
const pforms = [parent];
|
|
91
|
+
if (parent.startsWith(HOME + path.sep)) {
|
|
92
|
+
const rest = parent.slice(HOME.length);
|
|
93
|
+
pforms.push('~' + rest, '$HOME' + rest, '${HOME}' + rest);
|
|
94
|
+
}
|
|
95
|
+
const absAny = new RegExp('(?:' + pforms.map(esc).join('|') + ')/([A-Za-z0-9][\\w.-]*)', 'g');
|
|
96
|
+
const relAny = /(?:^|[\s"'(=:;&|`])(?:\.\/)?([A-Za-z0-9][\w.-]*)\//g;
|
|
97
|
+
const cdAny = /\bcd\s+(?:\.\/)?([A-Za-z0-9][\w.-]*)(?![\w.-])/g;
|
|
98
|
+
const folders = (text, cwd) => {
|
|
99
|
+
const f = new Set();
|
|
100
|
+
for (const x of text.matchAll(absAny)) if (siblings.has(x[1]) || mine(x[1])) f.add(x[1]);
|
|
101
|
+
if (cwd === parent) {
|
|
102
|
+
for (const x of text.matchAll(relAny)) if (siblings.has(x[1]) || mine(x[1])) f.add(x[1]);
|
|
103
|
+
for (const x of text.matchAll(cdAny)) if (siblings.has(x[1]) || mine(x[1])) f.add(x[1]);
|
|
104
|
+
}
|
|
105
|
+
return f;
|
|
106
|
+
};
|
|
107
|
+
return {
|
|
108
|
+
name, root, parent, folders,
|
|
109
|
+
// a session started inside another folder beside this one belongs to that folder
|
|
110
|
+
elsewhere: (cwd) => !!cwd && cwd.startsWith(parent + path.sep) && !inside(cwd) && siblings.has(cwd.slice(parent.length + 1).split(path.sep)[0]),
|
|
111
|
+
// is this turn mostly about this site? (a tie goes to the folder the turn touched first)
|
|
112
|
+
mostly(hits) {
|
|
113
|
+
let me = 0, myFirst = Infinity, i = 0;
|
|
114
|
+
const others = [];
|
|
115
|
+
for (const [f, n] of hits) {
|
|
116
|
+
if (mine(f)) { me += n; myFirst = Math.min(myFirst, i); } else others.push([n, i]);
|
|
117
|
+
i++;
|
|
118
|
+
}
|
|
119
|
+
if (!me) return false;
|
|
120
|
+
return others.every(([n, j]) => n < me || (n === me && myFirst < j));
|
|
121
|
+
},
|
|
122
|
+
// the file must name the repo's path, or run from its parent folder and name the repo
|
|
123
|
+
needles: [...forms.map((f) => Buffer.from(f)), Buffer.from(`"cwd":"${parent}"`), ...names.map((n) => Buffer.from(n))],
|
|
124
|
+
mentioned: (found) => found.slice(0, forms.length).some(Boolean) || (found[forms.length] && found.slice(forms.length + 1).some(Boolean)),
|
|
125
|
+
inside,
|
|
126
|
+
touches(text, cwd) {
|
|
127
|
+
if (abs.test(text)) return true;
|
|
128
|
+
if (cwd === parent && (rel.test(text) || cd.test(text))) return true;
|
|
129
|
+
return false;
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// cheap check before parsing: does the file mention the repo at all?
|
|
135
|
+
async function fileMentions(file, m) {
|
|
136
|
+
const fd = fs.openSync(file, 'r');
|
|
137
|
+
const size = 64 << 20, keep = 4096;
|
|
138
|
+
const buf = Buffer.alloc(size + keep);
|
|
139
|
+
const found = m.needles.map(() => false);
|
|
140
|
+
let carry = 0, pos = 0;
|
|
141
|
+
try {
|
|
142
|
+
for (;;) {
|
|
143
|
+
const n = fs.readSync(fd, buf, carry, size, pos);
|
|
144
|
+
if (n <= 0) return false;
|
|
145
|
+
const view = buf.subarray(0, carry + n);
|
|
146
|
+
m.needles.forEach((x, i) => { if (!found[i] && view.indexOf(x) !== -1) found[i] = true; });
|
|
147
|
+
if (m.mentioned(found)) return true;
|
|
148
|
+
pos += n;
|
|
149
|
+
carry = Math.min(keep, view.length);
|
|
150
|
+
view.copy(buf, 0, view.length - carry);
|
|
151
|
+
}
|
|
152
|
+
} finally {
|
|
153
|
+
fs.closeSync(fd);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function* lines(file) {
|
|
158
|
+
const rl = readline.createInterface({ input: fs.createReadStream(file), crlfDelay: Infinity });
|
|
159
|
+
for await (const l of rl) yield l;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const t = (s) => Date.parse(s) / 1000;
|
|
163
|
+
const tokensOut = (u) => (u && u.output_tokens) || 0;
|
|
164
|
+
|
|
165
|
+
// ---------- Claude Code ----------
|
|
166
|
+
// One turn = a prompt and everything the agent did until the next prompt.
|
|
167
|
+
// A turn counts for the repo if it ran inside it, or its tool calls touched this folder more than any other.
|
|
168
|
+
async function claudeSession(file, m) {
|
|
169
|
+
const turns = [];
|
|
170
|
+
let cur = null, cwd = null;
|
|
171
|
+
const seen = new Set();
|
|
172
|
+
const flush = () => { if (cur && (cur.hit || (!cur.elsewhere && m.mostly(cur.hits)))) turns.push(cur); };
|
|
173
|
+
for await (const line of lines(file)) {
|
|
174
|
+
if (!line.includes('"timestamp"')) continue;
|
|
175
|
+
let d;
|
|
176
|
+
try { d = JSON.parse(line); } catch { continue; }
|
|
177
|
+
// a message typed while the agent was still working: Claude Code files it as an attachment to the running turn, not
|
|
178
|
+
// as a prompt of its own. Only ones the person typed (the same queue carries task and subagent notices).
|
|
179
|
+
if (d.type === 'attachment') {
|
|
180
|
+
const a = d.attachment;
|
|
181
|
+
if (cur && d.timestamp && a && a.type === 'queued_command' && a.origin && a.origin.kind === 'human') {
|
|
182
|
+
const id = a.source_uuid || a.delivery_id || d.uuid;
|
|
183
|
+
if (!seen.has(id)) { seen.add(id); cur.typed.push(t(d.timestamp)); }
|
|
184
|
+
}
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if ((d.type !== 'user' && d.type !== 'assistant') || !d.timestamp) continue;
|
|
188
|
+
cwd = d.cwd || cwd;
|
|
189
|
+
const msg = d.message && typeof d.message === 'object' ? d.message : {};
|
|
190
|
+
const c = msg.content;
|
|
191
|
+
if (d.type === 'user') {
|
|
192
|
+
const isResult = Array.isArray(c) && c.some((x) => x && x.type === 'tool_result');
|
|
193
|
+
if (!isResult && !d.isMeta) {
|
|
194
|
+
flush();
|
|
195
|
+
const now = t(d.timestamp);
|
|
196
|
+
cur = { start: now, human: !!(d.origin && d.origin.kind === 'human'), typed: [], out: 0, segs: [[now, now]], hit: m.inside(cwd), elsewhere: m.elsewhere(cwd), hits: new Map() };
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (!cur) continue;
|
|
201
|
+
const now = t(d.timestamp);
|
|
202
|
+
const last = cur.segs[cur.segs.length - 1];
|
|
203
|
+
if (now - last[1] <= GAP) last[1] = Math.max(last[1], now);
|
|
204
|
+
else cur.segs.push([now, now]);
|
|
205
|
+
if (d.type === 'assistant') {
|
|
206
|
+
const rid = d.requestId || msg.id;
|
|
207
|
+
if (msg.usage && !seen.has(rid)) { seen.add(rid); cur.out += tokensOut(msg.usage); }
|
|
208
|
+
if (!cur.hit && Array.isArray(c)) {
|
|
209
|
+
for (const x of c) {
|
|
210
|
+
if (!x || x.type !== 'tool_use') continue;
|
|
211
|
+
for (const f of m.folders(JSON.stringify(x.input ?? ''), cwd)) cur.hits.set(f, (cur.hits.get(f) || 0) + 1);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
flush();
|
|
217
|
+
if (!turns.length) return null;
|
|
218
|
+
return {
|
|
219
|
+
tool: 'claude',
|
|
220
|
+
turns: turns.length,
|
|
221
|
+
prompts: turns.reduce((a, x) => a + (x.human ? 1 : 0) + x.typed.length, 0),
|
|
222
|
+
out: turns.reduce((a, x) => a + x.out, 0),
|
|
223
|
+
// prompts by the day they were typed (a turn's own prompt at its start), and work segments for hours
|
|
224
|
+
starts: [...turns.filter((x) => x.human).map((x) => x.start), ...turns.flatMap((x) => x.typed)].map(Math.round),
|
|
225
|
+
segs: turns.flatMap((x) => x.segs.filter(([a, b]) => b > a).map(([a, b]) => [Math.round(a), Math.round(b)])),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function claudeSubagent(file, m) {
|
|
230
|
+
let cwd = null, out = 0, hit = false;
|
|
231
|
+
const seen = new Set();
|
|
232
|
+
for await (const line of lines(file)) {
|
|
233
|
+
let d;
|
|
234
|
+
try { d = JSON.parse(line); } catch { continue; }
|
|
235
|
+
cwd = d.cwd || cwd;
|
|
236
|
+
if (m.inside(cwd)) hit = true;
|
|
237
|
+
if (d.type !== 'assistant') continue;
|
|
238
|
+
const msg = d.message && typeof d.message === 'object' ? d.message : {};
|
|
239
|
+
const rid = d.requestId || msg.id;
|
|
240
|
+
if (msg.usage && !seen.has(rid)) { seen.add(rid); out += tokensOut(msg.usage); }
|
|
241
|
+
if (!hit && Array.isArray(msg.content)) {
|
|
242
|
+
for (const x of msg.content) if (x && x.type === 'tool_use' && m.touches(JSON.stringify(x.input ?? ''), cwd)) { hit = true; break; }
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return hit ? { tool: 'claude-subagent', out } : null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ---------- Codex ----------
|
|
249
|
+
async function codexSession(file, m) {
|
|
250
|
+
let cwd = null, origin = null, out = 0, hit = false;
|
|
251
|
+
const segs = [], items = [];
|
|
252
|
+
let starts = [];
|
|
253
|
+
for await (const line of lines(file)) {
|
|
254
|
+
let d;
|
|
255
|
+
try { d = JSON.parse(line); } catch { continue; }
|
|
256
|
+
const p = d.payload || {};
|
|
257
|
+
if (d.type === 'session_meta') { cwd = p.cwd || cwd; origin = p.originator || null; }
|
|
258
|
+
if (d.type === 'turn_context' && p.cwd) cwd = p.cwd;
|
|
259
|
+
if (m.inside(cwd)) hit = true;
|
|
260
|
+
if (d.timestamp) {
|
|
261
|
+
const now = t(d.timestamp);
|
|
262
|
+
const last = segs[segs.length - 1];
|
|
263
|
+
if (last && now - last[1] <= GAP) last[1] = Math.max(last[1], now);
|
|
264
|
+
else segs.push([now, now]);
|
|
265
|
+
}
|
|
266
|
+
if (origin !== 'codex_exec' && d.timestamp) {
|
|
267
|
+
if (p.type === 'user_message') starts.push(Math.round(t(d.timestamp)));
|
|
268
|
+
if (p.type === 'item_completed' && p.item && p.item.type === 'UserMessage') items.push(Math.round(t(d.timestamp)));
|
|
269
|
+
}
|
|
270
|
+
if (p.type === 'token_count' && p.info && p.info.total_token_usage) out = p.info.total_token_usage.output_tokens || 0;
|
|
271
|
+
}
|
|
272
|
+
if (!hit) return null;
|
|
273
|
+
if (items.length > starts.length) starts = items;
|
|
274
|
+
return {
|
|
275
|
+
tool: origin === 'codex_exec' ? 'codex-run' : 'codex',
|
|
276
|
+
prompts: starts.length, out, starts,
|
|
277
|
+
segs: segs.filter(([a, b]) => b > a).map(([a, b]) => [Math.round(a), Math.round(b)]),
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// ---------- bank ----------
|
|
282
|
+
function bankPath(root) {
|
|
283
|
+
// (a different --also is a different count, so it gets its own bank)
|
|
284
|
+
const also = [...ALSO].sort().join('+');
|
|
285
|
+
const key = (root + (also ? '+' + also : '')).replace(/[^\w.+-]+/g, '_').replace(/^_+/, '');
|
|
286
|
+
return path.join(STORE, 'bank', key + '.json');
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function readJSON(p, fallback) {
|
|
290
|
+
try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return fallback; }
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function writeJSON(p, v, mode) {
|
|
294
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
295
|
+
fs.writeFileSync(p, JSON.stringify(v, null, 1) + '\n', mode ? { mode } : undefined);
|
|
296
|
+
if (mode) fs.chmodSync(p, mode);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async function scan(root, { quiet } = {}) {
|
|
300
|
+
const m = makeMatcher(root);
|
|
301
|
+
const bp = bankPath(root);
|
|
302
|
+
let bank = readJSON(bp, null);
|
|
303
|
+
if (!bank || bank.v !== BANK_VERSION) bank = { v: BANK_VERSION, root, sessions: {}, files: {} };
|
|
304
|
+
const ccDir = path.join(HOME, '.claude', 'projects');
|
|
305
|
+
const cxDir = path.join(HOME, '.codex', 'sessions');
|
|
306
|
+
const main = listFiles(ccDir, (p) => p.endsWith('.jsonl') && path.basename(path.dirname(p)) !== 'subagents', 1)
|
|
307
|
+
.filter((p) => path.dirname(path.dirname(p)) === ccDir);
|
|
308
|
+
const subs = listFiles(ccDir, (p) => p.endsWith('.jsonl') && path.basename(path.dirname(p)) === 'subagents', 3);
|
|
309
|
+
const codex = listFiles(cxDir, (p) => p.endsWith('.jsonl'), 4);
|
|
310
|
+
const all = [...main.map((f) => ['main', f]), ...subs.map((f) => ['sub', f]), ...codex.map((f) => ['codex', f])];
|
|
311
|
+
let read = 0;
|
|
312
|
+
for (const [kind, f] of all) {
|
|
313
|
+
let st;
|
|
314
|
+
try { st = fs.statSync(f); } catch { continue; }
|
|
315
|
+
const key = kind + ':' + path.relative(HOME, f);
|
|
316
|
+
if (bank.files[key] === st.mtimeMs) continue; // unchanged since last run
|
|
317
|
+
if (await fileMentions(f, m)) {
|
|
318
|
+
const r = kind === 'main' ? await claudeSession(f, m) : kind === 'sub' ? await claudeSubagent(f, m) : await codexSession(f, m);
|
|
319
|
+
read++;
|
|
320
|
+
const old = bank.sessions[key];
|
|
321
|
+
// logs only grow, until they're deleted; never let a shorter read replace a longer one
|
|
322
|
+
if (r && (!old || (r.turns ?? r.segs?.length ?? 0) >= (old.turns ?? old.segs?.length ?? 0))) bank.sessions[key] = r;
|
|
323
|
+
}
|
|
324
|
+
bank.files[key] = st.mtimeMs;
|
|
325
|
+
if (!quiet && read && read % 10 === 0) process.stderr.write(` read ${read} logs\r`);
|
|
326
|
+
}
|
|
327
|
+
bank.scanned = new Date().toISOString();
|
|
328
|
+
writeJSON(bp, bank);
|
|
329
|
+
return bank;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// ---------- the receipt ----------
|
|
333
|
+
const localDay = (s) => {
|
|
334
|
+
const d = new Date(s * 1000);
|
|
335
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
function union(segs) {
|
|
339
|
+
const s = [...segs].sort((a, b) => a[0] - b[0]);
|
|
340
|
+
let tot = 0, cur = null;
|
|
341
|
+
for (const [a, b] of s) {
|
|
342
|
+
if (cur && a <= cur[1]) cur[1] = Math.max(cur[1], b);
|
|
343
|
+
else { if (cur) tot += cur[1] - cur[0]; cur = [a, b]; }
|
|
344
|
+
}
|
|
345
|
+
if (cur) tot += cur[1] - cur[0];
|
|
346
|
+
return tot;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function summarize(bank, root) {
|
|
350
|
+
const S = Object.values(bank.sessions);
|
|
351
|
+
const segs = S.flatMap((s) => s.segs || []);
|
|
352
|
+
const byDay = {};
|
|
353
|
+
const day = (d) => (byDay[d] ||= { prompts: 0, hours: 0 });
|
|
354
|
+
for (const s of S) for (const x of s.starts || []) day(localDay(x)).prompts++;
|
|
355
|
+
// hours per day: split the merged work segments at midnight
|
|
356
|
+
const merged = [];
|
|
357
|
+
for (const [a, b] of [...segs].sort((x, y) => x[0] - y[0])) {
|
|
358
|
+
const last = merged[merged.length - 1];
|
|
359
|
+
if (last && a <= last[1]) last[1] = Math.max(last[1], b);
|
|
360
|
+
else merged.push([a, b]);
|
|
361
|
+
}
|
|
362
|
+
for (let [a, b] of merged) {
|
|
363
|
+
while (a < b) {
|
|
364
|
+
const d = new Date(a * 1000);
|
|
365
|
+
const next = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1).getTime() / 1000;
|
|
366
|
+
const end = Math.min(b, next);
|
|
367
|
+
day(localDay(a)).hours += (end - a) / 3600;
|
|
368
|
+
a = end;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
const days = Object.keys(byDay).sort().filter((d) => byDay[d].hours > 0 || byDay[d].prompts > 0);
|
|
372
|
+
for (const d of days) byDay[d].hours = Math.round(byDay[d].hours * 10) / 10;
|
|
373
|
+
const tools = [...new Set(S.map((s) => (s.tool.startsWith('codex') ? 'codex' : 'claude-code')))].sort();
|
|
374
|
+
return {
|
|
375
|
+
slopcard: VERSION,
|
|
376
|
+
project: path.basename(root),
|
|
377
|
+
measured: new Date().toISOString(),
|
|
378
|
+
prompts: S.reduce((a, s) => a + (s.prompts || 0), 0),
|
|
379
|
+
hours: Math.round((union(segs) / 3600) * 10) / 10,
|
|
380
|
+
days: days.length,
|
|
381
|
+
tokens_written: S.reduce((a, s) => a + (s.out || 0), 0),
|
|
382
|
+
sessions: S.filter((s) => s.tool === 'claude' || s.tool === 'codex').length,
|
|
383
|
+
first: days[0] || null,
|
|
384
|
+
last: days[days.length - 1] || null,
|
|
385
|
+
tools,
|
|
386
|
+
by_day: Object.fromEntries(days.map((d) => [d, byDay[d]])),
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const fmt = (n) => n >= 1e9 ? (n / 1e9).toFixed(1) + 'B' : n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? Math.round(n / 1e3) + 'K' : String(n);
|
|
391
|
+
|
|
392
|
+
async function measure(root, opts = {}) {
|
|
393
|
+
if (!opts.quiet) process.stderr.write(`${NAME}: reading your agent logs for ${path.basename(root)}...\n`);
|
|
394
|
+
const bank = await scan(root, opts);
|
|
395
|
+
const r = summarize(bank, root);
|
|
396
|
+
const file = arg('out') ? path.resolve(arg('out')) : path.join(root, 'slopcard.json');
|
|
397
|
+
const prev = readJSON(file, {});
|
|
398
|
+
if (prev.site) r.site = prev.site;
|
|
399
|
+
if (ALSO.length) r.also = ALSO;
|
|
400
|
+
writeJSON(file, r);
|
|
401
|
+
if (!opts.quiet && !r.days) console.log(`No Claude Code or Codex work found for ${path.basename(root)} in this computer's logs.`);
|
|
402
|
+
else if (!opts.quiet) {
|
|
403
|
+
console.log(`${r.prompts} prompt${r.prompts === 1 ? '' : 's'} · ${r.hours} agent hours · ${r.days} day${r.days === 1 ? '' : 's'} · ${fmt(r.tokens_written)} tokens written`);
|
|
404
|
+
console.log(`${r.first ?? '-'} to ${r.last ?? '-'} · ${r.sessions} session${r.sessions === 1 ? '' : 's'} · saved ${path.relative(process.cwd(), file) || file}`);
|
|
405
|
+
}
|
|
406
|
+
return r;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// ---------- submit ----------
|
|
410
|
+
function arg(name) {
|
|
411
|
+
const i = process.argv.indexOf('--' + name);
|
|
412
|
+
return i > 0 ? process.argv[i + 1] : undefined;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function normalizeUrl(u) {
|
|
416
|
+
if (!u) return null;
|
|
417
|
+
if (!/^https?:\/\//i.test(u)) u = 'https://' + u;
|
|
418
|
+
try {
|
|
419
|
+
const x = new URL(u);
|
|
420
|
+
// (plain http only for a test page, when sending to a test server on this computer)
|
|
421
|
+
const local = /^http:\/\/(localhost|127\.0\.0\.1)[:/]/.test(BASE + '/');
|
|
422
|
+
if (x.protocol !== 'https:' && !(local && x.protocol === 'http:' && /^(localhost|127\.0\.0\.1)$/.test(x.hostname))) return null;
|
|
423
|
+
x.hash = ''; x.search = '';
|
|
424
|
+
return x.toString().replace(/\/$/, '');
|
|
425
|
+
} catch { return null; }
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
async function ask(q) {
|
|
429
|
+
if (!process.stdin.isTTY) return false;
|
|
430
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
431
|
+
const a = await new Promise((res) => rl.question(q, res));
|
|
432
|
+
rl.close();
|
|
433
|
+
return /^y(es)?$/i.test(a.trim());
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
async function submit(root) {
|
|
437
|
+
const r = await measure(root);
|
|
438
|
+
if (!r.days) {
|
|
439
|
+
console.error(`\nNo agent work found for ${path.basename(root)}, so there's nothing to send. Run this in the folder the site was built in.`);
|
|
440
|
+
process.exit(1);
|
|
441
|
+
}
|
|
442
|
+
const file = arg('out') ? path.resolve(arg('out')) : path.join(root, 'slopcard.json');
|
|
443
|
+
const url = normalizeUrl(arg('url') || r.site?.url);
|
|
444
|
+
if (!url) { console.error('\nAdd the site\'s address: npx slopcard submit --url https://yoursite.com'); process.exit(1); }
|
|
445
|
+
const name = (arg('name') || r.site?.name || new URL(url).hostname.replace(/^www\./, '')).slice(0, 60);
|
|
446
|
+
const keys = readJSON(path.join(STORE, 'keys.json'), {});
|
|
447
|
+
if (r.site?.slug && !keys[url]) {
|
|
448
|
+
// made on another computer: its key lives there, so don't start a second slopcard for the same site
|
|
449
|
+
console.error(`\n${url} already has a slopcard, made on another computer. Send updates from that one.`);
|
|
450
|
+
process.exit(1);
|
|
451
|
+
}
|
|
452
|
+
const payload = {
|
|
453
|
+
url, name,
|
|
454
|
+
prompts: r.prompts, hours: r.hours, days: r.days, tokens_written: r.tokens_written,
|
|
455
|
+
first: r.first, last: r.last, tools: r.tools, by_day: r.by_day,
|
|
456
|
+
};
|
|
457
|
+
console.log(`\nThis is everything that will be sent to ${BASE}:\n`);
|
|
458
|
+
console.log(JSON.stringify(payload, null, 1));
|
|
459
|
+
if (!process.argv.includes('--yes') && !(await ask('\nSend it? (y/N) '))) {
|
|
460
|
+
console.log('Not sent. Run again with --yes once your user has seen this.');
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
const res = await fetch(BASE + '/api/submit', {
|
|
464
|
+
method: 'POST',
|
|
465
|
+
headers: { 'content-type': 'application/json', ...(keys[url] ? { 'x-slopcard-key': keys[url] } : {}) },
|
|
466
|
+
body: JSON.stringify(payload),
|
|
467
|
+
});
|
|
468
|
+
const body = await res.json().catch(() => ({}));
|
|
469
|
+
if (!res.ok) { console.error(`\nNot sent: ${body.error || res.status}`); process.exit(1); }
|
|
470
|
+
if (body.key) { keys[url] = body.key; writeJSON(path.join(STORE, 'keys.json'), keys, 0o600); }
|
|
471
|
+
r.site = { url, name, slug: body.slug, page: body.page, badge: body.badge };
|
|
472
|
+
writeJSON(file, r);
|
|
473
|
+
console.log(`\nSent. Slopcard: ${body.page}`);
|
|
474
|
+
console.log(body.listed ? `Listed at ${BASE}/directory.` : `It joins the directory at ${BASE}/directory by itself the first time the badge loads on ${url}.`);
|
|
475
|
+
printBadge(r);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function printBadge(r) {
|
|
479
|
+
const s = r.site;
|
|
480
|
+
if (!s || !s.slug) { console.error('Submit first: npx slopcard submit --url https://yoursite.com'); process.exit(1); }
|
|
481
|
+
const alt = `Slopcard: ${r.prompts} prompt${r.prompts === 1 ? '' : 's'}, ${r.days} day${r.days === 1 ? '' : 's'}`;
|
|
482
|
+
console.log('\nPut this where the site has room, usually the footer. The badge opens the slopcard in a modal:\n');
|
|
483
|
+
console.log(`<a href="${s.page}"><img src="${s.badge}" alt="${alt}" height="24"></a>`);
|
|
484
|
+
console.log(`<script async src="${BASE}/embed.js"></script>`);
|
|
485
|
+
console.log(`\nDark sites: add ?theme=dark to the image address. In a README, the first line alone is enough.`);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// ---------- main ----------
|
|
489
|
+
// (keep the fixed copy the hook runs, so `npx slopcard` today leaves `node ~/.slopcard/slopcard.mjs` working tomorrow)
|
|
490
|
+
try {
|
|
491
|
+
const me = fileURLToPath(import.meta.url), copy = path.join(STORE, 'slopcard.mjs');
|
|
492
|
+
if (path.resolve(me) !== path.resolve(copy)) { fs.mkdirSync(STORE, { recursive: true }); fs.copyFileSync(me, copy); }
|
|
493
|
+
} catch { /* read-only home, or run from a URL: the counts don't need the copy */ }
|
|
494
|
+
const cmd = process.argv[2] && !process.argv[2].startsWith('--') ? process.argv[2] : 'measure';
|
|
495
|
+
const root = arg('repo') ? path.resolve(arg('repo')) : repoRoot();
|
|
496
|
+
// --also is kept in slopcard.json, so a later plain `submit --yes` (the AGENTS.md note) counts the same folders
|
|
497
|
+
const ALSO = (arg('also') ?? (readJSON(arg('out') ? path.resolve(arg('out')) : path.join(root, 'slopcard.json'), {}).also || []).join(','))
|
|
498
|
+
.split(',').map((x) => x.trim()).filter(Boolean);
|
|
499
|
+
if (cmd === 'measure') await measure(root);
|
|
500
|
+
else if (cmd === 'submit') await submit(root);
|
|
501
|
+
else if (cmd === 'badge') printBadge(readJSON(arg('out') ? path.resolve(arg('out')) : path.join(root, 'slopcard.json'), {}));
|
|
502
|
+
else { console.error(`Unknown command: ${cmd}. Try: measure, submit, badge`); process.exit(1); }
|