-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatcher_status_pane.py
More file actions
1896 lines (1691 loc) · 73.8 KB
/
Copy pathwatcher_status_pane.py
File metadata and controls
1896 lines (1691 loc) · 73.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2026 Velascat
"""Curses watcher-status pane — dense at-a-glance OperationsCenter monitor.
Sections (always visible):
Roles — running/stopped, pid, uptime, restart count (⚡)
Campaigns — active kodo campaigns from OC state
Queue — pending tasks filtered by --profile
SwitchBoard — health check
Resources — load avg, RAM bar, swap bar
Arrows navigate roles. Enter opens action submenu:
tail logs, board, circuit breaker, memory
Usage: python3 -m operator_console.watcher_status_pane [--profile <name>]
"""
from __future__ import annotations
import curses
import json
import os
import re
import subprocess
import sys
import threading
import time
import urllib.request
from pathlib import Path
_OC_ROOT = Path.home() / "Documents" / "GitHub" / "OperationsCenter"
_WATCH_DIR = _OC_ROOT / "logs" / "local" / "watch-all"
_STATE_DIR = _OC_ROOT / "state"
_QUEUE_DIR = Path.home() / ".console" / "queue"
_PROFILES_DIR = Path(__file__).resolve().parent.parent.parent / "config" / "profiles"
_ROLES = ("intake", "goal", "test", "improve", "propose", "review", "spec", "watchdog")
_ACTIONS = ("tail logs", "board", "circuit breaker", "memory")
REFRESH_INTERVAL = 3
PLANE_REFRESH_INTERVAL = 30
LOG_TAIL_LINES = 60
BAR_W = 10 # width of █ progress bars
_OC_CONFIG = _OC_ROOT / "config" / "operations_center.local.yaml"
# States shown in each section
_BOARD_STATES = {"ready for ai", "backlog"}
_ACTIVE_STATES = {"running"}
# ── Plane data collection ────────────────────────────────────────────────────
def _plane_config() -> dict | None:
"""Parse OC config for Plane connection details. Returns None if not configured.
Avoids depending on PyYAML — the pane's Python may be a bare interpreter
(e.g. pyenv system Python without site-packages). The `plane:` block is
simple key-value pairs, so a manual parse is sufficient and robust.
"""
if not _OC_CONFIG.exists():
return None
out = {
"base_url": "http://localhost:8080",
"workspace_slug": "",
"project_id": "",
"token_env": "PLANE_API_TOKEN",
}
in_plane = False
try:
for raw in _OC_CONFIG.read_text(encoding="utf-8").splitlines():
stripped = raw.rstrip()
if not stripped or stripped.lstrip().startswith("#"):
continue
if not stripped.startswith(" ") and not stripped.startswith("\t"):
in_plane = stripped.startswith("plane:")
continue
if not in_plane:
continue
line = stripped.strip()
if ":" not in line:
continue
k, _, v = line.partition(":")
v = v.strip().strip('"').strip("'")
if not v:
continue
if k.strip() == "base_url":
out["base_url"] = v.rstrip("/")
elif k.strip() == "workspace_slug":
out["workspace_slug"] = v
elif k.strip() == "project_id":
out["project_id"] = v
elif k.strip() == "api_token_env":
out["token_env"] = v
except Exception:
return None
if not out["workspace_slug"] or not out["project_id"]:
return None
return out
def _read_token_from_env_file(token_env: str) -> str:
"""Read the Plane token from OperationsCenter's .env file.
The status pane often outlives a token rotation; reading from the env file
each fetch keeps it in sync without requiring a pane restart.
"""
env_file = _OC_ROOT / ".env.operations-center.local"
if not env_file.exists():
return ""
try:
for raw in env_file.read_text(encoding="utf-8").splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
if line.startswith("export "):
line = line[len("export "):]
k, _, v = line.partition("=")
if k.strip() == token_env:
return v.strip().strip('"').strip("'")
except Exception:
pass
return ""
def _plane_get(cfg: dict, token: str, path: str) -> list[dict]:
url = f"{cfg['base_url']}/api/v1/workspaces/{cfg['workspace_slug']}/projects/{cfg['project_id']}/{path}"
req = urllib.request.Request(url, headers={"X-API-Key": token})
try:
with urllib.request.urlopen(req, timeout=4) as r:
payload = json.loads(r.read())
if isinstance(payload, list):
return payload
if isinstance(payload, dict):
return payload.get("results", [])
except Exception:
return []
return []
def _plane_fetch(cfg: dict) -> list[dict]:
"""Fetch all work items from Plane with label IDs hydrated to names. [] on error."""
token = _read_token_from_env_file(cfg["token_env"]) or os.environ.get(cfg["token_env"], "")
if not token or not cfg["workspace_slug"] or not cfg["project_id"]:
return []
issues = _plane_get(cfg, token, "work-items/?expand=state")
if not issues:
return []
# Plane returns label refs as UUIDs; resolve to names so _repo_from_labels works.
labels = _plane_get(cfg, token, "labels/")
by_id = {str(lab.get("id")): lab for lab in labels if isinstance(lab, dict) and lab.get("id")}
for issue in issues:
raw = issue.get("labels") or []
if raw and not all(isinstance(r, dict) for r in raw):
issue["labels"] = [by_id.get(str(r), {"name": ""}) if not isinstance(r, dict) else r for r in raw]
return issues
def _repo_from_labels(labels: list) -> str:
for lab in labels:
name = (lab.get("name", "") if isinstance(lab, dict) else str(lab)).strip()
if name.lower().startswith("repo:"):
return name.split(":", 1)[1].strip()
return ""
def _plane_issues(repo_filter: set[str] | None) -> dict[str, list[dict]]:
"""Return {"active": [...], "board": [...]} filtered by repo_filter."""
cfg = _plane_config()
if not cfg:
return {"active": [], "board": []}
issues = _plane_fetch(cfg)
active, board = [], []
for issue in issues:
state_obj = issue.get("state")
state_name = (state_obj.get("name", "") if isinstance(state_obj, dict) else str(state_obj or "")).strip()
state_lower = state_name.lower()
labels = issue.get("labels", [])
repo = _repo_from_labels(labels)
if repo_filter and repo not in repo_filter:
continue
item = {
"title": issue.get("name", "Untitled"),
"state": state_name,
"repo": repo or "?",
}
if state_lower in _ACTIVE_STATES:
active.append(item)
elif state_lower in _BOARD_STATES:
board.append(item)
return {"active": active, "board": board}
# ── data collection ───────────────────────────────────────────────────────────
def _pid_alive(pid: str) -> bool:
try:
return subprocess.run(["kill", "-0", pid], capture_output=True).returncode == 0
except Exception:
return False
_STALE_HEARTBEAT_S = 600 # 10 minutes — alert threshold
# Banner severity ordering: CRIT > WARN > INFO > HEALTHY. The cycle
# always renders all active conditions regardless of level; the
# severity tag drives the banner's color.
BANNER_CRIT = "critical"
BANNER_WARN = "warning"
BANNER_INFO = "info"
BANNER_HEALTHY = "healthy"
_BANNER_LEVEL_ORDER = (BANNER_CRIT, BANNER_WARN, BANNER_INFO, BANNER_HEALTHY)
def _banner_color(level: str, C: dict) -> int:
"""Pick the color attr for a banner of a given severity."""
return {
BANNER_CRIT: C["BANNER_CRIT"],
BANNER_WARN: C["BANNER_WARN"],
BANNER_INFO: C["BANNER_INFO"],
BANNER_HEALTHY: C["BANNER_HEALTHY"],
}.get(level, C["BANNER_HEALTHY"]) | curses.A_BOLD
def _banner_conditions(data: dict, started_at: float) -> list[tuple[str, str]]:
"""Build the active banner list from a snapshot.
Returns a list of ``(severity, message)`` tuples sorted worst-first.
When nothing is wrong, returns a single HEALTHY entry so the always-on
ribbon still renders.
"""
conds: list[tuple[str, str]] = []
# ── CRITICAL ──
stale = _stale_heartbeat_roles()
if stale:
conds.append((
BANNER_CRIT,
f"⚠ STALL ALERT — {len(stale)} role(s) silent > "
f"{_STALE_HEARTBEAT_S // 60}min: {', '.join(stale)}",
))
if data.get("sb") is False:
conds.append((
BANNER_CRIT,
"⚠ SwitchBoard Offline — Lane Selection Unavailable",
))
# Resource gate at saturation = critical
gate = data.get("resource_gate") or {}
usage = data.get("backend_usage") or {}
res = data.get("resources") or {}
total_in_flight = sum(int(b.get("in_flight", 0)) for b in usage.values())
mc = gate.get("max_concurrent")
if mc is not None and total_in_flight >= mc:
conds.append((
BANNER_CRIT,
f"⚠ Global Gate at Cap — {total_in_flight}/{mc} Dispatches "
"in Flight; New Runs Blocked",
))
floor_mb = gate.get("min_available_memory_mb")
if floor_mb is not None:
free_ram_mb = int(max(0, (res.get("mem_total_gb", 0)
- res.get("mem_used_gb", 0))) * 1024)
free_swap_mb = int(max(0, (res.get("swap_total_gb", 0)
- res.get("swap_used_gb", 0))) * 1024)
free_mb = free_ram_mb + free_swap_mb
if free_mb and free_mb < floor_mb:
conds.append((
BANNER_CRIT,
f"⚠ Memory Below Gate Floor — {free_mb}MB Free, "
f"{floor_mb}MB Required",
))
# ── WARNING ──
caps = data.get("backend_caps") or {}
saturated_backends: list[str] = []
for backend, cap_cfg in caps.items():
bu = usage.get(backend) or {}
in_flight = int(bu.get("in_flight", 0))
backend_mc = cap_cfg.get("max_concurrent")
if backend_mc is not None and in_flight >= backend_mc:
saturated_backends.append(f"{backend} {in_flight}/{backend_mc}")
if saturated_backends:
conds.append((
BANNER_WARN,
"⚠ Backend(s) at Concurrency Cap: "
+ ", ".join(saturated_backends),
))
queue = data.get("queue") or []
if len(queue) >= 10:
conds.append((
BANNER_WARN,
f"⚠ Queue Depth {len(queue)} ≥ 10 — Backlog Accumulating",
))
# Free RAM near the gate floor (within 1.2× of the floor)
if floor_mb is not None:
free_ram_mb = int(max(0, (res.get("mem_total_gb", 0)
- res.get("mem_used_gb", 0))) * 1024)
free_swap_mb = int(max(0, (res.get("swap_total_gb", 0)
- res.get("swap_used_gb", 0))) * 1024)
free_mb = free_ram_mb + free_swap_mb
if free_mb and floor_mb <= free_mb < int(floor_mb * 1.2):
conds.append((
BANNER_WARN,
f"⚠ Memory Near Gate Floor — {free_mb}MB Free vs "
f"{floor_mb}MB Required (1.2× Margin)",
))
# ── INFO ──
# First 30 seconds after launch — readings may not be populated yet.
# Special-case: this banner is *pinned* to the front of the cycle so
# operators see "Just Started" first when the pane comes up, even when
# CRITICAL conditions are also present. Once the 30s window closes
# (or the operator has seen the message scroll past once), the regular
# severity-sorted order takes over.
just_started = (
started_at
and (time.time() - started_at) < 30
)
if conds:
order = {lvl: i for i, lvl in enumerate(_BANNER_LEVEL_ORDER)}
conds.sort(key=lambda c: order.get(c[0], 99))
else:
conds = [(BANNER_HEALTHY, "✓ All Systems Nominal")]
if just_started:
conds.insert(0, (BANNER_INFO, "ℹ Just Started — Readings Stabilizing"))
return conds
def _stale_heartbeat_roles() -> list[str]:
"""Return role names that are not visibly healthy.
A role is considered stalled when *any* of:
- its supervisor PID file is missing or the PID is dead
(the worker isn't running at all), OR
- its heartbeat file is missing (no proof of life), OR
- the heartbeat file is older than ``_STALE_HEARTBEAT_S``
(process up but not ticking — hung).
Iterating over the canonical ``_ROLES`` tuple guarantees every
declared worker gets evaluated, including ones that never started
(no heartbeat file would have been an invisible omission).
"""
now = time.time()
stale: list[str] = []
for role in _ROLES:
info = _role_info(role)
if not info.get("alive", False):
stale.append(role)
continue
hb = _WATCH_DIR / f"heartbeat_{role}.json"
if not hb.exists():
stale.append(role)
continue
try:
age = now - hb.stat().st_mtime
except OSError:
stale.append(role)
continue
if age > _STALE_HEARTBEAT_S:
stale.append(role)
return sorted(stale)
def _role_info(role: str) -> dict:
pid_file = _WATCH_DIR / f"{role}.pid"
if not pid_file.exists():
return {"alive": False, "pid": "", "mtime": None}
try:
pid = pid_file.read_text(encoding="utf-8").strip()
alive = _pid_alive(pid)
return {"alive": alive, "pid": pid, "mtime": pid_file.stat().st_mtime if alive else None}
except Exception:
return {"alive": False, "pid": "", "mtime": None}
def _restart_counts() -> dict[str, int]:
"""Count watcher_restart events per role from all log files."""
counts: dict[str, int] = {}
for log in _WATCH_DIR.glob("*.log"):
try:
for line in log.read_text(encoding="utf-8", errors="replace").splitlines():
if "watcher_restart" not in line:
continue
try:
ev = json.loads(line)
role = ev.get("role", "")
if role:
counts[role] = counts.get(role, 0) + 1
except Exception:
pass
except Exception:
pass
return counts
def _active_campaigns() -> list[dict]:
f = _STATE_DIR / "campaigns" / "active.json"
try:
return json.loads(f.read_text(encoding="utf-8")).get("campaigns", [])
except Exception:
return []
def _sb_ok() -> bool:
port = os.environ.get("PORT_SWITCHBOARD", "20401")
try:
with urllib.request.urlopen(f"http://localhost:{port}/health", timeout=2) as r:
return r.status == 200
except Exception:
return False
def _sys_resources() -> dict:
load = "?"
load_pct = "?"
num_cores = 0
try:
parts = Path("/proc/loadavg").read_text(encoding="ascii").split()
load = f"{parts[0]}/{parts[1]}/{parts[2]}"
with open("/proc/cpuinfo", encoding="ascii") as f:
num_cores = f.read().count("processor")
if num_cores > 0:
l1, l5, l15 = float(parts[0]), float(parts[1]), float(parts[2])
p1, p5, p15 = int(100 * l1 / num_cores), int(100 * l5 / num_cores), int(100 * l15 / num_cores)
load_pct = f"{p1}%/{p5}%/{p15}%"
except Exception:
pass
mem_pct = swap_pct = 0
mem_used_gb = mem_total_gb = swap_used_gb = swap_total_gb = 0.0
try:
info: dict[str, int] = {}
for line in Path("/proc/meminfo").read_text(encoding="utf-8").splitlines():
k, *v = line.split()
if v:
info[k.rstrip(":")] = int(v[0])
mt = info.get("MemTotal", 0)
ma = info.get("MemAvailable", 0)
st = info.get("SwapTotal", 0)
sf = info.get("SwapFree", 0)
if mt:
mem_used_gb = (mt - ma) / 1048576
mem_total_gb = mt / 1048576
mem_pct = int(100 * (mt - ma) / mt)
if st:
swap_used_gb = (st - sf) / 1048576
swap_total_gb = st / 1048576
swap_pct = int(100 * (st - sf) / st)
except Exception:
pass
return {
"load": load,
"load_pct": load_pct,
"num_cores": num_cores,
"mem_pct": mem_pct, "mem_used_gb": mem_used_gb, "mem_total_gb": mem_total_gb,
"swap_pct": swap_pct, "swap_used_gb": swap_used_gb, "swap_total_gb": swap_total_gb,
}
_USAGE_PATH = _OC_ROOT / "tools" / "report" / "operations_center" / "execution" / "usage.json"
def _exec_budget() -> dict:
"""Read OC's execution usage.json for global hourly/daily counts.
Caps come from env (defaults match OC: 10/hour, 50/day). Missing or
unreadable file returns zero counts so the pane keeps rendering.
"""
hourly = daily = 0
found = _USAGE_PATH.exists()
if found:
try:
data = json.loads(_USAGE_PATH.read_text(encoding="utf-8"))
hourly = int(data.get("hourly_exec_count", 0) or 0)
daily = int(data.get("daily_exec_count", 0) or 0)
except Exception:
found = False
cap_hour = int(os.environ.get("OPERATIONS_CENTER_MAX_EXEC_PER_HOUR", "10"))
cap_day = int(os.environ.get("OPERATIONS_CENTER_MAX_EXEC_PER_DAY", "50"))
return {"found": found, "hourly_used": hourly, "hourly_cap": cap_hour,
"daily_used": daily, "daily_cap": cap_day}
def _backend_caps() -> dict[str, dict[str, int]]:
"""Per-backend caps from OC's local YAML. Empty when unconfigured.
Reuses the lightweight indented-block parser pattern this module
already uses for the Plane block — keeps the pane bun-free even
on a bare interpreter without PyYAML.
"""
if not _OC_CONFIG.exists():
return {}
out: dict[str, dict[str, int]] = {}
in_block = False
current_backend: str | None = None
try:
for raw in _OC_CONFIG.read_text(encoding="utf-8").splitlines():
stripped = raw.rstrip()
if not stripped or stripped.lstrip().startswith("#"):
continue
if not stripped.startswith(" ") and not stripped.startswith("\t"):
in_block = stripped.startswith("backend_caps:")
current_backend = None
continue
if not in_block:
continue
# Determine indent level (2 spaces = backend, 4 spaces = field)
indent = len(stripped) - len(stripped.lstrip())
content = stripped.strip()
if ":" not in content:
continue
key, _, val = content.partition(":")
key = key.strip()
# Strip trailing inline comment then quotes/whitespace.
val = val.split("#", 1)[0].strip().strip('"').strip("'")
if indent == 2:
# New backend section starts
current_backend = key
out.setdefault(current_backend, {})
elif indent == 4 and current_backend is not None and val:
if key in ("max_per_hour", "max_per_day",
"min_available_memory_mb", "max_concurrent"):
try:
out[current_backend][key] = int(val)
except ValueError:
pass
except Exception:
return {}
# Drop empty stub entries (a backend with no fields)
return {k: v for k, v in out.items() if v}
def _resource_gate() -> dict[str, int]:
"""Read OC's global ``resource_gate:`` block from local YAML.
Returns ``{"max_concurrent": int, "min_available_memory_mb": int}``
with absent fields omitted. Empty dict when the block is missing
or unparseable. Mirrors the lightweight indented-block parser used
by ``_backend_caps`` so the pane stays bun-free.
"""
if not _OC_CONFIG.exists():
return {}
out: dict[str, int] = {}
in_block = False
try:
for raw in _OC_CONFIG.read_text(encoding="utf-8").splitlines():
stripped = raw.rstrip()
if not stripped or stripped.lstrip().startswith("#"):
continue
# Top-level boundary: starts at column 0.
if not stripped.startswith(" ") and not stripped.startswith("\t"):
in_block = stripped.startswith("resource_gate:")
continue
if not in_block:
continue
content = stripped.strip()
if ":" not in content:
continue
key, _, val = content.partition(":")
key = key.strip()
val = val.split("#", 1)[0].strip().strip('"').strip("'")
if key in ("max_concurrent", "min_available_memory_mb") and val:
try:
out[key] = int(val)
except ValueError:
pass
except Exception:
return {}
return out
def _backend_usage() -> dict[str, dict[str, int]]:
"""Per-backend live counters from usage.json events.
Returns ``{backend: {"hourly": int, "daily": int, "in_flight": int}}``
with the same logic as ``UsageStore.budget_decision_for_backend`` and
``concurrent_runs_for_backend``. Missing/unreadable file → ``{}``.
"""
if not _USAGE_PATH.exists():
return {}
try:
data = json.loads(_USAGE_PATH.read_text(encoding="utf-8"))
except Exception:
return {}
events = data.get("events", []) or []
now = time.time()
cutoff_hour = now - 3600
cutoff_day = now - 86400
cutoff_concurrency = now - 86400 # 24h stale window
per: dict[str, dict] = {}
in_flight: dict[str, set[str]] = {}
for ev in events:
if not isinstance(ev, dict):
continue
backend = ev.get("backend")
if not isinstance(backend, str) or not backend:
continue
ts_raw = ev.get("timestamp")
if not isinstance(ts_raw, str):
continue
try:
# Strip timezone and parse ISO; fall back gracefully.
from datetime import datetime as _dt
ts = _dt.fromisoformat(ts_raw).timestamp()
except (ValueError, OverflowError):
continue
bucket = per.setdefault(backend, {"hourly": 0, "daily": 0})
kind = ev.get("kind")
if kind == "execution":
if ts >= cutoff_day:
bucket["daily"] += 1
if ts >= cutoff_hour:
bucket["hourly"] += 1
elif ts >= cutoff_concurrency:
tid = ev.get("task_id")
if isinstance(tid, str):
if kind == "execution_started":
in_flight.setdefault(backend, set()).add(tid)
elif kind == "execution_finished":
in_flight.setdefault(backend, set()).discard(tid)
for backend, ids in in_flight.items():
per.setdefault(backend, {"hourly": 0, "daily": 0})["in_flight"] = len(ids)
for bucket in per.values():
bucket.setdefault("in_flight", 0)
return {k: dict(v) for k, v in per.items()}
def _profile_repos(profile_name: str) -> set[str] | None:
try:
from operator_console.profile_loader import load_profile
p = load_profile(profile_name, _PROFILES_DIR)
if "group" in p:
names: set[str] = set()
for sub in p["group"]:
try:
sp = load_profile(sub, _PROFILES_DIR)
names.add(sp.get("name", sub))
except Exception:
names.add(sub)
return names
return {p["name"]} if "name" in p else None
except Exception:
return None
def _queue_items(repo_filter: set[str] | None) -> list[dict]:
items = []
if not _QUEUE_DIR.exists():
return items
for f in sorted(_QUEUE_DIR.glob("*.json")):
try:
item = json.loads(f.read_text(encoding="utf-8"))
if repo_filter is None or item.get("repo_name") in repo_filter:
items.append(item)
except Exception:
pass
return items
_plane_cache: dict = {"active": [], "board": [], "fetched_at": 0.0}
def _collect(repo_filter: set[str] | None) -> dict:
global _plane_cache
now = time.time()
if now - _plane_cache["fetched_at"] >= PLANE_REFRESH_INTERVAL:
fresh = _plane_issues(repo_filter)
_plane_cache = {**fresh, "fetched_at": now}
return {
"roles": {r: _role_info(r) for r in _ROLES},
"restarts": _restart_counts(),
"campaigns": _active_campaigns(),
"sb": _sb_ok(),
"queue": _queue_items(repo_filter),
"resources": _sys_resources(),
"plane": {"active": _plane_cache["active"], "board": _plane_cache["board"]},
"recent": _recent_activity(),
"budget": _exec_budget(),
"backend_caps": _backend_caps(),
"backend_usage": _backend_usage(),
"resource_gate": _resource_gate(),
"at": now,
}
# ── drawing helpers ───────────────────────────────────────────────────────────
def _put(stdscr, row: int, h: int, w: int, text: str, attr: int = 0) -> None:
if row < 0 or row >= h:
return
try:
stdscr.addstr(row, 0, text[: w - 1].ljust(min(len(text) + 1, w - 1)), attr)
except curses.error:
pass
def _sep(stdscr, row: int, h: int, w: int, attr: int) -> int:
_put(stdscr, row, h, w, "─" * (w - 1), attr)
return row + 1
def _bar(pct: int, width: int = BAR_W) -> str:
filled = round(pct * width / 100)
return "█" * filled + "░" * (width - filled)
def _tc(s: str) -> str:
"""Title-Case a snake_case identifier for display.
``aider_local`` → ``Aider Local`` ; ``board_worker`` → ``Board Worker``.
Preserves internal capitalisation so PascalCase stays intact:
``OperationsCenter`` → ``OperationsCenter``. Empty input returns empty.
"""
if not s:
return s
parts = s.split("_")
return " ".join(p[:1].upper() + p[1:] if p else p for p in parts)
def _uptime(start: float) -> str:
e = int(time.time() - start)
if e < 60:
return f"{e}s"
if e < 3600:
return f"{e // 60}m"
return f"{e // 3600}h{(e % 3600) // 60}m"
def _latest_log(role: str) -> Path | None:
logs = sorted(_WATCH_DIR.glob(f"*_{role}.log"))
return logs[-1] if logs else None
_RECENT_WINDOW_S = 300 # 5 minutes
_RECENT_PAT = re.compile(
r"^(\d{2}:\d{2}:\d{2}) \[(\w+)\] (?:INFO|WARNING) board_worker\[\w+\]: "
r"(?:task_id=\S+\s+)?"
r"(claimed|completed|blocked|processing|failed)"
r"(?:.*?status=(\S+))?"
r"(?:.*?title=[\"\']([^\"\']{0,60}))?"
)
def _recent_activity() -> list[dict]:
"""Mine worker logs for claim/complete/block events in the last _RECENT_WINDOW_S seconds.
Returns events newest-first as {role, action, status, title, ts} dicts.
"""
cutoff = time.time() - _RECENT_WINDOW_S
events: list[dict] = []
for role in ("goal", "test", "improve"):
log = _latest_log(role)
if not log:
continue
try:
mtime = log.stat().st_mtime
except OSError:
continue
if mtime < cutoff:
continue
try:
text = log.read_text(encoding="utf-8", errors="replace")
except OSError:
continue
# Walk lines newest-first; stop after a few hits per role
lines = text.splitlines()
per_role = 0
for raw in reversed(lines):
if "board_worker[" not in raw:
continue
if not any(k in raw for k in (" claimed ", " completed ", " blocked ", " processing ", " failed ")):
continue
m = _RECENT_PAT.match(raw)
if not m:
continue
ts_str, lrole, action, status, title = m.groups()
events.append({
"role": lrole,
"action": action,
"status": status or "",
"title": (title or "").strip("`* "),
"ts": ts_str,
})
per_role += 1
if per_role >= 5:
break
return events
# ── main view ─────────────────────────────────────────────────────────────────
_SEP_MARKER = "\x00SEP\x00" # synthetic line that renders as a separator
def _build_sections(
data: dict, sel: int, w: int, C: dict,
) -> tuple[list[dict], int]:
"""Build the middle area as a list of independently scrollable sections.
Each section is a dict::
{"id": str, "lines": [(text, attr), ...], "sel_local": int}
``sel_local`` is the line index *within the section* of the currently
selected role (only set for the "roles" section; -1 elsewhere). The
caller uses it to keep the selection visible when scrolling the
roles section.
Returns ``(sections, focused_section_idx)`` — focused section is
where the selected role lives (always 0 today since "roles" is
always first), used as the default target for keyboard scroll keys.
"""
sections: list[dict] = []
# ── roles section ──
role_lines: list[tuple[str, int]] = []
role_sel_local = -1
roles = data.get("roles", {})
restarts = data.get("restarts", {})
n_up = sum(1 for r in _ROLES if roles.get(r, {}).get("alive", False))
total_rc = sum(restarts.get(r, 0) for r in _ROLES)
hdr_attr = (C["YLW"] | curses.A_BOLD) if (n_up < len(_ROLES) or total_rc > 0) else (C["HEAD"] | curses.A_BOLD)
rc_tag = f"{total_rc} Restarts" if total_rc else "Clean"
role_lines.append((f" Workers ({n_up}/{len(_ROLES)} Running, {rc_tag})", hdr_attr))
for i, role in enumerate(_ROLES):
info = roles.get(role, {})
alive = info.get("alive", False)
rc = restarts.get(role, 0)
rb = f" ↺{rc}" if rc else ""
if alive:
up = _uptime(info["mtime"]) if info.get("mtime") else "?"
line = f" ✓ {_tc(role):<14} Up {up}{rb}"
attr = C["RUN"]
else:
line = f" ✗ {_tc(role):<14} STOPPED{rb}"
attr = C["ERR"]
if i == sel:
role_sel_local = len(role_lines)
full = ("▶" + line[1:] + " [Enter]")[:w - 1]
role_lines.append((full, C["SEL"] | curses.A_BOLD))
else:
role_lines.append((line, attr))
sections.append({"id": "roles", "lines": role_lines, "sel_local": role_sel_local})
# ── active tasks (Plane: Running) ──
plane = data.get("plane", {})
active_tasks = plane.get("active", [])
if active_tasks:
active_lines: list[tuple[str, int]] = [
(f" Active ({len(active_tasks)} Running)", C["HEAD"] | curses.A_BOLD),
]
for item in active_tasks:
repo = _tc(item.get("repo", "?"))[:14]
title = item.get("title", "?")[:max(w - 20, 8)]
active_lines.append((f" ▶ {repo:<14} {title}", C["RUN"]))
sections.append({"id": "active", "lines": active_lines, "sel_local": -1})
# ── recent activity (worker logs) ──
recent = data.get("recent", [])
if recent:
recent_lines: list[tuple[str, int]] = [
(f" Recent ({len(recent)} Events, Last 5m)", C["HEAD"] | curses.A_BOLD),
]
for ev in recent[:8]:
action = ev.get("action", "")
status = ev.get("status", "")
title = ev.get("title", "")[:max(w - 32, 8)]
role = ev.get("role", "")
ts = ev.get("ts", "")
if action == "blocked":
icon, attr = "✗", C["ERR"]
elif action == "completed":
icon, attr = "✓", C["RUN"]
elif action == "claimed":
icon, attr = "→", C["YLW"]
else:
icon, attr = "·", C["DIM"]
tag = f"{action}({status})" if status else action
recent_lines.append((f" {icon} {ts} {_tc(role):<10} {tag:<22} {title}", attr))
sections.append({"id": "recent", "lines": recent_lines, "sel_local": -1})
# ── campaigns ── (Future — high-level workstreams)
campaigns = data.get("campaigns", [])
if campaigns:
camp_lines: list[tuple[str, int]] = [
(f" Campaigns ({len(campaigns)} Active)", C["HEAD"] | curses.A_BOLD),
]
for c in campaigns:
slug = c.get("slug", c.get("campaign_id", "?"))[:w - 6]
status = c.get("status", "")
if status == "done":
icon, attr = "✓", C["RUN"]
elif status == "failed":
icon, attr = "✗", C["ERR"]
else:
icon, attr = "▶", C["YLW"]
camp_lines.append((f" {icon} {slug}", attr))
sections.append({"id": "campaigns", "lines": camp_lines, "sel_local": -1})
# ── board ── (Future — items in motion)
board_items = plane.get("board", [])
if board_items:
board_lines: list[tuple[str, int]] = [
(f" Board ({len(board_items)} Queued)", C["HEAD"] | curses.A_BOLD),
]
for item in board_items:
repo = _tc(item.get("repo", "?"))[:14]
state = item.get("state", "")
icon = "·" if "backlog" in state.lower() else "→"
title = item.get("title", "?")[:max(w - 20, 8)]
board_lines.append((f" {icon} {repo:<14} {title}", C["DIM"]))
sections.append({"id": "board", "lines": board_lines, "sel_local": -1})
# ── queue ──
queue = data.get("queue", [])
if queue:
# Backlog signal: 0 → green, 1-4 → green, 5-9 → yellow, ≥10 → red.
n_q = len(queue)
q_attr = (
C["ERR"] if n_q >= 10
else C["YLW"] if n_q >= 5
else C["RUN"] if n_q else C["HEAD"]
)
queue_lines: list[tuple[str, int]] = [
(f" Queue ({n_q} Pending)", q_attr | curses.A_BOLD),
]
for item in queue:
typ = _tc((item.get("task_type") or "?"))[:6]
repo = _tc((item.get("repo_name") or "?"))[:14]
goal = (item.get("goal") or "")[:max(w - 24, 8)]
queue_lines.append((f" {typ:<7} {repo:<14} {goal}", C["DIM"]))
sections.append({"id": "queue", "lines": queue_lines, "sel_local": -1})
# Note: Global Rate moved to the bottom-anchored block alongside
# Global Gate and System Resources (see _bottom_sections).
# ── backend caps (per-backend rate / concurrency / RAM) ──
caps = data.get("backend_caps", {})
usage = data.get("backend_usage", {})
res = data.get("resources", {})
mem_avail_mb = 0
if res.get("mem_total_gb"):
mem_avail_mb = int(
(res["mem_total_gb"] - res.get("mem_used_gb", 0)) * 1024
)
if caps or usage:
bc_lines: list[tuple[str, int]] = []
bc_section_worst = C["RUN"]
for backend in sorted(set(caps) | set(usage)):
bc = caps.get(backend, {})
bu = usage.get(backend, {})
cells: list[str] = []
worst_attr = C["RUN"]
for win_label, used_key, cap_key in (
("Hourly", "hourly", "max_per_hour"),
("Daily", "daily", "max_per_day"),
):
limit = bc.get(cap_key)
used = bu.get(used_key, 0)
if limit is not None:
ratio = (used / limit) if limit else 0.0
if ratio >= 1:
worst_attr = C["ERR"]
elif ratio >= 0.8 and worst_attr is C["RUN"]:
worst_attr = C["YLW"]
cells.append(f"{win_label} {used}/{limit}")
elif used:
cells.append(f"{win_label} {used}/∞")
in_flight = bu.get("in_flight", 0)
mc = bc.get("max_concurrent")
if mc is not None:
ratio = (in_flight / mc) if mc else 0.0
if ratio >= 1:
worst_attr = C["ERR"]
elif ratio >= 0.8 and worst_attr is C["RUN"]:
worst_attr = C["YLW"]
cells.append(f"In-Flight {in_flight}/{mc}")
elif in_flight:
cells.append(f"In-Flight {in_flight}/∞")
ram_floor = bc.get("min_available_memory_mb")
if ram_floor is not None:
if mem_avail_mb and mem_avail_mb < ram_floor:
worst_attr = C["ERR"]
cells.append(f"RAM ≥ {ram_floor}MB")
row = " ".join(cells) if cells else "(No Limits)"
bc_lines.append((f" {_tc(backend):<14} {row}", worst_attr))
if worst_attr is C["ERR"]:
bc_section_worst = C["ERR"]
elif worst_attr is C["YLW"] and bc_section_worst is C["RUN"]:
bc_section_worst = C["YLW"]
sections.append({"id": "backend_caps", "lines": [
(" Backend Limits", bc_section_worst | curses.A_BOLD),
*bc_lines,
], "sel_local": -1})
# ── services ──
sb = data.get("sb", False)
sb_icon = "✓" if sb else "✗"