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,285 @@
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ from contextlib import closing
4
+ import json
5
+ from pathlib import Path
6
+ import sqlite3
7
+ import time
8
+
9
+ from robert_agent.common import emit
10
+ from robert_agent import storage, wakeup
11
+ from robert_agent import run_once as run_once_module
12
+ from robert_agent import validate_config
13
+
14
+
15
+ def _connect(db_path):
16
+ conn = sqlite3.connect(db_path)
17
+ conn.execute("PRAGMA foreign_keys = ON")
18
+ conn.execute("PRAGMA busy_timeout = 5000")
19
+ return conn
20
+
21
+
22
+ def load_config_db_path(config_path, skip_external=False):
23
+ db_path, _repo_ids = load_config_scope(config_path, skip_external=skip_external)
24
+ return db_path
25
+
26
+
27
+ def load_config_scope(config_path, skip_external=False):
28
+ config = validate_config.validate_config(config_path, skip_external=skip_external)
29
+ if not config.get("ok"):
30
+ raise ValueError(config.get("safe_error", "invalid config"))
31
+ db_path = Path(config["db_path"])
32
+ storage.init_database(db_path)
33
+ with closing(_connect(db_path)) as conn:
34
+ repo_ids = []
35
+ for repo in config["repos"]:
36
+ full_name = repo["full_name"]
37
+ row = conn.execute(
38
+ "SELECT repo_id FROM repos WHERE full_name = ?",
39
+ (full_name,),
40
+ ).fetchone()
41
+ repo_ids.append(row[0] if row else f"repo:{full_name}")
42
+ return db_path, repo_ids
43
+
44
+
45
+ def _count(conn, table, where="1 = 1", params=()):
46
+ return conn.execute(
47
+ f"SELECT COUNT(*) FROM {table} WHERE {where}",
48
+ params,
49
+ ).fetchone()[0]
50
+
51
+
52
+ def snapshot_progress(conn):
53
+ return {
54
+ "pending_wakeups": _count(conn, "wakeups", "status = 'pending'"),
55
+ "consumed_wakeups": _count(conn, "wakeups", "status = 'consumed'"),
56
+ "expired_wakeups": _count(conn, "wakeups", "status = 'expired'"),
57
+ "prepared_attempts": _count(conn, "attempts", "status = 'prepared'"),
58
+ "running_attempts": _count(conn, "attempts", "status = 'running'"),
59
+ "stale_attempts": _count(conn, "attempts", "status = 'stale'"),
60
+ "completed_attempts": _count(conn, "attempts", "status = 'completed'"),
61
+ "failed_attempts": _count(conn, "attempts", "status = 'failed'"),
62
+ "pending_actions": _count(conn, "github_actions", "audit_status = 'pending'"),
63
+ "accepted_unpublished_actions": _count(
64
+ conn,
65
+ "github_actions",
66
+ "audit_status = 'accepted' AND publish_status = 'not_published'",
67
+ ),
68
+ "published_actions": _count(conn, "github_actions", "publish_status = 'published'"),
69
+ "running_tasks": _count(conn, "tasks", "lifecycle IN ('queued', 'running')"),
70
+ "completed_tasks": _count(conn, "tasks", "lifecycle = 'completed'"),
71
+ "failed_tasks": _count(conn, "tasks", "lifecycle = 'failed'"),
72
+ "active_workstreams": _count(conn, "workstreams", "lifecycle = 'active'"),
73
+ "waiting_workstreams": _count(conn, "workstreams", "lifecycle = 'waiting_for_user'"),
74
+ "completed_workstreams": _count(conn, "workstreams", "lifecycle = 'completed'"),
75
+ }
76
+
77
+
78
+ def diff_progress(before, after):
79
+ changed = {
80
+ key: {"before": before.get(key), "after": after.get(key)}
81
+ for key in sorted(set(before) | set(after))
82
+ if before.get(key) != after.get(key)
83
+ }
84
+ return {"changed": bool(changed), "changed_fields": changed}
85
+
86
+
87
+ def _repo_filter(alias, repo_ids):
88
+ if not repo_ids:
89
+ return "", []
90
+ placeholders = ",".join("?" for _repo_id in repo_ids)
91
+ column = f"{alias}.repo_id" if alias else "repo_id"
92
+ return f" AND {column} IN ({placeholders})", repo_ids
93
+
94
+
95
+ def has_runnable_local_work(conn, repo_id=None, repo_ids=None):
96
+ if repo_id is not None and repo_ids is not None:
97
+ raise ValueError("repo_id and repo_ids are mutually exclusive")
98
+ repo_ids = [repo_id] if repo_id else list(repo_ids or [])
99
+ now = wakeup.utc_now()
100
+ wakeup.expire_due_wakeups(conn, now=now)
101
+ wakeup_repo_clause, wakeup_repo_params = _repo_filter("", repo_ids)
102
+ pending_wakeup = conn.execute(
103
+ f"""
104
+ SELECT 1
105
+ FROM wakeups
106
+ WHERE status = 'pending'
107
+ AND not_before_at <= ?
108
+ AND (expires_at IS NULL OR expires_at > ?)
109
+ {wakeup_repo_clause}
110
+ LIMIT 1
111
+ """,
112
+ [now, now] + wakeup_repo_params,
113
+ ).fetchone()
114
+ if pending_wakeup:
115
+ return True
116
+ workstream_repo_clause, workstream_repo_params = _repo_filter("w", repo_ids)
117
+ supervise_needed = conn.execute(
118
+ f"""
119
+ SELECT 1
120
+ FROM attempts a
121
+ JOIN tasks t ON t.task_id = a.task_id
122
+ JOIN workstreams w ON w.workstream_id = t.workstream_id
123
+ WHERE a.status IN ('running', 'stale')
124
+ AND t.lifecycle IN ('queued', 'running')
125
+ {workstream_repo_clause}
126
+ LIMIT 1
127
+ """,
128
+ workstream_repo_params,
129
+ ).fetchone()
130
+ if supervise_needed:
131
+ return True
132
+ prepared = conn.execute(
133
+ f"""
134
+ SELECT 1
135
+ FROM attempts a
136
+ JOIN tasks t ON t.task_id = a.task_id
137
+ JOIN workstreams w ON w.workstream_id = t.workstream_id
138
+ WHERE a.status = 'prepared'
139
+ AND t.lifecycle IN ('queued', 'running')
140
+ {workstream_repo_clause}
141
+ LIMIT 1
142
+ """,
143
+ workstream_repo_params,
144
+ ).fetchone()
145
+ if prepared:
146
+ return True
147
+ publishable = conn.execute(
148
+ f"""
149
+ SELECT 1
150
+ FROM github_actions ga
151
+ JOIN tasks t ON t.task_id = ga.task_id
152
+ JOIN workstreams w ON w.workstream_id = t.workstream_id
153
+ WHERE ga.audit_status = 'accepted'
154
+ AND ga.publish_status = 'not_published'
155
+ {workstream_repo_clause}
156
+ LIMIT 1
157
+ """,
158
+ workstream_repo_params,
159
+ ).fetchone()
160
+ return bool(publishable)
161
+
162
+
163
+ def _write_latest_loop(db_path, summary):
164
+ path = Path(db_path).parent / "latest-loop.json"
165
+ path.write_text(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
166
+ return str(path)
167
+
168
+
169
+ def run_loop(
170
+ config_path,
171
+ workflow_path=None,
172
+ dry_run=True,
173
+ skip_external=False,
174
+ skip_publish=False,
175
+ max_cycles=3,
176
+ max_seconds=120,
177
+ max_dispatches=2,
178
+ max_publish_actions=5,
179
+ runner=run_once_module.run_once,
180
+ ):
181
+ started = time.monotonic()
182
+ db_path, repo_ids = load_config_scope(config_path, skip_external=skip_external)
183
+ cycle_results = []
184
+ stop_reason = "max_cycles"
185
+ with closing(_connect(db_path)) as conn, conn:
186
+ if not has_runnable_local_work(conn, repo_ids=repo_ids):
187
+ summary = {
188
+ "ok": True,
189
+ "status": "completed",
190
+ "cycles": 0,
191
+ "stop_reason": "no_runnable_work",
192
+ "cycle_results": [],
193
+ "budgets": {
194
+ "max_cycles": max_cycles,
195
+ "max_seconds": max_seconds,
196
+ "max_dispatches": max_dispatches,
197
+ "max_publish_actions": max_publish_actions,
198
+ "max_publish_actions_enforcement": "not_enforced",
199
+ },
200
+ "db_path": str(db_path),
201
+ }
202
+ summary["latest_loop_path"] = _write_latest_loop(db_path, summary)
203
+ return summary
204
+
205
+ for cycle in range(max_cycles):
206
+ if time.monotonic() - started >= max_seconds:
207
+ stop_reason = "max_seconds"
208
+ break
209
+ with closing(_connect(db_path)) as conn, conn:
210
+ before = snapshot_progress(conn)
211
+ result = runner(
212
+ config_path,
213
+ workflow_path=workflow_path,
214
+ dry_run=dry_run,
215
+ skip_external=skip_external,
216
+ skip_publish=skip_publish,
217
+ max_dispatches=max_dispatches,
218
+ )
219
+ cycle_results.append(result)
220
+ if not result.get("ok"):
221
+ stop_reason = "run_once_failed"
222
+ break
223
+ with closing(_connect(db_path)) as conn, conn:
224
+ after = snapshot_progress(conn)
225
+ diff = diff_progress(before, after)
226
+ runnable = has_runnable_local_work(conn, repo_ids=repo_ids)
227
+ cycle_results[-1] = {**result, "progress": diff}
228
+ if not diff["changed"]:
229
+ stop_reason = "no_progress"
230
+ break
231
+ if not runnable:
232
+ stop_reason = "no_runnable_work"
233
+ break
234
+ else:
235
+ stop_reason = "max_cycles"
236
+ summary = {
237
+ "ok": stop_reason != "run_once_failed",
238
+ "status": "completed" if stop_reason != "run_once_failed" else "failed",
239
+ "cycles": len(cycle_results),
240
+ "stop_reason": stop_reason,
241
+ "cycle_results": cycle_results,
242
+ "budgets": {
243
+ "max_cycles": max_cycles,
244
+ "max_seconds": max_seconds,
245
+ "max_dispatches": max_dispatches,
246
+ "max_publish_actions": max_publish_actions,
247
+ "max_publish_actions_enforcement": "not_enforced",
248
+ },
249
+ "db_path": str(db_path),
250
+ }
251
+ summary["latest_loop_path"] = _write_latest_loop(db_path, summary)
252
+ return summary
253
+
254
+
255
+ def main(argv=None):
256
+ parser = argparse.ArgumentParser()
257
+ parser.add_argument("--config", required=True)
258
+ parser.add_argument("--workflow")
259
+ parser.add_argument("--dry-run", action="store_true")
260
+ parser.add_argument("--skip-external", action="store_true")
261
+ parser.add_argument("--skip-publish", action="store_true")
262
+ parser.add_argument("--max-cycles", type=int, default=3)
263
+ parser.add_argument("--max-seconds", type=int, default=120)
264
+ parser.add_argument("--max-dispatches", type=int, default=2)
265
+ parser.add_argument("--max-publish-actions", type=int, default=5)
266
+ args = parser.parse_args(argv)
267
+ try:
268
+ result = run_loop(
269
+ args.config,
270
+ workflow_path=args.workflow,
271
+ dry_run=args.dry_run,
272
+ skip_external=args.skip_external,
273
+ skip_publish=args.skip_publish,
274
+ max_cycles=args.max_cycles,
275
+ max_seconds=args.max_seconds,
276
+ max_dispatches=args.max_dispatches,
277
+ max_publish_actions=args.max_publish_actions,
278
+ )
279
+ except ValueError as exc:
280
+ return emit({"ok": False, "status": "failed_config", "safe_error": str(exc)}, exit_code=3)
281
+ return emit(result, 0 if result.get("ok") else 3)
282
+
283
+
284
+ if __name__ == "__main__":
285
+ raise SystemExit(main())
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ from contextlib import closing
4
+ from pathlib import Path
5
+ import sqlite3
6
+ from datetime import datetime, timezone
7
+
8
+ from robert_agent.common import emit
9
+ from robert_agent import runtime_knowledge, storage
10
+
11
+
12
+ def _now():
13
+ return datetime.now(timezone.utc).isoformat()
14
+
15
+
16
+ def _repo_id(conn, repo_id=None):
17
+ if repo_id:
18
+ return repo_id
19
+ row = conn.execute("SELECT repo_id FROM repos ORDER BY repo_id LIMIT 1").fetchone()
20
+ if not row:
21
+ raise ValueError("no repo rows found")
22
+ return row[0]
23
+
24
+
25
+ def run_command(argv=None):
26
+ parser = argparse.ArgumentParser()
27
+ parser.add_argument("--db", required=True)
28
+ subparsers = parser.add_subparsers(dest="command", required=True)
29
+
30
+ propose = subparsers.add_parser("propose")
31
+ propose.add_argument("--repo-id")
32
+
33
+ list_parser = subparsers.add_parser("list")
34
+ list_parser.add_argument("--repo-id")
35
+ list_parser.add_argument("--status")
36
+
37
+ show = subparsers.add_parser("show")
38
+ show.add_argument("--candidate-id", required=True)
39
+
40
+ approve = subparsers.add_parser("approve")
41
+ approve.add_argument("--candidate-id", required=True)
42
+ approve.add_argument("--scope-type", required=True)
43
+ approve.add_argument("--scope-value", default="")
44
+ approve.add_argument("--approved-by", required=True)
45
+
46
+ reject = subparsers.add_parser("reject")
47
+ reject.add_argument("--candidate-id", required=True)
48
+ reject.add_argument("--reviewer", required=True)
49
+ reject.add_argument("--review-note", default="")
50
+
51
+ args = parser.parse_args(argv)
52
+ db_path = Path(args.db).expanduser()
53
+ storage.init_database(db_path)
54
+ now = _now()
55
+ with closing(sqlite3.connect(db_path)) as conn, conn:
56
+ conn.execute("PRAGMA foreign_keys = ON")
57
+ conn.execute("PRAGMA busy_timeout = 5000")
58
+ if args.command == "propose":
59
+ return runtime_knowledge.propose_candidates(
60
+ conn,
61
+ _repo_id(conn, args.repo_id),
62
+ now,
63
+ )
64
+ if args.command == "list":
65
+ candidates = runtime_knowledge.list_candidates(
66
+ conn,
67
+ repo_id=args.repo_id,
68
+ status=args.status,
69
+ )
70
+ return {"ok": True, "status": "listed", "candidates": candidates}
71
+ if args.command == "show":
72
+ candidate = runtime_knowledge.show_candidate(conn, args.candidate_id)
73
+ if not candidate:
74
+ return {"ok": False, "status": "not_found", "safe_error": f"candidate not found: {args.candidate_id}"}
75
+ return {"ok": True, "status": "shown", "candidate": candidate}
76
+ if args.command == "approve":
77
+ return runtime_knowledge.approve_candidate(
78
+ conn,
79
+ candidate_id=args.candidate_id,
80
+ scope_type=args.scope_type,
81
+ scope_value=args.scope_value,
82
+ approved_by=args.approved_by,
83
+ run_now=now,
84
+ )
85
+ if args.command == "reject":
86
+ return runtime_knowledge.reject_candidate(
87
+ conn,
88
+ candidate_id=args.candidate_id,
89
+ reviewer=args.reviewer,
90
+ review_note=args.review_note,
91
+ run_now=now,
92
+ )
93
+ return {"ok": False, "status": "failed_command", "safe_error": f"unknown command: {args.command}"}
94
+
95
+
96
+ def main(argv=None):
97
+ try:
98
+ payload = run_command(argv)
99
+ except ValueError as exc:
100
+ payload = {"ok": False, "status": "failed_validation", "safe_error": str(exc)}
101
+ return emit(payload)
102
+
103
+
104
+ if __name__ == "__main__":
105
+ raise SystemExit(main())
@@ -0,0 +1,157 @@
1
+ from pathlib import Path
2
+ import shutil
3
+ import sqlite3
4
+
5
+ import yaml
6
+
7
+ from robert_agent.resource_files import resource
8
+
9
+
10
+ def plan_legacy_migration(source_dir, target_dir):
11
+ source = Path(source_dir).expanduser()
12
+ target = Path(target_dir).expanduser()
13
+ config = source / "config.yml"
14
+ database = source / "dd.sqlite3"
15
+ missing = [str(path) for path in [config, database] if not path.exists()]
16
+ return {
17
+ "ok": not missing and not target.exists(),
18
+ "source": str(source),
19
+ "target": str(target),
20
+ "missing": missing,
21
+ "target_exists": target.exists(),
22
+ }
23
+
24
+
25
+ def _convert_workers(raw_workers):
26
+ if not isinstance(raw_workers, list):
27
+ return raw_workers
28
+ workers = {}
29
+ for raw_worker in raw_workers:
30
+ if not isinstance(raw_worker, dict):
31
+ continue
32
+ name = str(raw_worker.get("name", "")).strip()
33
+ if not name:
34
+ continue
35
+ workers[name] = {
36
+ "adapter": raw_worker.get("agent", ""),
37
+ "command": raw_worker.get("command", ""),
38
+ "model": raw_worker.get("default_model", ""),
39
+ "effort": raw_worker.get("default_effort", ""),
40
+ }
41
+ return workers
42
+
43
+
44
+ def _convert_repos(raw_repos):
45
+ repos = []
46
+ for raw_repo in raw_repos or []:
47
+ if not isinstance(raw_repo, dict):
48
+ continue
49
+ repo = {
50
+ "full_name": raw_repo.get("full_name", ""),
51
+ "checkout": raw_repo.get("repo_root", ""),
52
+ "worktrees": raw_repo.get("worktree_root", ""),
53
+ "default_branch": raw_repo.get(
54
+ "default_base_branch",
55
+ "main",
56
+ ),
57
+ "trusted_actors": list(raw_repo.get("trusted_actors") or []),
58
+ }
59
+ if raw_repo.get("dd_account"):
60
+ repo["github_account"] = raw_repo["dd_account"]
61
+ if raw_repo.get("max_concurrency") is not None:
62
+ repo["max_concurrency"] = raw_repo["max_concurrency"]
63
+ repos.append(repo)
64
+ return repos
65
+
66
+
67
+ def _convert_config(source_path, target_path):
68
+ legacy = yaml.safe_load(source_path.read_text(encoding="utf-8"))
69
+ if not isinstance(legacy, dict):
70
+ raise ValueError("legacy config root must be a mapping")
71
+ github_account = legacy.pop("dd_account", "")
72
+ legacy["version"] = 1
73
+ legacy["data_dir"] = str(target_path.parent)
74
+ legacy["database"] = "robert.sqlite3"
75
+ legacy["github"] = {
76
+ "account": github_account,
77
+ "poll_seconds": 300,
78
+ }
79
+ legacy["workers"] = _convert_workers(legacy.get("workers"))
80
+ legacy["repos"] = _convert_repos(legacy.get("repos"))
81
+ legacy.setdefault("skills", {"search_paths": []})
82
+ route_worker_models = legacy.get("route_worker_models") or {}
83
+ legacy["routes"] = {
84
+ route_id: {"worker": route_config["worker"]}
85
+ for route_id, route_config in route_worker_models.items()
86
+ if isinstance(route_config, dict) and route_config.get("worker")
87
+ }
88
+ target_path.write_text(
89
+ yaml.safe_dump(legacy, sort_keys=False),
90
+ encoding="utf-8",
91
+ )
92
+
93
+
94
+ def _migrate_database(path):
95
+ migration_sql = resource(
96
+ "db",
97
+ "migrations",
98
+ "001_legacy_dd_to_robert.sql",
99
+ ).read_text(encoding="utf-8")
100
+ with sqlite3.connect(path) as conn, conn:
101
+ columns = {
102
+ row[1]
103
+ for row in conn.execute("PRAGMA table_info(repos)")
104
+ }
105
+ if "dd_account" in columns and "github_account" not in columns:
106
+ conn.execute(
107
+ "ALTER TABLE repos "
108
+ "RENAME COLUMN dd_account TO github_account"
109
+ )
110
+ conn.executescript(migration_sql)
111
+
112
+
113
+ def migrate_legacy(source_dir, target_dir, dry_run=False):
114
+ plan = plan_legacy_migration(source_dir, target_dir)
115
+ if not plan["ok"]:
116
+ return {
117
+ **plan,
118
+ "status": "refused",
119
+ "safe_error": "legacy migration preflight failed",
120
+ }
121
+ if dry_run:
122
+ return {**plan, "ok": True, "status": "planned"}
123
+
124
+ source = Path(source_dir).expanduser()
125
+ target = Path(target_dir).expanduser()
126
+ backup = target.parent / f"{target.name}.legacy-backup"
127
+ if backup.exists():
128
+ return {
129
+ **plan,
130
+ "ok": False,
131
+ "status": "refused",
132
+ "backup": str(backup),
133
+ "safe_error": f"legacy backup already exists: {backup}",
134
+ }
135
+ shutil.copytree(source, backup)
136
+ try:
137
+ target.mkdir(parents=True)
138
+ _convert_config(source / "config.yml", target / "config.yml")
139
+ shutil.copy2(source / "dd.sqlite3", target / "robert.sqlite3")
140
+ _migrate_database(target / "robert.sqlite3")
141
+ except Exception as exc:
142
+ shutil.rmtree(target, ignore_errors=True)
143
+ return {
144
+ "ok": False,
145
+ "status": "failed",
146
+ "source": str(source),
147
+ "target": str(target),
148
+ "backup": str(backup),
149
+ "safe_error": str(exc),
150
+ }
151
+ return {
152
+ "ok": True,
153
+ "status": "migrated",
154
+ "source": str(source),
155
+ "target": str(target),
156
+ "backup": str(backup),
157
+ }
robert_agent/notify.py ADDED
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ from contextlib import closing
4
+ import json
5
+ import shlex
6
+ import sqlite3
7
+ import subprocess
8
+ from datetime import datetime, timezone
9
+ from uuid import uuid4
10
+
11
+ from robert_agent.common import emit
12
+
13
+
14
+ def record_notification(db_path, notification_type, status, metadata=None, channel="local"):
15
+ metadata = metadata or {}
16
+ with closing(sqlite3.connect(db_path)) as conn, conn:
17
+ conn.execute(
18
+ """
19
+ INSERT INTO notifications(
20
+ notification_id, task_id, notification_type, channel, status, created_at, metadata_json
21
+ )
22
+ VALUES (?, ?, ?, ?, ?, ?, ?)
23
+ """,
24
+ (
25
+ f"notification-{uuid4().hex[:12]}",
26
+ metadata.get("task_id"),
27
+ notification_type,
28
+ channel,
29
+ status,
30
+ datetime.now(timezone.utc).isoformat(),
31
+ json.dumps(metadata, ensure_ascii=False, sort_keys=True),
32
+ ),
33
+ )
34
+ return {"ok": True, "status": status, "notification_type": notification_type}
35
+
36
+
37
+ def send_notification(db_path, notification, command=None, timeout_seconds=5):
38
+ status = "recorded"
39
+ if command:
40
+ proc = subprocess.run(
41
+ shlex.split(command),
42
+ input=json.dumps(notification, ensure_ascii=False),
43
+ text=True,
44
+ timeout=timeout_seconds,
45
+ check=False,
46
+ )
47
+ status = "sent" if proc.returncode == 0 else "failed"
48
+ return record_notification(
49
+ db_path=db_path,
50
+ notification_type=notification["type"],
51
+ status=status,
52
+ metadata=notification,
53
+ )
54
+
55
+
56
+ def main(argv=None):
57
+ parser = argparse.ArgumentParser()
58
+ parser.add_argument("--db", required=True)
59
+ parser.add_argument("--type", required=True)
60
+ parser.add_argument("--status", default="recorded")
61
+ parser.add_argument("--metadata", default="{}")
62
+ args = parser.parse_args(argv)
63
+ return emit(
64
+ record_notification(
65
+ db_path=args.db,
66
+ notification_type=args.type,
67
+ status=args.status,
68
+ metadata=json.loads(args.metadata),
69
+ )
70
+ )
71
+
72
+
73
+ if __name__ == "__main__":
74
+ raise SystemExit(main())
robert_agent/paths.py ADDED
@@ -0,0 +1,16 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+
5
+ def default_config_path() -> Path:
6
+ configured = os.environ.get("ROBERT_CONFIG")
7
+ if configured:
8
+ return Path(configured).expanduser()
9
+ return Path.home() / ".config" / "robert" / "config.yml"
10
+
11
+
12
+ def default_data_dir() -> Path:
13
+ configured = os.environ.get("ROBERT_DATA_DIR")
14
+ if configured:
15
+ return Path(configured).expanduser()
16
+ return Path.home() / ".local" / "share" / "robert"