your-cto-jev 0.11.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
@@ -42,7 +42,7 @@ Jev judges meaning and answers with probabilities, not prose. It costs about $0.
42
42
 
43
43
  `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.
44
44
 
45
- `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 (or a `(dropped: ...)` task the final message does not report as dropped) is sent back without asking Jev at all. It blocks at most once per stop, so it cannot loop.
45
+ `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 `(dropped: ...)` task the final message does not report as dropped is sent back without asking Jev at all. A ticked `manual` task never blocks: cto shows you what to look at. A task whose acceptance was a command and is switched to `manual` in the turn it is ticked is judged against that old command (when cto recorded where the turn started; otherwise against the last commit). It blocks at most once per stop, so it cannot loop.
46
46
 
47
47
  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.
48
48
 
@@ -56,13 +56,15 @@ Some checks need no model at all. They run first, before anything is sent anywhe
56
56
  | A `.env` file with values (not `.env.example`) | `git commit` | **Blocks** |
57
57
  | A file over 5 MB | `git commit` | Warns |
58
58
  | `package.json` dependencies changed, lock file not | `git commit` | Warns |
59
- | Development flow: a feature with tasks whose CONCEPT or SPEC is not `Status: approved` | `git commit` touching that feature | **Blocks**, naming the unsigned files |
59
+ | Development flow: a feature with tasks whose CONCEPT is not `Status: approved` | `git commit` touching that feature | **Blocks** |
60
60
  | Development flow: INDEX.md older than its inputs, an `(after:)` id nobody defines, a SPEC `## Interface` changed | `git commit` | Warns |
61
61
 
62
62
  `protected_branches` is empty by default; set it in `.cto.json` (`["main"]`) and the whole team's agents stop committing to main by accident. A commit a local check blocks never reaches Jev.
63
63
 
64
64
  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.
65
65
 
66
+ A turn that runs long gets one reminder, never a block. When a turn passes 20 minutes, 150 tool calls or 4 sub-agents since your last message, the agent's next shell command carries `[cto] This turn has run 21 min, 160 tool calls, 2 sub-agents. Stop and tell the user where you are, what is stuck, and what you plan next, before going on.`, and you see `[cto] This turn has run 21 min, 160 tool calls, 2 sub-agents; the agent has been asked to stop and report.` A background agent finishing does not start a new turn. Set the limits in `turn_limits` in `.cto.json`.
67
+
66
68
  When nothing crosses a threshold, `cto` prints nothing at all.
67
69
 
68
70
  ## How it works
@@ -140,7 +142,7 @@ cto index # regenerate docs/cto_jev/INDEX.md (bri
140
142
  cto docs # suggest what to do with old planning markdown; changes nothing
141
143
  ```
142
144
 
143
- `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.
144
146
 
145
147
  ## The rules, written down for the agent
146
148
 
@@ -216,7 +218,7 @@ docs/cto_jev/
216
218
  INDEX.md generated by cto: features, status, code paths, dependencies, sign-off
217
219
  PRODUCT.md who it is for, how it earns, what it will not do
218
220
  ARCHITECTURE.md stack, directory map, external services, the principles that do not change
219
- 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
220
222
  features/<slug>/
221
223
  CONCEPT.md why: purpose, business rules, non-goals
222
224
  SPEC.md how: ## Interface (what other features may use), ## Constraints, ## Acceptance, ## Internals
@@ -233,15 +235,17 @@ A task is one checklist line, and everything else is computed from it:
233
235
  - [ ] CUST-1.2 List UI (after: CUST-1.1) (files: src/customers/ui/, e2e/customers.spec.ts)
234
236
  accept: npx playwright test e2e/customers.spec.ts
235
237
  - [ ] CUST-1.3 List matches the brand (look) (after: CUST-1.2) (files: src/customers/ui/)
