In-memory task board with JSON persistence. Provides CRUD operations for tasks, a revision log for auditability, and atomic JSON persistence via tmp-file + rename.
| 36 | |
| 37 | |
| 38 | class TaskBoard: |
| 39 | """In-memory task board with JSON persistence. |
| 40 | |
| 41 | Provides CRUD operations for tasks, a revision log for auditability, |
| 42 | and atomic JSON persistence via tmp-file + rename. |
| 43 | """ |
| 44 | |
| 45 | def __init__(self, persist_path: Optional[Path] = None): |
| 46 | self._tasks: dict[str, Task] = {} |
| 47 | self._counter: int = 0 |
| 48 | self._lock = threading.Lock() |
| 49 | self._persist_path = persist_path |
| 50 | self._revision_log: list[dict] = [] |
| 51 | if persist_path and persist_path.exists(): |
| 52 | self._load() |
| 53 | |
| 54 | def create_task(self, description: str, parent_id: Optional[str] = None) -> Task: |
| 55 | """Create a new task and persist.""" |
| 56 | with self._lock: |
| 57 | self._counter += 1 |
| 58 | task_id = f"task_{self._counter:03d}" |
| 59 | now = datetime.now(timezone.utc).isoformat() |
| 60 | task = Task( |
| 61 | id=task_id, |
| 62 | description=description, |
| 63 | parent_id=parent_id, |
| 64 | created_at=now, |
| 65 | updated_at=now, |
| 66 | ) |
| 67 | self._tasks[task_id] = task |
| 68 | self._revision_log.append( |
| 69 | { |
| 70 | "timestamp": now, |
| 71 | "action": "created", |
| 72 | "task_id": task_id, |
| 73 | "description": description, |
| 74 | } |
| 75 | ) |
| 76 | self._persist() |
| 77 | return task |
| 78 | |
| 79 | def update_task(self, task_id: str, **kwargs) -> Task: |
| 80 | """Update task fields and persist. Accepts any Task field as kwarg.""" |
| 81 | with self._lock: |
| 82 | task = self._tasks.get(task_id) |
| 83 | if not task: |
| 84 | raise ValueError(f"Task {task_id} not found") |
| 85 | for key, value in kwargs.items(): |
| 86 | if value is None: |
| 87 | continue |
| 88 | if key == "status" and isinstance(value, str): |
| 89 | value = TaskStatus(value) |
| 90 | if hasattr(task, key): |
| 91 | setattr(task, key, value) |
| 92 | task.updated_at = datetime.now(timezone.utc).isoformat() |
| 93 | self._revision_log.append( |
| 94 | { |
| 95 | "timestamp": task.updated_at, |