your-cto-jev 0.12.0 → 0.13.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 CHANGED
@@ -142,7 +142,7 @@ cto index # regenerate docs/cto_jev/INDEX.md (bri
142
142
  cto docs # suggest what to do with old planning markdown; changes nothing
143
143
  ```
144
144
 
145
- `setup` appends marked blocks and merges JSON. It never overwrites your existing hooks or settings, and `--uninstall` puts them back exactly as they were. It never touches your shell rc files.
145
+ `setup` appends marked blocks and merges JSON. It never overwrites your existing hooks or settings, and `--uninstall` puts them back exactly as they were. The one exception is the model split in global scope (the default): it is shared by every project, so uninstalling one project keeps the user-level split, the `cto-reviewer` agent and the SessionStart hook. Before removing cto, run `cto models scope local`, which clears them. It never touches your shell rc files.
146
146
 
147
147
  ## The rules, written down for the agent
148
148
 
@@ -218,7 +218,7 @@ docs/cto_jev/
218
218
  INDEX.md generated by cto: features, status, code paths, dependencies, sign-off
219
219
  PRODUCT.md who it is for, how it earns, what it will not do
220
220
  ARCHITECTURE.md stack, directory map, external services, the principles that do not change
221
- decisions/NNNN-<slug>.md decision records, append-only
221
+ decisions/NNNN-<slug>.md decision records, append-only; the agent writes one on its own when the architecture changes
222
222
  features/<slug>/
223
223
  CONCEPT.md why: purpose, business rules, non-goals
224
224
  SPEC.md how: ## Interface (what other features may use), ## Constraints, ## Acceptance, ## Internals
@@ -263,11 +263,10 @@ The skill gives the agent seven named jobs, so they cannot be confused with anot
263
263
  | `cto-jev init` | scans the repo, fills PRODUCT.md and ARCHITECTURE.md, asks you the rest a few questions at a time, walks you through the result until you say it is complete |
264
264
  | `cto-jev feature` | talks the CONCEPT through first (who it is for, business rules, what the user sees when it works, what is out of scope, the simpler option it rejected), writes CONCEPT, then writes the SPEC itself (data migration and rollback, what other features may call, how a production failure gets noticed, the acceptance scenarios), has a zero-context reviewer check that a newcomer could build from them without making design decisions, that nothing unneeded or already in the code gets built and that every acceptance scenario has a result a script can check and a CONCEPT rule behind it, walks you through the CONCEPT, hands it over with a [Review handoff](#sign-off) and stops for your sign-off |
265
265
  | `cto-jev tasks` | breaks a feature with a signed-off CONCEPT into parent/child tasks with files, dependencies and an acceptance command each |
266
- | `cto-jev work` | dispatches Ready tasks to sub-agents with the narrowest brief, runs each acceptance command itself before ticking, has a zero-context reviewer read the diff **before every commit**: P1 findings are fixed first (and only the fixes reviewed again, at most three rounds in all; P1s left after that go to you), P2 findings become tasks, a finding is contested only with evidence the reviewer could read, then it commits the wave to the review branch and starts the next one, without asking, until nothing is Ready; tasks that need you (credentials, money, anything irreversible, a drop) are parked, not waited on; ends with one report of what is done and everything for you to look at. Never releases |
267
- | `cto-jev work all` | for a new project or a big batch: the same run on a `work-all` branch with one zero-context review of everything at the end instead of one per wave. Never releases |
266
+ | `cto-jev work` | dispatches Ready tasks to sub-agents with the narrowest brief, runs each acceptance command itself before ticking, has a zero-context reviewer read the diff **before every commit**: P1 findings are fixed first, then the whole change reviewed again by `cto-reviewer` (at most three rounds in all; P1s left after that go to you), P2 findings become tasks, a finding is contested only with evidence the reviewer could read, then it commits the wave to the review branch and starts the next one, without asking, until nothing is Ready; tasks that need you (credentials, money, anything irreversible, a drop) are parked, not waited on; ends with one report of what is done and everything for you to look at. Never releases |
267
+ | `cto-jev work all` | for a new project or a big batch: the same run on a `work-all` branch, every wave reviewed by a zero-context `cto-reviewer` before its commit, then hands over to `cto-jev release`, never merges. Never releases |
268
268
  | `cto-jev release` | reviews the whole unreleased diff against the SPECs (looking hardest at waves marked `self-review`), files P1/P2/P3 tasks under the same findings rules, requires every P1 ticked and `cto check --base <release branch>` green, then prepares the merge, PR or tag for you to perform |
269
269
  | `cto-jev docs` | runs `cto docs` and brings you the list; acts only on what you decide |
270
- | `cto-jev decision` | writes an append-only decision record under `decisions/` |
271
270
 
272
271
  "Release" adapts to the branches you have. A solo repo with only `main`: the wave review before each commit is the gate, and a release is a tag. `main` plus feature branches: the PR is the release. `main` plus `review`/`develop`/`staging`: merging the integration branch into `main`. `staging` and `live`: promoting one to the other. In every case the branch that reaches users takes nothing without a release review, and that is the branch to put in `protected_branches`. Changes inside an existing feature only add tasks; only a new module gets a new folder. The first time it runs it scans the repo, fills PRODUCT.md and ARCHITECTURE.md with what it can prove, asks you the rest a few questions at a time, and walks you through the result until you say it is complete. `unknown` is an allowed answer.
273
272
 
@@ -298,9 +297,11 @@ Data: which tables or stores change, whether old data migrates; "none" if nothin
298
297
  ```
