your-cto-jev 0.2.2 → 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 CHANGED
@@ -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.
@@ -186,7 +193,7 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
186
193
 
187
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.
188
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.
189
- - **Each agent shell command waits about half a second** for Node startup plus one Jev request.
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.
190
197
 
191
198
  ## Development
192
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
- // Cloudflare docs say unwrapped; tolerate a {success, result} envelope anyway.
58
- const out = json?.result?.answers ? json.result : json;
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
@@ -84,6 +84,9 @@ export const touchesTests = (diff) => TESTISH.test(diff);
84
84
  // Pinned diff format: user config (noprefix, color.diff=always, external diff, textconv) would break parsing and masking.
85
85
  export const DIFF_ARGS = ['diff', '--cached', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
86
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;
87
90
  // ---------- git-commit ----------
88
91
  export async function gitCommit(rawDiff, { root, lang, now }) {
89
92
  const cfg = loadConfig(root);
@@ -171,7 +174,7 @@ export async function agentPre(agent, input, { root, lang, now }) {
171
174
  }
172
175
  const notices = new Set();
173
176
  const { sessionId } = input;
174
- const r = await evaluate({ state, questions, ...(sessionId && { session_id: sessionId }) }, { brain, lang, timeoutMs: 2000, notices, now });
177
+ const r = await evaluate({ state, questions, ...(sessionId && { session_id: sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices, now });
175
178
  if (!r.ok)
176
179
  brain.skipped_attempts++;
177
180
  await sessionNotice(brain, sessionId, lang, r, notices);
package/dist/i18n.js CHANGED
@@ -82,9 +82,37 @@ const messages = {
82
82
  wiz_save_anyway: () => ' 仍要儲存這組 key 嗎?[y/N] ',
83
83
  wiz_saved: (v) => `[cto] key 已儲存到 ${v.path}`,
84
84
  wiz_no_keys: () => '[cto] 沒有設定任何 key,cto 會全部放行,之後可執行 cto setup --keys 補上。',
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] 有問題需要處理:',
85
113
  update_available: (v) => `[cto] 有新版 ${v.latest}(目前 ${v.current}),執行 cto update 更新`,
86
114
  update_done: () => '[cto] 已更新。已設定過的專案不用重跑 cto setup。',
87
- usage: () => '用法:cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--keys] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
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>',
88
116
  },
89
117
  en: {
90
118
  reason_402: () => 'out of credits',
@@ -138,9 +166,37 @@ const messages = {
138
166
  wiz_save_anyway: () => ' Save this key anyway? [y/N] ',
139
167
  wiz_saved: (v) => `[cto] Keys saved to ${v.path}`,
140
168
  wiz_no_keys: () => '[cto] No key set, so cto lets everything through. Run cto setup --keys later.',
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:',
141
197
  update_available: (v) => `[cto] Version ${v.latest} is available (you have ${v.current}). Run cto update`,
142
198
  update_done: () => '[cto] Updated. Projects already set up do not need cto setup again.',
143
- usage: () => 'Usage: cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--keys] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
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>',
144
200
  },
145
201
  };
146
202
  export function t(lang, key, vars = {}) {
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { agentNames, agents } from './agents.js';
5
5
  import { applyCredentials, findRoot } from './brain.js';
6
6
  import { agentPost, agentPre, gitCommit, stagedDiff } from './hooks.js';
7
7
  import { checkUpdate, currentVersion, runUpdate } from './update.js';
8
+ import { doctor } from './doctor.js';
8
9
  import { detectLang, t } from './i18n.js';
9
10
  import { maskDiff, maskSensitiveState } from './masker.js';
10
11
  import { detectAgents, setup } from './setup.js';
@@ -111,6 +112,11 @@ else if (args[0] === 'update') {
111
112
  if (!process.exitCode)
112
113
  console.log(t(lang, 'update_done'));
113
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
+ }
114
120
  else if (args[0] === '--version' || args[0] === '-v') {
115
121
  console.log(currentVersion());
116
122
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "your-cto-jev",
3
- "version": "0.2.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",