your-cto-jev 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -9
- package/dist/agents.js +34 -5
- package/dist/hooks.js +108 -20
- package/dist/i18n.js +2 -2
- package/dist/index.js +10 -4
- package/dist/setup.js +4 -4
- package/dist/shellwrites.js +40 -0
- package/dist/skill.js +2 -2
- package/dist/turn.js +72 -4
- package/dist/update.js +2 -1
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
**A sharp-tongued CTO that reviews what your AI coding agent is about to do, and says no.**
|
|
4
4
|
|
|
5
|
-
`cto` hooks into `git commit` and into Claude Code, Cursor, Gemini CLI and Codex. Before a commit lands, before an agent runs a shell command, and when
|
|
5
|
+
`cto` hooks into `git commit` and into Claude Code, Cursor, Gemini CLI and Codex. Before a commit lands, before an agent runs a shell command, and when an agent says it is done, it asks [TypeSafe Jev](https://developers.cloudflare.com/ai/models/typesafe/jev/), a typed decision model, a few yes/no questions. Then it blocks, warns, or stays completely silent.
|
|
6
6
|
|
|
7
7
|
```text
|
|
8
8
|
$ git commit -m "add payments"
|
|
@@ -34,7 +34,7 @@ Jev judges meaning and answers with probabilities, not prose. It costs about $0.
|
|
|
34
34
|
| `test_tampering` | `git commit`s that touch tests or test config | **Blocks** the commit |
|
|
35
35
|
| `destructive_command` | every agent shell command | **Blocks** the command |
|
|
36
36
|
| `infinite_loop` | agent shell commands, after a recent failure | **Blocks** the command |
|
|
37
|
-
| `done_unverified` |
|
|
37
|
+
| `done_unverified` | an agent ending a turn that edited code or checked off plan items | **Sends it back to work** until the change is verified or the gap is disclosed |
|
|
38
38
|
| `architecture_violation` | `git commit`, once you set a sprint goal | Warns only |
|
|
39
39
|
| `code_complexity` | every `git commit` | Warns only |
|
|
40
40
|
|
|
@@ -42,6 +42,8 @@ Jev judges meaning and answers with probabilities, not prose. It costs about $0.
|
|
|
42
42
|
|
|
43
43
|
`done_unverified` catches the other classic shortcut: "Done, all tests pass!" when nothing ran after the last edit, the last run failed, or the claim is not backed by anything the agent actually did. It lets through turns that ran a passing check after the last edit, turns that changed only docs or CI config, and turns where the agent honestly says what it could not verify. It blocks at most once per stop, so it cannot loop.
|
|
44
44
|
|
|
45
|
+
Checking off a plan item is the same claim. Whatever planning tool you use (spec-kit, GSD, Kiro, specOS, a hand-written `TODO.md`), plans end up as markdown checklists, so `cto` reads the uncommitted `- [ ]` to `- [x]` changes in tracked `.md` files and asks whether the turn backs them up. A phase or parent item counts as backed when everything nested under it is checked, or when the turn ran a passing check that covers it. Each tick is judged once. A turn that only ticks boxes, without doing the work, is checked too.
|
|
46
|
+
|
|
45
47
|
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.
|
|
46
48
|
|
|
47
49
|
When nothing crosses a threshold, `cto` prints nothing at all.
|
|
@@ -151,10 +153,10 @@ The git pre-commit check is always installed. It protects every agent and every
|
|
|
151
153
|
|
|
152
154
|
| Agent | Config written | Command gate | Loop detection | Knows about edits | Done check |
|
|
153
155
|
|---|---|---|---|---|---|
|
|
154
|
-
| Claude Code | `.claude/settings.local.json` | yes | yes | yes | yes |
|
|
155
|
-
| Cursor | `.cursor/hooks.json` | yes | yes | yes (`afterFileEdit`) |
|
|
156
|
-
| Gemini CLI | `.gemini/settings.json` | yes | yes | yes (`write_file`, `replace`) |
|
|
157
|
-
| Codex CLI | `.codex/hooks.json` | yes | limited: Codex has no failure event | yes (`apply_patch`) |
|
|
156
|
+
| Claude Code | `.claude/settings.local.json` | yes | yes | yes | yes, from its transcript |
|
|
157
|
+
| Cursor | `.cursor/hooks.json` | yes | yes | yes (`afterFileEdit`) | yes (`stop`, follow-up message) |
|
|
158
|
+
| Gemini CLI | `.gemini/settings.json` | yes | yes | yes (`write_file`, `replace`) | yes (`AfterAgent`, retry) |
|
|
159
|
+
| Codex CLI | `.codex/hooks.json` | yes | limited: Codex has no failure event | yes (`apply_patch`) | yes (`Stop`) |
|
|
158
160
|
|
|
159
161
|
Claude Code is tested end to end inside the agent. The Cursor, Gemini CLI and Codex adapters follow each agent's official hook docs and are tested with their documented payloads, but have not been run inside those agents yet. Reports welcome.
|
|
160
162
|
|
|
@@ -185,7 +187,7 @@ Every check sends text to your chosen provider. `cto` masks it first:
|
|
|
185
187
|
|
|
186
188
|
- **For commits:** the staged diff, with lock files, minified files, source maps and binaries removed.
|
|
187
189
|
- **For agent commands:** the command, plus up to five failures from the last 15 minutes when checking for loops.
|
|
188
|
-
- **When
|
|
190
|
+
- **When an agent ends a turn that edited code:** the agent's final message and a log of that turn: names of edited files, the shell commands it ran, whether each succeeded, and the end of each output (Claude Code) or of each failure (other agents).
|
|
189
191
|
- **For `cto check`:** the same as a commit; when nothing is staged, all working-tree changes, including the full content of new files git does not track yet.
|
|
190
192
|
- **Always masked:** private key blocks, Stripe, OpenAI, AWS, GitHub and npm tokens, and any `NAME=value` whose name ends in `PASSWORD`, `SECRET`, `TOKEN` or `KEY`. Every value in a `.env` file is masked as well.
|
|
191
193
|
|
|
@@ -212,7 +214,7 @@ Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6,
|
|
|
212
214
|
- **Thresholds**: Jev returns a probability from 0 to 1. `code_complexity` is the exception: it is a score from 0 (clean) to 4 (unmaintainable).
|
|
213
215
|
- **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.
|
|
214
216
|
- `done_unverified` (0.6) and `infinite_loop` (0.6) were calibrated the same way; the measurements are in the design spec.
|
|
215
|
-
-
|
|
217
|
+
- For `destructive_command`, the current question scores `git push --force` about 0.74 (blocked by default), `find -delete` about 0.65 and `git reset --hard` about 0.47 (both let through), and `rm -rf node_modules` about 0.12. Lower the threshold to about 0.45 to block all three; the calibration set is still small, so the default stays at 0.7.
|
|
216
218
|
|
|
217
219
|
`.cto-brain.json` holds personal runtime state and is gitignored.
|
|
218
220
|
|
|
@@ -227,7 +229,7 @@ Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6,
|
|
|
227
229
|
## Known limitations
|
|
228
230
|
|
|
229
231
|
- **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.
|
|
230
|
-
- **The done check
|
|
232
|
+
- **The done check sees edits from edit tools and from common shell commands** (`sed -i`, redirects, `tee`, formatters), but not writes hidden inside scripts such as `node -e`. It also misses a test run that targets the wrong package. Claude Code's turn comes from its transcript; for Cursor, Gemini CLI and Codex, whose transcript formats are not public, cto keeps its own log of commands and edits, and a command counts as successful unless a failure event arrives.
|
|
231
233
|
- **Loop detection knows about edits, but only through the agent's edit tools.** A first re-run after a code edit is a new attempt, while the same error coming back across repeated fixes still counts as a loop; each loop is blocked once, so the agent can still verify its next fix. A file changed only through a shell command is not seen as an edit, and failures expire after 15 minutes.
|
|
232
234
|
- **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.
|
|
233
235
|
|
|
@@ -247,6 +249,16 @@ npm version patch # or minor / major: bumps package.json, commits, tags
|
|
|
247
249
|
git push --follow-tags # the tag triggers .github/workflows/publish.yml
|
|
248
250
|
```
|
|
249
251
|
|
|
252
|
+
To re-measure the checks after changing a question, after a Jev model update, or after adding cases:
|
|
253
|
+
|
|
254
|
+
```sh
|
|
255
|
+
npm run calibrate # every signal, against the cases in calibration/
|
|
256
|
+
npm run calibrate -- --signal test_tampering
|
|
257
|
+
node scripts/harvest-commands.mjs --rows 300 # real agent commands from a public dataset, to label
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
`calibrate` uses exactly the questions and state builders that ship, prints every case's score, and reports how many cases the current threshold catches and wrongly blocks. Harvested candidates in `calibration/candidates/` (from nebius/SWE-rebench-openhands-trajectories, CC-BY-4.0) join the measurement once someone sets their `expect` label.
|
|
261
|
+
|
|
250
262
|
The full design, including the measured results behind the defaults, is in [`your-cto-jev-spec.html`](./your-cto-jev-spec.html) (written in 繁體中文).
|
|
251
263
|
|
|
252
264
|
## License
|
package/dist/agents.js
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
// One row per coding agent. The verdict logic is shared; each row only maps the agent's
|
|
2
2
|
// stdin shape, its blocking convention, and where setup writes its hook config.
|
|
3
|
+
export const PHASES = ['pre', 'post', 'stop', 'edit', 'reply'];
|
|
3
4
|
const str = (v) => (typeof v === 'string' && v.trim() ? v : undefined);
|
|
4
5
|
const cmdOf = (i) => String(i?.tool_input?.command ?? i?.command ?? '');
|
|
5
6
|
// Claude, Codex and Gemini share this convention: exit 2 + stderr blocks, exit 0 hides stderr so notices go out as systemMessage.
|
|
7
|
+
// For their stop events exit 2 also means "keep working", with stderr as the reason fed back to the agent.
|
|
6
8
|
const exit2Block = (lines) => ({ code: 2, stderr: lines });
|
|
7
9
|
const systemMessage = (msgs) => ({ code: 0, stdout: JSON.stringify({ systemMessage: msgs.join('\n') }), stderr: [] });
|
|
8
10
|
const nestedPre = (i) => ({ command: str(i?.tool_input?.command), sessionId: str(i?.session_id), cwd: str(i?.cwd) });
|
|
11
|
+
const sessionId = (i) => str(i?.session_id);
|
|
12
|
+
const cursorCwd = (i) => str(i?.cwd) ?? str(i?.workspace_roots?.[0]);
|
|
9
13
|
/** Pull a non-zero exit out of free-form tool output ("Exit Code: 1", "exit_code": 2, ...). */
|
|
10
14
|
function nonZeroExit(v) {
|
|
11
15
|
if (v && typeof v === 'object') {
|
|
@@ -22,6 +26,7 @@ export const agents = {
|
|
|
22
26
|
claude: {
|
|
23
27
|
label: 'Claude Code',
|
|
24
28
|
homeDir: '.claude',
|
|
29
|
+
transcriptTurns: true,
|
|
25
30
|
settings: '.claude/settings.local.json',
|
|
26
31
|
style: 'nested',
|
|
27
32
|
pre: { event: 'PreToolUse', matcher: 'Bash' },
|
|
@@ -37,8 +42,10 @@ export const agents = {
|
|
|
37
42
|
stopHookActive: i?.stop_hook_active === true,
|
|
38
43
|
}),
|
|
39
44
|
parsePre: nestedPre,
|
|
40
|
-
parsePost: (i) => (i?.is_interrupt || !str(i?.error) ? null : { command: cmdOf(i), error: i.error, cwd: str(i?.cwd) }),
|
|
45
|
+
parsePost: (i) => (i?.is_interrupt || !str(i?.error) ? null : { command: cmdOf(i), error: i.error, cwd: str(i?.cwd), sessionId: sessionId(i) }),
|
|
46
|
+
session: sessionId,
|
|
41
47
|
block: exit2Block,
|
|
48
|
+
stopBlock: exit2Block,
|
|
42
49
|
notice: systemMessage,
|
|
43
50
|
},
|
|
44
51
|
cursor: {
|
|
@@ -49,17 +56,31 @@ export const agents = {
|
|
|
49
56
|
pre: { event: 'beforeShellExecution' },
|
|
50
57
|
post: { event: 'postToolUseFailure' },
|
|
51
58
|
edit: { event: 'afterFileEdit' },
|
|
59
|
+
// stop carries no message text, so the final reply is captured by afterAgentResponse.
|
|
60
|
+
stop: { event: 'stop' },
|
|
61
|
+
reply: { event: 'afterAgentResponse' },
|
|
52
62
|
parseEdit: (i) => { const p = str(i?.file_path); return p ? [p] : undefined; },
|
|
53
|
-
parsePre: (i) => ({ command: str(i?.command), sessionId: str(i?.conversation_id), cwd:
|
|
63
|
+
parsePre: (i) => ({ command: str(i?.command), sessionId: str(i?.conversation_id), cwd: cursorCwd(i) }),
|
|
54
64
|
parsePost: (i) => i?.tool_name !== 'Shell' || i?.is_interrupt || !str(i?.error_message)
|
|
55
65
|
? null
|
|
56
|
-
: { command: cmdOf(i), error: i.error_message, cwd:
|
|
66
|
+
: { command: cmdOf(i), error: i.error_message, cwd: cursorCwd(i), sessionId: str(i?.conversation_id) },
|
|
67
|
+
parseStop: (i) => ({
|
|
68
|
+
sessionId: str(i?.conversation_id),
|
|
69
|
+
cwd: cursorCwd(i),
|
|
70
|
+
lastMessage: '',
|
|
71
|
+
// loop_count > 0: this stop follows our own follow-up; aborted/error stops are not "done" claims.
|
|
72
|
+
stopHookActive: Number(i?.loop_count ?? 0) > 0 || (i?.status !== undefined && i?.status !== 'completed'),
|
|
73
|
+
}),
|
|
74
|
+
parseReply: (i) => ({ sessionId: str(i?.conversation_id), cwd: cursorCwd(i), text: String(i?.text ?? '') }),
|
|
75
|
+
session: (i) => str(i?.conversation_id),
|
|
57
76
|
// Both documented block paths at once: exit 2 and permission "deny".
|
|
58
77
|
block: (lines) => ({
|
|
59
78
|
code: 2,
|
|
60
79
|
stdout: JSON.stringify({ permission: 'deny', user_message: lines.join('\n'), agent_message: lines.join('\n') }),
|
|
61
80
|
stderr: lines,
|
|
62
81
|
}),
|
|
82
|
+
// A non-empty followup_message is submitted as the next user message, so the agent keeps working.
|
|
83
|
+
stopBlock: (lines) => ({ code: 0, stdout: JSON.stringify({ followup_message: lines.join('\n') }), stderr: [] }),
|
|
63
84
|
notice: (msgs) => ({ code: 0, stdout: JSON.stringify({ permission: 'allow', user_message: msgs.join('\n') }), stderr: [] }),
|
|
64
85
|
},
|
|
65
86
|
gemini: {
|
|
@@ -70,6 +91,7 @@ export const agents = {
|
|
|
70
91
|
pre: { event: 'BeforeTool', matcher: 'run_shell_command' },
|
|
71
92
|
post: { event: 'AfterTool', matcher: 'run_shell_command' },
|
|
72
93
|
edit: { event: 'AfterTool', matcher: 'write_file|replace' },
|
|
94
|
+
stop: { event: 'AfterAgent' },
|
|
73
95
|
parseEdit: (i) => { const p = str(i?.tool_input?.file_path); return p ? [p] : undefined; },
|
|
74
96
|
parsePre: nestedPre,
|
|
75
97
|
parsePost: (i) => {
|
|
@@ -77,9 +99,12 @@ export const agents = {
|
|
|
77
99
|
return null;
|
|
78
100
|
const r = i?.tool_response;
|
|
79
101
|
const err = str(r?.error) ?? str(r?.error?.message) ?? nonZeroExit(r?.llmContent);
|
|
80
|
-
return err ? { command: cmdOf(i), error: err, cwd: str(i?.cwd) } : null;
|
|
102
|
+
return err ? { command: cmdOf(i), error: err, cwd: str(i?.cwd), sessionId: sessionId(i) } : null;
|
|
81
103
|
},
|
|
104
|
+
parseStop: (i) => ({ sessionId: sessionId(i), cwd: str(i?.cwd), lastMessage: String(i?.prompt_response ?? ''), stopHookActive: i?.stop_hook_active === true }),
|
|
105
|
+
session: sessionId,
|
|
82
106
|
block: exit2Block,
|
|
107
|
+
stopBlock: exit2Block, // AfterAgent: exit 2 retries with stderr as the new prompt
|
|
83
108
|
notice: systemMessage,
|
|
84
109
|
},
|
|
85
110
|
codex: {
|
|
@@ -92,6 +117,7 @@ export const agents = {
|
|
|
92
117
|
post: { event: 'PostToolUse', matcher: 'Bash' },
|
|
93
118
|
// Codex edits through apply_patch; the patch text names each file ("*** Update File: src/a.ts").
|
|
94
119
|
edit: { event: 'PostToolUse', matcher: 'apply_patch' },
|
|
120
|
+
stop: { event: 'Stop' },
|
|
95
121
|
parseEdit: (i) => {
|
|
96
122
|
const files = [...String(i?.tool_input?.command ?? '').matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => m[1].trim());
|
|
97
123
|
return files.length ? files : undefined;
|
|
@@ -100,9 +126,12 @@ export const agents = {
|
|
|
100
126
|
parsePre: nestedPre,
|
|
101
127
|
parsePost: (i) => {
|
|
102
128
|
const err = nonZeroExit(i?.tool_response);
|
|
103
|
-
return err ? { command: cmdOf(i), error: err, cwd: str(i?.cwd) } : null;
|
|
129
|
+
return err ? { command: cmdOf(i), error: err, cwd: str(i?.cwd), sessionId: sessionId(i) } : null;
|
|
104
130
|
},
|
|
131
|
+
parseStop: (i) => ({ sessionId: sessionId(i), cwd: str(i?.cwd), lastMessage: String(i?.last_assistant_message ?? ''), stopHookActive: i?.stop_hook_active === true }),
|
|
132
|
+
session: sessionId,
|
|
105
133
|
block: exit2Block,
|
|
134
|
+
stopBlock: exit2Block,
|
|
106
135
|
notice: systemMessage,
|
|
107
136
|
},
|
|
108
137
|
};
|
package/dist/hooks.js
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
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
9
|
import { 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
|
-
|
|
13
|
+
// Exported so the calibration script (scripts/calibrate.mjs) measures exactly the questions that ship.
|
|
14
|
+
export const Q = {
|
|
11
15
|
credential_leak: {
|
|
12
16
|
type: 'noul',
|
|
13
17
|
instructions: 'Does this git diff add a real secret (API key, token, password, private key) to the repository? ' +
|
|
@@ -55,12 +59,19 @@ const Q = {
|
|
|
55
59
|
},
|
|
56
60
|
// Calibrated 2026-10-05 on 21 hand-written turns: unverified >= 0.71 except a test run in the wrong package (0.17);
|
|
57
61
|
// verified <= 0.24. Needs the computed "Fact" line: without it, tests run before the last edit scored 0.25.
|
|
62
|
+
// 2026-10-06, +10 plan-checklist turns from real spec-kit/GSD/specOS plans: unsupported ticks 0.75-0.95, supported
|
|
63
|
+
// 0.11-0.30 (a parent whose nested items are all checked: 0.30). A parent ticked over open nested items scored 0.60
|
|
64
|
+
// until the open-nested-items Fact was added (0.75).
|
|
58
65
|
done_unverified: {
|
|
59
66
|
type: 'noul',
|
|
60
67
|
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
68
|
'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
|
-
'
|
|
69
|
+
'or the final message claims passing tests, a working result, or a manual check that the action log does not support; ' +
|
|
70
|
+
'or it marked plan checklist items done that its actions do not support. ' +
|
|
71
|
+
'A summary item (a phase, milestone, or an item with nested items) records work finished over earlier turns: ' +
|
|
72
|
+
'it is supported when its nested items are all checked, or when this turn ran a passing check that covers it; ' +
|
|
73
|
+
'it is unsupported when nested items are still open. ' +
|
|
74
|
+
'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
75
|
'or the agent plainly told the user what is not verified yet and why.',
|
|
65
76
|
criteria: {
|
|
66
77
|
true: 'The work is presented as done but the action log does not show it was verified',
|
|
@@ -103,6 +114,15 @@ export const touchesTests = (diff) => TESTISH.test(diff);
|
|
|
103
114
|
// Pinned diff format: user config (noprefix, color.diff=always, external diff, textconv) would break parsing and masking.
|
|
104
115
|
export const DIFF_ARGS = ['diff', '--cached', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
|
|
105
116
|
export const stagedDiff = (cwd) => execFileSync('git', DIFF_ARGS, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
117
|
+
/** Uncommitted changes (staged and not) to tracked markdown files, for checklist ticks. Empty outside git or before the first commit. */
|
|
118
|
+
export function planDiff(cwd) {
|
|
119
|
+
try {
|
|
120
|
+
return execFileSync('git', ['diff', 'HEAD', ...DIFF_ARGS.slice(2), '--', '*.md', '*.mdx'], { cwd, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return '';
|
|
124
|
+
}
|
|
125
|
+
}
|
|
106
126
|
// 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
127
|
// A timeout means "let it through unchecked", so wait as long as the git side does rather than fail open.
|
|
108
128
|
export const AGENT_TIMEOUT_MS = 5000;
|
|
@@ -208,15 +228,23 @@ export async function agentPre(agent, input, { root, lang, now }) {
|
|
|
208
228
|
const brain = loadBrain(root);
|
|
209
229
|
const questions = { destructive_command: Q.destructive_command };
|
|
210
230
|
let state = maskSensitiveState(command);
|
|
231
|
+
// A command that writes code files (sed -i, redirects, formatters) is a fix attempt, same as an edit tool. Marked
|
|
232
|
+
// before it runs: pre hooks exist for every agent, so this also covers agents without a usable edit event.
|
|
233
|
+
const written = shellWrites(command);
|
|
234
|
+
if (input.sessionId && !agent.transcriptTurns && agent.stop) {
|
|
235
|
+
for (const f of written)
|
|
236
|
+
logAction(brain, input.sessionId, { kind: 'edit', file: f === '?' ? `(files written by: ${command.slice(0, 60)})` : f });
|
|
237
|
+
logAction(brain, input.sessionId, { kind: 'run', command: maskSensitiveState(command), ok: true, tail: '' });
|
|
238
|
+
}
|
|
239
|
+
if (written.length && (written.includes('?') || written.some(isCodeFile)) && brain.recent_errors.some((e) => !e.edited_after)) {
|
|
240
|
+
brain.recent_errors = brain.recent_errors.map((e) => ({ ...e, edited_after: true }));
|
|
241
|
+
}
|
|
211
242
|
const recent = freshErrors(brain, (now ?? Date.now)());
|
|
212
243
|
// One block per loop episode: once warned about the latest failure, the next attempt may run (it may be the real fix).
|
|
213
244
|
// A new failure after that is unwarned again and can be blocked again.
|
|
214
245
|
if (recent.length && !recent.at(-1).warned) {
|
|
215
246
|
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)}`;
|
|
247
|
+
state = loopState(command, recent);
|
|
220
248
|
}
|
|
221
249
|
const notices = new Set();
|
|
222
250
|
const { sessionId } = input;
|
|
@@ -252,29 +280,71 @@ export async function agentPre(agent, input, { root, lang, now }) {
|
|
|
252
280
|
* Blocks once (exit 2 makes the agent keep working); never blocks again while a stop hook is already active,
|
|
253
281
|
* so it cannot loop. Turns without code edits never reach Jev.
|
|
254
282
|
*/
|
|
255
|
-
export async function agentStop(input, { root, lang, now }) {
|
|
256
|
-
|
|
257
|
-
|
|
283
|
+
export async function agentStop(agent, input, { root, lang, now }) {
|
|
284
|
+
let out = { code: 0, stderr: [] };
|
|
285
|
+
const brain = loadBrain(root);
|
|
286
|
+
// Claude Code: read the turn from its transcript. Others: cto's own turn log, which ends with this stop either way.
|
|
287
|
+
const logged = input.sessionId ? brain.turns?.[input.sessionId] : undefined;
|
|
288
|
+
if (!input.transcriptPath && input.sessionId && brain.turns?.[input.sessionId]) {
|
|
289
|
+
delete brain.turns[input.sessionId];
|
|
290
|
+
saveBrain(root, brain);
|
|
291
|
+
}
|
|
292
|
+
if (input.stopHookActive)
|
|
258
293
|
return out;
|
|
259
|
-
const actions = turnActions(input.transcriptPath, input.cwd);
|
|
260
|
-
|
|
294
|
+
const actions = input.transcriptPath ? turnActions(input.transcriptPath, input.cwd) : logged?.actions ?? [];
|
|
295
|
+
const lastMessage = input.lastMessage || logged?.reply || '';
|
|
296
|
+
// ponytail: ticks are attributed to the turn that ends after they appear, so a box the user ticked by hand between
|
|
297
|
+
// turns is judged against the agent's turn. Rare; per-turn snapshots of plan files would fix it.
|
|
298
|
+
const judged = new Set(brain.judged_items ?? []);
|
|
299
|
+
const ticked = tickedItems(planDiff(root), (f) => { try {
|
|
300
|
+
return readFileSync(join(root, f), 'utf8');
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
return undefined;
|
|
304
|
+
} })
|
|
305
|
+
.filter((t) => !judged.has(tickedKey(t)));
|
|
306
|
+
if (!ticked.length && !actions.some((a) => a.kind === 'edit' && isCodeFile(a.file)))
|
|
261
307
|
return out;
|
|
262
308
|
const cfg = loadConfig(root);
|
|
263
|
-
const
|
|
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 });
|
|
309
|
+
const r = await evaluate({ state: turnState(lastMessage, actions, ticked), questions: { done_unverified: Q.done_unverified }, ...(input.sessionId && { session_id: input.sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices: new Set(), now });
|
|
265
310
|
if (!r.ok)
|
|
266
311
|
brain.skipped_attempts++;
|
|
267
|
-
else
|
|
312
|
+
else {
|
|
268
313
|
countCheck(brain, now);
|
|
314
|
+
brain.judged_items = [...judged, ...ticked.map(tickedKey)].slice(-300);
|
|
315
|
+
}
|
|
269
316
|
const v = r.ok ? exceeded(r.answers, 'done_unverified', cfg) : undefined;
|
|
270
317
|
if (v !== undefined) {
|
|
271
318
|
brain.blocked_attempts++;
|
|
272
|
-
out
|
|
273
|
-
out.stderr = verdict(lang, 'done_unverified', v, cfg, null);
|
|
319
|
+
out = agent.stopBlock(verdict(lang, 'done_unverified', v, cfg, null));
|
|
274
320
|
}
|
|
275
321
|
saveBrain(root, brain);
|
|
276
322
|
return out;
|
|
277
323
|
}
|
|
324
|
+
// ---------- turn log (agents without a readable transcript) ----------
|
|
325
|
+
const TURN_MAX_ACTIONS = 80;
|
|
326
|
+
const TURN_MAX_SESSIONS = 5;
|
|
327
|
+
/** Append one action to a session's turn log; keeps the log and the number of sessions bounded. */
|
|
328
|
+
export function logAction(brain, sessionId, action) {
|
|
329
|
+
brain.turns ??= {};
|
|
330
|
+
const t = (brain.turns[sessionId] ??= { at: '', actions: [] });
|
|
331
|
+
t.actions = [...t.actions, action].slice(-TURN_MAX_ACTIONS);
|
|
332
|
+
t.at = new Date().toISOString();
|
|
333
|
+
const ids = Object.keys(brain.turns).sort((a, b) => brain.turns[b].at.localeCompare(brain.turns[a].at));
|
|
334
|
+
for (const id of ids.slice(TURN_MAX_SESSIONS))
|
|
335
|
+
delete brain.turns[id];
|
|
336
|
+
}
|
|
337
|
+
/** Cursor's final reply arrives in its own event, before stop. */
|
|
338
|
+
export function agentReply(input, { root }) {
|
|
339
|
+
if (!input.sessionId || !input.text.trim())
|
|
340
|
+
return { code: 0, stderr: [] };
|
|
341
|
+
const brain = loadBrain(root);
|
|
342
|
+
brain.turns ??= {};
|
|
343
|
+
const t = (brain.turns[input.sessionId] ??= { at: new Date().toISOString(), actions: [] });
|
|
344
|
+
t.reply = input.text;
|
|
345
|
+
saveBrain(root, brain);
|
|
346
|
+
return { code: 0, stderr: [] };
|
|
347
|
+
}
|
|
278
348
|
// ---------- post (failure recording) ----------
|
|
279
349
|
/** Record the failure only; never calls Jev. No error field, no record. */
|
|
280
350
|
/**
|
|
@@ -282,16 +352,28 @@ export async function agentStop(input, { root, lang, now }) {
|
|
|
282
352
|
* 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
353
|
* the history shows that. Local only: no Jev call, no network. Docs/YAML edits do not count.
|
|
284
354
|
*/
|
|
285
|
-
export function agentEdit(files, { root }) {
|
|
355
|
+
export function agentEdit(files, { root }, logSession) {
|
|
356
|
+
const brain = loadBrain(root);
|
|
357
|
+
if (logSession) {
|
|
358
|
+
for (const f of files ?? ['(unknown file)'])
|
|
359
|
+
logAction(brain, logSession, { kind: 'edit', file: f });
|
|
360
|
+
saveBrain(root, brain);
|
|
361
|
+
}
|
|
286
362
|
if (files && !files.some(isCodeFile))
|
|
287
363
|
return { code: 0, stderr: [] };
|
|
288
|
-
const brain = loadBrain(root);
|
|
289
364
|
if (brain.recent_errors.some((e) => !e.edited_after)) {
|
|
290
365
|
brain.recent_errors = brain.recent_errors.map((e) => ({ ...e, edited_after: true }));
|
|
291
366
|
saveBrain(root, brain);
|
|
292
367
|
}
|
|
293
368
|
return { code: 0, stderr: [] };
|
|
294
369
|
}
|
|
370
|
+
/** The state Jev sees for the loop question: the command, the recent failures (marked when code was edited after), and the computed fact. */
|
|
371
|
+
export function loopState(command, recent) {
|
|
372
|
+
const masked = maskSensitiveState(command);
|
|
373
|
+
return `Command about to run:\n${masked}\n\nRecently failed commands (oldest first):\n` +
|
|
374
|
+
recent.map((e) => `$ ${e.command}\n${e.error}${e.edited_after ? '\n(the agent edited code after this failure)' : ''}`).join('\n\n') +
|
|
375
|
+
`\n\n${loopFact(masked, recent)}`;
|
|
376
|
+
}
|
|
295
377
|
/** Facts code can count exactly, so Jev does not have to: repeats of this command, the error streak, edits since. */
|
|
296
378
|
export function loopFact(command, recent) {
|
|
297
379
|
const norm = (s) => s.trim().replace(/\s+/g, ' ');
|
|
@@ -308,6 +390,12 @@ export function agentPost(input, { root }) {
|
|
|
308
390
|
if (!input)
|
|
309
391
|
return { code: 0, stderr: [] };
|
|
310
392
|
const brain = loadBrain(root);
|
|
393
|
+
const turn = input.sessionId ? brain.turns?.[input.sessionId] : undefined;
|
|
394
|
+
const run = turn?.actions.findLast((a) => a.kind === 'run' && a.command === maskSensitiveState(input.command));
|
|
395
|
+
if (run && run.kind === 'run') {
|
|
396
|
+
run.ok = false;
|
|
397
|
+
run.tail = maskSensitiveState(input.error).slice(-300);
|
|
398
|
+
}
|
|
311
399
|
brain.recent_errors = [
|
|
312
400
|
...freshErrors(brain),
|
|
313
401
|
{
|
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
|
};
|
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, 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,7 @@ 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
|
+
const m = /^(claude|cursor|gemini|codex)-(pre|post|stop|edit|reply)$/.exec(name);
|
|
46
46
|
if (!m)
|
|
47
47
|
return { code: 0, stderr: [] };
|
|
48
48
|
const agent = agents[m[1]];
|
|
@@ -53,7 +53,13 @@ async function runHook(name) {
|
|
|
53
53
|
catch { /* fail-open below */ }
|
|
54
54
|
if (m[2] === 'edit') {
|
|
55
55
|
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 });
|
|
56
|
+
return agentEdit(agent.parseEdit?.(input), { root: findRoot(cwd), lang }, agent.transcriptTurns ? undefined : agent.session(input));
|
|
57
|
+
}
|
|
58
|
+
if (m[2] === 'reply') {
|
|
59
|
+
if (!agent.parseReply)
|
|
60
|
+
return { code: 0, stderr: [] };
|
|
61
|
+
const reply = agent.parseReply(input);
|
|
62
|
+
return agentReply(reply, { root: findRoot(reply.cwd ?? process.cwd()), lang });
|
|
57
63
|
}
|
|
58
64
|
if (m[2] === 'stop') {
|
|
59
65
|
if (!agent.parseStop)
|
|
@@ -61,7 +67,7 @@ async function runHook(name) {
|
|
|
61
67
|
const stop = agent.parseStop(input);
|
|
62
68
|
const root = findRoot(stop.cwd ?? process.cwd());
|
|
63
69
|
debug(root, maskSensitiveState(raw));
|
|
64
|
-
return agentStop(stop, { root, lang });
|
|
70
|
+
return agentStop(agent, stop, { root, lang });
|
|
65
71
|
}
|
|
66
72
|
if (m[2] === 'pre') {
|
|
67
73
|
const pre = agent.parsePre(input);
|
package/dist/setup.js
CHANGED
|
@@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process';
|
|
|
2
2
|
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { basename, dirname, join, relative } from 'node:path';
|
|
5
|
-
import { agentNames, agents, hookCommand } from './agents.js';
|
|
5
|
+
import { PHASES, agentNames, agents, hookCommand } from './agents.js';
|
|
6
6
|
import { t } from './i18n.js';
|
|
7
7
|
import { guidancePaths, syncGuidance } from './skill.js';
|
|
8
8
|
const START = '# >>> YOUR CTO JEV START >>>';
|
|
@@ -54,7 +54,7 @@ function validShape(json, name) {
|
|
|
54
54
|
if (!isObj(json.hooks))
|
|
55
55
|
return false;
|
|
56
56
|
const a = agents[name];
|
|
57
|
-
return
|
|
57
|
+
return PHASES.map((p) => a[p]).every((spec) => !spec || json.hooks[spec.event] === undefined || Array.isArray(json.hooks[spec.event]));
|
|
58
58
|
}
|
|
59
59
|
function writeOrRemove(path, settings) {
|
|
60
60
|
const meaningful = Object.keys(settings).filter((k) => k !== 'version');
|
|
@@ -72,7 +72,7 @@ function installAgent(settings, name) {
|
|
|
72
72
|
settings.hooks ??= {};
|
|
73
73
|
if (a.style === 'cursor')
|
|
74
74
|
settings.version ??= 1;
|
|
75
|
-
for (const phase of
|
|
75
|
+
for (const phase of PHASES) {
|
|
76
76
|
const spec = a[phase];
|
|
77
77
|
if (!spec)
|
|
78
78
|
continue;
|
|
@@ -242,7 +242,7 @@ export function missingHooks(root) {
|
|
|
242
242
|
const missing = [];
|
|
243
243
|
for (const n of wiredAgents(root)) {
|
|
244
244
|
const text = readFileSync(join(root, agents[n].settings), 'utf8');
|
|
245
|
-
for (const phase of
|
|
245
|
+
for (const phase of PHASES) {
|
|
246
246
|
if (agents[n][phase] && !text.includes(hookCommand(n, phase)))
|
|
247
247
|
missing.push(hookCommand(n, phase));
|
|
248
248
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Heuristic: which files does a shell command write? Agents often edit with sed -i, redirects or formatters instead
|
|
2
|
+
// of their edit tools, and both loop detection and the done check need to know an edit happened.
|
|
3
|
+
// Returns the files it can name, ['?'] when it clearly writes but the target is unclear, or [] for no write.
|
|
4
|
+
// ponytail: regex over the command line, no shell parser. Misses writes hidden in scripts (node -e, python -c);
|
|
5
|
+
// upgrade to a real shell tokenizer if false negatives matter.
|
|
6
|
+
const WRITERS = [
|
|
7
|
+
{ re: /\bsed\b[^|;&]*\s-i\b|\bsed\s+-[a-zA-Z]*i/, target: /(\S+)\s*$/ }, // sed -i ... file
|
|
8
|
+
{ re: /\bperl\b[^|;&]*\s-[a-zA-Z]*p[a-zA-Z]*i|\bperl\b[^|;&]*\s-[a-zA-Z]*i[a-zA-Z]*p/, target: /(\S+)\s*$/ },
|
|
9
|
+
{ re: /\btee\b(?:\s+-a)?\s+(\S+)/ },
|
|
10
|
+
{ re: /\b(?:cp|mv)\b(?:\s+-\S+)*\s+\S+\s+(\S+)/ }, // last argument is the destination
|
|
11
|
+
{ re: /\brm\b(?:\s+-\S+)*\s+(\S+)/ },
|
|
12
|
+
{ re: /\bgit\s+(?:apply|am|checkout\s+--|restore)\b/ },
|
|
13
|
+
{ re: /\bpatch\b\s+(?:-\S+\s+)*(\S+)?/ },
|
|
14
|
+
{ re: /\b(?:prettier|biome)\b[^|;&]*--write\b/ },
|
|
15
|
+
{ re: /\b(?:eslint|ruff|rubocop)\b[^|;&]*--fix\b/ },
|
|
16
|
+
{ re: /\b(?:black|gofmt\s+-w|cargo\s+fmt|ruff\s+format)\b/ },
|
|
17
|
+
];
|
|
18
|
+
// Redirect into a file: > or >> followed by a path. Not 2>&1, not >&2, not /dev/null, not process substitution.
|
|
19
|
+
const REDIRECT = /(?:^|[^\d&>])>>?\s*(?!&|\/dev\/null|\()([^\s;&|<>]+)/g;
|
|
20
|
+
const clean = (p) => p.replace(/^['"]|['"]$/g, '');
|
|
21
|
+
export function shellWrites(command) {
|
|
22
|
+
const files = new Set();
|
|
23
|
+
let unknown = false;
|
|
24
|
+
// Look at each simple command of a pipeline/list separately.
|
|
25
|
+
for (const part of command.split(/&&|\|\||;|\n/)) {
|
|
26
|
+
for (const m of part.matchAll(REDIRECT))
|
|
27
|
+
files.add(clean(m[1]));
|
|
28
|
+
for (const w of WRITERS) {
|
|
29
|
+
const m = w.re.exec(part);
|
|
30
|
+
if (!m)
|
|
31
|
+
continue;
|
|
32
|
+
const t = w.target ? w.target.exec(part)?.[1] : m[1];
|
|
33
|
+
if (t && !t.startsWith('-'))
|
|
34
|
+
files.add(clean(t));
|
|
35
|
+
else
|
|
36
|
+
unknown = true;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return files.size ? [...files] : unknown ? ['?'] : [];
|
|
40
|
+
}
|
package/dist/skill.js
CHANGED
|
@@ -24,7 +24,7 @@ This repo is guarded by cto: every rule below is checked automatically, and brea
|
|
|
24
24
|
|
|
25
25
|
- **Secrets stay out of code.** Use environment variables, never literal keys, tokens or passwords. (\`credential_leak\` blocks the commit)
|
|
26
26
|
- **Fix the code, not the tests.** Never skip, delete or loosen a test, rewrite an expectation to match wrong output, or lower coverage. (\`test_tampering\` blocks the commit)
|
|
27
|
-
- **Done means verified.** After your last code change, run the relevant tests or build and see them pass before saying done; otherwise say what is unverified. (\`done_unverified\` sends you back)
|
|
27
|
+
- **Done means verified.** After your last code change, run the relevant tests or build and see them pass before saying done or checking off a plan item; otherwise say what is unverified. (\`done_unverified\` sends you back)
|
|
28
28
|
- **Two strikes, change approach.** Same command, same error twice: stop retrying and try something different. (\`infinite_loop\` blocks the retry)
|
|
29
29
|
- **Ask before anything irreversible:** deleting data, force-pushing, rewriting history, dropping a database. (\`destructive_command\` blocks it)
|
|
30
30
|
- **Stay on the sprint goal in \`.cto.json\` and keep changes simple.** (\`architecture_violation\` and \`code_complexity\` warn)
|
|
@@ -48,7 +48,7 @@ Each rule below has a check behind it. Following the rules is faster than being
|
|
|
48
48
|
|---|---|
|
|
49
49
|
| **Secrets stay out of code.** Never write API keys, tokens, passwords or private keys into code or committed files. Read them from environment variables. | \`credential_leak\` blocks the commit |
|
|
50
50
|
| **Fix the code, not the tests.** When a test fails, change the code under test. Never skip, comment out or delete a test, loosen an assertion, change an expected value to match wrong output, swallow the error, or lower a coverage threshold. A test may only go away together with the feature it covers, and you say so. | \`test_tampering\` blocks the commit |
|
|
51
|
-
| **Done means verified.** After your last code change, run the relevant tests, build or type check and see it pass before you say the work is done. If you cannot, say plainly what is not verified and why. | \`done_unverified\` sends you back to work |
|
|
51
|
+
| **Done means verified.** After your last code change, run the relevant tests, build or type check and see it pass before you say the work is done. Checking off a plan item (\`- [x]\`) is the same claim; check off a phase or parent item only when everything under it is done. If you cannot, say plainly what is not verified and why. | \`done_unverified\` sends you back to work |
|
|
52
52
|
| **Two strikes, change approach.** If a command fails with the same error twice, stop retrying. Read the error, inspect the code, and try something different. | \`infinite_loop\` blocks the retry once |
|
|
53
53
|
| **Ask before anything irreversible.** Get the user's explicit OK before deleting data outside build output, force-pushing, rewriting shared history, or dropping a database. | \`destructive_command\` blocks the command |
|
|
54
54
|
| **Stay on the sprint goal.** If \`.cto.json\` sets a \`sprint_goal\`, keep changes inside it and point out anything unrelated. | \`architecture_violation\` warns |
|
package/dist/turn.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
2
|
import { relative } from 'node:path';
|
|
3
3
|
import { maskSensitiveState } from './masker.js';
|
|
4
|
+
import { shellWrites } from './shellwrites.js';
|
|
4
5
|
const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
|
|
5
6
|
// Edits that no local test could check: docs, CI and other YAML config.
|
|
6
7
|
const NON_CODE = /(\.(md|mdx|txt|rst|adoc|ya?ml)$)|(^|[\\/])\.github[\\/]/i;
|
|
@@ -70,14 +71,78 @@ export function turnActions(transcriptPath, cwd) {
|
|
|
70
71
|
const r = results.get(b.id);
|
|
71
72
|
if (!r)
|
|
72
73
|
continue; // not finished (or transcript lagging): no evidence either way
|
|
73
|
-
|
|
74
|
+
const command = String(b.input?.command ?? '');
|
|
75
|
+
// A successful shell command that writes files is an edit too (sed -i, redirects, formatters). Listed before
|
|
76
|
+
// the run itself, since in "sed -i ... && npm test" the write happens before the test.
|
|
77
|
+
if (r.ok)
|
|
78
|
+
for (const f of shellWrites(command))
|
|
79
|
+
actions.push({ kind: 'edit', file: f === '?' ? `(files written by: ${oneLine(command, 60)})` : f });
|
|
80
|
+
actions.push({ kind: 'run', command, ok: r.ok, tail: r.text });
|
|
74
81
|
}
|
|
75
82
|
}
|
|
76
83
|
}
|
|
77
84
|
return actions;
|
|
78
85
|
}
|
|
79
|
-
|
|
80
|
-
|
|
86
|
+
const BOX = /^(\s*)[-*+] \[([ xX])\]\s+(.*)$/;
|
|
87
|
+
const itemKey = (file, text) => `${file}:${text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 60)}`;
|
|
88
|
+
/**
|
|
89
|
+
* Checklist items a unified diff of markdown files marks done: every added "[x]" line, except ones that were already
|
|
90
|
+
* "[x]" before (reworded or moved). Works for any plan format that uses checkboxes (spec-kit, GSD, Kiro, specOS...),
|
|
91
|
+
* whatever tool wrote the file. `read` returns a file's current text, for the lines nested under each item.
|
|
92
|
+
*/
|
|
93
|
+
export function tickedItems(diff, read) {
|
|
94
|
+
let file = '';
|
|
95
|
+
const before = [];
|
|
96
|
+
const added = [];
|
|
97
|
+
for (const line of diff.split(/\r?\n/)) {
|
|
98
|
+
if (line.startsWith('+++ ')) {
|
|
99
|
+
file = line.slice(4).replace(/^b\//, '');
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (line.startsWith('--- '))
|
|
103
|
+
continue;
|
|
104
|
+
const m = BOX.exec(line.slice(1));
|
|
105
|
+
if (!m || m[2] === ' ')
|
|
106
|
+
continue;
|
|
107
|
+
if (line[0] === '-')
|
|
108
|
+
before.push(itemKey(file, m[3]));
|
|
109
|
+
else if (line[0] === '+')
|
|
110
|
+
added.push({ file, text: m[3].trim(), line: line.slice(1) });
|
|
111
|
+
}
|
|
112
|
+
// Already done before when one wording extends the other ("Fix X" -> "Fix X (see #12)").
|
|
113
|
+
const wasDone = (k) => before.some((b) => k.startsWith(b) || b.startsWith(k));
|
|
114
|
+
return added.filter((a) => !wasDone(itemKey(a.file, a.text))).map(({ line, ...a }) => ({ ...a, children: nested(read(a.file), line) }));
|
|
115
|
+
}
|
|
116
|
+
/** Checklist lines indented under `item` in `text` (at most 15). */
|
|
117
|
+
function nested(text, item) {
|
|
118
|
+
const lines = text?.split(/\r?\n/) ?? [];
|
|
119
|
+
const at = lines.indexOf(item);
|
|
120
|
+
if (at < 0)
|
|
121
|
+
return [];
|
|
122
|
+
const indent = BOX.exec(item)[1].length;
|
|
123
|
+
const out = [];
|
|
124
|
+
for (const l of lines.slice(at + 1)) {
|
|
125
|
+
if (!l.trim())
|
|
126
|
+
continue;
|
|
127
|
+
const m = BOX.exec(l);
|
|
128
|
+
if (!m || m[1].length <= indent)
|
|
129
|
+
break;
|
|
130
|
+
out.push(`[${m[2] === ' ' ? ' ' : 'x'}] ${m[3].trim()}`);
|
|
131
|
+
}
|
|
132
|
+
return out.slice(0, 15);
|
|
133
|
+
}
|
|
134
|
+
/** Only said when some item has nested items: "none open" next to plain items reads as support for them. */
|
|
135
|
+
function openParents(ticked) {
|
|
136
|
+
if (!ticked.some((t) => t.children.length))
|
|
137
|
+
return '';
|
|
138
|
+
const open = ticked.filter((t) => t.children.some((c) => c.startsWith('[ ]')));
|
|
139
|
+
return '\nFact: ' + (open.length
|
|
140
|
+
? `${open.length} of the items marked done still have unchecked nested items: ${open.map((t) => oneLine(t.text, 60)).join('; ')}.`
|
|
141
|
+
: 'every nested item under the items marked done is checked.');
|
|
142
|
+
}
|
|
143
|
+
export const tickedKey = (t) => itemKey(t.file, t.text);
|
|
144
|
+
/** The text Jev sees: final message, the action log, the checklist items marked done, and the one fact code can compute exactly. Masked. */
|
|
145
|
+
export function turnState(lastMessage, actions, ticked = []) {
|
|
81
146
|
// The fact is computed over the whole turn; only the log shown to Jev is trimmed.
|
|
82
147
|
let lastEdit = -1;
|
|
83
148
|
actions.forEach((a, i) => { if (a.kind === 'edit' && isCodeFile(a.file))
|
|
@@ -92,5 +157,8 @@ export function turnState(lastMessage, actions) {
|
|
|
92
157
|
? `${i + 1}. edited ${a.file}`
|
|
93
158
|
: `${i + 1}. ran: ${oneLine(a.command, 200)} -> ${a.ok ? 'succeeded' : 'FAILED'}${a.tail ? `\n output tail: ${tailOf(a.tail, 200)}` : ''}`).join('\n')
|
|
94
159
|
: '(none)';
|
|
95
|
-
|
|
160
|
+
const plan = ticked.length
|
|
161
|
+
? `\n\nPlan checklist items marked done this turn:\n` + ticked.slice(0, 20).map((t) => `- ${t.file}: ${oneLine(t.text, 200)}${t.children.length ? `\n nested items: ${t.children.map((c) => oneLine(c, 80)).join('; ')}` : ''}`).join('\n') + openParents(ticked)
|
|
162
|
+
: '';
|
|
163
|
+
return maskSensitiveState(`The agent's final message to the user:\n"""\n${tailOf(lastMessage, 1500)}\n"""\n\nActions this turn, in order:\n${log}${plan}\n\nFact: ${fact}`);
|
|
96
164
|
}
|
package/dist/update.js
CHANGED
|
@@ -48,7 +48,8 @@ export async function checkUpdate(timeoutMs = 1000, now = Date.now()) {
|
|
|
48
48
|
/** npm install -g your-cto-jev@latest, output streamed to the terminal. */
|
|
49
49
|
export function runUpdate() {
|
|
50
50
|
// npm is npm.cmd on Windows, which needs a shell. One constant command string: nothing user-supplied is interpolated.
|
|
51
|
-
|
|
51
|
+
// --prefer-online: right after a release the local npm cache may not list the new version yet (ETARGET).
|
|
52
|
+
const r = spawnSync(`npm install -g ${PKG}@latest --prefer-online`, { stdio: 'inherit', shell: true });
|
|
52
53
|
try {
|
|
53
54
|
writeFileSync(cachePath(), JSON.stringify({ checked_at: 0 }) + '\n');
|
|
54
55
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "your-cto-jev",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "A sharp-tongued CTO gatekeeper for AI coding agents: blocks leaked secrets in git commits and destructive shell commands in Claude Code, Cursor, Gemini CLI and Codex, using TypeSafe Jev.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude-code",
|
|
@@ -38,7 +38,8 @@
|
|
|
38
38
|
"scripts": {
|
|
39
39
|
"build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc",
|
|
40
40
|
"test": "tsc && node --test \"dist/*.test.js\"",
|
|
41
|
-
"prepublishOnly": "npm run build && node --test \"dist/*.test.js\""
|
|
41
|
+
"prepublishOnly": "npm run build && node --test \"dist/*.test.js\"",
|
|
42
|
+
"calibrate": "npm run build && node scripts/calibrate.mjs"
|
|
42
43
|
},
|
|
43
44
|
"devDependencies": {
|
|
44
45
|
"@types/node": "^26.6.3",
|