codehere 2.0.4 → 2.1.0-rc.2

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  **A team brain for vibe coders.** It stops your AI coding agent from going in circles, checks "done" for real, and shares what your team learns. It works through plain files in git.
4
4
 
5
- Codehere is built to remove work, not add it. You keep using Claude Code, Codex CLI or Copilot CLI as usual. Codehere talks to the agent, not to you, and stays silent unless it helps.
5
+ Codehere is built to remove work, not add it. You keep using Claude Code, Codex CLI or Copilot CLI as usual. Codehere talks to the agent, not to you, and stays silent unless it helps. For team chores, you ask your agent, and it shows you a draft first.
6
6
 
7
7
  ## What it does
8
8
 
@@ -14,8 +14,8 @@ Codehere is built to remove work, not add it. You keep using Claude Code, Codex
14
14
  | Watch the agent try the same failing fix again and again | After the same error 3 times, the agent is told to stop and find the root cause first |
15
15
  | Trust "Done!" and find it broken later | Codehere runs your tests itself. If they fail, the agent goes back to work. |
16
16
  | Miss that a test was skipped or deleted to make it "pass" | The agent is blocked and asked to restore it |
17
- | Lose a long, messy session and start over from scratch | When a long session keeps hitting the same error, the agent suggests `codehere brief`: one clean spec that the next session loads |
18
- | Write a long message to ask a friend for help | `codehere help` writes a redacted help card for you |
17
+ | Lose a long, messy session and start over from scratch | When a long session keeps hitting the same error, the agent offers a restart brief: one clean spec that the next session loads |
18
+ | Write a long message to ask a friend for help | Your agent writes a redacted help card and shows it to you |
19
19
  | Solve a bug that a teammate already solved last week | Their fix reaches your agent the first time the error appears |
20
20
 
21
21
  ## Install (2 minutes)
@@ -42,6 +42,21 @@ The test command is in `.codehere/config.json`, which anyone with push access ca
42
42
 
43
43
  ## The team loop
44
44
 
45
+ Ask your agent in chat. It runs a Codehere command that prints a draft, shows you the draft, and Codehere saves it only if your next message is a plain yes:
46
+
47
+ ```text
48
+ You: Add a team rule: prices are in cents, never floats.
49
+ Agent: Here is the draft:
50
+ - Prices are in cents. Never use floats for money. (Ana, 2026-11-03)
51
+ Save it?
52
+ You: yes
53
+ codehere › saved after your yes · rule · Prices are in cents. Never use floats for money.
54
+ ```
55
+
56
+ The agent's words vary; the draft line and the `codehere ›` line come from Codehere. A reply from a fixed list saves: "yes", "ok", "sure", "save it", "go ahead", "do it" and a few more, alone or followed by "please" or "thanks". Any other reply discards the draft, including "no", "change the wording first" and "yes, save it", and you see a line saying it was not saved. Then commit and push `.codehere/` yourself: Codehere never does, and the agent is told not to. Teammates get it after `git pull`.
57
+
58
+ The same works for "ask the team for help with this", "anything from my team?" and answering a teammate's card. These are the commands the agent runs. Typed in your own terminal, they save at once, as before:
59
+
45
60
  ```bash
46
61
  codehere rule "Prices are in cents. Never use floats for money." # every agent follows it
47
62
 
@@ -55,7 +70,7 @@ codehere reply <id> "Use price * qty; same bug was in checkout.js" --solved
55
70
  git add .codehere && git commit -m "answer" && git push
56
71
  ```
57
72
 
58
- `--solved` turns the answer into a **team lesson**. From then on, any teammate's agent that hits a similar error gets that fix automatically. When an agent solves a repeated error by itself, Codehere saves a lesson with the proof from that test run (command, exit code, commit, the files the fix changed) and asks the agent to fill in the cause and the fix.
73
+ `--solved` turns the answer into a **team lesson**. From then on, any teammate's agent that hits a similar error gets that fix automatically. When an agent solves a repeated error by itself, it offers the fix as a team lesson. When Codehere's own test run passed here, the lesson carries that proof (command, exit code, commit, the files the fix changed); otherwise it is saved as not verified. You see a line naming the error and the proof, and the lesson is saved only if you say yes.
59
74
 
