-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.py
More file actions
7518 lines (6838 loc) · 320 KB
/
Copy pathserve.py
File metadata and controls
7518 lines (6838 loc) · 320 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
#!/usr/bin/env python3
"""
REE Claims Explorer Server
Replaces `python3 -m http.server` with a server that also manages the
experiment runner processes (V2 and V3) via a small HTTP API.
Usage:
cd ~/REE_Working/REE_assembly
caffeinate -i python3 serve.py # http://localhost:8000/explorer
python3 serve.py --port 9000
API (POST, called by the Experiments tab in the explorer):
/api/runner/start -- start V3 runner (default)
/api/runner/stop -- graceful drain: finish current experiment then stop
/api/runner/force_stop -- immediate SIGKILL (data loss acceptable)
/api/runner/v3/start -- start V3 runner
/api/runner/v3/stop -- graceful drain V3 runner
/api/runner/v3/force_stop -- force-kill V3 runner immediately
/api/runner/v2/start -- start V2 runner
/api/runner/v2/stop -- graceful drain V2 runner
/api/runner/v2/force_stop -- force-kill V2 runner immediately
/api/runner/status -- JSON status of both runners (includes draining flag)
/api/review/tracker -- GET: reviewed/discussed state from review_tracker.json
/api/review/discuss -- POST {dir_name, discussed}: toggle discussed_experiment_dirs
/api/experiment/detail -- GET ?script=&queue_id=: curated manifest detail for a Completed card
/api/regression/preflight -- GET: ree-v3 preflight suite result (cached 60s)
/api/coordinator/phase3/preflight -- GET: Phase 3 cutover pre-checks (cached 60s)
/api/coordinator/phase3/writers -- GET: Phase 3 sync_daemon writer health (cached 60s)
/api/workspace/health -- GET: stale TASK_CLAIMS + orphaned git stashes (cached 60s)
/api/queue/live -- GET: active queue (coordinator DB when reachable, else file)
/api/queue/v3 -- GET: experiment_queue.json mirror (file)
The runners write progress to evidence/experiments/runner_status.json,
which the explorer polls automatically when the Experiments tab is open.
Output from runners is appended to runner.log in this directory.
Stop the server: Ctrl+C (also stops any runners started here)
"""
import argparse
import datetime
import http.server
import json
import os
import re
import shlex
import signal
import socket
import subprocess
import sys
import threading
import time
from pathlib import Path
from urllib.parse import urlparse
# Make EVERY subprocess.run(timeout=) in this module SIGTERM its child before
# SIGKILLing it. serve.py runs `git pull` / `status` / `add` / `commit` against
# REE_assembly and ree-v3 unattended; the stdlib's SIGKILL-on-timeout bypasses
# git's cleanup handler and orphans `.git/index.lock`, which then blocks
# ree_commit.py's shared-index refresh and arms a staged revert for the next
# session. See graceful_timeout.py's module docstring for the measurement.
# Module-local rebinding: the stdlib module is not mutated.
import graceful_timeout
subprocess = graceful_timeout.wrap(subprocess)
# Every hostname this module keys coordination state on -- heartbeat/status
# FILENAMES, the /machines aggregation key, the runner_commands filename -- is
# resolved through here rather than compared raw. macOS re-suffixes this Mac's
# LocalHostName on a Bonjour collision, so one physical laptop reported
# `DLAPTOP-4.local` and `DLAPTOP-5.local` across Jul-Aug 2026; keyed raw, that
# splits one box into two dashboard cards, the older of which ages into looking
# like a dead machine. VENDORED byte-identical from ree-v3 (the canonical copy,
# which carries the contract test) -- a cross-repo sys.path hop works on this Mac
# and breaks on the hub and the cloud workers. Identity gate:
# scripts/audit_vendored_copies.py --set machine_identity.
import machine_identity
try:
import yaml as _yaml
_YAML_OK = True
except ImportError:
_YAML_OK = False
# ── Paths ────────────────────────────────────────────────────────────────────
SERVE_DIR = Path(__file__).resolve().parent
STATUS_FILE = SERVE_DIR / "evidence" / "experiments" / "runner_status.json" # legacy monolithic
STATUS_DIR = SERVE_DIR / "evidence" / "experiments" / "runner_status" # per-machine split
HEARTBEAT_DIR = SERVE_DIR / "evidence" / "experiments" / "runner_heartbeats" # per-machine heartbeats
COMMANDS_DIR = SERVE_DIR / "evidence" / "experiments" / "runner_commands" # per-machine command queues
RUNNER_LOG = SERVE_DIR / "runner.log"
PLANNING_DIR = SERVE_DIR / "evidence" / "planning"
WORKSET_JSON_FILE = PLANNING_DIR / "inter_governance_workset.v1.json"
IGW_LEDGER_FILE = PLANNING_DIR / "igw_routine_ledger.json"
# Umbrella repo (SERVE_DIR.parent), same resolution used elsewhere in this file
# (see workdir = str(SERVE_DIR.parent) below) -- chip_ledger.py always writes
# TASK_CHIPS.json there, regardless of which repo a session's cwd is under.
TASK_CHIPS_FILE = SERVE_DIR.parent / "TASK_CHIPS.json"
# Command kinds the runner accepts (mirrors ree-v3/runner_remote_control.VALID_COMMAND_KINDS)
VALID_REMOTE_COMMAND_KINDS = (
"stop", "force_stop", "pause", "resume", "suspend", "resume_run",
"kick", "release_claim",
)
MAX_REMOTE_COMMAND_HISTORY = 50
REVIEW_TRACKER_FILE = SERVE_DIR / "evidence" / "experiments" / "review_tracker.json"
CONTRIBUTIONS_FILE = SERVE_DIR / "contributors" / "contributions.json"
# Timeline data paths
_TL_CLAIMS_YAML = SERVE_DIR / "docs" / "claims" / "claims.yaml"
_TL_CLAIM_EVIDENCE = SERVE_DIR / "evidence" / "experiments" / "claim_evidence.v1.json"
_TL_EVIDENCE_DIR = SERVE_DIR / "evidence" / "experiments"
_TL_LITERATURE_DIR = SERVE_DIR / "evidence" / "literature"
# --- claim_evidence.v1.json shared loader -------------------------------------
# The file is ~10 MB (486 claims / 4,983 entries). Two request paths used to
# json.loads() it independently on EVERY GET: _brain_load_claim_evidence()
# (/api/brain-map, which then reads 5 scalars per claim) and the confidence-series
# block in _build_timeline_events() (/api/timeline/events). Both want only the
# `claims` map; neither touches `entries`.
#
# Keyed on (mtime_ns, size) rather than a TTL on purpose: a governance rebuild is
# picked up on the very next request, so this cannot serve stale evidence. That
# matters here -- the no-cache posture for explorer data is deliberate (CLAUDE.md,
# "Explorer"), and a time-based cache would reintroduce exactly the staleness the
# no-cache headers exist to prevent.
#
# The returned dict is SHARED and must be treated as read-only by callers. It is
# not deep-copied -- copying 10 MB per request would defeat the purpose.
_CLAIM_EVIDENCE_CACHE: dict = {"key": None, "claims": {}}
# Same contract for the 3.7 MB docs/claims/claims.yaml parse; see _tl_load_claims().
_TL_CLAIMS_CACHE: dict = {"key": None, "claims": []}
def _load_claim_evidence_claims() -> dict:
"""Return the `claims` map from claim_evidence.v1.json. READ-ONLY; shared."""
try:
st = _TL_CLAIM_EVIDENCE.stat()
except OSError:
_CLAIM_EVIDENCE_CACHE["key"] = None
_CLAIM_EVIDENCE_CACHE["claims"] = {}
return {}
key = (st.st_mtime_ns, st.st_size)
if _CLAIM_EVIDENCE_CACHE["key"] != key:
try:
data = json.loads(_TL_CLAIM_EVIDENCE.read_text(encoding="utf-8"))
claims = data.get("claims") or {}
except Exception:
claims = {}
_CLAIM_EVIDENCE_CACHE["claims"] = claims if isinstance(claims, dict) else {}
_CLAIM_EVIDENCE_CACHE["key"] = key
return _CLAIM_EVIDENCE_CACHE["claims"]
_TL_MILESTONES = [
{"date": "2026-02-13T00:00:00Z", "label": "Project start / first experiments", "kind": "start"},
{"date": "2026-02-15T18:46:42Z", "label": "First governance batch (10 claims adjudicated)", "kind": "governance"},
{"date": "2026-02-25T16:56:00Z", "label": "Second governance batch", "kind": "governance"},
{"date": "2026-02-26T00:00:00Z", "label": "ree-experiments-lab archived; V2 real substrate", "kind": "architecture"},
{"date": "2026-02-27T00:00:00Z", "label": "Epoch start: ree_hybrid_guardrails_v1", "kind": "architecture"},
{"date": "2026-03-06T00:00:00Z", "label": "SD-002 resolved: E1 prior wired into HippocampalModule","kind": "architecture"},
{"date": "2026-03-14T00:00:00Z", "label": "SD-005: z_self/z_world split registered", "kind": "architecture"},
{"date": "2026-03-15T00:00:00Z", "label": "Control-plane heartbeat cluster registered", "kind": "architecture"},
{"date": "2026-03-16T00:00:00Z", "label": "Governance pipeline fixed; contamination corrected", "kind": "governance"},
{"date": "2026-03-18T00:00:00Z", "label": "V3 EXQ-013-019 root cause: SD-008/alpha_world", "kind": "milestone"},
{"date": "2026-03-19T00:00:00Z", "label": "V3 experiment series begins", "kind": "start"},
]
_TL_DATE_RE = re.compile(r'\b(20\d{2}-\d{2}-\d{2})\b')
_TL_REG_RE = re.compile(r'registered\s+(20\d{2}-\d{2}-\d{2})', re.IGNORECASE)
_TL_THOUGHT_RE = re.compile(r'docs/thoughts/(20\d{2}-\d{2}-\d{2})')
# Python executable -- prefer REE_PYTHON env var, then known torch-capable paths
def _default_python() -> str:
if env := os.environ.get("REE_PYTHON"):
return env
for p in (
"/opt/local/bin/python3", # macOS MacPorts
"/opt/homebrew/bin/python3", # macOS Homebrew
"/home/ree/.venv/ree/bin/python3", # Linux venv (see remote_setup.sh)
):
if os.path.exists(p):
return p
return sys.executable
_DEFAULT_PYTHON = _default_python()
V3_PYTHON = _DEFAULT_PYTHON
V2_PYTHON = _DEFAULT_PYTHON
def _utc_now_iso_z() -> str:
"""UTC ISO-8601 with Z suffix (microsecond precision)."""
return (
datetime.datetime.now(datetime.UTC)
.isoformat(timespec="microseconds")
.replace("+00:00", "Z")
)
def _utc_now_compact() -> str:
"""UTC ISO-8601 second precision with Z suffix."""
return datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
# Runner configs keyed by substrate version
RUNNERS = {
"v3": {
"script": SERVE_DIR.parent / "ree-v3" / "experiment_runner.py",
"pid_file": SERVE_DIR.parent / "ree-v3" / "runner.pid",
"queue_file": SERVE_DIR.parent / "ree-v3" / "experiment_queue.json",
"evidence_dir": SERVE_DIR / "evidence" / "experiments",
"python": V3_PYTHON,
"label": "V3 (ree-v3)",
"auto_sync": True,
"remote_control": True,
},
"v2": {
"script": SERVE_DIR.parent / "ree-v2" / "experiment_runner.py",
"pid_file": SERVE_DIR.parent / "ree-v2" / "runner.pid",
"queue_file": SERVE_DIR.parent / "ree-v2" / "experiment_queue.json",
"evidence_dir": SERVE_DIR.parent / "ree-v2" / "evidence" / "experiments",
"python": V2_PYTHON,
"label": "V2 (ree-v2)",
"auto_sync": True,
"remote_control": False,
},
}
DEFAULT_PORT = 8000
# ── Preflight badge ──────────────────────────────────────────────────────────
# Memoised result of `pytest tests/preflight` for the regression-suite badge
# in the explorer. Cached for _PREFLIGHT_TTL seconds so a clicked refresh
# doesn't spawn pytest on every paint.
_PREFLIGHT_TTL = 60
_preflight_cache: dict | None = None
_preflight_cache_at: float = 0.0
_preflight_lock = threading.Lock()
_phase3_preflight_cache: dict | None = None
_phase3_preflight_cache_at: float = 0.0
_phase3_preflight_lock = threading.Lock()
_PHASE3_PREFLIGHT_TTL = 60.0
_phase3_writers_cache: dict | None = None
_phase3_writers_cache_at: float = 0.0
_phase3_writers_lock = threading.Lock()
_PHASE3_WRITERS_TTL = 60.0
_PHASE3_HUB_DEFAULT_HOST = ""
# WireGuard-tunnel address of the coordinator HTTP plane on the hub.
# /writer-health is the durable replacement for the SSH+journal probe; we
# try this first and fall back to SSH if the call fails (deploy windows,
# auth issues, endpoint not yet rolled out to the hub).
_PHASE3_COORDINATOR_WG_URL = ""
# sync_daemon's tick interval. Used to colour writer rows by tick-age:
# the SYNC_INTERVAL bump from 60s -> 300s landed on the hub 2026-05-31.
# Mirroring the default here lets the explorer judge "is the writer
# alive" without depending on commit cadence.
_PHASE3_SYNC_INTERVAL_S = 300.0
def run_phase3_preflight_summary() -> dict:
"""Run coordinator phase3_preflight (dry-run: no SSH). Cached 60s."""
global _phase3_preflight_cache, _phase3_preflight_cache_at
with _phase3_preflight_lock:
now = time.time()
if (_phase3_preflight_cache is not None
and (now - _phase3_preflight_cache_at) < _PHASE3_PREFLIGHT_TTL):
return _phase3_preflight_cache
ree_v3 = SERVE_DIR.parent / "ree-v3"
script = ree_v3 / "coordinator" / "phase3_preflight.py"
env_file = SERVE_DIR / "coordinator.env"
if not script.exists():
result = {
"ok": False,
"error": "phase3_preflight.py missing",
"cached_at": _utc_now_iso_z(),
}
_phase3_preflight_cache = result
_phase3_preflight_cache_at = now
return result
try:
import importlib.util
spec = importlib.util.spec_from_file_location(
"phase3_preflight", script)
mod = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(mod)
summary = mod.run_preflight(
env_file=env_file,
dry_run=True,
mock=False,
quiet=True,
)
summary["cached_at"] = (
_utc_now_iso_z())
summary["dry_run"] = True
summary["note"] = (
"Explorer summary uses dry-run (no SSH). "
"Run phase3_preflight.py on Mac for full fleet probes.")
except Exception as exc:
summary = {
"ok": False,
"error": "%s: %s" % (type(exc).__name__, exc),
"cached_at": _utc_now_iso_z(),
}
_phase3_preflight_cache = summary
_phase3_preflight_cache_at = now
return summary
def _phase3_freshness_color(age_s: float | None,
writer: str = "default") -> str:
"""Map commit age to a UI colour, scaled per-writer.
Per-writer thresholds (seconds):
heartbeat_writer: green<10min yellow<35min red>=35min
(SYNC_INTERVAL=300 + future change-triggered with 30-min liveness
floor; old 5/15 thresholds false-alarmed during idle periods)
git_writer: green<60min yellow<180min red>=180min
(commits on experiment completion; quiet stretches 30-60min are
routine on a 3-4 worker fleet running multi-hour experiments)
queue_writer: green<60min yellow<180min red>=180min
(commits on queue claim/release/add; can be silent for hours
during long-running experiments)
default: green<5min yellow<15min red>=15min
(legacy thresholds preserved for any unknown writer name)
Note: these are 'last commit age' thresholds and still conflate
'writer process alive' with 'something has changed lately'. The
proper fix lives in chips: switch to journal-tick-age or a
coordinator /writer-health endpoint. Until then, the thresholds
above match each writer's realistic commit cadence so the explorer
stops false-alarming on healthy quiet periods.
"""
if age_s is None:
return "red"
thresholds = {
"heartbeat_writer": (10 * 60, 35 * 60),
"git_writer": (60 * 60, 180 * 60),
"queue_writer": (60 * 60, 180 * 60),
"default": (5 * 60, 15 * 60),
}
green_max, yellow_max = thresholds.get(writer, thresholds["default"])
if age_s < green_max:
return "green"
if age_s < yellow_max:
return "yellow"
return "red"
def _parse_phase3_log_line(line: str) -> dict:
"""One line of `git log --pretty='%H %at %s'`. Returns {sha10, ts, subject}
or {} on empty/malformed."""
line = (line or "").strip()
if not line:
return {}
parts = line.split(" ", 2)
if len(parts) < 2:
return {}
sha = parts[0]
try:
ts = int(parts[1])
except ValueError:
return {}
subject = parts[2] if len(parts) >= 3 else ""
return {"sha10": sha[:10], "committed_at": ts, "subject": subject}
def _phase3_writer_health_color(tick_age_s: float | None,
last_error: dict | None) -> str:
"""Tick-age-based health colour for HTTP-mode writer rows.
Healthy writer process iff it has ticked recently, regardless of
commit cadence. This is the durable signal the chip introduced:
"writer X last ticked at HH:MM" tells the explorer "the process is
alive and running its loop", which is what the user actually wants
to know. Commit age is kept on the row but is informational only.
Thresholds: < 2 x SYNC_INTERVAL green, 2-5 x yellow, > 5x red.
A non-None last_error always paints red regardless of tick age --
the writer is alive but failing, which still warrants attention.
last_error has already been aged out by the coordinator side
(WRITER_HEALTH_ERROR_TTL_S), so a present error is recent enough
to be load-bearing.
"""
if last_error is not None:
return "red"
if tick_age_s is None:
return "red"
if tick_age_s < 2.0 * _PHASE3_SYNC_INTERVAL_S:
return "green"
if tick_age_s < 5.0 * _PHASE3_SYNC_INTERVAL_S:
return "yellow"
return "red"
def _parse_iso_utc_to_unix(iso_str: str | None) -> int | None:
"""Parse `YYYY-MM-DDTHH:MM:SSZ` to a unix int; None on malformed."""
if not iso_str:
return None
try:
# Tolerate `Z` or `+00:00` suffix.
s = iso_str.rstrip("Z")
dt = datetime.datetime.fromisoformat(s)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=datetime.timezone.utc)
return int(dt.timestamp())
except (ValueError, TypeError):
return None
def _fetch_phase3_writer_health_http(cfg: dict) -> dict | None:
"""Single HTTP GET to coordinator /writer-health over WireGuard.
Returns the run_phase3_writers_summary-shaped result on success, or
None on any failure (so the caller can fall back to the SSH path).
Never raises. Token comes from coordinator.env COORDINATOR_LOCAL_TOKEN,
same as the other coordinator probes in this file.
"""
tok = cfg.get("COORDINATOR_LOCAL_TOKEN")
if not tok:
return None
base_url = (cfg.get("COORDINATOR_URL")
or _PHASE3_COORDINATOR_WG_URL).strip()
if not base_url:
return None
url = base_url.rstrip("/") + "/writer-health"
import urllib.error
import urllib.request
try:
req = urllib.request.Request(
url, headers={"Authorization": "Bearer " + tok}, method="GET")
with urllib.request.urlopen(req, timeout=5) as resp:
doc = json.loads(resp.read().decode("utf-8"))
except (urllib.error.URLError, urllib.error.HTTPError,
OSError, ValueError, TimeoutError):
return None
writers_doc = doc.get("writers")
if not isinstance(writers_doc, dict):
return None
now_unix = time.time()
cached_at = _utc_now_iso_z()
def _writer_row_from_health(rec: dict) -> dict:
last_tick = _parse_iso_utc_to_unix(rec.get("last_tick_at"))
last_commit = _parse_iso_utc_to_unix(rec.get("last_commit_at"))
tick_age = (now_unix - last_tick) if last_tick is not None else None
commit_age = (now_unix - last_commit) if last_commit is not None else None
sha = rec.get("last_commit_sha") or None
subject = rec.get("last_commit_subject")
err = rec.get("last_error") if isinstance(rec.get("last_error"), dict) else None
return {
# Keep the legacy shape so the existing UI consumer is bit-
# identical when reading committed_at / sha10 / subject.
"sha10": (sha[:10] if isinstance(sha, str) else None),
"committed_at": last_commit,
"subject": subject,
"age_s": int(commit_age) if commit_age is not None else None,
# NEW: tick-age telemetry surfaced for the explorer to render.
"last_tick_at": rec.get("last_tick_at"),
"tick_age_s": int(tick_age) if tick_age is not None else None,
"last_error": err,
"color": _phase3_writer_health_color(tick_age, err),
}
writers = {
"git_writer": _writer_row_from_health(
writers_doc.get("git_writer") or {}),
"queue_writer": _writer_row_from_health(
writers_doc.get("queue_writer") or {}),
"heartbeat_writer": _writer_row_from_health(
writers_doc.get("heartbeat_writer") or {}),
}
# Status hint derived from per-writer error presence. Coarser than the
# journal-line classifier, but the HTTP path is the durable fix and the
# error message itself is on the row for the operator to read.
any_error = any(w.get("last_error") is not None
for w in writers.values())
writer_status = "errored" if any_error else "idle"
for row in writers.values():
row["status"] = writer_status
spool_pending = None
raw_spool = doc.get("spool_pending")
if raw_spool is not None:
try:
spool_pending = int(raw_spool)
except (TypeError, ValueError):
spool_pending = None
return {
"hub_reachable": True,
"hub_host": cfg.get("SHADOW_SSH_HOST_ree-cloud-1")
or cfg.get("PHASE3_HUB_SSH_HOST")
or _PHASE3_HUB_DEFAULT_HOST,
"writers": writers,
"spool_pending": spool_pending,
# Journal tail still SSH-only; HTTP path leaves it empty.
"journal_tail": [],
"sync_daemon_pid": doc.get("sync_daemon_pid"),
"probe": "http",
"cached_at": cached_at,
}
def run_phase3_writers_summary() -> dict:
"""Fetch phase3 writer health for the explorer panel.
Primary path: HTTP GET coordinator:8787/writer-health (sync_daemon
publishes a snapshot every tick; the coordinator serves it). Single
auth'd call over WireGuard. Colours come from tick-age, not commit-age,
so healthy writers stay green during quiet periods.
Fallback: SSH to the hub, fetch the most recent commit per writer
(phase3:/phase3-queue:/phase3-heartbeats:), spool depth, and the last
few sync_daemon journal lines. Slower, conflates 'writer alive' with
'something has changed lately', and depends on SSH access -- but
survives any future deploy gap where the HTTP endpoint is unreachable.
Returns {hub_reachable: bool, writers: {git_writer: {...}, queue_writer:
{...}, heartbeat_writer: {...}} | None, spool_pending: int|null,
journal_tail: [str], probe: 'http'|'ssh', cached_at: iso,
fleet_drained: bool|null (optional)}.
"""
global _phase3_writers_cache, _phase3_writers_cache_at
with _phase3_writers_lock:
now = time.time()
if (_phase3_writers_cache is not None
and (now - _phase3_writers_cache_at) < _PHASE3_WRITERS_TTL):
return _phase3_writers_cache
cfg = _load_coordinator_cfg()
http_result = _fetch_phase3_writer_health_http(cfg)
if http_result is not None:
_phase3_writers_cache = http_result
_phase3_writers_cache_at = now
return http_result
# Hub SSH target: local configuration only. Do not hard-code deployment
# hostnames or public IPs in the public repo.
hub_host = (cfg.get("SHADOW_SSH_HOST_ree-cloud-1")
or cfg.get("PHASE3_HUB_SSH_HOST")
or _PHASE3_HUB_DEFAULT_HOST)
if not hub_host:
result = {
"hub_reachable": False,
"hub_host": None,
"writers": None,
"spool_pending": None,
"journal_tail": [],
"error": "PHASE3 hub SSH host is not configured locally.",
"probe": "ssh",
"cached_at": _utc_now_iso_z(),
}
_phase3_writers_cache = result
_phase3_writers_cache_at = now
return result
ssh_user = cfg.get("COORDINATOR_SSH_USER", "ree")
sentinel_g = "===PHASE3_GIT==="
sentinel_q = "===PHASE3_QUEUE==="
sentinel_h = "===PHASE3_HB==="
sentinel_s = "===PHASE3_SPOOL==="
sentinel_j = "===PHASE3_JOURNAL==="
# `--all` so we surface writer commits even if local HEAD is behind
# origin/<default>. `git -C ~/REE_Working/REE_assembly` -- the hub
# checkout path documented in CLAUDE.md Coordinator section.
cmd = (
"echo " + sentinel_g + " && "
"git -C ~/REE_Working/REE_assembly log -1 --all "
"--grep='^phase3:' --pretty='%H %at %s' 2>/dev/null && "
"echo " + sentinel_q + " && "
"git -C ~/REE_Working/ree-v3 log -1 --all "
"--grep='^phase3-queue:' --pretty='%H %at %s' 2>/dev/null && "
"echo " + sentinel_h + " && "
"git -C ~/REE_Working/REE_assembly log -1 --all "
"--grep='^phase3-heartbeats:' --pretty='%H %at %s' 2>/dev/null && "
"echo " + sentinel_s + " && "
"ls /home/ree/coordinator-spool/pending/ 2>/dev/null | wc -l && "
"echo " + sentinel_j + " && "
"(sudo -n journalctl -u ree-sync-daemon -n 3 --no-pager 2>&1 "
"|| journalctl -u ree-sync-daemon -n 3 --no-pager --user 2>&1 "
"|| echo 'journalctl unavailable')"
)
cached_at = _utc_now_iso_z()
# _ssh() truncates stdout to 300 chars -- not enough for the journal
# tail, so call subprocess directly. Same hardening as _ssh
# (BatchMode, ConnectTimeout, accept-new).
try:
cp = subprocess.run(
["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5",
"-o", "StrictHostKeyChecking=accept-new",
f"{ssh_user}@{hub_host}", cmd],
capture_output=True, text=True, timeout=25)
except Exception as exc: # noqa: BLE001
result = {
"hub_reachable": False,
"hub_host": hub_host,
"writers": None,
"spool_pending": None,
"journal_tail": [],
"error": repr(exc),
"probe": "ssh",
"cached_at": cached_at,
}
_phase3_writers_cache = result
_phase3_writers_cache_at = now
return result
if cp.returncode != 0:
detail = (cp.stderr or cp.stdout or "").strip()[:300]
result = {
"hub_reachable": False,
"hub_host": hub_host,
"writers": None,
"spool_pending": None,
"journal_tail": [],
"error": detail or ("ssh rc=%d" % cp.returncode),
"probe": "ssh",
"cached_at": cached_at,
}
_phase3_writers_cache = result
_phase3_writers_cache_at = now
return result
stdout = cp.stdout or ""
def _block(text: str, start: str, end: str | None) -> str:
i = text.find(start)
if i < 0:
return ""
i += len(start)
j = text.find(end, i) if end else len(text)
if j < 0:
j = len(text)
return text[i:j].strip()
g_block = _block(stdout, sentinel_g, sentinel_q)
q_block = _block(stdout, sentinel_q, sentinel_h)
h_block = _block(stdout, sentinel_h, sentinel_s)
s_block = _block(stdout, sentinel_s, sentinel_j)
j_block = _block(stdout, sentinel_j, None)
now_unix = time.time()
def _writer_row(block: str, writer: str = "default") -> dict:
parsed = _parse_phase3_log_line(block)
if not parsed:
return {"sha10": None, "committed_at": None, "subject": None,
"age_s": None, "color": "red"}
age = max(0.0, now_unix - parsed["committed_at"])
return {
"sha10": parsed["sha10"],
"committed_at": parsed["committed_at"],
"subject": parsed["subject"],
"age_s": int(age),
"color": _phase3_freshness_color(age, writer=writer),
}
writers = {
"git_writer": _writer_row(g_block, writer="git_writer"),
"queue_writer": _writer_row(q_block, writer="queue_writer"),
"heartbeat_writer": _writer_row(h_block, writer="heartbeat_writer"),
}
# Journal-derived status hint for each writer. Cheap pattern match;
# leaves "idle" as the default when the tail doesn't say otherwise.
journal_lines = [ln for ln in j_block.splitlines() if ln.strip()]
tail_blob = " ".join(journal_lines).lower()
if "push rejected" in tail_blob or "non-fast-forward" in tail_blob:
writer_status = "push-rejected"
elif ("conflict" in tail_blob or "rebase aborted" in tail_blob
or "needs operator" in tail_blob):
writer_status = "rebase-conflict"
elif "refusing" in tail_blob or "dirty tree" in tail_blob:
writer_status = "refusing"
elif ("committed" in tail_blob or "committing" in tail_blob
or "wrote" in tail_blob or "tick:" in tail_blob):
writer_status = "committing"
else:
writer_status = "idle"
for row in writers.values():
row["status"] = writer_status
try:
spool_pending = int(s_block.strip().splitlines()[-1])
except (ValueError, IndexError):
spool_pending = None
result = {
"hub_reachable": True,
"hub_host": hub_host,
"writers": writers,
"spool_pending": spool_pending,
"journal_tail": journal_lines[-3:],
"probe": "ssh",
"cached_at": cached_at,
}
_phase3_writers_cache = result
_phase3_writers_cache_at = now
return result
def run_preflight_suite() -> dict:
"""Run ree-v3/tests/preflight and return a serialisable result dict.
Fields: ok (bool), passed (int), failed (int), duration_s (float),
cached_at (iso8601 Z), tail (last stdout lines, <=40), error (str|None).
Memoised for _PREFLIGHT_TTL seconds.
"""
global _preflight_cache, _preflight_cache_at
with _preflight_lock:
now = time.time()
if _preflight_cache is not None and (now - _preflight_cache_at) < _PREFLIGHT_TTL:
return _preflight_cache
ree_v3 = SERVE_DIR.parent / "ree-v3"
preflight_dir = ree_v3 / "tests" / "preflight"
if not preflight_dir.exists():
result = {
"ok": False,
"passed": 0,
"failed": 0,
"duration_s": 0.0,
"cached_at": _utc_now_iso_z(),
"tail": [],
"error": f"preflight directory missing: {preflight_dir}",
}
_preflight_cache = result
_preflight_cache_at = now
return result
start = time.time()
try:
proc = subprocess.run(
[V3_PYTHON, "-m", "pytest", "-q", "--tb=line", str(preflight_dir)],
cwd=str(ree_v3),
capture_output=True,
text=True,
timeout=120,
)
duration = time.time() - start
out = (proc.stdout or "") + (proc.stderr or "")
# Parse "N passed" / "N failed" from pytest summary.
passed = 0
failed = 0
m_pass = re.search(r"(\d+)\s+passed", out)
m_fail = re.search(r"(\d+)\s+failed", out)
if m_pass:
passed = int(m_pass.group(1))
if m_fail:
failed = int(m_fail.group(1))
tail = out.splitlines()[-40:]
result = {
"ok": proc.returncode == 0,
"passed": passed,
"failed": failed,
"duration_s": round(duration, 3),
"cached_at": _utc_now_iso_z(),
"tail": tail,
"error": None if proc.returncode == 0 else f"exit {proc.returncode}",
}
except subprocess.TimeoutExpired:
result = {
"ok": False,
"passed": 0,
"failed": 0,
"duration_s": round(time.time() - start, 3),
"cached_at": _utc_now_iso_z(),
"tail": [],
"error": "timeout",
}
except Exception as exc:
result = {
"ok": False,
"passed": 0,
"failed": 0,
"duration_s": round(time.time() - start, 3),
"cached_at": _utc_now_iso_z(),
"tail": [],
"error": f"{type(exc).__name__}: {exc}",
}
_preflight_cache = result
_preflight_cache_at = now
return result
# ── Workspace health (stale TASK_CLAIMS + orphaned git stashes) ─────────────
# Explorer UI improvement plan B2: neither signal was computed by serve.py at
# all -- both were standalone CLI scripts (scripts/audit_stale_claims.py,
# scripts/audit_stashes.py) with no HTTP surface. Shells out to each with
# --json on a cheap cache TTL, mirroring run_preflight_suite() above rather
# than porting the classification logic (lower risk -- the scripts stay the
# single source of truth for what counts as stale/orphaned).
_WORKSPACE_HEALTH_TTL = 60.0
_workspace_health_cache: dict | None = None
_workspace_health_cache_at: float = 0.0
_workspace_health_lock = threading.Lock()
UMBRELLA_DIR = SERVE_DIR.parent
_SCRIPTS_DIR = UMBRELLA_DIR / "scripts"
def _run_json_script(script: Path, args: list[str], timeout: float) -> dict:
"""Run `python3 script *args` and parse stdout as JSON. Raises on failure."""
if not script.exists():
raise FileNotFoundError(f"{script} missing")
proc = subprocess.run(
[sys.executable, str(script), *args],
cwd=str(UMBRELLA_DIR),
capture_output=True,
text=True,
timeout=timeout,
)
try:
return json.loads(proc.stdout)
except (json.JSONDecodeError, ValueError) as exc:
tail = (proc.stderr or proc.stdout or "").strip().splitlines()[-5:]
raise ValueError(
f"exit {proc.returncode}, unparseable output: {'; '.join(tail)}"
) from exc
def _stale_claims_summary(timeout: float = 20.0) -> dict:
try:
data = _run_json_script(
_SCRIPTS_DIR / "audit_stale_claims.py", ["--json"], timeout)
buckets: dict[str, int] = {}
for r in data.get("records") or []:
b = r.get("bucket") or "?"
buckets[b] = buckets.get(b, 0) + 1
return {
"ok": True,
"count": data.get("stale_active", 0),
"contentions": len(data.get("contentions") or []),
"buckets": buckets,
"error": None,
}
except Exception as exc:
return {"ok": False, "count": 0, "contentions": 0, "buckets": {},
"error": f"{type(exc).__name__}: {exc}"}
def _orphaned_stashes_summary(timeout: float = 20.0) -> dict:
try:
data = _run_json_script(
_SCRIPTS_DIR / "audit_stashes.py", ["--json"], timeout)
repos = []
total = 0
for r in data.get("repos") or []:
n = len(r.get("entries") or [])
n_rebase = len(r.get("rebase_findings") or [])
total += n + n_rebase
if n or n_rebase or r.get("error"):
repos.append({
"repo": r.get("repo"),
"entries": n,
"rebase_findings": n_rebase,
"error": r.get("error"),
})
return {"ok": True, "count": total, "repos": repos, "error": None}
except Exception as exc:
return {"ok": False, "count": 0, "repos": [],
"error": f"{type(exc).__name__}: {exc}"}
def run_workspace_health_summary() -> dict:
"""Combined stale-claim + orphaned-stash summary. Memoised for
_WORKSPACE_HEALTH_TTL seconds -- each half is a git-touching CLI script,
not free, and the corner-dock panel polls this on a fixed interval.
"""
global _workspace_health_cache, _workspace_health_cache_at
with _workspace_health_lock:
now = time.time()
if (_workspace_health_cache is not None
and (now - _workspace_health_cache_at) < _WORKSPACE_HEALTH_TTL):
return _workspace_health_cache
stale_claims = _stale_claims_summary()
stashes = _orphaned_stashes_summary()
result = {
"ok": stale_claims["ok"] and stashes["ok"],
"cached_at": _utc_now_iso_z(),
"stale_claims": stale_claims,
"stashes": stashes,
}
_workspace_health_cache = result
_workspace_health_cache_at = now
return result
# ── Docs picker index ─────────────────────────────────────────────────────────
_DOCS_PICKER_CONFIG_PATH = SERVE_DIR / "docs_picker_config.json"
_DOCS_TITLE_ACRONYMS = {"REE", "E1", "E2", "E3", "JEPA", "V1", "V2", "V3", "V4"}
def _title_from_filename(path: Path) -> str:
words = re.split(r"[_\-]+", path.stem)
parts = [w.upper() if w.upper() in _DOCS_TITLE_ACRONYMS else w.capitalize()
for w in words if w]
return " ".join(parts) if parts else path.stem
def read_docs_index() -> dict:
"""Doc index for the Docs picker (GET /api/docs/index): curated groups
from docs_picker_config.json, plus every *.md file in that config's
low-noise 'auto_dirs' (titled from its filename). docs/architecture/ and
evidence/planning/ are deliberately NOT auto-scanned -- both are mostly
historical/working files rather than reference docs (247 vs ~48 curated,
799 vs 11 curated as of 2026-08-02) -- see docs_picker_config.json's
top-level comment and explorer_ui_improvement_plan.md C4.
"""
try:
config = json.loads(_DOCS_PICKER_CONFIG_PATH.read_text())
except Exception as exc:
return {"groups": [], "error": f"{type(exc).__name__}: {exc}"}
serve_root = SERVE_DIR.resolve()
groups = []
seen_paths = set()
for group in config.get("curated_groups", []):
docs = []
for doc in group.get("docs", []):
rel_path = doc.get("path")
if not rel_path:
continue
seen_paths.add(rel_path)
docs.append({"title": doc.get("title") or rel_path, "path": rel_path})
if docs:
groups.append({"label": group.get("label") or "Docs", "docs": docs})
for entry in config.get("auto_dirs", []):
rel_dir = entry.get("dir")
label = entry.get("group") or rel_dir
if not rel_dir:
continue
abs_dir = (SERVE_DIR / rel_dir).resolve()
if abs_dir != serve_root and serve_root not in abs_dir.parents:
continue # outside the repo root -- ignore rather than serve it
if not abs_dir.is_dir():
continue
docs = []
for f in sorted(abs_dir.glob("*.md")):
rel_path = str(f.relative_to(serve_root))
if rel_path in seen_paths:
continue # already reachable via a curated entry
seen_paths.add(rel_path)
docs.append({"title": _title_from_filename(f), "path": rel_path})
if docs:
groups.append({"label": label, "docs": docs})
return {"groups": groups, "error": None}
# ── GitHub fallback ───────────────────────────────────────────────────────────
ORG = "Latent-Fields"
ORG_MEMBERSHIP_URL = "https://github.com/orgs/Latent-Fields/teams"
REPO_NAMES: dict[str, str] = {
"v3": "ree-v3",
"v2": "ree-v2",
"v1": "ree-v1-minimal",
}
_GIT_ACCESS_DENIED = re.compile(
r"Repository not found|Permission denied|403|Authentication failed|could not read Username",
re.IGNORECASE,
)
def _ensure_git_file(file_path: Path, repo_dir: Path, repo_name: str, clone_url: str) -> dict | None:
"""Ensure file_path exists, attempting git pull/clone if missing.
Returns None on success, or an error dict on failure."""
if file_path.exists():
return None
if (repo_dir / ".git").is_dir():
cmd = ["git", "-C", str(repo_dir), "pull", "--ff-only"]
action = "pull"
else:
cmd = ["git", "clone", clone_url, str(repo_dir)]
action = "clone"
print(f"[serve] {file_path.name} missing -- attempting git {action} from {clone_url}", flush=True)
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
except subprocess.TimeoutExpired:
return {"status": "error", "error": "timeout",
"message": f"Git {action} timed out after 60s."}
stderr_combined = result.stderr + result.stdout
if result.returncode != 0 and _GIT_ACCESS_DENIED.search(stderr_combined):
return {
"status": "error",
"error": "access_denied",
"message": (
f"Cannot access {ORG}/{repo_name} on GitHub. "
"Request membership of the Latent-Fields organisation to gain access."
),
"action_url": ORG_MEMBERSHIP_URL,
"action_label": "Request Latent-Fields membership",