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/dist/flow.js ADDED
@@ -0,0 +1,186 @@
1
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { BOX } from './turn.js';
4
+ // docs/cto_jev/features/<slug>/TASKS.md: the one place the development flow keeps state. Everything else (INDEX,
5
+ // ready list, feature dependencies, code ownership) is computed from it. Spec: docs/cto_jev/features/cto-flow/SPEC.md.
6
+ export const FLOW_DIR = 'docs/cto_jev';
7
+ export const FEATURE_FILES = ['CONCEPT.md', 'SPEC.md', 'TASKS.md', 'REVIEW.md'];
8
+ const ID = /^([A-Z][A-Z0-9]*-\d+(?:\.\d+)*)\b\s*/;
9
+ const TAG = /\s*\((after|files):\s*([^)]*)\)/g;
10
+ const PRIORITY = /\s*\((P[123])\)/;
11
+ const SEQ = /\s*\(seq\)/;
12
+ const ACCEPT = /^\s*(?:驗收|accept)[::]\s*(.+?)\s*$/i;
13
+ const list = (s) => s.split(/[,,]/).map((x) => x.trim()).filter(Boolean);
14
+ /** Parses one TASKS.md. Items without an id are skipped (they are not tasks the flow can track). */
15
+ export function parseTasks(text, feature, file) {
16
+ const tasks = [];
17
+ const stack = [];
18
+ let fenced = false;
19
+ const lines = text.split(/\r?\n/);
20
+ lines.forEach((raw, i) => {
21
+ if (/^\s*(```|~~~)/.test(raw)) {
22
+ fenced = !fenced;
23
+ return;
24
+ }
25
+ if (fenced)
26
+ return;
27
+ const m = BOX.exec(raw);
28
+ if (!m) {
29
+ const a = ACCEPT.exec(raw);
30
+ const last = tasks[tasks.length - 1];
31
+ if (a && last && !last.accept)
32
+ last.accept = a[1];
33
+ return;
34
+ }
35
+ const indent = m[1].length;
36
+ const idm = ID.exec(m[3]);
37
+ if (!idm)
38
+ return;
39
+ const after = [];
40
+ const files = [];
41
+ let priority;
42
+ let seq = false;
43
+ const text = m[3].slice(idm[0].length)
44
+ .replace(TAG, (_, k, v) => { (k === 'after' ? after : files).push(...list(v)); return ''; })
45
+ .replace(PRIORITY, (_, p) => { priority = p; return ''; })
46
+ .replace(SEQ, () => { seq = true; return ''; })
47
+ .trim();
48
+ while (stack.length && stack[stack.length - 1].indent >= indent)
49
+ stack.pop();
50
+ const parent = stack[stack.length - 1]?.id;
51
+ const t = { id: idm[1], text, done: m[2] !== ' ', feature, file, line: i + 1, parent, children: [], after, files, ...(priority ? { priority } : {}), ...(seq ? { seq } : {}) };
52
+ if (parent)
53
+ tasks.find((p) => p.id === parent)?.children.push(t.id);
54
+ tasks.push(t);
55
+ stack.push({ indent, id: t.id });
56
+ });
57
+ return tasks;
58
+ }
59
+ /** Feature slugs: the directories under docs/cto_jev/features, from the file system (a new feature is not yet in git). */
60
+ export function listFeatures(root) {
61
+ const dir = join(root, FLOW_DIR, 'features');
62
+ if (!existsSync(dir))
63
+ return [];
64
+ return readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
65
+ }
66
+ export function loadTasks(root) {
67
+ return listFeatures(root).flatMap((slug) => {
68
+ const rel = `${FLOW_DIR}/features/${slug}/TASKS.md`;
69
+ try {
70
+ return parseTasks(readFileSync(join(root, rel), 'utf8'), slug, rel);
71
+ }
72
+ catch {
73
+ return [];
74
+ }
75
+ });
76
+ }
77
+ const isLeaf = (t) => t.children.length === 0;
78
+ /** Two file scopes collide when one is a prefix of the other ("src/a/" vs "src/a/b.ts"). */
79
+ const overlaps = (a, b) => a.some((x) => b.some((y) => x.startsWith(y) || y.startsWith(x)));
80
+ /** Open leaf tasks whose `after` tasks are all done. `blocked` says what each of the others is waiting for. */
81
+ export function openTasks(tasks) {
82
+ const byId = new Map(tasks.map((t) => [t.id, t]));
83
+ // A parent is done when every child is, whether or not anyone ticked its own box.
84
+ const done = (id) => {
85
+ const t = byId.get(id);
86
+ return !t ? false : isLeaf(t) ? t.done : t.children.every(done);
87
+ };
88
+ const ready = [];
89
+ const blocked = [];
90
+ for (const t of tasks) {
91
+ if (t.done || !isLeaf(t))
92
+ continue;
93
+ const waitingOn = t.after.filter((id) => !done(id));
94
+ if (waitingOn.length)
95
+ blocked.push({ task: t, waitingOn });
96
+ else
97
+ ready.push(t);
98
+ }
99
+ return { ready, blocked };
100
+ }
101
+ /**
102
+ * Ready tasks that can run at the same time: taken in the given order, skipping any whose files overlap one already
103
+ * taken and any marked (seq), which always runs on its own.
104
+ */
105
+ export function parallelTasks(ready) {
106
+ const out = [];
107
+ for (const t of ready)
108
+ if (!t.seq && !out.some((o) => overlaps(o.files, t.files)))
109
+ out.push(t);
110
+ return out;
111
+ }
112
+ /** Ids defined by more than one task, across all TASKS.md files. */
113
+ export const duplicateIds = (tasks) => {
114
+ const seen = new Set();
115
+ return [...new Set(tasks.filter((t) => seen.has(t.id) || !seen.add(t.id)).map((t) => t.id))];
116
+ };
117
+ /** `after` ids that no task defines. */
118
+ export const danglingAfter = (tasks) => {
119
+ const ids = new Set(tasks.map((t) => t.id));
120
+ return tasks.flatMap((t) => t.after.filter((id) => !ids.has(id)).map((id) => ({ task: t.id, missing: id })));
121
+ };
122
+ const readOr = (path) => { try {
123
+ return readFileSync(path, 'utf8');
124
+ }
125
+ catch {
126
+ return undefined;
127
+ } };
128
+ /** `Status: draft|approved` anywhere in the file; no file or no such line is 'missing'. */
129
+ const signoff = (path) => /^Status:\s*(draft|approved)\s*$/im.exec(readOr(path) ?? '')?.[1]?.toLowerCase() ?? 'missing';
130
+ function purpose(concept) {
131
+ const lines = concept.split(/\r?\n/);
132
+ const i = lines.findIndex((l) => /^##\s*目的\s*$/.test(l));
133
+ const next = i < 0 ? undefined : lines.slice(i + 1).find((l) => l.trim());
134
+ return next && !next.startsWith('#') ? next.trim() : '';
135
+ }
136
+ const uniqSorted = (xs) => [...new Set(xs)].sort();
137
+ export function featureIndex(root) {
138
+ const tasks = loadTasks(root);
139
+ const featureOf = new Map(tasks.map((t) => [t.id, t.feature]));
140
+ return listFeatures(root).map((slug) => {
141
+ const dir = join(root, FLOW_DIR, 'features', slug);
142
+ const mine = tasks.filter((t) => t.feature === slug);
143
+ const leaves = mine.filter(isLeaf);
144
+ const files = uniqSorted(mine.flatMap((t) => t.files));
145
+ return {
146
+ slug,
147
+ purpose: purpose(readOr(join(dir, 'CONCEPT.md')) ?? ''),
148
+ status: !mine.length ? 'planned' : leaves.every((t) => t.done) ? 'done' : 'active',
149
+ code: files.filter((f) => !files.some((o) => o !== f && f.startsWith(o))),
150
+ dependsOn: uniqSorted(mine.flatMap((t) => t.after).map((id) => featureOf.get(id)).filter((f) => !!f && f !== slug)),
151
+ signoff: { concept: signoff(join(dir, 'CONCEPT.md')), spec: signoff(join(dir, 'SPEC.md')) },
152
+ };
153
+ });
154
+ }
155
+ export function renderIndex(rows) {
156
+ const cell = (s) => s.replace(/\|/g, '\\|');
157
+ const line = (r) => `| ${r.slug} | ${r.status} | ${cell(r.purpose)} | ${r.code.join(', ')} | ${r.dependsOn.join(', ')} | ${r.signoff.concept}/${r.signoff.spec} |`;
158
+ return [
159
+ '# INDEX',
160
+ '',
161
+ '<!-- Generated by cto. Do not edit: run cto index. -->',
162
+ '',
163
+ 'Read the row of the feature you work on, then its SPEC.md; for each feature in "Depends on", read only the `## Interface` section of its SPEC.md.',
164
+ '',
165
+ '| Feature | Status | Purpose | Code | Depends on | Sign-off |',
166
+ '|---|---|---|---|---|---|',
167
+ ...[...rows].sort((a, b) => a.slug.localeCompare(b.slug)).map(line),
168
+ '',
169
+ ].join('\n');
170
+ }
171
+ const INDEX = `${FLOW_DIR}/INDEX.md`;
172
+ // CRLF-normalized so a checkout with autocrlf does not look stale forever.
173
+ const onDisk = (root) => readOr(join(root, INDEX))?.replace(/\r\n/g, '\n');
174
+ const hasFeatures = (root) => existsSync(join(root, FLOW_DIR, 'features'));
175
+ /** Rewrites INDEX.md only when its content changed; no features directory means nothing to do. */
176
+ export function writeIndex(root) {
177
+ if (!hasFeatures(root))
178
+ return { path: INDEX, changed: false };
179
+ const next = renderIndex(featureIndex(root));
180
+ if (onDisk(root) === next)
181
+ return { path: INDEX, changed: false };
182
+ writeFileSync(join(root, INDEX), next);
183
+ return { path: INDEX, changed: true };
184
+ }
185
+ /** True when INDEX.md is missing or no longer matches the feature folders. */
186
+ export const indexStale = (root) => hasFeatures(root) && onDisk(root) !== renderIndex(featureIndex(root));
package/dist/hooks.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { readFileSync } from 'node:fs';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
+ import { FLOW_DIR, featureIndex } from './flow.js';
4
5
  import { styleText } from 'node:util';
5
6
  import { checkUpdate, currentVersion } from './update.js';
6
7
  import { isCodeFile, tickedItems, tickedKey, turnActions, turnState } from './turn.js';
@@ -97,6 +98,83 @@ const architectureQ = (goal) => ({
97
98
  instructions: `The current sprint goal is: "${goal}". Does this change clearly work against or drift away from that goal?`,
98
99
  criteria: { true: 'Clearly off-goal or contradicts the sprint goal', false: 'Aligned with or neutral to the sprint goal' },
99
100
  });
101
+ /** Text under `## <heading>` up to the next `## `; '' when the heading is missing. */
102
+ function section(text, heading) {
103
+ const lines = text.split(/\r?\n/);
104
+ const i = lines.findIndex((l) => heading.test(l));
105
+ if (i < 0)
106
+ return '';
107
+ const rest = lines.slice(i + 1);
108
+ const end = rest.findIndex((l) => /^##\s/.test(l));
109
+ return rest.slice(0, end < 0 ? undefined : end).join('\n').trim();
110
+ }
111
+ const DRIFT_TEXT_CHARS = 1500;
112
+ // A skeleton field still reads `unknown`; telling Jev "the non-goals: unknown" only adds noise to the question.
113
+ const clip = (s) => (/^[-*\s]*\(?unknown\)?\s*$/i.test(s) ? '' : s.length > DRIFT_TEXT_CHARS ? s.slice(0, DRIFT_TEXT_CHARS) + '…' : s);
114
+ // Without src/ a "code change" is a source file outside dot-directories; lock files, config, images and CI yaml are not.
115
+ const SOURCE = /\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|kts|rb|php|cs|swift|c|cc|cpp|h|hpp|m|scala|ex|exs|erl|dart|vue|svelte|sql|sh|bash|ps1|lua|zig|hs|ml|clj|pl|r|groovy|tf)$/i;
116
+ const readOr = (path) => { try {
117
+ return readFileSync(path, 'utf8');
118
+ }
119
+ catch {
120
+ return '';
121
+ } };
122
+ /**
123
+ * The feature a diff belongs to: per touched file, the feature whose code scope is the longest prefix; the feature that
124
+ * wins the most files (ties by slug). Its SPEC `## Constraints` plus PRODUCT.md `## 不做的事`. Undefined without the
125
+ * flow, without a match, or when Constraints is missing or empty: the caller then falls back to sprint_goal.
126
+ */
127
+ export function driftContext(root, files) {
128
+ if (!existsSync(join(root, FLOW_DIR, 'features')))
129
+ return undefined;
130
+ const rows = featureIndex(root);
131
+ const wins = new Map();
132
+ for (const f of files) {
133
+ let best;
134
+ for (const r of rows)
135
+ for (const c of r.code)
136
+ if (f.startsWith(c) && c.length > (best?.len ?? 0))
137
+ best = { slug: r.slug, len: c.length };
138
+ if (best)
139
+ wins.set(best.slug, (wins.get(best.slug) ?? 0) + 1);
140
+ }
141
+ const feature = [...wins].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0];
142
+ if (!feature)
143
+ return undefined;
144
+ const constraints = clip(section(readOr(join(root, FLOW_DIR, 'features', feature, 'SPEC.md')), /^##\s*Constraints\s*$/));
145
+ if (!constraints)
146
+ return undefined;
147
+ const nonGoals = section(readOr(join(root, FLOW_DIR, 'PRODUCT.md')), /^##\s*不做的事\s*$/);
148
+ return { feature, constraints, nonGoals: clip(nonGoals) };
149
+ }
150
+ export const driftQ = ({ feature, constraints, nonGoals }) => ({
151
+ type: 'noul',
152
+ instructions: `This change belongs to the feature "${feature}". The feature's constraints:\n${constraints}\n` +
153
+ (nonGoals ? `\nThe product's non-goals (things it will not do):\n${nonGoals}\n` : '') +
154
+ '\nDoes this change clearly violate one of the listed constraints, or do one of the listed non-goals?',
155
+ criteria: { true: 'Violates a listed constraint or does a listed non-goal', false: 'Consistent with or unrelated to them' },
156
+ });
157
+ /**
158
+ * Ask for a decision record when a flow repo changes code under `src/` (a source file outside dot-directories when there
159
+ * is no `src/`) and the same commit adds nothing under `docs/cto_jev/decisions/`. Undefined when the question does not apply.
160
+ */
161
+ export function adrQuestion(root, paths) {
162
+ if (!existsSync(join(root, FLOW_DIR, 'features')))
163
+ return undefined;
164
+ const code = existsSync(join(root, 'src')) ? (p) => p.startsWith('src/') : (p) => SOURCE.test(p) && !/(^|\/)\./.test(p);
165
+ // A record is NNNN-slug.md; the .gitkeep that setup leaves in decisions/ is not one.
166
+ if (!paths.some(code) || paths.some((p) => p.startsWith(`${FLOW_DIR}/decisions/`) && /\.md$/i.test(p)))
167
+ return undefined;
168
+ const principles = clip(section(readOr(join(root, FLOW_DIR, 'ARCHITECTURE.md')), /^##\s*不變的原則\s*$/));
169
+ return {
170
+ type: 'noul',
171
+ instructions: (principles ? `The architecture's standing principles:\n${principles}\n\n` : '') +
172
+ 'Does this change introduce or remove a service, data store, external system or SDK the product now depends on, layer, module boundary or cross-cutting mechanism, ' +
173
+ 'or break one of the listed principles, i.e. a change that deserves a decision record? Adding a library, upgrading a version or importing a helper package is not that.',
174
+ criteria: { true: 'Changes the architecture or breaks a listed principle; a decision record is missing', false: 'Ordinary feature, fix, library import or version bump within the existing architecture' },
175
+ };
176
+ }
177
+ const diffPaths = (files) => files.map((f) => /^diff --git a\/.+? b\/(.+)$/m.exec(f)?.[1]).filter((p) => !!p);
100
178
  const value = (a) => (a?.type === 'noul' ? a.noul : a?.type === 'score' ? a.score : undefined);
101
179
  function exceeded(answers, signal, cfg) {
102
180
  const v = value(answers[signal]);
@@ -139,14 +217,22 @@ export function logDecision(brain, hook, state, answers, cfg, now) {
139
217
  }
140
218
  }
141
219
  /** Run the commit checks on a diff. Shared by the git hook and `cto check`. Mutates brain for provider state and the decision log. */
142
- export async function reviewDiff(rawDiff, cfg, brain, lang, now, hook = 'commit') {
220
+ export async function reviewDiff(rawDiff, cfg, brain, lang, now, hook = 'commit', root, release = false) {
143
221
  const files = filterDiff(maskDiff(rawDiff));
144
222
  if (!files.length)
145
223
  return null;
146
224
  const chunks = chunkDiff(files);
147
- const soft = { code_complexity: Q.code_complexity };
148
- if (cfg.sprint_goal.trim())
225
+ // Complexity is a judgement on one change; a whole branch (`cto check --base`) is docs, tests and many changes at once.
226
+ const soft = release ? {} : { code_complexity: Q.code_complexity };
227
+ const paths = root ? diffPaths(files) : [];
228
+ const drift = root ? driftContext(root, paths) : undefined;
229
+ if (drift)
230
+ soft.architecture_violation = driftQ(drift);
231
+ else if (cfg.sprint_goal.trim())
149
232
  soft.architecture_violation = architectureQ(cfg.sprint_goal.trim());
233
+ const adr = root ? adrQuestion(root, paths) : undefined;
234
+ if (adr)
235
+ soft.architecture_undocumented = adr;
150
236
  const notices = new Set();
151
237
  const asked = new Set();
152
238
  const ctx = { brain, lang, timeoutMs: 5000, notices, now };
@@ -184,7 +270,7 @@ export async function reviewDiff(rawDiff, cfg, brain, lang, now, hook = 'commit'
184
270
  return { files: files.length, scores, asked, failed: results.some((r) => !r.ok), noKeys, notices };
185
271
  }
186
272
  export const BLOCKING_COMMIT = ['credential_leak', 'test_tampering'];
187
- export const WARNING_COMMIT = ['architecture_violation', 'code_complexity'];
273
+ export const WARNING_COMMIT = ['architecture_violation', 'architecture_undocumented', 'code_complexity'];
188
274
  const over = (v, s, cfg) => v !== undefined && v > cfg.thresholds[s];
189
275
  export const localLines = (lang, findings) => findings.map((f) => t(lang, `local_${f.kind}`, { detail: f.detail }));
190
276
  export async function gitCommit(rawDiff, { root, lang, now }) {
@@ -198,7 +284,7 @@ export async function gitCommit(rawDiff, { root, lang, now }) {
198
284
  saveBrain(root, brain);
199
285
  return { code: 1, stderr: localLines(lang, local.filter((f) => f.block)) };
200
286
  }
201
- const review = await reviewDiff(rawDiff, cfg, brain, lang, now);
287
+ const review = await reviewDiff(rawDiff, cfg, brain, lang, now, 'commit', root);
202
288
  if (!review)
203
289
  return { ...out, stderr: localLines(lang, local) };
204
290
  if (review.failed)
package/dist/i18n.js CHANGED
@@ -19,6 +19,7 @@ export const personaDict = {
19
19
  destructive_command: '停手。這個指令有不可逆的破壞性,這次不准執行。',
20
20
  infinite_loop: '同樣的錯誤又來了,你們在鬼打牆燒 Token。這次工具呼叫我擋下了,先去看邏輯。',
21
21
  architecture_violation: '這次變更偏離了 Sprint 目標。我放你過,但這筆帳記著。',
22
+ architecture_undocumented: '這看起來改了架構,卻沒有決策紀錄。放你過,但去寫 docs/cto_jev/decisions/NNNN-<slug>.md。',
22
23
  test_tampering: '程式沒修好,倒先把測試改弱了?Commit 已攔下。去修程式,不是修測試。',
23
24
  done_unverified: '說做完了?證據呢?最後一次改程式之後,我沒看到通過的測試或建置,或是你打勾的計畫項目沒有證據。先跑相關的檢查,看到通過再收工;真的跑不了,就老實告訴使用者哪些還沒驗證。',
24
25
  code_complexity: '複雜度超標,過度工程化。這次不擋,但趕快重構。',
@@ -28,6 +29,7 @@ export const personaDict = {
28
29
  destructive_command: 'Hold it. This command is irreversibly destructive. Not running it.',
29
30
  infinite_loop: 'Same error again. You are looping and burning tokens. This tool call is BLOCKED. Fix the logic first.',
30
31
  architecture_violation: 'This change drifts from the sprint goal. Letting it through, but I noticed.',
32
+ architecture_undocumented: 'This looks like an architecture change with no decision record. Letting it through, but write docs/cto_jev/decisions/NNNN-<slug>.md.',
31
33
  test_tampering: 'Weakening the tests instead of fixing the code? Commit BLOCKED. Fix the code, not the tests.',
32
34
  done_unverified: 'Done, you say? Show me. Nothing passing ran after your last code change, or the plan items you checked off have no evidence. Run the relevant tests or build and see them pass before you stop; if you really cannot, tell the user plainly what is still unverified.',
33
35
  code_complexity: 'Over-engineered. Not blocking this time, but refactor it.',
@@ -57,6 +59,17 @@ const messages = {
57
59
  local_env_file: (v) => `[cto] 你正要把 ${v.detail} 連同值一起 commit。.env 不進 git,放進 .gitignore,要分享用 .env.example。`,
58
60
  local_big_file: (v) => `[cto] ${v.detail} 太大了,確定是要進 git 的東西?不擋,但想清楚。`,
59
61
  local_lock_drift: (v) => `[cto] package.json 改了相依套件,但 ${v.detail} 沒跟著改。先跑一次 install,不然隊友裝的會跟你不一樣。`,
62
+ local_flow_signoff: (v) => `[cto] ${v.detail} 已經有 TASKS.md,但 SPEC.md 還不是 Status: approved。沒簽核就開工?先請使用者簽核 SPEC,不然把 TASKS.md 拿掉。`,
63
+ local_flow_index_stale: (v) => `[cto] TASKS/CONCEPT/SPEC 改了,但 ${v.detail} 沒重新產生。跑 cto index 再 git add;這次不擋。`,
64
+ local_flow_dangling_after: (v) => `[cto] ${v.detail}:這個 after: 指到的任務 ID 不存在。改對 ID,或把那個任務加進 TASKS.md;這次不擋。`,
65
+ local_flow_duplicate_id: (v) => `[cto] ${v.detail}:這個任務 ID 在 TASKS.md 裡出現不只一次,after: 會指錯。改成唯一的 ID;這次不擋。`,
66
+ docs_none: () => 'docs/cto_jev/ 以外沒有過期的規劃文件。',
67
+ docs_group_delete: () => '刪除',
68
+ docs_group_merge: () => '併入某個 feature',
69
+ docs_group_archive: () => '封存到 docs/cto_jev/archive/',
70
+ docs_group_ask: () => '要看一下',
71
+ docs_footer: () => 'cto 只給建議:沒有移動或刪除任何檔案。',
72
+ local_flow_interface: (v) => `[cto] ${v.detail}:SPEC 的 Interface 改了。依賴它的 feature 要重看自己的 task;這次不擋。`,
60
73
  setup_not_git: () => '[cto] 這裡不是 git repository,setup 中止。',
61
74
  setup_bad_json: (v) => `[cto] ${v.path} 不是合法 JSON 或 hooks 格式不符,未修改任何檔案。請先修正該檔。`,
62
75
  setup_hook: (v) => `[cto] ${v.name} 區塊已寫入 ${v.path}`,
@@ -66,6 +79,10 @@ const messages = {
66
79
  setup_sprint: () => '[cto] 提示:在 .cto.json 填入 sprint_goal 以啟用架構對齊檢查。',
67
80
  setup_goal_bad_json: () => '[cto] .cto.json 不是合法 JSON,sprint goal 沒有寫入,檔案保持原樣。請先修正該檔。',
68
81
  setup_done: () => '[cto] 安裝完成。',
82
+ setup_flow_docs: (v) => `[cto] 已建立 docs/cto_jev/ 骨架:${v.list}`,
83
+ setup_flow_bad_json: () => '[cto] .cto.json 不是合法 JSON,開發流程的選擇沒有寫入,檔案保持原樣。請先修正該檔。',
84
+ setup_flow_next: () => '[cto] 下一步:打開你的 agent,跟它說「set up PRODUCT.md and ARCHITECTURE.md」,它會掃 repo 填好再問你剩下的。',
85
+ setup_flow_publish: (v) => `[cto] 偵測到 ${v.file}:docs/cto_jev/ 不要跟著文件網站一起發布(PRODUCT.md 寫著定價和商業規則),請在 ${v.file} 把這個資料夾排除。`,
69
86
  uninstall_hook: (v) => `[cto] 已從 ${v.path} 移除 cto 區塊`,
70
87
  uninstall_gitignore: () => '[cto] 已從 .gitignore 移除 cto 區塊',
71
88
  uninstall_done: () => '[cto] 已解除安裝(.cto.json 保留)。',
@@ -76,8 +93,22 @@ const messages = {
76
93
  wiz_ok: (v) => ` ${v.name} 驗證成功`,
77
94
  wiz_fail: (v) => ` ${v.name} 驗證失敗 (${v.status}) ${v.msg}`,
78
95
  ui_title: () => 'cto 設定',
79
- ui_first_run: () => '共四步:coding agent、Jev provider、API key、sprint goal。↑↓ 移動,Enter 確認,Esc 回上一步。完成後會回到總覽,之後也能單獨修改任何一項。',
80
- ui_agents_q: () => '要攔截哪些 coding agent 的指令?(git commit 檢查一律安裝)\n ↑↓ 移動 · 空白鍵勾選 · Enter 確認 · Esc 返回',
96
+ ui_first_run: () => '共五步:coding agent、Jev provider、API key、sprint goal、開發流程。↑↓ 移動,Enter 確認,Esc 回上一步。完成後會回到總覽,之後也能單獨修改任何一項。',
97
+ ui_agents_q: () => '要攔截哪些 coding agent 的指令?',
98
+ ui_agents_help: () => '↑↓ 移動 · 空白鍵勾選 · Enter 確認 · Esc 返回',
99
+ ui_always: () => '一律安裝',
100
+ ui_always_git: () => 'git 檢查',
101
+ ui_always_cfg: () => '共用設定',
102
+ ui_choose: () => '選擇 agent',
103
+ ui_selected: () => '已選:',
104
+ ui_plan_title: () => '將寫入',
105
+ ui_plan_new: () => '新增',
106
+ ui_plan_update: () => '更新 cto 的部分',
107
+ ui_plan_remove: () => '移除 cto 的部分',
108
+ ui_plan_none: () => '沒有檔案需要改',
109
+ ui_plan_q: () => '確定寫入?(否 = 回到設定總覽)',
110
+ ui_yes: () => '是',
111
+ ui_no: () => '否',
81
112
  ui_detected: () => '已偵測到',
82
113
  ui_providers_q: () => '要用哪些 Jev provider?',
83
114
  ui_providers_help: () => '↑↓ 移動 · 空白鍵勾選 · 按數字鍵把游標所在項目移到該順位 · Enter 確認 · Esc 返回\n│ 數字是優先順序:1 先用,失敗才換下一個',
@@ -99,6 +130,11 @@ const messages = {
99
130
  ui_drop: (v) => `不使用 ${v.name}`,
100
131
  ui_goal_q: () => 'Sprint goal(選填,填了才會檢查 commit 是否偏離目標)',
101
132
  ui_goal_ph: () => '例如:完成 Stripe 金流,不新增服務',
133
+ ui_flow_q: () => '要用 cto 開發流程嗎?你的 agent 當 CTO:在 docs/cto_jev/ 規劃、派工、驗收;cto 檢查簽核和漂移。',
134
+ ui_flow_yes: () => '要,寫入 cto-flow skill 和 docs/cto_jev/ 骨架',
135
+ ui_flow_no: () => '不用,只守關卡',
136
+ ui_on: () => '啟用',
137
+ ui_off: () => '未啟用',
102
138
  ui_lang_q: () => 'cto 的訊息語言',
103
139
  ui_lang_auto: () => '自動(跟系統語言)',
104
140
  ui_menu_q: () => '設定總覽:選一項修改,或儲存(↑↓ 移動 · Enter 選擇 · Esc 不儲存離開)',
@@ -106,6 +142,7 @@ const messages = {
106
142
  ui_m_providers: () => 'Jev providers 與順序',
107
143
  ui_m_keys: () => '更換 API key',
108
144
  ui_m_goal: () => 'Sprint goal',
145
+ ui_m_flow: () => '開發流程',
109
146
  ui_m_lang: () => '語言',
110
147
  ui_m_save: () => '儲存並完成',
111
148
  ui_m_quit: () => '不儲存離開',
@@ -118,7 +155,9 @@ const messages = {
118
155
  check_head_base: (v) => `[cto] 檢查這個分支相對於 ${v.base} 的改動(${v.files} 個檔案):`,
119
156
  check_unchecked: () => '[cto] 無法檢查:沒有可用的 Jev provider。執行 cto doctor 看原因。',
120
157
  check_why_tests: () => '未檢查:沒有改到測試相關檔案',
121
- check_why_goal: () => '未檢查:.cto.json 沒有設定 sprint_goal',
158
+ check_why_goal: () => '未檢查:.cto.json 沒有 sprint_goal,這些檔案也沒對到任何 feature 的 Constraints',
159
+ check_why_adr: () => '未檢查:沒有 docs/cto_jev/ 流程、沒改到程式碼,或這次 commit 已新增決策紀錄',
160
+ check_why_release: () => '未檢查:整條分支不算複雜度,每次 commit 時已經看過',
122
161
  check_why_failed: () => '未檢查:請求失敗',
123
162
  check_limit_block: (v) => `超過 ${v.limit} 會擋下`,
124
163
  check_limit_warn: (v) => `超過 ${v.limit} 會警告`,
@@ -162,6 +201,7 @@ const messages = {
162
201
  doc_none: () => '無',
163
202
  doc_goal_set: () => 'sprint_goal 已設定,架構對齊檢查啟用中',
164
203
  doc_goal_empty: () => 'sprint_goal 未設定,架構對齊檢查關閉(可在 .cto.json 填入)',
204
+ doc_flow_issues: (v) => `開發流程文件有 ${v.n} 處不一致(例如:${v.first})。跑 cto brief 看完整清單。`,
165
205
  log_empty: () => '[cto] 這個 repo 還沒有 Jev 回答過的檢查。',
166
206
  log_head: () => '[cto] 最近的判斷(最舊在上):',
167
207
  log_crossed: () => '超過門檻',
@@ -182,7 +222,7 @@ const messages = {
182
222
  doc_bad: () => '[cto] 有問題需要處理:',
183
223
  update_available: (v) => `[cto] 有新版 ${v.latest}(目前 ${v.current}),執行 cto update 更新`,
184
224
  update_done: () => '[cto] 已更新。已設定過的專案不用重跑 cto setup。',
185
- usage: () => '用法:cto brief | cto check [--base origin/main] | cto log | cto report [n] | cto doctor | cto update | cto --version | cto setup [--refresh] [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
225
+ usage: () => '用法:cto brief | cto check [--base origin/main] | cto log | cto report [n] | cto doctor | cto index | cto docs | cto update | cto --version | cto setup [--refresh] [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
186
226
  },
187
227
  en: {
188
228
  reason_402: () => 'out of credits',
@@ -207,6 +247,17 @@ const messages = {
207
247
  local_env_file: (v) => `[cto] You are about to commit ${v.detail} with real values. .env files stay out of git: add it to .gitignore and share a .env.example.`,
208
248
  local_big_file: (v) => `[cto] ${v.detail} is huge. Sure that belongs in git? Not blocking, but think.`,
209
249
  local_lock_drift: (v) => `[cto] package.json changed dependencies but ${v.detail} did not. Run install first, or your teammates get a different tree.`,
250
+ local_flow_signoff: (v) => `[cto] ${v.detail} has a TASKS.md but its SPEC.md is not Status: approved. No sign-off, no work: get the user to approve the SPEC, or remove TASKS.md.`,
251
+ local_flow_index_stale: (v) => `[cto] TASKS/CONCEPT/SPEC changed but ${v.detail} was not regenerated. Run cto index and git add it; not blocking.`,
252
+ local_flow_dangling_after: (v) => `[cto] ${v.detail}: that after: id does not exist. Fix the id or add the task to TASKS.md; not blocking.`,
253
+ local_flow_duplicate_id: (v) => `[cto] ${v.detail}: this task id appears more than once in TASKS.md, so after: may point at the wrong one. Make it unique; not blocking.`,
254
+ docs_none: () => 'No stale planning documents outside docs/cto_jev/.',
255
+ docs_group_delete: () => 'Delete',
256
+ docs_group_merge: () => 'Merge into a feature',
257
+ docs_group_archive: () => 'Archive to docs/cto_jev/archive/',
258
+ docs_group_ask: () => 'Needs a look',
259
+ docs_footer: () => 'cto only suggests: nothing was moved or deleted.',
260
+ local_flow_interface: (v) => `[cto] ${v.detail}: the SPEC's Interface changed. Dependent features must re-check their tasks; not blocking.`,
210
261
  setup_not_git: () => '[cto] Not a git repository, setup aborted.',
211
262
  setup_bad_json: (v) => `[cto] ${v.path} is not valid JSON or has an unexpected hooks shape. Nothing was changed. Fix it first.`,
212
263
  setup_hook: (v) => `[cto] ${v.name} block written to ${v.path}`,
@@ -216,6 +267,10 @@ const messages = {
216
267
  setup_sprint: () => '[cto] Tip: set sprint_goal in .cto.json to enable the architecture alignment check.',
217
268
  setup_goal_bad_json: () => '[cto] .cto.json is not valid JSON, so the sprint goal was not saved and the file was left untouched. Fix it first.',
218
269
  setup_done: () => '[cto] Setup complete.',
270
+ setup_flow_docs: (v) => `[cto] Created the docs/cto_jev/ skeleton: ${v.list}`,
271
+ setup_flow_bad_json: () => '[cto] .cto.json is not valid JSON, so the development flow choice was not saved and the file was left untouched. Fix it first.',
272
+ setup_flow_next: () => '[cto] Next: open your agent and say "set up PRODUCT.md and ARCHITECTURE.md". It scans the repo, fills what it can, and asks you the rest.',
273
+ setup_flow_publish: (v) => `[cto] ${v.file} found: keep docs/cto_jev/ out of the published site (PRODUCT.md holds pricing and business rules); exclude the folder in ${v.file}.`,
219
274
  uninstall_hook: (v) => `[cto] Removed the cto block from ${v.path}`,
220
275
  uninstall_gitignore: () => '[cto] Removed the cto block from .gitignore',
221
276
  uninstall_done: () => '[cto] Uninstalled (.cto.json kept).',
@@ -226,8 +281,22 @@ const messages = {
226
281
  wiz_ok: (v) => ` ${v.name} OK`,
227
282
  wiz_fail: (v) => ` ${v.name} failed (${v.status}) ${v.msg}`,
228
283
  ui_title: () => 'cto setup',
229
- ui_first_run: () => 'Four steps: coding agents, Jev providers, API keys, sprint goal. Up/Down to move, Enter to confirm, Esc to go back. You land on an overview at the end and can change any single item later.',
230
- ui_agents_q: () => 'Which coding agents should have their commands checked? (the git commit check is always installed)\n Up/Down move · Space toggles · Enter confirms · Esc goes back',
284
+ ui_first_run: () => 'Five steps: coding agents, Jev providers, API keys, sprint goal, development flow. Up/Down to move, Enter to confirm, Esc to go back. You land on an overview at the end and can change any single item later.',
285
+ ui_agents_q: () => 'Which coding agents should have their commands checked?',
286
+ ui_agents_help: () => 'Up/Down move · Space toggles · Enter confirms · Esc goes back',
287
+ ui_always: () => 'always installed',
288
+ ui_always_git: () => 'git checks',
289
+ ui_always_cfg: () => 'shared config',
290
+ ui_choose: () => 'pick agents',
291
+ ui_selected: () => 'Selected:',
292
+ ui_plan_title: () => 'Will write',
293
+ ui_plan_new: () => 'new',
294
+ ui_plan_update: () => "update cto's part",
295
+ ui_plan_remove: () => "remove cto's part",
296
+ ui_plan_none: () => 'Nothing to change',
297
+ ui_plan_q: () => 'Write these files? (No goes back to the overview)',
298
+ ui_yes: () => 'Yes',
299
+ ui_no: () => 'No',
231
300
  ui_detected: () => 'detected',
232
301
  ui_providers_q: () => 'Which Jev providers should cto use?',
233
302
  ui_providers_help: () => 'Up/Down move · Space toggles · press a number to move the item under the cursor to that position · Enter confirms · Esc goes back\n│ Numbers are priority: 1 first, the next one only on failure',
@@ -249,6 +318,11 @@ const messages = {
249
318
  ui_drop: (v) => `Do not use ${v.name}`,
250
319
  ui_goal_q: () => 'Sprint goal (optional; enables the check for commits that drift from it)',
251
320
  ui_goal_ph: () => 'e.g. Ship Stripe billing, no new services',
321
+ ui_flow_q: () => 'Use the cto development flow? Your agent acts as CTO: plans in docs/cto_jev/, dispatches, accepts; cto checks sign-off and drift.',
322
+ ui_flow_yes: () => 'Yes, write the cto-flow skill and a docs/cto_jev/ skeleton',
323
+ ui_flow_no: () => 'No, gatekeeping only',
324
+ ui_on: () => 'on',
325
+ ui_off: () => 'off',
252
326
  ui_lang_q: () => 'Language for cto messages',
253
327
  ui_lang_auto: () => 'Automatic (system language)',
254
328
  ui_menu_q: () => 'Overview: pick an item to change, or save (Up/Down move · Enter selects · Esc quits without saving)',
@@ -256,6 +330,7 @@ const messages = {
256
330
  ui_m_providers: () => 'Jev providers and order',
257
331
  ui_m_keys: () => 'Change API keys',
258
332
  ui_m_goal: () => 'Sprint goal',
333
+ ui_m_flow: () => 'Development flow',
259
334
  ui_m_lang: () => 'Language',
260
335
  ui_m_save: () => 'Save and finish',
261
336
  ui_m_quit: () => 'Quit without saving',
@@ -268,7 +343,9 @@ const messages = {
268
343
  check_head_base: (v) => `[cto] Checking what this branch adds on top of ${v.base} (${v.files} files):`,
269
344
  check_unchecked: () => '[cto] Could not check: no working Jev provider. Run cto doctor to see why.',
270
345
  check_why_tests: () => 'not checked: no test files changed',
271
- check_why_goal: () => 'not checked: sprint_goal is empty in .cto.json',
346
+ check_why_goal: () => 'not checked: no sprint_goal in .cto.json and no feature Constraints for these files',
347
+ check_why_adr: () => 'not checked: no docs/cto_jev/ flow, no code changed, or this commit adds a decision record',
348
+ check_why_release: () => 'not checked: a whole branch is not scored for complexity; each commit was',
272
349
  check_why_failed: () => 'not checked: request failed',
273
350
  check_limit_block: (v) => `blocks above ${v.limit}`,
274
351
  check_limit_warn: (v) => `warns above ${v.limit}`,
@@ -312,6 +389,7 @@ const messages = {
312
389
  doc_none: () => 'none',
313
390
  doc_goal_set: () => 'sprint_goal set, architecture check on',
314
391
  doc_goal_empty: () => 'sprint_goal empty, architecture check off (set it in .cto.json)',
392
+ doc_flow_issues: (v) => `Flow docs have ${v.n} inconsistencies (e.g. ${v.first}). Run cto brief for the full list.`,
315
393
  log_empty: () => '[cto] No check answered by Jev in this repo yet.',
316
394
  log_head: () => '[cto] Recent decisions (oldest first):',
317
395
  log_crossed: () => 'CROSSED',
@@ -332,7 +410,7 @@ const messages = {
332
410
  doc_bad: () => '[cto] Needs attention:',
333
411
  update_available: (v) => `[cto] Version ${v.latest} is available (you have ${v.current}). Run cto update`,
334
412
  update_done: () => '[cto] Updated. Projects already set up do not need cto setup again.',
335
- usage: () => 'Usage: cto brief | cto check [--base origin/main] | cto log | cto report [n] | cto doctor | cto update | cto --version | cto setup [--refresh] [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
413
+ usage: () => 'Usage: cto brief | cto check [--base origin/main] | cto log | cto report [n] | cto doctor | cto index | cto docs | cto update | cto --version | cto setup [--refresh] [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
336
414
  },
337
415
  };
338
416
  export function t(lang, key, vars = {}) {
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ import { checkUpdate, currentVersion, runUpdate } from './update.js';
10
10
  import { doctor } from './doctor.js';
11
11
  import { detectLang, t } from './i18n.js';
12
12
  import { maskDiff, maskSensitiveState } from './masker.js';
13
- import { detectAgents, gitRoot, setSprintGoal, setup, wiredAgents } from './setup.js';
13
+ import { detectAgents, gitRoot, planSetup, setSprintGoal, setup, wiredAgents } from './setup.js';
14
14
  async function readStdin() {
15
15
  if (process.stdin.isTTY)
16
16
  return '';
@@ -108,6 +108,7 @@ else if (args[0] === 'setup') {
108
108
  const uninstall = args.includes('--uninstall');
109
109
  let chosen;
110
110
  let goal;
111
+ let flow = args.includes('--flow') ? true : args.includes('--no-flow') ? false : undefined;
111
112
  const root = gitRoot(process.cwd());
112
113
  const list = flag('--agents');
113
114
  if (args.includes('--refresh')) {
@@ -131,21 +132,23 @@ else if (args[0] === 'setup') {
131
132
  keys: fileKeys,
132
133
  lang: prefs.lang,
133
134
  goal: loadConfig(root).sprint_goal,
135
+ flow: loadConfig(root).flow,
134
136
  };
135
137
  const firstRun = !wired.length && !providerOrder().length;
136
138
  const { setupUI } = await import('./setupui.js'); // clack loads only for interactive setup, never on the hook path
137
- const s = await setupUI(initial, firstRun, lang, { detected: detectAgents() });
139
+ const s = await setupUI(initial, firstRun, lang, { detected: detectAgents(), plan: (st) => planSetup(root, st.agents, st.flow ?? false, st.goal) });
138
140
  if (!s)
139
141
  process.exit(0); // quit without saving: nothing was written
140
142
  saveCredentials(s.keys);
141
143
  savePrefs({ provider_order: s.providers, ...(s.lang && { lang: s.lang }) });
142
144
  chosen = s.agents;
143
145
  goal = s.goal;
146
+ flow = s.flow ?? false;
144
147
  }
145
148
  else if (!uninstall) {
146
149
  chosen = detectAgents();
147
150
  }
148
- const r = setup(process.cwd(), lang, { uninstall, agents: chosen, exact: goal !== undefined });
151
+ const r = setup(process.cwd(), lang, { uninstall, agents: chosen, exact: goal !== undefined, flow });
149
152
  if (!r.code && root && goal !== undefined && goal !== loadConfig(root).sprint_goal && !setSprintGoal(root, goal)) {
150
153
  r.lines.push(t(lang, 'setup_goal_bad_json'));
151
154
  }
@@ -204,6 +207,25 @@ else if (args[0] === 'brief') {
204
207
  console.log(brief(root).join('\n'));
205
208
  }
206
209
  }
210
+ else if (args[0] === 'index' || args[0] === 'docs') {
211
+ const root = gitRoot(process.cwd());
212
+ if (!root) {
213
+ process.stderr.write(t(lang, 'setup_not_git') + '\n');
214
+ process.exitCode = 1;
215
+ }
216
+ else if (args[0] === 'index') {
217
+ const { writeIndex } = await import('./flow.js');
218
+ const r = writeIndex(root);
219
+ console.log(r.changed ? `[cto] ${r.path} updated` : `[cto] ${r.path} is up to date`);
220
+ }
221
+ else {
222
+ const { docsReport } = await import('./docs.js');
223
+ const { loadBrain, saveBrain } = await import('./brain.js');
224
+ const brain = loadBrain(root);
225
+ console.log((await docsReport(root, { brain, lang, timeoutMs: 5000, notices: new Set() })).join('\n'));
226
+ saveBrain(root, brain); // provider cooldowns, as the hook paths do
227
+ }
228
+ }
207
229
  else if (args[0] === 'doctor') {
208
230
  const r = await doctor(process.cwd(), lang);
209
231
  console.log(r.lines.join('\n'));