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