your-cto-jev 0.4.2 → 0.5.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 +37 -11
- package/dist/agents.js +1 -0
- package/dist/api.js +3 -2
- package/dist/brain.js +1 -1
- package/dist/check.js +67 -0
- package/dist/doctor.js +15 -1
- package/dist/hooks.js +102 -36
- package/dist/i18n.js +52 -2
- package/dist/index.js +41 -7
- package/dist/setup.js +45 -12
- package/dist/skill.js +154 -0
- package/dist/turn.js +6 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -100,18 +100,48 @@ Then restart your agent session so it picks up the new hooks, and check that eve
|
|
|
100
100
|
cto doctor
|
|
101
101
|
```
|
|
102
102
|
|
|
103
|
-
`cto doctor` sends one real request per provider, shows where each key comes from, checks the hooks in the current repo, 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.
|
|
103
|
+
`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.
|
|
104
104
|
|
|
105
105
|
Other forms:
|
|
106
106
|
|
|
107
107
|
```sh
|
|
108
|
-
cto setup --agents claude,cursor --yes # non-interactive (scripts, CI)
|
|
108
|
+
cto setup --agents claude,cursor --yes # non-interactive (scripts, CI); only adds, never removes
|
|
109
109
|
cto setup --uninstall # remove every cto hook again
|
|
110
110
|
cto doctor # is it actually working?
|
|
111
|
+
cto check # preview the commit checks on your current changes
|
|
111
112
|
```
|
|
112
113
|
|
|
113
114
|
`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.
|
|
114
115
|
|
|
116
|
+
## The rules, written down for the agent
|
|
117
|
+
|
|
118
|
+
`cto setup` also writes the development rules of the repo for coding agents, where every rule names the check that enforces it. Agents read them before they work, so they get blocked less, and when they are blocked they know why and how to fix it.
|
|
119
|
+
|
|
120
|
+
The rules go where agents always look: a short marked block appended to `CLAUDE.md` (Claude Code), `AGENTS.md` (Codex, Cursor) and `GEMINI.md` (Gemini CLI), only for the agents you picked. Your own content in those files is left alone, and uninstall takes out exactly the block. The details, including what each check looks for and how to handle a block, live in one skill at `.agents/skills/cto/SKILL.md`; the rules block points every agent there.
|
|
121
|
+
|
|
122
|
+
| Rule | Enforced by |
|
|
123
|
+
|---|---|
|
|
124
|
+
| Secrets stay out of code | `credential_leak` blocks the commit |
|
|
125
|
+
| Fix the code, not the tests | `test_tampering` blocks the commit |
|
|
126
|
+
| Done means verified | `done_unverified` sends the agent back to work |
|
|
127
|
+
| Two strikes, change approach | `infinite_loop` blocks the retry once |
|
|
128
|
+
| Ask before anything irreversible | `destructive_command` blocks the command |
|
|
129
|
+
| Stay on the sprint goal | `architecture_violation` warns |
|
|
130
|
+
| Keep it simple | `code_complexity` warns |
|
|
131
|
+
|
|
132
|
+
The rules also tell the agent to run `cto check` before committing, and never to bypass a block with `--no-verify` or by editing thresholds. Commit these files so the whole team's agents follow the same rules. `cto update` refreshes them (and any new hooks) in the repo you run it from; `cto doctor` flags a repo whose rules or hooks are older than the installed version, and `cto setup --refresh` brings it up to date.
|
|
133
|
+
|
|
134
|
+
`cto check` runs the commit checks on your staged changes (or, if nothing is staged, on every working-tree change including new files) without committing, and prints each score next to its threshold:
|
|
135
|
+
|
|
136
|
+
```text
|
|
137
|
+
[cto] Nothing staged, checking the working tree instead (9 files, including new untracked files):
|
|
138
|
+
credential_leak 0.03 blocks above 0.5 ok
|
|
139
|
+
test_tampering 0.03 blocks above 0.8 ok
|
|
140
|
+
architecture_violation not checked: sprint_goal is empty in .cto.json
|
|
141
|
+
code_complexity 2.02 warns above 2 would warn
|
|
142
|
+
[cto] Good to commit.
|
|
143
|
+
```
|
|
144
|
+
|
|
115
145
|
## Supported agents
|
|
116
146
|
|
|
117
147
|
The git pre-commit check is always installed. It protects every agent and every human who commits from that repo.
|
|
@@ -160,23 +190,19 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
|
|
|
160
190
|
|
|
161
191
|
## Configuration
|
|
162
192
|
|
|
163
|
-
`.cto.json` is shared with the team, so commit it:
|
|
193
|
+
`.cto.json` is shared with the team, so commit it. `cto setup` creates it with no thresholds, so the package defaults apply and improve with each release; add only the ones you want to override:
|
|
164
194
|
|
|
165
195
|
```json
|
|
166
196
|
{
|
|
167
197
|
"sprint_goal": "",
|
|
168
198
|
"thresholds": {
|
|
169
|
-
"
|
|
170
|
-
"test_tampering": 0.8,
|
|
171
|
-
"done_unverified": 0.6,
|
|
172
|
-
"destructive_command": 0.7,
|
|
173
|
-
"infinite_loop": 0.85,
|
|
174
|
-
"architecture_violation": 0.85,
|
|
175
|
-
"code_complexity": 2
|
|
199
|
+
"destructive_command": 0.45
|
|
176
200
|
}
|
|
177
201
|
}
|
|
178
202
|
```
|
|
179
203
|
|
|
204
|
+
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.
|
|
205
|
+
|
|
180
206
|
- **`sprint_goal`**: fill it in to enable the architecture check, for example `"Ship Stripe billing, no new services"`.
|
|
181
207
|
- **Thresholds**: Jev returns a probability from 0 to 1. `code_complexity` is the exception: it is a score from 0 (clean) to 4 (unmaintainable).
|
|
182
208
|
- **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.
|
|
@@ -196,7 +222,7 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
|
|
|
196
222
|
|
|
197
223
|
- **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.
|
|
198
224
|
- **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.
|
|
199
|
-
- **A
|
|
225
|
+
- **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.
|
|
200
226
|
- **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.
|
|
201
227
|
|
|
202
228
|
## Development
|
package/dist/agents.js
CHANGED
|
@@ -27,6 +27,7 @@ export const agents = {
|
|
|
27
27
|
pre: { event: 'PreToolUse', matcher: 'Bash' },
|
|
28
28
|
post: { event: 'PostToolUseFailure', matcher: 'Bash' },
|
|
29
29
|
stop: { event: 'Stop' },
|
|
30
|
+
edit: { event: 'PostToolUse', matcher: 'Edit|Write|MultiEdit|NotebookEdit' },
|
|
30
31
|
parseStop: (i) => ({
|
|
31
32
|
sessionId: str(i?.session_id),
|
|
32
33
|
cwd: str(i?.cwd),
|
package/dist/api.js
CHANGED
|
@@ -35,12 +35,13 @@ export const providers = {
|
|
|
35
35
|
},
|
|
36
36
|
};
|
|
37
37
|
/**
|
|
38
|
-
* Providers to try, in order: CTO_PROVIDER > the order picked in setup (only those
|
|
38
|
+
* Providers to try, in order: CTO_PROVIDER > the order picked in setup (only those; an empty pick means none) > every
|
|
39
|
+
* provider with a key when nothing was ever picked.
|
|
39
40
|
* Keys of providers left out of the picked order stay stored, so re-enabling one later needs no re-entry.
|
|
40
41
|
*/
|
|
41
42
|
export function providerOrder() {
|
|
42
43
|
const picked = loadPrefs().provider_order;
|
|
43
|
-
const order = env.CTO_PROVIDER ? [env.CTO_PROVIDER] : picked
|
|
44
|
+
const order = env.CTO_PROVIDER ? [env.CTO_PROVIDER] : picked !== undefined ? picked : Object.keys(providers);
|
|
44
45
|
return order.filter((n) => providers[n]?.enabled());
|
|
45
46
|
}
|
|
46
47
|
async function callOnce(name, req, timeoutMs) {
|
package/dist/brain.js
CHANGED
package/dist/check.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { loadBrain, loadConfig, saveBrain } from './brain.js';
|
|
3
|
+
import { BLOCKING_COMMIT, DIFF_ARGS, WARNING_COMMIT, reviewDiff } from './hooks.js';
|
|
4
|
+
import { personaDict, t } from './i18n.js';
|
|
5
|
+
const PINNED = DIFF_ARGS.filter((a) => a !== 'diff' && a !== '--cached');
|
|
6
|
+
const git = (cwd, args) => execFileSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
7
|
+
/**
|
|
8
|
+
* What a commit would contain: the staged changes if anything is staged, otherwise every working-tree change,
|
|
9
|
+
* including new files git does not track yet (agents create those often). Read-only: the index is never touched.
|
|
10
|
+
*/
|
|
11
|
+
export function pendingDiff(root) {
|
|
12
|
+
const staged = git(root, DIFF_ARGS);
|
|
13
|
+
if (staged.trim())
|
|
14
|
+
return { diff: staged, source: 'staged' };
|
|
15
|
+
let diff = git(root, ['diff', ...PINNED]);
|
|
16
|
+
const untracked = git(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean);
|
|
17
|
+
for (const f of untracked) {
|
|
18
|
+
try {
|
|
19
|
+
diff += git(root, ['diff', '--no-index', ...PINNED, '--', '/dev/null', f]);
|
|
20
|
+
}
|
|
21
|
+
catch (e) {
|
|
22
|
+
diff += String(e?.stdout ?? ''); // --no-index exits 1 when the files differ, which is always here
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return { diff, source: 'working' };
|
|
26
|
+
}
|
|
27
|
+
/** `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) {
|
|
29
|
+
const cfg = loadConfig(root);
|
|
30
|
+
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
|
|
34
|
+
if (!review)
|
|
35
|
+
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];
|
|
37
|
+
if (!Object.keys(review.scores).length) {
|
|
38
|
+
lines.push(t(lang, 'check_unchecked'));
|
|
39
|
+
return { code: 0, lines };
|
|
40
|
+
}
|
|
41
|
+
let code = 0;
|
|
42
|
+
const verdicts = [];
|
|
43
|
+
const width = Math.max(...[...BLOCKING_COMMIT, ...WARNING_COMMIT].map((s) => s.length));
|
|
44
|
+
for (const s of [...BLOCKING_COMMIT, ...WARNING_COMMIT]) {
|
|
45
|
+
const blocking = BLOCKING_COMMIT.includes(s);
|
|
46
|
+
const v = review.scores[s];
|
|
47
|
+
const name = s.padEnd(width);
|
|
48
|
+
if (v === undefined) {
|
|
49
|
+
const why = s === 'test_tampering' ? 'check_why_tests' : s === 'architecture_violation' ? 'check_why_goal' : 'check_why_failed';
|
|
50
|
+
lines.push(` ${name} ${t(lang, why)}`);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const limit = cfg.thresholds[s];
|
|
54
|
+
const bad = v > limit;
|
|
55
|
+
const status = bad ? t(lang, blocking ? 'check_block' : 'check_warn') : 'ok';
|
|
56
|
+
lines.push(` ${name} ${String(v).padEnd(5)} ${t(lang, blocking ? 'check_limit_block' : 'check_limit_warn', { limit })} ${status}`);
|
|
57
|
+
if (bad) {
|
|
58
|
+
verdicts.push(`[cto] ${personaDict[lang][s]}`);
|
|
59
|
+
if (blocking)
|
|
60
|
+
code = 1;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (review.failed)
|
|
64
|
+
lines.push(t(lang, 'check_partial'));
|
|
65
|
+
lines.push(...verdicts, code ? t(lang, 'check_result_block') : t(lang, 'check_result_ok'));
|
|
66
|
+
return { code, lines };
|
|
67
|
+
}
|
package/dist/doctor.js
CHANGED
|
@@ -6,7 +6,8 @@ import { probeProvider, 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 { wiredAgents } from './setup.js';
|
|
9
|
+
import { missingHooks, wiredAgents } from './setup.js';
|
|
10
|
+
import { staleGuidance } from './skill.js';
|
|
10
11
|
import { checkUpdate, currentVersion } from './update.js';
|
|
11
12
|
function hint(provider, status) {
|
|
12
13
|
if (status === '401')
|
|
@@ -78,10 +79,23 @@ export async function doctor(cwd, lang) {
|
|
|
78
79
|
}
|
|
79
80
|
const wired = wiredAgents(root);
|
|
80
81
|
L.push(` ${wired.length ? 'OK' : '--'} ${t(lang, 'doc_agents', { list: wired.map((n) => agents[n].label).join(', ') || t(lang, 'doc_none') })}`);
|
|
82
|
+
const stale = [...missingHooks(root), ...staleGuidance(root, wired)];
|
|
83
|
+
if (stale.length) {
|
|
84
|
+
L.push(` !! ${t(lang, 'doc_stale', { list: stale.join(', ') })}`);
|
|
85
|
+
problems.push(t(lang, 'doc_stale', { list: stale.join(', ') }));
|
|
86
|
+
}
|
|
81
87
|
const cfg = loadConfig(root);
|
|
82
88
|
L.push(` -- ${t(lang, cfg.sprint_goal.trim() ? 'doc_goal_set' : 'doc_goal_empty')}`);
|
|
83
89
|
const brain = loadBrain(root);
|
|
84
90
|
L.push(` -- ${t(lang, 'doc_stats', { blocked: brain.blocked_attempts, skipped: brain.skipped_attempts })}`);
|
|
91
|
+
if (brain.last_check_at) {
|
|
92
|
+
const mins = Math.max(0, Math.round((Date.now() - Date.parse(brain.last_check_at)) / 60_000));
|
|
93
|
+
const ago = mins < 60 ? t(lang, 'ago_min', { n: mins }) : mins < 1440 ? t(lang, 'ago_hour', { n: Math.round(mins / 60) }) : t(lang, 'ago_day', { n: Math.round(mins / 1440) });
|
|
94
|
+
L.push(` OK ${t(lang, 'doc_last_check', { ago, n: brain.checks ?? 0 })}`);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
L.push(` -- ${t(lang, 'doc_never_checked')}`);
|
|
98
|
+
}
|
|
85
99
|
for (const [p, cd] of Object.entries(brain.provider_cooldown)) {
|
|
86
100
|
if (cd.until > Date.now())
|
|
87
101
|
L.push(` !! ${t(lang, 'doc_cooldown', { name: providers[p]?.label ?? p, status: cd.status, until: new Date(cd.until).toLocaleTimeString() })}`);
|
package/dist/hooks.js
CHANGED
|
@@ -26,13 +26,17 @@ const Q = {
|
|
|
26
26
|
'in a way that cannot be undone?',
|
|
27
27
|
criteria: { true: 'Irreversibly destroys data or history', false: 'Safe, read-only, or reversible' },
|
|
28
28
|
},
|
|
29
|
+
// Recalibrated 2026-10-05 with edit markers and the computed loop fact: loops >= 0.75 (including the same error
|
|
30
|
+
// returning across repeated edits), genuine new attempts <= 0.14. Without edit info, edit-loops scored 0.31-0.39.
|
|
29
31
|
infinite_loop: {
|
|
30
32
|
type: 'noul',
|
|
31
|
-
instructions: 'The state holds a command about to run and recently failed commands with their errors. ' +
|
|
32
|
-
'Is the agent stuck
|
|
33
|
+
instructions: 'The state holds a command about to run and recently failed commands with their errors, each marked when the agent edited code after it. ' +
|
|
34
|
+
'Is the agent stuck in a loop, so running this command will fail the same way again? ' +
|
|
35
|
+
'Stuck: re-running a command that just failed with no code edited since; or the same error has come back two or more times even though code was edited between attempts. ' +
|
|
36
|
+
'Not stuck: the first re-run after editing code; the error changed after the last edit; or a different command.',
|
|
33
37
|
criteria: {
|
|
34
|
-
true: '
|
|
35
|
-
false: 'A new
|
|
38
|
+
true: 'Retrying without changing anything, or the same error keeps returning across repeated fix attempts',
|
|
39
|
+
false: 'A genuinely new attempt: first retry after an edit, a changed error, or a different command',
|
|
36
40
|
},
|
|
37
41
|
},
|
|
38
42
|
test_tampering: {
|
|
@@ -102,60 +106,84 @@ export const stagedDiff = (cwd) => execFileSync('git', DIFF_ARGS, { cwd, encodin
|
|
|
102
106
|
// Measured 2026-10-02: Cloudflare p50 0.9 s, p95 2.1 s, cold spikes to 3.2 s; OpenRouter p95 0.33 s.
|
|
103
107
|
// A timeout means "let it through unchecked", so wait as long as the git side does rather than fail open.
|
|
104
108
|
export const AGENT_TIMEOUT_MS = 5000;
|
|
105
|
-
|
|
106
|
-
export async function
|
|
107
|
-
const cfg = loadConfig(root);
|
|
108
|
-
const brain = loadBrain(root);
|
|
109
|
-
const out = { code: 0, stderr: [] };
|
|
109
|
+
/** Run the commit checks on a diff. Shared by the git hook and `cto check`. Mutates brain only for provider state. */
|
|
110
|
+
export async function reviewDiff(rawDiff, cfg, brain, lang, now) {
|
|
110
111
|
const files = filterDiff(maskDiff(rawDiff));
|
|
111
112
|
if (!files.length)
|
|
112
|
-
return
|
|
113
|
+
return null;
|
|
113
114
|
const chunks = chunkDiff(files);
|
|
114
115
|
const soft = { code_complexity: Q.code_complexity };
|
|
115
116
|
if (cfg.sprint_goal.trim())
|
|
116
117
|
soft.architecture_violation = architectureQ(cfg.sprint_goal.trim());
|
|
117
118
|
const notices = new Set();
|
|
119
|
+
const asked = new Set();
|
|
118
120
|
const ctx = { brain, lang, timeoutMs: 5000, notices, now };
|
|
119
121
|
// Credential check on every chunk (no sampling); test check on chunks that touch tests; soft signals on the first chunk only. Max 3 in flight.
|
|
120
|
-
const results = await pool(chunks, 3, (state, i) =>
|
|
121
|
-
|
|
122
|
-
questions: {
|
|
122
|
+
const results = await pool(chunks, 3, (state, i) => {
|
|
123
|
+
const questions = {
|
|
123
124
|
credential_leak: Q.credential_leak,
|
|
124
125
|
...(touchesTests(state) && { test_tampering: Q.test_tampering }),
|
|
125
126
|
...(i === 0 && soft),
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
127
|
+
};
|
|
128
|
+
for (const k of Object.keys(questions))
|
|
129
|
+
asked.add(k);
|
|
130
|
+
return evaluate({ state, questions }, ctx);
|
|
131
|
+
});
|
|
132
|
+
const scores = {};
|
|
133
|
+
for (const r of results) {
|
|
134
|
+
if (!r.ok)
|
|
135
|
+
continue;
|
|
136
|
+
for (const [k, a] of Object.entries(r.answers)) {
|
|
137
|
+
const v = value(a);
|
|
138
|
+
if (v !== undefined && asked.has(k))
|
|
139
|
+
scores[k] = Math.max(scores[k] ?? -Infinity, v);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
// No session concept in git: while degraded (non-primary provider), say so on every run.
|
|
133
143
|
const primary = providerOrder()[0];
|
|
134
144
|
for (const r of results)
|
|
135
145
|
if (r.ok && r.provider !== primary)
|
|
136
146
|
notices.add(t(lang, 'using', { name: providers[r.provider].label }));
|
|
147
|
+
const noKeys = results.some((r) => !r.ok && r.reason === 'no_keys');
|
|
148
|
+
if (noKeys)
|
|
149
|
+
notices.add(t(lang, 'no_keys'));
|
|
150
|
+
return { files: files.length, scores, asked, failed: results.some((r) => !r.ok), noKeys, notices };
|
|
151
|
+
}
|
|
152
|
+
export const BLOCKING_COMMIT = ['credential_leak', 'test_tampering'];
|
|
153
|
+
export const WARNING_COMMIT = ['architecture_violation', 'code_complexity'];
|
|
154
|
+
const over = (v, s, cfg) => v !== undefined && v > cfg.thresholds[s];
|
|
155
|
+
export async function gitCommit(rawDiff, { root, lang, now }) {
|
|
156
|
+
const cfg = loadConfig(root);
|
|
157
|
+
const brain = loadBrain(root);
|
|
158
|
+
const out = { code: 0, stderr: [] };
|
|
159
|
+
const review = await reviewDiff(rawDiff, cfg, brain, lang, now);
|
|
160
|
+
if (!review)
|
|
161
|
+
return out;
|
|
162
|
+
if (review.failed)
|
|
163
|
+
brain.skipped_attempts++;
|
|
164
|
+
if (Object.keys(review.scores).length)
|
|
165
|
+
countCheck(brain, now);
|
|
137
166
|
const lines = [];
|
|
138
|
-
for (const s of
|
|
139
|
-
|
|
140
|
-
if (!hits.length)
|
|
167
|
+
for (const s of BLOCKING_COMMIT) {
|
|
168
|
+
if (!over(review.scores[s], s, cfg))
|
|
141
169
|
continue;
|
|
142
170
|
out.code = 1;
|
|
143
|
-
lines.push(...verdict(lang, s,
|
|
171
|
+
lines.push(...verdict(lang, s, review.scores[s], cfg, 'red'));
|
|
144
172
|
}
|
|
145
173
|
if (out.code)
|
|
146
174
|
brain.blocked_attempts++;
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
if (v !== undefined)
|
|
152
|
-
lines.push(...verdict(lang, s, v, cfg, 'yellow'));
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
out.stderr = [...notices, ...lines];
|
|
175
|
+
for (const s of WARNING_COMMIT)
|
|
176
|
+
if (over(review.scores[s], s, cfg))
|
|
177
|
+
lines.push(...verdict(lang, s, review.scores[s], cfg, 'yellow'));
|
|
178
|
+
out.stderr = [...review.notices, ...lines];
|
|
156
179
|
saveBrain(root, brain);
|
|
157
180
|
return out;
|
|
158
181
|
}
|
|
182
|
+
/** Bookkeeping for `cto doctor`: how many checks Jev actually answered, and when the last one was. */
|
|
183
|
+
export function countCheck(brain, now) {
|
|
184
|
+
brain.checks = (brain.checks ?? 0) + 1;
|
|
185
|
+
brain.last_check_at = new Date((now ?? Date.now)()).toISOString();
|
|
186
|
+
}
|
|
159
187
|
// ---------- pre (Bash / shell command gate, any agent) ----------
|
|
160
188
|
async function sessionNotice(brain, sessionId, lang, r, notices) {
|
|
161
189
|
if (!sessionId || brain.notified_sessions.includes(sessionId))
|
|
@@ -181,25 +209,34 @@ export async function agentPre(agent, input, { root, lang, now }) {
|
|
|
181
209
|
const questions = { destructive_command: Q.destructive_command };
|
|
182
210
|
let state = maskSensitiveState(command);
|
|
183
211
|
const recent = freshErrors(brain, (now ?? Date.now)());
|
|
184
|
-
|
|
212
|
+
// One block per loop episode: once warned about the latest failure, the next attempt may run (it may be the real fix).
|
|
213
|
+
// A new failure after that is unwarned again and can be blocked again.
|
|
214
|
+
if (recent.length && !recent.at(-1).warned) {
|
|
185
215
|
questions.infinite_loop = Q.infinite_loop;
|
|
186
216
|
state =
|
|
187
217
|
`Command about to run:\n${state}\n\nRecently failed commands (oldest first):\n` +
|
|
188
|
-
recent.map((e) => `$ ${e.command}\n${e.error}`).join('\n\n')
|
|
218
|
+
recent.map((e) => `$ ${e.command}\n${e.error}${e.edited_after ? '\n(the agent edited code after this failure)' : ''}`).join('\n\n') +
|
|
219
|
+
`\n\n${loopFact(maskSensitiveState(command), recent)}`;
|
|
189
220
|
}
|
|
190
221
|
const notices = new Set();
|
|
191
222
|
const { sessionId } = input;
|
|
192
223
|
const r = await evaluate({ state, questions, ...(sessionId && { session_id: sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices, now });
|
|
193
224
|
if (!r.ok)
|
|
194
225
|
brain.skipped_attempts++;
|
|
226
|
+
else
|
|
227
|
+
countCheck(brain, now);
|
|
195
228
|
await sessionNotice(brain, sessionId, lang, r, notices);
|
|
196
229
|
let out = { code: 0, stderr: [] };
|
|
197
230
|
if (r.ok) {
|
|
198
231
|
for (const s of ['destructive_command', 'infinite_loop']) {
|
|
199
|
-
const v = exceeded(r.answers, s, cfg);
|
|
232
|
+
const v = questions[s] ? exceeded(r.answers, s, cfg) : undefined; // only judge what was asked
|
|
200
233
|
if (v === undefined)
|
|
201
234
|
continue;
|
|
202
235
|
brain.blocked_attempts++;
|
|
236
|
+
if (s === 'infinite_loop') {
|
|
237
|
+
const last = recent.at(-1);
|
|
238
|
+
brain.recent_errors = brain.recent_errors.map((e) => (e.at === last.at && e.command === last.command ? { ...e, warned: true } : e));
|
|
239
|
+
}
|
|
203
240
|
out = agent.block([...verdict(lang, s, v, cfg, null), ...notices]);
|
|
204
241
|
break;
|
|
205
242
|
}
|
|
@@ -227,6 +264,8 @@ export async function agentStop(input, { root, lang, now }) {
|
|
|
227
264
|
const r = await evaluate({ state: turnState(input.lastMessage, actions), questions: { done_unverified: Q.done_unverified }, ...(input.sessionId && { session_id: input.sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices: new Set(), now });
|
|
228
265
|
if (!r.ok)
|
|
229
266
|
brain.skipped_attempts++;
|
|
267
|
+
else
|
|
268
|
+
countCheck(brain, now);
|
|
230
269
|
const v = r.ok ? exceeded(r.answers, 'done_unverified', cfg) : undefined;
|
|
231
270
|
if (v !== undefined) {
|
|
232
271
|
brain.blocked_attempts++;
|
|
@@ -238,6 +277,33 @@ export async function agentStop(input, { root, lang, now }) {
|
|
|
238
277
|
}
|
|
239
278
|
// ---------- post (failure recording) ----------
|
|
240
279
|
/** Record the failure only; never calls Jev. No error field, no record. */
|
|
280
|
+
/**
|
|
281
|
+
* After the agent edits a code file, mark the recorded failures as "edited after". They are kept, not erased: a single
|
|
282
|
+
* re-run after a fix is a new attempt, but the same error coming back across repeated fixes is still a loop, and only
|
|
283
|
+
* the history shows that. Local only: no Jev call, no network. Docs/YAML edits do not count.
|
|
284
|
+
*/
|
|
285
|
+
export function agentEdit(file, { root }) {
|
|
286
|
+
if (file && !isCodeFile(file))
|
|
287
|
+
return { code: 0, stderr: [] };
|
|
288
|
+
const brain = loadBrain(root);
|
|
289
|
+
if (brain.recent_errors.some((e) => !e.edited_after)) {
|
|
290
|
+
brain.recent_errors = brain.recent_errors.map((e) => ({ ...e, edited_after: true }));
|
|
291
|
+
saveBrain(root, brain);
|
|
292
|
+
}
|
|
293
|
+
return { code: 0, stderr: [] };
|
|
294
|
+
}
|
|
295
|
+
/** Facts code can count exactly, so Jev does not have to: repeats of this command, the error streak, edits since. */
|
|
296
|
+
export function loopFact(command, recent) {
|
|
297
|
+
const norm = (s) => s.trim().replace(/\s+/g, ' ');
|
|
298
|
+
const same = recent.filter((e) => norm(e.command) === norm(command));
|
|
299
|
+
if (!same.length)
|
|
300
|
+
return 'Fact: none of the recent failures were this exact command.';
|
|
301
|
+
let streak = 1;
|
|
302
|
+
for (let i = same.length - 2; i >= 0 && norm(same[i].error) === norm(same.at(-1).error); i--)
|
|
303
|
+
streak++;
|
|
304
|
+
return `Fact: this exact command failed ${same.length} time(s) recently; its latest error has now appeared ${streak} time(s) in a row; ` +
|
|
305
|
+
(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.');
|
|
306
|
+
}
|
|
241
307
|
export function agentPost(input, { root }) {
|
|
242
308
|
if (!input)
|
|
243
309
|
return { code: 0, stderr: [] };
|
package/dist/i18n.js
CHANGED
|
@@ -59,6 +59,7 @@ const messages = {
|
|
|
59
59
|
setup_gitignore: () => '[cto] .gitignore 已加入 .cto-brain.json 與 debug_stdin.json',
|
|
60
60
|
setup_config: () => '[cto] 已建立 .cto.json(請 commit 給團隊共用)',
|
|
61
61
|
setup_sprint: () => '[cto] 提示:在 .cto.json 填入 sprint_goal 以啟用架構對齊檢查。',
|
|
62
|
+
setup_goal_bad_json: () => '[cto] .cto.json 不是合法 JSON,sprint goal 沒有寫入,檔案保持原樣。請先修正該檔。',
|
|
62
63
|
setup_done: () => '[cto] 安裝完成。',
|
|
63
64
|
uninstall_hook: (v) => `[cto] 已從 ${v.path} 移除 cto 區塊`,
|
|
64
65
|
uninstall_gitignore: () => '[cto] 已從 .gitignore 移除 cto 區塊',
|
|
@@ -106,6 +107,30 @@ const messages = {
|
|
|
106
107
|
ui_unset: () => '未設定',
|
|
107
108
|
ui_saved: () => '設定完成。之後執行 cto setup 可以回到這個總覽,cto doctor 可以確認是否正常運作。',
|
|
108
109
|
ui_quit: () => '已離開,沒有修改任何設定。',
|
|
110
|
+
check_nothing: () => '[cto] 沒有可檢查的改動。',
|
|
111
|
+
check_head_staged: (v) => `[cto] 檢查 staged 的改動(${v.files} 個檔案),跟 commit 時的檢查相同:`,
|
|
112
|
+
check_head_working: (v) => `[cto] 沒有 staged 的改動,改為檢查工作目錄(${v.files} 個檔案,含尚未加入 git 的新檔):`,
|
|
113
|
+
check_unchecked: () => '[cto] 無法檢查:沒有可用的 Jev provider。執行 cto doctor 看原因。',
|
|
114
|
+
check_why_tests: () => '未檢查:沒有改到測試相關檔案',
|
|
115
|
+
check_why_goal: () => '未檢查:.cto.json 沒有設定 sprint_goal',
|
|
116
|
+
check_why_failed: () => '未檢查:請求失敗',
|
|
117
|
+
check_limit_block: (v) => `超過 ${v.limit} 會擋下`,
|
|
118
|
+
check_limit_warn: (v) => `超過 ${v.limit} 會警告`,
|
|
119
|
+
check_block: () => '會被擋下',
|
|
120
|
+
check_warn: () => '會警告',
|
|
121
|
+
check_partial: () => '[cto] 注意:部分內容因請求失敗沒有檢查到。',
|
|
122
|
+
check_result_ok: () => '[cto] 可以 commit。',
|
|
123
|
+
check_result_block: () => '[cto] 現在 commit 會被擋下,先修正上面標示的問題。',
|
|
124
|
+
setup_skill: (v) => `[cto] cto 開發規矩已寫入 ${v.path}`,
|
|
125
|
+
refresh_none: () => '[cto] 這個 repo 還沒設定 cto,請先執行 cto setup。',
|
|
126
|
+
refresh_after_update: () => '[cto] 正在用新版更新目前 repo 的 hook 與規矩…',
|
|
127
|
+
doc_stale: (v) => `這個 repo 的 cto 設定比目前版本舊(${v.list}),執行 cto setup --refresh`,
|
|
128
|
+
uninstall_skill: (v) => `[cto] 已移除 cto 開發規矩:${v.path}`,
|
|
129
|
+
doc_last_check: (v) => `最近一次檢查:${v.ago},累計 ${v.n} 次`,
|
|
130
|
+
doc_never_checked: () => '還沒有任何一次成功的檢查',
|
|
131
|
+
ago_min: (v) => `${v.n} 分鐘前`,
|
|
132
|
+
ago_hour: (v) => `${v.n} 小時前`,
|
|
133
|
+
ago_day: (v) => `${v.n} 天前`,
|
|
109
134
|
doc_version: (v) => `cto ${v.v}`,
|
|
110
135
|
doc_keys: () => 'Jev API key(每個都用一次真實請求驗證):',
|
|
111
136
|
doc_not_set: (v) => `未設定(缺 ${v.keys})`,
|
|
@@ -136,7 +161,7 @@ const messages = {
|
|
|
136
161
|
doc_bad: () => '[cto] 有問題需要處理:',
|
|
137
162
|
update_available: (v) => `[cto] 有新版 ${v.latest}(目前 ${v.current}),執行 cto update 更新`,
|
|
138
163
|
update_done: () => '[cto] 已更新。已設定過的專案不用重跑 cto setup。',
|
|
139
|
-
usage: () => '用法:cto doctor | cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
|
|
164
|
+
usage: () => '用法:cto check | cto doctor | cto update | cto --version | cto setup [--refresh] [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
|
|
140
165
|
},
|
|
141
166
|
en: {
|
|
142
167
|
reason_402: () => 'out of credits',
|
|
@@ -163,6 +188,7 @@ const messages = {
|
|
|
163
188
|
setup_gitignore: () => '[cto] Added .cto-brain.json and debug_stdin.json to .gitignore',
|
|
164
189
|
setup_config: () => '[cto] Created .cto.json (commit it for the team)',
|
|
165
190
|
setup_sprint: () => '[cto] Tip: set sprint_goal in .cto.json to enable the architecture alignment check.',
|
|
191
|
+
setup_goal_bad_json: () => '[cto] .cto.json is not valid JSON, so the sprint goal was not saved and the file was left untouched. Fix it first.',
|
|
166
192
|
setup_done: () => '[cto] Setup complete.',
|
|
167
193
|
uninstall_hook: (v) => `[cto] Removed the cto block from ${v.path}`,
|
|
168
194
|
uninstall_gitignore: () => '[cto] Removed the cto block from .gitignore',
|
|
@@ -210,6 +236,30 @@ const messages = {
|
|
|
210
236
|
ui_unset: () => 'not set',
|
|
211
237
|
ui_saved: () => 'Done. Run cto setup to come back to this overview, and cto doctor to check that it works.',
|
|
212
238
|
ui_quit: () => 'Left without changing anything.',
|
|
239
|
+
check_nothing: () => '[cto] Nothing to check.',
|
|
240
|
+
check_head_staged: (v) => `[cto] Checking staged changes (${v.files} files), same checks as a commit:`,
|
|
241
|
+
check_head_working: (v) => `[cto] Nothing staged, checking the working tree instead (${v.files} files, including new untracked files):`,
|
|
242
|
+
check_unchecked: () => '[cto] Could not check: no working Jev provider. Run cto doctor to see why.',
|
|
243
|
+
check_why_tests: () => 'not checked: no test files changed',
|
|
244
|
+
check_why_goal: () => 'not checked: sprint_goal is empty in .cto.json',
|
|
245
|
+
check_why_failed: () => 'not checked: request failed',
|
|
246
|
+
check_limit_block: (v) => `blocks above ${v.limit}`,
|
|
247
|
+
check_limit_warn: (v) => `warns above ${v.limit}`,
|
|
248
|
+
check_block: () => 'WOULD BLOCK',
|
|
249
|
+
check_warn: () => 'would warn',
|
|
250
|
+
check_partial: () => '[cto] Note: part of the change could not be checked (request failed).',
|
|
251
|
+
check_result_ok: () => '[cto] Good to commit.',
|
|
252
|
+
check_result_block: () => '[cto] A commit now would be blocked. Fix what is flagged above first.',
|
|
253
|
+
setup_skill: (v) => `[cto] cto rules written to ${v.path}`,
|
|
254
|
+
refresh_none: () => '[cto] cto is not set up in this repo yet. Run cto setup first.',
|
|
255
|
+
refresh_after_update: () => '[cto] Refreshing hooks and rules in this repo with the new version…',
|
|
256
|
+
doc_stale: (v) => `cto in this repo is older than this version (${v.list}). Run cto setup --refresh`,
|
|
257
|
+
uninstall_skill: (v) => `[cto] Removed cto rules: ${v.path}`,
|
|
258
|
+
doc_last_check: (v) => `Last check: ${v.ago}, ${v.n} in total`,
|
|
259
|
+
doc_never_checked: () => 'No successful check yet',
|
|
260
|
+
ago_min: (v) => `${v.n} min ago`,
|
|
261
|
+
ago_hour: (v) => `${v.n} h ago`,
|
|
262
|
+
ago_day: (v) => `${v.n} days ago`,
|
|
213
263
|
doc_version: (v) => `cto ${v.v}`,
|
|
214
264
|
doc_keys: () => 'Jev API keys (each verified with one real request):',
|
|
215
265
|
doc_not_set: (v) => `not set (missing ${v.keys})`,
|
|
@@ -240,7 +290,7 @@ const messages = {
|
|
|
240
290
|
doc_bad: () => '[cto] Needs attention:',
|
|
241
291
|
update_available: (v) => `[cto] Version ${v.latest} is available (you have ${v.current}). Run cto update`,
|
|
242
292
|
update_done: () => '[cto] Updated. Projects already set up do not need cto setup again.',
|
|
243
|
-
usage: () => 'Usage: cto doctor | cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
|
|
293
|
+
usage: () => 'Usage: cto check | cto doctor | cto update | cto --version | cto setup [--refresh] [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
|
|
244
294
|
},
|
|
245
295
|
};
|
|
246
296
|
export function t(lang, key, vars = {}) {
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
2
3
|
import { writeFileSync } from 'node:fs';
|
|
3
4
|
import { join } from 'node:path';
|
|
4
5
|
import { agentNames, agents } from './agents.js';
|
|
5
6
|
import { applyCredentials, findRoot, loadConfig, loadCredentials, loadPrefs, saveCredentials, savePrefs } from './brain.js';
|
|
6
7
|
import { providerOrder, providers } from './api.js';
|
|
7
|
-
import { agentPost, agentPre, agentStop, gitCommit, stagedDiff } from './hooks.js';
|
|
8
|
+
import { agentEdit, agentPost, agentPre, agentStop, gitCommit, stagedDiff } from './hooks.js';
|
|
8
9
|
import { checkUpdate, currentVersion, runUpdate } from './update.js';
|
|
9
10
|
import { doctor } from './doctor.js';
|
|
10
11
|
import { detectLang, t } from './i18n.js';
|
|
@@ -41,7 +42,7 @@ async function runHook(name) {
|
|
|
41
42
|
return gitCommit(diff, { root, lang });
|
|
42
43
|
}
|
|
43
44
|
const raw = await readStdin();
|
|
44
|
-
const m = /^(claude|cursor|gemini|codex)-(pre|post|stop)$/.exec(name);
|
|
45
|
+
const m = /^(claude|cursor|gemini|codex)-(pre|post|stop|edit)$/.exec(name);
|
|
45
46
|
if (!m)
|
|
46
47
|
return { code: 0, stderr: [] };
|
|
47
48
|
const agent = agents[m[1]];
|
|
@@ -50,6 +51,10 @@ async function runHook(name) {
|
|
|
50
51
|
input = JSON.parse(raw);
|
|
51
52
|
}
|
|
52
53
|
catch { /* fail-open below */ }
|
|
54
|
+
if (m[2] === 'edit') {
|
|
55
|
+
const file = input?.tool_input?.file_path ?? input?.tool_input?.notebook_path;
|
|
56
|
+
return agentEdit(typeof file === 'string' ? file : undefined, { root: findRoot(typeof input?.cwd === 'string' ? input.cwd : process.cwd()), lang });
|
|
57
|
+
}
|
|
53
58
|
if (m[2] === 'stop') {
|
|
54
59
|
if (!agent.parseStop)
|
|
55
60
|
return { code: 0, stderr: [] };
|
|
@@ -93,7 +98,15 @@ else if (args[0] === 'setup') {
|
|
|
93
98
|
let goal;
|
|
94
99
|
const root = gitRoot(process.cwd());
|
|
95
100
|
const list = flag('--agents');
|
|
96
|
-
if (
|
|
101
|
+
if (args.includes('--refresh')) {
|
|
102
|
+
// Re-write everything cto manages for the agents already wired here; choices stay as they are.
|
|
103
|
+
chosen = root ? wiredAgents(root) : [];
|
|
104
|
+
if (root && !chosen.length) {
|
|
105
|
+
console.log(t(lang, 'refresh_none'));
|
|
106
|
+
process.exit(0);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
else if (list)
|
|
97
110
|
chosen = list.split(',').map((s) => s.trim()).filter((s) => agentNames.includes(s));
|
|
98
111
|
else if (!uninstall && root && process.stdin.isTTY && process.stdout.isTTY && !args.includes('--yes')) {
|
|
99
112
|
// Interactive: start from what is actually set up now, so re-running setup edits instead of starting over.
|
|
@@ -120,9 +133,10 @@ else if (args[0] === 'setup') {
|
|
|
120
133
|
else if (!uninstall) {
|
|
121
134
|
chosen = detectAgents();
|
|
122
135
|
}
|
|
123
|
-
const r = setup(process.cwd(), lang, { uninstall, agents: chosen });
|
|
124
|
-
if (!r.code && root && goal !== undefined)
|
|
125
|
-
|
|
136
|
+
const r = setup(process.cwd(), lang, { uninstall, agents: chosen, exact: goal !== undefined });
|
|
137
|
+
if (!r.code && root && goal !== undefined && goal !== loadConfig(root).sprint_goal && !setSprintGoal(root, goal)) {
|
|
138
|
+
r.lines.push(t(lang, 'setup_goal_bad_json'));
|
|
139
|
+
}
|
|
126
140
|
const latest = r.code ? undefined : await checkUpdate();
|
|
127
141
|
if (latest)
|
|
128
142
|
r.lines.push(t(lang, 'update_available', { latest, current: currentVersion() }));
|
|
@@ -131,8 +145,28 @@ else if (args[0] === 'setup') {
|
|
|
131
145
|
}
|
|
132
146
|
else if (args[0] === 'update') {
|
|
133
147
|
process.exitCode = runUpdate();
|
|
134
|
-
if (!process.exitCode)
|
|
148
|
+
if (!process.exitCode) {
|
|
135
149
|
console.log(t(lang, 'update_done'));
|
|
150
|
+
// The new version refreshes this repo's managed hooks and rules, so changes reach it without re-running setup.
|
|
151
|
+
const root = gitRoot(process.cwd());
|
|
152
|
+
if (root && wiredAgents(root).length) {
|
|
153
|
+
console.log(t(lang, 'refresh_after_update'));
|
|
154
|
+
spawnSync('cto setup --refresh', { stdio: 'inherit', shell: true, cwd: root });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
else if (args[0] === 'check') {
|
|
159
|
+
const root = gitRoot(process.cwd());
|
|
160
|
+
if (!root) {
|
|
161
|
+
process.stderr.write(t(lang, 'setup_not_git') + '\n');
|
|
162
|
+
process.exitCode = 1;
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
const { runCheck } = await import('./check.js');
|
|
166
|
+
const r = await runCheck(root, lang);
|
|
167
|
+
console.log(r.lines.join('\n'));
|
|
168
|
+
process.exitCode = r.code;
|
|
169
|
+
}
|
|
136
170
|
}
|
|
137
171
|
else if (args[0] === 'doctor') {
|
|
138
172
|
const r = await doctor(process.cwd(), lang);
|
package/dist/setup.js
CHANGED
|
@@ -3,8 +3,8 @@ import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync,
|
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { basename, dirname, join, relative } from 'node:path';
|
|
5
5
|
import { agentNames, agents, hookCommand } from './agents.js';
|
|
6
|
-
import { DEFAULT_CONFIG } from './brain.js';
|
|
7
6
|
import { t } from './i18n.js';
|
|
7
|
+
import { syncGuidance } from './skill.js';
|
|
8
8
|
const START = '# >>> YOUR CTO JEV START >>>';
|
|
9
9
|
const END = '# <<< YOUR CTO JEV END <<<';
|
|
10
10
|
// Keep the block minimal: all logic (including the git diff call) lives in the package, so npm update upgrades every repo.
|
|
@@ -54,7 +54,7 @@ function validShape(json, name) {
|
|
|
54
54
|
if (!isObj(json.hooks))
|
|
55
55
|
return false;
|
|
56
56
|
const a = agents[name];
|
|
57
|
-
return [a.pre, a.post, a.stop].every((spec) => !spec || json.hooks[spec.event] === undefined || Array.isArray(json.hooks[spec.event]));
|
|
57
|
+
return [a.pre, a.post, a.stop, a.edit].every((spec) => !spec || json.hooks[spec.event] === undefined || Array.isArray(json.hooks[spec.event]));
|
|
58
58
|
}
|
|
59
59
|
function writeOrRemove(path, settings) {
|
|
60
60
|
const meaningful = Object.keys(settings).filter((k) => k !== 'version');
|
|
@@ -72,7 +72,7 @@ function installAgent(settings, name) {
|
|
|
72
72
|
settings.hooks ??= {};
|
|
73
73
|
if (a.style === 'cursor')
|
|
74
74
|
settings.version ??= 1;
|
|
75
|
-
for (const phase of ['pre', 'post', 'stop']) {
|
|
75
|
+
for (const phase of ['pre', 'post', 'stop', 'edit']) {
|
|
76
76
|
const spec = a[phase];
|
|
77
77
|
if (!spec)
|
|
78
78
|
continue;
|
|
@@ -125,10 +125,12 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
125
125
|
return { code: 1, lines: [t(lang, 'setup_not_git')] };
|
|
126
126
|
}
|
|
127
127
|
const rel = (p) => relative(root, p) || p;
|
|
128
|
-
//
|
|
129
|
-
//
|
|
130
|
-
const targets = opts.uninstall || opts.agents ? agentNames : [];
|
|
128
|
+
// Files we will touch: chosen agents get hooks; in exact mode (and on uninstall) agents that currently have cto hooks
|
|
129
|
+
// lose them. Any other agent's config is never read, so a broken unrelated file cannot block the install.
|
|
131
130
|
const chosen = new Set(opts.uninstall ? [] : (opts.agents ?? []));
|
|
131
|
+
const removing = opts.uninstall || opts.exact ? wiredAgents(root).filter((n) => !chosen.has(n)) : [];
|
|
132
|
+
const targets = [...chosen, ...removing];
|
|
133
|
+
// Validate every config file we may touch before writing anything.
|
|
132
134
|
const settings = new Map();
|
|
133
135
|
for (const name of targets) {
|
|
134
136
|
const path = join(root, agents[name].settings);
|
|
@@ -168,6 +170,8 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
168
170
|
lines.push(t(lang, 'uninstall_gitignore'));
|
|
169
171
|
}
|
|
170
172
|
}
|
|
173
|
+
for (const p of syncGuidance(root, new Set(), true).removed)
|
|
174
|
+
lines.push(t(lang, 'uninstall_skill', { path: p }));
|
|
171
175
|
lines.push(t(lang, 'uninstall_done'));
|
|
172
176
|
return { code: 0, lines };
|
|
173
177
|
}
|
|
@@ -201,6 +205,12 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
201
205
|
if (note)
|
|
202
206
|
lines.push(t(lang, note));
|
|
203
207
|
}
|
|
208
|
+
// 2b. The cto skill (rules for the agent), for the chosen agents.
|
|
209
|
+
const skills = syncGuidance(root, chosen, !!opts.exact);
|
|
210
|
+
for (const p of skills.written)
|
|
211
|
+
lines.push(t(lang, 'setup_skill', { path: p }));
|
|
212
|
+
for (const p of skills.removed)
|
|
213
|
+
lines.push(t(lang, 'uninstall_skill', { path: p }));
|
|
204
214
|
// 3. .gitignore block.
|
|
205
215
|
writeFileSync(ignorePath, appendBlock(existsSync(ignorePath) ? readFileSync(ignorePath, 'utf8') : '', IGNORE_BODY));
|
|
206
216
|
lines.push(t(lang, 'setup_gitignore'));
|
|
@@ -208,7 +218,8 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
208
218
|
const cfgPath = join(root, '.cto.json');
|
|
209
219
|
let goal = '';
|
|
210
220
|
if (!existsSync(cfgPath)) {
|
|
211
|
-
|
|
221
|
+
// Thresholds are left out on purpose: the package defaults apply and improve with each release. Add only overrides.
|
|
222
|
+
writeFileSync(cfgPath, JSON.stringify({ sprint_goal: '', thresholds: {} }, null, 2) + '\n');
|
|
212
223
|
lines.push(t(lang, 'setup_config'));
|
|
213
224
|
}
|
|
214
225
|
else {
|
|
@@ -222,6 +233,18 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
222
233
|
lines.push(t(lang, 'setup_done'));
|
|
223
234
|
return { code: 0, lines };
|
|
224
235
|
}
|
|
236
|
+
/** Hook phases a wired agent should have but its config lacks (installed by an older version). */
|
|
237
|
+
export function missingHooks(root) {
|
|
238
|
+
const missing = [];
|
|
239
|
+
for (const n of wiredAgents(root)) {
|
|
240
|
+
const text = readFileSync(join(root, agents[n].settings), 'utf8');
|
|
241
|
+
for (const phase of ['pre', 'post', 'stop', 'edit']) {
|
|
242
|
+
if (agents[n][phase] && !text.includes(hookCommand(n, phase)))
|
|
243
|
+
missing.push(hookCommand(n, phase));
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return missing;
|
|
247
|
+
}
|
|
225
248
|
/** Agents whose config in this repo currently calls cto. */
|
|
226
249
|
export function wiredAgents(root) {
|
|
227
250
|
return agentNames.filter((n) => {
|
|
@@ -238,13 +261,23 @@ export function gitRoot(cwd) {
|
|
|
238
261
|
return undefined;
|
|
239
262
|
}
|
|
240
263
|
}
|
|
241
|
-
/**
|
|
264
|
+
/**
|
|
265
|
+
* Set sprint_goal in .cto.json, keeping everything else in the file.
|
|
266
|
+
* Refuses (returns false) when the file exists but is not a JSON object: never overwrite someone's thresholds.
|
|
267
|
+
*/
|
|
242
268
|
export function setSprintGoal(root, goal) {
|
|
243
269
|
const path = join(root, '.cto.json');
|
|
244
|
-
let cfg =
|
|
245
|
-
|
|
246
|
-
|
|
270
|
+
let cfg = { sprint_goal: '', thresholds: {} };
|
|
271
|
+
if (existsSync(path)) {
|
|
272
|
+
try {
|
|
273
|
+
cfg = JSON.parse(readFileSync(path, 'utf8'));
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg))
|
|
279
|
+
return false;
|
|
247
280
|
}
|
|
248
|
-
catch { /* create */ }
|
|
249
281
|
writeFileSync(path, JSON.stringify({ ...cfg, sprint_goal: goal }, null, 2) + '\n');
|
|
282
|
+
return true;
|
|
250
283
|
}
|
package/dist/skill.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, relative } from 'node:path';
|
|
3
|
+
// Guidance for coding agents, in two layers:
|
|
4
|
+
// 1. A short rules block in each agent's always-loaded project file (CLAUDE.md, AGENTS.md, GEMINI.md). Skills load
|
|
5
|
+
// only when the agent decides they are relevant, so rules that must always hold live here.
|
|
6
|
+
// 2. One detailed skill at .agents/skills/cto (read by Codex, Gemini CLI and Cursor; the rules block points Claude
|
|
7
|
+
// Code to the same file). A single copy, so Cursor (which also scans .claude/skills) never sees two.
|
|
8
|
+
// Every rule names the check that enforces it, and every enforcing check has a rule.
|
|
9
|
+
export const SKILL_MARK = '<!-- Managed by `cto setup`. Re-run it to update; local edits are overwritten. -->';
|
|
10
|
+
export const SKILL_PATH = '.agents/skills/cto/SKILL.md';
|
|
11
|
+
const LEGACY_SKILL = '.claude/skills/cto/SKILL.md'; // 0.5.0 pre-release layout, cleaned up on sync
|
|
12
|
+
const MD_START = '<!-- >>> YOUR CTO JEV START >>> -->';
|
|
13
|
+
const MD_END = '<!-- <<< YOUR CTO JEV END <<< -->';
|
|
14
|
+
const mdBlockRe = /\n?<!-- >>> YOUR CTO JEV START >>> -->\n[\s\S]*?<!-- <<< YOUR CTO JEV END <<< -->\n?/;
|
|
15
|
+
export const MEMORY_FILES = [
|
|
16
|
+
{ path: 'CLAUDE.md', agents: ['claude'] },
|
|
17
|
+
{ path: 'AGENTS.md', agents: ['codex', 'cursor'] },
|
|
18
|
+
{ path: 'GEMINI.md', agents: ['gemini'] },
|
|
19
|
+
];
|
|
20
|
+
export const RULES_BLOCK = `${MD_START}
|
|
21
|
+
## Rules enforced by cto
|
|
22
|
+
|
|
23
|
+
This repo is guarded by cto: every rule below is checked automatically, and breaking one gets you blocked.
|
|
24
|
+
|
|
25
|
+
- **Secrets stay out of code.** Use environment variables, never literal keys, tokens or passwords. (\`credential_leak\` blocks the commit)
|
|
26
|
+
- **Fix the code, not the tests.** Never skip, delete or loosen a test, rewrite an expectation to match wrong output, or lower coverage. (\`test_tampering\` blocks the commit)
|
|
27
|
+
- **Done means verified.** After your last code change, run the relevant tests or build and see them pass before saying done; otherwise say what is unverified. (\`done_unverified\` sends you back)
|
|
28
|
+
- **Two strikes, change approach.** Same command, same error twice: stop retrying and try something different. (\`infinite_loop\` blocks the retry)
|
|
29
|
+
- **Ask before anything irreversible:** deleting data, force-pushing, rewriting history, dropping a database. (\`destructive_command\` blocks it)
|
|
30
|
+
- **Stay on the sprint goal in \`.cto.json\` and keep changes simple.** (\`architecture_violation\` and \`code_complexity\` warn)
|
|
31
|
+
- **Run \`cto check\` before committing**, and never bypass a block (\`--no-verify\`, editing hooks or thresholds). If a block looks wrong, tell the user.
|
|
32
|
+
|
|
33
|
+
Details and how to handle a block: \`${SKILL_PATH}\`.
|
|
34
|
+
${MD_END}
|
|
35
|
+
`;
|
|
36
|
+
export const SKILL_TEXT = `---
|
|
37
|
+
name: cto
|
|
38
|
+
description: Development rules enforced in this repository by the cto gatekeeper, with what each check looks for and what to do when blocked. Use before committing, before saying a task is done, after a command fails, before running anything destructive, and whenever a cto hook blocks you.
|
|
39
|
+
---
|
|
40
|
+
${SKILL_MARK}
|
|
41
|
+
|
|
42
|
+
# cto: the rules of this repo
|
|
43
|
+
|
|
44
|
+
This repository is guarded by **cto** (your-cto-jev). Hooks review your commits and commands with a decision model.
|
|
45
|
+
Each rule below has a check behind it. Following the rules is faster than being blocked.
|
|
46
|
+
|
|
47
|
+
| Rule | What enforces it |
|
|
48
|
+
|---|---|
|
|
49
|
+
| **Secrets stay out of code.** Never write API keys, tokens, passwords or private keys into code or committed files. Read them from environment variables. | \`credential_leak\` blocks the commit |
|
|
50
|
+
| **Fix the code, not the tests.** When a test fails, change the code under test. Never skip, comment out or delete a test, loosen an assertion, change an expected value to match wrong output, swallow the error, or lower a coverage threshold. A test may only go away together with the feature it covers, and you say so. | \`test_tampering\` blocks the commit |
|
|
51
|
+
| **Done means verified.** After your last code change, run the relevant tests, build or type check and see it pass before you say the work is done. If you cannot, say plainly what is not verified and why. | \`done_unverified\` sends you back to work |
|
|
52
|
+
| **Two strikes, change approach.** If a command fails with the same error twice, stop retrying. Read the error, inspect the code, and try something different. | \`infinite_loop\` blocks the retry once |
|
|
53
|
+
| **Ask before anything irreversible.** Get the user's explicit OK before deleting data outside build output, force-pushing, rewriting shared history, or dropping a database. | \`destructive_command\` blocks the command |
|
|
54
|
+
| **Stay on the sprint goal.** If \`.cto.json\` sets a \`sprint_goal\`, keep changes inside it and point out anything unrelated. | \`architecture_violation\` warns |
|
|
55
|
+
| **Keep it simple.** Prefer the smallest change that solves the problem. | \`code_complexity\` warns |
|
|
56
|
+
|
|
57
|
+
## Before you commit
|
|
58
|
+
|
|
59
|
+
Run \`cto check\`. It runs the same commit checks on your staged changes (or, if nothing is staged, on all working-tree
|
|
60
|
+
changes including new files) without committing, and prints every score with its threshold. Fix anything it flags,
|
|
61
|
+
then commit. If \`cto\` is not installed on this machine, skip this step.
|
|
62
|
+
|
|
63
|
+
## When cto blocks you
|
|
64
|
+
|
|
65
|
+
Read the message, fix the cause, and try again. Never bypass a block: no \`git commit --no-verify\`, no disabling or
|
|
66
|
+
editing hooks, no changing \`.cto.json\` thresholds to get through. If you believe a block is wrong, stop and tell the
|
|
67
|
+
user what was blocked and why you disagree; the user decides.
|
|
68
|
+
|
|
69
|
+
## Commands
|
|
70
|
+
|
|
71
|
+
- \`cto check\`: preview the commit checks on your current changes.
|
|
72
|
+
- \`cto doctor\`: show whether cto is working here (keys, hooks, recent checks).
|
|
73
|
+
`;
|
|
74
|
+
// Removes exactly what appendMd added: the block, its trailing newline, and the one blank separator line before it.
|
|
75
|
+
const removeMd = (s) => s.replace(mdBlockRe, '');
|
|
76
|
+
const appendMd = (s) => {
|
|
77
|
+
const base = removeMd(s);
|
|
78
|
+
return (base && !base.endsWith('\n') ? base + '\n' : base) + (base.trim() ? '\n' : '') + RULES_BLOCK;
|
|
79
|
+
};
|
|
80
|
+
function removeFileAndEmptyDirs(root, path) {
|
|
81
|
+
unlinkSync(path);
|
|
82
|
+
for (let d = dirname(path), i = 0; i < 3 && !relative(root, d).startsWith('..') && relative(root, d) !== ''; i++, d = dirname(d)) {
|
|
83
|
+
try {
|
|
84
|
+
if (readdirSync(d).length)
|
|
85
|
+
break;
|
|
86
|
+
rmdirSync(d);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Bring guidance in line with the chosen agents: write/refresh the rules block and the skill for them; with
|
|
95
|
+
* removeOthers (exact mode or uninstall) take cto's content out of files no chosen agent reads. Only cto-marked
|
|
96
|
+
* content is ever removed or overwritten.
|
|
97
|
+
*/
|
|
98
|
+
export function syncGuidance(root, chosen, removeOthers) {
|
|
99
|
+
const written = [];
|
|
100
|
+
const removed = [];
|
|
101
|
+
for (const m of MEMORY_FILES) {
|
|
102
|
+
const path = join(root, m.path);
|
|
103
|
+
const current = existsSync(path) ? readFileSync(path, 'utf8') : '';
|
|
104
|
+
if (m.agents.some((a) => chosen.has(a))) {
|
|
105
|
+
const next = appendMd(current);
|
|
106
|
+
if (next !== current) {
|
|
107
|
+
writeFileSync(path, next);
|
|
108
|
+
written.push(m.path);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
else if (removeOthers && mdBlockRe.test(current)) {
|
|
112
|
+
const rest = removeMd(current);
|
|
113
|
+
if (rest.trim())
|
|
114
|
+
writeFileSync(path, rest);
|
|
115
|
+
else
|
|
116
|
+
unlinkSync(path);
|
|
117
|
+
removed.push(m.path);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const skill = join(root, SKILL_PATH);
|
|
121
|
+
if (chosen.size) {
|
|
122
|
+
if (!existsSync(skill) || readFileSync(skill, 'utf8') !== SKILL_TEXT) {
|
|
123
|
+
mkdirSync(dirname(skill), { recursive: true });
|
|
124
|
+
writeFileSync(skill, SKILL_TEXT);
|
|
125
|
+
written.push(SKILL_PATH);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
else if (removeOthers && existsSync(skill) && readFileSync(skill, 'utf8').includes(SKILL_MARK)) {
|
|
129
|
+
removeFileAndEmptyDirs(root, skill);
|
|
130
|
+
removed.push(SKILL_PATH);
|
|
131
|
+
}
|
|
132
|
+
const legacy = join(root, LEGACY_SKILL);
|
|
133
|
+
if (existsSync(legacy) && readFileSync(legacy, 'utf8').includes(SKILL_MARK))
|
|
134
|
+
removeFileAndEmptyDirs(root, legacy);
|
|
135
|
+
return { written, removed };
|
|
136
|
+
}
|
|
137
|
+
/** Guidance files that are missing or differ from what this version would write, for the given agents. */
|
|
138
|
+
export function staleGuidance(root, agentsInUse) {
|
|
139
|
+
if (!agentsInUse.length)
|
|
140
|
+
return [];
|
|
141
|
+
const stale = [];
|
|
142
|
+
for (const m of MEMORY_FILES) {
|
|
143
|
+
if (!m.agents.some((a) => agentsInUse.includes(a)))
|
|
144
|
+
continue;
|
|
145
|
+
const path = join(root, m.path);
|
|
146
|
+
const current = existsSync(path) ? readFileSync(path, 'utf8') : '';
|
|
147
|
+
if (!current.includes(RULES_BLOCK.trimEnd()))
|
|
148
|
+
stale.push(m.path);
|
|
149
|
+
}
|
|
150
|
+
const skill = join(root, SKILL_PATH);
|
|
151
|
+
if (!existsSync(skill) || readFileSync(skill, 'utf8') !== SKILL_TEXT)
|
|
152
|
+
stale.push(SKILL_PATH);
|
|
153
|
+
return stale;
|
|
154
|
+
}
|
package/dist/turn.js
CHANGED
|
@@ -6,7 +6,8 @@ const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
|
|
|
6
6
|
const NON_CODE = /(\.(md|mdx|txt|rst|adoc|ya?ml)$)|(^|[\\/])\.github[\\/]/i;
|
|
7
7
|
export const isCodeFile = (f) => !NON_CODE.test(f);
|
|
8
8
|
const isHumanTurn = (j) => {
|
|
9
|
-
|
|
9
|
+
// Claude Code writes meta entries (image notes, skill text, compact summaries) as type "user" mid-turn.
|
|
10
|
+
if (j?.type !== 'user' || j.isMeta || j.isCompactSummary)
|
|
10
11
|
return false;
|
|
11
12
|
const c = j.message?.content;
|
|
12
13
|
if (typeof c === 'string')
|
|
@@ -77,11 +78,12 @@ export function turnActions(transcriptPath, cwd) {
|
|
|
77
78
|
}
|
|
78
79
|
/** The text Jev sees: final message, the action log, and the one fact code can compute exactly. Masked. */
|
|
79
80
|
export function turnState(lastMessage, actions) {
|
|
80
|
-
|
|
81
|
+
// The fact is computed over the whole turn; only the log shown to Jev is trimmed.
|
|
81
82
|
let lastEdit = -1;
|
|
82
|
-
|
|
83
|
+
actions.forEach((a, i) => { if (a.kind === 'edit' && isCodeFile(a.file))
|
|
83
84
|
lastEdit = i; });
|
|
84
|
-
const after = lastEdit < 0 ? null :
|
|
85
|
+
const after = lastEdit < 0 ? null : actions.slice(lastEdit + 1).flatMap((a) => (a.kind === 'run' ? [oneLine(a.command, 120)] : []));
|
|
86
|
+
const recent = actions.slice(-40);
|
|
85
87
|
const fact = after === null
|
|
86
88
|
? 'No code files were edited this turn.'
|
|
87
89
|
: after.length ? `Commands that ran after the last code edit: ${after.join('; ')}` : 'No command ran after the last code edit.';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "your-cto-jev",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "A sharp-tongued CTO gatekeeper for AI coding agents: blocks leaked secrets in git commits and destructive shell commands in Claude Code, Cursor, Gemini CLI and Codex, using TypeSafe Jev.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude-code",
|