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.
- robert_agent/__init__.py +1 -0
- robert_agent/acceptance.py +394 -0
- robert_agent/acceptance_suite.py +287 -0
- robert_agent/audit_result.py +501 -0
- robert_agent/authorize.py +117 -0
- robert_agent/board.py +538 -0
- robert_agent/chat_status.py +338 -0
- robert_agent/cli/__init__.py +1 -0
- robert_agent/cli/exit_codes.py +5 -0
- robert_agent/cli/main.py +535 -0
- robert_agent/cli/output.py +20 -0
- robert_agent/common.py +6 -0
- robert_agent/controlled_e2e_acceptance.py +394 -0
- robert_agent/daemon.py +607 -0
- robert_agent/daemon_state.py +319 -0
- robert_agent/diagnostics.py +119 -0
- robert_agent/discover.py +775 -0
- robert_agent/dispatch.py +217 -0
- robert_agent/doctor.py +94 -0
- robert_agent/github_api.py +12 -0
- robert_agent/init_config.py +126 -0
- robert_agent/integrations/__init__.py +1 -0
- robert_agent/integrations/openclaw.py +285 -0
- robert_agent/live_discovery_acceptance.py +70 -0
- robert_agent/live_worker_acceptance.py +363 -0
- robert_agent/live_worktree_acceptance.py +344 -0
- robert_agent/loop_engine.py +285 -0
- robert_agent/memory_curator.py +105 -0
- robert_agent/migrate.py +157 -0
- robert_agent/notify.py +74 -0
- robert_agent/paths.py +16 -0
- robert_agent/production_write_canary.py +254 -0
- robert_agent/project_memory.py +503 -0
- robert_agent/publish.py +743 -0
- robert_agent/publish_dedupe_acceptance.py +270 -0
- robert_agent/redaction.py +41 -0
- robert_agent/render_prompt.py +544 -0
- robert_agent/resource_files.py +8 -0
- robert_agent/resources/__init__.py +1 -0
- robert_agent/resources/acceptance-matrix.md +120 -0
- robert_agent/resources/classifier.md +19 -0
- robert_agent/resources/command-matrix.md +38 -0
- robert_agent/resources/config.example.yml +20 -0
- robert_agent/resources/db/migrations/001_legacy_dd_to_robert.sql +14 -0
- robert_agent/resources/db/schema.sql +479 -0
- robert_agent/resources/failure-modes.md +36 -0
- robert_agent/resources/fixtures/actor-permission.json +1 -0
- robert_agent/resources/fixtures/discovery.json +1 -0
- robert_agent/resources/fixtures/redaction.json +1 -0
- robert_agent/resources/fixtures/review-followup.json +1 -0
- robert_agent/resources/fixtures/worker-results.json +1 -0
- robert_agent/resources/fixtures/workstreams.json +1 -0
- robert_agent/resources/github-events.md +77 -0
- robert_agent/resources/kanban-control.md +165 -0
- robert_agent/resources/redaction.md +29 -0
- robert_agent/resources/result-contract.md +56 -0
- robert_agent/resources/routes.yml +82 -0
- robert_agent/resources/schemas/config.schema.json +123 -0
- robert_agent/resources/schemas/event.schema.json +18 -0
- robert_agent/resources/schemas/result.schema.json +99 -0
- robert_agent/resources/schemas/route.schema.json +23 -0
- robert_agent/resources/schemas/snapshot.schema.json +17 -0
- robert_agent/resources/schemas/task.schema.json +15 -0
- robert_agent/resources/trust-model.md +16 -0
- robert_agent/resources/worker-prompt.md +121 -0
- robert_agent/resources/worker-protocol.md +47 -0
- robert_agent/resources/workflow.yml +50 -0
- robert_agent/resources/workstream-model.md +17 -0
- robert_agent/route.py +232 -0
- robert_agent/route_config.py +64 -0
- robert_agent/run_once.py +5375 -0
- robert_agent/runtime_knowledge.py +392 -0
- robert_agent/service.py +161 -0
- robert_agent/skills.py +28 -0
- robert_agent/status.py +1051 -0
- robert_agent/storage.py +376 -0
- robert_agent/summarize.py +100 -0
- robert_agent/supervise.py +72 -0
- robert_agent/usage.py +192 -0
- robert_agent/validate_config.py +616 -0
- robert_agent/wakeup.py +261 -0
- robert_agent/web.py +2893 -0
- robert_agent/web_assets/board.css +255 -0
- robert_agent/web_assets/board.html +165 -0
- robert_agent/web_assets/board.js +660 -0
- robert_agent/web_assets/github-shell.css +122 -0
- robert_agent/web_assets/index.html +103 -0
- robert_agent/web_assets/operations.css +168 -0
- robert_agent/web_assets/workbench.css +131 -0
- robert_agent/web_assets/workbench.js +581 -0
- robert_agent/work_items.py +1016 -0
- robert_agent/workbench.py +701 -0
- robert_agent/worker/__init__.py +1 -0
- robert_agent/worker/heartbeat.py +190 -0
- robert_agent/worker/result.py +321 -0
- robert_agent/worker/snapshot.py +98 -0
- robert_agent/worker_adapters/__init__.py +138 -0
- robert_agent/worker_adapters/cbc.py +68 -0
- robert_agent/worker_adapters/codex.py +56 -0
- robert_agent/worker_adapters/command.py +33 -0
- robert_agent/worker_adapters/tcodex.py +56 -0
- robert_agent/worker_heartbeat.py +6 -0
- robert_agent/worker_result.py +6 -0
- robert_agent/worker_snapshot.py +6 -0
- robert_agent/workstream.py +55 -0
- robert_agent/worktree.py +297 -0
- robert_github_agent-0.1.0b1.dist-info/METADATA +217 -0
- robert_github_agent-0.1.0b1.dist-info/RECORD +111 -0
- robert_github_agent-0.1.0b1.dist-info/WHEEL +4 -0
- robert_github_agent-0.1.0b1.dist-info/entry_points.txt +2 -0
- robert_github_agent-0.1.0b1.dist-info/licenses/LICENSE +201 -0
robert_agent/web.py
ADDED
|
@@ -0,0 +1,2893 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
import argparse
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from contextlib import closing
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from importlib.resources import files
|
|
8
|
+
import ipaddress
|
|
9
|
+
import json
|
|
10
|
+
import secrets
|
|
11
|
+
import sqlite3
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
14
|
+
from urllib.parse import parse_qs, unquote, urlsplit
|
|
15
|
+
|
|
16
|
+
from robert_agent import summarize
|
|
17
|
+
from robert_agent import validate_config
|
|
18
|
+
from robert_agent import (
|
|
19
|
+
board,
|
|
20
|
+
daemon_state,
|
|
21
|
+
runtime_knowledge,
|
|
22
|
+
storage,
|
|
23
|
+
usage,
|
|
24
|
+
wakeup,
|
|
25
|
+
work_items,
|
|
26
|
+
workbench,
|
|
27
|
+
)
|
|
28
|
+
from robert_agent.common import emit
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
RUN_STEP_ORDER = [
|
|
32
|
+
"validate_config",
|
|
33
|
+
"discover_notifications",
|
|
34
|
+
"acquire_lease",
|
|
35
|
+
"supervise",
|
|
36
|
+
"audit_results",
|
|
37
|
+
"publish_actions",
|
|
38
|
+
"reconcile",
|
|
39
|
+
"discover",
|
|
40
|
+
"authorize",
|
|
41
|
+
"route",
|
|
42
|
+
"repo_pipelines",
|
|
43
|
+
"dispatch",
|
|
44
|
+
"summarize",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
REPO_STEP_ORDER = [
|
|
48
|
+
"acquire_lease",
|
|
49
|
+
"supervise",
|
|
50
|
+
"audit_results",
|
|
51
|
+
"publish_actions",
|
|
52
|
+
"reconcile",
|
|
53
|
+
"discover",
|
|
54
|
+
"authorize",
|
|
55
|
+
"route",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
WEB_ASSET_ROOT = files("robert_agent").joinpath("web_assets")
|
|
59
|
+
WEB_ASSETS = {
|
|
60
|
+
"/": ("index.html", "text/html; charset=utf-8"),
|
|
61
|
+
"/board": ("board.html", "text/html; charset=utf-8"),
|
|
62
|
+
"/assets/github-shell.css": ("github-shell.css", "text/css; charset=utf-8"),
|
|
63
|
+
"/assets/operations.css": ("operations.css", "text/css; charset=utf-8"),
|
|
64
|
+
"/assets/board.css": ("board.css", "text/css; charset=utf-8"),
|
|
65
|
+
"/assets/board.js": ("board.js", "text/javascript; charset=utf-8"),
|
|
66
|
+
"/assets/workbench.css": ("workbench.css", "text/css; charset=utf-8"),
|
|
67
|
+
"/assets/workbench.js": (
|
|
68
|
+
"workbench.js",
|
|
69
|
+
"application/javascript; charset=utf-8",
|
|
70
|
+
),
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def validate_server_options(host, writable, allow_remote):
|
|
75
|
+
try:
|
|
76
|
+
address = ipaddress.ip_address(host)
|
|
77
|
+
loopback = address.is_loopback
|
|
78
|
+
except ValueError:
|
|
79
|
+
loopback = host == "localhost"
|
|
80
|
+
if not loopback and not allow_remote:
|
|
81
|
+
return {
|
|
82
|
+
"ok": False,
|
|
83
|
+
"status": "security_refusal",
|
|
84
|
+
"safe_error": (
|
|
85
|
+
"non-loopback binding requires --allow-remote and an "
|
|
86
|
+
"authenticated reverse proxy"
|
|
87
|
+
),
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
"ok": True,
|
|
91
|
+
"status": "valid",
|
|
92
|
+
"writable": bool(writable),
|
|
93
|
+
"csrf_required": bool(writable),
|
|
94
|
+
"remote_warning": not loopback,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class ControlContext:
|
|
100
|
+
db_path: str
|
|
101
|
+
operator_identity: str
|
|
102
|
+
allowed_repo_ids: frozenset[str]
|
|
103
|
+
allowed_workers: frozenset[str]
|
|
104
|
+
allowed_origins: frozenset[str]
|
|
105
|
+
csrf_token: str
|
|
106
|
+
writes_enabled: bool
|
|
107
|
+
write_error: str | None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _decode_json(value):
|
|
111
|
+
if not value:
|
|
112
|
+
return None
|
|
113
|
+
try:
|
|
114
|
+
return json.loads(value)
|
|
115
|
+
except (TypeError, ValueError):
|
|
116
|
+
return value
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _table_exists(conn, table_name):
|
|
120
|
+
row = conn.execute(
|
|
121
|
+
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",
|
|
122
|
+
(table_name,),
|
|
123
|
+
).fetchone()
|
|
124
|
+
return bool(row)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _load_latest_loop(db_path):
|
|
128
|
+
path = Path(db_path).parent / "latest-loop.json"
|
|
129
|
+
try:
|
|
130
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
131
|
+
except (OSError, ValueError):
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _is_authorized_unattached_event(event):
|
|
136
|
+
return (
|
|
137
|
+
event["authorization_status"]
|
|
138
|
+
in {"authorized", "authorized_trigger", "accepted_context", "accepted_review_participant"}
|
|
139
|
+
and not event["task_id"]
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _task_operator_state(task):
|
|
144
|
+
if task["lifecycle"] in {"failed", "canceled"}:
|
|
145
|
+
notification = task.get("latest_notification") or {}
|
|
146
|
+
if notification.get("notification_type") == "worker_timeout":
|
|
147
|
+
return "needs_attention", "inspect_worker_timeout"
|
|
148
|
+
if notification.get("notification_type") == "worker_startup_failed":
|
|
149
|
+
return "needs_attention", "inspect_worker_startup"
|
|
150
|
+
return "needs_attention", "inspect_failure_notification"
|
|
151
|
+
if task.get("failed_publish_actions", 0):
|
|
152
|
+
return "needs_attention", "inspect_github_publish_failure"
|
|
153
|
+
if task.get("skipped_publish_actions", 0):
|
|
154
|
+
return "needs_attention", "inspect_github_publish_skipped"
|
|
155
|
+
if task.get("failed_github_actions", 0):
|
|
156
|
+
return "needs_attention", "inspect_failure_notification"
|
|
157
|
+
if task.get("pending_publish_actions", 0):
|
|
158
|
+
return "waiting_publish", "publish_accepted_github_actions"
|
|
159
|
+
if task["lifecycle"] == "waiting_for_user" or task.get("workstream_lifecycle") == "waiting_for_user":
|
|
160
|
+
return "waiting_user", "wait_for_trusted_user_reply"
|
|
161
|
+
if task.get("latest_attempt_status") == "stale":
|
|
162
|
+
return "worker_stale", "inspect_worker_heartbeat"
|
|
163
|
+
if task["lifecycle"] in {"queued", "running"} and task.get("worker_resume_count", 0) >= 2:
|
|
164
|
+
return "worker_retrying", "inspect_worker_resume"
|
|
165
|
+
if task["lifecycle"] in {"queued", "running"} and task.get("result_pending_audit"):
|
|
166
|
+
return "result_pending_audit", "wait_next_cycle_or_run_once"
|
|
167
|
+
if (
|
|
168
|
+
task["lifecycle"] in {"queued", "running"}
|
|
169
|
+
and task.get("latest_attempt_status") == "running"
|
|
170
|
+
):
|
|
171
|
+
return "worker_running", "wait_for_worker_completion"
|
|
172
|
+
if task["lifecycle"] in {"detected", "authorized", "classified", "queued", "running"}:
|
|
173
|
+
return "waiting_worker", "wait_for_worker_or_supervise"
|
|
174
|
+
if task["lifecycle"] == "completed":
|
|
175
|
+
return "completed", "none"
|
|
176
|
+
if task["lifecycle"] == "ignored":
|
|
177
|
+
return "ignored", "none"
|
|
178
|
+
return "unknown", "inspect_task"
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _attach_task_operator_state(conn, recent_tasks):
|
|
182
|
+
if not recent_tasks:
|
|
183
|
+
return
|
|
184
|
+
task_ids = [task["task_id"] for task in recent_tasks]
|
|
185
|
+
placeholders = ",".join("?" for _task_id in task_ids)
|
|
186
|
+
actions_by_task = {
|
|
187
|
+
task_id: {
|
|
188
|
+
"pending_publish_actions": 0,
|
|
189
|
+
"failed_github_actions": 0,
|
|
190
|
+
"failed_publish_actions": 0,
|
|
191
|
+
"skipped_publish_actions": 0,
|
|
192
|
+
"latest_pending_publish": None,
|
|
193
|
+
"latest_publish_failure": None,
|
|
194
|
+
"latest_publish_skipped": None,
|
|
195
|
+
}
|
|
196
|
+
for task_id in task_ids
|
|
197
|
+
}
|
|
198
|
+
for row in conn.execute(
|
|
199
|
+
f"""
|
|
200
|
+
SELECT
|
|
201
|
+
task_id, action_id, action_type, target_url,
|
|
202
|
+
audit_status, publish_status, created_at, metadata_json
|
|
203
|
+
FROM github_actions
|
|
204
|
+
WHERE task_id IN ({placeholders})
|
|
205
|
+
ORDER BY created_at DESC, action_id DESC
|
|
206
|
+
""",
|
|
207
|
+
task_ids,
|
|
208
|
+
):
|
|
209
|
+
action_state = actions_by_task[row["task_id"]]
|
|
210
|
+
if row["audit_status"] == "accepted" and row["publish_status"] == "not_published":
|
|
211
|
+
action_state["pending_publish_actions"] += 1
|
|
212
|
+
if not action_state["latest_pending_publish"]:
|
|
213
|
+
action_state["latest_pending_publish"] = {
|
|
214
|
+
"action_id": row["action_id"],
|
|
215
|
+
"action_type": row["action_type"],
|
|
216
|
+
"target_url": row["target_url"],
|
|
217
|
+
}
|
|
218
|
+
if row["audit_status"] in {"failed", "policy_violation"}:
|
|
219
|
+
action_state["failed_github_actions"] += 1
|
|
220
|
+
metadata = _decode_json(row["metadata_json"]) or {}
|
|
221
|
+
publish = metadata.get("publish") if isinstance(metadata, dict) else {}
|
|
222
|
+
if row["audit_status"] == "accepted" and row["publish_status"] == "skipped":
|
|
223
|
+
action_state["skipped_publish_actions"] += 1
|
|
224
|
+
if not action_state["latest_publish_skipped"]:
|
|
225
|
+
action_state["latest_publish_skipped"] = {
|
|
226
|
+
"action_id": row["action_id"],
|
|
227
|
+
"action_type": row["action_type"],
|
|
228
|
+
"target_url": row["target_url"],
|
|
229
|
+
"safe_error": publish.get("safe_error") if isinstance(publish, dict) else None,
|
|
230
|
+
"command": publish.get("command") if isinstance(publish, dict) else None,
|
|
231
|
+
}
|
|
232
|
+
if isinstance(publish, dict) and publish.get("status") == "publish_failed":
|
|
233
|
+
action_state["failed_publish_actions"] += 1
|
|
234
|
+
if not action_state["latest_publish_failure"]:
|
|
235
|
+
action_state["latest_publish_failure"] = {
|
|
236
|
+
"action_id": row["action_id"],
|
|
237
|
+
"action_type": row["action_type"],
|
|
238
|
+
"target_url": row["target_url"],
|
|
239
|
+
"safe_error": publish.get("safe_error"),
|
|
240
|
+
"command": publish.get("command"),
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
attempts_by_task = {}
|
|
244
|
+
for row in conn.execute(
|
|
245
|
+
f"""
|
|
246
|
+
SELECT task_id, attempt_id, status, heartbeat_at, started_at, finished_at
|
|
247
|
+
FROM attempts
|
|
248
|
+
WHERE task_id IN ({placeholders})
|
|
249
|
+
ORDER BY attempt_no DESC, started_at DESC, attempt_id DESC
|
|
250
|
+
""",
|
|
251
|
+
task_ids,
|
|
252
|
+
):
|
|
253
|
+
attempts_by_task.setdefault(row["task_id"], dict(row))
|
|
254
|
+
|
|
255
|
+
notifications_by_task = {}
|
|
256
|
+
worker_resume_counts_by_task = {task_id: 0 for task_id in task_ids}
|
|
257
|
+
for row in conn.execute(
|
|
258
|
+
f"""
|
|
259
|
+
SELECT notification_id, task_id, notification_type, channel, status,
|
|
260
|
+
created_at, metadata_json
|
|
261
|
+
FROM notifications
|
|
262
|
+
WHERE task_id IN ({placeholders})
|
|
263
|
+
ORDER BY created_at DESC, notification_id DESC
|
|
264
|
+
""",
|
|
265
|
+
task_ids,
|
|
266
|
+
):
|
|
267
|
+
notification = dict(row)
|
|
268
|
+
notification["metadata"] = _decode_json(notification.pop("metadata_json"))
|
|
269
|
+
if notification["notification_type"] == "worker_resume_prepared":
|
|
270
|
+
worker_resume_counts_by_task[row["task_id"]] += 1
|
|
271
|
+
notifications_by_task.setdefault(row["task_id"], notification)
|
|
272
|
+
|
|
273
|
+
result_pending_audit_by_task = {task_id: False for task_id in task_ids}
|
|
274
|
+
for row in conn.execute(
|
|
275
|
+
f"""
|
|
276
|
+
SELECT wr.task_id, wr.metadata_json
|
|
277
|
+
FROM worker_results wr
|
|
278
|
+
JOIN attempts a ON a.attempt_id = wr.attempt_id
|
|
279
|
+
WHERE wr.task_id IN ({placeholders})
|
|
280
|
+
AND a.status = 'completed'
|
|
281
|
+
ORDER BY wr.created_at DESC, wr.result_id DESC
|
|
282
|
+
""",
|
|
283
|
+
task_ids,
|
|
284
|
+
):
|
|
285
|
+
metadata = _decode_json(row["metadata_json"]) or {}
|
|
286
|
+
if isinstance(metadata, dict) and not metadata.get("audit"):
|
|
287
|
+
result_pending_audit_by_task[row["task_id"]] = True
|
|
288
|
+
|
|
289
|
+
sources_by_task = {}
|
|
290
|
+
for row in conn.execute(
|
|
291
|
+
f"""
|
|
292
|
+
SELECT
|
|
293
|
+
te.task_id,
|
|
294
|
+
ge.event_fingerprint,
|
|
295
|
+
gs.source_key,
|
|
296
|
+
gs.title AS source_title,
|
|
297
|
+
gs.html_url,
|
|
298
|
+
gs.source_type,
|
|
299
|
+
gs.number
|
|
300
|
+
FROM task_events te
|
|
301
|
+
JOIN github_events ge ON ge.event_id = te.event_id
|
|
302
|
+
JOIN github_sources gs ON gs.source_id = ge.source_id
|
|
303
|
+
WHERE te.task_id IN ({placeholders})
|
|
304
|
+
ORDER BY
|
|
305
|
+
CASE te.relationship
|
|
306
|
+
WHEN 'trigger' THEN 0
|
|
307
|
+
WHEN 'context' THEN 1
|
|
308
|
+
WHEN 'pending' THEN 2
|
|
309
|
+
WHEN 'consumed' THEN 3
|
|
310
|
+
ELSE 4
|
|
311
|
+
END,
|
|
312
|
+
te.created_at DESC
|
|
313
|
+
""",
|
|
314
|
+
task_ids,
|
|
315
|
+
):
|
|
316
|
+
sources_by_task.setdefault(row["task_id"], dict(row))
|
|
317
|
+
|
|
318
|
+
artifacts_by_task = {task_id: {} for task_id in task_ids}
|
|
319
|
+
for row in conn.execute(
|
|
320
|
+
f"""
|
|
321
|
+
SELECT task_id, artifact_type, path, bytes, created_at
|
|
322
|
+
FROM artifacts
|
|
323
|
+
WHERE task_id IN ({placeholders})
|
|
324
|
+
ORDER BY created_at DESC, artifact_id DESC
|
|
325
|
+
""",
|
|
326
|
+
task_ids,
|
|
327
|
+
):
|
|
328
|
+
artifacts_by_task[row["task_id"]].setdefault(
|
|
329
|
+
row["artifact_type"],
|
|
330
|
+
{
|
|
331
|
+
"path": row["path"],
|
|
332
|
+
"bytes": row["bytes"],
|
|
333
|
+
},
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
for task in recent_tasks:
|
|
337
|
+
task.update(actions_by_task.get(task["task_id"], {}))
|
|
338
|
+
latest_attempt = attempts_by_task.get(task["task_id"]) or {}
|
|
339
|
+
task["latest_attempt_id"] = latest_attempt.get("attempt_id")
|
|
340
|
+
task["latest_attempt_status"] = latest_attempt.get("status")
|
|
341
|
+
task["latest_attempt_heartbeat_at"] = latest_attempt.get("heartbeat_at")
|
|
342
|
+
task["latest_attempt_started_at"] = latest_attempt.get("started_at")
|
|
343
|
+
task["latest_attempt_finished_at"] = latest_attempt.get("finished_at")
|
|
344
|
+
task["latest_notification"] = notifications_by_task.get(task["task_id"])
|
|
345
|
+
task["worker_resume_count"] = worker_resume_counts_by_task.get(task["task_id"], 0)
|
|
346
|
+
task["result_pending_audit"] = result_pending_audit_by_task.get(task["task_id"], False)
|
|
347
|
+
source = sources_by_task.get(task["task_id"]) or {}
|
|
348
|
+
task["source_key"] = source.get("source_key")
|
|
349
|
+
task["source_title"] = source.get("source_title")
|
|
350
|
+
task["github_url"] = source.get("html_url")
|
|
351
|
+
task["source_type"] = source.get("source_type")
|
|
352
|
+
task["source_number"] = source.get("number")
|
|
353
|
+
task["trigger_event_fingerprint"] = source.get("event_fingerprint")
|
|
354
|
+
task["artifacts"] = dict(sorted(artifacts_by_task.get(task["task_id"], {}).items()))
|
|
355
|
+
operator_state, next_action = _task_operator_state(task)
|
|
356
|
+
task["operator_state"] = operator_state
|
|
357
|
+
task["next_action"] = next_action
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _build_operator_alerts(operator_state_counts, event_flow_counts, summary_counts):
|
|
361
|
+
alerts = []
|
|
362
|
+
|
|
363
|
+
def add(alert_type, count, severity, next_action):
|
|
364
|
+
if count:
|
|
365
|
+
alerts.append(
|
|
366
|
+
{
|
|
367
|
+
"alert_type": alert_type,
|
|
368
|
+
"count": count,
|
|
369
|
+
"severity": severity,
|
|
370
|
+
"next_action": next_action,
|
|
371
|
+
}
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
add(
|
|
375
|
+
"needs_attention_tasks",
|
|
376
|
+
operator_state_counts.get("needs_attention", 0),
|
|
377
|
+
"critical",
|
|
378
|
+
"inspect_attention_tasks",
|
|
379
|
+
)
|
|
380
|
+
add(
|
|
381
|
+
"worker_stale_tasks",
|
|
382
|
+
operator_state_counts.get("worker_stale", 0),
|
|
383
|
+
"warning",
|
|
384
|
+
"inspect_worker_heartbeat",
|
|
385
|
+
)
|
|
386
|
+
add(
|
|
387
|
+
"worker_retrying_tasks",
|
|
388
|
+
operator_state_counts.get("worker_retrying", 0),
|
|
389
|
+
"warning",
|
|
390
|
+
"inspect_worker_resume",
|
|
391
|
+
)
|
|
392
|
+
add(
|
|
393
|
+
"result_pending_audit_tasks",
|
|
394
|
+
operator_state_counts.get("result_pending_audit", 0),
|
|
395
|
+
"warning",
|
|
396
|
+
"wait_next_cycle_or_run_once",
|
|
397
|
+
)
|
|
398
|
+
add(
|
|
399
|
+
"authorized_unattached_events",
|
|
400
|
+
event_flow_counts.get("authorized_unattached", 0),
|
|
401
|
+
"warning",
|
|
402
|
+
"inspect_recent_events",
|
|
403
|
+
)
|
|
404
|
+
add(
|
|
405
|
+
"pending_actor_permission_events",
|
|
406
|
+
summary_counts.get(
|
|
407
|
+
"pending_actor_permission_events",
|
|
408
|
+
event_flow_counts.get("authorization_status", {}).get("pending_actor_permission", 0),
|
|
409
|
+
),
|
|
410
|
+
"warning",
|
|
411
|
+
"resolve_actor_permission",
|
|
412
|
+
)
|
|
413
|
+
add(
|
|
414
|
+
"pending_authorization_events",
|
|
415
|
+
summary_counts.get(
|
|
416
|
+
"pending_authorization_events",
|
|
417
|
+
event_flow_counts.get("authorization_status", {}).get("pending_authorization", 0),
|
|
418
|
+
),
|
|
419
|
+
"warning",
|
|
420
|
+
"resolve_authorization_lookup",
|
|
421
|
+
)
|
|
422
|
+
add(
|
|
423
|
+
"waiting_publish_tasks",
|
|
424
|
+
operator_state_counts.get("waiting_publish", 0),
|
|
425
|
+
"info",
|
|
426
|
+
"publish_accepted_github_actions",
|
|
427
|
+
)
|
|
428
|
+
return alerts
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _event_operator_next_step(event):
|
|
432
|
+
if _is_authorized_unattached_event(event):
|
|
433
|
+
return {
|
|
434
|
+
"target_kind": "event",
|
|
435
|
+
"target_id": event["event_id"],
|
|
436
|
+
"github_url": event.get("html_url"),
|
|
437
|
+
"source_key": event.get("source_key"),
|
|
438
|
+
"source_title": event.get("source_title"),
|
|
439
|
+
"event_fingerprint": event.get("event_fingerprint"),
|
|
440
|
+
"actor_login": event.get("actor_login"),
|
|
441
|
+
"severity": "warning",
|
|
442
|
+
"next_action": "inspect_recent_events",
|
|
443
|
+
"reason": "authorized_unattached",
|
|
444
|
+
}
|
|
445
|
+
if event["authorization_status"] == "pending_actor_permission":
|
|
446
|
+
return {
|
|
447
|
+
"target_kind": "event",
|
|
448
|
+
"target_id": event["event_id"],
|
|
449
|
+
"github_url": event.get("html_url"),
|
|
450
|
+
"source_key": event.get("source_key"),
|
|
451
|
+
"source_title": event.get("source_title"),
|
|
452
|
+
"event_fingerprint": event.get("event_fingerprint"),
|
|
453
|
+
"actor_login": event.get("actor_login"),
|
|
454
|
+
"severity": "warning",
|
|
455
|
+
"next_action": "resolve_actor_permission",
|
|
456
|
+
"reason": "pending_actor_permission",
|
|
457
|
+
}
|
|
458
|
+
if event["authorization_status"] == "pending_authorization":
|
|
459
|
+
return {
|
|
460
|
+
"target_kind": "event",
|
|
461
|
+
"target_id": event["event_id"],
|
|
462
|
+
"github_url": event.get("html_url"),
|
|
463
|
+
"source_key": event.get("source_key"),
|
|
464
|
+
"source_title": event.get("source_title"),
|
|
465
|
+
"event_fingerprint": event.get("event_fingerprint"),
|
|
466
|
+
"actor_login": event.get("actor_login"),
|
|
467
|
+
"severity": "warning",
|
|
468
|
+
"next_action": "resolve_authorization_lookup",
|
|
469
|
+
"reason": "pending_authorization",
|
|
470
|
+
}
|
|
471
|
+
return None
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _build_operator_next_steps(recent_tasks, recent_events, priority_events=None):
|
|
475
|
+
steps = []
|
|
476
|
+
task_severities = {
|
|
477
|
+
"needs_attention": "critical",
|
|
478
|
+
"worker_stale": "warning",
|
|
479
|
+
"worker_retrying": "warning",
|
|
480
|
+
"result_pending_audit": "warning",
|
|
481
|
+
"waiting_publish": "info",
|
|
482
|
+
}
|
|
483
|
+
for task in recent_tasks:
|
|
484
|
+
severity = task_severities.get(task["operator_state"])
|
|
485
|
+
if not severity:
|
|
486
|
+
continue
|
|
487
|
+
step = {
|
|
488
|
+
"target_kind": "task",
|
|
489
|
+
"target_id": task["task_id"],
|
|
490
|
+
"github_url": task.get("github_url"),
|
|
491
|
+
"source_key": task.get("source_key"),
|
|
492
|
+
"source_title": task.get("source_title"),
|
|
493
|
+
"workstream_id": task["workstream_id"],
|
|
494
|
+
"route_id": task.get("route_id"),
|
|
495
|
+
"severity": severity,
|
|
496
|
+
"next_action": task["next_action"],
|
|
497
|
+
"reason": task["operator_state"],
|
|
498
|
+
}
|
|
499
|
+
if task["next_action"] == "inspect_github_publish_failure":
|
|
500
|
+
publish_failure = task.get("latest_publish_failure") or {}
|
|
501
|
+
step["notification_type"] = "github_publish_failed"
|
|
502
|
+
step["safe_error"] = publish_failure.get("safe_error")
|
|
503
|
+
step["command"] = publish_failure.get("command")
|
|
504
|
+
elif task["next_action"] == "inspect_github_publish_skipped":
|
|
505
|
+
publish_skipped = task.get("latest_publish_skipped") or {}
|
|
506
|
+
step["notification_type"] = "github_publish_skipped"
|
|
507
|
+
step["safe_error"] = publish_skipped.get("safe_error")
|
|
508
|
+
step["command"] = publish_skipped.get("command")
|
|
509
|
+
elif task["next_action"] == "publish_accepted_github_actions":
|
|
510
|
+
pending_publish = task.get("latest_pending_publish") or {}
|
|
511
|
+
step["action_id"] = pending_publish.get("action_id")
|
|
512
|
+
step["action_type"] = pending_publish.get("action_type")
|
|
513
|
+
step["target_url"] = pending_publish.get("target_url")
|
|
514
|
+
elif task["next_action"] == "inspect_failure_notification":
|
|
515
|
+
notification = task.get("latest_notification") or {}
|
|
516
|
+
metadata = notification.get("metadata") or {}
|
|
517
|
+
audit = metadata.get("audit") if isinstance(metadata, dict) else {}
|
|
518
|
+
step["notification_type"] = notification.get("notification_type")
|
|
519
|
+
step["result_id"] = metadata.get("result_id") if isinstance(metadata, dict) else None
|
|
520
|
+
step["safe_error"] = (
|
|
521
|
+
audit.get("safe_error")
|
|
522
|
+
if isinstance(audit, dict)
|
|
523
|
+
else metadata.get("safe_error") if isinstance(metadata, dict) else None
|
|
524
|
+
)
|
|
525
|
+
elif task["next_action"] in {"inspect_worker_heartbeat", "inspect_worker_timeout", "inspect_worker_startup"}:
|
|
526
|
+
step["attempt_id"] = task.get("latest_attempt_id")
|
|
527
|
+
step["attempt_status"] = task.get("latest_attempt_status")
|
|
528
|
+
step["heartbeat_at"] = task.get("latest_attempt_heartbeat_at")
|
|
529
|
+
step["started_at"] = task.get("latest_attempt_started_at")
|
|
530
|
+
step["finished_at"] = task.get("latest_attempt_finished_at")
|
|
531
|
+
elif task["next_action"] == "inspect_worker_resume":
|
|
532
|
+
notification = task.get("latest_notification") or {}
|
|
533
|
+
metadata = notification.get("metadata") or {}
|
|
534
|
+
step["notification_type"] = notification.get("notification_type")
|
|
535
|
+
step["attempt_id"] = metadata.get("attempt_id") if isinstance(metadata, dict) else None
|
|
536
|
+
step["resume_attempt_id"] = metadata.get("resume_attempt_id") if isinstance(metadata, dict) else None
|
|
537
|
+
step["recovery_artifact_path"] = (
|
|
538
|
+
metadata.get("recovery_artifact_path") if isinstance(metadata, dict) else None
|
|
539
|
+
)
|
|
540
|
+
step["worker_resume_count"] = task.get("worker_resume_count")
|
|
541
|
+
elif task["next_action"] == "wait_next_cycle_or_run_once":
|
|
542
|
+
step["attempt_id"] = task.get("latest_attempt_id")
|
|
543
|
+
step["attempt_status"] = task.get("latest_attempt_status")
|
|
544
|
+
steps.append(step)
|
|
545
|
+
seen_event_ids = set()
|
|
546
|
+
for event in list(recent_events) + list(priority_events or []):
|
|
547
|
+
if event["event_id"] in seen_event_ids:
|
|
548
|
+
continue
|
|
549
|
+
seen_event_ids.add(event["event_id"])
|
|
550
|
+
step = _event_operator_next_step(event)
|
|
551
|
+
if step:
|
|
552
|
+
steps.append(step)
|
|
553
|
+
severity_order = {"critical": 0, "warning": 1, "info": 2}
|
|
554
|
+
return sorted(
|
|
555
|
+
steps,
|
|
556
|
+
key=lambda step: (
|
|
557
|
+
severity_order.get(step["severity"], 99),
|
|
558
|
+
step["target_kind"],
|
|
559
|
+
step["target_id"],
|
|
560
|
+
),
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def _notification_metadata(value):
|
|
565
|
+
if isinstance(value, dict):
|
|
566
|
+
return value
|
|
567
|
+
if value is None:
|
|
568
|
+
return {}
|
|
569
|
+
return {"value": value}
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def _metadata_task_id(metadata):
|
|
573
|
+
if isinstance(metadata, dict):
|
|
574
|
+
return metadata.get("task_id")
|
|
575
|
+
return None
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def _notification_task_id(notification):
|
|
579
|
+
metadata = notification.get("metadata") or {}
|
|
580
|
+
return notification.get("task_id") or _metadata_task_id(metadata)
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _status_severity(*values):
|
|
584
|
+
text = " ".join(str(value or "").lower() for value in values)
|
|
585
|
+
if any(token in text for token in ("failed", "failure", "rejected", "timeout", "error")):
|
|
586
|
+
return "critical"
|
|
587
|
+
if any(token in text for token in ("stale", "retry", "skipped", "pending", "permission")):
|
|
588
|
+
return "warning"
|
|
589
|
+
if any(token in text for token in ("completed", "succeeded", "healthy", "resolved")):
|
|
590
|
+
return "ok"
|
|
591
|
+
return "info"
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def _notification_item(
|
|
595
|
+
*,
|
|
596
|
+
item_id,
|
|
597
|
+
kind,
|
|
598
|
+
severity,
|
|
599
|
+
title,
|
|
600
|
+
summary,
|
|
601
|
+
created_at=None,
|
|
602
|
+
task_id=None,
|
|
603
|
+
source_key=None,
|
|
604
|
+
source_title=None,
|
|
605
|
+
github_url=None,
|
|
606
|
+
metadata=None,
|
|
607
|
+
):
|
|
608
|
+
return {
|
|
609
|
+
"id": item_id,
|
|
610
|
+
"kind": kind,
|
|
611
|
+
"severity": severity,
|
|
612
|
+
"title": title,
|
|
613
|
+
"summary": summary,
|
|
614
|
+
"created_at": created_at,
|
|
615
|
+
"task_id": task_id,
|
|
616
|
+
"source_key": source_key,
|
|
617
|
+
"source_title": source_title,
|
|
618
|
+
"github_url": github_url,
|
|
619
|
+
"metadata": _notification_metadata(metadata),
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def _build_notification_center(
|
|
624
|
+
operator_alerts,
|
|
625
|
+
operator_next_steps,
|
|
626
|
+
recent_notifications,
|
|
627
|
+
recent_actions,
|
|
628
|
+
daemon_summary,
|
|
629
|
+
recent_runs,
|
|
630
|
+
recent_tasks,
|
|
631
|
+
):
|
|
632
|
+
items = []
|
|
633
|
+
tasks_by_id = {task["task_id"]: task for task in recent_tasks}
|
|
634
|
+
|
|
635
|
+
for alert in operator_alerts:
|
|
636
|
+
alert_type = alert.get("alert_type") or "operator_alert"
|
|
637
|
+
count = alert.get("count")
|
|
638
|
+
items.append(
|
|
639
|
+
_notification_item(
|
|
640
|
+
item_id=f"alert:{alert_type}",
|
|
641
|
+
kind="alert",
|
|
642
|
+
severity=alert.get("severity") or "warning",
|
|
643
|
+
title=alert_type,
|
|
644
|
+
summary=f"{count} item(s) need {alert.get('next_action') or 'operator review'}",
|
|
645
|
+
metadata=alert,
|
|
646
|
+
)
|
|
647
|
+
)
|
|
648
|
+
|
|
649
|
+
for step in operator_next_steps:
|
|
650
|
+
target_kind = step.get("target_kind") or "target"
|
|
651
|
+
target_id = step.get("target_id") or step.get("event_fingerprint") or "unknown"
|
|
652
|
+
task_id = target_id if target_kind == "task" else step.get("task_id")
|
|
653
|
+
items.append(
|
|
654
|
+
_notification_item(
|
|
655
|
+
item_id=f"next_step:{target_kind}:{target_id}:{step.get('next_action') or 'inspect'}",
|
|
656
|
+
kind="next_step",
|
|
657
|
+
severity=step.get("severity") or "info",
|
|
658
|
+
title=step.get("next_action") or "operator_next_step",
|
|
659
|
+
summary=step.get("reason") or target_id,
|
|
660
|
+
task_id=task_id,
|
|
661
|
+
source_key=step.get("source_key"),
|
|
662
|
+
source_title=step.get("source_title"),
|
|
663
|
+
github_url=step.get("github_url") or step.get("target_url"),
|
|
664
|
+
metadata=step,
|
|
665
|
+
)
|
|
666
|
+
)
|
|
667
|
+
|
|
668
|
+
for notification in recent_notifications:
|
|
669
|
+
metadata = notification.get("metadata") or {}
|
|
670
|
+
task_id = _notification_task_id(notification)
|
|
671
|
+
task = tasks_by_id.get(task_id, {})
|
|
672
|
+
summary = (
|
|
673
|
+
metadata.get("summary")
|
|
674
|
+
if isinstance(metadata, dict)
|
|
675
|
+
else None
|
|
676
|
+
) or notification.get("status") or notification.get("channel") or ""
|
|
677
|
+
items.append(
|
|
678
|
+
_notification_item(
|
|
679
|
+
item_id=f"notification:{notification.get('notification_id')}",
|
|
680
|
+
kind="notification",
|
|
681
|
+
severity=_status_severity(
|
|
682
|
+
notification.get("notification_type"),
|
|
683
|
+
notification.get("status"),
|
|
684
|
+
metadata.get("safe_error") if isinstance(metadata, dict) else None,
|
|
685
|
+
),
|
|
686
|
+
title=notification.get("notification_type") or "notification",
|
|
687
|
+
summary=summary,
|
|
688
|
+
created_at=notification.get("created_at"),
|
|
689
|
+
task_id=task_id,
|
|
690
|
+
source_key=task.get("source_key"),
|
|
691
|
+
source_title=task.get("source_title"),
|
|
692
|
+
github_url=task.get("github_url"),
|
|
693
|
+
metadata=notification,
|
|
694
|
+
)
|
|
695
|
+
)
|
|
696
|
+
|
|
697
|
+
for event in (daemon_summary or {}).get("recent_events") or []:
|
|
698
|
+
metadata = event.get("metadata") or {}
|
|
699
|
+
items.append(
|
|
700
|
+
_notification_item(
|
|
701
|
+
item_id=f"daemon_event:{event.get('daemon_event_id')}",
|
|
702
|
+
kind="daemon_event",
|
|
703
|
+
severity=_status_severity(event.get("status"), event.get("event_type")),
|
|
704
|
+
title=event.get("event_type") or "daemon_event",
|
|
705
|
+
summary=metadata.get("reason") if isinstance(metadata, dict) else event.get("status"),
|
|
706
|
+
created_at=event.get("created_at"),
|
|
707
|
+
metadata=event,
|
|
708
|
+
)
|
|
709
|
+
)
|
|
710
|
+
|
|
711
|
+
for action in recent_actions:
|
|
712
|
+
audit_status = action.get("audit_status")
|
|
713
|
+
publish_status = action.get("publish_status")
|
|
714
|
+
metadata = action.get("metadata") or {}
|
|
715
|
+
publish = metadata.get("publish") if isinstance(metadata, dict) else {}
|
|
716
|
+
failed_publish = isinstance(publish, dict) and publish.get("status") == "publish_failed"
|
|
717
|
+
if audit_status not in {"failed", "policy_violation"} and publish_status != "skipped" and not failed_publish:
|
|
718
|
+
continue
|
|
719
|
+
task = tasks_by_id.get(action.get("task_id"), {})
|
|
720
|
+
items.append(
|
|
721
|
+
_notification_item(
|
|
722
|
+
item_id=f"github_action:{action.get('action_id')}",
|
|
723
|
+
kind="github_action",
|
|
724
|
+
severity=_status_severity(audit_status, publish_status, publish.get("status") if isinstance(publish, dict) else None),
|
|
725
|
+
title=action.get("action_type") or "github_action",
|
|
726
|
+
summary=publish.get("safe_error") if isinstance(publish, dict) else publish_status or audit_status,
|
|
727
|
+
created_at=action.get("created_at"),
|
|
728
|
+
task_id=action.get("task_id"),
|
|
729
|
+
source_key=task.get("source_key"),
|
|
730
|
+
source_title=task.get("source_title"),
|
|
731
|
+
github_url=action.get("target_url") or task.get("github_url"),
|
|
732
|
+
metadata=action,
|
|
733
|
+
)
|
|
734
|
+
)
|
|
735
|
+
|
|
736
|
+
for run in recent_runs:
|
|
737
|
+
if run.get("status") not in {"failed", "canceled"}:
|
|
738
|
+
continue
|
|
739
|
+
items.append(
|
|
740
|
+
_notification_item(
|
|
741
|
+
item_id=f"run:{run.get('run_id')}",
|
|
742
|
+
kind="run",
|
|
743
|
+
severity="critical",
|
|
744
|
+
title=f"run {run.get('status')}",
|
|
745
|
+
summary=(run.get("error") or {}).get("status") if isinstance(run.get("error"), dict) else run.get("status"),
|
|
746
|
+
created_at=run.get("started_at"),
|
|
747
|
+
metadata=run,
|
|
748
|
+
)
|
|
749
|
+
)
|
|
750
|
+
|
|
751
|
+
return sorted(
|
|
752
|
+
items,
|
|
753
|
+
key=lambda item: (
|
|
754
|
+
item.get("created_at") or "",
|
|
755
|
+
item["id"],
|
|
756
|
+
),
|
|
757
|
+
reverse=True,
|
|
758
|
+
)
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _build_work_items(recent_tasks):
|
|
762
|
+
groups = {}
|
|
763
|
+
for task in recent_tasks:
|
|
764
|
+
item_id = task.get("source_key") or task.get("workstream_id") or task.get("task_id")
|
|
765
|
+
if not item_id:
|
|
766
|
+
continue
|
|
767
|
+
group = groups.setdefault(
|
|
768
|
+
item_id,
|
|
769
|
+
{
|
|
770
|
+
"id": item_id,
|
|
771
|
+
"source_key": task.get("source_key"),
|
|
772
|
+
"source_title": task.get("source_title"),
|
|
773
|
+
"source_type": task.get("source_type"),
|
|
774
|
+
"source_number": task.get("source_number"),
|
|
775
|
+
"repo_id": task.get("repo_id"),
|
|
776
|
+
"repo_full_name": task.get("repo_full_name"),
|
|
777
|
+
"github_url": task.get("github_url"),
|
|
778
|
+
"workstream_id": task.get("workstream_id"),
|
|
779
|
+
"latest_task_updated_at": task.get("updated_at"),
|
|
780
|
+
"task_count": 0,
|
|
781
|
+
"operator_state_counts": {},
|
|
782
|
+
"tasks": [],
|
|
783
|
+
},
|
|
784
|
+
)
|
|
785
|
+
if not group.get("source_key") and task.get("source_key"):
|
|
786
|
+
group["source_key"] = task.get("source_key")
|
|
787
|
+
if not group.get("source_title") and task.get("source_title"):
|
|
788
|
+
group["source_title"] = task.get("source_title")
|
|
789
|
+
if not group.get("source_type") and task.get("source_type"):
|
|
790
|
+
group["source_type"] = task.get("source_type")
|
|
791
|
+
if not group.get("source_number") and task.get("source_number"):
|
|
792
|
+
group["source_number"] = task.get("source_number")
|
|
793
|
+
if not group.get("repo_id") and task.get("repo_id"):
|
|
794
|
+
group["repo_id"] = task.get("repo_id")
|
|
795
|
+
if not group.get("repo_full_name") and task.get("repo_full_name"):
|
|
796
|
+
group["repo_full_name"] = task.get("repo_full_name")
|
|
797
|
+
if not group.get("github_url") and task.get("github_url"):
|
|
798
|
+
group["github_url"] = task.get("github_url")
|
|
799
|
+
if task.get("updated_at") and (not group.get("latest_task_updated_at") or task["updated_at"] > group["latest_task_updated_at"]):
|
|
800
|
+
group["latest_task_updated_at"] = task["updated_at"]
|
|
801
|
+
group["task_count"] += 1
|
|
802
|
+
state = task.get("operator_state") or "unknown"
|
|
803
|
+
group["operator_state_counts"][state] = group["operator_state_counts"].get(state, 0) + 1
|
|
804
|
+
group["tasks"].append(task)
|
|
805
|
+
|
|
806
|
+
state_priority = {
|
|
807
|
+
"needs_attention": 0,
|
|
808
|
+
"worker_stale": 1,
|
|
809
|
+
"worker_retrying": 2,
|
|
810
|
+
"result_pending_audit": 3,
|
|
811
|
+
"waiting_publish": 4,
|
|
812
|
+
"waiting_user": 5,
|
|
813
|
+
"worker_running": 6,
|
|
814
|
+
"waiting_worker": 7,
|
|
815
|
+
"completed": 8,
|
|
816
|
+
"ignored": 9,
|
|
817
|
+
}
|
|
818
|
+
work_items = []
|
|
819
|
+
for group in groups.values():
|
|
820
|
+
group["tasks"] = sorted(
|
|
821
|
+
group["tasks"],
|
|
822
|
+
key=lambda task: (task.get("updated_at") or "", task.get("task_id") or ""),
|
|
823
|
+
reverse=True,
|
|
824
|
+
)
|
|
825
|
+
group["top_operator_state"] = sorted(
|
|
826
|
+
group["operator_state_counts"],
|
|
827
|
+
key=lambda state: (state_priority.get(state, 99), state),
|
|
828
|
+
)[0]
|
|
829
|
+
work_items.append(group)
|
|
830
|
+
return sorted(
|
|
831
|
+
work_items,
|
|
832
|
+
key=lambda group: (group.get("latest_task_updated_at") or "", group["id"]),
|
|
833
|
+
reverse=True,
|
|
834
|
+
)
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def _load_priority_pending_events(conn, recent_events, history_limit):
|
|
838
|
+
recent_event_ids = {event["event_id"] for event in recent_events}
|
|
839
|
+
priority_limit = max(history_limit, 20)
|
|
840
|
+
rows = [
|
|
841
|
+
dict(row)
|
|
842
|
+
for row in conn.execute(
|
|
843
|
+
"""
|
|
844
|
+
SELECT
|
|
845
|
+
ge.event_id,
|
|
846
|
+
ge.event_fingerprint,
|
|
847
|
+
ge.event_type,
|
|
848
|
+
ge.actor_login,
|
|
849
|
+
ge.author_association,
|
|
850
|
+
ge.authorization_status,
|
|
851
|
+
ge.event_at,
|
|
852
|
+
ge.payload_json,
|
|
853
|
+
gs.source_key,
|
|
854
|
+
gs.title AS source_title,
|
|
855
|
+
gs.source_type,
|
|
856
|
+
gs.number,
|
|
857
|
+
gs.html_url,
|
|
858
|
+
NULL AS task_id,
|
|
859
|
+
NULL AS task_relationship,
|
|
860
|
+
NULL AS workstream_id
|
|
861
|
+
FROM github_events ge
|
|
862
|
+
JOIN github_sources gs ON gs.source_id = ge.source_id
|
|
863
|
+
WHERE ge.authorization_status IN (
|
|
864
|
+
'pending_actor_permission',
|
|
865
|
+
'pending_authorization'
|
|
866
|
+
)
|
|
867
|
+
ORDER BY ge.event_at DESC, ge.event_id DESC
|
|
868
|
+
LIMIT ?
|
|
869
|
+
""",
|
|
870
|
+
(priority_limit,),
|
|
871
|
+
)
|
|
872
|
+
]
|
|
873
|
+
priority_events = []
|
|
874
|
+
for event in rows:
|
|
875
|
+
if event["event_id"] in recent_event_ids:
|
|
876
|
+
continue
|
|
877
|
+
event["payload"] = _decode_json(event.pop("payload_json")) or {}
|
|
878
|
+
priority_events.append(event)
|
|
879
|
+
return priority_events
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
def _load_repos(conn):
|
|
883
|
+
if not _table_exists(conn, "repos"):
|
|
884
|
+
return []
|
|
885
|
+
return [
|
|
886
|
+
{
|
|
887
|
+
"repo_id": row["repo_id"],
|
|
888
|
+
"full_name": row["full_name"],
|
|
889
|
+
}
|
|
890
|
+
for row in conn.execute(
|
|
891
|
+
"""
|
|
892
|
+
SELECT repo_id, full_name
|
|
893
|
+
FROM repos
|
|
894
|
+
ORDER BY full_name, repo_id
|
|
895
|
+
"""
|
|
896
|
+
)
|
|
897
|
+
]
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
def build_dashboard_data(db_path, history_limit=20):
|
|
901
|
+
with closing(sqlite3.connect(db_path)) as conn, conn:
|
|
902
|
+
conn.row_factory = sqlite3.Row
|
|
903
|
+
repos = _load_repos(conn)
|
|
904
|
+
recent_tasks = [
|
|
905
|
+
dict(row)
|
|
906
|
+
for row in conn.execute(
|
|
907
|
+
"""
|
|
908
|
+
SELECT
|
|
909
|
+
t.task_id,
|
|
910
|
+
t.workstream_id,
|
|
911
|
+
t.lifecycle,
|
|
912
|
+
t.priority,
|
|
913
|
+
COALESCE(t.route_id, rd.route_id) AS route_id,
|
|
914
|
+
COALESCE(t.expected_output, rd.expected_output) AS expected_output,
|
|
915
|
+
t.updated_at,
|
|
916
|
+
w.lifecycle AS workstream_lifecycle,
|
|
917
|
+
w.repo_id,
|
|
918
|
+
repos.full_name AS repo_full_name,
|
|
919
|
+
rd.route_decision_id,
|
|
920
|
+
rd.confidence AS route_confidence,
|
|
921
|
+
rd.allowed_github_actions_json,
|
|
922
|
+
rd.recommended_skills_json
|
|
923
|
+
FROM tasks t
|
|
924
|
+
JOIN workstreams w ON w.workstream_id = t.workstream_id
|
|
925
|
+
JOIN repos ON repos.repo_id = w.repo_id
|
|
926
|
+
LEFT JOIN route_decisions rd ON rd.task_id = t.task_id
|
|
927
|
+
ORDER BY t.updated_at DESC, t.task_id DESC
|
|
928
|
+
LIMIT ?
|
|
929
|
+
""",
|
|
930
|
+
(history_limit,),
|
|
931
|
+
)
|
|
932
|
+
]
|
|
933
|
+
for task in recent_tasks:
|
|
934
|
+
task["allowed_github_actions"] = _decode_json(
|
|
935
|
+
task.pop("allowed_github_actions_json")
|
|
936
|
+
) or []
|
|
937
|
+
task["recommended_skills"] = _decode_json(
|
|
938
|
+
task.pop("recommended_skills_json")
|
|
939
|
+
) or []
|
|
940
|
+
_attach_task_operator_state(conn, recent_tasks)
|
|
941
|
+
operator_state_counts = dict(
|
|
942
|
+
sorted(Counter(task["operator_state"] for task in recent_tasks).items())
|
|
943
|
+
)
|
|
944
|
+
recent_actions = [
|
|
945
|
+
dict(row)
|
|
946
|
+
for row in conn.execute(
|
|
947
|
+
"""
|
|
948
|
+
SELECT action_id, result_id, task_id, action_type, target_url, external_id,
|
|
949
|
+
audit_status, publish_status, created_at, metadata_json
|
|
950
|
+
FROM github_actions
|
|
951
|
+
ORDER BY created_at DESC, action_id DESC
|
|
952
|
+
LIMIT ?
|
|
953
|
+
""",
|
|
954
|
+
(history_limit,),
|
|
955
|
+
)
|
|
956
|
+
]
|
|
957
|
+
for action in recent_actions:
|
|
958
|
+
action["metadata"] = _decode_json(action.pop("metadata_json"))
|
|
959
|
+
recent_notifications = [
|
|
960
|
+
dict(row)
|
|
961
|
+
for row in conn.execute(
|
|
962
|
+
"""
|
|
963
|
+
SELECT notification_id, task_id, notification_type, channel, status,
|
|
964
|
+
created_at, metadata_json
|
|
965
|
+
FROM notifications
|
|
966
|
+
ORDER BY created_at DESC, notification_id DESC
|
|
967
|
+
LIMIT ?
|
|
968
|
+
""",
|
|
969
|
+
(history_limit,),
|
|
970
|
+
)
|
|
971
|
+
]
|
|
972
|
+
for notification in recent_notifications:
|
|
973
|
+
notification["metadata"] = _decode_json(notification.pop("metadata_json"))
|
|
974
|
+
recent_worker_results = [
|
|
975
|
+
dict(row)
|
|
976
|
+
for row in conn.execute(
|
|
977
|
+
"""
|
|
978
|
+
SELECT result_id, task_id, attempt_id, output_type,
|
|
979
|
+
consumed_event_fingerprints_json, verification_json,
|
|
980
|
+
handoff, created_at, metadata_json
|
|
981
|
+
FROM worker_results
|
|
982
|
+
ORDER BY created_at DESC, result_id DESC
|
|
983
|
+
LIMIT ?
|
|
984
|
+
""",
|
|
985
|
+
(history_limit,),
|
|
986
|
+
)
|
|
987
|
+
]
|
|
988
|
+
used_skill_counts = Counter()
|
|
989
|
+
for result in recent_worker_results:
|
|
990
|
+
result["consumed_event_fingerprints"] = _decode_json(
|
|
991
|
+
result.pop("consumed_event_fingerprints_json")
|
|
992
|
+
) or []
|
|
993
|
+
result["verification"] = _decode_json(result.pop("verification_json")) or []
|
|
994
|
+
result["metadata"] = _decode_json(result.pop("metadata_json")) or {}
|
|
995
|
+
used_skill_counts.update(result["metadata"].get("used_skills") or [])
|
|
996
|
+
recent_events = [
|
|
997
|
+
dict(row)
|
|
998
|
+
for row in conn.execute(
|
|
999
|
+
"""
|
|
1000
|
+
SELECT
|
|
1001
|
+
ge.event_id,
|
|
1002
|
+
ge.event_fingerprint,
|
|
1003
|
+
ge.event_type,
|
|
1004
|
+
ge.actor_login,
|
|
1005
|
+
ge.author_association,
|
|
1006
|
+
ge.authorization_status,
|
|
1007
|
+
ge.event_at,
|
|
1008
|
+
ge.payload_json,
|
|
1009
|
+
gs.source_key,
|
|
1010
|
+
gs.title AS source_title,
|
|
1011
|
+
gs.source_type,
|
|
1012
|
+
gs.number,
|
|
1013
|
+
gs.html_url,
|
|
1014
|
+
te.task_id,
|
|
1015
|
+
te.relationship AS task_relationship,
|
|
1016
|
+
t.workstream_id
|
|
1017
|
+
FROM github_events ge
|
|
1018
|
+
JOIN github_sources gs ON gs.source_id = ge.source_id
|
|
1019
|
+
LEFT JOIN task_events te ON te.event_id = ge.event_id
|
|
1020
|
+
LEFT JOIN tasks t ON t.task_id = te.task_id
|
|
1021
|
+
ORDER BY ge.event_at DESC, ge.event_id DESC
|
|
1022
|
+
LIMIT ?
|
|
1023
|
+
""",
|
|
1024
|
+
(history_limit,),
|
|
1025
|
+
)
|
|
1026
|
+
]
|
|
1027
|
+
for event in recent_events:
|
|
1028
|
+
event["payload"] = _decode_json(event.pop("payload_json")) or {}
|
|
1029
|
+
priority_pending_events = _load_priority_pending_events(
|
|
1030
|
+
conn,
|
|
1031
|
+
recent_events,
|
|
1032
|
+
history_limit,
|
|
1033
|
+
)
|
|
1034
|
+
event_flow_counts = {
|
|
1035
|
+
"authorization_status": dict(
|
|
1036
|
+
sorted(Counter(event["authorization_status"] for event in recent_events).items())
|
|
1037
|
+
),
|
|
1038
|
+
"task_relationship": dict(
|
|
1039
|
+
sorted(
|
|
1040
|
+
Counter(
|
|
1041
|
+
event["task_relationship"] or "unattached"
|
|
1042
|
+
for event in recent_events
|
|
1043
|
+
).items()
|
|
1044
|
+
)
|
|
1045
|
+
),
|
|
1046
|
+
"authorized_unattached": sum(
|
|
1047
|
+
1
|
|
1048
|
+
for event in recent_events
|
|
1049
|
+
if _is_authorized_unattached_event(event)
|
|
1050
|
+
),
|
|
1051
|
+
"ignored_events": sum(
|
|
1052
|
+
1
|
|
1053
|
+
for event in recent_events
|
|
1054
|
+
if (event["authorization_status"] or "").startswith("ignored_")
|
|
1055
|
+
),
|
|
1056
|
+
}
|
|
1057
|
+
summary_counts = summarize.summarize_database(db_path)
|
|
1058
|
+
daemon_summary = daemon_state.latest_daemon_summary(conn)
|
|
1059
|
+
wakeup_summary = wakeup.summarize_wakeups(conn)
|
|
1060
|
+
recent_wakeups = wakeup.list_wakeups(conn, limit=history_limit)
|
|
1061
|
+
acceptance_metrics = usage.summarize_acceptance_metrics(conn)
|
|
1062
|
+
operator_alerts = _build_operator_alerts(
|
|
1063
|
+
operator_state_counts,
|
|
1064
|
+
event_flow_counts,
|
|
1065
|
+
summary_counts,
|
|
1066
|
+
)
|
|
1067
|
+
operator_next_steps = _build_operator_next_steps(
|
|
1068
|
+
recent_tasks,
|
|
1069
|
+
recent_events,
|
|
1070
|
+
priority_pending_events,
|
|
1071
|
+
)
|
|
1072
|
+
recent_runs = [
|
|
1073
|
+
dict(row)
|
|
1074
|
+
for row in conn.execute(
|
|
1075
|
+
"""
|
|
1076
|
+
SELECT run_id, status, started_at, finished_at, config_path, dry_run,
|
|
1077
|
+
summary_json, error_json
|
|
1078
|
+
FROM agent_runs
|
|
1079
|
+
ORDER BY started_at DESC, run_id DESC
|
|
1080
|
+
LIMIT ?
|
|
1081
|
+
""",
|
|
1082
|
+
(history_limit,),
|
|
1083
|
+
)
|
|
1084
|
+
]
|
|
1085
|
+
steps_by_run = {run["run_id"]: [] for run in recent_runs}
|
|
1086
|
+
if recent_runs:
|
|
1087
|
+
placeholders = ",".join("?" for _run in recent_runs)
|
|
1088
|
+
for row in conn.execute(
|
|
1089
|
+
f"""
|
|
1090
|
+
SELECT run_id, step_key, status, started_at, finished_at,
|
|
1091
|
+
output_json, error_json
|
|
1092
|
+
FROM run_steps
|
|
1093
|
+
WHERE run_id IN ({placeholders})
|
|
1094
|
+
""",
|
|
1095
|
+
[run["run_id"] for run in recent_runs],
|
|
1096
|
+
):
|
|
1097
|
+
step = dict(row)
|
|
1098
|
+
step["output"] = _decode_json(step.pop("output_json"))
|
|
1099
|
+
step["error"] = _decode_json(step.pop("error_json"))
|
|
1100
|
+
steps_by_run[step["run_id"]].append(step)
|
|
1101
|
+
repo_steps_by_run = {run["run_id"]: [] for run in recent_runs}
|
|
1102
|
+
if recent_runs and _table_exists(conn, "run_repo_steps"):
|
|
1103
|
+
placeholders = ",".join("?" for _run in recent_runs)
|
|
1104
|
+
for row in conn.execute(
|
|
1105
|
+
f"""
|
|
1106
|
+
SELECT rrs.run_id, rrs.repo_id, repos.full_name AS repo_full_name,
|
|
1107
|
+
rrs.step_key, rrs.status, rrs.started_at, rrs.finished_at,
|
|
1108
|
+
rrs.output_json, rrs.error_json
|
|
1109
|
+
FROM run_repo_steps rrs
|
|
1110
|
+
JOIN repos ON repos.repo_id = rrs.repo_id
|
|
1111
|
+
WHERE rrs.run_id IN ({placeholders})
|
|
1112
|
+
ORDER BY repos.full_name, rrs.step_key
|
|
1113
|
+
""",
|
|
1114
|
+
[run["run_id"] for run in recent_runs],
|
|
1115
|
+
):
|
|
1116
|
+
step = dict(row)
|
|
1117
|
+
step["output"] = _decode_json(step.pop("output_json"))
|
|
1118
|
+
step["error"] = _decode_json(step.pop("error_json"))
|
|
1119
|
+
repo_steps_by_run[step["run_id"]].append(step)
|
|
1120
|
+
order = {step: index for index, step in enumerate(RUN_STEP_ORDER)}
|
|
1121
|
+
repo_order = {step: index for index, step in enumerate(REPO_STEP_ORDER)}
|
|
1122
|
+
for run in recent_runs:
|
|
1123
|
+
run["summary"] = _decode_json(run.pop("summary_json"))
|
|
1124
|
+
run["error"] = _decode_json(run.pop("error_json"))
|
|
1125
|
+
run["steps"] = sorted(
|
|
1126
|
+
steps_by_run[run["run_id"]],
|
|
1127
|
+
key=lambda step: (order.get(step["step_key"], len(order)), step["step_key"]),
|
|
1128
|
+
)
|
|
1129
|
+
run["repo_steps"] = sorted(
|
|
1130
|
+
repo_steps_by_run.get(run["run_id"], []),
|
|
1131
|
+
key=lambda step: (
|
|
1132
|
+
step.get("repo_full_name") or "",
|
|
1133
|
+
repo_order.get(step["step_key"], len(repo_order)),
|
|
1134
|
+
step["step_key"],
|
|
1135
|
+
),
|
|
1136
|
+
)
|
|
1137
|
+
notification_center = _build_notification_center(
|
|
1138
|
+
operator_alerts,
|
|
1139
|
+
operator_next_steps,
|
|
1140
|
+
recent_notifications,
|
|
1141
|
+
recent_actions,
|
|
1142
|
+
daemon_summary,
|
|
1143
|
+
recent_runs,
|
|
1144
|
+
recent_tasks,
|
|
1145
|
+
)
|
|
1146
|
+
work_items = _build_work_items(recent_tasks)
|
|
1147
|
+
return {
|
|
1148
|
+
"summary": summary_counts,
|
|
1149
|
+
"repos": repos,
|
|
1150
|
+
"operator_state_counts": operator_state_counts,
|
|
1151
|
+
"recent_tasks": recent_tasks,
|
|
1152
|
+
"work_items": work_items,
|
|
1153
|
+
"recent_actions": recent_actions,
|
|
1154
|
+
"recent_notifications": recent_notifications,
|
|
1155
|
+
"notification_center": notification_center,
|
|
1156
|
+
"recent_worker_results": recent_worker_results,
|
|
1157
|
+
"recent_events": recent_events,
|
|
1158
|
+
"event_flow_counts": event_flow_counts,
|
|
1159
|
+
"operator_alerts": operator_alerts,
|
|
1160
|
+
"operator_next_steps": operator_next_steps,
|
|
1161
|
+
"daemon": daemon_summary,
|
|
1162
|
+
"wakeup_summary": wakeup_summary,
|
|
1163
|
+
"recent_wakeups": recent_wakeups,
|
|
1164
|
+
"acceptance_metrics": acceptance_metrics,
|
|
1165
|
+
"latest_loop": _load_latest_loop(db_path),
|
|
1166
|
+
"knowledge_review": _build_knowledge_review_data(conn),
|
|
1167
|
+
"used_skill_counts": dict(sorted(used_skill_counts.items())),
|
|
1168
|
+
"recent_runs": recent_runs,
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
|
|
1172
|
+
def _build_knowledge_review_data(conn, history_limit=20):
|
|
1173
|
+
proposal_repos = _knowledge_proposal_repos(conn)
|
|
1174
|
+
if not _table_exists(conn, "knowledge_candidates") or not _table_exists(conn, "runtime_knowledge"):
|
|
1175
|
+
return {
|
|
1176
|
+
"available": False,
|
|
1177
|
+
"submission_boundary": "local_runtime_knowledge_only",
|
|
1178
|
+
"counts": {"pending": 0, "approved": 0, "rejected": 0, "active": 0},
|
|
1179
|
+
"proposal_repos": proposal_repos,
|
|
1180
|
+
"pending_candidates": [],
|
|
1181
|
+
"recent_candidates": [],
|
|
1182
|
+
"active_knowledge": [],
|
|
1183
|
+
}
|
|
1184
|
+
candidate_counts = {
|
|
1185
|
+
row["status"]: row["count"]
|
|
1186
|
+
for row in conn.execute(
|
|
1187
|
+
"""
|
|
1188
|
+
SELECT status, COUNT(*) AS count
|
|
1189
|
+
FROM knowledge_candidates
|
|
1190
|
+
GROUP BY status
|
|
1191
|
+
"""
|
|
1192
|
+
)
|
|
1193
|
+
}
|
|
1194
|
+
active_count = conn.execute(
|
|
1195
|
+
"SELECT COUNT(*) FROM runtime_knowledge WHERE active = 1"
|
|
1196
|
+
).fetchone()[0]
|
|
1197
|
+
pending_candidates = [
|
|
1198
|
+
runtime_knowledge.show_candidate(conn, row["candidate_id"])
|
|
1199
|
+
for row in conn.execute(
|
|
1200
|
+
"""
|
|
1201
|
+
SELECT candidate_id
|
|
1202
|
+
FROM knowledge_candidates
|
|
1203
|
+
WHERE status = 'pending'
|
|
1204
|
+
ORDER BY created_at DESC, candidate_id
|
|
1205
|
+
LIMIT ?
|
|
1206
|
+
""",
|
|
1207
|
+
(history_limit,),
|
|
1208
|
+
)
|
|
1209
|
+
]
|
|
1210
|
+
recent_candidates = runtime_knowledge.list_candidates(conn)[:history_limit]
|
|
1211
|
+
active_knowledge = [
|
|
1212
|
+
{
|
|
1213
|
+
"knowledge_id": row["knowledge_id"],
|
|
1214
|
+
"candidate_id": row["candidate_id"],
|
|
1215
|
+
"repo_id": row["repo_id"],
|
|
1216
|
+
"scope_type": row["scope_type"],
|
|
1217
|
+
"scope_value": row["scope_value"],
|
|
1218
|
+
"title": row["title"],
|
|
1219
|
+
"prompt_text": row["prompt_text"],
|
|
1220
|
+
"approved_by": row["approved_by"],
|
|
1221
|
+
"approved_at": row["approved_at"],
|
|
1222
|
+
}
|
|
1223
|
+
for row in conn.execute(
|
|
1224
|
+
"""
|
|
1225
|
+
SELECT knowledge_id, candidate_id, repo_id, scope_type, scope_value,
|
|
1226
|
+
title, prompt_text, approved_by, approved_at
|
|
1227
|
+
FROM runtime_knowledge
|
|
1228
|
+
WHERE active = 1
|
|
1229
|
+
ORDER BY approved_at DESC, knowledge_id
|
|
1230
|
+
LIMIT ?
|
|
1231
|
+
""",
|
|
1232
|
+
(history_limit,),
|
|
1233
|
+
)
|
|
1234
|
+
]
|
|
1235
|
+
return {
|
|
1236
|
+
"available": True,
|
|
1237
|
+
"submission_boundary": "local_runtime_knowledge_only",
|
|
1238
|
+
"counts": {
|
|
1239
|
+
"pending": candidate_counts.get("pending", 0),
|
|
1240
|
+
"approved": candidate_counts.get("approved", 0),
|
|
1241
|
+
"rejected": candidate_counts.get("rejected", 0),
|
|
1242
|
+
"active": active_count,
|
|
1243
|
+
},
|
|
1244
|
+
"proposal_repos": proposal_repos,
|
|
1245
|
+
"pending_candidates": [item for item in pending_candidates if item],
|
|
1246
|
+
"recent_candidates": recent_candidates,
|
|
1247
|
+
"active_knowledge": active_knowledge,
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
|
|
1251
|
+
def _knowledge_proposal_repos(conn):
|
|
1252
|
+
if not _table_exists(conn, "repos"):
|
|
1253
|
+
return []
|
|
1254
|
+
memory_counts = {}
|
|
1255
|
+
if _table_exists(conn, "project_memory_entries"):
|
|
1256
|
+
memory_counts = {
|
|
1257
|
+
row["repo_id"]: row["count"]
|
|
1258
|
+
for row in conn.execute(
|
|
1259
|
+
"""
|
|
1260
|
+
SELECT repo_id, COUNT(*) AS count
|
|
1261
|
+
FROM project_memory_entries
|
|
1262
|
+
GROUP BY repo_id
|
|
1263
|
+
"""
|
|
1264
|
+
)
|
|
1265
|
+
}
|
|
1266
|
+
return [
|
|
1267
|
+
{
|
|
1268
|
+
"repo_id": row["repo_id"],
|
|
1269
|
+
"full_name": row["full_name"],
|
|
1270
|
+
"memory_count": memory_counts.get(row["repo_id"], 0),
|
|
1271
|
+
}
|
|
1272
|
+
for row in conn.execute(
|
|
1273
|
+
"""
|
|
1274
|
+
SELECT repo_id, full_name
|
|
1275
|
+
FROM repos
|
|
1276
|
+
ORDER BY full_name, repo_id
|
|
1277
|
+
"""
|
|
1278
|
+
)
|
|
1279
|
+
]
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
def _knowledge_tables_available(conn):
|
|
1283
|
+
return all(
|
|
1284
|
+
_table_exists(conn, table_name)
|
|
1285
|
+
for table_name in ["knowledge_candidates", "runtime_knowledge", "project_memory_entries"]
|
|
1286
|
+
)
|
|
1287
|
+
|
|
1288
|
+
|
|
1289
|
+
def load_artifact_preview(db_path, task_id, artifact_type, max_bytes=65536):
|
|
1290
|
+
if not task_id or not artifact_type:
|
|
1291
|
+
return None
|
|
1292
|
+
with closing(sqlite3.connect(db_path)) as conn, conn:
|
|
1293
|
+
conn.row_factory = sqlite3.Row
|
|
1294
|
+
row = conn.execute(
|
|
1295
|
+
"""
|
|
1296
|
+
SELECT artifact_type, path, bytes
|
|
1297
|
+
FROM artifacts
|
|
1298
|
+
WHERE task_id = ? AND artifact_type = ?
|
|
1299
|
+
ORDER BY created_at DESC, artifact_id DESC
|
|
1300
|
+
LIMIT 1
|
|
1301
|
+
""",
|
|
1302
|
+
(task_id, artifact_type),
|
|
1303
|
+
).fetchone()
|
|
1304
|
+
if not row:
|
|
1305
|
+
return None
|
|
1306
|
+
registered_path = str(row["path"])
|
|
1307
|
+
path = Path(registered_path).expanduser().resolve()
|
|
1308
|
+
if not path.is_file():
|
|
1309
|
+
return {
|
|
1310
|
+
"task_id": task_id,
|
|
1311
|
+
"artifact_type": artifact_type,
|
|
1312
|
+
"path": registered_path,
|
|
1313
|
+
"content": "",
|
|
1314
|
+
"truncated": False,
|
|
1315
|
+
"missing": True,
|
|
1316
|
+
}
|
|
1317
|
+
size = path.stat().st_size
|
|
1318
|
+
truncated = size > max_bytes
|
|
1319
|
+
with path.open("rb") as fh:
|
|
1320
|
+
if truncated:
|
|
1321
|
+
fh.seek(-max_bytes, 2)
|
|
1322
|
+
content = fh.read(max_bytes).decode("utf-8", errors="replace")
|
|
1323
|
+
return {
|
|
1324
|
+
"task_id": task_id,
|
|
1325
|
+
"artifact_type": artifact_type,
|
|
1326
|
+
"path": registered_path,
|
|
1327
|
+
"bytes": row["bytes"],
|
|
1328
|
+
"content": content,
|
|
1329
|
+
"truncated": truncated,
|
|
1330
|
+
"missing": False,
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
|
|
1334
|
+
def render_artifact_preview_text(preview):
|
|
1335
|
+
lines = [
|
|
1336
|
+
f"task_id={preview['task_id']}",
|
|
1337
|
+
f"artifact_type={preview['artifact_type']}",
|
|
1338
|
+
f"path={preview['path']}",
|
|
1339
|
+
f"truncated={str(bool(preview.get('truncated'))).lower()}",
|
|
1340
|
+
"",
|
|
1341
|
+
]
|
|
1342
|
+
if preview.get("missing"):
|
|
1343
|
+
lines.append("artifact file not found")
|
|
1344
|
+
else:
|
|
1345
|
+
lines.append(preview.get("content") or "")
|
|
1346
|
+
return "\n".join(lines).encode("utf-8")
|
|
1347
|
+
|
|
1348
|
+
|
|
1349
|
+
def render_dashboard_html():
|
|
1350
|
+
return r"""<!doctype html>
|
|
1351
|
+
<html lang="en">
|
|
1352
|
+
<head>
|
|
1353
|
+
<meta charset="utf-8">
|
|
1354
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1355
|
+
<title>Robert Operations</title>
|
|
1356
|
+
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Ccircle cx='32' cy='32' r='30' fill='%2324292f'/%3E%3Ctext x='32' y='40' text-anchor='middle' font-family='ui-sans-serif' font-size='24' font-weight='700' fill='%23f0f6fc'%3ER%3C/text%3E%3C/svg%3E">
|
|
1357
|
+
<script>
|
|
1358
|
+
(function () {
|
|
1359
|
+
const savedTheme = localStorage.getItem('robertWorkbenchTheme') || 'system';
|
|
1360
|
+
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
|
|
1361
|
+
document.documentElement.dataset.themeChoice = savedTheme;
|
|
1362
|
+
document.documentElement.dataset.theme = savedTheme === 'system'
|
|
1363
|
+
? (prefersDark ? 'dark' : 'light')
|
|
1364
|
+
: savedTheme;
|
|
1365
|
+
document.documentElement.dataset.colorMode = document.documentElement.dataset.theme;
|
|
1366
|
+
})();
|
|
1367
|
+
</script>
|
|
1368
|
+
<style>
|
|
1369
|
+
:root {
|
|
1370
|
+
color-scheme: light;
|
|
1371
|
+
--page: #f6f8fa;
|
|
1372
|
+
--surface: #ffffff;
|
|
1373
|
+
--surface-raised: #fbfbfc;
|
|
1374
|
+
--surface-muted: #f0f2f5;
|
|
1375
|
+
--text: #1f2328;
|
|
1376
|
+
--muted: #656d76;
|
|
1377
|
+
--line: #d8dee4;
|
|
1378
|
+
--line-soft: #eaedf0;
|
|
1379
|
+
--accent: #0969da;
|
|
1380
|
+
--accent-strong: #0550ae;
|
|
1381
|
+
--critical: #cf222e;
|
|
1382
|
+
--critical-soft: #ffebe9;
|
|
1383
|
+
--warning: #9a6700;
|
|
1384
|
+
--warning-soft: #fff8c5;
|
|
1385
|
+
--info: #0969da;
|
|
1386
|
+
--info-soft: #ddf4ff;
|
|
1387
|
+
--ok: #1a7f37;
|
|
1388
|
+
--ok-soft: #dafbe1;
|
|
1389
|
+
--shadow: 0 18px 44px rgba(31, 35, 40, 0.08);
|
|
1390
|
+
}
|
|
1391
|
+
html[data-theme="dark"] {
|
|
1392
|
+
color-scheme: dark;
|
|
1393
|
+
--page: #0d1117;
|
|
1394
|
+
--surface: #161b22;
|
|
1395
|
+
--surface-raised: #1c2128;
|
|
1396
|
+
--surface-muted: #21262d;
|
|
1397
|
+
--text: #e6edf3;
|
|
1398
|
+
--muted: #8b949e;
|
|
1399
|
+
--line: #30363d;
|
|
1400
|
+
--line-soft: #252b33;
|
|
1401
|
+
--accent: #58a6ff;
|
|
1402
|
+
--accent-strong: #79c0ff;
|
|
1403
|
+
--critical: #ff7b72;
|
|
1404
|
+
--critical-soft: #3d1e20;
|
|
1405
|
+
--warning: #d29922;
|
|
1406
|
+
--warning-soft: #342a14;
|
|
1407
|
+
--info: #79c0ff;
|
|
1408
|
+
--info-soft: #102a43;
|
|
1409
|
+
--ok: #56d364;
|
|
1410
|
+
--ok-soft: #14321f;
|
|
1411
|
+
--shadow: 0 20px 52px rgba(0, 0, 0, 0.32);
|
|
1412
|
+
}
|
|
1413
|
+
* { box-sizing: border-box; }
|
|
1414
|
+
body {
|
|
1415
|
+
margin: 0;
|
|
1416
|
+
min-height: 100dvh;
|
|
1417
|
+
background: var(--page);
|
|
1418
|
+
color: var(--text);
|
|
1419
|
+
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
1420
|
+
letter-spacing: 0;
|
|
1421
|
+
}
|
|
1422
|
+
a { color: inherit; }
|
|
1423
|
+
button, input, select, textarea { font: inherit; color: var(--text); }
|
|
1424
|
+
button:focus-visible, a:focus-visible, select:focus-visible, input:focus-visible, textarea:focus-visible {
|
|
1425
|
+
outline: 3px solid color-mix(in srgb, var(--accent) 45%, transparent);
|
|
1426
|
+
outline-offset: 2px;
|
|
1427
|
+
}
|
|
1428
|
+
.mission-shell {
|
|
1429
|
+
display: grid;
|
|
1430
|
+
grid-template-columns: 218px minmax(0, 1fr);
|
|
1431
|
+
grid-template-rows: auto minmax(0, 1fr);
|
|
1432
|
+
min-height: 100dvh;
|
|
1433
|
+
}
|
|
1434
|
+
.work-filter-bar {
|
|
1435
|
+
display: grid;
|
|
1436
|
+
grid-template-columns: minmax(220px, 1fr) minmax(180px, 280px);
|
|
1437
|
+
gap: 8px;
|
|
1438
|
+
padding: 10px 12px;
|
|
1439
|
+
border-bottom: 1px solid var(--line-soft);
|
|
1440
|
+
background: var(--surface);
|
|
1441
|
+
}
|
|
1442
|
+
.work-filter-bar label { display: block; min-width: 0; }
|
|
1443
|
+
.work-filter-bar .control-select { width: 100%; min-height: 34px; }
|
|
1444
|
+
.search-input {
|
|
1445
|
+
width: 100%;
|
|
1446
|
+
min-height: 34px;
|
|
1447
|
+
border: 1px solid var(--line);
|
|
1448
|
+
border-radius: 8px;
|
|
1449
|
+
background: var(--surface-raised);
|
|
1450
|
+
color: var(--text);
|
|
1451
|
+
padding: 7px 12px;
|
|
1452
|
+
box-shadow: inset 0 1px 0 rgba(31, 35, 40, 0.02);
|
|
1453
|
+
}
|
|
1454
|
+
.search-input::placeholder { color: var(--muted); }
|
|
1455
|
+
.control-select, .button, .control-pill {
|
|
1456
|
+
min-height: 32px;
|
|
1457
|
+
border: 1px solid var(--line);
|
|
1458
|
+
border-radius: 7px;
|
|
1459
|
+
background: var(--surface);
|
|
1460
|
+
color: var(--text);
|
|
1461
|
+
padding: 6px 9px;
|
|
1462
|
+
text-decoration: none;
|
|
1463
|
+
white-space: nowrap;
|
|
1464
|
+
font-size: 12px;
|
|
1465
|
+
}
|
|
1466
|
+
.button { cursor: pointer; }
|
|
1467
|
+
.button.primary { border-color: color-mix(in srgb, var(--accent) 45%, var(--line)); background: var(--surface); color: var(--accent-strong); font-weight: 650; }
|
|
1468
|
+
html[data-theme="dark"] .button.primary { color: var(--accent-strong); }
|
|
1469
|
+
.button:hover, .control-select:hover { border-color: color-mix(in srgb, var(--accent) 50%, var(--line)); }
|
|
1470
|
+
.button:active, .nav-button:active, .inline-button:active, .primary-button:active, .danger-button:active { transform: translateY(1px); }
|
|
1471
|
+
.refresh-control {
|
|
1472
|
+
display: inline-flex;
|
|
1473
|
+
align-items: center;
|
|
1474
|
+
gap: 7px;
|
|
1475
|
+
min-height: 32px;
|
|
1476
|
+
border: 1px solid var(--line);
|
|
1477
|
+
border-radius: 7px;
|
|
1478
|
+
background: var(--surface);
|
|
1479
|
+
padding: 4px 6px;
|
|
1480
|
+
white-space: nowrap;
|
|
1481
|
+
}
|
|
1482
|
+
.refresh-control label { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; }
|
|
1483
|
+
.refresh-control select { min-height: 24px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface-raised); padding: 2px 5px; font-size: 12px; }
|
|
1484
|
+
.mission-nav {
|
|
1485
|
+
position: sticky;
|
|
1486
|
+
top: 64px;
|
|
1487
|
+
align-self: start;
|
|
1488
|
+
height: calc(100dvh - 64px);
|
|
1489
|
+
z-index: 19;
|
|
1490
|
+
display: grid;
|
|
1491
|
+
align-content: start;
|
|
1492
|
+
gap: 4px;
|
|
1493
|
+
padding: 14px 10px;
|
|
1494
|
+
border-right: 1px solid var(--line);
|
|
1495
|
+
background: var(--surface);
|
|
1496
|
+
overflow-y: auto;
|
|
1497
|
+
}
|
|
1498
|
+
.nav-button {
|
|
1499
|
+
display: flex;
|
|
1500
|
+
align-items: center;
|
|
1501
|
+
gap: 8px;
|
|
1502
|
+
justify-content: flex-start;
|
|
1503
|
+
min-height: 34px;
|
|
1504
|
+
border: 1px solid transparent;
|
|
1505
|
+
border-radius: 7px;
|
|
1506
|
+
background: transparent;
|
|
1507
|
+
color: var(--muted);
|
|
1508
|
+
padding: 7px 10px;
|
|
1509
|
+
white-space: nowrap;
|
|
1510
|
+
cursor: pointer;
|
|
1511
|
+
font-size: 13px;
|
|
1512
|
+
}
|
|
1513
|
+
.nav-button:hover { color: var(--text); background: var(--surface-muted); }
|
|
1514
|
+
.nav-button.active {
|
|
1515
|
+
color: var(--text);
|
|
1516
|
+
border-color: var(--line);
|
|
1517
|
+
background: var(--surface-raised);
|
|
1518
|
+
font-weight: 700;
|
|
1519
|
+
}
|
|
1520
|
+
.nav-icon {
|
|
1521
|
+
display: inline-grid;
|
|
1522
|
+
place-items: center;
|
|
1523
|
+
width: 16px;
|
|
1524
|
+
color: var(--muted);
|
|
1525
|
+
font-size: 12px;
|
|
1526
|
+
font-weight: 700;
|
|
1527
|
+
line-height: 1;
|
|
1528
|
+
}
|
|
1529
|
+
.nav-label { flex: 1; text-align: left; }
|
|
1530
|
+
.nav-count {
|
|
1531
|
+
min-width: 20px;
|
|
1532
|
+
padding: 1px 6px;
|
|
1533
|
+
border: 1px solid var(--line);
|
|
1534
|
+
border-radius: 999px;
|
|
1535
|
+
background: var(--surface-muted);
|
|
1536
|
+
color: var(--text);
|
|
1537
|
+
font-size: 11px;
|
|
1538
|
+
font-variant-numeric: tabular-nums;
|
|
1539
|
+
font-weight: 650;
|
|
1540
|
+
text-align: center;
|
|
1541
|
+
}
|
|
1542
|
+
.nav-button.active .nav-count { border-color: color-mix(in srgb, var(--accent) 32%, var(--line)); color: var(--accent-strong); background: var(--info-soft); }
|
|
1543
|
+
.mission-workspace { min-width: 0; padding: 16px 18px 42px; }
|
|
1544
|
+
.view-panel[hidden] { display: none; }
|
|
1545
|
+
.view-panel { display: grid; gap: 12px; }
|
|
1546
|
+
.command-header {
|
|
1547
|
+
display: flex;
|
|
1548
|
+
justify-content: space-between;
|
|
1549
|
+
gap: 16px;
|
|
1550
|
+
align-items: end;
|
|
1551
|
+
padding: 2px 0 4px;
|
|
1552
|
+
}
|
|
1553
|
+
.command-title h1 { margin: 0; font-size: 22px; line-height: 1.2; letter-spacing: 0; }
|
|
1554
|
+
.command-title p { margin: 5px 0 0; color: var(--muted); font-size: 13px; line-height: 1.35; }
|
|
1555
|
+
.system-card { display: grid; gap: 10px; align-content: start; }
|
|
1556
|
+
.system-card h2, .panel-head h2 { margin: 0; font-size: 13px; line-height: 1.25; }
|
|
1557
|
+
.status-stack { display: grid; gap: 8px; }
|
|
1558
|
+
.status-stack.list { gap: 0; }
|
|
1559
|
+
.status-stack.list .row-between { padding: 10px 12px; border-bottom: 1px solid var(--line-soft); }
|
|
1560
|
+
.status-stack.list .row-between:last-child { border-bottom: 0; }
|
|
1561
|
+
.health-grid {
|
|
1562
|
+
display: grid;
|
|
1563
|
+
grid-template-columns: repeat(5, minmax(0, 1fr));
|
|
1564
|
+
border: 1px solid var(--line);
|
|
1565
|
+
border-radius: 8px;
|
|
1566
|
+
background: var(--surface);
|
|
1567
|
+
overflow: hidden;
|
|
1568
|
+
}
|
|
1569
|
+
.health-card {
|
|
1570
|
+
display: grid;
|
|
1571
|
+
grid-template-columns: minmax(0, 1fr) auto;
|
|
1572
|
+
gap: 6px 10px;
|
|
1573
|
+
align-items: center;
|
|
1574
|
+
min-height: 56px;
|
|
1575
|
+
padding: 10px 12px;
|
|
1576
|
+
border-right: 1px solid var(--line-soft);
|
|
1577
|
+
background: var(--surface);
|
|
1578
|
+
}
|
|
1579
|
+
.health-card:last-child { border-right: 0; }
|
|
1580
|
+
.health-card strong { justify-self: end; font-size: 18px; line-height: 1; font-variant-numeric: tabular-nums; }
|
|
1581
|
+
.health-card span { color: var(--muted); font-size: 12px; }
|
|
1582
|
+
.health-card .badge { justify-self: start; }
|
|
1583
|
+
.command-grid {
|
|
1584
|
+
display: grid;
|
|
1585
|
+
grid-template-columns: minmax(0, 1fr) 390px;
|
|
1586
|
+
grid-template-areas:
|
|
1587
|
+
"inbox inspector"
|
|
1588
|
+
"work inspector"
|
|
1589
|
+
"activity inspector";
|
|
1590
|
+
gap: 12px;
|
|
1591
|
+
align-items: start;
|
|
1592
|
+
}
|
|
1593
|
+
.operator-inbox { grid-area: inbox; }
|
|
1594
|
+
.active-workstreams { grid-area: work; }
|
|
1595
|
+
.activity-log { grid-area: activity; }
|
|
1596
|
+
.command-inspector { grid-area: inspector; position: sticky; top: 102px; }
|
|
1597
|
+
.grid-2 { display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(340px, 0.9fr); gap: 12px; align-items: start; }
|
|
1598
|
+
.work-grid { display: grid; grid-template-columns: minmax(260px, 340px) minmax(260px, 340px) minmax(0, 1fr); gap: 12px; align-items: start; }
|
|
1599
|
+
.panel { min-width: 0; overflow: hidden; }
|
|
1600
|
+
.panel {
|
|
1601
|
+
border: 1px solid var(--line);
|
|
1602
|
+
border-radius: 8px;
|
|
1603
|
+
background: var(--surface);
|
|
1604
|
+
box-shadow: 0 1px 0 rgba(31, 35, 40, 0.03);
|
|
1605
|
+
}
|
|
1606
|
+
.panel-head {
|
|
1607
|
+
display: flex;
|
|
1608
|
+
align-items: center;
|
|
1609
|
+
justify-content: space-between;
|
|
1610
|
+
gap: 12px;
|
|
1611
|
+
padding: 10px 12px;
|
|
1612
|
+
border-bottom: 1px solid var(--line);
|
|
1613
|
+
background: var(--surface-raised);
|
|
1614
|
+
}
|
|
1615
|
+
.panel-head span { color: var(--muted); font-size: 12px; }
|
|
1616
|
+
.list { display: grid; gap: 0; padding: 0; }
|
|
1617
|
+
.row-card, .task-card, .timeline-row, .notification-card, .artifact-row {
|
|
1618
|
+
border: 0;
|
|
1619
|
+
border-bottom: 1px solid var(--line-soft);
|
|
1620
|
+
border-radius: 0;
|
|
1621
|
+
background: var(--surface);
|
|
1622
|
+
padding: 10px 12px;
|
|
1623
|
+
line-height: 1.4;
|
|
1624
|
+
min-width: 0;
|
|
1625
|
+
}
|
|
1626
|
+
.row-card:last-child, .task-card:last-child, .timeline-row:last-child, .notification-card:last-child, .artifact-row:last-child { border-bottom: 0; }
|
|
1627
|
+
.task-card { width: 100%; text-align: left; cursor: pointer; transition: border-color 120ms ease, box-shadow 120ms ease, transform 120ms ease; }
|
|
1628
|
+
.task-card:hover, .task-card.active { background: var(--surface-raised); box-shadow: inset 3px 0 0 var(--accent); transform: none; }
|
|
1629
|
+
.row-between, .row-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
|
|
1630
|
+
.item-title { min-width: 0; font-weight: 720; overflow-wrap: anywhere; }
|
|
1631
|
+
.issue-row {
|
|
1632
|
+
display: grid;
|
|
1633
|
+
grid-template-columns: 20px minmax(0, 1fr) auto;
|
|
1634
|
+
gap: 10px;
|
|
1635
|
+
align-items: start;
|
|
1636
|
+
}
|
|
1637
|
+
.state-icon {
|
|
1638
|
+
display: inline-grid;
|
|
1639
|
+
place-items: center;
|
|
1640
|
+
width: 16px;
|
|
1641
|
+
height: 16px;
|
|
1642
|
+
margin-top: 2px;
|
|
1643
|
+
border: 1.5px solid var(--muted);
|
|
1644
|
+
border-radius: 999px;
|
|
1645
|
+
color: var(--muted);
|
|
1646
|
+
font-size: 10px;
|
|
1647
|
+
line-height: 1;
|
|
1648
|
+
font-weight: 800;
|
|
1649
|
+
}
|
|
1650
|
+
.state-icon.critical { border-color: var(--critical); color: var(--critical); }
|
|
1651
|
+
.state-icon.warning { border-color: var(--warning); color: var(--warning); }
|
|
1652
|
+
.state-icon.info { border-color: var(--info); color: var(--info); }
|
|
1653
|
+
.state-icon.ok { border-color: var(--ok); color: var(--ok); }
|
|
1654
|
+
.issue-meta {
|
|
1655
|
+
display: flex;
|
|
1656
|
+
flex-wrap: wrap;
|
|
1657
|
+
gap: 7px;
|
|
1658
|
+
margin-top: 4px;
|
|
1659
|
+
color: var(--muted);
|
|
1660
|
+
font-size: 12px;
|
|
1661
|
+
line-height: 1.4;
|
|
1662
|
+
}
|
|
1663
|
+
.issue-labels {
|
|
1664
|
+
display: flex;
|
|
1665
|
+
flex-wrap: wrap;
|
|
1666
|
+
justify-content: flex-end;
|
|
1667
|
+
gap: 6px;
|
|
1668
|
+
}
|
|
1669
|
+
.work-row {
|
|
1670
|
+
display: grid;
|
|
1671
|
+
grid-template-columns: minmax(180px, 1.2fr) minmax(130px, 0.8fr) minmax(130px, 0.8fr) auto;
|
|
1672
|
+
gap: 12px;
|
|
1673
|
+
align-items: center;
|
|
1674
|
+
}
|
|
1675
|
+
.work-row .action-row { justify-content: flex-end; margin-top: 0; }
|
|
1676
|
+
.inbox-row {
|
|
1677
|
+
display: grid;
|
|
1678
|
+
grid-template-columns: minmax(0, 1fr) auto;
|
|
1679
|
+
gap: 8px 12px;
|
|
1680
|
+
align-items: start;
|
|
1681
|
+
}
|
|
1682
|
+
.inbox-row .timeline-meta { grid-column: 1 / -1; }
|
|
1683
|
+
.muted { color: var(--muted); }
|
|
1684
|
+
.small { font-size: 12px; line-height: 1.4; }
|
|
1685
|
+
.empty, .error { padding: 18px; color: var(--muted); line-height: 1.45; }
|
|
1686
|
+
.error { color: var(--critical); background: var(--critical-soft); border: 1px solid color-mix(in srgb, var(--critical) 34%, var(--line)); border-radius: 8px; margin: 14px; }
|
|
1687
|
+
.badge {
|
|
1688
|
+
display: inline-flex;
|
|
1689
|
+
align-items: center;
|
|
1690
|
+
min-height: 20px;
|
|
1691
|
+
padding: 2px 7px;
|
|
1692
|
+
border: 1px solid var(--line);
|
|
1693
|
+
border-radius: 999px;
|
|
1694
|
+
background: var(--surface-muted);
|
|
1695
|
+
color: var(--text);
|
|
1696
|
+
font-size: 11px;
|
|
1697
|
+
white-space: nowrap;
|
|
1698
|
+
max-width: 100%;
|
|
1699
|
+
}
|
|
1700
|
+
.badge.critical { border-color: color-mix(in srgb, var(--critical) 34%, var(--line)); background: var(--critical-soft); color: var(--critical); }
|
|
1701
|
+
.badge.warning { border-color: color-mix(in srgb, var(--warning) 34%, var(--line)); background: var(--warning-soft); color: var(--warning); }
|
|
1702
|
+
.badge.info { border-color: color-mix(in srgb, var(--info) 30%, var(--line)); background: var(--info-soft); color: var(--info); }
|
|
1703
|
+
.badge.ok { border-color: color-mix(in srgb, var(--ok) 30%, var(--line)); background: var(--ok-soft); color: var(--ok); }
|
|
1704
|
+
.row-card.critical, .notification-card.critical, .timeline-row.critical { box-shadow: inset 3px 0 0 var(--critical); }
|
|
1705
|
+
.row-card.warning, .notification-card.warning, .timeline-row.warning { box-shadow: inset 3px 0 0 var(--warning); }
|
|
1706
|
+
.row-card.info, .notification-card.info, .timeline-row.info { box-shadow: inset 3px 0 0 var(--info); }
|
|
1707
|
+
.row-card.ok, .notification-card.ok, .timeline-row.ok { box-shadow: inset 3px 0 0 var(--ok); }
|
|
1708
|
+
.external-link { color: var(--accent-strong); text-decoration-thickness: 1px; text-underline-offset: 2px; overflow-wrap: anywhere; }
|
|
1709
|
+
.meta-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; padding: 12px; }
|
|
1710
|
+
.field { min-width: 0; border: 1px solid var(--line-soft); border-radius: 7px; padding: 8px; background: var(--surface-raised); }
|
|
1711
|
+
.field label { display: block; margin-bottom: 5px; color: var(--muted); font-size: 12px; }
|
|
1712
|
+
.field div, .field a { overflow-wrap: anywhere; font-size: 13px; line-height: 1.4; }
|
|
1713
|
+
.detail-title { padding: 12px 12px 0; }
|
|
1714
|
+
.detail-title h3 { margin: 0; font-size: 17px; line-height: 1.2; overflow-wrap: anywhere; }
|
|
1715
|
+
.detail-title p { margin: 6px 0 0; color: var(--muted); }
|
|
1716
|
+
.detail-actions { display: flex; flex-wrap: wrap; gap: 8px; padding: 10px 12px 0; }
|
|
1717
|
+
.subhead { margin: 14px 12px 7px; color: var(--muted); font-size: 12px; font-weight: 700; }
|
|
1718
|
+
.json-chip { display: inline-flex; margin: 4px 6px 0 0; padding: 4px 7px; border: 1px solid var(--line); border-radius: 999px; background: var(--surface-muted); color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
|
|
1719
|
+
.metadata { margin-top: 8px; }
|
|
1720
|
+
.metadata summary { cursor: pointer; color: var(--muted); font-size: 12px; }
|
|
1721
|
+
pre {
|
|
1722
|
+
margin: 8px 0 0;
|
|
1723
|
+
max-height: 260px;
|
|
1724
|
+
overflow: auto;
|
|
1725
|
+
border-radius: 7px;
|
|
1726
|
+
border: 1px solid var(--line);
|
|
1727
|
+
background: #111827;
|
|
1728
|
+
color: #e5e7eb;
|
|
1729
|
+
padding: 10px;
|
|
1730
|
+
font-size: 12px;
|
|
1731
|
+
line-height: 1.45;
|
|
1732
|
+
white-space: pre-wrap;
|
|
1733
|
+
overflow-wrap: anywhere;
|
|
1734
|
+
}
|
|
1735
|
+
html[data-theme="dark"] pre { background: #0b1220; color: #dbeafe; }
|
|
1736
|
+
.artifact-preview {
|
|
1737
|
+
min-height: 100%;
|
|
1738
|
+
overflow: auto;
|
|
1739
|
+
border-radius: 7px;
|
|
1740
|
+
border: 1px solid #d0d7de;
|
|
1741
|
+
background: #ffffff;
|
|
1742
|
+
color: #24292f;
|
|
1743
|
+
padding: 16px;
|
|
1744
|
+
font-size: 14px;
|
|
1745
|
+
line-height: 1.55;
|
|
1746
|
+
}
|
|
1747
|
+
.artifact-preview.placeholder { color: #57606a; }
|
|
1748
|
+
.artifact-preview.error { color: #cf222e; background: #ffebe9; }
|
|
1749
|
+
.preview-scrim {
|
|
1750
|
+
position: fixed;
|
|
1751
|
+
inset: 0;
|
|
1752
|
+
z-index: 50;
|
|
1753
|
+
display: none;
|
|
1754
|
+
background: rgba(15, 23, 42, 0.38);
|
|
1755
|
+
}
|
|
1756
|
+
.preview-scrim.open { display: block; }
|
|
1757
|
+
.artifact-drawer {
|
|
1758
|
+
position: fixed;
|
|
1759
|
+
top: 0;
|
|
1760
|
+
right: 0;
|
|
1761
|
+
bottom: 0;
|
|
1762
|
+
z-index: 60;
|
|
1763
|
+
display: flex;
|
|
1764
|
+
width: min(760px, calc(100vw - 32px));
|
|
1765
|
+
max-width: 100vw;
|
|
1766
|
+
flex-direction: column;
|
|
1767
|
+
border-left: 1px solid var(--line);
|
|
1768
|
+
background: var(--surface);
|
|
1769
|
+
box-shadow: -22px 0 48px rgba(15, 23, 42, 0.18);
|
|
1770
|
+
transform: translateX(100%);
|
|
1771
|
+
}
|
|
1772
|
+
.artifact-drawer.open { transform: translateX(0); }
|
|
1773
|
+
.artifact-drawer-head {
|
|
1774
|
+
display: flex;
|
|
1775
|
+
align-items: center;
|
|
1776
|
+
justify-content: space-between;
|
|
1777
|
+
gap: 12px;
|
|
1778
|
+
padding: 12px 14px;
|
|
1779
|
+
border-bottom: 1px solid var(--line);
|
|
1780
|
+
background: var(--surface-raised);
|
|
1781
|
+
}
|
|
1782
|
+
.artifact-drawer-head h2 {
|
|
1783
|
+
margin: 0;
|
|
1784
|
+
min-width: 0;
|
|
1785
|
+
font-size: 15px;
|
|
1786
|
+
line-height: 1.3;
|
|
1787
|
+
overflow-wrap: anywhere;
|
|
1788
|
+
}
|
|
1789
|
+
.artifact-drawer-body {
|
|
1790
|
+
min-height: 0;
|
|
1791
|
+
flex: 1;
|
|
1792
|
+
overflow: auto;
|
|
1793
|
+
padding: 14px;
|
|
1794
|
+
}
|
|
1795
|
+
body.preview-open { overflow: hidden; }
|
|
1796
|
+
.artifact-preview-header {
|
|
1797
|
+
display: flex;
|
|
1798
|
+
flex-wrap: wrap;
|
|
1799
|
+
gap: 6px;
|
|
1800
|
+
margin-bottom: 14px;
|
|
1801
|
+
padding-bottom: 12px;
|
|
1802
|
+
border-bottom: 1px solid #d8dee4;
|
|
1803
|
+
color: #57606a;
|
|
1804
|
+
font-size: 12px;
|
|
1805
|
+
}
|
|
1806
|
+
.artifact-preview-header span {
|
|
1807
|
+
max-width: 100%;
|
|
1808
|
+
padding: 2px 7px;
|
|
1809
|
+
border: 1px solid #d0d7de;
|
|
1810
|
+
border-radius: 999px;
|
|
1811
|
+
background: #f6f8fa;
|
|
1812
|
+
overflow-wrap: anywhere;
|
|
1813
|
+
}
|
|
1814
|
+
.artifact-preview h1, .artifact-preview h2, .artifact-preview h3 {
|
|
1815
|
+
margin: 18px 0 10px;
|
|
1816
|
+
color: #24292f;
|
|
1817
|
+
line-height: 1.25;
|
|
1818
|
+
border-bottom: 1px solid #d8dee4;
|
|
1819
|
+
padding-bottom: 0.3em;
|
|
1820
|
+
}
|
|
1821
|
+
.artifact-preview h1:first-child, .artifact-preview h2:first-child, .artifact-preview h3:first-child { margin-top: 0; }
|
|
1822
|
+
.artifact-preview p, .artifact-preview ul, .artifact-preview blockquote { margin: 0 0 12px; }
|
|
1823
|
+
.artifact-preview ul { padding-left: 24px; }
|
|
1824
|
+
.artifact-preview blockquote {
|
|
1825
|
+
padding-left: 12px;
|
|
1826
|
+
border-left: 4px solid #d0d7de;
|
|
1827
|
+
color: #57606a;
|
|
1828
|
+
}
|
|
1829
|
+
.artifact-preview code {
|
|
1830
|
+
font-family: ui-monospace, SFMono-Regular, SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;
|
|
1831
|
+
border-radius: 6px;
|
|
1832
|
+
background: rgba(175, 184, 193, 0.2);
|
|
1833
|
+
padding: 0.2em 0.4em;
|
|
1834
|
+
font-size: 85%;
|
|
1835
|
+
}
|
|
1836
|
+
.artifact-preview pre.gh-code {
|
|
1837
|
+
max-height: none;
|
|
1838
|
+
margin: 10px 0 14px;
|
|
1839
|
+
border: 1px solid #d0d7de;
|
|
1840
|
+
background: #f6f8fa;
|
|
1841
|
+
color: #24292f;
|
|
1842
|
+
padding: 16px;
|
|
1843
|
+
font-size: 12px;
|
|
1844
|
+
line-height: 1.45;
|
|
1845
|
+
white-space: pre;
|
|
1846
|
+
overflow: auto;
|
|
1847
|
+
}
|
|
1848
|
+
.artifact-preview pre.gh-code code {
|
|
1849
|
+
background: transparent;
|
|
1850
|
+
padding: 0;
|
|
1851
|
+
border-radius: 0;
|
|
1852
|
+
font-size: inherit;
|
|
1853
|
+
}
|
|
1854
|
+
.json-key { color: #0550ae; }
|
|
1855
|
+
.json-string { color: #0a3069; }
|
|
1856
|
+
.json-number { color: #953800; }
|
|
1857
|
+
.json-literal { color: #cf222e; }
|
|
1858
|
+
.inline-button, .primary-button, .danger-button { min-height: 30px; border: 1px solid var(--line); border-radius: 7px; background: var(--surface-raised); color: var(--text); padding: 5px 9px; cursor: pointer; font-size: 12px; }
|
|
1859
|
+
.primary-button { border-color: color-mix(in srgb, var(--accent) 45%, var(--line)); background: var(--surface); color: var(--accent-strong); font-weight: 650; }
|
|
1860
|
+
html[data-theme="dark"] .primary-button { color: var(--accent-strong); }
|
|
1861
|
+
.danger-button { border-color: color-mix(in srgb, var(--critical) 45%, var(--line)); background: var(--critical-soft); color: var(--critical); }
|
|
1862
|
+
.inline-button:hover, .primary-button:hover, .danger-button:hover { border-color: var(--accent); }
|
|
1863
|
+
.artifact-actions, .action-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: 8px; }
|
|
1864
|
+
.form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin-top: 10px; }
|
|
1865
|
+
.form-grid label, .proposal-box label { display: grid; gap: 5px; color: var(--muted); font-size: 12px; }
|
|
1866
|
+
.form-grid input, .form-grid select, .form-grid textarea, .proposal-box select { width: 100%; min-height: 32px; border: 1px solid var(--line); border-radius: 7px; background: var(--surface); color: var(--text); padding: 6px 8px; }
|
|
1867
|
+
.form-wide { grid-column: 1 / -1; }
|
|
1868
|
+
.proposal-box { display: grid; grid-template-columns: minmax(220px, 1fr) minmax(220px, 320px) auto; gap: 10px; align-items: end; margin: 12px; padding: 12px; border-bottom: 1px solid var(--line-soft); background: var(--surface-raised); }
|
|
1869
|
+
.boundary-note { margin: 14px; padding: 12px; border: 1px solid color-mix(in srgb, var(--warning) 35%, var(--line)); border-radius: 8px; background: var(--warning-soft); color: var(--warning); line-height: 1.45; }
|
|
1870
|
+
.timeline-row { display: grid; gap: 8px; }
|
|
1871
|
+
.timeline-meta { display: flex; flex-wrap: wrap; gap: 8px; color: var(--muted); font-size: 12px; }
|
|
1872
|
+
.timeline-filter-bar {
|
|
1873
|
+
display: flex;
|
|
1874
|
+
flex-wrap: wrap;
|
|
1875
|
+
gap: 8px;
|
|
1876
|
+
padding: 10px 12px;
|
|
1877
|
+
border-bottom: 1px solid var(--line-soft);
|
|
1878
|
+
background: var(--surface);
|
|
1879
|
+
}
|
|
1880
|
+
.checkbox-pill {
|
|
1881
|
+
display: inline-flex;
|
|
1882
|
+
align-items: center;
|
|
1883
|
+
gap: 5px;
|
|
1884
|
+
min-height: 28px;
|
|
1885
|
+
padding: 4px 8px;
|
|
1886
|
+
border: 1px solid var(--line);
|
|
1887
|
+
border-radius: 999px;
|
|
1888
|
+
background: var(--surface-raised);
|
|
1889
|
+
color: var(--muted);
|
|
1890
|
+
font-size: 12px;
|
|
1891
|
+
white-space: nowrap;
|
|
1892
|
+
}
|
|
1893
|
+
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
|
1894
|
+
@media (prefers-reduced-motion: no-preference) {
|
|
1895
|
+
.task-card, .button, .nav-button, .inline-button, .primary-button, .danger-button { transition: border-color 140ms ease, background 140ms ease, color 140ms ease, transform 140ms ease, box-shadow 140ms ease; }
|
|
1896
|
+
.artifact-drawer { transition: transform 180ms ease; }
|
|
1897
|
+
}
|
|
1898
|
+
@media (max-width: 1120px) {
|
|
1899
|
+
.mission-shell { grid-template-columns: 1fr; grid-template-rows: auto auto minmax(0, 1fr); }
|
|
1900
|
+
.mission-nav {
|
|
1901
|
+
position: sticky;
|
|
1902
|
+
top: 64px;
|
|
1903
|
+
height: auto;
|
|
1904
|
+
display: flex;
|
|
1905
|
+
border-right: 0;
|
|
1906
|
+
border-bottom: 1px solid var(--line);
|
|
1907
|
+
overflow-x: auto;
|
|
1908
|
+
}
|
|
1909
|
+
.mission-workspace { grid-column: 1; }
|
|
1910
|
+
.command-grid { grid-template-columns: 1fr; grid-template-areas: "inbox" "work" "inspector" "activity"; }
|
|
1911
|
+
.command-inspector { position: static; }
|
|
1912
|
+
.grid-2, .work-grid { grid-template-columns: 1fr; }
|
|
1913
|
+
.health-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
1914
|
+
}
|
|
1915
|
+
@media (max-width: 760px) {
|
|
1916
|
+
.work-filter-bar { grid-template-columns: 1fr; }
|
|
1917
|
+
.mission-nav { top: 0; }
|
|
1918
|
+
.mission-workspace { padding: 12px 10px 32px; }
|
|
1919
|
+
.command-header { display: grid; align-items: start; }
|
|
1920
|
+
.command-title h1 { font-size: 20px; }
|
|
1921
|
+
.health-grid, .meta-grid { grid-template-columns: 1fr; }
|
|
1922
|
+
.health-card { border-right: 0; border-bottom: 1px solid var(--line-soft); }
|
|
1923
|
+
.health-card:last-child { border-bottom: 0; }
|
|
1924
|
+
.work-row, .inbox-row { grid-template-columns: 1fr; }
|
|
1925
|
+
.issue-row { grid-template-columns: 20px minmax(0, 1fr); }
|
|
1926
|
+
.issue-labels { grid-column: 2; justify-content: flex-start; }
|
|
1927
|
+
.work-row .action-row { justify-content: flex-start; }
|
|
1928
|
+
.row-between, .row-top { flex-direction: column; }
|
|
1929
|
+
.form-grid, .proposal-box { grid-template-columns: 1fr; }
|
|
1930
|
+
.checkbox-pill { white-space: normal; }
|
|
1931
|
+
.control-select, .button, .control-pill, .refresh-control { width: 100%; justify-content: center; }
|
|
1932
|
+
.refresh-control { grid-column: 1 / -1; }
|
|
1933
|
+
.badge { white-space: normal; }
|
|
1934
|
+
}
|
|
1935
|
+
</style>
|
|
1936
|
+
<link rel="stylesheet" href="/assets/github-shell.css">
|
|
1937
|
+
<link rel="stylesheet" href="/assets/operations.css">
|
|
1938
|
+
</head>
|
|
1939
|
+
<body>
|
|
1940
|
+
<main id="dashboard-app" class="mission-shell" data-state="loading">
|
|
1941
|
+
<header class="global-bar">
|
|
1942
|
+
<a class="brand" href="/" aria-label="Robert Workbench">
|
|
1943
|
+
<span class="brand-mark" aria-hidden="true">R</span>
|
|
1944
|
+
<span>GitHub Agent</span>
|
|
1945
|
+
</a>
|
|
1946
|
+
<div class="global-actions" aria-label="Dashboard controls" data-i18n-aria="dashboardControls">
|
|
1947
|
+
<span class="live-indicator"><i aria-hidden="true"></i><span class="responsive-label" id="last-updated" data-i18n="loading">Loading</span></span>
|
|
1948
|
+
<button class="shell-button" type="button" id="refresh-button" data-i18n="refresh">Refresh</button>
|
|
1949
|
+
<details class="shell-settings">
|
|
1950
|
+
<summary class="shell-button" data-i18n="settings">Settings</summary>
|
|
1951
|
+
<div class="shell-settings-panel">
|
|
1952
|
+
<label><span data-i18n="theme">Theme</span><select id="theme-select" aria-label="Theme" data-i18n-aria="theme">
|
|
1953
|
+
<option value="system" data-i18n="themeSystem">System</option>
|
|
1954
|
+
<option value="light" data-i18n="themeLight">Light</option>
|
|
1955
|
+
<option value="dark" data-i18n="themeDark">Dark</option>
|
|
1956
|
+
</select></label>
|
|
1957
|
+
<label><span data-i18n="language">Language</span><select id="language-select" aria-label="Language" data-i18n-aria="language">
|
|
1958
|
+
<option value="en" data-i18n="languageEnglish">English</option>
|
|
1959
|
+
<option value="zh" data-i18n="languageChinese">中文</option>
|
|
1960
|
+
</select></label>
|
|
1961
|
+
<span class="refresh-control">
|
|
1962
|
+
<label><input type="checkbox" id="auto-refresh-toggle"> <span data-i18n="autoRefresh">Auto refresh</span></label>
|
|
1963
|
+
<select id="refresh-interval" aria-label="Auto refresh interval">
|
|
1964
|
+
<option value="15000">15s</option>
|
|
1965
|
+
<option value="30000" selected>30s</option>
|
|
1966
|
+
<option value="60000">60s</option>
|
|
1967
|
+
</select>
|
|
1968
|
+
<span class="muted small" id="refresh-status" data-i18n="off">Off</span>
|
|
1969
|
+
</span>
|
|
1970
|
+
<a class="button" href="/data.json" target="_blank" rel="noopener noreferrer" data-i18n="viewJson">View JSON</a>
|
|
1971
|
+
</div>
|
|
1972
|
+
</details>
|
|
1973
|
+
</div>
|
|
1974
|
+
</header>
|
|
1975
|
+
<header class="repo-header">
|
|
1976
|
+
<div class="repo-context"><a href="/">Robert</a><span>/</span><strong id="repo-context">operations</strong><span class="counter-label">Private</span></div>
|
|
1977
|
+
<nav class="underline-nav" aria-label="Workbench" data-i18n-aria="primaryNavigation">
|
|
1978
|
+
<a class="underline-nav-item" href="/"><span aria-hidden="true">⌁</span> <span data-i18n="primaryWork">Work</span></a>
|
|
1979
|
+
<a class="underline-nav-item" href="/board"><span aria-hidden="true">▦</span> <span data-i18n="navBoard">Board</span></a>
|
|
1980
|
+
<a class="underline-nav-item" href="/?bucket=history"><span aria-hidden="true">◷</span> <span data-i18n="navHistory">History</span></a>
|
|
1981
|
+
<a class="underline-nav-item selected" data-primary-view="operations" href="/operations"><span aria-hidden="true">▣</span> <span data-i18n="navOperations">Operations</span></a>
|
|
1982
|
+
<a class="underline-nav-item" data-primary-view="knowledge" href="/operations#knowledge"><span aria-hidden="true">◇</span> <span data-i18n="navKnowledge">Knowledge</span></a>
|
|
1983
|
+
</nav>
|
|
1984
|
+
</header>
|
|
1985
|
+
<nav class="mission-nav" aria-label="Dashboard sections" data-i18n-aria="diagnosticNavigation">
|
|
1986
|
+
<button class="nav-button active" type="button" data-view="command"><span class="nav-icon">#</span><span class="nav-label" data-i18n="navCommand">Command</span><span class="nav-count" id="nav-count-command">0</span></button>
|
|
1987
|
+
<button class="nav-button" type="button" data-view="timeline"><span class="nav-icon">T</span><span class="nav-label" data-i18n="navTimeline">Timeline</span><span class="nav-count" id="nav-count-timeline">0</span></button>
|
|
1988
|
+
<button class="nav-button" type="button" data-view="notifications"><span class="nav-icon">!</span><span class="nav-label" data-i18n="navNotifications">Notifications</span><span class="nav-count" id="nav-count-notifications">0</span></button>
|
|
1989
|
+
<button class="nav-button" type="button" data-view="daemon"><span class="nav-icon">R</span><span class="nav-label" data-i18n="navDaemon">Daemon</span><span class="nav-count" id="nav-count-daemon">0</span></button>
|
|
1990
|
+
</nav>
|
|
1991
|
+
<section class="mission-workspace">
|
|
1992
|
+
<section class="view-panel" id="view-command" data-view-panel="command">
|
|
1993
|
+
<section class="command-header">
|
|
1994
|
+
<div class="command-title">
|
|
1995
|
+
<h1 data-i18n="commandHeadline">Robert Command Center</h1>
|
|
1996
|
+
<p id="dashboard-subtitle" data-i18n="loadingState">Loading local control-plane state.</p>
|
|
1997
|
+
</div>
|
|
1998
|
+
<span id="system-snapshot-status" class="badge info" data-i18n="loading">Loading</span>
|
|
1999
|
+
</section>
|
|
2000
|
+
<section class="health-grid" id="summary-metrics" aria-label="Summary"></section>
|
|
2001
|
+
<section class="command-grid">
|
|
2002
|
+
<article class="panel operator-inbox">
|
|
2003
|
+
<div class="panel-head"><h2 data-i18n="operatorNextSteps">Operator next steps</h2><span id="next-step-count"></span></div>
|
|
2004
|
+
<div class="list" id="operator-next-steps"></div>
|
|
2005
|
+
</article>
|
|
2006
|
+
<article class="panel active-workstreams">
|
|
2007
|
+
<div class="panel-head"><h2 data-i18n="currentWork">Current work</h2><span id="overview-task-count"></span></div>
|
|
2008
|
+
<div class="list" id="now-lane"></div>
|
|
2009
|
+
</article>
|
|
2010
|
+
<aside class="panel command-inspector">
|
|
2011
|
+
<div class="panel-head"><h2 data-i18n="commandInspector">Inspector</h2><span id="command-inspector-status"></span></div>
|
|
2012
|
+
<div id="command-inspector"></div>
|
|
2013
|
+
<div class="panel-head"><h2 data-i18n="systemSnapshot">System snapshot</h2><span></span></div>
|
|
2014
|
+
<div class="status-stack list" id="system-snapshot"></div>
|
|
2015
|
+
</aside>
|
|
2016
|
+
<article class="panel activity-log">
|
|
2017
|
+
<div class="panel-head"><h2 data-i18n="recentActivity">Recent activity</h2><span id="activity-count"></span></div>
|
|
2018
|
+
<div class="list" id="command-activity"></div>
|
|
2019
|
+
</article>
|
|
2020
|
+
</section>
|
|
2021
|
+
</section>
|
|
2022
|
+
<section class="view-panel" id="view-work" data-view-panel="work" hidden>
|
|
2023
|
+
<section class="work-grid">
|
|
2024
|
+
<article class="panel">
|
|
2025
|
+
<div class="panel-head"><h2 data-i18n="workItems">PR / Issue</h2><span id="task-count"></span></div>
|
|
2026
|
+
<div class="work-filter-bar">
|
|
2027
|
+
<label><span class="sr-only" data-i18n="workSearch">Search work</span><input class="search-input" id="work-search" type="search" data-i18n-placeholder="workSearchPlaceholder" placeholder="Search PR title or task ID" aria-label="Search work"></label>
|
|
2028
|
+
<label><span class="sr-only" data-i18n="workProject">Project</span><select class="control-select" id="work-repo-filter" aria-label="Project"></select></label>
|
|
2029
|
+
</div>
|
|
2030
|
+
<div class="list" id="task-list"></div>
|
|
2031
|
+
</article>
|
|
2032
|
+
<aside class="panel" aria-live="polite">
|
|
2033
|
+
<div class="panel-head"><h2 data-i18n="workTasks">Tasks</h2><span id="work-task-count"></span></div>
|
|
2034
|
+
<div class="list" id="work-task-list"></div>
|
|
2035
|
+
</aside>
|
|
2036
|
+
<aside class="panel" id="detail-drawer" aria-live="polite">
|
|
2037
|
+
<div class="panel-head"><h2 data-i18n="taskDetail">Task detail</h2><span id="detail-status"></span></div>
|
|
2038
|
+
<div id="task-detail"></div>
|
|
2039
|
+
<div class="panel-head"><h2 data-i18n="logsArtifacts">Logs and artifacts</h2><span id="artifact-count"></span></div>
|
|
2040
|
+
<div class="list" id="artifact-list"></div>
|
|
2041
|
+
</aside>
|
|
2042
|
+
</section>
|
|
2043
|
+
</section>
|
|
2044
|
+
<section class="view-panel" id="view-daemon" data-view-panel="daemon" hidden>
|
|
2045
|
+
<section class="grid-2">
|
|
2046
|
+
<article class="panel">
|
|
2047
|
+
<div class="panel-head"><h2 data-i18n="daemonHealth">Daemon health</h2><span id="daemon-run-status"></span></div>
|
|
2048
|
+
<div class="meta-grid" id="daemon-health"></div>
|
|
2049
|
+
</article>
|
|
2050
|
+
<article class="panel">
|
|
2051
|
+
<div class="panel-head"><h2 data-i18n="daemonEvents">Daemon events</h2><span id="daemon-event-count"></span></div>
|
|
2052
|
+
<div class="list" id="daemon-events"></div>
|
|
2053
|
+
</article>
|
|
2054
|
+
</section>
|
|
2055
|
+
</section>
|
|
2056
|
+
<section class="view-panel" id="view-timeline" data-view-panel="timeline" hidden>
|
|
2057
|
+
<article class="panel">
|
|
2058
|
+
<div class="panel-head"><h2 data-i18n="timeline">Timeline</h2><span id="timeline-count"></span></div>
|
|
2059
|
+
<div class="timeline-filter-bar" id="timeline-filters" aria-label="Timeline type filters"></div>
|
|
2060
|
+
<div class="list" id="timeline-list"></div>
|
|
2061
|
+
</article>
|
|
2062
|
+
</section>
|
|
2063
|
+
<section class="view-panel" id="view-knowledge" data-view-panel="knowledge" hidden>
|
|
2064
|
+
<section class="grid-2">
|
|
2065
|
+
<article class="panel">
|
|
2066
|
+
<div class="panel-head"><h2 data-i18n="knowledgeReview">Knowledge review</h2><span id="knowledge-count"></span></div>
|
|
2067
|
+
<div class="boundary-note" data-i18n="knowledgeBoundary">Local approval only. This page writes only to local runtime knowledge tables.</div>
|
|
2068
|
+
<form class="proposal-box" id="knowledge-propose-form">
|
|
2069
|
+
<div><strong data-i18n="generateCandidates">Generate candidates</strong><div class="muted small" data-i18n="generateCandidatesHelp">Read local project memory and create pending candidates for human review.</div></div>
|
|
2070
|
+
<label><span data-i18n="repository">Repository</span><select name="repo_id" id="knowledge-propose-repo" required></select></label>
|
|
2071
|
+
<button class="primary-button" type="submit" data-i18n="generate">Generate</button>
|
|
2072
|
+
</form>
|
|
2073
|
+
<div class="list" id="knowledge-candidates"></div>
|
|
2074
|
+
</article>
|
|
2075
|
+
<article class="panel">
|
|
2076
|
+
<div class="panel-head"><h2 data-i18n="activeKnowledge">Active runtime knowledge</h2><span id="runtime-knowledge-count"></span></div>
|
|
2077
|
+
<div class="list" id="runtime-knowledge-list"></div>
|
|
2078
|
+
</article>
|
|
2079
|
+
</section>
|
|
2080
|
+
</section>
|
|
2081
|
+
<section class="view-panel" id="view-notifications" data-view-panel="notifications" hidden>
|
|
2082
|
+
<article class="panel">
|
|
2083
|
+
<div class="panel-head"><h2 data-i18n="notificationCenter">Notification center</h2><span id="notification-count"></span></div>
|
|
2084
|
+
<div class="list" id="notification-center"></div>
|
|
2085
|
+
</article>
|
|
2086
|
+
</section>
|
|
2087
|
+
</section>
|
|
2088
|
+
</main>
|
|
2089
|
+
<div id="preview-scrim" class="preview-scrim" data-close-artifact-preview></div>
|
|
2090
|
+
<aside id="artifact-preview-drawer" class="artifact-drawer" aria-hidden="true" aria-labelledby="artifact-preview-title">
|
|
2091
|
+
<div class="artifact-drawer-head">
|
|
2092
|
+
<h2 id="artifact-preview-title" data-i18n="artifactPreview">Artifact preview</h2>
|
|
2093
|
+
<button id="artifact-preview-close" class="inline-button" type="button" data-close-artifact-preview data-i18n="closePreview">Close</button>
|
|
2094
|
+
</div>
|
|
2095
|
+
<div class="artifact-drawer-body">
|
|
2096
|
+
<div id="artifact-preview" class="artifact-preview placeholder" data-i18n="selectArtifact">Select an artifact preview.</div>
|
|
2097
|
+
</div>
|
|
2098
|
+
</aside>
|
|
2099
|
+
<script>
|
|
2100
|
+
const translations = {
|
|
2101
|
+
en: {
|
|
2102
|
+
navWorkbench: 'Workbench', primaryWork: 'Work', navBoard: 'Board', navHistory: 'History', navOperations: 'Operations', navKnowledge: 'Knowledge',
|
|
2103
|
+
primaryNavigation: 'Primary navigation', diagnosticNavigation: 'Operations sections', repositoryContext: 'Repository context', dashboardControls: 'Dashboard controls',
|
|
2104
|
+
productSubtitle: 'Your Repo Teammate', loadingState: 'Loading local control-plane state.', theme: 'Theme', themeSystem: 'System', themeLight: 'Light', themeDark: 'Dark', language: 'Language', languageEnglish: 'English', languageChinese: 'Chinese', loading: 'Loading', autoRefresh: 'Auto refresh', off: 'Off', refresh: 'Refresh', settings: 'Settings', viewJson: 'View JSON', navCommand: 'Command', navWork: 'Work', navDaemon: 'Daemon', navTimeline: 'Timeline', navKnowledge: 'Knowledge', navNotifications: 'Notifications', commandHeadline: 'Robert Command Center', commandLead: 'Built for collaborators and maintainers who need an unattended GitHub agent they can actually trust.', commandInspector: 'Runtime inspector', systemSnapshot: 'System snapshot', operatorNextSteps: 'Operator Inbox', currentWork: 'Active workstreams', recentActivity: 'Event stream', tasks: 'Tasks', workItems: 'PR / Issue', workTasks: 'Tasks in source', taskDetail: 'Task detail', logsArtifacts: 'Logs and artifacts', daemonHealth: 'Daemon health', daemonEvents: 'Daemon events', timeline: 'Timeline', timelineFilters: 'Timeline filters', knowledgeReview: 'Knowledge review', knowledgeBoundary: 'Local approval only. This page writes only to local runtime knowledge tables.', generateCandidates: 'Generate candidates', generateCandidatesHelp: 'Read local project memory and create pending candidates for human review.', repository: 'Repository', generate: 'Generate', activeKnowledge: 'Active runtime knowledge', notificationCenter: 'Notification center', artifactPreview: 'Artifact preview', closePreview: 'Close', selectArtifact: 'Select an artifact preview.', updated: 'Updated', every: 'Every', open: 'open', recent: 'recent', pending: 'pending', active: 'active', inspect: 'Inspect', preview: 'Preview', openGithub: 'Open GitHub', metadata: 'Metadata', noOperatorAction: 'No operator action is waiting.', noWorkItems: 'No PR or issue work recorded.', noTasks: 'No tasks recorded.', noActivity: 'No recent activity recorded.', noDaemon: 'No daemon run recorded.', noDaemonEvents: 'No daemon events recorded.', noTimeline: 'No timeline evidence recorded.', noNotifications: 'No notifications recorded.', noKnowledgeTables: 'Knowledge tables are not available in this database yet.', noPendingKnowledge: 'No pending knowledge candidates.', noActiveKnowledge: 'No active runtime knowledge.', noArtifacts: 'No artifacts for this task.', artifactLoading: 'Loading artifact preview.', artifactUnavailable: 'Preview unavailable', failedLoad: 'Failed to load dashboard data', approve: 'Approve', reject: 'Reject', scopeType: 'Scope type', scopeValue: 'Scope value', approvedBy: 'Approved by', reviewer: 'Reviewer', rejectReason: 'Reject reason', allowedActions: 'Allowed GitHub actions', recommendedSkills: 'Recommended skills', latestNotification: 'Latest notification', source: 'Source', daemon: 'Daemon', queue: 'Queue', attention: 'Attention', publish: 'Publish', latestRun: 'Latest run', idleHealthy: 'Idle and healthy', needsReview: 'Needs review', workSearch: 'Search work', workProject: 'Project', workSearchPlaceholder: 'Search PR title or task ID', allProjects: 'All projects'
|
|
2105
|
+
},
|
|
2106
|
+
zh: {
|
|
2107
|
+
navWorkbench: '工作台', primaryWork: '工作', navBoard: '任务看板', navHistory: '历史', navOperations: '运行状态', navKnowledge: '知识',
|
|
2108
|
+
primaryNavigation: '一级导航', diagnosticNavigation: '运行状态分区', repositoryContext: '仓库上下文', dashboardControls: '控制台控制',
|
|
2109
|
+
productSubtitle: 'Your Repo Teammate', loadingState: '正在读取本地控制面状态。', theme: '主题', themeSystem: '跟随系统', themeLight: '浅色', themeDark: '深色', language: '语言', languageEnglish: 'English', languageChinese: '中文', loading: '加载中', autoRefresh: '自动刷新', off: '关闭', refresh: '刷新', settings: '设置', viewJson: '查看 JSON', navCommand: '指挥台', navWork: '工作流', navDaemon: '守护进程', navTimeline: '时间线', navKnowledge: '知识', navNotifications: '通知中心', commandHeadline: 'Robert 指挥中心', commandLead: '给协作者和维护者使用:让无人值守的 GitHub Agent 变得可理解、可信任。', commandInspector: '运行检查器', systemSnapshot: '系统快照', operatorNextSteps: '操作收件箱', currentWork: '活跃工作流', recentActivity: '事件流', tasks: '任务', workItems: 'PR / Issue', workTasks: '来源下的任务', taskDetail: '任务详情', logsArtifacts: '日志和产物', daemonHealth: '守护进程健康度', daemonEvents: '守护进程事件', timeline: '时间线', timelineFilters: '时间线过滤', knowledgeReview: '知识审核', knowledgeBoundary: '仅本地审批。此页面只写入本地 runtime knowledge 表。', generateCandidates: '生成候选知识', generateCandidatesHelp: '读取本地项目记忆,生成待人工审核的候选项。', repository: '仓库', generate: '生成', activeKnowledge: '已生效知识', notificationCenter: '通知中心', artifactPreview: '产物预览', closePreview: '关闭', selectArtifact: '选择一个产物预览。', updated: '已更新', every: '每', open: '未处理', recent: '最近', pending: '待处理', active: '活跃', inspect: '查看', preview: '预览', openGithub: '打开 GitHub', metadata: '元数据', noOperatorAction: '暂无需要操作的事项。', noWorkItems: '暂无 PR 或 Issue 工作记录。', noTasks: '暂无任务记录。', noActivity: '暂无最近动态。', noDaemon: '暂无守护进程运行记录。', noDaemonEvents: '暂无守护进程事件。', noTimeline: '暂无时间线证据。', noNotifications: '暂无通知。', noKnowledgeTables: '当前数据库还没有 knowledge 表。', noPendingKnowledge: '暂无待审核知识。', noActiveKnowledge: '暂无已生效知识。', noArtifacts: '这个任务暂无产物。', artifactLoading: '正在加载产物预览。', artifactUnavailable: '无法预览', failedLoad: '加载 dashboard 数据失败', approve: '批准', reject: '拒绝', scopeType: '作用域类型', scopeValue: '作用域值', approvedBy: '批准人', reviewer: '审核人', rejectReason: '拒绝原因', allowedActions: '允许的 GitHub 动作', recommendedSkills: '推荐技能', latestNotification: '最近通知', source: '来源', daemon: '守护', queue: '队列', attention: '关注', publish: '发布', latestRun: '最近运行', idleHealthy: '空闲且健康', needsReview: '需要查看', workSearch: '搜索工作流', workProject: '项目', workSearchPlaceholder: '搜索 PR 标题或 task ID', allProjects: '全部项目'
|
|
2110
|
+
}
|
|
2111
|
+
};
|
|
2112
|
+
const state = { data: null, selectedTaskId: null, selectedWorkItemId: null, currentView: 'command', autoRefreshTimer: null, autoRefreshIntervalMs: 30000, language: 'en', theme: 'system', searchQuery: '', workSearchQuery: '', workRepoFilter: '', timelineHiddenTypes: new Set(['daemon_heartbeat']) };
|
|
2113
|
+
const severityByState = { needs_attention: 'critical', worker_stale: 'warning', worker_retrying: 'warning', result_pending_audit: 'warning', waiting_publish: 'info', waiting_user: 'info', worker_running: 'info', waiting_worker: 'info', completed: 'ok', ignored: 'ok' };
|
|
2114
|
+
const labelByState = { needs_attention: 'Needs attention', worker_stale: 'Worker stale', worker_retrying: 'Worker retrying', result_pending_audit: 'Result pending audit', waiting_publish: 'Waiting publish', waiting_user: 'Waiting user', worker_running: 'Worker running', waiting_worker: 'Waiting worker', completed: 'Completed', ignored: 'Ignored', unknown: 'Unknown' };
|
|
2115
|
+
const dynamicLabels = {
|
|
2116
|
+
en: {},
|
|
2117
|
+
zh: {
|
|
2118
|
+
Actions: '动作', Attempt: '尝试', Channel: '渠道', Config: '配置', Created: '创建时间', Expires: '过期时间', Finished: '结束时间', Heartbeat: '心跳', Kind: '类型', Lifecycle: '生命周期', 'Latest attempt': '最近尝试', 'Latest event': '最近事件', 'Lease key': '租约键', 'Lease owner': '租约持有者', 'Lease status': '租约状态', 'Next action': '下一步动作', Owner: '持有者', Route: '路由', 'Route confidence': '路由置信度', 'Run ID': '运行 ID', 'Run status': '运行状态', Severity: '严重级别', Source: '来源', 'Source key': '来源标识', Started: '开始时间', Status: '状态', Trigger: '触发事件', Type: '类型', 'Type and number': '类型和编号', Updated: '更新时间', Workstream: '工作流',
|
|
2119
|
+
repos: '仓库', repo: '仓库', workstreams: '工作流', tasks: '任务', events: '事件', notifications: '通知', wakeups: '唤醒', files: '文件', bytes: '字节', 'size unknown': '大小未知', '0 files': '0 个文件', 'No repositories': '暂无仓库', memories: '条记忆', 'local control plane': '本地控制面',
|
|
2120
|
+
critical: '严重', warning: '警告', info: '信息', ok: '正常', unknown: '未知', active: '活跃', running: '运行中', completed: '已完成', failed: '失败', canceled: '已取消', expired: '已过期', pending: '待处理', skipped: '已跳过', recorded: '已记录', healthy: '健康',
|
|
2121
|
+
notification: '通知', run: '运行', daemon_event: '守护事件', github_action: 'GitHub 动作', github_event: 'GitHub 事件', worker_result: 'Worker 结果', next_step: '下一步', event: '事件',
|
|
2122
|
+
'run failed': '运行失败', failed_dispatch: '分发失败', worker_dispatch_failed: 'Worker 分发失败', worker_startup_failed: 'Worker 启动失败', worker_process_exited: 'Worker 进程退出', publish_failed: '发布失败', lease_expired: '租约已过期',
|
|
2123
|
+
needs_attention: '需要处理', worker_stale: 'Worker 已过期', worker_retrying: 'Worker 重试中', result_pending_audit: '结果待审计', waiting_publish: '等待发布', waiting_user: '等待用户', worker_running: 'Worker 运行中', waiting_worker: '等待 Worker', ignored: '已忽略', unrouted: '未路由', route: '路由', path: '路径', symbol: '符号', workstream: '工作流', global: '全局',
|
|
2124
|
+
inspect_recent_events: '查看最近事件', inspect_attention_tasks: '查看需处理任务', inspect_worker_timeout: '查看 Worker 超时', inspect_worker_startup: '查看 Worker 启动', inspect_failure_notification: '查看失败通知', inspect_github_publish_failure: '查看 GitHub 发布失败', inspect_github_publish_skipped: '查看跳过的 GitHub 发布', publish_accepted_github_actions: '发布已接受的 GitHub 动作', wait_for_trusted_user_reply: '等待可信用户回复', inspect_worker_heartbeat: '查看 Worker 心跳', inspect_worker_resume: '查看 Worker 恢复', wait_next_cycle_or_run_once: '等待下一轮或运行 run_once', wait_for_worker_completion: '等待 Worker 完成', wait_for_worker_or_supervise: '等待或监督 Worker', inspect_task: '查看任务'
|
|
2125
|
+
}
|
|
2126
|
+
};
|
|
2127
|
+
function $(id) { return document.getElementById(id); }
|
|
2128
|
+
function t(key, vars = {}) { const dict = translations[state.language] || translations.en; let value = dict[key] || translations.en[key] || key; Object.entries(vars).forEach(([name, replacement]) => { value = value.replaceAll(`{${name}}`, String(replacement)); }); return value; }
|
|
2129
|
+
function esc(value) { return String(value ?? '').replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); }
|
|
2130
|
+
function dl(value) { const text = String(value ?? ''); return (dynamicLabels[state.language] || {})[text] || text; }
|
|
2131
|
+
function stateLabel(value) { return dl(labelByState[value] || value || 'unknown'); }
|
|
2132
|
+
function matchesSearchObject(item) { const query = state.searchQuery.trim().toLowerCase(); if (!query) return true; const text = JSON.stringify(item || {}).toLowerCase(); return query.split(/\s+/).every((token) => { const match = token.match(/^([a-z_]+):(.+)$/); if (!match) return text.includes(token); return text.includes(match[2]); }); }
|
|
2133
|
+
function repoContext(data) { const repos = data.repos || []; if (repos.length === 1) return repos[0].full_name || dl('local control plane'); if (repos.length > 1) return `${repos.length} ${dl('repos')}`; return dl('local control plane'); }
|
|
2134
|
+
function setText(id, value) { const node = $(id); if (node) node.textContent = value; }
|
|
2135
|
+
function renderNavCounts(data) { const notifications = data.notification_center || []; const daemonEvents = (data.daemon || {}).recent_events || []; setText('nav-count-command', notifications.filter((item) => item.severity === 'critical' || item.severity === 'warning').length); setText('nav-count-daemon', daemonEvents.length); setText('nav-count-timeline', filteredTimelineItems(data).length); setText('nav-count-notifications', notifications.length); }
|
|
2136
|
+
function pad2(value) { return String(value).padStart(2, '0'); }
|
|
2137
|
+
function fmt(value) { if (!value) return '-'; const date = new Date(value); if (Number.isNaN(date.getTime())) return String(value); return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`; }
|
|
2138
|
+
function fmtShort(value) { if (!value) return '-'; const date = new Date(value); if (Number.isNaN(date.getTime())) return String(value); return `${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`; }
|
|
2139
|
+
function jsonBlock(value) { if (!value || (typeof value === 'object' && Object.keys(value).length === 0)) return ''; return `<pre>${esc(JSON.stringify(value, null, 2))}</pre>`; }
|
|
2140
|
+
function metadataDetails(value) { const block = jsonBlock(value); if (!block) return ''; return `<details class="metadata"><summary>${esc(t('metadata'))}</summary>${block}</details>`; }
|
|
2141
|
+
function badge(label, tone) { return `<span class="badge ${tone || ''}">${esc(dl(label))}</span>`; }
|
|
2142
|
+
function externalLink(url, label) { if (!url) return '-'; return `<a class="external-link" href="${esc(url)}" target="_blank" rel="noopener noreferrer">${esc(label || url)}</a>`; }
|
|
2143
|
+
function sourceTitle(item) { return item?.source_title || item?.title || item?.source_key || item?.id || item?.task_id || '-'; }
|
|
2144
|
+
function sourceMeta(item) { const parts = []; if (item?.source_key) parts.push(item.source_key); else if (item?.workstream_id) parts.push(item.workstream_id); if (item?.source_type || item?.source_number) parts.push(`${item.source_type || 'source'} #${item.source_number || '-'}`); return parts.filter(Boolean).join(' / '); }
|
|
2145
|
+
function applyTranslations() { document.documentElement.lang = state.language === 'zh' ? 'zh-CN' : 'en'; document.querySelectorAll('[data-i18n]').forEach((node) => { node.textContent = t(node.getAttribute('data-i18n')); }); document.querySelectorAll('[data-i18n-placeholder]').forEach((node) => { node.setAttribute('placeholder', t(node.getAttribute('data-i18n-placeholder'))); }); document.querySelectorAll('[data-i18n-aria]').forEach((node) => { node.setAttribute('aria-label', t(node.getAttribute('data-i18n-aria'))); }); $('theme-select').value = state.theme; $('language-select').value = state.language; }
|
|
2146
|
+
function setTheme(value) { const next = ['system', 'light', 'dark'].includes(value) ? value : 'system'; state.theme = next; window.localStorage.setItem('robertWorkbenchTheme', next); document.documentElement.dataset.themeChoice = next; const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; document.documentElement.dataset.theme = next === 'system' ? (prefersDark ? 'dark' : 'light') : next; document.documentElement.dataset.colorMode = document.documentElement.dataset.theme; $('theme-select').value = next; }
|
|
2147
|
+
function setLanguage(value) { const next = translations[value] ? value : 'en'; state.language = next; window.localStorage.setItem('robertLanguage', next); applyTranslations(); renderAll(); }
|
|
2148
|
+
function applyPreferences() { state.theme = window.localStorage.getItem('robertWorkbenchTheme') || 'system'; state.language = window.localStorage.getItem('robertLanguage') || 'en'; setTheme(state.theme); applyTranslations(); if (window.matchMedia) { window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (state.theme === 'system') setTheme('system'); }); } }
|
|
2149
|
+
function workItems(data = state.data) { return data?.work_items || []; }
|
|
2150
|
+
function workSearchTokens() { return state.workSearchQuery.trim().toLowerCase().split(/\s+/).filter(Boolean); }
|
|
2151
|
+
function textHasTokens(value, tokens) { const text = String(value || '').toLowerCase(); return tokens.every((token) => text.includes(token)); }
|
|
2152
|
+
function workItemTitleMatches(item, tokens = workSearchTokens()) { return !tokens.length || textHasTokens(item?.source_title, tokens); }
|
|
2153
|
+
function taskIdMatchesWorkSearch(task, tokens = workSearchTokens()) { return !tokens.length || textHasTokens(task?.task_id, tokens); }
|
|
2154
|
+
function workItemMatchesSearch(item) { const tokens = workSearchTokens(); return !tokens.length || workItemTitleMatches(item, tokens) || (item.tasks || []).some((task) => taskIdMatchesWorkSearch(task, tokens)); }
|
|
2155
|
+
function workItemMatchesRepo(item) { if (!state.workRepoFilter) return true; return item?.repo_full_name === state.workRepoFilter || item?.repo_id === state.workRepoFilter; }
|
|
2156
|
+
function filteredWorkItems(data = state.data) { return workItems(data).filter((item) => workItemMatchesRepo(item) && workItemMatchesSearch(item)); }
|
|
2157
|
+
function filteredTasksForWorkItem(item) { const tasks = item?.tasks || []; const tokens = workSearchTokens(); if (!tokens.length || workItemTitleMatches(item, tokens)) return tasks; return tasks.filter((task) => taskIdMatchesWorkSearch(task, tokens)); }
|
|
2158
|
+
function selectedWorkItem() { const items = filteredWorkItems(); const selected = items.find((item) => item.id === state.selectedWorkItemId); if (selected) return selected; if (state.selectedTaskId) return items.find((item) => (item.tasks || []).some((task) => task.task_id === state.selectedTaskId)) || null; return items[0] || null; }
|
|
2159
|
+
function tasksForSelectedWorkItem() { return filteredTasksForWorkItem(selectedWorkItem()); }
|
|
2160
|
+
function selectedTask() { const tasks = tasksForSelectedWorkItem(); return tasks.find((task) => task.task_id === state.selectedTaskId) || tasks[0] || null; }
|
|
2161
|
+
function chooseDefaultTask(data) { const items = filteredWorkItems(data); const tasks = items.flatMap((item) => filteredTasksForWorkItem(item)); if (state.selectedTaskId && tasks.some((task) => task.task_id === state.selectedTaskId)) { const item = items.find((workItem) => (workItem.tasks || []).some((task) => task.task_id === state.selectedTaskId)); state.selectedWorkItemId = item?.id || state.selectedWorkItemId; return; } const attention = tasks.find((task) => task.operator_state === 'needs_attention'); const fallbackTask = attention || tasks[0] || null; state.selectedTaskId = fallbackTask?.task_id || null; const item = items.find((workItem) => (workItem.tasks || []).some((task) => task.task_id === state.selectedTaskId)); state.selectedWorkItemId = item?.id || items[0]?.id || null; }
|
|
2162
|
+
function hashFor(view, taskId) { return view === 'work' && taskId ? `#work/${encodeURIComponent(taskId)}` : `#${encodeURIComponent(view)}`; }
|
|
2163
|
+
function setView(view, updateHash = true) { const validViews = new Set(['command', 'work', 'daemon', 'timeline', 'knowledge', 'notifications']); state.currentView = validViews.has(view) ? view : 'command'; document.querySelectorAll('[data-view-panel]').forEach((panel) => { panel.hidden = panel.getAttribute('data-view-panel') !== state.currentView; }); document.querySelectorAll('[data-view]').forEach((button) => { button.classList.toggle('active', button.getAttribute('data-view') === state.currentView); }); document.querySelectorAll('[data-primary-view]').forEach((link) => { link.classList.toggle('selected', link.getAttribute('data-primary-view') === (state.currentView === 'knowledge' ? 'knowledge' : 'operations')); }); if (updateHash) { const nextHash = hashFor(state.currentView, state.selectedTaskId); if (window.location.hash !== nextHash) window.history.replaceState(null, '', nextHash); } }
|
|
2164
|
+
function applyHash() { const hash = window.location.hash.replace(/^#/, ''); if (!hash) { setView('command', false); return; } const [view, rawTaskId] = hash.split('/'); if (view === 'work' && rawTaskId) state.selectedTaskId = decodeURIComponent(rawTaskId); setView(view || 'command', false); }
|
|
2165
|
+
function openTask(taskId) { state.selectedTaskId = taskId; const item = workItems().find((workItem) => (workItem.tasks || []).some((task) => task.task_id === taskId)); if (item) { state.selectedWorkItemId = item.id; if (state.workRepoFilter && !workItemMatchesRepo(item)) state.workRepoFilter = ''; if (state.workSearchQuery && !workItemMatchesSearch(item)) state.workSearchQuery = ''; } closeArtifactDrawer(); setView('work'); renderAll(); }
|
|
2166
|
+
function openWorkItem(itemId) { state.selectedWorkItemId = itemId; const item = selectedWorkItem(); state.selectedTaskId = (item?.tasks || [])[0]?.task_id || null; closeArtifactDrawer(); setView('work'); renderAll(); }
|
|
2167
|
+
function toneForStatus(status) { const value = String(status || '').toLowerCase(); if (['failed', 'failure', 'error', 'rejected', 'timeout', 'expired'].some((item) => value.includes(item))) return 'critical'; if (['pending', 'stale', 'skipped', 'retry', 'permission'].some((item) => value.includes(item))) return 'warning'; if (['completed', 'succeeded', 'healthy', 'active', 'running', 'published', 'resolved'].some((item) => value.includes(item))) return 'ok'; return 'info'; }
|
|
2168
|
+
function runDisplayStatus(run) { return run?.summary?.overall_status || run?.status; }
|
|
2169
|
+
function renderMetrics(data) { const summary = data.summary || {}; const daemon = data.daemon || {}; const latestRun = daemon.latest_run || {}; const items = [[t('daemon'), latestRun.status ? dl(latestRun.status) : (daemon.available ? t('idleHealthy') : '-'), toneForStatus(latestRun.status || 'healthy')], [t('queue'), (data.wakeup_summary || {}).pending || 0, ((data.wakeup_summary || {}).pending || 0) ? 'info' : 'ok'], [t('attention'), (data.notification_center || []).filter((item) => item.severity === 'critical' || item.severity === 'warning').length, (data.notification_center || []).some((item) => item.severity === 'critical') ? 'critical' : 'warning'], [t('publish'), summary.pending_publish_actions || 0, (summary.pending_publish_actions || 0) ? 'info' : 'ok'], [t('latestRun'), summary.agent_runs || 0, toneForStatus(runDisplayStatus((data.recent_runs || [])[0]))]]; $('summary-metrics').innerHTML = items.map(([label, value, tone]) => `<div class="health-card ${tone || ''}"><span>${esc(label)}</span><strong>${esc(value)}</strong>${badge(tone || 'info', tone)}</div>`).join(''); const hasCritical = (data.notification_center || []).some((item) => item.severity === 'critical'); $('system-snapshot-status').textContent = hasCritical ? t('needsReview') : t('idleHealthy'); $('system-snapshot-status').className = `badge ${hasCritical ? 'critical' : 'ok'}`; $('system-snapshot').innerHTML = [['repos', summary.repos || 0], ['tasks', summary.tasks || 0], ['events', summary.github_events || 0], ['notifications', summary.notifications || 0], ['wakeups', (data.wakeup_summary || {}).pending || 0]].map(([label, value]) => `<div class="row-between"><span class="muted">${esc(dl(label))}</span><strong>${esc(value)}</strong></div>`).join(''); }
|
|
2170
|
+
function stateIcon(tone) { const value = tone || 'info'; const mark = value === 'critical' ? '!' : value === 'warning' ? '!' : value === 'ok' ? '✓' : 'i'; return `<span class="state-icon ${esc(value)}" aria-hidden="true">${esc(mark)}</span>`; }
|
|
2171
|
+
function renderInboxItem(item) { const taskButton = item.task_id ? `<button class="inline-button" type="button" data-open-task="${esc(item.task_id)}">${esc(item.task_id)}</button>` : ''; return `<article class="row-card ${esc(item.severity || 'info')}"><div class="issue-row">${stateIcon(item.severity || 'info')}<div><div class="item-title">${esc(dl(item.title || item.kind || 'event'))}</div><div class="muted">${esc(dl(item.summary || item.reason || item.status || ''))}</div><div class="issue-meta"><span>${fmt(item.created_at)}</span><span>${esc(item.source_key || dl(item.kind || ''))}</span>${taskButton}${item.github_url ? externalLink(item.github_url, t('openGithub')) : ''}</div></div><div class="issue-labels">${badge(item.severity || item.kind || 'info', item.severity || 'info')}${badge(item.kind || 'event', '')}</div></div>${metadataDetails(item.metadata)}</article>`; }
|
|
2172
|
+
function renderNextSteps(data) { const steps = (data.operator_next_steps || []).filter(matchesSearchObject); const notifications = (data.notification_center || []).filter((item) => item.severity === 'critical' || item.severity === 'warning').filter(matchesSearchObject); const items = steps.length ? steps.map((step) => ({ id: step.target_id || step.event_fingerprint, kind: step.target_kind, severity: step.severity, title: step.next_action || 'inspect', summary: step.reason || step.target_kind || '', created_at: step.created_at, task_id: step.target_kind === 'task' ? step.target_id : step.task_id, source_key: step.source_key || step.target_id, github_url: step.github_url || step.target_url, metadata: step })) : notifications; $('next-step-count').textContent = `${items.length} ${t('open')}`; $('operator-next-steps').innerHTML = items.length ? items.slice(0, 7).map(renderInboxItem).join('') : `<div class="empty">${esc(t('noOperatorAction'))}</div>`; bindTaskButtons(); }
|
|
2173
|
+
function renderNowLane(data) { const items = (data.work_items || []).filter(matchesSearchObject); $('overview-task-count').textContent = `${items.length} ${t('recent')}`; $('now-lane').innerHTML = items.slice(0, 8).map((item) => { const tone = severityByState[item.top_operator_state] || 'info'; return `<article class="task-card"><div class="issue-row">${stateIcon(tone)}<div><div class="item-title">${esc(sourceTitle(item))}</div><div class="issue-meta"><span>${esc(sourceMeta(item))}</span><span>${esc(item.latest_task_updated_at ? `${t('updated')} ${fmt(item.latest_task_updated_at)}` : '')}</span><button class="inline-button" type="button" data-work-item-id="${esc(item.id)}">${esc(t('inspect'))}</button>${item.github_url ? externalLink(item.github_url, t('openGithub')) : ''}</div></div><div class="issue-labels">${badge(stateLabel(item.top_operator_state), tone)}${badge(`${item.task_count || 0} ${t('tasks')}`, '')}</div></div></article>`; }).join('') || `<div class="empty">${esc(t('noWorkItems'))}</div>`; bindWorkItemButtons(); }
|
|
2174
|
+
function renderWorkFilters(data) { const repos = data.repos || []; const select = $('work-repo-filter'); const search = $('work-search'); if (search && search.value !== state.workSearchQuery) search.value = state.workSearchQuery; if (!select) return; if (state.workRepoFilter && !repos.some((repo) => (repo.full_name || repo.repo_id) === state.workRepoFilter)) state.workRepoFilter = ''; select.innerHTML = `<option value="">${esc(t('allProjects'))}</option>${repos.map((repo) => { const value = repo.full_name || repo.repo_id; return `<option value="${esc(value)}">${esc(value)}</option>`; }).join('')}`; select.value = state.workRepoFilter; }
|
|
2175
|
+
function renderTasks(data) { const items = filteredWorkItems(data); $('task-count').textContent = `${items.length} ${t('recent')}`; $('task-list').innerHTML = items.length ? items.map((item) => { const tone = severityByState[item.top_operator_state] || ''; return `<button class="task-card ${item.id === state.selectedWorkItemId ? 'active' : ''}" type="button" data-work-item-id="${esc(item.id)}"><div class="row-top"><div class="item-title">${esc(sourceTitle(item))}</div>${badge(stateLabel(item.top_operator_state), tone)}</div><div class="muted">${esc(sourceMeta(item) || item.workstream_id || '')}</div><div>${badge(`${item.task_count || 0} ${t('tasks')}`, '')}${item.latest_task_updated_at ? badge(fmtShort(item.latest_task_updated_at), '') : ''}</div></button>`; }).join('') : `<div class="empty">${esc(t('noWorkItems'))}</div>`; bindWorkItemButtons(); }
|
|
2176
|
+
function renderWorkTaskList() { const tasks = tasksForSelectedWorkItem(); $('work-task-count').textContent = `${tasks.length} ${t('recent')}`; $('work-task-list').innerHTML = tasks.length ? tasks.map((task) => { const tone = severityByState[task.operator_state] || ''; return `<button class="task-card ${task.task_id === state.selectedTaskId ? 'active' : ''}" type="button" data-task-id="${esc(task.task_id)}"><div class="row-top"><div class="item-title">${esc(task.route_id || task.expected_output || task.task_id)}</div>${badge(stateLabel(task.operator_state), tone)}</div><div class="muted">${esc(task.task_id)}${task.updated_at ? ` / ${esc(t('updated'))} ${esc(fmtShort(task.updated_at))}` : ''}</div><div>${badge(task.priority || 'P?', '')}${badge(task.route_id || task.expected_output || 'unrouted', '')}${task.latest_attempt_status ? badge(`attempt ${task.latest_attempt_status}`, '') : ''}</div></button>`; }).join('') : `<div class="empty">${esc(t('noTasks'))}</div>`; document.querySelectorAll('[data-task-id]').forEach((button) => { button.addEventListener('click', () => { state.selectedTaskId = button.getAttribute('data-task-id'); closeArtifactDrawer(); renderAll(); }); }); }
|
|
2177
|
+
function field(label, value) { const display = value === 0 ? '0' : (value || '-'); return `<div class="field"><label>${esc(dl(label))}</label><div>${esc(dl(display))}</div></div>`; }
|
|
2178
|
+
function artifactPreviewOpen() { return $('artifact-preview-drawer')?.classList.contains('open'); }
|
|
2179
|
+
function setArtifactPreviewTitle(label) { const title = $('artifact-preview-title'); if (title) title.textContent = label || t('artifactPreview'); }
|
|
2180
|
+
function openArtifactDrawer(label) { const drawer = $('artifact-preview-drawer'); const scrim = $('preview-scrim'); if (!drawer || !scrim) return; setArtifactPreviewTitle(label ? `${t('artifactPreview')}: ${label}` : t('artifactPreview')); drawer.classList.add('open'); scrim.classList.add('open'); drawer.setAttribute('aria-hidden', 'false'); document.body.classList.add('preview-open'); $('artifact-preview-close')?.focus(); }
|
|
2181
|
+
function closeArtifactDrawer() { const drawer = $('artifact-preview-drawer'); const scrim = $('preview-scrim'); if (!drawer || !scrim) return; drawer.classList.remove('open'); scrim.classList.remove('open'); drawer.setAttribute('aria-hidden', 'true'); document.body.classList.remove('preview-open'); setArtifactPreviewTitle(t('artifactPreview')); }
|
|
2182
|
+
function resetArtifactPreview(message, mode = 'placeholder') { const target = $('artifact-preview'); if (!target) return; target.className = `artifact-preview ${mode}`; target.textContent = message; }
|
|
2183
|
+
function renderTaskDetail() { renderWorkTaskList(); const task = selectedTask(); if (!task) { $('detail-status').textContent = ''; $('task-detail').innerHTML = `<div class="empty">${esc(t('noTasks'))}</div>`; $('artifact-count').textContent = dl('0 files'); $('artifact-list').innerHTML = `<div class="empty">${esc(t('noArtifacts'))}</div>`; closeArtifactDrawer(); resetArtifactPreview(t('selectArtifact')); return; } const tone = severityByState[task.operator_state] || ''; $('detail-status').innerHTML = badge(stateLabel(task.operator_state), tone); $('task-detail').innerHTML = `<div class="detail-title"><h3>${esc(sourceTitle(task))}</h3><p>${esc(sourceMeta(task) || task.workstream_id || '')}</p></div><div class="detail-actions">${task.github_url ? externalLink(task.github_url, t('openGithub')) : ''}</div><div class="meta-grid">${field('Lifecycle', task.lifecycle)}${field('Workstream', task.workstream_lifecycle)}${field('Route', task.route_id || task.expected_output)}${field('Route confidence', task.route_confidence)}${field('Latest attempt', task.latest_attempt_status)}${field('Heartbeat', fmt(task.latest_attempt_heartbeat_at))}${field('Updated', fmt(task.updated_at))}${field('Trigger', task.trigger_event_fingerprint)}</div><div class="subhead">${esc(t('source'))}</div><div class="meta-grid">${field('Title', task.source_title)}${field('Source key', task.source_key)}${field('Type and number', `${task.source_type || '-'} #${task.source_number || '-'}`)}${field('Task ID', task.task_id)}<div class="field"><label>GitHub</label><div>${externalLink(task.github_url)}</div></div>${field('Next action', task.next_action)}</div><div class="subhead">${esc(t('allowedActions'))}</div><div class="meta-grid"><div class="field"><label>${esc(dl('Actions'))}</label><div>${(task.allowed_github_actions || []).map((item) => `<span class="json-chip">${esc(item)}</span>`).join('') || '-'}</div></div><div class="field"><label>${esc(t('recommendedSkills'))}</label><div>${(task.recommended_skills || []).map((item) => `<span class="json-chip">${esc(item)}</span>`).join('') || '-'}</div></div></div>${task.latest_notification ? `<div class="subhead">${esc(t('latestNotification'))}</div><div class="meta-grid">${field('Type', task.latest_notification.notification_type)}${field('Status', task.latest_notification.status)}${field('Created', fmt(task.latest_notification.created_at))}${field('Channel', task.latest_notification.channel)}</div>${metadataDetails(task.latest_notification.metadata)}` : ''}`; renderArtifacts(task); }
|
|
2184
|
+
function renderCommandInspector(data) { const task = selectedTask(); const daemon = data.daemon || {}; const latestRun = daemon.latest_run || {}; const latestLease = daemon.latest_lease || {}; const firstNotice = (data.notification_center || [])[0] || null; if (!task) { const noticeTone = firstNotice ? (firstNotice.severity || 'info') : toneForStatus(latestRun.status || 'healthy'); $('command-inspector-status').innerHTML = badge(firstNotice ? (firstNotice.severity || firstNotice.kind) : (latestRun.status || t('idleHealthy')), noticeTone); $('command-inspector').innerHTML = `${firstNotice ? `<div class="detail-title"><h3>${esc(sourceTitle(firstNotice))}</h3><p>${esc(dl(firstNotice.summary || firstNotice.kind || ''))}</p></div><div class="detail-actions">${firstNotice.task_id ? `<button class="inline-button" type="button" data-open-task="${esc(firstNotice.task_id)}">${esc(firstNotice.task_id)}</button>` : ''}${firstNotice.github_url ? externalLink(firstNotice.github_url, t('openGithub')) : ''}</div><div class="meta-grid">${field('Kind', firstNotice.kind)}${field('Source', sourceMeta(firstNotice))}${field('Created', fmt(firstNotice.created_at))}${field('Severity', firstNotice.severity)}</div>` : `<div class="empty">${esc(t('noTasks'))}</div>`}<div class="subhead">${esc(t('daemon'))}</div><div class="meta-grid">${field('Run status', latestRun.status || (daemon.available ? t('idleHealthy') : '-'))}${field('Run ID', latestRun.daemon_run_id)}${field('Lease owner', latestLease.owner_id)}${field('Heartbeat', fmt(latestLease.heartbeat_at))}</div>`; bindTaskButtons(); return; } const tone = severityByState[task.operator_state] || ''; $('command-inspector-status').innerHTML = badge(stateLabel(task.operator_state), tone); $('command-inspector').innerHTML = `<div class="detail-title"><h3>${esc(sourceTitle(task))}</h3><p>${esc(sourceMeta(task) || task.workstream_id || '')}</p></div><div class="detail-actions">${task.github_url ? externalLink(task.github_url, t('openGithub')) : ''}<button class="inline-button" type="button" data-open-task="${esc(task.task_id)}">${esc(t('inspect'))}</button></div><div class="meta-grid">${field('Lifecycle', task.lifecycle)}${field('Route', task.route_id || task.expected_output)}${field('Task ID', task.task_id)}${field('Attempt', task.latest_attempt_status)}${field('Updated', fmt(task.updated_at))}</div><div class="subhead">${esc(t('daemon'))}</div><div class="meta-grid">${field('Run status', latestRun.status)}${field('Lease owner', latestLease.owner_id)}${field('Heartbeat', fmt(latestLease.heartbeat_at))}${field('Expires', fmt(latestLease.expires_at))}</div>${task.latest_notification ? `<div class="subhead">${esc(t('latestNotification'))}</div><div class="meta-grid">${field('Type', task.latest_notification.notification_type)}${field('Status', task.latest_notification.status)}</div>` : ''}`; bindTaskButtons(); }
|
|
2185
|
+
function renderArtifacts(task) { const artifacts = Object.entries(task.artifacts || {}); $('artifact-count').textContent = `${artifacts.length} ${dl('files')}`; $('artifact-list').innerHTML = artifacts.length ? artifacts.map(([type, artifact]) => `<div class="artifact-row"><div class="row-between"><strong>${esc(type)}</strong>${badge(artifact.bytes ? `${artifact.bytes} ${dl('bytes')}` : dl('size unknown'), '')}</div><div class="muted">${esc(artifact.path || '')}</div><div class="artifact-actions"><button class="inline-button" type="button" data-preview-task="${esc(task.task_id)}" data-preview-artifact="${esc(type)}">${esc(t('preview'))}</button></div></div>`).join('') : `<div class="empty">${esc(t('noArtifacts'))}</div>`; if (!artifactPreviewOpen()) resetArtifactPreview(t('selectArtifact')); document.querySelectorAll('[data-preview-task]').forEach((button) => { button.addEventListener('click', () => previewArtifact(button.getAttribute('data-preview-task'), button.getAttribute('data-preview-artifact'))); }); }
|
|
2186
|
+
function parseArtifactPreview(text) { const parts = String(text || '').split(/\n\n/); const headerText = parts.length > 1 ? parts.shift() : ''; const fields = {}; headerText.split(/\n/).forEach((line) => { const match = line.match(/^([^=]+)=(.*)$/); if (match) fields[match[1]] = match[2]; }); return { fields, content: parts.join('\n\n') }; }
|
|
2187
|
+
function artifactPreviewHeader(fields) { const rows = ['task_id', 'artifact_type', 'path', 'truncated'].filter((key) => fields[key]).map((key) => `<span>${esc(key)}=${esc(fields[key])}</span>`).join(''); return rows ? `<div class="artifact-preview-header">${rows}</div>` : ''; }
|
|
2188
|
+
function safeMarkdownHref(url) { const value = String(url || '').trim(); return /^(https?:\/\/|mailto:|#)/i.test(value) ? value : ''; }
|
|
2189
|
+
function inlineMarkdown(text) { let html = esc(text); html = html.replace(/`([^`]+)`/g, '<code>$1</code>'); html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>'); html = html.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_match, label, url) => { const href = safeMarkdownHref(url); return href ? `<a class="external-link" href="${esc(href)}" target="_blank" rel="noopener noreferrer">${label}</a>` : label; }); return html; }
|
|
2190
|
+
function renderCodeBlock(code, language = '') { const text = String(code || ''); const lang = String(language || '').trim().toLowerCase(); if (lang === 'json') return `<pre class="gh-code"><code>${highlightJson(text) || esc(text)}</code></pre>`; return `<pre class="gh-code"><code>${esc(text)}</code></pre>`; }
|
|
2191
|
+
function renderMarkdown(content) { const lines = String(content || '').replace(/\r\n/g, '\n').split('\n'); const html = []; let paragraph = []; let list = []; const flushParagraph = () => { if (paragraph.length) { html.push(`<p>${inlineMarkdown(paragraph.join(' '))}</p>`); paragraph = []; } }; const flushList = () => { if (list.length) { html.push(`<ul>${list.map((item) => `<li>${inlineMarkdown(item)}</li>`).join('')}</ul>`); list = []; } }; for (let index = 0; index < lines.length; index += 1) { const line = lines[index]; const fence = line.match(/^```([A-Za-z0-9_-]*)\s*$/); if (fence) { flushParagraph(); flushList(); const code = []; index += 1; while (index < lines.length && !lines[index].match(/^```\s*$/)) { code.push(lines[index]); index += 1; } html.push(renderCodeBlock(code.join('\n'), fence[1])); continue; } const heading = line.match(/^(#{1,3})\s+(.+)$/); if (heading) { flushParagraph(); flushList(); const level = heading[1].length; html.push(`<h${level}>${inlineMarkdown(heading[2])}</h${level}>`); continue; } const item = line.match(/^\s*[-*]\s+(.+)$/); if (item) { flushParagraph(); list.push(item[1]); continue; } if (line.startsWith('> ')) { flushParagraph(); flushList(); html.push(`<blockquote>${inlineMarkdown(line.slice(2))}</blockquote>`); continue; } if (!line.trim()) { flushParagraph(); flushList(); continue; } paragraph.push(line.trim()); } flushParagraph(); flushList(); return html.join('') || renderPlainText(content); }
|
|
2192
|
+
function highlightJson(content) { try { const pretty = JSON.stringify(JSON.parse(content), null, 2); return pretty.replace(/("(?:\\u[\da-fA-F]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(?:true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g, (token) => { let cls = 'json-number'; if (token.endsWith(':')) cls = 'json-key'; else if (token.startsWith('"')) cls = 'json-string'; else if (/true|false|null/.test(token)) cls = 'json-literal'; return `<span class="${cls}">${esc(token)}</span>`; }); } catch (_error) { return ''; } }
|
|
2193
|
+
function renderPlainText(content) { return `<pre class="gh-code"><code>${esc(content || '')}</code></pre>`; }
|
|
2194
|
+
function artifactPreviewMode(fields, artifactType, content) { const path = String(fields.path || '').toLowerCase(); const type = String(artifactType || fields.artifact_type || '').toLowerCase(); const trimmed = String(content || '').trim(); if (path.endsWith('.md') || path.endsWith('.markdown') || type.includes('markdown') || type.includes('prompt') || type.includes('handoff')) return 'markdown'; if (path.endsWith('.json') || type.includes('json')) return 'json'; if ((trimmed.startsWith('{') || trimmed.startsWith('[')) && highlightJson(trimmed)) return 'json'; return 'text'; }
|
|
2195
|
+
function renderArtifactPreview(text, artifactType) { const target = $('artifact-preview'); if (!target) return; const parsed = parseArtifactPreview(text); const mode = artifactPreviewMode(parsed.fields, artifactType, parsed.content); const highlightedJson = mode === 'json' ? highlightJson(parsed.content) : ''; const body = mode === 'markdown' ? renderMarkdown(parsed.content) : highlightedJson ? `<pre class="gh-code"><code>${highlightedJson}</code></pre>` : renderPlainText(parsed.content); target.className = `artifact-preview ${mode}`; target.innerHTML = artifactPreviewHeader(parsed.fields) + body; }
|
|
2196
|
+
async function previewArtifact(taskId, artifactType) { openArtifactDrawer(artifactType); resetArtifactPreview(t('artifactLoading')); const url = `/artifact.txt?task_id=${encodeURIComponent(taskId)}&artifact_type=${encodeURIComponent(artifactType)}`; try { const response = await fetch(url, { cache: 'no-store' }); const text = await response.text(); if (response.ok) renderArtifactPreview(text, artifactType); else resetArtifactPreview(`${t('artifactUnavailable')}: ${text}`, 'error'); } catch (error) { resetArtifactPreview(`${t('artifactUnavailable')}: ${error.message}`, 'error'); } }
|
|
2197
|
+
function daemonLeaseStatus(lease) { if (!lease) return null; if (lease.status === 'active') { const expiresAt = new Date(lease.expires_at); if (!Number.isNaN(expiresAt.getTime()) && expiresAt.getTime() <= Date.now()) return 'expired'; } return lease.status || null; }
|
|
2198
|
+
function renderDaemon(data) { const daemon = data.daemon || {}; const latestRun = daemon.latest_run || null; const latestEvent = daemon.latest_event || null; const latestLease = daemon.latest_lease || null; const leaseStatus = daemonLeaseStatus(latestLease); const displayStatus = leaseStatus === 'expired' ? 'expired' : latestRun?.status; const recentEvents = daemon.recent_events || (latestEvent ? [latestEvent] : []); $('daemon-run-status').innerHTML = latestRun ? badge(displayStatus || 'unknown', toneForStatus(displayStatus)) : ''; $('daemon-health').innerHTML = (latestRun || latestEvent || latestLease) ? `${field('Run ID', latestRun?.daemon_run_id)}${field('Run status', latestRun?.status)}${field('Started', fmt(latestRun?.started_at))}${field('Finished', fmt(latestRun?.finished_at))}${field('Config', latestRun?.config_path)}${field('Owner', latestRun?.owner_id)}${field('Lease status', leaseStatus)}${field('Lease owner', latestLease?.owner_id)}${field('Lease key', latestLease?.resource_key)}${field('Heartbeat', fmt(latestLease?.heartbeat_at))}${field('Expires', fmt(latestLease?.expires_at))}${field('Latest event', latestEvent?.event_type)}` : `<div class="empty">${esc(t('noDaemon'))}</div>`; $('daemon-event-count').textContent = `${recentEvents.length} ${t('recent')}`; $('daemon-events').innerHTML = recentEvents.length ? recentEvents.map((event) => `<article class="row-card"><div class="row-between"><strong>${esc(dl(event.event_type || 'daemon_event'))}</strong>${badge(event.status || 'unknown', toneForStatus(event.status))}</div><div class="muted">${fmt(event.created_at)} / ${esc(event.daemon_run_id || '-')}</div>${metadataDetails(event.metadata)}</article>`).join('') : `<div class="empty">${esc(t('noDaemonEvents'))}</div>`; }
|
|
2199
|
+
function timelineItems(data) { const items = []; (data.notification_center || []).forEach((item) => { items.push({ id: item.id, kind: item.kind, type: item.kind === 'daemon_event' ? (item.title || item.kind) : item.kind, title: sourceTitle(item), summary: item.summary || item.title || '', at: item.created_at, severity: item.severity, task_id: item.task_id, github_url: item.github_url, source_key: item.source_key, source_title: item.source_title, metadata: item.metadata }); }); (data.recent_events || []).forEach((event) => { items.push({ id: event.event_id, kind: 'github_event', type: event.event_type || 'github_event', title: sourceTitle(event), summary: `${event.event_type || 'event'} / ${event.authorization_status || ''}`, at: event.event_at, severity: toneForStatus(event.authorization_status), task_id: event.task_id, github_url: event.html_url, source_key: event.source_key, source_title: event.source_title, metadata: event }); }); (data.recent_worker_results || []).forEach((result) => { items.push({ id: result.result_id, kind: 'worker_result', type: result.output_type || 'worker_result', title: result.output_type || 'worker_result', summary: result.handoff || result.task_id || '', at: result.created_at, severity: 'ok', task_id: result.task_id, metadata: result }); }); (data.recent_actions || []).forEach((action) => { items.push({ id: action.action_id, kind: 'github_action', type: action.action_type || 'github_action', title: action.action_type || 'github_action', summary: `${action.audit_status || '-'} / ${action.publish_status || '-'}`, at: action.created_at, severity: toneForStatus(`${action.audit_status || ''} ${action.publish_status || ''}`), task_id: action.task_id, github_url: action.target_url, metadata: action }); }); (data.recent_runs || []).forEach((run) => { const status = runDisplayStatus(run); items.push({ id: run.run_id, kind: 'run', type: 'run', title: run.run_id, summary: status || '', at: run.started_at, severity: toneForStatus(status), metadata: run }); }); return items.sort((a, b) => String(b.at || '').localeCompare(String(a.at || ''))); }
|
|
2200
|
+
function filteredTimelineItems(data) { return timelineItems(data).filter((item) => !state.timelineHiddenTypes.has(item.type || item.kind)); }
|
|
2201
|
+
function renderTimelineFilters(data) { const types = Array.from(new Set(timelineItems(data).map((item) => item.type || item.kind).filter(Boolean))).sort(); $('timeline-filters').innerHTML = types.length ? types.map((type) => `<label class="checkbox-pill"><input type="checkbox" data-timeline-type="${esc(type)}" ${state.timelineHiddenTypes.has(type) ? '' : 'checked'}><span>${esc(dl(type))}</span></label>`).join('') : ''; document.querySelectorAll('[data-timeline-type]').forEach((input) => { input.addEventListener('change', () => { const type = input.getAttribute('data-timeline-type'); if (input.checked) state.timelineHiddenTypes.delete(type); else state.timelineHiddenTypes.add(type); renderTimeline(state.data); renderNavCounts(state.data); }); }); }
|
|
2202
|
+
function timelineCard(item) { return `<article class="timeline-row ${esc(item.severity || 'info')}"><div class="row-between"><div><div class="item-title">${esc(dl(item.title || item.id))}</div><div class="muted">${esc(dl(item.summary || item.kind || ''))}</div></div>${badge(item.kind || 'event', item.severity || 'info')}</div><div class="timeline-meta"><span>${fmt(item.at)}</span>${sourceMeta(item) ? `<span>${esc(sourceMeta(item))}</span>` : ''}${item.task_id ? `<button class="inline-button" type="button" data-open-task="${esc(item.task_id)}">${esc(item.task_id)}</button>` : ''}${item.github_url ? externalLink(item.github_url, t('openGithub')) : ''}</div>${metadataDetails(item.metadata)}</article>`; }
|
|
2203
|
+
function renderTimeline(data) { renderTimelineFilters(data); const items = filteredTimelineItems(data).slice(0, 80); $('timeline-count').textContent = `${items.length} ${t('recent')}`; $('timeline-list').innerHTML = items.length ? items.map(timelineCard).join('') : `<div class="empty">${esc(t('noTimeline'))}</div>`; bindTaskButtons(); }
|
|
2204
|
+
function renderNotifications(data) { const items = data.notification_center || []; $('notification-count').textContent = `${items.length} ${t('recent')}`; $('notification-center').innerHTML = items.length ? items.map((item) => `<article class="notification-card ${esc(item.severity || 'info')}"><div class="row-between"><div><div class="item-title">${esc(sourceTitle(item))}</div><div class="muted">${esc(dl(item.summary || item.title || ''))}</div></div>${badge(item.severity || 'info', item.severity || 'info')}</div><div class="timeline-meta"><span>${fmt(item.created_at)}</span><span>${esc(dl(item.kind || ''))}</span>${sourceMeta(item) ? `<span>${esc(sourceMeta(item))}</span>` : ''}${item.github_url ? externalLink(item.github_url, t('openGithub')) : ''}</div><div class="action-row">${item.task_id ? `<button class="inline-button" type="button" data-open-task="${esc(item.task_id)}">${esc(t('inspect'))}</button>` : ''}</div>${metadataDetails(item.metadata)}</article>`).join('') : `<div class="empty">${esc(t('noNotifications'))}</div>`; bindTaskButtons(); }
|
|
2205
|
+
function candidateCard(candidate) { const evidence = (candidate.evidence || []).map((item) => `<span class="json-chip">${esc(item.type || 'evidence')}: ${esc(item.value || '')}</span>`).join(''); return `<article class="row-card"><div class="row-between"><div><strong>${esc(candidate.title)}</strong><div class="muted">${esc(candidate.summary)}</div></div>${badge(candidate.candidate_type || 'rule', '')}</div><pre>${esc(candidate.prompt_text || '')}</pre><div>${evidence || `<span class="muted">${esc(t('noActivity'))}</span>`}</div><form class="form-grid" onsubmit="return approveKnowledge(event, '${esc(candidate.candidate_id)}')"><label>${esc(t('scopeType'))}<select name="scope_type"><option value="route">route</option><option value="path">path</option><option value="symbol">symbol</option><option value="workstream">workstream</option><option value="global">global</option></select></label><label>${esc(t('scopeValue'))}<input name="scope_value" value=""></label><label>${esc(t('approvedBy'))}<input name="approved_by" value="${esc(window.localStorage.getItem('ddReviewer') || '')}" required></label><div class="action-row"><button class="primary-button" type="submit">${esc(t('approve'))}</button><button class="danger-button" type="button" onclick="rejectKnowledge('${esc(candidate.candidate_id)}')">${esc(t('reject'))}</button></div></form></article>`; }
|
|
2206
|
+
function renderKnowledge(data) { const review = data.knowledge_review || {}; const counts = review.counts || {}; const pending = review.pending_candidates || []; const active = review.active_knowledge || []; renderKnowledgeProposal(review); $('knowledge-count').textContent = `${counts.pending || 0} ${t('pending')}`; $('runtime-knowledge-count').textContent = `${counts.active || 0} ${t('active')}`; $('knowledge-candidates').innerHTML = review.available === false ? `<div class="empty">${esc(t('noKnowledgeTables'))}</div>` : pending.map(candidateCard).join('') || `<div class="empty">${esc(t('noPendingKnowledge'))}</div>`; $('runtime-knowledge-list').innerHTML = active.map((item) => `<article class="row-card"><div class="row-between"><strong>${esc(item.title)}</strong>${badge(`${item.scope_type}:${item.scope_value || 'global'}`, '')}</div><div class="muted">${esc(t('approvedBy'))} ${esc(item.approved_by)} / ${fmt(item.approved_at)}</div><pre>${esc(item.prompt_text || '')}</pre></article>`).join('') || `<div class="empty">${esc(t('noActiveKnowledge'))}</div>`; }
|
|
2207
|
+
function renderKnowledgeProposal(review) { const form = $('knowledge-propose-form'); const select = $('knowledge-propose-repo'); const repos = review.proposal_repos || []; select.innerHTML = repos.map((repo) => `<option value="${esc(repo.repo_id)}">${esc(repo.full_name || repo.repo_id)} (${repo.memory_count || 0} ${dl('memories')})</option>`).join(''); const disabled = review.available === false || repos.length === 0; form.querySelector('button').disabled = disabled; select.disabled = disabled; if (disabled && !repos.length) select.innerHTML = `<option value="">${esc(dl('No repositories'))}</option>`; }
|
|
2208
|
+
let controlSessionPromise = null;
|
|
2209
|
+
async function controlSession() { if (!controlSessionPromise) controlSessionPromise = fetch('/api/session', { cache: 'no-store' }).then((response) => response.json()); return controlSessionPromise; }
|
|
2210
|
+
async function postForm(url, formData) { const session = await controlSession(); const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', 'x-robert-csrf-token': session.csrf_token || '' }, body: new URLSearchParams(formData) }); const result = await response.json(); if (!result.ok) throw new Error(result.safe_error || result.status || 'request failed'); await loadDashboard(); setView('knowledge'); return result; }
|
|
2211
|
+
function approveKnowledge(event, candidateId) { event.preventDefault(); const form = new FormData(event.currentTarget); const approvedBy = form.get('approved_by') || ''; window.localStorage.setItem('ddReviewer', approvedBy); form.set('candidate_id', candidateId); postForm('/knowledge/approve', form).catch((error) => alert(error.message)); return false; }
|
|
2212
|
+
function rejectKnowledge(candidateId) { const reviewer = window.localStorage.getItem('ddReviewer') || window.prompt(t('reviewer')) || ''; if (!reviewer) return; const reviewNote = window.prompt(t('rejectReason')) || ''; postForm('/knowledge/reject', { candidate_id: candidateId, reviewer: reviewer, review_note: reviewNote }).catch((error) => alert(error.message)); }
|
|
2213
|
+
function proposeKnowledge(event) { event.preventDefault(); const form = new FormData(event.currentTarget); postForm('/knowledge/propose', form).catch((error) => alert(error.message)); return false; }
|
|
2214
|
+
function renderCommandActivity(data) { const items = (data.notification_center || []).filter(matchesSearchObject).slice(0, 8); $('activity-count').textContent = `${items.length} ${t('recent')}`; $('command-activity').innerHTML = items.length ? items.map(timelineCard).join('') : `<div class="empty">${esc(t('noActivity'))}</div>`; bindTaskButtons(); }
|
|
2215
|
+
function bindTaskButtons() { document.querySelectorAll('[data-open-task]').forEach((button) => { button.addEventListener('click', () => openTask(button.getAttribute('data-open-task'))); }); }
|
|
2216
|
+
function bindWorkItemButtons() { document.querySelectorAll('[data-work-item-id]').forEach((button) => { button.addEventListener('click', () => openWorkItem(button.getAttribute('data-work-item-id'))); }); }
|
|
2217
|
+
function renderAll() { const data = state.data; if (!data) return; $('repo-context').textContent = repoContext(data); $('dashboard-subtitle').textContent = `${data.summary?.repos || 0} ${dl('repo')} / ${data.summary?.workstreams || 0} ${dl('workstreams')} / ${data.summary?.github_events || 0} ${dl('events')}`; $('last-updated').textContent = `${t('updated')} ${fmt(new Date())}`; $('refresh-status').textContent = $('auto-refresh-toggle').checked ? `${t('every')} ${Number(state.autoRefreshIntervalMs) / 1000}s` : t('off'); renderNavCounts(data); renderMetrics(data); renderNextSteps(data); renderNowLane(data); renderCommandActivity(data); renderCommandInspector(data); renderDaemon(data); renderWorkFilters(data); renderTasks(data); renderTaskDetail(); renderTimeline(data); renderNotifications(data); renderKnowledge(data); }
|
|
2218
|
+
async function loadDashboard(options = {}) { try { if (options.reason === 'auto' && document.hidden) return; if (options.reason === 'auto') $('refresh-status').textContent = t('refresh'); const response = await fetch('/data.json', { cache: 'no-store' }); if (!response.ok) throw new Error(`HTTP ${response.status}`); state.data = await response.json(); chooseDefaultTask(state.data); renderAll(); } catch (error) { $('dashboard-app').insertAdjacentHTML('beforeend', `<div class="error">${esc(t('failedLoad'))}: ${esc(error.message)}</div>`); } finally { if ($('auto-refresh-toggle').checked) $('refresh-status').textContent = `${t('every')} ${Number(state.autoRefreshIntervalMs) / 1000}s`; } }
|
|
2219
|
+
function stopAutoRefresh() { if (state.autoRefreshTimer) window.clearInterval(state.autoRefreshTimer); state.autoRefreshTimer = null; }
|
|
2220
|
+
function startAutoRefresh() { stopAutoRefresh(); state.autoRefreshTimer = window.setInterval(() => loadDashboard({ reason: 'auto' }), state.autoRefreshIntervalMs); }
|
|
2221
|
+
function configureAutoRefresh() { const enabled = $('auto-refresh-toggle').checked; state.autoRefreshIntervalMs = Number($('refresh-interval').value || 30000); window.localStorage.setItem('ddAutoRefreshEnabled', enabled ? '1' : '0'); window.localStorage.setItem('ddAutoRefreshIntervalMs', String(state.autoRefreshIntervalMs)); $('refresh-status').textContent = enabled ? `${t('every')} ${state.autoRefreshIntervalMs / 1000}s` : t('off'); if (enabled) startAutoRefresh(); else stopAutoRefresh(); }
|
|
2222
|
+
function initAutoRefresh() { const savedInterval = Number(window.localStorage.getItem('ddAutoRefreshIntervalMs') || 30000); state.autoRefreshIntervalMs = [15000, 30000, 60000].includes(savedInterval) ? savedInterval : 30000; $('refresh-interval').value = String(state.autoRefreshIntervalMs); $('auto-refresh-toggle').checked = window.localStorage.getItem('ddAutoRefreshEnabled') === '1'; configureAutoRefresh(); $('auto-refresh-toggle').addEventListener('change', configureAutoRefresh); $('refresh-interval').addEventListener('change', configureAutoRefresh); document.addEventListener('visibilitychange', () => { if (!document.hidden && $('auto-refresh-toggle').checked) loadDashboard({ reason: 'visible' }); }); }
|
|
2223
|
+
$('theme-select').addEventListener('change', (event) => setTheme(event.target.value));
|
|
2224
|
+
$('language-select').addEventListener('change', (event) => setLanguage(event.target.value));
|
|
2225
|
+
$('work-search').addEventListener('input', (event) => { state.workSearchQuery = event.target.value || ''; chooseDefaultTask(state.data); renderAll(); });
|
|
2226
|
+
$('work-repo-filter').addEventListener('change', (event) => { state.workRepoFilter = event.target.value || ''; chooseDefaultTask(state.data); renderAll(); });
|
|
2227
|
+
document.querySelectorAll('[data-view]').forEach((button) => { button.addEventListener('click', () => setView(button.getAttribute('data-view'))); });
|
|
2228
|
+
document.querySelectorAll('[data-close-artifact-preview]').forEach((button) => { button.addEventListener('click', closeArtifactDrawer); });
|
|
2229
|
+
window.addEventListener('hashchange', applyHash);
|
|
2230
|
+
window.addEventListener('keydown', (event) => { if (event.key === 'Escape' && artifactPreviewOpen()) closeArtifactDrawer(); });
|
|
2231
|
+
$('knowledge-propose-form').addEventListener('submit', proposeKnowledge);
|
|
2232
|
+
$('refresh-button').addEventListener('click', () => loadDashboard({ reason: 'manual' }));
|
|
2233
|
+
applyPreferences();
|
|
2234
|
+
applyHash();
|
|
2235
|
+
initAutoRefresh();
|
|
2236
|
+
loadDashboard();
|
|
2237
|
+
</script>
|
|
2238
|
+
</body>
|
|
2239
|
+
</html>
|
|
2240
|
+
"""
|
|
2241
|
+
|
|
2242
|
+
|
|
2243
|
+
def _query_limit(query, default=50):
|
|
2244
|
+
raw = (query.get("limit") or [str(default)])[0]
|
|
2245
|
+
try:
|
|
2246
|
+
return int(raw)
|
|
2247
|
+
except (TypeError, ValueError) as exc:
|
|
2248
|
+
raise board.BoardQueryError("limit must be an integer") from exc
|
|
2249
|
+
|
|
2250
|
+
|
|
2251
|
+
def build_http_response(path, db_path, control_context=None):
|
|
2252
|
+
parsed = urlsplit(path)
|
|
2253
|
+
route = parsed.path
|
|
2254
|
+
if route == "/favicon.ico":
|
|
2255
|
+
return 204, {"content-type": "image/x-icon"}, b""
|
|
2256
|
+
if route in WEB_ASSETS:
|
|
2257
|
+
filename, content_type = WEB_ASSETS[route]
|
|
2258
|
+
try:
|
|
2259
|
+
payload = (WEB_ASSET_ROOT / filename).read_bytes()
|
|
2260
|
+
except OSError:
|
|
2261
|
+
return 404, {"content-type": "text/plain; charset=utf-8"}, b"not found\n"
|
|
2262
|
+
return 200, {"content-type": content_type}, payload
|
|
2263
|
+
if route == "/api/session":
|
|
2264
|
+
context = control_context
|
|
2265
|
+
payload = {
|
|
2266
|
+
"writes_enabled": bool(context and context.writes_enabled),
|
|
2267
|
+
"write_error": context.write_error if context else "Start with --config to enable writes.",
|
|
2268
|
+
"csrf_token": context.csrf_token if context else None,
|
|
2269
|
+
"operator_identity": context.operator_identity if context else None,
|
|
2270
|
+
"allowed_repo_ids": sorted(context.allowed_repo_ids) if context else [],
|
|
2271
|
+
"allowed_workers": sorted(context.allowed_workers) if context else [],
|
|
2272
|
+
}
|
|
2273
|
+
return _json_response(payload)
|
|
2274
|
+
if route == "/api/board":
|
|
2275
|
+
query = parse_qs(parsed.query)
|
|
2276
|
+
try:
|
|
2277
|
+
payload = board.list_board(
|
|
2278
|
+
db_path,
|
|
2279
|
+
repo=(query.get("repo") or [None])[0],
|
|
2280
|
+
column=(query.get("column") or [None])[0],
|
|
2281
|
+
agent=(query.get("agent") or [None])[0],
|
|
2282
|
+
priority=(query.get("priority") or [None])[0],
|
|
2283
|
+
attention=(query.get("attention") or [None])[0],
|
|
2284
|
+
query=(query.get("q") or [""])[0],
|
|
2285
|
+
limit=_query_limit(query),
|
|
2286
|
+
cursor=(query.get("cursor") or [None])[0],
|
|
2287
|
+
include_history=(query.get("include_history") or ["false"])[0].lower()
|
|
2288
|
+
in {"1", "true", "yes"},
|
|
2289
|
+
)
|
|
2290
|
+
except board.BoardQueryError as exc:
|
|
2291
|
+
return _json_response(
|
|
2292
|
+
{"ok": False, "status": "failed_validation", "safe_error": str(exc)},
|
|
2293
|
+
422,
|
|
2294
|
+
)
|
|
2295
|
+
return _json_response(payload)
|
|
2296
|
+
if route.startswith("/api/work-items/"):
|
|
2297
|
+
suffix = unquote(route[len("/api/work-items/") :])
|
|
2298
|
+
if not suffix or "/" in suffix.removesuffix("/events"):
|
|
2299
|
+
return _json_response({"ok": False, "status": "not_found"}, 404)
|
|
2300
|
+
if suffix.endswith("/events"):
|
|
2301
|
+
work_item_id = suffix[: -len("/events")]
|
|
2302
|
+
if board.get_work_item_detail(db_path, work_item_id) is None:
|
|
2303
|
+
return _json_response({"ok": False, "status": "not_found"}, 404)
|
|
2304
|
+
query = parse_qs(parsed.query)
|
|
2305
|
+
try:
|
|
2306
|
+
payload = board.list_work_item_events(
|
|
2307
|
+
db_path,
|
|
2308
|
+
work_item_id,
|
|
2309
|
+
limit=_query_limit(query),
|
|
2310
|
+
cursor=(query.get("cursor") or [None])[0],
|
|
2311
|
+
)
|
|
2312
|
+
except board.BoardQueryError as exc:
|
|
2313
|
+
return _json_response(
|
|
2314
|
+
{"ok": False, "status": "failed_validation", "safe_error": str(exc)},
|
|
2315
|
+
422,
|
|
2316
|
+
)
|
|
2317
|
+
return _json_response(payload)
|
|
2318
|
+
try:
|
|
2319
|
+
payload = board.get_work_item_detail(db_path, suffix)
|
|
2320
|
+
except sqlite3.OperationalError:
|
|
2321
|
+
payload = None
|
|
2322
|
+
if payload is not None:
|
|
2323
|
+
return _json_response(payload)
|
|
2324
|
+
try:
|
|
2325
|
+
payload = workbench.get_work_item(db_path, suffix)
|
|
2326
|
+
except sqlite3.OperationalError:
|
|
2327
|
+
return _json_response(
|
|
2328
|
+
{
|
|
2329
|
+
"ok": False,
|
|
2330
|
+
"status": "unavailable",
|
|
2331
|
+
"safe_error": "workbench data is unavailable for this database schema",
|
|
2332
|
+
},
|
|
2333
|
+
409,
|
|
2334
|
+
)
|
|
2335
|
+
if payload is None:
|
|
2336
|
+
return _json_response(
|
|
2337
|
+
{"ok": False, "status": "not_found", "safe_error": "work item not found"},
|
|
2338
|
+
404,
|
|
2339
|
+
)
|
|
2340
|
+
return _json_response(payload)
|
|
2341
|
+
if route == "/healthz":
|
|
2342
|
+
return 200, {"content-type": "text/plain; charset=utf-8"}, b"ok\n"
|
|
2343
|
+
if route == "/operations":
|
|
2344
|
+
payload = render_dashboard_html().encode("utf-8")
|
|
2345
|
+
return 200, {"content-type": "text/html; charset=utf-8"}, payload
|
|
2346
|
+
if route == "/api/work-items":
|
|
2347
|
+
query = parse_qs(parsed.query)
|
|
2348
|
+
try:
|
|
2349
|
+
raw_limit = (query.get("limit") or ["30"])[0]
|
|
2350
|
+
try:
|
|
2351
|
+
limit = int(raw_limit)
|
|
2352
|
+
except (TypeError, ValueError) as exc:
|
|
2353
|
+
raise workbench.WorkItemQueryError(
|
|
2354
|
+
"limit must be between 1 and 100"
|
|
2355
|
+
) from exc
|
|
2356
|
+
payload = workbench.list_work_items(
|
|
2357
|
+
db_path,
|
|
2358
|
+
bucket=(query.get("bucket") or [None])[0],
|
|
2359
|
+
repo=(query.get("repo") or [None])[0],
|
|
2360
|
+
actor=(query.get("actor") or [None])[0],
|
|
2361
|
+
query=(query.get("q") or [""])[0],
|
|
2362
|
+
sort=(query.get("sort") or ["priority"])[0],
|
|
2363
|
+
limit=limit,
|
|
2364
|
+
cursor=(query.get("cursor") or [None])[0],
|
|
2365
|
+
)
|
|
2366
|
+
except workbench.WorkItemQueryError as exc:
|
|
2367
|
+
return _json_response(
|
|
2368
|
+
{"ok": False, "status": "invalid_query", "safe_error": str(exc)},
|
|
2369
|
+
400,
|
|
2370
|
+
)
|
|
2371
|
+
except sqlite3.OperationalError:
|
|
2372
|
+
return _json_response(
|
|
2373
|
+
{
|
|
2374
|
+
"ok": False,
|
|
2375
|
+
"status": "unavailable",
|
|
2376
|
+
"safe_error": "workbench data is unavailable for this database schema",
|
|
2377
|
+
},
|
|
2378
|
+
409,
|
|
2379
|
+
)
|
|
2380
|
+
return _json_response(payload)
|
|
2381
|
+
if route in {"/data.json", "/history"}:
|
|
2382
|
+
payload = json.dumps(build_dashboard_data(db_path), ensure_ascii=False).encode()
|
|
2383
|
+
return 200, {"content-type": "application/json; charset=utf-8"}, payload
|
|
2384
|
+
if route == "/artifact.txt":
|
|
2385
|
+
query = parse_qs(parsed.query)
|
|
2386
|
+
preview = load_artifact_preview(
|
|
2387
|
+
db_path,
|
|
2388
|
+
(query.get("task_id") or [""])[0],
|
|
2389
|
+
(query.get("artifact_type") or [""])[0],
|
|
2390
|
+
)
|
|
2391
|
+
if not preview:
|
|
2392
|
+
return 404, {"content-type": "text/plain; charset=utf-8"}, b"artifact not found\n"
|
|
2393
|
+
if preview.get("missing"):
|
|
2394
|
+
return 404, {"content-type": "text/plain; charset=utf-8"}, render_artifact_preview_text(preview)
|
|
2395
|
+
return 200, {"content-type": "text/plain; charset=utf-8"}, render_artifact_preview_text(preview)
|
|
2396
|
+
return 404, {"content-type": "text/plain; charset=utf-8"}, b"not found\n"
|
|
2397
|
+
|
|
2398
|
+
|
|
2399
|
+
def _json_response(payload, status=200):
|
|
2400
|
+
return (
|
|
2401
|
+
status,
|
|
2402
|
+
{"content-type": "application/json; charset=utf-8"},
|
|
2403
|
+
json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8"),
|
|
2404
|
+
)
|
|
2405
|
+
|
|
2406
|
+
|
|
2407
|
+
def _lower_headers(headers):
|
|
2408
|
+
if not headers:
|
|
2409
|
+
return {}
|
|
2410
|
+
return {str(key).lower(): str(value) for key, value in headers.items()}
|
|
2411
|
+
|
|
2412
|
+
|
|
2413
|
+
def _control_request_error(control_context, headers, *, json_required):
|
|
2414
|
+
if not control_context:
|
|
2415
|
+
return _json_response(
|
|
2416
|
+
{"ok": False, "status": "unavailable", "safe_error": "writes are disabled"},
|
|
2417
|
+
503,
|
|
2418
|
+
)
|
|
2419
|
+
allowed_hosts = {urlsplit(origin).netloc for origin in control_context.allowed_origins}
|
|
2420
|
+
if headers.get("host") not in allowed_hosts:
|
|
2421
|
+
return _json_response(
|
|
2422
|
+
{"ok": False, "status": "forbidden", "safe_error": "invalid Host"},
|
|
2423
|
+
403,
|
|
2424
|
+
)
|
|
2425
|
+
if headers.get("origin") not in control_context.allowed_origins:
|
|
2426
|
+
return _json_response(
|
|
2427
|
+
{"ok": False, "status": "forbidden", "safe_error": "invalid Origin"},
|
|
2428
|
+
403,
|
|
2429
|
+
)
|
|
2430
|
+
if headers.get("x-robert-csrf-token") != control_context.csrf_token:
|
|
2431
|
+
return _json_response(
|
|
2432
|
+
{"ok": False, "status": "forbidden", "safe_error": "invalid CSRF token"},
|
|
2433
|
+
403,
|
|
2434
|
+
)
|
|
2435
|
+
content_type = headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
|
2436
|
+
expected = "application/json" if json_required else "application/x-www-form-urlencoded"
|
|
2437
|
+
if content_type != expected:
|
|
2438
|
+
return _json_response(
|
|
2439
|
+
{"ok": False, "status": "unsupported_media_type", "safe_error": f"content-type must be {expected}"},
|
|
2440
|
+
415,
|
|
2441
|
+
)
|
|
2442
|
+
return None
|
|
2443
|
+
|
|
2444
|
+
|
|
2445
|
+
def _work_item_context(control_context):
|
|
2446
|
+
return work_items.CommandContext(
|
|
2447
|
+
actor_kind="operator",
|
|
2448
|
+
actor_identity=control_context.operator_identity,
|
|
2449
|
+
allowed_repo_ids=control_context.allowed_repo_ids,
|
|
2450
|
+
allowed_workers=control_context.allowed_workers,
|
|
2451
|
+
)
|
|
2452
|
+
|
|
2453
|
+
|
|
2454
|
+
def _handle_work_item_post(route, body, db_path, control_context, headers):
|
|
2455
|
+
request_error = _control_request_error(control_context, headers, json_required=True)
|
|
2456
|
+
if request_error:
|
|
2457
|
+
return request_error
|
|
2458
|
+
if not control_context.writes_enabled:
|
|
2459
|
+
return _json_response(
|
|
2460
|
+
{
|
|
2461
|
+
"ok": False,
|
|
2462
|
+
"status": "unavailable",
|
|
2463
|
+
"safe_error": control_context.write_error or "writes are disabled",
|
|
2464
|
+
},
|
|
2465
|
+
503,
|
|
2466
|
+
)
|
|
2467
|
+
idempotency_key = headers.get("x-idempotency-key")
|
|
2468
|
+
if not idempotency_key:
|
|
2469
|
+
return _json_response(
|
|
2470
|
+
{"ok": False, "status": "failed_validation", "safe_error": "X-Idempotency-Key is required"},
|
|
2471
|
+
422,
|
|
2472
|
+
)
|
|
2473
|
+
try:
|
|
2474
|
+
payload = json.loads(body.decode("utf-8"))
|
|
2475
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
2476
|
+
return _json_response(
|
|
2477
|
+
{"ok": False, "status": "failed_validation", "safe_error": "invalid JSON body"},
|
|
2478
|
+
422,
|
|
2479
|
+
)
|
|
2480
|
+
if not isinstance(payload, dict):
|
|
2481
|
+
return _json_response(
|
|
2482
|
+
{"ok": False, "status": "failed_validation", "safe_error": "JSON body must be an object"},
|
|
2483
|
+
422,
|
|
2484
|
+
)
|
|
2485
|
+
try:
|
|
2486
|
+
if route == "/api/work-items":
|
|
2487
|
+
mode = payload.get("mode", "backlog")
|
|
2488
|
+
if mode not in {"backlog", "start"}:
|
|
2489
|
+
raise work_items.WorkItemValidationError("mode must be backlog or start")
|
|
2490
|
+
result = work_items.create_work_item(
|
|
2491
|
+
db_path,
|
|
2492
|
+
context=_work_item_context(control_context),
|
|
2493
|
+
repo_id=payload.get("repo_id"),
|
|
2494
|
+
title=payload.get("title", ""),
|
|
2495
|
+
description=payload.get("description", ""),
|
|
2496
|
+
priority=payload.get("priority", "P2"),
|
|
2497
|
+
routing_mode=payload.get("routing_mode", "auto"),
|
|
2498
|
+
requested_worker=payload.get("requested_worker"),
|
|
2499
|
+
start=mode == "start",
|
|
2500
|
+
idempotency_key=idempotency_key,
|
|
2501
|
+
)
|
|
2502
|
+
detail = board.get_work_item_detail(db_path, result["item"]["work_item_id"])
|
|
2503
|
+
return _json_response(detail, 201)
|
|
2504
|
+
prefix = "/api/work-items/"
|
|
2505
|
+
suffix = unquote(route[len(prefix) :])
|
|
2506
|
+
if not suffix.endswith("/commands"):
|
|
2507
|
+
return _json_response({"ok": False, "status": "not_found"}, 404)
|
|
2508
|
+
work_item_id = suffix[: -len("/commands")]
|
|
2509
|
+
result = work_items.execute_command(
|
|
2510
|
+
db_path,
|
|
2511
|
+
work_item_id,
|
|
2512
|
+
context=_work_item_context(control_context),
|
|
2513
|
+
command=payload.get("command"),
|
|
2514
|
+
expected_version=payload.get("expected_version"),
|
|
2515
|
+
idempotency_key=idempotency_key,
|
|
2516
|
+
body=payload.get("body", ""),
|
|
2517
|
+
routing_mode=payload.get("routing_mode"),
|
|
2518
|
+
requested_worker=payload.get("requested_worker"),
|
|
2519
|
+
title=payload.get("title"),
|
|
2520
|
+
description=payload.get("description"),
|
|
2521
|
+
priority=payload.get("priority"),
|
|
2522
|
+
)
|
|
2523
|
+
detail = board.get_work_item_detail(db_path, result["item"]["work_item_id"])
|
|
2524
|
+
return _json_response(detail)
|
|
2525
|
+
except work_items.WorkItemNotFoundError:
|
|
2526
|
+
return _json_response({"ok": False, "status": "not_found"}, 404)
|
|
2527
|
+
except work_items.WorkItemValidationError as exc:
|
|
2528
|
+
return _json_response(
|
|
2529
|
+
{"ok": False, "status": "failed_validation", "safe_error": str(exc)},
|
|
2530
|
+
422,
|
|
2531
|
+
)
|
|
2532
|
+
except work_items.WorkItemConflictError as exc:
|
|
2533
|
+
current = None
|
|
2534
|
+
if route.startswith("/api/work-items/"):
|
|
2535
|
+
work_item_id = unquote(route[len("/api/work-items/") :]).removesuffix("/commands")
|
|
2536
|
+
current = board.get_work_item_detail(db_path, work_item_id)
|
|
2537
|
+
return _json_response(
|
|
2538
|
+
{"ok": False, "status": "conflict", "safe_error": str(exc), "current": current},
|
|
2539
|
+
409,
|
|
2540
|
+
)
|
|
2541
|
+
|
|
2542
|
+
|
|
2543
|
+
def handle_dashboard_post(path, body, db_path, control_context=None, request_headers=None):
|
|
2544
|
+
route = urlsplit(path).path
|
|
2545
|
+
if len(body) > 64 * 1024:
|
|
2546
|
+
return _json_response(
|
|
2547
|
+
{"ok": False, "status": "payload_too_large", "safe_error": "request body exceeds 64 KiB"},
|
|
2548
|
+
413,
|
|
2549
|
+
)
|
|
2550
|
+
headers = _lower_headers(request_headers)
|
|
2551
|
+
if route == "/api/work-items" or (
|
|
2552
|
+
route.startswith("/api/work-items/") and route.endswith("/commands")
|
|
2553
|
+
):
|
|
2554
|
+
return _handle_work_item_post(route, body, db_path, control_context, headers)
|
|
2555
|
+
if control_context and route.startswith("/knowledge/"):
|
|
2556
|
+
request_error = _control_request_error(control_context, headers, json_required=False)
|
|
2557
|
+
if request_error:
|
|
2558
|
+
return request_error
|
|
2559
|
+
if not control_context.writes_enabled:
|
|
2560
|
+
return _json_response(
|
|
2561
|
+
{
|
|
2562
|
+
"ok": False,
|
|
2563
|
+
"status": "unavailable",
|
|
2564
|
+
"safe_error": control_context.write_error or "writes are disabled",
|
|
2565
|
+
},
|
|
2566
|
+
503,
|
|
2567
|
+
)
|
|
2568
|
+
form = parse_qs(body.decode("utf-8"))
|
|
2569
|
+
|
|
2570
|
+
def field(name):
|
|
2571
|
+
return (form.get(name) or [""])[0]
|
|
2572
|
+
|
|
2573
|
+
run_now = datetime.now(timezone.utc).isoformat()
|
|
2574
|
+
if route.startswith("/knowledge/"):
|
|
2575
|
+
with closing(sqlite3.connect(db_path)) as conn:
|
|
2576
|
+
if not _knowledge_tables_available(conn):
|
|
2577
|
+
return _json_response(
|
|
2578
|
+
{
|
|
2579
|
+
"ok": False,
|
|
2580
|
+
"status": "unavailable",
|
|
2581
|
+
"safe_error": "Knowledge tables are not available in this database yet.",
|
|
2582
|
+
},
|
|
2583
|
+
400,
|
|
2584
|
+
)
|
|
2585
|
+
if route == "/knowledge/propose":
|
|
2586
|
+
repo_id = field("repo_id")
|
|
2587
|
+
if not repo_id:
|
|
2588
|
+
return _json_response(
|
|
2589
|
+
{
|
|
2590
|
+
"ok": False,
|
|
2591
|
+
"status": "failed_validation",
|
|
2592
|
+
"safe_error": "repo_id is required",
|
|
2593
|
+
},
|
|
2594
|
+
400,
|
|
2595
|
+
)
|
|
2596
|
+
with closing(sqlite3.connect(db_path)) as conn, conn:
|
|
2597
|
+
result = runtime_knowledge.propose_candidates(
|
|
2598
|
+
conn,
|
|
2599
|
+
repo_id=repo_id,
|
|
2600
|
+
run_now=run_now,
|
|
2601
|
+
)
|
|
2602
|
+
status = 200 if result.get("ok") else 400
|
|
2603
|
+
return _json_response(result, status)
|
|
2604
|
+
if route == "/knowledge/approve":
|
|
2605
|
+
with closing(sqlite3.connect(db_path)) as conn, conn:
|
|
2606
|
+
result = runtime_knowledge.approve_candidate(
|
|
2607
|
+
conn,
|
|
2608
|
+
candidate_id=field("candidate_id"),
|
|
2609
|
+
scope_type=field("scope_type"),
|
|
2610
|
+
scope_value=field("scope_value"),
|
|
2611
|
+
approved_by=field("approved_by"),
|
|
2612
|
+
run_now=run_now,
|
|
2613
|
+
)
|
|
2614
|
+
status = 200 if result.get("ok") else 400
|
|
2615
|
+
return _json_response(result, status)
|
|
2616
|
+
if route == "/knowledge/reject":
|
|
2617
|
+
with closing(sqlite3.connect(db_path)) as conn, conn:
|
|
2618
|
+
result = runtime_knowledge.reject_candidate(
|
|
2619
|
+
conn,
|
|
2620
|
+
candidate_id=field("candidate_id"),
|
|
2621
|
+
reviewer=field("reviewer"),
|
|
2622
|
+
review_note=field("review_note"),
|
|
2623
|
+
run_now=run_now,
|
|
2624
|
+
)
|
|
2625
|
+
status = 200 if result.get("ok") else 400
|
|
2626
|
+
return _json_response(result, status)
|
|
2627
|
+
return _json_response(
|
|
2628
|
+
{
|
|
2629
|
+
"ok": False,
|
|
2630
|
+
"status": "unsupported",
|
|
2631
|
+
"safe_error": "unsupported dashboard action",
|
|
2632
|
+
},
|
|
2633
|
+
404,
|
|
2634
|
+
)
|
|
2635
|
+
|
|
2636
|
+
|
|
2637
|
+
def make_handler(db_path, control_context=None):
|
|
2638
|
+
class Handler(BaseHTTPRequestHandler):
|
|
2639
|
+
def _send(self, status, headers, payload):
|
|
2640
|
+
self.send_response(status)
|
|
2641
|
+
for name, value in headers.items():
|
|
2642
|
+
self.send_header(name, value)
|
|
2643
|
+
self.send_header("content-length", str(len(payload)))
|
|
2644
|
+
self.end_headers()
|
|
2645
|
+
self.wfile.write(payload)
|
|
2646
|
+
|
|
2647
|
+
def do_GET(self):
|
|
2648
|
+
try:
|
|
2649
|
+
response = build_http_response(
|
|
2650
|
+
self.path,
|
|
2651
|
+
db_path,
|
|
2652
|
+
control_context=control_context,
|
|
2653
|
+
)
|
|
2654
|
+
except Exception:
|
|
2655
|
+
response = _json_response(
|
|
2656
|
+
{
|
|
2657
|
+
"ok": False,
|
|
2658
|
+
"status": "internal_error",
|
|
2659
|
+
"safe_error": "request failed",
|
|
2660
|
+
},
|
|
2661
|
+
500,
|
|
2662
|
+
)
|
|
2663
|
+
self._send(*response)
|
|
2664
|
+
|
|
2665
|
+
def do_POST(self):
|
|
2666
|
+
try:
|
|
2667
|
+
length = int(self.headers.get("content-length") or "0")
|
|
2668
|
+
except ValueError:
|
|
2669
|
+
self._send(
|
|
2670
|
+
*_json_response(
|
|
2671
|
+
{
|
|
2672
|
+
"ok": False,
|
|
2673
|
+
"status": "failed_validation",
|
|
2674
|
+
"safe_error": "invalid content-length",
|
|
2675
|
+
},
|
|
2676
|
+
400,
|
|
2677
|
+
)
|
|
2678
|
+
)
|
|
2679
|
+
return
|
|
2680
|
+
if length < 0:
|
|
2681
|
+
self._send(
|
|
2682
|
+
*_json_response(
|
|
2683
|
+
{
|
|
2684
|
+
"ok": False,
|
|
2685
|
+
"status": "failed_validation",
|
|
2686
|
+
"safe_error": "invalid content-length",
|
|
2687
|
+
},
|
|
2688
|
+
400,
|
|
2689
|
+
)
|
|
2690
|
+
)
|
|
2691
|
+
return
|
|
2692
|
+
if length > 64 * 1024:
|
|
2693
|
+
self.close_connection = True
|
|
2694
|
+
self._send(
|
|
2695
|
+
*_json_response(
|
|
2696
|
+
{
|
|
2697
|
+
"ok": False,
|
|
2698
|
+
"status": "payload_too_large",
|
|
2699
|
+
"safe_error": "request body exceeds 64 KiB",
|
|
2700
|
+
},
|
|
2701
|
+
413,
|
|
2702
|
+
)
|
|
2703
|
+
)
|
|
2704
|
+
return
|
|
2705
|
+
try:
|
|
2706
|
+
body = self.rfile.read(length)
|
|
2707
|
+
response = handle_dashboard_post(
|
|
2708
|
+
self.path,
|
|
2709
|
+
body,
|
|
2710
|
+
db_path,
|
|
2711
|
+
control_context=control_context,
|
|
2712
|
+
request_headers=dict(self.headers.items()),
|
|
2713
|
+
)
|
|
2714
|
+
except Exception:
|
|
2715
|
+
response = _json_response(
|
|
2716
|
+
{
|
|
2717
|
+
"ok": False,
|
|
2718
|
+
"status": "internal_error",
|
|
2719
|
+
"safe_error": "request failed",
|
|
2720
|
+
},
|
|
2721
|
+
500,
|
|
2722
|
+
)
|
|
2723
|
+
self._send(*response)
|
|
2724
|
+
|
|
2725
|
+
def log_message(self, *_args):
|
|
2726
|
+
return
|
|
2727
|
+
|
|
2728
|
+
return Handler
|
|
2729
|
+
|
|
2730
|
+
|
|
2731
|
+
def _upsert_control_repo(conn, repo):
|
|
2732
|
+
repo_id = f"repo:{repo['full_name']}"
|
|
2733
|
+
conn.execute(
|
|
2734
|
+
"""
|
|
2735
|
+
INSERT INTO repos(
|
|
2736
|
+
repo_id, full_name, github_account, default_base_branch, repo_root, worktree_root, enabled
|
|
2737
|
+
)
|
|
2738
|
+
VALUES (?, ?, ?, ?, ?, ?, 1)
|
|
2739
|
+
ON CONFLICT(repo_id) DO UPDATE SET
|
|
2740
|
+
full_name = excluded.full_name,
|
|
2741
|
+
github_account = excluded.github_account,
|
|
2742
|
+
default_base_branch = excluded.default_base_branch,
|
|
2743
|
+
repo_root = excluded.repo_root,
|
|
2744
|
+
worktree_root = excluded.worktree_root,
|
|
2745
|
+
enabled = excluded.enabled
|
|
2746
|
+
""",
|
|
2747
|
+
(
|
|
2748
|
+
repo_id,
|
|
2749
|
+
repo["full_name"],
|
|
2750
|
+
repo["github_account"],
|
|
2751
|
+
repo["default_base_branch"],
|
|
2752
|
+
repo["repo_root"],
|
|
2753
|
+
repo["worktree_root"],
|
|
2754
|
+
),
|
|
2755
|
+
)
|
|
2756
|
+
return repo_id
|
|
2757
|
+
|
|
2758
|
+
|
|
2759
|
+
def build_control_context_from_config(
|
|
2760
|
+
config_path,
|
|
2761
|
+
*,
|
|
2762
|
+
host,
|
|
2763
|
+
port,
|
|
2764
|
+
operator_identity,
|
|
2765
|
+
csrf_token=None,
|
|
2766
|
+
):
|
|
2767
|
+
config_result = validate_config.validate_config(config_path, skip_external=True)
|
|
2768
|
+
if not config_result["ok"]:
|
|
2769
|
+
raise ValueError(config_result["safe_error"])
|
|
2770
|
+
db_path = config_result["db_path"]
|
|
2771
|
+
storage.init_database(db_path)
|
|
2772
|
+
with closing(sqlite3.connect(db_path)) as conn, conn:
|
|
2773
|
+
allowed_repo_ids = frozenset(
|
|
2774
|
+
_upsert_control_repo(conn, repo) for repo in config_result["repos"]
|
|
2775
|
+
)
|
|
2776
|
+
return ControlContext(
|
|
2777
|
+
db_path=db_path,
|
|
2778
|
+
operator_identity=operator_identity,
|
|
2779
|
+
allowed_repo_ids=allowed_repo_ids,
|
|
2780
|
+
allowed_workers=frozenset(worker["name"] for worker in config_result["workers"]),
|
|
2781
|
+
allowed_origins=frozenset({f"http://{host}:{port}"}),
|
|
2782
|
+
csrf_token=csrf_token or secrets.token_urlsafe(32),
|
|
2783
|
+
writes_enabled=True,
|
|
2784
|
+
write_error=None,
|
|
2785
|
+
)
|
|
2786
|
+
|
|
2787
|
+
|
|
2788
|
+
def build_read_only_control_context(db_path, *, host, port):
|
|
2789
|
+
return ControlContext(
|
|
2790
|
+
db_path=str(db_path),
|
|
2791
|
+
operator_identity="local-operator",
|
|
2792
|
+
allowed_repo_ids=frozenset(),
|
|
2793
|
+
allowed_workers=frozenset(),
|
|
2794
|
+
allowed_origins=frozenset({f"http://{host}:{port}"}),
|
|
2795
|
+
csrf_token=secrets.token_urlsafe(32),
|
|
2796
|
+
writes_enabled=False,
|
|
2797
|
+
write_error="Start with --config to enable writes.",
|
|
2798
|
+
)
|
|
2799
|
+
|
|
2800
|
+
|
|
2801
|
+
def serve(db_path, host="127.0.0.1", port=8765, control_context=None):
|
|
2802
|
+
if control_context is None:
|
|
2803
|
+
control_context = build_read_only_control_context(db_path, host=host, port=port)
|
|
2804
|
+
server = ThreadingHTTPServer(
|
|
2805
|
+
(host, port),
|
|
2806
|
+
make_handler(db_path, control_context),
|
|
2807
|
+
)
|
|
2808
|
+
server.serve_forever()
|
|
2809
|
+
|
|
2810
|
+
|
|
2811
|
+
def main(argv=None):
|
|
2812
|
+
parser = argparse.ArgumentParser()
|
|
2813
|
+
source = parser.add_mutually_exclusive_group()
|
|
2814
|
+
source.add_argument("--db")
|
|
2815
|
+
source.add_argument("--config")
|
|
2816
|
+
parser.add_argument("--host", default="127.0.0.1")
|
|
2817
|
+
parser.add_argument("--port", type=int, default=8765)
|
|
2818
|
+
parser.add_argument("--operator", default="local-operator")
|
|
2819
|
+
parser.add_argument("--writable", action="store_true")
|
|
2820
|
+
parser.add_argument("--allow-remote", action="store_true")
|
|
2821
|
+
parser.add_argument("--json", action="store_true")
|
|
2822
|
+
args = parser.parse_args(argv)
|
|
2823
|
+
options = validate_server_options(
|
|
2824
|
+
args.host,
|
|
2825
|
+
args.writable,
|
|
2826
|
+
args.allow_remote,
|
|
2827
|
+
)
|
|
2828
|
+
if not options["ok"]:
|
|
2829
|
+
return emit(options, 4)
|
|
2830
|
+
if args.writable and not args.config:
|
|
2831
|
+
return emit(
|
|
2832
|
+
{
|
|
2833
|
+
"ok": False,
|
|
2834
|
+
"status": "failed_input",
|
|
2835
|
+
"safe_error": "--writable requires --config",
|
|
2836
|
+
},
|
|
2837
|
+
3,
|
|
2838
|
+
)
|
|
2839
|
+
if args.config:
|
|
2840
|
+
config_result = validate_config.validate_config(
|
|
2841
|
+
args.config,
|
|
2842
|
+
skip_external=True,
|
|
2843
|
+
)
|
|
2844
|
+
if not config_result["ok"]:
|
|
2845
|
+
return emit(config_result, 3)
|
|
2846
|
+
db_path = config_result["db_path"]
|
|
2847
|
+
if args.writable:
|
|
2848
|
+
try:
|
|
2849
|
+
control_context = build_control_context_from_config(
|
|
2850
|
+
args.config,
|
|
2851
|
+
host=args.host,
|
|
2852
|
+
port=args.port,
|
|
2853
|
+
operator_identity=args.operator,
|
|
2854
|
+
)
|
|
2855
|
+
except ValueError as exc:
|
|
2856
|
+
return emit(
|
|
2857
|
+
{
|
|
2858
|
+
"ok": False,
|
|
2859
|
+
"status": "failed_config",
|
|
2860
|
+
"safe_error": str(exc),
|
|
2861
|
+
},
|
|
2862
|
+
3,
|
|
2863
|
+
)
|
|
2864
|
+
else:
|
|
2865
|
+
control_context = build_read_only_control_context(
|
|
2866
|
+
db_path,
|
|
2867
|
+
host=args.host,
|
|
2868
|
+
port=args.port,
|
|
2869
|
+
)
|
|
2870
|
+
elif args.db:
|
|
2871
|
+
db_path = args.db
|
|
2872
|
+
control_context = build_read_only_control_context(
|
|
2873
|
+
db_path,
|
|
2874
|
+
host=args.host,
|
|
2875
|
+
port=args.port,
|
|
2876
|
+
)
|
|
2877
|
+
else:
|
|
2878
|
+
return emit(
|
|
2879
|
+
{
|
|
2880
|
+
"ok": False,
|
|
2881
|
+
"status": "failed_input",
|
|
2882
|
+
"safe_error": "--config or --db is required",
|
|
2883
|
+
},
|
|
2884
|
+
3,
|
|
2885
|
+
)
|
|
2886
|
+
if args.json:
|
|
2887
|
+
return emit({"ok": True, "status": "ready", "data": build_dashboard_data(db_path)})
|
|
2888
|
+
serve(db_path, args.host, args.port, control_context=control_context)
|
|
2889
|
+
return 0
|
|
2890
|
+
|
|
2891
|
+
|
|
2892
|
+
if __name__ == "__main__":
|
|
2893
|
+
raise SystemExit(main())
|