robert-github-agent 0.1.0b1__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.
Files changed (111) hide show
  1. robert_agent/__init__.py +1 -0
  2. robert_agent/acceptance.py +394 -0
  3. robert_agent/acceptance_suite.py +287 -0
  4. robert_agent/audit_result.py +501 -0
  5. robert_agent/authorize.py +117 -0
  6. robert_agent/board.py +538 -0
  7. robert_agent/chat_status.py +338 -0
  8. robert_agent/cli/__init__.py +1 -0
  9. robert_agent/cli/exit_codes.py +5 -0
  10. robert_agent/cli/main.py +535 -0
  11. robert_agent/cli/output.py +20 -0
  12. robert_agent/common.py +6 -0
  13. robert_agent/controlled_e2e_acceptance.py +394 -0
  14. robert_agent/daemon.py +607 -0
  15. robert_agent/daemon_state.py +319 -0
  16. robert_agent/diagnostics.py +119 -0
  17. robert_agent/discover.py +775 -0
  18. robert_agent/dispatch.py +217 -0
  19. robert_agent/doctor.py +94 -0
  20. robert_agent/github_api.py +12 -0
  21. robert_agent/init_config.py +126 -0
  22. robert_agent/integrations/__init__.py +1 -0
  23. robert_agent/integrations/openclaw.py +285 -0
  24. robert_agent/live_discovery_acceptance.py +70 -0
  25. robert_agent/live_worker_acceptance.py +363 -0
  26. robert_agent/live_worktree_acceptance.py +344 -0
  27. robert_agent/loop_engine.py +285 -0
  28. robert_agent/memory_curator.py +105 -0
  29. robert_agent/migrate.py +157 -0
  30. robert_agent/notify.py +74 -0
  31. robert_agent/paths.py +16 -0
  32. robert_agent/production_write_canary.py +254 -0
  33. robert_agent/project_memory.py +503 -0
  34. robert_agent/publish.py +743 -0
  35. robert_agent/publish_dedupe_acceptance.py +270 -0
  36. robert_agent/redaction.py +41 -0
  37. robert_agent/render_prompt.py +544 -0
  38. robert_agent/resource_files.py +8 -0
  39. robert_agent/resources/__init__.py +1 -0
  40. robert_agent/resources/acceptance-matrix.md +120 -0
  41. robert_agent/resources/classifier.md +19 -0
  42. robert_agent/resources/command-matrix.md +38 -0
  43. robert_agent/resources/config.example.yml +20 -0
  44. robert_agent/resources/db/migrations/001_legacy_dd_to_robert.sql +14 -0
  45. robert_agent/resources/db/schema.sql +479 -0
  46. robert_agent/resources/failure-modes.md +36 -0
  47. robert_agent/resources/fixtures/actor-permission.json +1 -0
  48. robert_agent/resources/fixtures/discovery.json +1 -0
  49. robert_agent/resources/fixtures/redaction.json +1 -0
  50. robert_agent/resources/fixtures/review-followup.json +1 -0
  51. robert_agent/resources/fixtures/worker-results.json +1 -0
  52. robert_agent/resources/fixtures/workstreams.json +1 -0
  53. robert_agent/resources/github-events.md +77 -0
  54. robert_agent/resources/kanban-control.md +165 -0
  55. robert_agent/resources/redaction.md +29 -0
  56. robert_agent/resources/result-contract.md +56 -0
  57. robert_agent/resources/routes.yml +82 -0
  58. robert_agent/resources/schemas/config.schema.json +123 -0
  59. robert_agent/resources/schemas/event.schema.json +18 -0
  60. robert_agent/resources/schemas/result.schema.json +99 -0
  61. robert_agent/resources/schemas/route.schema.json +23 -0
  62. robert_agent/resources/schemas/snapshot.schema.json +17 -0
  63. robert_agent/resources/schemas/task.schema.json +15 -0
  64. robert_agent/resources/trust-model.md +16 -0
  65. robert_agent/resources/worker-prompt.md +121 -0
  66. robert_agent/resources/worker-protocol.md +47 -0
  67. robert_agent/resources/workflow.yml +50 -0
  68. robert_agent/resources/workstream-model.md +17 -0
  69. robert_agent/route.py +232 -0
  70. robert_agent/route_config.py +64 -0
  71. robert_agent/run_once.py +5375 -0
  72. robert_agent/runtime_knowledge.py +392 -0
  73. robert_agent/service.py +161 -0
  74. robert_agent/skills.py +28 -0
  75. robert_agent/status.py +1051 -0
  76. robert_agent/storage.py +376 -0
  77. robert_agent/summarize.py +100 -0
  78. robert_agent/supervise.py +72 -0
  79. robert_agent/usage.py +192 -0
  80. robert_agent/validate_config.py +616 -0
  81. robert_agent/wakeup.py +261 -0
  82. robert_agent/web.py +2893 -0
  83. robert_agent/web_assets/board.css +255 -0
  84. robert_agent/web_assets/board.html +165 -0
  85. robert_agent/web_assets/board.js +660 -0
  86. robert_agent/web_assets/github-shell.css +122 -0
  87. robert_agent/web_assets/index.html +103 -0
  88. robert_agent/web_assets/operations.css +168 -0
  89. robert_agent/web_assets/workbench.css +131 -0
  90. robert_agent/web_assets/workbench.js +581 -0
  91. robert_agent/work_items.py +1016 -0
  92. robert_agent/workbench.py +701 -0
  93. robert_agent/worker/__init__.py +1 -0
  94. robert_agent/worker/heartbeat.py +190 -0
  95. robert_agent/worker/result.py +321 -0
  96. robert_agent/worker/snapshot.py +98 -0
  97. robert_agent/worker_adapters/__init__.py +138 -0
  98. robert_agent/worker_adapters/cbc.py +68 -0
  99. robert_agent/worker_adapters/codex.py +56 -0
  100. robert_agent/worker_adapters/command.py +33 -0
  101. robert_agent/worker_adapters/tcodex.py +56 -0
  102. robert_agent/worker_heartbeat.py +6 -0
  103. robert_agent/worker_result.py +6 -0
  104. robert_agent/worker_snapshot.py +6 -0
  105. robert_agent/workstream.py +55 -0
  106. robert_agent/worktree.py +297 -0
  107. robert_github_agent-0.1.0b1.dist-info/METADATA +217 -0
  108. robert_github_agent-0.1.0b1.dist-info/RECORD +111 -0
  109. robert_github_agent-0.1.0b1.dist-info/WHEEL +4 -0
  110. robert_github_agent-0.1.0b1.dist-info/entry_points.txt +2 -0
  111. robert_github_agent-0.1.0b1.dist-info/licenses/LICENSE +201 -0
