@leocm/flowcraft 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +7 -2
  2. package/bin/cli.js +108 -108
  3. package/flowcraft.yaml +30 -30
  4. package/install.sh +24 -24
  5. package/lib/args.js +38 -38
  6. package/lib/config.js +20 -20
  7. package/lib/copy.js +131 -131
  8. package/lib/fix.js +110 -110
  9. package/lib/fsutil.js +104 -104
  10. package/lib/global.js +229 -229
  11. package/lib/init.js +43 -43
  12. package/lib/runtime.js +84 -84
  13. package/lib/version.js +55 -55
  14. package/lib/wizard.js +125 -125
  15. package/package.json +33 -33
  16. package/presets/backend.yaml +20 -20
  17. package/presets/default.yaml +15 -15
  18. package/presets/frontend.yaml +20 -20
  19. package/presets/quick-fix.yaml +15 -15
  20. package/setup/.claude/hooks/check-phase-test.py +152 -152
  21. package/setup/.claude/hooks/check-phase-write.py +235 -235
  22. package/setup/.claude/hooks/dispatch.py +67 -67
  23. package/setup/.claude/hooks/file-suggestion.py +45 -45
  24. package/setup/.claude/hooks/flowcraft_env.py +162 -162
  25. package/setup/.claude/hooks/permission-request.py +132 -132
  26. package/setup/.claude/hooks/post-tool-failure.py +36 -36
  27. package/setup/.claude/hooks/pre-compact.py +66 -66
  28. package/setup/.claude/hooks/review-runner.py +846 -846
  29. package/setup/.claude/hooks/setup-keys.py +282 -282
  30. package/setup/.claude/hooks/statusline.py +63 -63
  31. package/setup/.claude/hooks/stop-check.py +186 -186
  32. package/setup/.claude/hooks/subagent-start.py +50 -50
  33. package/setup/.claude/hooks/subagent-stop.py +63 -63
  34. package/setup/.claude/hooks/task-completed.py +57 -57
  35. package/setup/.claude/hooks/task_manager.py +592 -592
  36. package/setup/.claude/hooks/user-prompt-submit.py +91 -91
  37. package/setup/.claude/settings.json +233 -233
  38. package/setup/.claude/skills/Pstatus/SKILL.md +68 -68
  39. package/setup/.claude/skills/archive/SKILL.md +195 -195
  40. package/setup/.claude/skills/brainstorming/SKILL.md +5 -5
  41. package/setup/.claude/skills/brainstorming/scripts/server.cjs +723 -723
  42. package/setup/.claude/skills/brainstorming/scripts/start-server.py +245 -245
  43. package/setup/.claude/skills/brainstorming/scripts/stop-server.py +178 -178
  44. package/setup/.claude/skills/brainstorming/visual-companion.md +298 -298
  45. package/setup/.claude/skills/chrome-integration/SKILL.md +66 -66
  46. package/setup/.claude/skills/code-review/SKILL.md +264 -264
  47. package/setup/.claude/skills/executing-plans/SKILL.md +1 -1
  48. package/setup/.claude/skills/gitnexus/gitnexus-cli/SKILL.md +67 -67
  49. package/setup/.claude/skills/gitnexus/gitnexus-debugging/SKILL.md +1 -1
  50. package/setup/.claude/skills/gitnexus/gitnexus-exploring/SKILL.md +1 -1
  51. package/setup/.claude/skills/gitnexus/gitnexus-guide/SKILL.md +1 -1
  52. package/setup/.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md +1 -1
  53. package/setup/.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md +1 -1
  54. package/setup/.claude/skills/methodology/SKILL.md +124 -0
  55. package/setup/.claude/skills/phase/SKILL.md +62 -62
  56. package/setup/.claude/skills/playwright/SKILL.md +85 -85
  57. package/setup/.claude/skills/review/SKILL.md +97 -97
  58. package/setup/.claude/skills/task/SKILL.md +26 -26
  59. package/setup/.claude/skills/test-driven-development/SKILL.md +1 -1
  60. package/setup/.claude/skills/ui-ux-pro-max/SKILL.md +1 -1
  61. package/setup/.claude/skills/verification-before-completion/SKILL.md +1 -1
  62. package/setup/.claude/skills/writing-plans/SKILL.md +1 -1
  63. package/setup/.codex/.agents/skills/archive/SKILL.md +195 -195
  64. package/setup/.codex/.agents/skills/brainstorming/SKILL.md +5 -5
  65. package/setup/.codex/.agents/skills/brainstorming/scripts/server.cjs +723 -723
  66. package/setup/.codex/.agents/skills/brainstorming/scripts/start-server.py +245 -245
  67. package/setup/.codex/.agents/skills/brainstorming/scripts/stop-server.py +178 -178
  68. package/setup/.codex/.agents/skills/brainstorming/visual-companion.md +298 -298
  69. package/setup/.codex/.agents/skills/chrome-integration/SKILL.md +66 -66
  70. package/setup/.codex/.agents/skills/code-review/SKILL.md +264 -264
  71. package/setup/.codex/.agents/skills/executing-plans/SKILL.md +1 -1
  72. package/setup/.codex/.agents/skills/gitnexus/gitnexus-cli/SKILL.md +67 -67
  73. package/setup/.codex/.agents/skills/gitnexus/gitnexus-debugging/SKILL.md +1 -1
  74. package/setup/.codex/.agents/skills/gitnexus/gitnexus-exploring/SKILL.md +1 -1
  75. package/setup/.codex/.agents/skills/gitnexus/gitnexus-guide/SKILL.md +1 -1
  76. package/setup/.codex/.agents/skills/gitnexus/gitnexus-impact-analysis/SKILL.md +1 -1
  77. package/setup/.codex/.agents/skills/gitnexus/gitnexus-refactoring/SKILL.md +1 -1
  78. package/setup/.codex/.agents/skills/methodology/SKILL.md +124 -0
  79. package/setup/.codex/.agents/skills/phase/SKILL.md +62 -62
  80. package/setup/.codex/.agents/skills/playwright/SKILL.md +85 -85
  81. package/setup/.codex/.agents/skills/review/SKILL.md +97 -97
  82. package/setup/.codex/.agents/skills/task/SKILL.md +27 -27
  83. package/setup/.codex/.agents/skills/test-driven-development/SKILL.md +1 -1
  84. package/setup/.codex/.agents/skills/ui-ux-pro-max/SKILL.md +1 -1
  85. package/setup/.codex/.agents/skills/verification-before-completion/SKILL.md +1 -1
  86. package/setup/.codex/.agents/skills/writing-plans/SKILL.md +1 -1
  87. package/setup/.codex/hooks/review-runner.py +851 -851
  88. package/setup/.codex/hooks/setup-keys.py +287 -287
  89. package/setup/AGENTS.md +11 -1
  90. package/setup/CLAUDE.md +11 -1
  91. package/setup/install.sh +24 -24
  92. package/setup/tests/test_decision_timeout.py +241 -241
  93. package/setup/tests/test_hook_guards.py +357 -357
  94. package/setup/tests/test_sdlc_bootstrap.py +167 -167
  95. package/setup/tests/test_sessionlog_switch.py +199 -199
  96. package/setup/tests/test_task_manager.py +148 -148
