your-cto-jev 0.9.5 → 0.9.6

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
@@ -41,7 +41,7 @@ Jev judges meaning and answers with probabilities, not prose. It costs about $0.
41
41
 
42
42
  `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.
43
43
 
44
- `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
+ `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. Checked-off items count even when the agent committed them in the same turn. For a task with an acceptance line (`accept:` or `驗收:`), cto itself works out whether that exact command ran and passed after the last edit and tells Jev, and a `manual` task ticked without the final message saying the user accepted it is sent back without asking Jev at all. It blocks at most once per stop, so it cannot loop.
45
45
 
46
46
  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.
47
47
 
@@ -362,7 +362,7 @@ Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6,
362
362
  - **`protected_branches`**: for example `["main", "release"]`. Commits on them and pushes that delete or rewrite them are blocked locally, no key needed. Empty by default.
363
363
  - **Thresholds**: Jev returns a probability from 0 to 1. `code_complexity` is the exception: it is a score from 0 (clean) to 4 (unmaintainable).
364
364
  - **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.
365
- - `done_unverified` (0.6) and `infinite_loop` (0.6) were calibrated the same way; the measurements are in the design spec.
365
+ - `done_unverified` (0.6) and `infinite_loop` (0.6) were calibrated the same way; the cases are in `calibration/`.
366
366
  - `architecture_violation` against a SPEC: on 11 hand-written diffs for one feature (three constraints, two non-goals), every violation scored 0.94 or above and every legitimate change 0.30 or below, so the 0.85 default sits in the gap. `architecture_undocumented` shares that default and has no calibration set yet; treat its warnings as hints.
367
367
  - **When a call is wrong**: `cto log` lists the last 30 answered questions in this repo with their scores and thresholds. `cto report` (or `cto report <n>`) records that the last (or n-th) one was wrong and writes it, with the exact masked state Jev saw, as a calibration case to `reports/<signal>.jsonl` next to your credentials file. Nothing is sent anywhere; paste the line into `calibration/candidates/` in a PR or an issue and it joins the next measurement. That is how the thresholds get better from real use instead of hand-written diffs.
368
368
  - 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.
package/dist/flow.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { BOX } from './turn.js';
3
+ import { ACCEPT, BOX } from './turn.js';
4
4
  // docs/cto_jev/features/<slug>/TASKS.md: the one place the development flow keeps state. Everything else (INDEX,
5
5
  // ready list, feature dependencies, code ownership) is computed from it. Format: FLOW_SKILL_TEXT in skill.ts.
6
6
  export const FLOW_DIR = 'docs/cto_jev';
@@ -9,7 +9,6 @@ const ID = /^([A-Z][A-Z0-9]*-\d+(?:\.\d+)*)\b\s*/;
9
9
  const TAG = /\s*\((after|files):\s*([^)]*)\)/g;
10
10
  const PRIORITY = /\s*\((P[123])\)/;
11
11
  const SEQ = /\s*\(seq\)/;
12
- const ACCEPT = /^\s*(?:驗收|accept)[::]\s*(.+?)\s*$/i;
13
12
  const list = (s) => s.split(/[,,]/).map((x) => x.trim()).filter(Boolean);
14
13
  /** Parses one TASKS.md. Items without an id are skipped (they are not tasks the flow can track). */
15
14
  export function parseTasks(text, feature, file) {
package/dist/hooks.js CHANGED
@@ -4,7 +4,7 @@ import { join } from 'node:path';
4
4
  import { FLOW_DIR, featureIndex } from './flow.js';
5
5
  import { styleText } from 'node:util';
6
6
  import { checkUpdate, currentVersion } from './update.js';
7
- import { isCodeFile, tickedItems, tickedKey, turnActions, turnState } from './turn.js';
7
+ import { isCodeFile, manualUnconfirmed, tickedItems, tickedKey, turnActions, turnState } from './turn.js';
8
8
  import { shellWrites } from './shellwrites.js';
9
9
  import { evaluate, providerOrder, providers } from './api.js';
10
10
  import { DECISIONS_KEPT, DECISION_STATE_CHARS, freshErrors, loadBrain, loadConfig, saveBrain } from './brain.js';
@@ -195,9 +195,22 @@ export const touchesTests = (diff) => TESTISH.test(diff);
195
195
  export const DIFF_ARGS = ['diff', '--cached', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
196
196
  export const stagedDiff = (cwd) => execFileSync('git', DIFF_ARGS, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
197
197
  /** Uncommitted changes (staged and not) to tracked markdown files, for checklist ticks. Empty outside git or before the first commit. */
198
- export function planDiff(cwd) {
198
+ /** How long a recorded turn base stays valid: longer than any one agent turn, shorter than a gap between sessions. */
199
+ export const TURN_BASE_TTL_MS = 6 * 60 * 60 * 1000;
200
+ /** `commit` still exists and is an ancestor of HEAD (not amended or rebased away). */
201
+ function isAncestor(cwd, commit) {
199
202
  try {
200
- return execFileSync('git', ['diff', 'HEAD', ...DIFF_ARGS.slice(2), '--', '*.md', '*.mdx'], { cwd, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
203
+ execFileSync('git', ['merge-base', '--is-ancestor', commit, 'HEAD'], { cwd, stdio: 'ignore' });
204
+ return true;
205
+ }
206
+ catch {
207
+ return false;
208
+ }
209
+ }
210
+ /** Markdown changes from `base` (default HEAD) to the working tree: committed since `base` and uncommitted alike. */
211
+ export function planDiff(cwd, base = 'HEAD') {
212
+ try {
213
+ return execFileSync('git', ['diff', base, ...DIFF_ARGS.slice(2), '--', '*.md', '*.mdx'], { cwd, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
201
214
  }
202
215
  catch {
203
216
  return '';
@@ -344,6 +357,19 @@ export async function agentPre(agent, input, { root, lang, now }) {
344
357
  return { code: 0, stderr: [] };
345
358
  const cfg = loadConfig(root);
346
359
  const brain = loadBrain(root);
360
+ // The flow ticks a task and commits it in the same turn; the stop check diffs from here so those ticks are not missed.
361
+ const turnKey = input.sessionId ?? '';
362
+ const at = (now ?? Date.now)();
363
+ const kept = brain.turn_base?.[turnKey];
364
+ // A turn interrupted without a stop event leaves its base behind; one older than TURN_BASE_TTL_MS belongs to it.
365
+ if (/\bgit\b[^;&|]*\bcommit\b/.test(command) && (!kept || at - kept.at > TURN_BASE_TTL_MS)) {
366
+ try {
367
+ const head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
368
+ const others = Object.entries(brain.turn_base ?? {}).filter(([k, b]) => k !== turnKey && at - b.at <= TURN_BASE_TTL_MS);
369
+ brain.turn_base = Object.fromEntries([...others.slice(-20), [turnKey, { head, at }]]);
370
+ }
371
+ catch { /* no commit yet: the plain HEAD diff covers it */ }
372
+ }
347
373
  const questions = { destructive_command: Q.destructive_command };
348
374
  let state = maskSensitiveState(command);
349
375
  // A command that writes code files (sed -i, redirects, formatters) is a fix attempt, same as an edit tool. Marked
@@ -414,13 +440,21 @@ export async function agentStop(agent, input, { root, lang, now }) {
414
440
  const lessons = loadLessons(root);
415
441
  if (resolveFromTurn(lessons, actions, root, new Date((now ?? Date.now)())).length)
416
442
  saveLessons(root, lessons);
443
+ // Every stop ends the turn, so the recorded base is used once and cleared.
444
+ const turnKey = input.sessionId ?? '';
445
+ const recorded = brain.turn_base?.[turnKey];
446
+ if (recorded) {
447
+ delete brain.turn_base[turnKey];
448
+ saveBrain(root, brain);
449
+ }
450
+ const base = recorded && (now ?? Date.now)() - recorded.at <= TURN_BASE_TTL_MS && isAncestor(root, recorded.head) ? recorded.head : undefined;
417
451
  if (input.stopHookActive)
418
452
  return out;
419
453
  const lastMessage = input.lastMessage || logged?.reply || '';
420
454
  // ponytail: ticks are attributed to the turn that ends after they appear, so a box the user ticked by hand between
421
455
  // turns is judged against the agent's turn. Rare; per-turn snapshots of plan files would fix it.
422
456
  const judged = new Set(brain.judged_items ?? []);
423
- const ticked = tickedItems(planDiff(root), (f) => { try {
457
+ const ticked = tickedItems(planDiff(root, base), (f) => { try {
424
458
  return readFileSync(join(root, f), 'utf8');
425
459
  }
426
460
  catch {
@@ -429,20 +463,35 @@ export async function agentStop(agent, input, { root, lang, now }) {
429
463
  .filter((t) => !judged.has(tickedKey(t)));
430
464
  if (!ticked.length && !actions.some((a) => a.kind === 'edit' && isCodeFile(a.file)))
431
465
  return out;
466
+ // A manual task ticked without the user's confirmation is a text fact, not a judgement: cto blocks it itself. Jev
467
+ // still judges everything else in the turn, since this stop's block is the only one it gets.
468
+ const manual = manualUnconfirmed(ticked, lastMessage);
469
+ const manualLines = manual.slice(0, 5).map((m) => t(lang, 'done_manual', { detail: m.text.slice(0, 80) }));
470
+ const rest = ticked.filter((x) => !manual.includes(x));
471
+ if (!rest.length && !actions.some((a) => a.kind === 'edit' && isCodeFile(a.file))) {
472
+ brain.blocked_attempts++;
473
+ brain.judged_items = [...judged, ...manual.map(tickedKey)].slice(-300);
474
+ saveBrain(root, brain);
475
+ return agent.stopBlock(manualLines);
476
+ }
432
477
  const cfg = loadConfig(root);
433
- const state = turnState(lastMessage, actions, ticked);
478
+ const state = turnState(lastMessage, actions, rest);
434
479
  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 });
435
- if (!r.ok)
480
+ if (!r.ok) {
436
481
  brain.skipped_attempts++;
482
+ if (manual.length)
483
+ brain.judged_items = [...judged, ...manual.map(tickedKey)].slice(-300);
484
+ }
437
485
  else {
438
486
  countCheck(brain, now);
439
487
  logDecision(brain, 'stop', state, r.answers, cfg, now);
440
488
  brain.judged_items = [...judged, ...ticked.map(tickedKey)].slice(-300);
441
489
  }
442
490
  const v = r.ok ? exceeded(r.answers, 'done_unverified', cfg) : undefined;
443
- if (v !== undefined) {
491
+ const lines = [...manualLines, ...(v !== undefined ? verdict(lang, 'done_unverified', v, cfg, null) : [])];
492
+ if (lines.length) {
444
493
  brain.blocked_attempts++;
445
- out = agent.stopBlock(verdict(lang, 'done_unverified', v, cfg, null));
494
+ out = agent.stopBlock(lines);
446
495
  }
447
496
  saveBrain(root, brain);
448
497
  return out;
package/dist/i18n.js CHANGED
@@ -63,6 +63,7 @@ const messages = {
63
63
  local_flow_index_stale: (v) => `[cto] TASKS/CONCEPT/SPEC 改了,但 ${v.detail} 沒重新產生。跑 cto index 再 git add;這次不擋。`,
64
64
  local_flow_dangling_after: (v) => `[cto] ${v.detail}:這個 after: 指到的任務 ID 不存在。改對 ID,或把那個任務加進 TASKS.md;這次不擋。`,
65
65
  local_flow_duplicate_id: (v) => `[cto] ${v.detail}:這個任務 ID 在 TASKS.md 裡出現不只一次,after: 會指錯。改成唯一的 ID;這次不擋。`,
66
+ done_manual: (v) => `[cto] ${v.detail}:這是要使用者驗收的 task(manual),但你的最後訊息沒說使用者已經確認。先請使用者確認,確認後寫「accepted manually」再打勾;還沒確認就取消打勾,列給使用者。`,
66
67
  docs_none: () => 'docs/cto_jev/ 以外沒有過期的規劃文件。',
67
68
  docs_group_delete: () => '刪除',
68
69
  docs_group_merge: () => '併入某個 feature',
@@ -251,6 +252,7 @@ const messages = {
251
252
  local_flow_index_stale: (v) => `[cto] TASKS/CONCEPT/SPEC changed but ${v.detail} was not regenerated. Run cto index and git add it; not blocking.`,
252
253
  local_flow_dangling_after: (v) => `[cto] ${v.detail}: that after: id does not exist. Fix the id or add the task to TASKS.md; not blocking.`,
253
254
  local_flow_duplicate_id: (v) => `[cto] ${v.detail}: this task id appears more than once in TASKS.md, so after: may point at the wrong one. Make it unique; not blocking.`,
255
+ done_manual: (v) => `[cto] ${v.detail}: this task is accepted by the user (manual), but your final message does not say the user confirmed it. Ask the user; once they confirm, say "accepted manually" and tick it. Until then untick it and list it for them.`,
254
256
  docs_none: () => 'No stale planning documents outside docs/cto_jev/.',
255
257
  docs_group_delete: () => 'Delete',
256
258
  docs_group_merge: () => 'Merge into a feature',
package/dist/turn.js CHANGED
@@ -84,6 +84,8 @@ export function turnActions(transcriptPath, cwd) {
84
84
  return actions;
85
85
  }
86
86
  export const BOX = /^(\s*)[-*+] \[([ xX])\]\s+(.*)$/;
87
+ /** A task's acceptance line (cto-flow TASKS.md): `驗收: <command>` or `accept: <command>`, or `manual`. */
88
+ export const ACCEPT = /^\s*(?:驗收|accept)[::]\s*(.+?)\s*$/i;
87
89
  const itemKey = (file, text) => `${file}:${text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 60)}`;
88
90
  /**
89
91
  * Checklist items a unified diff of markdown files marks done: every added "[x]" line, except ones that were already
@@ -111,7 +113,69 @@ export function tickedItems(diff, read) {
111
113
  }
112
114
  // Already done before when one wording extends the other ("Fix X" -> "Fix X (see #12)").
113
115
  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) }));
116
+ return added.filter((a) => !wasDone(itemKey(a.file, a.text))).map(({ line, ...a }) => {
117
+ const text = read(a.file);
118
+ // Only cto-flow TASKS.md carry acceptance lines; elsewhere "驗收:" is usually prose, not a command.
119
+ const accept = a.file.startsWith('docs/cto_jev/') ? acceptOf(text, line) : undefined;
120
+ return { ...a, children: nested(text, line), ...(accept && { accept }) };
121
+ });
122
+ }
123
+ /** The acceptance line indented under `item`, before any nested item or anything at the item's depth or lower. */
124
+ function acceptOf(text, item) {
125
+ const lines = text?.split(/\r?\n/) ?? [];
126
+ const at = lines.indexOf(item);
127
+ if (at < 0)
128
+ return undefined;
129
+ const indent = BOX.exec(item)[1].length;
130
+ for (const l of lines.slice(at + 1)) {
131
+ if (!l.trim())
132
+ continue;
133
+ if (l.length - l.trimStart().length <= indent || BOX.test(l))
134
+ return undefined; // next item, or a child's own line
135
+ const m = ACCEPT.exec(l);
136
+ if (m)
137
+ return m[1].replace(/^`+|`+$/g, '').trim() || undefined;
138
+ }
139
+ return undefined;
140
+ }
141
+ const squash = (s) => s.replace(/\s+/g, ' ').trim();
142
+ const MANUAL = /^manual\b/i;
143
+ const TASK_ID = /^[A-Z][A-Z0-9]*-\d+(?:\.\d+)*\b/;
144
+ /** The final message says this task was accepted manually: the phrase, not negated, in a line naming the task's id. */
145
+ function acceptedManually(t, lastMessage) {
146
+ const id = TASK_ID.exec(t.text)?.[0];
147
+ return lastMessage.split(/\r?\n|(?<=[.。;;])\s*/).some((s) => /accepted manually/i.test(s) && !/\bnot\s+(?:yet\s+)?accepted manually/i.test(s) && (!id || s.includes(id)));
148
+ }
149
+ /** Ticked `manual` tasks the final message does not report as accepted by the user: a text check, so no model judges it. */
150
+ export const manualUnconfirmed = (ticked, lastMessage) => ticked.filter((t) => MANUAL.test(squash(t.accept ?? '')) && !acceptedManually(t, lastMessage));
151
+ /** `cmd` run as a command of its own: at a command boundary, and not with its failure swallowed (`|| true`). */
152
+ const runsCommand = (command, cmd) => {
153
+ const esc = cmd.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
154
+ return new RegExp(`(?:^|[;&|(]\\s*)${esc}\\s*(?:$|&&|;|\\)|\\|(?!\\|))`).test(command);
155
+ };
156
+ /**
157
+ * Computed, not judged: for each ticked task with an acceptance line, whether that exact command ran and passed after
158
+ * the last code edit, or for `manual`, whether the final message says the user accepted it.
159
+ */
160
+ function acceptFacts(ticked, actions, lastEdit, lastMessage) {
161
+ const lines = ticked.filter((t) => t.accept).slice(0, 20).map((t) => {
162
+ const name = oneLine(t.text, 60);
163
+ const cmd = squash(t.accept);
164
+ if (MANUAL.test(cmd)) {
165
+ return acceptedManually(t, lastMessage)
166
+ ? `"${name}" is accepted by the user (manual), and the final message says it was accepted manually.`
167
+ : `"${name}" is accepted by the user (manual), but the final message does not say the user accepted it.`;
168
+ }
169
+ const runs = actions.flatMap((a, i) => (a.kind === 'run' && runsCommand(squash(a.command), cmd) ? [{ i, ok: a.ok }] : []));
170
+ if (runs.some((r) => r.i > lastEdit && r.ok))
171
+ return `"${name}": its acceptance command \`${cmd}\` ran after the last code edit and passed.`;
172
+ if (runs.some((r) => r.ok))
173
+ return `"${name}": its acceptance command \`${cmd}\` passed, but only before the last code edit.`;
174
+ if (runs.length)
175
+ return `"${name}": its acceptance command \`${cmd}\` ran this turn and failed.`;
176
+ return `"${name}": its acceptance command \`${cmd}\` did not run this turn.`;
177
+ });
178
+ return lines.length ? `\nFact: ${lines.join('\nFact: ')}` : '';
115
179
  }
116
180
  /** Checklist lines indented under `item` in `text` (at most 15). */
117
181
  function nested(text, item) {
@@ -158,7 +222,7 @@ export function turnState(lastMessage, actions, ticked = []) {
158
222
  : `${i + 1}. ran: ${oneLine(a.command, 200)} -> ${a.ok ? 'succeeded' : 'FAILED'}${a.tail ? `\n output tail: ${tailOf(a.tail, 200)}` : ''}`).join('\n')
159
223
  : '(none)';
160
224
  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)
225
+ ? `\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) + acceptFacts(ticked, actions, lastEdit, lastMessage)
162
226
  : '';
163
227
  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}`);
164
228
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "your-cto-jev",
3
- "version": "0.9.5",
3
+ "version": "0.9.6",
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",