@leocm/flowcraft 2.1.0 → 2.3.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.
Files changed (96) hide show
  1. package/README.md +19 -2
  2. package/bin/cli.js +108 -108
  3. package/flowcraft.yaml +30 -30
  4. package/install.sh +24 -24
  5. package/lib/args.js +38 -38
  6. package/lib/config.js +20 -20
  7. package/lib/copy.js +131 -131
  8. package/lib/fix.js +110 -110
  9. package/lib/fsutil.js +104 -104
  10. package/lib/global.js +229 -229
  11. package/lib/init.js +43 -43
  12. package/lib/runtime.js +84 -84
  13. package/lib/version.js +55 -55
  14. package/lib/wizard.js +125 -125
  15. package/package.json +33 -33
  16. package/presets/backend.yaml +20 -20
  17. package/presets/default.yaml +15 -15
  18. package/presets/frontend.yaml +20 -20
  19. package/presets/quick-fix.yaml +15 -15
  20. package/setup/.claude/hooks/check-phase-test.py +152 -152
  21. package/setup/.claude/hooks/check-phase-write.py +235 -235
  22. package/setup/.claude/hooks/dispatch.py +67 -67
  23. package/setup/.claude/hooks/file-suggestion.py +45 -45
  24. package/setup/.claude/hooks/flowcraft_env.py +162 -137
  25. package/setup/.claude/hooks/permission-request.py +132 -125
  26. package/setup/.claude/hooks/post-tool-failure.py +36 -36
  27. package/setup/.claude/hooks/pre-compact.py +66 -66
  28. package/setup/.claude/hooks/review-runner.py +846 -846
  29. package/setup/.claude/hooks/setup-keys.py +282 -282
  30. package/setup/.claude/hooks/statusline.py +63 -63
  31. package/setup/.claude/hooks/stop-check.py +186 -171
  32. package/setup/.claude/hooks/subagent-start.py +50 -50
  33. package/setup/.claude/hooks/subagent-stop.py +63 -63
  34. package/setup/.claude/hooks/task-completed.py +57 -57
  35. package/setup/.claude/hooks/task_manager.py +592 -592
  36. package/setup/.claude/hooks/user-prompt-submit.py +91 -85
  37. package/setup/.claude/settings.json +233 -237
  38. package/setup/.claude/skills/Pstatus/SKILL.md +68 -68
  39. package/setup/.claude/skills/archive/SKILL.md +195 -195
  40. package/setup/.claude/skills/brainstorming/SKILL.md +5 -5
  41. package/setup/.claude/skills/brainstorming/scripts/server.cjs +723 -723
  42. package/setup/.claude/skills/brainstorming/scripts/start-server.py +245 -245
  43. package/setup/.claude/skills/brainstorming/scripts/stop-server.py +178 -178
  44. package/setup/.claude/skills/brainstorming/visual-companion.md +298 -298
  45. package/setup/.claude/skills/chrome-integration/SKILL.md +66 -66
  46. package/setup/.claude/skills/code-review/SKILL.md +264 -264
  47. package/setup/.claude/skills/executing-plans/SKILL.md +1 -1
  48. package/setup/.claude/skills/gitnexus/gitnexus-cli/SKILL.md +67 -67
  49. package/setup/.claude/skills/gitnexus/gitnexus-debugging/SKILL.md +1 -1
  50. package/setup/.claude/skills/gitnexus/gitnexus-exploring/SKILL.md +1 -1
  51. package/setup/.claude/skills/gitnexus/gitnexus-guide/SKILL.md +1 -1
  52. package/setup/.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md +1 -1
  53. package/setup/.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md +1 -1
  54. package/setup/.claude/skills/methodology/SKILL.md +124 -0
  55. package/setup/.claude/skills/phase/SKILL.md +62 -62
  56. package/setup/.claude/skills/playwright/SKILL.md +85 -85
  57. package/setup/.claude/skills/review/SKILL.md +97 -97
  58. package/setup/.claude/skills/task/SKILL.md +26 -26
  59. package/setup/.claude/skills/test-driven-development/SKILL.md +1 -1
  60. package/setup/.claude/skills/ui-ux-pro-max/SKILL.md +1 -1
  61. package/setup/.claude/skills/verification-before-completion/SKILL.md +1 -1
  62. package/setup/.claude/skills/writing-plans/SKILL.md +1 -1
  63. package/setup/.codex/.agents/skills/archive/SKILL.md +195 -195
  64. package/setup/.codex/.agents/skills/brainstorming/SKILL.md +5 -5
  65. package/setup/.codex/.agents/skills/brainstorming/scripts/server.cjs +723 -723
  66. package/setup/.codex/.agents/skills/brainstorming/scripts/start-server.py +245 -245
  67. package/setup/.codex/.agents/skills/brainstorming/scripts/stop-server.py +178 -178
  68. package/setup/.codex/.agents/skills/brainstorming/visual-companion.md +298 -298
  69. package/setup/.codex/.agents/skills/chrome-integration/SKILL.md +66 -66
  70. package/setup/.codex/.agents/skills/code-review/SKILL.md +264 -264
  71. package/setup/.codex/.agents/skills/executing-plans/SKILL.md +1 -1
  72. package/setup/.codex/.agents/skills/gitnexus/gitnexus-cli/SKILL.md +67 -67
  73. package/setup/.codex/.agents/skills/gitnexus/gitnexus-debugging/SKILL.md +1 -1
  74. package/setup/.codex/.agents/skills/gitnexus/gitnexus-exploring/SKILL.md +1 -1
  75. package/setup/.codex/.agents/skills/gitnexus/gitnexus-guide/SKILL.md +1 -1
  76. package/setup/.codex/.agents/skills/gitnexus/gitnexus-impact-analysis/SKILL.md +1 -1
  77. package/setup/.codex/.agents/skills/gitnexus/gitnexus-refactoring/SKILL.md +1 -1
  78. package/setup/.codex/.agents/skills/methodology/SKILL.md +124 -0
  79. package/setup/.codex/.agents/skills/phase/SKILL.md +62 -62
  80. package/setup/.codex/.agents/skills/playwright/SKILL.md +85 -85
  81. package/setup/.codex/.agents/skills/review/SKILL.md +97 -97
  82. package/setup/.codex/.agents/skills/task/SKILL.md +27 -27
  83. package/setup/.codex/.agents/skills/test-driven-development/SKILL.md +1 -1
  84. package/setup/.codex/.agents/skills/ui-ux-pro-max/SKILL.md +1 -1
  85. package/setup/.codex/.agents/skills/verification-before-completion/SKILL.md +1 -1
  86. package/setup/.codex/.agents/skills/writing-plans/SKILL.md +1 -1
  87. package/setup/.codex/hooks/review-runner.py +851 -851
  88. package/setup/.codex/hooks/setup-keys.py +287 -287
  89. package/setup/AGENTS.md +11 -1
  90. package/setup/CLAUDE.md +11 -1
  91. package/setup/install.sh +24 -24
  92. package/setup/tests/test_decision_timeout.py +241 -241
  93. package/setup/tests/test_hook_guards.py +357 -357
  94. package/setup/tests/test_sdlc_bootstrap.py +167 -167
  95. package/setup/tests/test_sessionlog_switch.py +199 -0
  96. package/setup/tests/test_task_manager.py +148 -148