299
298
 
300
299
  - **Claude Code:** just agree in the chat. cto's `UserPromptSubmit` hook asks Jev whether your reply agrees to every listed file and, if so, sets the listed drafts to `Status: approved` and tells you which files it signed. "OK, but change X", a question or agreeing to only some files signs nothing. When Jev cannot sign, it signs nothing and says why: no API key yet (run `cto setup`), the service failed a moment ago and is paused (reply again later), or it is unreachable. In each case you can also edit the line yourself.
300
+ - **Claude Code, by name:** a reply that is only names from the `Review:` line plus a yes signs just those, without asking Jev: "imports ok", "imports、catalog 好". A feature is named by its slug, PRODUCT and ARCHITECTURE by their own names. "ok all" or "全部 ok" signs every listed draft; a bare "都可以" goes to Jev, since it may answer another question. The rest stay on the `Review:` line for later.
301
+ - **Claude Code, from a menu:** whenever the agent stops for you, the skill has it put everything waiting on you in one menu (`/cto-jev decide` lists it all at once): docs to sign, decisions, parked tasks, `manual` checks. Each item has a short summary and 2–3 options with pros and cons, the recommended one first, plus "之後再選" (later). A sign-off question covers one doc and its summary lists every `Assumed:` line and data change; picking `Approve` signs that doc at once (a `PostToolUse` hook on `AskUserQuestion`, no Jev call). Anything typed under "Other" is a follow-up question and signs nothing. cto blocks a sign-off menu the agent prefilled with answers, and ignores menus from sub-agents.
301
302
  - **Codex, Cursor, Gemini CLI:** edit the `Status:` line yourself.
302
303
 
303
- Agreeing covers what is written, `Assumed:` lines included. A signed-off CONCEPT, PRODUCT or ARCHITECTURE can only change after going back to `Status: draft` and a new Review. In Claude Code cto blocks the agent from setting `approved` itself or skipping that step (Edit, Write, MultiEdit; PowerShell may not touch those files at all). For every agent, shell commands may not write them. As a backstop in Claude Code, when a turn ends cto puts any sign-off doc that became `approved` during the turn without your reply back to `draft` and tells the agent, however it was written (a glob, a variable, a script). Codex, Cursor and Gemini edit tools are not guarded yet; there only the skill's rules hold.
304
+ Agreeing covers what is written, `Assumed:` lines included. A signed-off CONCEPT, PRODUCT or ARCHITECTURE can only change after going back to `Status: draft` and a new Review. In Claude Code cto blocks the agent from setting `approved` itself or skipping that step (Edit, Write, MultiEdit; PowerShell may not touch those files at all). For every agent, shell commands may not write them. As a backstop in Claude Code, when a turn ends cto puts any sign-off doc that became `approved` during the turn without your reply or menu choice back to `draft` and tells the agent, however it was written (a glob, a variable, a script). Codex, Cursor and Gemini edit tools are not guarded yet; there only the skill's rules hold.
304
305
 
