your-cto-jev 0.6.0 → 0.8.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/dist/doctor.js CHANGED
@@ -6,7 +6,7 @@ import { probeProvider, providerOrder, providers } from './api.js';
6
6
  import { loadBrain, loadConfig, loadCredentials } from './brain.js';
7
7
  import { AGENT_TIMEOUT_MS } from './hooks.js';
8
8
  import { t } from './i18n.js';
9
- import { ignoredByGit, missingHooks, wiredAgents } from './setup.js';
9
+ import { GIT_HOOKS, conflictLines, ignoredByGit, missingHooks, wiredAgents } from './setup.js';
10
10
  import { guidancePaths, staleGuidance } from './skill.js';
11
11
  import { checkUpdate, currentVersion } from './update.js';
12
12
  function hint(provider, status) {
@@ -82,13 +82,15 @@ export async function doctor(cwd, lang, slowMs = AGENT_TIMEOUT_MS) {
82
82
  else {
83
83
  L.push('', t(lang, 'doc_repo', { root }));
84
84
  const hooksDir = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-path', 'hooks'], { cwd: root, encoding: 'utf8' }).trim();
85
- const hookPath = join(hooksDir, 'pre-commit');
86
- const hook = existsSync(hookPath) ? readFileSync(hookPath, 'utf8') : '';
87
- if (hook.includes('YOUR CTO JEV START'))
88
- L.push(` OK ${t(lang, 'doc_hook_ok', { path: hookPath })}`);
89
- else {
90
- L.push(` !! ${t(lang, 'doc_hook_missing')}`);
91
- problems.push(t(lang, 'doc_hook_missing'));
85
+ for (const [name] of GIT_HOOKS) {
86
+ const hookPath = join(hooksDir, name);
87
+ const hook = existsSync(hookPath) ? readFileSync(hookPath, 'utf8') : '';
88
+ if (hook.includes('YOUR CTO JEV START'))
89
+ L.push(` OK ${t(lang, 'doc_hook_ok', { name, path: hookPath })}`);
90
+ else {
91
+ L.push(` !! ${t(lang, 'doc_hook_missing', { name })}`);
92
+ problems.push(t(lang, 'doc_hook_missing', { name }));
93
+ }
92
94
  }
93
95
  const wired = wiredAgents(root);
94
96
  L.push(` ${wired.length ? 'OK' : '--'} ${t(lang, 'doc_agents', { list: wired.map((n) => agents[n].label).join(', ') || t(lang, 'doc_none') })}`);
@@ -103,6 +105,7 @@ export async function doctor(cwd, lang, slowMs = AGENT_TIMEOUT_MS) {
103
105
  }
104
106
  const cfg = loadConfig(root);
105
107
  L.push(` -- ${t(lang, cfg.sprint_goal.trim() ? 'doc_goal_set' : 'doc_goal_empty')}`);
108
+ L.push(...conflictLines(root, wired, lang).map((l) => ` ${l}`));
106
109
  const brain = loadBrain(root);
107
110
  L.push(` -- ${t(lang, 'doc_stats', { blocked: brain.blocked_attempts, skipped: brain.skipped_attempts })}`);
108
111
  if (brain.last_check_at) {
package/dist/hooks.js CHANGED
@@ -1,13 +1,19 @@
1
1
  import { execFileSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
2
4
  import { styleText } from 'node:util';
3
5
  import { checkUpdate, currentVersion } from './update.js';
4
- import { isCodeFile, turnActions, turnState } from './turn.js';
6
+ import { isCodeFile, tickedItems, tickedKey, turnActions, turnState } from './turn.js';
7
+ import { shellWrites } from './shellwrites.js';
5
8
  import { evaluate, providerOrder, providers } from './api.js';
6
- import { freshErrors, loadBrain, loadConfig, saveBrain } from './brain.js';
9
+ import { DECISIONS_KEPT, DECISION_STATE_CHARS, freshErrors, loadBrain, loadConfig, saveBrain } from './brain.js';
7
10
  import { chunkDiff, filterDiff, pool } from './diff.js';
8
11
  import { personaDict, t } from './i18n.js';
9
12
  import { maskDiff, maskSensitiveState } from './masker.js';
10
- const Q = {
13
+ import { loadLessons, recordFailure, resolveFromTurn, saveLessons } from './lessons.js';
14
+ import { localCommitChecks, localPushChecks } from './local.js';
15
+ // Exported so the calibration script (scripts/calibrate.mjs) measures exactly the questions that ship.
16
+ export const Q = {
11
17
  credential_leak: {
12
18
  type: 'noul',
13
19
  instructions: 'Does this git diff add a real secret (API key, token, password, private key) to the repository? ' +
@@ -55,12 +61,19 @@ const Q = {
55
61
  },
56
62
  // Calibrated 2026-10-05 on 21 hand-written turns: unverified >= 0.71 except a test run in the wrong package (0.17);
57
63
  // verified <= 0.24. Needs the computed "Fact" line: without it, tests run before the last edit scored 0.25.
64
+ // 2026-10-06, +10 plan-checklist turns from real spec-kit/GSD/specOS plans: unsupported ticks 0.75-0.95, supported
65
+ // 0.11-0.30 (a parent whose nested items are all checked: 0.30). A parent ticked over open nested items scored 0.60
66
+ // until the open-nested-items Fact was added (0.75).
58
67
  done_unverified: {
59
68
  type: 'noul',
60
69
  instructions: 'A coding agent is ending its turn. Did it change code and stop without verifying that change, or claim more than its actions show? ' +
61
70
  'Unverified: no test, build, or type check ran after the last code edit; or the last such run failed; ' +
62
- 'or the final message claims passing tests, a working result, or a manual check that the action log does not support. ' +
63
- 'Not unverified: a relevant check ran after the last edit and passed; the turn changed no code, or only docs or config; ' +
71
+ 'or the final message claims passing tests, a working result, or a manual check that the action log does not support; ' +
72
+ 'or it marked plan checklist items done that its actions do not support. ' +
73
+ 'A summary item (a phase, milestone, or an item with nested items) records work finished over earlier turns: ' +
74
+ 'it is supported when its nested items are all checked, or when this turn ran a passing check that covers it; ' +
75
+ 'it is unsupported when nested items are still open. ' +
76
+ 'Not unverified: a relevant check ran after the last edit and passed; the turn changed no code, or only docs or config, and marked nothing done that needed code; ' +
64
77
  'or the agent plainly told the user what is not verified yet and why.',
65
78
  criteria: {
66
79
  true: 'The work is presented as done but the action log does not show it was verified',
@@ -103,11 +116,30 @@ export const touchesTests = (diff) => TESTISH.test(diff);
103
116
  // Pinned diff format: user config (noprefix, color.diff=always, external diff, textconv) would break parsing and masking.
104
117
  export const DIFF_ARGS = ['diff', '--cached', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
105
118
  export const stagedDiff = (cwd) => execFileSync('git', DIFF_ARGS, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
119
+ /** Uncommitted changes (staged and not) to tracked markdown files, for checklist ticks. Empty outside git or before the first commit. */
120
+ export function planDiff(cwd) {
121
+ try {
122
+ return execFileSync('git', ['diff', 'HEAD', ...DIFF_ARGS.slice(2), '--', '*.md', '*.mdx'], { cwd, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
123
+ }
124
+ catch {
125
+ return '';
126
+ }
127
+ }
106
128
  // 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
129
  // A timeout means "let it through unchecked", so wait as long as the git side does rather than fail open.
108
130
  export const AGENT_TIMEOUT_MS = 5000;
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) {
131
+ /** Remember every answered yes/no question (score questions have no right answer to report). Keeps the last 30. */
132
+ export function logDecision(brain, hook, state, answers, cfg, now) {
133
+ const at = new Date((now ?? Date.now)()).toISOString();
134
+ for (const [k, a] of Object.entries(answers)) {
135
+ if (a?.type !== 'noul' || !(k in cfg.thresholds))
136
+ continue;
137
+ const signal = k;
138
+ brain.decisions = [...(brain.decisions ?? []), { at, hook, signal, value: a.noul, threshold: cfg.thresholds[signal], state: state.slice(0, DECISION_STATE_CHARS) }].slice(-DECISIONS_KEPT);
139
+ }
140
+ }
141
+ /** Run the commit checks on a diff. Shared by the git hook and `cto check`. Mutates brain for provider state and the decision log. */
142
+ export async function reviewDiff(rawDiff, cfg, brain, lang, now, hook = 'commit') {
111
143
  const files = filterDiff(maskDiff(rawDiff));
112
144
  if (!files.length)
113
145
  return null;
@@ -130,6 +162,8 @@ export async function reviewDiff(rawDiff, cfg, brain, lang, now) {
130
162
  return evaluate({ state, questions }, ctx);
131
163
  });
132
164
  const scores = {};
165
+ results.forEach((r, i) => { if (r.ok)
166
+ logDecision(brain, hook, chunks[i], r.answers, cfg, now); });
133
167
  for (const r of results) {
134
168
  if (!r.ok)
135
169
  continue;
@@ -152,18 +186,26 @@ export async function reviewDiff(rawDiff, cfg, brain, lang, now) {
152
186
  export const BLOCKING_COMMIT = ['credential_leak', 'test_tampering'];
153
187
  export const WARNING_COMMIT = ['architecture_violation', 'code_complexity'];
154
188
  const over = (v, s, cfg) => v !== undefined && v > cfg.thresholds[s];
189
+ export const localLines = (lang, findings) => findings.map((f) => t(lang, `local_${f.kind}`, { detail: f.detail }));
155
190
  export async function gitCommit(rawDiff, { root, lang, now }) {
156
191
  const cfg = loadConfig(root);
157
192
  const brain = loadBrain(root);
158
193
  const out = { code: 0, stderr: [] };
194
+ // Local checks first: a commit they block never reaches Jev, and they work without any key.
195
+ const local = localCommitChecks(rawDiff, cfg, root);
196
+ if (local.some((f) => f.block)) {
197
+ brain.blocked_attempts++;
198
+ saveBrain(root, brain);
199
+ return { code: 1, stderr: localLines(lang, local.filter((f) => f.block)) };
200
+ }
159
201
  const review = await reviewDiff(rawDiff, cfg, brain, lang, now);
160
202
  if (!review)
161
- return out;
203
+ return { ...out, stderr: localLines(lang, local) };
162
204
  if (review.failed)
163
205
  brain.skipped_attempts++;
164
206
  if (Object.keys(review.scores).length)
165
207
  countCheck(brain, now);
166
- const lines = [];
208
+ const lines = localLines(lang, local);
167
209
  for (const s of BLOCKING_COMMIT) {
168
210
  if (!over(review.scores[s], s, cfg))
169
211
  continue;
@@ -179,6 +221,16 @@ export async function gitCommit(rawDiff, { root, lang, now }) {
179
221
  saveBrain(root, brain);
180
222
  return out;
181
223
  }
224
+ /** pre-push: protected branches cannot be deleted or force-pushed. Local only. */
225
+ export function gitPush(stdin, { root, lang }) {
226
+ const findings = localPushChecks(stdin, loadConfig(root), root);
227
+ if (!findings.length)
228
+ return { code: 0, stderr: [] };
229
+ const brain = loadBrain(root);
230
+ brain.blocked_attempts++;
231
+ saveBrain(root, brain);
232
+ return { code: 1, stderr: localLines(lang, findings) };
233
+ }
182
234
  /** Bookkeeping for `cto doctor`: how many checks Jev actually answered, and when the last one was. */
183
235
  export function countCheck(brain, now) {
184
236
  brain.checks = (brain.checks ?? 0) + 1;
@@ -208,23 +260,33 @@ export async function agentPre(agent, input, { root, lang, now }) {
208
260
  const brain = loadBrain(root);
209
261
  const questions = { destructive_command: Q.destructive_command };
210
262
  let state = maskSensitiveState(command);
263
+ // A command that writes code files (sed -i, redirects, formatters) is a fix attempt, same as an edit tool. Marked
264
+ // before it runs: pre hooks exist for every agent, so this also covers agents without a usable edit event.
265
+ const written = shellWrites(command);
266
+ if (input.sessionId && !agent.transcriptTurns && agent.stop) {
267
+ for (const f of written)
268
+ logAction(brain, input.sessionId, { kind: 'edit', file: f === '?' ? `(files written by: ${command.slice(0, 60)})` : f });
269
+ logAction(brain, input.sessionId, { kind: 'run', command: maskSensitiveState(command), ok: true, tail: '' });
270
+ }
271
+ if (written.length && (written.includes('?') || written.some(isCodeFile)) && brain.recent_errors.some((e) => !e.edited_after)) {
272
+ brain.recent_errors = brain.recent_errors.map((e) => ({ ...e, edited_after: true }));
273
+ }
211
274
  const recent = freshErrors(brain, (now ?? Date.now)());
212
275
  // One block per loop episode: once warned about the latest failure, the next attempt may run (it may be the real fix).
213
276
  // A new failure after that is unwarned again and can be blocked again.
214
277
  if (recent.length && !recent.at(-1).warned) {
215
278
  questions.infinite_loop = Q.infinite_loop;
216
- state =
217
- `Command about to run:\n${state}\n\nRecently failed commands (oldest first):\n` +
218
- recent.map((e) => `$ ${e.command}\n${e.error}${e.edited_after ? '\n(the agent edited code after this failure)' : ''}`).join('\n\n') +
219
- `\n\n${loopFact(maskSensitiveState(command), recent)}`;
279
+ state = loopState(command, recent);
220
280
  }
221
281
  const notices = new Set();
222
282
  const { sessionId } = input;
223
283
  const r = await evaluate({ state, questions, ...(sessionId && { session_id: sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices, now });
224
284
  if (!r.ok)
225
285
  brain.skipped_attempts++;
226
- else
286
+ else {
227
287
  countCheck(brain, now);
288
+ logDecision(brain, 'command', state, r.answers, cfg, now);
289
+ }
228
290
  await sessionNotice(brain, sessionId, lang, r, notices);
229
291
  let out = { code: 0, stderr: [] };
230
292
  if (r.ok) {
@@ -252,29 +314,77 @@ export async function agentPre(agent, input, { root, lang, now }) {
252
314
  * Blocks once (exit 2 makes the agent keep working); never blocks again while a stop hook is already active,
253
315
  * so it cannot loop. Turns without code edits never reach Jev.
254
316
  */
255
- export async function agentStop(input, { root, lang, now }) {
256
- const out = { code: 0, stderr: [] };
257
- if (input.stopHookActive || !input.transcriptPath)
317
+ export async function agentStop(agent, input, { root, lang, now }) {
318
+ let out = { code: 0, stderr: [] };
319
+ const brain = loadBrain(root);
320
+ // Claude Code: read the turn from its transcript. Others: cto's own turn log, which ends with this stop either way.
321
+ const logged = input.sessionId ? brain.turns?.[input.sessionId] : undefined;
322
+ if (!input.transcriptPath && input.sessionId && brain.turns?.[input.sessionId]) {
323
+ delete brain.turns[input.sessionId];
324
+ saveBrain(root, brain);
325
+ }
326
+ const actions = input.transcriptPath ? turnActions(input.transcriptPath, input.cwd) : logged?.actions ?? [];
327
+ // Lessons learn from every stop, including the one after our own block: that is when the fix usually lands.
328
+ const lessons = loadLessons(root);
329
+ if (resolveFromTurn(lessons, actions, root, new Date((now ?? Date.now)())).length)
330
+ saveLessons(root, lessons);
331
+ if (input.stopHookActive)
258
332
  return out;
259
- const actions = turnActions(input.transcriptPath, input.cwd);
260
- if (!actions.some((a) => a.kind === 'edit' && isCodeFile(a.file)))
333
+ const lastMessage = input.lastMessage || logged?.reply || '';
334
+ // ponytail: ticks are attributed to the turn that ends after they appear, so a box the user ticked by hand between
335
+ // turns is judged against the agent's turn. Rare; per-turn snapshots of plan files would fix it.
336
+ const judged = new Set(brain.judged_items ?? []);
337
+ const ticked = tickedItems(planDiff(root), (f) => { try {
338
+ return readFileSync(join(root, f), 'utf8');
339
+ }
340
+ catch {
341
+ return undefined;
342
+ } })
343
+ .filter((t) => !judged.has(tickedKey(t)));
344
+ if (!ticked.length && !actions.some((a) => a.kind === 'edit' && isCodeFile(a.file)))
261
345
  return out;
262
346
  const cfg = loadConfig(root);
263
- const brain = loadBrain(root);
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 });
347
+ const state = turnState(lastMessage, actions, ticked);
348
+ const r = await evaluate({ state, questions: { done_unverified: Q.done_unverified }, ...(input.sessionId && { session_id: input.sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices: new Set(), now });
265
349
  if (!r.ok)
266
350
  brain.skipped_attempts++;
267
- else
351
+ else {
268
352
  countCheck(brain, now);
353
+ logDecision(brain, 'stop', state, r.answers, cfg, now);
354
+ brain.judged_items = [...judged, ...ticked.map(tickedKey)].slice(-300);
355
+ }
269
356
  const v = r.ok ? exceeded(r.answers, 'done_unverified', cfg) : undefined;
270
357
  if (v !== undefined) {
271
358
  brain.blocked_attempts++;
272
- out.code = 2;
273
- out.stderr = verdict(lang, 'done_unverified', v, cfg, null);
359
+ out = agent.stopBlock(verdict(lang, 'done_unverified', v, cfg, null));
274
360
  }
275
361
  saveBrain(root, brain);
276
362
  return out;
277
363
  }
364
+ // ---------- turn log (agents without a readable transcript) ----------
365
+ const TURN_MAX_ACTIONS = 80;
366
+ const TURN_MAX_SESSIONS = 5;
367
+ /** Append one action to a session's turn log; keeps the log and the number of sessions bounded. */
368
+ export function logAction(brain, sessionId, action) {
369
+ brain.turns ??= {};
370
+ const t = (brain.turns[sessionId] ??= { at: '', actions: [] });
371
+ t.actions = [...t.actions, action].slice(-TURN_MAX_ACTIONS);
372
+ t.at = new Date().toISOString();
373
+ const ids = Object.keys(brain.turns).sort((a, b) => brain.turns[b].at.localeCompare(brain.turns[a].at));
374
+ for (const id of ids.slice(TURN_MAX_SESSIONS))
375
+ delete brain.turns[id];
376
+ }
377
+ /** Cursor's final reply arrives in its own event, before stop. */
378
+ export function agentReply(input, { root }) {
379
+ if (!input.sessionId || !input.text.trim())
380
+ return { code: 0, stderr: [] };
381
+ const brain = loadBrain(root);
382
+ brain.turns ??= {};
383
+ const t = (brain.turns[input.sessionId] ??= { at: new Date().toISOString(), actions: [] });
384
+ t.reply = input.text;
385
+ saveBrain(root, brain);
386
+ return { code: 0, stderr: [] };
387
+ }
278
388
  // ---------- post (failure recording) ----------
279
389
  /** Record the failure only; never calls Jev. No error field, no record. */
280
390
  /**
@@ -282,16 +392,28 @@ export async function agentStop(input, { root, lang, now }) {
282
392
  * re-run after a fix is a new attempt, but the same error coming back across repeated fixes is still a loop, and only
283
393
  * the history shows that. Local only: no Jev call, no network. Docs/YAML edits do not count.
284
394
  */
285
- export function agentEdit(files, { root }) {
395
+ export function agentEdit(files, { root }, logSession) {
396
+ const brain = loadBrain(root);
397
+ if (logSession) {
398
+ for (const f of files ?? ['(unknown file)'])
399
+ logAction(brain, logSession, { kind: 'edit', file: f });
400
+ saveBrain(root, brain);
401
+ }
286
402
  if (files && !files.some(isCodeFile))
287
403
  return { code: 0, stderr: [] };
288
- const brain = loadBrain(root);
289
404
  if (brain.recent_errors.some((e) => !e.edited_after)) {
290
405
  brain.recent_errors = brain.recent_errors.map((e) => ({ ...e, edited_after: true }));
291
406
  saveBrain(root, brain);
292
407
  }
293
408
  return { code: 0, stderr: [] };
294
409
  }
410
+ /** The state Jev sees for the loop question: the command, the recent failures (marked when code was edited after), and the computed fact. */
411
+ export function loopState(command, recent) {
412
+ const masked = maskSensitiveState(command);
413
+ return `Command about to run:\n${masked}\n\nRecently failed commands (oldest first):\n` +
414
+ recent.map((e) => `$ ${e.command}\n${e.error}${e.edited_after ? '\n(the agent edited code after this failure)' : ''}`).join('\n\n') +
415
+ `\n\n${loopFact(masked, recent)}`;
416
+ }
295
417
  /** Facts code can count exactly, so Jev does not have to: repeats of this command, the error streak, edits since. */
296
418
  export function loopFact(command, recent) {
297
419
  const norm = (s) => s.trim().replace(/\s+/g, ' ');
@@ -304,10 +426,19 @@ export function loopFact(command, recent) {
304
426
  return `Fact: this exact command failed ${same.length} time(s) recently; its latest error has now appeared ${streak} time(s) in a row; ` +
305
427
  (recent.at(-1).edited_after ? 'the agent has edited code since the most recent failure.' : 'the agent has not edited any code since the most recent failure.');
306
428
  }
307
- export function agentPost(input, { root }) {
429
+ export function agentPost(input, { root }, agent = 'unknown') {
308
430
  if (!input)
309
431
  return { code: 0, stderr: [] };
432
+ const lessons = loadLessons(root);
433
+ recordFailure(lessons, input.command, input.error, root, agent);
434
+ saveLessons(root, lessons);
310
435
  const brain = loadBrain(root);
436
+ const turn = input.sessionId ? brain.turns?.[input.sessionId] : undefined;
437
+ const run = turn?.actions.findLast((a) => a.kind === 'run' && a.command === maskSensitiveState(input.command));
438
+ if (run && run.kind === 'run') {
439
+ run.ok = false;
440
+ run.tail = maskSensitiveState(input.error).slice(-300);
441
+ }
311
442
  brain.recent_errors = [
312
443
  ...freshErrors(brain),
313
444
  {
package/dist/i18n.js CHANGED
@@ -20,7 +20,7 @@ export const personaDict = {
20
20
  infinite_loop: '同樣的錯誤又來了,你們在鬼打牆燒 Token。這次工具呼叫我擋下了,先去看邏輯。',
21
21
  architecture_violation: '這次變更偏離了 Sprint 目標。我放你過,但這筆帳記著。',
22
22
  test_tampering: '程式沒修好,倒先把測試改弱了?Commit 已攔下。去修程式,不是修測試。',
23
- done_unverified: '說做完了?證據呢?最後一次改程式之後,我沒看到通過的測試或建置。先跑相關的檢查,看到通過再收工;真的跑不了,就老實告訴使用者哪些還沒驗證。',
23
+ done_unverified: '說做完了?證據呢?最後一次改程式之後,我沒看到通過的測試或建置,或是你打勾的計畫項目沒有證據。先跑相關的檢查,看到通過再收工;真的跑不了,就老實告訴使用者哪些還沒驗證。',
24
24
  code_complexity: '複雜度超標,過度工程化。這次不擋,但趕快重構。',
25
25
  },
26
26
  en: {
@@ -29,7 +29,7 @@ export const personaDict = {
29
29
  infinite_loop: 'Same error again. You are looping and burning tokens. This tool call is BLOCKED. Fix the logic first.',
30
30
  architecture_violation: 'This change drifts from the sprint goal. Letting it through, but I noticed.',
31
31
  test_tampering: 'Weakening the tests instead of fixing the code? Commit BLOCKED. Fix the code, not the tests.',
32
- done_unverified: 'Done, you say? Show me. Nothing passing ran after your last code change. Run the relevant tests or build and see them pass before you stop; if you really cannot, tell the user plainly what is still unverified.',
32
+ done_unverified: 'Done, you say? Show me. Nothing passing ran after your last code change, or the plan items you checked off have no evidence. Run the relevant tests or build and see them pass before you stop; if you really cannot, tell the user plainly what is still unverified.',
33
33
  code_complexity: 'Over-engineered. Not blocking this time, but refactor it.',
34
34
  },
35
35
  };
@@ -52,9 +52,14 @@ const messages = {
52
52
  bad_request: (v) => `[cto] Jev 拒絕請求 (400),這次直接放行:${v.msg}`,
53
53
  no_keys: () => '[cto] 未設定 Jev API key,全部放行。請設定 CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID 或 OPENROUTER_API_KEY',
54
54
  detail: (v) => `${v.signal} = ${v.value}(門檻 > ${v.threshold})`,
55
+ local_protected_branch: (v) => `[cto] ${v.detail} 是受保護的分支,不准直接動。開一個 branch 再來。(protected_branches)`,
56
+ local_conflict_marker: (v) => `[cto] ${v.detail} 裡還有 merge 衝突標記,你打算把 <<<<<<< 一起 commit 進去?先解完衝突。`,
57
+ local_env_file: (v) => `[cto] 你正要把 ${v.detail} 連同值一起 commit。.env 不進 git,放進 .gitignore,要分享用 .env.example。`,
58
+ local_big_file: (v) => `[cto] ${v.detail} 太大了,確定是要進 git 的東西?不擋,但想清楚。`,
59
+ local_lock_drift: (v) => `[cto] package.json 改了相依套件,但 ${v.detail} 沒跟著改。先跑一次 install,不然隊友裝的會跟你不一樣。`,
55
60
  setup_not_git: () => '[cto] 這裡不是 git repository,setup 中止。',
56
61
  setup_bad_json: (v) => `[cto] ${v.path} 不是合法 JSON 或 hooks 格式不符,未修改任何檔案。請先修正該檔。`,
57
- setup_hook: (v) => `[cto] pre-commit 區塊已寫入 ${v.path}`,
62
+ setup_hook: (v) => `[cto] ${v.name} 區塊已寫入 ${v.path}`,
58
63
  setup_hook_exit: (v) => `[cto] 警告:${v.path} 在 cto 區塊之前有 exit 0,cto 檢查不會執行。請調整該 hook。`,
59
64
  setup_gitignore: () => '[cto] .gitignore 已加入 .cto-brain.json 與 debug_stdin.json',
60
65
  setup_config: () => '[cto] 已建立 .cto.json(請 commit 給團隊共用)',
@@ -110,6 +115,7 @@ const messages = {
110
115
  check_nothing: () => '[cto] 沒有可檢查的改動。',
111
116
  check_head_staged: (v) => `[cto] 檢查 staged 的改動(${v.files} 個檔案),跟 commit 時的檢查相同:`,
112
117
  check_head_working: (v) => `[cto] 沒有 staged 的改動,改為檢查工作目錄(${v.files} 個檔案,含尚未加入 git 的新檔):`,
118
+ check_head_base: (v) => `[cto] 檢查這個分支相對於 ${v.base} 的改動(${v.files} 個檔案):`,
113
119
  check_unchecked: () => '[cto] 無法檢查:沒有可用的 Jev provider。執行 cto doctor 看原因。',
114
120
  check_why_tests: () => '未檢查:沒有改到測試相關檔案',
115
121
  check_why_goal: () => '未檢查:.cto.json 沒有設定 sprint_goal',
@@ -147,15 +153,27 @@ const messages = {
147
153
  doc_hint_401: () => 'key 無效或已撤銷,請重新產生後執行 cto setup',
148
154
  doc_hint_402: () => '額度不足,請到 provider 後台儲值',
149
155
  doc_hint_network: () => '連不上或太慢,檢查網路或稍後再試',
150
- doc_hint_other: () => '非預期的回應,請回報到 github.com/rainday/your-cto-jev/issues',
156
+ doc_hint_other: () => '非預期的回應,請回報到 github.com/hierichhsu/your-cto-jev/issues',
151
157
  doc_repo: (v) => `目前的 repo:${v.root}`,
152
158
  doc_no_repo: () => '目前不在 git repo 裡,略過專案檢查。',
153
- doc_hook_ok: (v) => `git pre-commit 已安裝(${v.path})`,
154
- doc_hook_missing: () => 'git pre-commit 沒有 cto 區塊,請在此 repo 執行 cto setup',
159
+ doc_hook_ok: (v) => `git ${v.name} 已安裝(${v.path})`,
160
+ doc_hook_missing: (v) => `git ${v.name} 沒有 cto 區塊,請在此 repo 執行 cto setup`,
155
161
  doc_agents: (v) => `已接上的 agent:${v.list}`,
156
162
  doc_none: () => '無',
157
163
  doc_goal_set: () => 'sprint_goal 已設定,架構對齊檢查啟用中',
158
164
  doc_goal_empty: () => 'sprint_goal 未設定,架構對齊檢查關閉(可在 .cto.json 填入)',
165
+ log_empty: () => '[cto] 這個 repo 還沒有 Jev 回答過的檢查。',
166
+ log_head: () => '[cto] 最近的判斷(最舊在上):',
167
+ log_crossed: () => '超過門檻',
168
+ log_hint: () => '[cto] 哪一筆判斷錯了?cto report <編號>(不給編號就是最後一筆)會把它存成校正案例。',
169
+ report_bad_n: (v) => `[cto] 沒有這個編號,cto log 只有 1 到 ${v.max}。`,
170
+ report_wrong: (v) => `[cto] 記下了:${v.signal} 給 ${v.value} 是誤擋,正確答案應該是「否」。`,
171
+ report_missed: (v) => `[cto] 記下了:${v.signal} 給 ${v.value} 是漏判,正確答案應該是「是」。`,
172
+ report_written: (v) => `[cto] 已寫入 ${v.path}(只在這台電腦,已遮罩)。要幫 cto 校正:把那行貼進 your-cto-jev 的 calibration/candidates/${v.signal}.jsonl 開 PR,或貼進 issue。`,
173
+ conflicts_head: () => '[cto] 其他也在管 agent 的東西(請確認沒有跟 cto 打架):',
174
+ conflict_hook: (v) => `cto 的事件上還有別的 hook:${v.where} → ${v.detail}。先擋的那個 cto 看不到;cto 擋了之後,後面的不會跑。`,
175
+ conflict_guidance: (v) => `${v.where} 這行看起來在教 agent 做 cto 會擋的事:「${v.detail}」`,
176
+ conflict_dup_skill: (v) => `skill「${v.where}」在 ${v.detail} 各裝了一份,agent 會看到兩個版本。`,
159
177
  doc_stats: (v) => `累計:擋下 ${v.blocked} 次,因無法檢查而放行 ${v.skipped} 次`,
160
178
  doc_cooldown: (v) => `${v.name} 冷卻中,原因 ${v.status},到 ${v.until} 才會重試`,
161
179
  doc_p_no_provider: () => '沒有任何可用的 provider:現在所有檢查都會直接放行',
@@ -164,7 +182,7 @@ const messages = {
164
182
  doc_bad: () => '[cto] 有問題需要處理:',
165
183
  update_available: (v) => `[cto] 有新版 ${v.latest}(目前 ${v.current}),執行 cto update 更新`,
166
184
  update_done: () => '[cto] 已更新。已設定過的專案不用重跑 cto setup。',
167
- usage: () => '用法:cto check | cto doctor | cto update | cto --version | cto setup [--refresh] [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
185
+ usage: () => '用法:cto brief | cto check [--base origin/main] | cto log | cto report [n] | cto doctor | cto update | cto --version | cto setup [--refresh] [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
168
186
  },
169
187
  en: {
170
188
  reason_402: () => 'out of credits',
@@ -184,9 +202,14 @@ const messages = {
184
202
  bad_request: (v) => `[cto] Jev rejected the request (400), letting this one through: ${v.msg}`,
185
203
  no_keys: () => '[cto] No Jev API key set, everything passes. Set CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID or OPENROUTER_API_KEY',
186
204
  detail: (v) => `${v.signal} = ${v.value} (threshold > ${v.threshold})`,
205
+ local_protected_branch: (v) => `[cto] ${v.detail} is a protected branch. Not on my watch: make a branch. (protected_branches)`,
206
+ local_conflict_marker: (v) => `[cto] ${v.detail} still has merge conflict markers. Committing <<<<<<< is not a strategy. Resolve it first.`,
207
+ local_env_file: (v) => `[cto] You are about to commit ${v.detail} with real values. .env files stay out of git: add it to .gitignore and share a .env.example.`,
208
+ local_big_file: (v) => `[cto] ${v.detail} is huge. Sure that belongs in git? Not blocking, but think.`,
209
+ local_lock_drift: (v) => `[cto] package.json changed dependencies but ${v.detail} did not. Run install first, or your teammates get a different tree.`,
187
210
  setup_not_git: () => '[cto] Not a git repository, setup aborted.',
188
211
  setup_bad_json: (v) => `[cto] ${v.path} is not valid JSON or has an unexpected hooks shape. Nothing was changed. Fix it first.`,
189
- setup_hook: (v) => `[cto] pre-commit block written to ${v.path}`,
212
+ setup_hook: (v) => `[cto] ${v.name} block written to ${v.path}`,
190
213
  setup_hook_exit: (v) => `[cto] Warning: ${v.path} has an exit 0 before the cto block, so cto will never run. Adjust that hook.`,
191
214
  setup_gitignore: () => '[cto] Added .cto-brain.json and debug_stdin.json to .gitignore',
192
215
  setup_config: () => '[cto] Created .cto.json (commit it for the team)',
@@ -242,6 +265,7 @@ const messages = {
242
265
  check_nothing: () => '[cto] Nothing to check.',
243
266
  check_head_staged: (v) => `[cto] Checking staged changes (${v.files} files), same checks as a commit:`,
244
267
  check_head_working: (v) => `[cto] Nothing staged, checking the working tree instead (${v.files} files, including new untracked files):`,
268
+ check_head_base: (v) => `[cto] Checking what this branch adds on top of ${v.base} (${v.files} files):`,
245
269
  check_unchecked: () => '[cto] Could not check: no working Jev provider. Run cto doctor to see why.',
246
270
  check_why_tests: () => 'not checked: no test files changed',
247
271
  check_why_goal: () => 'not checked: sprint_goal is empty in .cto.json',
@@ -279,15 +303,27 @@ const messages = {
279
303
  doc_hint_401: () => 'Key invalid or revoked. Create a new one and run cto setup',
280
304
  doc_hint_402: () => 'Out of credits. Top up in the provider dashboard',
281
305
  doc_hint_network: () => 'Unreachable or too slow. Check your network or try again later',
282
- doc_hint_other: () => 'Unexpected response. Please report it at github.com/rainday/your-cto-jev/issues',
306
+ doc_hint_other: () => 'Unexpected response. Please report it at github.com/hierichhsu/your-cto-jev/issues',
283
307
  doc_repo: (v) => `Current repo: ${v.root}`,
284
308
  doc_no_repo: () => 'Not inside a git repo, skipping project checks.',
285
- doc_hook_ok: (v) => `git pre-commit installed (${v.path})`,
286
- doc_hook_missing: () => 'git pre-commit has no cto block. Run cto setup in this repo',
309
+ doc_hook_ok: (v) => `git ${v.name} installed (${v.path})`,
310
+ doc_hook_missing: (v) => `git ${v.name} has no cto block. Run cto setup in this repo`,
287
311
  doc_agents: (v) => `Agents wired up: ${v.list}`,
288
312
  doc_none: () => 'none',
289
313
  doc_goal_set: () => 'sprint_goal set, architecture check on',
290
314
  doc_goal_empty: () => 'sprint_goal empty, architecture check off (set it in .cto.json)',
315
+ log_empty: () => '[cto] No check answered by Jev in this repo yet.',
316
+ log_head: () => '[cto] Recent decisions (oldest first):',
317
+ log_crossed: () => 'CROSSED',
318
+ log_hint: () => '[cto] One of these was wrong? cto report <n> (the last one when n is omitted) saves it as a calibration case.',
319
+ report_bad_n: (v) => `[cto] No such entry; cto log has 1 to ${v.max}.`,
320
+ report_wrong: (v) => `[cto] Noted: ${v.signal} at ${v.value} was a false alarm, the right answer is "no".`,
321
+ report_missed: (v) => `[cto] Noted: ${v.signal} at ${v.value} was a miss, the right answer is "yes".`,
322
+ report_written: (v) => `[cto] Written to ${v.path} (this machine only, masked). To help calibrate cto, paste that line into calibration/candidates/${v.signal}.jsonl of your-cto-jev in a PR, or into an issue.`,
323
+ conflicts_head: () => '[cto] Other things steering the agents here (make sure they do not fight cto):',
324
+ conflict_hook: (v) => `another hook on cto's events: ${v.where} -> ${v.detail}. Whichever blocks first hides the call from the rest.`,
325
+ conflict_guidance: (v) => `${v.where} looks like it tells the agent to do what cto blocks: "${v.detail}"`,
326
+ conflict_dup_skill: (v) => `skill "${v.where}" is installed in both ${v.detail}; the agent sees two versions.`,
291
327
  doc_stats: (v) => `So far: blocked ${v.blocked}, let through unchecked ${v.skipped}`,
292
328
  doc_cooldown: (v) => `${v.name} is cooling down after ${v.status}, retried after ${v.until}`,
293
329
  doc_p_no_provider: () => 'No working provider: every check is currently let through',
@@ -296,7 +332,7 @@ const messages = {
296
332
  doc_bad: () => '[cto] Needs attention:',
297
333
  update_available: (v) => `[cto] Version ${v.latest} is available (you have ${v.current}). Run cto update`,
298
334
  update_done: () => '[cto] Updated. Projects already set up do not need cto setup again.',
299
- usage: () => 'Usage: cto check | cto doctor | cto update | cto --version | cto setup [--refresh] [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
335
+ usage: () => 'Usage: cto brief | cto check [--base origin/main] | cto log | cto report [n] | cto doctor | cto update | cto --version | cto setup [--refresh] [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
300
336
  },
301
337
  };
302
338
  export function t(lang, key, vars = {}) {
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { join } from 'node:path';
5
5
  import { agentNames, agents } from './agents.js';
6
6
  import { applyCredentials, findRoot, loadConfig, loadCredentials, loadPrefs, saveCredentials, savePrefs } from './brain.js';
7
7
  import { DEFAULT_ORDER, providerOrder, providers } from './api.js';
8
- import { agentEdit, agentPost, agentPre, agentStop, gitCommit, stagedDiff } from './hooks.js';
8
+ import { agentEdit, agentPost, agentPre, agentReply, agentStop, gitCommit, gitPush, stagedDiff } from './hooks.js';
9
9
  import { checkUpdate, currentVersion, runUpdate } from './update.js';
10
10
  import { doctor } from './doctor.js';
11
11
  import { detectLang, t } from './i18n.js';
@@ -42,7 +42,9 @@ async function runHook(name) {
42
42
  return gitCommit(diff, { root, lang });
43
43
  }
44
44
  const raw = await readStdin();
45
- const m = /^(claude|cursor|gemini|codex)-(pre|post|stop|edit)$/.exec(name);
45
+ if (name === 'git-push')
46
+ return gitPush(raw, { root: findRoot(), lang });
47
+ const m = /^(claude|cursor|gemini|codex)-(pre|post|stop|edit|reply|start)$/.exec(name);
46
48
  if (!m)
47
49
  return { code: 0, stderr: [] };
48
50
  const agent = agents[m[1]];
@@ -51,9 +53,19 @@ async function runHook(name) {
51
53
  input = JSON.parse(raw);
52
54
  }
53
55
  catch { /* fail-open below */ }
56
+ if (m[2] === 'start') {
57
+ const { brief } = await import('./brief.js');
58
+ return { code: 0, stdout: brief(findRoot(typeof input?.cwd === 'string' ? input.cwd : process.cwd())).join('\n'), stderr: [] };
59
+ }
54
60
  if (m[2] === 'edit') {
55
61
  const cwd = typeof input?.cwd === 'string' ? input.cwd : typeof input?.workspace_roots?.[0] === 'string' ? input.workspace_roots[0] : process.cwd();
56
- return agentEdit(agent.parseEdit?.(input), { root: findRoot(cwd), lang });
62
+ return agentEdit(agent.parseEdit?.(input), { root: findRoot(cwd), lang }, agent.transcriptTurns ? undefined : agent.session(input));
63
+ }
64
+ if (m[2] === 'reply') {
65
+ if (!agent.parseReply)
66
+ return { code: 0, stderr: [] };
67
+ const reply = agent.parseReply(input);
68
+ return agentReply(reply, { root: findRoot(reply.cwd ?? process.cwd()), lang });
57
69
  }
58
70
  if (m[2] === 'stop') {
59
71
  if (!agent.parseStop)
@@ -61,7 +73,7 @@ async function runHook(name) {
61
73
  const stop = agent.parseStop(input);
62
74
  const root = findRoot(stop.cwd ?? process.cwd());
63
75
  debug(root, maskSensitiveState(raw));
64
- return agentStop(stop, { root, lang });
76
+ return agentStop(agent, stop, { root, lang });
65
77
  }
66
78
  if (m[2] === 'pre') {
67
79
  const pre = agent.parsePre(input);
@@ -72,7 +84,7 @@ async function runHook(name) {
72
84
  const post = agent.parsePost(input);
73
85
  const root = findRoot(post?.cwd ?? input?.cwd ?? process.cwd());
74
86
  debug(root, maskSensitiveState(raw));
75
- return agentPost(post, { root, lang });
87
+ return agentPost(post, { root, lang }, m[1]);
76
88
  }
77
89
  const args = process.argv.slice(2);
78
90
  const lang = detectLang();
@@ -163,11 +175,35 @@ else if (args[0] === 'check') {
163
175
  }
164
176
  else {
165
177
  const { runCheck } = await import('./check.js');
166
- const r = await runCheck(root, lang);
178
+ const r = await runCheck(root, lang, flag('--base'));
167
179
  console.log(r.lines.join('\n'));
168
180
  process.exitCode = r.code;
169
181
  }
170
182
  }
183
+ else if (args[0] === 'log' || args[0] === 'report') {
184
+ const root = gitRoot(process.cwd());
185
+ if (!root) {
186
+ process.stderr.write(t(lang, 'setup_not_git') + '\n');
187
+ process.exitCode = 1;
188
+ }
189
+ else {
190
+ const { showLog, report } = await import('./report.js');
191
+ const r = args[0] === 'log' ? showLog(root, lang) : report(root, lang, args[1]);
192
+ (r.code ? process.stderr : process.stdout).write(r.lines.join('\n') + '\n');
193
+ process.exitCode = r.code;
194
+ }
195
+ }
196
+ else if (args[0] === 'brief') {
197
+ const root = gitRoot(process.cwd());
198
+ if (!root) {
199
+ process.stderr.write(t(lang, 'setup_not_git') + '\n');
200
+ process.exitCode = 1;
201
+ }
202
+ else {
203
+ const { brief } = await import('./brief.js');
204
+ console.log(brief(root).join('\n'));
205
+ }
206
+ }
171
207
  else if (args[0] === 'doctor') {
172
208
  const r = await doctor(process.cwd(), lang);
173
209
  console.log(r.lines.join('\n'));