236
- accept: manual
238
+ accept: manual: list page against the brand sheet, at 375px and 1280px @ http://localhost:3000/customers
237
239
  ```
238
240
 
239
- You confirm what is expected, not what was built. A SPEC's `## Acceptance` lists each scenario as steps and a result a script can compare ("at 375px wide: no horizontal scroll"), and it is signed with the SPEC, so the agent cannot quietly change it. A task you would see is accepted by the end-to-end test written from those lines before the code; if the agent thinks an expectation is wrong, it asks you and changes the SPEC, not the test. `manual` is left for taste (does it look right, does it match the brand), and the agent shows you screenshots at each width before you say yes. A task that will not be done is closed with `(dropped: <reason>)` on its line, and the agent must say "<id> dropped" in its final message.
241
+ You sign one document per feature, the CONCEPT: what it is for, the business rules, what the user sees when it works, what is out of scope. Until you sign it the agent talks with you (the CONCEPT questions); after that it waits for you in one place only: before the merge in `cto-jev release`. The SPEC is the agent's technical document, derived from the CONCEPT; nobody signs it and the agent may change it. Its `## Acceptance` lists each scenario as steps and a result a script can compare ("at 375px wide: no horizontal scroll"), each from a rule in the CONCEPT. A task you would see is accepted by the end-to-end test written from those lines before the code; if the agent thinks an expectation is wrong, the CONCEPT decides, and the Acceptance line changes before the test does. What the CONCEPT leaves open the agent decides and writes down as `Assumed:`; you read those in the release report. `manual` is left for taste (does it look right, does it match the brand) and blocks nothing: its line says what to look at and where (`manual: list page against the brand sheet @ http://localhost:3000/customers`), cto shows you that text when the turn ends, and the release report lists them all. A task that will not be done is closed with `(dropped: <reason>)` on its line, and the agent must say "<id> dropped" in its final message.
242
+
243
+ The trade: fewer stops, later discovery. A SPEC that drifted from what you meant shows up in the release review, not at a mid-way approval, and the agent writes both the code and its tests. The zero-context review before every commit is what stands in for you there: it checks the diff against the CONCEPT and asks of each acceptance test whether it would fail if its scenario broke.
240
244
 
241
245
  `(after:)` says what must be ticked first, across features too; `(files:)` says what the task changes. Two optional tags: `(P1)`/`(P2)`/`(P3)` for priority (P1 first and nothing releases while one is open; no tag means P2; P3 last) and `(seq)` for a task that must run alone (migrations, shared types). From that, `cto brief` lists what is ready in priority order, what can run at the same time (no overlapping files, not `(seq)`), what is blocked and on whom:
242
246
 
