your-cto-jev 0.4.3 → 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 +31 -1
- package/dist/check.js +67 -0
- package/dist/doctor.js +15 -1
- package/dist/hooks.js +57 -29
- package/dist/i18n.js +50 -2
- package/dist/index.js +31 -2
- package/dist/setup.js +21 -0
- package/dist/skill.js +154 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -100,7 +100,7 @@ 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
|
|
|
@@ -108,10 +108,40 @@ Other forms:
|
|
|
108
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.
|
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
|
@@ -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++;
|
package/dist/i18n.js
CHANGED
|
@@ -107,6 +107,30 @@ 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
|
+
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} 天前`,
|
|
110
134
|
doc_version: (v) => `cto ${v.v}`,
|
|
111
135
|
doc_keys: () => 'Jev API key(每個都用一次真實請求驗證):',
|
|
112
136
|
doc_not_set: (v) => `未設定(缺 ${v.keys})`,
|
|
@@ -137,7 +161,7 @@ const messages = {
|
|
|
137
161
|
doc_bad: () => '[cto] 有問題需要處理:',
|
|
138
162
|
update_available: (v) => `[cto] 有新版 ${v.latest}(目前 ${v.current}),執行 cto update 更新`,
|
|
139
163
|
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>',
|
|
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>',
|
|
141
165
|
},
|
|
142
166
|
en: {
|
|
143
167
|
reason_402: () => 'out of credits',
|
|
@@ -212,6 +236,30 @@ const messages = {
|
|
|
212
236
|
ui_unset: () => 'not set',
|
|
213
237
|
ui_saved: () => 'Done. Run cto setup to come back to this overview, and cto doctor to check that it works.',
|
|
214
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`,
|
|
215
263
|
doc_version: (v) => `cto ${v.v}`,
|
|
216
264
|
doc_keys: () => 'Jev API keys (each verified with one real request):',
|
|
217
265
|
doc_not_set: (v) => `not set (missing ${v.keys})`,
|
|
@@ -242,7 +290,7 @@ const messages = {
|
|
|
242
290
|
doc_bad: () => '[cto] Needs attention:',
|
|
243
291
|
update_available: (v) => `[cto] Version ${v.latest} is available (you have ${v.current}). Run cto update`,
|
|
244
292
|
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>',
|
|
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>',
|
|
246
294
|
},
|
|
247
295
|
};
|
|
248
296
|
export function t(lang, key, vars = {}) {
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
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';
|
|
@@ -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.
|
|
@@ -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 { 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,12 @@ 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
|
+
for (const p of skills.removed)
|
|
213
|
+
lines.push(t(lang, 'uninstall_skill', { path: p }));
|
|
205
214
|
// 3. .gitignore block.
|
|
206
215
|
writeFileSync(ignorePath, appendBlock(existsSync(ignorePath) ? readFileSync(ignorePath, 'utf8') : '', IGNORE_BODY));
|
|
207
216
|
lines.push(t(lang, 'setup_gitignore'));
|
|
@@ -224,6 +233,18 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
224
233
|
lines.push(t(lang, 'setup_done'));
|
|
225
234
|
return { code: 0, lines };
|
|
226
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
|
+
}
|
|
227
248
|
/** Agents whose config in this repo currently calls cto. */
|
|
228
249
|
export function wiredAgents(root) {
|
|
229
250
|
return agentNames.filter((n) => {
|
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/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",
|