-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathacoder.py
More file actions
executable file
·1466 lines (1171 loc) · 46.3 KB
/
acoder.py
File metadata and controls
executable file
·1466 lines (1171 loc) · 46.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
ACoder - 工具脚本
用于项目操作、任务管理等核心功能
混合模式:
- 此脚本负责:创建目录、模板文件、JSON 读写、状态更新
- AI 负责:需求分析、任务拆分、代码编写、测试验证
路径自动检测:
- 自动查找当前目录及父目录下的 .acoder 目录
- 如果不存在,自动在当前目录创建
"""
import json
import sys
import os
import subprocess
from pathlib import Path
from datetime import datetime
from typing import Optional
# 配置
SKILL_PATH = Path.home() / ".claude" / "skills" / "acoder"
CONFIG_FILE = SKILL_PATH / "config.json"
TEMPLATES_PATH = SKILL_PATH / "templates"
# 自动检测的路径缓存
_detected_paths = None
def find_acoder_dir(start_path: Path = None) -> Path:
"""
查找工作目录
查找顺序:
1. 当前工作目录下的 .acoder
2. 逐级向上查找父目录下的 .acoder
3. 查找现有的 projects/ 目录(兼容旧版)
4. 如果都没找到,在当前目录创建 .acoder
"""
if start_path is None:
start_path = Path.cwd()
# 1. 从当前目录开始查找 .acoder
current = start_path
while current != current.parent:
candidate = current / ".acoder"
if candidate.exists() and candidate.is_dir():
return candidate
current = current.parent
# 检查根目录
candidate = current / ".acoder"
if candidate.exists() and candidate.is_dir():
return candidate
# 2. 查找现有的 projects/ 目录(兼容旧版结构)
current = start_path
while current != current.parent:
projects_dir = current / "projects"
if projects_dir.exists() and projects_dir.is_dir():
# 检查是否有 project.json 文件(确认是 acoder 的 projects 目录)
has_project = any(
(p / "project.json").exists()
for p in projects_dir.iterdir()
if p.is_dir()
)
if has_project:
# 返回父目录作为工作目录
return current
current = current.parent
# 3. 没找到,在当前工作目录创建 .acoder
acoder_dir = Path.cwd() / ".acoder"
acoder_dir.mkdir(parents=True, exist_ok=True)
(acoder_dir / "projects").mkdir(exist_ok=True)
return acoder_dir
def detect_paths() -> dict:
"""
自动检测项目路径
工作目录为 .acoder/,在当前项目下创建
返回:
{
"acoder_path": ".acoder 目录路径",
"projects_path": "项目存储目录",
"code_base_path": "代码库根目录"
}
"""
global _detected_paths
if _detected_paths is not None:
return _detected_paths
# 先检查配置文件是否有硬编码路径
config = load_config()
if not config.get("auto_detect_paths", True):
# 使用配置文件中的路径
_detected_paths = {
"acoder_path": Path(config.get("acoder_path", Path.cwd() / ".acoder")),
"projects_path": Path(config.get("projects_path", Path.cwd() / ".acoder" / "projects")),
"code_base_path": Path(config.get("code_base_path", Path.cwd())),
}
return _detected_paths
# 自动检测:查找或创建 .acoder 目录
start_path = Path.cwd()
current = start_path
# 1. 从当前目录开始向上查找 .acoder
while current != current.parent:
candidate = current / ".acoder"
if candidate.exists() and candidate.is_dir():
projects_dir = candidate / "projects"
projects_dir.mkdir(exist_ok=True)
_detected_paths = {
"acoder_path": candidate,
"projects_path": projects_dir,
"code_base_path": current,
}
return _detected_paths
current = current.parent
# 2. 没找到,在当前工作目录创建 .acoder
acoder_dir = Path.cwd() / ".acoder"
acoder_dir.mkdir(parents=True, exist_ok=True)
projects_dir = acoder_dir / "projects"
projects_dir.mkdir(exist_ok=True)
_detected_paths = {
"acoder_path": acoder_dir,
"projects_path": projects_dir,
"code_base_path": Path.cwd(),
}
return _detected_paths
def load_config() -> dict:
"""加载配置"""
if CONFIG_FILE.exists():
with open(CONFIG_FILE) as f:
return json.load(f)
return {
"auto_detect_paths": True,
"auto_commit": True,
"default_priority": "medium",
}
def get_project_path(project_name: str) -> Path:
"""获取项目路径"""
paths = detect_paths()
return paths["projects_path"] / project_name
def project_exists(project_name: str) -> bool:
"""检查项目是否存在"""
return get_project_path(project_name).exists()
def create_project(project_name: str, description: str = "", branch: str = None, create_branch: bool = False) -> dict:
"""创建新项目目录结构
参数:
project_name: 项目名
description: 项目描述
branch: 指定分支名(None 表示使用项目名作为分支名)
create_branch: 是否创建分支(默认不创建)
"""
project_path = get_project_path(project_name)
if project_path.exists():
return {"success": False, "error": f"项目 '{project_name}' 已存在"}
# 分支处理逻辑
branch_name = None
branch_created = False
code_base = get_code_base_path()
# 获取当前分支
try:
result = subprocess.run(
["git", "branch", "--show-current"],
cwd=code_base,
capture_output=True,
text=True
)
current_branch = result.stdout.strip()
except:
current_branch = "unknown"
# 只有明确指定 create_branch=True 时才创建新分支
if create_branch:
branch_name = branch if branch else project_name
try:
subprocess.run(
["git", "checkout", "-b", branch_name],
cwd=code_base,
check=True,
capture_output=True
)
branch_created = True
except subprocess.CalledProcessError as e:
return {"success": False, "error": f"创建分支失败: {e.stderr}"}
else:
# 不创建分支,使用当前分支
branch_name = current_branch if current_branch else "main"
# 创建目录结构
(project_path / "logs").mkdir(parents=True)
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 使用模板文件
template_project = TEMPLATES_PATH / "project.json"
# 创建 project.json
if template_project.exists():
with open(template_project) as f:
project_json = json.load(f)
project_json["id"] = project_name
project_json["name"] = project_name
project_json["status"] = "initialized"
project_json["created_at"] = now
project_json["updated_at"] = now
project_json["description"] = description
project_json["branch"] = branch_name
project_json["session"] = {
"phase": "initialized",
"current_step": 0,
"total_steps": 0,
"current_task_id": None
}
else:
project_json = {
"id": project_name,
"name": project_name,
"status": "initialized",
"created_at": now,
"updated_at": now,
"paused_at": None,
"description": description,
"target_path": "../../",
"total_features": 0,
"completed_features": 0,
"branch": branch_name,
"session": {
"phase": "initialized",
"current_step": 0,
"total_steps": 0,
"current_task_id": None
}
}
with open(project_path / "project.json", "w") as f:
json.dump(project_json, f, indent=2, ensure_ascii=False)
# 创建 feature_list.md (Markdown 格式)
feature_md_content = f"""# Feature List: {project_name}
**Created**: {now}
**Description**: {description}
**Branch**: {branch_name or 'N/A'}
---
## 任务列表
<!-- 任务将由 AI 逐个添加,每个任务包含完整的上下文信息 -->
---
## 统计
- 总任务数: 0
- 已完成: 0
- 进行中: 0
"""
with open(project_path / "feature_list.md", "w") as f:
f.write(feature_md_content)
# 同时保留 JSON 格式用于程序化处理
feature_json = {
"features": [],
"implementation_order": [],
"phases": [],
"metadata": {
"project_name": project_name,
"created_at": now,
"description": description,
"branch": branch_name,
},
}
with open(project_path / "feature_list.json", "w") as f:
json.dump(feature_json, f, indent=2, ensure_ascii=False)
# 创建 progress.txt
progress_content = f"""# Agent Progress Log
## Session 0 - Initialization
- Date: {now}
- Agent: Initializer
- Action: Project initialization
### Completed:
- Created project structure
- Created feature_list.json (empty - waiting for AI analysis)
- Created progress.txt
### Next Steps:
- AI will analyze requirements and populate feature_list.json
- Run /acoder code to start implementation
---
"""
with open(project_path / "progress.txt", "w") as f:
f.write(progress_content)
# 创建 init.sh
init_sh = """#!/bin/bash
# 项目初始化脚本
# 请根据项目需要修改此脚本
set -e
echo "初始化项目环境..."
# TODO: 添加项目特定的初始化命令
# 例如:
# - 安装依赖
# - 启动开发服务器
# - 运行测试
echo "初始化完成"
"""
with open(project_path / "init.sh", "w") as f:
f.write(init_sh)
os.chmod(project_path / "init.sh", 0o755)
return {
"success": True,
"path": str(project_path),
"branch": branch_name,
"branch_created": branch_created,
"message": f"项目目录已创建" + (f",分支: {branch_name}" if branch_name else ""),
}
def update_session(project_name: str, phase: str = None, current_step: int = None,
total_steps: int = None, current_task_id: str = None) -> dict:
"""更新会话状态"""
project_path = get_project_path(project_name)
project_file = project_path / "project.json"
if not project_file.exists():
return {"success": False, "error": "project.json 不存在"}
with open(project_file) as f:
data = json.load(f)
if "session" not in data:
data["session"] = {}
if phase is not None:
data["session"]["phase"] = phase
if current_step is not None:
data["session"]["current_step"] = current_step
if total_steps is not None:
data["session"]["total_steps"] = total_steps
if current_task_id is not None:
data["session"]["current_task_id"] = current_task_id
data["updated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(project_file, "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
return {"success": True, "session": data["session"]}
def get_session(project_name: str) -> dict:
"""获取会话状态"""
data = load_project(project_name)
if not data.get("success"):
return {"success": False, "error": data.get("error")}
project = data.get("project", {})
return {
"success": True,
"session": project.get("session", {
"phase": "unknown",
"current_step": 0,
"total_steps": 0,
"current_task_id": None
})
}
def get_phases_status(project_name: str) -> dict:
"""获取 Phases 状态(用于可视化显示)"""
data = load_project(project_name)
if not data.get("success"):
return {"success": False, "error": data.get("error")}
features = data.get("features", {}).get("features", [])
phases_data = data.get("features", {}).get("phases", [])
implementation_order = data.get("features", {}).get("implementation_order", [])
# 如果没有 phases,按任务顺序生成默认 phases
if not phases_data:
phases_data = [{
"id": "phase-1",
"name": "Phase 1",
"description": "实现阶段",
"tasks": implementation_order,
"status": "in_progress" if any(not f.get("passes") for f in features) else "completed"
}]
# 更新每个 phase 的状态
feature_map = {f["id"]: f for f in features}
phases_status = []
for phase in phases_data:
phase_tasks = phase.get("tasks", [])
completed_in_phase = sum(1 for tid in phase_tasks if feature_map.get(tid, {}).get("passes", False))
total_in_phase = len(phase_tasks)
phase_status = {
"id": phase["id"],
"name": phase["name"],
"description": phase.get("description", ""),
"completed": completed_in_phase,
"total": total_in_phase,
"status": "completed" if completed_in_phase == total_in_phase and total_in_phase > 0 else
"in_progress" if completed_in_phase > 0 else "pending",
"tasks": [
{
"id": tid,
"description": feature_map.get(tid, {}).get("description", ""),
"passes": feature_map.get(tid, {}).get("passes", False)
}
for tid in phase_tasks
]
}
phases_status.append(phase_status)
return {
"success": True,
"phases": phases_status,
"total_tasks": len(features),
"completed_tasks": sum(1 for f in features if f.get("passes", False))
}
def load_project(project_name: str) -> dict:
"""加载项目信息"""
project_path = get_project_path(project_name)
if not project_path.exists():
return {"success": False, "error": f"项目 '{project_name}' 不存在"}
result = {"success": True, "path": str(project_path)}
project_file = project_path / "project.json"
if project_file.exists():
with open(project_file) as f:
result["project"] = json.load(f)
feature_file = project_path / "feature_list.json"
if feature_file.exists():
with open(feature_file) as f:
result["features"] = json.load(f)
progress_file = project_path / "progress.txt"
if progress_file.exists():
result["progress"] = progress_file.read_text()
return result
def get_next_task(project_name: str) -> Optional[dict]:
"""获取下一个待完成任务"""
data = load_project(project_name)
if not data.get("success"):
return None
features = data.get("features", {}).get("features", [])
order = data.get("features", {}).get("implementation_order", [])
feature_map = {f["id"]: f for f in features}
# 按 implementation_order 找下一个可执行的任务
for fid in order:
if fid in feature_map and not feature_map[fid].get("passes", False):
deps = feature_map[fid].get("dependencies", [])
deps_ok = all(feature_map.get(d, {}).get("passes", False) for d in deps)
if deps_ok:
return feature_map[fid]
# 如果没有 order,按顺序找
for f in features:
if not f.get("passes", False):
deps = f.get("dependencies", [])
deps_ok = all(
any(x["id"] == d and x.get("passes", False) for x in features)
for d in deps
)
if deps_ok:
return f
return None
def update_task_status(project_name: str, task_id: str, passes: bool) -> dict:
"""更新任务状态(同时更新 JSON 和 Markdown)"""
project_path = get_project_path(project_name)
feature_file = project_path / "feature_list.json"
if not feature_file.exists():
return {"success": False, "error": "feature_list.json 不存在"}
with open(feature_file) as f:
data = json.load(f)
found = False
for feature in data["features"]:
if feature["id"] == task_id:
feature["passes"] = passes
feature["completed_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") if passes else None
found = True
break
if not found:
return {"success": False, "error": f"任务 '{task_id}' 不存在"}
with open(feature_file, "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# 同步更新 Markdown 文件
md_file = project_path / "feature_list.md"
if md_file.exists():
with open(md_file) as f:
md_content = f.read()
import re
# 更新任务标题行的状态
status_pattern = rf"(## {re.escape(task_id)}:.*?\n\n\*\*状态\*:) [^\n]+"
new_status = "✅ 已完成" if passes else "⬜ 待完成"
md_content = re.sub(status_pattern, rf"\1 {new_status}", md_content)
# 更新完成时间
if passes:
time_pattern = rf"(## {re.escape(task_id)}:.*?\n\n\*\*状态\*.*?\n)"
replacement = rf"\1**完成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
md_content = re.sub(time_pattern, replacement, md_content, flags=re.DOTALL)
# 更新统计
completed = sum(1 for f in data["features"] if f.get("passes"))
md_content = update_stats_in_md(md_content, len(data["features"]), completed)
with open(md_file, "w") as f:
f.write(md_content)
# 更新 project.json
project_file = project_path / "project.json"
if project_file.exists():
with open(project_file) as f:
project_data = json.load(f)
completed = sum(1 for f in data["features"] if f.get("passes"))
project_data["completed_features"] = completed
project_data["updated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(project_file, "w") as f:
json.dump(project_data, f, indent=2, ensure_ascii=False)
return {"success": True}
def add_task(
project_name: str,
task_id: str,
description: str,
category: str = "functional",
priority: str = "medium",
steps: list = None,
files_affected: list = None,
dependencies: list = None,
) -> dict:
"""添加任务"""
project_path = get_project_path(project_name)
feature_file = project_path / "feature_list.json"
if not feature_file.exists():
return {"success": False, "error": "feature_list.json 不存在"}
with open(feature_file) as f:
data = json.load(f)
# 检查 ID 是否已存在
if any(f["id"] == task_id for f in data["features"]):
return {"success": False, "error": f"任务 ID '{task_id}' 已存在"}
new_task = {
"id": task_id,
"category": category,
"priority": priority,
"description": description,
"steps": steps or [],
"files_affected": files_affected or [],
"dependencies": dependencies or [],
"passes": False,
"completed_at": None,
}
data["features"].append(new_task)
data["implementation_order"].append(task_id)
with open(feature_file, "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
return {"success": True, "task": new_task}
def list_projects() -> list:
"""列出所有项目"""
paths = detect_paths()
projects_path = paths["projects_path"]
if not projects_path.exists():
return []
projects = []
for project_dir in projects_path.iterdir():
if project_dir.is_dir():
project_file = project_dir / "project.json"
feature_file = project_dir / "feature_list.json"
project_info = {"name": project_dir.name, "path": str(project_dir)}
if project_file.exists():
try:
with open(project_file) as f:
project_info["project"] = json.load(f)
except json.JSONDecodeError:
project_info["project_error"] = "Invalid JSON"
if feature_file.exists():
try:
with open(feature_file) as f:
feature_data = json.load(f)
features = feature_data.get("features", [])
total = len(features)
completed = sum(1 for f in features if f.get("passes", False))
project_info["progress"] = f"{completed}/{total}"
except json.JSONDecodeError:
project_info["progress"] = "JSON Error"
projects.append(project_info)
return projects
def append_progress(project_name: str, content: str) -> dict:
"""追加进度记录"""
project_path = get_project_path(project_name)
progress_file = project_path / "progress.txt"
if not progress_file.exists():
return {"success": False, "error": "progress.txt 不存在"}
with open(progress_file, "a") as f:
f.write("\n" + content + "\n")
return {"success": True}
def save_feature_list(project_name: str, feature_list: dict) -> dict:
"""
保存完整的功能列表(AI 分析需求后调用此函数)
这是混合模式的核心函数:
- AI 负责分析需求、拆分任务
- 调用此函数保存结果
"""
project_path = get_project_path(project_name)
feature_file = project_path / "feature_list.json"
if not project_path.exists():
return {"success": False, "error": f"项目 '{project_name}' 不存在"}
# 验证格式
if "features" not in feature_list:
return {"success": False, "error": "feature_list 必须包含 'features' 字段"}
# 确保 implementation_order 存在
if "implementation_order" not in feature_list:
feature_list["implementation_order"] = [f["id"] for f in feature_list["features"]]
# 确保所有任务的 passes 为 false
for feature in feature_list["features"]:
feature["passes"] = False
feature["completed_at"] = None
# 更新 metadata
if "metadata" not in feature_list:
feature_list["metadata"] = {}
feature_list["metadata"]["updated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(feature_file, "w") as f:
json.dump(feature_list, f, indent=2, ensure_ascii=False)
# 同时生成 Markdown 版本
md_content = generate_feature_list_md(project_name, feature_list)
with open(project_path / "feature_list.md", "w") as f:
f.write(md_content)
# 更新 project.json
project_file = project_path / "project.json"
if project_file.exists():
with open(project_file) as f:
project_data = json.load(f)
project_data["total_features"] = len(feature_list["features"])
project_data["completed_features"] = 0
project_data["status"] = "ready"
project_data["updated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(project_file, "w") as f:
json.dump(project_data, f, indent=2, ensure_ascii=False)
total = len(feature_list["features"])
return {
"success": True,
"message": f"已保存 {total} 个任务",
"total_features": total,
}
def generate_feature_list_md(project_name: str, feature_list: dict) -> str:
"""生成 Markdown 格式的 feature_list"""
metadata = feature_list.get("metadata", {})
features = feature_list.get("features", [])
phases = feature_list.get("phases", [])
md = f"""# Feature List: {project_name}
**Created**: {metadata.get('created_at', 'N/A')}
**Description**: {metadata.get('description', 'N/A')}
**Branch**: {metadata.get('branch', 'N/A')}
---
"""
if phases:
md += "## Phases 概览\n\n"
for phase in phases:
md += f"### {phase.get('name', phase.get('id', 'Unknown'))}\n\n"
md += f"{phase.get('description', '')}\n\n"
for task_id in phase.get("tasks", []):
task = next((f for f in features if f["id"] == task_id), None)
if task:
status = "✅" if task.get("passes") else "⬜"
md += f"- {status} {task_id}: {task.get('title', task.get('description', 'No title'))}\n"
md += "\n"
md += "---\n\n"
md += "## 任务详情\n\n"
for feature in features:
md += generate_task_md(feature)
md += "\n---\n\n"
# 统计
completed = sum(1 for f in features if f.get("passes"))
md += f"""## 统计
- 总任务数: {len(features)}
- 已完成: {completed}
- 进行中: {len(features) - completed}
"""
return md
def generate_task_md(task: dict) -> str:
"""生成单个任务的 Markdown 内容"""
task_id = task.get("id", "Unknown")
title = task.get("title", task.get("description", "No title"))
status = "✅ 已完成" if task.get("passes") else "⬜ 待完成"
md = f"""## {task_id}: {title}
**状态**: {status}
"""
if task.get("completed_at"):
md += f"**完成时间**: {task['completed_at']}\n"
md += "\n"
# 背景
if task.get("background"):
md += f"""### 背景 (Background)
{task['background']}
"""
# 需求
if task.get("requirements"):
md += f"""### 需求 (Requirements)
{task['requirements']}
"""
# 技术设计
if task.get("tech_design"):
md += f"""### 技术设计 (Technical Design)
{task['tech_design']}
"""
# 验收标准
if task.get("acceptance_criteria"):
md += f"""### 验收标准 (Acceptance Criteria)
{task['acceptance_criteria']}
"""
# 影响文件
if task.get("files_affected"):
md += "### 影响文件 (Files Affected)\n\n"
for f in task["files_affected"]:
md += f"- `{f}`\n"
md += "\n"
# 依赖
if task.get("dependencies"):
md += "### 依赖 (Dependencies)\n\n"
for d in task["dependencies"]:
md += f"- {d}\n"
md += "\n"
return md
def add_task_md(
project_name: str,
task_id: str,
title: str,
background: str = "",
requirements: str = "",
tech_design: str = "",
acceptance_criteria: str = "",
files_affected: list = None,
dependencies: list = None,
priority: str = "medium",
) -> dict:
"""
添加任务(Markdown 格式,包含完整上下文)
这是新的推荐方式,每个任务包含:
- background: 任务背景
- requirements: 需求描述
- tech_design: 技术设计
- acceptance_criteria: 验收标准
- files_affected: 影响的文件
- dependencies: 依赖的任务
所有字段都应该是自包含的,不应引用外部文档。
"""
project_path = get_project_path(project_name)
if not project_path.exists():
return {"success": False, "error": f"项目 '{project_name}' 不存在"}
# 读取现有 JSON
feature_file = project_path / "feature_list.json"
if feature_file.exists():
with open(feature_file) as f:
data = json.load(f)
else:
data = {"features": [], "implementation_order": [], "phases": [], "metadata": {}}
# 检查 ID 是否已存在
if any(f["id"] == task_id for f in data.get("features", [])):
return {"success": False, "error": f"任务 ID '{task_id}' 已存在"}
# 创建新任务
new_task = {
"id": task_id,
"title": title,
"description": title, # 保持兼容性
"background": background,
"requirements": requirements,
"tech_design": tech_design,
"acceptance_criteria": acceptance_criteria,
"files_affected": files_affected or [],
"dependencies": dependencies or [],
"priority": priority,
"passes": False,
"completed_at": None,
}
data["features"].append(new_task)
data["implementation_order"].append(task_id)
# 保存 JSON
with open(feature_file, "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# 更新 Markdown 文件
md_file = project_path / "feature_list.md"
if md_file.exists():
with open(md_file) as f:
md_content = f.read()
# 在最后一个 "## 任务" 之前插入新任务(保持正序)
task_md = generate_task_md(new_task)
marker = "## 统计"
if marker in md_content:
# 在统计部分之前插入新任务
parts = md_content.rsplit(marker, 1)
new_content = parts[0] + task_md + "\n---\n\n" + marker + parts[1]
else:
# 没有统计部分,直接追加
new_content = md_content + "\n---\n\n" + task_md + "\n"
# 更新统计
new_content = update_stats_in_md(new_content, len(data["features"]), 0)
with open(md_file, "w") as f:
f.write(new_content)
# 更新 project.json
project_file = project_path / "project.json"
if project_file.exists():
with open(project_file) as f:
project_data = json.load(f)
project_data["total_features"] = len(data["features"])
project_data["updated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(project_file, "w") as f:
json.dump(project_data, f, indent=2, ensure_ascii=False)
return {"success": True, "task": new_task}
def update_stats_in_md(md_content: str, total: int, completed: int) -> str:
"""更新 Markdown 中的统计信息"""
import re
stats_pattern = r"## 统计\s*\n\s*- 总任务数: \d+\s*\n\s*- 已完成: \d+\s*\n\s*- 进行中: \d+"
new_stats = f"""## 统计
- 总任务数: {total}
- 已完成: {completed}
- 进行中: {total - completed}"""
return re.sub(stats_pattern, new_stats, md_content)
def get_task_full_context(project_name: str, task_id: str) -> Optional[str]:
"""
获取任务的完整上下文(Markdown 格式)
用于执行任务时提供完整上下文给子代理
"""
project_path = get_project_path(project_name)
md_file = project_path / "feature_list.md"
if not md_file.exists():
return None
with open(md_file) as f:
content = f.read()
# 提取指定任务的内容
import re
pattern = rf"## {re.escape(task_id)}:.*?(?=\n---\n|## [A-Z]+-\d+:|$)"
match = re.search(pattern, content, re.DOTALL)
if match:
return match.group(0).strip()
return None
def update_project_status(project_name: str, status: str) -> dict:
"""更新项目状态"""
project_path = get_project_path(project_name)