your-cto-jev 0.1.0 → 0.2.2

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
@@ -31,11 +31,14 @@ Jev judges meaning and answers with probabilities, not prose. It costs about $0.
31
31
  | Signal | Where | What happens |
32
32
  |---|---|---|
33
33
  | `credential_leak` | every `git commit` | **Blocks** the commit |
34
+ | `test_tampering` | `git commit`s that touch tests or test config | **Blocks** the commit |
34
35
  | `destructive_command` | every agent shell command | **Blocks** the command |
35
36
  | `infinite_loop` | agent shell commands, after a recent failure | **Blocks** the command |
36
37
  | `architecture_violation` | `git commit`, once you set a sprint goal | Warns only |
37
38
  | `code_complexity` | every `git commit` | Warns only |
38
39
 
40
+ `test_tampering` catches the classic agent shortcut: making a red test green by skipping it, deleting its assertions, loosening the expectation, or lowering the coverage bar, instead of fixing the code. It lets through real fixes, new or tighter tests, refactors, and tests removed together with their feature.
41
+
39
42
  Architecture and complexity only warn on purpose. They are subjective, and a gate that blocks too often teaches people to use `git commit --no-verify`, which switches off the secret check too.
40
43
 
41
44
  When nothing crosses a threshold, `cto` prints nothing at all.
@@ -55,7 +58,7 @@ flowchart TD
55
58
  P1 -- "error, cooling down or no key" --> P2{"OpenRouter"}
56
59
  P2 -- "answers" --> J
57
60
  P2 -- "error or no key" --> O["Fail open<br/>let it through"]
58
- J -- "secret, destructive or loop" --> X["BLOCK<br/>commit exit 1 · tool call exit 2"]
61
+ J -- "secret, weakened tests,<br/>destructive or loop" --> X["BLOCK<br/>commit exit 1 · tool call exit 2"]
59
62
  J -- "complex or off the sprint goal" --> W["Warn, then allow"]
60
63
  J -- "nothing crosses" --> S["Allow silently"]
61
64
  ```
@@ -72,7 +75,7 @@ cd your-project
72
75
  cto setup
73
76
  ```
74
77
 
75
- Run the same install command again to update.
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.
76
79
 
77
80
  `cto setup` walks you through it in the terminal:
78
81
 
@@ -155,6 +158,7 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
155
158
  "sprint_goal": "",