305
306
  **Upgrading.** `cto update` refreshes the repo you run it from and adds the new Claude Code sign-off hooks; elsewhere run `cto setup --refresh` (`cto doctor` reports missing hooks). From 0.12 only the CONCEPT is signed: a `Status:` line left in an old SPEC is ignored, the commit check reads CONCEPT alone, and INDEX.md's sign-off column holds one value (the first commit after upgrading asks for `cto index`). `manual` tasks no longer need "accepted manually" in the agent's message.
306
307
 
@@ -411,6 +412,29 @@ Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6,
411
412
  | `CTO_DEBUG=1` | Write masked hook input to `debug_stdin.json` |
412
413
  | `CTO_NO_UPDATE_CHECK=1` | Never check npm for a new version |
413
414
 
415
+ ## Models and the review gate
416
+
417
+ On Claude Code, `cto setup` writes a model split:
418
+
419
+ - **Fable** advises the main agent.
420
+ - **Sonnet** is the main model.
421
+ - **Haiku** runs the sub-agents.
422
+ - **Opus** runs `cto-reviewer`, which reviews code with none of the main agent's context.
423
+
424
+ The split is written to your user settings (`global`, the default, every project) or to this project only (`local`). Fable advises only after you agree to it in Claude Code with `/model fable`; to use Opus as the advisor instead, run `cto models advisor opus`.
425
+
426
+ ```sh
427
+ cto models # status: the split, its scope, and what would change
428
+ cto models advisor fable|opus # the advisor model
429
+ cto models autofix on|off # let cto write the split (session start, setup, refresh, update)
430
+ cto models scope global|local # where the split is written, for every project (local in a folder without cto only clears the user level)
431
+ cto models review on|off # the review gate; for you only, agents cannot change it
432
+ ```
433
+
434
+ **The review gate.** With Claude Code wired, the gate on (`review_gate` in `.cto.json`) and a `docs/cto_jev/` folder in the repo, a code commit needs a `cto-reviewer` review of the current working tree and no unresolved P1. Code means the files under `src/` when HEAD tracks a `src/` folder, otherwise source files anywhere; other changes need no review. A dispatch prompt that leaves changed paths out or sets the verdict also blocks: dispatch again with a prompt that covers the whole change. The staged code must match the files on disk: a file changed after `git add` is not the reviewed code. A P1 counts as resolved when REVIEW.md contests it with evidence or marks it escalated to the user. Run the project's formatter before dispatching the reviewer: a formatter that changes files after the review needs another review. Only a Claude Code session can satisfy the gate; other agents stop with the wave uncommitted.
435
+
436
+ Accepted limits: the guards are text heuristics against honest mistakes. They do not stop an agent that deliberately uses nested shells, heredoc or quoting edge cases, aliases, plumbing commands or wrapper forms. When HEAD first tracks a file under `src/`, only `src/` counts as code from then on, so the next commit after that first split needs a fresh review. Jev sees the REVIEW.md of the four most recently changed features only: a P1 contested in an older feature's REVIEW.md is not seen. There is no review check on push, so code that reaches HEAD without pre-commit (rebase, cherry-pick, plumbing) is not reviewed.
437
+
414
438
  ## Known limitations
415
439
 
416
440
  - **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.
package/dist/agents.js CHANGED
@@ -1,6 +1,6 @@
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', 'start', 'prompt', 'guard'];
3
+ export const PHASES = ['pre', 'post', 'stop', 'edit', 'reply', 'start', 'prompt', 'guard', 'menu', 'agent', 'models'];
4
4
  const str = (v) => (typeof v === 'string' && v.trim() ? v : undefined);
5
5
  const cmdOf = (i) => String(i?.tool_input?.command ?? i?.command ?? '');
6
6
  // Claude, Codex and Gemini share this convention: exit 2 + stderr blocks, exit 0 hides stderr so notices go out as systemMessage.