@@ -1,851 +1,851 @@
1
- #!/usr/bin/env python3
2
- """SDLC cross-model review runner (cross-platform: Windows / macOS / Linux).
3
-
4
- Rules:
5
- - Runs CURRENT model + USER-SELECTED model in PARALLEL, then merges into one
6
- report. Same model -> runs once. Different -> both run concurrently.
7
- - Codex side -> codex CLI (temp CODEX_HOME + env_key). Claude side -> claude
8
- CLI (temp settings). Never cross-use: each side uses its own CLI.
9
- - Model source of truth: per-directory api-keys.json (Codex:
10
- ~/.codex/api-keys.json; Claude: ~/.claude/api-keys.json).
11
- model-catalog.json = alternatives (-List). Missing key -> -SetKey.
12
- - Choosing an unconfigured model: confirm base_url / context / key / model
13
- with the user first.
14
-
15
- Usage:
16
- python .codex/hooks/review-runner.py -Task "task" [-Provider <id>] [-Model "model"] \
17
- [-Cli codex|claude] [-KeyFile <api-keys.json>] [-SetKey <provider>:<key>] \
18
- [-List] [-BaseUrl <url>] [-WireApi responses|chat] [-Output <path>] \
19
- [-Timeout <seconds>] (default 300; per-reviewer subprocess cap)
20
- """
21
- import concurrent.futures
22
- import json
23
- import os
24
- import re
25
- import shutil
26
- import subprocess
27
- import sys
28
- import tempfile
29
- import time
30
- import urllib.request
31
- from datetime import datetime
32
- from pathlib import Path
33
-
34
- # R2 UTF-8 stdio 双保险(消除 Windows GBK 乱码)
35
- for _s in (sys.stdout, sys.stderr):
36
- try:
37
- _s.reconfigure(encoding="utf-8", errors="replace")
38
- except Exception:
39
- pass
40
-
41
-
42
- def parse_args(argv):
43
- args = {
44
- "task": "current-task",
45
- "output": "",
46
- "provider": "",
47
- "model": "",
48
- "cli": "",
49
- "keyfile": "",
50
- "setkey": "",
51
- "baseurl": "",
52
- "wireapi": "",
53
- "timeout": 300, # seconds per reviewer
54
- "mode": "api", # api = direct dual-model API (fast); cli = codex/claude exec
55
- "base": "", # branch base ref for "since checkout" scope
56
- "scope": "", # branch | uncommitted | last | custom (default branch)
57
- "list": False,
58
- }
59
- i = 0
60
- while i < len(argv):
61
- a = argv[i]
62
- if a in ("-Task", "-Provider", "-Model", "-Cli", "-KeyFile", "-SetKey",
63
- "-BaseUrl", "-WireApi", "-Output", "-Timeout", "-Mode", "-Base", "-Scope") and i + 1 < len(argv):
64
- key = a[1:].lower()
65
- args[key] = argv[i + 1]
66
- i += 2
67
- elif a == "-List":
68
- args["list"] = True
69
- i += 1
70
- else:
71
- i += 1
72
- return args
73
-
74
-
75
- def repo_root(script_dir: Path) -> Path:
76
- if script_dir.name == "hooks":
77
- return script_dir.parent.parent
78
- return script_dir.parent
79
-
80
-
81
- def load_catalog(catalog: Path) -> dict:
82
- prov = {}
83
- if catalog.is_file():
84
- try:
85
- for p in json.load(open(catalog, encoding="utf-8")).get("providers", []):
86
- prov[p["id"]] = {
87
- "name": p.get("name", p["id"]),
88
- "base_url": p.get("base_url", ""),
89
- "key_env": p.get("key_env", p["id"].upper() + "_API_KEY"),
90
- "model": p.get("default_model", ""),
91
- "context": p.get("default_context", ""),
92
- "models": p.get("models", []),
93
- "key": "",
94
- "openai_base_url": p.get("openai_base_url", ""),
95
- "openai_wire": p.get("openai_wire", ""),
96
- }
97
- except Exception:
98
- pass
99
- return prov
100
-
101
-
102
- def providers_tsv(keyfile: Path, catalog: Path) -> list:
103
- """Return provider dicts (id, name, base_url, model, context, has_key,
104
- oai_base, oai_wire, models)."""
105
- prov = load_catalog(catalog)
106
- if keyfile.is_file():
107
- try:
108
- data = json.load(open(keyfile, encoding="utf-8"))
109
- for pid, e in data.items():
110
- if pid not in prov:
111
- prov[pid] = {
112
- "name": e.get("name", pid),
113
- "base_url": e.get("base_url", ""),
114
- "key_env": pid.upper() + "_API_KEY",
115
- "model": e.get("model", ""),
116
- "context": e.get("context", ""),
117
- "models": [],
118
- "key": "",
119
- "openai_base_url": "",
120
- "openai_wire": "",
121
- }
122
- for fld in ("name", "base_url", "model", "context", "key",
123
- "openai_base_url", "openai_wire"):
124
- if fld in e:
125
- prov[pid][fld] = e[fld]
126
- except Exception:
127
- pass
128
- rows = []
129
- for pid, p in sorted(prov.items()):
130
- models = ",".join(
131
- str(m.get("name", "")) + "(" + str(m.get("context", "")) + ")"
132
- for m in p.get("models", [])
133
- )
134
- rows.append({
135
- "id": pid,
136
- "name": p.get("name", ""),
137
- "base_url": p.get("base_url", ""),
138
- "model": p.get("model", ""),
139
- "context": p.get("context", ""),
140
- "has_key": "1" if p.get("key") else "0",
141
- "oai_base": p.get("openai_base_url", ""),
142
- "oai_wire": p.get("openai_wire", ""),
143
- "models": models,
144
- })
145
- return rows
146
-
147
-
148
- def current_line(cfg: Path) -> str:
149
- if not cfg.is_file():
150
- return "model=(unknown) provider=(unknown)"
151
- try:
152
- t = cfg.read_text(encoding="utf-8")
153
- except Exception:
154
- return "model=(unknown) provider=(unknown)"
155
- m = re.search(r'^\s*model\s*=\s*"([^"]+)"', t, re.M)
156
- model = m.group(1) if m else "unknown"
157
- mp = re.search(r'^\s*model_provider\s*=\s*"([^"]+)"', t, re.M)
158
- provider = mp.group(1) if mp else "unknown"
159
- return f"model={model} provider={provider}"
160
-
161
-
162
- def current_provider(keyfile: Path, catalog: Path, cfg: Path) -> str:
163
- prov = {}
164
- if catalog.is_file():
165
- try:
166
- for p in json.load(open(catalog, encoding="utf-8")).get("providers", []):
167
- prov[p["id"]] = {"base_url": p.get("base_url", ""), "key": ""}
168
- except Exception:
169
- pass
170
- if keyfile.is_file():
171
- try:
172
- data = json.load(open(keyfile, encoding="utf-8"))
173
- for pid, e in data.items():
174
- if pid not in prov:
175
- prov[pid] = {"base_url": e.get("base_url", ""), "key": ""}
176
- prov[pid]["key"] = e.get("key", "")
177
- except Exception:
178
- pass
179
- mp, mp_base = "", ""
180
- if cfg.is_file():
181
- try:
182
- t = cfg.read_text(encoding="utf-8")
183
- mm = re.search(r'^\s*model_provider\s*=\s*"([^"]+)"', t, re.M)
184
- if mm:
185
- mp = mm.group(1)
186
- mb = re.search(r'^\s*base_url\s*=\s*"([^"]+)"', t, re.M)
187
- if mb:
188
- mp_base = mb.group(1).rstrip("/")
189
- except Exception:
190
- pass
191
- strip = lambda u: re.sub(r"/anthropic/?$", "", u.rstrip("/"))
192
- if mp and mp in prov:
193
- return mp
194
- if mp_base:
195
- for pid, p in prov.items():
196
- if strip(p["base_url"]) == strip(mp_base):
197
- return pid
198
- for pid, p in sorted(prov.items()):
199
- if p.get("key"):
200
- return pid
201
- return mp or ""
202
-
203
-
204
- def set_key(keyfile: Path, setkey: str, catalog: Path) -> int:
205
- if ":" not in setkey:
206
- print("SetKey format: <provider>:<key>", file=sys.stderr)
207
- return 1
208
- pid, pkey = setkey.split(":", 1)
209
- prov = {}
210
- if catalog.is_file():
211
- try:
212
- for p in json.load(open(catalog, encoding="utf-8")).get("providers", []):
213
- prov[p["id"]] = {
214
- "name": p.get("name", p["id"]),
215
- "base_url": p.get("base_url", ""),
216
- "model": p.get("default_model", ""),
217
- "context": p.get("default_context", ""),
218
- }
219
- except Exception:
220
- pass
221
- data = {}
222
- if keyfile.is_file():
223
- try:
224
- data = json.load(open(keyfile, encoding="utf-8"))
225
- except Exception:
226
- pass
227
- if pid not in prov:
228
- print(f"unknown provider: {pid}", file=sys.stderr)
229
- return 1
230
- entry = data.get(pid, {})
231
- entry.setdefault("name", prov[pid]["name"])
232
- entry.setdefault("base_url", prov[pid]["base_url"])
233
- entry.setdefault("model", prov[pid]["model"])
234
- entry.setdefault("context", prov[pid]["context"])
235
- entry["key"] = pkey
236
- data[pid] = entry
237
- keyfile.parent.mkdir(parents=True, exist_ok=True)
238
- json.dump(data, open(keyfile, "w", encoding="utf-8"), ensure_ascii=False, indent=4)
239
- print(f"key written back -> {keyfile} [provider={pid}]")
240
- return 0
241
-
242
-
243
- _CLI_PROBE_TIMEOUT = 10 # seconds allowed for the --version probe
244
-
245
-
246
- def _cli_runnable(exe: str) -> bool:
247
- """Verify a codex CLI candidate actually runs.
248
-
249
- Probes ``<exe> --version`` and requires a zero exit code plus codex-ish
250
- stdout, so non-runnable candidates (e.g. the Windows Store/MSIX app alias
251
- that raises PermissionError on direct launch, or a broken alias that exits
252
- 0 without output) are skipped. ``CREATE_NO_WINDOW`` prevents a console
253
- flash on Windows.
254
- """
255
- try:
256
- r = subprocess.run(
257
- [exe, "--version"],
258
- capture_output=True,
259
- timeout=_CLI_PROBE_TIMEOUT,
260
- creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
261
- )
262
- if r.returncode != 0:
263
- return False
264
- out = (r.stdout or b"") + (r.stderr or b"")
265
- return b"codex" in out.lower()
266
- except Exception:
267
- return False
268
-
269
-
270
- def find_codex_cli() -> str:
271
- cand = os.environ.get("CODEX_CLI_PATH") or ""
272
- if cand and os.path.isfile(cand) and _cli_runnable(cand):
273
- return cand
274
- for name in ("codex", "codex.exe"):
275
- p = shutil.which(name)
276
- if p and os.path.isfile(p) and _cli_runnable(p):
277
- return p
278
- for env in ("LOCALAPPDATA", "APPDATA"):
279
- base = os.environ.get(env)
280
- if not base:
281
- continue
282
- for p in sorted(Path(base, "OpenAI", "Codex", "bin").glob("*/codex.exe")):
283
- if _cli_runnable(str(p)):
284
- return str(p)
285
- return ""
286
-
287
-
288
- def find_claude_cli() -> str:
289
- for name in ("claude", "claude.cmd"):
290
- p = shutil.which(name)
291
- if p:
292
- return p
293
- return ""
294
-
295
-
296
- def key_of(keyfile: Path, pid: str) -> str:
297
- try:
298
- data = json.load(open(keyfile, encoding="utf-8"))
299
- return data.get(pid, {}).get("key", "")
300
- except Exception:
301
- return ""
302
-
303
-
304
-
305
-
306
- def _git_rc(repo: Path, args):
307
- """Run git, return (returncode, stdout-utf8)."""
308
- try:
309
- r = subprocess.run(["git"] + args, cwd=str(repo), capture_output=True, timeout=15)
310
- return r.returncode, r.stdout.decode("utf-8", errors="replace")
311
- except Exception:
312
- return -1, ""
313
-
314
-
315
- def resolve_branch_base(repo: Path) -> str:
316
- """Find the branch point of the current branch.
317
-
318
- Picks the closest local branch whose tip is an ancestor of HEAD (i.e. the
319
- branch this one was checked out from); falls back to origin/main, main,
320
- or HEAD~1.
321
- """
322
- rc, cur = _git_rc(repo, ["rev-parse", "--abbrev-ref", "HEAD"])
323
- cur = cur.strip()
324
- rc, refs = _git_rc(repo, ["for-each-ref", "--format=%(refname:short)", "refs/heads"])
325
- best, best_n = "", None
326
- for br in refs.splitlines():
327
- br = br.strip()
328
- if not br or br == cur:
329
- continue
330
- rc, _ = _git_rc(repo, ["merge-base", "--is-ancestor", br, "HEAD"])
331
- if rc != 0:
332
- continue
333
- rc, out = _git_rc(repo, ["rev-list", "--count", br + "..HEAD"])
334
- if rc != 0:
335
- continue
336
- try:
337
- n = int(out.strip() or "0")
338
- except ValueError:
339
- continue
340
- if best_n is None or n < best_n:
341
- best, best_n = br, n
342
- if best:
343
- return best
344
- for cand in ("origin/main", "origin/master", "main", "master", "HEAD~1"):
345
- rc, _ = _git_rc(repo, ["rev-parse", "--verify", "--quiet", cand + "^{commit}"])
346
- if rc == 0:
347
- return cand
348
- return "HEAD~1"
349
-
350
-
351
-
352
- def review_diff(repo: Path, scope: str = "branch", base: str = ""):
353
- """Return (diff_stat, changed_names) for the selected scope.
354
-
355
- scope: branch (default) = uncommitted + all commits since the branch was
356
- checked out; uncommitted = git diff HEAD; last = git diff HEAD~1;
357
- custom = git diff <base>.
358
- """
359
- def _git(args):
360
- try:
361
- r = subprocess.run(["git"] + args, cwd=str(repo), capture_output=True, timeout=15)
362
- return r.stdout.decode("utf-8", errors="replace") if r.returncode == 0 else ""
363
- except Exception:
364
- return ""
365
-
366
- if scope == "uncommitted":
367
- stat = _git(["diff", "--stat", "HEAD"])
368
- if stat.strip():
369
- names = _git(["diff", "--name-only", "HEAD"])
370
- return stat, " ".join(names.split())
371
- return "", ""
372
-
373
- if scope == "last":
374
- stat = _git(["diff", "--stat", "HEAD~1"])
375
- if stat.strip():
376
- names = _git(["diff", "--name-only", "HEAD~1"])
377
- return stat, " ".join(names.split())
378
- return "", ""
379
-
380
- if scope == "custom" and base:
381
- stat = _git(["diff", "--stat", base])
382
- if stat.strip():
383
- names = _git(["diff", "--name-only", base])
384
- return stat, " ".join(names.split())
385
- return "", ""
386
-
387
- # branch (default): uncommitted + committed changes since the branch point
388
- if not base:
389
- base = resolve_branch_base(repo)
390
- stat_head = _git(["diff", "--stat", "HEAD"])
391
- names_head = _git(["diff", "--name-only", "HEAD"])
392
- stat_branch = ""
393
- names_branch = ""
394
- if base:
395
- stat_branch = _git(["diff", "--stat", base + "...HEAD"])
396
- names_branch = _git(["diff", "--name-only", base + "...HEAD"])
397
- if stat_head.strip() or stat_branch.strip():
398
- names = " ".join(dict.fromkeys((names_head + " " + names_branch).split()))
399
- stat = (stat_head.strip() + "\n" + stat_branch.strip()).strip()
400
- return stat, names
401
- stat = _git(["diff", "--stat", "HEAD~1"])
402
- if stat.strip():
403
- names = _git(["diff", "--name-only", "HEAD~1"])
404
- return stat, " ".join(names.split())
405
- return "", ""
406
-
407
-
408
- def build_prompt(repo: Path, task: str, base: str = "", scope: str = "branch") -> str:
409
- prd = repo / ".codex" / "prd.md"
410
- prd_text = str(prd) if prd.is_file() else "(PRD not found)"
411
- diff, changed = review_diff(repo, scope, base)
412
- if not changed:
413
- changed = "(no committed-baseline diff; reviewing current workspace)"
414
- return (
415
- "你是【独立代码审查者】。下面的代码由实现模型完成,请以独立视角审查,不要预设实现正确,也不要客套。\n"
416
- f"任务:{task}\n\n"
417
- "审查输入(证据):\n"
418
- f"- PRD:{prd_text}(请读取)\n"
419
- f"- 变更文件:\n{changed}\n"
420
- f"- Diff 摘要:\n{diff}\n\n"
421
- "审查要求:\n"
422
- "1) 逐条对照 PRD 验收标准,检查实现是否满足;有无越界/多余改动\n"
423
- "2) 检查代码质量:安全(注入/XSS/密钥泄露)、事务、异常处理、注释完整性、魔法值\n"
424
- "3) 请用中文输出报告,格式如下(描述请通俗易懂,避免专业术语堆砌):\n"
425
- "## 审查报告\n"
426
- "### 严重(必须修)\n"
427
- "### 警告(建议修)\n"
428
- "### 建议(可选)\n"
429
- "每条:文件:行号 + 问题描述 + 修改建议\n"
430
- "### 结论:通过 / 需修改(说明原因)"
431
- )
432
-
433
-
434
- def run_reviewer(idx, reviewer, args, rows, repo, prompt, tmpdir, keyfile):
435
- """Run one reviewer (codex or claude) and write its output to out-{idx}."""
436
- out = tmpdir / f"out-{idx}"
437
- rprov, rmodel = reviewer.split("|", 1)
438
- row = next((r for r in rows if r["id"] == rprov), None)
439
- if row is None:
440
- out.write_text("(未知 provider)", encoding="utf-8")
441
- return
442
- apimodel = re.sub(r"\[.*\]$", "", rmodel)
443
- if args["cli"] == "codex":
444
- codex_cli = find_codex_cli()
445
- if not codex_cli:
446
- out.write_text("(未找到可运行的 codex CLI)", encoding="utf-8")
447
- return
448
- cxbase = args["baseurl"] or row["oai_base"] or row["base_url"]
449
- cxbase = re.sub(r"/anthropic/?$", "", cxbase)
450
- cxwire = args["wireapi"] or row["oai_wire"] or "responses"
451
- envkey = rprov.upper() + "_API_KEY"
452
- rkey = key_of(keyfile, rprov)
453
- rchome = tmpdir / f"home-{idx}"
454
- rchome.mkdir(parents=True, exist_ok=True)
455
- (rchome / "config.toml").write_text(
456
- f'model = "{apimodel}"\n'
457
- f'model_provider = "{rprov}"\n\n'
458
- f'[model_providers.{rprov}]\n'
459
- f'name = "{row["name"]}"\n'
460
- f'base_url = "{cxbase}"\n'
461
- f'wire_api = "{cxwire}"\n'
462
- f'env_key = "{envkey}"\n',
463
- encoding="utf-8",
464
- )
465
- reptmp = rchome / "report.txt"
466
- env = dict(os.environ)
467
- env["CODEX_HOME"] = str(rchome)
468
- env[envkey] = rkey
469
- try:
470
- subprocess.run(
471
- [codex_cli, "exec", "--color", "never", "--ephemeral", "-s",
472
- "read-only", "-C", str(repo), "-o", str(reptmp), "-m", apimodel, prompt],
473
- env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
474
- timeout=int(args.get("timeout", 300)),
475
- )
476
- except Exception:
477
- pass
478
- if reptmp.is_file():
479
- out.write_text(reptmp.read_text(encoding="utf-8", errors="replace"), encoding="utf-8")
480
- else:
481
- out.write_text(f"(codex 执行未产出报告:{apimodel};请检查 CLI/API 配置)", encoding="utf-8")
482
- else:
483
- claude_bin = find_claude_cli()
484
- if not claude_bin:
485
- out.write_text("(未找到 claude CLI)", encoding="utf-8")
486
- return
487
- rkey = key_of(keyfile, rprov)
488
- tmp_settings = tmpdir / f"settings-{idx}.json"
489
- tmp_settings.write_text(
490
- json.dumps({
491
- "env": {
492
- "ANTHROPIC_BASE_URL": row["base_url"],
493
- "ANTHROPIC_AUTH_TOKEN": rkey,
494
- "ANTHROPIC_MODEL": apimodel,
495
- "ANTHROPIC_DEFAULT_SONNET_MODEL": apimodel,
496
- "ANTHROPIC_DEFAULT_OPUS_MODEL": apimodel,
497
- "ANTHROPIC_DEFAULT_HAIKU_MODEL": apimodel,
498
- }
499
- }, ensure_ascii=False),
500
- encoding="utf-8",
501
- )
502
- try:
503
- with open(out, "w", encoding="utf-8") as fh:
504
- subprocess.run(
505
- [claude_bin, "--settings", str(tmp_settings), "-p", prompt],
506
- stdout=fh, stderr=subprocess.DEVNULL, timeout=int(args.get("timeout", 300)),
507
- )
508
- except Exception:
509
- pass
510
- if out.stat().st_size == 0:
511
- out.write_text(f"(claude 未产出报告:{apimodel})", encoding="utf-8")
512
-
513
-
514
-
515
-
516
- def api_endpoint(row: dict) -> str:
517
- """OpenAI-compatible chat/completions endpoint for a provider row."""
518
- base = row.get("oai_base") or re.sub(r"/anthropic/?$", "", row["base_url"])
519
- return base.rstrip("/") + "/chat/completions"
520
-
521
-
522
- def api_chat(row: dict, api_key: str, model: str, prompt: str, timeout: int) -> dict:
523
- """Call a provider's OpenAI-compatible chat/completions endpoint."""
524
- body = {
525
- "model": model,
526
- "messages": [{"role": "user", "content": prompt}],
527
- "max_tokens": 4096,
528
- }
529
- req = urllib.request.Request(
530
- api_endpoint(row),
531
- data=json.dumps(body).encode("utf-8"),
532
- headers={"Content-Type": "application/json", "Authorization": "Bearer " + api_key},
533
- method="POST",
534
- )
535
- with urllib.request.urlopen(req, timeout=timeout) as resp:
536
- return json.loads(resp.read().decode("utf-8"))
537
-
538
-
539
- def api_content(data: dict) -> str:
540
- """Extract the reply text from a chat/completions response."""
541
- choices = data.get("choices") or []
542
- if not choices:
543
- return json.dumps(data, ensure_ascii=False)[:2000]
544
- msg = choices[0].get("message", {})
545
- content = msg.get("content") or msg.get("reasoning_content") or ""
546
- return content if isinstance(content, str) else json.dumps(content, ensure_ascii=False)
547
-
548
-
549
- def run_api_reviewer(idx, reviewer, rows, prompt, keyfile, timeout, out):
550
- """Run one reviewer via a direct API call and write its output to out."""
551
- rprov, rmodel = reviewer.split("|", 1)
552
- apimodel = re.sub(r"\[.*\]$", "", rmodel)
553
- row = next((r for r in rows if r["id"] == rprov), None)
554
- if row is None:
555
- out.write_text("(未知 provider)", encoding="utf-8")
556
- return
557
- rkey = key_of(keyfile, rprov)
558
- if not rkey:
559
- out.write_text(f"({rprov} 未配置 key,无法直连)", encoding="utf-8")
560
- return
561
- if not (row.get("oai_base") or row.get("base_url")):
562
- out.write_text(f"({rprov} 未配置 base_url,无法直连)", encoding="utf-8")
563
- return
564
- try:
565
- data = api_chat(row, rkey, apimodel, prompt, timeout)
566
- text = api_content(data)
567
- out.write_text(text or "(API 返回空)", encoding="utf-8")
568
- except Exception as e:
569
- out.write_text(f"(API 调用失败:{type(e).__name__}: {str(e)[:200]})", encoding="utf-8")
570
-
571
-
572
-
573
-
574
- def review_diff_text(repo: Path, base: str = "") -> str:
575
- """Full diff text (HEAD uncommitted, then <base>...HEAD branch commits)."""
576
- def _git(args):
577
- try:
578
- r = subprocess.run(["git"] + args, cwd=str(repo), capture_output=True, timeout=15)
579
- return r.stdout.decode("utf-8", errors="replace") if r.returncode == 0 else ""
580
- except Exception:
581
- return ""
582
-
583
- out = _git(["diff", "HEAD"])
584
- if out.strip():
585
- return out
586
- if not base:
587
- for cand in ("@{upstream}", "origin/main", "origin/master", "main", "master"):
588
- if _git(["rev-parse", "--verify", "--quiet", cand + "^{commit}"]):
589
- base = cand
590
- break
591
- if not base:
592
- base = "HEAD~1"
593
- out = _git(["diff", base + "...HEAD"])
594
- if out.strip():
595
- return out
596
- out = _git(["diff", "HEAD~1"])
597
- if out.strip():
598
- return out
599
- return ""
600
-
601
-
602
- def build_api_prompt(repo: Path, task: str, base: str = "", scope: str = "branch") -> str:
603
- """Prompt for the direct-API path: embeds PRD + full content of every
604
- changed file so the model can actually read the code (it has no local
605
- file access)."""
606
- prd = repo / ".codex" / "prd.md"
607
- prd_text = prd.read_text(encoding="utf-8") if prd.is_file() else "(PRD not found)"
608
- _, changed = review_diff(repo, scope, base)
609
- names = [n for n in changed.split() if n and (repo / n).is_file()]
610
-
611
- lines = [
612
- "你是【独立代码审查者】。请只根据下面提供的资料审查,不要假设你能访问本地文件。",
613
- f"任务:{task}",
614
- "",
615
- "审查输入(证据):",
616
- "### PRD(请据此核对验收标准)",
617
- prd_text,
618
- "",
619
- "### 变更文件清单",
620
- "\n".join(names) if names else "(无)",
621
- "",
622
- ]
623
-
624
- if names:
625
- lines.append("### 变更文件内容(完整源码,请逐行审查)")
626
- budget = 50000 # chars of embedded source
627
- used = 0
628
- for name in names:
629
- try:
630
- content = (repo / name).read_text(encoding="utf-8", errors="replace")
631
- except Exception:
632
- content = ""
633
- block = f"\n===== {name} =====\n{content}\n"
634
- if used + len(block) > budget:
635
- lines.append(f"\n===== {name} =====\n...(源码过长已截断,共 {len(names)} 个文件)")
636
- break
637
- lines.append(block)
638
- used += len(block)
639
- lines.append("")
640
-
641
- lines += [
642
- "审查要求:",
643
- "1) 逐条对照 PRD 验收标准,检查实现是否满足;有无越界/多余改动",
644
- "2) 检查代码质量:安全(注入/XSS/密钥泄露)、事务、异常处理、注释完整性、魔法值",
645
- "3) 请用中文输出报告,格式如下(描述请通俗易懂,避免专业术语堆砌):",
646
- "## 审查报告",
647
- "### 严重(必须修)",
648
- "### 警告(建议修)",
649
- "### 建议(可选)",
650
- "每条:文件:行号 + 问题描述 + 修改建议",
651
- "### 结论:通过 / 需修改(说明原因)",
652
- ]
653
- return "\n".join(lines)
654
-
655
-
656
- def write_merged_report(args, repo, reviewers, tmpdir, curmodel, curprov, selmodel, selprov, exec_desc):
657
- """Merge per-reviewer outputs into the cross-model report file."""
658
- nrev = len(reviewers)
659
- output = args["output"]
660
- if not output:
661
- out_dir = repo / ".codex" / "reviews"
662
- out_dir.mkdir(parents=True, exist_ok=True)
663
- output = str(out_dir / f"cross-review-{datetime.now().strftime('%Y%m%d-%H%M')}.md")
664
- curmodel_clean = re.sub(r"\[.*\]$", "", curmodel)
665
- selmodel_clean = re.sub(r"\[.*\]$", "", selmodel)
666
- with open(output, "w", encoding="utf-8") as fh:
667
- fh.write("# 跨模型审查报告(合并)\n")
668
- fh.write(f"- 任务:{args['task']}\n")
669
- fh.write(f"- 时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
670
- fh.write(f"- 当前模型(实现):{curmodel_clean}({curprov})\n")
671
- fh.write(f"- 选定审查模型:{selmodel_clean}({selprov})\n")
672
- fh.write(f"- 审查模型数:{nrev}\n")
673
- fh.write(f"- 执行方式:{exec_desc}\n")
674
- fh.write("\n")
675
- for i, rv in enumerate(reviewers, 1):
676
- apimodel = re.sub(r"\[.*\]$", "", rv.split("|", 1)[1])
677
- if i > 1:
678
- fh.write("\n---\n\n")
679
- fh.write(f"## 审查者 [{i}/{nrev}]:{apimodel}({rv.split('|', 1)[0]})\n\n")
680
- out_file = tmpdir / f"out-{i}"
681
- if out_file.is_file():
682
- fh.write(out_file.read_text(encoding="utf-8", errors="replace"))
683
- else:
684
- fh.write("(无输出)\n")
685
- return output
686
-
687
-
688
-
689
-
690
- def select_scope(argv_scope: str) -> str:
691
- """Interactive scope selection; default = branch changes."""
692
- if argv_scope:
693
- return argv_scope
694
- if not sys.stdin.isatty():
695
- return "branch"
696
- print("请选择审查范围(默认 1:分支变动):")
697
- print(" 1. 分支变动(自检出以来全部改动,含未提交)")
698
- print(" 2. 仅未提交")
699
- print(" 3. 最近一次提交")
700
- print(" 4. 自定义 -Base <ref>")
701
- try:
702
- choice = input("选择 [1]: ").strip()
703
- except EOFError:
704
- choice = ""
705
- return {"": "branch", "1": "branch", "2": "uncommitted", "3": "last", "4": "custom"}.get(choice, "branch")
706
-
707
-
708
- def main(argv=None) -> int:
709
- argv = sys.argv[1:] if argv is None else argv
710
- args = parse_args(argv)
711
- args["scope"] = select_scope(args.get("scope", ""))
712
-
713
- script_dir = Path(__file__).resolve().parent
714
- repo = repo_root(script_dir)
715
- catalog = repo / ".codex" / "model-catalog.json"
716
- keyfile = Path(args["keyfile"]) if args["keyfile"] else Path.home() / ".codex" / "api-keys.json"
717
-
718
- # ---- -SetKey ----
719
- if args["setkey"]:
720
- return set_key(keyfile, args["setkey"], catalog)
721
-
722
- # ---- -List ----
723
- if args["list"]:
724
- print(
725
- f"===== Providers (key file: {keyfile}; current: "
726
- f"{current_line(Path.home() / '.codex' / 'config.toml')}) ====="
727
- )
728
- for r in providers_tsv(keyfile, catalog):
729
- kstat = "key=MISSING" if r["has_key"] != "1" else "key=set"
730
- print(
731
- f"[{r['id']}] {r['name']} base={r['base_url']} model={r['model']} "
732
- f"context={r['context']} {kstat}"
733
- )
734
- if r["models"]:
735
- print(f" models: {r['models']}")
736
- return 0
737
-
738
- # ---- decide CLI ----
739
- cli = args["cli"]
740
- if not cli:
741
- cli = "claude" if ".claude" in str(keyfile) else "codex"
742
- if cli not in ("codex", "claude"):
743
- print(f"[跨模型审查] Cli 只能是 codex 或 claude(当前:{cli})。", file=sys.stderr)
744
- return 1
745
- args["cli"] = cli
746
-
747
- # ---- provider / model resolution ----
748
- curprov = current_provider(keyfile, catalog, Path.home() / ".codex" / "config.toml")
749
- if not curprov:
750
- print("[跨模型审查] 无法确定当前模型所属 provider。请用 -Provider <id> 指定,或用 -List 查看。", file=sys.stderr)
751
- return 1
752
-
753
- rows = providers_tsv(keyfile, catalog)
754
- selprov = args["provider"] or curprov
755
- selrow = next((r for r in rows if r["id"] == selprov), None)
756
- if selrow is None:
757
- print(f"[跨模型审查] 未知 Provider:{selprov}(用 -List 查看可用项)。", file=sys.stderr)
758
- return 1
759
- selmodel = args["model"] or selrow["model"]
760
-
761
- currow = next((r for r in rows if r["id"] == curprov), None)
762
- curmodel = ""
763
- try:
764
- cfg_text = (Path.home() / ".codex" / "config.toml").read_text(encoding="utf-8")
765
- m = re.search(r'^\s*model\s*=\s*"([^"]+)"', cfg_text, re.M)
766
- if m:
767
- curmodel = m.group(1)
768
- except Exception:
769
- pass
770
- if not curmodel and currow:
771
- curmodel = currow["model"]
772
-
773
- if f"{curprov}|{curmodel}" == f"{selprov}|{selmodel}":
774
- reviewers = [f"{curprov}|{curmodel}"]
775
- else:
776
- reviewers = [f"{curprov}|{curmodel}", f"{selprov}|{selmodel}"]
777
-
778
- # ---- key/base_url checks ----
779
- for rv in reviewers:
780
- rprov = rv.split("|", 1)[0]
781
- row = next((r for r in rows if r["id"] == rprov), None)
782
- if row is None:
783
- continue
784
- if row["has_key"] != "1":
785
- print(
786
- f"[跨模型审查] provider [{rprov}] 未配置 key。请补 key 并写回:"
787
- f"python {Path(__file__).name} -SetKey {rprov}:<你的key> -KeyFile {keyfile}",
788
- file=sys.stderr,
789
- )
790
- return 1
791
- if not row["base_url"]:
792
- print(f"[跨模型审查] {rprov} 未配置 base_url。", file=sys.stderr)
793
- return 1
794
-
795
- # ---- fast direct-API path (default; two independent models) ----
796
- if args["mode"] == "api":
797
- if not args["provider"] and not args["model"]:
798
- # default: two INDEPENDENT providers (current + first other keyed)
799
- reviewers = [f"{curprov}|{curmodel}"]
800
- for r in rows:
801
- if r["id"] != curprov and r["has_key"] == "1":
802
- reviewers.append(f"{r['id']}|{r['model']}")
803
- selprov, selmodel = r["id"], r["model"]
804
- break
805
- prompt = build_api_prompt(repo, args["task"], args.get("base", ""), args["scope"])
806
- nrev = len(reviewers)
807
- t0 = time.time()
808
- with tempfile.TemporaryDirectory(prefix="review-api-") as td:
809
- tmpdir = Path(td)
810
- with concurrent.futures.ThreadPoolExecutor(max_workers=nrev) as ex:
811
- futures = [
812
- ex.submit(run_api_reviewer, i + 1, rv, rows, prompt, keyfile,
813
- int(args.get("timeout", 300)), tmpdir / f"out-{i + 1}")
814
- for i, rv in enumerate(reviewers)
815
- ]
816
- for f in futures:
817
- f.result()
818
- output = write_merged_report(
819
- args, repo, reviewers, tmpdir, curmodel, curprov, selmodel, selprov,
820
- f"直连API({nrev} 个独立模型)",
821
- )
822
- elapsed = time.time() - t0
823
- print(f"跨模型审查完成(独立模型数={nrev},耗时 {elapsed:.1f}s)-> {output}")
824
- return 0
825
-
826
- # ---- build prompt ----
827
- prompt = build_prompt(repo, args["task"], args.get("base", ""), args["scope"])
828
-
829
- # ---- run reviewers in parallel ----
830
- nrev = len(reviewers)
831
- with tempfile.TemporaryDirectory(prefix="review-") as td:
832
- tmpdir = Path(td)
833
- with concurrent.futures.ThreadPoolExecutor(max_workers=nrev) as ex:
834
- futures = [
835
- ex.submit(run_reviewer, i + 1, rv, args, rows, repo, prompt, tmpdir, keyfile)
836
- for i, rv in enumerate(reviewers)
837
- ]
838
- for f in futures:
839
- f.result()
840
-
841
- # ---- merge + write report ----
842
- output = write_merged_report(
843
- args, repo, reviewers, tmpdir, curmodel, curprov, selmodel, selprov,
844
- f"CLI({cli})",
845
- )
846
- print(f"跨模型审查完成(审查者数={nrev})-> {output}")
847
- return 0
848
-
849
-
850
- if __name__ == "__main__":
851
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """SDLC cross-model review runner (cross-platform: Windows / macOS / Linux).
3
+
4
+ Rules:
5
+ - Runs CURRENT model + USER-SELECTED model in PARALLEL, then merges into one
6
+ report. Same model -> runs once. Different -> both run concurrently.
7
+ - Codex side -> codex CLI (temp CODEX_HOME + env_key). Claude side -> claude
8
+ CLI (temp settings). Never cross-use: each side uses its own CLI.
9
+ - Model source of truth: per-directory api-keys.json (Codex:
10
+ ~/.codex/api-keys.json; Claude: ~/.claude/api-keys.json).
11
+ model-catalog.json = alternatives (-List). Missing key -> -SetKey.
12
+ - Choosing an unconfigured model: confirm base_url / context / key / model
13
+ with the user first.
14
+
15
+ Usage:
16
+ python .codex/hooks/review-runner.py -Task "task" [-Provider <id>] [-Model "model"] \
17
+ [-Cli codex|claude] [-KeyFile <api-keys.json>] [-SetKey <provider>:<key>] \
18
+ [-List] [-BaseUrl <url>] [-WireApi responses|chat] [-Output <path>] \
19
+ [-Timeout <seconds>] (default 300; per-reviewer subprocess cap)
20
+ """
21
+ import concurrent.futures
22
+ import json
23
+ import os
24
+ import re
25
+ import shutil
26
+ import subprocess
27
+ import sys
28
+ import tempfile
29
+ import time
30
+ import urllib.request
31
+ from datetime import datetime
32
+ from pathlib import Path
33
+
34
+ # R2 UTF-8 stdio 双保险(消除 Windows GBK 乱码)
35
+ for _s in (sys.stdout, sys.stderr):
36
+ try:
37
+ _s.reconfigure(encoding="utf-8", errors="replace")
38
+ except Exception:
39
+ pass
40
+
41
+
42
+ def parse_args(argv):
43
+ args = {
44
+ "task": "current-task",
45
+ "output": "",
46
+ "provider": "",
47
+ "model": "",
48
+ "cli": "",
49
+ "keyfile": "",
50
+ "setkey": "",
51
+ "baseurl": "",
52
+ "wireapi": "",
53
+ "timeout": 300, # seconds per reviewer
54
+ "mode": "api", # api = direct dual-model API (fast); cli = codex/claude exec
55
+ "base": "", # branch base ref for "since checkout" scope
56
+ "scope": "", # branch | uncommitted | last | custom (default branch)
57
+ "list": False,
58
+ }
59
+ i = 0
60
+ while i < len(argv):
61
+ a = argv[i]
62
+ if a in ("-Task", "-Provider", "-Model", "-Cli", "-KeyFile", "-SetKey",
63
+ "-BaseUrl", "-WireApi", "-Output", "-Timeout", "-Mode", "-Base", "-Scope") and i + 1 < len(argv):
64
+ key = a[1:].lower()
65
+ args[key] = argv[i + 1]
66
+ i += 2
67
+ elif a == "-List":
68
+ args["list"] = True
69
+ i += 1
70
+ else:
71
+ i += 1
72
+ return args
73
+
74
+
75
+ def repo_root(script_dir: Path) -> Path:
76
+ if script_dir.name == "hooks":
77
+ return script_dir.parent.parent
78
+ return script_dir.parent
79
+
80
+
81
+ def load_catalog(catalog: Path) -> dict:
82
+ prov = {}
83
+ if catalog.is_file():
84
+ try:
85
+ for p in json.load(open(catalog, encoding="utf-8")).get("providers", []):
86
+ prov[p["id"]] = {
87
+ "name": p.get("name", p["id"]),
88
+ "base_url": p.get("base_url", ""),
89
+ "key_env": p.get("key_env", p["id"].upper() + "_API_KEY"),
90
+ "model": p.get("default_model", ""),
91
+ "context": p.get("default_context", ""),
92
+ "models": p.get("models", []),
93
+ "key": "",
94
+ "openai_base_url": p.get("openai_base_url", ""),
95
+ "openai_wire": p.get("openai_wire", ""),
96
+ }
97
+ except Exception:
98
+ pass
99
+ return prov
100
+
101
+
102
+ def providers_tsv(keyfile: Path, catalog: Path) -> list:
103
+ """Return provider dicts (id, name, base_url, model, context, has_key,
104
+ oai_base, oai_wire, models)."""
105
+ prov = load_catalog(catalog)
106
+ if keyfile.is_file():
107
+ try:
108
+ data = json.load(open(keyfile, encoding="utf-8"))
109
+ for pid, e in data.items():
110
+ if pid not in prov:
111
+ prov[pid] = {
112
+ "name": e.get("name", pid),
113
+ "base_url": e.get("base_url", ""),
114
+ "key_env": pid.upper() + "_API_KEY",
115
+ "model": e.get("model", ""),
116
+ "context": e.get("context", ""),
117
+ "models": [],
118
+ "key": "",
119
+ "openai_base_url": "",
120
+ "openai_wire": "",
121
+ }
122
+ for fld in ("name", "base_url", "model", "context", "key",
123
+ "openai_base_url", "openai_wire"):
124
+ if fld in e:
125
+ prov[pid][fld] = e[fld]
126
+ except Exception:
127
+ pass
128
+ rows = []
129
+ for pid, p in sorted(prov.items()):
130
+ models = ",".join(
131
+ str(m.get("name", "")) + "(" + str(m.get("context", "")) + ")"
132
+ for m in p.get("models", [])
133
+ )
134
+ rows.append({
135
+ "id": pid,
136
+ "name": p.get("name", ""),
137
+ "base_url": p.get("base_url", ""),
138
+ "model": p.get("model", ""),
139
+ "context": p.get("context", ""),
140
+ "has_key": "1" if p.get("key") else "0",
141
+ "oai_base": p.get("openai_base_url", ""),
142
+ "oai_wire": p.get("openai_wire", ""),
143
+ "models": models,
144
+ })
145
+ return rows
146
+
147
+
148
+ def current_line(cfg: Path) -> str:
149
+ if not cfg.is_file():
150
+ return "model=(unknown) provider=(unknown)"
151
+ try:
152
+ t = cfg.read_text(encoding="utf-8")
153
+ except Exception:
154
+ return "model=(unknown) provider=(unknown)"
155
+ m = re.search(r'^\s*model\s*=\s*"([^"]+)"', t, re.M)
156
+ model = m.group(1) if m else "unknown"
157
+ mp = re.search(r'^\s*model_provider\s*=\s*"([^"]+)"', t, re.M)
158
+ provider = mp.group(1) if mp else "unknown"
159
+ return f"model={model} provider={provider}"
160
+
161
+
162
+ def current_provider(keyfile: Path, catalog: Path, cfg: Path) -> str:
163
+ prov = {}
164
+ if catalog.is_file():
165
+ try:
166
+ for p in json.load(open(catalog, encoding="utf-8")).get("providers", []):
167
+ prov[p["id"]] = {"base_url": p.get("base_url", ""), "key": ""}
168
+ except Exception:
169
+ pass
170
+ if keyfile.is_file():
171
+ try:
172
+ data = json.load(open(keyfile, encoding="utf-8"))
173
+ for pid, e in data.items():
174
+ if pid not in prov:
175
+ prov[pid] = {"base_url": e.get("base_url", ""), "key": ""}
176
+ prov[pid]["key"] = e.get("key", "")
177
+ except Exception:
178
+ pass
179
+ mp, mp_base = "", ""
180
+ if cfg.is_file():
181
+ try:
182
+ t = cfg.read_text(encoding="utf-8")
183
+ mm = re.search(r'^\s*model_provider\s*=\s*"([^"]+)"', t, re.M)
184
+ if mm:
185
+ mp = mm.group(1)
186
+ mb = re.search(r'^\s*base_url\s*=\s*"([^"]+)"', t, re.M)
187
+ if mb:
188
+ mp_base = mb.group(1).rstrip("/")
189
+ except Exception:
190
+ pass
191
+ strip = lambda u: re.sub(r"/anthropic/?$", "", u.rstrip("/"))
192
+ if mp and mp in prov:
193
+ return mp
194
+ if mp_base:
195
+ for pid, p in prov.items():
196
+ if strip(p["base_url"]) == strip(mp_base):
197
+ return pid
198
+ for pid, p in sorted(prov.items()):
199
+ if p.get("key"):
200
+ return pid
201
+ return mp or ""
202
+
203
+
204
+ def set_key(keyfile: Path, setkey: str, catalog: Path) -> int:
205
+ if ":" not in setkey:
206
+ print("SetKey format: <provider>:<key>", file=sys.stderr)
207
+ return 1
208
+ pid, pkey = setkey.split(":", 1)
209
+ prov = {}
210
+ if catalog.is_file():
211
+ try:
212
+ for p in json.load(open(catalog, encoding="utf-8")).get("providers", []):
213
+ prov[p["id"]] = {
214
+ "name": p.get("name", p["id"]),
215
+ "base_url": p.get("base_url", ""),
216
+ "model": p.get("default_model", ""),
217
+ "context": p.get("default_context", ""),
218
+ }
219
+ except Exception:
220
+ pass
221
+ data = {}
222
+ if keyfile.is_file():
223
+ try:
224
+ data = json.load(open(keyfile, encoding="utf-8"))
225
+ except Exception:
226
+ pass
227
+ if pid not in prov:
228
+ print(f"unknown provider: {pid}", file=sys.stderr)
229
+ return 1
230
+ entry = data.get(pid, {})
231
+ entry.setdefault("name", prov[pid]["name"])
232
+ entry.setdefault("base_url", prov[pid]["base_url"])
233
+ entry.setdefault("model", prov[pid]["model"])
234
+ entry.setdefault("context", prov[pid]["context"])
235
+ entry["key"] = pkey
236
+ data[pid] = entry
237
+ keyfile.parent.mkdir(parents=True, exist_ok=True)
238
+ json.dump(data, open(keyfile, "w", encoding="utf-8"), ensure_ascii=False, indent=4)
239
+ print(f"key written back -> {keyfile} [provider={pid}]")
240
+ return 0
241
+
242
+
243
+ _CLI_PROBE_TIMEOUT = 10 # seconds allowed for the --version probe
244
+
245
+
246
+ def _cli_runnable(exe: str) -> bool:
247
+ """Verify a codex CLI candidate actually runs.
248
+
249
+ Probes ``<exe> --version`` and requires a zero exit code plus codex-ish
250
+ stdout, so non-runnable candidates (e.g. the Windows Store/MSIX app alias
251
+ that raises PermissionError on direct launch, or a broken alias that exits
252
+ 0 without output) are skipped. ``CREATE_NO_WINDOW`` prevents a console
253
+ flash on Windows.
254
+ """
255
+ try:
256
+ r = subprocess.run(
257
+ [exe, "--version"],
258
+ capture_output=True,
259
+ timeout=_CLI_PROBE_TIMEOUT,
260
+ creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
261
+ )
262
+ if r.returncode != 0:
263
+ return False
264
+ out = (r.stdout or b"") + (r.stderr or b"")
265
+ return b"codex" in out.lower()
266
+ except Exception:
267
+ return False
268
+
269
+
270
+ def find_codex_cli() -> str:
271
+ cand = os.environ.get("CODEX_CLI_PATH") or ""
272
+ if cand and os.path.isfile(cand) and _cli_runnable(cand):
273
+ return cand
274
+ for name in ("codex", "codex.exe"):
275
+ p = shutil.which(name)
276
+ if p and os.path.isfile(p) and _cli_runnable(p):
277
+ return p
278
+ for env in ("LOCALAPPDATA", "APPDATA"):
279
+ base = os.environ.get(env)
280
+ if not base:
281
+ continue
282
+ for p in sorted(Path(base, "OpenAI", "Codex", "bin").glob("*/codex.exe")):
283
+ if _cli_runnable(str(p)):
284
+ return str(p)
285
+ return ""
286
+
287
+
288
+ def find_claude_cli() -> str:
289
+ for name in ("claude", "claude.cmd"):
290
+ p = shutil.which(name)
291
+ if p:
292
+ return p
293
+ return ""
294
+
295
+
296
+ def key_of(keyfile: Path, pid: str) -> str:
297
+ try:
298
+ data = json.load(open(keyfile, encoding="utf-8"))
299
+ return data.get(pid, {}).get("key", "")
300
+ except Exception:
301
+ return ""
302
+
303
+
304
+
305
+
306
+ def _git_rc(repo: Path, args):
307
+ """Run git, return (returncode, stdout-utf8)."""
308
+ try:
309
+ r = subprocess.run(["git"] + args, cwd=str(repo), capture_output=True, timeout=15)
310
+ return r.returncode, r.stdout.decode("utf-8", errors="replace")
311
+ except Exception:
312
+ return -1, ""
313
+
314
+
315
+ def resolve_branch_base(repo: Path) -> str:
316
+ """Find the branch point of the current branch.
317
+
318
+ Picks the closest local branch whose tip is an ancestor of HEAD (i.e. the
319
+ branch this one was checked out from); falls back to origin/main, main,
320
+ or HEAD~1.
321
+ """
322
+ rc, cur = _git_rc(repo, ["rev-parse", "--abbrev-ref", "HEAD"])
323
+ cur = cur.strip()
324
+ rc, refs = _git_rc(repo, ["for-each-ref", "--format=%(refname:short)", "refs/heads"])
325
+ best, best_n = "", None
326
+ for br in refs.splitlines():
327
+ br = br.strip()
328
+ if not br or br == cur:
329
+ continue
330
+ rc, _ = _git_rc(repo, ["merge-base", "--is-ancestor", br, "HEAD"])
331
+ if rc != 0:
332
+ continue
333
+ rc, out = _git_rc(repo, ["rev-list", "--count", br + "..HEAD"])
334
+ if rc != 0:
335
+ continue
336
+ try:
337
+ n = int(out.strip() or "0")
338
+ except ValueError:
339
+ continue
340
+ if best_n is None or n < best_n:
341
+ best, best_n = br, n
342
+ if best:
343
+ return best
344
+ for cand in ("origin/main", "origin/master", "main", "master", "HEAD~1"):
345
+ rc, _ = _git_rc(repo, ["rev-parse", "--verify", "--quiet", cand + "^{commit}"])
346
+ if rc == 0:
347
+ return cand
348
+ return "HEAD~1"
349
+
350
+
351
+
352
+ def review_diff(repo: Path, scope: str = "branch", base: str = ""):
353
+ """Return (diff_stat, changed_names) for the selected scope.
354
+
355
+ scope: branch (default) = uncommitted + all commits since the branch was
356
+ checked out; uncommitted = git diff HEAD; last = git diff HEAD~1;
357
+ custom = git diff <base>.
358
+ """
359
+ def _git(args):
360
+ try:
361
+ r = subprocess.run(["git"] + args, cwd=str(repo), capture_output=True, timeout=15)
362
+ return r.stdout.decode("utf-8", errors="replace") if r.returncode == 0 else ""
363
+ except Exception:
364
+ return ""
365
+
366
+ if scope == "uncommitted":
367
+ stat = _git(["diff", "--stat", "HEAD"])
368
+ if stat.strip():
369
+ names = _git(["diff", "--name-only", "HEAD"])
370
+ return stat, " ".join(names.split())
371
+ return "", ""
372
+
373
+ if scope == "last":
374
+ stat = _git(["diff", "--stat", "HEAD~1"])
375
+ if stat.strip():
376
+ names = _git(["diff", "--name-only", "HEAD~1"])
377
+ return stat, " ".join(names.split())
378
+ return "", ""
379
+
380
+ if scope == "custom" and base:
381
+ stat = _git(["diff", "--stat", base])
382
+ if stat.strip():
383
+ names = _git(["diff", "--name-only", base])
384
+ return stat, " ".join(names.split())
385
+ return "", ""
386
+
387
+ # branch (default): uncommitted + committed changes since the branch point
388
+ if not base:
389
+ base = resolve_branch_base(repo)
390
+ stat_head = _git(["diff", "--stat", "HEAD"])
391
+ names_head = _git(["diff", "--name-only", "HEAD"])
392
+ stat_branch = ""
393
+ names_branch = ""
394
+ if base:
395
+ stat_branch = _git(["diff", "--stat", base + "...HEAD"])
396
+ names_branch = _git(["diff", "--name-only", base + "...HEAD"])
397
+ if stat_head.strip() or stat_branch.strip():
398
+ names = " ".join(dict.fromkeys((names_head + " " + names_branch).split()))
399
+ stat = (stat_head.strip() + "\n" + stat_branch.strip()).strip()
400
+ return stat, names
401
+ stat = _git(["diff", "--stat", "HEAD~1"])
402
+ if stat.strip():
403
+ names = _git(["diff", "--name-only", "HEAD~1"])
404
+ return stat, " ".join(names.split())
405
+ return "", ""
406
+
407
+
408
+ def build_prompt(repo: Path, task: str, base: str = "", scope: str = "branch") -> str:
409
+ prd = repo / ".codex" / "prd.md"
410
+ prd_text = str(prd) if prd.is_file() else "(PRD not found)"
411
+ diff, changed = review_diff(repo, scope, base)
412
+ if not changed:
413
+ changed = "(no committed-baseline diff; reviewing current workspace)"
414
+ return (
415
+ "你是【独立代码审查者】。下面的代码由实现模型完成,请以独立视角审查,不要预设实现正确,也不要客套。\n"
416
+ f"任务:{task}\n\n"
417
+ "审查输入(证据):\n"
418
+ f"- PRD:{prd_text}(请读取)\n"
419
+ f"- 变更文件:\n{changed}\n"
420
+ f"- Diff 摘要:\n{diff}\n\n"
421
+ "审查要求:\n"
422
+ "1) 逐条对照 PRD 验收标准,检查实现是否满足;有无越界/多余改动\n"
423
+ "2) 检查代码质量:安全(注入/XSS/密钥泄露)、事务、异常处理、注释完整性、魔法值\n"
424
+ "3) 请用中文输出报告,格式如下(描述请通俗易懂,避免专业术语堆砌):\n"
425
+ "## 审查报告\n"
426
+ "### 严重(必须修)\n"
427
+ "### 警告(建议修)\n"
428
+ "### 建议(可选)\n"
429
+ "每条:文件:行号 + 问题描述 + 修改建议\n"
430
+ "### 结论:通过 / 需修改(说明原因)"
431
+ )
432
+
433
+
434
+ def run_reviewer(idx, reviewer, args, rows, repo, prompt, tmpdir, keyfile):
435
+ """Run one reviewer (codex or claude) and write its output to out-{idx}."""
436
+ out = tmpdir / f"out-{idx}"
437
+ rprov, rmodel = reviewer.split("|", 1)
438
+ row = next((r for r in rows if r["id"] == rprov), None)
439
+ if row is None:
440
+ out.write_text("(未知 provider)", encoding="utf-8")
441
+ return
442
+ apimodel = re.sub(r"\[.*\]$", "", rmodel)
443
+ if args["cli"] == "codex":
444
+ codex_cli = find_codex_cli()
445
+ if not codex_cli:
446
+ out.write_text("(未找到可运行的 codex CLI)", encoding="utf-8")
447
+ return
448
+ cxbase = args["baseurl"] or row["oai_base"] or row["base_url"]
449
+ cxbase = re.sub(r"/anthropic/?$", "", cxbase)
450
+ cxwire = args["wireapi"] or row["oai_wire"] or "responses"
451
+ envkey = rprov.upper() + "_API_KEY"
452
+ rkey = key_of(keyfile, rprov)
453
+ rchome = tmpdir / f"home-{idx}"
454
+ rchome.mkdir(parents=True, exist_ok=True)
455
+ (rchome / "config.toml").write_text(
456
+ f'model = "{apimodel}"\n'
457
+ f'model_provider = "{rprov}"\n\n'
458
+ f'[model_providers.{rprov}]\n'
459
+ f'name = "{row["name"]}"\n'
460
+ f'base_url = "{cxbase}"\n'
461
+ f'wire_api = "{cxwire}"\n'
462
+ f'env_key = "{envkey}"\n',
463
+ encoding="utf-8",
464
+ )
465
+ reptmp = rchome / "report.txt"
466
+ env = dict(os.environ)
467
+ env["CODEX_HOME"] = str(rchome)
468
+ env[envkey] = rkey
469
+ try:
470
+ subprocess.run(
471
+ [codex_cli, "exec", "--color", "never", "--ephemeral", "-s",
472
+ "read-only", "-C", str(repo), "-o", str(reptmp), "-m", apimodel, prompt],
473
+ env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
474
+ timeout=int(args.get("timeout", 300)),
475
+ )
476
+ except Exception:
477
+ pass
478
+ if reptmp.is_file():
479
+ out.write_text(reptmp.read_text(encoding="utf-8", errors="replace"), encoding="utf-8")
480
+ else:
481
+ out.write_text(f"(codex 执行未产出报告:{apimodel};请检查 CLI/API 配置)", encoding="utf-8")
482
+ else:
483
+ claude_bin = find_claude_cli()
484
+ if not claude_bin:
485
+ out.write_text("(未找到 claude CLI)", encoding="utf-8")
486
+ return
487
+ rkey = key_of(keyfile, rprov)
488
+ tmp_settings = tmpdir / f"settings-{idx}.json"
489
+ tmp_settings.write_text(
490
+ json.dumps({
491
+ "env": {
492
+ "ANTHROPIC_BASE_URL": row["base_url"],
493
+ "ANTHROPIC_AUTH_TOKEN": rkey,
494
+ "ANTHROPIC_MODEL": apimodel,
495
+ "ANTHROPIC_DEFAULT_SONNET_MODEL": apimodel,
496
+ "ANTHROPIC_DEFAULT_OPUS_MODEL": apimodel,
497
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL": apimodel,
498
+ }
499
+ }, ensure_ascii=False),
500
+ encoding="utf-8",
501
+ )
502
+ try:
503
+ with open(out, "w", encoding="utf-8") as fh:
504
+ subprocess.run(
505
+ [claude_bin, "--settings", str(tmp_settings), "-p", prompt],
506
+ stdout=fh, stderr=subprocess.DEVNULL, timeout=int(args.get("timeout", 300)),
507
+ )
508
+ except Exception:
509
+ pass
510
+ if out.stat().st_size == 0:
511
+ out.write_text(f"(claude 未产出报告:{apimodel})", encoding="utf-8")
512
+
513
+
514
+
515
+
516
+ def api_endpoint(row: dict) -> str:
517
+ """OpenAI-compatible chat/completions endpoint for a provider row."""
518
+ base = row.get("oai_base") or re.sub(r"/anthropic/?$", "", row["base_url"])
519
+ return base.rstrip("/") + "/chat/completions"
520
+
521
+
522
+ def api_chat(row: dict, api_key: str, model: str, prompt: str, timeout: int) -> dict:
523
+ """Call a provider's OpenAI-compatible chat/completions endpoint."""
524
+ body = {
525
+ "model": model,
526
+ "messages": [{"role": "user", "content": prompt}],
527
+ "max_tokens": 4096,
528
+ }
529
+ req = urllib.request.Request(
530
+ api_endpoint(row),
531
+ data=json.dumps(body).encode("utf-8"),
532
+ headers={"Content-Type": "application/json", "Authorization": "Bearer " + api_key},
533
+ method="POST",
534
+ )
535
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
536
+ return json.loads(resp.read().decode("utf-8"))
537
+
538
+
539
+ def api_content(data: dict) -> str:
540
+ """Extract the reply text from a chat/completions response."""
541
+ choices = data.get("choices") or []
542
+ if not choices:
543
+ return json.dumps(data, ensure_ascii=False)[:2000]
544
+ msg = choices[0].get("message", {})
545
+ content = msg.get("content") or msg.get("reasoning_content") or ""
546
+ return content if isinstance(content, str) else json.dumps(content, ensure_ascii=False)
547
+
548
+
549
+ def run_api_reviewer(idx, reviewer, rows, prompt, keyfile, timeout, out):
550
+ """Run one reviewer via a direct API call and write its output to out."""
551
+ rprov, rmodel = reviewer.split("|", 1)
552
+ apimodel = re.sub(r"\[.*\]$", "", rmodel)
553
+ row = next((r for r in rows if r["id"] == rprov), None)
554
+ if row is None:
555
+ out.write_text("(未知 provider)", encoding="utf-8")
556
+ return
557
+ rkey = key_of(keyfile, rprov)
558
+ if not rkey:
559
+ out.write_text(f"({rprov} 未配置 key,无法直连)", encoding="utf-8")
560
+ return
561
+ if not (row.get("oai_base") or row.get("base_url")):
562
+ out.write_text(f"({rprov} 未配置 base_url,无法直连)", encoding="utf-8")
563
+ return
564
+ try:
565
+ data = api_chat(row, rkey, apimodel, prompt, timeout)
566
+ text = api_content(data)
567
+ out.write_text(text or "(API 返回空)", encoding="utf-8")
568
+ except Exception as e:
569
+ out.write_text(f"(API 调用失败:{type(e).__name__}: {str(e)[:200]})", encoding="utf-8")
570
+
571
+
572
+
573
+
574
+ def review_diff_text(repo: Path, base: str = "") -> str:
575
+ """Full diff text (HEAD uncommitted, then <base>...HEAD branch commits)."""
576
+ def _git(args):
577
+ try:
578
+ r = subprocess.run(["git"] + args, cwd=str(repo), capture_output=True, timeout=15)
579
+ return r.stdout.decode("utf-8", errors="replace") if r.returncode == 0 else ""
580
+ except Exception:
581
+ return ""
582
+
583
+ out = _git(["diff", "HEAD"])
584
+ if out.strip():
585
+ return out
586
+ if not base:
587
+ for cand in ("@{upstream}", "origin/main", "origin/master", "main", "master"):
588
+ if _git(["rev-parse", "--verify", "--quiet", cand + "^{commit}"]):
589
+ base = cand
590
+ break
591
+ if not base:
592
+ base = "HEAD~1"
593
+ out = _git(["diff", base + "...HEAD"])
594
+ if out.strip():
595
+ return out
596
+ out = _git(["diff", "HEAD~1"])
597
+ if out.strip():
598
+ return out
599
+ return ""
600
+
601
+
602
+ def build_api_prompt(repo: Path, task: str, base: str = "", scope: str = "branch") -> str:
603
+ """Prompt for the direct-API path: embeds PRD + full content of every
604
+ changed file so the model can actually read the code (it has no local
605
+ file access)."""
606
+ prd = repo / ".codex" / "prd.md"
607
+ prd_text = prd.read_text(encoding="utf-8") if prd.is_file() else "(PRD not found)"
608
+ _, changed = review_diff(repo, scope, base)
609
+ names = [n for n in changed.split() if n and (repo / n).is_file()]
610
+
611
+ lines = [
612
+ "你是【独立代码审查者】。请只根据下面提供的资料审查,不要假设你能访问本地文件。",
613
+ f"任务:{task}",
614
+ "",
615
+ "审查输入(证据):",
616
+ "### PRD(请据此核对验收标准)",
617
+ prd_text,
618
+ "",
619
+ "### 变更文件清单",
620
+ "\n".join(names) if names else "(无)",
621
+ "",
622
+ ]
623
+
624
+ if names:
625
+ lines.append("### 变更文件内容(完整源码,请逐行审查)")
626
+ budget = 50000 # chars of embedded source
627
+ used = 0
628
+ for name in names:
629
+ try:
630
+ content = (repo / name).read_text(encoding="utf-8", errors="replace")
631
+ except Exception:
632
+ content = ""
633
+ block = f"\n===== {name} =====\n{content}\n"
634
+ if used + len(block) > budget:
635
+ lines.append(f"\n===== {name} =====\n...(源码过长已截断,共 {len(names)} 个文件)")
636
+ break
637
+ lines.append(block)
638
+ used += len(block)
639
+ lines.append("")
640
+
641
+ lines += [
642
+ "审查要求:",
643
+ "1) 逐条对照 PRD 验收标准,检查实现是否满足;有无越界/多余改动",
644
+ "2) 检查代码质量:安全(注入/XSS/密钥泄露)、事务、异常处理、注释完整性、魔法值",
645
+ "3) 请用中文输出报告,格式如下(描述请通俗易懂,避免专业术语堆砌):",
646
+ "## 审查报告",
647
+ "### 严重(必须修)",
648
+ "### 警告(建议修)",
649
+ "### 建议(可选)",
650
+ "每条:文件:行号 + 问题描述 + 修改建议",
651
+ "### 结论:通过 / 需修改(说明原因)",
652
+ ]
653
+ return "\n".join(lines)
654
+
655
+
656
+ def write_merged_report(args, repo, reviewers, tmpdir, curmodel, curprov, selmodel, selprov, exec_desc):
657
+ """Merge per-reviewer outputs into the cross-model report file."""
658
+ nrev = len(reviewers)
659
+ output = args["output"]
660
+ if not output:
661
+ out_dir = repo / ".codex" / "reviews"
662
+ out_dir.mkdir(parents=True, exist_ok=True)
663
+ output = str(out_dir / f"cross-review-{datetime.now().strftime('%Y%m%d-%H%M')}.md")
664
+ curmodel_clean = re.sub(r"\[.*\]$", "", curmodel)
665
+ selmodel_clean = re.sub(r"\[.*\]$", "", selmodel)
666
+ with open(output, "w", encoding="utf-8") as fh:
667
+ fh.write("# 跨模型审查报告(合并)\n")
668
+ fh.write(f"- 任务:{args['task']}\n")
669
+ fh.write(f"- 时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
670
+ fh.write(f"- 当前模型(实现):{curmodel_clean}({curprov})\n")
671
+ fh.write(f"- 选定审查模型:{selmodel_clean}({selprov})\n")
672
+ fh.write(f"- 审查模型数:{nrev}\n")
673
+ fh.write(f"- 执行方式:{exec_desc}\n")
674
+ fh.write("\n")
675
+ for i, rv in enumerate(reviewers, 1):
676
+ apimodel = re.sub(r"\[.*\]$", "", rv.split("|", 1)[1])
677
+ if i > 1:
678
+ fh.write("\n---\n\n")
679
+ fh.write(f"## 审查者 [{i}/{nrev}]:{apimodel}({rv.split('|', 1)[0]})\n\n")
680
+ out_file = tmpdir / f"out-{i}"
681
+ if out_file.is_file():
682
+ fh.write(out_file.read_text(encoding="utf-8", errors="replace"))
683
+ else:
684
+ fh.write("(无输出)\n")
685
+ return output
686
+
687
+
688
+
689
+
690
+ def select_scope(argv_scope: str) -> str:
691
+ """Interactive scope selection; default = branch changes."""
692
+ if argv_scope:
693
+ return argv_scope
694
+ if not sys.stdin.isatty():
695
+ return "branch"
696
+ print("请选择审查范围(默认 1:分支变动):")
697
+ print(" 1. 分支变动(自检出以来全部改动,含未提交)")
698
+ print(" 2. 仅未提交")
699
+ print(" 3. 最近一次提交")
700
+ print(" 4. 自定义 -Base <ref>")
701
+ try:
702
+ choice = input("选择 [1]: ").strip()
703
+ except EOFError:
704
+ choice = ""
705
+ return {"": "branch", "1": "branch", "2": "uncommitted", "3": "last", "4": "custom"}.get(choice, "branch")
706
+
707
+
708
+ def main(argv=None) -> int:
709
+ argv = sys.argv[1:] if argv is None else argv
710
+ args = parse_args(argv)
711
+ args["scope"] = select_scope(args.get("scope", ""))
712
+
713
+ script_dir = Path(__file__).resolve().parent
714
+ repo = repo_root(script_dir)
715
+ catalog = repo / ".codex" / "model-catalog.json"
716
+ keyfile = Path(args["keyfile"]) if args["keyfile"] else Path.home() / ".codex" / "api-keys.json"
717
+
718
+ # ---- -SetKey ----
719
+ if args["setkey"]:
720
+ return set_key(keyfile, args["setkey"], catalog)
721
+
722
+ # ---- -List ----
723
+ if args["list"]:
724
+ print(
725
+ f"===== Providers (key file: {keyfile}; current: "
726
+ f"{current_line(Path.home() / '.codex' / 'config.toml')}) ====="
727
+ )
728
+ for r in providers_tsv(keyfile, catalog):
729
+ kstat = "key=MISSING" if r["has_key"] != "1" else "key=set"
730
+ print(
731
+ f"[{r['id']}] {r['name']} base={r['base_url']} model={r['model']} "
732
+ f"context={r['context']} {kstat}"
733
+ )
734
+ if r["models"]:
735
+ print(f" models: {r['models']}")
736
+ return 0
737
+
738
+ # ---- decide CLI ----
739
+ cli = args["cli"]
740
+ if not cli:
741
+ cli = "claude" if ".claude" in str(keyfile) else "codex"
742
+ if cli not in ("codex", "claude"):
743
+ print(f"[跨模型审查] Cli 只能是 codex 或 claude(当前:{cli})。", file=sys.stderr)
744
+ return 1
745
+ args["cli"] = cli
746
+
747
+ # ---- provider / model resolution ----
748
+ curprov = current_provider(keyfile, catalog, Path.home() / ".codex" / "config.toml")
749
+ if not curprov:
750
+ print("[跨模型审查] 无法确定当前模型所属 provider。请用 -Provider <id> 指定,或用 -List 查看。", file=sys.stderr)
751
+ return 1
752
+
753
+ rows = providers_tsv(keyfile, catalog)
754
+ selprov = args["provider"] or curprov
755
+ selrow = next((r for r in rows if r["id"] == selprov), None)
756
+ if selrow is None:
757
+ print(f"[跨模型审查] 未知 Provider:{selprov}(用 -List 查看可用项)。", file=sys.stderr)
758
+ return 1
759
+ selmodel = args["model"] or selrow["model"]
760
+
761
+ currow = next((r for r in rows if r["id"] == curprov), None)
762
+ curmodel = ""
763
+ try:
764
+ cfg_text = (Path.home() / ".codex" / "config.toml").read_text(encoding="utf-8")
765
+ m = re.search(r'^\s*model\s*=\s*"([^"]+)"', cfg_text, re.M)
766
+ if m:
767
+ curmodel = m.group(1)
768
+ except Exception:
769
+ pass
770
+ if not curmodel and currow:
771
+ curmodel = currow["model"]
772
+
773
+ if f"{curprov}|{curmodel}" == f"{selprov}|{selmodel}":
774
+ reviewers = [f"{curprov}|{curmodel}"]
775
+ else:
776
+ reviewers = [f"{curprov}|{curmodel}", f"{selprov}|{selmodel}"]
777
+
778
+ # ---- key/base_url checks ----
779
+ for rv in reviewers:
780
+ rprov = rv.split("|", 1)[0]
781
+ row = next((r for r in rows if r["id"] == rprov), None)
782
+ if row is None:
783
+ continue
784
+ if row["has_key"] != "1":
785
+ print(
786
+ f"[跨模型审查] provider [{rprov}] 未配置 key。请补 key 并写回:"
787
+ f"python {Path(__file__).name} -SetKey {rprov}:<你的key> -KeyFile {keyfile}",
788
+ file=sys.stderr,
789
+ )
790
+ return 1
791
+ if not row["base_url"]:
792
+ print(f"[跨模型审查] {rprov} 未配置 base_url。", file=sys.stderr)
793
+ return 1
794
+
795
+ # ---- fast direct-API path (default; two independent models) ----
796
+ if args["mode"] == "api":
797
+ if not args["provider"] and not args["model"]:
798
+ # default: two INDEPENDENT providers (current + first other keyed)
799
+ reviewers = [f"{curprov}|{curmodel}"]
800
+ for r in rows:
801
+ if r["id"] != curprov and r["has_key"] == "1":
802
+ reviewers.append(f"{r['id']}|{r['model']}")
803
+ selprov, selmodel = r["id"], r["model"]
804
+ break
805
+ prompt = build_api_prompt(repo, args["task"], args.get("base", ""), args["scope"])
806
+ nrev = len(reviewers)
807
+ t0 = time.time()
808
+ with tempfile.TemporaryDirectory(prefix="review-api-") as td:
809
+ tmpdir = Path(td)
810
+ with concurrent.futures.ThreadPoolExecutor(max_workers=nrev) as ex:
811
+ futures = [
812
+ ex.submit(run_api_reviewer, i + 1, rv, rows, prompt, keyfile,
813
+ int(args.get("timeout", 300)), tmpdir / f"out-{i + 1}")
814
+ for i, rv in enumerate(reviewers)
815
+ ]
816
+ for f in futures:
817
+ f.result()
818
+ output = write_merged_report(
819
+ args, repo, reviewers, tmpdir, curmodel, curprov, selmodel, selprov,
820
+ f"直连API({nrev} 个独立模型)",
821
+ )
822
+ elapsed = time.time() - t0
823
+ print(f"跨模型审查完成(独立模型数={nrev},耗时 {elapsed:.1f}s)-> {output}")
824
+ return 0
825
+
826
+ # ---- build prompt ----
827
+ prompt = build_prompt(repo, args["task"], args.get("base", ""), args["scope"])
828
+
829
+ # ---- run reviewers in parallel ----
830
+ nrev = len(reviewers)
831
+ with tempfile.TemporaryDirectory(prefix="review-") as td:
832
+ tmpdir = Path(td)
833
+ with concurrent.futures.ThreadPoolExecutor(max_workers=nrev) as ex:
834
+ futures = [
835
+ ex.submit(run_reviewer, i + 1, rv, args, rows, repo, prompt, tmpdir, keyfile)
836
+ for i, rv in enumerate(reviewers)
837
+ ]
838
+ for f in futures:
839
+ f.result()
840
+
841
+ # ---- merge + write report ----
842
+ output = write_merged_report(
843
+ args, repo, reviewers, tmpdir, curmodel, curprov, selmodel, selprov,
844
+ f"CLI({cli})",
845
+ )
846
+ print(f"跨模型审查完成(审查者数={nrev})-> {output}")
847
+ return 0
848
+
849
+
850
+ if __name__ == "__main__":
851
+ sys.exit(main())