243
247
  ```text
244
- Features · 2 · 1 active · 1 planned · sign-off pending: billing (spec draft)
248
+ Features · 2 · 1 active · 1 planned · sign-off pending: billing (concept draft)
245
249
 
246
250
  Ready · 3 (run together: CUST-1.2, PERM-3)
247
251
  CUST-1.2 P1 List UI files src/customers/ui/, e2e/customers.spec.ts accept: npx playwright test e2e/customers.spec.ts
@@ -257,13 +261,12 @@ The skill gives the agent seven named jobs, so they cannot be confused with anot
257
261
  | Say | The agent |
258
262
  |---|---|
259
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 |
260
- | `cto-jev feature` | talks the request through first (who it is for, business rules, what is out of scope, the simpler option it rejected, data migration and rollback, what other features may call, how a production failure gets noticed, the acceptance scenarios you will confirm), writes CONCEPT and SPEC, 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, walks you through them, hands them over with a [Review handoff](#sign-off) and stops for your sign-off |
261
- | `cto-jev tasks` | breaks an approved SPEC into parent/child tasks with files, dependencies and an acceptance command each |
262
- | `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 that one wave to the review branch and stops |
263
- | `cto-jev work all` | for a new project or a big batch: runs every wave in one go, fixes failing acceptance along the way, parks (does not stop for) tasks that need you, then one zero-context review of everything it did with P1s fixed; ends with one report of what is done and every question for you. Never releases |
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
+ | `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, 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 |
264
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 |
265
269
  | `cto-jev docs` | runs `cto docs` and brings you the list; acts only on what you decide |
266
- | `cto-jev decision` | writes an append-only decision record under `decisions/` |
267
270
 
268
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.
269
272
 
@@ -271,9 +274,11 @@ What `cto` adds on top, all without a model call unless noted:
271
274
 
272
275
  | Check | Where | What happens |
273
276
  |---|---|---|
274
- | A feature has tasks but its CONCEPT or SPEC is not approved | `git commit` touching that feature | **Blocks**, naming the unsigned files |
277
+ | A feature has tasks but its CONCEPT is not approved | `git commit` touching that feature | **Blocks** |
275
278
  | The agent sets `Status: approved` itself, or changes signed-off content without going back to draft | Claude Code edit tools and PowerShell | **Blocks** ([sign-off](#sign-off)) |
276
- | A shell command writes CONCEPT, SPEC, PRODUCT or ARCHITECTURE under `docs/cto_jev/` | every agent's shell command | **Blocks** |
279
+ | A shell command writes CONCEPT, PRODUCT or ARCHITECTURE under `docs/cto_jev/` | every agent's shell command | **Blocks** |
280
+ | A `manual` task is ticked | every agent, when the turn ends (Cursor may not display it) | **Tells you** what to look at and where, from the task's acceptance line; never blocks |
281
+ | An open task's acceptance line says only `manual` | `git commit` touching that TASKS.md | Warns: say what to look at |
277
282
  | A sign-off doc became `approved` during the turn without your reply (however it was written) | Claude Code, when the turn ends | **Reverts** it to `draft` and tells the agent |
278
283
  | `architecture_violation` judged against the feature's `## Constraints` and PRODUCT's non-goals instead of a one-line goal | `git commit` (Jev) | Warns |
279
284
  | An architecture change with no new decision record | `git commit` (Jev) | Warns |
@@ -282,21 +287,23 @@ What `cto` adds on top, all without a model call unless noted:
282
287
 
283
288
  ### Sign-off
284
289
 
285
- CONCEPT, SPEC, PRODUCT and ARCHITECTURE are signed off when their `Status:` line says `approved`, and only you decide that. Each time the agent wants you to read them it ends with a Review handoff:
290
+ CONCEPT, PRODUCT and ARCHITECTURE are signed off when their `Status:` line says `approved`, and only you decide that. SPEC is not signed. Each time the agent wants you to read them it ends with a Review handoff:
286
291
 
287
292
  ```text
288
- Review: docs/cto_jev/features/<slug>/CONCEPT.md, docs/cto_jev/features/<slug>/SPEC.md
293
+ Review: docs/cto_jev/features/<slug>/CONCEPT.md
289
294
  Key points: at most three lines
290
295
  Might be missing: what the agent is unsure of, pointing to the `Assumed:` lines in the docs
291
296
  Data: which tables or stores change, whether old data migrates; "none" if nothing
292
297
  ```
293
298
 
294
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.
295
302
  - **Codex, Cursor, Gemini CLI:** edit the `Status:` line yourself.
296
303
 
297
- Agreeing covers what is written, `Assumed:` lines included. A signed-off CONCEPT, PRODUCT or ARCHITECTURE, and a signed-off SPEC's `## Interface` and `## Constraints`, can only change after going back to `Status: draft` and a new Review; a SPEC's `## Internals` stays editable. 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.
298
305
 
299
- **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). The commit check now wants CONCEPT signed off as well as SPEC, so a feature whose SPEC is approved but CONCEPT is still `draft` is blocked at commit until you approve its CONCEPT.
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.
300
307
 
301
308
  `cto docs` deals with the rest of the repo: it finds markdown outside `docs/cto_jev/` that looks like an old plan (tool output under `.planning/`, `specs/`, `.kiro/`, fully ticked `TODO.md`s, checklists untouched for a month), asks Jev about the ambiguous ones, and prints merge / archive / delete suggestions. It changes nothing; the agent acts only after you decide.