@@ -9,11 +9,11 @@ const exit2Block = (lines) => ({ code: 2, stderr: lines });
9
9
  const systemMessage = (msgs) => ({ code: 0, stdout: JSON.stringify({ systemMessage: msgs.join('\n') }), stderr: [] });
10
10
  const nestedPre = (i) => ({ command: str(i?.tool_input?.command), sessionId: str(i?.session_id), cwd: str(i?.cwd), transcriptPath: str(i?.transcript_path), subagent: !!str(i?.agent_id) });
11
11
  const sessionId = (i) => str(i?.session_id);
12
- /** UserPromptSubmit reply: context reaches Claude, user reaches the user; nothing at all when both are absent. */
13
- export function promptOutput(context, user) {
12
+ /** UserPromptSubmit (or another event's) reply: context reaches Claude, user reaches the user; nothing at all when both are absent. */
13
+ export function promptOutput(context, user, hookEventName = 'UserPromptSubmit') {
14
14
  if (!context && !user)
15
15
  return { code: 0, stderr: [] };
16
- const out = { ...(context && { hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: context } }), ...(user && { systemMessage: user }) };
16
+ const out = { ...(context && { hookSpecificOutput: { hookEventName, additionalContext: context } }), ...(user && { systemMessage: user }) };
17
17
  return { code: 0, stdout: JSON.stringify(out), stderr: [] };
18
18
  }
19
19
  const cursorCwd = (i) => str(i?.cwd) ?? str(i?.workspace_roots?.[0]);
