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
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import re
4
+ import subprocess
5
+ import time
6
+ from pathlib import Path
7
+
8
+ from robert_agent.common import emit
9
+ from robert_agent.worker import snapshot
10
+
11
+ DEFAULT_TAIL_BYTES = 8192
12
+ DEFAULT_TAIL_LINES = 80
13
+ MIN_HEARTBEAT_INTERVAL_SECONDS = 0.1
14
+
15
+
16
+ def build_command_record(task_id, attempt_id, phase, command):
17
+ return {
18
+ "task_id": task_id,
19
+ "attempt_id": attempt_id,
20
+ "phase": phase,
21
+ "active_command": list(command),
22
+ }
23
+
24
+
25
+ def _safe_filename_part(value):
26
+ value = re.sub(r"[^A-Za-z0-9_.-]+", "_", str(value or "").strip())
27
+ return value.strip("._") or "command"
28
+
29
+
30
+ def _default_output_dir(db_path, task_id):
31
+ return Path(db_path).expanduser().parent / "artifacts" / task_id
32
+
33
+
34
+ def _tail_file(path, max_bytes=DEFAULT_TAIL_BYTES, max_lines=DEFAULT_TAIL_LINES):
35
+ path = Path(path)
36
+ try:
37
+ size = path.stat().st_size
38
+ with path.open("rb") as handle:
39
+ handle.seek(max(0, size - max_bytes))
40
+ data = handle.read()
41
+ except OSError:
42
+ return {
43
+ "path": str(path),
44
+ "bytes": 0,
45
+ "tail": "",
46
+ "truncated": False,
47
+ }
48
+ text = data.decode("utf-8", errors="replace")
49
+ lines = text.splitlines()
50
+ line_truncated = len(lines) > max_lines
51
+ if line_truncated:
52
+ text = "\n".join(lines[-max_lines:])
53
+ return {
54
+ "path": str(path),
55
+ "bytes": size,
56
+ "tail": text,
57
+ "truncated": size > max_bytes or line_truncated,
58
+ }
59
+
60
+
61
+ def run_command_with_heartbeat(
62
+ db_path,
63
+ task_id,
64
+ attempt_id,
65
+ phase,
66
+ command,
67
+ timeout_seconds=5400,
68
+ heartbeat_interval_seconds=60,
69
+ output_dir=None,
70
+ tail_bytes=DEFAULT_TAIL_BYTES,
71
+ tail_lines=DEFAULT_TAIL_LINES,
72
+ ):
73
+ snapshot.record_snapshot(
74
+ db_path=db_path,
75
+ task_id=task_id,
76
+ attempt_id=attempt_id,
77
+ phase=phase,
78
+ status="running",
79
+ summary="Starting command",
80
+ next_step="Wait for command completion",
81
+ )
82
+ output_dir = Path(output_dir).expanduser() if output_dir else _default_output_dir(db_path, task_id)
83
+ output_dir.mkdir(parents=True, exist_ok=True)
84
+ output_prefix = f"{_safe_filename_part(attempt_id)}.{_safe_filename_part(phase)}.{time.time_ns()}"
85
+ stdout_path = output_dir / f"{output_prefix}.stdout.log"
86
+ stderr_path = output_dir / f"{output_prefix}.stderr.log"
87
+ started = time.monotonic()
88
+ timed_out = False
89
+ heartbeat_interval_seconds = max(
90
+ float(heartbeat_interval_seconds),
91
+ MIN_HEARTBEAT_INTERVAL_SECONDS,
92
+ )
93
+ with stdout_path.open("wb") as stdout_file, stderr_path.open("wb") as stderr_file:
94
+ proc = subprocess.Popen(
95
+ command,
96
+ stdout=stdout_file,
97
+ stderr=stderr_file,
98
+ )
99
+ while True:
100
+ if proc.poll() is not None:
101
+ break
102
+ elapsed = time.monotonic() - started
103
+ remaining = timeout_seconds - elapsed
104
+ if remaining <= 0:
105
+ timed_out = True
106
+ proc.kill()
107
+ proc.wait()
108
+ break
109
+ time.sleep(min(heartbeat_interval_seconds, remaining))
110
+ if proc.poll() is None:
111
+ snapshot.record_snapshot(
112
+ db_path=db_path,
113
+ task_id=task_id,
114
+ attempt_id=attempt_id,
115
+ phase=phase,
116
+ status="running",
117
+ summary="Command still running",
118
+ next_step="Wait for command completion",
119
+ )
120
+ stdout_info = _tail_file(stdout_path, max_bytes=tail_bytes, max_lines=tail_lines)
121
+ stderr_info = _tail_file(stderr_path, max_bytes=tail_bytes, max_lines=tail_lines)
122
+ returncode = None if timed_out else proc.returncode
123
+ if timed_out:
124
+ status = "failed"
125
+ summary = f"Command timed out after {timeout_seconds} seconds"
126
+ else:
127
+ status = "completed" if returncode == 0 else "failed"
128
+ summary = f"Command exited {returncode}"
129
+ snapshot.record_snapshot(
130
+ db_path=db_path,
131
+ task_id=task_id,
132
+ attempt_id=attempt_id,
133
+ phase=phase,
134
+ status=status,
135
+ summary=summary,
136
+ next_step="Inspect saved command output and record result",
137
+ )
138
+ return {
139
+ "ok": returncode == 0,
140
+ "status": status,
141
+ "returncode": returncode,
142
+ "stdout_path": stdout_info["path"],
143
+ "stderr_path": stderr_info["path"],
144
+ "stdout_bytes": stdout_info["bytes"],
145
+ "stderr_bytes": stderr_info["bytes"],
146
+ "stdout_tail": stdout_info["tail"],
147
+ "stderr_tail": stderr_info["tail"],
148
+ "stdout_truncated": stdout_info["truncated"],
149
+ "stderr_truncated": stderr_info["truncated"],
150
+ }
151
+
152
+
153
+ def main(argv=None):
154
+ parser = argparse.ArgumentParser()
155
+ parser.add_argument("--db")
156
+ parser.add_argument("--task-id", required=True)
157
+ parser.add_argument("--attempt-id", required=True)
158
+ parser.add_argument("--phase", required=True)
159
+ parser.add_argument("--timeout-seconds", type=int, default=5400)
160
+ parser.add_argument("--heartbeat-interval-seconds", type=float, default=60)
161
+ parser.add_argument("--output-dir")
162
+ parser.add_argument("--tail-bytes", type=int, default=DEFAULT_TAIL_BYTES)
163
+ parser.add_argument("--tail-lines", type=int, default=DEFAULT_TAIL_LINES)
164
+ parser.add_argument("command", nargs=argparse.REMAINDER)
165
+ args = parser.parse_args(argv)
166
+ command = args.command[1:] if args.command[:1] == ["--"] else args.command
167
+ if args.db:
168
+ result = run_command_with_heartbeat(
169
+ db_path=args.db,
170
+ task_id=args.task_id,
171
+ attempt_id=args.attempt_id,
172
+ phase=args.phase,
173
+ command=command,
174
+ timeout_seconds=args.timeout_seconds,
175
+ heartbeat_interval_seconds=args.heartbeat_interval_seconds,
176
+ output_dir=args.output_dir,
177
+ tail_bytes=args.tail_bytes,
178
+ tail_lines=args.tail_lines,
179
+ )
180
+ else:
181
+ result = {
182
+ "ok": True,
183
+ "status": "built",
184
+ "command": build_command_record(args.task_id, args.attempt_id, args.phase, command),
185
+ }
186
+ return emit(result)
187
+
188
+
189
+ if __name__ == "__main__":
190
+ raise SystemExit(main())
@@ -0,0 +1,321 @@
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ from contextlib import closing
4
+ import json
5
+ import sqlite3
6
+ import sys
7
+ from datetime import datetime, timedelta, timezone
8
+ from uuid import uuid4
9
+
10
+ from robert_agent.common import emit
11
+
12
+
13
+ def _insert_worker_result_wakeup(conn, payload, result_id, created_at):
14
+ repo = conn.execute(
15
+ """
16
+ SELECT w.repo_id, wi.work_item_id
17
+ FROM tasks t
18
+ JOIN workstreams w ON w.workstream_id = t.workstream_id
19
+ LEFT JOIN work_items wi ON wi.workstream_id = t.workstream_id
20
+ WHERE t.task_id = ?
21
+ """,
22
+ (payload["task_id"],),
23
+ ).fetchone()
24
+ if not repo:
25
+ return None
26
+ wakeup_id = f"wakeup-{uuid4().hex[:12]}"
27
+ metadata = {
28
+ "recorded_by": "robert.worker",
29
+ "output_type": payload.get("output_type"),
30
+ }
31
+ conn.execute(
32
+ """
33
+ INSERT OR IGNORE INTO wakeups(
34
+ wakeup_id, repo_id, reason, dedupe_key, work_item_id, task_id, attempt_id,
35
+ result_id, status, not_before_at, created_at, updated_at, metadata_json
36
+ )
37
+ VALUES (?, ?, 'worker_result_ready', ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)
38
+ """,
39
+ (
40
+ wakeup_id,
41
+ repo[0],
42
+ result_id,
43
+ repo[1],
44
+ payload["task_id"],
45
+ payload["attempt_id"],
46
+ result_id,
47
+ created_at,
48
+ created_at,
49
+ created_at,
50
+ json.dumps(metadata, sort_keys=True),
51
+ ),
52
+ )
53
+ return wakeup_id
54
+
55
+
56
+ def _validate_actions(actions):
57
+ if not isinstance(actions, list):
58
+ return None, "planned_github_actions must be a list"
59
+ for action in actions:
60
+ if not isinstance(action, dict):
61
+ return None, "planned_github_actions entries must be objects"
62
+ action_type = action.get("type")
63
+ if not isinstance(action_type, str) or not action_type:
64
+ return None, "planned_github_actions[*].type must be a non-empty string"
65
+ return actions, None
66
+
67
+
68
+ def _validate_used_skills(used_skills):
69
+ if not isinstance(used_skills, list):
70
+ return None, "used_skills must be a list"
71
+ for skill in used_skills:
72
+ if not isinstance(skill, str) or not skill:
73
+ return None, "used_skills entries must be non-empty strings"
74
+ return used_skills, None
75
+
76
+
77
+ def _validate_verification(verification):
78
+ if verification is None:
79
+ return [], None
80
+ if not isinstance(verification, list):
81
+ return None, "verification must be a list"
82
+ for entry in verification:
83
+ if not isinstance(entry, dict):
84
+ return None, "verification entries must be objects"
85
+ return verification, None
86
+
87
+
88
+ def _validate_operator_question(question):
89
+ if question is None:
90
+ return None, None
91
+ if not isinstance(question, dict):
92
+ return None, "operator_question must be an object"
93
+ if question.get("kind") not in {
94
+ "clarification",
95
+ "scope_decision",
96
+ "completion_acceptance",
97
+ }:
98
+ return None, "operator_question.kind is invalid"
99
+ summary = question.get("summary")
100
+ if not isinstance(summary, str) or not summary.strip() or len(summary) > 2000:
101
+ return None, "operator_question.summary is invalid"
102
+ choices = question.get("choices", [])
103
+ if not isinstance(choices, list) or len(choices) > 5:
104
+ return None, "operator_question.choices is invalid"
105
+ for choice in choices:
106
+ if not isinstance(choice, dict):
107
+ return None, "operator_question choices must be objects"
108
+ if not isinstance(choice.get("id"), str) or not choice["id"]:
109
+ return None, "operator_question choice id is required"
110
+ if not isinstance(choice.get("label"), str) or not choice["label"]:
111
+ return None, "operator_question choice label is required"
112
+ return question, None
113
+
114
+
115
+ def _optional_string_list(value):
116
+ if not isinstance(value, list):
117
+ return []
118
+ return [item for item in value if isinstance(item, str) and item]
119
+
120
+
121
+ def build_result(
122
+ task_id,
123
+ attempt_id,
124
+ output_type,
125
+ consumed_event_fingerprints,
126
+ verification,
127
+ handoff,
128
+ planned_github_actions=None,
129
+ used_skills=None,
130
+ memory_delta=None,
131
+ used_memory_ids=None,
132
+ recommended_route=None,
133
+ branch_slug=None,
134
+ review_point_evaluation=None,
135
+ consumed_work_item_event_ids=None,
136
+ operator_question=None,
137
+ ):
138
+ payload = {
139
+ "task_id": task_id,
140
+ "attempt_id": attempt_id,
141
+ "output_type": output_type,
142
+ "planned_github_actions": list(planned_github_actions or []),
143
+ "consumed_event_fingerprints": list(consumed_event_fingerprints),
144
+ "consumed_work_item_event_ids": list(consumed_work_item_event_ids or []),
145
+ "verification": list(verification or []),
146
+ "handoff": handoff,
147
+ "used_skills": list(used_skills or []),
148
+ }
149
+ if memory_delta is not None:
150
+ payload["memory_delta"] = memory_delta
151
+ if used_memory_ids is not None:
152
+ payload["used_memory_ids"] = list(used_memory_ids)
153
+ if recommended_route is not None:
154
+ payload["recommended_route"] = recommended_route
155
+ if branch_slug is not None:
156
+ payload["branch_slug"] = branch_slug
157
+ if review_point_evaluation is not None:
158
+ if not isinstance(review_point_evaluation, list):
159
+ raise ValueError("review_point_evaluation must be a list")
160
+ payload["review_point_evaluation"] = list(review_point_evaluation)
161
+ if operator_question is not None:
162
+ payload["operator_question"] = operator_question
163
+ return payload
164
+
165
+
166
+ def record_result(db_path, payload):
167
+ if "planned_github_actions" not in payload:
168
+ return {
169
+ "ok": False,
170
+ "status": "failed_validation",
171
+ "safe_error": "planned_github_actions is required; actual_github_actions is legacy",
172
+ }
173
+ action_payload = payload.get("planned_github_actions")
174
+ actions, action_error = _validate_actions(action_payload)
175
+ if action_error:
176
+ return {"ok": False, "status": "failed_validation", "safe_error": action_error}
177
+ used_skills, skill_error = _validate_used_skills(payload.get("used_skills"))
178
+ if skill_error:
179
+ return {"ok": False, "status": "failed_validation", "safe_error": skill_error}
180
+ verification, verification_error = _validate_verification(payload.get("verification", []))
181
+ if verification_error:
182
+ return {"ok": False, "status": "failed_validation", "safe_error": verification_error}
183
+ local_event_ids = payload.get("consumed_work_item_event_ids", [])
184
+ if not isinstance(local_event_ids, list) or not all(
185
+ isinstance(event_id, str) and event_id for event_id in local_event_ids
186
+ ):
187
+ return {
188
+ "ok": False,
189
+ "status": "failed_validation",
190
+ "safe_error": "consumed_work_item_event_ids must be a string list",
191
+ }
192
+ operator_question, question_error = _validate_operator_question(
193
+ payload.get("operator_question")
194
+ )
195
+ if question_error:
196
+ return {"ok": False, "status": "failed_validation", "safe_error": question_error}
197
+ metadata = {
198
+ "recorded_by": "robert.worker",
199
+ "used_skills": used_skills,
200
+ "memory_delta": payload.get(
201
+ "memory_delta",
202
+ {
203
+ "status": "none",
204
+ "reason": "worker did not provide reusable project memory",
205
+ },
206
+ ),
207
+ "used_memory_ids": _optional_string_list(payload.get("used_memory_ids")),
208
+ "review_point_evaluation": payload.get("review_point_evaluation", []),
209
+ "consumed_work_item_event_ids": local_event_ids,
210
+ }
211
+ if operator_question is not None:
212
+ metadata["operator_question"] = operator_question
213
+ recommended_route = payload.get("recommended_route")
214
+ if isinstance(recommended_route, str) and recommended_route:
215
+ metadata["recommended_route"] = recommended_route
216
+ branch_slug = payload.get("branch_slug")
217
+ if isinstance(branch_slug, str) and branch_slug:
218
+ metadata["branch_slug"] = branch_slug
219
+
220
+ created_at = datetime.now(timezone.utc)
221
+ result_created_at = created_at.isoformat()
222
+ result_id = f"result-{uuid4().hex[:12]}"
223
+ with closing(sqlite3.connect(db_path)) as conn, conn:
224
+ conn.execute("PRAGMA foreign_keys = ON")
225
+ conn.execute("PRAGMA busy_timeout = 5000")
226
+ conn.execute(
227
+ """
228
+ INSERT INTO worker_results(
229
+ result_id, task_id, attempt_id, output_type,
230
+ consumed_event_fingerprints_json, verification_json, handoff, created_at,
231
+ metadata_json
232
+ )
233
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
234
+ """,
235
+ (
236
+ result_id,
237
+ payload["task_id"],
238
+ payload["attempt_id"],
239
+ payload["output_type"],
240
+ json.dumps(payload["consumed_event_fingerprints"], sort_keys=True),
241
+ json.dumps(verification, sort_keys=True),
242
+ payload.get("handoff", ""),
243
+ result_created_at,
244
+ json.dumps(
245
+ metadata,
246
+ sort_keys=True,
247
+ ),
248
+ ),
249
+ )
250
+ for index, action in enumerate(actions):
251
+ action_created_at = (created_at + timedelta(microseconds=index)).isoformat()
252
+ conn.execute(
253
+ """
254
+ INSERT INTO github_actions(
255
+ action_id, result_id, task_id, action_type, target_url, external_id,
256
+ audit_status, publish_status, created_at, metadata_json
257
+ )
258
+ VALUES (?, ?, ?, ?, ?, ?, 'pending', 'not_published', ?, ?)
259
+ """,
260
+ (
261
+ f"action-{uuid4().hex[:12]}",
262
+ result_id,
263
+ payload["task_id"],
264
+ action["type"],
265
+ action.get("target_url") or action.get("url"),
266
+ action.get("id"),
267
+ action_created_at,
268
+ json.dumps(action, sort_keys=True),
269
+ ),
270
+ )
271
+ cur = conn.execute(
272
+ """
273
+ UPDATE attempts
274
+ SET status = 'completed', finished_at = ?
275
+ WHERE attempt_id = ?
276
+ AND status IN ('running', 'prepared', 'stale')
277
+ """,
278
+ (result_created_at, payload["attempt_id"]),
279
+ )
280
+ if cur.rowcount == 0:
281
+ conn.rollback()
282
+ return {"ok": False, "status": "rejected_by_supervisor", "result_id": result_id}
283
+ _insert_worker_result_wakeup(conn, payload, result_id, result_created_at)
284
+ return {"ok": True, "status": "recorded", "result_id": result_id}
285
+
286
+
287
+ def main(argv=None):
288
+ parser = argparse.ArgumentParser()
289
+ parser.add_argument("--db")
290
+ parser.add_argument("--task-id", required=True)
291
+ parser.add_argument("--attempt-id", required=True)
292
+ parser.add_argument("--output-type", required=True)
293
+ parser.add_argument("--handoff", default="")
294
+ args = parser.parse_args(argv)
295
+ payload = json.load(sys.stdin)
296
+ result = build_result(
297
+ task_id=args.task_id,
298
+ attempt_id=args.attempt_id,
299
+ output_type=args.output_type,
300
+ planned_github_actions=payload.get("planned_github_actions", []),
301
+ consumed_event_fingerprints=payload.get("consumed_event_fingerprints", []),
302
+ verification=payload.get("verification", []),
303
+ handoff=args.handoff or payload.get("handoff", ""),
304
+ used_skills=payload.get("used_skills", []),
305
+ memory_delta=payload.get("memory_delta"),
306
+ used_memory_ids=payload.get("used_memory_ids"),
307
+ recommended_route=payload.get("recommended_route"),
308
+ branch_slug=payload.get("branch_slug"),
309
+ review_point_evaluation=payload.get("review_point_evaluation"),
310
+ consumed_work_item_event_ids=payload.get("consumed_work_item_event_ids", []),
311
+ operator_question=payload.get("operator_question"),
312
+ )
313
+ if args.db:
314
+ output = record_result(args.db, result)
315
+ else:
316
+ output = {"ok": True, "status": "built", "result": result}
317
+ return emit(output)
318
+
319
+
320
+ if __name__ == "__main__":
321
+ raise SystemExit(main())
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ from contextlib import closing
4
+ import sqlite3
5
+ from datetime import datetime, timezone
6
+ from uuid import uuid4
7
+
8
+ from robert_agent.common import emit
9
+
10
+
11
+ VALID_PHASES = {"prepare", "analyze", "plan", "execute", "verify", "publish", "handoff"}
12
+
13
+
14
+ def build_snapshot(task_id, attempt_id, phase, status, summary, next_step=""):
15
+ if phase not in VALID_PHASES:
16
+ raise ValueError(f"invalid worker phase: {phase}")
17
+ return {
18
+ "task_id": task_id,
19
+ "attempt_id": attempt_id,
20
+ "phase": phase,
21
+ "status": status,
22
+ "summary": summary,
23
+ "next_step": next_step,
24
+ }
25
+
26
+
27
+ def record_snapshot(db_path, task_id, attempt_id, phase, status, summary, next_step=""):
28
+ row = build_snapshot(task_id, attempt_id, phase, status, summary, next_step)
29
+ created_at = datetime.now(timezone.utc).isoformat()
30
+ with closing(sqlite3.connect(db_path)) as conn, conn:
31
+ conn.execute("PRAGMA foreign_keys = ON")
32
+ conn.execute("PRAGMA busy_timeout = 5000")
33
+ conn.execute(
34
+ """
35
+ INSERT INTO worker_phases(
36
+ phase_id, attempt_id, phase, status, summary, next_step, created_at
37
+ )
38
+ VALUES (?, ?, ?, ?, ?, ?, ?)
39
+ """,
40
+ (
41
+ f"phase-{uuid4().hex[:12]}",
42
+ attempt_id,
43
+ phase,
44
+ status,
45
+ summary,
46
+ next_step,
47
+ created_at,
48
+ ),
49
+ )
50
+ updated = conn.execute(
51
+ "UPDATE attempts SET heartbeat_at = ? WHERE attempt_id = ?",
52
+ (created_at, attempt_id),
53
+ ).rowcount
54
+ if updated != 1:
55
+ raise ValueError("attempt_id does not exist")
56
+ matched = conn.execute(
57
+ "SELECT 1 FROM attempts WHERE attempt_id = ? AND task_id = ?",
58
+ (attempt_id, task_id),
59
+ ).fetchone()
60
+ if not matched:
61
+ raise ValueError("attempt_id does not belong to task_id")
62
+ return {"ok": True, "status": "recorded", "snapshot": row}
63
+
64
+
65
+ def main(argv=None):
66
+ parser = argparse.ArgumentParser()
67
+ parser.add_argument("--db")
68
+ parser.add_argument("--task-id", required=True)
69
+ parser.add_argument("--attempt-id", required=True)
70
+ parser.add_argument("--phase", required=True)
71
+ parser.add_argument("--status", required=True)
72
+ parser.add_argument("--summary", required=True)
73
+ parser.add_argument("--next-step", default="")
74
+ args = parser.parse_args(argv)
75
+ if args.db:
76
+ result = record_snapshot(
77
+ db_path=args.db,
78
+ task_id=args.task_id,
79
+ attempt_id=args.attempt_id,
80
+ phase=args.phase,
81
+ status=args.status,
82
+ summary=args.summary,
83
+ next_step=args.next_step,
84
+ )
85
+ else:
86
+ result = {"ok": True, "status": "built", "snapshot": build_snapshot(
87
+ task_id=args.task_id,
88
+ attempt_id=args.attempt_id,
89
+ phase=args.phase,
90
+ status=args.status,
91
+ summary=args.summary,
92
+ next_step=args.next_step,
93
+ )}
94
+ return emit(result)
95
+
96
+
97
+ if __name__ == "__main__":
98
+ raise SystemExit(main())