156
159
  "thresholds": {
157
160
  "credential_leak": 0.5,
161
+ "test_tampering": 0.8,
158
162
  "destructive_command": 0.7,
159
163
  "infinite_loop": 0.85,
160
164
  "architecture_violation": 0.85,
@@ -165,7 +169,8 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
165
169
 
166
170
  - **`sprint_goal`**: fill it in to enable the architecture check, for example `"Ship Stripe billing, no new services"`.
167
171
  - **Thresholds**: Jev returns a probability from 0 to 1. `code_complexity` is the exception: it is a score from 0 (clean) to 4 (unmaintainable).
168
- - **Calibration**: in our tests `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.
172
+ - **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.
173
+ - 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.
169
174
 
170
175
  `.cto-brain.json` holds personal runtime state and is gitignored.
171
176
 
@@ -175,6 +180,7 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
175
180
  | `CTO_FAILOVER=0` | Never switch providers |
176
181
  | `CTO_LANG` | `en` or `zh-TW` (default: your locale) |
177
182
  | `CTO_DEBUG=1` | Write masked hook input to `debug_stdin.json` |
183
+ | `CTO_NO_UPDATE_CHECK=1` | Never check npm for a new version |
178
184
 
179
185
  ## Known limitations
180
186
 
package/dist/brain.js CHANGED
@@ -8,6 +8,7 @@ export const DEFAULT_CONFIG = {
8
8
  destructive_command: 0.7,
9
9
  infinite_loop: 0.85,
10
10
  architecture_violation: 0.85,
11
+ test_tampering: 0.8,
11
12
  code_complexity: 2,
12
13
  },
13
14
  };
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';
@@ -32,6 +34,20 @@ const Q = {
32
34
  false: 'A new approach, a fix attempt, or unrelated to the earlier failures',
33
35
  },
34
36
  },
37
+ test_tampering: {
38
+ type: 'noul',
39
+ instructions: 'Does this git diff weaken the test suite to make failures disappear, rather than fixing the code under test? ' +
40
+ 'Weakening includes: skipping or commenting out tests, deleting assertions or whole tests while the code they cover stays, ' +
41
+ 'replacing exact expectations with vague ones, changing an expected value to match current output without changing the code, ' +
42
+ 'swallowing errors the test should check, or lowering coverage thresholds. ' +
43
+ 'Not weakening: fixing source code, adding or tightening tests, refactoring tests without losing checks, ' +
44
+ 'updating expectations together with an intentional source change, removing tests together with the feature they cover, ' +
45
+ 'or a conditional skip with a concrete reason and alternative coverage.',
46
+ criteria: {
47
+ true: 'The diff reduces what the tests verify without a matching intentional code change',
48
+ false: 'The tests verify as much or more, or changed together with the code they cover',
49
+ },
50
+ },
35
51
  code_complexity: {
36
52
  type: 'score',
37
53
  instructions: 'Rate the maintenance cost and structural complexity of this change.',
@@ -62,6 +78,12 @@ function verdict(lang, signal, v, cfg, color) {
62
78
  const s = (fmt, txt) => styleText(fmt, txt, { stream: process.stderr });
63
79
  return [s([color, 'bold'], head), s('dim', detail)];
64
80
  }
81
+ // Test files, snapshots, test runner configs and package.json (test script). Matched on diff headers.
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;
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'] });
65
87
  // ---------- git-commit ----------
66
88
  export async function gitCommit(rawDiff, { root, lang, now }) {
67
89
  const cfg = loadConfig(root);
@@ -76,8 +98,15 @@ export async function gitCommit(rawDiff, { root, lang, now }) {
76
98
  soft.architecture_violation = architectureQ(cfg.sprint_goal.trim());
77
99
  const notices = new Set();
78
100
  const ctx = { brain, lang, timeoutMs: 5000, notices, now };
79
- // Credential check on every chunk (no sampling); soft signals on the first chunk only. Max 3 in flight.
80
- const results = await pool(chunks, 3, (state, i) => evaluate({ state, questions: i === 0 ? { credential_leak: Q.credential_leak, ...soft } : { credential_leak: Q.credential_leak } }, ctx));
101
+ // 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.
102
+ const results = await pool(chunks, 3, (state, i) => evaluate({
103
+ state,
104
+ questions: {
105
+ credential_leak: Q.credential_leak,
106
+ ...(touchesTests(state) && { test_tampering: Q.test_tampering }),
107
+ ...(i === 0 && soft),
108
+ },
109
+ }, ctx));
81
110
  if (results.some((r) => !r.ok))
82
111
  brain.skipped_attempts++;
83
112
  if (results.some((r) => !r.ok && r.reason === 'no_keys'))
@@ -88,12 +117,15 @@ export async function gitCommit(rawDiff, { root, lang, now }) {
88
117
  if (r.ok && r.provider !== primary)
89
118
  notices.add(t(lang, 'using', { name: providers[r.provider].label }));
90
119
  const lines = [];
91
- const leaks = results.flatMap((r) => (r.ok ? [exceeded(r.answers, 'credential_leak', cfg)] : [])).filter((v) => v !== undefined);
92
- if (leaks.length) {
120
+ for (const s of ['credential_leak', 'test_tampering']) {
121
+ const hits = results.flatMap((r) => (r.ok ? [exceeded(r.answers, s, cfg)] : [])).filter((v) => v !== undefined);
122
+ if (!hits.length)
123
+ continue;
93
124
  out.code = 1;
94
- brain.blocked_attempts++;
95
- lines.push(...verdict(lang, 'credential_leak', Math.max(...leaks), cfg, 'red'));
125
+ lines.push(...verdict(lang, s, Math.max(...hits), cfg, 'red'));
96
126
  }
127
+ if (out.code)
128
+ brain.blocked_attempts++;
97
129
  const first = results[0];
98
130
  if (first?.ok) {
99
131
  for (const s of ['architecture_violation', 'code_complexity']) {
@@ -107,9 +139,13 @@ export async function gitCommit(rawDiff, { root, lang, now }) {
107
139
  return out;
108
140
  }
109
141
  // ---------- pre (Bash / shell command gate, any agent) ----------
110
- function sessionNotice(brain, sessionId, lang, r, notices) {
142
+ async function sessionNotice(brain, sessionId, lang, r, notices) {
111
143
  if (!sessionId || brain.notified_sessions.includes(sessionId))
112
144
  return;
145
+ // Piggyback on the once-per-session notice: at most one registry call a day, never extra noise.
146
+ const latest = await checkUpdate();
147
+ if (latest)
148
+ notices.add(t(lang, 'update_available', { latest, current: currentVersion() }));
113
149
  brain.notified_sessions = [...brain.notified_sessions, sessionId].slice(-20);
114
150
  if (r.ok)
115
151
  notices.add(t(lang, 'using', { name: providers[r.provider].label }));
@@ -138,7 +174,7 @@ export async function agentPre(agent, input, { root, lang, now }) {
138
174
  const r = await evaluate({ state, questions, ...(sessionId && { session_id: sessionId }) }, { brain, lang, timeoutMs: 2000, notices, now });
139
175
  if (!r.ok)
140
176
  brain.skipped_attempts++;
141
- sessionNotice(brain, sessionId, lang, r, notices);
177
+ await sessionNotice(brain, sessionId, lang, r, notices);
142
178
  let out = { code: 0, stderr: [] };
143
179
  if (r.ok) {
144
180
  for (const s of ['destructive_command', 'infinite_loop']) {
package/dist/i18n.js CHANGED
@@ -17,6 +17,7 @@ export const personaDict = {
17
17
  destructive_command: '停手。這個指令有不可逆的破壞性,這次不准執行。',
18
18
  infinite_loop: '同樣的錯誤又來了,你們在鬼打牆燒 Token。這次工具呼叫我擋下了,先去看邏輯。',
19
19
  architecture_violation: '這次變更偏離了 Sprint 目標。我放你過,但這筆帳記著。',
20
+ test_tampering: '程式沒修好,倒先把測試改弱了?Commit 已攔下。去修程式,不是修測試。',
20
21
  code_complexity: '複雜度超標,過度工程化。這次不擋,但趕快重構。',
21
22
  },
22
23
  en: {
@@ -24,6 +25,7 @@ export const personaDict = {
24
25
  destructive_command: 'Hold it. This command is irreversibly destructive. Not running it.',
25
26
  infinite_loop: 'Same error again. You are looping and burning tokens. This tool call is BLOCKED. Fix the logic first.',
26
27
  architecture_violation: 'This change drifts from the sprint goal. Letting it through, but I noticed.',
28
+ test_tampering: 'Weakening the tests instead of fixing the code? Commit BLOCKED. Fix the code, not the tests.',
27
29
  code_complexity: 'Over-engineered. Not blocking this time, but refactor it.',
28
30
  },
29
31
  };
@@ -60,11 +62,17 @@ const messages = {
60
62
  setup_agent: (v) => `[cto] ${v.label} hooks 已寫入 ${v.path}`,
61
63
  uninstall_agent: (v) => `[cto] 已從 ${v.path} 移除 ${v.label} hooks`,
62
64
  note_codex_trust: () => '[cto] 注意:Codex 只在專案被信任後才執行 .codex/ 的 hook,第一次在此目錄開 codex 時請選擇信任。',
63
- wiz_agents: () => '\n要為哪些 coding agent 安裝指令攔截?(git commit 檢查一律安裝,所有 agent 共用)',
64
- wiz_agent_q: (v) => ` ${v.label}${v.found} [${v.hint}] `,
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。',
65
69
  wiz_found: () => '(已偵測到)',
66
- wiz_keys_present: () => '[cto] 已從環境變數或憑證檔找到 Jev API key,略過金鑰設定。要重設請執行 cto setup --keys',
67
- wiz_keys: (v) => `\n設定 Jev API key(至少一組,直接 Enter 跳過)。key 存在 ${v.path},只有你的帳號可讀,不會進 git。`,
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 先跳過:',
68
76
  wiz_or_key: () => ' OpenRouter API key: ',
69
77
  wiz_cf_account: () => ' Cloudflare Account ID: ',
70
78
  wiz_cf_token: () => ' Cloudflare API token: ',
@@ -74,7 +82,9 @@ const messages = {
74
82
  wiz_save_anyway: () => ' 仍要儲存這組 key 嗎?[y/N] ',
75
83
  wiz_saved: (v) => `[cto] key 已儲存到 ${v.path}`,
76
84
  wiz_no_keys: () => '[cto] 沒有設定任何 key,cto 會全部放行,之後可執行 cto setup --keys 補上。',
77
- usage: () => '用法:cto setup [--agents claude,cursor,gemini,codex] [--keys] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
85
+ update_available: (v) => `[cto] 有新版 ${v.latest}(目前 ${v.current}),執行 cto update 更新`,
86
+ 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>',
78
88
  },
79
89
  en: {
80
90
  reason_402: () => 'out of credits',
@@ -108,11 +118,17 @@ const messages = {
108
118
  setup_agent: (v) => `[cto] ${v.label} hooks written to ${v.path}`,
109
119
  uninstall_agent: (v) => `[cto] Removed ${v.label} hooks from ${v.path}`,
110
120
  note_codex_trust: () => '[cto] Note: Codex only runs .codex/ hooks once the project is trusted. Trust it the first time you open codex here.',
111
- wiz_agents: () => '\nWhich coding agents should get command interception? (the git commit check is always installed and covers every agent)',
112
- wiz_agent_q: (v) => ` ${v.label}${v.found} [${v.hint}] `,
121
+ 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)',
122
+ wiz_step_agents: () => '\nStep 1/2: Which coding agents should have their commands checked?',
123
+ wiz_agents_hint: () => 'Type numbers to toggle (e.g. 3 or 1,3), or press Enter to confirm: ',
124
+ wiz_invalid: () => ' Did not understand that. Type numbers from the list, e.g. 1 or 1,3.',
113
125
  wiz_found: () => ' (detected)',
114
- wiz_keys_present: () => '[cto] Found a Jev API key in env or the credentials file, skipping key setup. Run cto setup --keys to change it.',
115
- wiz_keys: (v) => `\nSet up a Jev API key (at least one; press Enter to skip). Keys are stored in ${v.path}, readable only by you, never in git.`,
126
+ wiz_step_keys: () => '\nStep 2/2: Jev API key',
127
+ 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.',
128
+ 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.`,
129
+ wiz_provider_openrouter: () => 'OpenRouter: easiest, one API key (openrouter.ai)',
130
+ wiz_provider_cloudflare: () => 'Cloudflare Workers AI: Account ID plus API token, and Authenticated Gateway must be on in your AI Gateway',
131
+ wiz_providers_hint: () => 'Which ones? Type numbers (e.g. 1 or 1,2), or press Enter to skip for now: ',
116
132
  wiz_or_key: () => ' OpenRouter API key: ',
117
133
  wiz_cf_account: () => ' Cloudflare Account ID: ',
118
134
  wiz_cf_token: () => ' Cloudflare API token: ',
@@ -122,7 +138,9 @@ const messages = {
122
138
  wiz_save_anyway: () => ' Save this key anyway? [y/N] ',
123
139
  wiz_saved: (v) => `[cto] Keys saved to ${v.path}`,
124
140
  wiz_no_keys: () => '[cto] No key set, so cto lets everything through. Run cto setup --keys later.',
125
- usage: () => 'Usage: cto setup [--agents claude,cursor,gemini,codex] [--keys] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
141
+ update_available: (v) => `[cto] Version ${v.latest} is available (you have ${v.current}). Run cto update`,
142
+ 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>',
126
144
  },
127
145
  };
