Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
1599 lines (1424 loc) · 83.2 KB
/
Copy pathserver.py
File metadata and controls
1599 lines (1424 loc) · 83.2 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
"""Self-editable Starlette/uvicorn entry point for UI and supervisor runtime."""
import asyncio
import json
import subprocess as subprocess
import os
import pathlib
import sys
import threading
import time
import uuid
# Before any import resolves a path: the executing checkout is the implicit repository and the data root is
# settled; an explicit value wins, and APP_ROOT alone never silently leaves historical memory (#1239).
from ouroboros.launch_roots import enter_direct, same_location # noqa: E402 — standard library only
os.environ.update(enter_direct(os.path.dirname(os.path.abspath(__file__))))
# Protect Python import diagnostics too. Only the forkserver's preload stays thread-free (it forks
# every pool child); a spawned child, the event-bus manager's included, relays from here.
from ouroboros.process_logging import _install_output_relay, preloading_forkserver # noqa: E402
_install_output_relay(start_thread=not preloading_forkserver())
from ouroboros.utils import read_json_dict as read_json_dict, utc_now_iso # noqa: E402
from typing import Any, Dict, Optional
from starlette.applications import Starlette
from starlette.routing import Route
import uvicorn
from ouroboros.server_control import (PanicIngress, execute_panic_stop as _execute_panic_stop_impl,
exit_after_shutdown, panic_termination_requested,
restart_current_process as _restart_current_process_impl) # noqa: F401 — restart lifecycle binding
from ouroboros.owned_shutdown import (begin_owned_stop, finish_unconfirmed_stops, start_inherited_import,
stop_owned_work)
from ouroboros.server_auth import (
NetworkAuthGate,
get_network_auth_startup_warning,
validate_network_auth_configuration,
)
from ouroboros.server_entrypoint import (ServerAdmissionRefused, admit_data_root, bound_service_socket,
find_free_port, parse_server_args, raise_gc_threshold, reserved_service_ports,
shorten_switch_interval, write_port_file)
from ouroboros.launcher_bootstrap import automatic_launch_allowed
from ouroboros import body_adoption, places, process_scope, server_boot, store_switch
from ouroboros.server_web import ServedUI
from ouroboros.config import resolve_port_file
from ouroboros.process_logging import configure_process_logging
from ouroboros.task_finalization import host_operation_reply_kwargs
from ouroboros import usage_store # the boot import of the retired journal (run_startup_phase below)
from ouroboros.gateway import collect_routes
from ouroboros.gateway import settings as _gateway_settings
from ouroboros.gateway.ws import (
broadcast_ws,
broadcast_ws_sync,
close_all_ws,
has_ws_clients as _has_ws_clients,
set_event_loop as _set_ws_event_loop,
)
from ouroboros.server_process import ( # noqa: F401
DATA_DIR, _owner_restart_requested,
_request_restart_exit, _restart_requested,
_supervisor_stop, _exit_signalled,
_SignalStopServer,
capture_server_source_baseline, server_stop_cause, log, restart_gate_line, restored_queue_sentence,
FAULT_BUS_LOST, FAULT_LOOP_FAILED, bind_fault_exit, end_generation_on_fault, fault_cancel_reason,
fault_exit, held_saved_work_count, previous_fault_sentence, end_fault_held_runs, raise_open_file_limit,
)
from ouroboros.server_routing_context import ( # noqa: F401
_addressable_root_tasks,
_chat_running_tasks,
_clip_marked,
_decision_turn_metadata,
_latest_project_task_result,
_main_routing_manifest,
_owner_binding_chat_id,
_reserved_project_for_chat,
_scoped_task_metadata,
main_lane_routing_metadata,
)
from ouroboros.server_owner_routing import ( # noqa: F401
_owner_evolution_stop,
_route_owner_message,
_route_project_chat_to_running_task,
)
from ouroboros.server_liveness import ( # noqa: F401
_chat_turn_wedged,
_start_supervisor_liveness_watchdog,
_supervisor_loop_stalled,
drain_worker_events, flush_budget_projection, publish_supervisor_load,
)
from ouroboros.server_liveness import BOOT, start_boot_coordinator, wait_event
from ouroboros.server_maintenance import ( # noqa: F401
bind_body_lifespan,
_migrate_startup_cancel_latches,
_startup_worker_pids,
_installed_skill_names,
_periodic_supervisor_maintenance,
_prune_delegated_snapshots,
_prune_worktrees,
_reconcile_delegated_runs,
_resume_interrupted_project_deletions,
_run_startup_task_recovery,
_startup_retired_settings_notice,
_startup_environment_review_notice,
_startup_review_pool_notice,
_startup_custody_sweep,
_startup_prune_sweeps,
)
from ouroboros.ui_translation import start_background as _start_ui_translation
from supervisor.workspace_preparation import start_generation as _start_preparation_generation
from supervisor.event_observation import pending_idle_observations
from ouroboros import server_restart as _restart_lifecycle
from ouroboros.server_restart import ( # noqa: F401
_begin_task_teardown, _live_running_task_ids, _managed_update_pending_kwargs,
_perform_owner_restart, _safe_restart_serialized,
_shutdown_supervisor_event_bus, _shutdown_task_cleanup_args,
_stop_owned_daemon_for_new_pin,
)
REPO_DIR = pathlib.Path(os.environ["OUROBOROS_REPO_DIR"])
capture_server_source_baseline(REPO_DIR)
DEFAULT_HOST = os.environ.get("OUROBOROS_SERVER_HOST", "127.0.0.1")
DEFAULT_PORT = int(os.environ.get("OUROBOROS_SERVER_PORT", "8765"))
PORT_FILE = resolve_port_file(DATA_DIR, hosting_data_dir=DATA_DIR)
sys.path.insert(0, str(REPO_DIR))
if isinstance(sys.executable, str) and sys.executable: # this host's interpreter, never an inherited (moved-app) one
os.environ["OUROBOROS_AGENT_PYTHON"] = sys.executable
# Logging is configured in main(), not at import: a spawn/forkserver worker re-imports
# this module as ``__mp_main__`` and configures itself in ``worker_main``
# (ouroboros/process_logging.py), so importing the server never attaches handlers.
_pytest_default_real_data_dir = (
"pytest" in sys.modules
and not os.environ.get("OUROBOROS_DATA_DIR")
and same_location(DATA_DIR, pathlib.Path.home() / "Ouroboros" / "data")
)
RESTART_EXIT_CODE = 42
PANIC_EXIT_CODE = 99
_planned_delegate_restart_transaction_id = ""
_LAUNCHER_MANAGED = str(os.environ.get("OUROBOROS_MANAGED_BY_LAUNCHER", "") or "").strip() == "1"
_LAUNCHER_MANAGED_REPO_DIR = str(os.environ.get("OUROBOROS_MANAGED_REPO_DIR", "") or "").strip()
# Captured in main() for Settings LAN-reachability metadata.
_BIND_HOST = DEFAULT_HOST
def _has_active_evolution_transaction() -> bool:
try:
path = DATA_DIR / "state" / "evolution_campaign.json"
if not path.is_file():
return False
raw = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(raw, dict):
return False
if raw.get("status") not in {"active", "paused"}:
return False
tx = raw.get("active_transaction")
return isinstance(tx, dict) and not str(tx.get("commit_sha") or "").strip()
except Exception:
return False
def _launcher_managed_repo_matches() -> bool:
try:
from supervisor import git_ops as git_ops_module
return git_ops_module.launcher_managed_repo_matches(
REPO_DIR, managed_by_launcher=_LAUNCHER_MANAGED, managed_repo_dir=_LAUNCHER_MANAGED_REPO_DIR)
except (OSError, RuntimeError, ValueError, ImportError):
return False
def _restart_current_process(host: str, port: int) -> None:
return _restart_lifecycle._restart_current_process(sys.modules[__name__], host, port)
from ouroboros.config import (
SERVER_GRACEFUL_SHUTDOWN_TIMEOUT_SEC,
SETTINGS_DEFAULTS,
SettingsIntegrityError,
load_settings, save_settings, verify_settings_integrity,
apply_settings_to_env as _apply_settings_to_env,
)
from ouroboros.server_runtime import (
apply_runtime_provider_defaults,
has_startup_ready_provider,
needs_local_model_autostart,
setup_remote_if_configured,
ws_heartbeat_loop,
)
_supervisor_ready = threading.Event() # a live generation finished init: the API's `supervisor_ready`
# Init reached ready or `_supervisor_error`. Stop before init is deliberately no outcome:
# a dying generation must not release the update finalizer waiting on this event.
_supervisor_init_done = threading.Event()
_supervisor_error: Optional[str] = None
_bootstrap_ok: Optional[bool] = None # this generation's `_bootstrap_supervisor_repo` outcome; None until it ran
_event_loop: Optional[asyncio.AbstractEventLoop] = None
_supervisor_thread: Optional[threading.Thread] = None
_consciousness: Any = None
# This generation's extensions registered their event-bus subscribers: the supervisor's first tick
# (an overdue note) waits for it. Set outside a lifespan, cleared when one starts, set by its boot step.
_extensions_ready = threading.Event()
_extensions_ready.set()
_dialogue_bridge: Any = None # the chat bridge published at the store's publication (`dialogue_ready`)
_dialogue_lock = threading.Lock()
from ouroboros.consciousness_view import _clock_of as _clock_of, describe_consciousness, describe_consciousness_state
def _describe_bg_consciousness_state(requested_enabled: bool | None) -> dict:
return describe_consciousness_state(_consciousness.status_snapshot() if _consciousness else {}, requested_enabled, supervisor_failed=bool(_supervisor_error))
def _start_supervisor_if_needed(settings: dict) -> bool:
"""Start the supervisor once when runtime providers become available."""
global _supervisor_thread, _supervisor_error, _bootstrap_ok
if not has_startup_ready_provider(settings):
return False
if _supervisor_thread and _supervisor_thread.is_alive():
return False
if _exit_signalled.is_set():
return False # the process is exiting: no revival behind the teardown
_supervisor_error = None
_bootstrap_ok = None
_supervisor_stop.clear() # in-process revival after a teardown-stopped generation
_supervisor_ready.clear() # readiness is THIS generation's: Starting, not a stale Online, until init succeeds
_supervisor_init_done.clear()
_supervisor_thread = threading.Thread(
target=_supervisor_generation,
args=(settings,),
daemon=True,
name="supervisor-main",
)
_supervisor_thread.start()
return True
def _supervisor_generation(settings: dict) -> None:
"""Thread body: re-check the exit latch, then run one supervisor generation.
Admission (`_start_supervisor_if_needed`) and this thread start are separate steps,
so a settings save can pass the latch check a moment before SIGTERM; a generation
that starts anyway must end here, before its startup kill/spawn would run behind
the teardown's `kill_workers` (#1142).
"""
global _supervisor_thread
if _exit_signalled.is_set() or not _await_extensions_ready():
_supervisor_thread = None
return
_run_supervisor(settings)
def _await_extensions_ready(*stops: threading.Event) -> bool:
"""Wait until this generation's extensions registered their event-bus subscribers; False when
the generation ends first. The supervisor's first scheduler tick may consume an overdue note
and the bus keeps no history, so a subscriber attached later (Telegram) would miss it."""
return wait_event(_extensions_ready, _exit_signalled, _supervisor_stop, _restart_requested, *stops)
def _preserve_unprocessed_updates(bridge, updates, consumed: int) -> int:
"""Best effort, never raises: hand the tail behind the ``consumed``-th update back to the bridge, ids
intact, for this process's next read; what is not kept is logged as lost.
Memory only: it dies with process exit; accepted rows outlive it."""
tail, requeue, kept = list(updates[consumed:]), getattr(bridge, "requeue_updates", None), 0
try:
if tail and callable(requeue):
kept = int(requeue(tail) or 0)
except Exception as exc:
log.error("Bridge %s hand-back raised: %s", type(bridge).__name__, exc, exc_info=True)
if kept < len(tail):
log.error("Bridge %s cannot take back %d unprocessed update(s); they are lost", type(bridge).__name__, len(tail) - kept)
return kept
def _process_bridge_updates(bridge, offset: int, ctx: Any, *, timeout: float = 1) -> int:
updates = bridge.get_updates(offset=offset, timeout=timeout)
cursor = [0] # updates taken up so far, the one in flight included
try:
return _handle_bridge_update_batch(bridge, updates, offset, ctx, cursor)
except Exception as exc:
# The failing update is the crash the loop accounts for; the ones behind it were
# only dequeued, never handled, and come back next tick (the hand-back never raises).
failed = (updates[cursor[0] - 1] if 0 < cursor[0] <= len(updates) else {}).get("update_id")
kept = _preserve_unprocessed_updates(bridge, updates, cursor[0])
log.error("Bridge update %s failed: %s; %d later update(s) handed back to the bridge", failed, exc, kept)
raise
def _handle_bridge_update_batch(bridge, updates, offset: int, ctx: Any, cursor: list) -> int:
from supervisor.message_bus import coerce_chat_identity
from ouroboros.chat_uploads import attachment_placeholder
for upd in updates:
cursor[0] += 1
offset = int(upd["update_id"]) + 1
msg = upd.get("message") or {}
if not msg:
continue
# get_updates may return several already-queued messages. Rebind the
# transport per message rather than using the last route in the batch.
if hasattr(bridge, "activate_update_transport"):
bridge.activate_update_transport(msg)
chat_id = coerce_chat_identity((msg.get("chat") or {}).get("id"), 1)
user_id = coerce_chat_identity((msg.get("from") or {}).get("id"), chat_id or 1)
text = str(msg.get("text") or "")
source = str(msg.get("source") or "web")
sender_session_id = str(msg.get("sender_session_id") or "")
client_message_id = str(msg.get("client_message_id") or "")
transport = msg.get("transport") if isinstance(msg.get("transport"), dict) else {}
image_base64 = str(msg.get("image_base64") or "")
image_mime = str(msg.get("image_mime") or "image/jpeg")
image_caption = str(msg.get("image_caption") or "")
task_constraint = msg.get("task_constraint") if isinstance(msg.get("task_constraint"), dict) else None
task_metadata = msg.get("task_metadata") if isinstance(msg.get("task_metadata"), dict) else None
image_data = (image_base64, image_mime, image_caption) if image_base64 else None
log_text = text.strip() or image_caption.strip() or attachment_placeholder(image_base64, task_metadata)
now_iso = utc_now_iso()
if not client_message_id:
# Some owner transports have no client-generated id. Give the
# canonical row a deterministic host id before logging/routing so a
# typed non-bubble acknowledgement cannot be silently dropped and a
# replay of the same inbound update remains idempotent.
identity = json.dumps(
{
"source": source,
"session": sender_session_id,
"chat_id": chat_id,
"user_id": user_id,
"update_id": int(upd.get("update_id") or 0),
"text": text,
"caption": image_caption,
"transport": transport,
},
ensure_ascii=False,
sort_keys=True,
default=str,
)
client_message_id = f"host-{uuid.uuid5(uuid.NAMESPACE_URL, identity).hex}"
lowered = text.strip().lower()
is_slash_command = lowered.startswith("/")
is_external_transport = source != "web"
external_identity_present = (not is_external_transport) or (chat_id > 0 and user_id > 0)
# Emergency Stop Invariant (#1307): the local door stops before any state read,
# chat record, state update or reply; an external transport needs a POSITIVELY
# bound owner (one lock-free read) and never registers a stranger from an unknown slot.
panic = lowered.startswith("/panic")
if panic and not is_external_transport:
_execute_panic_stop(ctx.consciousness, ctx.kill_workers)
return offset # Never drain another already-queued message after Panic.
from supervisor.state import StateUnavailable, control_value
st = ctx.load_state()
if getattr(bridge, "panic", None) is not None:
bridge.panic.observe_owner(st)
from ouroboros.server_control import external_owner_binding
ext_known, owner_ext_id, bound_pair = external_owner_binding(st)
if panic and external_identity_present and ext_known and owner_ext_id is not None and (
bound_pair == (user_id, chat_id)):
_execute_panic_stop(ctx.consciousness, ctx.kill_workers)
return offset
from supervisor.message_bus import record_inbound_message
# The same writer mints ordinary ingress and validates preaccepted
# skill deliveries; the latter already have their one canonical row.
origin_message_ref = record_inbound_message(
bridge, msg, chat_id=chat_id, user_id=user_id,
client_message_id=client_message_id, text=log_text, ts=now_iso,
)
if task_metadata or msg.get("accepted_source_ref"):
task_metadata = {k: v for k, v in (task_metadata or {}).items() if k != "_host_operation"}
if msg.get("accepted_source_ref"):
task_metadata["_host_operation"] = True
reply_source = origin_message_ref if msg.get("accepted_source_ref") else None
def reply(body: str, status: str = "completed") -> None:
ctx.send_with_budget(chat_id, body, **host_operation_reply_kwargs(reply_source, status, client_message_id), role="system", system_type="command_reply")
def _stamp_owner_activity(live: dict) -> None:
# Global owner = primary chat for outbound notices (web on desktop, the first
# transport on headless Colab), bound once — only into a slot KNOWN to be empty.
if control_value(live, "owner_id") == (True, None) and external_identity_present:
live["owner_id"] = user_id
live["owner_chat_id"] = _owner_binding_chat_id(ctx, chat_id, is_external_transport)
live["last_owner_message_at"] = now_iso
try:
ctx.update_state(_stamp_owner_activity)
except StateUnavailable as exc:
log.warning("Owner activity not stamped: %s", exc) # the message itself still proceeds
if not text and not image_base64 and not (task_metadata or {}).get("chat_attachment_uploads"):
continue
if is_external_transport and is_slash_command:
if not external_identity_present:
reply("⚠️ Command ignored: this transport did not provide owner identity.", "failed")
continue
if not ext_known:
reply("⚠️ Command ignored: the bound owner chat is unknown right now (runtime state "
"is unavailable or recovering), so no command runs and no chat is registered.", "failed")
continue
if owner_ext_id is None:
bound = {"ok": False}
def _bind_external_owner(live: dict) -> None:
if control_value(live, "owner_external_id") == (True, None):
live["owner_external_id"] = user_id
live["owner_external_chat_id"] = chat_id
live["owner_external_bound_at"] = now_iso
bound["ok"] = True
try:
saved_owner = ctx.update_state(_bind_external_owner)
if getattr(bridge, "panic", None) is not None:
bridge.panic.observe_owner(saved_owner)
except StateUnavailable:
pass
reply("✅ Owner chat registered. Send the command again to execute it." if bound["ok"] else
"⚠️ Command ignored: the owner chat could not be registered right now.",
"completed" if bound["ok"] else "failed")
continue
if bound_pair != (user_id, chat_id):
reply("⚠️ Command ignored: this transport is not the bound owner chat.", "failed")
continue
if lowered.startswith("/restart"):
reply("♻️ Restarting." + restart_gate_line(REPO_DIR, DATA_DIR), "")
ok, restart_msg = _perform_owner_restart(ctx, reply)
if not ok:
reply(f"⚠️ Restart cancelled: {restart_msg}", "failed")
continue
_preserve_unprocessed_updates(bridge, updates, cursor[0]) # best effort; this generation handles nothing more
return offset # Remaining accepted rows stay durable; no replay is promised.
elif lowered == "/review" or lowered.startswith("/review "):
# Target the requesting chat so the ack and results return to the
# external transport owner, not the default web owner_chat_id.
# `/review <row>` names the executor (the Web selector sends it);
# a bare `/review` (Telegram) runs on the Main model.
parts = text.split(None, 1)
ctx.queue_deep_self_review_task(reason="owner:/review", force=True, chat_id=chat_id, client_message_id=client_message_id,
reviewer=parts[1].strip() if len(parts) > 1 else "", origin={"work_kind": "owner"})
elif lowered.startswith("/evolve"):
parts = lowered.split()
action = parts[1] if len(parts) > 1 else "on"
turn_on = action not in ("off", "stop", "0")
objective = ""
if turn_on and len(parts) > 2:
objective = text.split(None, 2)[2].strip()
if turn_on:
from supervisor.events_runtime_controls import owner_evolution_start
refusal = owner_evolution_start(objective, source="owner_chat")
reply(refusal or "🧬 Evolution campaign: ON", "failed" if refusal else "completed")
else:
reply(f"🧬 Evolution campaign: {_owner_evolution_stop(ctx, chat_id)}")
elif lowered.startswith("/bg"):
parts = lowered.split()
action = parts[1] if len(parts) > 1 else "status"
if action in ("start", "on", "1", "stop", "off", "0"):
from ouroboros.consciousness import OWNER_STOP
on = action in ("start", "on", "1") # the owner's door: app, Telegram and onboarding all send /bg
result = ctx.consciousness.start() if on else ctx.consciousness.stop(source=OWNER_STOP)
reply(f"🧠 {result}")
else:
from supervisor.state import control_value
known, enabled = control_value(ctx.load_state(), "bg_consciousness_enabled")
described = _describe_bg_consciousness_state(bool(enabled) if known else None)
note = f" {described['detail_note']}" if described.get("detail_note") else ""
reply(f"🧠 Background consciousness: {described['status']} — {described['detail']}{note}")
elif lowered.startswith("/status"):
from supervisor.state import status_text
status = status_text(ctx.WORKERS, ctx.PENDING, ctx.RUNNING)
reply(status)
else:
_route_owner_message(
bridge,
ctx,
{
"chat_id": chat_id,
"text": text,
"image_caption": image_caption,
"client_message_id": client_message_id,
"image_data": image_data,
"task_constraint": task_constraint,
"task_metadata": task_metadata,
"log_text": log_text,
"origin_message_ref": origin_message_ref,
"source": source, "received_at": str(msg.get("received_at") or ""),
},
)
return offset
def _runtime_branch_defaults() -> tuple[str, str]:
if _LAUNCHER_MANAGED:
try:
from supervisor import git_ops as git_ops_module
return git_ops_module.managed_branch_defaults(REPO_DIR)
except Exception:
pass
return "ouroboros", "ouroboros-stable"
def _bootstrap_supervisor_repo(settings: dict, git_ops_module=None):
if git_ops_module is None:
from supervisor import git_ops as git_ops_module
branch_dev, branch_stable = _runtime_branch_defaults()
git_ops_module.init(
repo_dir=REPO_DIR,
drive_root=DATA_DIR,
remote_url="",
branch_dev=branch_dev,
branch_stable=branch_stable,
)
git_ops_module.ensure_repo_present()
setup_remote_if_configured(settings, log)
# This tree is inside an adoption transition (landed, returned or still open): never reset it.
adoption_boot = body_adoption.holds_checkout(DATA_DIR, REPO_DIR)
if _launcher_managed_repo_matches() and not adoption_boot:
# An in-flight managed-update assisted merge intentionally leaves MERGE_HEAD + the partly
# resolved merge in the live worktree (over pre_update_sha). Use the NON-destructive
# rescue_and_block policy so the bootstrap restart does not reset/clean that merge state
# away before finalize_managed_update_on_boot / _recover_assisted_on_boot can resume it.
try:
from supervisor.update_merge import active_update_tx
_managed_update_active = bool(active_update_tx())
except Exception:
_managed_update_active = False
block = _has_active_evolution_transaction() or _managed_update_active
policy = "rescue_and_block" if block else "rescue_and_reset"
from ouroboros.server_restart import _noticed_bootstrap # its failure, not a deferral, is told
ok, msg = _safe_restart_serialized(
_noticed_bootstrap(git_ops_module.safe_restart),
reason="bootstrap",
unsynced_policy=policy,
)
if not ok and policy == "rescue_and_block":
try:
from supervisor.evolution_lifecycle import disable_evolution_projection, pause_evolution_campaign
disable_evolution_projection()
pause_evolution_campaign(f"bootstrap blocked to protect active evolution transaction: {msg}")
except Exception:
log.debug("Failed to pause evolution after blocked bootstrap", exc_info=True)
return ok, msg
if _LAUNCHER_MANAGED and not adoption_boot:
log.warning("Managed marker lacks matching repository identity; skipping destructive bootstrap for %s.", REPO_DIR)
log.info("Local-dev server start detected — skipping bootstrap git reset.")
deps_ok, deps_msg = git_ops_module.sync_runtime_dependencies(reason="bootstrap_local_dev")
if not deps_ok:
return False, f"Failed local-dev deps sync: {deps_msg}"
import_result = git_ops_module.import_test()
if import_result.get("ok"):
return True, "OK: local-dev bootstrap"
return False, f"Local-dev import test failed (rc={import_result.get('returncode', -1)})"
def _initialize_runtime_state(settings: dict, *, stop_requested=None) -> None:
"""Initialize before ingress; unavailable controls stay unknown while independent work continues."""
from supervisor.state import init as state_init, init_state
state_init(DATA_DIR, float(settings.get("TOTAL_BUDGET", SETTINGS_DEFAULTS["TOTAL_BUDGET"])),
stop_requested=stop_requested)
boot_state = init_state()
if boot_state.quality not in {"current", "recovered"}:
log.critical("Runtime state is %s (%s): owner binding, evolution and consciousness "
"controls stay unknown until it is readable", boot_state.quality, boot_state.reason)
def _dialogue_cutover(root: pathlib.Path) -> None:
"""The dialogue store takes over the live chat/progress files once per root (recent client ids
dedup before the first accepted message); a failure is this step's, and the dialogue still opens:
its writer seam repeats an unfinished cutover before it stores a row, and readers answer
"still importing" until one completes."""
from ouroboros.dialogue_import import cutover
BOOT.step_started("dialogue_cutover")
try:
cutover(root, initialize_journal=True) # the boot alone chooses an existing file's journal
except Exception as exc:
log.warning("Dialogue cutover did not complete; the first stored row repeats it", exc_info=True)
BOOT.step_ended("dialogue_cutover", error=f"{type(exc).__name__}: {exc}")
return
BOOT.step_ended("dialogue_cutover")
def _open_dialogue(settings: dict, *, stop_requested=None):
"""Publish the chat bridge and bus once per process: from then on an owner message is
accepted durably (its canonical chat row is written and the turn waits for its executor),
which is ``dialogue_ready``. The boot runs this at the store's publication, before any
repair; the supervisor attaches to the published bridge instead of creating a second one
(a direct supervisor start without a boot creates it here)."""
global _dialogue_bridge
from supervisor.message_bus import LocalChatBridge, init as bus_init, try_get_bridge
with _dialogue_lock:
if _dialogue_bridge is not None and try_get_bridge() is _dialogue_bridge:
return _dialogue_bridge
_initialize_runtime_state(settings, stop_requested=stop_requested)
from supervisor.state import load_state
bridge = LocalChatBridge(settings)
bridge.startup_owner_command = _startup_owner_command
bridge.panic = PanicIngress(_startup_owner_command("/panic"))
bridge.panic.observe_owner(load_state())
bridge._broadcast_fn = broadcast_ws_sync
from ouroboros.utils import set_log_sink
from supervisor.events import make_server_log_sink
set_log_sink(make_server_log_sink(bridge, pathlib.Path(DATA_DIR)))
bus_init(drive_root=DATA_DIR, chat_bridge=bridge)
_dialogue_bridge = bridge
BOOT.dialogue_ready()
log.info("Dialogue ready: owner messages are accepted.")
return bridge
def _run_supervisor(settings: dict) -> None:
"""Initialize and run the supervisor loop. Called in a background thread."""
global _supervisor_error, _supervisor_thread, _consciousness
_apply_settings_to_env(settings)
# Revival must drop the prior consciousness. Native turns own fresh agents.
if _consciousness is not None:
try:
_consciousness.stop()
except Exception:
log.debug("Failed to stop previous consciousness instance", exc_info=True)
_consciousness = None
prior_worker_pids: set[int] | None = None
_watchdog_stop = threading.Event() # per-generation: set on EVERY exit of this generation
def stop_requested(stop=_watchdog_stop) -> bool: # this generation's token bound now; shared stops read per call
return any(e.is_set() for e in (stop, _supervisor_stop, _restart_requested, _exit_signalled))
try:
BOOT.step_started("supervisor") # tasks_ready is this generation's; its sub-steps follow
# Watch startup stalls; even a failed watchdog start publishes an init outcome.
from ouroboros.server_liveness import loop_phase_facts, note_supervisor_ready, run_startup_phase
_loop_liveness = [time.monotonic(), {}, time.thread_time(), None] # slots: server_liveness.py
_loop_liveness[1], _loop_liveness[0] = loop_phase_facts(_loop_liveness, "startup", new_tick=True), time.monotonic()
_start_supervisor_liveness_watchdog(_loop_liveness, _watchdog_stop)
run_startup_phase(_loop_liveness, "startup:usage_store", lambda: usage_store.migrate_from_journal(pathlib.Path(DATA_DIR)))
run_startup_phase(_loop_liveness, "startup:current_store", lambda: store_switch.require_published(DATA_DIR)) # published before any worker or recovery write
from supervisor.state import control_is, load_state, save_state, update_state
from supervisor.state import append_jsonl, update_budget_from_usage, rotate_jsonl_log_if_needed
# The dialogue opened at the store's publication; this generation attaches to it.
bridge = _open_dialogue(settings, stop_requested=stop_requested)
from supervisor.git_ops import safe_restart
ok, msg = run_startup_phase(_loop_liveness, "startup:bootstrap", lambda: _bootstrap_supervisor_repo(settings))
global _bootstrap_ok
_bootstrap_ok = bool(ok)
if not ok:
log.error("Supervisor bootstrap failed: %s", msg)
from ouroboros.store_import import note_current_stamp
note_current_stamp(DATA_DIR) # the stamp the bootstrap just wrote: the legacy detector's observation
from supervisor.queue import (
enqueue_task, enforce_due_task_timeouts, enqueue_evolution_task_if_needed,
persist_queue_snapshot, publish_queue_changes, publish_queue_snapshot, restore_pending_from_snapshot,
queue_deep_self_review_task, sort_pending, start_queue_writer, stop_queue_writer, tick_publisher_started,
)
from supervisor.workers import (
init as workers_init, get_event_q, WORKERS, PENDING, RUNNING,
spawn_workers, kill_workers, assign_tasks, ensure_workers_healthy,
handle_chat_direct, auto_resume_after_restart, EventBusLost, event_bus_exitcode,
)
# Managed manifest branch defaults must drive worker commit/restart flows too.
branch_dev, branch_stable = _runtime_branch_defaults()
if not server_boot.wait_event_queue(lambda: panic_termination_requested() or stop_requested()):
_watchdog_stop.set()
BOOT.step_ended("supervisor", error="stopped before init")
return
run_startup_phase(_loop_liveness, "startup:workers_init", lambda: workers_init(
repo_dir=REPO_DIR, drive_root=DATA_DIR,
branch_dev=branch_dev, branch_stable=branch_stable,
))
from supervisor.message_bus import send_with_budget
from ouroboros.consciousness import BackgroundConsciousness
import types
prior_worker_pids = _startup_worker_pids(DATA_DIR)
interrupted_running: list = []
restored_pending = run_startup_phase(_loop_liveness, "startup:queue_restore", lambda: restore_pending_from_snapshot(terminalized=interrupted_running))
_start_preparation_generation(stop=stop_requested)
run_startup_phase(_loop_liveness, "startup:old_workers_stop", lambda: kill_workers(preserve_pending=True))
run_startup_phase(_loop_liveness, "startup:worker_spawn", spawn_workers)
from ouroboros.server_process import record_applied_restart_settings
record_applied_restart_settings({"OUROBOROS_SKILLS_REPO_PATH": settings.get("OUROBOROS_SKILLS_REPO_PATH", "")})
persist_queue_snapshot(reason="startup")
try:
from ouroboros.delegate_recovery import pre_adopt_planned_handoffs
run_startup_phase(_loop_liveness, "startup:delegate_pre_adopt", lambda: pre_adopt_planned_handoffs(DATA_DIR, list(PENDING)))
except Exception:
log.debug("Planned delegate pre-adoption failed", exc_info=True)
run_startup_phase(_loop_liveness, "startup:custody", _startup_custody_sweep)
recovered_files = run_startup_phase(_loop_liveness, "startup:task_recovery", lambda: _run_startup_task_recovery(
DATA_DIR, REPO_DIR, skip_live_data=_pytest_default_real_data_dir,
prior_worker_pids=prior_worker_pids,
))
_resume_interrupted_project_deletions()
run_startup_phase(_loop_liveness, "startup:prune", lambda: _startup_prune_sweeps(preserve_task_sources=bool(
recovered_files["unresolved"] or recovered_files["protected"] or recovered_files["errors"]), recovery_report=recovered_files))
previous_fault = previous_fault_sentence(held_saved_work_count(PENDING)) # the last generation's fault, if one
if restored_pending > 0 or interrupted_running or previous_fault:
st_boot = load_state()
if st_boot.get("owner_chat_id"):
# The second clause states an INTENT, not an outcome: restore only fences an interrupted task with a
# durable cancel intent; cancellation custody writes its terminal a watchdog window later (task_lifecycle._INTENT_WATCHDOG_MIN_AGE_SEC).
notice = ["♻️"]
if restored_pending > 0:
notice.append(restored_queue_sentence(restored_pending, PENDING, DATA_DIR))
if interrupted_running:
count = len(interrupted_running)
notice.append(f"Settling {count} task{'' if count == 1 else 's'} that "
f"{'was' if count == 1 else 'were'} still running when the server stopped.")
notice.extend(filter(None, [previous_fault, places.paused_places_sentence(DATA_DIR)]))
send_with_budget(int(st_boot["owner_chat_id"]), " ".join(notice), role="system", system_type="startup_notice")
_startup_retired_settings_notice(settings)
_startup_environment_review_notice()
_startup_review_pool_notice(settings)
store_switch.startup_notice(DATA_DIR)
from ouroboros.upgrade_notices import startup_upgrade_notices
startup_upgrade_notices(settings)
run_startup_phase(_loop_liveness, "startup:resume", auto_resume_after_restart)
def _get_owner_chat_id() -> Optional[int]:
try:
return int((load_state() or {}).get("owner_chat_id") or 0) or None
except Exception:
return None
_consciousness = BackgroundConsciousness(
drive_root=DATA_DIR, repo_dir=REPO_DIR, owner_chat_id_fn=_get_owner_chat_id,
routing_metadata_fn=lambda cid: main_lane_routing_metadata(_event_ctx, cid)) # _event_ctx is built below
# A boot grant needs a KNOWN True and no unconsumed Panic flag (#1307).
from ouroboros.installation_stop import installation_panic
if control_is(load_state(), "bg_consciousness_enabled", True) and not installation_panic(DATA_DIR):
_consciousness.start()
log.info("Background consciousness auto-restored from saved state.")
_event_ctx = types.SimpleNamespace(
DRIVE_ROOT=DATA_DIR, REPO_DIR=REPO_DIR,
BRANCH_DEV=branch_dev, BRANCH_STABLE=branch_stable,
bridge=bridge, WORKERS=WORKERS, PENDING=PENDING, RUNNING=RUNNING,
send_with_budget=send_with_budget, load_state=load_state, save_state=save_state,
update_state=update_state,
update_budget_from_usage=update_budget_from_usage, append_jsonl=append_jsonl,
enqueue_task=enqueue_task,
queue_deep_self_review_task=queue_deep_self_review_task, persist_queue_snapshot=persist_queue_snapshot,
publish_queue_snapshot=publish_queue_snapshot, safe_restart=safe_restart, kill_workers=kill_workers, spawn_workers=spawn_workers,
sort_pending=sort_pending, consciousness=_consciousness,
handle_chat_direct=handle_chat_direct,
request_restart=_request_restart_exit,
)
except Exception as exc:
_supervisor_error = f"Supervisor init failed: {exc}"
_consciousness = None
log.critical("Supervisor initialization failed", exc_info=True)
try:
# Provider-configured lifespan normally relies on this supervisor
# owner for boot recovery. If initialization itself fails, keep the
# same custody pass instead of serving with orphan RUNNING rows.
recovery_pids = prior_worker_pids
if recovery_pids is None:
try:
recovery_pids = _startup_worker_pids(DATA_DIR)
except Exception:
recovery_pids = None
_run_startup_task_recovery(
DATA_DIR, REPO_DIR, skip_live_data=_pytest_default_real_data_dir,
prior_worker_pids=recovery_pids,
)
except Exception:
log.critical("Startup recovery after supervisor initialization failure failed", exc_info=True)
_supervisor_ready.clear() # never reached its loop: the API must not paint Online over the error
_supervisor_init_done.set()
BOOT.step_ended("supervisor", error=_supervisor_error)
_supervisor_thread = None
_watchdog_stop.set() # a generation that died in init has no loop to watch
return
_supervisor_ready.set()
_supervisor_init_done.set()
BOOT.step_ended("supervisor")
note_supervisor_ready()
offset = 0
crash_count = 0
_last_custody_reap = [0.0] # recovered checking copies become eligible off-loop after readiness
_last_review_job_reconcile = [time.time()]
# The watchdog was started before startup recovery; never start another here.
tick_publisher_started() # queue marks publish on this loop's tick while it lives (queue_publication)
start_queue_writer() # ...and their documents are written on the publisher thread, never on this one
while not _restart_requested.is_set() and not _supervisor_stop.is_set() and not _exit_signalled.is_set():
try:
_loop_liveness[1], _loop_liveness[0] = loop_phase_facts(_loop_liveness, "events", new_tick=True), time.monotonic()
# The dialogue chains (chat, progress) live in state/dialog.sqlite and were rotated one last
# time by the cutover; the remaining unbounded hot logs rotate on this tick with the one rotator.
# events.jsonl went LAST behind chain-aware custody readers (the store import's custody fold, legacy usage
# import, swarm rollup, worker boot verify) — rows keep replaying from archive/events_*.jsonl; tools/supervisor/
# task_reflections readers are tail-bounded and archive-backfilled (memory.read_jsonl_tail, api_logs_tail).
rotate_jsonl_log_if_needed(DATA_DIR, "events.jsonl", "events")
rotate_jsonl_log_if_needed(DATA_DIR, "tools.jsonl", "tools")
rotate_jsonl_log_if_needed(DATA_DIR, "supervisor.jsonl", "supervisor")
rotate_jsonl_log_if_needed(DATA_DIR, "task_reflections.jsonl", "task_reflections")
get_event_q() # the bus fact first: no dead worker is handed to the reaper on a dead bus
ensure_workers_healthy()
# One BOUNDED events batch (count + time; the remainder waits for the next
# turn), so a producer that keeps the queue non-empty cannot hide intake.
backlog = drain_worker_events(
get_event_q(), _event_ctx, _loop_liveness, on_restart=_handle_restart_in_supervisor,
)
if _restart_requested.is_set():
flush_budget_projection(_event_ctx) # this turn's drained llm_usage still reaches state.json
break
# WS3: intake new bridge messages EARLY — before the heavy steps
# (enforce_task_timeouts / assign_tasks / evolution) — so a later
# blocking step can never starve new-message intake (the wedge class
# where no task_received fired for hours until a full restart). A drain that stopped
# at its bound only polls: the idle wait would steal its backlog's second.
offset = _process_bridge_updates(bridge, offset, _event_ctx, timeout=0 if backlog else 1)
# The one budget-projection write of this turn (llm_usage events only mark it dirty).
flush_budget_projection(_event_ctx)
_loop_liveness[1], _loop_liveness[0] = loop_phase_facts(_loop_liveness, "maintenance"), time.monotonic()
enforce_due_task_timeouts(lambda: pending_idle_observations(get_event_q()))
_periodic_supervisor_maintenance( # includes the off-loop schedule duty
_last_custody_reap, _last_review_job_reconcile, stop_event=_watchdog_stop,
)
_loop_liveness[1], _loop_liveness[0] = loop_phase_facts(_loop_liveness, "assign"), time.monotonic()
# The requester's finalization starts the drain; its accepted intent
# already holds independent starts. Existing trees still finish.
draining = _check_pending_restart_drain(_event_ctx)
if not draining and not _restart_lifecycle.agent_restart_pending():
try:
from ouroboros.post_task_evolution import apply_pending_request
from supervisor import state as _pte_state
apply_pending_request(_pte_state.DRIVE_ROOT)
except Exception:
log.debug("Post-task evolution apply failed", exc_info=True)
enqueue_evolution_task_if_needed()
if _restart_requested.is_set():
break # restart just triggered (drain done) — exit without assigning new work (bridge intake already ran early this iteration)
assign_tasks()
if publish_queue_changes() is False: # captured here, written by the publisher thread; None: a saved queue kept as it is
raise RuntimeError("queue publication failed")
if _consciousness is not None and not draining and not _restart_lifecycle.agent_restart_pending():
try:
_consciousness.tick(time.time())
except Exception:
log.warning("Consciousness alarm tick failed", exc_info=True)
crash_count = 0
publish_supervisor_load(get_event_q(), DATA_DIR) # one row a minute, never under Q; never raises
if not backlog:
time.sleep(0.5) # a turn that hit its events bound drains the backlog at full speed
except Exception as exc:
if _supervisor_stop.is_set() or _restart_requested.is_set() or _exit_signalled.is_set() or panic_termination_requested():
# A shutdown-torn Manager proxy is not a supervisor crash; nor is the bus Panic itself killed.
log.info("Supervisor loop exiting on shutdown: %s", exc)
break
# Two causes, one door (end_generation_on_fault): the core is lost (the bus fact, confirmed for a proxy error too; no retries) or the third consecutive failure on a live bus.
bus_exitcode = exc.exitcode if isinstance(exc, EventBusLost) else event_bus_exitcode()
if bus_exitcode is not None:
_supervisor_ready.clear()
end_generation_on_fault(FAULT_BUS_LOST, exitcode=bus_exitcode, error=exc)
break
crash_count += 1
log.error("Supervisor loop crash #%d: %s", crash_count, exc, exc_info=True)
if crash_count >= 3:
_supervisor_ready.clear()
end_generation_on_fault(FAULT_LOOP_FAILED, error=exc)
break
# Backoff on the stop event, not time.sleep, so a shutdown is prompt.
_supervisor_stop.wait(min(30, 2 ** crash_count))
_watchdog_stop.set() # every ordinary exit (restart, shutdown, crash death) stops this generation's watchdog
stop_queue_writer() # ...and its queue writer: the doors after the loop publish synchronously where they stand
_supervisor_thread = None
# Deferred restart-drain state (multi-project, v6.32.0). The drain MUST NOT
# sleep on the supervisor loop thread (it is the only thread that processes
# heartbeats / task_done and shrinks RUNNING). Instead a restart with live
# tasks is recorded here and re-checked every loop tick, so events keep
# flowing and the drain actually observes tasks finishing.
_pending_restart: Dict[str, Any] = {}
def _handle_restart_in_supervisor(evt: Dict[str, Any], ctx: Any) -> None:
return _restart_lifecycle._handle_restart_in_supervisor(sys.modules[__name__], evt, ctx)
def _check_pending_restart_drain(ctx: Any) -> bool:
return _restart_lifecycle._check_pending_restart_drain(sys.modules[__name__], ctx)
def _perform_supervisor_restart(ctx: Any, *, restart_reason="agent_restart_request", evolution_restart=False) -> None:
return _restart_lifecycle._perform_supervisor_restart(
sys.modules[__name__], ctx, restart_reason=restart_reason, evolution_restart=evolution_restart)
def _wait_for_supervisor_update_finalize() -> bool:
"""Wait for a real init outcome; slow dependency sync is not a failed boot."""
_supervisor_init_done.wait()
return not bool(_supervisor_error)
def _boot_managed_update_tasks() -> None:
"""Finalize a pending update, restart after rollback, then refresh its feed."""
try:
from ouroboros.gateway.update_progress import observe_boot
from supervisor.git_ops import advance_recovery_point, compute_managed_update_status
from supervisor.update_merge import active_update_tx, finalize_managed_update_on_boot
ready = _wait_for_supervisor_update_finalize()
# Observation only: the finalizer's result and every decision below stay its own.
result = observe_boot(finalize_managed_update_on_boot, ready=ready, bootstrap_ok=_bootstrap_ok is True)
# A failed bootstrap (dependency sync or the import test of this tree) is not a
# ready generation even when the supervisor thread survived it: the adoption
# of a tree that does not import is returned, not finalized.
body_adoption.settle_on_boot(DATA_DIR, REPO_DIR, supervisor_ready=ready and _bootstrap_ok is True)
stash_note = str(result.get("stash_note") or "")
if stash_note:
# Q1=C disclosure contract: a stash restore that conflicted keeps the
# entry and the OWNER must see the exact recovery command, not only
# the supervisor log.
try:
from supervisor.message_bus import send_with_budget
from supervisor.state import load_state as _load_state
owner_chat = int((_load_state() or {}).get("owner_chat_id") or 0)
if owner_chat:
send_with_budget(owner_chat, f"📦 Managed update: {stash_note}", role="system", system_type="managed_update_notice")
except Exception:
log.debug("stash note owner notification failed", exc_info=True)
if result.get("rolled_back") is True and active_update_tx():
# Completed restore custody survives re-exec; the restored generation
# clears it without another checkout or restart.
from supervisor.workers import close_repo_writer_admission
close_repo_writer_admission("managed_update:rollback_restart")
_request_restart_exit()
return
advance_recovery_point(ready and _bootstrap_ok is True and result.get("rolled_back") is not True)
update_status = compute_managed_update_status(fetch=True)
try:
from ouroboros.update_letter import refresh_after_check, runtime_status
refresh_after_check(runtime_status(update_status))
except Exception:
log.debug("boot update letter refresh failed", exc_info=True)
broadcast_ws_sync({
"type": "update_status_ready",
"available": bool(update_status.get("available")),
"check_ok": update_status.get("check_ok"),
})
except Exception:
log.debug("boot managed-update tasks failed", exc_info=True)
def _execute_panic_stop(consciousness, kill_workers_fn) -> None:
_execute_panic_stop_impl(
consciousness,
kill_workers_fn,
data_dir=DATA_DIR,
panic_exit_code=PANIC_EXIT_CODE,
log=log,
)
def _startup_owner_command(command: str, *, send_kwargs=None, source="web", user_id=0, chat_id=0, reply=None):
"""Bind the emergency owner directly; startup Restart retains normal routing."""
verb = str(command).strip().lower()
if verb not in {"/panic", "/restart"}:
return None
from supervisor.message_bus import try_get_bridge