your-cto-jev 0.2.0 → 0.2.3
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 +11 -3
- package/dist/api.js +8 -2
- package/dist/doctor.js +106 -0
- package/dist/hooks.js +15 -3
- package/dist/i18n.js +82 -10
- package/dist/index.js +25 -4
- package/dist/setup.js +2 -3
- package/dist/update.js +57 -0
- package/dist/wizard.js +57 -16
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -75,7 +75,7 @@ cd your-project
|
|
|
75
75
|
cto setup
|
|
76
76
|
```
|
|
77
77
|
|
|
78
|
-
|
|
78
|
+
To update later, run `cto update`. Projects you already set up pick up the new version automatically: every hook only calls `cto`, and all the logic lives in the package. `cto` checks npm for a new version at most once a day and mentions it in its once-per-session notice, never on its own.
|
|
79
79
|
|
|
80
80
|
`cto setup` walks you through it in the terminal:
|
|
81
81
|
|
|
@@ -92,7 +92,13 @@ Set up a Jev API key (at least one; press Enter to skip).
|
|
|
92
92
|
OpenRouter OK
|
|
93
93
|
```
|
|
94
94
|
|
|
95
|
-
Then restart your agent session so it picks up the new hooks
|
|
95
|
+
Then restart your agent session so it picks up the new hooks, and check that everything really works:
|
|
96
|
+
|
|
97
|
+
```sh
|
|
98
|
+
cto doctor
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`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.
|
|
96
102
|
|
|
97
103
|
Other forms:
|
|
98
104
|
|
|
@@ -100,6 +106,7 @@ Other forms:
|
|
|
100
106
|
cto setup --agents claude,cursor --yes # non-interactive (scripts, CI)
|
|
101
107
|
cto setup --keys # change keys later
|
|
102
108
|
cto setup --uninstall # remove every cto hook again
|
|
109
|
+
cto doctor # is it actually working?
|
|
103
110
|
```
|
|
104
111
|
|
|
105
112
|
`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.
|
|
@@ -180,12 +187,13 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
|
|
|
180
187
|
| `CTO_FAILOVER=0` | Never switch providers |
|
|
181
188
|
| `CTO_LANG` | `en` or `zh-TW` (default: your locale) |
|
|
182
189
|
| `CTO_DEBUG=1` | Write masked hook input to `debug_stdin.json` |
|
|
190
|
+
| `CTO_NO_UPDATE_CHECK=1` | Never check npm for a new version |
|
|
183
191
|
|
|
184
192
|
## Known limitations
|
|
185
193
|
|
|
186
194
|
- **Git GUIs hide warnings.** VS Code, SourceTree and GitKraken usually hide hook output when the commit succeeds, so the architecture and complexity warnings are invisible there. Blocks still show.
|
|
187
195
|
- **A retry after a fix can look like a loop.** The loop check sees recent failures but not the edits you made since. Failures expire after 15 minutes. Raise `infinite_loop` if it gets in your way.
|
|
188
|
-
- **Each agent shell command waits about
|
|
196
|
+
- **Each agent shell command waits for one Jev request.** OpenRouter answered in about 0.3 s in our tests, Cloudflare in about 0.9 s with occasional spikes past 3 s. Agent checks wait up to 5 s before failing open.
|
|
189
197
|
|
|
190
198
|
## Development
|
|
191
199
|
|
package/dist/api.js
CHANGED
|
@@ -54,8 +54,14 @@ async function callOnce(name, req, timeoutMs) {
|
|
|
54
54
|
return { ok: false, kind: 'transient', status: '429', reason: 'reason_429', message };
|
|
55
55
|
return { ok: false, kind: 'transient', status: String(s), reason: 'reason_5xx', message };
|
|
56
56
|
}
|
|
57
|
-
//
|
|
58
|
-
|
|
57
|
+
// Docs say unwrapped, but Cloudflare actually returns {success, result: {state: "Completed", result: {answers}}}
|
|
58
|
+
// (verified 2026-10-02). Walk down "result" until the answers show up.
|
|
59
|
+
let out = json;
|
|
60
|
+
for (let i = 0; i < 3 && out && !out.answers && out.result; i++) {
|
|
61
|
+
if (out.state && out.state !== 'Completed')
|
|
62
|
+
break;
|
|
63
|
+
out = out.result;
|
|
64
|
+
}
|
|
59
65
|
if (!out?.answers || typeof out.answers !== 'object') {
|
|
60
66
|
return { ok: false, kind: 'transient', status: String(res.status), reason: 'reason_bad_response' };
|
|
61
67
|
}
|
package/dist/doctor.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { agentNames, agents } from './agents.js';
|
|
5
|
+
import { probeProvider, providers } from './api.js';
|
|
6
|
+
import { loadBrain, loadConfig, loadCredentials } from './brain.js';
|
|
7
|
+
import { AGENT_TIMEOUT_MS } from './hooks.js';
|
|
8
|
+
import { t } from './i18n.js';
|
|
9
|
+
import { checkUpdate, currentVersion } from './update.js';
|
|
10
|
+
const KEYS = {
|
|
11
|
+
cloudflare: ['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN'],
|
|
12
|
+
openrouter: ['OPENROUTER_API_KEY'],
|
|
13
|
+
};
|
|
14
|
+
function hint(provider, status) {
|
|
15
|
+
if (status === '401')
|
|
16
|
+
return provider === 'cloudflare' ? 'doc_hint_cf_401' : 'doc_hint_401';
|
|
17
|
+
if (status === '403')
|
|
18
|
+
return provider === 'cloudflare' ? 'doc_hint_cf_403' : 'doc_hint_401';
|
|
19
|
+
if (status === '402')
|
|
20
|
+
return 'doc_hint_402';
|
|
21
|
+
if (status === 'timeout' || status === 'network')
|
|
22
|
+
return 'doc_hint_network';
|
|
23
|
+
return 'doc_hint_other';
|
|
24
|
+
}
|
|
25
|
+
/** One screen answering "is cto actually working here?". Exit 1 when it is not. */
|
|
26
|
+
export async function doctor(cwd, lang) {
|
|
27
|
+
const L = [];
|
|
28
|
+
const problems = [];
|
|
29
|
+
const latest = await checkUpdate();
|
|
30
|
+
L.push(t(lang, 'doc_version', { v: currentVersion() }) + (latest ? ' ' + t(lang, 'update_available', { latest, current: currentVersion() }) : ''));
|
|
31
|
+
// Keys and a live probe per provider
|
|
32
|
+
L.push('', t(lang, 'doc_keys'));
|
|
33
|
+
const file = loadCredentials();
|
|
34
|
+
let working = 0;
|
|
35
|
+
for (const name of Object.keys(providers)) {
|
|
36
|
+
const label = providers[name].label;
|
|
37
|
+
const missing = KEYS[name].filter((k) => !process.env[k]);
|
|
38
|
+
if (missing.length) {
|
|
39
|
+
L.push(` - ${label}: ${t(lang, 'doc_not_set', { keys: missing.join(', ') })}`);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const fromFile = KEYS[name].every((k) => file[k] && file[k] === process.env[k]);
|
|
43
|
+
const source = t(lang, fromFile ? 'doc_src_file' : 'doc_src_env');
|
|
44
|
+
const start = performance.now();
|
|
45
|
+
const r = await probeProvider(name);
|
|
46
|
+
const ms = Math.round(performance.now() - start);
|
|
47
|
+
if (r.ok) {
|
|
48
|
+
working++;
|
|
49
|
+
const slow = ms > AGENT_TIMEOUT_MS;
|
|
50
|
+
L.push(` ${slow ? '!!' : 'OK'} ${label} (${source}): ${t(lang, 'doc_ok', { ms })}${slow ? ' ' + t(lang, 'doc_slow', { limit: AGENT_TIMEOUT_MS / 1000 }) : ''}`);
|
|
51
|
+
if (slow)
|
|
52
|
+
problems.push(t(lang, 'doc_slow', { limit: AGENT_TIMEOUT_MS / 1000 }));
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
L.push(` !! ${label} (${source}): ${t(lang, 'doc_fail', { status: r.status })} ${r.message ?? ''}`.trimEnd());
|
|
56
|
+
L.push(` ${t(lang, hint(name, r.status))}`);
|
|
57
|
+
problems.push(t(lang, 'doc_p_provider', { name: label }));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (!working)
|
|
61
|
+
problems.unshift(t(lang, 'doc_p_no_provider'));
|
|
62
|
+
// Current repository
|
|
63
|
+
let root;
|
|
64
|
+
try {
|
|
65
|
+
root = execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
66
|
+
}
|
|
67
|
+
catch { /* not a repo */ }
|
|
68
|
+
if (!root) {
|
|
69
|
+
L.push('', t(lang, 'doc_no_repo'));
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
L.push('', t(lang, 'doc_repo', { root }));
|
|
73
|
+
const hooksDir = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-path', 'hooks'], { cwd: root, encoding: 'utf8' }).trim();
|
|
74
|
+
const hookPath = join(hooksDir, 'pre-commit');
|
|
75
|
+
const hook = existsSync(hookPath) ? readFileSync(hookPath, 'utf8') : '';
|
|
76
|
+
if (hook.includes('YOUR CTO JEV START'))
|
|
77
|
+
L.push(` OK ${t(lang, 'doc_hook_ok', { path: hookPath })}`);
|
|
78
|
+
else {
|
|
79
|
+
L.push(` !! ${t(lang, 'doc_hook_missing')}`);
|
|
80
|
+
problems.push(t(lang, 'doc_hook_missing'));
|
|
81
|
+
}
|
|
82
|
+
const wired = agentNames.filter((n) => {
|
|
83
|
+
const p = join(root, agents[n].settings);
|
|
84
|
+
return existsSync(p) && readFileSync(p, 'utf8').includes('cto --hook ');
|
|
85
|
+
});
|
|
86
|
+
L.push(` ${wired.length ? 'OK' : '--'} ${t(lang, 'doc_agents', { list: wired.map((n) => agents[n].label).join(', ') || t(lang, 'doc_none') })}`);
|
|
87
|
+
const cfg = loadConfig(root);
|
|
88
|
+
L.push(` -- ${t(lang, cfg.sprint_goal.trim() ? 'doc_goal_set' : 'doc_goal_empty')}`);
|
|
89
|
+
const brain = loadBrain(root);
|
|
90
|
+
L.push(` -- ${t(lang, 'doc_stats', { blocked: brain.blocked_attempts, skipped: brain.skipped_attempts })}`);
|
|
91
|
+
for (const [p, cd] of Object.entries(brain.provider_cooldown)) {
|
|
92
|
+
if (cd.until > Date.now())
|
|
93
|
+
L.push(` !! ${t(lang, 'doc_cooldown', { name: providers[p]?.label ?? p, status: cd.status, until: new Date(cd.until).toLocaleTimeString() })}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
L.push('');
|
|
97
|
+
if (problems.length) {
|
|
98
|
+
L.push(t(lang, 'doc_bad'));
|
|
99
|
+
for (const p of problems)
|
|
100
|
+
L.push(` - ${p}`);
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
L.push(t(lang, 'doc_good'));
|
|
104
|
+
}
|
|
105
|
+
return { code: problems.length ? 1 : 0, lines: L };
|
|
106
|
+
}
|
package/dist/hooks.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
1
2
|
import { styleText } from 'node:util';
|
|
3
|
+
import { checkUpdate, currentVersion } from './update.js';
|
|
2
4
|
import { evaluate, providerOrder, providers } from './api.js';
|
|
3
5
|
import { freshErrors, loadBrain, loadConfig, saveBrain } from './brain.js';
|
|
4
6
|
import { chunkDiff, filterDiff, pool } from './diff.js';
|
|
@@ -79,6 +81,12 @@ function verdict(lang, signal, v, cfg, color) {
|
|
|
79
81
|
// Test files, snapshots, test runner configs and package.json (test script). Matched on diff headers.
|
|
80
82
|
const TESTISH = /^diff --git a\/.+? b\/(?:.*\/)?(?:(?:tests?|__tests__|spec)\/.*|[^/]*\.(?:test|spec)\.[cm]?[jt]sx?|test_[^/]*\.py|[^/]*_test\.(?:py|go)|[^/]*\.snap|(?:jest|vitest|karma|playwright)\.config\.[^/]*|pytest\.ini|conftest\.py|tox\.ini|package\.json)$/m;
|
|
81
83
|
export const touchesTests = (diff) => TESTISH.test(diff);
|
|
84
|
+
// Pinned diff format: user config (noprefix, color.diff=always, external diff, textconv) would break parsing and masking.
|
|
85
|
+
export const DIFF_ARGS = ['diff', '--cached', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
|
|
86
|
+
export const stagedDiff = (cwd) => execFileSync('git', DIFF_ARGS, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
87
|
+
// Measured 2026-10-02: Cloudflare p50 0.9 s, p95 2.1 s, cold spikes to 3.2 s; OpenRouter p95 0.33 s.
|
|
88
|
+
// A timeout means "let it through unchecked", so wait as long as the git side does rather than fail open.
|
|
89
|
+
export const AGENT_TIMEOUT_MS = 5000;
|
|
82
90
|
// ---------- git-commit ----------
|
|
83
91
|
export async function gitCommit(rawDiff, { root, lang, now }) {
|
|
84
92
|
const cfg = loadConfig(root);
|
|
@@ -134,9 +142,13 @@ export async function gitCommit(rawDiff, { root, lang, now }) {
|
|
|
134
142
|
return out;
|
|
135
143
|
}
|
|
136
144
|
// ---------- pre (Bash / shell command gate, any agent) ----------
|
|
137
|
-
function sessionNotice(brain, sessionId, lang, r, notices) {
|
|
145
|
+
async function sessionNotice(brain, sessionId, lang, r, notices) {
|
|
138
146
|
if (!sessionId || brain.notified_sessions.includes(sessionId))
|
|
139
147
|
return;
|
|
148
|
+
// Piggyback on the once-per-session notice: at most one registry call a day, never extra noise.
|
|
149
|
+
const latest = await checkUpdate();
|
|
150
|
+
if (latest)
|
|
151
|
+
notices.add(t(lang, 'update_available', { latest, current: currentVersion() }));
|
|
140
152
|
brain.notified_sessions = [...brain.notified_sessions, sessionId].slice(-20);
|
|
141
153
|
if (r.ok)
|
|
142
154
|
notices.add(t(lang, 'using', { name: providers[r.provider].label }));
|
|
@@ -162,10 +174,10 @@ export async function agentPre(agent, input, { root, lang, now }) {
|
|
|
162
174
|
}
|
|
163
175
|
const notices = new Set();
|
|
164
176
|
const { sessionId } = input;
|
|
165
|
-
const r = await evaluate({ state, questions, ...(sessionId && { session_id: sessionId }) }, { brain, lang, timeoutMs:
|
|
177
|
+
const r = await evaluate({ state, questions, ...(sessionId && { session_id: sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices, now });
|
|
166
178
|
if (!r.ok)
|
|
167
179
|
brain.skipped_attempts++;
|
|
168
|
-
sessionNotice(brain, sessionId, lang, r, notices);
|
|
180
|
+
await sessionNotice(brain, sessionId, lang, r, notices);
|
|
169
181
|
let out = { code: 0, stderr: [] };
|
|
170
182
|
if (r.ok) {
|
|
171
183
|
for (const s of ['destructive_command', 'infinite_loop']) {
|
package/dist/i18n.js
CHANGED
|
@@ -62,11 +62,17 @@ const messages = {
|
|
|
62
62
|
setup_agent: (v) => `[cto] ${v.label} hooks 已寫入 ${v.path}`,
|
|
63
63
|
uninstall_agent: (v) => `[cto] 已從 ${v.path} 移除 ${v.label} hooks`,
|
|
64
64
|
note_codex_trust: () => '[cto] 注意:Codex 只在專案被信任後才執行 .codex/ 的 hook,第一次在此目錄開 codex 時請選擇信任。',
|
|
65
|
-
|
|
66
|
-
|
|
65
|
+
wiz_intro: () => '\ncto 設定共兩步:1. 選擇要保護的 coding agent 2. 設定 Jev API key\n(git commit 檢查一律安裝,所有 agent 和手動 commit 共用)',
|
|
66
|
+
wiz_step_agents: () => '\n步驟 1/2:要攔截哪些 coding agent 的指令?',
|
|
67
|
+
wiz_agents_hint: () => '輸入編號切換勾選(例如 3 或 1,3),直接 Enter 確認:',
|
|
68
|
+
wiz_invalid: () => ' 看不懂這個輸入,請輸入清單上的編號,例如 1 或 1,3。',
|
|
67
69
|
wiz_found: () => '(已偵測到)',
|
|
68
|
-
|
|
69
|
-
|
|
70
|
+
wiz_step_keys: () => '\n步驟 2/2:Jev API key',
|
|
71
|
+
wiz_keys_present: () => '[cto] 已從環境變數或憑證檔找到 Jev API key,略過這步。要重設請執行 cto setup --keys',
|
|
72
|
+
wiz_keys: (v) => `可用的 provider 如下,至少要設定一個 cto 才會開始檢查。key 存在 ${v.path},只有你的帳號可讀,不會進 git。`,
|
|
73
|
+
wiz_provider_openrouter: () => 'OpenRouter:最簡單,只要一組 API key(openrouter.ai)',
|
|
74
|
+
wiz_provider_cloudflare: () => 'Cloudflare Workers AI:需要 Account ID 與 API token,且帳號的 AI Gateway 要開啟 Authenticated Gateway',
|
|
75
|
+
wiz_providers_hint: () => '要設定哪些?輸入編號(例如 1 或 1,2),直接 Enter 先跳過:',
|
|
70
76
|
wiz_or_key: () => ' OpenRouter API key: ',
|
|
71
77
|
wiz_cf_account: () => ' Cloudflare Account ID: ',
|
|
72
78
|
wiz_cf_token: () => ' Cloudflare API token: ',
|
|
@@ -76,7 +82,37 @@ const messages = {
|
|
|
76
82
|
wiz_save_anyway: () => ' 仍要儲存這組 key 嗎?[y/N] ',
|
|
77
83
|
wiz_saved: (v) => `[cto] key 已儲存到 ${v.path}`,
|
|
78
84
|
wiz_no_keys: () => '[cto] 沒有設定任何 key,cto 會全部放行,之後可執行 cto setup --keys 補上。',
|
|
79
|
-
|
|
85
|
+
doc_version: (v) => `cto ${v.v}`,
|
|
86
|
+
doc_keys: () => 'Jev API key(每個都用一次真實請求驗證):',
|
|
87
|
+
doc_not_set: (v) => `未設定(缺 ${v.keys})`,
|
|
88
|
+
doc_src_file: () => '來自憑證檔',
|
|
89
|
+
doc_src_env: () => '來自環境變數',
|
|
90
|
+
doc_ok: (v) => `可用,${v.ms} ms`,
|
|
91
|
+
doc_slow: (v) => `注意:超過 agent 端 ${v.limit} 秒逾時,這次在 agent 裡會被放行`,
|
|
92
|
+
doc_fail: (v) => `失敗 (${v.status})`,
|
|
93
|
+
doc_hint_cf_401: () => 'token 無效或缺少權限:Account > Workers AI > Read',
|
|
94
|
+
doc_hint_cf_403: () => '到 AI > AI Gateway > default > Settings 開啟 Authenticated Gateway',
|
|
95
|
+
doc_hint_401: () => 'key 無效或已撤銷,請重新產生後執行 cto setup --keys',
|
|
96
|
+
doc_hint_402: () => '額度不足,請到 provider 後台儲值',
|
|
97
|
+
doc_hint_network: () => '連不上或太慢,檢查網路或稍後再試',
|
|
98
|
+
doc_hint_other: () => '非預期的回應,請回報到 github.com/rainday/your-cto-jev/issues',
|
|
99
|
+
doc_repo: (v) => `目前的 repo:${v.root}`,
|
|
100
|
+
doc_no_repo: () => '目前不在 git repo 裡,略過專案檢查。',
|
|
101
|
+
doc_hook_ok: (v) => `git pre-commit 已安裝(${v.path})`,
|
|
102
|
+
doc_hook_missing: () => 'git pre-commit 沒有 cto 區塊,請在此 repo 執行 cto setup',
|
|
103
|
+
doc_agents: (v) => `已接上的 agent:${v.list}`,
|
|
104
|
+
doc_none: () => '無',
|
|
105
|
+
doc_goal_set: () => 'sprint_goal 已設定,架構對齊檢查啟用中',
|
|
106
|
+
doc_goal_empty: () => 'sprint_goal 未設定,架構對齊檢查關閉(可在 .cto.json 填入)',
|
|
107
|
+
doc_stats: (v) => `累計:擋下 ${v.blocked} 次,因無法檢查而放行 ${v.skipped} 次`,
|
|
108
|
+
doc_cooldown: (v) => `${v.name} 冷卻中,原因 ${v.status},到 ${v.until} 才會重試`,
|
|
109
|
+
doc_p_no_provider: () => '沒有任何可用的 provider:現在所有檢查都會直接放行',
|
|
110
|
+
doc_p_provider: (v) => `${v.name} 無法使用`,
|
|
111
|
+
doc_good: () => '[cto] 一切正常,cto 正在保護這個 repo。',
|
|
112
|
+
doc_bad: () => '[cto] 有問題需要處理:',
|
|
113
|
+
update_available: (v) => `[cto] 有新版 ${v.latest}(目前 ${v.current}),執行 cto update 更新`,
|
|
114
|
+
update_done: () => '[cto] 已更新。已設定過的專案不用重跑 cto setup。',
|
|
115
|
+
usage: () => '用法:cto doctor | cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--keys] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
|
|
80
116
|
},
|
|
81
117
|
en: {
|
|
82
118
|
reason_402: () => 'out of credits',
|
|
@@ -110,11 +146,17 @@ const messages = {
|
|
|
110
146
|
setup_agent: (v) => `[cto] ${v.label} hooks written to ${v.path}`,
|
|
111
147
|
uninstall_agent: (v) => `[cto] Removed ${v.label} hooks from ${v.path}`,
|
|
112
148
|
note_codex_trust: () => '[cto] Note: Codex only runs .codex/ hooks once the project is trusted. Trust it the first time you open codex here.',
|
|
113
|
-
|
|
114
|
-
|
|
149
|
+
wiz_intro: () => '\ncto setup has two steps: 1. pick the coding agents to protect 2. set up a Jev API key\n(the git commit check is always installed and covers every agent and manual commits)',
|
|
150
|
+
wiz_step_agents: () => '\nStep 1/2: Which coding agents should have their commands checked?',
|
|
151
|
+
wiz_agents_hint: () => 'Type numbers to toggle (e.g. 3 or 1,3), or press Enter to confirm: ',
|
|
152
|
+
wiz_invalid: () => ' Did not understand that. Type numbers from the list, e.g. 1 or 1,3.',
|
|
115
153
|
wiz_found: () => ' (detected)',
|
|
116
|
-
|
|
117
|
-
|
|
154
|
+
wiz_step_keys: () => '\nStep 2/2: Jev API key',
|
|
155
|
+
wiz_keys_present: () => '[cto] Found a Jev API key in env or the credentials file, skipping this step. Run cto setup --keys to change it.',
|
|
156
|
+
wiz_keys: (v) => `These providers are available. Set up at least one, or cto checks nothing. Keys are stored in ${v.path}, readable only by you, never in git.`,
|
|
157
|
+
wiz_provider_openrouter: () => 'OpenRouter: easiest, one API key (openrouter.ai)',
|
|
158
|
+
wiz_provider_cloudflare: () => 'Cloudflare Workers AI: Account ID plus API token, and Authenticated Gateway must be on in your AI Gateway',
|
|
159
|
+
wiz_providers_hint: () => 'Which ones? Type numbers (e.g. 1 or 1,2), or press Enter to skip for now: ',
|
|
118
160
|
wiz_or_key: () => ' OpenRouter API key: ',
|
|
119
161
|
wiz_cf_account: () => ' Cloudflare Account ID: ',
|
|
120
162
|
wiz_cf_token: () => ' Cloudflare API token: ',
|
|
@@ -124,7 +166,37 @@ const messages = {
|
|
|
124
166
|
wiz_save_anyway: () => ' Save this key anyway? [y/N] ',
|
|
125
167
|
wiz_saved: (v) => `[cto] Keys saved to ${v.path}`,
|
|
126
168
|
wiz_no_keys: () => '[cto] No key set, so cto lets everything through. Run cto setup --keys later.',
|
|
127
|
-
|
|
169
|
+
doc_version: (v) => `cto ${v.v}`,
|
|
170
|
+
doc_keys: () => 'Jev API keys (each verified with one real request):',
|
|
171
|
+
doc_not_set: (v) => `not set (missing ${v.keys})`,
|
|
172
|
+
doc_src_file: () => 'credentials file',
|
|
173
|
+
doc_src_env: () => 'environment',
|
|
174
|
+
doc_ok: (v) => `working, ${v.ms} ms`,
|
|
175
|
+
doc_slow: (v) => `warning: slower than the ${v.limit} s agent timeout, so this check would be skipped inside an agent`,
|
|
176
|
+
doc_fail: (v) => `failed (${v.status})`,
|
|
177
|
+
doc_hint_cf_401: () => 'Token invalid or missing the Account > Workers AI > Read permission',
|
|
178
|
+
doc_hint_cf_403: () => 'Turn on Authenticated Gateway under AI > AI Gateway > default > Settings',
|
|
179
|
+
doc_hint_401: () => 'Key invalid or revoked. Create a new one and run cto setup --keys',
|
|
180
|
+
doc_hint_402: () => 'Out of credits. Top up in the provider dashboard',
|
|
181
|
+
doc_hint_network: () => 'Unreachable or too slow. Check your network or try again later',
|
|
182
|
+
doc_hint_other: () => 'Unexpected response. Please report it at github.com/rainday/your-cto-jev/issues',
|
|
183
|
+
doc_repo: (v) => `Current repo: ${v.root}`,
|
|
184
|
+
doc_no_repo: () => 'Not inside a git repo, skipping project checks.',
|
|
185
|
+
doc_hook_ok: (v) => `git pre-commit installed (${v.path})`,
|
|
186
|
+
doc_hook_missing: () => 'git pre-commit has no cto block. Run cto setup in this repo',
|
|
187
|
+
doc_agents: (v) => `Agents wired up: ${v.list}`,
|
|
188
|
+
doc_none: () => 'none',
|
|
189
|
+
doc_goal_set: () => 'sprint_goal set, architecture check on',
|
|
190
|
+
doc_goal_empty: () => 'sprint_goal empty, architecture check off (set it in .cto.json)',
|
|
191
|
+
doc_stats: (v) => `So far: blocked ${v.blocked}, let through unchecked ${v.skipped}`,
|
|
192
|
+
doc_cooldown: (v) => `${v.name} is cooling down after ${v.status}, retried after ${v.until}`,
|
|
193
|
+
doc_p_no_provider: () => 'No working provider: every check is currently let through',
|
|
194
|
+
doc_p_provider: (v) => `${v.name} is not working`,
|
|
195
|
+
doc_good: () => '[cto] All good. cto is protecting this repo.',
|
|
196
|
+
doc_bad: () => '[cto] Needs attention:',
|
|
197
|
+
update_available: (v) => `[cto] Version ${v.latest} is available (you have ${v.current}). Run cto update`,
|
|
198
|
+
update_done: () => '[cto] Updated. Projects already set up do not need cto setup again.',
|
|
199
|
+
usage: () => 'Usage: cto doctor | cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--keys] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
|
|
128
200
|
},
|
|
129
201
|
};
|
|
130
202
|
export function t(lang, key, vars = {}) {
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,9 @@ import { writeFileSync } from 'node:fs';
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { agentNames, agents } from './agents.js';
|
|
5
5
|
import { applyCredentials, findRoot } from './brain.js';
|
|
6
|
-
import { agentPost, agentPre, gitCommit } from './hooks.js';
|
|
6
|
+
import { agentPost, agentPre, gitCommit, stagedDiff } from './hooks.js';
|
|
7
|
+
import { checkUpdate, currentVersion, runUpdate } from './update.js';
|
|
8
|
+
import { doctor } from './doctor.js';
|
|
7
9
|
import { detectLang, t } from './i18n.js';
|
|
8
10
|
import { maskDiff, maskSensitiveState } from './masker.js';
|
|
9
11
|
import { detectAgents, setup } from './setup.js';
|
|
@@ -25,17 +27,20 @@ function emit(out) {
|
|
|
25
27
|
process.exitCode = out.code;
|
|
26
28
|
}
|
|
27
29
|
async function runHook(name) {
|
|
28
|
-
const raw = await readStdin();
|
|
29
30
|
const lang = detectLang();
|
|
30
31
|
const debug = (root, text) => {
|
|
31
32
|
if (process.env.CTO_DEBUG === '1')
|
|
32
33
|
writeFileSync(join(root, 'debug_stdin.json'), text);
|
|
33
34
|
};
|
|
34
35
|
if (name === 'git-commit') {
|
|
36
|
+
// Read the staged diff ourselves with pinned args. Never touch stdin here: older hook blocks still pipe a diff
|
|
37
|
+
// (ignored, harmless), and an agent's shell may hand us a pipe that never closes.
|
|
35
38
|
const root = findRoot();
|
|
36
|
-
|
|
37
|
-
|
|
39
|
+
const diff = stagedDiff(process.cwd());
|
|
40
|
+
debug(root, maskDiff(diff));
|
|
41
|
+
return gitCommit(diff, { root, lang });
|
|
38
42
|
}
|
|
43
|
+
const raw = await readStdin();
|
|
39
44
|
const m = /^(claude|cursor|gemini|codex)-(pre|post)$/.exec(name);
|
|
40
45
|
if (!m)
|
|
41
46
|
return { code: 0, stderr: [] };
|
|
@@ -96,9 +101,25 @@ else if (args[0] === 'setup') {
|
|
|
96
101
|
chosen = detectAgents();
|
|
97
102
|
}
|
|
98
103
|
const r = setup(process.cwd(), lang, { uninstall, agents: chosen });
|
|
104
|
+
const latest = r.code ? undefined : await checkUpdate();
|
|
105
|
+
if (latest)
|
|
106
|
+
r.lines.push(t(lang, 'update_available', { latest, current: currentVersion() }));
|
|
99
107
|
(r.code ? process.stderr : process.stdout).write(r.lines.join('\n') + '\n');
|
|
100
108
|
process.exitCode = r.code;
|
|
101
109
|
}
|
|
110
|
+
else if (args[0] === 'update') {
|
|
111
|
+
process.exitCode = runUpdate();
|
|
112
|
+
if (!process.exitCode)
|
|
113
|
+
console.log(t(lang, 'update_done'));
|
|
114
|
+
}
|
|
115
|
+
else if (args[0] === 'doctor') {
|
|
116
|
+
const r = await doctor(process.cwd(), lang);
|
|
117
|
+
console.log(r.lines.join('\n'));
|
|
118
|
+
process.exitCode = r.code;
|
|
119
|
+
}
|
|
120
|
+
else if (args[0] === '--version' || args[0] === '-v') {
|
|
121
|
+
console.log(currentVersion());
|
|
122
|
+
}
|
|
102
123
|
else {
|
|
103
124
|
process.stderr.write(t(lang, 'usage') + '\n');
|
|
104
125
|
process.exitCode = args.length ? 1 : 0;
|
package/dist/setup.js
CHANGED
|
@@ -7,9 +7,8 @@ import { DEFAULT_CONFIG } from './brain.js';
|
|
|
7
7
|
import { t } from './i18n.js';
|
|
8
8
|
const START = '# >>> YOUR CTO JEV START >>>';
|
|
9
9
|
const END = '# <<< YOUR CTO JEV END <<<';
|
|
10
|
-
//
|
|
11
|
-
|
|
12
|
-
const HOOK_BODY = `if command -v cto >/dev/null 2>&1; then\n ${DIFF_CMD} | cto --hook git-commit || exit 1\nfi\n`;
|
|
10
|
+
// Keep the block minimal: all logic (including the git diff call) lives in the package, so npm update upgrades every repo.
|
|
11
|
+
const HOOK_BODY = 'if command -v cto >/dev/null 2>&1; then\n cto --hook git-commit || exit 1\nfi\n';
|
|
13
12
|
const IGNORE_BODY = '.cto-brain.json\n.cto-brain.json.*tmp\ndebug_stdin.json\n';
|
|
14
13
|
const OURS = (cmd) => typeof cmd === 'string' && cmd.startsWith('cto --hook ');
|
|
15
14
|
const block = (body) => `${START}\n${body}${END}\n`;
|
package/dist/update.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { credentialsPath } from './brain.js';
|
|
5
|
+
const PKG = 'your-cto-jev';
|
|
6
|
+
const DAY = 86_400_000;
|
|
7
|
+
export const currentVersion = () => JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
8
|
+
/** a > b for plain x.y.z versions. */
|
|
9
|
+
export function newer(a, b) {
|
|
10
|
+
const pa = a.split('.').map(Number), pb = b.split('.').map(Number);
|
|
11
|
+
for (let i = 0; i < 3; i++)
|
|
12
|
+
if ((pa[i] ?? 0) !== (pb[i] ?? 0))
|
|
13
|
+
return (pa[i] ?? 0) > (pb[i] ?? 0);
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
const cachePath = () => join(dirname(credentialsPath()), 'update-check.json');
|
|
17
|
+
/**
|
|
18
|
+
* Latest version if it is newer than this one, else undefined.
|
|
19
|
+
* Hits the npm registry at most once a day (cached next to the credentials file); every failure is silent.
|
|
20
|
+
* CTO_NO_UPDATE_CHECK=1 turns it off.
|
|
21
|
+
*/
|
|
22
|
+
export async function checkUpdate(timeoutMs = 1000, now = Date.now()) {
|
|
23
|
+
if (process.env.CTO_NO_UPDATE_CHECK === '1')
|
|
24
|
+
return undefined;
|
|
25
|
+
let latest;
|
|
26
|
+
try {
|
|
27
|
+
const c = JSON.parse(readFileSync(cachePath(), 'utf8'));
|
|
28
|
+
if (now - c.checked_at < DAY && typeof c.latest === 'string')
|
|
29
|
+
latest = c.latest;
|
|
30
|
+
}
|
|
31
|
+
catch { /* no cache yet */ }
|
|
32
|
+
if (!latest) {
|
|
33
|
+
try {
|
|
34
|
+
const r = await fetch(`https://registry.npmjs.org/${PKG}/latest`, { signal: AbortSignal.timeout(timeoutMs) });
|
|
35
|
+
const v = (await r.json())?.version;
|
|
36
|
+
if (typeof v !== 'string' || !/^\d+\.\d+\.\d+$/.test(v))
|
|
37
|
+
return undefined;
|
|
38
|
+
latest = v;
|
|
39
|
+
mkdirSync(dirname(cachePath()), { recursive: true });
|
|
40
|
+
writeFileSync(cachePath(), JSON.stringify({ checked_at: now, latest }) + '\n');
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return newer(latest, currentVersion()) ? latest : undefined;
|
|
47
|
+
}
|
|
48
|
+
/** npm install -g your-cto-jev@latest, output streamed to the terminal. */
|
|
49
|
+
export function runUpdate() {
|
|
50
|
+
// npm is npm.cmd on Windows, which needs a shell. One constant command string: nothing user-supplied is interpolated.
|
|
51
|
+
const r = spawnSync(`npm install -g ${PKG}@latest`, { stdio: 'inherit', shell: true });
|
|
52
|
+
try {
|
|
53
|
+
writeFileSync(cachePath(), JSON.stringify({ checked_at: 0 }) + '\n');
|
|
54
|
+
}
|
|
55
|
+
catch { /* cache is optional */ }
|
|
56
|
+
return r.status ?? 1;
|
|
57
|
+
}
|
package/dist/wizard.js
CHANGED
|
@@ -56,19 +56,48 @@ export function terminalAsk() {
|
|
|
56
56
|
return { ask, close: () => process.stdin.pause() };
|
|
57
57
|
}
|
|
58
58
|
const yes = (ans, def) => (ans ? /^y/i.test(ans) : def);
|
|
59
|
+
/** Parse "1,3" or "1 3" into 0-based indexes; null if anything is not a number in range. */
|
|
60
|
+
export function parsePicks(input, n) {
|
|
61
|
+
const idx = input.split(/[\s,]+/).filter(Boolean).map((p) => Number(p) - 1);
|
|
62
|
+
return idx.every((i) => Number.isInteger(i) && i >= 0 && i < n) ? [...new Set(idx)] : null;
|
|
63
|
+
}
|
|
64
|
+
const PROVIDER_OPTIONS = ['openrouter', 'cloudflare'];
|
|
59
65
|
/**
|
|
60
|
-
* Interactive setup
|
|
66
|
+
* Interactive setup in two announced steps. Each step shows its full checklist first, so nobody misses an option:
|
|
67
|
+
* 1. Agents: detected ones pre-checked; type numbers to toggle, Enter to confirm.
|
|
68
|
+
* 2. API providers: type numbers to pick, Enter to skip. Keys are asked only for picked providers, then verified.
|
|
61
69
|
* Keys already present in env are kept as-is unless forceKeys.
|
|
62
70
|
*/
|
|
63
71
|
export async function wizard(ask, lang, detected, log, forceKeys = false) {
|
|
64
|
-
log(t(lang, '
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
72
|
+
log(t(lang, 'wiz_intro'));
|
|
73
|
+
// Step 1: agents checklist
|
|
74
|
+
log(t(lang, 'wiz_step_agents'));
|
|
75
|
+
const picked = new Set(detected);
|
|
76
|
+
for (;;) {
|
|
77
|
+
agentNames.forEach((name, i) => {
|
|
78
|
+
const box = picked.has(name) ? '[x]' : '[ ]';
|
|
79
|
+
const found = detected.includes(name) ? t(lang, 'wiz_found') : '';
|
|
80
|
+
log(` ${box} ${i + 1}. ${agents[name].label}${found}`);
|
|
81
|
+
});
|
|
82
|
+
const ans = await ask(t(lang, 'wiz_agents_hint'));
|
|
83
|
+
if (!ans)
|
|
84
|
+
break;
|
|
85
|
+
const idx = parsePicks(ans, agentNames.length);
|
|
86
|
+
if (!idx) {
|
|
87
|
+
log(t(lang, 'wiz_invalid'));
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
for (const i of idx) {
|
|
91
|
+
const n = agentNames[i];
|
|
92
|
+
if (picked.has(n))
|
|
93
|
+
picked.delete(n);
|
|
94
|
+
else
|
|
95
|
+
picked.add(n);
|
|
96
|
+
}
|
|
71
97
|
}
|
|
98
|
+
const chosen = agentNames.filter((n) => picked.has(n));
|
|
99
|
+
// Step 2: API providers checklist
|
|
100
|
+
log(t(lang, 'wiz_step_keys'));
|
|
72
101
|
const env = process.env;
|
|
73
102
|
const hasKey = !!(env.OPENROUTER_API_KEY || (env.CLOUDFLARE_API_TOKEN && env.CLOUDFLARE_ACCOUNT_ID));
|
|
74
103
|
if (hasKey && !forceKeys) {
|
|
@@ -76,6 +105,14 @@ export async function wizard(ask, lang, detected, log, forceKeys = false) {
|
|
|
76
105
|
return chosen;
|
|
77
106
|
}
|
|
78
107
|
log(t(lang, 'wiz_keys', { path: credentialsPath() }));
|
|
108
|
+
PROVIDER_OPTIONS.forEach((p, i) => log(` ${i + 1}. ${t(lang, 'wiz_provider_' + p)}`));
|
|
109
|
+
let which = null;
|
|
110
|
+
while (!which) {
|
|
111
|
+
const ans = await ask(t(lang, 'wiz_providers_hint'));
|
|
112
|
+
which = ans ? parsePicks(ans, PROVIDER_OPTIONS.length) : [];
|
|
113
|
+
if (!which)
|
|
114
|
+
log(t(lang, 'wiz_invalid'));
|
|
115
|
+
}
|
|
79
116
|
const creds = { ...loadCredentials() };
|
|
80
117
|
const tryKey = async (provider, set) => {
|
|
81
118
|
const saved = { ...env };
|
|
@@ -98,14 +135,18 @@ export async function wizard(ask, lang, detected, log, forceKeys = false) {
|
|
|
98
135
|
env[k] = saved[k];
|
|
99
136
|
}
|
|
100
137
|
};
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
138
|
+
for (const i of which) {
|
|
139
|
+
if (PROVIDER_OPTIONS[i] === 'openrouter') {
|
|
140
|
+
const key = await ask(t(lang, 'wiz_or_key'), true);
|
|
141
|
+
if (key)
|
|
142
|
+
await tryKey('openrouter', { OPENROUTER_API_KEY: key });
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
const acc = await ask(t(lang, 'wiz_cf_account'));
|
|
146
|
+
const tok = acc ? await ask(t(lang, 'wiz_cf_token'), true) : '';
|
|
147
|
+
if (acc && tok)
|
|
148
|
+
await tryKey('cloudflare', { CLOUDFLARE_ACCOUNT_ID: acc, CLOUDFLARE_API_TOKEN: tok });
|
|
149
|
+
}
|
|
109
150
|
}
|
|
110
151
|
if (Object.keys(creds).length)
|
|
111
152
|
log(t(lang, 'wiz_saved', { path: saveCredentials(creds) }));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "your-cto-jev",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
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",
|