128
146
  export function t(lang, key, vars = {}) {
package/dist/index.js CHANGED
@@ -3,7 +3,8 @@ 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';
7
8
  import { detectLang, t } from './i18n.js';
8
9
  import { maskDiff, maskSensitiveState } from './masker.js';
9
10
  import { detectAgents, setup } from './setup.js';
@@ -25,17 +26,20 @@ function emit(out) {
25
26
  process.exitCode = out.code;
26
27
  }
27
28
  async function runHook(name) {
28
- const raw = await readStdin();
29
29
  const lang = detectLang();
30
30
  const debug = (root, text) => {
31
31
  if (process.env.CTO_DEBUG === '1')
32
32
  writeFileSync(join(root, 'debug_stdin.json'), text);
33
33
  };
34
34
  if (name === 'git-commit') {
35
+ // Read the staged diff ourselves with pinned args. Never touch stdin here: older hook blocks still pipe a diff
36
+ // (ignored, harmless), and an agent's shell may hand us a pipe that never closes.
35
37
  const root = findRoot();
36
- debug(root, maskDiff(raw));
37
- return gitCommit(raw, { root, lang });
38
+ const diff = stagedDiff(process.cwd());
39
+ debug(root, maskDiff(diff));
40
+ return gitCommit(diff, { root, lang });
38
41
  }
42
+ const raw = await readStdin();
39
43
  const m = /^(claude|cursor|gemini|codex)-(pre|post)$/.exec(name);
40
44
  if (!m)
41
45
  return { code: 0, stderr: [] };
@@ -85,6 +89,9 @@ else if (args[0] === 'setup') {
85
89
  try {
86
90
  chosen = await wizard(ask, lang, detectAgents(), (s) => console.log(s), args.includes('--keys'));
87
91
  }
92
+ catch {
93
+ process.exit(130); // Ctrl+C or closed input: stop quietly, nothing has been written yet
94
+ }
88
95
  finally {
89
96
  close();
90
97
  }
@@ -93,9 +100,20 @@ else if (args[0] === 'setup') {
93
100
  chosen = detectAgents();
94
101
  }
95
102
  const r = setup(process.cwd(), lang, { uninstall, agents: chosen });
103
+ const latest = r.code ? undefined : await checkUpdate();
104
+ if (latest)
105
+ r.lines.push(t(lang, 'update_available', { latest, current: currentVersion() }));
96
106
  (r.code ? process.stderr : process.stdout).write(r.lines.join('\n') + '\n');
97
107
  process.exitCode = r.code;
98
108
  }
109
+ else if (args[0] === 'update') {
110
+ process.exitCode = runUpdate();
111
+ if (!process.exitCode)
112
+ console.log(t(lang, 'update_done'));
113
+ }
114
+ else if (args[0] === '--version' || args[0] === '-v') {
115
+ console.log(currentVersion());
116
+ }
99
117
  else {
100
118
  process.stderr.write(t(lang, 'usage') + '\n');
101
119
  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
- // Pin the diff format: user config (noprefix, color.diff=always, external diff, textconv) would break parsing and masking.
11
- export const DIFF_CMD = 'git diff --cached --no-color --no-ext-diff --no-textconv --src-prefix=a/ --dst-prefix=b/';
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
@@ -3,43 +3,101 @@ import { agentNames, agents } from './agents.js';
3
3
  import { probeProvider, providers } from './api.js';
4
4
  import { credentialsPath, loadCredentials, saveCredentials } from './brain.js';
5
5
  import { t } from './i18n.js';
6
- /** Terminal prompt; hidden input echoes nothing (for keys). */
6
+ /**
7
+ * Read a line without echoing it (for keys). Public APIs only: raw mode + our own key handling.
8
+ * Enter submits, Backspace deletes, Ctrl+C aborts; escape sequences such as bracketed paste markers are dropped.
9
+ */
10
+ export function readHidden(q, input = process.stdin, output = process.stdout) {
11
+ return new Promise((resolve, reject) => {
12
+ output.write(q);
13
+ let buf = '';
14
+ const finish = (err) => {
15
+ input.removeListener('data', onData);
16
+ input.setRawMode?.(false);
17
+ input.pause();
18
+ output.write('\n');
19
+ if (err)
20
+ reject(err);
21
+ else
22
+ resolve(buf.trim());
23
+ };
24
+ const onData = (chunk) => {
25
+ const s = String(chunk).replace(/\x1b\[[0-9;]*[~A-Za-z]/g, '');
26
+ for (const ch of s) {
27
+ if (ch === '\r' || ch === '\n')
28
+ return finish();
29
+ if (ch === '\u0003')
30
+ return finish(new Error('aborted'));
31
+ if (ch === '\u007f' || ch === '\b')
32
+ buf = buf.slice(0, -1);
33
+ else if (ch >= ' ')
34
+ buf += ch;
35
+ }
36
+ };
37
+ input.setRawMode?.(true);
38
+ input.setEncoding('utf8');
39
+ input.on('data', onData);
40
+ input.resume();
41
+ });
42
+ }
43
+ /** Terminal prompts. A fresh readline per visible question, so it never fights raw-mode hidden input. */
7
44
  export function terminalAsk() {
8
- const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
9
- const anyRl = rl;
10
- const write = anyRl._writeToOutput.bind(rl);
11
- let muted = false;
12
- anyRl._writeToOutput = (s) => { if (!muted)
13
- write(s); };
14
45
  const ask = async (q, hidden = false) => {
15
- if (!hidden)
16
- return (await rl.question(q)).trim();
17
- process.stdout.write(q);
18
- muted = true;
46
+ if (hidden)
47
+ return readHidden(q);
48
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
19
49
  try {
20
- return (await rl.question('')).trim();
50
+ return (await rl.question(q)).trim();
21
51
  }
22
52
  finally {
23
- muted = false;
24
- process.stdout.write('\n');
53
+ rl.close();
25
54
  }
26
55
  };
27
- return { ask, close: () => rl.close() };
56
+ return { ask, close: () => process.stdin.pause() };
28
57
  }
29
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'];
30
65
  /**
31
- * Interactive setup: pick agents (detected ones default to yes), then enter and verify keys.
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.
32
69
  * Keys already present in env are kept as-is unless forceKeys.
33
70
  */
34
71
  export async function wizard(ask, lang, detected, log, forceKeys = false) {
35
- log(t(lang, 'wiz_agents'));
36
- const chosen = [];
37
- for (const name of agentNames) {
38
- const def = detected.includes(name);
39
- const ans = await ask(t(lang, 'wiz_agent_q', { label: agents[name].label, hint: def ? 'Y/n' : 'y/N', found: def ? t(lang, 'wiz_found') : '' }));
40
- if (yes(ans, def))
41
- chosen.push(name);
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
+ }
42
97
  }
98
+ const chosen = agentNames.filter((n) => picked.has(n));
99
+ // Step 2: API providers checklist
100
+ log(t(lang, 'wiz_step_keys'));
43
101
  const env = process.env;
44
102
  const hasKey = !!(env.OPENROUTER_API_KEY || (env.CLOUDFLARE_API_TOKEN && env.CLOUDFLARE_ACCOUNT_ID));
45
103
  if (hasKey && !forceKeys) {
@@ -47,6 +105,14 @@ export async function wizard(ask, lang, detected, log, forceKeys = false) {
47
105
  return chosen;
48
106
  }
49
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
+ }
50
116
  const creds = { ...loadCredentials() };
51
117
  const tryKey = async (provider, set) => {
52
118
  const saved = { ...env };
@@ -69,14 +135,18 @@ export async function wizard(ask, lang, detected, log, forceKeys = false) {
69
135
  env[k] = saved[k];
70
136
  }
71
137
  };
72
- const or = await ask(t(lang, 'wiz_or_key'), true);
73
- if (or)
74
- await tryKey('openrouter', { OPENROUTER_API_KEY: or });
75
- const acc = await ask(t(lang, 'wiz_cf_account'));
76
- if (acc) {
77
- const tok = await ask(t(lang, 'wiz_cf_token'), true);
78
- if (tok)
79
- await tryKey('cloudflare', { CLOUDFLARE_ACCOUNT_ID: acc, CLOUDFLARE_API_TOKEN: tok });
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
+ }
80
150
  }
81
151
  if (Object.keys(creds).length)
82
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.1.0",
3
+ "version": "0.2.2",
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",