60
75
  You see one line per event:
61
76
 
@@ -80,11 +95,12 @@ Don't want to commit help cards? Copy the printed text into WhatsApp, Discord or
80
95
  | Finish check: your tests re-run, the agent sent back | yes | yes | yes |
81
96
  | Your one line (✓ ✕ ⊘ ›) | yes | in the interactive screen, as `↳ Hook · codehere ✓ …`; not in `codex exec` | no; when the agent is sent back, you see the full reason as the next prompt |
82
97
  | Restart-brief suggestion in long sessions | yes | no | no |
98
+ | Ask the agent for a team chore, saved on your yes | yes: 12 of 12 runs (rule, help card, answer a card, lesson; [result](docs/conformance/2026-11-03-claude-2.1.317-haiku-chores.md)) | partly, with a 9B local model: lesson 2 of 3, rule, help card and answer 0 of 3; the agent wrote the team files itself ([result](docs/conformance/2026-11-03-codex-0.164.0-qwen3.5-9b-q4_K_M-chores.md), [lesson](docs/conformance/2026-11-03-codex-0.164.0-qwen3.5-9b-q4_K_M-chores-L10.md)) | partly, with a 9B local model: rule and answer 3 of 3, help card and lesson 0 of 3 ([result](docs/conformance/2026-11-03-copilot-1.0.105-qwen3.5-9b-q4_K_M-chores.md)) |
83
99
  | Before it works | nothing | each developer trusts the hooks in `/hooks` | each developer trusts the folder when Copilot asks |
84
100
  | MCP tools, instruction file | no | no | no |
85
101
  | Tested on | 2.1.311 with haiku: [result](docs/conformance/2026-10-27-claude-2.1.311-haiku.md) | 0.164.0 with a local model (Qwen 3.5 9B through Ollama): [result](docs/conformance/2026-10-27-codex-0.164.0-qwen3.5-9b-q4-K-M.md) | 1.0.105 with a local model (Qwen 3.5 9B through Ollama): [result](docs/conformance/2026-10-29-copilot-1.0.105-qwen3.5-9b-q4-K-M.md), with only the Claude Code hooks installed: [result](docs/conformance/2026-10-29-copilot-1.0.105-qwen3.5-9b-q4-K-M-claude-hooks-only.md), and with a GitHub-hosted model (`auto`, which picked gpt-6-luna): [result](docs/conformance/2026-10-29-copilot-1.0.105-auto.md) |
86
102
 
87
- The rows for rules, lessons and the finish check are checked on the real agent by `node scripts/conformance.mjs`. The other rows are checked by `npm test` on hook inputs recorded from each agent.
103
+ The rows for rules, lessons and the finish check are checked on the real agent by `node scripts/conformance.mjs`, and the chores row by `node scripts/chores.mjs` (3 runs per chore, each in a fresh repo). The other rows are checked by `npm test` on hook inputs recorded from each agent.
88
104
 
89
105
  ## Commands
90
106
 
@@ -94,7 +110,8 @@ codehere init [--agent claude,codex,copilot] [--test "npm test"]
94
110
  codehere approve let the finish check run the test command on this machine
95
111
  codehere uninstall remove Codehere from this repo (asks first)
96
112
  codehere rule ["text"] add or list team rules
97
- codehere lesson ["problem" --fix "..."] add or list lessons
113
+ codehere lesson ["problem" --fix "..." [--cause "..."]]
114
+ add or list lessons
98
115
  codehere brief [--gemma] restart brief for a fresh session
99
116
  codehere help ["question"] [--gemma] help card for a teammate
100
117
  codehere inbox [--all] teammates' help cards
@@ -102,18 +119,23 @@ codehere show <id> read a help card
102
119
  codehere reply <id> "answer" [--solved] answer; --solved makes a lesson
