-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcca8_controller.py
More file actions
2003 lines (1654 loc) · 82.7 KB
/
Copy pathcca8_controller.py
File metadata and controls
2003 lines (1654 loc) · 82.7 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
# -*- coding: utf-8 -*-
"""
CCA8 Controller: drives, primitives ("policies"), and action center.
Concepts
--------
- Drives: numeric homeostatic values (hunger, fatigue, warmth) → derive 'drive:*' flags (ephemeral tags that are not written to worldgraph)
- Policy (primitive): behavior object with two parts -- trigger(...) and execute(...)
-parameter 'world' represents the episode state, e.g., already standing? fallen?, cues present?, anchors/latest?
-parameter 'drives' represent internal needs, i.e., homeostatic values (e.g., hunger, fatigue, etc)
-drive tags are derived from numeric levels, e.g., hunger > 0.60 --> "drive:hunger_high"
[note: WorldGraph index layer uses four tag families: pred:*, action:*, cue:*, anchor:*.
drive:* are ephemeral controller flags, not graph tags.
On a real WorldGraph, action nodes carry both "action:*" and legacy "pred:action:*" tags
(for back-compat); edges are generic "then" links that encode weak temporal/causal
succession between bindings.]
[created by Drives.flags() for trigger logic only and are never written to WorldGraph]
[e.g., plannable drive condition, then yes, can create a node with e.g., "pred:drive:hunger_high", or evidence, e.g., cue:drive:hunger_high]
-policies use drive tags in triggering (e.g., SeekNipple needs hunger), while execute may update drives (e.g., Rest reduces fatigue a bit)
-parameter 'ctx' represents runtime context
-includes age_days, sigma and jump (tie-breaking, exploration settings), ticks (i.e., how many autonomic 'heartbeats' have passed), profile (e.g., "goat", "chimp", etc),
winners_k, hal and body (for multi-brain scaffolding and embodiment stub)
-policies don't really require ctx but useful for gating behavior by age/profile, calling into HAL stubs, writing provenance, e.g., ticks, to meta
-trigger(world, drives)
-execute(world, drives, ctx) -- appends small chain of bindings/edges and set provenance to world; adjust internal states to drives; optional gating, embodiment via ctx
-e.g., def trigger (self, world, drives): if _has(world, ...) or drives.fatigue... return False
def execute (self, world, ctx, drives): meta=... ; world.add_predicate("action:look_around"); return self._success(reward, notes, binding)
-if display WorldGraph: b1(NOW) --then--> b2[action:look_around]--then--> b3[state:alert]
-when executed, a policy appends a *small chain* of predicates/edges to the WorldGraph and returns a status dict
-status dict: {"policy": "policy:<name>", "status": "ok|fail|noop|error", "reward": float, "notes": str}.
- Provenance: bindings created by a policy stamp meta.policy = "policy:<name>".
"provenance" means when a primitive/policy fires and creates bindings or links we stamp metadata
eg, "created_by: policy:<name>", timestamp, tag "policy:stand_up", "note: 'standing'"
thus effective means recording origin so later debugging/credit assignment skill ledger,RL is explainable
-state predicates, e.g., state:posture_standing, assert something about the agent or world that reasoner can use as facts
-provenance tags, e.g., policy:stand_up, assert who/what produced this binding/edge rather than something plan for, it already occurred
-despite the same effect predicate being produced there could have been two different policies creating it, provenance tags help figure out which one
- Skill ledger: tiny RL-style counters (n, succ, q, last_reward) per policy; not used for selection yet.
Clarification of Predicates versus other similar looking terms
--------------------------------------------------------------
-only predicates or cues or anchors are written to the WorldGraph, i.e., they live in the bindings (nodes)
-drive:* tags which we now call "flags" to reduce confusion are ephemeral and are not written to the WorldGraph or the binding's records
-it is possible to make a drive:* flag into a predicate or cue to put on the WorldGraph if it was to be used for planning /inspection purposes,
e.g., "pred:drive:*" or "cue:drive:*"
-"state:posture_standing" is shorthand for the token part of the full predicate which is "pred:state:posture_standing", i.e, "pred:state:*"
- we use state:* tokens for relatively stable facts about the agent/world and are ok to persist in the WorldGraph
-"action:run" would normally be stored on the edges as execution provenance; however can turn into a predicate "pred:action:run" for
WorldGraph is want the action as a fact for planning or for inspection
-worldgraph==world stores pred:<token>, where <token> may be state:*, action:*, etc.
-the controller uses ephemeral drive:* flags (never written as pred:*) to decide triggers.
-for compatibility, we sometimes write a legacy alias and the canonical tag on the same binding
(e.g., pred:posture:standing and pred:state:posture_standing) so older tests/tools still work while new code reads the canonical form.
Token quick-ref (canonicalization & usage)
------------------------------------------
Families in the WorldGraph:
• pred:* — facts (assertions the reasoner can use)
• action:* — action nodes (verbs in the navigation map)
• cue:* — observations/engram evidence (non-factual sensory tags)
• anchor:* — structural anchors (NOW, NOW_ORIGIN, etc.)
Canonical tokens (second-level namespaces under pred:*):
• posture:* — body posture facts (e.g., posture:standing, posture:fallen)
• proximity:*— spatial relations (e.g., proximity:mom:close, proximity:mom:far)
• nipple:*, milk:* — feeding milestones (e.g., nipple:latched, milk:drinking)
Canonical tokens (second-level namespaces under action:*):
• <verb> — action semantics / provenance (e.g., push_up, extend_legs, look_around, orient_to_mom)
NOTE:
- On a real WorldGraph, actions are stored as both "action:<verb>" and the legacy
"pred:action:<verb>" on the same binding (for back-compat).
- Edges carry generic "then" relations; actions are nodes, not edge labels.
Controller-only flags (never written as pred:*):
• drive:* — ephemeral homeostatic flags derived from Drives (e.g., drive:hunger_high)
Why constants:
• Single source of truth, IDE autocomplete, fewer typos.
• Easy refactors (rename once; keep legacy in CANON_SYNONYMS for back-compat).
• Clear lexicon surface for docs/tests.
Reading & writing helpers:
• _canon(token) → maps legacy → canonical (e.g., "posture:standing" → "state:posture_standing")
• _add_pred(world, token, ...) → adds pred:<canonical_token> (WorldGraph prefixes 'pred:')
• _has(world, token) → True if pred:<canonical OR legacy> exists (alias-aware)
Back-compat policy (WorldGraph only):
• For selected tokens we tag the SAME binding with both the legacy alias and canonical tag
(e.g., pred:posture:standing + pred:state:posture_standing) so older tools/tests still pass.
Naming rules:
• snake_case, colon-namespaces, no spaces.
• state:* uses noun phrases (state:posture_standing).
• action:* uses verb phrases (action:orient_to_mom).
• Avoid inventing new top-level families; prefer state:* or action:* and document here.
Common tokens (constants → stored token):
• STATE_POSTURE_STANDING → state:posture_standing (legacy: posture:standing)
• STATE_POSTURE_FALLEN → state:posture_fallen (legacy: posture:fallen)
• STATE_RESTING → state:resting
• STATE_ALERT → state:alert
• STATE_SEEKING_MOM → state:seeking_mom (legacy: seeking_mom)
• ACTION_PUSH_UP → action:push_up
• ACTION_EXTEND_LEGS → action:extend_legs
• ACTION_LOOK_AROUND → action:look_around
• ACTION_ORIENT_TO_MOM → action:orient_to_mom
Usage patterns (examples):
• Write a fact:
b = _add_pred(world, STATE_POSTURE_STANDING, attach="latest", meta=meta)
# In real WorldGraph, the same binding also carries the legacy alias for compatibility.
• Check a fact (alias-aware):
if _has(world, STATE_POSTURE_STANDING): ...
• Add a new canonical token:
NEW_CONST = "state:foo_bar"
CANON_SYNONYMS.update({"legacy:foo": NEW_CONST}) # optional back-compat mapping
Agent loop note:
• Drives produce drive:* flags (ephemeral).
• Action selection can prefer policies linked to the largest drive deficits; the controller
remains the safety gate (e.g., stand up if fallen), while the world stores only pred:* facts.
Action loop
-----------
-the Action Center is like a single-step orchestrator --
-safety short-circuit, e.g., if the world shows a fallen state then immediately run StandUp
-otherwise scan PRIMITIVES in order call trigger(world, dirves)
-run the first policy whose trigger is True --> _run wraps execute(...) and updates the skill ledger
-returns a status dict {"policy":"policy:<name>" | None, "status": "ok|fail|noop|error", "reward":float, "notes":str}
-the order of PRIMITIVES matters and we placed in our priority scheme:
StandUp (safety) --> SeekNipple(hunger) --> Rest (fatigue) --> FollowMom (fallback) --> ExploreCheck (stub)
-permissive fallback (e.g., FollowMom) (i.e., a policy whose trigger(...) is basically always True or at least in most normal states)
-the action center returns {"status":"noop"} only when no policy triggers
-if FollowMom.trigger(...) is nearly always True, then never see a "noop" because the fallback will always fire and produce an "ok" step instead
-if ever want occasional no-ops (i.e., do nothing controller steps) then tighten FollowMom(...) trigger (e.g., return False if tired/hungry/just acted) or
move FollowMom even further down or add a timer/debounce so it doesn't constantly fire
-when multiple policies trigger, selection defaults to deficit scoring with legacy-order fallback
-selection defaults to deficit scoring; to integrate an external adviser, pass preferred='policy:...' (controller remains the safety gate)
"""
# --- Imports -------------------------------------------------------------
# Standard Library Imports
from __future__ import annotations
from dataclasses import dataclass, asdict
from collections import deque
from datetime import datetime
from typing import Dict, List
import random
# PyPI and Third-Party Imports
# --none at this time at program startup--
# CCA8 Module Imports
# --none at this time at program startup--
# --- Public API index and version-------------------------------------------------------------
#nb version number of different modules are unique to that module
#nb the public API index specifies what downstream code should import from this module
__version__ = "0.2.1"
__all__ = [
# Version
"__version__",
# Drives and thresholds
"Drives",
"HUNGER_HIGH",
"FATIGUE_HIGH",
"WARMTH_COLD",
"STANDUP_RETRY_WINDOW",
# Skill ledger
"SkillStat",
"skill_q",
"update_skill",
"reset_skills",
"skills_to_dict",
"skills_from_dict",
"skill_readout",
# Policy base and concrete primitives
"Primitive",
"StandUp",
"RecoverFall",
"SeekNipple",
"FollowMom",
"ExploreCheck",
"Probe",
"Rest",
"PRIMITIVES",
"action_center_step",
"drives_summary",
"Suckle",
# BodyMap / current-state helpers
"body_posture",
"body_mom_distance",
"body_shelter_distance",
"body_cliff_distance",
"body_space_zone",
"body_nipple_state",
"body_is_standing",
"body_is_fallen",
"body_mom_is_near",
"body_nipple_latched",
"bodymap_is_stale",
"body_shelter_is_near",
"body_cliff_is_near",
# Public token constants
"STATE_POSTURE_STANDING",
"STATE_POSTURE_FALLEN",
"STATE_RESTING",
"STATE_ALERT",
"STATE_SEEKING_MOM",
"ACTION_PUSH_UP",
"ACTION_EXTEND_LEGS",
"ACTION_LOOK_AROUND",
"ACTION_ORIENT_TO_MOM",
"ACTION_RECOVER_FALL",
"ACTION_SUCKLE",
"VALENCE_LIKE",
"VALENCE_HATE",
# Small helper surface
"add_valence_binding",
]
# Drive thresholds
HUNGER_HIGH = 0.60
FATIGUE_HIGH = 0.70
WARMTH_COLD = 0.30
# --- Safety / retry control constants -----------------------------------
STANDUP_RETRY_WINDOW = 5 # controller steps to wait before retrying
# --- Canonical tokens ---------------------------------------------------------
# Canonical tokens (second-level namespaces under pred:*)
# We treat "posture:*", "resting", "alert", "seeking_mom" as the canonical forms.
# Legacy "state:*" forms are still recognized when *reading* so older snapshots/tests work.
STATE_POSTURE_STANDING = "posture:standing"
STATE_POSTURE_FALLEN = "posture:fallen"
STATE_RESTING = "resting"
STATE_ALERT = "alert"
STATE_SEEKING_MOM = "seeking_mom"
ACTION_PUSH_UP = "action:push_up"
ACTION_EXTEND_LEGS = "action:extend_legs"
ACTION_LOOK_AROUND = "action:look_around"
ACTION_ORIENT_TO_MOM = "action:orient_to_mom"
ACTION_RECOVER_FALL = "action:recover_fall"
ACTION_SUCKLE = "action:suckle"
VALENCE_LIKE = "valence:like"
VALENCE_HATE = "valence:hate"
# Back-compat synonyms we still recognize when *reading* from the graph.
# These map legacy state:* forms onto the new canonical tokens.
CANON_SYNONYMS: dict[str, str] = {}
def _canon(token: str) -> str:
return CANON_SYNONYMS.get(token, token)
def _is_worldgraph(world) -> bool:
"""Heuristic: real WorldGraph exposes planning.
True or False regarding if world.plan_to_predicate() exists
"""
return hasattr(world, "plan_to_predicate") and callable(getattr(world, "plan_to_predicate"))
def _add_tag_to_binding(world, bid: str, full_tag: str) -> None:
"""Best-effort: add a tag to an existing binding (works for WorldGraph and FakeWorld).
-will add "full_tag" to binding "bid" assuming a binding exists for "bid", and then adds "full_tag"
to whatever binding.tags exists
-doesn't return anything since mutates binding.tags in place
"""
try:
b = getattr(world, "_bindings", {}).get(bid) #if world._bindings exists look up bid
if not b:
return
tags = getattr(b, "tags", None) #fetches attribute b.tags if exists, otherwise creates from "full_tag" passed into the function
if tags is None:
b.tags = {full_tag} #if no b.tags then we rebind the attribute here
return
if isinstance(tags, set): #mutate t.tags set in place --> change will persist after the function returns
tags.add(full_tag)
elif isinstance(tags, list): # #mutate t.tags list in place --> change will persist after the function returns
if full_tag not in tags:
tags.append(full_tag)
except Exception:
pass
def _add_pred(world, token: str, **kwargs):
"""Wrapper to add a canonical predicate token. WorldGraph will add the 'pred:' family automatically.
-calls in worldgraph module world.add_predicate but with token updated to any newer tokens should they existing
"""
return world.add_predicate(_canon(token), **kwargs)
def _add_action(world, token: str, **kwargs):
"""Wrapper to add an action binding.
On a real WorldGraph, this calls `world.add_action(...)`, which writes
both "action:*" and legacy "pred:action:*" tags on the same binding.
On FakeWorld (tests) or other WorldGraph-like stubs that don't yet define
`add_action(...)`, we fall back to `_add_pred(...)`, which writes only
"pred:action:*" (preserving older test expectations).
"""
# Apply canonical mapping (currently only used for state:*; action:* passes through)
tok = _canon(token)
if _is_worldgraph(world) and hasattr(world, "add_action") and callable(getattr(world, "add_action")):
# Real WorldGraph path: action-family binding
return world.add_action(tok, **kwargs)
# Fallback for FakeWorld or older stubs: treat actions as predicates
return _add_pred(world, token, **kwargs)
# ==== Base-aware write STUB (NO-OP) =========================================
#pylint: disable=unused-argument
def _add_pred_base_aware(world, token: str, ctx, *, default_attach="latest", meta=None):
"""
STUB: Later, if a suggested write-base exists on ctx, write unattached and
manual-link base->new. Today this is identical to _add_pred(...).
Note: -We already compute a "write base" suggestion via choose_contextual_base(...)
e.g., as seen in the Instinct Step menu selection.
-these stubs give a single place to switch from attach="latest" to
base-anchored placement later.
- _maybe_anchor_attach(...) and add_spatial_relation stubs are in Runner module
"""
return _add_pred(world, token, attach=default_attach, meta=meta)
#pylint: enable=unused-argument
# ==== STUB spatial helpers =========================================
def add_valence_binding(world, ctx, polarity: str, *, target: str | None = None, strength: float = 1.0) -> str:
"""
Stub helper to write a valence predicate binding into the WorldGraph.
This creates a binding tagged with either:
pred:valence:like
or
pred:valence:hate
and stores the target + strength in meta. Future code may interpret this
when weighting plans or gating policies.
Parameters
----------
world : WorldGraph-like
The main episode graph.
ctx : Any
Runtime context (used only to seed provenance via _policy_meta).
polarity : str
'like' or 'hate'. Any non-'like' value is treated as 'hate' for now.
target : str | None
Optional symbolic token for what this valence refers to, e.g. 'mom',
'cliff', 'shelter', 'research:approach_A', etc.
strength : float
Optional magnitude of valence (default 1.0). Allows gradients later
without changing the basic representation.
Returns
-------
bid : str
The new binding id carrying the valence predicate.
"""
if polarity == "like":
tok = VALENCE_LIKE
else:
tok = VALENCE_HATE
meta = _policy_meta(ctx, "valence_stub")
meta.update(
{
"valence_polarity": polarity,
"valence_target": target,
"valence_strength": float(strength),
}
)
# Attach to 'latest' by default; call sites can choose a different attach mode later.
return _add_pred(world, tok, attach="latest", meta=meta)
# -----------------------------------------------------------------------------
# Drives
# -----------------------------------------------------------------------------
@dataclass(slots=True)
class Drives:
"""Agent internal state.
Attributes:
hunger: 0..1; >0.6 yields 'drive:hunger_high'.
fatigue: 0..1; >0.7 yields 'drive:fatigue_high'.
warmth: 0..1; <0.3 yields 'drive:cold'.
-note slots=True therefore no other attributes can be added
Methods:
-note dataclass, thus e.g., aa=Drives() (default values or can specify) -> aa.hunger will be 0.7
flags(): convert numeric drives to 'drive:*' flags (i.e., ephemeral tags) used by policy triggers.
to_dict()/from_dict(): autosave support.
"""
hunger: float = 0.7
fatigue: float = 0.2
warmth: float = 0.6
def flags(self) -> List[str]:
"""Return ephemeral 'drive:*' flags for policy triggers (not persisted in the graph)
-note that above in constants section: HUNGER_HIGH = 0.60, FATIGUE_HIGH = 0.70, WARMTH_COLD = 0.30
-returns a list of drive:* flags where sensory values triggered e.g., ["drive:hunger_high"]
"""
tags: List[str] = []
if self.hunger > HUNGER_HIGH:
tags.append("drive:hunger_high")
if self.fatigue > FATIGUE_HIGH:
tags.append("drive:fatigue_high")
if self.warmth < WARMTH_COLD:
tags.append("drive:cold")
return tags
def predicates(self) -> List[str]: # pragma: no cover (legacy alias)
"""DEPRECATED: use flags().
Back-compat for older code/tests
"""
return self.flags()
def to_dict(self) -> dict:
"""Return a plain JSON-safe dict of drive values for autosave/snapshots.
"""
return {"hunger": self.hunger, "fatigue": self.fatigue, "warmth": self.warmth}
@classmethod
def from_dict(cls, d: dict) -> "Drives":
"""Construct a Drives from a snapshot dict (robust to missing keys)
e.g., to_dict() → {"hunger": 0.7, "fatigue": 0.2, "warmth": 0.6}
from_dict({"hunger": 0.7, "fatigue": 0.2, "warmth": 0.6}) -> Drive
this classmethod returns a new instance of Drives
actually is called from and returns to the Load Session menu option in the runner module
"""
return cls(
hunger=float(d.get("hunger", 0.7)),
fatigue=float(d.get("fatigue", 0.2)),
warmth=float(d.get("warmth", 0.6)),
)
# -----------------------------------------------------------------------------
# Skills (tiny RL-style ledger)
# -----------------------------------------------------------------------------
@dataclass(slots=True)
class SkillStat:
"""Simple running stats per policy
-this is a tiny dataclass that tracks per-policy learning-like statistics
-really scaffolding for future RL
e.g., aa = SkillStat() #SkillStat(n=0, succ=0, q=0.0, last_reward=0.0)
print(type(aa)) #<class 'cca8_controller.SkillStat'>
"""
n: int = 0 #how many times this policy has been updated/attempted
succ: int = 0 #how many of those attempts successful
q: float = 0.0 #exponential moving average EMA of recent rewards
last_reward: float = 0.0 #most recent reward observed for that policy
SKILLS: Dict[str, SkillStat] = {}
#module level dictionary keyed by policy name, i.e., {policy_name:SkillStat, ...}
#e.g., StandUp.name = "policy:stand_up" (defined on the primitive)
#e.g., SKILLS = {"policy:stand_up": SkillStat(n=3, succ=2, q=0.447, last_reward=1.0),...}
def update_skill(name: str, reward: float, ok: bool = True, alpha: float = 0.3) -> None:
"""Update (or create) a SkillStat:
- n += 1; succ += 1 if ok
- q ← (1 - alpha) * q + alpha * reward (exponential moving average)
- last_reward ← reward
Notes:
* The ledger is in-memory only (not used for selection yet).
* Callers should pass rewards on the same scale across policies.
Operation:
e.g., let's assume SKILLS = {"policy:stand_up": SkillStat(n=3, succ=2, q=0.447, last_reward=1.0),...}
thus, s= SKILLS.get(name) = SkillStat(n=3, succ=2, q=0.447, last_reward=1.0)
if s returns as None then create instance of default SkillStat as s and then assign it to SKILLS[name]
then we increment the counter n, i.e., how many times policy attempted or updated and possibly the succ attribute
then we adjust the exponential moving average and update the last_reward
"""
s = SKILLS.get(name)
if s is None:
s = SkillStat()
SKILLS[name] = s
s.n += 1
if ok:
s.succ += 1
s.q = (1 - alpha) * s.q + alpha * float(reward)
s.last_reward = float(reward)
def reset_skills() -> None:
"""Clear the in-memory skill ledger(testing/demo convenience).
SKILLS becomes {}
"""
SKILLS.clear()
def skills_to_dict() -> dict:
"""Return a JSON-safe mapping of skill stats:
{ "policy:stand_up": {"n": int, "succ": int, "q": float, "last_reward": float}, ...}
"""
return {k: asdict(v) for k, v in SKILLS.items()}
def skills_from_dict(d: dict) -> None:
"""Rebuild SKILLS dataclass values from plain dicts (robust to bad inputs).
"""
SKILLS.clear()
for k, v in (d or {}).items():
try:
SKILLS[k] = SkillStat(
n=int(v.get("n", 0)),
succ=int(v.get("succ", 0)),
q=float(v.get("q", 0.0)),
last_reward=float(v.get("last_reward", 0.0)),
)
except Exception:
# Skip malformed rows rather than breaking session load.
continue
def skill_readout() -> str:
"""Human-readable policy stats: one line per policy (n/succ/rate/q/last)
-goes through SKILLS' stats and prints out
"""
if not SKILLS:
return "(no skill stats yet)"
lines: List[str] = []
for name in sorted(SKILLS):
s = SKILLS[name]
rate = (s.succ / s.n) if s.n else 0.0
lines.append(
f"{name}: n={s.n}, succ={s.succ}, rate={rate:.2f}, q={s.q:.2f}, last={s.last_reward:+.2f}"
)
return "\n".join(lines)
def skill_q(name: str, default: float = 0.0) -> float:
"""Return the current learned q-value for a policy.
The controller maintains a tiny skill ledger (SKILLS) keyed by policy name.
Each entry holds an exponential moving average (EMA) of observed rewards for
that policy (see update_skill()).
When policy-level reinforcement learning is enabled (ctx.rl_enabled=True),
selection logic can use this value as a secondary tie-breaker (or small bonus)
among multiple triggered policies.
"""
s = SKILLS.get(name)
if s is None:
return float(default)
try:
return float(s.q)
except Exception:
return float(default)
# -----------------------------------------------------------------------------
# Helper queries (controller-local; simple global scans)
# -----------------------------------------------------------------------------
# Note: world._bindings is an internal/private attribute of world object instance of WorldGraph, meaning it shouldn't
# really be accessed from outside the class (or immediate subclasses), i.e., "peeking" is occurring
# -however, these helper queries are considered a trusted-friend shortcut and we allow access rather than
# implementing a more formal public API in WorldGraph (can be considered in the future if WorldGraph internal changes,
# graph size exceeds 50K bindings, we introduce tag indices/aliasing that really belong inside WorldGraph)
# -scope guard: do not access world._bindings anywhere else in the codebase
def _any_tag(world, full_tag: str) -> bool:
"""Return True if any binding carries the exact tag (e.g., 'pred:...')
-checks to see if full_tag argument is in the set/list/tuple attributes found
"""
try:
for b in world._bindings.values(): # pylint: disable=protected-access
tags = getattr(b, "tags", ())
if isinstance(tags, (set, list, tuple)) and full_tag in tags:
return True
except (AttributeError, TypeError, KeyError):
pass
return False
def _has(world, token: str) -> bool:
"""
Previously: True if either the canonical *or* raw token exists as a pred:* tag
-recall from above that _canon(token: str) -> CANON_SYNONYMS.get(token, token)
-then the argument token is fed into __any_tag(...)
New version: Return True if any binding has tag 'pred:<token>'.
-Thin wrapper over _any_tag(...), which is the only helper allowed
to peek at world._bindings (and is guarded with the appropriate
pylint pragma).
"""
target = f"pred:{token}"
return _any_tag(world, target)
def _any_cue_present(world) -> bool:
"""Loose cue check: True if any tag starts with 'cue:' (no proximity semantics).
-scans through tags in world._bindings.values() to see if any starts with "cue" and
if so returns True
-used as a coarse perception gate to tell the controller if a cue present
"""
try:
for b in world._bindings.values(): # pylint: disable=protected-access
tags = getattr(b, "tags", ())
if not isinstance(tags, (set, list, tuple)):
continue
for t in tags:
if isinstance(t, str) and t.startswith("cue:"):
return True
except (AttributeError, TypeError, KeyError):
pass
return False
def _fallen_near_now(world, ctx, max_hops: int = 3) -> bool:
"""
Return True if the agent is "fallen" according to BodyMap when available,
otherwise fall back to scanning the episode graph near NOW for posture:fallen.
Body-first logic (neonate):
• If BodyMap is FRESH and posture == 'fallen' → treat as fallen (True).
• If BodyMap is FRESH and posture in {'standing',
'resting'} → treat as not fallen (False).
• Otherwise, fall back to: any pred:posture:fallen reachable from NOW
within <= max_hops edges.
This function feeds the Action Center safety override. It keeps the safety
check local to the current NOW anchor so that old posture:fallen facts far
in the past do not keep StandUp firing forever.
"""
# --- BodyMap override when fresh ---
try:
if ctx is not None and not bodymap_is_stale(ctx):
bp = body_posture(ctx)
if bp == "fallen":
return True
if bp in ("standing", "resting"):
return False
# If BodyMap is fresh but posture is unknown (None or other),
# we fall through to the graph-based check below.
except Exception:
# If anything goes wrong with BodyMap, fall back to graph only.
pass
# --- Graph-based local check around NOW anchor ---
try:
anchors = getattr(world, "_anchors", None)
if not isinstance(anchors, dict):
return False
now_id = anchors.get("NOW")
if not isinstance(now_id, str):
return False
except Exception:
return False
fallen_tags = {f"pred:{STATE_POSTURE_FALLEN}", "pred:posture:fallen"}
q = deque([now_id])
seen = {now_id}
depth: Dict[str, int] = {now_id: 0}
while q:
u = q.popleft()
b = world._bindings.get(u) # pylint: disable=protected-access
# Check this node's tags for a fallen posture
if b is not None:
tags = getattr(b, "tags", None) or []
for t in tags:
if isinstance(t, str) and t in fallen_tags:
return True
# Respect hop limit
if depth.get(u, 0) >= max_hops:
continue
# Walk forward along outgoing edges; be tolerant to layout variants.
edges: list = []
if b is not None:
edges = (
getattr(b, "edges", []) or
getattr(b, "out", []) or
getattr(b, "links", []) or
getattr(b, "outgoing", [])
)
if isinstance(edges, list):
for e in edges:
if not isinstance(e, dict):
continue
v = e.get("to") or e.get("dst") or e.get("dst_id") or e.get("id")
if isinstance(v, str) and v not in seen:
seen.add(v)
depth[v] = depth.get(u, 0) + 1
q.append(v)
return False
def _body_slot_tags(ctx, slot: str) -> set[str]:
"""
Return the tag set for a given BodyMap slot ('posture', 'mom', 'nipple')
or an empty set if BodyMap is not available.
We treat BodyMap as a tiny, separate WorldGraph instance hanging off ctx.
"""
try:
bw = getattr(ctx, "body_world", None)
body_ids = getattr(ctx, "body_ids", {}) or {}
if bw is None or not isinstance(body_ids, dict):
return set()
bid = body_ids.get(slot)
if not isinstance(bid, str):
return set()
b = getattr(bw, "_bindings", {}).get(bid)
if not b:
return set()
tags = getattr(b, "tags", None)
if isinstance(tags, set):
return set(tags)
if isinstance(tags, (list, tuple)):
return set(tags)
except Exception:
return set()
return set()
def body_posture(ctx) -> str | None:
"""
Read the BodyMap's posture slot and return a simple posture label:
'standing', 'fallen', 'resting', or None if unknown.
This is the preferred source of body posture for gating policies.
"""
tags = _body_slot_tags(ctx, "posture")
if "pred:posture:standing" in tags:
return "standing"
if "pred:posture:fallen" in tags:
return "fallen"
if "pred:resting" in tags or "resting" in tags:
return "resting"
return None
def body_mom_distance(ctx) -> str | None:
"""
Read the BodyMap's mom-distance slot and return 'near'/'far' (or None).
"""
tags = _body_slot_tags(ctx, "mom")
if "pred:proximity:mom:close" in tags:
return "near"
if "pred:proximity:mom:far" in tags:
return "far"
return None
def body_shelter_distance(ctx) -> str | None:
"""
Read the BodyMap's shelter-distance slot and return 'near'/'far' (or None).
This will be driven by predicates like:
proximity:shelter:near / proximity:shelter:far
mirrored into BodyMap as pred:proximity:shelter:* tags.
"""
tags = _body_slot_tags(ctx, "shelter")
if "pred:proximity:shelter:near" in tags:
return "near"
if "pred:proximity:shelter:far" in tags:
return "far"
return None
def body_cliff_distance(ctx) -> str | None:
"""
Read the BodyMap's cliff / dangerous drop slot and return 'near'/'far' (or None).
This is driven by hazard:cliff:* style predicates (if present in EnvObservation):
hazard:cliff:near / hazard:cliff:far
mirrored into BodyMap as pred:hazard:cliff:* tags.
"""
tags = _body_slot_tags(ctx, "cliff")
if "pred:hazard:cliff:near" in tags:
return "near"
if "pred:hazard:cliff:far" in tags:
return "far"
return None
def body_space_zone(ctx) -> str:
"""
Coarse body/space classification based on BodyMap shelter/cliff slots.
Returns one of:
'unsafe_cliff_near' — BodyMap is fresh and cliff is 'near' while shelter is not 'near'.
'safe' — BodyMap is fresh and shelter is 'near' while cliff is not 'near'.
'unknown' — BodyMap is stale/unavailable or we have insufficient information.
This helper is used by:
• the Rest gate (to veto resting in clearly unsafe geometry),
• snapshot/BodyMap displays (for a one-word zone label),
• environment-loop summaries (to show how the agent reacts to each zone).
It deliberately does *not* try to interpret all possible combinations
(e.g., both cliff and shelter 'near'); those are reported as 'unknown'
so callers can treat them conservatively or extend the taxonomy later.
"""
try:
# If BodyMap is missing or stale, we do not trust spatial slots.
if ctx is None or bodymap_is_stale(ctx):
return "unknown"
except Exception:
return "unknown"
try:
cliff = body_cliff_distance(ctx)
shelter = body_shelter_distance(ctx)
except Exception:
return "unknown"
if cliff is None and shelter is None:
return "unknown"
if cliff == "near" and shelter != "near":
return "unsafe_cliff_near"
if shelter == "near" and cliff != "near":
return "safe"
# Any other combination (including inconsistent or partially-known) is treated
# as 'unknown' so that gates can fall back to drive-based behaviour.
return "unknown"
def body_shelter_is_near(ctx) -> bool:
"""for future use
"""
return body_shelter_distance(ctx) == "near"
def body_cliff_is_near(ctx) -> bool:
"""for future use
"""
return body_cliff_distance(ctx) == "near"
def body_nipple_state(ctx) -> str | None:
"""
Read the BodyMap's nipple slot and return a simple nipple state label:
'latched', 'found', 'hidden', or None.
We also map milk:drinking to 'latched' if present.
"""
tags = _body_slot_tags(ctx, "nipple")
if "pred:nipple:latched" in tags:
return "latched"
if "pred:milk:drinking" in tags:
return "latched"
if "pred:nipple:found" in tags:
return "found"
if "pred:nipple:hidden" in tags:
return "hidden"
return None
def body_is_standing(ctx) -> bool:
"""
Convenience: True if BodyMap reports posture == 'standing'.
Falls back to False if posture is unknown or BodyMap is unavailable.
"""
return body_posture(ctx) == "standing"
def body_is_fallen(ctx) -> bool:
"""
Convenience: True if BodyMap reports posture == 'fallen'.
Falls back to False if posture is unknown or BodyMap is unavailable.
"""
return body_posture(ctx) == "fallen"
def body_mom_is_near(ctx) -> bool:
"""
Convenience: True if BodyMap reports mom is 'near'.
"""
return body_mom_distance(ctx) == "near"
def body_nipple_latched(ctx) -> bool:
"""
Convenience: True if BodyMap reports the nipple is latched (or actively drinking).
"""
return body_nipple_state(ctx) == "latched"
def bodymap_is_stale(ctx, max_steps: int = 5) -> bool:
"""
Return True if the BodyMap has not been updated in more than `max_steps`
controller steps.
We use:
• ctx.bodymap_last_update_step — set by update_body_world_from_obs(...)
• ctx.controller_steps — incremented by Instinct/Autonomic/env loops.
When this returns True, callers should treat BodyMap as advisory only and
fall back to the episode graph for posture/mom distance.
"""
try:
last = getattr(ctx, "bodymap_last_update_step", None)
steps = int(getattr(ctx, "controller_steps", 0))
if last is None:
# Never updated → treat as stale so we fall back to graph predicates.
return True
return (steps - int(last)) > max_steps
except Exception:
# In ambiguous situations, treat BodyMap as stale and let callers
# fall back to other sources.
return True
def _policy_deficit_score(name: str, drives: Drives) -> float:
"""
priority-by-deficit approach for policies:
Return a non-negative score reflecting how off-setpoint the relevant drive(s) are
for a given policy. Higher score → higher priority.
Current mapping (simple and transparent):
- policy:seek_nipple → max(0, hunger - HUNGER_HIGH) * 1.0
- policy:rest → max(0, fatigue - FATIGUE_HIGH) * 0.7
- others → 0.0 (rely on triggers & fallback ordering)
Rationale:
This affects *selection among policies that already triggered*.
Safety is handled before scoring (e.g., explicit 'fallen' → StandUp).
-future external/LLM advisory approach for policies:
We already support 'preferred' in action_center_step(...). To integrate an external
agent or LLM, expose 'drives_summary(drives)' and world facts; let the agent propose
a 'preferred' policy string. The controller remains the safety gate (e.g., fallen →
StandUp overrides everything). See action_center_step docstring for details.
(NOTE: "deficit" here means drive-urgency = max(0, drive_value - HIGH_THRESHOLD) (amount ABOVE threshold, not a negative deficit).)
(Policies without a drive-urgency term score 0.00 and will tie-break by stable policy order (or RL tie-break, if enabled).)
"""
if name == "policy:seek_nipple":
return max(0.0, float(drives.hunger) - float(HUNGER_HIGH)) * 1.0
if name == "policy:rest":
return max(0.0, float(drives.fatigue) - float(FATIGUE_HIGH)) * 0.7
return 0.0
def drives_summary(drives: Drives) -> dict:
"""
Compact snapshot of drives suitable for external advisory/LLM
Safe to log/serialize; does not include world internals
"""
return {"hunger": drives.hunger, "fatigue": drives.fatigue, "warmth": drives.warmth, "flags": list(drives.flags())}
# -----------------------------------------------------------------------------
# Policy base
# -----------------------------------------------------------------------------