mirror of
https://github.com/cexll/myclaude.git
synced 2026-02-05 02:30:26 +08:00
Compare commits
24 Commits
v4.2.2
...
v4.7-alpha
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b172343235 | ||
|
|
c8a652ec15 | ||
|
|
12e47affa9 | ||
|
|
612150f72e | ||
|
|
77d9870094 | ||
|
|
c96c07be2a | ||
|
|
cee467fc0e | ||
|
|
71305da77e | ||
|
|
c4021cf58a | ||
|
|
9a18a03061 | ||
|
|
b5183c7711 | ||
|
|
3fab18a6bb | ||
|
|
12af992d8c | ||
|
|
bbd2f50c38 | ||
|
|
3f7652f992 | ||
|
|
2cbe36b532 | ||
|
|
fdb152872d | ||
|
|
916b970665 | ||
|
|
10070a9bef | ||
|
|
b18439f268 | ||
|
|
4230479ff4 | ||
|
|
18c26a252a | ||
|
|
f6fc9a338f | ||
|
|
6223d59042 |
@@ -175,6 +175,87 @@
|
||||
"skills": [
|
||||
"./skills/SKILL.md"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "codex-cli",
|
||||
"source": "./skills/codex/",
|
||||
"description": "Execute Codex CLI for code analysis, refactoring, and automated code changes with file references (@syntax) and structured output",
|
||||
"version": "1.0.0",
|
||||
"author": {
|
||||
"name": "Claude Code Dev Workflows",
|
||||
"url": "https://github.com/cexll/myclaude"
|
||||
},
|
||||
"homepage": "https://github.com/cexll/myclaude",
|
||||
"repository": "https://github.com/cexll/myclaude",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"codex",
|
||||
"code-analysis",
|
||||
"refactoring",
|
||||
"automation",
|
||||
"gpt-5",
|
||||
"ai-coding"
|
||||
],
|
||||
"category": "essentials",
|
||||
"strict": false,
|
||||
"skills": [
|
||||
"./SKILL.md"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "gemini-cli",
|
||||
"source": "./skills/gemini/",
|
||||
"description": "Execute Gemini CLI for AI-powered code analysis and generation with Google's latest Gemini models",
|
||||
"version": "1.0.0",
|
||||
"author": {
|
||||
"name": "Claude Code Dev Workflows",
|
||||
"url": "https://github.com/cexll/myclaude"
|
||||
},
|
||||
"homepage": "https://github.com/cexll/myclaude",
|
||||
"repository": "https://github.com/cexll/myclaude",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"gemini",
|
||||
"google-ai",
|
||||
"code-analysis",
|
||||
"code-generation",
|
||||
"ai-reasoning"
|
||||
],
|
||||
"category": "essentials",
|
||||
"strict": false,
|
||||
"skills": [
|
||||
"./SKILL.md"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "dev-workflow",
|
||||
"source": "./dev-workflow/",
|
||||
"description": "Minimal lightweight development workflow with requirements clarification, parallel codex execution, and mandatory 90% test coverage",
|
||||
"version": "1.0.0",
|
||||
"author": {
|
||||
"name": "Claude Code Dev Workflows",
|
||||
"url": "https://github.com/cexll/myclaude"
|
||||
},
|
||||
"homepage": "https://github.com/cexll/myclaude",
|
||||
"repository": "https://github.com/cexll/myclaude",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"dev",
|
||||
"workflow",
|
||||
"codex",
|
||||
"testing",
|
||||
"coverage",
|
||||
"concurrent",
|
||||
"lightweight"
|
||||
],
|
||||
"category": "workflows",
|
||||
"strict": false,
|
||||
"commands": [
|
||||
"./commands/dev.md"
|
||||
],
|
||||
"agents": [
|
||||
"./agents/dev-plan-generator.md"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
104
.github/workflows/release.yml
vendored
Normal file
104
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,104 @@
|
||||
name: Release codex-wrapper
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.21'
|
||||
|
||||
- name: Run tests
|
||||
working-directory: codex-wrapper
|
||||
run: go test -v -coverprofile=cover.out ./...
|
||||
|
||||
- name: Check coverage
|
||||
working-directory: codex-wrapper
|
||||
run: |
|
||||
go tool cover -func=cover.out | grep total
|
||||
COVERAGE=$(go tool cover -func=cover.out | grep total | awk '{print $3}' | sed 's/%//')
|
||||
echo "Coverage: ${COVERAGE}%"
|
||||
|
||||
build:
|
||||
name: Build
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- goos: linux
|
||||
goarch: amd64
|
||||
- goos: linux
|
||||
goarch: arm64
|
||||
- goos: darwin
|
||||
goarch: amd64
|
||||
- goos: darwin
|
||||
goarch: arm64
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.21'
|
||||
|
||||
- name: Build binary
|
||||
working-directory: codex-wrapper
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
CGO_ENABLED: 0
|
||||
run: |
|
||||
VERSION=${GITHUB_REF#refs/tags/}
|
||||
OUTPUT_NAME=codex-wrapper-${{ matrix.goos }}-${{ matrix.goarch }}
|
||||
go build -ldflags="-s -w -X main.version=${VERSION}" -o ${OUTPUT_NAME} .
|
||||
chmod +x ${OUTPUT_NAME}
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: codex-wrapper-${{ matrix.goos }}-${{ matrix.goarch }}
|
||||
path: codex-wrapper/codex-wrapper-${{ matrix.goos }}-${{ matrix.goarch }}
|
||||
|
||||
release:
|
||||
name: Create Release
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Prepare release files
|
||||
run: |
|
||||
mkdir -p release
|
||||
find artifacts -type f -name "codex-wrapper-*" -exec mv {} release/ \;
|
||||
cp install.sh release/
|
||||
ls -la release/
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: release/*
|
||||
generate_release_notes: true
|
||||
draft: false
|
||||
prerelease: false
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,4 +1,3 @@
|
||||
CLAUDE.md
|
||||
.claude/
|
||||
|
||||
|
||||
.claude-trace
|
||||
|
||||
15
README.md
15
README.md
@@ -2,7 +2,7 @@
|
||||
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://claude.ai/code)
|
||||
[](https://github.com/cexll/myclaude)
|
||||
[](https://github.com/cexll/myclaude)
|
||||
[](https://docs.claude.com/en/docs/claude-code/plugins)
|
||||
|
||||
> Enterprise-grade agile development automation with AI-powered multi-agent orchestration
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
**Plugin System (Recommended)**
|
||||
```bash
|
||||
/plugin github.com/cexll/myclaude
|
||||
/plugin marketplace add cexll/myclaude
|
||||
```
|
||||
|
||||
**Traditional Installation**
|
||||
@@ -44,6 +44,8 @@ make install
|
||||
|--------|-------------|--------------|
|
||||
| **[bmad-agile-workflow](docs/BMAD-WORKFLOW.md)** | Complete BMAD methodology with 6 specialized agents | `/bmad-pilot` |
|
||||
| **[requirements-driven-workflow](docs/REQUIREMENTS-WORKFLOW.md)** | Streamlined requirements-to-code workflow | `/requirements-pilot` |
|
||||
| **[dev-workflow](dev-workflow/README.md)** | Extreme lightweight end-to-end development workflow | `/dev` |
|
||||
| **[codex-wrapper](codex-wrapper/)** | Go binary wrapper for Codex CLI integration | `codex-wrapper` |
|
||||
| **[development-essentials](docs/DEVELOPMENT-COMMANDS.md)** | Core development slash commands | `/code` `/debug` `/test` `/optimize` |
|
||||
| **[advanced-ai-agents](docs/ADVANCED-AGENTS.md)** | GPT-5 deep reasoning integration | Agent: `gpt5` |
|
||||
| **[requirements-clarity](docs/REQUIREMENTS-CLARITY.md)** | Automated requirements clarification with 100-point scoring | Auto-activated skill |
|
||||
@@ -88,6 +90,11 @@ make install
|
||||
|
||||
## 🛠️ Installation Methods
|
||||
|
||||
**Codex Wrapper** (Go binary for Codex CLI)
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/chenwenjie/myclaude/master/install.sh | bash
|
||||
```
|
||||
|
||||
**Method 1: Plugin Install** (One command)
|
||||
```bash
|
||||
/plugin install bmad-agile-workflow
|
||||
@@ -101,8 +108,8 @@ make deploy-all # Everything
|
||||
```
|
||||
|
||||
**Method 3: Manual Setup**
|
||||
- Copy `/commands/*.md` to `~/.config/claude/commands/`
|
||||
- Copy `/agents/*.md` to `~/.config/claude/agents/`
|
||||
- Copy `./commands/*.md` to `~/.config/claude/commands/`
|
||||
- Copy `./agents/*.md` to `~/.config/claude/agents/`
|
||||
|
||||
Run `make help` for all options.
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://claude.ai/code)
|
||||
[](https://github.com/cexll/myclaude)
|
||||
[](https://github.com/cexll/myclaude)
|
||||
[](https://docs.claude.com/en/docs/claude-code/plugins)
|
||||
|
||||
> 企业级敏捷开发自动化与 AI 驱动的多智能体编排
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
**插件系统(推荐)**
|
||||
```bash
|
||||
/plugin github.com/cexll/myclaude
|
||||
/plugin marketplace add cexll/myclaude
|
||||
```
|
||||
|
||||
**传统安装**
|
||||
@@ -44,6 +44,7 @@ make install
|
||||
|------|------|---------|
|
||||
| **[bmad-agile-workflow](docs/BMAD-WORKFLOW.md)** | 完整 BMAD 方法论,包含6个专业智能体 | `/bmad-pilot` |
|
||||
| **[requirements-driven-workflow](docs/REQUIREMENTS-WORKFLOW.md)** | 精简的需求到代码工作流 | `/requirements-pilot` |
|
||||
| **[dev-workflow](dev-workflow/README.md)** | 极简端到端开发工作流 | `/dev` |
|
||||
| **[development-essentials](docs/DEVELOPMENT-COMMANDS.md)** | 核心开发斜杠命令 | `/code` `/debug` `/test` `/optimize` |
|
||||
| **[advanced-ai-agents](docs/ADVANCED-AGENTS.md)** | GPT-5 深度推理集成 | 智能体: `gpt5` |
|
||||
| **[requirements-clarity](docs/REQUIREMENTS-CLARITY.md)** | 自动需求澄清,100分制质量评分 | 自动激活技能 |
|
||||
@@ -101,8 +102,8 @@ make deploy-all # 全部安装
|
||||
```
|
||||
|
||||
**方式3: 手动安装**
|
||||
- 复制 `/commands/*.md` 到 `~/.config/claude/commands/`
|
||||
- 复制 `/agents/*.md` 到 `~/.config/claude/agents/`
|
||||
- 复制 `./commands/*.md` 到 `~/.config/claude/commands/`
|
||||
- 复制 `./agents/*.md` 到 `~/.config/claude/agents/`
|
||||
|
||||
运行 `make help` 查看所有选项。
|
||||
|
||||
|
||||
3
codex-wrapper/go.mod
Normal file
3
codex-wrapper/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module codex-wrapper
|
||||
|
||||
go 1.25.3
|
||||
492
codex-wrapper/main.go
Normal file
492
codex-wrapper/main.go
Normal file
@@ -0,0 +1,492 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
version = "1.0.0"
|
||||
defaultWorkdir = "."
|
||||
defaultTimeout = 7200 // seconds
|
||||
forceKillDelay = 5 // seconds
|
||||
)
|
||||
|
||||
// Test hooks for dependency injection
|
||||
var (
|
||||
stdinReader io.Reader = os.Stdin
|
||||
isTerminalFn = defaultIsTerminal
|
||||
codexCommand = "codex"
|
||||
)
|
||||
|
||||
// Config holds CLI configuration
|
||||
type Config struct {
|
||||
Mode string // "new" or "resume"
|
||||
Task string
|
||||
SessionID string
|
||||
WorkDir string
|
||||
ExplicitStdin bool
|
||||
Timeout int
|
||||
}
|
||||
|
||||
// JSONEvent represents a Codex JSON output event
|
||||
type JSONEvent struct {
|
||||
Type string `json:"type"`
|
||||
ThreadID string `json:"thread_id,omitempty"`
|
||||
Item *EventItem `json:"item,omitempty"`
|
||||
}
|
||||
|
||||
// EventItem represents the item field in a JSON event
|
||||
type EventItem struct {
|
||||
Type string `json:"type"`
|
||||
Text interface{} `json:"text"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
exitCode := run()
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
|
||||
// run is the main logic, returns exit code for testability
|
||||
func run() int {
|
||||
// Handle --version and --help first
|
||||
if len(os.Args) > 1 {
|
||||
switch os.Args[1] {
|
||||
case "--version", "-v":
|
||||
fmt.Printf("codex-wrapper version %s\n", version)
|
||||
return 0
|
||||
case "--help", "-h":
|
||||
printHelp()
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
logInfo("Script started")
|
||||
|
||||
cfg, err := parseArgs()
|
||||
if err != nil {
|
||||
logError(err.Error())
|
||||
return 1
|
||||
}
|
||||
logInfo(fmt.Sprintf("Parsed args: mode=%s, task_len=%d", cfg.Mode, len(cfg.Task)))
|
||||
|
||||
timeoutSec := resolveTimeout()
|
||||
logInfo(fmt.Sprintf("Timeout: %ds", timeoutSec))
|
||||
cfg.Timeout = timeoutSec
|
||||
|
||||
// Determine task text and stdin mode
|
||||
var taskText string
|
||||
var piped bool
|
||||
|
||||
if cfg.ExplicitStdin {
|
||||
logInfo("Explicit stdin mode: reading task from stdin")
|
||||
data, err := io.ReadAll(stdinReader)
|
||||
if err != nil {
|
||||
logError("Failed to read stdin: " + err.Error())
|
||||
return 1
|
||||
}
|
||||
taskText = string(data)
|
||||
if taskText == "" {
|
||||
logError("Explicit stdin mode requires task input from stdin")
|
||||
return 1
|
||||
}
|
||||
piped = !isTerminal()
|
||||
} else {
|
||||
pipedTask := readPipedTask()
|
||||
piped = pipedTask != ""
|
||||
if piped {
|
||||
taskText = pipedTask
|
||||
} else {
|
||||
taskText = cfg.Task
|
||||
}
|
||||
}
|
||||
|
||||
useStdin := cfg.ExplicitStdin || shouldUseStdin(taskText, piped)
|
||||
|
||||
if useStdin {
|
||||
var reasons []string
|
||||
if piped {
|
||||
reasons = append(reasons, "piped input")
|
||||
}
|
||||
if cfg.ExplicitStdin {
|
||||
reasons = append(reasons, "explicit \"-\"")
|
||||
}
|
||||
if strings.Contains(taskText, "\n") {
|
||||
reasons = append(reasons, "newline")
|
||||
}
|
||||
if strings.Contains(taskText, "\\") {
|
||||
reasons = append(reasons, "backslash")
|
||||
}
|
||||
if len(taskText) > 800 {
|
||||
reasons = append(reasons, "length>800")
|
||||
}
|
||||
if len(reasons) > 0 {
|
||||
logWarn(fmt.Sprintf("Using stdin mode for task due to: %s", strings.Join(reasons, ", ")))
|
||||
}
|
||||
}
|
||||
|
||||
targetArg := taskText
|
||||
if useStdin {
|
||||
targetArg = "-"
|
||||
}
|
||||
|
||||
codexArgs := buildCodexArgs(cfg, targetArg)
|
||||
logInfo("codex running...")
|
||||
|
||||
message, threadID, exitCode := runCodexProcess(codexArgs, taskText, useStdin, cfg.Timeout)
|
||||
|
||||
if exitCode != 0 {
|
||||
return exitCode
|
||||
}
|
||||
|
||||
// Output agent_message
|
||||
fmt.Println(message)
|
||||
|
||||
// Output session_id if present
|
||||
if threadID != "" {
|
||||
fmt.Printf("\n---\nSESSION_ID: %s\n", threadID)
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
func parseArgs() (*Config, error) {
|
||||
args := os.Args[1:]
|
||||
if len(args) == 0 {
|
||||
return nil, fmt.Errorf("task required")
|
||||
}
|
||||
|
||||
cfg := &Config{
|
||||
WorkDir: defaultWorkdir,
|
||||
}
|
||||
|
||||
// Check for resume mode
|
||||
if args[0] == "resume" {
|
||||
if len(args) < 3 {
|
||||
return nil, fmt.Errorf("resume mode requires: resume <session_id> <task>")
|
||||
}
|
||||
cfg.Mode = "resume"
|
||||
cfg.SessionID = args[1]
|
||||
cfg.Task = args[2]
|
||||
cfg.ExplicitStdin = (args[2] == "-")
|
||||
if len(args) > 3 {
|
||||
cfg.WorkDir = args[3]
|
||||
}
|
||||
} else {
|
||||
cfg.Mode = "new"
|
||||
cfg.Task = args[0]
|
||||
cfg.ExplicitStdin = (args[0] == "-")
|
||||
if len(args) > 1 {
|
||||
cfg.WorkDir = args[1]
|
||||
}
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func readPipedTask() string {
|
||||
if isTerminal() {
|
||||
logInfo("Stdin is tty, skipping pipe read")
|
||||
return ""
|
||||
}
|
||||
logInfo("Reading from stdin pipe...")
|
||||
data, err := io.ReadAll(stdinReader)
|
||||
if err != nil || len(data) == 0 {
|
||||
logInfo("Stdin pipe returned empty data")
|
||||
return ""
|
||||
}
|
||||
logInfo(fmt.Sprintf("Read %d bytes from stdin pipe", len(data)))
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func shouldUseStdin(taskText string, piped bool) bool {
|
||||
if piped {
|
||||
return true
|
||||
}
|
||||
if strings.Contains(taskText, "\n") {
|
||||
return true
|
||||
}
|
||||
if strings.Contains(taskText, "\\") {
|
||||
return true
|
||||
}
|
||||
if len(taskText) > 800 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func buildCodexArgs(cfg *Config, targetArg string) []string {
|
||||
if cfg.Mode == "resume" {
|
||||
return []string{
|
||||
"e",
|
||||
"--skip-git-repo-check",
|
||||
"--json",
|
||||
"resume",
|
||||
cfg.SessionID,
|
||||
targetArg,
|
||||
}
|
||||
}
|
||||
return []string{
|
||||
"e",
|
||||
"--skip-git-repo-check",
|
||||
"-C", cfg.WorkDir,
|
||||
"--json",
|
||||
targetArg,
|
||||
}
|
||||
}
|
||||
|
||||
func runCodexProcess(codexArgs []string, taskText string, useStdin bool, timeoutSec int) (message, threadID string, exitCode int) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSec)*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cmd := exec.CommandContext(ctx, codexCommand, codexArgs...)
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
// Setup stdin if needed
|
||||
var stdinPipe io.WriteCloser
|
||||
var err error
|
||||
if useStdin {
|
||||
stdinPipe, err = cmd.StdinPipe()
|
||||
if err != nil {
|
||||
logError("Failed to create stdin pipe: " + err.Error())
|
||||
return "", "", 1
|
||||
}
|
||||
}
|
||||
|
||||
// Setup stdout
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
logError("Failed to create stdout pipe: " + err.Error())
|
||||
return "", "", 1
|
||||
}
|
||||
|
||||
logInfo(fmt.Sprintf("Starting codex with args: codex %s...", strings.Join(codexArgs[:min(5, len(codexArgs))], " ")))
|
||||
|
||||
// Start process
|
||||
if err := cmd.Start(); err != nil {
|
||||
if strings.Contains(err.Error(), "executable file not found") {
|
||||
logError("codex command not found in PATH")
|
||||
return "", "", 127
|
||||
}
|
||||
logError("Failed to start codex: " + err.Error())
|
||||
return "", "", 1
|
||||
}
|
||||
logInfo(fmt.Sprintf("Process started with PID: %d", cmd.Process.Pid))
|
||||
|
||||
// Write to stdin if needed
|
||||
if useStdin && stdinPipe != nil {
|
||||
logInfo(fmt.Sprintf("Writing %d chars to stdin...", len(taskText)))
|
||||
go func() {
|
||||
defer stdinPipe.Close()
|
||||
io.WriteString(stdinPipe, taskText)
|
||||
}()
|
||||
logInfo("Stdin closed")
|
||||
}
|
||||
|
||||
// Setup signal handling
|
||||
sigCh := make(chan os.Signal, 1)
|
||||
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
|
||||
go func() {
|
||||
sig := <-sigCh
|
||||
logError(fmt.Sprintf("Received signal: %v", sig))
|
||||
if cmd.Process != nil {
|
||||
cmd.Process.Signal(syscall.SIGTERM)
|
||||
time.AfterFunc(time.Duration(forceKillDelay)*time.Second, func() {
|
||||
if cmd.Process != nil {
|
||||
cmd.Process.Kill()
|
||||
}
|
||||
})
|
||||
}
|
||||
}()
|
||||
|
||||
logInfo("Reading stdout...")
|
||||
|
||||
// Parse JSON stream
|
||||
message, threadID = parseJSONStream(stdout)
|
||||
|
||||
// Wait for process to complete
|
||||
err = cmd.Wait()
|
||||
|
||||
// Check for timeout
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
logError("Codex execution timeout")
|
||||
if cmd.Process != nil {
|
||||
cmd.Process.Kill()
|
||||
}
|
||||
return "", "", 124
|
||||
}
|
||||
|
||||
// Check exit code
|
||||
if err != nil {
|
||||
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
code := exitErr.ExitCode()
|
||||
logError(fmt.Sprintf("Codex exited with status %d", code))
|
||||
return "", "", code
|
||||
}
|
||||
logError("Codex error: " + err.Error())
|
||||
return "", "", 1
|
||||
}
|
||||
|
||||
if message == "" {
|
||||
logError("Codex completed without agent_message output")
|
||||
return "", "", 1
|
||||
}
|
||||
|
||||
return message, threadID, 0
|
||||
}
|
||||
|
||||
func parseJSONStream(r io.Reader) (message, threadID string) {
|
||||
scanner := bufio.NewScanner(r)
|
||||
// Set larger buffer for long lines
|
||||
buf := make([]byte, 0, 64*1024)
|
||||
scanner.Buffer(buf, 1024*1024)
|
||||
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
var event JSONEvent
|
||||
if err := json.Unmarshal([]byte(line), &event); err != nil {
|
||||
logWarn(fmt.Sprintf("Failed to parse line: %s", truncate(line, 100)))
|
||||
continue
|
||||
}
|
||||
|
||||
// Capture thread_id
|
||||
if event.Type == "thread.started" {
|
||||
threadID = event.ThreadID
|
||||
}
|
||||
|
||||
// Capture agent_message
|
||||
if event.Type == "item.completed" && event.Item != nil {
|
||||
if event.Item.Type == "agent_message" {
|
||||
text := normalizeText(event.Item.Text)
|
||||
if text != "" {
|
||||
message = text
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
logWarn("Scanner error: " + err.Error())
|
||||
}
|
||||
|
||||
return message, threadID
|
||||
}
|
||||
|
||||
func normalizeText(text interface{}) string {
|
||||
switch v := text.(type) {
|
||||
case string:
|
||||
return v
|
||||
case []interface{}:
|
||||
var sb strings.Builder
|
||||
for _, item := range v {
|
||||
if s, ok := item.(string); ok {
|
||||
sb.WriteString(s)
|
||||
}
|
||||
}
|
||||
return sb.String()
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func resolveTimeout() int {
|
||||
raw := os.Getenv("CODEX_TIMEOUT")
|
||||
if raw == "" {
|
||||
return defaultTimeout
|
||||
}
|
||||
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil || parsed <= 0 {
|
||||
logWarn(fmt.Sprintf("Invalid CODEX_TIMEOUT '%s', falling back to %ds", raw, defaultTimeout))
|
||||
return defaultTimeout
|
||||
}
|
||||
|
||||
// Environment variable is in milliseconds if > 10000, convert to seconds
|
||||
if parsed > 10000 {
|
||||
return parsed / 1000
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func defaultIsTerminal() bool {
|
||||
fi, err := os.Stdin.Stat()
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
return (fi.Mode() & os.ModeCharDevice) != 0
|
||||
}
|
||||
|
||||
func isTerminal() bool {
|
||||
return isTerminalFn()
|
||||
}
|
||||
|
||||
func getEnv(key, defaultValue string) string {
|
||||
if val := os.Getenv(key); val != "" {
|
||||
return val
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
func truncate(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return s[:maxLen] + "..."
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func logInfo(msg string) {
|
||||
fmt.Fprintf(os.Stderr, "INFO: %s\n", msg)
|
||||
}
|
||||
|
||||
func logWarn(msg string) {
|
||||
fmt.Fprintf(os.Stderr, "WARN: %s\n", msg)
|
||||
}
|
||||
|
||||
func logError(msg string) {
|
||||
fmt.Fprintf(os.Stderr, "ERROR: %s\n", msg)
|
||||
}
|
||||
|
||||
func printHelp() {
|
||||
help := `codex-wrapper - Go wrapper for Codex CLI
|
||||
|
||||
Usage:
|
||||
codex-wrapper "task" [workdir]
|
||||
codex-wrapper - [workdir] Read task from stdin
|
||||
codex-wrapper resume <session_id> "task" [workdir]
|
||||
codex-wrapper resume <session_id> - [workdir]
|
||||
codex-wrapper --version
|
||||
codex-wrapper --help
|
||||
|
||||
Environment Variables:
|
||||
CODEX_TIMEOUT Timeout in milliseconds (default: 7200000)
|
||||
|
||||
Exit Codes:
|
||||
0 Success
|
||||
1 General error (missing args, no output)
|
||||
124 Timeout
|
||||
127 codex command not found
|
||||
130 Interrupted (Ctrl+C)
|
||||
* Passthrough from codex process`
|
||||
fmt.Println(help)
|
||||
}
|
||||
748
codex-wrapper/main_test.go
Normal file
748
codex-wrapper/main_test.go
Normal file
@@ -0,0 +1,748 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Helper to reset test hooks
|
||||
func resetTestHooks() {
|
||||
stdinReader = os.Stdin
|
||||
isTerminalFn = defaultIsTerminal
|
||||
codexCommand = "codex"
|
||||
}
|
||||
|
||||
func TestParseArgs_NewMode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
want *Config
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "simple task",
|
||||
args: []string{"codex-wrapper", "analyze code"},
|
||||
want: &Config{
|
||||
Mode: "new",
|
||||
Task: "analyze code",
|
||||
WorkDir: ".",
|
||||
ExplicitStdin: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "task with workdir",
|
||||
args: []string{"codex-wrapper", "analyze code", "/path/to/dir"},
|
||||
want: &Config{
|
||||
Mode: "new",
|
||||
Task: "analyze code",
|
||||
WorkDir: "/path/to/dir",
|
||||
ExplicitStdin: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "explicit stdin mode",
|
||||
args: []string{"codex-wrapper", "-"},
|
||||
want: &Config{
|
||||
Mode: "new",
|
||||
Task: "-",
|
||||
WorkDir: ".",
|
||||
ExplicitStdin: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "stdin with workdir",
|
||||
args: []string{"codex-wrapper", "-", "/some/dir"},
|
||||
want: &Config{
|
||||
Mode: "new",
|
||||
Task: "-",
|
||||
WorkDir: "/some/dir",
|
||||
ExplicitStdin: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "no args",
|
||||
args: []string{"codex-wrapper"},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
os.Args = tt.args
|
||||
|
||||
cfg, err := parseArgs()
|
||||
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Errorf("parseArgs() expected error, got nil")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("parseArgs() unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if cfg.Mode != tt.want.Mode {
|
||||
t.Errorf("Mode = %v, want %v", cfg.Mode, tt.want.Mode)
|
||||
}
|
||||
if cfg.Task != tt.want.Task {
|
||||
t.Errorf("Task = %v, want %v", cfg.Task, tt.want.Task)
|
||||
}
|
||||
if cfg.WorkDir != tt.want.WorkDir {
|
||||
t.Errorf("WorkDir = %v, want %v", cfg.WorkDir, tt.want.WorkDir)
|
||||
}
|
||||
if cfg.ExplicitStdin != tt.want.ExplicitStdin {
|
||||
t.Errorf("ExplicitStdin = %v, want %v", cfg.ExplicitStdin, tt.want.ExplicitStdin)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseArgs_ResumeMode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
want *Config
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "resume with task",
|
||||
args: []string{"codex-wrapper", "resume", "session-123", "continue task"},
|
||||
want: &Config{
|
||||
Mode: "resume",
|
||||
SessionID: "session-123",
|
||||
Task: "continue task",
|
||||
WorkDir: ".",
|
||||
ExplicitStdin: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "resume with workdir",
|
||||
args: []string{"codex-wrapper", "resume", "session-456", "task", "/work"},
|
||||
want: &Config{
|
||||
Mode: "resume",
|
||||
SessionID: "session-456",
|
||||
Task: "task",
|
||||
WorkDir: "/work",
|
||||
ExplicitStdin: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "resume with stdin",
|
||||
args: []string{"codex-wrapper", "resume", "session-789", "-"},
|
||||
want: &Config{
|
||||
Mode: "resume",
|
||||
SessionID: "session-789",
|
||||
Task: "-",
|
||||
WorkDir: ".",
|
||||
ExplicitStdin: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "resume missing session_id",
|
||||
args: []string{"codex-wrapper", "resume"},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "resume missing task",
|
||||
args: []string{"codex-wrapper", "resume", "session-123"},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
os.Args = tt.args
|
||||
|
||||
cfg, err := parseArgs()
|
||||
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Errorf("parseArgs() expected error, got nil")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("parseArgs() unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if cfg.Mode != tt.want.Mode {
|
||||
t.Errorf("Mode = %v, want %v", cfg.Mode, tt.want.Mode)
|
||||
}
|
||||
if cfg.SessionID != tt.want.SessionID {
|
||||
t.Errorf("SessionID = %v, want %v", cfg.SessionID, tt.want.SessionID)
|
||||
}
|
||||
if cfg.Task != tt.want.Task {
|
||||
t.Errorf("Task = %v, want %v", cfg.Task, tt.want.Task)
|
||||
}
|
||||
if cfg.WorkDir != tt.want.WorkDir {
|
||||
t.Errorf("WorkDir = %v, want %v", cfg.WorkDir, tt.want.WorkDir)
|
||||
}
|
||||
if cfg.ExplicitStdin != tt.want.ExplicitStdin {
|
||||
t.Errorf("ExplicitStdin = %v, want %v", cfg.ExplicitStdin, tt.want.ExplicitStdin)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldUseStdin(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
task string
|
||||
piped bool
|
||||
want bool
|
||||
}{
|
||||
{"simple task", "analyze code", false, false},
|
||||
{"piped input", "analyze code", true, true},
|
||||
{"contains newline", "line1\nline2", false, true},
|
||||
{"contains backslash", "path\\to\\file", false, true},
|
||||
{"long task", strings.Repeat("a", 801), false, true},
|
||||
{"exactly 800 chars", strings.Repeat("a", 800), false, false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := shouldUseStdin(tt.task, tt.piped)
|
||||
if got != tt.want {
|
||||
t.Errorf("shouldUseStdin(%q, %v) = %v, want %v", truncate(tt.task, 20), tt.piped, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildCodexArgs_NewMode(t *testing.T) {
|
||||
cfg := &Config{
|
||||
Mode: "new",
|
||||
WorkDir: "/test/dir",
|
||||
}
|
||||
|
||||
args := buildCodexArgs(cfg, "my task")
|
||||
|
||||
expected := []string{
|
||||
"e",
|
||||
"--skip-git-repo-check",
|
||||
"-C", "/test/dir",
|
||||
"--json",
|
||||
"my task",
|
||||
}
|
||||
|
||||
if len(args) != len(expected) {
|
||||
t.Errorf("buildCodexArgs() returned %d args, want %d", len(args), len(expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, arg := range args {
|
||||
if arg != expected[i] {
|
||||
t.Errorf("buildCodexArgs()[%d] = %v, want %v", i, arg, expected[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildCodexArgs_ResumeMode(t *testing.T) {
|
||||
cfg := &Config{
|
||||
Mode: "resume",
|
||||
SessionID: "session-abc",
|
||||
}
|
||||
|
||||
args := buildCodexArgs(cfg, "-")
|
||||
|
||||
expected := []string{
|
||||
"e",
|
||||
"--skip-git-repo-check",
|
||||
"--json",
|
||||
"resume",
|
||||
"session-abc",
|
||||
"-",
|
||||
}
|
||||
|
||||
if len(args) != len(expected) {
|
||||
t.Errorf("buildCodexArgs() returned %d args, want %d", len(args), len(expected))
|
||||
return
|
||||
}
|
||||
|
||||
for i, arg := range args {
|
||||
if arg != expected[i] {
|
||||
t.Errorf("buildCodexArgs()[%d] = %v, want %v", i, arg, expected[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTimeout(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
envVal string
|
||||
want int
|
||||
}{
|
||||
{"empty env", "", 7200},
|
||||
{"milliseconds", "7200000", 7200},
|
||||
{"seconds", "3600", 3600},
|
||||
{"invalid", "invalid", 7200},
|
||||
{"negative", "-100", 7200},
|
||||
{"zero", "0", 7200},
|
||||
{"small milliseconds", "5000", 5000},
|
||||
{"boundary", "10000", 10000},
|
||||
{"above boundary", "10001", 10},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
os.Setenv("CODEX_TIMEOUT", tt.envVal)
|
||||
defer os.Unsetenv("CODEX_TIMEOUT")
|
||||
|
||||
got := resolveTimeout()
|
||||
if got != tt.want {
|
||||
t.Errorf("resolveTimeout() with env=%q = %v, want %v", tt.envVal, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeText(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input interface{}
|
||||
want string
|
||||
}{
|
||||
{"string", "hello world", "hello world"},
|
||||
{"string array", []interface{}{"hello", " ", "world"}, "hello world"},
|
||||
{"empty array", []interface{}{}, ""},
|
||||
{"mixed array", []interface{}{"text", 123, "more"}, "textmore"},
|
||||
{"nil", nil, ""},
|
||||
{"number", 123, ""},
|
||||
{"empty string", "", ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := normalizeText(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("normalizeText(%v) = %q, want %q", tt.input, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseJSONStream(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
wantMessage string
|
||||
wantThreadID string
|
||||
}{
|
||||
{
|
||||
name: "thread started and agent message",
|
||||
input: `{"type":"thread.started","thread_id":"abc-123"}
|
||||
{"type":"item.completed","item":{"type":"agent_message","text":"Hello world"}}`,
|
||||
wantMessage: "Hello world",
|
||||
wantThreadID: "abc-123",
|
||||
},
|
||||
{
|
||||
name: "multiple agent messages (last wins)",
|
||||
input: `{"type":"item.completed","item":{"type":"agent_message","text":"First"}}
|
||||
{"type":"item.completed","item":{"type":"agent_message","text":"Second"}}`,
|
||||
wantMessage: "Second",
|
||||
wantThreadID: "",
|
||||
},
|
||||
{
|
||||
name: "text as array",
|
||||
input: `{"type":"item.completed","item":{"type":"agent_message","text":["Hello"," ","World"]}}`,
|
||||
wantMessage: "Hello World",
|
||||
wantThreadID: "",
|
||||
},
|
||||
{
|
||||
name: "ignore other event types",
|
||||
input: `{"type":"other.event","data":"ignored"}
|
||||
{"type":"item.completed","item":{"type":"other_type","text":"ignored"}}
|
||||
{"type":"item.completed","item":{"type":"agent_message","text":"Valid"}}`,
|
||||
wantMessage: "Valid",
|
||||
wantThreadID: "",
|
||||
},
|
||||
{
|
||||
name: "empty input",
|
||||
input: "",
|
||||
wantMessage: "",
|
||||
wantThreadID: "",
|
||||
},
|
||||
{
|
||||
name: "invalid JSON (skipped)",
|
||||
input: "not valid json\n{\"type\":\"thread.started\",\"thread_id\":\"xyz\"}",
|
||||
wantMessage: "",
|
||||
wantThreadID: "xyz",
|
||||
},
|
||||
{
|
||||
name: "blank lines ignored",
|
||||
input: "\n\n{\"type\":\"thread.started\",\"thread_id\":\"test\"}\n\n",
|
||||
wantMessage: "",
|
||||
wantThreadID: "test",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r := strings.NewReader(tt.input)
|
||||
gotMessage, gotThreadID := parseJSONStream(r)
|
||||
|
||||
if gotMessage != tt.wantMessage {
|
||||
t.Errorf("parseJSONStream() message = %q, want %q", gotMessage, tt.wantMessage)
|
||||
}
|
||||
if gotThreadID != tt.wantThreadID {
|
||||
t.Errorf("parseJSONStream() threadID = %q, want %q", gotThreadID, tt.wantThreadID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetEnv(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
key string
|
||||
defaultVal string
|
||||
envVal string
|
||||
setEnv bool
|
||||
want string
|
||||
}{
|
||||
{"env set", "TEST_KEY", "default", "custom", true, "custom"},
|
||||
{"env not set", "TEST_KEY_MISSING", "default", "", false, "default"},
|
||||
{"env empty", "TEST_KEY_EMPTY", "default", "", true, "default"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
os.Unsetenv(tt.key)
|
||||
if tt.setEnv {
|
||||
os.Setenv(tt.key, tt.envVal)
|
||||
defer os.Unsetenv(tt.key)
|
||||
}
|
||||
|
||||
got := getEnv(tt.key, tt.defaultVal)
|
||||
if got != tt.want {
|
||||
t.Errorf("getEnv(%q, %q) = %q, want %q", tt.key, tt.defaultVal, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
maxLen int
|
||||
want string
|
||||
}{
|
||||
{"short string", "hello", 10, "hello"},
|
||||
{"exact length", "hello", 5, "hello"},
|
||||
{"truncate", "hello world", 5, "hello..."},
|
||||
{"empty", "", 5, ""},
|
||||
{"zero maxLen", "hello", 0, "..."},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := truncate(tt.input, tt.maxLen)
|
||||
if got != tt.want {
|
||||
t.Errorf("truncate(%q, %d) = %q, want %q", tt.input, tt.maxLen, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMin(t *testing.T) {
|
||||
tests := []struct {
|
||||
a, b, want int
|
||||
}{
|
||||
{1, 2, 1},
|
||||
{2, 1, 1},
|
||||
{5, 5, 5},
|
||||
{-1, 0, -1},
|
||||
{0, -1, -1},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run("", func(t *testing.T) {
|
||||
got := min(tt.a, tt.b)
|
||||
if got != tt.want {
|
||||
t.Errorf("min(%d, %d) = %d, want %d", tt.a, tt.b, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogFunctions(t *testing.T) {
|
||||
// Capture stderr
|
||||
oldStderr := os.Stderr
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stderr = w
|
||||
|
||||
logInfo("info message")
|
||||
logWarn("warn message")
|
||||
logError("error message")
|
||||
|
||||
w.Close()
|
||||
os.Stderr = oldStderr
|
||||
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, r)
|
||||
output := buf.String()
|
||||
|
||||
if !strings.Contains(output, "INFO: info message") {
|
||||
t.Errorf("logInfo output missing, got: %s", output)
|
||||
}
|
||||
if !strings.Contains(output, "WARN: warn message") {
|
||||
t.Errorf("logWarn output missing, got: %s", output)
|
||||
}
|
||||
if !strings.Contains(output, "ERROR: error message") {
|
||||
t.Errorf("logError output missing, got: %s", output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintHelp(t *testing.T) {
|
||||
// Capture stdout
|
||||
oldStdout := os.Stdout
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stdout = w
|
||||
|
||||
printHelp()
|
||||
|
||||
w.Close()
|
||||
os.Stdout = oldStdout
|
||||
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, r)
|
||||
output := buf.String()
|
||||
|
||||
expectedPhrases := []string{
|
||||
"codex-wrapper",
|
||||
"Usage:",
|
||||
"resume",
|
||||
"CODEX_TIMEOUT",
|
||||
"Exit Codes:",
|
||||
}
|
||||
|
||||
for _, phrase := range expectedPhrases {
|
||||
if !strings.Contains(output, phrase) {
|
||||
t.Errorf("printHelp() missing phrase %q", phrase)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tests for isTerminal with mock
|
||||
func TestIsTerminal(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mockFn func() bool
|
||||
want bool
|
||||
}{
|
||||
{"is terminal", func() bool { return true }, true},
|
||||
{"is not terminal", func() bool { return false }, false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
isTerminalFn = tt.mockFn
|
||||
got := isTerminal()
|
||||
if got != tt.want {
|
||||
t.Errorf("isTerminal() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Tests for readPipedTask with mock
|
||||
func TestReadPipedTask(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
isTerminal bool
|
||||
stdinContent string
|
||||
want string
|
||||
}{
|
||||
{"terminal mode", true, "ignored", ""},
|
||||
{"piped with data", false, "task from pipe", "task from pipe"},
|
||||
{"piped empty", false, "", ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
isTerminalFn = func() bool { return tt.isTerminal }
|
||||
stdinReader = strings.NewReader(tt.stdinContent)
|
||||
|
||||
got := readPipedTask()
|
||||
if got != tt.want {
|
||||
t.Errorf("readPipedTask() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Tests for runCodexProcess with mock command
|
||||
func TestRunCodexProcess_CommandNotFound(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
codexCommand = "nonexistent-command-xyz"
|
||||
|
||||
_, _, exitCode := runCodexProcess([]string{"arg1"}, "task", false, 10)
|
||||
|
||||
if exitCode != 127 {
|
||||
t.Errorf("runCodexProcess() exitCode = %d, want 127 for command not found", exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCodexProcess_WithEcho(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
// Use echo to simulate codex output
|
||||
codexCommand = "echo"
|
||||
|
||||
jsonOutput := `{"type":"thread.started","thread_id":"test-session"}
|
||||
{"type":"item.completed","item":{"type":"agent_message","text":"Test output"}}`
|
||||
|
||||
message, threadID, exitCode := runCodexProcess([]string{jsonOutput}, "", false, 10)
|
||||
|
||||
if exitCode != 0 {
|
||||
t.Errorf("runCodexProcess() exitCode = %d, want 0", exitCode)
|
||||
}
|
||||
if message != "Test output" {
|
||||
t.Errorf("runCodexProcess() message = %q, want %q", message, "Test output")
|
||||
}
|
||||
if threadID != "test-session" {
|
||||
t.Errorf("runCodexProcess() threadID = %q, want %q", threadID, "test-session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCodexProcess_NoMessage(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
codexCommand = "echo"
|
||||
|
||||
// Output without agent_message
|
||||
jsonOutput := `{"type":"thread.started","thread_id":"test-session"}`
|
||||
|
||||
_, _, exitCode := runCodexProcess([]string{jsonOutput}, "", false, 10)
|
||||
|
||||
if exitCode != 1 {
|
||||
t.Errorf("runCodexProcess() exitCode = %d, want 1 for no message", exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCodexProcess_WithStdin(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
// Use cat to echo stdin back
|
||||
codexCommand = "cat"
|
||||
|
||||
message, _, exitCode := runCodexProcess([]string{}, `{"type":"item.completed","item":{"type":"agent_message","text":"from stdin"}}`, true, 10)
|
||||
|
||||
if exitCode != 0 {
|
||||
t.Errorf("runCodexProcess() exitCode = %d, want 0", exitCode)
|
||||
}
|
||||
if message != "from stdin" {
|
||||
t.Errorf("runCodexProcess() message = %q, want %q", message, "from stdin")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCodexProcess_ExitError(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
// Use false command which exits with code 1
|
||||
codexCommand = "false"
|
||||
|
||||
_, _, exitCode := runCodexProcess([]string{}, "", false, 10)
|
||||
|
||||
if exitCode == 0 {
|
||||
t.Errorf("runCodexProcess() exitCode = 0, want non-zero for failed command")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultIsTerminal(t *testing.T) {
|
||||
// This test just ensures defaultIsTerminal doesn't panic
|
||||
// The actual result depends on the test environment
|
||||
_ = defaultIsTerminal()
|
||||
}
|
||||
|
||||
// Tests for run() function
|
||||
func TestRun_Version(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
os.Args = []string{"codex-wrapper", "--version"}
|
||||
exitCode := run()
|
||||
if exitCode != 0 {
|
||||
t.Errorf("run() with --version returned %d, want 0", exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_VersionShort(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
os.Args = []string{"codex-wrapper", "-v"}
|
||||
exitCode := run()
|
||||
if exitCode != 0 {
|
||||
t.Errorf("run() with -v returned %d, want 0", exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_Help(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
os.Args = []string{"codex-wrapper", "--help"}
|
||||
exitCode := run()
|
||||
if exitCode != 0 {
|
||||
t.Errorf("run() with --help returned %d, want 0", exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_HelpShort(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
os.Args = []string{"codex-wrapper", "-h"}
|
||||
exitCode := run()
|
||||
if exitCode != 0 {
|
||||
t.Errorf("run() with -h returned %d, want 0", exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_NoArgs(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
os.Args = []string{"codex-wrapper"}
|
||||
exitCode := run()
|
||||
if exitCode != 1 {
|
||||
t.Errorf("run() with no args returned %d, want 1", exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_ExplicitStdinEmpty(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
os.Args = []string{"codex-wrapper", "-"}
|
||||
stdinReader = strings.NewReader("")
|
||||
isTerminalFn = func() bool { return false }
|
||||
|
||||
exitCode := run()
|
||||
if exitCode != 1 {
|
||||
t.Errorf("run() with empty stdin returned %d, want 1", exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_CommandFails(t *testing.T) {
|
||||
defer resetTestHooks()
|
||||
|
||||
os.Args = []string{"codex-wrapper", "task"}
|
||||
stdinReader = strings.NewReader("")
|
||||
isTerminalFn = func() bool { return true }
|
||||
codexCommand = "false"
|
||||
|
||||
exitCode := run()
|
||||
if exitCode == 0 {
|
||||
t.Errorf("run() with failing command returned 0, want non-zero")
|
||||
}
|
||||
}
|
||||
163
dev-workflow/README.md
Normal file
163
dev-workflow/README.md
Normal file
@@ -0,0 +1,163 @@
|
||||
# /dev - Minimal Dev Workflow
|
||||
|
||||
## Overview
|
||||
|
||||
A freshly designed lightweight development workflow with no legacy baggage, focused on delivering high-quality code fast.
|
||||
|
||||
## Flow
|
||||
|
||||
```
|
||||
/dev trigger
|
||||
↓
|
||||
AskUserQuestion (requirements clarification)
|
||||
↓
|
||||
Codex analysis (extract key points and tasks)
|
||||
↓
|
||||
develop-doc-generator (create dev doc)
|
||||
↓
|
||||
Codex concurrent development (2–5 tasks)
|
||||
↓
|
||||
Codex testing & verification (≥90% coverage)
|
||||
↓
|
||||
Done (generate summary)
|
||||
```
|
||||
|
||||
## The 6 Steps
|
||||
|
||||
### 1. Clarify Requirements
|
||||
- Use **AskUserQuestion** to ask the user directly
|
||||
- No scoring system, no complex logic
|
||||
- 2–3 rounds of Q&A until the requirement is clear
|
||||
|
||||
### 2. Codex Analysis
|
||||
- Call codex to analyze the request
|
||||
- Extract: core functions, technical points, task list (2–5 items)
|
||||
- Output a structured analysis
|
||||
|
||||
### 3. Generate Dev Doc
|
||||
- Call the **develop-doc-generator** agent
|
||||
- Produce a single `dev-plan.md`
|
||||
- Include: task breakdown, file scope, dependencies, test commands
|
||||
|
||||
### 4. Concurrent Development
|
||||
- Work from the task list in dev-plan.md
|
||||
- Independent tasks → run in parallel
|
||||
- Conflicting tasks → run serially
|
||||
|
||||
### 5. Testing & Verification
|
||||
- Each codex task:
|
||||
- Implements the feature
|
||||
- Writes tests
|
||||
- Runs coverage
|
||||
- Reports results (≥90%)
|
||||
|
||||
### 6. Complete
|
||||
- Summarize task status
|
||||
- Record coverage
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
/dev "Implement user login with email + password"
|
||||
```
|
||||
|
||||
**No options**, fixed workflow, works out of the box.
|
||||
|
||||
## Output Structure
|
||||
|
||||
```
|
||||
.claude/specs/{feature_name}/
|
||||
└── dev-plan.md # Dev document generated by agent
|
||||
```
|
||||
|
||||
Only one file—minimal and clear.
|
||||
|
||||
## Core Components
|
||||
|
||||
### Tools
|
||||
- **AskUserQuestion**: interactive requirement clarification
|
||||
- **codex**: analysis, development, testing
|
||||
- **develop-doc-generator**: generate dev doc (subagent, saves context)
|
||||
|
||||
## Key Features
|
||||
|
||||
### ✅ Fresh Design
|
||||
- No legacy project residue
|
||||
- No complex scoring logic
|
||||
- No extra abstraction layers
|
||||
|
||||
### ✅ Minimal Orchestration
|
||||
- Orchestrator controls the flow directly
|
||||
- Only three tools/components
|
||||
- Steps are straightforward
|
||||
|
||||
### ✅ Concurrency
|
||||
- 2–5 tasks in parallel
|
||||
- Auto-detect dependencies and conflicts
|
||||
- Codex executes independently
|
||||
|
||||
### ✅ Quality Assurance
|
||||
- Enforces 90% coverage
|
||||
- Codex tests and verifies its own work
|
||||
- Automatic retry on failure
|
||||
|
||||
## Example
|
||||
|
||||
```bash
|
||||
# Trigger
|
||||
/dev "Add user login feature"
|
||||
|
||||
# Step 1: Clarify requirements
|
||||
Q: What login methods are supported?
|
||||
A: Email + password
|
||||
Q: Should login be remembered?
|
||||
A: Yes, use JWT token
|
||||
|
||||
# Step 2: Codex analysis
|
||||
Output:
|
||||
- Core: email/password login + JWT auth
|
||||
- Task 1: Backend API
|
||||
- Task 2: Password hashing
|
||||
- Task 3: Frontend form
|
||||
|
||||
# Step 3: Generate doc
|
||||
dev-plan.md generated ✓
|
||||
|
||||
# Step 4-5: Concurrent development
|
||||
[task-1] Backend API → tests → 92% ✓
|
||||
[task-2] Password hashing → tests → 95% ✓
|
||||
[task-3] Frontend form → tests → 91% ✓
|
||||
```
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
dev-workflow/
|
||||
├── README.md # This doc
|
||||
├── commands/
|
||||
│ └── dev.md # Workflow definition
|
||||
└── agents/
|
||||
└── develop-doc-generator.md # Doc generator
|
||||
```
|
||||
|
||||
Minimal structure, only three files.
|
||||
|
||||
## When to Use
|
||||
|
||||
✅ **Good for**:
|
||||
- Any feature size
|
||||
- Fast iterations
|
||||
- High test coverage needs
|
||||
- Wanting concurrent speed-up
|
||||
|
||||
## Design Principles
|
||||
|
||||
1. **KISS**: keep it simple
|
||||
2. **Disposable**: no persistent config
|
||||
3. **Quality first**: enforce 90% coverage
|
||||
4. **Concurrency first**: leverage codex
|
||||
5. **No legacy baggage**: clean-slate design
|
||||
|
||||
---
|
||||
|
||||
**Philosophy**: zero tolerance for complexity—ship the smallest usable solution, like Linus would.
|
||||
114
dev-workflow/agents/dev-plan-generator.md
Normal file
114
dev-workflow/agents/dev-plan-generator.md
Normal file
@@ -0,0 +1,114 @@
|
||||
---
|
||||
name: dev-plan-generator
|
||||
description: Use this agent when you need to generate a structured development plan document (`dev-plan.md`) that breaks down a feature into concrete implementation tasks with testing requirements and acceptance criteria. This agent should be called after requirements analysis and before actual implementation begins.\n\n<example>\nContext: User is orchestrating a feature development workflow and needs to create a development plan after Codex analysis is complete.\nuser: "Create a development plan for the user authentication feature based on the requirements and analysis"\nassistant: "I'll use the Task tool to launch the dev-plan-generator agent to create the structured development plan document."\n<commentary>\nThe user needs a dev-plan.md document generated from requirements and analysis. Use the dev-plan-generator agent to create the structured task breakdown.\n</commentary>\n</example>\n\n<example>\nContext: Orchestrator has completed requirements gathering and Codex analysis for a new feature and needs to generate the development plan before moving to implementation.\nuser: "We've completed the analysis for the payment integration feature. Generate the development plan."\nassistant: "I'm going to use the Task tool to launch the dev-plan-generator agent to create the dev-plan.md document with task breakdown and testing requirements."\n<commentary>\nThis is the step in the workflow where the development plan document needs to be generated. Use the dev-plan-generator agent to create the structured plan.\n</commentary>\n</example>\n\n<example>\nContext: User is working through a requirements-driven workflow and has just approved the technical specifications.\nuser: "The specs look good. Let's move forward with creating the implementation plan."\nassistant: "I'll use the Task tool to launch the dev-plan-generator agent to generate the dev-plan.md document with the task breakdown."\n<commentary>\nAfter spec approval, the next step is generating the development plan. Use the dev-plan-generator agent to create the structured document.\n</commentary>\n</example>
|
||||
tools: Glob, Grep, Read, Edit, Write, TodoWrite
|
||||
model: sonnet
|
||||
color: green
|
||||
---
|
||||
|
||||
You are a specialized Development Plan Document Generator. Your sole responsibility is to create structured, actionable development plan documents (`dev-plan.md`) that break down features into concrete implementation tasks.
|
||||
|
||||
## Your Role
|
||||
|
||||
You receive context from an orchestrator including:
|
||||
- Feature requirements description
|
||||
- Codex analysis results (feature highlights, task decomposition)
|
||||
- Feature name (in kebab-case format)
|
||||
|
||||
Your output is a single file: `./.claude/specs/{feature_name}/dev-plan.md`
|
||||
|
||||
## Document Structure You Must Follow
|
||||
|
||||
```markdown
|
||||
# {Feature Name} - Development Plan
|
||||
|
||||
## Overview
|
||||
[One-sentence description of core functionality]
|
||||
|
||||
## Task Breakdown
|
||||
|
||||
### Task 1: [Task Name]
|
||||
- **ID**: task-1
|
||||
- **Description**: [What needs to be done]
|
||||
- **File Scope**: [Directories or files involved, e.g., src/auth/**, tests/auth/]
|
||||
- **Dependencies**: [None or depends on task-x]
|
||||
- **Test Command**: [e.g., pytest tests/auth --cov=src/auth --cov-report=term]
|
||||
- **Test Focus**: [Scenarios to cover]
|
||||
|
||||
### Task 2: [Task Name]
|
||||
...
|
||||
|
||||
(2-5 tasks)
|
||||
|
||||
## Acceptance Criteria
|
||||
- [ ] Feature point 1
|
||||
- [ ] Feature point 2
|
||||
- [ ] All unit tests pass
|
||||
- [ ] Code coverage ≥90%
|
||||
|
||||
## Technical Notes
|
||||
- [Key technical decisions]
|
||||
- [Constraints to be aware of]
|
||||
```
|
||||
|
||||
## Generation Rules You Must Enforce
|
||||
|
||||
1. **Task Count**: Generate 2-5 tasks (no more, no less unless the feature is extremely simple or complex)
|
||||
2. **Task Requirements**: Each task MUST include:
|
||||
- Clear ID (task-1, task-2, etc.)
|
||||
- Specific description of what needs to be done
|
||||
- Explicit file scope (directories or files affected)
|
||||
- Dependency declaration ("None" or "depends on task-x")
|
||||
- Complete test command with coverage parameters
|
||||
- Testing focus points (scenarios to cover)
|
||||
3. **Task Independence**: Design tasks to be as independent as possible to enable parallel execution
|
||||
4. **Test Commands**: Must include coverage parameters (e.g., `--cov=module --cov-report=term` for pytest, `--coverage` for npm)
|
||||
5. **Coverage Threshold**: Always require ≥90% code coverage in acceptance criteria
|
||||
|
||||
## Your Workflow
|
||||
|
||||
1. **Analyze Input**: Review the requirements description and Codex analysis results
|
||||
2. **Identify Tasks**: Break down the feature into 2-5 logical, independent tasks
|
||||
3. **Determine Dependencies**: Map out which tasks depend on others (minimize dependencies)
|
||||
4. **Specify Testing**: For each task, define the exact test command and coverage requirements
|
||||
5. **Define Acceptance**: List concrete, measurable acceptance criteria including the 90% coverage requirement
|
||||
6. **Document Technical Points**: Note key technical decisions and constraints
|
||||
7. **Write File**: Use the Write tool to create `./.claude/specs/{feature_name}/dev-plan.md`
|
||||
|
||||
## Quality Checks Before Writing
|
||||
|
||||
- [ ] Task count is between 2-5
|
||||
- [ ] Every task has all 6 required fields (ID, Description, File Scope, Dependencies, Test Command, Test Focus)
|
||||
- [ ] Test commands include coverage parameters
|
||||
- [ ] Dependencies are explicitly stated
|
||||
- [ ] Acceptance criteria includes 90% coverage requirement
|
||||
- [ ] File scope is specific (not vague like "all files")
|
||||
- [ ] Testing focus is concrete (not generic like "test everything")
|
||||
|
||||
## Critical Constraints
|
||||
|
||||
- **Document Only**: You generate documentation. You do NOT execute code, run tests, or modify source files.
|
||||
- **Single Output**: You produce exactly one file: `dev-plan.md` in the correct location
|
||||
- **Path Accuracy**: The path must be `./.claude/specs/{feature_name}/dev-plan.md` where {feature_name} matches the input
|
||||
- **Language Matching**: Output language matches user input (Chinese input → Chinese doc, English input → English doc)
|
||||
- **Structured Format**: Follow the exact markdown structure provided
|
||||
|
||||
## Example Output Quality
|
||||
|
||||
Refer to the user login example in your instructions as the quality benchmark. Your outputs should have:
|
||||
- Clear, actionable task descriptions
|
||||
- Specific file paths (not generic)
|
||||
- Realistic test commands for the actual tech stack
|
||||
- Concrete testing scenarios (not abstract)
|
||||
- Measurable acceptance criteria
|
||||
- Relevant technical decisions
|
||||
|
||||
## Error Handling
|
||||
|
||||
If the input context is incomplete or unclear:
|
||||
1. Request the missing information explicitly
|
||||
2. Do NOT proceed with generating a low-quality document
|
||||
3. Do NOT make up requirements or technical details
|
||||
4. Ask for clarification on: feature scope, tech stack, testing framework, file structure
|
||||
|
||||
Remember: Your document will be used by other agents to implement the feature. Precision and completeness are critical. Every field must be filled with specific, actionable information.
|
||||
101
dev-workflow/commands/dev.md
Normal file
101
dev-workflow/commands/dev.md
Normal file
@@ -0,0 +1,101 @@
|
||||
---
|
||||
description: Extreme lightweight end-to-end development workflow with requirements clarification, parallel codex execution, and mandatory 90% test coverage
|
||||
---
|
||||
|
||||
|
||||
You are the /dev Workflow Orchestrator, an expert development workflow manager specializing in orchestrating minimal, efficient end-to-end development processes with parallel task execution and rigorous test coverage validation.
|
||||
|
||||
**Core Responsibilities**
|
||||
- Orchestrate a streamlined 6-step development workflow:
|
||||
1. Requirement clarification through targeted questioning
|
||||
2. Technical analysis using Codex
|
||||
3. Development documentation generation
|
||||
4. Parallel development execution
|
||||
5. Coverage validation (≥90% requirement)
|
||||
6. Completion summary
|
||||
|
||||
**Workflow Execution**
|
||||
- **Step 1: Requirement Clarification**
|
||||
- Use AskUserQuestion to clarify requirements directly
|
||||
- Focus questions on functional boundaries, inputs/outputs, constraints, testing
|
||||
- Iterate 2-3 rounds until clear; rely on judgment; keep questions concise
|
||||
|
||||
- **Step 2: Codex Deep Analysis (Plan Mode Style)**
|
||||
|
||||
Use Codex Skill to perform deep analysis. Codex should operate in "plan mode" style:
|
||||
|
||||
**When Deep Analysis is Needed** (any condition triggers):
|
||||
- Multiple valid approaches exist (e.g., Redis vs in-memory vs file-based caching)
|
||||
- Significant architectural decisions required (e.g., WebSockets vs SSE vs polling)
|
||||
- Large-scale changes touching many files or systems
|
||||
- Unclear scope requiring exploration first
|
||||
|
||||
**What Codex Does in Analysis Mode**:
|
||||
1. **Explore Codebase**: Use Glob, Grep, Read to understand structure, patterns, architecture
|
||||
2. **Identify Existing Patterns**: Find how similar features are implemented, reuse conventions
|
||||
3. **Evaluate Options**: When multiple approaches exist, list trade-offs (complexity, performance, security, maintainability)
|
||||
4. **Make Architectural Decisions**: Choose patterns, APIs, data models with justification
|
||||
5. **Design Task Breakdown**: Produce 2-5 parallelizable tasks with file scope and dependencies
|
||||
|
||||
**Analysis Output Structure**:
|
||||
```
|
||||
## Context & Constraints
|
||||
[Tech stack, existing patterns, constraints discovered]
|
||||
|
||||
## Codebase Exploration
|
||||
[Key files, modules, patterns found via Glob/Grep/Read]
|
||||
|
||||
## Implementation Options (if multiple approaches)
|
||||
| Option | Pros | Cons | Recommendation |
|
||||
|
||||
## Technical Decisions
|
||||
[API design, data models, architecture choices made]
|
||||
|
||||
## Task Breakdown
|
||||
[2-5 tasks with: ID, description, file scope, dependencies, test command]
|
||||
```
|
||||
|
||||
**Skip Deep Analysis When**:
|
||||
- Simple, straightforward implementation with obvious approach
|
||||
- Small changes confined to 1-2 files
|
||||
- Clear requirements with single implementation path
|
||||
|
||||
- **Step 3: Generate Development Documentation**
|
||||
- invoke agent dev-plan-generator
|
||||
|
||||
- **Step 4: Parallel Development Execution**
|
||||
- For each task in `dev-plan.md`, invoke Codex with this brief:
|
||||
```
|
||||
Task: [task-id]
|
||||
Reference: @.claude/specs/{feature_name}/dev-plan.md
|
||||
Scope: [task file scope]
|
||||
Test: [test command]
|
||||
Deliverables: code + unit tests + coverage ≥90% + coverage summary
|
||||
```
|
||||
- Execute independent tasks concurrently; serialize conflicting ones; track coverage reports
|
||||
|
||||
- **Step 5: Coverage Validation**
|
||||
- Validate each task’s coverage:
|
||||
- All ≥90% → pass
|
||||
- Any <90% → request more tests (max 2 rounds)
|
||||
|
||||
- **Step 6: Completion Summary**
|
||||
- Provide completed task list, coverage per task, key file changes
|
||||
|
||||
**Error Handling**
|
||||
- Codex failure: retry once, then log and continue
|
||||
- Insufficient coverage: request more tests (max 2 rounds)
|
||||
- Dependency conflicts: serialize automatically
|
||||
|
||||
**Quality Standards**
|
||||
- Code coverage ≥90%
|
||||
- 2-5 genuinely parallelizable tasks
|
||||
- Documentation must be minimal yet actionable
|
||||
- No verbose implementations; only essential code
|
||||
|
||||
**Communication Style**
|
||||
- Be direct and concise
|
||||
- Report progress at each workflow step
|
||||
- Highlight blockers immediately
|
||||
- Provide actionable next steps when coverage fails
|
||||
- Prioritize speed via parallelization while enforcing coverage validation
|
||||
@@ -104,7 +104,7 @@ This repository provides 4 ready-to-use Claude Code plugins that can be installe
|
||||
|
||||
```bash
|
||||
# Install from GitHub repository
|
||||
/plugin github.com/cexll/myclaude
|
||||
/plugin marketplace add cexll/myclaude
|
||||
```
|
||||
|
||||
This will present all available plugins from the repository.
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
```bash
|
||||
# Install everything with one command
|
||||
/plugin github.com/cexll/myclaude
|
||||
/plugin marketplace add cexll/myclaude
|
||||
```
|
||||
|
||||
### Option 2: Make Install
|
||||
|
||||
46
install.sh
Normal file
46
install.sh
Normal file
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Detect platform
|
||||
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
|
||||
ARCH=$(uname -m)
|
||||
|
||||
# Normalize architecture names
|
||||
case "$ARCH" in
|
||||
x86_64) ARCH="amd64" ;;
|
||||
aarch64|arm64) ARCH="arm64" ;;
|
||||
*) echo "Unsupported architecture: $ARCH" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
# Build download URL
|
||||
REPO="chenwenjie/myclaude"
|
||||
VERSION="latest"
|
||||
BINARY_NAME="codex-wrapper-${OS}-${ARCH}"
|
||||
URL="https://github.com/${REPO}/releases/${VERSION}/download/${BINARY_NAME}"
|
||||
|
||||
echo "Downloading codex-wrapper from ${URL}..."
|
||||
if ! curl -fsSL "$URL" -o /tmp/codex-wrapper; then
|
||||
echo "ERROR: failed to download binary" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$HOME/bin"
|
||||
|
||||
mv /tmp/codex-wrapper "$HOME/bin/codex-wrapper"
|
||||
chmod +x "$HOME/bin/codex-wrapper"
|
||||
|
||||
if "$HOME/bin/codex-wrapper" --version >/dev/null 2>&1; then
|
||||
echo "codex-wrapper installed successfully to ~/bin/codex-wrapper"
|
||||
else
|
||||
echo "ERROR: installation verification failed" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ":$PATH:" != *":$HOME/bin:"* ]]; then
|
||||
echo ""
|
||||
echo "WARNING: ~/bin is not in your PATH"
|
||||
echo "Add this line to your ~/.bashrc or ~/.zshrc:"
|
||||
echo ""
|
||||
echo " export PATH=\"\$HOME/bin:\$PATH\""
|
||||
echo ""
|
||||
fi
|
||||
@@ -14,30 +14,51 @@ Execute Codex CLI commands and parse structured JSON responses. Supports file re
|
||||
- Complex code analysis requiring deep understanding
|
||||
- Large-scale refactoring across multiple files
|
||||
- Automated code generation with safety controls
|
||||
- Tasks requiring specialized reasoning models (gpt-5.1, gpt-5.1-codex)
|
||||
|
||||
## Usage
|
||||
|
||||
**推荐方式**(使用 uv run,自动管理 Python 环境):
|
||||
**Mandatory**: Run every automated invocation through the Bash tool in the foreground with **HEREDOC syntax** to avoid shell quoting issues, keeping the `timeout` parameter fixed at `7200000` milliseconds (do not change it or use any other entry point).
|
||||
|
||||
```bash
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
codex-wrapper - [working_dir] <<'EOF'
|
||||
<task content here>
|
||||
EOF
|
||||
```
|
||||
|
||||
**备选方式**(直接执行或使用 Python):
|
||||
**Why HEREDOC?** Tasks often contain code blocks, nested quotes, shell metacharacters (`$`, `` ` ``, `\`), and multiline text. HEREDOC (Here Document) syntax passes these safely without shell interpretation, eliminating quote-escaping nightmares.
|
||||
|
||||
**Foreground only (no background/BashOutput)**: Never set `background: true`, never accept Claude's "Running in the background" mode, and avoid `BashOutput` streaming loops. Keep a single foreground Bash call per Codex task; if work might be long, split it into smaller foreground runs instead of offloading to background execution.
|
||||
|
||||
**Simple tasks** (backward compatibility):
|
||||
For simple single-line tasks without special characters, you can still use direct quoting:
|
||||
```bash
|
||||
~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
# 或
|
||||
python3 ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
codex-wrapper "simple task here" [working_dir]
|
||||
```
|
||||
|
||||
恢复会话:
|
||||
**Resume a session with HEREDOC:**
|
||||
```bash
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py resume <session_id> "<task>" [model] [working_dir]
|
||||
codex-wrapper resume <session_id> - [working_dir] <<'EOF'
|
||||
<task content>
|
||||
EOF
|
||||
```
|
||||
|
||||
**Cross-platform notes:**
|
||||
- **Bash/Zsh**: Use `<<'EOF'` (single quotes prevent variable expansion)
|
||||
- **PowerShell 5.1+**: Use `@'` and `'@` (here-string syntax)
|
||||
```powershell
|
||||
codex-wrapper - @'
|
||||
task content
|
||||
'@
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- **CODEX_TIMEOUT**: Override timeout in milliseconds (default: 7200000 = 2 hours)
|
||||
- Example: `export CODEX_TIMEOUT=3600000` for 1 hour
|
||||
|
||||
## Timeout Control
|
||||
|
||||
- **Built-in**: Script enforces 2-hour timeout by default
|
||||
- **Built-in**: Binary enforces 2-hour timeout by default
|
||||
- **Override**: Set `CODEX_TIMEOUT` environment variable (in milliseconds, e.g., `CODEX_TIMEOUT=3600000` for 1 hour)
|
||||
- **Behavior**: On timeout, sends SIGTERM, then SIGKILL after 5s if process doesn't exit
|
||||
- **Exit code**: Returns 124 on timeout (consistent with GNU timeout)
|
||||
@@ -46,9 +67,6 @@ uv run ~/.claude/skills/codex/scripts/codex.py resume <session_id> "<task>" [mod
|
||||
### Parameters
|
||||
|
||||
- `task` (required): Task description, supports `@file` references
|
||||
- `model` (optional): Model to use (default: gpt-5.1-codex)
|
||||
- `gpt-5.1-codex`: Default, optimized for code
|
||||
- `gpt-5.1`: Fast general purpose
|
||||
- `working_dir` (optional): Working directory (default: current)
|
||||
|
||||
### Return Format
|
||||
@@ -66,73 +84,106 @@ Error format (stderr):
|
||||
ERROR: Error message
|
||||
```
|
||||
|
||||
Return only the final agent message and session ID—do not paste raw `BashOutput` logs or background-task chatter into the conversation.
|
||||
|
||||
### Invocation Pattern
|
||||
|
||||
When calling via Bash tool, always include the timeout parameter:
|
||||
All automated executions must use HEREDOC syntax through the Bash tool in the foreground, with `timeout` fixed at `7200000` (non-negotiable):
|
||||
|
||||
```
|
||||
Bash tool parameters:
|
||||
- command: uv run ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
- command: codex-wrapper - [working_dir] <<'EOF'
|
||||
<task content>
|
||||
EOF
|
||||
- timeout: 7200000
|
||||
- description: <brief description of the task>
|
||||
```
|
||||
|
||||
Alternatives:
|
||||
```
|
||||
# Direct execution (simplest)
|
||||
- command: ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
Run every call in the foreground—never append `&` to background it—so logs and errors stay visible for timely interruption or diagnosis.
|
||||
|
||||
# Using python3
|
||||
- command: python3 ~/.claude/skills/codex/scripts/codex.py "<task>" [model] [working_dir]
|
||||
```
|
||||
**Important:** Use HEREDOC (`<<'EOF'`) for all but the simplest tasks. This prevents shell interpretation of quotes, variables, and special characters.
|
||||
|
||||
### Examples
|
||||
|
||||
**Basic code analysis:**
|
||||
```bash
|
||||
# Recommended: via uv run (auto-manages Python environment)
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "explain @src/main.ts"
|
||||
# Recommended: with HEREDOC (handles any special characters)
|
||||
codex-wrapper - <<'EOF'
|
||||
explain @src/main.ts
|
||||
EOF
|
||||
# timeout: 7200000
|
||||
|
||||
# Alternative: direct execution
|
||||
~/.claude/skills/codex/scripts/codex.py "explain @src/main.ts"
|
||||
# Alternative: simple direct quoting (if task is simple)
|
||||
codex-wrapper "explain @src/main.ts"
|
||||
```
|
||||
|
||||
**Refactoring with specific model:**
|
||||
**Refactoring with multiline instructions:**
|
||||
```bash
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "refactor @src/utils for performance" "gpt-5.1-codex"
|
||||
codex-wrapper - <<'EOF'
|
||||
refactor @src/utils for performance:
|
||||
- Extract duplicate code into helpers
|
||||
- Use memoization for expensive calculations
|
||||
- Add inline comments for non-obvious logic
|
||||
EOF
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**Multi-file analysis:**
|
||||
```bash
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "analyze @. and find security issues" "gpt-5.1-codex" "/path/to/project"
|
||||
codex-wrapper - "/path/to/project" <<'EOF'
|
||||
analyze @. and find security issues:
|
||||
1. Check for SQL injection vulnerabilities
|
||||
2. Identify XSS risks in templates
|
||||
3. Review authentication/authorization logic
|
||||
4. Flag hardcoded credentials or secrets
|
||||
EOF
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**Resume previous session:**
|
||||
```bash
|
||||
# First session
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py "add comments to @utils.js" "gpt-5.1-codex"
|
||||
codex-wrapper - <<'EOF'
|
||||
add comments to @utils.js explaining the caching logic
|
||||
EOF
|
||||
# Output includes: SESSION_ID: 019a7247-ac9d-71f3-89e2-a823dbd8fd14
|
||||
|
||||
# Continue the conversation
|
||||
uv run ~/.claude/skills/codex/scripts/codex.py resume 019a7247-ac9d-71f3-89e2-a823dbd8fd14 "now add type hints"
|
||||
# Continue the conversation with more context
|
||||
codex-wrapper resume 019a7247-ac9d-71f3-89e2-a823dbd8fd14 - <<'EOF'
|
||||
now add TypeScript type hints and handle edge cases where cache is null
|
||||
EOF
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**Using python3 directly (alternative):**
|
||||
**Task with code snippets and special characters:**
|
||||
```bash
|
||||
python3 ~/.claude/skills/codex/scripts/codex.py "your task here"
|
||||
codex-wrapper - <<'EOF'
|
||||
Fix the bug in @app.js where the regex /\d+/ doesn't match "123"
|
||||
The current code is:
|
||||
const re = /\d+/;
|
||||
if (re.test(input)) { ... }
|
||||
Add proper escaping and handle $variables correctly.
|
||||
EOF
|
||||
```
|
||||
|
||||
### Large Task Protocol
|
||||
|
||||
- For every large task, first produce a canonical task list that enumerates the Task ID, description, file/directory scope, dependencies, test commands, and the expected Codex Bash invocation.
|
||||
- Tasks without dependencies should be executed concurrently via multiple foreground Bash calls (you can keep separate terminal windows) and each run must log start/end times plus any shared resource usage.
|
||||
- Reuse context aggressively (such as @spec.md or prior analysis output), and after concurrent execution finishes, reconcile against the task list to report which items completed and which slipped.
|
||||
|
||||
| ID | Description | Scope | Dependencies | Tests | Command |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| T1 | Review @spec.md to extract requirements | docs/, @spec.md | None | None | `codex-wrapper - <<'EOF'`<br/>`analyze requirements @spec.md`<br/>`EOF` |
|
||||
| T2 | Implement the module and add test cases | src/module | T1 | npm test -- --runInBand | `codex-wrapper - <<'EOF'`<br/>`implement and test @src/module`<br/>`EOF` |
|
||||
|
||||
## Notes
|
||||
|
||||
- **Recommended**: Use `uv run` for automatic Python environment management (requires uv installed)
|
||||
- **Alternative**: Direct execution `./codex.py` (uses system Python via shebang)
|
||||
- Python implementation using standard library (zero dependencies)
|
||||
- Cross-platform compatible (Windows/macOS/Linux)
|
||||
- PEP 723 compliant (inline script metadata)
|
||||
- Runs with `--dangerously-bypass-approvals-and-sandbox` for automation (new sessions only)
|
||||
- **Binary distribution**: Single Go binary, zero dependencies
|
||||
- **Installation**: Download from GitHub Releases or use install.sh
|
||||
- **Cross-platform compatible**: Linux (amd64/arm64), macOS (amd64/arm64)
|
||||
- All automated runs must use the Bash tool with the fixed timeout to provide dual timeout protection and unified logging/exit semantics
|
||||
for automation (new sessions only)
|
||||
- Uses `--skip-git-repo-check` to work in any directory
|
||||
- Streams progress, returns only final agent message
|
||||
- Every execution returns a session ID for resuming conversations
|
||||
|
||||
@@ -8,10 +8,14 @@ Codex CLI wrapper with cross-platform support and session management.
|
||||
**FIXED**: Auto-detect long inputs and use stdin mode to avoid shell argument issues.
|
||||
|
||||
Usage:
|
||||
New session: uv run codex.py "task" [model] [workdir]
|
||||
Resume: uv run codex.py resume <session_id> "task" [model] [workdir]
|
||||
New session: uv run codex.py "task" [workdir]
|
||||
Stdin mode: uv run codex.py - [workdir]
|
||||
Resume: uv run codex.py resume <session_id> "task" [workdir]
|
||||
Resume stdin: uv run codex.py resume <session_id> - [workdir]
|
||||
Alternative: python3 codex.py "task"
|
||||
Direct exec: ./codex.py "task"
|
||||
|
||||
Model configuration: Set CODEX_MODEL environment variable (default: gpt-5.1-codex)
|
||||
"""
|
||||
import subprocess
|
||||
import json
|
||||
@@ -19,11 +23,10 @@ import sys
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
DEFAULT_MODEL = 'gpt-5.1-codex'
|
||||
DEFAULT_MODEL = os.environ.get('CODEX_MODEL', 'gpt-5.1-codex')
|
||||
DEFAULT_WORKDIR = '.'
|
||||
DEFAULT_TIMEOUT = 7200 # 2 hours in seconds
|
||||
FORCE_KILL_DELAY = 5
|
||||
STDIN_THRESHOLD = 800 # Auto-switch to stdin for prompts longer than 800 chars
|
||||
|
||||
|
||||
def log_error(message: str):
|
||||
@@ -36,6 +39,11 @@ def log_warn(message: str):
|
||||
sys.stderr.write(f"WARN: {message}\n")
|
||||
|
||||
|
||||
def log_info(message: str):
|
||||
"""输出信息到 stderr"""
|
||||
sys.stderr.write(f"INFO: {message}\n")
|
||||
|
||||
|
||||
def resolve_timeout() -> int:
|
||||
"""解析超时配置(秒)"""
|
||||
raw = os.environ.get('CODEX_TIMEOUT', '')
|
||||
@@ -74,100 +82,132 @@ def parse_args():
|
||||
if len(sys.argv) < 4:
|
||||
log_error('Resume mode requires: resume <session_id> <task>')
|
||||
sys.exit(1)
|
||||
task_arg = sys.argv[3]
|
||||
return {
|
||||
'mode': 'resume',
|
||||
'session_id': sys.argv[2],
|
||||
'task': sys.argv[3],
|
||||
'model': sys.argv[4] if len(sys.argv) > 4 else DEFAULT_MODEL,
|
||||
'workdir': sys.argv[5] if len(sys.argv) > 5 else DEFAULT_WORKDIR
|
||||
}
|
||||
else:
|
||||
return {
|
||||
'mode': 'new',
|
||||
'task': sys.argv[1],
|
||||
'model': sys.argv[2] if len(sys.argv) > 2 else DEFAULT_MODEL,
|
||||
'workdir': sys.argv[3] if len(sys.argv) > 3 else DEFAULT_WORKDIR
|
||||
'task': task_arg,
|
||||
'explicit_stdin': task_arg == '-',
|
||||
'workdir': sys.argv[4] if len(sys.argv) > 4 else DEFAULT_WORKDIR,
|
||||
}
|
||||
|
||||
task_arg = sys.argv[1]
|
||||
return {
|
||||
'mode': 'new',
|
||||
'task': task_arg,
|
||||
'explicit_stdin': task_arg == '-',
|
||||
'workdir': sys.argv[2] if len(sys.argv) > 2 else DEFAULT_WORKDIR,
|
||||
}
|
||||
|
||||
def build_codex_args(params: dict, use_stdin: bool) -> list:
|
||||
|
||||
def read_piped_task() -> Optional[str]:
|
||||
"""
|
||||
从 stdin 读取任务文本:
|
||||
- 如果 stdin 是管道(非 tty)且存在内容,返回读取到的字符串
|
||||
- 否则返回 None
|
||||
"""
|
||||
stdin = sys.stdin
|
||||
if stdin is None or stdin.isatty():
|
||||
log_info("Stdin is tty or None, skipping pipe read")
|
||||
return None
|
||||
log_info("Reading from stdin pipe...")
|
||||
data = stdin.read()
|
||||
if not data:
|
||||
log_info("Stdin pipe returned empty data")
|
||||
return None
|
||||
|
||||
log_info(f"Read {len(data)} bytes from stdin pipe")
|
||||
return data
|
||||
|
||||
|
||||
def should_stream_via_stdin(task_text: str, piped: bool) -> bool:
|
||||
"""
|
||||
判定是否通过 stdin 传递任务:
|
||||
- 有管道输入
|
||||
- 文本包含换行
|
||||
- 文本包含反斜杠
|
||||
- 文本长度 > 800
|
||||
"""
|
||||
if piped:
|
||||
return True
|
||||
if '\n' in task_text:
|
||||
return True
|
||||
if '\\' in task_text:
|
||||
return True
|
||||
if len(task_text) > 800:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def build_codex_args(params: dict, target_arg: str) -> list:
|
||||
"""
|
||||
构建 codex CLI 参数
|
||||
|
||||
Args:
|
||||
params: 参数字典
|
||||
use_stdin: 是否使用 stdin 模式(不在命令行参数中传递 task)
|
||||
target_arg: 最终传递给 codex 的参数('-' 或具体 task 文本)
|
||||
"""
|
||||
if params['mode'] == 'resume':
|
||||
if use_stdin:
|
||||
return [
|
||||
'codex', 'e',
|
||||
'--skip-git-repo-check',
|
||||
'--json',
|
||||
'resume',
|
||||
params['session_id'],
|
||||
'-' # 从 stdin 读取
|
||||
]
|
||||
else:
|
||||
return [
|
||||
'codex', 'e',
|
||||
'--skip-git-repo-check',
|
||||
'--json',
|
||||
'resume',
|
||||
params['session_id'],
|
||||
params['task']
|
||||
]
|
||||
return [
|
||||
'codex', 'e',
|
||||
'-m', DEFAULT_MODEL,
|
||||
'--skip-git-repo-check',
|
||||
'--json',
|
||||
'resume',
|
||||
params['session_id'],
|
||||
target_arg
|
||||
]
|
||||
else:
|
||||
base_args = [
|
||||
'codex', 'e',
|
||||
'-m', params['model'],
|
||||
'-m', DEFAULT_MODEL,
|
||||
'--dangerously-bypass-approvals-and-sandbox',
|
||||
'--skip-git-repo-check',
|
||||
'-C', params['workdir'],
|
||||
'--json'
|
||||
'--json',
|
||||
target_arg
|
||||
]
|
||||
|
||||
if use_stdin:
|
||||
base_args.append('-') # 从 stdin 读取
|
||||
else:
|
||||
base_args.append(params['task'])
|
||||
|
||||
return base_args
|
||||
|
||||
|
||||
def main():
|
||||
params = parse_args()
|
||||
timeout_sec = resolve_timeout()
|
||||
|
||||
# **FIX: Auto-detect long inputs and enable stdin mode**
|
||||
task_length = len(params['task'])
|
||||
use_stdin = task_length > STDIN_THRESHOLD
|
||||
|
||||
if use_stdin:
|
||||
log_warn(f"Task length ({task_length} chars) exceeds threshold, using stdin mode to avoid shell escaping issues")
|
||||
|
||||
codex_args = build_codex_args(params, use_stdin)
|
||||
|
||||
def run_codex_process(codex_args, task_text: str, use_stdin: bool, timeout_sec: int):
|
||||
"""
|
||||
启动 codex 子进程,处理 stdin / JSON 行输出和错误,成功时返回 (last_agent_message, thread_id)。
|
||||
失败路径上负责日志和退出码。
|
||||
"""
|
||||
thread_id: Optional[str] = None
|
||||
last_agent_message: Optional[str] = None
|
||||
process: Optional[subprocess.Popen] = None
|
||||
|
||||
try:
|
||||
# 启动 codex 子进程
|
||||
# 启动 codex 子进程(文本模式管道)
|
||||
log_info(f"Starting codex with args: {' '.join(codex_args[:5])}...")
|
||||
process = subprocess.Popen(
|
||||
codex_args,
|
||||
stdin=subprocess.PIPE if use_stdin else None, # **FIX: Enable stdin**
|
||||
stdin=subprocess.PIPE if use_stdin else None,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=sys.stderr, # 错误直接透传到 stderr
|
||||
stderr=sys.stderr,
|
||||
text=True,
|
||||
bufsize=1 # 行缓冲
|
||||
bufsize=1,
|
||||
)
|
||||
log_info(f"Process started with PID: {process.pid}")
|
||||
|
||||
# **FIX: 如果使用 stdin 模式,写入任务到 stdin**
|
||||
if use_stdin:
|
||||
process.stdin.write(params['task'])
|
||||
# 如果使用 stdin 模式,写入任务到 stdin 并关闭
|
||||
if use_stdin and process.stdin is not None:
|
||||
log_info(f"Writing {len(task_text)} chars to stdin...")
|
||||
process.stdin.write(task_text)
|
||||
process.stdin.flush() # 强制刷新缓冲区,避免大任务死锁
|
||||
process.stdin.close()
|
||||
log_info("Stdin closed")
|
||||
|
||||
# 逐行解析 JSON 输出
|
||||
if process.stdout is None:
|
||||
log_error('Codex stdout pipe not available')
|
||||
sys.exit(1)
|
||||
|
||||
log_info("Reading stdout...")
|
||||
|
||||
for line in process.stdout:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
@@ -190,33 +230,26 @@ def main():
|
||||
except json.JSONDecodeError:
|
||||
log_warn(f"Failed to parse line: {line}")
|
||||
|
||||
# 等待进程结束
|
||||
# 等待进程结束并检查退出码
|
||||
returncode = process.wait(timeout=timeout_sec)
|
||||
|
||||
if returncode == 0:
|
||||
if last_agent_message:
|
||||
# 输出 agent_message
|
||||
sys.stdout.write(f"{last_agent_message}\n")
|
||||
|
||||
# 输出 session_id(如果存在)
|
||||
if thread_id:
|
||||
sys.stdout.write(f"\n---\nSESSION_ID: {thread_id}\n")
|
||||
|
||||
sys.exit(0)
|
||||
else:
|
||||
log_error('Codex completed without agent_message output')
|
||||
sys.exit(1)
|
||||
else:
|
||||
if returncode != 0:
|
||||
log_error(f'Codex exited with status {returncode}')
|
||||
sys.exit(returncode)
|
||||
|
||||
if not last_agent_message:
|
||||
log_error('Codex completed without agent_message output')
|
||||
sys.exit(1)
|
||||
|
||||
return last_agent_message, thread_id
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
log_error('Codex execution timeout')
|
||||
process.kill()
|
||||
try:
|
||||
process.wait(timeout=FORCE_KILL_DELAY)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
if process is not None:
|
||||
process.kill()
|
||||
try:
|
||||
process.wait(timeout=FORCE_KILL_DELAY)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
sys.exit(124)
|
||||
|
||||
except FileNotFoundError:
|
||||
@@ -224,13 +257,76 @@ def main():
|
||||
sys.exit(127)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=FORCE_KILL_DELAY)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
log_error("Codex interrupted by user")
|
||||
if process is not None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=FORCE_KILL_DELAY)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
sys.exit(130)
|
||||
|
||||
|
||||
def main():
|
||||
log_info("Script started")
|
||||
params = parse_args()
|
||||
log_info(f"Parsed args: mode={params['mode']}, task_len={len(params['task'])}")
|
||||
timeout_sec = resolve_timeout()
|
||||
log_info(f"Timeout: {timeout_sec}s")
|
||||
|
||||
explicit_stdin = params.get('explicit_stdin', False)
|
||||
|
||||
if explicit_stdin:
|
||||
log_info("Explicit stdin mode: reading task from stdin")
|
||||
task_text = sys.stdin.read()
|
||||
if not task_text:
|
||||
log_error("Explicit stdin mode requires task input from stdin")
|
||||
sys.exit(1)
|
||||
piped = not sys.stdin.isatty()
|
||||
else:
|
||||
piped_task = read_piped_task()
|
||||
piped = piped_task is not None
|
||||
task_text = piped_task if piped else params['task']
|
||||
|
||||
use_stdin = explicit_stdin or should_stream_via_stdin(task_text, piped)
|
||||
|
||||
if use_stdin:
|
||||
reasons = []
|
||||
if piped:
|
||||
reasons.append('piped input')
|
||||
if explicit_stdin:
|
||||
reasons.append('explicit "-"')
|
||||
if '\n' in task_text:
|
||||
reasons.append('newline')
|
||||
if '\\' in task_text:
|
||||
reasons.append('backslash')
|
||||
if len(task_text) > 800:
|
||||
reasons.append('length>800')
|
||||
|
||||
if reasons:
|
||||
log_warn(f"Using stdin mode for task due to: {', '.join(reasons)}")
|
||||
|
||||
target_arg = '-' if use_stdin else params['task']
|
||||
codex_args = build_codex_args(params, target_arg)
|
||||
|
||||
log_info('codex running...')
|
||||
|
||||
last_agent_message, thread_id = run_codex_process(
|
||||
codex_args=codex_args,
|
||||
task_text=task_text,
|
||||
use_stdin=use_stdin,
|
||||
timeout_sec=timeout_sec,
|
||||
)
|
||||
|
||||
# 输出 agent_message
|
||||
sys.stdout.write(f"{last_agent_message}\n")
|
||||
|
||||
# 输出 session_id(如果存在)
|
||||
if thread_id:
|
||||
sys.stdout.write(f"\n---\nSESSION_ID: {thread_id}\n")
|
||||
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
120
skills/gemini/SKILL.md
Normal file
120
skills/gemini/SKILL.md
Normal file
@@ -0,0 +1,120 @@
|
||||
---
|
||||
name: gemini
|
||||
description: Execute Gemini CLI for AI-powered code analysis and generation. Use when you need to leverage Google's Gemini models for complex reasoning tasks.
|
||||
---
|
||||
|
||||
# Gemini CLI Integration
|
||||
|
||||
## Overview
|
||||
|
||||
Execute Gemini CLI commands with support for multiple models and flexible prompt input. Integrates Google's Gemini AI models into Claude Code workflows.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Complex reasoning tasks requiring advanced AI capabilities
|
||||
- Code generation and analysis with Gemini models
|
||||
- Tasks requiring Google's latest AI technology
|
||||
- Alternative perspective on code problems
|
||||
|
||||
## Usage
|
||||
**Mandatory**: Run via uv with fixed timeout 7200000ms (foreground):
|
||||
```bash
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py "<prompt>" [working_dir]
|
||||
```
|
||||
|
||||
**Optional** (direct execution or using Python):
|
||||
```bash
|
||||
~/.claude/skills/gemini/scripts/gemini.py "<prompt>" [working_dir]
|
||||
# or
|
||||
python3 ~/.claude/skills/gemini/scripts/gemini.py "<prompt>" [working_dir]
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- **GEMINI_MODEL**: Configure model (default: `gemini-3-pro-preview`)
|
||||
- Example: `export GEMINI_MODEL=gemini-3`
|
||||
|
||||
## Timeout Control
|
||||
|
||||
- **Fixed**: 7200000 milliseconds (2 hours), immutable
|
||||
- **Bash tool**: Always set `timeout: 7200000` for double protection
|
||||
|
||||
### Parameters
|
||||
|
||||
- `prompt` (required): Task prompt or question
|
||||
- `working_dir` (optional): Working directory (default: current directory)
|
||||
|
||||
### Return Format
|
||||
|
||||
Plain text output from Gemini:
|
||||
|
||||
```text
|
||||
Model response text here...
|
||||
```
|
||||
|
||||
Error format (stderr):
|
||||
|
||||
```text
|
||||
ERROR: Error message
|
||||
```
|
||||
|
||||
### Invocation Pattern
|
||||
|
||||
When calling via Bash tool, always include the timeout parameter:
|
||||
|
||||
```yaml
|
||||
Bash tool parameters:
|
||||
- command: uv run ~/.claude/skills/gemini/scripts/gemini.py "<prompt>"
|
||||
- timeout: 7200000
|
||||
- description: <brief description of the task>
|
||||
```
|
||||
|
||||
Alternatives:
|
||||
|
||||
```yaml
|
||||
# Direct execution (simplest)
|
||||
- command: ~/.claude/skills/gemini/scripts/gemini.py "<prompt>"
|
||||
|
||||
# Using python3
|
||||
- command: python3 ~/.claude/skills/gemini/scripts/gemini.py "<prompt>"
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
**Basic query:**
|
||||
|
||||
```bash
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py "explain quantum computing"
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**Code analysis:**
|
||||
|
||||
```bash
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py "review this code for security issues: $(cat app.py)"
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**With specific working directory:**
|
||||
|
||||
```bash
|
||||
uv run ~/.claude/skills/gemini/scripts/gemini.py "analyze project structure" "/path/to/project"
|
||||
# timeout: 7200000
|
||||
```
|
||||
|
||||
**Using python3 directly (alternative):**
|
||||
|
||||
```bash
|
||||
python3 ~/.claude/skills/gemini/scripts/gemini.py "your prompt here"
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- **Recommended**: Use `uv run` for automatic Python environment management (requires uv installed)
|
||||
- **Alternative**: Direct execution `./gemini.py` (uses system Python via shebang)
|
||||
- Python implementation using standard library (zero dependencies)
|
||||
- Cross-platform compatible (Windows/macOS/Linux)
|
||||
- PEP 723 compliant (inline script metadata)
|
||||
- Requires Gemini CLI installed and authenticated
|
||||
- Supports all Gemini model variants (configure via `GEMINI_MODEL` environment variable)
|
||||
- Output is streamed directly from Gemini CLI
|
||||
140
skills/gemini/scripts/gemini.py
Executable file
140
skills/gemini/scripts/gemini.py
Executable file
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
# /// script
|
||||
# requires-python = ">=3.8"
|
||||
# dependencies = []
|
||||
# ///
|
||||
"""
|
||||
Gemini CLI wrapper with cross-platform support.
|
||||
|
||||
Usage:
|
||||
uv run gemini.py "<prompt>" [workdir]
|
||||
python3 gemini.py "<prompt>"
|
||||
./gemini.py "your prompt"
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
|
||||
DEFAULT_MODEL = os.environ.get('GEMINI_MODEL', 'gemini-3-pro-preview')
|
||||
DEFAULT_WORKDIR = '.'
|
||||
TIMEOUT_MS = 7_200_000 # 固定 2 小时,毫秒
|
||||
DEFAULT_TIMEOUT = TIMEOUT_MS // 1000
|
||||
FORCE_KILL_DELAY = 5
|
||||
|
||||
|
||||
def log_error(message: str):
|
||||
"""输出错误信息到 stderr"""
|
||||
sys.stderr.write(f"ERROR: {message}\n")
|
||||
|
||||
|
||||
def log_warn(message: str):
|
||||
"""输出警告信息到 stderr"""
|
||||
sys.stderr.write(f"WARN: {message}\n")
|
||||
|
||||
|
||||
def log_info(message: str):
|
||||
"""输出信息到 stderr"""
|
||||
sys.stderr.write(f"INFO: {message}\n")
|
||||
|
||||
|
||||
def parse_args():
|
||||
"""解析位置参数"""
|
||||
if len(sys.argv) < 2:
|
||||
log_error('Prompt required')
|
||||
sys.exit(1)
|
||||
|
||||
return {
|
||||
'prompt': sys.argv[1],
|
||||
'workdir': sys.argv[2] if len(sys.argv) > 2 else DEFAULT_WORKDIR
|
||||
}
|
||||
|
||||
|
||||
def build_gemini_args(args) -> list:
|
||||
"""构建 gemini CLI 参数"""
|
||||
return [
|
||||
'gemini',
|
||||
'-m', DEFAULT_MODEL,
|
||||
'-p', args['prompt']
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
log_info('Script started')
|
||||
args = parse_args()
|
||||
log_info(f"Prompt length: {len(args['prompt'])}")
|
||||
log_info(f"Working dir: {args['workdir']}")
|
||||
gemini_args = build_gemini_args(args)
|
||||
timeout_sec = DEFAULT_TIMEOUT
|
||||
log_info(f"Timeout: {timeout_sec}s")
|
||||
|
||||
# 如果指定了工作目录,切换到该目录
|
||||
if args['workdir'] != DEFAULT_WORKDIR:
|
||||
try:
|
||||
os.chdir(args['workdir'])
|
||||
except FileNotFoundError:
|
||||
log_error(f"Working directory not found: {args['workdir']}")
|
||||
sys.exit(1)
|
||||
except PermissionError:
|
||||
log_error(f"Permission denied: {args['workdir']}")
|
||||
sys.exit(1)
|
||||
log_info('Changed working directory')
|
||||
|
||||
try:
|
||||
log_info(f"Starting gemini with model {DEFAULT_MODEL}")
|
||||
process = None
|
||||
# 启动 gemini 子进程,直接透传 stdout 和 stderr
|
||||
process = subprocess.Popen(
|
||||
gemini_args,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1 # 行缓冲
|
||||
)
|
||||
|
||||
# 实时输出 stdout
|
||||
for line in process.stdout:
|
||||
sys.stdout.write(line)
|
||||
sys.stdout.flush()
|
||||
|
||||
# 等待进程结束
|
||||
returncode = process.wait(timeout=timeout_sec)
|
||||
|
||||
# 读取 stderr
|
||||
stderr_output = process.stderr.read()
|
||||
if stderr_output:
|
||||
sys.stderr.write(stderr_output)
|
||||
|
||||
# 检查退出码
|
||||
if returncode != 0:
|
||||
log_error(f'Gemini exited with status {returncode}')
|
||||
sys.exit(returncode)
|
||||
|
||||
sys.exit(0)
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
log_error(f'Gemini execution timeout ({timeout_sec}s)')
|
||||
if process is not None:
|
||||
process.kill()
|
||||
try:
|
||||
process.wait(timeout=FORCE_KILL_DELAY)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
sys.exit(124)
|
||||
|
||||
except FileNotFoundError:
|
||||
log_error("gemini command not found in PATH")
|
||||
log_error("Please install Gemini CLI: https://github.com/google/generative-ai-python")
|
||||
sys.exit(127)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
if process is not None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=FORCE_KILL_DELAY)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
sys.exit(130)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user