your-cto-jev 0.4.3 → 0.6.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 +57 -21
- package/dist/agents.js +11 -0
- package/dist/api.js +4 -1
- package/dist/check.js +67 -0
- package/dist/doctor.js +38 -7
- package/dist/hooks.js +59 -31
- package/dist/i18n.js +56 -2
- package/dist/index.js +35 -6
- package/dist/setup.js +40 -0
- package/dist/setupui.js +2 -2
- package/dist/skill.js +161 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
**A sharp-tongued CTO that reviews what your AI coding agent is about to do, and says no.**
|
|
4
4
|
|
|
5
|
-
`cto` hooks into `git commit` and into
|
|
5
|
+
`cto` hooks into `git commit` and into Claude Code, Cursor, Gemini CLI and Codex. Before a commit lands, before an agent runs a shell command, and when Claude Code says it is done, it asks [TypeSafe Jev](https://developers.cloudflare.com/ai/models/typesafe/jev/), a typed decision model, a few yes/no questions. Then it blocks, warns, or stays completely silent.
|
|
6
6
|
|
|
7
7
|
```text
|
|
8
8
|
$ git commit -m "add payments"
|
|
@@ -15,7 +15,7 @@ $ git commit -m "add payments"
|
|
|
15
15
|
|
|
16
16
|
# Same build fails twice, agent tries the exact same thing again
|
|
17
17
|
[cto] Same error again. You are looping and burning tokens. This tool call is BLOCKED. Fix the logic first.
|
|
18
|
-
infinite_loop = 0.95 (threshold > 0.
|
|
18
|
+
infinite_loop = 0.95 (threshold > 0.6)
|
|
19
19
|
```
|
|
20
20
|
|
|
21
21
|
Messages come in English or 繁體中文, picked from your locale.
|
|
@@ -50,18 +50,20 @@ When nothing crosses a threshold, `cto` prints nothing at all.
|
|
|
50
50
|
|
|
51
51
|
```mermaid
|
|
52
52
|
flowchart TD
|
|
53
|
-
A["git commit"] --> B["Staged diff<br/>minus lock files
|
|
54
|
-
C["Agent shell command<br/>Claude Code · Cursor · Gemini CLI · Codex"] --> D["Command + failures from the last 15 min"]
|
|
55
|
-
E["Agent command failed"] --> F[("
|
|
53
|
+
A["git commit<br/>or cto check"] --> B["Staged diff (cto check: working tree<br/>when nothing is staged), minus lock files,<br/>minified files, maps, binaries · ~24k-token chunks"]
|
|
54
|
+
C["Agent shell command<br/>Claude Code · Cursor · Gemini CLI · Codex"] --> D["Command + failures from the last 15 min<br/>marked when code was edited since"]
|
|
55
|
+
E["Agent command failed"] --> F[("Failure log, kept locally<br/>edits mark entries · no API call")]
|
|
56
|
+
G["Agent edited a code file"] --> F
|
|
56
57
|
F -.-> D
|
|
58
|
+
H["Claude Code ends a turn<br/>that edited code"] --> I["Final message + this turn's actions<br/>+ what ran after the last edit"]
|
|
57
59
|
B --> M["Mask secrets<br/>keys, tokens, .env values"]
|
|
58
60
|
D --> M
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
P1 -- "
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
J -- "secret, weakened tests,<br/>destructive or
|
|
61
|
+
I --> M
|
|
62
|
+
M --> P1{"Providers in your order<br/>default: OpenRouter, TypeSafe, Cloudflare"}
|
|
63
|
+
P1 -- "answers" --> J{"Jev scores vs<br/>thresholds"}
|
|
64
|
+
P1 -- "error, cooling down or no key:<br/>next provider" --> P1
|
|
65
|
+
P1 -- "none left" --> O["Fail open<br/>let it through"]
|
|
66
|
+
J -- "secret, weakened tests,<br/>destructive, loop, or unverified done" --> X["BLOCK<br/>commit exit 1 · tool call or stop exit 2"]
|
|
65
67
|
J -- "complex or off the sprint goal" --> W["Warn, then allow"]
|
|
66
68
|
J -- "nothing crosses" --> S["Allow silently"]
|
|
67
69
|
```
|
|
@@ -100,28 +102,59 @@ Then restart your agent session so it picks up the new hooks, and check that eve
|
|
|
100
102
|
cto doctor
|
|
101
103
|
```
|
|
102
104
|
|
|
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.
|
|
105
|
+
`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
106
|
|
|
105
107
|
Other forms:
|
|
106
108
|
|
|
107
109
|
```sh
|
|
108
110
|
cto setup --agents claude,cursor --yes # non-interactive (scripts, CI); only adds, never removes
|
|
109
|
-
cto setup --
|
|
111
|
+
cto setup --refresh # re-write hooks and rules for the agents already set up
|
|
112
|
+
cto setup --uninstall # remove every cto hook, rules block and skill again
|
|
110
113
|
cto doctor # is it actually working?
|
|
114
|
+
cto check # preview the commit checks on your current changes
|
|
111
115
|
```
|
|
112
116
|
|
|
113
117
|
`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
118
|
|
|
119
|
+
## The rules, written down for the agent
|
|
120
|
+
|
|
121
|
+
`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.
|
|
122
|
+
|
|
123
|
+
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.
|
|
124
|
+
|
|
125
|
+
| Rule | Enforced by |
|
|
126
|
+
|---|---|
|
|
127
|
+
| Secrets stay out of code | `credential_leak` blocks the commit |
|
|
128
|
+
| Fix the code, not the tests | `test_tampering` blocks the commit |
|
|
129
|
+
| Done means verified | `done_unverified` sends the agent back to work |
|
|
130
|
+
| Two strikes, change approach | `infinite_loop` blocks the retry once |
|
|
131
|
+
| Ask before anything irreversible | `destructive_command` blocks the command |
|
|
132
|
+
| Stay on the sprint goal | `architecture_violation` warns |
|
|
133
|
+
| Keep it simple | `code_complexity` warns |
|
|
134
|
+
|
|
135
|
+
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.
|
|
136
|
+
|
|
137
|
+
`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:
|
|
138
|
+
|
|
139
|
+
```text
|
|
140
|
+
[cto] Nothing staged, checking the working tree instead (9 files, including new untracked files):
|
|
141
|
+
credential_leak 0.03 blocks above 0.5 ok
|
|
142
|
+
test_tampering 0.03 blocks above 0.8 ok
|
|
143
|
+
architecture_violation not checked: sprint_goal is empty in .cto.json
|
|
144
|
+
code_complexity 2.02 warns above 2 would warn
|
|
145
|
+
[cto] Good to commit.
|
|
146
|
+
```
|
|
147
|
+
|
|
115
148
|
## Supported agents
|
|
116
149
|
|
|
117
150
|
The git pre-commit check is always installed. It protects every agent and every human who commits from that repo.
|
|
118
151
|
|
|
119
|
-
| Agent | Config written | Command gate | Loop detection |
|
|
120
|
-
|
|
121
|
-
| Claude Code | `.claude/settings.local.json` | yes | yes |
|
|
122
|
-
| Cursor | `.cursor/hooks.json` | yes | yes |
|
|
123
|
-
| Gemini CLI | `.gemini/settings.json` | yes | yes |
|
|
124
|
-
| Codex CLI | `.codex/hooks.json` | yes | limited: Codex has no failure event |
|
|
152
|
+
| Agent | Config written | Command gate | Loop detection | Knows about edits | Done check |
|
|
153
|
+
|---|---|---|---|---|---|
|
|
154
|
+
| Claude Code | `.claude/settings.local.json` | yes | yes | yes | yes |
|
|
155
|
+
| Cursor | `.cursor/hooks.json` | yes | yes | yes (`afterFileEdit`) | not yet |
|
|
156
|
+
| Gemini CLI | `.gemini/settings.json` | yes | yes | yes (`write_file`, `replace`) | not yet |
|
|
157
|
+
| Codex CLI | `.codex/hooks.json` | yes | limited: Codex has no failure event | yes (`apply_patch`) | not yet |
|
|
125
158
|
|
|
126
159
|
Claude Code is tested end to end inside the agent. The Cursor, Gemini CLI and Codex adapters follow each agent's official hook docs and are tested with their documented payloads, but have not been run inside those agents yet. Reports welcome.
|
|
127
160
|
|
|
@@ -137,7 +170,7 @@ You need at least one provider. `cto setup` lets you pick which ones to use and
|
|
|
137
170
|
| [TypeSafe](https://docs.typesafe.ai/introduction/quickstart) | `TYPESAFE_API_KEY` | Direct from the makers of Jev. Get a key at console.typesafe.ai/keys. Pinned to `jev-1.13.0`, the version the thresholds were calibrated on. Not yet tested with a live key |
|
|
138
171
|
| [Cloudflare Workers AI](https://developers.cloudflare.com/ai/models/typesafe/jev/) | `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID` | Token needs Account > Workers AI > Read. Your account's default AI Gateway must have **Authenticated Gateway** on and Unified Billing credits |
|
|
139
172
|
|
|
140
|
-
If the first provider fails, `cto` switches to the next one in your order and tells you once. It retries the first provider later. A missing key, a timeout or an outage never blocks you: `cto` fails open and lets the action through. It only blocks when Jev answers and the answer crosses a threshold.
|
|
173
|
+
Without a picked order, the fastest measured provider goes first: OpenRouter, then TypeSafe, then Cloudflare. If the first provider fails, `cto` switches to the next one in your order and tells you once. It retries the first provider later. A missing key, a timeout or an outage never blocks you: `cto` fails open and lets the action through. It only blocks when Jev answers and the answer crosses a threshold.
|
|
141
174
|
|
|
142
175
|
**Where keys live.** Environment variables win. Otherwise `cto` reads a per-user file that `setup` writes:
|
|
143
176
|
|
|
@@ -152,6 +185,8 @@ Every check sends text to your chosen provider. `cto` masks it first:
|
|
|
152
185
|
|
|
153
186
|
- **For commits:** the staged diff, with lock files, minified files, source maps and binaries removed.
|
|
154
187
|
- **For agent commands:** the command, plus up to five failures from the last 15 minutes when checking for loops.
|
|
188
|
+
- **When Claude Code ends a turn that edited code:** the agent's final message and a log of that turn: names of edited files, the shell commands it ran, whether each succeeded, and the last 200 characters of each output.
|
|
189
|
+
- **For `cto check`:** the same as a commit; when nothing is staged, all working-tree changes, including the full content of new files git does not track yet.
|
|
155
190
|
- **Always masked:** private key blocks, Stripe, OpenAI, AWS, GitHub and npm tokens, and any `NAME=value` whose name ends in `PASSWORD`, `SECRET`, `TOKEN` or `KEY`. Every value in a `.env` file is masked as well.
|
|
156
191
|
|
|
157
192
|
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.
|
|
@@ -176,13 +211,14 @@ Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6,
|
|
|
176
211
|
- **`sprint_goal`**: fill it in to enable the architecture check, for example `"Ship Stripe billing, no new services"`.
|
|
177
212
|
- **Thresholds**: Jev returns a probability from 0 to 1. `code_complexity` is the exception: it is a score from 0 (clean) to 4 (unmaintainable).
|
|
178
213
|
- **Calibration**: on 32 hand-written diffs, every one scoring above 0.8 for `test_tampering` really weakened the tests, and no legitimate change scored above 0.37. The 0.8 default caught 13 of 16 weakening diffs; the misses were subtle ones such as a meaningless float tolerance or a skip hidden behind an env var. Lower it to 0.5 to catch 15 of 16, at a higher risk of blocking honest commits.
|
|
214
|
+
- `done_unverified` (0.6) and `infinite_loop` (0.6) were calibrated the same way; the measurements are in the design spec.
|
|
179
215
|
- In the same way, `git push --force` scored about 0.50 for `destructive_command`, so the default lets it through. Lower that threshold to about 0.45 if you want force pushes blocked.
|
|
180
216
|
|
|
181
217
|
`.cto-brain.json` holds personal runtime state and is gitignored.
|
|
182
218
|
|
|
183
219
|
| Env var | Purpose |
|
|
184
220
|
|---|---|
|
|
185
|
-
| `CTO_PROVIDER` | Use only `
|
|
221
|
+
| `CTO_PROVIDER` | Use only one provider: `openrouter`, `typesafe` or `cloudflare` |
|
|
186
222
|
| `CTO_FAILOVER=0` | Never switch providers |
|
|
187
223
|
| `CTO_LANG` | `en` or `zh-TW` (default: your locale) |
|
|
188
224
|
| `CTO_DEBUG=1` | Write masked hook input to `debug_stdin.json` |
|
package/dist/agents.js
CHANGED
|
@@ -28,6 +28,7 @@ export const agents = {
|
|
|
28
28
|
post: { event: 'PostToolUseFailure', matcher: 'Bash' },
|
|
29
29
|
stop: { event: 'Stop' },
|
|
30
30
|
edit: { event: 'PostToolUse', matcher: 'Edit|Write|MultiEdit|NotebookEdit' },
|
|
31
|
+
parseEdit: (i) => { const p = str(i?.tool_input?.file_path) ?? str(i?.tool_input?.notebook_path); return p ? [p] : undefined; },
|
|
31
32
|
parseStop: (i) => ({
|
|
32
33
|
sessionId: str(i?.session_id),
|
|
33
34
|
cwd: str(i?.cwd),
|
|
@@ -47,6 +48,8 @@ export const agents = {
|
|
|
47
48
|
style: 'cursor',
|
|
48
49
|
pre: { event: 'beforeShellExecution' },
|
|
49
50
|
post: { event: 'postToolUseFailure' },
|
|
51
|
+
edit: { event: 'afterFileEdit' },
|
|
52
|
+
parseEdit: (i) => { const p = str(i?.file_path); return p ? [p] : undefined; },
|
|
50
53
|
parsePre: (i) => ({ command: str(i?.command), sessionId: str(i?.conversation_id), cwd: str(i?.cwd) ?? str(i?.workspace_roots?.[0]) }),
|
|
51
54
|
parsePost: (i) => i?.tool_name !== 'Shell' || i?.is_interrupt || !str(i?.error_message)
|
|
52
55
|
? null
|
|
@@ -66,6 +69,8 @@ export const agents = {
|
|
|
66
69
|
style: 'nested',
|
|
67
70
|
pre: { event: 'BeforeTool', matcher: 'run_shell_command' },
|
|
68
71
|
post: { event: 'AfterTool', matcher: 'run_shell_command' },
|
|
72
|
+
edit: { event: 'AfterTool', matcher: 'write_file|replace' },
|
|
73
|
+
parseEdit: (i) => { const p = str(i?.tool_input?.file_path); return p ? [p] : undefined; },
|
|
69
74
|
parsePre: nestedPre,
|
|
70
75
|
parsePost: (i) => {
|
|
71
76
|
if (i?.tool_name !== 'run_shell_command')
|
|
@@ -85,6 +90,12 @@ export const agents = {
|
|
|
85
90
|
pre: { event: 'PreToolUse', matcher: 'Bash' },
|
|
86
91
|
// Codex has no failure event; PostToolUse is recorded only when its output shows a non-zero exit.
|
|
87
92
|
post: { event: 'PostToolUse', matcher: 'Bash' },
|
|
93
|
+
// Codex edits through apply_patch; the patch text names each file ("*** Update File: src/a.ts").
|
|
94
|
+
edit: { event: 'PostToolUse', matcher: 'apply_patch' },
|
|
95
|
+
parseEdit: (i) => {
|
|
96
|
+
const files = [...String(i?.tool_input?.command ?? '').matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => m[1].trim());
|
|
97
|
+
return files.length ? files : undefined;
|
|
98
|
+
},
|
|
88
99
|
note: 'note_codex_trust',
|
|
89
100
|
parsePre: nestedPre,
|
|
90
101
|
parsePost: (i) => {
|
package/dist/api.js
CHANGED
|
@@ -34,6 +34,9 @@ export const providers = {
|
|
|
34
34
|
body: ({ session_id: _, ...req }) => ({ model: 'jev-1.13.0', ...req }),
|
|
35
35
|
},
|
|
36
36
|
};
|
|
37
|
+
// Default order when nothing was ever picked: fastest measured first (OpenRouter p95 ~0.33 s; Cloudflare p50 ~0.9 s
|
|
38
|
+
// with spikes past 3 s, 2026-10-02/05). TypeSafe direct sits in between until it has been measured.
|
|
39
|
+
export const DEFAULT_ORDER = ['openrouter', 'typesafe', 'cloudflare'];
|
|
37
40
|
/**
|
|
38
41
|
* Providers to try, in order: CTO_PROVIDER > the order picked in setup (only those; an empty pick means none) > every
|
|
39
42
|
* provider with a key when nothing was ever picked.
|
|
@@ -41,7 +44,7 @@ export const providers = {
|
|
|
41
44
|
*/
|
|
42
45
|
export function providerOrder() {
|
|
43
46
|
const picked = loadPrefs().provider_order;
|
|
44
|
-
const order = env.CTO_PROVIDER ? [env.CTO_PROVIDER] : picked !== undefined ? picked :
|
|
47
|
+
const order = env.CTO_PROVIDER ? [env.CTO_PROVIDER] : picked !== undefined ? picked : DEFAULT_ORDER;
|
|
45
48
|
return order.filter((n) => providers[n]?.enabled());
|
|
46
49
|
}
|
|
47
50
|
async function callOnce(name, req, timeoutMs) {
|
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
|
@@ -2,11 +2,12 @@ import { execFileSync } from 'node:child_process';
|
|
|
2
2
|
import { existsSync, readFileSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { agents } from './agents.js';
|
|
5
|
-
import { probeProvider, providers } from './api.js';
|
|
5
|
+
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 { wiredAgents } from './setup.js';
|
|
9
|
+
import { ignoredByGit, missingHooks, wiredAgents } from './setup.js';
|
|
10
|
+
import { guidancePaths, staleGuidance } from './skill.js';
|
|
10
11
|
import { checkUpdate, currentVersion } from './update.js';
|
|
11
12
|
function hint(provider, status) {
|
|
12
13
|
if (status === '401')
|
|
@@ -19,8 +20,17 @@ function hint(provider, status) {
|
|
|
19
20
|
return 'doc_hint_network';
|
|
20
21
|
return 'doc_hint_other';
|
|
21
22
|
}
|
|
23
|
+
const isTracked = (root, p) => {
|
|
24
|
+
try {
|
|
25
|
+
execFileSync('git', ['ls-files', '--error-unmatch', p], { cwd: root, stdio: 'ignore' });
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
22
32
|
/** One screen answering "is cto actually working here?". Exit 1 when it is not. */
|
|
23
|
-
export async function doctor(cwd, lang) {
|
|
33
|
+
export async function doctor(cwd, lang, slowMs = AGENT_TIMEOUT_MS) {
|
|
24
34
|
const L = [];
|
|
25
35
|
const problems = [];
|
|
26
36
|
const latest = await checkUpdate();
|
|
@@ -29,6 +39,7 @@ export async function doctor(cwd, lang) {
|
|
|
29
39
|
L.push('', t(lang, 'doc_keys'));
|
|
30
40
|
const file = loadCredentials();
|
|
31
41
|
let working = 0;
|
|
42
|
+
const primary = providerOrder()[0];
|
|
32
43
|
for (const name of Object.keys(providers)) {
|
|
33
44
|
const label = providers[name].label;
|
|
34
45
|
const missing = providers[name].keys.filter((k) => !process.env[k]);
|
|
@@ -43,10 +54,13 @@ export async function doctor(cwd, lang) {
|
|
|
43
54
|
const ms = Math.round(performance.now() - start);
|
|
44
55
|
if (r.ok) {
|
|
45
56
|
working++;
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
57
|
+
// Only the provider tried first decides whether checks finish in time; a slow backup is worth a note, not a failure.
|
|
58
|
+
const slow = ms > slowMs;
|
|
59
|
+
const mark = !slow ? 'OK' : name === primary ? '!!' : '--';
|
|
60
|
+
const note = !slow ? '' : ' ' + t(lang, name === primary ? 'doc_slow' : 'doc_slow_backup', { limit: slowMs / 1000 });
|
|
61
|
+
L.push(` ${mark} ${label} (${source}): ${t(lang, 'doc_ok', { ms })}${note}`);
|
|
62
|
+
if (slow && name === primary)
|
|
63
|
+
problems.push(t(lang, 'doc_slow', { limit: slowMs / 1000 }));
|
|
50
64
|
}
|
|
51
65
|
else {
|
|
52
66
|
L.push(` !! ${label} (${source}): ${t(lang, 'doc_fail', { status: r.status })} ${r.message ?? ''}`.trimEnd());
|
|
@@ -78,10 +92,27 @@ export async function doctor(cwd, lang) {
|
|
|
78
92
|
}
|
|
79
93
|
const wired = wiredAgents(root);
|
|
80
94
|
L.push(` ${wired.length ? 'OK' : '--'} ${t(lang, 'doc_agents', { list: wired.map((n) => agents[n].label).join(', ') || t(lang, 'doc_none') })}`);
|
|
95
|
+
// Only files git ignores AND does not track yet: once added with -f they are tracked and fine.
|
|
96
|
+
const hidden = ignoredByGit(root, guidancePaths(wired)).filter((p) => !isTracked(root, p));
|
|
97
|
+
if (hidden.length)
|
|
98
|
+
L.push(` -- ${t(lang, 'doc_ignored', { list: hidden.join(', '), cmd: `git add -f ${hidden.join(' ')}` })}`);
|
|
99
|
+
const stale = [...missingHooks(root), ...staleGuidance(root, wired)];
|
|
100
|
+
if (stale.length) {
|
|
101
|
+
L.push(` !! ${t(lang, 'doc_stale', { list: stale.join(', ') })}`);
|
|
102
|
+
problems.push(t(lang, 'doc_stale', { list: stale.join(', ') }));
|
|
103
|
+
}
|
|
81
104
|
const cfg = loadConfig(root);
|
|
82
105
|
L.push(` -- ${t(lang, cfg.sprint_goal.trim() ? 'doc_goal_set' : 'doc_goal_empty')}`);
|
|
83
106
|
const brain = loadBrain(root);
|
|
84
107
|
L.push(` -- ${t(lang, 'doc_stats', { blocked: brain.blocked_attempts, skipped: brain.skipped_attempts })}`);
|
|
108
|
+
if (brain.last_check_at) {
|
|
109
|
+
const mins = Math.max(0, Math.round((Date.now() - Date.parse(brain.last_check_at)) / 60_000));
|
|
110
|
+
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) });
|
|
111
|
+
L.push(` OK ${t(lang, 'doc_last_check', { ago, n: brain.checks ?? 0 })}`);
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
L.push(` -- ${t(lang, 'doc_never_checked')}`);
|
|
115
|
+
}
|
|
85
116
|
for (const [p, cd] of Object.entries(brain.provider_cooldown)) {
|
|
86
117
|
if (cd.until > Date.now())
|
|
87
118
|
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
|
@@ -106,60 +106,84 @@ export const stagedDiff = (cwd) => execFileSync('git', DIFF_ARGS, { cwd, encodin
|
|
|
106
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.
|
|
107
107
|
// A timeout means "let it through unchecked", so wait as long as the git side does rather than fail open.
|
|
108
108
|
export const AGENT_TIMEOUT_MS = 5000;
|
|
109
|
-
|
|
110
|
-
export async function
|
|
111
|
-
const cfg = loadConfig(root);
|
|
112
|
-
const brain = loadBrain(root);
|
|
113
|
-
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) {
|
|
114
111
|
const files = filterDiff(maskDiff(rawDiff));
|
|
115
112
|
if (!files.length)
|
|
116
|
-
return
|
|
113
|
+
return null;
|
|
117
114
|
const chunks = chunkDiff(files);
|
|
118
115
|
const soft = { code_complexity: Q.code_complexity };
|
|
119
116
|
if (cfg.sprint_goal.trim())
|
|
120
117
|
soft.architecture_violation = architectureQ(cfg.sprint_goal.trim());
|
|
121
118
|
const notices = new Set();
|
|
119
|
+
const asked = new Set();
|
|
122
120
|
const ctx = { brain, lang, timeoutMs: 5000, notices, now };
|
|
123
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.
|
|
124
|
-
const results = await pool(chunks, 3, (state, i) =>
|
|
125
|
-
|
|
126
|
-
questions: {
|
|
122
|
+
const results = await pool(chunks, 3, (state, i) => {
|
|
123
|
+
const questions = {
|
|
127
124
|
credential_leak: Q.credential_leak,
|
|
128
125
|
...(touchesTests(state) && { test_tampering: Q.test_tampering }),
|
|
129
126
|
...(i === 0 && soft),
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
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.
|
|
137
143
|
const primary = providerOrder()[0];
|
|
138
144
|
for (const r of results)
|
|
139
145
|
if (r.ok && r.provider !== primary)
|
|
140
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);
|
|
141
166
|
const lines = [];
|
|
142
|
-
for (const s of
|
|
143
|
-
|
|
144
|
-
if (!hits.length)
|
|
167
|
+
for (const s of BLOCKING_COMMIT) {
|
|
168
|
+
if (!over(review.scores[s], s, cfg))
|
|
145
169
|
continue;
|
|
146
170
|
out.code = 1;
|
|
147
|
-
lines.push(...verdict(lang, s,
|
|
171
|
+
lines.push(...verdict(lang, s, review.scores[s], cfg, 'red'));
|
|
148
172
|
}
|
|
149
173
|
if (out.code)
|
|
150
174
|
brain.blocked_attempts++;
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
if (v !== undefined)
|
|
156
|
-
lines.push(...verdict(lang, s, v, cfg, 'yellow'));
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
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];
|
|
160
179
|
saveBrain(root, brain);
|
|
161
180
|
return out;
|
|
162
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
|
+
}
|
|
163
187
|
// ---------- pre (Bash / shell command gate, any agent) ----------
|
|
164
188
|
async function sessionNotice(brain, sessionId, lang, r, notices) {
|
|
165
189
|
if (!sessionId || brain.notified_sessions.includes(sessionId))
|
|
@@ -199,6 +223,8 @@ export async function agentPre(agent, input, { root, lang, now }) {
|
|
|
199
223
|
const r = await evaluate({ state, questions, ...(sessionId && { session_id: sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices, now });
|
|
200
224
|
if (!r.ok)
|
|
201
225
|
brain.skipped_attempts++;
|
|
226
|
+
else
|
|
227
|
+
countCheck(brain, now);
|
|
202
228
|
await sessionNotice(brain, sessionId, lang, r, notices);
|
|
203
229
|
let out = { code: 0, stderr: [] };
|
|
204
230
|
if (r.ok) {
|
|
@@ -238,6 +264,8 @@ export async function agentStop(input, { root, lang, now }) {
|
|
|
238
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 });
|
|
239
265
|
if (!r.ok)
|
|
240
266
|
brain.skipped_attempts++;
|
|
267
|
+
else
|
|
268
|
+
countCheck(brain, now);
|
|
241
269
|
const v = r.ok ? exceeded(r.answers, 'done_unverified', cfg) : undefined;
|
|
242
270
|
if (v !== undefined) {
|
|
243
271
|
brain.blocked_attempts++;
|
|
@@ -254,8 +282,8 @@ export async function agentStop(input, { root, lang, now }) {
|
|
|
254
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
|
|
255
283
|
* the history shows that. Local only: no Jev call, no network. Docs/YAML edits do not count.
|
|
256
284
|
*/
|
|
257
|
-
export function agentEdit(
|
|
258
|
-
if (
|
|
285
|
+
export function agentEdit(files, { root }) {
|
|
286
|
+
if (files && !files.some(isCodeFile))
|
|
259
287
|
return { code: 0, stderr: [] };
|
|
260
288
|
const brain = loadBrain(root);
|
|
261
289
|
if (brain.recent_errors.some((e) => !e.edited_after)) {
|
package/dist/i18n.js
CHANGED
|
@@ -107,6 +107,33 @@ const messages = {
|
|
|
107
107
|
ui_unset: () => '未設定',
|
|
108
108
|
ui_saved: () => '設定完成。之後執行 cto setup 可以回到這個總覽,cto doctor 可以確認是否正常運作。',
|
|
109
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
|
+
setup_ignored: (v) => `[cto] 注意:${v.list} 被 .gitignore 排除,commit 時不會帶上,隊友的 agent 讀不到。要分享就執行:${v.cmd}`,
|
|
127
|
+
doc_ignored: (v) => `${v.list} 被 .gitignore 排除且尚未加入 git,只存在這台電腦。要分享給隊友就執行:${v.cmd}`,
|
|
128
|
+
doc_slow_backup: (v) => `備援 provider 這次超過 ${v.limit} 秒;主要 provider 正常時不影響檢查`,
|
|
129
|
+
refresh_after_update: () => '[cto] 正在用新版更新目前 repo 的 hook 與規矩…',
|
|
130
|
+
doc_stale: (v) => `這個 repo 的 cto 設定比目前版本舊(${v.list}),執行 cto setup --refresh`,
|
|
131
|
+
uninstall_skill: (v) => `[cto] 已移除 cto 開發規矩:${v.path}`,
|
|
132
|
+
doc_last_check: (v) => `最近一次檢查:${v.ago},累計 ${v.n} 次`,
|
|
133
|
+
doc_never_checked: () => '還沒有任何一次成功的檢查',
|
|
134
|
+
ago_min: (v) => `${v.n} 分鐘前`,
|
|
135
|
+
ago_hour: (v) => `${v.n} 小時前`,
|
|
136
|
+
ago_day: (v) => `${v.n} 天前`,
|
|
110
137
|
doc_version: (v) => `cto ${v.v}`,
|
|
111
138
|
doc_keys: () => 'Jev API key(每個都用一次真實請求驗證):',
|
|
112
139
|
doc_not_set: (v) => `未設定(缺 ${v.keys})`,
|
|
@@ -137,7 +164,7 @@ const messages = {
|
|
|
137
164
|
doc_bad: () => '[cto] 有問題需要處理:',
|
|
138
165
|
update_available: (v) => `[cto] 有新版 ${v.latest}(目前 ${v.current}),執行 cto update 更新`,
|
|
139
166
|
update_done: () => '[cto] 已更新。已設定過的專案不用重跑 cto setup。',
|
|
140
|
-
usage: () => '用法:cto doctor | cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
|
|
167
|
+
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>',
|
|
141
168
|
},
|
|
142
169
|
en: {
|
|
143
170
|
reason_402: () => 'out of credits',
|
|
@@ -212,6 +239,33 @@ const messages = {
|
|
|
212
239
|
ui_unset: () => 'not set',
|
|
213
240
|
ui_saved: () => 'Done. Run cto setup to come back to this overview, and cto doctor to check that it works.',
|
|
214
241
|
ui_quit: () => 'Left without changing anything.',
|
|
242
|
+
check_nothing: () => '[cto] Nothing to check.',
|
|
243
|
+
check_head_staged: (v) => `[cto] Checking staged changes (${v.files} files), same checks as a commit:`,
|
|
244
|
+
check_head_working: (v) => `[cto] Nothing staged, checking the working tree instead (${v.files} files, including new untracked files):`,
|
|
245
|
+
check_unchecked: () => '[cto] Could not check: no working Jev provider. Run cto doctor to see why.',
|
|
246
|
+
check_why_tests: () => 'not checked: no test files changed',
|
|
247
|
+
check_why_goal: () => 'not checked: sprint_goal is empty in .cto.json',
|
|
248
|
+
check_why_failed: () => 'not checked: request failed',
|
|
249
|
+
check_limit_block: (v) => `blocks above ${v.limit}`,
|
|
250
|
+
check_limit_warn: (v) => `warns above ${v.limit}`,
|
|
251
|
+
check_block: () => 'WOULD BLOCK',
|
|
252
|
+
check_warn: () => 'would warn',
|
|
253
|
+
check_partial: () => '[cto] Note: part of the change could not be checked (request failed).',
|
|
254
|
+
check_result_ok: () => '[cto] Good to commit.',
|
|
255
|
+
check_result_block: () => '[cto] A commit now would be blocked. Fix what is flagged above first.',
|
|
256
|
+
setup_skill: (v) => `[cto] cto rules written to ${v.path}`,
|
|
257
|
+
refresh_none: () => '[cto] cto is not set up in this repo yet. Run cto setup first.',
|
|
258
|
+
setup_ignored: (v) => `[cto] Note: ${v.list} is ignored by .gitignore, so it will not be committed and teammates' agents will not see it. To share it, run: ${v.cmd}`,
|
|
259
|
+
doc_ignored: (v) => `${v.list} is ignored by .gitignore and not tracked, so it exists only on this machine. To share it with teammates, run: ${v.cmd}`,
|
|
260
|
+
doc_slow_backup: (v) => `this backup provider took longer than ${v.limit} s; checks are unaffected while the primary is healthy`,
|
|
261
|
+
refresh_after_update: () => '[cto] Refreshing hooks and rules in this repo with the new version…',
|
|
262
|
+
doc_stale: (v) => `cto in this repo is older than this version (${v.list}). Run cto setup --refresh`,
|
|
263
|
+
uninstall_skill: (v) => `[cto] Removed cto rules: ${v.path}`,
|
|
264
|
+
doc_last_check: (v) => `Last check: ${v.ago}, ${v.n} in total`,
|
|
265
|
+
doc_never_checked: () => 'No successful check yet',
|
|
266
|
+
ago_min: (v) => `${v.n} min ago`,
|
|
267
|
+
ago_hour: (v) => `${v.n} h ago`,
|
|
268
|
+
ago_day: (v) => `${v.n} days ago`,
|
|
215
269
|
doc_version: (v) => `cto ${v.v}`,
|
|
216
270
|
doc_keys: () => 'Jev API keys (each verified with one real request):',
|
|
217
271
|
doc_not_set: (v) => `not set (missing ${v.keys})`,
|
|
@@ -242,7 +296,7 @@ const messages = {
|
|
|
242
296
|
doc_bad: () => '[cto] Needs attention:',
|
|
243
297
|
update_available: (v) => `[cto] Version ${v.latest} is available (you have ${v.current}). Run cto update`,
|
|
244
298
|
update_done: () => '[cto] Updated. Projects already set up do not need cto setup again.',
|
|
245
|
-
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>',
|
|
299
|
+
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>',
|
|
246
300
|
},
|
|
247
301
|
};
|
|
248
302
|
export function t(lang, key, vars = {}) {
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
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
|
-
import { providerOrder, providers } from './api.js';
|
|
7
|
+
import { DEFAULT_ORDER, providerOrder, providers } from './api.js';
|
|
7
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';
|
|
@@ -51,8 +52,8 @@ async function runHook(name) {
|
|
|
51
52
|
}
|
|
52
53
|
catch { /* fail-open below */ }
|
|
53
54
|
if (m[2] === 'edit') {
|
|
54
|
-
const
|
|
55
|
-
return agentEdit(
|
|
55
|
+
const cwd = typeof input?.cwd === 'string' ? input.cwd : typeof input?.workspace_roots?.[0] === 'string' ? input.workspace_roots[0] : process.cwd();
|
|
56
|
+
return agentEdit(agent.parseEdit?.(input), { root: findRoot(cwd), lang });
|
|
56
57
|
}
|
|
57
58
|
if (m[2] === 'stop') {
|
|
58
59
|
if (!agent.parseStop)
|
|
@@ -97,7 +98,15 @@ else if (args[0] === 'setup') {
|
|
|
97
98
|
let goal;
|
|
98
99
|
const root = gitRoot(process.cwd());
|
|
99
100
|
const list = flag('--agents');
|
|
100
|
-
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)
|
|
101
110
|
chosen = list.split(',').map((s) => s.trim()).filter((s) => agentNames.includes(s));
|
|
102
111
|
else if (!uninstall && root && process.stdin.isTTY && process.stdout.isTTY && !args.includes('--yes')) {
|
|
103
112
|
// Interactive: start from what is actually set up now, so re-running setup edits instead of starting over.
|
|
@@ -106,7 +115,7 @@ else if (args[0] === 'setup') {
|
|
|
106
115
|
const wired = wiredAgents(root);
|
|
107
116
|
const initial = {
|
|
108
117
|
agents: wired.length ? wired : detectAgents(),
|
|
109
|
-
providers: prefs.provider_order ??
|
|
118
|
+
providers: prefs.provider_order ?? DEFAULT_ORDER.filter((p) => providers[p].enabled()),
|
|
110
119
|
keys: fileKeys,
|
|
111
120
|
lang: prefs.lang,
|
|
112
121
|
goal: loadConfig(root).sprint_goal,
|
|
@@ -136,8 +145,28 @@ else if (args[0] === 'setup') {
|
|
|
136
145
|
}
|
|
137
146
|
else if (args[0] === 'update') {
|
|
138
147
|
process.exitCode = runUpdate();
|
|
139
|
-
if (!process.exitCode)
|
|
148
|
+
if (!process.exitCode) {
|
|
140
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
|
+
}
|
|
141
170
|
}
|
|
142
171
|
else if (args[0] === 'doctor') {
|
|
143
172
|
const r = await doctor(process.cwd(), lang);
|
package/dist/setup.js
CHANGED
|
@@ -4,6 +4,7 @@ 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
6
|
import { t } from './i18n.js';
|
|
7
|
+
import { guidancePaths, syncGuidance } from './skill.js';
|
|
7
8
|
const START = '# >>> YOUR CTO JEV START >>>';
|
|
8
9
|
const END = '# <<< YOUR CTO JEV END <<<';
|
|
9
10
|
// Keep the block minimal: all logic (including the git diff call) lives in the package, so npm update upgrades every repo.
|
|
@@ -169,6 +170,8 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
169
170
|
lines.push(t(lang, 'uninstall_gitignore'));
|
|
170
171
|
}
|
|
171
172
|
}
|
|
173
|
+
for (const p of syncGuidance(root, new Set(), true).removed)
|
|
174
|
+
lines.push(t(lang, 'uninstall_skill', { path: p }));
|
|
172
175
|
lines.push(t(lang, 'uninstall_done'));
|
|
173
176
|
return { code: 0, lines };
|
|
174
177
|
}
|
|
@@ -202,6 +205,16 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
202
205
|
if (note)
|
|
203
206
|
lines.push(t(lang, note));
|
|
204
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
|
+
const hidden = ignoredByGit(root, guidancePaths(chosen));
|
|
213
|
+
// Advise git add -f: a .gitignore negation cannot re-include a file whose parent folder is excluded (git rule).
|
|
214
|
+
if (hidden.length)
|
|
215
|
+
lines.push(t(lang, 'setup_ignored', { list: hidden.join(', '), cmd: `git add -f ${hidden.join(' ')}` }));
|
|
216
|
+
for (const p of skills.removed)
|
|
217
|
+
lines.push(t(lang, 'uninstall_skill', { path: p }));
|
|
205
218
|
// 3. .gitignore block.
|
|
206
219
|
writeFileSync(ignorePath, appendBlock(existsSync(ignorePath) ? readFileSync(ignorePath, 'utf8') : '', IGNORE_BODY));
|
|
207
220
|
lines.push(t(lang, 'setup_gitignore'));
|
|
@@ -224,6 +237,33 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
224
237
|
lines.push(t(lang, 'setup_done'));
|
|
225
238
|
return { code: 0, lines };
|
|
226
239
|
}
|
|
240
|
+
/** Hook phases a wired agent should have but its config lacks (installed by an older version). */
|
|
241
|
+
export function missingHooks(root) {
|
|
242
|
+
const missing = [];
|
|
243
|
+
for (const n of wiredAgents(root)) {
|
|
244
|
+
const text = readFileSync(join(root, agents[n].settings), 'utf8');
|
|
245
|
+
for (const phase of ['pre', 'post', 'stop', 'edit']) {
|
|
246
|
+
if (agents[n][phase] && !text.includes(hookCommand(n, phase)))
|
|
247
|
+
missing.push(hookCommand(n, phase));
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return missing;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Paths git would ignore. cto's rules are meant to be committed so every teammate's agent follows them; a repo
|
|
254
|
+
* .gitignore that excludes them (often a broad rule like .agents/skills/) silently keeps them on one machine.
|
|
255
|
+
*/
|
|
256
|
+
export function ignoredByGit(root, paths) {
|
|
257
|
+
return paths.filter((p) => {
|
|
258
|
+
try {
|
|
259
|
+
execFileSync('git', ['check-ignore', '-q', p], { cwd: root, stdio: 'ignore' });
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
227
267
|
/** Agents whose config in this repo currently calls cto. */
|
|
228
268
|
export function wiredAgents(root) {
|
|
229
269
|
return agentNames.filter((n) => {
|
package/dist/setupui.js
CHANGED
|
@@ -2,10 +2,10 @@ import { MultiSelectPrompt } from '@clack/core';
|
|
|
2
2
|
import { S_BAR, S_BAR_END, S_STEP_ACTIVE, S_STEP_CANCEL, S_STEP_SUBMIT, intro, isCancel, log, multiselect, outro, password, select, spinner, text } from '@clack/prompts';
|
|
3
3
|
import { styleText } from 'node:util';
|
|
4
4
|
import { agentNames, agents } from './agents.js';
|
|
5
|
-
import { probeProvider, providers } from './api.js';
|
|
5
|
+
import { DEFAULT_ORDER, probeProvider, providers } from './api.js';
|
|
6
6
|
import { t } from './i18n.js';
|
|
7
7
|
const BACK = Symbol('back');
|
|
8
|
-
const PROVIDER_ORDER =
|
|
8
|
+
const PROVIDER_ORDER = DEFAULT_ORDER;
|
|
9
9
|
const dim = (s) => styleText('dim', s);
|
|
10
10
|
const tail = (v) => `…${v.slice(-4)}`;
|
|
11
11
|
/** Terminal columns: CJK and full-width characters take two. */
|
package/dist/skill.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
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
|
+
/** The guidance files the given agents use (what should be committed for them). */
|
|
138
|
+
export function guidancePaths(agentsInUse) {
|
|
139
|
+
const set = new Set(agentsInUse);
|
|
140
|
+
if (!set.size)
|
|
141
|
+
return [];
|
|
142
|
+
return [...MEMORY_FILES.filter((m) => m.agents.some((a) => set.has(a))).map((m) => m.path), SKILL_PATH];
|
|
143
|
+
}
|
|
144
|
+
/** Guidance files that are missing or differ from what this version would write, for the given agents. */
|
|
145
|
+
export function staleGuidance(root, agentsInUse) {
|
|
146
|
+
if (!agentsInUse.length)
|
|
147
|
+
return [];
|
|
148
|
+
const stale = [];
|
|
149
|
+
for (const m of MEMORY_FILES) {
|
|
150
|
+
if (!m.agents.some((a) => agentsInUse.includes(a)))
|
|
151
|
+
continue;
|
|
152
|
+
const path = join(root, m.path);
|
|
153
|
+
const current = existsSync(path) ? readFileSync(path, 'utf8') : '';
|
|
154
|
+
if (!current.includes(RULES_BLOCK.trimEnd()))
|
|
155
|
+
stale.push(m.path);
|
|
156
|
+
}
|
|
157
|
+
const skill = join(root, SKILL_PATH);
|
|
158
|
+
if (!existsSync(skill) || readFileSync(skill, 'utf8') !== SKILL_TEXT)
|
|
159
|
+
stale.push(SKILL_PATH);
|
|
160
|
+
return stale;
|
|
161
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "your-cto-jev",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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",
|