302
309
 
@@ -387,6 +394,7 @@ Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6,
387
394
  - **`flow`**: `true` turns on the [development flow](#the-development-flow-optional). `cto setup --flow` / `--no-flow` set it; `cto setup --refresh` follows the saved value. `--no-flow` removes the cto-jev skill, `/cto-jev` and its rule but keeps `docs/cto_jev/`; while `docs/cto_jev/features/` exists, the sign-off, index and drift checks keep running. Delete or archive that folder to stop them.
388
395
  - **`test_command`**: what `cto brief` tells the agent to verify with, for example `"pnpm test"`. Detected from the project when empty.
389
396
  - **`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.
397
+ - **`turn_limits`**: `{ "minutes": 20, "tool_calls": 150, "agents": 4 }` by default; a turn past any one of them gets one reminder to stop and report. `0` turns that limit off; a key you leave out keeps its default.
390
398
  - **Thresholds**: Jev returns a probability from 0 to 1. `code_complexity` is the exception: it is a score from 0 (clean) to 4 (unmaintainable).
391
399
  - **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.
392
400
  - `done_unverified` (0.6) and `infinite_loop` (0.6) were calibrated the same way; the cases are in `calibration/`.
@@ -404,6 +412,29 @@ Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6,
404
412
  | `CTO_DEBUG=1` | Write masked hook input to `debug_stdin.json` |
405
413
  | `CTO_NO_UPDATE_CHECK=1` | Never check npm for a new version |
406
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
+
407
438
  ## Known limitations
408
439
 
409
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.
@@ -411,7 +442,8 @@ Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6,
411
442
  - **A lesson's fix is the edit between a failure and the next pass of a command with the same first two words.** A fix that was verified by a different command (`npm test` fails, `npx vitest run` passes) is not recorded, and a turn that edits files for other reasons in between credits them to the fix as well.
412
443
  - **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.
413
444
  - **The development flow reads exact headings and prefixes.** `## Interface`, `## Constraints`, `Status: approved` and the PRODUCT/ARCHITECTURE field headings must match the skeleton as written; a reworded heading is "missing" in `cto brief` and silently skipped by the checks. A commit maps to a feature by `(files:)` prefix, so a task written as `src/` claims everything and `./src/x/` claims nothing. The two Jev questions look at the first diff chunk only.
414
- - **The sign-off guard has gaps.** Shell writes it cannot resolve (paths in variables, scripts such as `node -e`, `git checkout --`, `git apply`) are not blocked up front; in Claude Code a self-approval made that way is put back to `draft` when the turn ends, but a change to signed-off content is not. Codex, Cursor and Gemini edit tools are not guarded. If you flip a Status to `approved` by hand while the agent is mid-turn, that end-of-turn check reverts it too; flip it again afterwards. The hook signs only the reply right after a Review handoff, and keeps no record: a hook sign-off and a hand edit look the same in git.
445
+ - **The sign-off guard has gaps.** Shell writes it cannot resolve (paths in variables, scripts such as `node -e`, `git checkout --`, `git apply`) are not blocked up front; in Claude Code a self-approval made that way is put back to `draft` when the turn ends, and so is a signed doc whose content changed during the turn (set to draft, edited, approved again). All of this catches an agent that takes a shortcut or makes a mistake. It is not a security boundary against one set on cheating: anything the agent can run can also rewrite the record that check keeps in `.cto-brain.json`, and the commit check reads only the Status line. Codex, Cursor and Gemini edit tools are not guarded. If you flip a Status to `approved` by hand while the agent is mid-turn, that end-of-turn check reverts it too; flip it again afterwards. The hook signs only the reply right after a Review handoff, and keeps no record: a hook sign-off and a hand edit look the same in git.
446
+ - **The long-turn reminder is checked only when the agent runs a shell command.** A turn that only reads and edits files is not reminded until its next command. It works in Claude Code only: the other agents have no hook that marks where a turn starts.
415
447
  - **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.
416
448
 
417
449
  ## Development
package/dist/agents.js CHANGED
@@ -1,19 +1,19 @@
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.
7
7
  // For their stop events exit 2 also means "keep working", with stderr as the reason fed back to the agent.
8
8
  const exit2Block = (lines) => ({ code: 2, stderr: lines });
9
9
  const systemMessage = (msgs) => ({ code: 0, stdout: JSON.stringify({ systemMessage: msgs.join('\n') }), stderr: [] });
10
- const nestedPre = (i) => ({ command: str(i?.tool_input?.command), sessionId: str(i?.session_id), cwd: str(i?.cwd) });
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),
@@ -59,6 +70,8 @@ export const agents = {
59
70
  block: exit2Block,
60
71
  stopBlock: exit2Block,
61
72
  notice: systemMessage,
73
+ // additionalContext reaches Claude next to the tool result; systemMessage reaches the user only.
74
+ preContext: (forAgent, forUser) => ({ code: 0, stdout: JSON.stringify({ systemMessage: forUser.join('\n'), hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: forAgent } }), stderr: [] }),
62
75
  },
