Download dev_workbench.py from manjunathan123/max: direct link, hf CLI and curl.
- Browser
- Download file 30.5 kB
-
https://huggingface.co/manjunathan123/max/resolve/main/dev_workbench.py
- Command line
-
hf download hf://manjunathan123/max/dev_workbench.py
-
curl -L -o dev_workbench.py https://huggingface.co/manjunathan123/max/resolve/main/dev_workbench.py
30.5 kB
| #!/usr/bin/env python3 | |
| """Approval-gated coding workspace for SNN Baby Brain 40.4. | |
| The model can draft code proposals, explain/review files, and suggest fixes. Nothing | |
| written by the model reaches the project tree until the operator runs `dev apply`. | |
| Tests are run only when the operator explicitly runs `dev test`; this is NOT an OS | |
| security sandbox, so only test code you trust. | |
| """ | |
| from __future__ import annotations | |
| import ast | |
| import json | |
| import os | |
| import re | |
| import shutil | |
| import subprocess | |
| import sys | |
| import time | |
| import uuid | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any, Callable, Optional | |
| ALLOWED_EXTENSIONS = { | |
| ".py", ".pyi", ".md", ".txt", ".json", ".toml", ".yaml", ".yml", | |
| ".html", ".css", ".js", ".ts", ".jsx", ".tsx", ".xml", ".csv", ".sql", | |
| ".ini", ".cfg", ".rst", ".sh", ".ps1", | |
| } | |
| MAX_FILES_PER_PROPOSAL = 20 | |
| MAX_FILE_BYTES = 300_000 | |
| MAX_PROPOSAL_BYTES = 700_000 | |
| MAX_READ_BYTES = 180_000 | |
| DEFAULT_TEST_TIMEOUT = 45 | |
| class DevWorkbenchError(RuntimeError): | |
| pass | |
| class DevelopmentWorkbench: | |
| def __init__(self, workspace_root: Path | str, llm_call: Optional[Callable[..., str]] = None, | |
| test_timeout: int = DEFAULT_TEST_TIMEOUT): | |
| self.root = Path(workspace_root).expanduser().resolve() | |
| self.projects_root = self.root / "projects" | |
| self.meta_root = self.root / ".meta" | |
| self.proposals_root = self.meta_root / "proposals" | |
| self.backups_root = self.root / "backups" | |
| self.llm_call = llm_call | |
| self.test_timeout = max(5, min(int(test_timeout), 180)) | |
| for directory in (self.projects_root, self.meta_root, self.proposals_root, self.backups_root): | |
| directory.mkdir(parents=True, exist_ok=True) | |
| def _now() -> str: | |
| return datetime.now(timezone.utc).isoformat() | |
| def _project_name(name: str) -> str: | |
| name = str(name or "").strip() | |
| if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,49}", name) or name in {".", ".."}: | |
| raise DevWorkbenchError("Project name must be 1-50 letters/numbers/dot/dash/underscore and start alphanumeric.") | |
| if name.upper() in {"CON", "PRN", "AUX", "NUL", *(f"COM{i}" for i in range(1, 10)), *(f"LPT{i}" for i in range(1, 10))}: | |
| raise DevWorkbenchError("That name is reserved by Windows. Choose another project name.") | |
| return name | |
| def _relative_path(value: str) -> Path: | |
| value = str(value or "").strip().replace("\\", "/") | |
| path = Path(value) | |
| if not value or path.is_absolute() or any(part in {"..", ""} for part in path.parts): | |
| raise DevWorkbenchError("Use a project-relative path and do not include '..' or an absolute path.") | |
| if path.parts and re.match(r"^[A-Za-z]:", path.parts[0]): | |
| raise DevWorkbenchError("Drive-qualified paths are not allowed; use a project-relative path.") | |
| if path.suffix.lower() not in ALLOWED_EXTENSIONS: | |
| raise DevWorkbenchError(f"File extension {path.suffix!r} is not on the developer-workspace allowlist.") | |
| if len(value) > 220: | |
| raise DevWorkbenchError("Path is too long.") | |
| return path | |
| def _project_dir(self, name: str, must_exist: bool = True) -> Path: | |
| slug = self._project_name(name) | |
| candidate = (self.projects_root / slug).resolve() | |
| if not candidate.is_relative_to(self.projects_root.resolve()): | |
| raise DevWorkbenchError("Project path escapes the workspace.") | |
| if must_exist and not candidate.is_dir(): | |
| raise DevWorkbenchError(f"Project {slug!r} does not exist. Create it with `dev create {slug} :: <spec>` first.") | |
| return candidate | |
| def _project_file(self, project: str, rel: str, must_exist: bool = True) -> Path: | |
| base = self._project_dir(project, must_exist=must_exist) | |
| relative = self._relative_path(rel) | |
| candidate = (base / relative).resolve() | |
| if not candidate.is_relative_to(base.resolve()): | |
| raise DevWorkbenchError("Resolved file path escapes the project (possible symlink traversal).") | |
| if must_exist and not candidate.is_file(): | |
| raise DevWorkbenchError(f"File not found: {relative.as_posix()}") | |
| return candidate | |
| def _call_model(self, system: str, prompt: str, max_tokens: int = 1400) -> str: | |
| if not callable(self.llm_call): | |
| raise DevWorkbenchError("No language-model backend is available. Configure the Teacher API or load a supported local foundation backend.") | |
| try: | |
| result = self.llm_call(system, prompt, max_tokens=max_tokens) | |
| except TypeError: | |
| result = self.llm_call(system, prompt) | |
| result = str(result or "").strip() | |
| if not result: | |
| raise DevWorkbenchError("The configured model returned no content. Check backend readiness and retry.") | |
| return result | |
| def _parse_json(text: str) -> dict[str, Any]: | |
| cleaned = text.strip() | |
| cleaned = re.sub(r"^```(?:json)?\s*", "", cleaned, flags=re.IGNORECASE) | |
| cleaned = re.sub(r"\s*```$", "", cleaned) | |
| try: | |
| data = json.loads(cleaned) | |
| except json.JSONDecodeError: | |
| start, end = cleaned.find("{"), cleaned.rfind("}") | |
| if start < 0 or end <= start: | |
| raise DevWorkbenchError("Model response was not valid JSON. No files were written; ask for a smaller request.") | |
| try: | |
| data = json.loads(cleaned[start:end + 1]) | |
| except json.JSONDecodeError as exc: | |
| raise DevWorkbenchError(f"Model response JSON was incomplete/invalid ({exc}). No files were written; ask for a smaller request.") from exc | |
| if not isinstance(data, dict): | |
| raise DevWorkbenchError("Model response must be a JSON object. No files were written.") | |
| return data | |
| def plan(self, goal: str) -> dict[str, Any]: | |
| goal = str(goal or "").strip() | |
| if not goal: | |
| raise DevWorkbenchError("Usage: dev plan <coding/project goal>") | |
| fallback = { | |
| "status": "fallback_plan_only", | |
| "goal": goal, | |
| "roles": [ | |
| {"role": "architect", "responsibility": "Identify requirements, design and file boundaries."}, | |
| {"role": "developer", "responsibility": "Implement changes only in the isolated project workspace."}, | |
| {"role": "tester", "responsibility": "Compile and run trusted tests; report failures without hiding them."}, | |
| {"role": "reviewer", "responsibility": "Review correctness, security, maintainability and acceptance criteria."}, | |
| {"role": "owner", "responsibility": "Approve application of proposed files and accept the final deliverable."}, | |
| ], | |
| "execution_policy": "Plan only. No code was generated or executed.", | |
| } | |
| prompt = ( | |
| "Produce a realistic, concise software-development plan as strict JSON with keys: " | |
| "goal, assumptions, acceptance_criteria (array), steps (array of objects with id, title, role, depends_on, output, verification), " | |
| "risks (array), owner_questions (array). Assign conceptual roles architect, developer, tester, reviewer, owner. " | |
| "Do not claim tools were run. Prefer small deliverable increments, explicit verification, and reversible changes.\n\nGOAL:\n" + goal[:9000] | |
| ) | |
| try: | |
| data = self._parse_json(self._call_model("You are a careful engineering project manager. Return JSON only.", prompt, 1200)) | |
| data.setdefault("goal", goal) | |
| data["status"] = "plan_only" | |
| data["execution_policy"] = "Plan only. No files were written and no code was executed." | |
| path = self.meta_root / f"plan_{int(time.time())}_{uuid.uuid4().hex[:6]}.json" | |
| path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") | |
| data["plan_path"] = str(path) | |
| return data | |
| except DevWorkbenchError as exc: | |
| fallback["issue"] = str(exc) | |
| return fallback | |
| def _new_proposal(self, project: str, task: str, response: str) -> dict[str, Any]: | |
| data = self._parse_json(response) | |
| files = data.get("files") | |
| if not isinstance(files, list) or not files: | |
| raise DevWorkbenchError("Model response must contain a non-empty 'files' array. No project files were changed.") | |
| if len(files) > MAX_FILES_PER_PROPOSAL: | |
| raise DevWorkbenchError(f"Proposal has more than {MAX_FILES_PER_PROPOSAL} files; request a smaller increment.") | |
| checked: list[dict[str, str]] = [] | |
| total = 0 | |
| seen = set() | |
| for entry in files: | |
| if not isinstance(entry, dict) or not isinstance(entry.get("path"), str) or not isinstance(entry.get("content"), str): | |
| raise DevWorkbenchError("Every file entry must contain string 'path' and 'content' fields.") | |
| rel = self._relative_path(entry["path"]) | |
| rel_text = rel.as_posix() | |
| if rel_text in seen: | |
| raise DevWorkbenchError(f"Duplicate path in proposal: {rel_text}") | |
| seen.add(rel_text) | |
| content = entry["content"] | |
| size = len(content.encode("utf-8")) | |
| if size > MAX_FILE_BYTES: | |
| raise DevWorkbenchError(f"Proposed file {rel_text} exceeds the {MAX_FILE_BYTES}-byte limit.") | |
| total += size | |
| if rel.suffix.lower() == ".py": | |
| try: | |
| ast.parse(content, filename=rel_text) | |
| except SyntaxError as exc: | |
| raise DevWorkbenchError(f"Proposed Python file {rel_text} has a syntax error at line {exc.lineno}: {exc.msg}. No files were changed.") from exc | |
| checked.append({"path": rel_text, "content": content}) | |
| if total > MAX_PROPOSAL_BYTES: | |
| raise DevWorkbenchError(f"Proposal is {total} bytes, beyond the {MAX_PROPOSAL_BYTES}-byte total limit. Request a smaller increment.") | |
| proposal_id = f"P-{datetime.now().strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:6]}" | |
| proposal = { | |
| "proposal_id": proposal_id, | |
| "created_at": self._now(), | |
| "project": self._project_name(project), | |
| "task": str(task)[:6000], | |
| "summary": str(data.get("summary", "Model-generated code proposal"))[:3000], | |
| "verification_plan": data.get("verification_plan", []), | |
| "risks": data.get("risks", []), | |
| "files": checked, | |
| "status": "pending_operator_apply", | |
| "notice": "Model-generated draft; review before applying. No code was executed while drafting.", | |
| } | |
| output = self.proposals_root / f"{proposal_id}.json" | |
| output.write_text(json.dumps(proposal, ensure_ascii=False, indent=2), encoding="utf-8") | |
| return self._proposal_summary(proposal) | |
| def _proposal_summary(proposal: dict[str, Any]) -> dict[str, Any]: | |
| return {k: proposal.get(k) for k in ("proposal_id", "created_at", "project", "task", "summary", "verification_plan", "risks", "status", "notice")} | { | |
| "files": [{"path": f["path"], "bytes": len(f["content"].encode("utf-8"))} for f in proposal.get("files", [])] | |
| } | |
| def create(self, project: str, spec: str) -> dict[str, Any]: | |
| project = self._project_name(project) | |
| spec = str(spec or "").strip() | |
| if not spec: | |
| raise DevWorkbenchError("Usage: dev create <project-name> :: <specific software request>") | |
| prompt = ( | |
| "Create a small, complete first increment of a software project. Return strict JSON only with keys: " | |
| "summary, files (array of objects {path,content}), verification_plan (array), risks (array). " | |
| "Write clean readable code with comments, errors handled, and tests where useful. Do not include markdown fences. " | |
| "Keep the response compact enough to be complete; typically create 1-4 files. Avoid external dependencies unless required. " | |
| "Do not include secrets, shell commands, malware, credential collection, destructive behavior, or automatic network exfiltration. " | |
| "All file paths must be project-relative.\n\nPROJECT: " + project + "\nREQUEST:\n" + spec[:9000] | |
| ) | |
| response = self._call_model("You are a senior software engineer. Draft code, but do not claim it was executed or tested.", prompt, 1600) | |
| return self._new_proposal(project, spec, response) | |
| def patch(self, project: str, rel: str, instruction: str) -> dict[str, Any]: | |
| path = self._project_file(project, rel) | |
| if path.stat().st_size > MAX_READ_BYTES: | |
| raise DevWorkbenchError("File is too large for a single patch proposal; split it into smaller modules first.") | |
| current = path.read_text(encoding="utf-8", errors="replace") | |
| prompt = ( | |
| "Return strict JSON only: {summary, files:[{path,content}], verification_plan:[...], risks:[...]}. " | |
| "Propose the complete updated contents for only the requested file. Preserve unrelated behavior and public interfaces. " | |
| "Do not claim the code was executed or tested. Do not add secrets or dangerous behavior.\n\n" | |
| f"PROJECT: {project}\nFILE: {rel}\nCHANGE REQUEST:\n{instruction[:6000]}\n\nCURRENT FILE:\n" | |
| f"{current[:MAX_READ_BYTES]}" | |
| ) | |
| response = self._call_model("You are a careful engineer modifying an existing codebase. Return JSON only.", prompt, 1600) | |
| proposal = self._new_proposal(project, f"Patch {rel}: {instruction}", response) | |
| expected = Path(rel.replace("\\", "/")).as_posix() | |
| if any(f["path"] != expected for f in self._load_proposal(proposal["proposal_id"]).get("files", [])): | |
| (self.proposals_root / f"{proposal['proposal_id']}.json").unlink(missing_ok=True) | |
| raise DevWorkbenchError("Patch response included a file other than the requested path; proposal discarded.") | |
| return proposal | |
| def debug(self, project: str, rel: str, error: str) -> dict[str, Any]: | |
| error = str(error or "").strip() | |
| if not error: | |
| raise DevWorkbenchError("Usage: dev debug <project>/<file.py> :: <error or failing behavior>") | |
| return self.patch(project, rel, "Debug this reported problem. Diagnose likely root cause, preserve other behavior, and add a regression test if the requested file structure makes that appropriate. Reported error/behavior:\n" + error) | |
| def _read_context(self, project: str, rel: str) -> tuple[Path, str]: | |
| path = self._project_file(project, rel) | |
| if path.stat().st_size > MAX_READ_BYTES: | |
| raise DevWorkbenchError(f"File is larger than the {MAX_READ_BYTES}-byte model context limit; inspect a smaller file or split it.") | |
| return path, path.read_text(encoding="utf-8", errors="replace") | |
| def explain(self, project: str, rel: str) -> str: | |
| _, content = self._read_context(project, rel) | |
| return self._call_model("You are a patient programming teacher. Explain only what the code supports; flag uncertainty.", | |
| f"Explain the file for a developer: purpose, control flow, important functions, dependencies, edge cases, and a simple example.\nPROJECT={project}\nFILE={rel}\n\nSOURCE:\n{content}", 1200) | |
| def review(self, project: str, rel: str) -> str: | |
| _, content = self._read_context(project, rel) | |
| return self._call_model("You are an independent code reviewer. Do not assume tests passed.", | |
| f"Review this file for correctness, security, reliability, readability and test gaps. Report findings by severity and line where possible. Do not edit the file and do not claim you executed it.\nPROJECT={project}\nFILE={rel}\n\nSOURCE:\n{content}", 1400) | |
| def _load_proposal(self, proposal_id: str) -> dict[str, Any]: | |
| if not re.fullmatch(r"P-[0-9]{8}-[0-9]{6}-[a-f0-9]{6}", str(proposal_id or "")): | |
| raise DevWorkbenchError("Malformed proposal ID.") | |
| path = (self.proposals_root / f"{proposal_id}.json").resolve() | |
| if not path.is_relative_to(self.proposals_root.resolve()) or not path.is_file(): | |
| raise DevWorkbenchError(f"Proposal {proposal_id!r} not found.") | |
| return json.loads(path.read_text(encoding="utf-8")) | |
| def proposals(self) -> list[dict[str, Any]]: | |
| rows = [] | |
| for path in sorted(self.proposals_root.glob("P-*.json"), key=lambda p: p.stat().st_mtime, reverse=True): | |
| try: | |
| rows.append(self._proposal_summary(json.loads(path.read_text(encoding="utf-8")))) | |
| except Exception: | |
| continue | |
| return rows[:50] | |
| def apply(self, proposal_id: str) -> dict[str, Any]: | |
| proposal = self._load_proposal(proposal_id) | |
| if proposal.get("status") != "pending_operator_apply": | |
| raise DevWorkbenchError(f"Proposal is not pending; current status={proposal.get('status')!r}.") | |
| project = self._project_dir(proposal["project"], must_exist=False) | |
| project.mkdir(parents=True, exist_ok=True) | |
| project = self._project_dir(proposal["project"], must_exist=True) | |
| backup_id = datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:6] | |
| backup_dir = self.backups_root / backup_id / proposal["project"] | |
| changed, created, errors = [], [], [] | |
| # Preflight all destinations before writing anything. | |
| destinations = [] | |
| for item in proposal["files"]: | |
| destination = self._project_file(proposal["project"], item["path"], must_exist=False) | |
| if destination.exists() and not destination.is_file(): | |
| raise DevWorkbenchError(f"Destination exists and is not a file: {item['path']}") | |
| destinations.append((item, destination)) | |
| try: | |
| for item, destination in destinations: | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| # Re-resolve after mkdir to guard against unexpected symlinks. | |
| destination = self._project_file(proposal["project"], item["path"], must_exist=False) | |
| if destination.exists(): | |
| backup_path = backup_dir / item["path"] | |
| backup_path.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(destination, backup_path) | |
| changed.append(item["path"]) | |
| else: | |
| created.append(item["path"]) | |
| temporary = destination.with_name(destination.name + ".tmp-" + uuid.uuid4().hex[:8]) | |
| temporary.write_text(item["content"], encoding="utf-8", newline="\n") | |
| os.replace(temporary, destination) | |
| except Exception as exc: | |
| errors.append(f"{type(exc).__name__}: {exc}") | |
| # Roll back already-written files, preserving an audit log. | |
| for rel in reversed(created): | |
| try: | |
| self._project_file(proposal["project"], rel, must_exist=False).unlink(missing_ok=True) | |
| except Exception: | |
| pass | |
| for rel in reversed(changed): | |
| try: | |
| bp = backup_dir / rel | |
| if bp.is_file(): | |
| dst = self._project_file(proposal["project"], rel, must_exist=False) | |
| dst.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(bp, dst) | |
| except Exception: | |
| pass | |
| proposal["status"] = "apply_failed_rolled_back" | |
| proposal["apply_error"] = errors[0] | |
| (self.proposals_root / f"{proposal_id}.json").write_text(json.dumps(proposal, ensure_ascii=False, indent=2), encoding="utf-8") | |
| raise DevWorkbenchError("Applying proposal failed; best-effort rollback was attempted. " + errors[0]) from exc | |
| proposal["status"] = "applied" | |
| proposal["applied_at"] = self._now() | |
| proposal["backup_dir"] = str(backup_dir) if changed else None | |
| (self.proposals_root / f"{proposal_id}.json").write_text(json.dumps(proposal, ensure_ascii=False, indent=2), encoding="utf-8") | |
| return {"status": "applied", "proposal_id": proposal_id, "project": proposal["project"], "created": created, | |
| "updated": changed, "backup_dir": str(backup_dir) if changed else None, | |
| "warning": "Files are now changed inside the isolated developer workspace only. Review the diff and run tests before using them elsewhere."} | |
| def files(self, project: str) -> list[dict[str, Any]]: | |
| base = self._project_dir(project) | |
| rows = [] | |
| for path in sorted(base.rglob("*")): | |
| if not path.is_file() or path.is_symlink(): | |
| continue | |
| resolved = path.resolve() | |
| if not resolved.is_relative_to(base.resolve()): | |
| continue | |
| rel = resolved.relative_to(base.resolve()).as_posix() | |
| if rel.endswith(".tmp") or ".tmp-" in rel: | |
| continue | |
| rows.append({"path": rel, "bytes": path.stat().st_size, "extension": path.suffix.lower()}) | |
| return rows[:500] | |
| def read(self, project: str, rel: str) -> str: | |
| path, text = self._read_context(project, rel) | |
| return f"FILE: {path.name} ({len(text.encode('utf-8'))} bytes)\n\n{text}" | |
| def test(self, project: str, compile_only: bool = False) -> dict[str, Any]: | |
| base = self._project_dir(project) | |
| python_files = [p for p in base.rglob("*.py") if p.is_file() and not p.is_symlink() and p.resolve().is_relative_to(base.resolve())] | |
| syntax_results = [] | |
| for path in python_files: | |
| try: | |
| if path.stat().st_size > MAX_FILE_BYTES: | |
| syntax_results.append({"file": path.relative_to(base).as_posix(), "status": "skipped", "reason": "file exceeds size limit"}) | |
| continue | |
| source = path.read_text(encoding="utf-8", errors="replace") | |
| compile(source, str(path), "exec", dont_inherit=True) | |
| syntax_results.append({"file": path.relative_to(base).as_posix(), "status": "passed"}) | |
| except (SyntaxError, UnicodeError, OSError) as exc: | |
| syntax_results.append({"file": path.relative_to(base).as_posix(), "status": "failed", "error": str(exc)}) | |
| syntax_ok = all(row["status"] == "passed" for row in syntax_results) | |
| report: dict[str, Any] = {"project": project, "created_at": self._now(), "phase": "syntax_only" if compile_only else "syntax_and_tests", | |
| "python_files": len(python_files), "syntax": syntax_results, "syntax_passed": syntax_ok, | |
| "tests": {"status": "not_run"}} | |
| if not syntax_ok or compile_only: | |
| report["status"] = "passed" if syntax_ok else "failed" | |
| else: | |
| test_files = [p for p in base.rglob("test*.py") if p.is_file() and not p.is_symlink() and p.resolve().is_relative_to(base.resolve())] | |
| test_files += [p for p in base.rglob("*_test.py") if p.is_file() and not p.is_symlink() and p.resolve().is_relative_to(base.resolve())] | |
| test_files = sorted(set(test_files)) | |
| if not test_files: | |
| report["status"] = "syntax_passed_tests_not_found" | |
| report["tests"] = {"status": "not_found", "message": "Python syntax passed but no test*.py or *_test.py files were found."} | |
| else: | |
| # Tests execute as the current OS user. No shell is used, and there is a timeout, | |
| # but this is not a security sandbox: only run code/tests you trust. | |
| runner = ( | |
| "import sys,unittest; sys.path.insert(0, '.'); " | |
| "suite=unittest.defaultTestLoader.discover('.', pattern='test*.py'); " | |
| "suite2=unittest.defaultTestLoader.discover('.', pattern='*_test.py'); " | |
| "suite.addTests(suite2); " | |
| "result=unittest.TextTestRunner(verbosity=2).run(suite); " | |
| "raise SystemExit(0 if result.wasSuccessful() else 1)" | |
| ) | |
| sensitive_markers = ("API_KEY", "TOKEN", "SECRET", "PASSWORD", "CREDENTIAL", "UNSLOTH", | |
| "OPENAI", "ANTHROPIC", "GOOGLE", "GEMINI", "AZURE", "AWS_", "GITHUB_") | |
| environment = {k: v for k, v in os.environ.items() | |
| if k.upper() not in {"PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "PYTHONINSPECT", "PYTHONUSERBASE"} | |
| and not any(marker in k.upper() for marker in sensitive_markers)} | |
| try: | |
| proc = subprocess.run([sys.executable, "-I", "-c", runner], cwd=str(base), env=environment, | |
| stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, | |
| timeout=self.test_timeout, shell=False, check=False) | |
| report["tests"] = {"status": "passed" if proc.returncode == 0 else "failed", "returncode": proc.returncode, | |
| "output": (proc.stdout or "")[-12000:], "timeout_seconds": self.test_timeout} | |
| report["status"] = "passed" if proc.returncode == 0 else "failed" | |
| except subprocess.TimeoutExpired as exc: | |
| output = exc.stdout or "" | |
| if isinstance(output, bytes): | |
| output = output.decode("utf-8", errors="replace") | |
| report["tests"] = {"status": "timeout", "timeout_seconds": self.test_timeout, "output": str(output)[-12000:]} | |
| report["status"] = "failed_timeout" | |
| out_path = self.meta_root / f"test_{self._project_name(project)}_{datetime.now().strftime('%Y%m%d-%H%M%S')}.json" | |
| out_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") | |
| report["report_path"] = str(out_path) | |
| return report | |
| def status(self) -> dict[str, Any]: | |
| projects = [] | |
| for path in sorted(self.projects_root.iterdir()) if self.projects_root.exists() else []: | |
| if path.is_dir() and not path.is_symlink() and path.resolve().is_relative_to(self.projects_root.resolve()): | |
| try: | |
| projects.append({"name": path.name, "files": len(self.files(path.name)), "updated_at": datetime.fromtimestamp(path.stat().st_mtime, timezone.utc).isoformat()}) | |
| except Exception: | |
| continue | |
| return {"component": "developer_workbench", "status": "ready", "workspace": str(self.root), "projects": projects, | |
| "pending_proposals": [p for p in self.proposals() if p.get("status") == "pending_operator_apply"], | |
| "model_backend_configured": callable(self.llm_call), | |
| "capabilities": ["project planning", "code draft proposals", "code explanation", "code review", "debug patch proposals", "syntax checks", "explicit trusted test runs", "file backups"], | |
| "boundaries": ["model drafts are not applied until `dev apply`", "no arbitrary shell command interface", "tests run as the current OS user and are not a security sandbox", "workspace is separate from the live Baby Brain source"]} | |
| def dispatch(self, payload: str) -> Any: | |
| payload = str(payload or "").strip() | |
| action, _, arg = payload.partition(" ") | |
| action, arg = action.lower().strip(), arg.strip() | |
| if action in {"", "help", "--help"}: | |
| return {"commands": [ | |
| "dev status", "dev plan <goal>", "dev create <project-name> :: <spec>", | |
| "dev patch <project>/<file> :: <change request>", "dev debug <project>/<file> :: <error>", | |
| "dev explain <project>/<file>", "dev review <project>/<file>", "dev apply <proposal-id>", | |
| "dev proposals", "dev files <project>", "dev read <project>/<file>", | |
| "dev test <project> [--compile-only]"], | |
| "note": "Model drafts are not applied until explicitly approved with dev apply. Tests run as your OS user; use only trusted code."} | |
| if action == "status": | |
| return self.status() | |
| if action == "plan": | |
| return self.plan(arg) | |
| if action == "proposals": | |
| return self.proposals() | |
| if action == "create": | |
| if "::" not in arg: raise DevWorkbenchError("Usage: dev create <project-name> :: <spec>") | |
| project, spec = arg.split("::", 1) | |
| return self.create(project.strip(), spec.strip()) | |
| if action in {"patch", "debug"}: | |
| if "::" not in arg: raise DevWorkbenchError(f"Usage: dev {action} <project>/<file> :: <change/error>") | |
| target, instruction = arg.split("::", 1) | |
| target = target.strip().replace("\\", "/") | |
| if "/" not in target: raise DevWorkbenchError("Target must be <project>/<project-relative-file>.") | |
| project, rel = target.split("/", 1) | |
| return self.patch(project, rel, instruction.strip()) if action == "patch" else self.debug(project, rel, instruction.strip()) | |
| if action in {"explain", "review", "read"}: | |
| target = arg.replace("\\", "/") | |
| if "/" not in target: raise DevWorkbenchError(f"Usage: dev {action} <project>/<project-relative-file>") | |
| project, rel = target.split("/", 1) | |
| return self.read(project, rel) if action == "read" else (self.explain(project, rel) if action == "explain" else self.review(project, rel)) | |
| if action == "apply": | |
| if not arg: raise DevWorkbenchError("Usage: dev apply <proposal-id>") | |
| return self.apply(arg) | |
| if action == "files": | |
| if not arg: raise DevWorkbenchError("Usage: dev files <project>") | |
| return self.files(arg) | |
| if action == "test": | |
| if not arg: raise DevWorkbenchError("Usage: dev test <project> [--compile-only]") | |
| fields = arg.split() | |
| return self.test(fields[0], compile_only="--compile-only" in fields[1:]) | |
| raise DevWorkbenchError("Unknown dev command. Run `dev help`.") | |