@@ -42,9 +42,20 @@ export const agents = {
42
42
  edit: { event: 'PostToolUse', matcher: 'Edit|Write|MultiEdit|NotebookEdit' },
43
43
  start: { event: 'SessionStart' }, // stdout of a SessionStart hook is added to Claude's context
44
44
  prompt: { event: 'UserPromptSubmit' },
45
- guard: { event: 'PreToolUse', matcher: 'Edit|Write|MultiEdit|PowerShell' },
45
+ guard: { event: 'PreToolUse', matcher: 'Edit|Write|MultiEdit|PowerShell|AskUserQuestion|Agent|Task' }, // Agent (Task on older Claude Code): notes the code and prompt a cto-reviewer starts with
46
+ menu: { event: 'PostToolUse', matcher: 'AskUserQuestion' },
47
+ agent: { event: 'SubagentStop' },
48
+ models: { event: 'SessionStart', user: true },
49
+ parseMenu: (i) => ({
50
+ sessionId: sessionId(i),
51
+ cwd: str(i?.cwd),
52
+ subagent: !!str(i?.agent_id),
53
+ questions: Array.isArray(i?.tool_input?.questions) ? i.tool_input.questions : [],
54
+ // Only what the user chose; tool_input.answers may have been written by the CTO.
55
+ answers: i?.tool_response?.answers && typeof i.tool_response.answers === 'object' ? i.tool_response.answers : {},
56
+ }),
46
57
  parsePrompt: (i) => ({ sessionId: sessionId(i), cwd: str(i?.cwd), transcriptPath: str(i?.transcript_path), prompt: String(i?.prompt ?? '') }),
47
- parseGuard: (i) => ({ cwd: str(i?.cwd), toolName: String(i?.tool_name ?? ''), toolInput: i?.tool_input ?? {} }),
58
+ parseGuard: (i) => ({ cwd: str(i?.cwd), sessionId: sessionId(i), toolName: String(i?.tool_name ?? ''), toolInput: i?.tool_input ?? {} }),
48
59
  parseEdit: (i) => { const p = str(i?.tool_input?.file_path) ?? str(i?.tool_input?.notebook_path); return p ? [p] : undefined; },
49
60
  parseStop: (i) => ({
50
61
  sessionId: str(i?.session_id),
package/dist/brain.js CHANGED
@@ -1,6 +1,6 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
1
+ import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
- import { dirname, join } from 'node:path';
3
+ import { basename, dirname, join } from 'node:path';
4
4
  const turnLimits = (raw) => {
5
5
  const n = (k) => (typeof raw?.[k] === 'number' && raw[k] >= 0 ? raw[k] : DEFAULT_CONFIG.turn_limits[k]);
6
6
  return { minutes: n('minutes'), tool_calls: n('tool_calls'), agents: n('agents') };
@@ -9,6 +9,8 @@ export const DECISIONS_KEPT = 30;
9
9
  export const DECISION_STATE_CHARS = 12_000;
10
10
  /** Sign-off writes approved for the user, so an agent editing .cto.json may raise this bar but never lower it. */
11
11
  export const SIGNOFF_FLOOR = 0.8;
12
+ /** review_unresolved and review_prompt default and ceiling: .cto.json can only lower them. */
13
+ export const REVIEW_CEIL = 0.7;
12
14
  export const signoffThreshold = (override) => Math.max(typeof override === 'number' && Number.isFinite(override) ? override : 0, SIGNOFF_FLOOR);
13
15
  export const DEFAULT_CONFIG = {
14
16
  sprint_goal: '',
@@ -25,8 +27,11 @@ export const DEFAULT_CONFIG = {
25
27
  test_tampering: 0.8,
26
28
  done_unverified: 0.6,
27
29
  signoff_approved: SIGNOFF_FLOOR,
30
+ review_unresolved: REVIEW_CEIL, // not calibrated yet; blocks the commit
31
+ review_prompt: REVIEW_CEIL, // not calibrated yet; blocks the commit
28
32
  code_complexity: 2,
29
33
  },
34
+ review_gate: true,
30
35
  turn_limits: { minutes: 20, tool_calls: 150, agents: 4 },
31
36
  };
32
37
  const emptyBrain = () => ({
@@ -61,12 +66,18 @@ export function loadConfig(root) {
61
66
  const raw = readJson(join(root, '.cto.json')) ?? {};
62
67
  const thresholds = { ...DEFAULT_CONFIG.thresholds, ...(raw.thresholds ?? {}) };
63
68
  thresholds.signoff_approved = signoffThreshold(thresholds.signoff_approved);
69
+ // An agent editing .cto.json may make the review gate stricter, never looser.
70
+ for (const k of ['review_unresolved', 'review_prompt']) {
71
+ const v = thresholds[k];
72
+ thresholds[k] = Math.min(typeof v === 'number' && Number.isFinite(v) ? v : REVIEW_CEIL, REVIEW_CEIL);
73
+ }
64
74
  return {
65
75
  sprint_goal: typeof raw.sprint_goal === 'string' ? raw.sprint_goal : '',
66
76
  test_command: typeof raw.test_command === 'string' ? raw.test_command : '',
67
77
  protected_branches: Array.isArray(raw.protected_branches) ? raw.protected_branches.filter((b) => typeof b === 'string') : [],
68
78
  flow: raw.flow === true,
69
79
  thresholds,
80
+ review_gate: raw.review_gate !== false,
70
81
  turn_limits: turnLimits(raw.turn_limits),
71
82
  };
72
83
  }
@@ -95,47 +106,212 @@ export function applyCredentials(env = process.env) {
95
106
  }
96
107
  /** Replace the stored keys with exactly `c`; personal prefs in the same file are kept. */
97
108
  export function saveCredentials(c) {
98
- const raw = readJson(credentialsPath()) ?? {};
109
+ const raw = readUserFile();
99
110
  for (const k of CREDENTIAL_KEYS)
100
111
  delete raw[k];
101
112
  return writeUserFile({ ...raw, ...c });
102
113
  }
114
+ export const DEFAULT_MODELS = { scope: 'global', advisor: 'fable', autoFix: true };
115
+ export const modelsPrefs = (p = loadPrefs()) => ({ ...DEFAULT_MODELS, ...p.models });
103
116
  export function loadPrefs() {
104
117
  const raw = readJson(credentialsPath()) ?? {};
118
+ const m = raw.models;
119
+ const models = m && typeof m === 'object' && !Array.isArray(m) && {
120
+ ...((m.scope === 'global' || m.scope === 'local') && { scope: m.scope }),
121
+ ...((m.advisor === 'fable' || m.advisor === 'opus') && { advisor: m.advisor }),
122
+ ...(typeof m.autoFix === 'boolean' && { autoFix: m.autoFix }),
123
+ ...((m.seenUserAdvisor === 'fable' || m.seenUserAdvisor === 'opus') && { seenUserAdvisor: m.seenUserAdvisor }),
124
+ };
105
125
  return {
106
126
  ...(Array.isArray(raw.provider_order) && { provider_order: raw.provider_order.filter((p) => typeof p === 'string') }),
107
127
  ...((raw.lang === 'zh-TW' || raw.lang === 'en') && { lang: raw.lang }),
128
+ ...(models && { models: { ...DEFAULT_MODELS, ...models } }),
108
129
  };
109
130
  }
131
+ /** provider_order and lang are replaced by `p` (absent = cleared); models is kept unless `p` sets it. */
110
132
  export function savePrefs(p) {
111
- const raw = readJson(credentialsPath()) ?? {};
133
+ const raw = readUserFile();
112
134
  delete raw.provider_order;
113
135
  delete raw.lang;
114
136
  return writeUserFile({ ...raw, ...p });
115
137
  }
138
+ /**
139
+ * The file holds API keys: a file that exists but does not parse is never overwritten (its keys would be lost).
140
+ * Throws then; callers that run unattended (SessionStart) catch it and report.
141
+ */
142
+ function readUserFile() {
143
+ const path = credentialsPath();
144
+ if (!existsSync(path))
145
+ return {};
146
+ const raw = readJson(path);
147
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
148
+ throw new Error(`${path} is not valid JSON; fix or delete it, cto will not overwrite it`);
149
+ return raw;
150
+ }
116
151
  function writeUserFile(data) {
117
152
  const path = credentialsPath();
153
+ const tmp = `${path}.${process.pid}.tmp`;
118
154
  mkdirSync(dirname(path), { recursive: true });
119
- writeFileSync(path, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
155
+ try {
156
+ writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
157
+ renameSync(tmp, path); // a crash mid-write never leaves half a key file
158
+ }
159
+ catch (e) {
160
+ try {
161
+ unlinkSync(tmp);
162
+ }
163
+ catch { /* nothing to clean */ }
164
+ throw e;
165
+ }
120
166
  return path;
121
167
  }
122
168
  /**
123
169
  * Atomic write via per-process tmp + rename. No file lock (spec section 7): parallel hooks race, last write wins.
124
170
  * Never throws: losing bookkeeping is fine, but an exception here would turn a block into a fail-open pass.
125
171
  */
172
+ const sleepMs = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
173
+ /** rename, retried for EPERM (Windows: an antivirus or indexer holds the file for a moment); other errors throw at once. */
174
+ export function renameWithRetry(rename, from, to, attempts = 50) {
175
+ for (let i = 1;; i++) {
176
+ try {
177
+ rename(from, to);
178
+ return;
179
+ }
180
+ catch (e) {
181
+ if (e?.code !== 'EPERM' || i >= attempts)
182
+ throw e;
183
+ sleepMs(20);
184
+ }
185
+ }
186
+ }
126
187
  export function saveBrain(root, brain) {
127
188
  const path = join(root, '.cto-brain.json');
128
189
  const tmp = `${path}.${process.pid}.tmp`;
129
190
  try {
130
191
  writeFileSync(tmp, JSON.stringify(brain, null, 2) + '\n');
131
- renameSync(tmp, path);
192
+ renameWithRetry(renameSync, tmp, path);
132
193
  }
133
- catch {
194
+ catch (e) {
134
195
  try {
135
196
  unlinkSync(tmp);
136
197
  }
137
198
  catch { /* nothing to clean */ }
199
+ // Losing bookkeeping does not block a hook, but the loss is said, not dropped silently.
200
+ process.stderr.write(`[cto] could not save ${path}: ${e.message}\n`);
201
+ }
202
+ }
203
+ /**
204
+ * Runs fn holding .cto-brain.json.lock: an O_EXCL create, retried for about 2 s. A lock older than 10 s is a crashed
205
+ * writer's and is taken over. When the lock cannot be had in time, fn runs unlocked and the lock is left alone.
206
+ */
207
+ export function withBrainLock(root, fn, afterRename) {
208
+ const lock = join(root, '.cto-brain.json.lock');
209
+ const token = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`; // the lock is ours only while it holds this
210
+ const until = Date.now() + 2000;
211
+ let held = false;
212
+ for (;;) {
213
+ try {
214
+ writeFileSync(lock, token, { flag: 'wx' });
215
+ held = true;
216
+ break;
217
+ }
218
+ catch (e) {
219
+ if (e?.code !== 'EEXIST')
220
+ break;
221
+ let stale = false;
222
+ try {
223
+ stale = Date.now() - statSync(lock).mtimeMs > STALE_LOCK_MS;
224
+ }
225
+ catch { /* vanished: try again */ }
226
+ if (stale)
227
+ takeOver(lock, afterRename);
228
+ if (Date.now() > until)
229
+ break;
230
+ sleepMs(20);
231
+ }
138
232
  }
233
+ try {
234
+ return fn();
235
+ }
236
+ finally {
237
+ if (held)
238
+ try {
239
+ if (readFileSync(lock, 'utf8') === token)
240
+ unlinkSync(lock);
241
+ }
242
+ catch { /* already gone */ }
243
+ }
244
+ }
245
+ const STALE_LOCK_MS = 10_000;
246
+ /** Moved-aside stale locks left behind by a takeover that did not put the file back: removed once they are stale too. */
247
+ function sweepAsides(lock) {
248
+ const dir = dirname(lock);
249
+ const prefix = `${basename(lock)}.stale-`;
250
+ try {
251
+ for (const name of readdirSync(dir)) {
252
+ if (!name.startsWith(prefix))
253
+ continue;
254
+ const p = join(dir, name);
255
+ try {
256
+ if (Date.now() - statSync(p).mtimeMs > STALE_LOCK_MS)
257
+ unlinkSync(p);
258
+ }
259
+ catch { /* gone, or held by another hook */ }
260
+ }
261
+ }
262
+ catch { /* brain dir unreadable: the takeover itself reports nothing */ }
263
+ }
264
+ /**
265
+ * Takes over a lock that looked stale: it is renamed to a unique name first, so of the hooks racing for it only one rename
266
+ * succeeds. The moved file is checked again: a holder that refreshed it meanwhile gets its lock back and nothing is removed.
267
+ */
268
+ function takeOver(lock, afterRename) {
269
+ sweepAsides(lock);
270
+ const aside = `${lock}.stale-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
271
+ try {
272
+ renameSync(lock, aside);
273
+ }
274
+ catch {
275
+ return;
276
+ } // another hook renamed it first
277
+ afterRename?.(aside);
278
+ let still = false;
279
+ try {
280
+ still = Date.now() - statSync(aside).mtimeMs > STALE_LOCK_MS;
281
+ }
282
+ catch {
283
+ return;
284
+ }
285
+ if (still) {
286
+ try {
287
+ unlinkSync(aside);
288
+ }
289
+ catch { /* gone */ }
290
+ return;
291
+ }
292
+ // Put back with a link, which fails when the lock path was taken meanwhile: then the moved file stays where it is and the
293
+ // holder's new lock is left alone.
294
+ try {
295
+ linkSync(aside, lock);
296
+ }
297
+ catch {
298
+ return;
299
+ }
300
+ try {
301
+ unlinkSync(aside);
302
+ }
303
+ catch { /* gone */ }
304
+ }
305
+ /**
306
+ * Saves a brain read before a long wait (a Jev call): the fields other hooks write while it waits (reviews, review_start)
307
+ * come from a fresh read, under the brain lock, so a record another hook wrote in the meantime is kept.
308
+ * shortcut: the other fields are still this hook's snapshot; a counter another hook bumps in the same window is lost.
309
+ */
310
+ export function saveKeeping(root, brain) {
311
+ withBrainLock(root, () => {
312
+ const fresh = loadBrain(root);
313
+ saveBrain(root, { ...brain, reviews: fresh.reviews, review_start: fresh.review_start });
314
+ });
139
315
  }
140
316
  /** Failures older than this are history, not a loop. */
141
317
  export const RECENT_ERROR_WINDOW_MS = 15 * 60_000;
package/dist/check.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { loadBrain, loadConfig, saveBrain } from './brain.js';
3
- import { BLOCKING_COMMIT, DIFF_ARGS, WARNING_COMMIT, localLines, reviewDiff } from './hooks.js';
2
+ import { loadBrain, loadConfig, saveKeeping } from './brain.js';
3
+ import { BLOCKING_COMMIT, DIFF_ARGS, WARNING_COMMIT, countCheck, localLines, reviewDiff, reviewGate } from './hooks.js';
4
4
  import { personaDict, t } from './i18n.js';
5
5
  import { localCommitChecks } from './local.js';
6
6
  const PINNED = DIFF_ARGS.filter((a) => a !== 'diff' && a !== '--cached');
@@ -34,14 +34,21 @@ export async function runCheck(root, lang, base) {
34
34
  const brain = loadBrain(root);
35
35
  const { diff, source } = pendingDiff(root, base);
36
36
  const local = localCommitChecks(diff, cfg, root);
37
- const review = await reviewDiff(diff, cfg, brain, lang, undefined, 'check', root, !!base);
38
- saveBrain(root, brain); // provider cooldowns and the decision log; check runs are not counted as blocks
37
+ // The review records are local to this machine, so a branch diff for CI (--base) has none to match.
38
+ const [gate, review] = await Promise.all([
39
+ base ? { block: false, lines: [], answered: false } : reviewGate(diff, cfg, brain, root, lang, undefined, 'check', source === 'staged'),
40
+ reviewDiff(diff, cfg, brain, lang, undefined, 'check', root, !!base),
41
+ ]);
42
+ if (gate.answered)
43
+ countCheck(brain); // the gate's Jev calls count as one check, like a commit's
44
+ saveKeeping(root, brain); // provider cooldowns and the decision log; check runs are not counted as blocks
45
+ // The gate decides even when no commit check has anything to judge (every section filtered out): its block stands.
39
46
  if (!review)
40
- return { code: 0, lines: [t(lang, 'check_nothing')] };
47
+ return gate.block ? { code: 1, lines: gate.lines } : { code: 0, lines: [t(lang, 'check_nothing'), ...gate.lines] };
41
48
  const head = source === 'staged' ? 'check_head_staged' : source === 'working' ? 'check_head_working' : 'check_head_base';
42
49
  const lines = [t(lang, head, { files: review.files, base: base ?? '' }), ...review.notices];
43
- let code = local.some((f) => f.block) ? 1 : 0;
44
- const verdicts = localLines(lang, local);
50
+ let code = local.some((f) => f.block) || gate.block ? 1 : 0;
51
+ const verdicts = [...localLines(lang, local), ...gate.lines];
45
52
  if (!Object.keys(review.scores).length) {
46
53
  lines.push(t(lang, 'check_unchecked'), ...verdicts);
47
54
  return { code, lines };
package/dist/docs.js CHANGED
@@ -2,6 +2,7 @@ import { execFileSync } from 'node:child_process';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { evaluate } from './api.js';
5
+ import { loadBrain, saveKeeping } from './brain.js';
5
6
  import { estimateTokens } from './diff.js';
6
7
  import { featureIndex, renderIndex } from './flow.js';
7
8
  import { t } from './i18n.js';
@@ -121,6 +122,13 @@ export async function judgeDocs(root, candidates, ctx) {
121
122
  export async function docsReport(root, ctx) {
122
123
  return renderDocs(await judgeDocs(root, docCandidates(root), ctx), ctx.lang);
123
124
  }
125
+ /** `cto docs`: the report, then the brain saved with what other hooks wrote during the Jev calls (saveKeeping). */
126
+ export async function runDocs(root, lang) {
127
+ const brain = loadBrain(root);
128
+ const lines = await docsReport(root, { brain, lang, timeoutMs: 5000, notices: new Set() });
129
+ saveKeeping(root, brain); // provider cooldowns, as the hook paths do
130
+ return lines;
131
+ }
124
132
  const GROUPS = ['delete', 'merge', 'archive', 'ask'];
125
133
  export function renderDocs(c, lang = 'en') {
126
134
  if (!c.length)