63
76
  cursor: {
64
77
  label: 'Cursor',
package/dist/brain.js CHANGED
@@ -1,10 +1,16 @@
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
+ const turnLimits = (raw) => {
5
+ const n = (k) => (typeof raw?.[k] === 'number' && raw[k] >= 0 ? raw[k] : DEFAULT_CONFIG.turn_limits[k]);
6
+ return { minutes: n('minutes'), tool_calls: n('tool_calls'), agents: n('agents') };
7
+ };
4
8
  export const DECISIONS_KEPT = 30;
5
9
  export const DECISION_STATE_CHARS = 12_000;
6
10
  /** Sign-off writes approved for the user, so an agent editing .cto.json may raise this bar but never lower it. */
7
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;
8
14
  export const signoffThreshold = (override) => Math.max(typeof override === 'number' && Number.isFinite(override) ? override : 0, SIGNOFF_FLOOR);
9
15
  export const DEFAULT_CONFIG = {
10
16
  sprint_goal: '',
@@ -21,8 +27,12 @@ export const DEFAULT_CONFIG = {
21
27
  test_tampering: 0.8,
22
28
  done_unverified: 0.6,
23
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
24
32
  code_complexity: 2,
25
33
  },
34
+ review_gate: true,
35
+ turn_limits: { minutes: 20, tool_calls: 150, agents: 4 },
26
36
  };
27
37
  const emptyBrain = () => ({
28
38
  recent_errors: [],
@@ -56,12 +66,19 @@ export function loadConfig(root) {
56
66
  const raw = readJson(join(root, '.cto.json')) ?? {};
57
67
  const thresholds = { ...DEFAULT_CONFIG.thresholds, ...(raw.thresholds ?? {}) };
58
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
+ }
59
74
  return {
60
75
  sprint_goal: typeof raw.sprint_goal === 'string' ? raw.sprint_goal : '',
61
76
  test_command: typeof raw.test_command === 'string' ? raw.test_command : '',
62
77
  protected_branches: Array.isArray(raw.protected_branches) ? raw.protected_branches.filter((b) => typeof b === 'string') : [],
63
78
  flow: raw.flow === true,
64
79
  thresholds,
80
+ review_gate: raw.review_gate !== false,
81
+ turn_limits: turnLimits(raw.turn_limits),
65
82
  };
66
83
  }
67
84
  /** Corrupt or missing state rebuilds as empty: the gate must never crash on its own bookkeeping. */
@@ -89,47 +106,212 @@ export function applyCredentials(env = process.env) {
89
106
  }
90
107
  /** Replace the stored keys with exactly `c`; personal prefs in the same file are kept. */
91
108
  export function saveCredentials(c) {
92
- const raw = readJson(credentialsPath()) ?? {};
109
+ const raw = readUserFile();
93
110
  for (const k of CREDENTIAL_KEYS)
94
111
  delete raw[k];
95
112
  return writeUserFile({ ...raw, ...c });
96
113
  }
114
+ export const DEFAULT_MODELS = { scope: 'global', advisor: 'fable', autoFix: true };
115
+ export const modelsPrefs = (p = loadPrefs()) => ({ ...DEFAULT_MODELS, ...p.models });
97
116
  export function loadPrefs() {
98
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
+ };
99
125
  return {
100
126
  ...(Array.isArray(raw.provider_order) && { provider_order: raw.provider_order.filter((p) => typeof p === 'string') }),
101
127
  ...((raw.lang === 'zh-TW' || raw.lang === 'en') && { lang: raw.lang }),
128
+ ...(models && { models: { ...DEFAULT_MODELS, ...models } }),
102
129
  };
103
130
  }
131
+ /** provider_order and lang are replaced by `p` (absent = cleared); models is kept unless `p` sets it. */
104
132
  export function savePrefs(p) {
105
- const raw = readJson(credentialsPath()) ?? {};
133
+ const raw = readUserFile();
106
134
  delete raw.provider_order;
107
135
  delete raw.lang;
108
136
  return writeUserFile({ ...raw, ...p });
109
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
+ }
110
151
  function writeUserFile(data) {
111
152
  const path = credentialsPath();
153
+ const tmp = `${path}.${process.pid}.tmp`;
112
154
  mkdirSync(dirname(path), { recursive: true });
113
- 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
+ }
114
166
  return path;
115
167
  }
