gptodo 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gptodo/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """gptodo - Task management and work queue generation utilities for gptme agents.
2
+
3
+ This package provides CLI tools for managing tasks in gptme agent workspaces.
4
+
5
+ Installation:
6
+ # Standalone (recommended)
7
+ uv tool install git+https://github.com/gptme/gptme-contrib#subdirectory=packages/gptodo
8
+
9
+ # From workspace
10
+ uv pip install -e packages/gptodo
11
+ """
12
+
13
+ __version__ = "0.1.0"
gptodo/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Main entry point for gptodo CLI.
2
+
3
+ Provides a unified command-line interface for task management operations.
4
+ Supports both direct invocation (`python -m gptodo`) and package entry point.
5
+ """
6
+
7
+ from gptodo.cli import cli
8
+
9
+ if __name__ == "__main__":
10
+ cli()
gptodo/agents.py ADDED
@@ -0,0 +1,314 @@
1
+ """Agent registry for multi-agent coordination.
2
+
3
+ Tracks which agents exist and their status via file-based coordination.
4
+ Agent status files are stored in state/agents/ directory.
5
+
6
+ Status file format: {agent_id}.status containing JSON:
7
+ {
8
+ "agent_id": "bob-session-123",
9
+ "instance_type": "autonomous",
10
+ "started": "2026-01-28T08:00:00Z",
11
+ "last_heartbeat": "2026-01-28T08:15:00Z",
12
+ "current_task": "implement-feature-x",
13
+ "tasks_completed": 3,
14
+ "status": "working",
15
+ "workspace": "/home/bob/bob"
16
+ }
17
+
18
+ Design doc: tools/gptodo/docs/DESIGN-multi-agent-coordination.md
19
+ Tracking: ErikBjare/bob#263
20
+ """
21
+
22
+ import json
23
+ import logging
24
+ from dataclasses import dataclass, asdict
25
+ from datetime import datetime, timezone, timedelta
26
+ from pathlib import Path
27
+ from typing import Optional, List, Literal
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ # Default heartbeat timeout - agent considered stale after this
32
+ DEFAULT_HEARTBEAT_TIMEOUT_MINUTES = 30
33
+
34
+ # Agent status values
35
+ AgentStatus = Literal["starting", "idle", "working", "waiting", "stopping"]
36
+
37
+
38
+ @dataclass
39
+ class AgentInfo:
40
+ """Information about a registered agent."""
41
+
42
+ agent_id: str
43
+ instance_type: str = "autonomous"
44
+ started: str = ""
45
+ last_heartbeat: str = ""
46
+ current_task: Optional[str] = None
47
+ tasks_completed: int = 0
48
+ status: AgentStatus = "starting"
49
+ workspace: str = ""
50
+
51
+ def __post_init__(self):
52
+ if not self.started:
53
+ self.started = datetime.now(timezone.utc).isoformat()
54
+ if not self.last_heartbeat:
55
+ self.last_heartbeat = self.started
56
+
57
+ def is_stale(self, timeout_minutes: int = DEFAULT_HEARTBEAT_TIMEOUT_MINUTES) -> bool:
58
+ """Check if agent heartbeat has timed out."""
59
+ try:
60
+ heartbeat_time = datetime.fromisoformat(self.last_heartbeat.replace("Z", "+00:00"))
61
+ cutoff = datetime.now(timezone.utc) - timedelta(minutes=timeout_minutes)
62
+ return heartbeat_time < cutoff
63
+ except (ValueError, TypeError):
64
+ return True
65
+
66
+ def to_dict(self) -> dict:
67
+ """Convert to dictionary for JSON serialization."""
68
+ return asdict(self)
69
+
70
+ @classmethod
71
+ def from_dict(cls, data: dict) -> "AgentInfo":
72
+ """Create AgentInfo from dictionary."""
73
+ # Filter to only known fields
74
+ known_fields = {
75
+ "agent_id",
76
+ "instance_type",
77
+ "started",
78
+ "last_heartbeat",
79
+ "current_task",
80
+ "tasks_completed",
81
+ "status",
82
+ "workspace",
83
+ }
84
+ filtered = {k: v for k, v in data.items() if k in known_fields}
85
+ return cls(**filtered)
86
+
87
+
88
+ def get_agents_dir(workspace: Optional[Path] = None) -> Path:
89
+ """Get the agents status directory path.
90
+
91
+ Args:
92
+ workspace: Optional workspace root. Defaults to cwd.
93
+
94
+ Returns:
95
+ Path to state/agents/ directory
96
+ """
97
+ if workspace is None:
98
+ workspace = Path.cwd()
99
+ return workspace / "state" / "agents"
100
+
101
+
102
+ def register_agent(
103
+ agent_id: str,
104
+ workspace: Optional[Path] = None,
105
+ instance_type: str = "autonomous",
106
+ ) -> AgentInfo:
107
+ """Register a new agent or update existing registration.
108
+
109
+ Args:
110
+ agent_id: Unique identifier for the agent instance
111
+ workspace: Workspace root directory
112
+ instance_type: Type of agent (autonomous, interactive, etc.)
113
+
114
+ Returns:
115
+ AgentInfo for the registered agent
116
+ """
117
+ agents_dir = get_agents_dir(workspace)
118
+ agents_dir.mkdir(parents=True, exist_ok=True)
119
+
120
+ status_file = agents_dir / f"{agent_id}.status"
121
+
122
+ # Check if agent already exists
123
+ existing = None
124
+ if status_file.exists():
125
+ try:
126
+ existing = AgentInfo.from_dict(json.loads(status_file.read_text()))
127
+ except (json.JSONDecodeError, KeyError):
128
+ pass
129
+
130
+ # Create or update agent info
131
+ now = datetime.now(timezone.utc).isoformat()
132
+ if existing:
133
+ # Update existing agent
134
+ existing.last_heartbeat = now
135
+ existing.status = "idle"
136
+ agent_info = existing
137
+ else:
138
+ # Create new agent
139
+ agent_info = AgentInfo(
140
+ agent_id=agent_id,
141
+ instance_type=instance_type,
142
+ started=now,
143
+ last_heartbeat=now,
144
+ status="starting",
145
+ workspace=str(workspace or Path.cwd()),
146
+ )
147
+
148
+ # Write status file
149
+ status_file.write_text(json.dumps(agent_info.to_dict(), indent=2))
150
+ logger.info(f"Registered agent: {agent_id}")
151
+
152
+ return agent_info
153
+
154
+
155
+ def update_agent_status(
156
+ agent_id: str,
157
+ status: AgentStatus,
158
+ current_task: Optional[str] = None,
159
+ workspace: Optional[Path] = None,
160
+ ) -> Optional[AgentInfo]:
161
+ """Update agent status and heartbeat.
162
+
163
+ Args:
164
+ agent_id: Agent identifier
165
+ status: New status value
166
+ current_task: Task currently being worked on (or None)
167
+ workspace: Workspace root directory
168
+
169
+ Returns:
170
+ Updated AgentInfo or None if agent not found
171
+ """
172
+ agents_dir = get_agents_dir(workspace)
173
+ status_file = agents_dir / f"{agent_id}.status"
174
+
175
+ if not status_file.exists():
176
+ logger.warning(f"Agent not found: {agent_id}")
177
+ return None
178
+
179
+ try:
180
+ agent_info = AgentInfo.from_dict(json.loads(status_file.read_text()))
181
+ except (json.JSONDecodeError, KeyError) as e:
182
+ logger.error(f"Failed to read agent status: {e}")
183
+ return None
184
+
185
+ # Update fields
186
+ agent_info.status = status
187
+ agent_info.current_task = current_task
188
+ agent_info.last_heartbeat = datetime.now(timezone.utc).isoformat()
189
+
190
+ # Increment completed count when transitioning from working to idle
191
+ # (This is a simple heuristic - could be made more sophisticated)
192
+
193
+ # Write updated status
194
+ status_file.write_text(json.dumps(agent_info.to_dict(), indent=2))
195
+
196
+ return agent_info
197
+
198
+
199
+ def unregister_agent(agent_id: str, workspace: Optional[Path] = None) -> bool:
200
+ """Remove agent registration.
201
+
202
+ Args:
203
+ agent_id: Agent identifier
204
+ workspace: Workspace root directory
205
+
206
+ Returns:
207
+ True if agent was unregistered, False if not found
208
+ """
209
+ agents_dir = get_agents_dir(workspace)
210
+ status_file = agents_dir / f"{agent_id}.status"
211
+
212
+ if status_file.exists():
213
+ status_file.unlink()
214
+ logger.info(f"Unregistered agent: {agent_id}")
215
+ return True
216
+ return False
217
+
218
+
219
+ def list_agents(
220
+ workspace: Optional[Path] = None,
221
+ include_stale: bool = False,
222
+ timeout_minutes: int = DEFAULT_HEARTBEAT_TIMEOUT_MINUTES,
223
+ ) -> List[AgentInfo]:
224
+ """List all registered agents.
225
+
226
+ Args:
227
+ workspace: Workspace root directory
228
+ include_stale: Include agents with stale heartbeats
229
+ timeout_minutes: Minutes before heartbeat is considered stale
230
+
231
+ Returns:
232
+ List of AgentInfo objects for registered agents
233
+ """
234
+ agents_dir = get_agents_dir(workspace)
235
+ if not agents_dir.exists():
236
+ return []
237
+
238
+ agents = []
239
+ for status_file in agents_dir.glob("*.status"):
240
+ try:
241
+ data = json.loads(status_file.read_text())
242
+ agent_info = AgentInfo.from_dict(data)
243
+
244
+ # Skip stale agents unless requested
245
+ if not include_stale and agent_info.is_stale(timeout_minutes):
246
+ continue
247
+
248
+ agents.append(agent_info)
249
+ except (json.JSONDecodeError, KeyError) as e:
250
+ logger.warning(f"Failed to read agent status {status_file}: {e}")
251
+ continue
252
+
253
+ # Sort by started time (newest first)
254
+ agents.sort(key=lambda a: a.started, reverse=True)
255
+ return agents
256
+
257
+
258
+ def cleanup_stale_agents(
259
+ workspace: Optional[Path] = None,
260
+ timeout_minutes: int = DEFAULT_HEARTBEAT_TIMEOUT_MINUTES,
261
+ ) -> List[str]:
262
+ """Remove stale agent registrations.
263
+
264
+ Args:
265
+ workspace: Workspace root directory
266
+ timeout_minutes: Minutes before heartbeat is considered stale
267
+
268
+ Returns:
269
+ List of cleaned up agent IDs
270
+ """
271
+ agents_dir = get_agents_dir(workspace)
272
+ if not agents_dir.exists():
273
+ return []
274
+
275
+ cleaned = []
276
+ for status_file in agents_dir.glob("*.status"):
277
+ try:
278
+ data = json.loads(status_file.read_text())
279
+ agent_info = AgentInfo.from_dict(data)
280
+
281
+ if agent_info.is_stale(timeout_minutes):
282
+ status_file.unlink()
283
+ cleaned.append(agent_info.agent_id)
284
+ logger.info(f"Cleaned up stale agent: {agent_info.agent_id}")
285
+ except (json.JSONDecodeError, KeyError) as e:
286
+ # Remove corrupt status files
287
+ status_file.unlink()
288
+ cleaned.append(status_file.stem)
289
+ logger.warning(f"Removed corrupt agent status {status_file}: {e}")
290
+
291
+ return cleaned
292
+
293
+
294
+ def get_agent(agent_id: str, workspace: Optional[Path] = None) -> Optional[AgentInfo]:
295
+ """Get info for a specific agent.
296
+
297
+ Args:
298
+ agent_id: Agent identifier
299
+ workspace: Workspace root directory
300
+
301
+ Returns:
302
+ AgentInfo or None if not found
303
+ """
304
+ agents_dir = get_agents_dir(workspace)
305
+ status_file = agents_dir / f"{agent_id}.status"
306
+
307
+ if not status_file.exists():
308
+ return None
309
+
310
+ try:
311
+ data = json.loads(status_file.read_text())
312
+ return AgentInfo.from_dict(data)
313
+ except (json.JSONDecodeError, KeyError):
314
+ return None
gptodo/checker.py ADDED
@@ -0,0 +1,342 @@
1
+ #!/usr/bin/env python3
2
+ """Checker pattern implementation for task verification.
3
+
4
+ The checker pattern provides periodic verification of task state,
5
+ detecting completion, identifying issues, and auto-creating fix tasks.
6
+
7
+ This pattern is inspired by Claude Code's checker agent which monitors
8
+ task progress and ensures quality.
9
+ """
10
+
11
+ import logging
12
+ import time
13
+ from dataclasses import dataclass, field
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+ from typing import Callable, TypedDict
17
+
18
+ from .utils import (
19
+ TaskInfo,
20
+ load_tasks,
21
+ )
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class CheckDetails(TypedDict, total=False):
27
+ """Type for check details dictionary."""
28
+
29
+ completed: int
30
+ total: int
31
+ percentage: float
32
+ resolved: list[str]
33
+ unresolved: list[str]
34
+ valid_states: list[str]
35
+ previous_state: str
36
+ allowed_transitions: list[str]
37
+ next_states: list[str]
38
+
39
+
40
+ class CheckResultDict(TypedDict):
41
+ """Type for individual check result."""
42
+
43
+ check: str
44
+ passed: bool
45
+ message: str
46
+ details: CheckDetails
47
+
48
+
49
+ @dataclass
50
+ class CheckResult:
51
+ """Result of a task check."""
52
+
53
+ task_id: str
54
+ timestamp: str
55
+ status: str # "passed", "failed", "needs_attention", "in_progress"
56
+ checks: list[CheckResultDict] = field(default_factory=list)
57
+ fixes_created: list[str] = field(default_factory=list)
58
+ message: str = ""
59
+
60
+
61
+ @dataclass
62
+ class CheckerConfig:
63
+ """Configuration for the checker agent."""
64
+
65
+ # Polling configuration
66
+ poll_interval_seconds: int = 30 # How often to check (default: 30s)
67
+ max_polls: int = 100 # Maximum number of polls before timeout
68
+
69
+ # Verification settings
70
+ verify_subtasks: bool = True # Check subtask completion
71
+ verify_dependencies: bool = True # Check dependency resolution
72
+ verify_state_transitions: bool = True # Check valid state transitions
73
+
74
+ # Auto-fix settings
75
+ auto_create_fix_tasks: bool = False # Auto-create tasks for issues
76
+ fix_task_prefix: str = "fix-" # Prefix for auto-created fix tasks
77
+
78
+ # Agent settings
79
+ use_agent_verification: bool = False # Use LLM agent for semantic verification
80
+ agent_model: str | None = None # Model for agent verification
81
+
82
+
83
+ # Valid state transitions
84
+ VALID_TRANSITIONS: dict[str, list[str]] = {
85
+ "backlog": ["todo", "cancelled"],
86
+ "todo": ["active", "backlog", "cancelled"],
87
+ "active": ["ready_for_review", "waiting", "done", "cancelled"],
88
+ "ready_for_review": ["active", "done", "cancelled"], # Can go back to active if review fails
89
+ "waiting": ["active", "cancelled"],
90
+ "done": [], # Terminal state
91
+ "cancelled": [], # Terminal state
92
+ }
93
+
94
+
95
+ def check_subtask_completion(task: TaskInfo) -> CheckResultDict:
96
+ """Check if all subtasks are completed for a task marked as done/ready_for_review."""
97
+ details: CheckDetails = {}
98
+ result: CheckResultDict = {
99
+ "check": "subtask_completion",
100
+ "passed": True,
101
+ "message": "",
102
+ "details": details,
103
+ }
104
+
105
+ if task.subtasks.total == 0:
106
+ result["message"] = "No subtasks defined"
107
+ return result
108
+
109
+ completion_pct = (task.subtasks.completed / task.subtasks.total) * 100
110
+ details["completed"] = task.subtasks.completed
111
+ details["total"] = task.subtasks.total
112
+ details["percentage"] = completion_pct
113
+
114
+ if task.state in ["done", "ready_for_review"] and completion_pct < 100:
115
+ result["passed"] = False
116
+ result["message"] = (
117
+ f"Task marked as {task.state} but only {task.subtasks.completed}/{task.subtasks.total} "
118
+ f"subtasks completed ({completion_pct:.0f}%)"
119
+ )
120
+ else:
121
+ result["message"] = f"{task.subtasks.completed}/{task.subtasks.total} subtasks completed"
122
+
123
+ return result
124
+
125
+
126
+ def check_dependency_resolution(task: TaskInfo, all_tasks: dict[str, TaskInfo]) -> CheckResultDict:
127
+ """Check if all dependencies are resolved for an active/done task."""
128
+ details: CheckDetails = {}
129
+ result: CheckResultDict = {
130
+ "check": "dependency_resolution",
131
+ "passed": True,
132
+ "message": "",
133
+ "details": details,
134
+ }
135
+
136
+ if not task.requires:
137
+ result["message"] = "No dependencies"
138
+ return result
139
+
140
+ unresolved: list[str] = []
141
+ resolved: list[str] = []
142
+
143
+ for dep in task.requires:
144
+ if dep.startswith("http"):
145
+ # URL dependency - can't check without cache
146
+ continue
147
+ dep_task = all_tasks.get(dep)
148
+ if dep_task is None:
149
+ unresolved.append(f"{dep} (not found)")
150
+ elif dep_task.state not in ["done", "cancelled"]:
151
+ unresolved.append(f"{dep} ({dep_task.state})")
152
+ else:
153
+ resolved.append(dep)
154
+
155
+ # Exclude URL deps from total since they're skipped
156
+ url_deps = sum(1 for dep in task.requires if dep.startswith("http"))
157
+ details["resolved"] = resolved
158
+ details["unresolved"] = unresolved
159
+ details["total"] = len(task.requires) - url_deps
160
+
161
+ if unresolved and task.state in ["active", "done", "ready_for_review"]:
162
+ result["passed"] = False
163
+ result["message"] = f"Unresolved dependencies: {', '.join(unresolved)}"
164
+ else:
165
+ result["message"] = f"{len(resolved)}/{len(task.requires)} dependencies resolved"
166
+
167
+ return result
168
+
169
+
170
+ def check_state_validity(task: TaskInfo, previous_state: str | None = None) -> CheckResultDict:
171
+ """Check if task state is valid and transition is allowed."""
172
+ details: CheckDetails = {}
173
+ result: CheckResultDict = {
174
+ "check": "state_validity",
175
+ "passed": True,
176
+ "message": "",
177
+ "details": details,
178
+ }
179
+
180
+ valid_states = list(VALID_TRANSITIONS.keys())
181
+
182
+ if task.state not in valid_states:
183
+ result["passed"] = False
184
+ result["message"] = f"Invalid state: {task.state}"
185
+ details["valid_states"] = valid_states
186
+ return result
187
+
188
+ if previous_state and previous_state in VALID_TRANSITIONS:
189
+ allowed = VALID_TRANSITIONS[previous_state]
190
+ if task.state not in allowed and task.state != previous_state:
191
+ result["passed"] = False
192
+ result["message"] = (
193
+ f"Invalid state transition: {previous_state} → {task.state}. " f"Allowed: {allowed}"
194
+ )
195
+ details["previous_state"] = previous_state
196
+ details["allowed_transitions"] = allowed
197
+ return result
198
+
199
+ result["message"] = f"State '{task.state}' is valid"
200
+ details["next_states"] = VALID_TRANSITIONS.get(task.state, [])
201
+ return result
202
+
203
+
204
+ def run_checker(
205
+ task_id: str,
206
+ repo_root: Path,
207
+ config: CheckerConfig | None = None,
208
+ on_check: Callable[[CheckResult], None] | None = None,
209
+ ) -> CheckResult:
210
+ """Run checker verification on a task.
211
+
212
+ Args:
213
+ task_id: Task ID or name to check
214
+ repo_root: Repository root path
215
+ config: Checker configuration (uses defaults if None)
216
+ on_check: Optional callback for each check iteration
217
+
218
+ Returns:
219
+ CheckResult with verification outcome
220
+ """
221
+ config = config or CheckerConfig()
222
+ tasks_dir = repo_root / "tasks"
223
+
224
+ # Load tasks
225
+ tasks = load_tasks(tasks_dir)
226
+ all_tasks = {t.name: t for t in tasks}
227
+
228
+ # Find target task
229
+ task = all_tasks.get(task_id)
230
+ if not task:
231
+ # Try matching by ID
232
+ for t in tasks:
233
+ if t.id == task_id:
234
+ task = t
235
+ break
236
+
237
+ if not task:
238
+ return CheckResult(
239
+ task_id=task_id,
240
+ timestamp=datetime.now(timezone.utc).isoformat(),
241
+ status="failed",
242
+ message=f"Task not found: {task_id}",
243
+ )
244
+
245
+ # Run checks
246
+ checks: list[CheckResultDict] = []
247
+ all_passed = True
248
+
249
+ # Check 1: Subtask completion
250
+ if config.verify_subtasks:
251
+ subtask_check = check_subtask_completion(task)
252
+ checks.append(subtask_check)
253
+ if not subtask_check["passed"]:
254
+ all_passed = False
255
+
256
+ # Check 2: Dependency resolution
257
+ if config.verify_dependencies:
258
+ dep_check = check_dependency_resolution(task, all_tasks)
259
+ checks.append(dep_check)
260
+ if not dep_check["passed"]:
261
+ all_passed = False
262
+
263
+ # Check 3: State validity
264
+ if config.verify_state_transitions:
265
+ state_check = check_state_validity(task)
266
+ checks.append(state_check)
267
+ if not state_check["passed"]:
268
+ all_passed = False
269
+
270
+ # Determine overall status
271
+ if all_passed:
272
+ if task.state in ["done", "cancelled"]:
273
+ status = "passed"
274
+ message = f"Task {task_id} verification passed (state: {task.state})"
275
+ elif task.state == "ready_for_review":
276
+ status = "needs_attention"
277
+ message = f"Task {task_id} is ready for review"
278
+ else:
279
+ status = "in_progress"
280
+ message = f"Task {task_id} is in progress (state: {task.state})"
281
+ else:
282
+ status = "failed"
283
+ failed_checks = [c["check"] for c in checks if not c["passed"]]
284
+ message = f"Task {task_id} failed checks: {', '.join(failed_checks)}"
285
+
286
+ result = CheckResult(
287
+ task_id=task_id,
288
+ timestamp=datetime.now(timezone.utc).isoformat(),
289
+ status=status,
290
+ checks=checks,
291
+ message=message,
292
+ )
293
+
294
+ if on_check:
295
+ on_check(result)
296
+
297
+ return result
298
+
299
+
300
+ def poll_task_completion(
301
+ task_id: str,
302
+ repo_root: Path,
303
+ config: CheckerConfig | None = None,
304
+ on_poll: Callable[[int, CheckResult], bool] | None = None,
305
+ ) -> CheckResult:
306
+ """Poll a task until it reaches completion or timeout.
307
+
308
+ Args:
309
+ task_id: Task ID to poll
310
+ repo_root: Repository root path
311
+ config: Checker configuration
312
+ on_poll: Callback(poll_num, result) - return False to stop polling
313
+
314
+ Returns:
315
+ Final CheckResult
316
+ """
317
+ config = config or CheckerConfig()
318
+
319
+ for poll_num in range(config.max_polls):
320
+ result = run_checker(task_id, repo_root, config)
321
+
322
+ # Check if we should stop
323
+ if result.status in ["passed", "failed"]:
324
+ return result
325
+
326
+ # Callback
327
+ if on_poll:
328
+ should_continue = on_poll(poll_num, result)
329
+ if not should_continue:
330
+ return result
331
+
332
+ # Wait before next poll
333
+ if poll_num < config.max_polls - 1:
334
+ time.sleep(config.poll_interval_seconds)
335
+
336
+ # Timeout
337
+ return CheckResult(
338
+ task_id=task_id,
339
+ timestamp=datetime.now(timezone.utc).isoformat(),
340
+ status="failed",
341
+ message=f"Timeout after {config.max_polls} polls",
342
+ )