-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheidos.py
More file actions
3719 lines (3460 loc) · 211 KB
/
Copy patheidos.py
File metadata and controls
3719 lines (3460 loc) · 211 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
"""eiDOS — the always-on autonomous agent.
Entry point: crash recovery, tick loop, signal handling.
"""
import argparse
import collections
import hashlib
import json
import logging
import os
import re
import signal
import subprocess
import sys
import time
import types
from pathlib import Path
from config import Config, load_config
from atomicio import replace_with_retry
from context import assemble_context, _norm_cmd
from compaction import should_compact, compact_briefing, emit_flavor
from llm import complete, LLMError, ReasoningExhausted
from gpu_gate import yield_to_speech, control_wait
from memory import (
append_observation,
append_thought,
has_junk_run,
is_degenerate,
log_degeneration,
read_goal,
validate_observations,
write_plan,
)
from parser import parse_tool_call, parse_reply
from persona import (
load_persona,
save_persona,
record_tick,
record_compaction,
record_error_recovery,
compute_traits,
check_titles,
format_prefix,
format_status_line,
)
from rotation import rotate_if_needed, cleanup_old_archives, rotate_llm_log, rotate_metrics, rotate_thoughts, cleanup_old_snapshots
from safety import check_ram, check_disk_space
from telemetry import write_heartbeat, append_metrics, write_activity, get_cpu_pct, record_goal_horizon
from tools import execute_tool, refresh_jobs, collect_finished_jobs, reap_jobs, _BUILTIN_TOOL_NAMES
logger = logging.getLogger("eidos")
# --- Globals for signal handling ---
_shutdown_requested = False
def _handle_signal(signum, frame):
global _shutdown_requested
_shutdown_requested = True
def main():
parser = argparse.ArgumentParser(description="eiDOS autonomous supervisor")
parser.add_argument("--config", default="config.toml", help="Path to config file")
parser.add_argument("--llm-url", default=None, help="Override LLM endpoint URL")
args = parser.parse_args()
config = load_config(args.config)
if args.llm_url:
config.llm_url = args.llm_url
# eidos runs as LocalSystem (child of the EidosDashboard service, which doesn't export
# PI_CODING_AGENT_DIR). delegate.py already sets it per-spawn, but make it process-wide so
# ANY pi eidos ever spawns resolves the user's config (the `house` provider + subagents
# extension). setdefault: a real service-env value, if ever added, still wins. Derived from the
# user's home so it's correct on any machine; only set when that dir actually exists (pi is an
# optional feature — a friend without it just doesn't get delegate, no broken env).
_pi_agent_dir = Path.home() / ".pi" / "agent"
if _pi_agent_dir.is_dir():
os.environ.setdefault("PI_CODING_AGENT_DIR", str(_pi_agent_dir))
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(name)s %(levelname)s %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
# Ensure workspace exists
config.workspace.mkdir(parents=True, exist_ok=True)
config.interventions_dir.mkdir(parents=True, exist_ok=True)
config.snapshots_dir.mkdir(parents=True, exist_ok=True)
config.outputs_dir.mkdir(parents=True, exist_ok=True)
# Hot-load any skills eiDOS has previously authored
try:
from skills import load_active_skills
loaded = load_active_skills(config)
if loaded:
print(f"[skills] loaded {len(loaded)}: {', '.join(loaded)}")
except Exception as e: # noqa: BLE001
print(f"[skills] load failed: {e}")
# Reap any background jobs orphaned by the previous run (bg_run/async detach into their own
# process group, so they survive a kill of eidos and would otherwise run forever).
try:
n = reap_jobs(config, kill_all=True)
if n:
print(f"[jobs] reaped {n} orphaned background job(s) from the previous run")
except Exception as e: # noqa: BLE001
print(f"[jobs] reap failed: {e}")
# Signal handling for clean shutdown
signal.signal(signal.SIGTERM, _handle_signal)
signal.signal(signal.SIGINT, _handle_signal)
# Crash recovery
wal = recover(config)
# Load persona
persona = None
if config.persona_enabled:
persona = load_persona(config.workspace)
compute_traits(persona)
pfx = format_prefix(persona)
print(f"{pfx} Online. {format_status_line(persona)}")
# Main loop
run_loop(config, persona, wal=wal)
def _pfx(persona, config):
"""Return persona prefix or fallback."""
if config.persona_enabled and persona:
return format_prefix(persona)
return "[eidos]"
def _write_chat_reply(config: Config, tick_number: int, reply_text: str):
"""Append a chat reply to chat_replies.jsonl. Dedup-aware: if eiDOS also `speak`s this same line
in the tick, the two writes merge into ONE entry (marked spoken) instead of duplicating."""
from memory import append_chat_line
append_chat_line(config, reply_text, spoken=False, tick=tick_number)
def _first_sentences(text: str, max_sentences: int = 2, max_chars: int = 200) -> str:
"""The opening 1-2 sentences of a reply — what we voice. TTS runs ~1.5x slower than realtime here
(Chatterbox's own pipeline; the house model now uses 64k ctx so VRAM isn't the bottleneck), so
speaking a long paragraph would still lag. The spoken opener + readable text body is the right split."""
import re as _re
parts = _re.split(r"(?<=[.!?])\s+", (text or "").strip())
out = ""
for p in parts[:max_sentences]:
if out and len(out) + len(p) > max_chars:
break
out = (out + " " + p).strip()
return out[:max_chars]
def _post_speech(config: Config, text: str) -> bool:
"""POST one utterance to the dashboard's instant-return TTS. Best-effort; True on success."""
if not text:
return False
try:
import urllib.request as _u
port = getattr(config, "voice_port", 8098) # voice is its own service now (phase 8.3)
sid = str(int(time.time() * 1000))
req = _u.Request(f"http://127.0.0.1:{port}/api/speech/say",
data=json.dumps({"id": sid, "text": text}).encode("utf-8"),
headers={"Content-Type": "application/json"}, method="POST")
_u.urlopen(req, timeout=4).read()
return True
except Exception: # noqa: BLE001 - voice is best-effort; never disturb the tick
return False
def _auto_speak(config: Config, text: str) -> None:
"""Voice an outgoing chat reply so Boss HEARS every response — voice is first-class, not opt-in.
We speak only the opening 1-2 sentences; the full text stays readable in chat. Backstop for when
the model replies with text instead of calling `speak`. Phase 3 fires this EARLY via the streaming
pump when possible; this is the post-tick fallback for replies the pump didn't already voice."""
_post_speech(config, _first_sentences(text))
_REPLY_OPEN_RE = re.compile(r"<reply>(.*?)(?:</reply>|$)", re.DOTALL)
class _ReplyVoicePump:
"""Streaming reply→TTS pump (phase 3, BIBLE realtime). Fed the accumulating partial text
during generation; the instant the reply's opening 1-2 sentences are complete it fires ONE
speech POST — overlapping TTS synthesis with the rest of the tick's generation instead of
waiting for the whole response. With reply-first grammar (Boss waiting), the reply is among
the first tokens, so first-audio drops from ~12s to ~2.5s. Idempotent: fires at most once;
records what it spoke so the post-tick _auto_speak doesn't repeat it."""
def __init__(self, config):
self.config = config
self.fired = False
self.spoken_from = "" # the reply text the early POST was derived from
def feed(self, partial_text: str) -> None:
if self.fired or not partial_text:
return
m = _REPLY_OPEN_RE.search(partial_text)
if not m:
return
reply_so_far = m.group(1)
closed = "</reply>" in partial_text
# Fire only when there is something definitively complete to speak: the reply tag
# closed, or a sentence terminator is followed by whitespace (the first sentence
# ended and the next began). Never speak a half-formed fragment.
if not (closed or re.search(r"[.!?]\s", reply_so_far)):
return
if closed:
speakable = reply_so_far
else:
last = max(reply_so_far.rfind("."), reply_so_far.rfind("!"), reply_so_far.rfind("?"))
speakable = reply_so_far[: last + 1]
opener = _first_sentences(speakable)
if opener and _post_speech(self.config, opener):
self.fired = True
self.spoken_from = speakable
def already_spoke(self, final_reply: str) -> bool:
"""True if the pump already voiced this reply's opener — suppress the post-tick speak so
the opener isn't spoken twice. (The pump only ever voices the opener; the full text stays
readable in chat, so 'fired at all' is the right suppression signal.)"""
return self.fired
def _has_pending_interventions(config: Config) -> bool:
"""Check if any un-consumed intervention files exist."""
idir = config.interventions_dir
if not idir.exists():
return False
for p in idir.iterdir():
if not p.name.startswith(".") and p.suffix != ".done":
return True
return False
def _should_open_sleep_window(config: Config, ticks_since_compaction: int, *, forced: bool) -> bool:
"""#47 OPERATOR INTERLOCK. A forced sleep (operator sleep_now / force_nap) always opens. A NATURAL
sleep (should_compact) is DEFERRED for one tick when an operator message is pending — the creature
spends the tick engaging Charlie, not dreaming past him. The deferral is bounded and safe: the
pending message is consumed (renamed .done) during THIS tick's context build, so `should_compact`
fires again next tick with no message in the way, and the token/dry-spell backstop is delayed by
at most one tick — well inside the compaction threshold's headroom."""
if forced:
return True
if not should_compact(config, ticks_since_compaction):
return False
return not _has_pending_interventions(config)
def _chat_hold_active(config: Config) -> bool:
"""Listening hold: True when Dean has the chat box focused (a soft pause distinct from
the operator pause). The dashboard owns the flag file; eiDOS only reads it. Fails OPEN
to autonomy on any anomaly (missing, corrupt, stale, backward clock, ceiling exceeded).
A pending intervention overrides the hold so a sent message is answered immediately.
"""
try:
path = config.chat_hold_path
raw = path.read_text(encoding="utf-8", errors="replace")
import json as _json
d = _json.loads(raw)
if not d.get("held"):
return False
now = time.time()
ts = float(d.get("ts", 0) or 0)
try:
mtime = path.stat().st_mtime
except OSError:
mtime = ts
age = now - max(ts, mtime) # freshest of payload ts / file mtime
if age < 0: # backward clock → treat as stale
return False
if age > float(config.chat_hold_ttl_s):
return False
first = float(d.get("first_held_ts", ts) or ts)
if now - first > float(config.chat_hold_max_continuous_s):
return False # hard ceiling — never pin the loop forever
if _has_pending_interventions(config):
return False # a message is waiting — go answer it
return True
except (FileNotFoundError, ValueError, OSError):
return False
# Control-channel seq cursor (phase 4). -1 = unsynced; the first wait syncs it.
_ctl_cursor = -1
def _control_wait_change(config: Config, max_s: float) -> bool:
"""Block until the dashboard's control state CHANGES (pause/resume/hold/chat) or `max_s`
elapses — the event-driven replacement for the gates' fixed sleeps (ARCH #1). Returns True
if the channel delivered (event or timeout), False if it's down (caller already slept via
the fallback nap inside). The sentinel files remain ground truth; callers re-check them."""
global _ctl_cursor
res = control_wait(config, _ctl_cursor, max_s=min(max_s, 25.0))
if res is None:
time.sleep(min(max_s, 5.0)) # channel down: bounded nap (the old behavior)
return False
seq = res.get("seq", 0)
if seq < _ctl_cursor:
logger.info("control channel reset (dashboard restarted) — resyncing")
_ctl_cursor = seq
return True
def _interruptible_sleep(config: Config, interval: float = None):
"""Sleep up to `interval` (default tick_interval_s), waking EARLY on shutdown, a new Boss
message, a listening hold, or a pause — via ONE server-side event wait on the dashboard's
control channel (ARCH #1: notify, not nap-polls). Falls back to the bounded nap-poll when
the channel is down, so the loop never depends on the dashboard to keep ticking."""
global _ctl_cursor
target = config.tick_interval_s if interval is None else float(interval)
if target <= 0:
time.sleep(0) # zero-interval (fast cadence): yield the GIL once; keep ONE time.sleep
return # call so this stays a cooperative throttle point (and a test seam)
deadline = time.monotonic() + target
while not _shutdown_requested:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
res = control_wait(config, _ctl_cursor, max_s=min(remaining, 25.0))
if res is None:
# Channel down — the old nap-poll, bounded; re-check files like v1 did.
time.sleep(min(2.0, max(0.1, remaining)))
if _shutdown_requested:
break
if _has_pending_interventions(config):
logger.info("Early wake: pending intervention detected")
break
if _chat_hold_active(config):
break # reach the listening gate promptly
continue
_ctl_cursor = res.get("seq", _ctl_cursor)
# The snapshot rode back with the event — no extra file reads on the happy path.
if res.get("interventions"):
logger.info("Early wake: pending intervention (event)")
break
if res.get("held") and _chat_hold_active(config): # validate TTL/ceiling rules
break # reach the listening gate promptly
if res.get("paused"):
break # reach the pause gate promptly
# else: long-poll timeout or an already-cleared change — keep waiting out the interval
def _adaptive_tick_interval(config: Config, tick_tool_name: str) -> float:
"""Fast cadence when there's MOMENTUM (a real action was just taken, or background jobs are
still running → results are coming), idle cadence otherwise. A flat sleep throttles an actively
working agent and wastes cycles when idle; this reacts to work, not a metronome."""
active = bool(tick_tool_name) and tick_tool_name not in ("thought", "__no_tool__")
if not active:
try:
from tools import _read_jobs
active = any(j.get("status") == "running" for j in _read_jobs(config))
except Exception: # noqa: BLE001
pass
return float(getattr(config, "tick_interval_active_s", 0.4)) if active else float(config.tick_interval_s)
def _count_skills(config: Config) -> int:
"""Count authored skill files (for the goal-tension progress signal — a new skill = progress)."""
try:
return len([p for p in (config.workspace / "skills").glob("*.py")])
except Exception: # noqa: BLE001
return 0
def _consume_sleep_now(config: Config) -> bool:
"""Operator-forced sleep: True (once) if the dashboard dropped the `eidos.sleep_now` sentinel.
Consume-and-delete so a single request fires exactly one forced consolidation. Best-effort."""
try:
p = config.workspace / "eidos.sleep_now"
if p.exists():
p.unlink()
return True
except Exception: # noqa: BLE001
pass
return False
def _consume_force_nap(config: Config) -> bool:
"""Operator dev fast-forward: True (once) if the dashboard dropped the `eidos.force_nap`
sentinel. Distinct from `sleep_now` — this asks the loop to RAISE the live adenosine to the nap
threshold before the window, so the forced consolidation classifies as a real NAP (advancing the
maturation counters), not a dream. Consume-and-delete; best-effort."""
try:
p = config.workspace / "eidos.force_nap"
if p.exists():
p.unlink()
return True
except Exception: # noqa: BLE001
pass
return False
def _count_artifacts(config: Config) -> int:
"""Count durable files the creature has authored in its own writable home — the cheap harness fact
that makes 'organize the workspace' REGISTER as progress. Before this, progress was blind to
everything but knowledge/skill counts, so an objective like "organize the cocoon" could never
settle: every file it created was invisible, so every tick on it was a stall, frustration ratcheted
to park, and it died un-closed (2026-07-13 run: 0/4 objectives closed, frustration pinned at 8). A
NEW file appearing is real external change — it counts. Rewriting an existing file does not raise
the count, so it is not a progress-farming lever. Bounded, best-effort, never raises."""
try:
import tools as _tools
root = _tools._creature_root(config)
if not root.exists():
return 0
n = 0
for p in root.rglob("*"):
if p.is_file():
n += 1
if n >= 100000: # sanity ceiling — never walk unbounded
break
return n
except Exception: # noqa: BLE001
return 0
def write_wal(config: Config, tick_number: int, ticks_since_compaction: int,
goal_start_time: float, consecutive_failures: int = 0,
reasoning_exhaustions: int = 0, current_max_tokens: int = 0,
last_progress_tick: int = 0):
"""Atomically write tick state to WAL for crash recovery."""
wal = {
"tick_number": tick_number,
"ticks_since_compaction": ticks_since_compaction,
"goal_start_time": goal_start_time,
"consecutive_failures": consecutive_failures,
"reasoning_exhaustions": reasoning_exhaustions,
"current_max_tokens": current_max_tokens,
"last_progress_tick": last_progress_tick,
"ts": time.time(),
}
tmp = config.wal_path.with_suffix(".tmp")
tmp.write_text(json.dumps(wal))
replace_with_retry(tmp, config.wal_path)
def read_wal(config: Config) -> dict:
"""Read WAL state, return empty dict on missing/corrupt."""
try:
return json.loads(config.wal_path.read_text())
except (FileNotFoundError, json.JSONDecodeError, OSError):
return {}
def clear_wal(config: Config):
"""Remove WAL after clean shutdown."""
try:
config.wal_path.unlink()
except FileNotFoundError:
pass
def recover(config: Config) -> dict:
"""Crash recovery: validate state, fix corruption, log restart.
Returns WAL state dict (may be empty on fresh start).
"""
print("[eidos] Running crash recovery...")
# 0. Read WAL (tick state from before crash)
wal = read_wal(config)
if wal:
print(f"[eidos] WAL recovered: tick={wal.get('tick_number')}, "
f"compaction_gap={wal.get('ticks_since_compaction')}")
# 1. Verify goal.md
goal = read_goal(config)
if not goal:
print("[eidos] WARNING: No goal.md found. Agent will idle until one is created.")
# 2. Create plan.md (working memory) if missing, or restore from snapshot if empty
plan_missing = not config.plan_path.exists()
plan_empty = False
if not plan_missing:
try:
plan_empty = config.plan_path.stat().st_size == 0
except OSError:
plan_empty = True
if plan_missing or plan_empty:
# Try restoring from most recent dream snapshot (either filename generation)
restored = False
if config.snapshots_dir.exists():
snapshots = sorted(
list(config.snapshots_dir.glob("plan_snapshot_*"))
+ list(config.snapshots_dir.glob("memory_snapshot_*")),
key=lambda p: p.stat().st_mtime,
reverse=True,
)
if snapshots:
try:
content = snapshots[0].read_text()
if content.strip():
write_plan(config, content)
restored = True
print(f"[eidos] Restored plan.md from snapshot: {snapshots[0].name}")
append_observation(config, {
"tick": 0,
"tool": "system",
"success": True,
"output": f"Restored plan from snapshot {snapshots[0].name} after {'missing' if plan_missing else 'empty'} plan.md.",
})
except OSError:
pass
if not restored:
write_plan(config, "# Plan\nFresh start. No prior context.")
print("[eidos] Created initial plan.md")
# 3. Validate observations.jsonl
truncated = validate_observations(config)
if truncated:
print(f"[eidos] Truncated {truncated} malformed line(s) from observations.jsonl")
append_observation(config, {
"tick": 0,
"tool": "system",
"success": False,
"output": (f"Crash recovery: {truncated} corrupted observation(s) "
f"removed from observations.jsonl. Recent history may be incomplete."),
})
# 4. Scan background jobs, mark dead ones
jobs = refresh_jobs(config)
dead = [j for j in jobs if j["status"] != "running"]
if dead:
print(f"[eidos] Found {len(dead)} completed/dead background jobs")
dead_names = ", ".join(j.get("cmd", "?")[:60] for j in dead)
append_observation(config, {
"tick": 0,
"tool": "system",
"success": False,
"output": (f"Background jobs died during downtime: {dead_names}. "
f"Their results are unavailable. Re-launch if still needed."),
})
# 5. Log the restart with pre-restart state — honestly attributed (principle #4).
# recover() runs on EVERY boot: an operator/tooling restart (dashboard Start, self-edit apply,
# git restore, rollback) AND a genuine crash-respawn. It is NOT the crash-narrator — only the
# watchdog knows a death was unexpected, and it writes that note itself just before respawn. So
# recover() reports the RESUME and, when the pausefile names an operator/tooling cause, attributes
# it; it never calls an operator-initiated restart a "crash". The pausefile is normally cleared on
# operator GO/resume, but it can OUTLIVE its restart if the operator never resumes and the creature
# then crashes — the freshness check below rejects such a stale survivor. Only the restart-causing
# operator actions prefix it "paused:" / "paused on start"; a bare "paused by operator" means a
# RUNNING creature was paused, so a boot that sees it is a crash-while-paused, not a restart the
# operator asked for.
pause_reason = ""
try:
_pf = config.workspace / "paused"
if _pf.exists():
# A "paused: <op-action>" file can OUTLIVE the restart that wrote it: the operator applies
# a self-edit, never clicks GO, and the creature later crashes while paused-for-review.
# Attributing THAT crash to the operator would be a fresh lie — so trust the operator
# attribution only when the pausefile is roughly contemporaneous with THIS boot's spawn
# (it is written moments before the process is (re)spawned). A file that predates this
# boot's eidos_spawn.ts by more than a boot's worth of slack is a stale survivor → a crash.
fresh = True
try:
_spawn_ts = float((config.workspace / "eidos_spawn.ts").read_text().strip() or 0)
if _spawn_ts > 0 and (_spawn_ts - _pf.stat().st_mtime) > 90:
fresh = False
except (OSError, ValueError):
pass
if fresh:
pause_reason = _pf.read_text(encoding="utf-8", errors="replace").strip()
except OSError:
pass
operator_restart = pause_reason.startswith("paused:") or pause_reason.startswith("paused on start")
if wal:
if operator_restart:
cause = f"Restarted by operator/tooling ({pause_reason})."
else:
cause = "Resumed after an unexpected restart (the watchdog note above, if any, has the cause)."
recovery_detail = (
f"{cause} Resuming at tick {wal.get('tick_number', '?')}. "
f"State before the restart: {wal.get('consecutive_failures', 0)} consecutive LLM failures, "
f"{wal.get('reasoning_exhaustions', 0)} reasoning exhaustions, "
f"max_tokens was {wal.get('current_max_tokens', config.llm_max_tokens)}. "
f"Review recent observations — the last action may not have completed."
)
else:
# No WAL: a true fresh birth OR a CLEAN-shutdown restart (clean shutdown clears the WAL). Do
# not say "no prior state" — an established creature that was cleanly restarted keeps all its
# memory, level, and history; only the in-flight tick-loop state is absent. Speak to the
# session, not the life (principle #4).
recovery_detail = "eiDOS starting a fresh session — no in-flight tick state to resume."
append_observation(config, {
"tick": 0,
"tool": "system",
"success": True,
"output": recovery_detail,
})
# 6. Rotate logs and clean old archives
if rotate_if_needed(config):
print("[eidos] Rotated observations.jsonl")
deleted = cleanup_old_archives(config)
if deleted:
print(f"[eidos] Cleaned {deleted} old archive(s)")
# 7. Birth-preflight SOFT re-check (HABITAT_PLAN.md §WS1): the same limb sweep
# scripts/fresh_slate.sh runs as a HARD gate before a wipe, re-run here as an honest,
# never-blocking observation — a creature whose delegate/embedder/manual died SINCE its last
# hatch is TOLD, not left to discover it the hard way mid-life (Gen 2's looping delegate,
# Gen 3's dead embedder). Skips the delegate live-fire (default) and mock_mode entirely — a
# real network round-trip on every restart is not what a soft boot-time check is for; the
# delegate's own liveness still surfaces the normal way, a typed fail_kind on first real use.
if not config.mock_mode and not os.environ.get("EIDOS_NO_DASHBOARD"):
try:
import preflight as _preflight
_pf_msg = _preflight.run_soft_recheck(config)
if _pf_msg:
print(f"[eidos] {_pf_msg}")
append_observation(config, {
"tick": 0,
"tool": "system",
"success": False,
"output": _pf_msg,
})
except Exception as _pf_e: # noqa: BLE001 - a preflight fault must never block boot
logger.warning("preflight soft recheck failed: %s", _pf_e)
return wal
# Arg keys that carry a CONTENT PAYLOAD rather than identify the action's target. Stripped before the
# tick's action label is truncated, so the identifying args (path/cmd/name) survive into the label the
# reward learner derives shape+target from. See the truncation comment at the label build site.
_LABEL_BULK_KEYS = frozenset({"content", "text", "body", "data", "output", "value", "answer", "code"})
_THOUGHT_TAG_RE = re.compile(r"<tool>.*?</tool>|<args>.*?</args>|<reply>.*?</reply>",
re.DOTALL | re.IGNORECASE)
_LEADING_ELLIPSIS_RE = re.compile(r"^\s*(?:\.{2,}|…)\s*")
def _extract_thought(response: str) -> str:
"""This tick's reasoning — the model's raw output minus the action/reply tags."""
if not response:
return ""
thought = _THOUGHT_TAG_RE.sub("", response).strip()
# The 'continuous stream / mid-thought' framing makes the model open nearly EVERY thought with a
# leading ellipsis (its "I'm continuing the stream" marker) — 100% of thoughts, incl. the very
# first. A thought is a thought, not a perpetual mid-sentence; strip the artifact. (The tick-prompt
# framing that induces it is also softened, so this is a backstop, not the only fix.)
return _LEADING_ELLIPSIS_RE.sub("", thought)
# A newborn should THINK like a newborn — a fragment, not a treatise. But the stored thought is what
# the creature re-reads as its own recent voice (the history thread) and what thoughts.jsonl / the
# dashboard show, so a young creature that writes a 70-word essay then marinates in a dozen of its own
# essays next tick locks into an over-elaborate register (self-imitation). We clamp the STORED thought
# by life-stage — the young remember a fragment; depth (length) is EARNED, so adult/guardian are never
# clamped. This runs AFTER parse_tool_call has read the FULL response, so it NEVER truncates an action;
# it only shortens the memory, which is what starves the self-imitation loop. (Register — word choice —
# is shaped elsewhere: the stage tone-cue, the flatter base prompt, and the no-projects gate.)
_STAGE_THOUGHT_MAX_SENTENCES = {"egg": 2, "hatchling": 2, "juvenile": 3} # adult/guardian: unclamped
_STAGE_THOUGHT_MAX_WORDS = {"egg": 22, "hatchling": 22, "juvenile": 55}
_SENTENCE_SPLIT_RE = re.compile(r'(?<=[.!?…])\s+')
def _clamp_thought_for_stage(thought: str, stage: str) -> str:
"""Trim a stored thought to a life-stage-appropriate length — whole sentences first (never a
mid-word cut), then a hard word backstop for a single run-on. Young stages only; a mature creature
keeps the full thought it has earned. Fail-open: unknown stage or empty text → returned unchanged."""
if not thought or stage not in _STAGE_THOUGHT_MAX_WORDS:
return thought
parts = _SENTENCE_SPLIT_RE.split(thought.strip())
clipped = " ".join(parts[:_STAGE_THOUGHT_MAX_SENTENCES[stage]]).strip()
words = clipped.split()
cap = _STAGE_THOUGHT_MAX_WORDS[stage]
if len(words) > cap:
clipped = " ".join(words[:cap]).rstrip(",;:—- ") + "…"
return clipped or thought
# --- Phase 1.1: per-tick hooks for the 2 drive organs migrated onto the organ registry
# (goal-tension, curiosity). Each is a pure f(ctx) closure over the tick's locals, which the loop
# packs into `ctx` (a SimpleNamespace) and hands to `organ_registry.run_post_tick(ctx)`. The
# bodies are lifted VERBATIM from the old inline call sites — same inputs, same effects, same bus
# events — so this is a strictly behaviour-preserving change of *dispatch*, not of behaviour. Each
# is guarded by the registry (I5), so its logging matches the old per-organ try/except. ---
def _goaltension_post_tick(ctx):
"""Goal-tension drive (Ventral Striatum): fold this tick's objective state into the incompletion/
regret pressure. Lifted from the old inline block: an OPEN objective with no progress charges the
tension (a frustrated one harder); progress discharges it; past threshold it raises a bounded
arousal floor. Initiative temperament scales how hard it bites."""
_active = ctx.gate.get("active")
_open = bool(_active)
_frac = (float(_active.get("frustration", 0)) / max(1, (ctx.park_at or ctx.obj.FRUST_PARK))
if _active else 0.0)
_init = ctx.temperament.initiative if ctx.temperament is not None else 0.5
ctx.goaltension.observe(made_progress=ctx.made_progress, open_objective=_open,
frustration_frac=_frac, initiative=_init,
open_commission=bool(getattr(ctx, "commission_open", False)))
def _curiosity_post_tick(ctx):
"""Curiosity drive: turn the world-model's LEARNING PROGRESS at this transition into a small
intrinsic-reward bonus + restlessness. Lifted from the old inline block inside the reward-learner
step: observe the (prev_sit, prev_act -> this_sit) transition, read last_progress, fold it into
curiosity. The intrinsic bonus is written back onto ctx for the (non-migrated) learner to consume
this same tick — so the value still flows exactly as before."""
if ctx.worldmodel is not None and ctx.wm_prev_sit is not None:
ctx.worldmodel.observe(ctx.wm_prev_sit, ctx.wm_prev_act, ctx.tick_situation)
_progress = float(getattr(ctx.worldmodel, "last_progress", 0.0) or 0.0)
ctx.intrinsic = ctx.curiosity.observe(_progress)
# ================================================================================================
# Pillars 5.5 — the wiring pass: every dark organ's call sites, STILL DARK (PILLARS_TODO 5.5).
#
# The hub below is constructed ONLY when at least one pillars flag is on; with every flag off (the
# default) run_loop keeps `pillars = None`, the tick body's new branches are all `if pillars is not
# None`, and NO pillars module is even imported — the flags-off loop is byte-identical to the
# unwired code. Every method is guarded per subsystem (I5): one organ's exception is logged and
# swallowed, never breaking the tick. Flipping flags one at a time (the 5.5 schedule) is what
# actually brings each organ online; this class only provides the call sites.
#
# Registry note (1.1): run_pre_tick is invoked here (behind the salience flag — the gate is its
# only registrant, so single execution is preserved); run_on_sleep runs inside the sleep engine's
# OrganSleepHooksJob (behind the sleep flag). run_post_tick is invoked in the tick body (the
# deferred seam, closed): the old inline goal-tension/curiosity blocks are retired and the
# registry's hooks are the ONE dispatch — the loop packs their inputs into a per-tick ctx and
# curiosity's intrinsic bonus rides that ctx to the (non-migrated) reward learner.
# ================================================================================================
_PILLARS_WIRED_FLAGS = (
"pillars_memory_engram_enabled", # 2.1 engram economy (consolidator for the sleep jobs)
"pillars_memory_manager_enabled", # 2.2 importer + 4-layer recall + encode-through-manager
"pillars_bet_ledger_enabled", # 2.3 open_bets on recall injection + glue.settle_bets
"pillars_sleep_engine_enabled", # 2.4 run_sleep at the sleep window + adenosine accounting
"pillars_expectations_enabled", # 4.1 predict tool + glue.settle_predictions + awaiting block
"pillars_salience_gate_enabled", # 1.3 gate organ registered + relevance_set published
"pillars_quests_enabled", # 5.1 quest window + event-driven cadence + adjudication
"pillars_news_enabled", # 4.4 three-source ingest + presence-gated surfacing
"pillars_mastery_gates_enabled", # 4.3 tier outcomes + level candidacy through the gate
"pillars_learning_xp_enabled", # 4.2 progress tracker fed from adjudicated wrongness
"pillars_administrator_enabled", # 5.2 event-driven check-ins (lazy llm; never on a timer)
"pillars_tool_unlocks_enabled", # 5.x TOOL_PROGRESSION ladder: unit grants at the quest
# seams, milestone adjudication + I8 probe, the felt
# moment, stage-expressed alleles + phenotype artifact
"pillars_commission_enabled", # COMMISSION_PLAN.md: standing orders — verbs registered,
# verdicts/claims settled at the after_outcome beat
"operator_directives_enabled", # OPERATOR_DIRECTIVES: the System frames Charlie's command
# as a priority objective (needs the hub for _live_llm)
"reminders_enabled", # the `remind` primitive: tool registration + per-tick
# due-check both live behind the hub construction
)
def _pillars_any_enabled(config) -> bool:
"""True iff any wired pillars flag is on. False (the default) keeps the hub un-constructed —
the flags-off ground state adds zero work and zero imports to the tick."""
return any(getattr(config, f, False) for f in _PILLARS_WIRED_FLAGS)
# --- TOOL_PROGRESSION I8: the organ-reachability probe (decision #1) -----------------------------
# A granted limb that 500s is a felt lie: a service-gated unit (sight, voice) holds PENDING until
# the organ actually answers. The probe is a bounded HTTP round-trip, memoized per process so
# per-tick adjudication never hammers a dead port (voice :8098 is down on Sprinter today — the
# hold is the expected steady state there). Tests inject their own probe through the hub's
# `unlock_probe` seam.
_UNLOCK_PROBE_TIMEOUT_S = 1.0 # declared: the reachability check costs the adjudicator at most
# ~1s per TTL window — bounded, never a stalled tick
_UNLOCK_PROBE_TTL_S = 60.0 # declared: memoize the answer ~60s; a just-started organ lands
# its held grant within a minute, a dead one costs ~1s/minute
_unlock_probe_cache: dict = {} # service -> (monotonic_ts, answered)
def _probe_service(config, service: str) -> bool:
"""Does the named organ actually answer (I8)? `voice` = an HTTP round-trip to the voice
service (config.voice_port, default 8098). `vision` = an HTTP round-trip to the SERVED MIND
(config.llm_url, default :8080) — the exact endpoint tool_vision calls through llm.complete
(WSA4 2026-07-24: sight no longer depends on the voice service; it depends on the mind being
up, so it is probed there instead). ANY HTTP status counts as an answer — a 404 is still a
live socket — while refusal/timeout is silence. Unknown service names never answer (an organ
is never guessed back). Never raises."""
now = time.monotonic()
hit = _unlock_probe_cache.get(service)
if hit is not None and (now - hit[0]) < _UNLOCK_PROBE_TTL_S:
return bool(hit[1])
answered = False
if service == "voice":
try:
import urllib.error
import urllib.request
port = int(getattr(config, "voice_port", 8098) or 8098)
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/",
timeout=_UNLOCK_PROBE_TIMEOUT_S):
answered = True
except urllib.error.HTTPError:
answered = True # an HTTP error IS an answer — the organ is alive
except Exception: # noqa: BLE001 - refused / timed out / unreachable: no answer
answered = False
except Exception: # noqa: BLE001 - probing must never wound the adjudicator
answered = False
elif service == "vision":
try:
import urllib.error
import urllib.request
base = str(getattr(config, "llm_url", "") or "").rstrip("/")
for _suf in ("/v1/chat/completions", "/chat/completions", "/v1"):
if base.endswith(_suf):
base = base[: -len(_suf)].rstrip("/")
break
url = base + "/v1/models"
try:
with urllib.request.urlopen(url, timeout=_UNLOCK_PROBE_TIMEOUT_S):
answered = True
except urllib.error.HTTPError:
answered = True # an HTTP error IS an answer — the served mind is alive
except Exception: # noqa: BLE001 - refused / timed out / unreachable: no answer
answered = False
except Exception: # noqa: BLE001 - probing must never wound the adjudicator
answered = False
_unlock_probe_cache[service] = (now, answered)
return answered
class _Pillars:
"""The Pillars 5.5 wiring hub: owns the flag-on subsystem instances and exposes the loop's
call sites (pre_tick / recall_block / open_bets / after_outcome / sleep_window / on_presence).
Each subsystem is built and driven ONLY behind its own flag; each call is guarded (I5)."""
def __init__(self, config, *, bus=None, neuromod=None, organ_registry=None,
curiosity=None, learner=None):
self.config = config
self.bus = bus
self.neuromod = neuromod
self.organ_registry = organ_registry
self.curiosity = curiosity
self.learner = learner
self.temperament = None # DMN Temperament — set by run_loop after construction so the
# sleep calibration job can apply its bounded caution step
self.metabolism = None # Metabolism — set by run_loop so a confirmed commission task
# can feed the reserve (work earns food)
self.manager = None # 2.2 MemoryManager
self.bets = None # 2.3 BetLedger
self.news = None # 4.4 NewsQueue
self.quests = None # 5.1 quests.System
self.tracker = None # 4.2 ProgressTracker
self.salience = None # 1.3 SalienceGate
self.llm = None # lazy (messages, grammar=None, temperature=None) -> str; TEST
# SEAM: inject a mock here — it is never constructed in mock
# mode, so tests can never reach a live model by accident.
# `temperature` (WS6, HABITAT_PLAN) lets a distiller retry ONCE
# at a lower temperature after distill_guard rejects a
# degenerate first attempt (strategy.py's grammar bounds FORM;
# a lower-temperature retry is the mitigation for QUALITY).
self.injected = [] # engrams this tick's recall injected (the bet slate, 2.3)
self._persona = None # the live persona dict, refreshed each after_outcome
self._level_snapshot = None # 4.3: the gate-authoritative level (only apply_level_up moves it)
self._candidacy_fired_for = None # 5.2: level_candidacy is EDGE-triggered — once per level
# crossing, not every tick past the floor (18 proposal
# bricks/hour came from the level-triggered flood)
self.unlock_probe = None # I8 TEST SEAM: inject a callable(service)->bool; None = the
# process-memoized voice probe (_probe_service)
self._stage_seen = None # stage-transition memo: skip the genome read while the
# derived stage hasn't moved (ground truth stays the genome)
self._unlock_books_checked = False # load-or-birth migration runs once per process
self._aden_mark = time.monotonic() # wake-time accounting anchor for adenosine (2.4)
self._last_anomaly_sig = "" # 4.4 anomaly source de-dup (report by exception, once per streak)
c = config
# 2.2 — the memory manager (+ the idempotent importer, run once at boot; read-only on legacy)
if getattr(c, "pillars_memory_manager_enabled", False):
try:
from memory_manager import MemoryManager
self.manager = MemoryManager(c, neuromod=neuromod)
counts = self.manager.import_all()
if any(counts.values()):
logger.info("pillars memory import: %s", counts)
except Exception as e: # noqa: BLE001 - one organ's fault never blocks the others (I5)
logger.warning("pillars memory manager init failed: %s", e)
self.manager = None
# 2.3 — the bet ledger (shares the manager's consolidator so strength writes stay single-writer)
if getattr(c, "pillars_bet_ledger_enabled", False):
try:
import bets as _bets
self.bets = (_bets.BetLedger(c, consolidator=self.manager.consolidator)
if self.manager is not None else _bets.BetLedger(c))
except Exception as e: # noqa: BLE001
logger.warning("pillars bet ledger init failed: %s", e)
self.bets = None
# 4.1 — the predict tool joins the registry (register_predict_tool is itself flag-gated)
if getattr(c, "pillars_expectations_enabled", False):
try:
from tools import register_predict_tool
register_predict_tool(c)
except Exception as e: # noqa: BLE001
logger.warning("pillars predict tool registration failed: %s", e)
# WORLD_PLAN §5 (W1) — the `go` movement tool joins the registry (register_world_tool is
# itself flag-gated on `world_enabled`). Flag off (default) → absent from TOOLS, never in
# the grammar; the world stays fully dark (W7). Exception-guarded like every flag organ.
if getattr(c, "world_enabled", False):
try:
from tools import register_world_tool
register_world_tool(c)
except Exception as e: # noqa: BLE001
logger.warning("world go tool registration failed: %s", e)
# OPERATOR_DIRECTIVES — the `remind` tool joins the registry (register_reminders_tool is
# flag-gated on `reminders_enabled`). Flag off (default) → absent, dark.
if getattr(c, "reminders_enabled", False):
try:
from tools import register_reminders_tool
register_reminders_tool(c)
except Exception as e: # noqa: BLE001
logger.warning("remind tool registration failed: %s", e)
# The Commission (COMMISSION_PLAN.md) — the standing-order organ: verbs join the registry
# (register_commission_tools is itself flag-gated) and the engine settles verdicts/claims
# at the after_outcome beat.
self.commission = None
self._commission_open = False # memo for the goal-tension drive (a fact, not a file)
self._commission_claimed_seen: set = set() # claimed-task ids already announced as news
if getattr(c, "pillars_commission_enabled", False):
try:
from tools import register_commission_tools
register_commission_tools(c)
from commission import Commission
self.commission = Commission(c)
live = self.commission.live()
self._commission_open = any(t.state == "open" for t in live)
self._commission_claimed_seen = {t.id for t in live
if t.state == "done_claimed"}
except Exception as e: # noqa: BLE001
logger.warning("pillars commission init failed: %s", e)
self.commission = None
# 1.3 — the salience gate registers with the 1.1 organ registry (pre_tick intake)
if getattr(c, "pillars_salience_gate_enabled", False) and bus is not None:
try:
from nervous.salience import SalienceGate
self.salience = SalienceGate(bus, config=c)
if organ_registry is not None:
self.salience.register(organ_registry)
except Exception as e: # noqa: BLE001
logger.warning("pillars salience gate init failed: %s", e)
self.salience = None
# 4.4 — the news queue (engram writes ride the same single consolidator)
if getattr(c, "pillars_news_enabled", False):
try:
from news import NewsQueue
self.news = (NewsQueue(c, consolidator=self.manager.consolidator)
if self.manager is not None else NewsQueue(c))
except Exception as e: # noqa: BLE001
logger.warning("pillars news queue init failed: %s", e)
self.news = None
# 5.1 — the quest System (reward sink threads config through award_xp — 4.3's gate hold)
if getattr(c, "pillars_quests_enabled", False):
try:
import quests as _quests
self.quests = _quests.System(c, reward_sink=self._quest_reward_sink)
except Exception as e: # noqa: BLE001
logger.warning("pillars quest system init failed: %s", e)
self.quests = None
# 4.2 — the learning-progress tracker
if getattr(c, "pillars_learning_xp_enabled", False):
try:
from learning_progress import ProgressTracker
self.tracker = ProgressTracker(c)
except Exception as e: # noqa: BLE001
logger.warning("pillars progress tracker init failed: %s", e)
self.tracker = None
def describe(self) -> str:
"""One line for the boot print: which organs this hub actually wired."""
parts = []
for name, obj in (("memory", self.manager), ("bets", self.bets), ("news", self.news),
("quests", self.quests), ("progress", self.tracker),
("salience", self.salience)):
if obj is not None:
parts.append(name)
c = self.config
for name, flag in (("sleep", "pillars_sleep_engine_enabled"),
("expectations", "pillars_expectations_enabled"),
("gates", "pillars_mastery_gates_enabled"),
("administrator", "pillars_administrator_enabled"),
("unlocks", "pillars_tool_unlocks_enabled")):
if getattr(c, flag, False):
parts.append(name)