your-cto-jev 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  **A sharp-tongued CTO that reviews what your AI coding agent is about to do, and says no.**
4
4
 
5
- `cto` hooks into `git commit` and into Claude Code, Cursor, Gemini CLI and Codex. Before a commit lands, before an agent runs a shell command, and when Claude Code says it is done, it asks [TypeSafe Jev](https://developers.cloudflare.com/ai/models/typesafe/jev/), a typed decision model, a few yes/no questions. Then it blocks, warns, or stays completely silent.
5
+ `cto` hooks into `git commit` and into Claude Code, Cursor, Gemini CLI and Codex. Before a commit lands, before an agent runs a shell command, and when an agent says it is done, it asks [TypeSafe Jev](https://developers.cloudflare.com/ai/models/typesafe/jev/), a typed decision model, a few yes/no questions. Then it blocks, warns, or stays completely silent.
6
6
 
7
7
  ```text
8
8
  $ git commit -m "add payments"
@@ -34,7 +34,7 @@ Jev judges meaning and answers with probabilities, not prose. It costs about $0.
34
34
  | `test_tampering` | `git commit`s that touch tests or test config | **Blocks** the commit |
35
35
  | `destructive_command` | every agent shell command | **Blocks** the command |
36
36
  | `infinite_loop` | agent shell commands, after a recent failure | **Blocks** the command |
37
- | `done_unverified` | Claude Code ending a turn that edited code | **Sends it back to work** until the change is verified or the gap is disclosed |
37
+ | `done_unverified` | an agent ending a turn that edited code or checked off plan items | **Sends it back to work** until the change is verified or the gap is disclosed |
38
38
  | `architecture_violation` | `git commit`, once you set a sprint goal | Warns only |
39
39
  | `code_complexity` | every `git commit` | Warns only |
40
40
 
@@ -42,6 +42,21 @@ Jev judges meaning and answers with probabilities, not prose. It costs about $0.
42
42
 
43
43
  `done_unverified` catches the other classic shortcut: "Done, all tests pass!" when nothing ran after the last edit, the last run failed, or the claim is not backed by anything the agent actually did. It lets through turns that ran a passing check after the last edit, turns that changed only docs or CI config, and turns where the agent honestly says what it could not verify. It blocks at most once per stop, so it cannot loop.
44
44
 
45
+ Checking off a plan item is the same claim. Whatever planning tool you use (spec-kit, GSD, Kiro, specOS, a hand-written `TODO.md`), plans end up as markdown checklists, so `cto` reads the uncommitted `- [ ]` to `- [x]` changes in tracked `.md` files and asks whether the turn backs them up. A phase or parent item counts as backed when everything nested under it is checked, or when the turn ran a passing check that covers it. Each tick is judged once. A turn that only ticks boxes, without doing the work, is checked too.
46
+
47
+ Some checks need no model at all. They run first, before anything is sent anywhere, and they work with no API key:
48
+
49
+ | Local check | Where | What happens |
50
+ |---|---|---|
51
+ | Commit on a branch listed in `protected_branches` | `git commit` | **Blocks** |
52
+ | Deleting or rewriting history of a protected branch | `git push` (pre-push hook) | **Blocks**, whatever ran the push: agent, human, GUI |
53
+ | Merge conflict markers in added lines | `git commit` | **Blocks** |
54
+ | A `.env` file with values (not `.env.example`) | `git commit` | **Blocks** |
55
+ | A file over 5 MB | `git commit` | Warns |
56
+ | `package.json` dependencies changed, lock file not | `git commit` | Warns |
57
+
58
+ `protected_branches` is empty by default; set it in `.cto.json` (`["main"]`) and the whole team's agents stop committing to main by accident. A commit a local check blocks never reaches Jev.
59
+
45
60
  Architecture and complexity only warn on purpose. They are subjective, and a gate that blocks too often teaches people to use `git commit --no-verify`, which switches off the secret check too.
46
61
 
47
62
  When nothing crosses a threshold, `cto` prints nothing at all.
@@ -104,6 +119,8 @@ cto doctor
104
119
 
105
120
  `cto doctor` sends one real request per provider, shows where each key comes from, checks the hooks in the current repo, shows when the last check ran, and counts how often a check was blocked or let through unchecked. It exits non-zero when something needs attention. Run it whenever you are unsure whether `cto` is protecting you: because `cto` fails open, a broken key looks exactly like a clean pass.
106
121
 
122
+ Both `setup` and `doctor` also look at what else is steering the agents, and say so when something could fight cto: other hooks on the same events (in the project and in your user-level settings), lines in `CLAUDE.md`, `AGENTS.md`, `GEMINI.md`, `.cursor/rules` or any installed skill that tell the agent to do what cto blocks (`--no-verify`, skip the tests, commit straight to main, force-push), and a skill installed both globally and in the project. Notes only, never a failure: cto writes its rules into the project and never into your global files, so a global rule that contradicts them is yours to sort out.
123
+
107
124
  Other forms:
108
125
 
109
126
  ```sh
@@ -111,7 +128,9 @@ cto setup --agents claude,cursor --yes # non-interactive (scripts, CI); only a
111
128
  cto setup --refresh # re-write hooks and rules for the agents already set up
112
129
  cto setup --uninstall # remove every cto hook, rules block and skill again
113
130
  cto doctor # is it actually working?
131
+ cto brief # what an agent should know before it starts here
114
132
  cto check # preview the commit checks on your current changes
133
+ cto log # recent decisions with scores; cto report [n] flags a wrong one
115
134
  ```
116
135
 
117
136
  `setup` appends marked blocks and merges JSON. It never overwrites your existing hooks or settings, and `--uninstall` puts them back exactly as they were. It never touches your shell rc files.
@@ -145,21 +164,67 @@ The rules also tell the agent to run `cto check` before committing, and never to
145
164
  [cto] Good to commit.
146
165
  ```
147
166
 
167
+ ## What the agent knows before it starts
168
+
169
+ Gates say no after the fact. `cto brief` works before: it prints what an agent should know on its first turn in the repo, and Claude Code gets it automatically at session start (a `SessionStart` hook; the rules block tells the other agents to run it).
170
+
171
+ ```text
172
+ [cto] brief · shop · main · 2 files uncommitted
173
+
174
+ Sprint goal Ship Stripe billing, no new services
175
+ Verify with npm test
176
+
177
+ Open plan items · TODO.md 3 · 3 unchecked
178
+ - [ ] Add webhook handler
179
+ - [ ] Retry on 5xx
180
+ - [ ] Phase 2: docs
181
+
182
+ Lessons from this repo · 3 of 23 · unresolved and frequent first
183
+ !! npx tsc TS2307: Cannot find module './x.js'
184
+ seen 2x · last 3h ago · UNRESOLVED
185
+ ! npm test TypeError: Cannot read properties of undefined (reading 'map')
186
+ seen 3x · last 2d ago · fixed by editing src/turn.ts · verified by npm test
187
+ - git push rejected: non-fast-forward
188
+ seen 1x · last 5d ago · fixed by editing src/a.ts · verified by git push
189
+
190
+ Failures in the last 15 min none
191
+ Guards secrets · test tampering · destructive commands · loops · unverified done
192
+ ```
193
+
194
+ The lessons are collected without anyone writing them down. Every failed agent command is fingerprinted (the command's first two words plus its first telling error line, with numbers, quoted names and paths normalised) and counted in `.cto-lessons.jsonl`. When the same command later passes after code edits, the files edited in between are recorded as the fix. The file is masked like everything else cto writes, holds at most 200 lessons, and is one JSON line per lesson so teammates' additions merge without conflicts. Commit it: the whole team's agents then start with the repo's history of what breaks and what fixed it. No Jev call is involved.
195
+
196
+ `Verify with` comes from `test_command` in `.cto.json`, or is detected from `package.json`, a `Makefile`, pytest, Cargo or Go when it is empty. Open plan items are the unchecked `- [ ]` lines in tracked markdown files, whatever planning tool wrote them.
197
+
148
198
  ## Supported agents
149
199
 
150
- The git pre-commit check is always installed. It protects every agent and every human who commits from that repo.
200
+ The git pre-commit and pre-push checks are always installed. They protect every agent and every human who commits or pushes from that repo.
151
201
 
152
202
  | Agent | Config written | Command gate | Loop detection | Knows about edits | Done check |
153
203
  |---|---|---|---|---|---|
154
- | Claude Code | `.claude/settings.local.json` | yes | yes | yes | yes |
155
- | Cursor | `.cursor/hooks.json` | yes | yes | yes (`afterFileEdit`) | not yet |
156
- | Gemini CLI | `.gemini/settings.json` | yes | yes | yes (`write_file`, `replace`) | not yet |
157
- | Codex CLI | `.codex/hooks.json` | yes | limited: Codex has no failure event | yes (`apply_patch`) | not yet |
204
+ | Claude Code | `.claude/settings.local.json` | yes | yes | yes | yes, from its transcript |
205
+ | Cursor | `.cursor/hooks.json` | yes | yes | yes (`afterFileEdit`) | yes (`stop`, follow-up message) |
206
+ | Gemini CLI | `.gemini/settings.json` | yes | yes | yes (`write_file`, `replace`) | yes (`AfterAgent`, retry) |
207
+ | Codex CLI | `.codex/hooks.json` | yes | limited: Codex has no failure event | yes (`apply_patch`) | yes (`Stop`) |
158
208
 
159
209
  Claude Code is tested end to end inside the agent. The Cursor, Gemini CLI and Codex adapters follow each agent's official hook docs and are tested with their documented payloads, but have not been run inside those agents yet. Reports welcome.
160
210
 
161
211
  Codex only runs project hooks after you trust the project. Teammates who have not installed `cto` are never blocked: the git hook checks for `cto` first, and Claude Code, Cursor and Gemini CLI document a failed hook command (other than exit 2) as non-blocking.
162
212
 
213
+ To cover them anyway, run the same check on every pull request. One job, using the reusable workflow in this repo:
214
+
215
+ ```yaml
216
+ name: cto
217
+ on: [pull_request]
218
+ permissions: { contents: read }
219
+ jobs:
220
+ cto:
221
+ uses: hierichhsu/your-cto-jev/.github/workflows/cto-check.yml@main
222
+ secrets:
223
+ OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}
224
+ ```
225
+
226
+ It runs `cto check --base origin/<base branch>` on what the branch adds since its merge base, and fails the job when a commit would have been blocked. Without a key it prints "could not check" and passes, the same fail-open as everywhere else.
227
+
163
228
  ## API keys
164
229
 
165
230
  You need at least one provider. `cto setup` lets you pick which ones to use and in what order:
@@ -185,12 +250,14 @@ Every check sends text to your chosen provider. `cto` masks it first:
185
250
 
186
251
  - **For commits:** the staged diff, with lock files, minified files, source maps and binaries removed.
187
252
  - **For agent commands:** the command, plus up to five failures from the last 15 minutes when checking for loops.
188
- - **When Claude Code ends a turn that edited code:** the agent's final message and a log of that turn: names of edited files, the shell commands it ran, whether each succeeded, and the last 200 characters of each output.
253
+ - **When an agent ends a turn that edited code:** the agent's final message and a log of that turn: names of edited files, the shell commands it ran, whether each succeeded, and the end of each output (Claude Code) or of each failure (other agents).
189
254
  - **For `cto check`:** the same as a commit; when nothing is staged, all working-tree changes, including the full content of new files git does not track yet.
190
255
  - **Always masked:** private key blocks, Stripe, OpenAI, AWS, GitHub and npm tokens, and any `NAME=value` whose name ends in `PASSWORD`, `SECRET`, `TOKEN` or `KEY`. Every value in a `.env` file is masked as well.
191
256
 
192
257
  Masking only controls what goes out. Jev still sees labels such as `[REDACTED: STRIPE_KEY]`, which is how it knows a real secret was there.
193
258
 
259
+ `.cto-lessons.jsonl` is written locally from the same masked text and never sent anywhere by cto; it leaves your machine only if you commit it.
260
+
194
261
  Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. That writes the masked input to `debug_stdin.json`, which `setup` adds to `.gitignore`.
195
262
 
196
263
  ## Configuration
@@ -209,10 +276,13 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
209
276
  Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6, `test_tampering` 0.8, `done_unverified` 0.6, `architecture_violation` 0.85, `code_complexity` 2.
210
277
 
211
278
  - **`sprint_goal`**: fill it in to enable the architecture check, for example `"Ship Stripe billing, no new services"`.
279
+ - **`test_command`**: what `cto brief` tells the agent to verify with, for example `"pnpm test"`. Detected from the project when empty.
280
+ - **`protected_branches`**: for example `["main", "release"]`. Commits on them and pushes that delete or rewrite them are blocked locally, no key needed. Empty by default.
212
281
  - **Thresholds**: Jev returns a probability from 0 to 1. `code_complexity` is the exception: it is a score from 0 (clean) to 4 (unmaintainable).
213
282
  - **Calibration**: on 32 hand-written diffs, every one scoring above 0.8 for `test_tampering` really weakened the tests, and no legitimate change scored above 0.37. The 0.8 default caught 13 of 16 weakening diffs; the misses were subtle ones such as a meaningless float tolerance or a skip hidden behind an env var. Lower it to 0.5 to catch 15 of 16, at a higher risk of blocking honest commits.
214
283
  - `done_unverified` (0.6) and `infinite_loop` (0.6) were calibrated the same way; the measurements are in the design spec.
215
- - In the same way, `git push --force` scored about 0.50 for `destructive_command`, so the default lets it through. Lower that threshold to about 0.45 if you want force pushes blocked.
284
+ - **When a call is wrong**: `cto log` lists the last 30 answered questions in this repo with their scores and thresholds. `cto report` (or `cto report <n>`) records that the last (or n-th) one was wrong and writes it, with the exact masked state Jev saw, as a calibration case to `reports/<signal>.jsonl` next to your credentials file. Nothing is sent anywhere; paste the line into `calibration/candidates/` in a PR or an issue and it joins the next measurement. That is how the thresholds get better from real use instead of hand-written diffs.
285
+ - For `destructive_command`, the current question scores `git push --force` about 0.74 (blocked by default), `find -delete` about 0.65 and `git reset --hard` about 0.47 (both let through), and `rm -rf node_modules` about 0.12. Lower the threshold to about 0.45 to block all three; the calibration set is still small, so the default stays at 0.7.
216
286
 
217
287
  `.cto-brain.json` holds personal runtime state and is gitignored.
218
288
 
@@ -227,14 +297,15 @@ Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6,
227
297
  ## Known limitations
228
298
 
229
299
  - **Git GUIs hide warnings.** VS Code, SourceTree and GitKraken usually hide hook output when the commit succeeds, so the architecture and complexity warnings are invisible there. Blocks still show.
230
- - **The done check only sees edits made with the agent's edit tools.** A file changed through a shell command (for example `sed`) does not count as an edit, so that turn is not checked. It also misses a test run that targets the wrong package. It runs in Claude Code only for now.
300
+ - **The done check sees edits from edit tools and from common shell commands** (`sed -i`, redirects, `tee`, formatters), but not writes hidden inside scripts such as `node -e`. It also misses a test run that targets the wrong package. Claude Code's turn comes from its transcript; for Cursor, Gemini CLI and Codex, whose transcript formats are not public, cto keeps its own log of commands and edits, and a command counts as successful unless a failure event arrives.
301
+ - **A lesson's fix is the edit between a failure and the next pass of a command with the same first two words.** A fix that was verified by a different command (`npm test` fails, `npx vitest run` passes) is not recorded, and a turn that edits files for other reasons in between credits them to the fix as well.
231
302
  - **Loop detection knows about edits, but only through the agent's edit tools.** A first re-run after a code edit is a new attempt, while the same error coming back across repeated fixes still counts as a loop; each loop is blocked once, so the agent can still verify its next fix. A file changed only through a shell command is not seen as an edit, and failures expire after 15 minutes.
232
303
  - **Each agent shell command waits for one Jev request.** OpenRouter answered in about 0.3 s in our tests, Cloudflare in about 0.9 s with occasional spikes past 3 s. Agent checks wait up to 5 s before failing open.
233
304
 
234
305
  ## Development
235
306
 
236
307
  ```sh
237
- git clone https://github.com/rainday/your-cto-jev
308
+ git clone https://github.com/hierichhsu/your-cto-jev
238
309
  cd your-cto-jev
239
310
  npm install
240
311
  npm test
@@ -247,6 +318,16 @@ npm version patch # or minor / major: bumps package.json, commits, tags
247
318
  git push --follow-tags # the tag triggers .github/workflows/publish.yml
248
319
  ```
249
320
 
321
+ To re-measure the checks after changing a question, after a Jev model update, or after adding cases:
322
+
323
+ ```sh
324
+ npm run calibrate # every signal, against the cases in calibration/
325
+ npm run calibrate -- --signal test_tampering
326
+ node scripts/harvest-commands.mjs --rows 300 # real agent commands from a public dataset, to label
327
+ ```
328
+
329
+ `calibrate` uses exactly the questions and state builders that ship, prints every case's score, and reports how many cases the current threshold catches and wrongly blocks. Harvested candidates in `calibration/candidates/` (from nebius/SWE-rebench-openhands-trajectories, CC-BY-4.0) join the measurement once someone sets their `expect` label.
330
+
250
331
  The full design, including the measured results behind the defaults, is in [`your-cto-jev-spec.html`](./your-cto-jev-spec.html) (written in 繁體中文).
251
332
 
252
333
  ## License
package/dist/agents.js CHANGED
@@ -1,11 +1,15 @@
1
1
  // One row per coding agent. The verdict logic is shared; each row only maps the agent's
2
2
  // stdin shape, its blocking convention, and where setup writes its hook config.
3
+ export const PHASES = ['pre', 'post', 'stop', 'edit', 'reply', 'start'];
3
4
  const str = (v) => (typeof v === 'string' && v.trim() ? v : undefined);
4
5
  const cmdOf = (i) => String(i?.tool_input?.command ?? i?.command ?? '');
5
6
  // Claude, Codex and Gemini share this convention: exit 2 + stderr blocks, exit 0 hides stderr so notices go out as systemMessage.
7
+ // For their stop events exit 2 also means "keep working", with stderr as the reason fed back to the agent.
6
8
  const exit2Block = (lines) => ({ code: 2, stderr: lines });
7
9
  const systemMessage = (msgs) => ({ code: 0, stdout: JSON.stringify({ systemMessage: msgs.join('\n') }), stderr: [] });
8
10
  const nestedPre = (i) => ({ command: str(i?.tool_input?.command), sessionId: str(i?.session_id), cwd: str(i?.cwd) });
11
+ const sessionId = (i) => str(i?.session_id);
12
+ const cursorCwd = (i) => str(i?.cwd) ?? str(i?.workspace_roots?.[0]);
9
13
  /** Pull a non-zero exit out of free-form tool output ("Exit Code: 1", "exit_code": 2, ...). */
10
14
  function nonZeroExit(v) {
11
15
  if (v && typeof v === 'object') {
@@ -22,12 +26,14 @@ export const agents = {
22
26
  claude: {
23
27
  label: 'Claude Code',
24
28
  homeDir: '.claude',
29
+ transcriptTurns: true,
25
30
  settings: '.claude/settings.local.json',
26
31
  style: 'nested',
27
32
  pre: { event: 'PreToolUse', matcher: 'Bash' },
28
33
  post: { event: 'PostToolUseFailure', matcher: 'Bash' },
29
34
  stop: { event: 'Stop' },
30
35
  edit: { event: 'PostToolUse', matcher: 'Edit|Write|MultiEdit|NotebookEdit' },
36
+ start: { event: 'SessionStart' }, // stdout of a SessionStart hook is added to Claude's context
31
37
  parseEdit: (i) => { const p = str(i?.tool_input?.file_path) ?? str(i?.tool_input?.notebook_path); return p ? [p] : undefined; },
32
38
  parseStop: (i) => ({
33
39
  sessionId: str(i?.session_id),
@@ -37,8 +43,10 @@ export const agents = {
37
43
  stopHookActive: i?.stop_hook_active === true,
38
44
  }),
39
45
  parsePre: nestedPre,
40
- parsePost: (i) => (i?.is_interrupt || !str(i?.error) ? null : { command: cmdOf(i), error: i.error, cwd: str(i?.cwd) }),
46
+ parsePost: (i) => (i?.is_interrupt || !str(i?.error) ? null : { command: cmdOf(i), error: i.error, cwd: str(i?.cwd), sessionId: sessionId(i) }),
47
+ session: sessionId,
41
48
  block: exit2Block,
49
+ stopBlock: exit2Block,
42
50
  notice: systemMessage,
43
51
  },
44
52
  cursor: {
@@ -49,17 +57,31 @@ export const agents = {
49
57
  pre: { event: 'beforeShellExecution' },
50
58
  post: { event: 'postToolUseFailure' },
51
59
  edit: { event: 'afterFileEdit' },
60
+ // stop carries no message text, so the final reply is captured by afterAgentResponse.
61
+ stop: { event: 'stop' },
62
+ reply: { event: 'afterAgentResponse' },
52
63
  parseEdit: (i) => { const p = str(i?.file_path); return p ? [p] : undefined; },
53
- parsePre: (i) => ({ command: str(i?.command), sessionId: str(i?.conversation_id), cwd: str(i?.cwd) ?? str(i?.workspace_roots?.[0]) }),
64
+ parsePre: (i) => ({ command: str(i?.command), sessionId: str(i?.conversation_id), cwd: cursorCwd(i) }),
54
65
  parsePost: (i) => i?.tool_name !== 'Shell' || i?.is_interrupt || !str(i?.error_message)
55
66
  ? null
56
- : { command: cmdOf(i), error: i.error_message, cwd: str(i?.cwd) ?? str(i?.workspace_roots?.[0]) },
67
+ : { command: cmdOf(i), error: i.error_message, cwd: cursorCwd(i), sessionId: str(i?.conversation_id) },
68
+ parseStop: (i) => ({
69
+ sessionId: str(i?.conversation_id),
70
+ cwd: cursorCwd(i),
71
+ lastMessage: '',
72
+ // loop_count > 0: this stop follows our own follow-up; aborted/error stops are not "done" claims.
73
+ stopHookActive: Number(i?.loop_count ?? 0) > 0 || (i?.status !== undefined && i?.status !== 'completed'),
74
+ }),
75
+ parseReply: (i) => ({ sessionId: str(i?.conversation_id), cwd: cursorCwd(i), text: String(i?.text ?? '') }),
76
+ session: (i) => str(i?.conversation_id),
57
77
  // Both documented block paths at once: exit 2 and permission "deny".
58
78
  block: (lines) => ({
59
79
  code: 2,
60
80
  stdout: JSON.stringify({ permission: 'deny', user_message: lines.join('\n'), agent_message: lines.join('\n') }),
61
81
  stderr: lines,
62
82
  }),
83
+ // A non-empty followup_message is submitted as the next user message, so the agent keeps working.
84
+ stopBlock: (lines) => ({ code: 0, stdout: JSON.stringify({ followup_message: lines.join('\n') }), stderr: [] }),
63
85
  notice: (msgs) => ({ code: 0, stdout: JSON.stringify({ permission: 'allow', user_message: msgs.join('\n') }), stderr: [] }),
64
86
  },
65
87
  gemini: {
@@ -70,6 +92,7 @@ export const agents = {
70
92
  pre: { event: 'BeforeTool', matcher: 'run_shell_command' },
71
93
  post: { event: 'AfterTool', matcher: 'run_shell_command' },
72
94
  edit: { event: 'AfterTool', matcher: 'write_file|replace' },
95
+ stop: { event: 'AfterAgent' },
73
96
  parseEdit: (i) => { const p = str(i?.tool_input?.file_path); return p ? [p] : undefined; },
74
97
  parsePre: nestedPre,
75
98
  parsePost: (i) => {
@@ -77,9 +100,12 @@ export const agents = {
77
100
  return null;
78
101
  const r = i?.tool_response;
79
102
  const err = str(r?.error) ?? str(r?.error?.message) ?? nonZeroExit(r?.llmContent);
80
- return err ? { command: cmdOf(i), error: err, cwd: str(i?.cwd) } : null;
103
+ return err ? { command: cmdOf(i), error: err, cwd: str(i?.cwd), sessionId: sessionId(i) } : null;
81
104
  },
105
+ parseStop: (i) => ({ sessionId: sessionId(i), cwd: str(i?.cwd), lastMessage: String(i?.prompt_response ?? ''), stopHookActive: i?.stop_hook_active === true }),
106
+ session: sessionId,
82
107
  block: exit2Block,
108
+ stopBlock: exit2Block, // AfterAgent: exit 2 retries with stderr as the new prompt
83
109
  notice: systemMessage,
84
110
  },
85
111
  codex: {
@@ -92,6 +118,7 @@ export const agents = {
92
118
  post: { event: 'PostToolUse', matcher: 'Bash' },
93
119
  // Codex edits through apply_patch; the patch text names each file ("*** Update File: src/a.ts").
94
120
  edit: { event: 'PostToolUse', matcher: 'apply_patch' },
121
+ stop: { event: 'Stop' },
95
122
  parseEdit: (i) => {
96
123
  const files = [...String(i?.tool_input?.command ?? '').matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => m[1].trim());
97
124
  return files.length ? files : undefined;
@@ -100,9 +127,12 @@ export const agents = {
100
127
  parsePre: nestedPre,
101
128
  parsePost: (i) => {
102
129
  const err = nonZeroExit(i?.tool_response);
103
- return err ? { command: cmdOf(i), error: err, cwd: str(i?.cwd) } : null;
130
+ return err ? { command: cmdOf(i), error: err, cwd: str(i?.cwd), sessionId: sessionId(i) } : null;
104
131
  },
132
+ parseStop: (i) => ({ sessionId: sessionId(i), cwd: str(i?.cwd), lastMessage: String(i?.last_assistant_message ?? ''), stopHookActive: i?.stop_hook_active === true }),
133
+ session: sessionId,
105
134
  block: exit2Block,
135
+ stopBlock: exit2Block,
106
136
  notice: systemMessage,
107
137
  },
108
138
  };
package/dist/brain.js CHANGED
@@ -1,8 +1,12 @@
1
1
  import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, join } from 'node:path';
4
+ export const DECISIONS_KEPT = 30;
5
+ export const DECISION_STATE_CHARS = 12_000;
4
6
  export const DEFAULT_CONFIG = {
5
7
  sprint_goal: '',
8
+ test_command: '',
9
+ protected_branches: [],
6
10
  thresholds: {
7
11
  credential_leak: 0.5,
8
12
  destructive_command: 0.7,
@@ -45,6 +49,8 @@ export function loadConfig(root) {
45
49
  const raw = readJson(join(root, '.cto.json')) ?? {};
46
50
  return {
47
51
  sprint_goal: typeof raw.sprint_goal === 'string' ? raw.sprint_goal : '',
52
+ test_command: typeof raw.test_command === 'string' ? raw.test_command : '',
53
+ protected_branches: Array.isArray(raw.protected_branches) ? raw.protected_branches.filter((b) => typeof b === 'string') : [],
48
54
  thresholds: { ...DEFAULT_CONFIG.thresholds, ...(raw.thresholds ?? {}) },
49
55
  };
50
56
  }
package/dist/brief.js ADDED
@@ -0,0 +1,108 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { freshErrors, loadBrain, loadConfig } from './brain.js';
5
+ import { loadLessons, packageManager, rankLessons } from './lessons.js';
6
+ import { BOX } from './turn.js';
7
+ // `cto brief`: what an agent should know before it starts working in this repo. Read by agents (Claude Code gets it
8
+ // at SessionStart), so it is English only and fits on one screen.
9
+ const git = (cwd, ...args) => {
10
+ try {
11
+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
12
+ }
13
+ catch {
14
+ return '';
15
+ }
16
+ };
17
+ /** The command that verifies this repo, from .cto.json or the project files. Empty when unknown. */
18
+ export function detectTestCommand(root) {
19
+ try {
20
+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
21
+ const script = pkg?.scripts?.test;
22
+ if (typeof script === 'string' && !/no test specified/.test(script))
23
+ return `${packageManager(root)} test`;
24
+ }
25
+ catch { /* not a node project */ }
26
+ const has = (f) => existsSync(join(root, f));
27
+ if (has('Makefile') && /^test:/m.test(readFileSync(join(root, 'Makefile'), 'utf8')))
28
+ return 'make test';
29
+ if (has('pytest.ini') || has('conftest.py') || (has('pyproject.toml') && /pytest/.test(readFileSync(join(root, 'pyproject.toml'), 'utf8'))))
30
+ return 'pytest';
31
+ if (has('Cargo.toml'))
32
+ return 'cargo test';
33
+ if (has('go.mod'))
34
+ return 'go test ./...';
35
+ return '';
36
+ }
37
+ /** Unchecked "- [ ]" items in tracked markdown files, by file. */
38
+ export function openPlanItems(root) {
39
+ const files = git(root, 'ls-files', '-z', '--', '*.md', '*.mdx').split('\0').filter(Boolean);
40
+ const out = [];
41
+ for (const file of files) {
42
+ let text = '';
43
+ try {
44
+ text = readFileSync(join(root, file), 'utf8');
45
+ }
46
+ catch {
47
+ continue;
48
+ }
49
+ if (text.length > 200_000)
50
+ continue;
51
+ // Boxes inside ``` fences are examples (a README showing a plan), not plan items.
52
+ let fenced = false;
53
+ const items = text.split(/\r?\n/).flatMap((l) => {
54
+ if (/^\s*(```|~~~)/.test(l)) {
55
+ fenced = !fenced;
56
+ return [];
57
+ }
58
+ const m = fenced ? null : BOX.exec(l);
59
+ return m && m[2] === ' ' ? [m[3].trim()] : [];
60
+ });
61
+ if (items.length)
62
+ out.push({ file, items });
63
+ }
64
+ return out;
65
+ }
66
+ const ago = (iso, now) => {
67
+ const mins = Math.max(0, Math.round((now - Date.parse(iso)) / 60_000));
68
+ return mins < 60 ? `${mins}m ago` : mins < 1440 ? `${Math.round(mins / 60)}h ago` : `${Math.round(mins / 1440)}d ago`;
69
+ };
70
+ export function lessonLines(l, now) {
71
+ const mark = !l.fix ? '!!' : l.seen > 1 ? '! ' : '- ';
72
+ const how = l.fix ? `fixed by editing ${l.fix.files.join(', ')} · verified by ${l.fix.verified_by}` : 'UNRESOLVED';
73
+ return [
74
+ ` ${mark} ${l.command.padEnd(16).slice(0, 16)} ${l.error[0] ?? ''}`,
75
+ ` seen ${l.seen}x · last ${ago(l.last_at, now)} · ${how}${l.note ? ` · note: ${l.note}` : ''}`,
76
+ ];
77
+ }
78
+ export function brief(root, now = Date.now()) {
79
+ const cfg = loadConfig(root);
80
+ const brain = loadBrain(root);
81
+ const name = root.replace(/[\\/]+$/, '').split(/[\\/]/).pop();
82
+ const branch = git(root, 'rev-parse', '--abbrev-ref', 'HEAD');
83
+ const dirty = git(root, 'status', '--porcelain').split('\n').filter(Boolean).length;
84
+ const L = [`[cto] brief · ${name}${branch ? ` · ${branch}` : ''} · ${dirty} files uncommitted`, ''];
85
+ L.push(`Sprint goal ${cfg.sprint_goal.trim() || '(none set in .cto.json)'}`);
86
+ const test = cfg.test_command.trim() || detectTestCommand(root);
87
+ L.push(`Verify with ${test || '(unknown: set test_command in .cto.json)'}${test && !cfg.test_command.trim() ? ' (detected; pin it as test_command in .cto.json)' : ''}`);
88
+ const plans = openPlanItems(root);
89
+ if (plans.length) {
90
+ const total = plans.reduce((n, p) => n + p.items.length, 0);
91
+ L.push('', `Open plan items · ${plans.map((p) => `${p.file} ${p.items.length}`).join(' · ')} · ${total} unchecked`);
92
+ for (const it of plans.flatMap((p) => p.items).slice(0, 5))
93
+ L.push(` - [ ] ${it.slice(0, 100)}`);
94
+ if (total > 5)
95
+ L.push(` … ${total - 5} more`);
96
+ }
97
+ const lessons = rankLessons(loadLessons(root));
98
+ if (lessons.length) {
99
+ L.push('', `Lessons from this repo · ${Math.min(5, lessons.length)} of ${lessons.length} · unresolved and frequent first`);
100
+ for (const l of lessons.slice(0, 5))
101
+ L.push(...lessonLines(l, now));
102
+ }
103
+ const recent = freshErrors(brain, now);
104
+ L.push('', `Failures in the last 15 min ${recent.length ? recent.map((e) => e.command.slice(0, 60)).join('; ') : 'none'}`);
105
+ L.push('Guards secrets · test tampering · destructive commands · loops · unverified done');
106
+ L.push(' Run cto check before committing. Same error twice: change approach.');
107
+ return L;
108
+ }
package/dist/check.js CHANGED
@@ -1,14 +1,18 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { loadBrain, loadConfig, saveBrain } from './brain.js';
3
- import { BLOCKING_COMMIT, DIFF_ARGS, WARNING_COMMIT, reviewDiff } from './hooks.js';
3
+ import { BLOCKING_COMMIT, DIFF_ARGS, WARNING_COMMIT, localLines, reviewDiff } from './hooks.js';
4
4
  import { personaDict, t } from './i18n.js';
5
+ import { localCommitChecks } from './local.js';
5
6
  const PINNED = DIFF_ARGS.filter((a) => a !== 'diff' && a !== '--cached');
6
7
  const git = (cwd, args) => execFileSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
7
8
  /**
8
9
  * What a commit would contain: the staged changes if anything is staged, otherwise every working-tree change,
9
10
  * including new files git does not track yet (agents create those often). Read-only: the index is never touched.
10
11
  */
11
- export function pendingDiff(root) {
12
+ export function pendingDiff(root, base) {
13
+ // CI: everything the branch adds on top of base (three-dot: since the merge base), nothing else.
14
+ if (base)
15
+ return { diff: git(root, ['diff', `${base}...HEAD`, ...PINNED]), source: 'base' };
12
16
  const staged = git(root, DIFF_ARGS);
13
17
  if (staged.trim())
14
18
  return { diff: staged, source: 'staged' };
@@ -25,21 +29,23 @@ export function pendingDiff(root) {
25
29
  return { diff, source: 'working' };
26
30
  }
27
31
  /** `cto check`: the commit checks, run now, with every score shown. Exit 1 when a commit would be blocked. */
28
- export async function runCheck(root, lang) {
32
+ export async function runCheck(root, lang, base) {
29
33
  const cfg = loadConfig(root);
30
34
  const brain = loadBrain(root);
31
- const { diff, source } = pendingDiff(root);
32
- const review = await reviewDiff(diff, cfg, brain, lang);
33
- saveBrain(root, brain); // provider cooldowns only; check runs are not counted as blocks
35
+ const { diff, source } = pendingDiff(root, base);
36
+ const local = localCommitChecks(diff, cfg, root);
37
+ const review = await reviewDiff(diff, cfg, brain, lang, undefined, 'check');
38
+ saveBrain(root, brain); // provider cooldowns and the decision log; check runs are not counted as blocks
34
39
  if (!review)
35
40
  return { code: 0, lines: [t(lang, 'check_nothing')] };
36
- const lines = [t(lang, source === 'staged' ? 'check_head_staged' : 'check_head_working', { files: review.files }), ...review.notices];
41
+ const head = source === 'staged' ? 'check_head_staged' : source === 'working' ? 'check_head_working' : 'check_head_base';
42
+ const lines = [t(lang, head, { files: review.files, base: base ?? '' }), ...review.notices];
43
+ let code = local.some((f) => f.block) ? 1 : 0;
44
+ const verdicts = localLines(lang, local);
37
45
  if (!Object.keys(review.scores).length) {
38
- lines.push(t(lang, 'check_unchecked'));
39
- return { code: 0, lines };
46
+ lines.push(t(lang, 'check_unchecked'), ...verdicts);
47
+ return { code, lines };
40
48
  }
41
- let code = 0;
42
- const verdicts = [];
43
49
  const width = Math.max(...[...BLOCKING_COMMIT, ...WARNING_COMMIT].map((s) => s.length));
44
50
  for (const s of [...BLOCKING_COMMIT, ...WARNING_COMMIT]) {
45
51
  const blocking = BLOCKING_COMMIT.includes(s);
@@ -0,0 +1,93 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join, relative } from 'node:path';
4
+ import { PHASES, agents } from './agents.js';
5
+ import { SKILL_MARK } from './skill.js';
6
+ const OTHER_SETTINGS = { claude: '.claude/settings.json', cursor: '', gemini: '', codex: '' };
7
+ const USER_SETTINGS = { claude: '.claude/settings.json', cursor: '', gemini: '.gemini/settings.json', codex: '.codex/hooks.json' };
8
+ /** Hook commands other than cto's on the same events, per file. The order is the order they run in. */
9
+ function hooksOn(file, name) {
10
+ let json;
11
+ try {
12
+ json = JSON.parse(readFileSync(file, 'utf8'));
13
+ }
14
+ catch {
15
+ return [];
16
+ }
17
+ const a = agents[name];
18
+ const out = [];
19
+ for (const phase of PHASES) {
20
+ const spec = a[phase];
21
+ const arr = spec && json?.hooks?.[spec.event];
22
+ if (!spec || !Array.isArray(arr))
23
+ continue;
24
+ const commands = arr.flatMap((m) => (a.style === 'cursor' ? [m?.command] : (m?.hooks ?? []).map((h) => h?.command)))
25
+ .filter((c) => typeof c === 'string' && !c.startsWith('cto --hook '));
26
+ if (commands.length)
27
+ out.push({ event: spec.event, commands });
28
+ }
29
+ return out;
30
+ }
31
+ const mdBlockRe = /<!-- >>> YOUR CTO JEV START >>> -->[\s\S]*?<!-- <<< YOUR CTO JEV END <<< -->/g;
32
+ // Instructions that would undo a cto rule. A line that forbids the thing ("never --no-verify") is not a conflict.
33
+ const AGAINST = /--no-verify|skip(?:ping)? (?:the )?tests?|commit(?:s)? (?:directly |straight )?(?:to|on) (?:main|master)|force[- ]push|push -f\b|disable (?:the )?hooks?|\bit\.skip\b/i;
34
+ // "no" alone is not here: "--no-verify" and "no PRs" would hide the very lines this looks for.
35
+ const NEGATED = /\b(?:never|not|don'?t|avoid|forbidden|forbid)\b|禁止|不要|不准|嚴禁|不可|別/i;
36
+ function guidanceFiles(root, home) {
37
+ const files = [join(home, '.claude', 'CLAUDE.md'), ...['CLAUDE.md', 'AGENTS.md', 'GEMINI.md'].map((f) => join(root, f))];
38
+ const skillDirs = [join(home, '.claude', 'skills'), join(root, '.claude', 'skills'), join(root, '.agents', 'skills'), join(root, '.cursor', 'rules')];
39
+ for (const d of skillDirs) {
40
+ try {
41
+ for (const e of readdirSync(d, { withFileTypes: true })) {
42
+ if (e.isDirectory())
43
+ files.push(join(d, e.name, 'SKILL.md'));
44
+ else if (/\.mdc?$/.test(e.name))
45
+ files.push(join(d, e.name));
46
+ }
47
+ }
48
+ catch { /* no such dir */ }
49
+ }
50
+ return files.filter(existsSync);
51
+ }
52
+ function skillNames(dir) {
53
+ try {
54
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
55
+ }
56
+ catch {
57
+ return [];
58
+ }
59
+ }
60
+ export function findConflicts(root, wired, home = homedir()) {
61
+ const out = [];
62
+ const show = (p) => (p.startsWith(home) ? '~' + p.slice(home.length) : relative(root, p) || p).replace(/\\/g, '/');
63
+ for (const name of wired) {
64
+ const files = [join(root, agents[name].settings), OTHER_SETTINGS[name] && join(root, OTHER_SETTINGS[name]), USER_SETTINGS[name] && join(home, USER_SETTINGS[name])];
65
+ for (const f of files) {
66
+ if (!f || !existsSync(f))
67
+ continue;
68
+ const events = new Map(); // one line per command, listing its events
69
+ for (const h of hooksOn(f, name))
70
+ for (const c of h.commands)
71
+ events.set(c, [...(events.get(c) ?? []), h.event]);
72
+ for (const [c, ev] of events)
73
+ out.push({ kind: 'hook', where: show(f), detail: `${c} (${ev.join(', ')})` });
74
+ }
75
+ }
76
+ for (const f of guidanceFiles(root, home)) {
77
+ let text = readFileSync(f, 'utf8');
78
+ if (text.includes(SKILL_MARK))
79
+ continue; // cto's own skill
80
+ text = text.replace(mdBlockRe, '');
81
+ text.split(/\r?\n/).forEach((line, i) => {
82
+ if (AGAINST.test(line) && !NEGATED.test(line))
83
+ out.push({ kind: 'guidance', where: `${show(f)}:${i + 1}`, detail: line.trim().slice(0, 100) });
84
+ });
85
+ }
86
+ const global = skillNames(join(home, '.claude', 'skills'));
87
+ for (const d of ['.claude/skills', '.agents/skills']) {
88
+ for (const s of skillNames(join(root, d)))
89
+ if (global.includes(s))
90
+ out.push({ kind: 'dup_skill', where: s, detail: `~/.claude/skills and ${d}` });
91
+ }
92
+ return out;
93
+ }
package/dist/diff.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Large diff handling (spec section 6): filter noise, then chunk by file.
2
- const EXCLUDE = /(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$|\.min\.js$|\.map$/;
2
+ // .cto-lessons.jsonl changes on every agent failure; it is cto's own masked output, not something to review.
3
+ const EXCLUDE = /(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|\.cto-lessons\.jsonl)$|\.min\.js$|\.map$/;
3
4
  export const CHUNK_TOKENS = 24_000;
4
5
  /** ~1 token per CJK char, ~4 chars per token otherwise. */
5
6
  export function estimateTokens(s) {