Update recursive_context.py
Browse files397 unmodified lines3983994004014024034044054064074084094104114124134144154161 unmodified line4184194204214224234246 unmodified lines4314324334344354364374384394404414424434442 unmodified lines4474484494504514524534544554564574584591 unmodified line4614624634644654664677 unmodified lines475476477478479480104 unmodified lines585586587397 unmodified linesreturn f"STDOUT: {result.stdout}\nSTDERR: {result.stderr}"except Exception as e:return f"Execution Error: {e}"def push_to_github(self, commit_message="Auto-backup from Clawdbot"):"""Pushes the current workspace to the configured GitHub repository."""token = os.getenv("GITHUB_TOKEN")repo = os.getenv("GITHUB_REPO")if not token or not repo:return "β Error: GITHUB_TOKEN or GITHUB_REPO secret is missing."# authenticated URLremote_url = f"https://{token}@github.com/{repo}.git"try:# 1. Initialize if needed (Docker containers often lack .git)if not (self.repo_path / ".git").exists():subprocess.run(["git", "init"], cwd=self.repo_path, check=True)subprocess.run(["git", "config", "user.email", "clawdbot@e-t-systems.ai"], cwd=self.repo_path)1 unmodified linesubprocess.run(["git", "branch", "-M", "main"], cwd=self.repo_path)# 2. Configure Remote (Idempotent)# Remove existing remote to ensure token is fresh/correctsubprocess.run(["git", "remote", "remove", "origin"], cwd=self.repo_path, stderr=subprocess.DEVNULL)subprocess.run(["git", "remote", "add", "origin", remote_url], cwd=self.repo_path, check=True)6 unmodified linescwd=self.repo_path, capture_output=True, text=True)# Push (force is safer for a backup mirror to overwrite conflicts)push_res = subprocess.run(["git", "push", "-u", "origin", "main", "--force"],cwd=self.repo_path, capture_output=True, text=True)if push_res.returncode == 0:return f"β Successfully pushed to GitHub: https://github.com/{repo}"else:return f"β οΈ Git Push Failed: {push_res.stderr}"2 unmodified linesdef pull_from_github(self, branch="main"):"""Hard reset: Destroys local changes and pulls clean code from GitHub."""token = os.getenv("GITHUB_TOKEN")repo = os.getenv("GITHUB_REPO")if not token or not repo:return "β Error: GITHUB_TOKEN or GITHUB_REPO secret is missing."remote_url = f"https://{token}@github.com/{repo}.git"try:# 1. Init if missing1 unmodified linesubprocess.run(["git", "init"], cwd=self.repo_path, check=True)subprocess.run(["git", "remote", "add", "origin", remote_url], cwd=self.repo_path)# 2. Fetch and Reset (Destructive but safe for recovery)subprocess.run(["git", "fetch", "origin"], cwd=self.repo_path, check=True)res = subprocess.run(["git", "reset", "--hard", f"origin/{branch}"],7 unmodified linesexcept Exception as e:return f"β Critical Git Error: {e}"# =====================================================================# RECURSIVE SEARCH TOOLS# =====================================================================104 unmodified lines# 3. Push the entire manifest back to your PRO storage datasetself.persistence.save_conversations(full_data)397 unmodified lines3983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294301 unmodified line4324334344354364376 unmodified lines4444454464474484494504514524534544554564574584592 unmodified lines4624634644654664674684694701 unmodified line4724734744754764774787 unmodified lines486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557104 unmodified lines662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804397 unmodified linesreturn f"STDOUT: {result.stdout}\nSTDERR: {result.stderr}"except Exception as e:return f"Execution Error: {e}"# =====================================================================# GIT TOOLS (Fixed for Double-URL Issue)# =====================================================================def _get_authenticated_remote_url(self):"""Helper to construct the correct authenticated URL."""token = os.getenv("GITHUB_TOKEN")repo = os.getenv("GITHUB_REPO")if not token or not repo:return None# Clean the repo string if it's already a full URLif repo.startswith("https://github.com/"):repo = repo.replace("https://github.com/", "")if repo.endswith(".git"):repo = repo[:-4]return f"https://{token}@github.com/{repo}.git"def push_to_github(self, commit_message="Auto-backup from Clawdbot"):"""Pushes the current workspace to the configured GitHub repository."""remote_url = self._get_authenticated_remote_url()if not remote_url:return "β Error: GITHUB_TOKEN or GITHUB_REPO secret is missing."try:# 1. Initialize if neededif not (self.repo_path / ".git").exists():subprocess.run(["git", "init"], cwd=self.repo_path, check=True)subprocess.run(["git", "config", "user.email", "clawdbot@e-t-systems.ai"], cwd=self.repo_path)1 unmodified linesubprocess.run(["git", "branch", "-M", "main"], cwd=self.repo_path)# 2. Configure Remote (Idempotent)subprocess.run(["git", "remote", "remove", "origin"], cwd=self.repo_path, stderr=subprocess.DEVNULL)subprocess.run(["git", "remote", "add", "origin", remote_url], cwd=self.repo_path, check=True)6 unmodified linescwd=self.repo_path, capture_output=True, text=True)# Push (force is safer for a backup mirror)push_res = subprocess.run(["git", "push", "-u", "origin", "main", "--force"],cwd=self.repo_path, capture_output=True, text=True)if push_res.returncode == 0:# Clean URL for display securitydisplay_url = remote_url.replace(os.getenv("GITHUB_TOKEN"), "TOKEN_HIDDEN")return f"β Successfully pushed to GitHub"else:return f"β οΈ Git Push Failed: {push_res.stderr}"2 unmodified linesdef pull_from_github(self, branch="main"):"""Hard reset: Destroys local changes and pulls clean code from GitHub."""remote_url = self._get_authenticated_remote_url()if not remote_url:return "β Error: GITHUB_TOKEN or GITHUB_REPO secret is missing."try:# 1. Init if missing1 unmodified linesubprocess.run(["git", "init"], cwd=self.repo_path, check=True)subprocess.run(["git", "remote", "add", "origin", remote_url], cwd=self.repo_path)# 2. Fetch and Resetsubprocess.run(["git", "fetch", "origin"], cwd=self.repo_path, check=True)res = subprocess.run(["git", "reset", "--hard", f"origin/{branch}"],7 unmodified linesexcept Exception as e:return f"β Critical Git Error: {e}"# =====================================================================# WORKING MEMORY NOTEBOOK (Structured List)# =====================================================================def _load_notebook(self) -> List[Dict]:"""Internal helper to load notebook JSON."""notebook_path = self.repo_path / "memory" / "notebook.json"if not notebook_path.exists():return []try:return json.loads(notebook_path.read_text(encoding='utf-8'))except:return []def _save_notebook(self, notes: List[Dict]):"""Internal helper to save notebook JSON with audit logging."""notebook_path = self.repo_path / "memory" / "notebook.json"log_path = self.repo_path / "memory" / "history.log"notebook_path.parent.mkdir(parents=True, exist_ok=True)notebook_path.write_text(json.dumps(notes, indent=2), encoding='utf-8')# Audit Log (Metadata only)try:timestamp = time.strftime("%Y-%m-%d %H:%M:%S")with open(log_path, "a") as f:f.write(f"[{timestamp}] NOTEBOOK UPDATED | Count: {len(notes)}\n")except: passdef notebook_read(self) -> str:"""Reads the Working Memory notebook."""notes = self._load_notebook()if not notes:return ""display = []for i, note in enumerate(notes):display.append(f"{i+1}. [{note['timestamp']}] {note['content']}")return "\n".join(display)def notebook_add(self, content: str) -> str:"""Adds a new note to the notebook."""notes = self._load_notebook()if len(notes) >= 25:return "β οΈ Notebook full (25/25 slots). Please delete obsolete notes first."timestamp = time.strftime("%Y-%m-%d %H:%M")notes.append({"timestamp": timestamp, "content": content})self._save_notebook(notes)return f"β Note added. ({len(notes)}/25 slots used)"def notebook_delete(self, index: int) -> str:"""Deletes a note by its number (1-based index)."""notes = self._load_notebook()try:idx = int(index) - 1if 0 <= idx < len(notes):removed = notes.pop(idx)self._save_notebook(notes)return f"β Deleted note #{index}: '{removed['content'][:30]}...'"else:return f"β Invalid index: {index}. Valid range: 1-{len(notes)}"except ValueError:return "β Index must be a number."# =====================================================================# RECURSIVE SEARCH TOOLS# =====================================================================104 unmodified lines# 3. Push the entire manifest back to your PRO storage datasetself.persistence.save_conversations(full_data)# =====================================================================# GIT TOOLS# =====================================================================def _get_authenticated_remote_url(self):"""Helper to construct the correct authenticated URL."""token = os.getenv("GITHUB_TOKEN")repo = os.getenv("GITHUB_REPO")if not token or not repo:return None# Clean the repo string if it's already a full URLif repo.startswith("https://github.com/"):repo = repo.replace("https://github.com/", "")if repo.endswith(".git"):repo = repo[:-4]return f"https://{token}@github.com/{repo}.git"def push_to_github(self, commit_message="Auto-backup from Clawdbot"):"""Pushes the current workspace to the configured GitHub repository."""remote_url = self._get_authenticated_remote_url()if not remote_url:return "β Error: GITHUB_TOKEN or GITHUB_REPO secret is missing."try:# 1. Initialize if neededif not (self.repo_path / ".git").exists():subprocess.run(["git", "init"], cwd=self.repo_path, check=True)subprocess.run(["git", "config", "user.email", "clawdbot@e-t-systems.ai"], cwd=self.repo_path)subprocess.run(["git", "config", "user.name", "Clawdbot"], cwd=self.repo_path)subprocess.run(["git", "branch", "-M", "main"], cwd=self.repo_path)# 2. Configure Remote (Idempotent)subprocess.run(["git", "remote", "remove", "origin"], cwd=self.repo_path, stderr=subprocess.DEVNULL)subprocess.run(["git", "remote", "add", "origin", remote_url], cwd=self.repo_path, check=True)# 3. Add, Commit, Pushsubprocess.run(["git", "add", "."], cwd=self.repo_path, check=True)# Commit (allow empty if nothing changed)commit_res = subprocess.run(["git", "commit", "-m", commit_message],cwd=self.repo_path, capture_output=True, text=True)# Push (force is safer for a backup mirror)push_res = subprocess.run(["git", "push", "-u", "origin", "main", "--force"],cwd=self.repo_path, capture_output=True, text=True)if push_res.returncode == 0:repo_name = os.getenv("GITHUB_REPO").replace("https://github.com/", "").replace(".git", "")return f"β Successfully pushed to GitHub: https://github.com/{repo_name}"else:return f"β οΈ Git Push Failed: {push_res.stderr}"except Exception as e:return f"β Critical Git Error: {e}"def pull_from_github(self, branch="main"):"""Hard reset: Destroys local changes and pulls clean code from GitHub."""remote_url = self._get_authenticated_remote_url()if not remote_url:return "β Error: GITHUB_TOKEN or GITHUB_REPO secret is missing."try:# 1. Init if missingif not (self.repo_path / ".git").exists():subprocess.run(["git", "init"], cwd=self.repo_path, check=True)subprocess.run(["git", "remote", "add", "origin", remote_url], cwd=self.repo_path)# 2. Fetch and Resetsubprocess.run(["git", "fetch", "origin"], cwd=self.repo_path, check=True)res = subprocess.run(["git", "reset", "--hard", f"origin/{branch}"],cwd=self.repo_path, capture_output=True, text=True)if res.returncode == 0:return f"β RESTORE COMPLETED. Local files replaced with GitHub/{branch}."else:return f"β οΈ Pull Failed: {res.stderr}"except Exception as e:return f"β Critical Git Error: {e}"# =====================================================================# WORKING MEMORY NOTEBOOK (Structured List)# =====================================================================def _load_notebook(self) -> List[Dict]:"""Internal helper to load notebook JSON."""notebook_path = self.repo_path / "memory" / "notebook.json"if not notebook_path.exists(): return []try: return json.loads(notebook_path.read_text(encoding='utf-8'))except: return []def _save_notebook(self, notes: List[Dict]):"""Internal helper to save notebook JSON with audit logging."""notebook_path = self.repo_path / "memory" / "notebook.json"log_path = self.repo_path / "memory" / "history.log"notebook_path.parent.mkdir(parents=True, exist_ok=True)notebook_path.write_text(json.dumps(notes, indent=2), encoding='utf-8')try:timestamp = time.strftime("%Y-%m-%d %H:%M:%S")with open(log_path, "a") as f: f.write(f"[{timestamp}] NOTEBOOK UPDATED | Count: {len(notes)}\n")except: passdef notebook_read(self) -> str:"""Reads the Working Memory notebook."""notes = self._load_notebook()if not notes: return ""display = []for i, note in enumerate(notes):display.append(f"{i+1}. [{note['timestamp']}] {note['content']}")return "\n".join(display)def notebook_add(self, content: str) -> str:"""Adds a new note to the notebook."""notes = self._load_notebook()if len(notes) >= 25: return "β οΈ Notebook full (25/25 slots). Please delete obsolete notes first."timestamp = time.strftime("%Y-%m-%d %H:%M")notes.append({"timestamp": timestamp, "content": content})self._save_notebook(notes)return f"β Note added. ({len(notes)}/25 slots used)"def notebook_delete(self, index: int) -> str:"""Deletes a note by its number (1-based index)."""notes = self._load_notebook()try:idx = int(index) - 1if 0 <= idx < len(notes):removed = notes.pop(idx)self._save_notebook(notes)return f"β Deleted note #{index}: '{removed['content'][:30]}...'"else: return f"β Invalid index: {index}. Valid range: 1-{len(notes)}"except ValueError: return "β Index must be a number."
recursive_context.py+233-16