agentblame 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +197 -2
- package/bin/agentblame.js +129 -0
- package/package.json +40 -4
- package/src/attribute.js +180 -0
- package/src/cache.js +56 -0
- package/src/commands/blame.js +76 -0
- package/src/commands/map-template.js +133 -0
- package/src/commands/map.js +53 -0
- package/src/commands/notes.js +67 -0
- package/src/commands/pr.js +254 -0
- package/src/commands/stats.js +71 -0
- package/src/format.js +28 -0
- package/src/git.js +56 -0
- package/src/normalize.js +60 -0
- package/src/progress.js +24 -0
- package/src/redact.js +55 -0
- package/src/sources/claude.js +202 -0
- package/src/sources/codex.js +213 -0
- package/src/sources/shell.js +187 -0
- package/src/sources/walk.js +13 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { attributeFile } from '../attribute.js';
|
|
2
|
+
import { redact, truncate } from '../redact.js';
|
|
3
|
+
import { bold, cyan, date, dim, gray, magenta, pad, shortModel, who, yellow } from '../format.js';
|
|
4
|
+
|
|
5
|
+
export function serialize(r, { noPrompts } = {}) {
|
|
6
|
+
const o = { line: r.line, kind: r.kind, text: r.text };
|
|
7
|
+
if (r.match) { o.match = r.match; o.confidence = r.confidence; }
|
|
8
|
+
if (r.similarity) o.similarity = r.similarity;
|
|
9
|
+
if (r.event) {
|
|
10
|
+
o.agent = {
|
|
11
|
+
source: r.event.source, model: r.event.model, sessionId: r.event.sessionId, at: new Date(r.event.ts).toISOString(),
|
|
12
|
+
tool: r.event.tool, subagent: !!r.event.subagent,
|
|
13
|
+
...(noPrompts ? {} : { prompt: truncate(redact(r.event.prompt), 500) }),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
if (r.blame && !r.blame.uncommitted) o.commit = r.blame.commit;
|
|
17
|
+
return o;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function cmdBlame(ctx, rel, target, opts) {
|
|
21
|
+
const res = attributeFile(ctx, rel);
|
|
22
|
+
if (!res) { console.error(`agentblame: cannot read ${rel}`); process.exit(1); }
|
|
23
|
+
const from = target.start || 1;
|
|
24
|
+
const to = target.end || res.length;
|
|
25
|
+
const slice = res.slice(from - 1, to);
|
|
26
|
+
|
|
27
|
+
if (opts.json) { console.log(JSON.stringify({ file: rel, lines: slice.map((r) => serialize(r, opts)) }, null, 2)); return; }
|
|
28
|
+
|
|
29
|
+
const w = String(to).length;
|
|
30
|
+
let lastKey = null;
|
|
31
|
+
for (const r of slice) {
|
|
32
|
+
const key = r.event ? `${r.event.idx}` : r.kind;
|
|
33
|
+
const label = pad(who(r), 18);
|
|
34
|
+
const tag = r.kind === 'agent' ? magenta(label) : r.kind === 'modified' ? yellow(label) : r.kind === 'human' ? cyan(label) : gray(label);
|
|
35
|
+
let note = '';
|
|
36
|
+
if (r.event && key !== lastKey) note = truncate(redact(r.event.prompt || ''), 38);
|
|
37
|
+
else if (r.event) note = '〃';
|
|
38
|
+
else if (r.blame && !r.blame.uncommitted && r.kind !== 'trivial') note = `${r.blame.commit.slice(0, 8)} ${date(r.blame.authorTime)}`;
|
|
39
|
+
lastKey = key;
|
|
40
|
+
console.log(`${dim(String(r.line).padStart(w))} ${tag} ${dim(pad(note, 40))} │ ${r.text}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function cmdWhy(ctx, rel, line, opts) {
|
|
45
|
+
const res = attributeFile(ctx, rel);
|
|
46
|
+
const r = res?.[line - 1];
|
|
47
|
+
if (!r) { console.error(`agentblame: no line ${line} in ${rel}`); process.exit(1); }
|
|
48
|
+
if (opts.json) { console.log(JSON.stringify(serialize(r, opts), null, 2)); return; }
|
|
49
|
+
console.log(`${bold(`${rel}:${line}`)} ${dim(r.text.trim())}\n`);
|
|
50
|
+
if (!r.event) {
|
|
51
|
+
const msg = {
|
|
52
|
+
human: 'Written by a human (no agent edit in your transcripts produced this line).',
|
|
53
|
+
unknown: 'Predates the transcripts on this machine — origin unknown.',
|
|
54
|
+
trivial: 'Trivial line (braces, blank, keywords) — not attributed.',
|
|
55
|
+
}[r.kind];
|
|
56
|
+
console.log(msg);
|
|
57
|
+
if (r.blame && !r.blame.uncommitted) console.log(dim(`commit ${r.blame.commit.slice(0, 12)} by ${r.blame.author} on ${date(r.blame.authorTime)}`));
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const e = r.event;
|
|
61
|
+
const kind = r.kind === 'agent'
|
|
62
|
+
? `Written by an agent (${r.match} match, ${r.confidence} confidence)`
|
|
63
|
+
: `Written by an agent, then edited by a human (${Math.round(r.similarity * 100)}% similar to the agent's version)`;
|
|
64
|
+
console.log(kind);
|
|
65
|
+
console.log(` agent ${e.source}${e.subagent ? ' (subagent)' : ''} · ${shortModel(e.model) || 'unknown model'} · ${e.tool}`);
|
|
66
|
+
console.log(` when ${new Date(e.ts).toLocaleString()}`);
|
|
67
|
+
console.log(` session ${e.sessionId || '—'}`);
|
|
68
|
+
if (e.fromNote) console.log(` from git note on ${e.fromNote.slice(0, 12)}`);
|
|
69
|
+
else console.log(` transcript ${dim(e.transcript)}`);
|
|
70
|
+
if (e.userModified) console.log(` note ${yellow('you modified this edit when approving it')}`);
|
|
71
|
+
console.log(`\n${bold('Prompt')}\n${indent(redact(e.prompt) || dim('(no prompt captured)'))}\n`);
|
|
72
|
+
if (e.source === 'claude' && e.sessionId) console.log(dim(`Resume it: claude --resume ${e.sessionId}`));
|
|
73
|
+
if (r.kind === 'modified' && r.original != null) console.log(dim(`Agent's original: ${r.original.trim()}`));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function indent(s) { return String(s).split('\n').slice(0, 30).map((l) => ` ${l}`).join('\n'); }
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// Self-contained provenance map. All untrusted strings (code, prompts) are
|
|
2
|
+
// rendered with textContent — never innerHTML.
|
|
3
|
+
export const HTML_TEMPLATE = `<!doctype html>
|
|
4
|
+
<html lang="en">
|
|
5
|
+
<head>
|
|
6
|
+
<meta charset="utf-8">
|
|
7
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
8
|
+
<title>agentblame · provenance map</title>
|
|
9
|
+
<style>
|
|
10
|
+
:root{--bg:#fbfaf8;--fg:#1d1b19;--mute:#6f6a64;--line:#e7e3de;--panel:#fff;--ai:#1e56d9;--mod:#b45309;--hu:#2f7d5f;--un:#b9bdb8;--hl:#f3efe9}
|
|
11
|
+
@media (prefers-color-scheme:dark){:root{--bg:#141312;--fg:#ece8e3;--mute:#9a948d;--line:#2b2826;--panel:#1b1a18;--ai:#7aa2ff;--mod:#f0a24a;--hu:#5cc79f;--un:#4a4f54;--hl:#24221f}}
|
|
12
|
+
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
13
|
+
header{padding:28px 32px 18px;border-bottom:1px solid var(--line)}
|
|
14
|
+
h1{font-size:13px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--mute);margin:0 0 6px}
|
|
15
|
+
.big{font-size:44px;font-weight:700;letter-spacing:-.02em;line-height:1.1}
|
|
16
|
+
.big small{font-size:16px;font-weight:500;color:var(--mute);letter-spacing:0}
|
|
17
|
+
.bar{display:flex;height:10px;border-radius:5px;overflow:hidden;margin:14px 0 8px;max-width:720px;background:var(--line)}
|
|
18
|
+
.bar i{display:block}.legend{display:flex;gap:18px;flex-wrap:wrap;color:var(--mute);font-size:12.5px}
|
|
19
|
+
.legend b{display:inline-block;width:9px;height:9px;border-radius:2px;margin-right:6px;vertical-align:0}
|
|
20
|
+
main{display:grid;grid-template-columns:minmax(260px,340px) 1fr;min-height:calc(100vh - 150px)}
|
|
21
|
+
aside{border-right:1px solid var(--line);overflow:auto;max-height:calc(100vh - 150px)}
|
|
22
|
+
.sec{padding:14px 16px 6px;font-size:11.5px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;color:var(--mute)}
|
|
23
|
+
.prompt{padding:8px 16px;font-size:12.5px;border-bottom:1px solid var(--line)}
|
|
24
|
+
.prompt .n{font-variant-numeric:tabular-nums;font-weight:600;color:var(--ai)}
|
|
25
|
+
.file{display:grid;grid-template-columns:1fr 54px;gap:8px;align-items:center;padding:6px 16px;cursor:pointer;font:12.5px ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
26
|
+
.file:hover,.file.on{background:var(--hl)}.file span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;direction:rtl;text-align:left}
|
|
27
|
+
.mini{display:flex;height:6px;border-radius:3px;overflow:hidden;background:var(--line)}
|
|
28
|
+
input{margin:10px 16px;width:calc(100% - 32px);padding:7px 10px;border:1px solid var(--line);border-radius:6px;background:var(--panel);color:var(--fg);font:inherit}
|
|
29
|
+
section{overflow:auto;max-height:calc(100vh - 150px)}
|
|
30
|
+
.code{font:12.5px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;padding:8px 0 40px}
|
|
31
|
+
.ln{display:grid;grid-template-columns:4px 52px 1fr;white-space:pre}.ln:hover{background:var(--hl)}
|
|
32
|
+
.ln .g{}.ln .no{color:var(--mute);text-align:right;padding-right:14px;user-select:none}
|
|
33
|
+
.ln.a .g{background:var(--ai)}.ln.m .g{background:var(--mod)}.ln.h .g{background:var(--hu)}.ln.u .g{background:var(--un)}
|
|
34
|
+
.ln.start{border-top:1px dashed var(--line)}
|
|
35
|
+
.fh{position:sticky;top:0;background:var(--bg);padding:12px 20px;border-bottom:1px solid var(--line);font:600 13px ui-monospace,Menlo,monospace;z-index:1}
|
|
36
|
+
#tip{position:fixed;pointer-events:none;max-width:440px;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:10px 12px;font-size:12.5px;box-shadow:0 8px 30px rgba(0,0,0,.12);display:none;z-index:5}
|
|
37
|
+
#tip .k{font-weight:600;margin-bottom:4px}#tip .p{white-space:pre-wrap;color:var(--fg)}#tip .meta{color:var(--mute);margin-top:6px;font-size:11.5px}
|
|
38
|
+
footer{color:var(--mute);font-size:12px;padding:10px 32px;border-top:1px solid var(--line)}
|
|
39
|
+
@media (max-width:760px){main{grid-template-columns:1fr}aside,section{max-height:none}}
|
|
40
|
+
</style>
|
|
41
|
+
</head>
|
|
42
|
+
<body>
|
|
43
|
+
<header>
|
|
44
|
+
<h1 id="repo"></h1>
|
|
45
|
+
<div class="big" id="share"></div>
|
|
46
|
+
<div class="bar" id="bar"></div>
|
|
47
|
+
<div class="legend">
|
|
48
|
+
<span><b style="background:var(--ai)"></b>agent-written</span>
|
|
49
|
+
<span><b style="background:var(--mod)"></b>agent-written, human-edited</span>
|
|
50
|
+
<span><b style="background:var(--hu)"></b>human</span>
|
|
51
|
+
<span><b style="background:var(--un)"></b>before transcripts began</span>
|
|
52
|
+
<span id="cov"></span>
|
|
53
|
+
</div>
|
|
54
|
+
</header>
|
|
55
|
+
<main>
|
|
56
|
+
<aside>
|
|
57
|
+
<div class="sec">Prompts that wrote the most surviving code</div>
|
|
58
|
+
<div id="prompts"></div>
|
|
59
|
+
<div class="sec">Files</div>
|
|
60
|
+
<input id="q" placeholder="Filter files…" aria-label="Filter files">
|
|
61
|
+
<div id="files"></div>
|
|
62
|
+
</aside>
|
|
63
|
+
<section id="view"></section>
|
|
64
|
+
</main>
|
|
65
|
+
<footer>Generated by <b>agentblame</b> on <span id="gen"></span>. Attribution is inferred from local agent transcripts and git history; see confidence notes in the README.</footer>
|
|
66
|
+
<div id="tip"></div>
|
|
67
|
+
<script>
|
|
68
|
+
const D = __DATA__;
|
|
69
|
+
const $ = (id) => document.getElementById(id);
|
|
70
|
+
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
|
|
71
|
+
const T = D.total, att = T.attributable || 1;
|
|
72
|
+
$('repo').textContent = D.repo + ' · provenance map';
|
|
73
|
+
$('share').textContent = (T.agentShare * 100).toFixed(1) + '% ';
|
|
74
|
+
$('share').append(el('small', null, 'of ' + att.toLocaleString() + ' attributable lines were written by AI agents'));
|
|
75
|
+
const seg = (w, c) => { const i = el('i'); i.style.width = (w * 100) + '%'; i.style.background = c; return i; };
|
|
76
|
+
const tot = T.agent + T.modified + T.human + T.unknown || 1;
|
|
77
|
+
$('bar').append(seg(T.agent / tot, 'var(--ai)'), seg(T.modified / tot, 'var(--mod)'), seg(T.human / tot, 'var(--hu)'), seg(T.unknown / tot, 'var(--un)'));
|
|
78
|
+
if (D.coverageStart) $('cov').textContent = 'transcripts from ' + new Date(D.coverageStart).toISOString().slice(0, 10);
|
|
79
|
+
$('gen').textContent = new Date(D.generated).toLocaleString();
|
|
80
|
+
for (const p of D.prompts) {
|
|
81
|
+
const d = el('div', 'prompt');
|
|
82
|
+
d.append(el('span', 'n', p.lines + ' lines'), document.createTextNode(' · ' + p.model + ' · ' + p.files + ' file(s)'), el('div', null, p.p || '(prompt hidden)'));
|
|
83
|
+
$('prompts').append(d);
|
|
84
|
+
}
|
|
85
|
+
function mini(f) {
|
|
86
|
+
const m = el('div', 'mini'); const n = (f.a + f.m + f.h + f.u) || 1;
|
|
87
|
+
m.append(seg(f.a / n, 'var(--ai)'), seg(f.m / n, 'var(--mod)'), seg(f.h / n, 'var(--hu)'), seg(f.u / n, 'var(--un)'));
|
|
88
|
+
return m;
|
|
89
|
+
}
|
|
90
|
+
let current = null;
|
|
91
|
+
function renderList() {
|
|
92
|
+
const q = $('q').value.toLowerCase(); $('files').replaceChildren();
|
|
93
|
+
for (const f of D.files) {
|
|
94
|
+
if (q && !f.f.toLowerCase().includes(q)) continue;
|
|
95
|
+
const row = el('div', 'file' + (current === f ? ' on' : ''));
|
|
96
|
+
const name = el('span'); name.append(el('bdi', null, f.f)); row.append(name, mini(f));
|
|
97
|
+
row.title = f.f + ' — ' + (f.s * 100).toFixed(0) + '% agent';
|
|
98
|
+
row.onclick = () => { current = f; renderList(); renderFile(f); };
|
|
99
|
+
$('files').append(row);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function renderFile(f) {
|
|
103
|
+
const v = $('view'); v.replaceChildren(); v.scrollTop = 0;
|
|
104
|
+
v.append(el('div', 'fh', f.f + ' · ' + (f.s * 100).toFixed(1) + '% agent-written'));
|
|
105
|
+
const code = el('div', 'code');
|
|
106
|
+
for (let i = 0; i < f.t.length; i++) {
|
|
107
|
+
const k = f.k[i]; const e = f.e[i];
|
|
108
|
+
const ln = el('div', 'ln ' + k + (e >= 0 && e !== f.e[i - 1] ? ' start' : ''));
|
|
109
|
+
ln.append(el('span', 'g'), el('span', 'no', String(i + 1)), el('span', null, f.t[i]));
|
|
110
|
+
ln.dataset.i = i;
|
|
111
|
+
code.append(ln);
|
|
112
|
+
}
|
|
113
|
+
code.onmousemove = (ev) => {
|
|
114
|
+
const ln = ev.target.closest('.ln'); const tip = $('tip');
|
|
115
|
+
if (!ln) { tip.style.display = 'none'; return; }
|
|
116
|
+
const i = +ln.dataset.i, k = f.k[i], e = f.e[i];
|
|
117
|
+
if (e < 0) { tip.style.display = 'none'; return; }
|
|
118
|
+
const E = D.events[e];
|
|
119
|
+
tip.replaceChildren(el('div', 'k', k === 'a' ? 'Written by ' + (E.model || E.src) : 'Written by ' + (E.model || E.src) + ', then edited by a human'),
|
|
120
|
+
el('div', 'p', E.p || '(prompt hidden)'), el('div', 'meta', E.src + ' · ' + new Date(E.at).toLocaleString() + (E.session ? ' · session ' + E.session.slice(0, 8) : '')));
|
|
121
|
+
tip.style.display = 'block';
|
|
122
|
+
tip.style.left = Math.min(ev.clientX + 16, innerWidth - 460) + 'px';
|
|
123
|
+
tip.style.top = Math.min(ev.clientY + 16, innerHeight - tip.offsetHeight - 10) + 'px';
|
|
124
|
+
};
|
|
125
|
+
code.onmouseleave = () => { $('tip').style.display = 'none'; };
|
|
126
|
+
v.append(code);
|
|
127
|
+
}
|
|
128
|
+
$('q').oninput = renderList;
|
|
129
|
+
renderList();
|
|
130
|
+
if (D.files[0]) { current = D.files[0]; renderList(); renderFile(D.files[0]); }
|
|
131
|
+
</script>
|
|
132
|
+
</body>
|
|
133
|
+
</html>`;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { writeFileSync } from 'node:fs';
|
|
2
|
+
import { basename } from 'node:path';
|
|
3
|
+
import { attributeFile } from '../attribute.js';
|
|
4
|
+
import { repoStats } from './stats.js';
|
|
5
|
+
import { redact, truncate } from '../redact.js';
|
|
6
|
+
import { shortModel } from '../format.js';
|
|
7
|
+
import { HTML_TEMPLATE } from './map-template.js';
|
|
8
|
+
|
|
9
|
+
const KIND = { agent: 'a', modified: 'm', human: 'h', unknown: 'u', trivial: 't' };
|
|
10
|
+
|
|
11
|
+
export function buildMapData(ctx, { noPrompts, maxFiles = 400 } = {}) {
|
|
12
|
+
const st = repoStats(ctx);
|
|
13
|
+
const evIndex = new Map();
|
|
14
|
+
const events = [];
|
|
15
|
+
const files = [];
|
|
16
|
+
const ranked = st.files.filter((f) => f.attributable > 0 || f.unknown > 0)
|
|
17
|
+
.sort((a, b) => (b.agent + b.modified) - (a.agent + a.modified) || a.file.localeCompare(b.file))
|
|
18
|
+
.slice(0, maxFiles);
|
|
19
|
+
for (const f of ranked) {
|
|
20
|
+
const res = attributeFile(ctx, f.file);
|
|
21
|
+
if (!res) continue;
|
|
22
|
+
files.push({
|
|
23
|
+
f: f.file, s: f.agentShare, n: f.attributable, a: f.agent, m: f.modified, h: f.human, u: f.unknown,
|
|
24
|
+
k: res.map((r) => KIND[r.kind]).join(''),
|
|
25
|
+
e: res.map((r) => {
|
|
26
|
+
if (!r.event) return -1;
|
|
27
|
+
if (!evIndex.has(r.event.idx)) {
|
|
28
|
+
evIndex.set(r.event.idx, events.length);
|
|
29
|
+
events.push({
|
|
30
|
+
src: r.event.source, model: shortModel(r.event.model) || '', at: r.event.ts, session: r.event.sessionId || '',
|
|
31
|
+
p: noPrompts ? '' : truncate(redact(r.event.prompt || ''), 400),
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
return evIndex.get(r.event.idx);
|
|
35
|
+
}),
|
|
36
|
+
t: res.map((r) => r.text),
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
repo: basename(ctx.root), generated: new Date().toISOString(), total: st.total, coverageStart: st.coverageStart,
|
|
41
|
+
prompts: st.prompts.slice(0, 10).map((p) => ({ lines: p.lines, files: p.files.length, model: shortModel(p.model) || p.source, p: noPrompts ? '' : truncate(redact(p.prompt || ''), 200) })),
|
|
42
|
+
models: st.models, events, files,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function cmdMap(ctx, opts) {
|
|
47
|
+
const data = buildMapData(ctx, opts);
|
|
48
|
+
const out = opts.out || 'agentblame.html';
|
|
49
|
+
const json = JSON.stringify(data).replace(/</g, '\\u003c');
|
|
50
|
+
writeFileSync(out, HTML_TEMPLATE.replace('__DATA__', () => json));
|
|
51
|
+
console.log(`Wrote ${out} — ${data.files.length} files, ${(data.total.agentShare * 100).toFixed(1)}% agent-written. Open it in a browser.`);
|
|
52
|
+
if (!opts.noPrompts) console.log('\x1b[2mPrompts are redacted for secrets but included. Use --no-prompts before sharing publicly.\x1b[0m');
|
|
53
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { git } from '../git.js';
|
|
2
|
+
import { hash, isTrivial, normalizeLine } from '../normalize.js';
|
|
3
|
+
import { redact, truncate } from '../redact.js';
|
|
4
|
+
import { dim } from '../format.js';
|
|
5
|
+
|
|
6
|
+
const SLACK_MS = 5 * 60 * 1000;
|
|
7
|
+
|
|
8
|
+
/** Added lines per file for one commit. */
|
|
9
|
+
export function commitAdditions(root, sha) {
|
|
10
|
+
const diff = git(root, ['show', '--format=', '--unified=0', '--no-color', '--no-renames', sha]);
|
|
11
|
+
const files = new Map();
|
|
12
|
+
let cur = null;
|
|
13
|
+
for (const l of diff.split('\n')) {
|
|
14
|
+
if (l.startsWith('+++ ')) { cur = l === '+++ /dev/null' ? null : l.replace(/^\+\+\+ b\//, ''); if (cur && !files.has(cur)) files.set(cur, []); continue; }
|
|
15
|
+
if (l.startsWith('--- ')) continue;
|
|
16
|
+
if (cur && l.startsWith('+')) files.get(cur).push(l.slice(1));
|
|
17
|
+
}
|
|
18
|
+
return files;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Build the note payload for one commit: which agent edits produced which added lines.
|
|
23
|
+
* Prompt text is left out unless `prompts` is true. Notes are pushed with the repo,
|
|
24
|
+
* so prompts are opt-in.
|
|
25
|
+
*/
|
|
26
|
+
export function noteForCommit(ctx, sha, { prompts = false } = {}) {
|
|
27
|
+
const [ct, at] = git(ctx.root, ['show', '-s', '--format=%ct%n%at', sha]).trim().split('\n').map((x) => Number(x) * 1000);
|
|
28
|
+
const commitTime = Math.max(ct, at);
|
|
29
|
+
const groups = new Map();
|
|
30
|
+
for (const [file, lines] of commitAdditions(ctx.root, sha)) {
|
|
31
|
+
for (const line of lines) {
|
|
32
|
+
if (isTrivial(line)) continue;
|
|
33
|
+
const h = hash(normalizeLine(line));
|
|
34
|
+
const cands = (ctx.byHash.get(h) || []).filter((e) => e.ev.rel === file && !e.ev.fromNote && e.ev.ts <= commitTime + SLACK_MS);
|
|
35
|
+
if (!cands.length) continue;
|
|
36
|
+
const pick = cands.reduce((a, b) => (b.ev.ts > a.ev.ts ? b : a));
|
|
37
|
+
const ev = pick.ev;
|
|
38
|
+
const key = `${ev.idx}`;
|
|
39
|
+
if (!groups.has(key)) {
|
|
40
|
+
groups.set(key, {
|
|
41
|
+
source: ev.source, sessionId: ev.sessionId, model: ev.model, ts: ev.ts, file,
|
|
42
|
+
...(prompts ? { prompt: truncate(redact(ev.prompt), 400) } : {}), lines: [],
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
groups.get(key).lines.push(h);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return groups.size ? { v: 1, tool: 'agentblame', entries: [...groups.values()] } : null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function cmdNotes(ctx, range, opts) {
|
|
52
|
+
const args = ['rev-list', range || 'HEAD'];
|
|
53
|
+
if (!range && Number.isFinite(ctx.coverageStart)) args.push(`--since=${Math.floor((ctx.coverageStart - 86400000) / 1000)}`);
|
|
54
|
+
let shas = [];
|
|
55
|
+
try { shas = git(ctx.root, args).split('\n').filter(Boolean); } catch (e) { console.error(`agentblame: bad range ${range}`); process.exit(1); }
|
|
56
|
+
let written = 0, lines = 0;
|
|
57
|
+
for (const sha of shas) {
|
|
58
|
+
const note = noteForCommit(ctx, sha, { prompts: !!opts.prompts });
|
|
59
|
+
if (!note) continue;
|
|
60
|
+
written++;
|
|
61
|
+
lines += note.entries.reduce((n, e) => n + e.lines.length, 0);
|
|
62
|
+
if (opts.dryRun) { console.log(`${sha.slice(0, 10)} ${note.entries.length} agent edit(s), ${note.entries.reduce((n, e) => n + e.lines.length, 0)} lines`); continue; }
|
|
63
|
+
git(ctx.root, ['notes', '--ref=agentblame', 'add', '-f', '-m', JSON.stringify(note), sha]);
|
|
64
|
+
}
|
|
65
|
+
console.log(`${opts.dryRun ? 'Would annotate' : 'Annotated'} ${written} of ${shas.length} commits (${lines} agent-written lines).`);
|
|
66
|
+
if (!opts.dryRun && written) console.log(dim('Share them: git push origin refs/notes/agentblame\nFetch them: git fetch origin refs/notes/agentblame:refs/notes/agentblame'));
|
|
67
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { git } from '../git.js';
|
|
2
|
+
import { hash, isTrivial, normalizeLine } from '../normalize.js';
|
|
3
|
+
import { redact, truncate } from '../redact.js';
|
|
4
|
+
import { bold, dim, magenta, pad, pct, shortModel } from '../format.js';
|
|
5
|
+
|
|
6
|
+
// Same slack as notes.js (noteForCommit) and attribute.js. Duplicated here
|
|
7
|
+
// because neither module exports it and notes behaviour must not change.
|
|
8
|
+
const SLACK_MS = 5 * 60 * 1000;
|
|
9
|
+
const PROMPT_KEEP = 300; // chars kept per prompt in the report (JSON, all views)
|
|
10
|
+
const PROMPT_SHOW = 120; // chars shown per prompt in terminal and markdown
|
|
11
|
+
const TERM_PROMPTS = 5;
|
|
12
|
+
const MD_PROMPTS = 3;
|
|
13
|
+
const MD_ROWS = 50;
|
|
14
|
+
|
|
15
|
+
/** "base", "base..head" or "base...head" -> { base, head }. Head defaults to HEAD. */
|
|
16
|
+
export function parseRange(spec) {
|
|
17
|
+
const s = String(spec ?? '').trim();
|
|
18
|
+
const i = s.indexOf('..');
|
|
19
|
+
if (i < 0) return { base: s, head: 'HEAD' };
|
|
20
|
+
return { base: s.slice(0, i), head: s.slice(i + 2).replace(/^\./, '') || 'HEAD' };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function resolveCommit(root, rev) {
|
|
24
|
+
if (!rev || rev.startsWith('-')) throw new Error(`bad revision: ${rev || '(empty)'}`);
|
|
25
|
+
try { return git(root, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`]).trim(); }
|
|
26
|
+
catch { throw new Error(`unknown revision: ${rev}`); }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function commitTimeMs(root, sha) {
|
|
30
|
+
const [ct, at] = git(root, ['show', '-s', '--format=%ct%n%at', sha]).trim().split('\n').map((x) => Number(x) * 1000);
|
|
31
|
+
return Math.max(ct, at);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function unquote(p) {
|
|
35
|
+
if (!p.startsWith('"')) return p;
|
|
36
|
+
return p.slice(1, -1).replace(/\\(.)/g, (_, c) => (c === 't' ? '\t' : c === 'n' ? '\n' : c));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Lines the range adds, per repo-relative file. `line` is the line number in
|
|
41
|
+
* head, taken from the hunk headers (--unified=0 keeps them exact).
|
|
42
|
+
*/
|
|
43
|
+
export function addedLines(root, baseSha, headSha) {
|
|
44
|
+
const diff = git(root, ['-c', 'core.quotepath=off', 'diff', '--unified=0', '--no-color', '--no-renames', '--no-ext-diff', `${baseSha}...${headSha}`, '--']);
|
|
45
|
+
const files = new Map();
|
|
46
|
+
let file = null, inHunk = false, lineNo = 0;
|
|
47
|
+
for (const l of diff.split('\n')) {
|
|
48
|
+
if (l.startsWith('diff --git ')) { file = null; inHunk = false; continue; }
|
|
49
|
+
const hunk = l.match(/^@@ -\S+ \+(\d+)(?:,\d+)? @@/);
|
|
50
|
+
if (hunk) { inHunk = true; lineNo = Number(hunk[1]); continue; }
|
|
51
|
+
if (!inHunk) {
|
|
52
|
+
if (l.startsWith('+++ ')) {
|
|
53
|
+
const p = l.slice(4).replace(/\t$/, '');
|
|
54
|
+
file = p === '/dev/null' ? null : unquote(p).replace(/^b\//, '');
|
|
55
|
+
if (file && !files.has(file)) files.set(file, []);
|
|
56
|
+
}
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (l.startsWith('+') && file) { files.get(file).push({ line: lineNo, text: l.slice(1) }); lineNo++; }
|
|
60
|
+
}
|
|
61
|
+
return files;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Commit time of every line of `file` at `rev`, indexed by line - 1. Same
|
|
66
|
+
* flags as git.js blame (-w -M -C), but against a revision, not the worktree.
|
|
67
|
+
*/
|
|
68
|
+
function blameTimes(root, rev, file) {
|
|
69
|
+
let out;
|
|
70
|
+
try { out = git(root, ['blame', '--line-porcelain', '-w', '-M', '-C', rev, '--', file]); }
|
|
71
|
+
catch { return null; }
|
|
72
|
+
const times = [];
|
|
73
|
+
let cur = null;
|
|
74
|
+
for (const l of out.split('\n')) {
|
|
75
|
+
if (l.startsWith('\t')) { times.push(cur ? Math.max(cur.a, cur.c) : null); cur = null; continue; }
|
|
76
|
+
if (/^[0-9a-f]{40} \d+ \d+/.test(l)) { cur = { a: 0, c: 0 }; continue; }
|
|
77
|
+
if (!cur) continue;
|
|
78
|
+
if (l.startsWith('author-time ')) cur.a = Number(l.slice(12)) * 1000;
|
|
79
|
+
else if (l.startsWith('committer-time ')) cur.c = Number(l.slice(15)) * 1000;
|
|
80
|
+
}
|
|
81
|
+
return times;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Attribute every non-trivial line the range adds.
|
|
86
|
+
* agent – an event (transcript or git note) with the same normalized
|
|
87
|
+
* hash, the same file, and ts <= commit time + slack. Same rule
|
|
88
|
+
* as noteForCommit, except notes-derived events are allowed.
|
|
89
|
+
* human – no match, and the commit is not older than the earliest
|
|
90
|
+
* transcript or note (the rule `agentblame <file>` uses).
|
|
91
|
+
* unknown – no match, and the commit predates our coverage.
|
|
92
|
+
*/
|
|
93
|
+
export function prReport(ctx, spec, { noPrompts = false } = {}) {
|
|
94
|
+
const { base, head } = parseRange(spec);
|
|
95
|
+
const baseSha = resolveCommit(ctx.root, base);
|
|
96
|
+
const headSha = resolveCommit(ctx.root, head);
|
|
97
|
+
const headTime = commitTimeMs(ctx.root, headSha);
|
|
98
|
+
const added = addedLines(ctx.root, baseSha, headSha);
|
|
99
|
+
|
|
100
|
+
const totals = { agent: 0, human: 0, unknown: 0, trivial: 0 };
|
|
101
|
+
const files = [];
|
|
102
|
+
const prompts = new Map();
|
|
103
|
+
|
|
104
|
+
for (const [file, entries] of added) {
|
|
105
|
+
const times = blameTimes(ctx.root, headSha, file);
|
|
106
|
+
const row = { file, added: 0, agent: 0, human: 0, unknown: 0, trivial: 0 };
|
|
107
|
+
for (const { line, text } of entries) {
|
|
108
|
+
if (isTrivial(text)) { row.trivial++; continue; }
|
|
109
|
+
const t = times?.[line - 1] || headTime;
|
|
110
|
+
const cands = (ctx.byHash.get(hash(normalizeLine(text))) || [])
|
|
111
|
+
.filter((e) => e.ev.rel === file && e.ev.ts <= t + SLACK_MS);
|
|
112
|
+
if (cands.length) {
|
|
113
|
+
const ev = cands.reduce((a, b) => (b.ev.ts > a.ev.ts ? b : a)).ev;
|
|
114
|
+
row.agent++;
|
|
115
|
+
const key = `${ev.sessionId}\u0000${ev.prompt}`;
|
|
116
|
+
const p = prompts.get(key) || {
|
|
117
|
+
sessionId: ev.sessionId, source: ev.source, model: ev.model,
|
|
118
|
+
...(noPrompts ? {} : { prompt: truncate(redact(ev.prompt), PROMPT_KEEP) }),
|
|
119
|
+
lines: 0, files: new Set(),
|
|
120
|
+
};
|
|
121
|
+
p.lines++; p.files.add(file);
|
|
122
|
+
prompts.set(key, p);
|
|
123
|
+
} else if (t >= ctx.coverageStart - SLACK_MS) {
|
|
124
|
+
row.human++;
|
|
125
|
+
} else {
|
|
126
|
+
row.unknown++;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
row.added = row.agent + row.human + row.unknown;
|
|
130
|
+
for (const k of Object.keys(totals)) totals[k] += row[k];
|
|
131
|
+
files.push(row);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
files.sort((a, b) => b.added - a.added || a.file.localeCompare(b.file));
|
|
135
|
+
const counted = totals.agent + totals.human + totals.unknown;
|
|
136
|
+
return {
|
|
137
|
+
range: { spec, base, head, baseSha, headSha },
|
|
138
|
+
lines: { added: counted, agent: totals.agent, human: totals.human, unknown: totals.unknown, trivial: totals.trivial },
|
|
139
|
+
agentShare: counted ? totals.agent / counted : 0,
|
|
140
|
+
knownShare: counted ? (totals.agent + totals.human) / counted : null,
|
|
141
|
+
coverageStart: Number.isFinite(ctx.coverageStart) ? ctx.coverageStart : null,
|
|
142
|
+
files: files.map((f) => ({ ...f, agentShare: f.added ? f.agent / f.added : 0 })),
|
|
143
|
+
...(noPrompts ? {} : {
|
|
144
|
+
prompts: [...prompts.values()]
|
|
145
|
+
.sort((a, b) => b.lines - a.lines)
|
|
146
|
+
.slice(0, 20)
|
|
147
|
+
.map((p) => ({ ...p, files: [...p.files] })),
|
|
148
|
+
}),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Check for --fail-under-attributed: known provenance (agent or human) must reach `threshold` percent. */
|
|
153
|
+
export function failUnderCheck(report, threshold) {
|
|
154
|
+
const { added, agent, human } = report.lines;
|
|
155
|
+
if (!added) return { ok: true, share: null, threshold };
|
|
156
|
+
const share = ((agent + human) * 100) / added;
|
|
157
|
+
return { ok: share >= threshold, share, threshold };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const bar = (share) => {
|
|
161
|
+
const n = Math.round(share * 30);
|
|
162
|
+
return magenta('█'.repeat(n)) + dim('░'.repeat(30 - n));
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
export function renderTerminal(r, { noPrompts } = {}) {
|
|
166
|
+
const { lines } = r;
|
|
167
|
+
const out = [`\n${bold(`agentblame pr ${r.range.base}..${r.range.head}`)} ${dim(`${r.range.baseSha.slice(0, 8)}..${r.range.headSha.slice(0, 8)}`)}`];
|
|
168
|
+
if (!lines.added) {
|
|
169
|
+
out.push(dim(' no attributable lines were added in this range'), '');
|
|
170
|
+
return out.join('\n');
|
|
171
|
+
}
|
|
172
|
+
out.push(`\n${bold(`${pct(r.agentShare)} of ${lines.added} added lines were written by agents`)} ${bar(r.agentShare)}`);
|
|
173
|
+
out.push(dim(` ${lines.agent} agent · ${lines.human} human · ${lines.unknown} unknown · ${lines.trivial} trivial (excluded)`));
|
|
174
|
+
out.push(dim(` known provenance (agent or human): ${pct(r.knownShare)}`));
|
|
175
|
+
if (r.coverageStart) out.push(dim(` coverage starts ${new Date(r.coverageStart).toISOString().slice(0, 10)}; older lines are unknown, not human`));
|
|
176
|
+
|
|
177
|
+
const rows = r.files.filter((f) => f.added > 0);
|
|
178
|
+
if (rows.length) {
|
|
179
|
+
const w = Math.min(50, Math.max(...rows.map((f) => f.file.length)));
|
|
180
|
+
out.push(`\n${bold('Per file')}`);
|
|
181
|
+
out.push(dim(` ${pad('file', w)} ${'added'.padStart(6)} ${'agent'.padStart(6)} ${'human/unknown'.padStart(14)} ${'% agent'.padStart(8)}`));
|
|
182
|
+
for (const f of rows.slice(0, MD_ROWS)) {
|
|
183
|
+
out.push(` ${pad(f.file.slice(-w), w)} ${String(f.added).padStart(6)} ${String(f.agent).padStart(6)} ${String(f.human + f.unknown).padStart(14)} ${pct(f.agentShare).padStart(8)}`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (!noPrompts && r.prompts?.length) {
|
|
187
|
+
out.push(`\n${bold('Top prompts')}`);
|
|
188
|
+
for (const p of r.prompts.slice(0, TERM_PROMPTS)) {
|
|
189
|
+
const text = truncate(p.prompt || '(no prompt captured)', PROMPT_SHOW);
|
|
190
|
+
out.push(` ${magenta(String(p.lines).padStart(6))} lines ${text} ${dim(shortModel(p.model) || p.source)}`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
out.push('');
|
|
194
|
+
return out.join('\n');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Escape text for a GitHub-flavoured markdown table cell or list item. */
|
|
198
|
+
const mdEsc = (s) => String(s ?? '').replace(/[\\`*_[\]<>|#~&]/g, '\\$&');
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Prompt text is user-written, so an @mention in it must not notify anyone
|
|
202
|
+
* when the markdown is posted. A zero-width space after the @ stops GitHub
|
|
203
|
+
* from linking it. Applied to prompt text only.
|
|
204
|
+
*/
|
|
205
|
+
export const neutralizeMentions = (s) => String(s ?? '').replace(/@(?=\w)/g, '@');
|
|
206
|
+
|
|
207
|
+
export function renderMarkdown(r, { noPrompts } = {}) {
|
|
208
|
+
const { lines } = r;
|
|
209
|
+
const out = ['## agentblame report', ''];
|
|
210
|
+
if (!lines.added) {
|
|
211
|
+
out.push(`No attributable lines were added in ${mdEsc(r.range.base)}..${mdEsc(r.range.head)}.`, '');
|
|
212
|
+
} else {
|
|
213
|
+
const trivialNote = lines.trivial === 1 ? '1 trivial line is' : `${lines.trivial} trivial lines are`;
|
|
214
|
+
out.push(`**${pct(r.agentShare)} of ${lines.added} added lines were written by agents.** ${lines.agent} agent, ${lines.human + lines.unknown} human or unknown. ${trivialNote} not counted.`, '');
|
|
215
|
+
const rows = r.files.filter((f) => f.added > 0);
|
|
216
|
+
out.push('| file | added | agent | human-or-unknown | % agent |', '|---|---:|---:|---:|---:|');
|
|
217
|
+
for (const f of rows.slice(0, MD_ROWS)) {
|
|
218
|
+
out.push(`| ${mdEsc(f.file)} | ${f.added} | ${f.agent} | ${f.human + f.unknown} | ${pct(f.agentShare)} |`);
|
|
219
|
+
}
|
|
220
|
+
out.push(`| **Total** | ${lines.added} | ${lines.agent} | ${lines.human + lines.unknown} | ${pct(r.agentShare)} |`);
|
|
221
|
+
if (rows.length > MD_ROWS) out.push('', `_${rows.length - MD_ROWS} more files not shown._`);
|
|
222
|
+
out.push('');
|
|
223
|
+
|
|
224
|
+
if (!noPrompts && r.prompts?.length) {
|
|
225
|
+
out.push('### Top prompts', '');
|
|
226
|
+
for (const p of r.prompts.slice(0, MD_PROMPTS)) {
|
|
227
|
+
const text = mdEsc(neutralizeMentions(truncate(p.prompt || '(no prompt captured)', PROMPT_SHOW)));
|
|
228
|
+
out.push(`- **${p.lines} ${p.lines === 1 ? 'line' : 'lines'}** · ${mdEsc(shortModel(p.model) || p.source)} · ${text}`);
|
|
229
|
+
}
|
|
230
|
+
out.push('');
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
out.push('---', '');
|
|
234
|
+
out.push('_agentblame counts the non-trivial lines this pull request adds. A line is **agent** when an agentblame git note or a local transcript matches its text and the edit came no later than the commit that added it. A line is **human** when nothing matches it and its commit is newer than the earliest note or transcript. Lines without a note or transcript show as **unknown**: agentblame has no record either way, so unknown is not the same as human. This measures how much provenance is recorded. It does not judge code quality._');
|
|
235
|
+
return out.join('\n');
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function cmdPr(ctx, spec, opts = {}) {
|
|
239
|
+
let report;
|
|
240
|
+
try { report = prReport(ctx, spec, { noPrompts: !!opts.noPrompts }); }
|
|
241
|
+
catch (e) { console.error(`agentblame: ${e.message}`); process.exitCode = 1; return; }
|
|
242
|
+
|
|
243
|
+
if (opts.json) console.log(JSON.stringify(report, null, 2));
|
|
244
|
+
else if (opts.markdown) console.log(renderMarkdown(report, opts));
|
|
245
|
+
else console.log(renderTerminal(report, opts));
|
|
246
|
+
|
|
247
|
+
if (opts.failUnder != null) {
|
|
248
|
+
const g = failUnderCheck(report, opts.failUnder);
|
|
249
|
+
if (!g.ok) {
|
|
250
|
+
console.error(`agentblame: ${g.share.toFixed(1)}% of ${report.lines.added} added lines have known provenance, below the required ${opts.failUnder}%. This checks provenance coverage, not code quality.`);
|
|
251
|
+
process.exitCode = 1;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { attributeFile, summarize } from '../attribute.js';
|
|
2
|
+
import { trackedFiles } from '../git.js';
|
|
3
|
+
import { redact, truncate } from '../redact.js';
|
|
4
|
+
import { bold, dim, magenta, pad, pct, shortModel, yellow } from '../format.js';
|
|
5
|
+
|
|
6
|
+
const SKIP = /(^|\/)(node_modules|vendor|dist|build|\.next|coverage)\/|(\.lock|-lock\.json|\.min\.js|\.map|\.svg|\.png|\.jpg|\.jpeg|\.gif|\.ico|\.pdf|\.woff2?)$/i;
|
|
7
|
+
|
|
8
|
+
export function repoStats(ctx, paths = []) {
|
|
9
|
+
let files = trackedFiles(ctx.root).filter((f) => !SKIP.test(f));
|
|
10
|
+
if (paths.length) files = files.filter((f) => paths.some((p) => p === '' || p === '.' || f === p || f.startsWith(p.replace(/\/$/, '') + '/')));
|
|
11
|
+
// Include untracked files agents created but nobody committed yet.
|
|
12
|
+
const seen = new Set(files);
|
|
13
|
+
for (const rel of ctx.byPath.keys()) if (!seen.has(rel) && !SKIP.test(rel) && (!paths.length || paths.some((p) => rel.startsWith(p)))) files.push(rel);
|
|
14
|
+
|
|
15
|
+
const total = { agent: 0, modified: 0, human: 0, unknown: 0, trivial: 0 };
|
|
16
|
+
const perFile = [];
|
|
17
|
+
const perPrompt = new Map();
|
|
18
|
+
const perModel = new Map();
|
|
19
|
+
for (const rel of files) {
|
|
20
|
+
const res = attributeFile(ctx, rel);
|
|
21
|
+
if (!res) continue;
|
|
22
|
+
const s = summarize(res);
|
|
23
|
+
for (const k of Object.keys(total)) total[k] += s[k];
|
|
24
|
+
perFile.push({ file: rel, ...s });
|
|
25
|
+
for (const r of res) {
|
|
26
|
+
if (!r.event) continue;
|
|
27
|
+
const key = `${r.event.sessionId}\u0000${r.event.prompt}`;
|
|
28
|
+
const p = perPrompt.get(key) || { sessionId: r.event.sessionId, prompt: r.event.prompt, model: r.event.model, source: r.event.source, at: r.event.promptTs || r.event.ts, lines: 0, files: new Set() };
|
|
29
|
+
p.lines++; p.files.add(rel); perPrompt.set(key, p);
|
|
30
|
+
const m = shortModel(r.event.model) || r.event.source;
|
|
31
|
+
perModel.set(m, (perModel.get(m) || 0) + 1);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const attributable = total.agent + total.modified + total.human;
|
|
35
|
+
return {
|
|
36
|
+
total: { ...total, attributable, agentShare: attributable ? (total.agent + total.modified) / attributable : 0 },
|
|
37
|
+
coverageStart: Number.isFinite(ctx.coverageStart) ? ctx.coverageStart : null,
|
|
38
|
+
files: perFile,
|
|
39
|
+
prompts: [...perPrompt.values()].sort((a, b) => b.lines - a.lines).map((p) => ({ ...p, files: [...p.files] })),
|
|
40
|
+
models: [...perModel.entries()].sort((a, b) => b[1] - a[1]).map(([model, lines]) => ({ model, lines })),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function cmdStats(ctx, paths, opts) {
|
|
45
|
+
const st = repoStats(ctx, paths);
|
|
46
|
+
const top = opts.top || 5;
|
|
47
|
+
if (opts.json) {
|
|
48
|
+
const prompts = st.prompts.slice(0, opts.top || 20).map((p) => ({ ...p, prompt: opts.noPrompts ? undefined : truncate(redact(p.prompt), 300) }));
|
|
49
|
+
console.log(JSON.stringify({ ...st, prompts }, null, 2));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const t = st.total;
|
|
53
|
+
const bar = (share) => { const n = Math.round(share * 30); return magenta('█'.repeat(n)) + dim('░'.repeat(30 - n)); };
|
|
54
|
+
console.log(`\n${bold(`${pct(t.agentShare)} of attributable lines were written by agents`)} ${bar(t.agentShare)}`);
|
|
55
|
+
console.log(dim(` ${t.agent} agent · ${t.modified} agent-then-human-edited · ${t.human} human · ${t.unknown} before transcripts began · ${t.trivial} trivial (excluded)`));
|
|
56
|
+
if (st.coverageStart) console.log(dim(` transcript coverage starts ${new Date(st.coverageStart).toISOString().slice(0, 10)}; older lines count as unknown, not human`));
|
|
57
|
+
|
|
58
|
+
if (st.prompts.length) {
|
|
59
|
+
console.log(`\n${bold('Prompts that produced the most surviving code')}`);
|
|
60
|
+
for (const p of st.prompts.slice(0, top)) {
|
|
61
|
+
console.log(` ${magenta(String(p.lines).padStart(6))} lines ${pad(truncate(redact(p.prompt || '(no prompt)'), 70), 70)} ${dim(shortModel(p.model) || p.source)}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const files = st.files.filter((f) => f.attributable > 0).sort((a, b) => (b.agent + b.modified) - (a.agent + a.modified));
|
|
65
|
+
if (files.length) {
|
|
66
|
+
console.log(`\n${bold('Most agent-written files')}`);
|
|
67
|
+
for (const f of files.slice(0, top)) console.log(` ${pad(f.file, 50)} ${bar(f.agentShare)} ${pct(f.agentShare).padStart(6)} ${dim(`of ${f.attributable}`)}`);
|
|
68
|
+
}
|
|
69
|
+
if (st.models.length) console.log(`\n${bold('By model')} ${st.models.map((m) => `${m.model} ${yellow(m.lines)}`).join(dim(' · '))}`);
|
|
70
|
+
console.log('');
|
|
71
|
+
}
|