@@ -1,592 +1,592 @@
1
- #!/usr/bin/env python3
2
- """FlowCraft task manager - multi-task state management.
3
-
4
- Each task gets its own state file at .claude/tasks/{task-id}.md.
5
- Hooks use get_task_state() to route state reads/writes to the correct task file.
6
-
7
- Resolution priority (R1-R4):
8
- 1. explicit task_id argument (CLI/API override)
9
- 2. FLOWCRAFT_TASK_ID environment variable (advanced override, R3)
10
- 3. session binding .claude/tasks/.bindings.json[session_id] (R2)
11
- 4. directory default .claude/tasks/{directory-name}.md when present (R1)
12
- 5. fallback: project-state.md single-task mode (R4, backward compatible)
13
-
14
- FLOWCRAFT_SESSION_ID is set by dispatch.py from the hook payload.
15
- """
16
- import json
17
- import os
18
- import re
19
- import sys
20
- import tempfile
21
- from datetime import datetime
22
- from pathlib import Path
23
-
24
- from flowcraft_env import get_project_root
25
-
26
- # File/directory naming constants under .claude/
27
- TASKS_DIR_NAME = "tasks"
28
- BINDINGS_FILE = ".bindings.json"
29
- LAST_SESSION_FILE = ".last-session"
30
- # Environment variable names
31
- ENV_TASK_ID = "FLOWCRAFT_TASK_ID"
32
- ENV_SESSION_ID = "FLOWCRAFT_SESSION_ID"
33
- # Characters forbidden in task IDs (path separators, extension, Windows-reserved)
34
- _UNSAFE_TASK_ID_CHARS = set('/\\:*?"<>|\0')
35
-
36
-
37
- def _safe_task_id(task_id: str) -> str:
38
- """Validate a task ID used as a filename (OWASP path traversal defense).
39
-
40
- Args:
41
- task_id: Candidate task ID.
42
- Returns:
43
- The trimmed task ID when safe (no leading dot, no path/extension/reserved
44
- chars, at most 100 chars), otherwise empty string.
45
- """
46
- tid = (task_id or "").strip()
47
- if not tid or len(tid) > 100:
48
- return ""
49
- if tid.startswith(".") or any(ch in _UNSAFE_TASK_ID_CHARS for ch in tid):
50
- return ""
51
- return tid
52
-
53
-
54
- def get_active_task_id() -> str:
55
- """Get the explicit task ID override from the environment (R3).
56
-
57
- Returns:
58
- Task ID string, or empty string if not set.
59
- """
60
- return os.environ.get(ENV_TASK_ID, "").strip()
61
-
62
-
63
- def get_session_id() -> str:
64
- """Get the current session ID injected by dispatch.py.
65
-
66
- Returns:
67
- Session ID string, or empty string when unavailable.
68
- """
69
- return os.environ.get(ENV_SESSION_ID, "").strip()
70
-
71
-
72
- def _tasks_dir(project_root: Path) -> Path:
73
- """Return the .claude/tasks directory for the project.
74
-
75
- Args:
76
- project_root: Project root directory.
77
- Returns:
78
- Path to the tasks directory.
79
- """
80
- return project_root / ".claude" / TASKS_DIR_NAME
81
-
82
-
83
- def _dir_task_id(project_root: Path) -> str:
84
- """Derive the default task ID from the working root directory name (R1).
85
-
86
- Args:
87
- project_root: Project root directory.
88
- Returns:
89
- Sanitized directory basename used as task ID.
90
- """
91
- name = (project_root.name or "").strip()
92
- return name.replace('"', "'")
93
-
94
-
95
- def resolve_task_id(project_root: Path, task_id: str = None) -> str:
96
- """Resolve the effective task ID via the priority chain (R1-R3).
97
-
98
- Args:
99
- project_root: Project root directory.
100
- task_id: Explicit override (highest priority).
101
- Returns:
102
- Task ID string, or "" to fall back to single-task mode (R4).
103
- """
104
- if task_id:
105
- return _safe_task_id(task_id)
106
- env_id = _safe_task_id(get_active_task_id())
107
- if env_id:
108
- return env_id
109
- sid = get_session_id()
110
- if sid:
111
- bound = _safe_task_id(_read_bindings(project_root).get(sid, ""))
112
- if bound:
113
- return bound
114
- dir_id = _safe_task_id(_dir_task_id(project_root))
115
- if dir_id and (_tasks_dir(project_root) / f"{dir_id}.md").is_file():
116
- return dir_id
117
- return ""
118
-
119
-
120
- def get_task_state_path(project_root: Path, task_id: str = None) -> Path:
121
- """Resolve the state file path for a given task.
122
-
123
- Args:
124
- project_root: Project root directory.
125
- task_id: Task ID. If None, uses resolve_task_id().
126
- Returns:
127
- Path to the task state file, or project-state.md for single-task mode.
128
- """
129
- if task_id is None:
130
- task_id = resolve_task_id(project_root)
131
- else:
132
- task_id = _safe_task_id(task_id)
133
- if task_id:
134
- return _tasks_dir(project_root) / f"{task_id}.md"
135
- return project_root / ".claude" / "project-state.md"
136
-
137
-
138
- def get_task_state(script_path: str = None, task_id: str = None) -> Path:
139
- """Get the state file path for the current task (hook entry point).
140
-
141
- Args:
142
- script_path: Path(__file__) from the calling hook (for project root detection).
143
- task_id: Explicit task ID override. If None, uses the priority chain.
144
- Returns:
145
- Path to the correct state file.
146
- """
147
- project_root = get_project_root(script_path)
148
- return get_task_state_path(project_root, task_id)
149
-
150
-
151
- def _read_bindings(project_root: Path) -> dict:
152
- """Read the session binding table (session_id -> task_id) (R2).
153
-
154
- Args:
155
- project_root: Project root directory.
156
- Returns:
157
- Mapping dict; empty when missing or corrupt (graceful fallback).
158
- """
159
- path = _tasks_dir(project_root) / BINDINGS_FILE
160
- if not path.is_file():
161
- return {}
162
- try:
163
- data = json.loads(path.read_text(encoding="utf-8"))
164
- return data if isinstance(data, dict) else {}
165
- except Exception:
166
- return {}
167
-
168
-
169
- def _atomic_write_text(path: Path, text: str) -> None:
170
- """Write text atomically (tempfile + os.replace) to avoid torn files (AC3).
171
-
172
- Args:
173
- path: Target file path.
174
- text: Full file content.
175
- Raises:
176
- OSError: when the write fails (temporary file is cleaned up first).
177
- """
178
- path.parent.mkdir(parents=True, exist_ok=True)
179
- fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
180
- try:
181
- with os.fdopen(fd, "w", encoding="utf-8") as fh:
182
- fh.write(text)
183
- os.replace(tmp, path)
184
- except Exception:
185
- try:
186
- os.unlink(tmp)
187
- except OSError:
188
- pass
189
- raise
190
-
191
-
192
- def bind_session(project_root: Path, session_id: str, task_id: str) -> bool:
193
- """Bind a session to a task in the binding table (R2).
194
-
195
- Args:
196
- project_root: Project root directory.
197
- session_id: Claude session ID.
198
- task_id: Task ID to bind.
199
- Returns:
200
- True when the binding was written.
201
- """
202
- if not session_id or not _safe_task_id(task_id):
203
- return False
204
- bindings = _read_bindings(project_root)
205
- bindings[session_id] = task_id
206
- payload = json.dumps(bindings, ensure_ascii=False, indent=2)
207
- _atomic_write_text(_tasks_dir(project_root) / BINDINGS_FILE, payload)
208
- return True
209
-
210
-
211
- def ensure_session_binding(project_root: Path, session_id: str, task_id: str) -> None:
212
- """Bind a session to a task only when no binding exists yet.
213
-
214
- Args:
215
- project_root: Project root directory.
216
- session_id: Session ID.
217
- task_id: Default task ID for this working root.
218
- """
219
- if not session_id or not task_id:
220
- return
221
- if session_id not in _read_bindings(project_root):
222
- bind_session(project_root, session_id, task_id)
223
-
224
-
225
- def remember_session(project_root: Path, session_id: str) -> None:
226
- """Record the latest seen session ID for CLI `use` fallback lookups.
227
-
228
- Args:
229
- project_root: Project root directory.
230
- session_id: Session ID to remember.
231
- """
232
- if session_id:
233
- _atomic_write_text(_tasks_dir(project_root) / LAST_SESSION_FILE, session_id + "\n")
234
-
235
-
236
- def _last_session_id(project_root: Path) -> str:
237
- """Read the last recorded session ID (CLI fallback when not provided).
238
-
239
- Args:
240
- project_root: Project root directory.
241
- Returns:
242
- Session ID string, or empty when unavailable.
243
- """
244
- path = _tasks_dir(project_root) / LAST_SESSION_FILE
245
- if not path.is_file():
246
- return ""
247
- try:
248
- return path.read_text(encoding="utf-8").strip()
249
- except Exception:
250
- return ""
251
-
252
-
253
- def create_task(task_id: str, description: str = "", project_root: Path = None) -> Path:
254
- """Create a new task state file and register it in project-state.md active_tasks.
255
-
256
- Args:
257
- task_id: Unique task identifier (used as filename).
258
- description: Task description.
259
- project_root: Project root. If None, auto-detected.
260
- Returns:
261
- Path to the created task state file.
262
- Raises:
263
- ValueError: when task_id fails _safe_task_id validation.
264
- """
265
- task_id = _safe_task_id(task_id)
266
- if not task_id:
267
- raise ValueError("invalid task-id: no leading dot, no path/extension/reserved chars")
268
- if project_root is None:
269
- project_root = get_project_root(__file__)
270
-
271
- tasks_dir = _tasks_dir(project_root)
272
- tasks_dir.mkdir(parents=True, exist_ok=True)
273
-
274
- task_file = tasks_dir / f"{task_id}.md"
275
- if task_file.exists():
276
- raise ValueError(f"task already exists: {task_id} (refusing to overwrite)")
277
- now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
278
-
279
- template = _task_template(task_id, description, now)
280
- task_file.write_text(template, encoding="utf-8")
281
-
282
- _register_active_task(project_root, task_id, description)
283
- return task_file
284
-
285
-
286
- def archive_task(task_id: str, project_root: Path = None) -> bool:
287
- """Archive a task: move its state to completed_tasks, delete the task file.
288
-
289
- Args:
290
- task_id: Task ID to archive.
291
- project_root: Project root. If None, auto-detected.
292
- Returns:
293
- True if archived successfully.
294
- """
295
- task_id = _safe_task_id(task_id)
296
- if not task_id:
297
- return False
298
- if project_root is None:
299
- project_root = get_project_root(__file__)
300
-
301
- task_file = _tasks_dir(project_root) / f"{task_id}.md"
302
- if not task_file.is_file():
303
- return False
304
-
305
- summary = _extract_task_summary(task_file)
306
-
307
- state_file = project_root / ".claude" / "project-state.md"
308
- if state_file.is_file():
309
- _append_completed_task(state_file, task_id, summary)
310
-
311
- _unregister_active_task(project_root, task_id)
312
-
313
- task_file.unlink()
314
- return True
315
-
316
-
317
- def list_tasks(project_root: Path = None) -> list:
318
- """List all active tasks.
319
-
320
- Args:
321
- project_root: Project root. If None, auto-detected.
322
- Returns:
323
- List of dicts with task_id, description, phase, task_file.
324
- """
325
- if project_root is None:
326
- project_root = get_project_root(__file__)
327
-
328
- tasks_dir = _tasks_dir(project_root)
329
- if not tasks_dir.is_dir():
330
- return []
331
-
332
- tasks = []
333
- for f in sorted(tasks_dir.glob("*.md")):
334
- info = _parse_task_file(f)
335
- tasks.append(info)
336
- return tasks
337
-
338
-
339
- def _task_template(task_id: str, description: str, now: str) -> str:
340
- """Generate the task state file template.
341
-
342
- Args:
343
- task_id: Task identifier.
344
- description: Task description.
345
- now: Creation timestamp string.
346
- Returns:
347
- YAML-in-Markdown template text (quotes sanitized).
348
- """
349
- safe_id = task_id.replace('"', "'")
350
- safe_desc = description.replace('"', "'")
351
- return f"""# 任务状态: {safe_id}
352
-
353
- ```yaml
354
- task_id: "{safe_id}"
355
- task_description: "{safe_desc}"
356
- current_phase: "P0"
357
- complexity_level: ""
358
- started_at: "{now}"
359
- last_updated: "{now}"
360
- phase_history: []
361
- prd_file: ""
362
- plan_file: ""
363
- dev_method: ""
364
- code_method: ""
365
- architecture_decisions: []
366
- requirements_clarification: []
367
- deliverable_checklist:
368
- P1: []
369
- P2: []
370
- P3: []
371
- P4: []
372
- P5: []
373
- modified_files: []
374
- review_retry_count: 0
375
- key_context: ""
376
- ```
377
- """
378
-
379
-
380
- def _parse_task_file(task_file: Path) -> dict:
381
- """Parse a task file and extract key fields.
382
-
383
- Args:
384
- task_file: Path to the task state file.
385
- Returns:
386
- Dict with task_id, task_description, current_phase and task_file.
387
- """
388
- info = {"task_file": str(task_file)}
389
- try:
390
- content = task_file.read_text(encoding="utf-8")
391
- for field in ("task_id", "task_description", "current_phase"):
392
- m = re.search(rf"^{field}:\s*\"?([^\"]*?)\"?\s*$", content, re.M)
393
- info[field] = m.group(1) if m else ""
394
- except Exception:
395
- info["task_id"] = task_file.stem
396
- info["task_description"] = ""
397
- info["current_phase"] = "P0"
398
- return info
399
-
400
-
401
- def _extract_task_summary(task_file: Path) -> dict:
402
- """Extract summary fields from a task file for completed_tasks entry.
403
-
404
- Args:
405
- task_file: Path to the task state file.
406
- Returns:
407
- Dict with description, complexity and modified files.
408
- """
409
- info = _parse_task_file(task_file)
410
- try:
411
- content = task_file.read_text(encoding="utf-8")
412
- m = re.search(r"^complexity_level:\s*\"?([^\"]*?)\"?\s*$", content, re.M)
413
- info["complexity_level"] = m.group(1) if m else ""
414
- m = re.search(r"^modified_files:\s*\n((?:\s+-\s+.*\n)*)", content, re.M)
415
- if m:
416
- files = re.findall(r"-\s+\"?([^\"]*?)\"?\s*$", m.group(1), re.M)
417
- info["modified_files"] = files
418
- else:
419
- info["modified_files"] = []
420
- except Exception:
421
- info["complexity_level"] = ""
422
- info["modified_files"] = []
423
- return info
424
-
425
-
426
- def _insert_yaml_list_entry(content: str, key: str, entry: str) -> str:
427
- """Insert an entry under a YAML list key, supporting inline-empty [] format (Issue 5).
428
-
429
- Args:
430
- content: Full state file content.
431
- key: List key ("active_tasks" / "completed_tasks").
432
- entry: Pre-indented entry text ending with newline.
433
- Returns:
434
- Updated content with the entry appended to the list (unchanged if key absent).
435
- """
436
- inline = re.search(rf"^{re.escape(key)}:\s*\[\s*\]\s*$", content, re.M)
437
- if inline:
438
- tail = content[inline.end():]
439
- if tail.startswith("\n"):
440
- tail = tail[1:]
441
- return content[: inline.start()] + f"{key}:\n{entry}" + tail
442
- block = re.search(rf"{re.escape(key)}:\s*\n", content)
443
- if block:
444
- return content[: block.end()] + entry + content[block.end():]
445
- return content
446
-
447
-
448
- def _register_active_task(project_root: Path, task_id: str, description: str) -> None:
449
- """Add a task entry to project-state.md active_tasks list.
450
-
451
- Args:
452
- project_root: Project root directory.
453
- task_id: Task identifier.
454
- description: Task description.
455
- """
456
- state_file = project_root / ".claude" / "project-state.md"
457
- if not state_file.is_file():
458
- return
459
- try:
460
- content = state_file.read_text(encoding="utf-8")
461
- safe_id = task_id.replace('"', "'")
462
- safe_desc = description.replace('"', "'")
463
- entry = f' - task_id: "{safe_id}"\n description: "{safe_desc}"\n task_file: ".claude/tasks/{safe_id}.md"\n'
464
- if "active_tasks:" in content:
465
- content = _insert_yaml_list_entry(content, "active_tasks", entry)
466
- else:
467
- content = re.sub(
468
- r"(\n# 当前任务)",
469
- lambda m: f"\nactive_tasks:\n{entry}" + m.group(1),
470
- content,
471
- count=1,
472
- )
473
- state_file.write_text(content, encoding="utf-8")
474
- except Exception:
475
- pass
476
-
477
-
478
- def _unregister_active_task(project_root: Path, task_id: str) -> None:
479
- """Remove a task entry from project-state.md active_tasks list.
480
-
481
- Args:
482
- project_root: Project root directory.
483
- task_id: Task identifier.
484
- """
485
- state_file = project_root / ".claude" / "project-state.md"
486
- if not state_file.is_file():
487
- return
488
- try:
489
- content = state_file.read_text(encoding="utf-8")
490
- content = re.sub(
491
- rf"\s*-\s+task_id:\s*\"{re.escape(task_id)}\"\n(?:\s+\w+:.*\n)*",
492
- "\n",
493
- content,
494
- count=1,
495
- )
496
- state_file.write_text(content, encoding="utf-8")
497
- except Exception:
498
- pass
499
-
500
-
501
- def _append_completed_task(state_file: Path, task_id: str, summary: dict) -> None:
502
- """Append a task entry to completed_tasks in project-state.md.
503
-
504
- Args:
505
- state_file: Path to project-state.md.
506
- task_id: Task identifier.
507
- summary: Summary dict from _extract_task_summary().
508
- """
509
- try:
510
- content = state_file.read_text(encoding="utf-8")
511
- now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
512
- safe_desc = summary.get("task_description", "").replace('"', "'")
513
- safe_files = ", ".join(summary.get("modified_files", [])).replace('"', "'")
514
- entry = (
515
- f' - task: "{safe_desc}"\n'
516
- f' prd_summary: "{safe_desc}"\n'
517
- f' key_decisions: ["{safe_files}"]\n'
518
- f' completed_at: "{now}"\n'
519
- )
520
- content = _insert_yaml_list_entry(content, "completed_tasks", entry)
521
- state_file.write_text(content, encoding="utf-8")
522
- except Exception:
523
- pass
524
-
525
-
526
- def _cli(argv: list) -> int:
527
- """CLI entry point: create / archive / list / use.
528
-
529
- Args:
530
- argv: Arguments without the script name.
531
- Returns:
532
- Process exit code.
533
- """
534
- if not argv:
535
- print("Usage: task_manager.py <create|archive|list|use> [task-id] [description|session-id]")
536
- return 1
537
- cmd = argv[0]
538
- root = get_project_root(__file__)
539
-
540
- if cmd == "create":
541
- tid = argv[1] if len(argv) > 1 else ""
542
- desc = argv[2] if len(argv) > 2 else ""
543
- if not tid:
544
- print("Error: task-id required")
545
- return 1
546
- try:
547
- path = create_task(tid, desc, root)
548
- except ValueError as exc:
549
- print(f"Error: {exc}")
550
- return 1
551
- print(f"Created: {path}")
552
- return 0
553
-
554
- if cmd == "archive":
555
- tid = argv[1] if len(argv) > 1 else ""
556
- if not tid:
557
- print("Error: task-id required")
558
- return 1
559
- ok = archive_task(tid, root)
560
- print(f"Archived: {ok}")
561
- return 0
562
-
563
- if cmd == "use":
564
- tid = argv[1] if len(argv) > 1 else ""
565
- if not tid:
566
- print("Error: task-id required")
567
- return 1
568
- sid = (argv[2] if len(argv) > 2 else "").strip() or _last_session_id(root)
569
- if not sid:
570
- print("Error: session-id unavailable (pass it explicitly)")
571
- return 1
572
- ok = bind_session(root, sid, tid)
573
- if not ok:
574
- print("Error: invalid task-id or empty session")
575
- return 1
576
- remember_session(root, sid)
577
- print(f"Bound: session {sid} -> {tid}")
578
- return 0
579
-
580
- if cmd == "list":
581
- for t in list_tasks(root):
582
- print(f" [{t.get('current_phase', '?')}] {t.get('task_id', '?')} - {t.get('task_description', '')}")
583
- for sid, tid in _read_bindings(root).items():
584
- print(f" session {sid} -> {tid}")
585
- return 0
586
-
587
- print(f"Unknown command: {cmd}")
588
- return 1
589
-
590
-
591
- if __name__ == "__main__":
592
- sys.exit(_cli(sys.argv[1:]))
1
+ #!/usr/bin/env python3
2
+ """FlowCraft task manager - multi-task state management.
3
+
4
+ Each task gets its own state file at .claude/tasks/{task-id}.md.
5
+ Hooks use get_task_state() to route state reads/writes to the correct task file.
6
+
7
+ Resolution priority (R1-R4):
8
+ 1. explicit task_id argument (CLI/API override)
9
+ 2. FLOWCRAFT_TASK_ID environment variable (advanced override, R3)
10
+ 3. session binding .claude/tasks/.bindings.json[session_id] (R2)
11
+ 4. directory default .claude/tasks/{directory-name}.md when present (R1)
12
+ 5. fallback: project-state.md single-task mode (R4, backward compatible)
13
+
14
+ FLOWCRAFT_SESSION_ID is set by dispatch.py from the hook payload.
15
+ """
16
+ import json
17
+ import os
18
+ import re
19
+ import sys
20
+ import tempfile
21
+ from datetime import datetime
22
+ from pathlib import Path
23
+
24
+ from flowcraft_env import get_project_root
25
+
26
+ # File/directory naming constants under .claude/
27
+ TASKS_DIR_NAME = "tasks"
28
+ BINDINGS_FILE = ".bindings.json"
29
+ LAST_SESSION_FILE = ".last-session"
30
+ # Environment variable names
31
+ ENV_TASK_ID = "FLOWCRAFT_TASK_ID"
32
+ ENV_SESSION_ID = "FLOWCRAFT_SESSION_ID"
33
+ # Characters forbidden in task IDs (path separators, extension, Windows-reserved)
34
+ _UNSAFE_TASK_ID_CHARS = set('/\\:*?"<>|\0')
35
+
36
+
37
+ def _safe_task_id(task_id: str) -> str:
38
+ """Validate a task ID used as a filename (OWASP path traversal defense).
39
+
40
+ Args:
41
+ task_id: Candidate task ID.
42
+ Returns:
43
+ The trimmed task ID when safe (no leading dot, no path/extension/reserved
44
+ chars, at most 100 chars), otherwise empty string.
45
+ """
46
+ tid = (task_id or "").strip()
47
+ if not tid or len(tid) > 100:
48
+ return ""
49
+ if tid.startswith(".") or any(ch in _UNSAFE_TASK_ID_CHARS for ch in tid):
50
+ return ""
51
+ return tid
52
+
53
+
54
+ def get_active_task_id() -> str:
55
+ """Get the explicit task ID override from the environment (R3).
56
+
57
+ Returns:
58
+ Task ID string, or empty string if not set.
59
+ """
60
+ return os.environ.get(ENV_TASK_ID, "").strip()
61
+
62
+
63
+ def get_session_id() -> str:
64
+ """Get the current session ID injected by dispatch.py.
65
+
66
+ Returns:
67
+ Session ID string, or empty string when unavailable.
68
+ """
69
+ return os.environ.get(ENV_SESSION_ID, "").strip()
70
+
71
+
72
+ def _tasks_dir(project_root: Path) -> Path:
73
+ """Return the .claude/tasks directory for the project.
74
+
75
+ Args:
76
+ project_root: Project root directory.
77
+ Returns:
78
+ Path to the tasks directory.
79
+ """
80
+ return project_root / ".claude" / TASKS_DIR_NAME
81
+
82
+
83
+ def _dir_task_id(project_root: Path) -> str:
84
+ """Derive the default task ID from the working root directory name (R1).
85
+
86
+ Args:
87
+ project_root: Project root directory.
88
+ Returns:
89
+ Sanitized directory basename used as task ID.
90
+ """
91
+ name = (project_root.name or "").strip()
92
+ return name.replace('"', "'")
93
+
94
+
95
+ def resolve_task_id(project_root: Path, task_id: str = None) -> str:
96
+ """Resolve the effective task ID via the priority chain (R1-R3).
97
+
98
+ Args:
99
+ project_root: Project root directory.
100
+ task_id: Explicit override (highest priority).
101
+ Returns:
102
+ Task ID string, or "" to fall back to single-task mode (R4).
103
+ """
104
+ if task_id:
105
+ return _safe_task_id(task_id)
106
+ env_id = _safe_task_id(get_active_task_id())
107
+ if env_id:
108
+ return env_id
109
+ sid = get_session_id()
110
+ if sid:
111
+ bound = _safe_task_id(_read_bindings(project_root).get(sid, ""))
112
+ if bound:
113
+ return bound
114
+ dir_id = _safe_task_id(_dir_task_id(project_root))
115
+ if dir_id and (_tasks_dir(project_root) / f"{dir_id}.md").is_file():
116
+ return dir_id
117
+ return ""
118
+
119
+
120
+ def get_task_state_path(project_root: Path, task_id: str = None) -> Path:
121
+ """Resolve the state file path for a given task.
122
+
123
+ Args:
124
+ project_root: Project root directory.
125
+ task_id: Task ID. If None, uses resolve_task_id().
126
+ Returns:
127
+ Path to the task state file, or project-state.md for single-task mode.
128
+ """
129
+ if task_id is None:
130
+ task_id = resolve_task_id(project_root)
131
+ else:
132
+ task_id = _safe_task_id(task_id)
133
+ if task_id:
134
+ return _tasks_dir(project_root) / f"{task_id}.md"
135
+ return project_root / ".claude" / "project-state.md"
136
+
137
+
138
+ def get_task_state(script_path: str = None, task_id: str = None) -> Path:
139
+ """Get the state file path for the current task (hook entry point).
140
+
141
+ Args:
142
+ script_path: Path(__file__) from the calling hook (for project root detection).
143
+ task_id: Explicit task ID override. If None, uses the priority chain.
144
+ Returns:
145
+ Path to the correct state file.
146
+ """
147
+ project_root = get_project_root(script_path)
148
+ return get_task_state_path(project_root, task_id)
149
+
150
+
151
+ def _read_bindings(project_root: Path) -> dict:
152
+ """Read the session binding table (session_id -> task_id) (R2).
153
+
154
+ Args:
155
+ project_root: Project root directory.
156
+ Returns:
157
+ Mapping dict; empty when missing or corrupt (graceful fallback).
158
+ """
159
+ path = _tasks_dir(project_root) / BINDINGS_FILE
160
+ if not path.is_file():
161
+ return {}
162
+ try:
163
+ data = json.loads(path.read_text(encoding="utf-8"))
164
+ return data if isinstance(data, dict) else {}
165
+ except Exception:
166
+ return {}
167
+
168
+
169
+ def _atomic_write_text(path: Path, text: str) -> None:
170
+ """Write text atomically (tempfile + os.replace) to avoid torn files (AC3).
171
+
172
+ Args:
173
+ path: Target file path.
174
+ text: Full file content.
175
+ Raises:
176
+ OSError: when the write fails (temporary file is cleaned up first).
177
+ """
178
+ path.parent.mkdir(parents=True, exist_ok=True)
179
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
180
+ try:
181
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
182
+ fh.write(text)
183
+ os.replace(tmp, path)
184
+ except Exception:
185
+ try:
186
+ os.unlink(tmp)
187
+ except OSError:
188
+ pass
189
+ raise
190
+
191
+
192
+ def bind_session(project_root: Path, session_id: str, task_id: str) -> bool:
193
+ """Bind a session to a task in the binding table (R2).
194
+
195
+ Args:
196
+ project_root: Project root directory.
197
+ session_id: Claude session ID.
198
+ task_id: Task ID to bind.
199
+ Returns:
200
+ True when the binding was written.
201
+ """
202
+ if not session_id or not _safe_task_id(task_id):
203
+ return False
204
+ bindings = _read_bindings(project_root)
205
+ bindings[session_id] = task_id
206
+ payload = json.dumps(bindings, ensure_ascii=False, indent=2)
207
+ _atomic_write_text(_tasks_dir(project_root) / BINDINGS_FILE, payload)
208
+ return True
209
+
210
+
211
+ def ensure_session_binding(project_root: Path, session_id: str, task_id: str) -> None:
212
+ """Bind a session to a task only when no binding exists yet.
213
+
214
+ Args:
215
+ project_root: Project root directory.
216
+ session_id: Session ID.
217
+ task_id: Default task ID for this working root.
218
+ """
219
+ if not session_id or not task_id:
220
+ return
221
+ if session_id not in _read_bindings(project_root):
222
+ bind_session(project_root, session_id, task_id)
223
+
224
+
225
+ def remember_session(project_root: Path, session_id: str) -> None:
226
+ """Record the latest seen session ID for CLI `use` fallback lookups.
227
+
228
+ Args:
229
+ project_root: Project root directory.
230
+ session_id: Session ID to remember.
231
+ """
232
+ if session_id:
233
+ _atomic_write_text(_tasks_dir(project_root) / LAST_SESSION_FILE, session_id + "\n")
234
+
235
+
236
+ def _last_session_id(project_root: Path) -> str:
237
+ """Read the last recorded session ID (CLI fallback when not provided).
238
+
239
+ Args:
240
+ project_root: Project root directory.
241
+ Returns:
242
+ Session ID string, or empty when unavailable.
243
+ """
244
+ path = _tasks_dir(project_root) / LAST_SESSION_FILE
245
+ if not path.is_file():
246
+ return ""
247
+ try:
248
+ return path.read_text(encoding="utf-8").strip()
249
+ except Exception:
250
+ return ""
251
+
252
+
253
+ def create_task(task_id: str, description: str = "", project_root: Path = None) -> Path:
254
+ """Create a new task state file and register it in project-state.md active_tasks.
255
+
256
+ Args:
257
+ task_id: Unique task identifier (used as filename).
258
+ description: Task description.
259
+ project_root: Project root. If None, auto-detected.
260
+ Returns:
261
+ Path to the created task state file.
262
+ Raises:
263
+ ValueError: when task_id fails _safe_task_id validation.
264
+ """
265
+ task_id = _safe_task_id(task_id)
266
+ if not task_id:
267
+ raise ValueError("invalid task-id: no leading dot, no path/extension/reserved chars")
268
+ if project_root is None:
269
+ project_root = get_project_root(__file__)
270
+
271
+ tasks_dir = _tasks_dir(project_root)
272
+ tasks_dir.mkdir(parents=True, exist_ok=True)
273
+
274
+ task_file = tasks_dir / f"{task_id}.md"
275
+ if task_file.exists():
276
+ raise ValueError(f"task already exists: {task_id} (refusing to overwrite)")
277
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
278
+
279
+ template = _task_template(task_id, description, now)
280
+ task_file.write_text(template, encoding="utf-8")
281
+
282
+ _register_active_task(project_root, task_id, description)
283
+ return task_file
284
+
285
+
286
+ def archive_task(task_id: str, project_root: Path = None) -> bool:
287
+ """Archive a task: move its state to completed_tasks, delete the task file.
288
+
289
+ Args:
290
+ task_id: Task ID to archive.
291
+ project_root: Project root. If None, auto-detected.
292
+ Returns:
293
+ True if archived successfully.
294
+ """
295
+ task_id = _safe_task_id(task_id)
296
+ if not task_id:
297
+ return False
298
+ if project_root is None:
299
+ project_root = get_project_root(__file__)
300
+
301
+ task_file = _tasks_dir(project_root) / f"{task_id}.md"
302
+ if not task_file.is_file():
303
+ return False
304
+
305
+ summary = _extract_task_summary(task_file)
306
+
307
+ state_file = project_root / ".claude" / "project-state.md"
308
+ if state_file.is_file():
309
+ _append_completed_task(state_file, task_id, summary)
310
+
311
+ _unregister_active_task(project_root, task_id)
312
+
313
+ task_file.unlink()
314
+ return True
315
+
316
+
317
+ def list_tasks(project_root: Path = None) -> list:
318
+ """List all active tasks.
319
+
320
+ Args:
321
+ project_root: Project root. If None, auto-detected.
322
+ Returns:
323
+ List of dicts with task_id, description, phase, task_file.
324
+ """
325
+ if project_root is None:
326
+ project_root = get_project_root(__file__)
327
+
328
+ tasks_dir = _tasks_dir(project_root)
329
+ if not tasks_dir.is_dir():
330
+ return []
331
+
332
+ tasks = []
333
+ for f in sorted(tasks_dir.glob("*.md")):
334
+ info = _parse_task_file(f)
335
+ tasks.append(info)
336
+ return tasks
337
+
338
+
339
+ def _task_template(task_id: str, description: str, now: str) -> str:
340
+ """Generate the task state file template.
341
+
342
+ Args:
343
+ task_id: Task identifier.
344
+ description: Task description.
345
+ now: Creation timestamp string.
346
+ Returns:
347
+ YAML-in-Markdown template text (quotes sanitized).
348
+ """
349
+ safe_id = task_id.replace('"', "'")
350
+ safe_desc = description.replace('"', "'")
351
+ return f"""# 任务状态: {safe_id}
352
+
353
+ ```yaml
354
+ task_id: "{safe_id}"
355
+ task_description: "{safe_desc}"
356
+ current_phase: "P0"
357
+ complexity_level: ""
358
+ started_at: "{now}"
359
+ last_updated: "{now}"
360
+ phase_history: []
361
+ prd_file: ""
362
+ plan_file: ""
363
+ dev_method: ""
364
+ code_method: ""
365
+ architecture_decisions: []
366
+ requirements_clarification: []
367
+ deliverable_checklist:
368
+ P1: []
369
+ P2: []
370
+ P3: []
371
+ P4: []
372
+ P5: []
373
+ modified_files: []
374
+ review_retry_count: 0
375
+ key_context: ""
376
+ ```
377
+ """
378
+
379
+
380
+ def _parse_task_file(task_file: Path) -> dict:
381
+ """Parse a task file and extract key fields.
382
+
383
+ Args:
384
+ task_file: Path to the task state file.
385
+ Returns:
386
+ Dict with task_id, task_description, current_phase and task_file.
387
+ """
388
+ info = {"task_file": str(task_file)}
389
+ try:
390
+ content = task_file.read_text(encoding="utf-8")
391
+ for field in ("task_id", "task_description", "current_phase"):
392
+ m = re.search(rf"^{field}:\s*\"?([^\"]*?)\"?\s*$", content, re.M)
393
+ info[field] = m.group(1) if m else ""
394
+ except Exception:
395
+ info["task_id"] = task_file.stem
396
+ info["task_description"] = ""
397
+ info["current_phase"] = "P0"
398
+ return info
399
+
400
+
401
+ def _extract_task_summary(task_file: Path) -> dict:
402
+ """Extract summary fields from a task file for completed_tasks entry.
403
+
404
+ Args:
405
+ task_file: Path to the task state file.
406
+ Returns:
407
+ Dict with description, complexity and modified files.
408
+ """
409
+ info = _parse_task_file(task_file)
410
+ try:
411
+ content = task_file.read_text(encoding="utf-8")
412
+ m = re.search(r"^complexity_level:\s*\"?([^\"]*?)\"?\s*$", content, re.M)
413
+ info["complexity_level"] = m.group(1) if m else ""
414
+ m = re.search(r"^modified_files:\s*\n((?:\s+-\s+.*\n)*)", content, re.M)
415
+ if m:
416
+ files = re.findall(r"-\s+\"?([^\"]*?)\"?\s*$", m.group(1), re.M)
417
+ info["modified_files"] = files
418
+ else:
419
+ info["modified_files"] = []
420
+ except Exception:
421
+ info["complexity_level"] = ""
422
+ info["modified_files"] = []
423
+ return info
424
+
425
+
426
+ def _insert_yaml_list_entry(content: str, key: str, entry: str) -> str:
427
+ """Insert an entry under a YAML list key, supporting inline-empty [] format (Issue 5).
428
+
429
+ Args:
430
+ content: Full state file content.
431
+ key: List key ("active_tasks" / "completed_tasks").
432
+ entry: Pre-indented entry text ending with newline.
433
+ Returns:
434
+ Updated content with the entry appended to the list (unchanged if key absent).
435
+ """
436
+ inline = re.search(rf"^{re.escape(key)}:\s*\[\s*\]\s*$", content, re.M)
437
+ if inline:
438
+ tail = content[inline.end():]
439
+ if tail.startswith("\n"):
440
+ tail = tail[1:]
441
+ return content[: inline.start()] + f"{key}:\n{entry}" + tail
442
+ block = re.search(rf"{re.escape(key)}:\s*\n", content)
443
+ if block:
444
+ return content[: block.end()] + entry + content[block.end():]
445
+ return content
446
+
447
+
448
+ def _register_active_task(project_root: Path, task_id: str, description: str) -> None:
449
+ """Add a task entry to project-state.md active_tasks list.
450
+
451
+ Args:
452
+ project_root: Project root directory.
453
+ task_id: Task identifier.
454
+ description: Task description.
455
+ """
456
+ state_file = project_root / ".claude" / "project-state.md"
457
+ if not state_file.is_file():
458
+ return
459
+ try:
460
+ content = state_file.read_text(encoding="utf-8")
461
+ safe_id = task_id.replace('"', "'")
462
+ safe_desc = description.replace('"', "'")
463
+ entry = f' - task_id: "{safe_id}"\n description: "{safe_desc}"\n task_file: ".claude/tasks/{safe_id}.md"\n'
464
+ if "active_tasks:" in content:
465
+ content = _insert_yaml_list_entry(content, "active_tasks", entry)
466
+ else:
467
+ content = re.sub(
468
+ r"(\n# 当前任务)",
469
+ lambda m: f"\nactive_tasks:\n{entry}" + m.group(1),
470
+ content,
471
+ count=1,
472
+ )
473
+ state_file.write_text(content, encoding="utf-8")
474
+ except Exception:
475
+ pass
476
+
477
+
478
+ def _unregister_active_task(project_root: Path, task_id: str) -> None:
479
+ """Remove a task entry from project-state.md active_tasks list.
480
+
481
+ Args:
482
+ project_root: Project root directory.
483
+ task_id: Task identifier.
484
+ """
485
+ state_file = project_root / ".claude" / "project-state.md"
486
+ if not state_file.is_file():
487
+ return
488
+ try:
489
+ content = state_file.read_text(encoding="utf-8")
490
+ content = re.sub(
491
+ rf"\s*-\s+task_id:\s*\"{re.escape(task_id)}\"\n(?:\s+\w+:.*\n)*",
492
+ "\n",
493
+ content,
494
+ count=1,
495
+ )
496
+ state_file.write_text(content, encoding="utf-8")
497
+ except Exception:
498
+ pass
499
+
500
+
501
+ def _append_completed_task(state_file: Path, task_id: str, summary: dict) -> None:
502
+ """Append a task entry to completed_tasks in project-state.md.
503
+
504
+ Args:
505
+ state_file: Path to project-state.md.
506
+ task_id: Task identifier.
507
+ summary: Summary dict from _extract_task_summary().
508
+ """
509
+ try:
510
+ content = state_file.read_text(encoding="utf-8")
511
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
512
+ safe_desc = summary.get("task_description", "").replace('"', "'")
513
+ safe_files = ", ".join(summary.get("modified_files", [])).replace('"', "'")
514
+ entry = (
515
+ f' - task: "{safe_desc}"\n'
516
+ f' prd_summary: "{safe_desc}"\n'
517
+ f' key_decisions: ["{safe_files}"]\n'
518
+ f' completed_at: "{now}"\n'
519
+ )
520
+ content = _insert_yaml_list_entry(content, "completed_tasks", entry)
521
+ state_file.write_text(content, encoding="utf-8")
522
+ except Exception:
523
+ pass
524
+
525
+
526
+ def _cli(argv: list) -> int:
527
+ """CLI entry point: create / archive / list / use.
528
+
529
+ Args:
530
+ argv: Arguments without the script name.
531
+ Returns:
532
+ Process exit code.
533
+ """
534
+ if not argv:
535
+ print("Usage: task_manager.py <create|archive|list|use> [task-id] [description|session-id]")
536
+ return 1
537
+ cmd = argv[0]
538
+ root = get_project_root(__file__)
539
+
540
+ if cmd == "create":
541
+ tid = argv[1] if len(argv) > 1 else ""
542
+ desc = argv[2] if len(argv) > 2 else ""
543
+ if not tid:
544
+ print("Error: task-id required")
545
+ return 1
546
+ try:
547
+ path = create_task(tid, desc, root)
548
+ except ValueError as exc:
549
+ print(f"Error: {exc}")
550
+ return 1
551
+ print(f"Created: {path}")
552
+ return 0
553
+
554
+ if cmd == "archive":
555
+ tid = argv[1] if len(argv) > 1 else ""
556
+ if not tid:
557
+ print("Error: task-id required")
558
+ return 1
559
+ ok = archive_task(tid, root)
560
+ print(f"Archived: {ok}")
561
+ return 0
562
+
563
+ if cmd == "use":
564
+ tid = argv[1] if len(argv) > 1 else ""
565
+ if not tid:
566
+ print("Error: task-id required")
567
+ return 1
568
+ sid = (argv[2] if len(argv) > 2 else "").strip() or _last_session_id(root)
569
+ if not sid:
570
+ print("Error: session-id unavailable (pass it explicitly)")
571
+ return 1
572
+ ok = bind_session(root, sid, tid)
573
+ if not ok:
574
+ print("Error: invalid task-id or empty session")
575
+ return 1
576
+ remember_session(root, sid)
577
+ print(f"Bound: session {sid} -> {tid}")
578
+ return 0
579
+
580
+ if cmd == "list":
581
+ for t in list_tasks(root):
582
+ print(f" [{t.get('current_phase', '?')}] {t.get('task_id', '?')} - {t.get('task_description', '')}")
583
+ for sid, tid in _read_bindings(root).items():
584
+ print(f" session {sid} -> {tid}")
585
+ return 0
586
+
587
+ print(f"Unknown command: {cmd}")
588
+ return 1
589
+
590
+
591
+ if __name__ == "__main__":
592
+ sys.exit(_cli(sys.argv[1:]))