your-cto-jev 0.7.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
@@ -44,6 +44,19 @@ Jev judges meaning and answers with probabilities, not prose. It costs about $0.
44
44
 
45
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
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
+
47
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.
48
61
 
49
62
  When nothing crosses a threshold, `cto` prints nothing at all.
@@ -106,6 +119,8 @@ cto doctor
106
119
 
107
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.
108
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
+
109
124
  Other forms:
110
125
 
111
126
  ```sh
@@ -113,7 +128,9 @@ cto setup --agents claude,cursor --yes # non-interactive (scripts, CI); only a
113
128
  cto setup --refresh # re-write hooks and rules for the agents already set up
114
129
  cto setup --uninstall # remove every cto hook, rules block and skill again
115
130
  cto doctor # is it actually working?
131
+ cto brief # what an agent should know before it starts here
116
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
117
134
  ```
118
135
 
119
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.
@@ -147,9 +164,40 @@ The rules also tell the agent to run `cto check` before committing, and never to
147
164
  [cto] Good to commit.
148
165
  ```
149
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
+
150
198
  ## Supported agents
151
199
 
152
- 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.
153
201
 
154
202
  | Agent | Config written | Command gate | Loop detection | Knows about edits | Done check |
155
203
  |---|---|---|---|---|---|
@@ -162,6 +210,21 @@ Claude Code is tested end to end inside the agent. The Cursor, Gemini CLI and Co
162
210
 
163
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.
164
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
+
165
228
  ## API keys
166
229
 
167
230
  You need at least one provider. `cto setup` lets you pick which ones to use and in what order:
@@ -193,6 +256,8 @@ Every check sends text to your chosen provider. `cto` masks it first:
193
256
 
194
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.
195
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
+
196
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`.
197
262
 
198
263
  ## Configuration
@@ -211,9 +276,12 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
211
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.
212
277
 
213
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.
214
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).
215
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.
216
283
  - `done_unverified` (0.6) and `infinite_loop` (0.6) were calibrated the same way; the measurements are in the design spec.
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.
217
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.
218
286
 
219
287
  `.cto-brain.json` holds personal runtime state and is gitignored.
@@ -230,13 +298,14 @@ Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6,
230
298
 
231
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.
232
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.
233
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.
234
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.
235
304
 
236
305
  ## Development
237
306
 