103
120
  codehere status what Codehere has seen
104
121
  codehere stats turns to green, loops stopped, context size
122
+ codehere audit commits of the last 90 days that deleted, skipped or weakened tests
105
123
  ```
106
124
 
125
+ `codehere audit` reads this repo's git history on your machine and sends nothing anywhere. It lists every commit that deleted a test file, skipped a test, or removed or weakened assertions in test files, and says which ones carry an agent's marker (`Co-Authored-By` naming Claude, Copilot or Codex, `Claude-Session:`, `Agent-Logs-Url:`, or the `copilot-swe-agent[bot]` author). The count is found by pattern: read each commit before drawing a conclusion. A commit with no marker may still be an agent's, since markers can be turned off.
126
+
127
+ When an agent runs `rule`, `lesson`, `help` or `reply`, the command prints a draft and saves nothing. Codehere saves it if your next message is a plain yes. Typed in your own terminal, they save at once.
128
+
107
129
  ## What lives where
108
130
 
109
131
  ```
110
132
  .codehere/
111
- rules.md team rules (written by people)
133
+ rules.md team rules (typed by a person, or saved after their yes)
112
134
  lessons/ solved errors, one markdown file each
113
135
  help/ help cards
114
136
  briefs/ restart briefs
115
137
  config.json test command, loop threshold
