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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 agentblame contributors
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,198 @@
|
|
|
1
|
-
#
|
|
1
|
+
# agentblame
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/agentblame)
|
|
4
|
+
[](https://github.com/Yatishgrandhe/agentblame/actions/workflows/ci.yml)
|
|
5
|
+
|
|
6
|
+
agentblame: git blame for AI-written code.
|
|
7
|
+
|
|
8
|
+
Find the prompt behind any line of code.
|
|
9
|
+
|
|
10
|
+
agentblame reads the session logs Claude Code and Codex already keep on your machine, lines them up with git history, and shows which lines an agent wrote, which ones you rewrote, and the exact prompt behind each.
|
|
11
|
+
|
|
12
|
+
Runs locally. No account, no upload, no telemetry.
|
|
13
|
+
|
|
14
|
+
## Quick start
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npx agentblame src/app.ts
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Blame a line range from this repository:
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
$ NO_COLOR=1 node bin/agentblame.js src/normalize.js:1-12
|
|
24
|
+
1 AI opus-5-5 (prompt) │ import { createHash } from 'node:crypto';
|
|
25
|
+
2 │
|
|
26
|
+
3 │ /**
|
|
27
|
+
4 AI opus-5-5 (prompt) │ * Normalization is what lets attribution survive formatters (prettier, black,
|
|
28
|
+
5 AI opus-5-5 〃 │ * gofmt): indentation, whitespace runs, quote style, trailing commas and
|
|
29
|
+
6 AI opus-5-5 〃 │ * semicolons are ignored. Two lines that differ only in those ways are the
|
|
30
|
+
7 AI opus-5-5 〃 │ * "same" line for attribution purposes.
|
|
31
|
+
8 │ */
|
|
32
|
+
9 AI opus-5-5 (prompt) │ export function normalizeLine(line) {
|
|
33
|
+
10 AI opus-5-5 〃 │ return line
|
|
34
|
+
11 AI opus-5-5 〃 │ .replace(/\r$/, '')
|
|
35
|
+
12 AI opus-5-5 〃 │ .trim()
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Each row gives the line's origin: `AI` for agent-written, `AI~` for agent-written and then edited by a person, `human`, or `?` for lines older than your transcripts. The note column shows the prompt that produced the line; it is replaced with `(prompt)` here. Run `agentblame why <file>:<line>` for the full prompt, model and session, and a resume command for Claude Code sessions.
|
|
39
|
+
|
|
40
|
+
## Commands
|
|
41
|
+
|
|
42
|
+
| Command | What it does |
|
|
43
|
+
|---|---|
|
|
44
|
+
| `agentblame <file>[:<line>[-<end>]]` | Blame a file: the origin of each line, per line. |
|
|
45
|
+
| `agentblame why <file>:<line>` | The prompt, model, session and transcript behind one line. |
|
|
46
|
+
| `agentblame stats [paths…]` | Share of attributable lines written by agents, the prompts that produced the most surviving code, and the most agent-written files. |
|
|
47
|
+
| `agentblame map [-o file.html]` | Writes a self-contained HTML provenance map, with redacted prompts unless `--no-prompts` is given. |
|
|
48
|
+
| `agentblame notes [<rev-range>]` | Stores attribution in git notes under `refs/notes/agentblame`. |
|
|
49
|
+
|
|
50
|
+
## Options
|
|
51
|
+
|
|
52
|
+
| Flag | Meaning |
|
|
53
|
+
|---|---|
|
|
54
|
+
| `--json` | Machine-readable output. |
|
|
55
|
+
| `--prompts` | `notes` only: store redacted prompt text. Off by default. |
|
|
56
|
+
| `--no-prompts` | Omit prompt text from `map`, `pr` and JSON output. |
|
|
57
|
+
| `--no-claude` | Ignore Claude Code transcripts (`~/.claude/projects`). |
|
|
58
|
+
| `--no-codex` | Ignore Codex transcripts (`~/.codex/sessions`). |
|
|
59
|
+
| `--no-notes` | Ignore `refs/notes/agentblame`. |
|
|
60
|
+
| `--claude-dir DIR` | Claude Code transcripts location (default `~/.claude/projects`). |
|
|
61
|
+
| `--deep` | Scan every Claude project directory, not only those that can touch this repository (slow). |
|
|
62
|
+
| `--no-cache` | Do not read or write the parsed-transcript cache (`~/.cache/agentblame`). |
|
|
63
|
+
| `--codex-dir DIR` | Codex sessions location (default `~/.codex/sessions`). |
|
|
64
|
+
| `--top N` | Rows in `stats` tables (default 5). |
|
|
65
|
+
| `-o, --out FILE` | Output path for `map`. |
|
|
66
|
+
| `-h, --help` | Show help. |
|
|
67
|
+
|
|
68
|
+
Environment variables `AGENTBLAME_CLAUDE_DIR` and `AGENTBLAME_CODEX_DIR` set the transcript locations when the flags are not given. `NO_COLOR` disables colored output.
|
|
69
|
+
|
|
70
|
+
## How it works
|
|
71
|
+
|
|
72
|
+
agentblame works in four steps. The details and constants are in [docs/DESIGN.md](docs/DESIGN.md).
|
|
73
|
+
|
|
74
|
+
1. **Read what the agent wrote.** Claude Code records the result of each edit. agentblame uses the lines that landed on disk (`structuredPatch`, or the diff for a Bash edit) and drops edits that failed or were rejected. Files created with a shell heredoc are found from the command text and marked unverified. Codex `apply_patch` edits are supported experimentally.
|
|
75
|
+
2. **Match lines, ignoring formatting.** Indentation, whitespace runs, quote style, trailing commas and semicolons are normalized before lines are compared, so running a formatter afterwards does not change who wrote a line. Trivial lines (braces, blank lines, `return;`) are never attributed.
|
|
76
|
+
3. **Check the order of events with git.** An agent edit can only explain a line if it happened no later than the commit that introduced the line, allowing five minutes of clock skew. Blame runs with `-w -M -C`, so reformatted and moved code keeps its origin. A block of at least three consecutive lines from one agent edit is credited when it moved to another file.
|
|
77
|
+
4. **Say how sure it is.** Each line gets a kind and a confidence. `agent` and `modified` come with `exact` or `normalized` matches (high confidence), or `moved` matches (medium). `modified` lines that differ from the agent's version by fuzzy similarity are reported with a similarity score. Lines older than the earliest transcript are `unknown`, never `human`.
|
|
78
|
+
|
|
79
|
+
## Accuracy
|
|
80
|
+
|
|
81
|
+
### Real Claude Code sessions
|
|
82
|
+
|
|
83
|
+
The main result comes from ten tasks run through the real Claude Code CLI (`claude -p --model haiku`). Ground truth comes from the files on disk, and the run scores 1,526 lines. The method, per-task results and caveats are in [docs/REAL-SESSIONS.md](docs/REAL-SESSIONS.md).
|
|
84
|
+
|
|
85
|
+
| Metric | Value (95% CI over tasks) |
|
|
86
|
+
|---|---|
|
|
87
|
+
| Precision | 100.0% (100.0%–100.0%) |
|
|
88
|
+
| Recall | 98.6% (95.2%–100.0%) |
|
|
89
|
+
| Kind accuracy | 48.2% (32.7%–60.0%) |
|
|
90
|
+
| Human as AI | 0.0% (0.0%–0.0%) |
|
|
91
|
+
|
|
92
|
+
51.8% of the scored lines were `unknown`, because the seed code predates the transcripts. agentblame labels those lines `unknown` rather than guessing, and the ground truth calls them `human`. That puts kind accuracy at 48.2%. Over the lines agentblame did attribute, kind accuracy is 100%. Precision and recall are not affected, because `unknown` is never counted as AI.
|
|
93
|
+
|
|
94
|
+
The human-as-AI result is lightly tested. Only 84 lines were scripted human edits after the agent (34 fully rewritten, 50 inserted). A further 134 lines were lightly edited, and those still count as agent-written.
|
|
95
|
+
|
|
96
|
+
### Synthetic benchmark
|
|
97
|
+
|
|
98
|
+
The synthetic benchmark uses generated repositories with known authorship, and its transcripts are written by the harness. It tests the matching rules under controlled conditions. It does not measure real sessions. The table is the held-out split (seeds not used for tuning) from `bench/results.heldout.json`, overall, with 95% bootstrap confidence intervals over 20 seeds per scenario. The development split is shown for comparison.
|
|
99
|
+
|
|
100
|
+
| Split | Lines | Precision | Recall | Kind accuracy | Human as AI |
|
|
101
|
+
|---|---:|---:|---:|---:|---:|
|
|
102
|
+
| **Held-out, overall** | 17854 | 100.0% (100.0%–100.0%) | 99.0% (98.9%–99.2%) | 99.3% (99.2%–99.5%) | 0.02% (0.0%–0.05%) |
|
|
103
|
+
| Development, overall | 17701 | 100.0% (99.9%–100.0%) | 99.0% (98.8%–99.2%) | 99.3% (99.2%–99.5%) | 0.05% (0.0%–0.14%) |
|
|
104
|
+
|
|
105
|
+
Precision is the share of lines predicted as agent-written that really were. Recall is the share of agent-written lines that were predicted as agent-written. Kind accuracy counts a prediction of `unknown` or `trivial` as wrong. Human as AI is the share of person-written lines predicted as agent-written.
|
|
106
|
+
|
|
107
|
+
The synthetic 99.3% kind accuracy uses a coverage anchor that real repositories lack. Each benchmark repository gets an unrelated agent session five days earlier, so transcript coverage starts before the human-written files. Without that anchor, synthetic kind accuracy is 68.0%. `node bench/run.js --sensitivity` shows those results.
|
|
108
|
+
|
|
109
|
+
Caveats for the synthetic results:
|
|
110
|
+
|
|
111
|
+
- **Synthetic code.** Code lines come from templates and word lists. Real code repeats idioms more often, so false and missed matches may differ.
|
|
112
|
+
- **Simulated human edits.** Light edits change one token. Full rewrites replace lines with random ones. Real edits are usually larger and more mixed. S5 is the only scenario below 100%.
|
|
113
|
+
- **One model name and one edit style.** Every simulated edit uses the same model name and a single tool call per change. No subagents, no MultiEdit.
|
|
114
|
+
- **Small samples.** Each scenario has 20 seeds and 40 to 120 line files, so per-scenario intervals are wide.
|
|
115
|
+
|
|
116
|
+
Full method and scenario descriptions: [docs/BENCHMARK.md](docs/BENCHMARK.md). Real-session method and caveats: [docs/REAL-SESSIONS.md](docs/REAL-SESSIONS.md).
|
|
117
|
+
|
|
118
|
+
## Limits
|
|
119
|
+
|
|
120
|
+
- Code pasted from a chat window is not tracked. There is no agent session on disk behind it.
|
|
121
|
+
- Transcripts must be on this machine. Sessions from other machines are visible only if a teammate shared them through git notes.
|
|
122
|
+
- A line that a person retypes exactly as the agent wrote it still counts as the agent's.
|
|
123
|
+
- Files written by programs an agent ran (a build step, a code generator, a migration tool) count as human, because no agent edit put those lines on disk.
|
|
124
|
+
- Codex support is experimental. It is validated against fixtures built from the openai/codex rollout schema at commit `d0b140efb5d326ae481d77aaf40b925226a74cae`; not yet tested on real user sessions. Codex patch edits are not verified against disk, and `*** Move to` renames are followed to the new path.
|
|
125
|
+
- Attribution depends on the transcript format. A Claude Code change in the format of its logs can reduce coverage until agentblame is updated.
|
|
126
|
+
|
|
127
|
+
## Privacy
|
|
128
|
+
|
|
129
|
+
- Everything runs locally. agentblame makes no network calls and has no telemetry.
|
|
130
|
+
- It reads `~/.claude/projects` and `~/.codex/sessions`, and writes a parse cache under `~/.cache/agentblame`.
|
|
131
|
+
- Prompts are redacted before they appear in a map, a PR report, a git note or JSON output. Redaction covers:
|
|
132
|
+
- user names in home directory paths (`/Users/<name>`, `/home/<name>`, `C:\Users\<name>`);
|
|
133
|
+
- private key blocks;
|
|
134
|
+
- API keys: `sk-`, `sk-ant-`, and Stripe-style `sk_live_`, `pk_test_` and similar keys;
|
|
135
|
+
- npm, GitHub, GitLab and Slack tokens, AWS access key IDs and Google API keys;
|
|
136
|
+
- JWTs and `Bearer` or `Basic` authorization values;
|
|
137
|
+
- quoted and unquoted values of `password`, `secret`, `token`, `api_key`, `access_key` and `client_secret`;
|
|
138
|
+
- email addresses;
|
|
139
|
+
- long hex strings and long base64-looking blobs.
|
|
140
|
+
- Redaction is pattern-based and can miss secrets; use `--no-prompts` when in doubt.
|
|
141
|
+
- `--no-prompts` removes prompt text from `map`, `pr` and `--json` output entirely. `notes` stores no prompt text unless you pass `--prompts`.
|
|
142
|
+
- `blame` and `why` print prompt text to your terminal. Scrubbing is best effort, so review a map or note before you share it.
|
|
143
|
+
|
|
144
|
+
## Sharing provenance with your team (git notes)
|
|
145
|
+
|
|
146
|
+
`agentblame notes` writes a note for each commit that contains agent-written lines. The note records the source, session, model, time, file, and a hash of each line. It is stored under `refs/notes/agentblame`, not in your branches.
|
|
147
|
+
|
|
148
|
+
Prompts are not stored in notes unless you pass `--prompts`, because notes are pushed with the repo. With `--prompts`, the note also includes a redacted, truncated prompt.
|
|
149
|
+
|
|
150
|
+
```sh
|
|
151
|
+
agentblame notes # annotate commits since transcript coverage began
|
|
152
|
+
git push origin refs/notes/agentblame # share them
|
|
153
|
+
git fetch origin refs/notes/agentblame:refs/notes/agentblame # teammates fetch them
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Teammates then see the same answers from `blame`, `why`, `stats` and `map` without your transcripts. Notes are not signed. Treat them as a record of what the author claimed. Pushing them shares session IDs, models, times and line hashes with everyone who can read the remote, and it shares prompts too if you used `--prompts`.
|
|
157
|
+
|
|
158
|
+
## Pull requests and CI
|
|
159
|
+
|
|
160
|
+
`agentblame pr <base>[..<head>]` attributes the lines a pull request adds. The head defaults to `HEAD`.
|
|
161
|
+
|
|
162
|
+
```sh
|
|
163
|
+
agentblame pr origin/main # terminal summary: % agent, lines by kind, per file, top prompts
|
|
164
|
+
agentblame pr origin/main --json # machine-readable
|
|
165
|
+
agentblame pr origin/main --markdown # a GitHub PR comment body
|
|
166
|
+
agentblame pr origin/main --markdown --no-prompts
|
|
167
|
+
agentblame pr origin/main --fail-under-attributed 60 # exit 1 if under 60% of added lines have known provenance
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
In CI there are usually no transcripts, so the report relies on git notes. Teammates push them with `git push origin refs/notes/agentblame`, and the CI job fetches them. Lines that no note or transcript covers show as `unknown`, not `human`.
|
|
171
|
+
|
|
172
|
+
`--fail-under-attributed` checks provenance coverage, not quality. A team can use it to require that agent-heavy PRs carry notes. It cannot tell whether the code is good.
|
|
173
|
+
|
|
174
|
+
The composite action in [`action/`](action/README.md) runs the report on pull requests, writes it to the job summary, and posts or updates one PR comment. It needs `fetch-depth: 0`. Prompts stay out of the comment unless you set `prompts: true`.
|
|
175
|
+
|
|
176
|
+
## Development
|
|
177
|
+
|
|
178
|
+
Requirements: Node 20 or later and git. The CLI has no npm dependencies.
|
|
179
|
+
|
|
180
|
+
```sh
|
|
181
|
+
npm test # unit tests (node --test)
|
|
182
|
+
npm run bench # accuracy benchmark, about 67 seconds; rewrites bench/results.json and docs/BENCHMARK.md
|
|
183
|
+
cd crates/codecity && cargo test --release
|
|
184
|
+
crates/codecity/build.sh # build the WebAssembly used by the site (needs the wasm32-unknown-unknown target and wasm-bindgen-cli 0.2.130)
|
|
185
|
+
cd site && npm ci && npm run dev
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
The site lives in `site/`. The generated WebAssembly files `site/src/wasm` and `site/public/wasm` are committed, so the site builds without a Rust toolchain.
|
|
189
|
+
|
|
190
|
+
Contributing guidelines are in [CONTRIBUTING.md](CONTRIBUTING.md). Design notes are in [docs/DESIGN.md](docs/DESIGN.md).
|
|
191
|
+
|
|
192
|
+
## About this project
|
|
193
|
+
|
|
194
|
+
This tool and its site were written by AI agents. Running `agentblame stats` on this repository shows how much of it agents wrote.
|
|
195
|
+
|
|
196
|
+
## License
|
|
197
|
+
|
|
198
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
import { relative, resolve } from 'node:path';
|
|
4
|
+
import { repoRoot } from '../src/git.js';
|
|
5
|
+
import { loadContext } from '../src/attribute.js';
|
|
6
|
+
import { cmdBlame, cmdWhy } from '../src/commands/blame.js';
|
|
7
|
+
import { cmdStats } from '../src/commands/stats.js';
|
|
8
|
+
import { cmdMap } from '../src/commands/map.js';
|
|
9
|
+
import { cmdNotes } from '../src/commands/notes.js';
|
|
10
|
+
import { cmdPr } from '../src/commands/pr.js';
|
|
11
|
+
|
|
12
|
+
const HELP = `agentblame — git blame, but for AI
|
|
13
|
+
|
|
14
|
+
Usage:
|
|
15
|
+
agentblame <file>[:<line>[-<end>]] blame a file (AI vs human, per line)
|
|
16
|
+
agentblame why <file>:<line> the prompt, session and model behind one line
|
|
17
|
+
agentblame stats [paths…] how much of this repo agents wrote, and which prompts
|
|
18
|
+
agentblame map [-o file.html] self-contained HTML provenance map
|
|
19
|
+
agentblame notes [<rev-range>] store provenance in git notes (refs/notes/agentblame), without prompts
|
|
20
|
+
agentblame pr <base>[..<head>] attribution for the lines a PR adds (head defaults to HEAD)
|
|
21
|
+
|
|
22
|
+
Options:
|
|
23
|
+
--json machine-readable output
|
|
24
|
+
--markdown pr: a GitHub PR comment body
|
|
25
|
+
--fail-under-attributed PCT
|
|
26
|
+
pr: exit 1 unless PCT% of added lines have known provenance
|
|
27
|
+
--prompts notes: store redacted prompt text. Prompts are not stored in notes unless you pass --prompts, because notes are pushed with the repo.
|
|
28
|
+
--no-prompts omit prompt text (map / pr / json)
|
|
29
|
+
--no-claude ignore Claude Code transcripts (~/.claude/projects)
|
|
30
|
+
--no-codex ignore Codex transcripts (~/.codex/sessions)
|
|
31
|
+
--no-notes ignore refs/notes/agentblame
|
|
32
|
+
--claude-dir DIR transcripts location (default ~/.claude/projects)
|
|
33
|
+
--deep scan every Claude project dir, not only those that can touch this repo (slow)
|
|
34
|
+
--no-cache don't read or write the parsed-transcript cache (~/.cache/agentblame)
|
|
35
|
+
--codex-dir DIR Codex sessions location (default ~/.codex/sessions)
|
|
36
|
+
--top N rows in stats tables (default 5)
|
|
37
|
+
-o, --out FILE output path for map
|
|
38
|
+
-h, --help show this help
|
|
39
|
+
|
|
40
|
+
Everything runs locally. Nothing is uploaded.`;
|
|
41
|
+
|
|
42
|
+
function parseArgs(argv) {
|
|
43
|
+
const opts = { _: [] };
|
|
44
|
+
for (let i = 0; i < argv.length; i++) {
|
|
45
|
+
const a = argv[i];
|
|
46
|
+
const val = () => argv[++i];
|
|
47
|
+
if (a === '-h' || a === '--help') opts.help = true;
|
|
48
|
+
else if (a === '--json') opts.json = true;
|
|
49
|
+
else if (a === '--no-prompts') opts.noPrompts = true;
|
|
50
|
+
else if (a === '--prompts') opts.prompts = true;
|
|
51
|
+
else if (a === '--no-claude') opts.claude = false;
|
|
52
|
+
else if (a === '--no-codex') opts.codex = false;
|
|
53
|
+
else if (a === '--no-notes') opts.notes = false;
|
|
54
|
+
else if (a === '--dry-run') opts.dryRun = true;
|
|
55
|
+
else if (a === '--deep') opts.deep = true;
|
|
56
|
+
else if (a === '--no-cache') opts.cache = false;
|
|
57
|
+
else if (a === '--claude-dir') opts.claudeDir = val();
|
|
58
|
+
else if (a === '--codex-dir') opts.codexDir = val();
|
|
59
|
+
else if (a === '--top') opts.top = Number(val());
|
|
60
|
+
else if (a === '--markdown') opts.markdown = true;
|
|
61
|
+
else if (a === '--fail-under-attributed') opts.failUnder = Number(val());
|
|
62
|
+
else if (a === '-o' || a === '--out') opts.out = val();
|
|
63
|
+
else if (a === '--version' || a === '-v') opts.version = true;
|
|
64
|
+
else opts._.push(a);
|
|
65
|
+
}
|
|
66
|
+
return opts;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function main() {
|
|
70
|
+
const opts = parseArgs(process.argv.slice(2));
|
|
71
|
+
if (opts.version) { console.log('0.1.0'); return; }
|
|
72
|
+
if (opts.help || opts._.length === 0) { console.log(HELP); return; }
|
|
73
|
+
|
|
74
|
+
const root = repoRoot(process.cwd());
|
|
75
|
+
if (!root) fail('not inside a git repository');
|
|
76
|
+
const [cmd, ...rest] = opts._;
|
|
77
|
+
|
|
78
|
+
const ctx = () => {
|
|
79
|
+
const t = Date.now();
|
|
80
|
+
const c = loadContext(root, opts);
|
|
81
|
+
if (!opts.json) process.stderr.write(`\x1b[2m${c.events.length} agent edits loaded from transcripts in ${Date.now() - t}ms\x1b[0m\n`);
|
|
82
|
+
return c;
|
|
83
|
+
};
|
|
84
|
+
const relOf = (p) => {
|
|
85
|
+
const abs = resolve(process.cwd(), p);
|
|
86
|
+
let real = abs;
|
|
87
|
+
try { real = realpathSync(abs); } catch {}
|
|
88
|
+
return relative(root, real);
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
switch (cmd) {
|
|
92
|
+
case 'stats': return cmdStats(ctx(), rest.map(relOf), opts);
|
|
93
|
+
case 'map': return cmdMap(ctx(), opts);
|
|
94
|
+
case 'notes': return cmdNotes(ctx(), rest[0], opts);
|
|
95
|
+
case 'pr': {
|
|
96
|
+
if (!rest[0]) fail('usage: agentblame pr <base>[..<head>]');
|
|
97
|
+
if (opts.failUnder !== undefined && !(opts.failUnder >= 0 && opts.failUnder <= 100)) fail('--fail-under-attributed takes a percentage from 0 to 100');
|
|
98
|
+
return cmdPr(ctx(), rest[0], opts);
|
|
99
|
+
}
|
|
100
|
+
case 'why': {
|
|
101
|
+
const t = parseTarget(rest[0]);
|
|
102
|
+
if (!t?.start) fail('usage: agentblame why <file>:<line>');
|
|
103
|
+
return cmdWhy(ctx(), relOf(t.file), t.start, opts);
|
|
104
|
+
}
|
|
105
|
+
case 'blame': {
|
|
106
|
+
const t = parseTarget(rest[0]);
|
|
107
|
+
if (!t) fail('usage: agentblame blame <file>[:line]');
|
|
108
|
+
return cmdBlame(ctx(), relOf(t.file), t, opts);
|
|
109
|
+
}
|
|
110
|
+
default: {
|
|
111
|
+
const t = parseTarget(cmd);
|
|
112
|
+
return cmdBlame(ctx(), relOf(t.file), t, opts);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function parseTarget(s) {
|
|
118
|
+
if (!s) return null;
|
|
119
|
+
const m = s.match(/^(.*?):(\d+)(?:-(\d+))?$/);
|
|
120
|
+
if (!m) return { file: s };
|
|
121
|
+
return { file: m[1], start: Number(m[2]), end: Number(m[3] || m[2]) };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function fail(msg) {
|
|
125
|
+
console.error(`agentblame: ${msg}`);
|
|
126
|
+
process.exit(1);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
main().catch((e) => fail(e.stack || e.message));
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentblame",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "git blame, but for AI. See which agent session — and which prompt — wrote every line of your code.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"agentblame": "bin/agentblame.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=20"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "node --test test/*.test.js",
|
|
20
|
+
"bench": "node bench/run.js"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"git",
|
|
24
|
+
"blame",
|
|
25
|
+
"ai",
|
|
26
|
+
"agents",
|
|
27
|
+
"claude-code",
|
|
28
|
+
"codex",
|
|
29
|
+
"provenance",
|
|
30
|
+
"attribution"
|
|
31
|
+
],
|
|
32
|
+
"license": "MIT",
|
|
33
|
+
"author": "agentblame contributors",
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "git+https://github.com/Yatishgrandhe/agentblame.git"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://github.com/Yatishgrandhe/agentblame#readme",
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/Yatishgrandhe/agentblame/issues"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/attribute.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { loadClaudeEvents } from './sources/claude.js';
|
|
5
|
+
import { loadCodexEvents } from './sources/codex.js';
|
|
6
|
+
import { blame, readNotes } from './git.js';
|
|
7
|
+
import { hash, isTrivial, normalizeLine, similarity, splitLines } from './normalize.js';
|
|
8
|
+
import { progressReporter } from './progress.js';
|
|
9
|
+
|
|
10
|
+
const SLACK_MS = 5 * 60 * 1000; // clock skew between transcript timestamps and git
|
|
11
|
+
// Hand-picked before the benchmark existed; not tuned. A token-level alternative was
|
|
12
|
+
// tried and rejected on held-out seeds (see docs/BENCHMARK.md, S5).
|
|
13
|
+
const FUZZY_THRESHOLD = 0.72;
|
|
14
|
+
|
|
15
|
+
/** Map an absolute path an agent wrote to a repo-relative path (handles git worktrees). */
|
|
16
|
+
export function relPathFor(file, root) {
|
|
17
|
+
const strip = (p) => p.replace(/^\/private(?=\/)/, '');
|
|
18
|
+
const f = strip(file), r = strip(root);
|
|
19
|
+
if (!f.startsWith(r + '/')) return null;
|
|
20
|
+
let rel = f.slice(r.length + 1);
|
|
21
|
+
const wt = rel.match(/^\.(?:claude|codex)\/worktrees\/[^/]+\/(.+)$/) || rel.match(/^\.worktrees\/[^/]+\/(.+)$/);
|
|
22
|
+
if (wt) rel = wt[1];
|
|
23
|
+
return rel;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function loadContext(root, opts = {}) {
|
|
27
|
+
const claudeDir = opts.claudeDir || process.env.AGENTBLAME_CLAUDE_DIR || join(homedir(), '.claude', 'projects');
|
|
28
|
+
const codexDir = opts.codexDir || process.env.AGENTBLAME_CODEX_DIR || join(homedir(), '.codex', 'sessions');
|
|
29
|
+
const cache = opts.cache !== false;
|
|
30
|
+
const progress = progressReporter({ enabled: !opts.json && !!process.stderr.isTTY });
|
|
31
|
+
const events = [];
|
|
32
|
+
if (opts.claude !== false) events.push(...loadClaudeEvents(claudeDir, { root, deep: !!opts.deep, cache, progress }));
|
|
33
|
+
if (opts.codex !== false) events.push(...loadCodexEvents(codexDir, { cache, progress }));
|
|
34
|
+
progress.finish();
|
|
35
|
+
events.push(...(opts.extraEvents || []));
|
|
36
|
+
if (opts.notes !== false) events.push(...notesToEvents(readNotes(root)));
|
|
37
|
+
return buildContext(root, events);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function buildContext(root, rawEvents) {
|
|
41
|
+
const events = [];
|
|
42
|
+
for (const ev of rawEvents) {
|
|
43
|
+
const rel = ev.rel || relPathFor(ev.file, root);
|
|
44
|
+
if (!rel || !ev.ts) continue;
|
|
45
|
+
events.push({ ...ev, rel, idx: events.length });
|
|
46
|
+
}
|
|
47
|
+
const byHash = new Map();
|
|
48
|
+
const byPath = new Map();
|
|
49
|
+
for (const ev of events) {
|
|
50
|
+
for (const a of ev.added) {
|
|
51
|
+
if (a.text != null && isTrivial(a.text)) continue;
|
|
52
|
+
const h = a.h || hash(normalizeLine(a.text));
|
|
53
|
+
const entry = { ev, text: a.text ?? null, h, block: a.block, pos: a.pos };
|
|
54
|
+
if (!byHash.has(h)) byHash.set(h, []);
|
|
55
|
+
byHash.get(h).push(entry);
|
|
56
|
+
if (a.text != null) {
|
|
57
|
+
if (!byPath.has(ev.rel)) byPath.set(ev.rel, []);
|
|
58
|
+
byPath.get(ev.rel).push(entry);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// A loop, not Math.min(...spread): spreading a large array overflows the call stack.
|
|
63
|
+
let coverageStart = Infinity;
|
|
64
|
+
for (const e of events) if (e.ts < coverageStart) coverageStart = e.ts;
|
|
65
|
+
return { root, events, byHash, byPath, coverageStart, trigramCache: new Map() };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Attribute every line of a file. Each line gets one of:
|
|
70
|
+
* agent – an agent wrote it and it survives unchanged (modulo formatting)
|
|
71
|
+
* modified – an agent wrote it, a human later edited it
|
|
72
|
+
* human – written after transcript coverage began, no agent match
|
|
73
|
+
* unknown – predates any transcript we have; we can't say
|
|
74
|
+
* trivial – braces/blank lines; excluded from all percentages
|
|
75
|
+
*/
|
|
76
|
+
export function attributeFile(ctx, rel, { content, blameLines } = {}) {
|
|
77
|
+
const text = content ?? safeRead(join(ctx.root, rel));
|
|
78
|
+
if (text == null) return null;
|
|
79
|
+
const lines = splitLines(text);
|
|
80
|
+
const bl = blameLines === undefined ? blame(ctx.root, rel) : blameLines;
|
|
81
|
+
const now = Date.now();
|
|
82
|
+
|
|
83
|
+
const commitTime = (b) => (!b || b.uncommitted ? now : Math.max(b.authorTime || 0, b.committerTime || 0));
|
|
84
|
+
const valid = (entry, b) => entry.ev.ts <= commitTime(b) + SLACK_MS;
|
|
85
|
+
|
|
86
|
+
// Pass 1: exact / normalized hash matches.
|
|
87
|
+
const cands = lines.map((line, i) => {
|
|
88
|
+
if (isTrivial(line)) return null;
|
|
89
|
+
const list = ctx.byHash.get(hash(normalizeLine(line))) || [];
|
|
90
|
+
return list.filter((e) => valid(e, bl?.[i]));
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const out = lines.map((line, i) => {
|
|
94
|
+
const b = bl?.[i] || null;
|
|
95
|
+
const base = { line: i + 1, text: line, blame: b };
|
|
96
|
+
if (cands[i] === null) return { ...base, kind: 'trivial' };
|
|
97
|
+
const same = cands[i].filter((e) => e.ev.rel === rel);
|
|
98
|
+
let pick = latest(same);
|
|
99
|
+
let match = pick ? (pick.text === line ? 'exact' : 'normalized') : null;
|
|
100
|
+
|
|
101
|
+
// Cross-file matches only count as part of a moved *block* (≥3 consecutive
|
|
102
|
+
// lines from the same agent edit) — a lone `return null` elsewhere is noise.
|
|
103
|
+
if (!pick && cands[i].length) {
|
|
104
|
+
const moved = cands[i].filter((e) => e.ev.rel !== rel && blockSupport(cands, i, e) >= 3);
|
|
105
|
+
pick = latest(moved);
|
|
106
|
+
if (pick) match = 'moved';
|
|
107
|
+
}
|
|
108
|
+
if (pick) {
|
|
109
|
+
const confidence = match === 'exact' ? 'high' : match === 'normalized' ? 'high' : 'medium';
|
|
110
|
+
return { ...base, kind: 'agent', match, confidence, event: pick.ev };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Pass 2: fuzzy — agent-written line a human later edited.
|
|
114
|
+
const fz = fuzzyMatch(ctx, rel, line, b, valid);
|
|
115
|
+
if (fz) return { ...base, kind: 'modified', match: 'fuzzy', confidence: fz.sim > 0.85 ? 'medium' : 'low', similarity: Number(fz.sim.toFixed(2)), original: fz.entry.text, event: fz.entry.ev };
|
|
116
|
+
|
|
117
|
+
const t = commitTime(b);
|
|
118
|
+
if (t < ctx.coverageStart - SLACK_MS) return { ...base, kind: 'unknown' };
|
|
119
|
+
return { ...base, kind: 'human' };
|
|
120
|
+
});
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function latest(list) {
|
|
125
|
+
let best = null;
|
|
126
|
+
for (const e of list) if (!best || e.ev.ts > best.ev.ts) best = e;
|
|
127
|
+
return best;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function blockSupport(cands, i, e) {
|
|
131
|
+
const same = (j) => cands[j]?.some((c) => c.ev.idx === e.ev.idx && c.block === e.block);
|
|
132
|
+
let n = 1;
|
|
133
|
+
for (let j = i - 1; j >= 0 && (cands[j] === null || same(j)); j--) if (cands[j]) n++;
|
|
134
|
+
for (let j = i + 1; j < cands.length && (cands[j] === null || same(j)); j++) if (cands[j]) n++;
|
|
135
|
+
return n;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function fuzzyMatch(ctx, rel, line, b, valid) {
|
|
139
|
+
const pool = ctx.byPath.get(rel);
|
|
140
|
+
if (!pool || normalizeLine(line).length < 12) return null;
|
|
141
|
+
let best = null;
|
|
142
|
+
for (const entry of pool) {
|
|
143
|
+
if (!valid(entry, b) || entry.text == null) continue;
|
|
144
|
+
const s = similarity(line, entry.text);
|
|
145
|
+
if (s >= FUZZY_THRESHOLD && (!best || s > best.sim || (s === best.sim && entry.ev.ts > best.entry.ev.ts))) best = { sim: s, entry };
|
|
146
|
+
}
|
|
147
|
+
return best;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function safeRead(p) {
|
|
151
|
+
try {
|
|
152
|
+
const st = statSync(p);
|
|
153
|
+
if (!st.isFile() || st.size > 2 * 1024 * 1024) return null;
|
|
154
|
+
const buf = readFileSync(p);
|
|
155
|
+
if (buf.includes(0)) return null; // binary
|
|
156
|
+
return buf.toString('utf8');
|
|
157
|
+
} catch { return null; }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** git notes written by `agentblame notes` become events, so provenance travels with the repo. */
|
|
161
|
+
export function notesToEvents(notes) {
|
|
162
|
+
const out = [];
|
|
163
|
+
for (const [commit, note] of notes) {
|
|
164
|
+
for (const e of note?.entries || []) {
|
|
165
|
+
out.push({
|
|
166
|
+
source: e.source || 'notes', sessionId: e.sessionId, ts: e.ts, model: e.model, prompt: e.prompt,
|
|
167
|
+
rel: e.file, file: e.file, tool: 'notes', fromNote: commit, verified: true,
|
|
168
|
+
added: (e.lines || []).map((h, i) => ({ h, text: null, block: 0, pos: i })),
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function summarize(results) {
|
|
176
|
+
const counts = { agent: 0, modified: 0, human: 0, unknown: 0, trivial: 0 };
|
|
177
|
+
for (const r of results) counts[r.kind]++;
|
|
178
|
+
const attributable = counts.agent + counts.modified + counts.human;
|
|
179
|
+
return { ...counts, attributable, agentShare: attributable ? (counts.agent + counts.modified) / attributable : 0 };
|
|
180
|
+
}
|
package/src/cache.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
|
|
6
|
+
// Bump the version directory whenever the parsers change what they emit.
|
|
7
|
+
const CACHE_VERSION = 'v2'; // v2: Bash heredoc writes are now emitted (src/sources/shell.js)
|
|
8
|
+
|
|
9
|
+
export function cacheDir() {
|
|
10
|
+
const base = process.env.XDG_CACHE_HOME || join(homedir(), '.cache');
|
|
11
|
+
return join(base, 'agentblame', CACHE_VERSION);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Parse one transcript, or reuse the events cached for it. A cache entry is
|
|
16
|
+
* valid only while the transcript's size and mtime are unchanged. Entries hold
|
|
17
|
+
* every event in the file, so they do not depend on which repo is being looked
|
|
18
|
+
* at; repo filtering happens later in buildContext.
|
|
19
|
+
*/
|
|
20
|
+
export function cachedTranscript(file, parse, { cache = true, namespace = '' } = {}) {
|
|
21
|
+
let st;
|
|
22
|
+
try { st = statSync(file); } catch { return []; }
|
|
23
|
+
if (!st.isFile()) return [];
|
|
24
|
+
const abs = resolve(file);
|
|
25
|
+
const dir = cacheDir();
|
|
26
|
+
const entry = join(dir, `${createHash('sha1').update(namespace + abs).digest('hex')}.json`);
|
|
27
|
+
if (cache) {
|
|
28
|
+
const hit = readEntry(entry, abs, st);
|
|
29
|
+
if (hit) return hit;
|
|
30
|
+
}
|
|
31
|
+
let text;
|
|
32
|
+
try { text = readFileSync(abs, 'utf8'); } catch { return []; }
|
|
33
|
+
const events = parse(text, abs);
|
|
34
|
+
if (cache) writeEntry(dir, entry, { path: abs, size: st.size, mtimeMs: st.mtimeMs, events });
|
|
35
|
+
return events;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function readEntry(entry, abs, st) {
|
|
39
|
+
try {
|
|
40
|
+
const c = JSON.parse(readFileSync(entry, 'utf8'));
|
|
41
|
+
if (c && c.path === abs && c.size === st.size && c.mtimeMs === st.mtimeMs && Array.isArray(c.events)) return c.events;
|
|
42
|
+
} catch {}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function writeEntry(dir, entry, data) {
|
|
47
|
+
let tmp = null;
|
|
48
|
+
try {
|
|
49
|
+
mkdirSync(dir, { recursive: true });
|
|
50
|
+
tmp = `${entry}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
51
|
+
writeFileSync(tmp, JSON.stringify(data));
|
|
52
|
+
renameSync(tmp, entry);
|
|
53
|
+
} catch {
|
|
54
|
+
if (tmp) try { unlinkSync(tmp); } catch {}
|
|
55
|
+
}
|
|
56
|
+
}
|