238
307
  ```sh
239
- git clone https://github.com/rainday/your-cto-jev
308
+ git clone https://github.com/hierichhsu/your-cto-jev
240
309
  cd your-cto-jev
241
310
  npm install
242
311
  npm test
package/dist/agents.js CHANGED
@@ -1,6 +1,6 @@
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'];
3
+ export const PHASES = ['pre', 'post', 'stop', 'edit', 'reply', 'start'];
4
4
  const str = (v) => (typeof v === 'string' && v.trim() ? v : undefined);
5
5
  const cmdOf = (i) => String(i?.tool_input?.command ?? i?.command ?? '');
6
6
  // Claude, Codex and Gemini share this convention: exit 2 + stderr blocks, exit 0 hides stderr so notices go out as systemMessage.
@@ -33,6 +33,7 @@ export const agents = {
33
33
  post: { event: 'PostToolUseFailure', matcher: 'Bash' },
34
34
  stop: { event: 'Stop' },
35
35
  edit: { event: 'PostToolUse', matcher: 'Edit|Write|MultiEdit|NotebookEdit' },
36
+ start: { event: 'SessionStart' }, // stdout of a SessionStart hook is added to Claude's context
36
37
  parseEdit: (i) => { const p = str(i?.tool_input?.file_path) ?? str(i?.tool_input?.notebook_path); return p ? [p] : undefined; },
37
38
  parseStop: (i) => ({
38
39
  sessionId: str(i?.session_id),
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) {
package/dist/doctor.js CHANGED
@@ -6,7 +6,7 @@ import { probeProvider, providerOrder, providers } from './api.js';
6
6
  import { loadBrain, loadConfig, loadCredentials } from './brain.js';
7
7
  import { AGENT_TIMEOUT_MS } from './hooks.js';
8
8
  import { t } from './i18n.js';
9
- import { ignoredByGit, missingHooks, wiredAgents } from './setup.js';
9
+ import { GIT_HOOKS, conflictLines, ignoredByGit, missingHooks, wiredAgents } from './setup.js';
10
10
  import { guidancePaths, staleGuidance } from './skill.js';
11
11
  import { checkUpdate, currentVersion } from './update.js';
12
12
  function hint(provider, status) {
@@ -82,13 +82,15 @@ export async function doctor(cwd, lang, slowMs = AGENT_TIMEOUT_MS) {
82
82
  else {
83
83
  L.push('', t(lang, 'doc_repo', { root }));
84
84
  const hooksDir = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-path', 'hooks'], { cwd: root, encoding: 'utf8' }).trim();
85
- const hookPath = join(hooksDir, 'pre-commit');
86
- const hook = existsSync(hookPath) ? readFileSync(hookPath, 'utf8') : '';
87
- if (hook.includes('YOUR CTO JEV START'))
88
- L.push(` OK ${t(lang, 'doc_hook_ok', { path: hookPath })}`);
89
- else {
90
- L.push(` !! ${t(lang, 'doc_hook_missing')}`);
91
- problems.push(t(lang, 'doc_hook_missing'));
85
+ for (const [name] of GIT_HOOKS) {
86
+ const hookPath = join(hooksDir, name);
87
+ const hook = existsSync(hookPath) ? readFileSync(hookPath, 'utf8') : '';
88
+ if (hook.includes('YOUR CTO JEV START'))
89
+ L.push(` OK ${t(lang, 'doc_hook_ok', { name, path: hookPath })}`);
90
+ else {
91
+ L.push(` !! ${t(lang, 'doc_hook_missing', { name })}`);
92
+ problems.push(t(lang, 'doc_hook_missing', { name }));
93
+ }
92
94
  }
93
95
  const wired = wiredAgents(root);
94
96
  L.push(` ${wired.length ? 'OK' : '--'} ${t(lang, 'doc_agents', { list: wired.map((n) => agents[n].label).join(', ') || t(lang, 'doc_none') })}`);
@@ -103,6 +105,7 @@ export async function doctor(cwd, lang, slowMs = AGENT_TIMEOUT_MS) {
103
105
  }
104
106
  const cfg = loadConfig(root);
105
107
  L.push(` -- ${t(lang, cfg.sprint_goal.trim() ? 'doc_goal_set' : 'doc_goal_empty')}`);
108
+ L.push(...conflictLines(root, wired, lang).map((l) => ` ${l}`));
106
109
  const brain = loadBrain(root);
107
110
  L.push(` -- ${t(lang, 'doc_stats', { blocked: brain.blocked_attempts, skipped: brain.skipped_attempts })}`);
108
111
  if (brain.last_check_at) {
package/dist/hooks.js CHANGED
@@ -6,10 +6,12 @@ import { checkUpdate, currentVersion } from './update.js';
6
6
  import { isCodeFile, tickedItems, tickedKey, turnActions, turnState } from './turn.js';
7
7
  import { shellWrites } from './shellwrites.js';
8
8
  import { evaluate, providerOrder, providers } from './api.js';
9
- import { freshErrors, loadBrain, loadConfig, saveBrain } from './brain.js';
9
+ import { DECISIONS_KEPT, DECISION_STATE_CHARS, freshErrors, loadBrain, loadConfig, saveBrain } from './brain.js';
10
10
  import { chunkDiff, filterDiff, pool } from './diff.js';
11
11
  import { personaDict, t } from './i18n.js';
12
12
  import { maskDiff, maskSensitiveState } from './masker.js';
13
+ import { loadLessons, recordFailure, resolveFromTurn, saveLessons } from './lessons.js';
14
+ import { localCommitChecks, localPushChecks } from './local.js';
13
15
  // Exported so the calibration script (scripts/calibrate.mjs) measures exactly the questions that ship.
14
16
  export const Q = {
15
17
  credential_leak: {
@@ -126,8 +128,18 @@ export function planDiff(cwd) {
126
128
  // Measured 2026-10-02: Cloudflare p50 0.9 s, p95 2.1 s, cold spikes to 3.2 s; OpenRouter p95 0.33 s.
127
129
  // A timeout means "let it through unchecked", so wait as long as the git side does rather than fail open.
128
130
  export const AGENT_TIMEOUT_MS = 5000;
129
- /** Run the commit checks on a diff. Shared by the git hook and `cto check`. Mutates brain only for provider state. */
130
- export async function reviewDiff(rawDiff, cfg, brain, lang, now) {
131
+ /** Remember every answered yes/no question (score questions have no right answer to report). Keeps the last 30. */
132
+ export function logDecision(brain, hook, state, answers, cfg, now) {
133
+ const at = new Date((now ?? Date.now)()).toISOString();
134
+ for (const [k, a] of Object.entries(answers)) {
135
+ if (a?.type !== 'noul' || !(k in cfg.thresholds))
136
+ continue;
137
+ const signal = k;
138
+ brain.decisions = [...(brain.decisions ?? []), { at, hook, signal, value: a.noul, threshold: cfg.thresholds[signal], state: state.slice(0, DECISION_STATE_CHARS) }].slice(-DECISIONS_KEPT);
139
+ }
140
+ }
141
+ /** Run the commit checks on a diff. Shared by the git hook and `cto check`. Mutates brain for provider state and the decision log. */
142
+ export async function reviewDiff(rawDiff, cfg, brain, lang, now, hook = 'commit') {
131
143
  const files = filterDiff(maskDiff(rawDiff));
132
144
  if (!files.length)
133
145
  return null;
@@ -150,6 +162,8 @@ export async function reviewDiff(rawDiff, cfg, brain, lang, now) {
150
162
  return evaluate({ state, questions }, ctx);
151
163
  });
152
164
  const scores = {};
165
+ results.forEach((r, i) => { if (r.ok)
166
+ logDecision(brain, hook, chunks[i], r.answers, cfg, now); });
153
167
  for (const r of results) {
154
168
  if (!r.ok)
155
169
  continue;
@@ -172,18 +186,26 @@ export async function reviewDiff(rawDiff, cfg, brain, lang, now) {
172
186
  export const BLOCKING_COMMIT = ['credential_leak', 'test_tampering'];
173
187
  export const WARNING_COMMIT = ['architecture_violation', 'code_complexity'];
174
188
  const over = (v, s, cfg) => v !== undefined && v > cfg.thresholds[s];
189
+ export const localLines = (lang, findings) => findings.map((f) => t(lang, `local_${f.kind}`, { detail: f.detail }));
175
190
  export async function gitCommit(rawDiff, { root, lang, now }) {
176
191
  const cfg = loadConfig(root);
177
192
  const brain = loadBrain(root);
178
193
  const out = { code: 0, stderr: [] };
194
+ // Local checks first: a commit they block never reaches Jev, and they work without any key.
195
+ const local = localCommitChecks(rawDiff, cfg, root);
196
+ if (local.some((f) => f.block)) {
197
+ brain.blocked_attempts++;
198
+ saveBrain(root, brain);
199
+ return { code: 1, stderr: localLines(lang, local.filter((f) => f.block)) };
200
+ }
179
201
  const review = await reviewDiff(rawDiff, cfg, brain, lang, now);
180
202
  if (!review)
181
- return out;
203
+ return { ...out, stderr: localLines(lang, local) };
182
204
  if (review.failed)
183
205
  brain.skipped_attempts++;
184
206
  if (Object.keys(review.scores).length)
185
207
  countCheck(brain, now);
186
- const lines = [];
208
+ const lines = localLines(lang, local);
187
209
  for (const s of BLOCKING_COMMIT) {
188
210
  if (!over(review.scores[s], s, cfg))
189
211
  continue;
@@ -199,6 +221,16 @@ export async function gitCommit(rawDiff, { root, lang, now }) {
199
221
  saveBrain(root, brain);
200
222
  return out;
201
223
  }
224
+ /** pre-push: protected branches cannot be deleted or force-pushed. Local only. */
225
+ export function gitPush(stdin, { root, lang }) {
226
+ const findings = localPushChecks(stdin, loadConfig(root), root);
227
+ if (!findings.length)
228
+ return { code: 0, stderr: [] };
229
+ const brain = loadBrain(root);
230
+ brain.blocked_attempts++;
231
+ saveBrain(root, brain);
232
+ return { code: 1, stderr: localLines(lang, findings) };
233
+ }
202
234
  /** Bookkeeping for `cto doctor`: how many checks Jev actually answered, and when the last one was. */
203
235
  export function countCheck(brain, now) {
204
236
  brain.checks = (brain.checks ?? 0) + 1;
@@ -251,8 +283,10 @@ export async function agentPre(agent, input, { root, lang, now }) {
251
283
  const r = await evaluate({ state, questions, ...(sessionId && { session_id: sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices, now });
252
284
  if (!r.ok)
253
285
  brain.skipped_attempts++;
254
- else
286
+ else {
255
287
  countCheck(brain, now);
288
+ logDecision(brain, 'command', state, r.answers, cfg, now);
289
+ }
256
290
  await sessionNotice(brain, sessionId, lang, r, notices);
257
291
  let out = { code: 0, stderr: [] };
258
292
  if (r.ok) {
@@ -289,9 +323,13 @@ export async function agentStop(agent, input, { root, lang, now }) {
289
323
  delete brain.turns[input.sessionId];
290
324
  saveBrain(root, brain);
291
325
  }
326
+ const actions = input.transcriptPath ? turnActions(input.transcriptPath, input.cwd) : logged?.actions ?? [];
327
+ // Lessons learn from every stop, including the one after our own block: that is when the fix usually lands.
328
+ const lessons = loadLessons(root);
329
+ if (resolveFromTurn(lessons, actions, root, new Date((now ?? Date.now)())).length)
330
+ saveLessons(root, lessons);
292
331
  if (input.stopHookActive)
293
332
  return out;
294
- const actions = input.transcriptPath ? turnActions(input.transcriptPath, input.cwd) : logged?.actions ?? [];
295
333
  const lastMessage = input.lastMessage || logged?.reply || '';
296
334
  // ponytail: ticks are attributed to the turn that ends after they appear, so a box the user ticked by hand between
297
335
  // turns is judged against the agent's turn. Rare; per-turn snapshots of plan files would fix it.
@@ -306,11 +344,13 @@ export async function agentStop(agent, input, { root, lang, now }) {
306
344
  if (!ticked.length && !actions.some((a) => a.kind === 'edit' && isCodeFile(a.file)))
307
345
  return out;
308
346
  const cfg = loadConfig(root);
309
- const r = await evaluate({ state: turnState(lastMessage, actions, ticked), questions: { done_unverified: Q.done_unverified }, ...(input.sessionId && { session_id: input.sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices: new Set(), now });
347
+ const state = turnState(lastMessage, actions, ticked);
348
+ const r = await evaluate({ state, questions: { done_unverified: Q.done_unverified }, ...(input.sessionId && { session_id: input.sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices: new Set(), now });
310
349
  if (!r.ok)
311
350
  brain.skipped_attempts++;
312
351
  else {
313
352
  countCheck(brain, now);
353
+ logDecision(brain, 'stop', state, r.answers, cfg, now);
314
354
  brain.judged_items = [...judged, ...ticked.map(tickedKey)].slice(-300);
315
355
  }
316
356
  const v = r.ok ? exceeded(r.answers, 'done_unverified', cfg) : undefined;
@@ -386,9 +426,12 @@ export function loopFact(command, recent) {
386
426
  return `Fact: this exact command failed ${same.length} time(s) recently; its latest error has now appeared ${streak} time(s) in a row; ` +
387
427
  (recent.at(-1).edited_after ? 'the agent has edited code since the most recent failure.' : 'the agent has not edited any code since the most recent failure.');
388
428
  }
389
- export function agentPost(input, { root }) {
429
+ export function agentPost(input, { root }, agent = 'unknown') {
390
430
  if (!input)
391
431
  return { code: 0, stderr: [] };
432
+ const lessons = loadLessons(root);
433
+ recordFailure(lessons, input.command, input.error, root, agent);
434
+ saveLessons(root, lessons);
392
435
  const brain = loadBrain(root);
393
436
  const turn = input.sessionId ? brain.turns?.[input.sessionId] : undefined;
394
437
  const run = turn?.actions.findLast((a) => a.kind === 'run' && a.command === maskSensitiveState(input.command));