116
- local/ this machine only, git-ignored (session state)
138
+ local/ this machine only, git-ignored (session state, drafts)
117
139
  ```
118
140
 
119
141
  Everything is plain markdown, so you can read, edit, review and delete it like any other file.
@@ -121,13 +143,13 @@ Everything is plain markdown, so you can read, edit, review and delete it like a
121
143
  ## Design rules (from the research)
122
144
 
123
145
  - **No AI in the decision path.** Loops, failed tests and tampering are detected with plain rules, so Codehere doesn't inherit the agent's mistakes.
124
- - **It talks to the agent, not to you.** If Codehere is wrong, the agent does one extra check. You lose nothing.
125
- - **Silent on normal turns.** Your prompt gets extra context only after a failure, for a feature with no way to check it, or in a long session stuck on one error. Each at most once, under 300 tokens.
126
- - **It only reacts to this session's work.** Changes you had before the session are ignored. If the agent changed nothing, Codehere does nothing.
146
+ - **It talks to the agent, not to you.** If Codehere is wrong, the agent does one extra check. You lose nothing. For team chores, you ask your agent, and it shows you a draft first.
147
+ - **Silent on normal turns.** Your prompt gets extra context only after a failure, for a feature with no way to check it, or in a long session stuck on one error. Each at most once, under 300 tokens. After you answer a draft, you also get one line saying whether it was saved.
148
+ - **It only reacts to this session's work.** Changes you had before the session are ignored. If the agent changed nothing, Codehere does nothing. A draft saved after your yes does not count as a change by the agent.
127
149
  - **It never traps the agent.** At most 3 "not done yet" messages per session, then it lets go.
128
150
  - **It fails open.** If anything breaks, the hook exits quietly and the agent carries on.
129
151
  - **Small model, small job.** Gemma 4 (via Ollama) is optional and only writes summaries for briefs and help cards, which you read before using. Turn it on with `--gemma`. The text goes only to a model on this machine: Codehere refuses an `OLLAMA_HOST` on another machine and Ollama cloud models, and uses the plain text instead.
130
- - **Only human-confirmed context at session start.** Rules are written by people. Lessons appear only when a matching error shows up, because auto-generated context files can make agents worse.
152
+ - **Only human-confirmed context at session start.** Rules and lessons are typed by a person, or drafted by the agent and saved after the person's yes. Lessons appear only when a matching error shows up, because auto-generated context files can make agents worse.
131
153
 
132
154
  ## Try the demo (no Claude account needed)
133
155
 
@@ -145,13 +167,24 @@ npm test # end-to-end checks
145
167
  - The "done" check needs a test command. Without one, only the tampering check runs.
146
168
  - Approvals are per folder. Each git worktree or extra clone needs its own `codehere approve`.
147
169
  - In `codex exec`, Codex shows you none of Codehere's lines. The agent still gets every message, and the finish check still sends it back.
148
- - Copilot shows you none of Codehere's lines either, so on Copilot you do not see the ✓, the ⊘, or the notes about an approval, an uninstall or a settings change during a session. The agent still gets every message, and when the finish check sends it back you see the reason as the next prompt.
170
+ - Copilot shows you none of Codehere's lines either, so on Copilot you do not see the ✓, the ⊘, or the notes about an approval, an uninstall, a settings change or team files changed during a session. The agent gets every message except what Codehere adds to your prompt (Copilot drops that, so its agent is not told when a draft is saved or discarded), and when the finish check sends it back you see the reason as the next prompt.
149
171
  - Copilot's cloud agent also runs the committed `.github/hooks/codehere.json`. `codehere` is not installed there, so by GitHub's docs each hook fails and the job carries on without Codehere.
150
172
  - `codehere approve` and `codehere uninstall` ask only in your own terminal. They refuse when Claude Code, Codex or Copilot is among the processes above them, and inside Codex's sandbox. An agent that detaches its terminal on purpose can still answer, so the finish check of a session that was open tells you when an approval or an uninstall happened (not on Copilot, which shows none of these lines).
151
173
  - Approving `npm test` approves that command, not the scripts behind it in `package.json`. And Claude Code runs any hook a teammate adds to the committed `.claude/settings.json`, as Copilot does in a trusted folder for `.github/hooks/` and `.claude/settings.json`; Codex asks each developer to trust a new or changed hook first. Both are your repo's code, with the same trust as running it yourself.
152
- - When the agent changes `.codehere/config.json`, `.codehere/rules.md`, the hook and env settings in `.claude/settings*.json` or `.github/copilot/settings*.json`, or `.codex/hooks.json`, `.codex/config.toml` or `.github/hooks/codehere.json` during a session, the finish check tells you. It cannot tell you if the session ends without a finish check, for example when you close it mid-turn. An agent that sets out to fake your terminal or rewrite Codehere's local files can also get around this.
174
+ - When the agent changes `.codehere/config.json`, `.codehere/rules.md` (except a rule saved after your yes), the hook and env settings in `.claude/settings*.json` or `.github/copilot/settings*.json`, or `.codex/hooks.json`, `.codex/config.toml` or `.github/hooks/codehere.json` during a session, the finish check tells you. It cannot tell you if the session ends without a finish check, for example when you close it mid-turn. An agent that sets out to fake your terminal or rewrite Codehere's local files can also get around this.
175
+ - When the agent writes, changes or deletes a lesson or help card in `.codehere/` itself during a session, without a draft you said yes to, the finish check lists the files for you (not on Copilot or in `codex exec`, which show none of Codehere's lines). It does not stop the agent, and it does not list files that arrive committed, such as after a `git pull`, or a change the agent commits itself. A card a pull changes while it holds your own uncommitted changes is listed. A command that also deletes Codehere's local files, such as `git clean -x`, hides the change, and so can an agent that sets out to hide a change from git.
153
176
  - Only the test command needs approval. A teammate who sets `verifyOnStop` to `false` in `.codehere/config.json` turns the finish check off for everyone; `codehere status` shows it as off.
154
177
  - Sharing is through git. There is no server, so teammates see updates after `git pull`.
178
+ - `codehere audit` follows git's `--since`: git stops reading history at the first commit older than 90 days, so a newer commit behind a back-dated one is not read. A shallow clone has no history to read, and the audit says so.
179
+ - The yes before a draft is saved is checked by Codehere's hooks with a word list. An agent deliberately working around Codehere could fake that reply, as it could fake other hook input.
180
+ - A command you send through the agent drafts: Claude Code's `!` and scripts with no terminal take the agent's path, and so does every command on a machine without `ps`. In VS Code an agent's command can run in a real terminal with no agent above it, and then saves at once. No test has shown whether a `!` command reaches Codehere's hooks; if it does not, your yes gets a "nothing saved" line.
181
+ - A one-shot run (`claude -p`, `codex exec`) that is never resumed has no next message, so its drafts are never saved; a resumed turn (`--resume`, `codex exec resume`) can answer them. Unsaved drafts are removed after 7 days.
182
+ - Codex saves no drafts until you trust its hooks in `/hooks`.
183
+ - If the agent deletes a draft after showing it to you, your yes saves nothing and neither of you is told.
184
+ - Two agent sessions in one repo at once: `help` and `brief` read the session that last ran a hook, a yes in one session can get a wrong "nothing saved" line about the other session's draft, and a rule saved after a yes can be reported once as a settings change.
185
+ - A lesson offered at the finish check is saved only if you say yes. In 2.0.3 every solved repeated error left a lesson file.
186
+ - Restart briefs are written without a yes, for your own next session. They enter git only if you commit `.codehere/briefs/`.
187
+ - A committed link to a folder that holds another repo's `.codehere/` can lead Codehere, run from inside that folder, to write its own local files there. `init` can stop halfway on a file it may not write, such as a read-only `.gitignore`.
155
188
  - Prompt checks are plain word lists (English and Indonesian). They can miss a short prompt in another language.
156
189
  - The weakened-test scan catches skipped and focused tests (`.skip`, `xit`, `{ skip: true }`, `.only`, `fit`), deleted test files, an assertion commented out with `//` or `#`, assertions that cannot fail (`assert.equal(1, 1)`), at least two more assertion lines removed than added, and a `package.json` test script changed to always pass (`|| true`). It does not catch one removed assertion, assertions wrapped in `/* */`, options spread over several lines, an edited expected value, or a `return` above an assertion; see `docs/overlap-with-check.md`.
