Repository navigation
Expand file tree
/
Copy pathkanban
More file actions
executable file
·746 lines (630 loc) · 25.6 KB
/
Copy pathkanban
File metadata and controls
executable file
·746 lines (630 loc) · 25.6 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
#!/usr/bin/env python3
import argparse
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Dict, Iterable, Optional
STATES = ("backlog", "todo", "working", "done", "archived", "trash")
TRANSITIONS = {
"backlog": {"todo", "archived", "trash"},
"todo": {"working", "archived", "trash"},
"working": {"done", "archived", "trash"},
"done": {"archived", "trash"},
"archived": {"trash"},
"trash": set(),
}
TASK_ID_RE = re.compile(r"^\d{8}-[a-z0-9]+(?:-[a-z0-9]+)*-task$")
SLUG_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
TYPE_NAMES = {
"feature": "Feature",
"bug": "Bug",
"chore": "Chore",
"research": "Research",
}
READY_SECTIONS = ("任务目标", "预期成果", "验收条件", "不在本轮范围")
ARCHIVE_RESULTS = {"completed", "cancelled", "duplicate", "wontfix"}
AGENT_NAMES = ("codex", "claude")
class KanbanError(Exception):
pass
@dataclass(frozen=True)
class Entry:
task_id: str
state: str
path: Path
document: Path
kind: str
@dataclass(frozen=True)
class Board:
"""一次扫描的结果.
无效入口不再让整个看板不可读: 它们进入 problems 由 `check` 汇报, 而与某个
任务 ID 绑定的违规 (重复 ID, 大任务缺 spec.md) 另外记入 blocked, 只让操作
该任务的命令失败. 未受影响的任务照常可读可迁移.
"""
entries: Dict[str, Entry]
blocked: Dict[str, str]
problems: list["Problem"]
@dataclass(frozen=True)
class Problem:
path: Path
message: str
def git_main_worktree(directory: Path) -> Optional[Path]:
try:
git = subprocess.run(
["git", "-C", str(directory), "worktree", "list", "--porcelain"],
text=True,
capture_output=True,
check=False,
)
except OSError:
return None
if git.returncode != 0:
return None
for line in git.stdout.splitlines():
if line.startswith("worktree "):
return Path(line.removeprefix("worktree ")).resolve()
return None
def board_root() -> Path:
configured = os.environ.get("KANBAN_DIR")
if configured:
return Path(configured).expanduser().resolve()
main_worktree = git_main_worktree(Path.cwd())
if main_worktree:
candidate = main_worktree / "kanban"
if candidate.is_dir():
return candidate.resolve()
current = Path.cwd().resolve()
for parent in (current, *current.parents):
candidate = parent / "kanban"
if candidate.is_dir():
return candidate.resolve()
raise KanbanError("找不到看板目录; 请在项目内运行或设置 KANBAN_DIR")
def global_rules_path() -> Path:
return Path.home() / ".agents" / "KANBAN-RULES.md"
def command_rules() -> None:
rules = global_rules_path()
if not rules.is_file():
raise KanbanError(f"全局规则不存在: {rules}")
sys.stdout.write(rules.read_text(encoding="utf-8"))
def add_git_exclude(root: Path) -> Optional[Path]:
try:
git_root_result = subprocess.run(
["git", "-C", str(root.parent), "rev-parse", "--show-toplevel"],
text=True,
capture_output=True,
check=False,
)
except OSError:
return None
if git_root_result.returncode != 0:
return None
git_root = Path(git_root_result.stdout.strip()).resolve()
try:
relative = root.resolve().relative_to(git_root)
except ValueError:
return None
exclude_result = subprocess.run(
["git", "-C", str(git_root), "rev-parse", "--git-path", "info/exclude"],
text=True,
capture_output=True,
check=False,
)
if exclude_result.returncode != 0:
raise KanbanError("无法定位 Git info/exclude")
exclude = Path(exclude_result.stdout.strip())
if not exclude.is_absolute():
exclude = git_root / exclude
pattern = f"/{relative.as_posix().strip('/')}/"
existing = exclude.read_text(encoding="utf-8") if exclude.exists() else ""
if pattern not in existing.splitlines():
exclude.parent.mkdir(parents=True, exist_ok=True)
with exclude.open("a", encoding="utf-8", newline="\n") as file:
if existing and not existing.endswith("\n"):
file.write("\n")
file.write(pattern + "\n")
return exclude.resolve()
def command_init(args: argparse.Namespace) -> None:
configured = os.environ.get("KANBAN_DIR")
if args.project and configured:
raise KanbanError("不能同时指定 project-path 和 KANBAN_DIR")
if args.project:
project = Path(args.project).expanduser().resolve()
if not project.is_dir():
raise KanbanError(f"项目目录不存在: {project}")
root = project / "kanban"
elif configured:
root = Path(configured).expanduser().resolve()
else:
project = git_main_worktree(Path.cwd()) or Path.cwd().resolve()
root = project / "kanban"
if root.exists() and not root.is_dir():
raise KanbanError(f"看板路径不是目录: {root}")
root.mkdir(parents=True, exist_ok=True)
for state in STATES:
path = root / state
if path.exists() and not path.is_dir():
raise KanbanError(f"状态路径不是目录: {path}")
path.mkdir(exist_ok=True)
exclude = add_git_exclude(root)
print(f"initialized: {root}")
if exclude:
print(f"git exclude: {exclude}")
print(f"rules: {global_rules_path()}")
def ensure_layout(root: Path) -> None:
if not root.is_dir():
raise KanbanError(f"看板目录不存在: {root}")
for state in STATES:
path = root / state
if not path.is_dir():
raise KanbanError(f"状态目录不存在: {path}")
def scan(root: Path) -> Board:
ensure_layout(root)
entries: Dict[str, Entry] = {}
blocked: Dict[str, str] = {}
problems: list[Problem] = []
def reject(path: Path, message: str, task_id: Optional[str] = None) -> None:
problems.append(Problem(path, message))
if task_id:
blocked[task_id] = message
entries.pop(task_id, None)
for state in STATES:
for path in sorted((root / state).iterdir(), key=lambda item: item.name):
if path.name.startswith("."):
continue
if path.is_symlink():
reject(path, f"任务入口不得是符号链接: {path}")
continue
if path.is_file() and path.name.endswith("-task.md"):
task_id, document, kind = path.name[:-3], path, "small"
elif path.is_dir() and path.name.endswith("-task"):
task_id, document, kind = path.name, path / "spec.md", "large"
else:
reject(path, f"无效任务入口: {path}")
continue
if not TASK_ID_RE.fullmatch(task_id):
reject(path, f"无效任务 ID: {task_id}")
continue
if kind == "large" and not document.is_file():
reject(path, f"大任务缺少 spec.md: {path}", task_id)
continue
if task_id in blocked:
problems.append(Problem(path, f"任务 ID 存在冲突: {task_id}"))
continue
if task_id in entries:
reject(path, f"重复任务 ID: {entries[task_id].path} 与 {path}", task_id)
continue
entries[task_id] = Entry(task_id, state, path, document, kind)
return Board(entries, blocked, problems)
def load_board(root: Path) -> Board:
board = scan(root)
if board.problems:
print(
f"kanban: 警告: {len(board.problems)} 个无效入口已忽略, 运行 kanban check 查看",
file=sys.stderr,
)
return board
def normalize_task_id(value: str) -> str:
if "/" in value or "\\" in value:
raise KanbanError("任务参数只能使用任务 ID 或入口名")
task_id = value[:-3] if value.endswith(".md") else value
if not TASK_ID_RE.fullmatch(task_id):
raise KanbanError(f"无效任务 ID: {value}")
return task_id
def locate(board: Board, value: str) -> Entry:
task_id = normalize_task_id(value)
if task_id in board.blocked:
raise KanbanError(board.blocked[task_id])
try:
return board.entries[task_id]
except KeyError as error:
raise KanbanError(f"任务不存在: {task_id}") from error
def read_document(entry: Entry) -> str:
try:
return entry.document.read_text(encoding="utf-8")
except UnicodeError as error:
raise KanbanError(f"任务文档不是有效 UTF-8: {entry.document}") from error
def title_from(text: str) -> str:
for line in text.splitlines():
if line.startswith("# "):
return line[2:].strip()
return "(无标题)"
def section_body(text: str, heading: str) -> Optional[str]:
match = re.search(rf"(?m)^## {re.escape(heading)}\s*$", text)
if not match:
return None
next_heading = re.search(r"(?m)^## ", text[match.end() :])
end = match.end() + next_heading.start() if next_heading else len(text)
return text[match.end() : end].strip()
def result_from(text: str) -> str:
match = re.search(r"(?m)^- 结果:\s*(.*?)\s*$", text)
return match.group(1) if match else ""
def metadata_from(text: str, name: str) -> str:
match = re.search(rf"(?m)^- {re.escape(name)}:[ \t]*(.*?)[ \t]*$", text)
return match.group(1) if match else ""
def completion_metadata(text: str) -> str:
value = datetime.now().strftime("%Y-%m-%d %H:%M")
matches = list(re.finditer(r"(?m)^- 完成时间:.*$", text))
if len(matches) == 1:
return re.sub(r"(?m)^- 完成时间:.*$", f"- 完成时间: {value}", text, count=1)
if matches:
raise KanbanError("任务文档缺少唯一元数据字段: 完成时间")
started = list(re.finditer(r"(?m)^- 开始时间:.*$", text))
if len(started) != 1:
raise KanbanError("任务文档缺少唯一元数据字段: 开始时间")
return re.sub(
r"(?m)^(- 开始时间:.*)$", rf"\1\n- 完成时间: {value}", text, count=1
)
def write_text_atomic(path: Path, text: str) -> None:
handle, temp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
temp_path = Path(temp_name)
try:
with os.fdopen(handle, "w", encoding="utf-8", newline="\n") as file:
file.write(text)
os.chmod(temp_path, path.stat().st_mode)
os.replace(temp_path, path)
except BaseException:
temp_path.unlink(missing_ok=True)
raise
def validate_ready(entry: Entry, text: str) -> None:
missing = []
for heading in READY_SECTIONS:
body = section_body(text, heading)
if not body or "<填写>" in body:
missing.append(heading)
if missing:
raise KanbanError("任务未满足 todo 条件: " + ", ".join(missing))
def validate_target(entry: Entry, target_state: str, text: str) -> None:
if target_state == "todo":
validate_ready(entry, text)
elif target_state == "done":
if result_from(text) != "completed":
raise KanbanError("移入 done 前必须填写: 结果: completed")
if entry.kind == "small":
summary = section_body(text, "完成总结")
if not summary or "<填写>" in summary:
raise KanbanError("小任务移入 done 前必须填写完成总结")
else:
report = entry.path / "report.md"
if not report.is_file() or not report.read_text(encoding="utf-8").strip():
raise KanbanError("大任务移入 done 前必须完成 report.md")
elif target_state == "archived":
result = result_from(text)
if result not in ARCHIVE_RESULTS:
allowed = ", ".join(sorted(ARCHIVE_RESULTS))
raise KanbanError(f"移入 archived 前必须填写有效结果: {allowed}")
elif target_state == "trash" and result_from(text) != "trashed":
raise KanbanError("移入 trash 前必须填写: 结果: trashed")
def render_contract(title: str, task_type: str) -> str:
created = datetime.now().strftime("%Y-%m-%d %H:%M")
return f"""# {title}
- 类型: {TYPE_NAMES[task_type]}
- 创建时间: {created}
- 负责人:
- 开始时间:
- 完成时间:
- 任务分支:
- 结果:
## 任务目标
<填写>
## 用户决策
N/A
## 预期成果
<填写>
## 验收条件
- [ ] <填写>
## 威胁模型
N/A
## 不在本轮范围
- <填写>
## 讨论与决策
"""
def command_new(args: argparse.Namespace, root: Path) -> None:
if not SLUG_RE.fullmatch(args.slug):
raise KanbanError("slug 只能包含小写 ASCII 字母, 数字和连字符")
title = " ".join(args.title).strip()
if not title or "\n" in title or "\r" in title:
raise KanbanError("标题不能为空或包含换行")
board = load_board(root)
task_id = f"{datetime.now().strftime('%Y%m%d')}-{args.slug}-task"
if task_id in board.entries or task_id in board.blocked:
raise KanbanError(f"任务已存在: {task_id}")
contract = render_contract(title, args.type)
if args.large:
target = root / "backlog" / task_id
target.mkdir()
try:
(target / "spec.md").write_text(contract, encoding="utf-8")
except Exception:
(target / "spec.md").unlink(missing_ok=True)
target.rmdir()
raise
else:
target = root / "backlog" / f"{task_id}.md"
content = contract + """## 实施与验证
<填写>
## 完成总结
<填写>
"""
with target.open("x", encoding="utf-8", newline="\n") as file:
file.write(content)
print(target)
def selected_entries(entries: Dict[str, Entry], state: Optional[str]) -> Iterable[Entry]:
state_order = {name: index for index, name in enumerate(STATES)}
return sorted(
(entry for entry in entries.values() if state is None or entry.state == state),
key=lambda entry: (state_order[entry.state], entry.task_id),
)
def select_todo(board: Board, task: Optional[str]) -> Entry:
if task:
entry = locate(board, task)
if entry.state != "todo":
raise KanbanError(f"只能启动 todo 任务: {entry.task_id} 当前位于 {entry.state}")
return entry
todo = list(selected_entries(board.entries, "todo"))
if not todo:
raise KanbanError("todo 中没有任务")
for index, entry in enumerate(todo, 1):
print(f"{index}. {entry.task_id}\t{title_from(read_document(entry))}")
while True:
try:
choice = input("选择任务编号: ").strip()
except EOFError as error:
raise KanbanError("未选择任务; 请指定 task-id") from error
if choice.isdecimal() and 1 <= int(choice) <= len(todo):
return todo[int(choice) - 1]
print(f"请输入 1-{len(todo)}")
def command_list(args: argparse.Namespace, root: Path) -> None:
board = load_board(root)
rows = []
for entry in selected_entries(board.entries, args.state):
text = read_document(entry)
name = "开始时间" if entry.state == "working" else "完成时间"
timestamp = metadata_from(text, name) if entry.state in {"working", "done"} else ""
if entry.state == "done" and not timestamp:
timestamp = datetime.fromtimestamp(entry.document.stat().st_mtime).strftime(
"%Y-%m-%d %H:%M"
)
rows.append(
(entry.state, entry.kind, timestamp or "-", entry.task_id, title_from(text))
)
rows.sort(key=lambda row: (row[2], row[3]), reverse=True)
rows.sort(key=lambda row: STATES.index(row[0]))
headers = ("STATE", "SIZE", "TIME")
widths = [
max([len(header), *(len(row[index]) for row in rows)])
for index, header in enumerate(headers)
]
use_color = "NO_COLOR" not in os.environ and (
sys.stdout.isatty() or os.environ.get("CLICOLOR_FORCE") == "1"
)
def color(text: str, code: str) -> str:
return f"\033[{code}m{text}\033[0m" if use_color else text
light_background = os.environ.get("COLORFGBG", "").rsplit(";", 1)[-1] in {"7", "15"}
palette = (
{
"backlog": "30", "todo": "33", "working": "34", "done": "32",
"archived": "35", "trash": "31", "small": "30", "large": "1;35",
"task": "34", "title": "35",
}
if light_background
else {
"backlog": "90", "todo": "93", "working": "96", "done": "92",
"archived": "94", "trash": "91", "small": "90", "large": "1;95",
"task": "96", "title": "95",
}
)
if args.mobile:
for index, row in enumerate(rows):
if index:
print()
print(
f"{color(row[0], palette[row[0]])} "
f"{color(row[1], palette[row[1]])} {row[2]}"
)
print(color(row[3], palette["task"]))
print(color(row[4], palette["title"]))
return
heading = " ".join(f"{header:<{width}}" for header, width in zip(headers, widths))
print(color(heading + " TASK ID / TITLE", "1"))
print(" ".join("-" * width for width in widths) + " ---------------")
for row in rows:
state = color(f"{row[0]:<{widths[0]}}", palette[row[0]])
size = color(f"{row[1]:<{widths[1]}}", palette[row[1]])
timestamp = f"{row[2]:<{widths[2]}}"
print(
f"{state} {size} {timestamp} "
f"{color(row[3], palette['task'])} {color(row[4], palette['title'])}"
)
def command_show(args: argparse.Namespace, root: Path) -> None:
entry = locate(load_board(root), args.task)
sys.stdout.write(read_document(entry))
def move_entry(entry: Entry, root: Path, target_state: str) -> Entry:
if target_state not in TRANSITIONS[entry.state]:
raise KanbanError(f"不允许迁移: {entry.state} -> {target_state}")
text = read_document(entry)
validate_target(entry, target_state, text)
updated = completion_metadata(text) if target_state == "done" else text
target = root / target_state / entry.path.name
if target.exists() or target.is_symlink():
raise KanbanError(f"目标已存在: {target}")
try:
entry.path.rename(target)
except OSError as error:
raise KanbanError(f"迁移失败: {error}") from error
if entry.path.exists() or not target.exists():
raise KanbanError("迁移后状态校验失败, 请保留现场")
document = target if entry.kind == "small" else target / "spec.md"
if updated != text:
try:
write_text_atomic(document, updated)
except (OSError, UnicodeError) as error:
try:
target.rename(entry.path)
except (OSError, UnicodeError) as rollback_error:
raise KanbanError(
f"记录完成时间失败且回滚失败; 卡片保留在 done: {error}; {rollback_error}"
) from error
raise KanbanError(f"记录完成时间失败: {error}") from error
return Entry(entry.task_id, target_state, target, document, entry.kind)
def command_move(args: argparse.Namespace, root: Path) -> None:
entry = locate(load_board(root), args.task)
print(move_entry(entry, root, args.state).path)
def start_metadata(text: str, agent: str) -> str:
for name, value in (
("负责人", agent),
("开始时间", datetime.now().strftime("%Y-%m-%d %H:%M")),
):
pattern = rf"(?m)^- {name}:\s*$"
if len(re.findall(pattern, text)) != 1:
raise KanbanError(f"任务文档缺少唯一元数据字段: {name}")
text = re.sub(pattern, f"- {name}: {value}", text, count=1)
return text
def tmux_session_id(tmux: str) -> str:
pane = os.environ.get("TMUX_PANE")
if not os.environ.get("TMUX") or not pane:
raise KanbanError("当前不在 tmux session")
result = subprocess.run(
[tmux, "display-message", "-p", "-t", pane, "#{session_id}"],
text=True,
capture_output=True,
check=False,
)
session = result.stdout.strip()
if result.returncode != 0 or not re.fullmatch(r"\$\d+", session):
detail = result.stderr.strip() or "无法确定当前 session"
raise KanbanError(f"读取 tmux session 失败: {detail}")
return session
def command_start(args: argparse.Namespace, root: Path) -> None:
entry = select_todo(load_board(root), args.task)
agent = shutil.which(args.agent)
tmux = shutil.which("tmux")
if not agent:
raise KanbanError(f"Agent 不在 PATH: {args.agent}")
if not tmux:
raise KanbanError("tmux 不在 PATH")
session = tmux_session_id(tmux)
original = read_document(entry)
updated = start_metadata(original, args.agent)
moved = move_entry(entry, root, "working")
prompt = (
f"执行 Kanban 任务 {entry.task_id}. 先运行 kanban rules, 再运行 "
f"kanban show {entry.task_id}. 卡片已进入 working. 遵守目标项目 AGENTS.md, "
"补充任务分支, 并按项目规则完成任务、验证、审核、集成和看板收尾."
)
slug = entry.task_id[9:].removesuffix("-task")
effort = "high" if entry.kind == "large" else "medium"
agent_args = (
[
agent,
"--model",
"gpt-5.6-sol",
"--config",
f'model_reasoning_effort="{effort}"',
"--dangerously-bypass-approvals-and-sandbox",
]
if args.agent == "codex"
else [agent, "--model", "opus", "--effort", effort, "--dangerously-skip-permissions"]
)
command = shlex.join([*agent_args, prompt])
try:
moved.document.write_text(updated, encoding="utf-8")
result = subprocess.run(
[
tmux,
"new-window",
"-P",
"-F",
"#{window_id}",
"-t",
session + ":",
"-c",
str(root.parent),
"-n",
f"kb-{slug}"[:50],
command,
],
text=True,
capture_output=True,
check=False,
)
if result.returncode != 0:
detail = result.stderr.strip() or f"exit {result.returncode}"
raise KanbanError(f"tmux new-window 失败: {detail}")
except (KanbanError, OSError, UnicodeError) as error:
try:
moved.document.write_text(original, encoding="utf-8")
moved.path.rename(entry.path)
except (OSError, UnicodeError) as rollback_error:
raise KanbanError(
f"启动失败且回滚失败; 卡片保留在 working: {error}; {rollback_error}"
) from error
raise
window = result.stdout.strip() or "unknown"
print(f"started: {entry.task_id}\tagent={args.agent}\twindow={window}")
def command_check(root: Path) -> int:
board = scan(root)
for problem in board.problems:
print(f"invalid: {problem.message}", file=sys.stderr)
print(f"ok: {len(board.entries)} tasks")
return 1 if board.problems else 0
def parser() -> argparse.ArgumentParser:
result = argparse.ArgumentParser(prog="kanban", description="本地文件看板")
commands = result.add_subparsers(dest="command", required=True)
init_parser = commands.add_parser("init", help="创建看板目录框架")
init_parser.add_argument("project", nargs="?", help="项目根目录, 默认当前项目")
commands.add_parser("rules", help="输出全局看板规则")
list_parser = commands.add_parser("list", aliases=["ls"], help="列出任务")
list_parser.add_argument("state", nargs="?", choices=STATES)
list_parser.add_argument("--mobile", action="store_true", help="使用竖屏手机布局")
show_parser = commands.add_parser("show", help="输出入口任务文档")
show_parser.add_argument("task")
new_parser = commands.add_parser("new", help="在 backlog 创建任务")
new_parser.add_argument("--large", action="store_true", help="创建大任务目录")
new_parser.add_argument("type", choices=tuple(TYPE_NAMES))
new_parser.add_argument("slug")
new_parser.add_argument("title", nargs="+")
move_parser = commands.add_parser("move", help="迁移任务状态")
move_parser.add_argument("task")
move_parser.add_argument("state", choices=STATES)
pick_parser = commands.add_parser("pick", help="将 backlog 任务移入 todo")
pick_parser.add_argument("task")
pick_parser.set_defaults(state="todo")
start_parser = commands.add_parser("start", help="领取任务并在当前 tmux session 启动 Agent")
start_parser.add_argument("task", nargs="?")
start_parser.add_argument("--agent", choices=AGENT_NAMES, default="codex")
commands.add_parser("check", help="检查看板不变量")
return result
def main() -> int:
args = parser().parse_args()
try:
if args.command == "init":
command_init(args)
return 0
if args.command == "rules":
command_rules()
return 0
root = board_root()
if args.command in ("list", "ls"):
command_list(args, root)
elif args.command == "show":
command_show(args, root)
elif args.command == "new":
command_new(args, root)
elif args.command in ("move", "pick"):
command_move(args, root)
elif args.command == "start":
command_start(args, root)
elif args.command == "check":
return command_check(root)
return 0
except (KanbanError, OSError, UnicodeError) as error:
print(f"kanban: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())