116
168
  /**
117
169
  * Atomic write via per-process tmp + rename. No file lock (spec section 7): parallel hooks race, last write wins.
118
170
  * Never throws: losing bookkeeping is fine, but an exception here would turn a block into a fail-open pass.
119
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
+ }
120
187
  export function saveBrain(root, brain) {
121
188
  const path = join(root, '.cto-brain.json');
122
189
  const tmp = `${path}.${process.pid}.tmp`;
123
190
  try {
124
191
  writeFileSync(tmp, JSON.stringify(brain, null, 2) + '\n');
125
- renameSync(tmp, path);
192
+ renameWithRetry(renameSync, tmp, path);
126
193
  }
127
- catch {
194
+ catch (e) {
128
195
  try {
129
196
  unlinkSync(tmp);
130
197
  }
131
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
+ }
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);
132
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
+ });
133
315
  }
134
316
  /** Failures older than this are history, not a loop. */
135
317
  export const RECENT_ERROR_WINDOW_MS = 15 * 60_000;
package/dist/brief.js CHANGED
@@ -153,8 +153,7 @@ export function flowLines(root) {
153
153
  // Nothing truncated: the text and the acceptance command are what the agent dispatches and runs.
154
154
  const line = (t, rest) => ` ${t.id.padEnd(idW)} ${(t.priority ? `${t.priority} ` : '') + t.text} ${rest}`;
155
155
  const counts = ['active', 'planned', 'done'].filter((s) => rows.some((r) => r.status === s)).map((s) => `${rows.filter((r) => r.status === s).length} ${s}`);
156
- const pending = rows.filter((r) => r.signoff.concept !== 'approved' || r.signoff.spec !== 'approved')
157
- .map((r) => `${r.slug} (${['concept', 'spec'].filter((k) => r.signoff[k] !== 'approved').map((k) => `${k} ${r.signoff[k]}`).join(', ')})`);
156
+ const pending = rows.filter((r) => r.signoff !== 'approved').map((r) => `${r.slug} (concept ${r.signoff})`);
158
157
  const L = ['', ['Features', String(rows.length), ...counts, ...(pending.length ? [`sign-off pending: ${pending.join(', ')}`] : [])].join(' · ')];
159
158
  L.push('', ready.length
160
159
  ? `Ready · ${ready.length}${together.length > 1 ? ` (run together: ${together.map((t) => t.id).join(', ')})` : ''}`
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)