ai-dev-flow 3.10.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ai_dev_flow/__init__.py +5 -0
- ai_dev_flow/__main__.py +6 -0
- ai_dev_flow/checkpoint.py +65 -0
- ai_dev_flow/cli.py +598 -0
- ai_dev_flow/config.py +404 -0
- ai_dev_flow/data/pipeline.yaml +193 -0
- ai_dev_flow/data/profiles/java-spring.yml +140 -0
- ai_dev_flow/data/recipes/steps/00-init-project.yaml +168 -0
- ai_dev_flow/data/recipes/steps/01-refine-requirement.yaml +117 -0
- ai_dev_flow/data/recipes/steps/02-analysis.yaml +97 -0
- ai_dev_flow/data/recipes/steps/03-design.yaml +91 -0
- ai_dev_flow/data/recipes/steps/03.5-decompose.yaml +120 -0
- ai_dev_flow/data/recipes/steps/05-build.yaml +72 -0
- ai_dev_flow/data/recipes/steps/06-review.yaml +115 -0
- ai_dev_flow/data/recipes/steps/07-delivery.yaml +76 -0
- ai_dev_flow/data/recipes/steps/task-template.yaml +74 -0
- ai_dev_flow/error_handler.py +122 -0
- ai_dev_flow/executor.py +406 -0
- ai_dev_flow/git_ops.py +187 -0
- ai_dev_flow/knowledge_accumulator.py +121 -0
- ai_dev_flow/logger.py +84 -0
- ai_dev_flow/sandbox.py +291 -0
- ai_dev_flow/semantic_summarizer.py +351 -0
- ai_dev_flow/snapshot.py +210 -0
- ai_dev_flow/state.py +87 -0
- ai_dev_flow/task_context.py +134 -0
- ai_dev_flow/task_graph.py +841 -0
- ai_dev_flow/task_state.py +151 -0
- ai_dev_flow/watchdog.py +120 -0
- ai_dev_flow-3.10.0.dist-info/METADATA +171 -0
- ai_dev_flow-3.10.0.dist-info/RECORD +35 -0
- ai_dev_flow-3.10.0.dist-info/WHEEL +5 -0
- ai_dev_flow-3.10.0.dist-info/entry_points.txt +2 -0
- ai_dev_flow-3.10.0.dist-info/licenses/LICENSE +21 -0
- ai_dev_flow-3.10.0.dist-info/top_level.txt +1 -0
ai_dev_flow/executor.py
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
"""goose CLI 调用封装 — 实时输出、看门狗超时、日志捕获。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
import shutil
|
|
8
|
+
import logging
|
|
9
|
+
import threading
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
from collections import deque
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from ai_dev_flow.watchdog import ProcessWatchdog
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger("ai-dev-flow")
|
|
18
|
+
|
|
19
|
+
HEARTBEAT_INTERVAL = 60
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class GooseError(Exception):
|
|
23
|
+
def __init__(self, returncode: int, stderr: str = ""):
|
|
24
|
+
self.returncode = returncode
|
|
25
|
+
self.stderr = stderr
|
|
26
|
+
super().__init__(f"goose exited with code {returncode}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class GooseNotFound(Exception):
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def check_goose() -> str:
|
|
34
|
+
goose = shutil.which("goose")
|
|
35
|
+
if not goose:
|
|
36
|
+
raise GooseNotFound(
|
|
37
|
+
"goose CLI not found in PATH.\n"
|
|
38
|
+
"Install: https://block.github.io/goose/"
|
|
39
|
+
)
|
|
40
|
+
logger.debug(f"goose found: {goose}")
|
|
41
|
+
return goose
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def build_params(params: dict[str, str]) -> list[str]:
|
|
45
|
+
"""构建 goose --params 参数列表。值含 YAML 特殊字符时自动加引号。"""
|
|
46
|
+
result = []
|
|
47
|
+
for key, value in params.items():
|
|
48
|
+
# goose 可能将 --params key=value 解析为 YAML,
|
|
49
|
+
# 若 value 含 : # { } [ ] , & * ? | > < ! % @ ` 等字符则加引号
|
|
50
|
+
if _needs_yaml_quoting(value):
|
|
51
|
+
value = f'"{value}"'
|
|
52
|
+
result.extend(["--params", f"{key}={value}"])
|
|
53
|
+
return result
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _needs_yaml_quoting(value: str) -> bool:
|
|
57
|
+
"""检查 YAML 标量值是否需要引号包裹。
|
|
58
|
+
|
|
59
|
+
跳过合法的 YAML flow sequence/mapping ([] 或 {}),其余含特殊字符的值需加引号。
|
|
60
|
+
"""
|
|
61
|
+
import re as _re
|
|
62
|
+
stripped = value.strip()
|
|
63
|
+
if _re.match(r'^\[.*?\]$', stripped) or _re.match(r'^\{.*?\}$', stripped):
|
|
64
|
+
return False
|
|
65
|
+
for ch in value:
|
|
66
|
+
if ch in ':#{}[]&*?!|>%@`,' or ch == '"':
|
|
67
|
+
return True
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _build_args(recipe: str, max_turns: int, params: dict[str, str], quiet: bool = False) -> list[str]:
|
|
72
|
+
args = [
|
|
73
|
+
"goose", "run",
|
|
74
|
+
"--recipe", recipe,
|
|
75
|
+
"--max-turns", str(max_turns),
|
|
76
|
+
]
|
|
77
|
+
if quiet:
|
|
78
|
+
args.append("-q")
|
|
79
|
+
args.extend(build_params(params))
|
|
80
|
+
return args
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _spawn(args: list[str], cwd: Path, env: dict[str, str] | None = None) -> subprocess.Popen:
|
|
84
|
+
"""启动 goose 子进程,捕获 stdout/stderr 管道。env 合并入子进程环境。
|
|
85
|
+
|
|
86
|
+
POSIX 下使用独立会话:看门狗超时用 killpg 终止时,只会命中 goose 进程树,
|
|
87
|
+
不会波及管线自身所在的进程组。
|
|
88
|
+
"""
|
|
89
|
+
proc_env = None
|
|
90
|
+
if env:
|
|
91
|
+
proc_env = {**os.environ, **env}
|
|
92
|
+
isolated = {} if sys.platform == "win32" else {"start_new_session": True}
|
|
93
|
+
try:
|
|
94
|
+
return subprocess.Popen(
|
|
95
|
+
args,
|
|
96
|
+
cwd=str(cwd),
|
|
97
|
+
stdin=subprocess.DEVNULL,
|
|
98
|
+
stdout=subprocess.PIPE,
|
|
99
|
+
stderr=subprocess.PIPE,
|
|
100
|
+
text=True,
|
|
101
|
+
encoding="utf-8",
|
|
102
|
+
errors="replace",
|
|
103
|
+
env=proc_env,
|
|
104
|
+
**isolated,
|
|
105
|
+
)
|
|
106
|
+
except FileNotFoundError:
|
|
107
|
+
raise GooseNotFound("goose CLI not found in PATH")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _probe_process(pid: int) -> str:
|
|
111
|
+
"""查询进程状态用于诊断。返回简短描述字符串。
|
|
112
|
+
|
|
113
|
+
用 tasklist /V 获取 Status (Running/Not Responding) 和 CPU Time,
|
|
114
|
+
辅助判断是 API I/O 阻塞还是 CPU 死循环。
|
|
115
|
+
"""
|
|
116
|
+
try:
|
|
117
|
+
result = subprocess.run(
|
|
118
|
+
["tasklist", "/FI", f"PID eq {pid}", "/V", "/FO", "CSV", "/NH"],
|
|
119
|
+
capture_output=True, text=True, timeout=5,
|
|
120
|
+
)
|
|
121
|
+
line = result.stdout.strip()
|
|
122
|
+
if not line or str(pid) not in line:
|
|
123
|
+
return "state=exited"
|
|
124
|
+
parts = [p.strip().strip('"') for p in line.split(",")]
|
|
125
|
+
if len(parts) < 8:
|
|
126
|
+
return "state=parse_error"
|
|
127
|
+
# parts: 0=Name, 1=PID, 2=Session, 3=Session#, 4=Mem, 5=Status, 6=User, 7=CPU_Time
|
|
128
|
+
status = parts[5]
|
|
129
|
+
mem = parts[4]
|
|
130
|
+
cpu_time = parts[7] if len(parts) > 7 else "N/A"
|
|
131
|
+
classification = _classify_state(status, cpu_time)
|
|
132
|
+
return f"state={classification} status={status} mem={mem} cpu_time={cpu_time}"
|
|
133
|
+
except Exception:
|
|
134
|
+
return "state=unknown"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _classify_state(status: str, cpu_time: str) -> str:
|
|
138
|
+
"""基于进程状态和 CPU 时间推断卡死原因。"""
|
|
139
|
+
if status == "Not Responding":
|
|
140
|
+
return "IO_wait(API_hang?)"
|
|
141
|
+
if cpu_time and cpu_time != "0:00:00":
|
|
142
|
+
return "CPU_busy(loop?)"
|
|
143
|
+
return "idle"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _run_with_watchdog(
|
|
147
|
+
args: list[str],
|
|
148
|
+
cwd: Path,
|
|
149
|
+
timeout_seconds: int | None,
|
|
150
|
+
on_timeout=None,
|
|
151
|
+
env: dict[str, str] | None = None,
|
|
152
|
+
) -> subprocess.CompletedProcess:
|
|
153
|
+
"""核心执行逻辑:线程化 I/O + 可选的看门狗超时控制。
|
|
154
|
+
|
|
155
|
+
env 注入自定义环境变量(如 JAVA_HOME)到 goose 子进程。
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
proc = _spawn(args, cwd, env=env)
|
|
159
|
+
|
|
160
|
+
stderr_lines: list[str] = []
|
|
161
|
+
stdout_lines: list[str] = []
|
|
162
|
+
heartbeat = {"last": time.time()}
|
|
163
|
+
recent_stderr: deque[str] = deque(maxlen=10) # 最近 stderr 行,用于循环检测
|
|
164
|
+
|
|
165
|
+
def _read_stdout():
|
|
166
|
+
for raw_line in proc.stdout:
|
|
167
|
+
line = raw_line.rstrip()
|
|
168
|
+
if line:
|
|
169
|
+
stdout_lines.append(line)
|
|
170
|
+
logger.debug(f"[goose] {line}")
|
|
171
|
+
heartbeat["last"] = time.time()
|
|
172
|
+
|
|
173
|
+
def _read_stderr():
|
|
174
|
+
for line in proc.stderr:
|
|
175
|
+
stripped = line.rstrip()
|
|
176
|
+
if stripped:
|
|
177
|
+
stderr_lines.append(stripped)
|
|
178
|
+
recent_stderr.append(stripped)
|
|
179
|
+
logger.warning(f"[goose] {stripped}")
|
|
180
|
+
heartbeat["last"] = time.time()
|
|
181
|
+
|
|
182
|
+
stdout_thread = threading.Thread(target=_read_stdout, daemon=True)
|
|
183
|
+
stderr_thread = threading.Thread(target=_read_stderr, daemon=True)
|
|
184
|
+
stdout_thread.start()
|
|
185
|
+
stderr_thread.start()
|
|
186
|
+
|
|
187
|
+
# 看门狗(可选)
|
|
188
|
+
watchdog = None
|
|
189
|
+
if timeout_seconds and timeout_seconds > 0:
|
|
190
|
+
watchdog = ProcessWatchdog(proc.pid, timeout_seconds, on_timeout=on_timeout)
|
|
191
|
+
watchdog.start()
|
|
192
|
+
|
|
193
|
+
# 心跳日志(含进程状态诊断 + 循环检测)
|
|
194
|
+
LOOP_DETECT_THRESHOLD = 5 # 连续相同 stderr 行 >= 5 次视为循环
|
|
195
|
+
_loop_warning_count = 0
|
|
196
|
+
|
|
197
|
+
def _heartbeat_loop():
|
|
198
|
+
nonlocal _loop_warning_count
|
|
199
|
+
while proc.poll() is None:
|
|
200
|
+
elapsed = time.time() - heartbeat["last"]
|
|
201
|
+
if elapsed > HEARTBEAT_INTERVAL:
|
|
202
|
+
info = _probe_process(proc.pid)
|
|
203
|
+
logger.warning(
|
|
204
|
+
f"Goose has produced no output for {int(elapsed)}s (pid={proc.pid}, {info})"
|
|
205
|
+
)
|
|
206
|
+
# 循环检测:最近 N 行 stderr 全部相同 → 卡死在重试循环
|
|
207
|
+
if len(recent_stderr) >= LOOP_DETECT_THRESHOLD:
|
|
208
|
+
recent_list = list(recent_stderr)
|
|
209
|
+
if all(line == recent_list[-1] for line in recent_list[-LOOP_DETECT_THRESHOLD:]):
|
|
210
|
+
_loop_warning_count += 1
|
|
211
|
+
if _loop_warning_count >= 3:
|
|
212
|
+
logger.critical(
|
|
213
|
+
f"Goose appears stuck in a retry loop (same stderr {LOOP_DETECT_THRESHOLD}x): "
|
|
214
|
+
f"{recent_list[-1][:200]}"
|
|
215
|
+
)
|
|
216
|
+
proc.kill()
|
|
217
|
+
break
|
|
218
|
+
time.sleep(min(HEARTBEAT_INTERVAL, 30))
|
|
219
|
+
|
|
220
|
+
heartbeat_thread = threading.Thread(target=_heartbeat_loop, daemon=True)
|
|
221
|
+
heartbeat_thread.start()
|
|
222
|
+
|
|
223
|
+
# 主线程等待进程退出(有超时,防止 taskkill 失败导致永久卡死)
|
|
224
|
+
if timeout_seconds:
|
|
225
|
+
try:
|
|
226
|
+
proc.wait(timeout=timeout_seconds + 30)
|
|
227
|
+
except subprocess.TimeoutExpired:
|
|
228
|
+
logger.critical(f"Process {proc.pid} survived watchdog, force killing")
|
|
229
|
+
proc.kill()
|
|
230
|
+
try:
|
|
231
|
+
proc.wait(timeout=10)
|
|
232
|
+
except subprocess.TimeoutExpired:
|
|
233
|
+
logger.critical(f"Process {proc.pid} UNKILLABLE")
|
|
234
|
+
else:
|
|
235
|
+
proc.wait()
|
|
236
|
+
|
|
237
|
+
# 看门狗取消
|
|
238
|
+
if watchdog:
|
|
239
|
+
watchdog.cancel()
|
|
240
|
+
|
|
241
|
+
# 等待 I/O 线程结束
|
|
242
|
+
stdout_thread.join(timeout=5)
|
|
243
|
+
stderr_thread.join(timeout=5)
|
|
244
|
+
|
|
245
|
+
# 收集结果
|
|
246
|
+
stderr_text = "\n".join(stderr_lines)
|
|
247
|
+
|
|
248
|
+
if watchdog and watchdog.triggered:
|
|
249
|
+
return subprocess.CompletedProcess(
|
|
250
|
+
args=args, returncode=-1,
|
|
251
|
+
stdout="", stderr=f"Process killed by watchdog after {timeout_seconds}s"
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
if proc.returncode != 0:
|
|
255
|
+
logger.error(f"goose exited with code {proc.returncode}")
|
|
256
|
+
|
|
257
|
+
return subprocess.CompletedProcess(
|
|
258
|
+
args=args,
|
|
259
|
+
returncode=proc.returncode,
|
|
260
|
+
stdout="",
|
|
261
|
+
stderr=stderr_text,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def run_stage(
|
|
266
|
+
recipe: str,
|
|
267
|
+
max_turns: int,
|
|
268
|
+
params: dict[str, str],
|
|
269
|
+
cwd: Path | None = None,
|
|
270
|
+
timeout_minutes: int | None = None,
|
|
271
|
+
quiet: bool = True,
|
|
272
|
+
env: dict[str, str] | None = None,
|
|
273
|
+
) -> subprocess.CompletedProcess:
|
|
274
|
+
"""执行 goose recipe 阶段。
|
|
275
|
+
|
|
276
|
+
timeout_minutes=None 时无超时限制(阶段级执行),>0 时启用心跳看门狗。
|
|
277
|
+
quiet=True 时传 -q 给 goose,隐藏文件扫描噪音,仅显示模型回复。
|
|
278
|
+
env 注入自定义环境变量(如 JAVA_HOME)。
|
|
279
|
+
"""
|
|
280
|
+
recipe_path = Path(recipe)
|
|
281
|
+
args = _build_args(str(recipe_path), max_turns, params, quiet=quiet)
|
|
282
|
+
|
|
283
|
+
logger.info(f"goose run --recipe {recipe_path.name} --max-turns {max_turns}" +
|
|
284
|
+
(" -q" if quiet else ""))
|
|
285
|
+
logger.debug(f"stage params: {params}")
|
|
286
|
+
|
|
287
|
+
timeout_secs = (timeout_minutes * 60) if timeout_minutes else None
|
|
288
|
+
return _run_with_watchdog(args, cwd or Path.cwd(), timeout_secs, env=env)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def run_task(
|
|
292
|
+
recipe: str,
|
|
293
|
+
max_turns: int,
|
|
294
|
+
params: dict[str, str],
|
|
295
|
+
cwd: Path,
|
|
296
|
+
timeout_minutes: int = 15,
|
|
297
|
+
on_timeout=None,
|
|
298
|
+
quiet: bool = True,
|
|
299
|
+
env: dict[str, str] | None = None,
|
|
300
|
+
) -> subprocess.CompletedProcess:
|
|
301
|
+
"""执行单个任务。与 run_stage 相同流程,但始终启用心跳看门狗超时控制。
|
|
302
|
+
|
|
303
|
+
on_timeout 在进程被看门狗终止后调用(用于沙箱清理等)。
|
|
304
|
+
quiet=True 时传 -q 给 goose,隐藏文件扫描噪音,仅显示模型回复。
|
|
305
|
+
env 注入自定义环境变量(如 JAVA_HOME)。
|
|
306
|
+
"""
|
|
307
|
+
recipe_path = Path(recipe)
|
|
308
|
+
args = _build_args(str(recipe_path), max_turns, params, quiet=quiet)
|
|
309
|
+
|
|
310
|
+
logger.info(f"task: goose run --recipe {recipe_path.name} --max-turns {max_turns}" +
|
|
311
|
+
(" -q" if quiet else ""))
|
|
312
|
+
logger.debug(f"task params: {params}")
|
|
313
|
+
logger.debug(f"goose args: {args}")
|
|
314
|
+
|
|
315
|
+
return _run_with_watchdog(args, cwd, timeout_minutes * 60, on_timeout=on_timeout, env=env)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
class JdkNotFound(Exception):
|
|
319
|
+
"""未找到匹配版本的 JDK。"""
|
|
320
|
+
def __init__(self, required: int, searched: list[str]):
|
|
321
|
+
self.required = required
|
|
322
|
+
self.searched = searched
|
|
323
|
+
msg = (
|
|
324
|
+
f"未找到 JDK {required}。已搜索:\n" +
|
|
325
|
+
"\n".join(f" - {p}" for p in searched) +
|
|
326
|
+
f"\n请安装 JDK {required} 或设置 JAVA_HOME 环境变量。"
|
|
327
|
+
)
|
|
328
|
+
super().__init__(msg)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def detect_jdk(required_version: int = 17) -> str:
|
|
332
|
+
"""扫描系统找到匹配主版本的 JDK,返回 JAVA_HOME 路径。
|
|
333
|
+
|
|
334
|
+
搜索顺序:D 盘 Azul Zulu → common JDK 路径 → PATH 中的 javac。
|
|
335
|
+
找不到则抛出 JdkNotFound。
|
|
336
|
+
"""
|
|
337
|
+
search_roots = [
|
|
338
|
+
# D 盘常见路径
|
|
339
|
+
Path("D:/"),
|
|
340
|
+
# 系统盘常见路径
|
|
341
|
+
Path("C:/Program Files/Eclipse Adoptium"),
|
|
342
|
+
Path("C:/Program Files/Java"),
|
|
343
|
+
]
|
|
344
|
+
|
|
345
|
+
javac_paths: list[Path] = []
|
|
346
|
+
|
|
347
|
+
# 1. 扫描已知安装目录
|
|
348
|
+
for root in search_roots:
|
|
349
|
+
if not root.exists():
|
|
350
|
+
continue
|
|
351
|
+
if root.name == "D:/" or root == Path("D:/"):
|
|
352
|
+
# 扫描 D 盘根目录下的 JDK 目录
|
|
353
|
+
for d in root.iterdir():
|
|
354
|
+
if d.is_dir() and ("jdk" in d.name.lower() or "zulu" in d.name.lower()):
|
|
355
|
+
javac = d / "bin" / "javac.exe"
|
|
356
|
+
if javac.exists():
|
|
357
|
+
javac_paths.append(javac)
|
|
358
|
+
else:
|
|
359
|
+
for d in root.glob("jdk*"):
|
|
360
|
+
javac = d / "bin" / "javac.exe"
|
|
361
|
+
if javac.exists():
|
|
362
|
+
javac_paths.append(javac)
|
|
363
|
+
for d in root.glob("*"):
|
|
364
|
+
if d.is_dir():
|
|
365
|
+
javac = d / "bin" / "javac.exe"
|
|
366
|
+
if javac.exists():
|
|
367
|
+
javac_paths.append(javac)
|
|
368
|
+
|
|
369
|
+
# 2. PATH 中的 javac
|
|
370
|
+
import shutil as _shutil
|
|
371
|
+
path_javac = _shutil.which("javac")
|
|
372
|
+
if path_javac:
|
|
373
|
+
javac_paths.append(Path(path_javac))
|
|
374
|
+
|
|
375
|
+
# 3. 逐个检查版本
|
|
376
|
+
seen = set()
|
|
377
|
+
for javac in javac_paths:
|
|
378
|
+
javac = javac.resolve()
|
|
379
|
+
key = str(javac)
|
|
380
|
+
if key in seen:
|
|
381
|
+
continue
|
|
382
|
+
seen.add(key)
|
|
383
|
+
try:
|
|
384
|
+
proc = subprocess.run(
|
|
385
|
+
[str(javac), "-version"],
|
|
386
|
+
capture_output=True, text=True, timeout=10,
|
|
387
|
+
)
|
|
388
|
+
output = proc.stdout + proc.stderr
|
|
389
|
+
version_str = _parse_javac_version(output)
|
|
390
|
+
if version_str and version_str[0] == required_version:
|
|
391
|
+
java_home = str(javac.parent.parent)
|
|
392
|
+
logger.info(f"JDK {required_version} detected: {java_home} (v{'.'.join(map(str, version_str))})")
|
|
393
|
+
return java_home
|
|
394
|
+
except Exception:
|
|
395
|
+
continue
|
|
396
|
+
|
|
397
|
+
raise JdkNotFound(required_version, [str(p) for p in javac_paths])
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _parse_javac_version(output: str) -> tuple[int, ...] | None:
|
|
401
|
+
"""从 javac -version 输出中提取版本号。如 'javac 17.0.13' → (17, 0, 13)。"""
|
|
402
|
+
import re
|
|
403
|
+
m = re.search(r'(\d+)\.(\d+)(?:\.(\d+))?', output)
|
|
404
|
+
if m:
|
|
405
|
+
return tuple(int(x) for x in m.groups() if x is not None)
|
|
406
|
+
return None
|
ai_dev_flow/git_ops.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Git 操作封装 — 自动提交、stash、commit hash 提取。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import subprocess
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger("ai-dev-flow")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class GitOps:
|
|
13
|
+
"""管理任务驱动的 Git 操作。"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, repo_root: Path):
|
|
16
|
+
self.repo = repo_root
|
|
17
|
+
if not (repo_root / ".git").exists():
|
|
18
|
+
raise RuntimeError(f"Not a git repository: {repo_root}")
|
|
19
|
+
self._branch = self._detect_branch()
|
|
20
|
+
self._tracking_remote, self._tracking_ref = self._detect_upstream()
|
|
21
|
+
|
|
22
|
+
def _detect_branch(self) -> str:
|
|
23
|
+
"""检测当前分支名。"""
|
|
24
|
+
try:
|
|
25
|
+
result = subprocess.run(
|
|
26
|
+
["git", "-C", str(self.repo), "rev-parse", "--abbrev-ref", "HEAD"],
|
|
27
|
+
capture_output=True, text=True, timeout=5,
|
|
28
|
+
)
|
|
29
|
+
return result.stdout.strip()
|
|
30
|
+
except Exception:
|
|
31
|
+
logger.warning("Cannot detect current branch")
|
|
32
|
+
return ""
|
|
33
|
+
|
|
34
|
+
def _detect_upstream(self) -> tuple[str, str]:
|
|
35
|
+
"""检测当前分支的 tracking remote 和 merge ref。返回 (remote, ref)。"""
|
|
36
|
+
if not self._branch:
|
|
37
|
+
return ("", "")
|
|
38
|
+
try:
|
|
39
|
+
remote = subprocess.run(
|
|
40
|
+
["git", "-C", str(self.repo), "config",
|
|
41
|
+
f"branch.{self._branch}.remote"],
|
|
42
|
+
capture_output=True, text=True, timeout=5,
|
|
43
|
+
)
|
|
44
|
+
merge = subprocess.run(
|
|
45
|
+
["git", "-C", str(self.repo), "config",
|
|
46
|
+
f"branch.{self._branch}.merge"],
|
|
47
|
+
capture_output=True, text=True, timeout=5,
|
|
48
|
+
)
|
|
49
|
+
r = remote.stdout.strip()
|
|
50
|
+
m = merge.stdout.strip()
|
|
51
|
+
if r and m:
|
|
52
|
+
logger.debug(f"Upstream: {r}/{m} (branch={self._branch})")
|
|
53
|
+
else:
|
|
54
|
+
logger.warning(f"No upstream tracking for branch '{self._branch}'")
|
|
55
|
+
return (r, m)
|
|
56
|
+
except Exception:
|
|
57
|
+
return ("", "")
|
|
58
|
+
|
|
59
|
+
def commit_task(self, task_id: str, task_name: str, category: str, priority: str,
|
|
60
|
+
estimated_turns: int) -> str | None:
|
|
61
|
+
"""Stage 所有变更并提交,返回 commit hash。无变更时返回 None。"""
|
|
62
|
+
# Check if there's anything to commit
|
|
63
|
+
status = subprocess.run(
|
|
64
|
+
["git", "-C", str(self.repo), "status", "--porcelain"],
|
|
65
|
+
capture_output=True, text=True
|
|
66
|
+
)
|
|
67
|
+
if not status.stdout.strip():
|
|
68
|
+
logger.debug(f"No changes to commit for task {task_id}")
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
# Stage all changes
|
|
72
|
+
subprocess.run(
|
|
73
|
+
["git", "-C", str(self.repo), "add", "-A"],
|
|
74
|
+
capture_output=True, text=True
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
message = (
|
|
78
|
+
f"[ai-dev-flow] {task_id}: {task_name}\n\n"
|
|
79
|
+
f"Category: {category}\n"
|
|
80
|
+
f"Priority: {priority}\n"
|
|
81
|
+
f"Estimated turns: {estimated_turns}"
|
|
82
|
+
)
|
|
83
|
+
result = subprocess.run(
|
|
84
|
+
["git", "-C", str(self.repo), "commit", "-m", message],
|
|
85
|
+
capture_output=True, text=True
|
|
86
|
+
)
|
|
87
|
+
if result.returncode != 0:
|
|
88
|
+
logger.error(f"Git commit failed: {result.stderr}")
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
# Get commit hash
|
|
92
|
+
hash_result = subprocess.run(
|
|
93
|
+
["git", "-C", str(self.repo), "rev-parse", "HEAD"],
|
|
94
|
+
capture_output=True, text=True
|
|
95
|
+
)
|
|
96
|
+
commit_hash = hash_result.stdout.strip()[:8]
|
|
97
|
+
logger.info(f"Task {task_id} committed: {commit_hash}")
|
|
98
|
+
return commit_hash
|
|
99
|
+
|
|
100
|
+
def commit_files(self, file_paths: list[str], task_id: str, task_name: str,
|
|
101
|
+
category: str, priority: str,
|
|
102
|
+
estimated_turns: int) -> str | None:
|
|
103
|
+
"""仅 stage 指定文件并提交。无变更时返回 None。"""
|
|
104
|
+
if not file_paths:
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
for fp in file_paths:
|
|
108
|
+
subprocess.run(
|
|
109
|
+
["git", "-C", str(self.repo), "add", fp],
|
|
110
|
+
capture_output=True, text=True,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
message = (
|
|
114
|
+
f"[ai-dev-flow] {task_id}: {task_name}\n\n"
|
|
115
|
+
f"Category: {category}\n"
|
|
116
|
+
f"Priority: {priority}\n"
|
|
117
|
+
f"Estimated turns: {estimated_turns}"
|
|
118
|
+
)
|
|
119
|
+
result = subprocess.run(
|
|
120
|
+
["git", "-C", str(self.repo), "commit", "-m", message],
|
|
121
|
+
capture_output=True, text=True,
|
|
122
|
+
)
|
|
123
|
+
if result.returncode != 0:
|
|
124
|
+
logger.error(f"Git commit failed: {result.stderr}")
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
hash_result = subprocess.run(
|
|
128
|
+
["git", "-C", str(self.repo), "rev-parse", "HEAD"],
|
|
129
|
+
capture_output=True, text=True,
|
|
130
|
+
)
|
|
131
|
+
commit_hash = hash_result.stdout.strip()[:8]
|
|
132
|
+
logger.info(f"Task {task_id} committed ({len(file_paths)} files): {commit_hash}")
|
|
133
|
+
return commit_hash
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def can_push(self) -> bool:
|
|
137
|
+
"""是否具备推送条件:有 remote 且 tracking 已配置。"""
|
|
138
|
+
return bool(self._tracking_remote and self._tracking_ref and self._branch)
|
|
139
|
+
|
|
140
|
+
def push(self) -> bool:
|
|
141
|
+
"""推送当前分支到 tracking remote。失败时返回 False 不抛异常。
|
|
142
|
+
|
|
143
|
+
先检测当前分支的 upstream (branch.<name>.remote + merge),
|
|
144
|
+
若未配置 tracking 则跳过推送并告警。
|
|
145
|
+
"""
|
|
146
|
+
if not self.can_push:
|
|
147
|
+
logger.warning(
|
|
148
|
+
f"Cannot push: branch '{self._branch}' has no tracking remote configured"
|
|
149
|
+
)
|
|
150
|
+
return False
|
|
151
|
+
|
|
152
|
+
try:
|
|
153
|
+
result = subprocess.run(
|
|
154
|
+
["git", "-C", str(self.repo), "push",
|
|
155
|
+
self._tracking_remote, f"HEAD:{self._tracking_ref}"],
|
|
156
|
+
capture_output=True, text=True,
|
|
157
|
+
timeout=30,
|
|
158
|
+
)
|
|
159
|
+
if result.returncode != 0:
|
|
160
|
+
logger.warning(f"Git push failed: {result.stderr.strip()}")
|
|
161
|
+
return False
|
|
162
|
+
logger.info(
|
|
163
|
+
f"Pushed to {self._tracking_remote}/{self._tracking_ref} "
|
|
164
|
+
f"(branch={self._branch})"
|
|
165
|
+
)
|
|
166
|
+
return True
|
|
167
|
+
except subprocess.TimeoutExpired:
|
|
168
|
+
logger.warning("Git push timed out")
|
|
169
|
+
return False
|
|
170
|
+
except Exception:
|
|
171
|
+
logger.warning("Git push failed (network/permission)")
|
|
172
|
+
return False
|
|
173
|
+
|
|
174
|
+
def pre_task_check(self) -> bool:
|
|
175
|
+
"""检查工作区是否干净,不干净时自动 stash。"""
|
|
176
|
+
status = subprocess.run(
|
|
177
|
+
["git", "-C", str(self.repo), "status", "--porcelain"],
|
|
178
|
+
capture_output=True, text=True
|
|
179
|
+
)
|
|
180
|
+
if status.stdout.strip():
|
|
181
|
+
logger.warning("Working tree is dirty, creating auto-stash")
|
|
182
|
+
subprocess.run(
|
|
183
|
+
["git", "-C", str(self.repo), "stash", "push", "-m",
|
|
184
|
+
"ai-dev-flow auto-stash before task"],
|
|
185
|
+
capture_output=True, text=True
|
|
186
|
+
)
|
|
187
|
+
return True
|