robert_agent/board.py ADDED
@@ -0,0 +1,538 @@
1
+ """Deterministic read models for the DD repository task board."""
2
+
3
+ import base64
4
+ from contextlib import closing
5
+ import json
6
+ from pathlib import Path
7
+ import sqlite3
8
+ from urllib.parse import urlsplit
9
+
10
+
11
+ COLUMNS = (
12
+ ("backlog", "Backlog"),
13
+ ("todo", "TODO"),
14
+ ("doing", "Doing"),
15
+ ("waiting", "Waiting for You"),
16
+ ("review", "Review"),
17
+ ("done", "Done"),
18
+ )
19
+ ATTENTION_EVENTS = frozenset(
20
+ {
21
+ "operator_question",
22
+ "completion_acceptance_requested",
23
+ "operator_decision_required",
24
+ "execution_failed",
25
+ "publication_failed",
26
+ "manual_worker_unavailable",
27
+ "review_attention",
28
+ "unmerged_pr_closed",
29
+ }
30
+ )
31
+ SAFE_EVENT_METADATA_KEYS = frozenset(
32
+ {
33
+ "kind",
34
+ "task_id",
35
+ "result_id",
36
+ "source_id",
37
+ "source_key",
38
+ "workstream_id",
39
+ "pr_number",
40
+ "url",
41
+ "route_confidence",
42
+ "requested_worker",
43
+ }
44
+ )
45
+
46
+
47
+ class BoardQueryError(ValueError):
48
+ pass
49
+
50
+
51
+ def _connect(db_path):
52
+ conn = sqlite3.connect(Path(db_path).expanduser())
53
+ conn.row_factory = sqlite3.Row
54
+ conn.execute("PRAGMA foreign_keys = ON")
55
+ conn.execute("PRAGMA busy_timeout = 5000")
56
+ return conn
57
+
58
+
59
+ def _decode_json(value, default):
60
+ if not value:
61
+ return default
62
+ try:
63
+ return json.loads(value)
64
+ except (TypeError, ValueError):
65
+ return default
66
+
67
+
68
+ def _cursor_encode(values):
69
+ raw = json.dumps(values, separators=(",", ":")).encode("utf-8")
70
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
71
+
72
+
73
+ def _cursor_decode(value):
74
+ if not value:
75
+ return None
76
+ try:
77
+ padded = value + "=" * (-len(value) % 4)
78
+ decoded = json.loads(base64.urlsafe_b64decode(padded).decode("utf-8"))
79
+ except (ValueError, TypeError, UnicodeDecodeError, json.JSONDecodeError) as exc:
80
+ raise BoardQueryError("invalid cursor") from exc
81
+ if (
82
+ not isinstance(decoded, list)
83
+ or len(decoded) != 2
84
+ or not all(isinstance(part, str) and part for part in decoded)
85
+ ):
86
+ raise BoardQueryError("invalid cursor")
87
+ return tuple(decoded)
88
+
89
+
90
+ def _safe_event_metadata(value):
91
+ metadata = _decode_json(value, {})
92
+ if not isinstance(metadata, dict):
93
+ return {}
94
+ return {
95
+ key: metadata[key]
96
+ for key in SAFE_EVENT_METADATA_KEYS
97
+ if key in metadata and isinstance(metadata[key], (str, int, float, bool, type(None)))
98
+ }
99
+
100
+
101
+ def _safe_http_url(value):
102
+ if not isinstance(value, str):
103
+ return None
104
+ parsed = urlsplit(value)
105
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
106
+ return None
107
+ return value
108
+
109
+
110
+ def _unresolved_attention(conn, work_item_id):
111
+ placeholders = ",".join("?" for _event_type in ATTENTION_EVENTS)
112
+ rows = conn.execute(
113
+ f"""
114
+ SELECT e.event_id, e.event_type, e.body, e.created_at, e.metadata_json
115
+ FROM work_item_events e
116
+ WHERE e.work_item_id = ?
117
+ AND e.event_type IN ({placeholders})
118
+ AND NOT EXISTS (
119
+ SELECT 1 FROM work_item_events response
120
+ WHERE response.resolves_event_id = e.event_id
121
+ )
122
+ ORDER BY e.created_at DESC, e.event_id DESC
123
+ """,
124
+ [work_item_id] + sorted(ATTENTION_EVENTS),
125
+ ).fetchall()
126
+ return [
127
+ {
128
+ "event_id": row["event_id"],
129
+ "type": row["event_type"],
130
+ "summary": row["body"][:500],
131
+ "created_at": row["created_at"],
132
+ "metadata": _safe_event_metadata(row["metadata_json"]),
133
+ }
134
+ for row in rows
135
+ ]
136
+
137
+
138
+ def _latest_task(conn, workstream_id):
139
+ return conn.execute(
140
+ """
141
+ SELECT task_id, lifecycle, priority, route_id, expected_output,
142
+ routing_mode, requested_worker, created_at, updated_at
143
+ FROM tasks
144
+ WHERE workstream_id = ?
145
+ ORDER BY created_at DESC, task_id DESC
146
+ LIMIT 1
147
+ """,
148
+ (workstream_id,),
149
+ ).fetchone()
150
+
151
+
152
+ def _latest_attempt(conn, workstream_id):
153
+ return conn.execute(
154
+ """
155
+ SELECT a.attempt_id, a.status, a.branch_name, a.worktree_path,
156
+ a.started_at, a.finished_at
157
+ FROM attempts a
158
+ JOIN tasks t ON t.task_id = a.task_id
159
+ WHERE t.workstream_id = ?
160
+ ORDER BY a.started_at DESC, a.attempt_id DESC
161
+ LIMIT 1
162
+ """,
163
+ (workstream_id,),
164
+ ).fetchone()
165
+
166
+
167
+ def _derived_pr(conn, root_workstream_id):
168
+ return conn.execute(
169
+ """
170
+ SELECT gs.number, gs.html_url, gs.state, w.workstream_id
171
+ FROM workstreams w
172
+ JOIN github_sources gs ON gs.source_id = w.primary_source_id
173
+ WHERE w.origin_workstream_id = ?
174
+ AND gs.source_type = 'pull_request'
175
+ ORDER BY w.updated_at DESC, gs.number DESC
176
+ LIMIT 1
177
+ """,
178
+ (root_workstream_id,),
179
+ ).fetchone()
180
+
181
+
182
+ def _valid_commands(item, column, attention, *, running=False):
183
+ if column == "backlog":
184
+ return ["edit", "start", "cancel"]
185
+ if column == "waiting":
186
+ if attention and attention[0]["type"] == "operator_decision_required":
187
+ return ["approve"] if running else ["approve", "cancel"]
188
+ commands = ["approve", "request_changes", "cancel"]
189
+ if any(signal["type"] in {"operator_question", "completion_acceptance_requested"} for signal in attention):
190
+ commands.insert(1, "reply")
191
+ if any(signal["type"] in ATTENTION_EVENTS - {"operator_question", "completion_acceptance_requested", "operator_decision_required"} for signal in attention):
192
+ commands.insert(-1, "retry")
193
+ return commands
194
+ if column == "review":
195
+ return ["request_changes", "cancel"] if attention else ["request_changes"]
196
+ if column == "done":
197
+ return ["reopen"]
198
+ if column == "todo":
199
+ return ["cancel"]
200
+ return []
201
+
202
+
203
+ def _project_item(conn, row):
204
+ work_item_id = row["work_item_id"]
205
+ workstream_id = row["workstream_id"]
206
+ attention = _unresolved_attention(conn, work_item_id)
207
+ task = _latest_task(conn, workstream_id) if workstream_id else None
208
+ attempt = _latest_attempt(conn, workstream_id) if workstream_id else None
209
+ pr = _derived_pr(conn, workstream_id) if workstream_id else None
210
+ running = bool(
211
+ workstream_id
212
+ and conn.execute(
213
+ """
214
+ SELECT 1 FROM attempts a
215
+ JOIN tasks t ON t.task_id = a.task_id
216
+ WHERE t.workstream_id = ? AND a.status = 'running'
217
+ LIMIT 1
218
+ """,
219
+ (workstream_id,),
220
+ ).fetchone()
221
+ )
222
+ publication_in_progress = bool(
223
+ workstream_id
224
+ and conn.execute(
225
+ """
226
+ SELECT 1 FROM github_actions ga
227
+ JOIN tasks t ON t.task_id = ga.task_id
228
+ WHERE t.workstream_id = ?
229
+ AND (ga.audit_status = 'pending'
230
+ OR (ga.audit_status = 'accepted' AND ga.publish_status = 'not_published'))
231
+ LIMIT 1
232
+ """,
233
+ (workstream_id,),
234
+ ).fetchone()
235
+ )
236
+
237
+ if row["canceled_at"]:
238
+ column, reason_code, reason_summary = "history", "canceled", "Canceled by the operator"
239
+ elif row["completed_at"]:
240
+ column, reason_code, reason_summary = "done", "completed", "Completion is satisfied"
241
+ elif attention and not (pr and attention[0]["type"] in {"publication_failed", "unmerged_pr_closed", "review_attention"}):
242
+ column, reason_code, reason_summary = "waiting", attention[0]["type"], attention[0]["summary"] or "Operator input is required"
243
+ elif running or publication_in_progress:
244
+ column, reason_code, reason_summary = "doing", "running", "Agent execution or publication is in progress"
245
+ elif pr and attention and attention[0]["type"] in {"publication_failed", "unmerged_pr_closed", "review_attention"}:
246
+ column, reason_code, reason_summary = "review", attention[0]["type"], attention[0]["summary"] or "Pull request review needs attention"
247
+ elif task and task["lifecycle"] in {"detected", "authorized", "classified", "queued", "running"}:
248
+ column, reason_code, reason_summary = "todo", task["lifecycle"], "Runnable work is queued"
249
+ elif pr and (pr["state"] or "open").lower() == "open":
250
+ column, reason_code, reason_summary = "review", "open_pr", f"PR #{pr['number']} is open"
251
+ elif not row["activated_at"]:
252
+ column, reason_code, reason_summary = "backlog", "draft", "Requirement is editable"
253
+ else:
254
+ column, reason_code, reason_summary = "todo", "activated", "Activated work is pending"
255
+
256
+ routing_mode = task["routing_mode"] if task else row["routing_mode"]
257
+ requested_worker = task["requested_worker"] if task else row["requested_worker"]
258
+ card = {
259
+ "work_item_id": work_item_id,
260
+ "repo_id": row["repo_id"],
261
+ "repo_full_name": row["repo_full_name"],
262
+ "title": row["title"],
263
+ "priority": row["priority"],
264
+ "origin_type": row["origin_type"],
265
+ "column": column,
266
+ "reason_code": reason_code,
267
+ "reason_summary": reason_summary,
268
+ "routing_mode": routing_mode,
269
+ "agent": requested_worker if routing_mode == "manual" else "Auto",
270
+ "task_id": task["task_id"] if task else None,
271
+ "task_lifecycle": task["lifecycle"] if task else None,
272
+ "branch": attempt["branch_name"] if attempt else None,
273
+ "worktree_label": Path(attempt["worktree_path"]).name if attempt and attempt["worktree_path"] else None,
274
+ "pr": (
275
+ {
276
+ "number": pr["number"],
277
+ "url": _safe_http_url(pr["html_url"]),
278
+ "state": pr["state"],
279
+ }
280
+ if pr
281
+ else None
282
+ ),
283
+ "attention_signals": attention,
284
+ "version": row["version"],
285
+ "created_at": row["created_at"],
286
+ "updated_at": row["updated_at"],
287
+ }
288
+ card["valid_commands"] = _valid_commands(row, column, attention, running=running)
289
+ return card
290
+
291
+
292
+ def _all_projections(conn):
293
+ rows = conn.execute(
294
+ """
295
+ SELECT wi.*, r.full_name AS repo_full_name
296
+ FROM work_items wi
297
+ JOIN repos r ON r.repo_id = wi.repo_id
298
+ ORDER BY wi.updated_at DESC, wi.work_item_id DESC
299
+ """
300
+ ).fetchall()
301
+ return [_project_item(conn, row) for row in rows]
302
+
303
+
304
+ def _matches(item, *, repo, agent, priority, attention, query):
305
+ if repo and repo not in {item["repo_id"], item["repo_full_name"]}:
306
+ return False
307
+ if agent and item["agent"] != agent:
308
+ return False
309
+ if priority and item["priority"] != priority:
310
+ return False
311
+ if attention is not None:
312
+ wanted = attention in {True, "true", "1", "yes"}
313
+ if bool(item["attention_signals"]) != wanted:
314
+ return False
315
+ if query:
316
+ haystack = " ".join(
317
+ str(value or "")
318
+ for value in (
319
+ item["title"], item["work_item_id"], item["task_id"], item["branch"],
320
+ (item["pr"] or {}).get("number"),
321
+ )
322
+ ).lower()
323
+ if query.lower() not in haystack:
324
+ return False
325
+ return True
326
+
327
+
328
+ def list_board(
329
+ db_path,
330
+ *,
331
+ repo=None,
332
+ column=None,
333
+ agent=None,
334
+ priority=None,
335
+ attention=None,
336
+ query="",
337
+ limit=50,
338
+ cursor=None,
339
+ include_history=False,
340
+ ):
341
+ if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 200:
342
+ raise BoardQueryError("limit must be between 1 and 200")
343
+ valid_columns = {column_id for column_id, _label in COLUMNS} | {"history"}
344
+ if column and column not in valid_columns:
345
+ raise BoardQueryError("invalid column")
346
+ if priority and priority not in {"P0", "P1", "P2", "P3"}:
347
+ raise BoardQueryError("invalid priority")
348
+ cursor_value = _cursor_decode(cursor)
349
+ with closing(_connect(db_path)) as conn:
350
+ projections = [
351
+ item
352
+ for item in _all_projections(conn)
353
+ if _matches(
354
+ item,
355
+ repo=repo,
356
+ agent=agent,
357
+ priority=priority,
358
+ attention=attention,
359
+ query=query,
360
+ )
361
+ and (include_history or item["column"] != "history")
362
+ ]
363
+ counts = {
364
+ column_id: sum(1 for item in projections if item["column"] == column_id)
365
+ for column_id, _label in COLUMNS
366
+ }
367
+ if cursor_value:
368
+ projections = [
369
+ item
370
+ for item in projections
371
+ if (item["updated_at"], item["work_item_id"]) < cursor_value
372
+ ]
373
+ if column:
374
+ projections = [item for item in projections if item["column"] == column]
375
+ page = projections[: limit + 1]
376
+ has_more = len(page) > limit
377
+ items = page[:limit]
378
+ next_cursor = (
379
+ _cursor_encode([items[-1]["updated_at"], items[-1]["work_item_id"]])
380
+ if has_more and items
381
+ else None
382
+ )
383
+ running_rows = conn.execute(
384
+ """
385
+ SELECT w.repo_id, COUNT(*)
386
+ FROM attempts a
387
+ JOIN tasks t ON t.task_id = a.task_id
388
+ JOIN workstreams w ON w.workstream_id = t.workstream_id
389
+ WHERE a.status = 'running'
390
+ GROUP BY w.repo_id
391
+ """
392
+ ).fetchall()
393
+ per_repo_running = {row[0]: row[1] for row in running_rows}
394
+ repos = [
395
+ {"repo_id": row[0], "full_name": row[1], "running": per_repo_running.get(row[0], 0)}
396
+ for row in conn.execute("SELECT repo_id, full_name FROM repos ORDER BY full_name")
397
+ ]
398
+ agents = sorted({item["agent"] for item in projections} | {"Auto"})
399
+ return {
400
+ "columns": [
401
+ {"id": column_id, "label": label, "count": counts[column_id]}
402
+ for column_id, label in COLUMNS
403
+ ],
404
+ "counts": counts,
405
+ "capacity": {
406
+ "running": sum(per_repo_running.values()),
407
+ "by_repo": per_repo_running,
408
+ },
409
+ "filters": {
410
+ "repos": repos,
411
+ "agents": agents,
412
+ "priorities": ["P0", "P1", "P2", "P3"],
413
+ },
414
+ "items": items,
415
+ "next_cursor": next_cursor,
416
+ }
417
+
418
+
419
+ def get_work_item_detail(db_path, work_item_id):
420
+ with closing(_connect(db_path)) as conn:
421
+ row = conn.execute(
422
+ """
423
+ SELECT wi.*, r.full_name AS repo_full_name
424
+ FROM work_items wi JOIN repos r ON r.repo_id = wi.repo_id
425
+ WHERE wi.work_item_id = ?
426
+ """,
427
+ (work_item_id,),
428
+ ).fetchone()
429
+ if not row:
430
+ return None
431
+ card = _project_item(conn, row)
432
+ tasks = []
433
+ if row["workstream_id"]:
434
+ task_rows = conn.execute(
435
+ """
436
+ SELECT task_id, parent_task_id, lifecycle, priority, route_id,
437
+ expected_output, routing_mode, requested_worker, created_at, updated_at
438
+ FROM tasks WHERE workstream_id = ?
439
+ ORDER BY created_at, task_id
440
+ """,
441
+ (row["workstream_id"],),
442
+ ).fetchall()
443
+ for task in task_rows:
444
+ attempts = [
445
+ {
446
+ "attempt_id": attempt["attempt_id"],
447
+ "status": attempt["status"],
448
+ "branch": attempt["branch_name"],
449
+ "worktree_label": Path(attempt["worktree_path"]).name if attempt["worktree_path"] else None,
450
+ "started_at": attempt["started_at"],
451
+ "finished_at": attempt["finished_at"],
452
+ }
453
+ for attempt in conn.execute(
454
+ """
455
+ SELECT attempt_id, status, branch_name, worktree_path,
456
+ started_at, finished_at
457
+ FROM attempts WHERE task_id = ? ORDER BY attempt_no
458
+ """,
459
+ (task["task_id"],),
460
+ )
461
+ ]
462
+ tasks.append(
463
+ {
464
+ "task_id": task["task_id"],
465
+ "parent_task_id": task["parent_task_id"],
466
+ "lifecycle": task["lifecycle"],
467
+ "priority": task["priority"],
468
+ "route_id": task["route_id"],
469
+ "expected_output": task["expected_output"],
470
+ "routing_mode": task["routing_mode"],
471
+ "requested_worker": task["requested_worker"],
472
+ "created_at": task["created_at"],
473
+ "updated_at": task["updated_at"],
474
+ "attempts": attempts,
475
+ }
476
+ )
477
+ timeline = list_work_item_events(db_path, work_item_id, limit=20)
478
+ return {
479
+ **card,
480
+ "description": row["description"],
481
+ "created_by": row["created_by"],
482
+ "activated_at": row["activated_at"],
483
+ "completed_at": row["completed_at"],
484
+ "canceled_at": row["canceled_at"],
485
+ "tasks": tasks,
486
+ "events": timeline["events"],
487
+ "events_next_cursor": timeline["next_cursor"],
488
+ }
489
+
490
+
491
+ def list_work_item_events(db_path, work_item_id, *, limit=50, cursor=None):
492
+ if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 200:
493
+ raise BoardQueryError("limit must be between 1 and 200")
494
+ cursor_value = _cursor_decode(cursor)
495
+ with closing(_connect(db_path)) as conn:
496
+ exists = conn.execute(
497
+ "SELECT 1 FROM work_items WHERE work_item_id = ?",
498
+ (work_item_id,),
499
+ ).fetchone()
500
+ if not exists:
501
+ return {"events": [], "next_cursor": None}
502
+ params = [work_item_id]
503
+ cursor_clause = ""
504
+ if cursor_value:
505
+ cursor_clause = "AND (created_at, event_id) < (?, ?)"
506
+ params.extend(cursor_value)
507
+ rows = conn.execute(
508
+ f"""
509
+ SELECT event_id, event_type, actor_kind, actor_identity, body,
510
+ resolves_event_id, idempotency_key, created_at, metadata_json
511
+ FROM work_item_events
512
+ WHERE work_item_id = ? {cursor_clause}
513
+ ORDER BY created_at DESC, event_id DESC
514
+ LIMIT ?
515
+ """,
516
+ params + [limit + 1],
517
+ ).fetchall()
518
+ has_more = len(rows) > limit
519
+ rows = rows[:limit]
520
+ events = [
521
+ {
522
+ "event_id": row["event_id"],
523
+ "event_type": row["event_type"],
524
+ "actor_kind": row["actor_kind"],
525
+ "actor_identity": row["actor_identity"],
526
+ "body": row["body"],
527
+ "resolves_event_id": row["resolves_event_id"],
528
+ "created_at": row["created_at"],
529
+ "metadata": _safe_event_metadata(row["metadata_json"]),
530
+ }
531
+ for row in rows
532
+ ]
533
+ next_cursor = (
534
+ _cursor_encode([rows[-1]["created_at"], rows[-1]["event_id"]])
535
+ if has_more and rows
536
+ else None
537
+ )
538
+ return {"events": events, "next_cursor": next_cursor}