your-cto-jev 0.8.0 → 0.9.1
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 +92 -9
- package/dist/brain.js +3 -0
- package/dist/brief.js +120 -3
- package/dist/check.js +2 -2
- package/dist/docs.js +143 -0
- package/dist/doctor.js +4 -0
- package/dist/flow.js +186 -0
- package/dist/hooks.js +92 -6
- package/dist/i18n.js +86 -8
- package/dist/index.js +25 -3
- package/dist/local.js +115 -1
- package/dist/setup.js +135 -13
- package/dist/setupui.js +77 -12
- package/dist/skill.js +225 -20
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -35,7 +35,8 @@ Jev judges meaning and answers with probabilities, not prose. It costs about $0.
|
|
|
35
35
|
| `destructive_command` | every agent shell command | **Blocks** the command |
|
|
36
36
|
| `infinite_loop` | agent shell commands, after a recent failure | **Blocks** the command |
|
|
37
37
|
| `done_unverified` | an agent ending a turn that edited code or checked off plan items | **Sends it back to work** until the change is verified or the gap is disclosed |
|
|
38
|
-
| `architecture_violation` | `git commit`, once you set a sprint goal | Warns only |
|
|
38
|
+
| `architecture_violation` | `git commit`, once you set a sprint goal, or when the [development flow](#the-development-flow-optional) maps the commit to a feature's SPEC | Warns only |
|
|
39
|
+
| `architecture_undocumented` | `git commit` under the development flow, when code changes and no decision record is added | Warns only |
|
|
39
40
|
| `code_complexity` | every `git commit` | Warns only |
|
|
40
41
|
|
|
41
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.
|
|
@@ -54,6 +55,8 @@ Some checks need no model at all. They run first, before anything is sent anywhe
|
|
|
54
55
|
| A `.env` file with values (not `.env.example`) | `git commit` | **Blocks** |
|
|
55
56
|
| A file over 5 MB | `git commit` | Warns |
|
|
56
57
|
| `package.json` dependencies changed, lock file not | `git commit` | Warns |
|
|
58
|
+
| Development flow: a feature with tasks whose SPEC is not `Status: approved` | `git commit` touching that feature | **Blocks** |
|
|
59
|
+
| Development flow: INDEX.md older than its inputs, an `(after:)` id nobody defines, a SPEC `## Interface` changed | `git commit` | Warns |
|
|
57
60
|
|
|
58
61
|
`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.
|
|
59
62
|
|
|
@@ -97,7 +100,7 @@ cto setup
|
|
|
97
100
|
|
|
98
101
|
To update later, run `cto update`. Projects you already set up pick up the new version automatically: every hook only calls `cto`, and all the logic lives in the package. `cto` checks npm for a new version at most once a day and mentions it in its once-per-session notice, never on its own.
|
|
99
102
|
|
|
100
|
-
`cto setup` walks you through
|
|
103
|
+
`cto setup` walks you through five steps with arrow keys: coding agents, Jev providers, API keys, an optional sprint goal, and whether to use the [development flow](#the-development-flow-optional). Esc goes back a step. The agent list shows what is always installed (the git hooks, `.cto.json`) and the files each agent adds; before anything is written, setup lists every file it will create, update or remove and asks once. Providers are ticked in priority order, so the numbers you see are the failover order. Press a number to move the item under the cursor straight to that position:
|
|
101
104
|
|
|
102
105
|
```text
|
|
103
106
|
◆ Which Jev providers should cto use?
|
|
@@ -127,10 +130,13 @@ Other forms:
|
|
|
127
130
|
cto setup --agents claude,cursor --yes # non-interactive (scripts, CI); only adds, never removes
|
|
128
131
|
cto setup --refresh # re-write hooks and rules for the agents already set up
|
|
129
132
|
cto setup --uninstall # remove every cto hook, rules block and skill again
|
|
133
|
+
cto setup --flow # turn on the development flow (docs/cto_jev, cto-flow skill); --no-flow removes the skill and rule
|
|
130
134
|
cto doctor # is it actually working?
|
|
131
135
|
cto brief # what an agent should know before it starts here
|
|
132
136
|
cto check # preview the commit checks on your current changes
|
|
133
137
|
cto log # recent decisions with scores; cto report [n] flags a wrong one
|
|
138
|
+
cto index # regenerate docs/cto_jev/INDEX.md (brief does this too)
|
|
139
|
+
cto docs # suggest what to do with old planning markdown; changes nothing
|
|
134
140
|
```
|
|
135
141
|
|
|
136
142
|
`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.
|
|
@@ -148,8 +154,9 @@ The rules go where agents always look: a short marked block appended to `CLAUDE.
|
|
|
148
154
|
| Done means verified | `done_unverified` sends the agent back to work |
|
|
149
155
|
| Two strikes, change approach | `infinite_loop` blocks the retry once |
|
|
150
156
|
| Ask before anything irreversible | `destructive_command` blocks the command |
|
|
151
|
-
| Stay on the sprint goal | `architecture_violation` warns |
|
|
157
|
+
| Stay on the sprint goal, or inside the feature's SPEC | `architecture_violation` warns |
|
|
152
158
|
| Keep it simple | `code_complexity` warns |
|
|
159
|
+
| Work is planned in `docs/cto_jev/` (flow only); no work without sign-off | `flow_signoff` blocks the commit |
|
|
153
160
|
|
|
154
161
|
The rules also tell the agent to run `cto check` before committing, and never to bypass a block with `--no-verify` or by editing thresholds. Commit these files so the whole team's agents follow the same rules. `cto update` refreshes them (and any new hooks) in the repo you run it from; `cto doctor` flags a repo whose rules or hooks are older than the installed version, and `cto setup --refresh` brings it up to date.
|
|
155
162
|
|
|
@@ -157,10 +164,11 @@ The rules also tell the agent to run `cto check` before committing, and never to
|
|
|
157
164
|
|
|
158
165
|
```text
|
|
159
166
|
[cto] Nothing staged, checking the working tree instead (9 files, including new untracked files):
|
|
160
|
-
credential_leak
|
|
161
|
-
test_tampering
|
|
162
|
-
architecture_violation
|
|
163
|
-
|
|
167
|
+
credential_leak 0.03 blocks above 0.5 ok
|
|
168
|
+
test_tampering 0.03 blocks above 0.8 ok
|
|
169
|
+
architecture_violation not checked: no sprint_goal in .cto.json and no feature Constraints for these files
|
|
170
|
+
architecture_undocumented not checked: no docs/cto_jev/ flow, or this commit adds a decision record
|
|
171
|
+
code_complexity 2.02 warns above 2 would warn
|
|
164
172
|
[cto] Good to commit.
|
|
165
173
|
```
|
|
166
174
|
|
|
@@ -195,6 +203,77 @@ The lessons are collected without anyone writing them down. Every failed agent c
|
|
|
195
203
|
|
|
196
204
|
`Verify with` comes from `test_command` in `.cto.json`, or is detected from `package.json`, a `Makefile`, pytest, Cargo or Go when it is empty. Open plan items are the unchecked `- [ ]` lines in tracked markdown files, whatever planning tool wrote them.
|
|
197
205
|
|
|
206
|
+
## The development flow (optional)
|
|
207
|
+
|
|
208
|
+
Everything above says no after the fact. The flow is the part before: your agent acts as the CTO of the repo (plans, breaks work down, dispatches, accepts), and `cto` keeps it honest. It is off by default; `cto setup --flow` (or the question at the end of interactive setup) turns it on, and repos that never enable it see no change.
|
|
209
|
+
|
|
210
|
+
The agent does not get a new tool. It gets a skill (`.agents/skills/cto-flow/SKILL.md`), a fixed place for plans, and a few more checks:
|
|
211
|
+
|
|
212
|
+
```text
|
|
213
|
+
docs/cto_jev/
|
|
214
|
+
INDEX.md generated by cto: features, status, code paths, dependencies, sign-off
|
|
215
|
+
PRODUCT.md who it is for, how it earns, what it will not do
|
|
216
|
+
ARCHITECTURE.md stack, directory map, external services, the principles that do not change
|
|
217
|
+
decisions/NNNN-<slug>.md decision records, append-only
|
|
218
|
+
features/<slug>/
|
|
219
|
+
CONCEPT.md why: purpose, business rules, non-goals
|
|
220
|
+
SPEC.md how: ## Interface (what other features may use), ## Constraints, ## Internals
|
|
221
|
+
TASKS.md the only state: a checklist with ids, dependencies and an acceptance command
|
|
222
|
+
REVIEW.md what a zero-context reviewer found, and which tasks it became
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
A task is one checklist line, and everything else is computed from it:
|
|
226
|
+
|
|
227
|
+
```md
|
|
228
|
+
- [ ] CUST-1 Customer list
|
|
229
|
+
- [x] CUST-1.1 List API, filtered by role (after: PERM-2) (files: src/customers/api/)
|
|
230
|
+
accept: npm test -- customers/api
|
|
231
|
+
- [ ] CUST-1.2 List UI (after: CUST-1.1) (files: src/customers/ui/)
|
|
232
|
+
accept: manual
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
`(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:
|
|
236
|
+
|
|
237
|
+
```text
|
|
238
|
+
Features · 2 · 1 active · 1 planned · sign-off pending: billing (spec draft)
|
|
239
|
+
|
|
240
|
+
Ready · 3 (run together: CUST-1.2, PERM-3)
|
|
241
|
+
CUST-1.2 P1 List UI files src/customers/ui/ accept: manual
|
|
242
|
+
PERM-3 Role cache files src/auth/cache/ accept: npm test -- auth
|
|
243
|
+
CUST-2 Export files src/customers/ accept: manual (overlaps CUST-1.2: run after)
|
|
244
|
+
|
|
245
|
+
Blocked · 1
|
|
246
|
+
CUST-1.3 Shared types waiting on PERM-9 (missing), CUST-1.2
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
The skill gives the agent seven named jobs, so they cannot be confused with another skill's steps; say the name and it does that job:
|
|
250
|
+
|
|
251
|
+
| Say | The agent |
|
|
252
|
+
|---|---|
|
|
253
|
+
| `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 |
|
|
254
|
+
| `cto-jev feature` | talks the request through first (who it is for, business rules, what is out of scope, what other features may call, how it will be verified), writes CONCEPT and SPEC, walks you through them, stops for your `Status: approved` |
|
|
255
|
+
| `cto-jev tasks` | breaks an approved SPEC into parent/child tasks with files, dependencies and an acceptance command each |
|
|
256
|
+
| `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, P2 findings become tasks, then it commits to the review branch |
|
|
257
|
+
| `cto-jev release` | reviews the whole unreleased diff against the SPECs, files P1/P2/P3 tasks, requires every P1 ticked and `cto check --base <release branch>` green, then prepares the merge, PR or tag for you to perform |
|
|
258
|
+
| `cto-jev docs` | runs `cto docs` and brings you the list; acts only on what you decide |
|
|
259
|
+
| `cto-jev decision` | writes an append-only decision record under `decisions/` |
|
|
260
|
+
|
|
261
|
+
"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.
|
|
262
|
+
|
|
263
|
+
What `cto` adds on top, all without a model call unless noted:
|
|
264
|
+
|
|
265
|
+
| Check | Where | What happens |
|
|
266
|
+
|---|---|---|
|
|
267
|
+
| A feature has tasks but its SPEC is not approved | `git commit` touching that feature | **Blocks** |
|
|
268
|
+
| `architecture_violation` judged against the feature's `## Constraints` and PRODUCT's non-goals instead of a one-line goal | `git commit` (Jev) | Warns |
|
|
269
|
+
| An architecture change with no new decision record | `git commit` (Jev) | Warns |
|
|
270
|
+
| INDEX.md older than the TASKS it is built from; an `(after:)` id nobody defines; a SPEC's `## Interface` changed | `git commit` | Warns, naming dependants |
|
|
271
|
+
| Missing feature files, dead `(files:)` paths, `src/` directories owned by no feature, missing headings | `cto brief`, `cto doctor` | Listed |
|
|
272
|
+
|
|
273
|
+
`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.
|
|
274
|
+
|
|
275
|
+
If a docs site generator is configured (`mkdocs.yml`, `docusaurus.config.*`, `_config.yml`, ...), setup reminds you to keep `docs/cto_jev/` out of it: PRODUCT.md holds your pricing and business rules.
|
|
276
|
+
|
|
198
277
|
## Supported agents
|
|
199
278
|
|
|
200
279
|
The git pre-commit and pre-push checks are always installed. They protect every agent and every human who commits or pushes from that repo.
|
|
@@ -267,20 +346,23 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
|
|
|
267
346
|
```json
|
|
268
347
|
{
|
|
269
348
|
"sprint_goal": "",
|
|
349
|
+
"flow": false,
|
|
270
350
|
"thresholds": {
|
|
271
351
|
"destructive_command": 0.45
|
|
272
352
|
}
|
|
273
353
|
}
|
|
274
354
|
```
|
|
275
355
|
|
|
276
|
-
Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6, `test_tampering` 0.8, `done_unverified` 0.6, `architecture_violation` 0.85, `code_complexity` 2.
|
|
356
|
+
Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6, `test_tampering` 0.8, `done_unverified` 0.6, `architecture_violation` 0.85, `architecture_undocumented` 0.85, `code_complexity` 2.
|
|
277
357
|
|
|
278
|
-
- **`sprint_goal`**: fill it in to enable the architecture check, for example `"Ship Stripe billing, no new services"`.
|
|
358
|
+
- **`sprint_goal`**: fill it in to enable the architecture check, for example `"Ship Stripe billing, no new services"`. Under the development flow a commit that falls inside a feature's code scope is judged against that feature's SPEC instead; the goal is the fallback.
|
|
359
|
+
- **`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-flow skill 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.
|
|
279
360
|
- **`test_command`**: what `cto brief` tells the agent to verify with, for example `"pnpm test"`. Detected from the project when empty.
|
|
280
361
|
- **`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.
|
|
281
362
|
- **Thresholds**: Jev returns a probability from 0 to 1. `code_complexity` is the exception: it is a score from 0 (clean) to 4 (unmaintainable).
|
|
282
363
|
- **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.
|
|
283
364
|
- `done_unverified` (0.6) and `infinite_loop` (0.6) were calibrated the same way; the measurements are in the design spec.
|
|
365
|
+
- `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.
|
|
284
366
|
- **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.
|
|
285
367
|
- 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.
|
|
286
368
|
|
|
@@ -300,6 +382,7 @@ Defaults: `credential_leak` 0.5, `destructive_command` 0.7, `infinite_loop` 0.6,
|
|
|
300
382
|
- **The done check sees edits from edit tools and from common shell commands** (`sed -i`, redirects, `tee`, formatters), but not writes hidden inside scripts such as `node -e`. It also misses a test run that targets the wrong package. Claude Code's turn comes from its transcript; for Cursor, Gemini CLI and Codex, whose transcript formats are not public, cto keeps its own log of commands and edits, and a command counts as successful unless a failure event arrives.
|
|
301
383
|
- **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.
|
|
302
384
|
- **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.
|
|
385
|
+
- **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.
|
|
303
386
|
- **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.
|
|
304
387
|
|
|
305
388
|
## Development
|
package/dist/brain.js
CHANGED
|
@@ -7,11 +7,13 @@ export const DEFAULT_CONFIG = {
|
|
|
7
7
|
sprint_goal: '',
|
|
8
8
|
test_command: '',
|
|
9
9
|
protected_branches: [],
|
|
10
|
+
flow: false,
|
|
10
11
|
thresholds: {
|
|
11
12
|
credential_leak: 0.5,
|
|
12
13
|
destructive_command: 0.7,
|
|
13
14
|
infinite_loop: 0.6,
|
|
14
15
|
architecture_violation: 0.85,
|
|
16
|
+
architecture_undocumented: 0.85,
|
|
15
17
|
test_tampering: 0.8,
|
|
16
18
|
done_unverified: 0.6,
|
|
17
19
|
code_complexity: 2,
|
|
@@ -51,6 +53,7 @@ export function loadConfig(root) {
|
|
|
51
53
|
sprint_goal: typeof raw.sprint_goal === 'string' ? raw.sprint_goal : '',
|
|
52
54
|
test_command: typeof raw.test_command === 'string' ? raw.test_command : '',
|
|
53
55
|
protected_branches: Array.isArray(raw.protected_branches) ? raw.protected_branches.filter((b) => typeof b === 'string') : [],
|
|
56
|
+
flow: raw.flow === true,
|
|
54
57
|
thresholds: { ...DEFAULT_CONFIG.thresholds, ...(raw.thresholds ?? {}) },
|
|
55
58
|
};
|
|
56
59
|
}
|
package/dist/brief.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { execFileSync } from 'node:child_process';
|
|
2
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { freshErrors, loadBrain, loadConfig } from './brain.js';
|
|
5
|
+
import { FEATURE_FILES, FLOW_DIR, featureIndex, listFeatures, loadTasks, openTasks, parallelTasks, writeIndex } from './flow.js';
|
|
5
6
|
import { loadLessons, packageManager, rankLessons } from './lessons.js';
|
|
6
7
|
import { BOX } from './turn.js';
|
|
7
8
|
// `cto brief`: what an agent should know before it starts working in this repo. Read by agents (Claude Code gets it
|
|
@@ -34,9 +35,9 @@ export function detectTestCommand(root) {
|
|
|
34
35
|
return 'go test ./...';
|
|
35
36
|
return '';
|
|
36
37
|
}
|
|
37
|
-
/** Unchecked "- [ ]" items in tracked markdown files, by file. */
|
|
38
|
+
/** Unchecked "- [ ]" items in tracked markdown files, by file. The flow's own docs are listed by flowLines instead. */
|
|
38
39
|
export function openPlanItems(root) {
|
|
39
|
-
const files = git(root, 'ls-files', '-z', '--', '*.md', '*.mdx').split('\0').filter(
|
|
40
|
+
const files = git(root, 'ls-files', '-z', '--', '*.md', '*.mdx').split('\0').filter((f) => f && !f.startsWith(`${FLOW_DIR}/`));
|
|
40
41
|
const out = [];
|
|
41
42
|
for (const file of files) {
|
|
42
43
|
let text = '';
|
|
@@ -63,6 +64,121 @@ export function openPlanItems(root) {
|
|
|
63
64
|
}
|
|
64
65
|
return out;
|
|
65
66
|
}
|
|
67
|
+
const overlaps = (a, b) => a.some((x) => b.some((y) => x.startsWith(y) || y.startsWith(x)));
|
|
68
|
+
const unknownCount = (path) => {
|
|
69
|
+
try {
|
|
70
|
+
return readFileSync(path, 'utf8').split(/\r?\n/).filter((l) => /\(unknown\)|unknown\s*$/.test(l)).length;
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return 0;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
// Fixed headings, as the SPEC's 欄位 tables name them (docs/cto_jev/features/cto-flow/SPEC.md).
|
|
77
|
+
const HEADINGS = [
|
|
78
|
+
['PRODUCT.md', ['一句話', '使用者角色', '怎麼賺錢', '方案與限制', '不做的事', '設計約束']],
|
|
79
|
+
['ARCHITECTURE.md', ['技術棧', '目錄地圖', '外部服務與資料', '驗證指令', '不變的原則']],
|
|
80
|
+
];
|
|
81
|
+
const NOT_CODE = new Set(['node_modules', 'dist', 'build', 'docs', 'test', 'tests', '__tests__', 'coverage']);
|
|
82
|
+
const ISSUE_CAP = 12;
|
|
83
|
+
/** Consistency problems in the flow docs, one per line, in English. Empty when the repo does not use the flow or all is well. */
|
|
84
|
+
export function flowIssues(root) {
|
|
85
|
+
if (!existsSync(join(root, FLOW_DIR, 'features')))
|
|
86
|
+
return [];
|
|
87
|
+
const out = [];
|
|
88
|
+
// `file` is relative to docs/cto_jev; a missing file is reported by the feature-file check, not here.
|
|
89
|
+
const headings = (file, names) => {
|
|
90
|
+
let text;
|
|
91
|
+
try {
|
|
92
|
+
text = readFileSync(join(root, FLOW_DIR, file), 'utf8');
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const miss = names.filter((h) => !new RegExp(`^##\\s*${h}\\s*$`, 'm').test(text));
|
|
98
|
+
if (miss.length)
|
|
99
|
+
out.push(`${file}: missing heading ${miss.map((h) => `## ${h}`).join(', ')}`);
|
|
100
|
+
};
|
|
101
|
+
const features = listFeatures(root);
|
|
102
|
+
for (const slug of features) {
|
|
103
|
+
const missing = FEATURE_FILES.filter((f) => !existsSync(join(root, FLOW_DIR, 'features', slug, f)));
|
|
104
|
+
if (missing.length)
|
|
105
|
+
out.push(`features/${slug}: missing ${missing.join(', ')}`);
|
|
106
|
+
}
|
|
107
|
+
const tasks = loadTasks(root);
|
|
108
|
+
// No "(files:) not found" check: a task's files do not exist until it is done, and a done task may have deleted them.
|
|
109
|
+
// Directories under src/ that no task's (files:) entry points into. Without src/ the repo root holds too much that is
|
|
110
|
+
// not feature code (target/, vendor/, scripts/, cmd/) to call any of it an orphan.
|
|
111
|
+
const owned = tasks.flatMap((t) => t.files.map((f) => `${f.replace(/\\/g, '/')}/`));
|
|
112
|
+
const orphans = !existsSync(join(root, 'src')) ? [] : readdirSync(join(root, 'src'), { withFileTypes: true })
|
|
113
|
+
.filter((d) => d.isDirectory() && !d.name.startsWith('.') && !NOT_CODE.has(d.name))
|
|
114
|
+
.map((d) => `src/${d.name}/`)
|
|
115
|
+
.filter((dir) => !owned.some((f) => f.startsWith(dir)))
|
|
116
|
+
.sort();
|
|
117
|
+
if (orphans.length > 3)
|
|
118
|
+
out.push(`${orphans.join(', ')} belong to no feature`);
|
|
119
|
+
else
|
|
120
|
+
for (const dir of orphans)
|
|
121
|
+
out.push(`${dir} belongs to no feature`);
|
|
122
|
+
for (const slug of features) {
|
|
123
|
+
headings(`features/${slug}/SPEC.md`, ['Interface', 'Constraints', 'Internals']);
|
|
124
|
+
headings(`features/${slug}/CONCEPT.md`, ['目的']);
|
|
125
|
+
}
|
|
126
|
+
for (const [file, names] of HEADINGS)
|
|
127
|
+
headings(file, names);
|
|
128
|
+
return out.length > ISSUE_CAP ? [...out.slice(0, ISSUE_CAP), `… ${out.length - ISSUE_CAP} more`] : out;
|
|
129
|
+
}
|
|
130
|
+
/** How many issues a (possibly capped) flowIssues list stands for. */
|
|
131
|
+
export function issueTotal(issues) {
|
|
132
|
+
const more = /^… (\d+) more$/.exec(issues[issues.length - 1] ?? '');
|
|
133
|
+
return more ? ISSUE_CAP + Number(more[1]) : issues.length;
|
|
134
|
+
}
|
|
135
|
+
/** The development flow (docs/cto_jev/features): Ready and Blocked tasks, pending sign-offs, unknown fields. Empty when the repo does not use it. */
|
|
136
|
+
export function flowLines(root) {
|
|
137
|
+
if (!existsSync(join(root, FLOW_DIR, 'features')))
|
|
138
|
+
return [];
|
|
139
|
+
try {
|
|
140
|
+
writeIndex(root);
|
|
141
|
+
}
|
|
142
|
+
catch { /* read-only checkout (CI): brief still reads, it just cannot refresh INDEX.md */ }
|
|
143
|
+
const rows = featureIndex(root);
|
|
144
|
+
const tasks = loadTasks(root);
|
|
145
|
+
const ids = new Set(tasks.map((t) => t.id));
|
|
146
|
+
const open = openTasks(tasks);
|
|
147
|
+
const blocked = open.blocked;
|
|
148
|
+
// P1 before everything, P3 after everything; no tag means P2. Stable, so file order holds within a rank.
|
|
149
|
+
const rank = (t) => (t.priority === 'P1' ? 0 : t.priority === 'P3' ? 2 : 1);
|
|
150
|
+
const ready = [...open.ready].sort((a, b) => rank(a) - rank(b));
|
|
151
|
+
const together = parallelTasks(ready);
|
|
152
|
+
const idW = Math.max(8, ...tasks.map((t) => t.id.length));
|
|
153
|
+
// Nothing truncated: the text and the acceptance command are what the agent dispatches and runs.
|
|
154
|
+
const line = (t, rest) => ` ${t.id.padEnd(idW)} ${(t.priority ? `${t.priority} ` : '') + t.text} ${rest}`;
|
|
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(', ')})`);
|
|
158
|
+
const L = ['', ['Features', String(rows.length), ...counts, ...(pending.length ? [`sign-off pending: ${pending.join(', ')}`] : [])].join(' · ')];
|
|
159
|
+
L.push('', ready.length
|
|
160
|
+
? `Ready · ${ready.length}${together.length > 1 ? ` (run together: ${together.map((t) => t.id).join(', ')})` : ''}`
|
|
161
|
+
: `Ready · none${tasks.length ? '' : ` · add tasks to ${FLOW_DIR}/features/<slug>/TASKS.md`}`);
|
|
162
|
+
for (const t of ready) {
|
|
163
|
+
const first = together.includes(t) ? undefined : together.find((o) => overlaps(o.files, t.files));
|
|
164
|
+
const note = t.seq ? ' (seq: runs alone)' : first ? ` (overlaps ${first.id}: run after)` : '';
|
|
165
|
+
L.push(line(t, `files ${t.files.join(', ') || '-'} accept: ${t.accept ?? '-'}${note}`));
|
|
166
|
+
}
|
|
167
|
+
if (blocked.length) {
|
|
168
|
+
L.push('', `Blocked · ${blocked.length}`);
|
|
169
|
+
for (const b of blocked.slice(0, 8))
|
|
170
|
+
L.push(line(b.task, `waiting on ${b.waitingOn.map((id) => (ids.has(id) ? id : `${id} (missing)`)).join(', ')}`));
|
|
171
|
+
if (blocked.length > 8)
|
|
172
|
+
L.push(` … ${blocked.length - 8} more`);
|
|
173
|
+
}
|
|
174
|
+
const issues = flowIssues(root);
|
|
175
|
+
if (issues.length)
|
|
176
|
+
L.push('', `Flow issues · ${issueTotal(issues)}`, ...issues.map((i) => ` ${i}`));
|
|
177
|
+
const unknown = ['PRODUCT.md', 'ARCHITECTURE.md'].map((f) => [f, unknownCount(join(root, FLOW_DIR, f))]).filter(([, n]) => n > 0);
|
|
178
|
+
if (unknown.length)
|
|
179
|
+
L.push('', `Unknown fields · ${unknown.map(([f, n]) => `${f} ${n}`).join(' · ')}`);
|
|
180
|
+
return L;
|
|
181
|
+
}
|
|
66
182
|
const ago = (iso, now) => {
|
|
67
183
|
const mins = Math.max(0, Math.round((now - Date.parse(iso)) / 60_000));
|
|
68
184
|
return mins < 60 ? `${mins}m ago` : mins < 1440 ? `${Math.round(mins / 60)}h ago` : `${Math.round(mins / 1440)}d ago`;
|
|
@@ -85,6 +201,7 @@ export function brief(root, now = Date.now()) {
|
|
|
85
201
|
L.push(`Sprint goal ${cfg.sprint_goal.trim() || '(none set in .cto.json)'}`);
|
|
86
202
|
const test = cfg.test_command.trim() || detectTestCommand(root);
|
|
87
203
|
L.push(`Verify with ${test || '(unknown: set test_command in .cto.json)'}${test && !cfg.test_command.trim() ? ' (detected; pin it as test_command in .cto.json)' : ''}`);
|
|
204
|
+
L.push(...flowLines(root));
|
|
88
205
|
const plans = openPlanItems(root);
|
|
89
206
|
if (plans.length) {
|
|
90
207
|
const total = plans.reduce((n, p) => n + p.items.length, 0);
|
package/dist/check.js
CHANGED
|
@@ -34,7 +34,7 @@ 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');
|
|
37
|
+
const review = await reviewDiff(diff, cfg, brain, lang, undefined, 'check', root, !!base);
|
|
38
38
|
saveBrain(root, brain); // provider cooldowns and the decision log; check runs are not counted as blocks
|
|
39
39
|
if (!review)
|
|
40
40
|
return { code: 0, lines: [t(lang, 'check_nothing')] };
|
|
@@ -52,7 +52,7 @@ export async function runCheck(root, lang, base) {
|
|
|
52
52
|
const v = review.scores[s];
|
|
53
53
|
const name = s.padEnd(width);
|
|
54
54
|
if (v === undefined) {
|
|
55
|
-
const why = s === 'test_tampering' ? 'check_why_tests' : s === 'architecture_violation' ? 'check_why_goal' : 'check_why_failed';
|
|
55
|
+
const why = s === 'test_tampering' ? 'check_why_tests' : s === 'architecture_violation' ? 'check_why_goal' : s === 'architecture_undocumented' ? 'check_why_adr' : s === 'code_complexity' && base ? 'check_why_release' : 'check_why_failed';
|
|
56
56
|
lines.push(` ${name} ${t(lang, why)}`);
|
|
57
57
|
continue;
|
|
58
58
|
}
|
package/dist/docs.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { evaluate } from './api.js';
|
|
5
|
+
import { estimateTokens } from './diff.js';
|
|
6
|
+
import { featureIndex, renderIndex } from './flow.js';
|
|
7
|
+
import { t } from './i18n.js';
|
|
8
|
+
import { maskSensitiveState } from './masker.js';
|
|
9
|
+
import { BOX } from './turn.js';
|
|
10
|
+
const PLANNING_MIN = 0.6;
|
|
11
|
+
const FINISHED_MIN = 0.6;
|
|
12
|
+
const CONFLICTS_MIN = 0.6;
|
|
13
|
+
const STATE_TOKENS = 6000;
|
|
14
|
+
const UNAVAILABLE = 'Jev unavailable; decide by hand';
|
|
15
|
+
const git = (cwd, ...args) => {
|
|
16
|
+
try {
|
|
17
|
+
return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return '';
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
const EXCLUDED = /^(README|CONTRIBUTING|CHANGELOG|SECURITY)\.md$|^LICENSE/i;
|
|
24
|
+
const TOOL_DIR = /(^|\/)(\.planning|specs|\.kiro)\//;
|
|
25
|
+
const TOOL_FILE = /^(PLAN|TODO|NOTES)\.md$|-plan\.md$/i;
|
|
26
|
+
const STALE_DAYS = 30;
|
|
27
|
+
/** Checkbox counts, ignoring boxes inside ``` fences exactly like openPlanItems. */
|
|
28
|
+
function countBoxes(text) {
|
|
29
|
+
let fenced = false, open = 0, done = 0;
|
|
30
|
+
for (const l of text.split(/\r?\n/)) {
|
|
31
|
+
if (/^\s*(```|~~~)/.test(l)) {
|
|
32
|
+
fenced = !fenced;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const m = fenced ? null : BOX.exec(l);
|
|
36
|
+
if (m)
|
|
37
|
+
m[2] === ' ' ? open++ : done++;
|
|
38
|
+
}
|
|
39
|
+
return { open, done };
|
|
40
|
+
}
|
|
41
|
+
export function docCandidates(root, now = Date.now()) {
|
|
42
|
+
const files = git(root, 'ls-files', '-z', '--', '*.md', '*.mdx').split('\0').filter(Boolean);
|
|
43
|
+
const out = [];
|
|
44
|
+
for (const file of files) {
|
|
45
|
+
const base = file.split('/').pop();
|
|
46
|
+
if (EXCLUDED.test(base) || file.startsWith('docs/cto_jev/'))
|
|
47
|
+
continue;
|
|
48
|
+
let text = '';
|
|
49
|
+
try {
|
|
50
|
+
text = readFileSync(join(root, file), 'utf8');
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (text.length > 200_000)
|
|
56
|
+
continue;
|
|
57
|
+
const { open, done } = countBoxes(text);
|
|
58
|
+
const tool = TOOL_DIR.test(file) || TOOL_FILE.test(base);
|
|
59
|
+
const boxed = open + done > 0;
|
|
60
|
+
if (!boxed && !tool)
|
|
61
|
+
continue; // plain docs are never candidates, under docs/ or anywhere else
|
|
62
|
+
const ct = Number(git(root, 'log', '-1', '--format=%ct', '--', file));
|
|
63
|
+
const lastModifiedDays = ct > 0 ? Math.floor((now / 1000 - ct) / 86_400) : null;
|
|
64
|
+
const ticked = boxed && open === 0;
|
|
65
|
+
const [verdict, reason] = tool && ticked ? ['delete', 'planning file, every item ticked'] :
|
|
66
|
+
ticked && lastModifiedDays !== null && lastModifiedDays > STALE_DAYS ? ['delete', `every item ticked, untouched for ${lastModifiedDays} days`] :
|
|
67
|
+
tool && open > 0 ? ['merge', `planning file with ${open} open item${open === 1 ? '' : 's'}`] :
|
|
68
|
+
['ask', tool ? 'planning file without a checklist' : 'has a checklist outside a planning path'];
|
|
69
|
+
out.push({ file, verdict, reason, open, done, lastModifiedDays });
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
const QUESTIONS = {
|
|
74
|
+
planning: { type: 'noul', instructions: 'Is this document a plan, spec, checklist or working notes rather than documentation written for users of the software?' },
|
|
75
|
+
finished: { type: 'noul', instructions: 'Is the work this document describes already done, or already covered by the features listed in the INDEX?' },
|
|
76
|
+
conflicts: { type: 'noul', instructions: 'Does this document contradict the current INDEX or the features it lists?' },
|
|
77
|
+
};
|
|
78
|
+
function clip(s) {
|
|
79
|
+
let n = s.length;
|
|
80
|
+
while (n > 0 && estimateTokens(s.slice(0, n)) > STATE_TOKENS)
|
|
81
|
+
n = Math.floor(n * 0.8);
|
|
82
|
+
return s.slice(0, n);
|
|
83
|
+
}
|
|
84
|
+
/** Ask Jev about every `ask` candidate, one request per file, sequentially. Any failure leaves the candidate as `ask` (fail open). */
|
|
85
|
+
export async function judgeDocs(root, candidates, ctx) {
|
|
86
|
+
if (!candidates.some((c) => c.verdict === 'ask'))
|
|
87
|
+
return candidates;
|
|
88
|
+
const index = renderIndex(featureIndex(root));
|
|
89
|
+
const out = [];
|
|
90
|
+
for (const c of candidates) {
|
|
91
|
+
if (c.verdict !== 'ask') {
|
|
92
|
+
out.push(c);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
let text = '';
|
|
96
|
+
try {
|
|
97
|
+
text = readFileSync(join(root, c.file), 'utf8');
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
out.push({ ...c, reason: UNAVAILABLE });
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const state = maskSensitiveState(`INDEX (docs/cto_jev/INDEX.md):\n${index}\n\nDocument ${c.file}:\n${clip(text)}`);
|
|
104
|
+
const r = await evaluate({ state, questions: QUESTIONS }, ctx).catch(() => null);
|
|
105
|
+
const p = (k) => { const a = r?.ok ? r.answers[k] : undefined; return a?.type === 'noul' && typeof a.noul === 'number' ? a.noul : NaN; };
|
|
106
|
+
const [planning, finished, conflicts] = [p('planning'), p('finished'), p('conflicts')];
|
|
107
|
+
if ([planning, finished, conflicts].some(Number.isNaN)) {
|
|
108
|
+
out.push({ ...c, reason: UNAVAILABLE });
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const probs = `planning ${planning.toFixed(2)} · finished ${finished.toFixed(2)} · conflicts ${conflicts.toFixed(2)}`;
|
|
112
|
+
const [verdict, why] = planning < PLANNING_MIN ? ['ask', 'looks like user documentation; not touched'] :
|
|
113
|
+
finished >= FINISHED_MIN ? (c.open === 0 ? ['delete', 'work already done'] : ['archive', 'work already done, open items left']) :
|
|
114
|
+
conflicts >= CONFLICTS_MIN ? ['archive', 'contradicts current features; keep for humans, agents should not read it'] :
|
|
115
|
+
['merge', 'open work not yet in docs/cto_jev/'];
|
|
116
|
+
out.push({ ...c, verdict, reason: `${why} (${probs})` });
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
/** The whole `cto docs` report: rules, then Jev on what the rules left open. No network call when nothing is `ask`. */
|
|
121
|
+
export async function docsReport(root, ctx) {
|
|
122
|
+
return renderDocs(await judgeDocs(root, docCandidates(root), ctx), ctx.lang);
|
|
123
|
+
}
|
|
124
|
+
const GROUPS = ['delete', 'merge', 'archive', 'ask'];
|
|
125
|
+
export function renderDocs(c, lang = 'en') {
|
|
126
|
+
if (!c.length)
|
|
127
|
+
return [t(lang, 'docs_none')];
|
|
128
|
+
const L = [];
|
|
129
|
+
for (const verdict of GROUPS) {
|
|
130
|
+
const rows = c.filter((d) => d.verdict === verdict);
|
|
131
|
+
if (!rows.length)
|
|
132
|
+
continue;
|
|
133
|
+
if (L.length)
|
|
134
|
+
L.push('');
|
|
135
|
+
L.push(t(lang, `docs_group_${verdict}`));
|
|
136
|
+
for (const d of rows) {
|
|
137
|
+
const age = d.lastModifiedDays === null ? 'age unknown' : `${d.lastModifiedDays}d old`;
|
|
138
|
+
L.push(` ${d.file} ${d.open} open · ${d.done} done · ${age} — ${d.reason}`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
L.push('', t(lang, 'docs_footer'));
|
|
142
|
+
return L;
|
|
143
|
+
}
|
package/dist/doctor.js
CHANGED
|
@@ -4,6 +4,7 @@ import { join } from 'node:path';
|
|
|
4
4
|
import { agents } from './agents.js';
|
|
5
5
|
import { probeProvider, providerOrder, providers } from './api.js';
|
|
6
6
|
import { loadBrain, loadConfig, loadCredentials } from './brain.js';
|
|
7
|
+
import { flowIssues, issueTotal } from './brief.js';
|
|
7
8
|
import { AGENT_TIMEOUT_MS } from './hooks.js';
|
|
8
9
|
import { t } from './i18n.js';
|
|
9
10
|
import { GIT_HOOKS, conflictLines, ignoredByGit, missingHooks, wiredAgents } from './setup.js';
|
|
@@ -106,6 +107,9 @@ export async function doctor(cwd, lang, slowMs = AGENT_TIMEOUT_MS) {
|
|
|
106
107
|
const cfg = loadConfig(root);
|
|
107
108
|
L.push(` -- ${t(lang, cfg.sprint_goal.trim() ? 'doc_goal_set' : 'doc_goal_empty')}`);
|
|
108
109
|
L.push(...conflictLines(root, wired, lang).map((l) => ` ${l}`));
|
|
110
|
+
const issues = flowIssues(root); // a note, not a problem: the docs are the user's, cto only points at them
|
|
111
|
+
if (issues.length)
|
|
112
|
+
L.push(` -- ${t(lang, 'doc_flow_issues', { n: issueTotal(issues), first: issues[0] })}`);
|
|
109
113
|
const brain = loadBrain(root);
|
|
110
114
|
L.push(` -- ${t(lang, 'doc_stats', { blocked: brain.blocked_attempts, skipped: brain.skipped_attempts })}`);
|
|
111
115
|
if (brain.last_check_at) {
|