157
190
 
package/bin/codehere.js CHANGED
@@ -33,7 +33,7 @@ Setup
33
33
 
34
34
  Team brain
35
35
  codehere rule ["text"] add a team rule (or list rules)
36
- codehere lesson ["problem" --fix "what fixed it" --sig "error text"]
36
+ codehere lesson ["problem" --fix "what fixed it" --cause "why" --sig "error text"]
37
37
  add a lesson (or list lessons)
38
38
 
39
39
  When you're stuck
@@ -47,6 +47,10 @@ When you're stuck
47
47
 
48
48
  codehere status what Codehere has seen
49
49
  codehere stats turns to green, loops stopped, session size
50
+ codehere audit commits of the last 90 days that deleted, skipped or weakened tests
51
+
52
+ Run by an agent, rule, lesson, help and reply print a draft; it is saved if your next
53
+ message in the chat is a plain yes. Typed in your own terminal, they save at once.
50
54
 
51
55
  Hooks (called by the agent, not by you)
52
56
  codehere hook session-start | prompt | post-tool | stop [--agent codex|copilot]
@@ -83,6 +87,12 @@ const run = async () => {
83
87
  return cmd.status();
84
88
  case 'stats':
85
89
  return cmd.stats();
90
+ case 'audit': {
91
+ // loaded only here: the hooks run on every agent turn and must stay fast
92
+ const { audit } = await import('../src/audit.js');
93
+ process.exitCode = await audit(process.cwd());
94
+ return;
95
+ }
86
96
  default:
87
97
  if (flags.version || command === '-v') {
88
98
  return console.log(`codehere ${JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codehere",
3
- "version": "2.0.4",
3
+ "version": "2.1.0-rc.2",
4
4
  "description": "A git-native team brain for vibe coders. Silent fixes for AI coding agents: breaks doom loops, verifies 'done', blocks test tampering, and shares what your team learned.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/audit.js ADDED
@@ -0,0 +1,163 @@
1
+ // codehere audit: the commits of the last 90 days that weakened tests, each listed for a person to read.
2
+ // Read-only: it runs git on this machine and sends nothing anywhere. The kinds come from the finish
3
+ // check's own detector. A count found by pattern is a list of candidates, never proof (DESIGN.md §1).
4
+ import { spawn, execFileSync } from 'node:child_process';
5
+ import readline from 'node:readline';
6
+ import { printable } from './brain.js';
7
+ import { tamperEvents, isTestFile } from './signals.js';
8
+
9
+ const DAYS = 90;
10
+ const KINDS = new Set(['test-deleted', 'test-skipped', 'assertion-weakened']);
11
+ const BIG = 512 * 1024 * 1024;
12
+
13
+ // How agents mark their commits. A commit without a marker is still counted and listed, unmarked:
14
+ // markers can be turned off, and some agents leave none.
15
+ const MARKERS = [
16
+ { re: /^Co-authored-by:[^\n]*\b(Claude|Copilot|Codex)\b/im, name: (m) => `Co-Authored-By ${m[1]}` },
17
+ { re: /^Claude-Session:/im, name: () => 'Claude-Session' },
18
+ { re: /^Agent-Logs-Url:/im, name: () => 'Agent-Logs-Url' },
19
+ ];
20
+
21
+ export function markersOf(author, body) {
22
+ const found = /copilot-swe-agent\[bot\]/i.test(author) ? ['copilot-swe-agent[bot]'] : [];
23
+ for (const m of MARKERS) {
24
+ const x = m.re.exec(body);
25
+ if (x) found.push(m.name(x));
26
+ }
27
+ return found;
28
+ }
29
+
30
+ function gitLine(root, args) {
31
+ try {
32
+ return execFileSync('git', args, { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ // Every non-merge commit since `since`, with what the markers need.
39
+ function commitsSince(root, since) {
40
+ const out = execFileSync('git', ['log', '--no-merges', `--since=${since}`, '--format=%H%x1f%an <%ae>%x1f%cs%x1f%s%x1f%B%x1e'], {
41
+ cwd: root,
42
+ stdio: ['ignore', 'pipe', 'ignore'],
43
+ maxBuffer: BIG,
44
+ }).toString();
45
+ return out
46
+ .split('\x1e')
47
+ .map((r) => r.replace(/^\n/, ''))
48
+ .filter(Boolean)
49
+ .map((r) => {
50
+ const [sha, author, date, subject, body = ''] = r.split('\x1f');
51
+ return { sha, author, date, subject, body, events: [] };
52
+ });
53
+ }
54
+
55
+ // The path in `diff --git a/P b/P` when both sides name the same file, as they do for a deletion.
56
+ function samePath(line) {
57
+ const rest = line.slice('diff --git a/'.length);
58
+ const half = (rest.length - ' b/'.length) / 2;
59
+ return Number.isInteger(half) && rest.slice(half, half + 3) === ' b/' ? rest.slice(0, half) : '';
60
+ }
61
+
62
+ // One `git log -p`, read line by line: test-file hunks are kept, a deleted file by its name only, so
63
+ // memory stays small however large a commit is. Each commit's kinds go on its entry in bySha.
64
+ function scanChanges(root, since, bySha) {
65
+ return new Promise((resolve, reject) => {
66
+ const child = spawn('git', ['log', '--no-merges', `--since=${since}`, '-p', '--no-color', '--format=%x00%H'], {
67
+ cwd: root,
68
+ stdio: ['ignore', 'pipe', 'ignore'],
69
+ });
70
+ const lines = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
71
+ let commit = null;
72
+ let nameStatus = [];
73
+ let kept = [];
74
+ let keep = false;
75
+ let deleted = '';
76
+ const finish = () => {
77
+ if (commit) commit.events = tamperEvents(nameStatus.join('\n'), kept.join('\n')).filter((e) => KINDS.has(e.kind));
78
+ };
79
+ lines.on('line', (line) => {
80
+ if (line.startsWith('\0')) {
81
+ finish();
82
+ commit = bySha.get(line.slice(1)) || null;
83
+ nameStatus = [];
84
+ kept = [];
85
+ keep = false;
86
+ return;
87
+ }
88
+ if (!commit) return;
89
+ if (line.startsWith('diff --git ')) {
90
+ keep = false;
91
+ deleted = samePath(line);
92
+ return;
93
+ }
94
+ if (line.startsWith('deleted file mode')) {
95
+ if (deleted && isTestFile(deleted)) nameStatus.push(`D\t${deleted}`);
96
+ deleted = '';
97
+ keep = false;
98
+ return;
99
+ }
100
+ if (line.startsWith('+++ ')) {
101
+ const file = line.replace(/^\+\+\+ (b\/)?/, '');
102
+ keep = file !== '/dev/null' && isTestFile(file);
103
+ if (keep) kept.push(`+++ ${file}`);
104
+ return;
105
+ }
106
+ if (keep && !line.startsWith('--- ')) kept.push(line);
107
+ });
108
+ let failed = null;
109
+ child.on('error', (e) => (failed = e));
110
+ const ended = new Promise((r) => lines.on('close', r));
111
+ child.on('close', async (code) => {
112
+ await ended;
113
+ finish();
114
+ if (failed || code !== 0) reject(failed || new Error(`git log exited ${code}`));
115
+ else resolve();
116
+ });
117
+ });
118
+ }
119
+
120
+ function summary(events) {
121
+ const deletedFiles = events.filter((e) => e.kind === 'test-deleted');
122
+ const other = events.filter((e) => e.kind !== 'test-deleted').map((e) => e.why);
123
+ const parts = deletedFiles.length > 1 ? [`${deletedFiles.length} test files deleted`] : deletedFiles.map((e) => e.why);
124
+ parts.push(...other.slice(0, 3));
125
+ if (other.length > 3) parts.push(`and ${other.length - 3} more`);
126
+ return parts.join(' · ');
127
+ }
128
+
129
+ // Prints the audit; returns the exit code.
130
+ export async function audit(root, { out = console.log, err = console.error, now = Date.now() } = {}) {
131
+ if (gitLine(root, ['rev-parse', '--is-inside-work-tree']) !== 'true') {
132
+ err('codehere audit: not inside a git repository');
133
+ return 1;
134
+ }
135
+ if (gitLine(root, ['rev-parse', '--is-shallow-repository']) === 'true') {
136
+ err('codehere audit: this clone is shallow, so its history is not available › git fetch --unshallow');
137
+ return 1;
138
+ }
139
+ const since = new Date(now - DAYS * 24 * 3600 * 1000).toISOString();
140
+ let list;
141
+ try {
142
+ list = commitsSince(root, since);
143
+ if (list.length > 500) err(`codehere audit: reading ${list.length} commits`);
144
+ await scanChanges(root, since, new Map(list.map((c) => [c.sha, c])));
145
+ } catch {
146
+ err('codehere audit: git log failed, so nothing was counted');
147
+ return 1;
148
+ }
149
+ const flagged = list.filter((c) => c.events.length);
150
+ const marked = flagged.filter((c) => markersOf(c.author, c.body).length);
151
+ const n = (k, one, many) => `${k} ${k === 1 ? one : many}`;
152
+ out(`codehere audit · last ${DAYS} days · ${n(list.length, 'commit', 'commits')} read`);
153
+ out(`codehere › ${n(flagged.length, 'commit', 'commits')} weakened tests · ${n(marked.length, 'carries', 'carry')} an agent marker`);
154
+ if (!flagged.length) return 0;
155
+ out('codehere › each was found by pattern: read the commit before drawing a conclusion');
156
+ for (const c of flagged) {
157
+ const m = markersOf(c.author, c.body);
158
+ out('');
159
+ out(` ${c.sha.slice(0, 8)} · ${c.date} · ${m.length ? m.join(', ') : 'no agent marker'} · ${printable(c.subject)}`);
160
+ out(` ${printable(summary(c.events))}`);
161
+ }
162
+ return 0;
163
+ }