#!/usr/bin/env python3 """Reapply SNN Baby Brain dynamic-growth + persistent-skill fixes to an updated script. Usage: python apply_lifelong_growth_patch.py path/to/38.py python apply_lifelong_growth_patch.py path/to/38.py --in-place Default writes a separate *_growth_memory_fixed.py file. --in-place makes a timestamped backup first. If the upstream file changed too much for safe anchor-based patching, the script stops instead of silently producing a partially patched brain. """ from __future__ import annotations import argparse import os import re import shutil import sys import time from pathlib import Path PATCH_MARKER = "LIFELONG_GROWTH_PERSISTENCE_PATCH_V1" def replace_once(text: str, old: str, new: str, label: str) -> str: if new in text: return text if old not in text: raise RuntimeError(f"Cannot safely apply '{label}': expected source anchor was not found.") return text.replace(old, new, 1) def insert_before(text: str, anchor: str, block: str, label: str) -> str: if block.strip() in text: return text if anchor not in text: raise RuntimeError(f"Cannot safely apply '{label}': insertion anchor was not found.") return text.replace(anchor, block + anchor, 1) def patch_source(text: str) -> str: # 1) Never ship a credential embedded in source. Environment variable is the only source. key_pattern = re.compile(r"(?m)^\s*UNSLOTH_API_KEY\s*=\s*(['\"]).*?\1\.strip\(\)\s*$") if "UNSLOTH_API_KEY = os.environ.get(" not in text: text2, n = key_pattern.subn(' UNSLOTH_API_KEY = os.environ.get("UNSLOTH_API_KEY", "").strip()', text, count=1) if n != 1: raise RuntimeError("Could not safely remove the embedded UNSLOTH_API_KEY fallback.") text = text2 # 2) Adapter keys must be valid ModuleDict names; track newly-created adapter slots. text = replace_once( text, ' self.adapters = nn.ModuleDict()\n', ' self.adapters = nn.ModuleDict()\n # Persistent registry generation allows discovery to be recorded immediately.\n self.registry_generation = 0\n', "skill adapter registry generation", ) text = replace_once( text, ' name = re.sub(r"[^a-z0-9_.-]+", "_", name)\n return name[:80] or Config.SKILL_DEFAULT\n', ' # PyTorch ModuleDict forbids dots in child names; map them to underscores.\n name = re.sub(r"[^a-z0-9_-]+", "_", name).strip("_")\n return name[:80] or Config.SKILL_DEFAULT\n', "valid adapter naming", ) text = replace_once( text, ' self.adapters[key] = adapter\n else:\n', ' self.adapters[key] = adapter\n self.registry_generation = int(getattr(self, "registry_generation", 0)) + 1\n else:\n', "adapter generation counter", ) # 3) Durable registry + append-only audit log. Insert helper functions once. registry_helpers = '''# LIFELONG_GROWTH_PERSISTENCE_PATCH_V1: durable skills and growth event ledger. def _persist_skill_registry(student, reason: str = "checkpoint") -> bool: """Persist adapter names/route metadata separately; adapter tensors stay in active brain.""" bank = getattr(student, "skill_adapters", None) if bank is None: return False try: prior = {} if SKILL_STATE_FILE.exists(): try: prior = json.loads(SKILL_STATE_FILE.read_text(encoding="utf-8")) if not isinstance(prior, dict): prior = {} except Exception: prior = {} names = sorted(set(str(x) for x in bank.names() if str(x).strip())) payload = dict(prior) payload.update({ "schema_version": 2, "skills": names, "active_skill": str(getattr(student, "active_skill", Config.SKILL_DEFAULT)), "router_confidence": float(getattr(student, "skill_router_confidence", 0.0)), "router_reason": str(getattr(student, "skill_router_reason", "default")), "registry_generation": int(getattr(bank, "registry_generation", len(names))), "embed_dim": int(getattr(student, "embed_dim", getattr(bank, "embed_dim", 0))), "weights_embedded_in": ACTIVE_BRAIN_FILE.name, "updated_at": datetime.now().isoformat(timespec="seconds"), "last_reason": str(reason)[:120], }) _atomic_json_save(payload, SKILL_STATE_FILE) setattr(student, "_skill_registry_saved_generation", int(getattr(bank, "registry_generation", len(names)))) return True except Exception as exc: try: logger.warning("Could not persist lifelong skill registry (%s): %s", reason, exc) except Exception: pass return False def _notify_skill_growth(student, skill_name: str, previous_generation: int) -> None: """Record a newly discovered adapter without writing model weights from inside forward().""" bank = getattr(student, "skill_adapters", None) if bank is None: return current_generation = int(getattr(bank, "registry_generation", 0)) if current_generation <= int(previous_generation): return _persist_skill_registry(student, reason="automatic_skill_discovery") try: log_lifelong_event("skill_adapter_created", { "skill": str(skill_name), "registry_generation": current_generation, "available_skills": len(bank.names()), "embed_dim": int(getattr(student, "embed_dim", getattr(bank, "embed_dim", 0))), }) except Exception: pass ''' text = insert_before(text, 'def save_skill_adapters(student: nn.Module) -> int:\n', registry_helpers, "skill registry helpers") # 4) Persist an append-only audit trail for durable memory/skills and topology growth. if "def log_lifelong_event(" not in text: event_helper = '''def log_lifelong_event(event_type: str, details: dict) -> None: """Append a durable, versioned event; knowledge answers are not self-certified here.""" try: path = SCRIPT_DIR / "lifelong_learning_events.jsonl" payload = { "schema_version": 1, "timestamp": time.time(), "event_type": str(event_type)[:100], "details": details if isinstance(details, dict) else {"value": str(details)}, } path.parent.mkdir(parents=True, exist_ok=True) with open(path, "a", encoding="utf-8") as handle: handle.write(json.dumps(payload, ensure_ascii=False, default=str, allow_nan=False) + "\\n") handle.flush() os.fsync(handle.fileno()) except Exception as exc: try: logger.warning("Lifelong event log write failed: %s", exc) except Exception: pass ''' text = insert_before(text, 'def log_unsupervised(event_type: str, details: dict):\n', event_helper, "lifelong event log") # 5) Route selection and the first forward pass persist new skill names immediately. old_method = ''' def set_active_skill(self, skill_name: str, confidence: float = 0.0, reason: str = "manual") -> str: key = self.skill_adapters.ensure(skill_name) if Config.SKILL_ISOLATION_ENABLED else SkillAdapterBank.normalize(skill_name) self.active_skill = key self.skill_router_confidence = float(max(0.0, min(1.0, confidence))) self.skill_router_reason = str(reason) return key ''' new_method = ''' def set_active_skill(self, skill_name: str, confidence: float = 0.0, reason: str = "manual") -> str: old_generation = int(getattr(self.skill_adapters, "registry_generation", 0)) key = self.skill_adapters.ensure(skill_name) if Config.SKILL_ISOLATION_ENABLED else SkillAdapterBank.normalize(skill_name) self.active_skill = key self.skill_router_confidence = float(max(0.0, min(1.0, confidence))) self.skill_router_reason = str(reason) _notify_skill_growth(self, key, old_generation) return key ''' text = replace_once(text, old_method, new_method, "persist discovered skills from routing") old_forward = ''' if Config.SKILL_ISOLATION_ENABLED: self.skill_adapters.ensure(skill_name) hidden = self.skill_adapters(hidden, skill_name) ''' new_forward = ''' if Config.SKILL_ISOLATION_ENABLED: old_generation = int(getattr(self.skill_adapters, "registry_generation", 0)) self.skill_adapters.ensure(skill_name) _notify_skill_growth(self, skill_name, old_generation) hidden = self.skill_adapters(hidden, skill_name) ''' text = replace_once(text, old_forward, new_forward, "persist automatically routed skills") # 6) Skill adapters stored only in checkpoint weights must be recreated before state_dict load. text = replace_once( text, 'def load_skill_adapters(student: nn.Module) -> int:\n', 'def load_skill_adapters(student: nn.Module, checkpoint_state_dict: Optional[dict] = None) -> int:\n', "recover skill names from active checkpoint", ) text = replace_once( text, ' names = []\n if SKILL_STATE_FILE.exists():\n', ''' names = [] # Recover adapter names directly from the authoritative checkpoint as well as metadata. # This repairs older updates where the weights survived but the registry JSON did not. if isinstance(checkpoint_state_dict, dict): prefix = "skill_adapters.adapters." for raw_key in checkpoint_state_dict.keys(): raw_key = str(raw_key) if raw_key.startswith(prefix): tail = raw_key[len(prefix):] name = tail.split(".", 1)[0].strip() if name and name not in names: names.append(name) if SKILL_STATE_FILE.exists(): ''', "discover skill names from checkpoint tensors", ) text = replace_once( text, ' names = list(meta.get("skills", []))\n', ''' # Merge metadata with checkpoint-derived names; metadata may be stale after an update. saved_skills = meta.get("skills", []) if isinstance(saved_skills, (list, tuple, set)): for saved_name in saved_skills: if isinstance(saved_name, str) and saved_name.strip(): normalized_name = SkillAdapterBank.normalize(saved_name) if normalized_name not in names: names.append(normalized_name) names = list(dict.fromkeys(SkillAdapterBank.normalize(name) for name in names if str(name).strip())) ''', "merge metadata and checkpoint skill names", ) # Legacy save path must not overwrite the upgraded v2 registry with stale schema-v1 metadata. text = replace_once( text, ' print(f"[SKILL] {len(sd)} adapter tensors stored in {ACTIVE_BRAIN_FILE.name}; no sidecar weights created.")\n', ' _persist_skill_registry(student, reason="save_skill_adapters")\n print(f"[SKILL] {len(sd)} adapter tensors stored in {ACTIVE_BRAIN_FILE.name}; no sidecar weights created.")\n', "persist registry after skill checkpoint save", ) text = replace_once( text, ' if not SKILL_ADAPTER_FILE.exists():\n return 0\n', ''' if not SKILL_ADAPTER_FILE.exists(): _persist_skill_registry(student, reason="startup_registry_recovery") return 0 ''', "persist recovered skill metadata", ) text = replace_once( text, ' print(f"[SKILL] Restored {loaded} adapter tensors ({len(names)} skills)")\n return loaded\n', ' print(f"[SKILL] Restored {loaded} adapter tensors ({len(names)} skills)")\n _persist_skill_registry(student, reason="startup_registry_restore")\n return loaded\n', "persist adapter migration metadata", ) text = replace_once( text, ' load_skill_adapters(student)\n', ' load_skill_adapters(student, preloaded_state_dict)\n', "restore skill adapters from active checkpoint before state loading", ) # 7) Keep registry synchronized whenever normal or topology checkpoints are committed. text = replace_once( text, ' student._snn_checkpoint_loaded = True\n except Exception as e:\n logger.exception("Active brain save failed; checkpoint/progress not advanced: %s", e)\n', ' student._snn_checkpoint_loaded = True\n _persist_skill_registry(student, reason="save_brain")\n except Exception as e:\n logger.exception("Active brain save failed; checkpoint/progress not advanced: %s", e)\n', "persist skills with normal brain checkpoints", ) text = replace_once( text, ' student._snn_checkpoint_loaded = True\n metadata = {}\n', ' student._snn_checkpoint_loaded = True\n _persist_skill_registry(student, reason="topology_checkpoint")\n metadata = {}\n', "persist skills with topology checkpoints", ) text = replace_once( text, ' log_neurogenesis(\'topology_checkpoint\', {\n \'student_ff_units\': student.count_total_neurons(),\n \'student_layers\': len(student.layers),\n \'emulator_active_neurons\': len(brain.loihi_emulator.neurons),\n \'emulator_active_synapses\': len(brain.loihi_emulator.synapses),\n \'reason\': \'neurogenesis_or_pruning\',\n }, component=\'runtime\')\n', ' log_neurogenesis(\'topology_checkpoint\', {\n \'student_ff_units\': student.count_total_neurons(),\n \'student_layers\': len(student.layers),\n \'emulator_active_neurons\': len(brain.loihi_emulator.neurons),\n \'emulator_active_synapses\': len(brain.loihi_emulator.synapses),\n \'reason\': \'neurogenesis_or_pruning\',\n }, component=\'runtime\')\n log_lifelong_event("neural_topology_checkpoint", {\n "architecture": student.get_architecture_stats(),\n "neurogenesis": student.get_neurogenesis_stats(),\n "skills": list(student.skill_adapters.names()) if hasattr(student, "skill_adapters") else [],\n })\n', "audit architecture and skills after topology growth", ) # 8) Teaching-triggered growth must synchronize the optimizer after replacing/growing parameters. text = replace_once( text, ' brain.check_neurogenesis(student_model, da_neuromod, min(1.0, 1.0 - score))\n', ' brain.check_neurogenesis(student_model, da_neuromod, min(1.0, 1.0 - score), optimizer=optimizer)\n', "synchronize teaching optimizer after dynamic growth", ) # 9) Audit verified memory writes without storing the private prompt/answer in the event ledger. text = replace_once( text, ' self.items[key] = item\n self._save()\n return {"item_id": key, "skill": item["skill"], "due_at": item["due_at"],\n', ' self.items[key] = item\n self._save()\n try:\n log_lifelong_event("verified_memory_saved", {"item_id": key, "skill": item["skill"], "source": item["source"]})\n except Exception:\n pass\n return {"item_id": key, "skill": item["skill"], "due_at": item["due_at"],\n', "audit verified memory persistence", ) # 10) If a feature wasn't available in this upstream version, fail with a clear reason. if 'def auto_neurogenesis(self, learning_demand:' not in text: raise RuntimeError("This script has no student auto_neurogenesis implementation; refusing to claim dynamic growth was patched.") if 'def save_neurogenesis_topology_checkpoint(' not in text: raise RuntimeError("This script has no topology checkpoint helper; refusing to claim topology persistence was patched.") # Make the patched build distinguishable from the unpatched v29.3 source. text = text.replace( "SNN BABY BRAIN v29.3 - SNN-ONLY MULTIMODAL RGB + PYLANCE FIX PASS", "SNN BABY BRAIN v29.4 - DYNAMIC GROWTH + PERSISTENT MEMORY/SKILLS\nLIFELONG_GROWTH_BUILD_MARKER", 1, ) return text def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("source", type=Path, help="Updated SNN Baby Brain Python source file") parser.add_argument("--in-place", action="store_true", help="Patch source in place after creating a backup") parser.add_argument("--output", type=Path, help="Output path (default: _growth_memory_fixed.py)") args = parser.parse_args() src = args.source.expanduser().resolve() if not src.is_file(): print(f"ERROR: source file not found: {src}", file=sys.stderr) return 2 original = src.read_text(encoding="utf-8", errors="replace") try: patched = patch_source(original) except Exception as exc: print(f"PATCH ABORTED (no output written): {exc}", file=sys.stderr) return 3 if args.in_place: backup = src.with_suffix(src.suffix + f".backup_{time.strftime('%Y%m%d_%H%M%S')}") shutil.copy2(src, backup) target = src else: target = args.output.expanduser().resolve() if args.output else src.with_name(src.stem + "_growth_memory_fixed" + src.suffix) if target == src: print("ERROR: output resolves to source; use --in-place for intentional replacement.", file=sys.stderr) return 2 backup = None target.parent.mkdir(parents=True, exist_ok=True) target.write_text(patched, encoding="utf-8", newline="") print(f"Patched source: {src}") print(f"Output: {target}") if backup: print(f"Backup: {backup}") print("Included: dynamic-growth optimizer sync, checkpoint skill recovery, atomic skill registry, append-only lifelong event ledger, verified-memory audit, API-key environment-only fix.") return 0 if __name__ == "__main__": raise SystemExit(main())