Spaces:
Running
Running
Deploy canonical runtime 4af0011 from GitHub Actions
Browse filesFiles changed (7)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Bounded controls for autonomous research execution.
This module deliberately controls orchestration only. It cannot weaken safetypolicies, evaluation thresholds, credential rules or ledger admission gates."""from __future__ import annotations
import jsonimport osimport timefrom contextlib import contextmanagerfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Iterator
STOP_EXIT_CODE = 78
def _truthy(value: str | None, default: bool = False) -> bool: if value is None or not value.strip(): return default return value.strip().lower() in {"1", "true", "yes", "on"}
def autonomy_enabled() -> bool: return _truthy(os.getenv("AUTONOMY_ENABLED"), default=True)
def emergency_stop_active() -> bool: return _truthy(os.getenv("EMERGENCY_STOP"), default=False)
def _state_path(root: Path) -> Path: return root / "knowledge_base" / "autonomy_control.json"
def record_event(root: Path, event: str, **details: object) -> None: path = _state_path(root) path.parent.mkdir(parents=True, exist_ok=True) payload = { "updated_at": datetime.now(timezone.utc).isoformat(), "event": event, "details": details, } path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
@contextmanagerdef single_run_lock(root: Path) -> Iterator[None]: """Acquire a process lock without leaving a stale lock after normal exit.""" path = root / "knowledge_base" / ".autonomy.lock" path.parent.mkdir(parents=True, exist_ok=True) try: fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) except FileExistsError as exc: raise RuntimeError("another autonomous run is already active") from exc try: os.write(fd, str(os.getpid()).encode("ascii")) os.close(fd) record_event(root, "started", pid=os.getpid()) yield finally: try: path.unlink() except FileNotFoundError: pass record_event(root, "finished", pid=os.getpid())
def guard(root: Path) -> int: if not autonomy_enabled(): record_event(root, "disabled") return STOP_EXIT_CODE if emergency_stop_active(): record_event(root, "emergency_stop") return STOP_EXIT_CODE return 010 unmodified lines1112131415161718195 unmodified lines25262728293031323310 unmodified lines"scientific_accuracy": 92.0,"novelty_score": 78.0,"usefulness_score": 85.0,"created": "2026-08-19T23:02:39.313866"},"created": "2026-08-19T23:02:39.313872"},"1d94037a7442ae1b": {"id": "1d94037a7442ae1b",5 unmodified lines"scientific_accuracy": 94.0,"novelty_score": 82.0,"usefulness_score": 88.0,"created": "2026-08-19T23:02:39.313878"},"created": "2026-08-19T23:02:39.313881"}},"relationships": [],10 unmodified lines1112131415161718195 unmodified lines25262728293031323310 unmodified lines"scientific_accuracy": 92.0,"novelty_score": 78.0,"usefulness_score": 85.0,"created": "2026-08-19T23:18:44.887396"},"created": "2026-08-19T23:18:44.887401"},"1d94037a7442ae1b": {"id": "1d94037a7442ae1b",5 unmodified lines"scientific_accuracy": 94.0,"novelty_score": 82.0,"usefulness_score": 88.0,"created": "2026-08-19T23:18:44.887407"},"created": "2026-08-19T23:18:44.887415"}},"relationships": [],
1 unmodified line2345678910111213141516171819202122232425262728293031323 unmodified lines36373839401 unmodified line"chain": [{"index": 0,"timestamp": "2026-08-19T23:02:41.256836","transactions": [{"tx_id": "8d50babf9315426ae6f799ea","sender": "genesis","recipient": "system_treasury","amount": 0.0,"timestamp": "2026-08-19T23:02:41.256797","metadata": {"note": "Nuclear Intelligence Genesis Block v1.0.0","version": "1.0.0","timestamp": "2026-08-19T23:02:41.256791","difficulty": 3,"system": "Nuclear Intelligence Virtual Blockchain"},"signature": "79d4a76d904a8d43865b72cc2cf419264a887d543c1897112e05675aa27b4e88b4a96f107856b63723d99b8d51c20357","nonce": 0,"status": "confirmed"}],"merkle_root": "896fe285d4dda7087c04990371b1888ee4b0a4f0a2af3b2053fb96f0012be498","previous_hash": "0000000000000000000000000000000000000000000000000000000000000000","nonce": 689,"hash": "000bd36bdd9118245115e28121171a3069447672b6bea2491415999c6d1e6aa9","difficulty": 3,"miner": "genesis","reward": 1.0,"tx_count": 1,3 unmodified lines"difficulty": 3,"nes_supply": 0.0,"total_transactions": 0,"saved_at": "2026-08-19T23:02:41.261056"}1 unmodified line2345678910111213141516171819202122232425262728293031323 unmodified lines36373839401 unmodified line"chain": [{"index": 0,"timestamp": "2026-08-19T23:18:46.449901","transactions": [{"tx_id": "d265bc60f03bf60cacb513b4","sender": "genesis","recipient": "system_treasury","amount": 0.0,"timestamp": "2026-08-19T23:18:46.449875","metadata": {"note": "Nuclear Intelligence Genesis Block v1.0.0","version": "1.0.0","timestamp": "2026-08-19T23:18:46.449870","difficulty": 3,"system": "Nuclear Intelligence Virtual Blockchain"},"signature": "b6a4d37283f4753590881c1464de45cfa3ca15f544f5fb4a659099b5c750475b6ac021583fa63fcae30cbd5680832150","nonce": 0,"status": "confirmed"}],"merkle_root": "0ba9a8ed95b7f2b6cd529f3d09684bace87905261e1c4efab66800b2120e6b7a","previous_hash": "0000000000000000000000000000000000000000000000000000000000000000","nonce": 1001,"hash": "031781fb07a426a9cfaf9332c7dde1d1a4d74e5b57f7c245394415a23d0c1eb6","difficulty": 1,"miner": "genesis","reward": 1.0,"tx_count": 1,3 unmodified lines"difficulty": 3,"nes_supply": 0.0,"total_transactions": 0,"saved_at": "2026-08-19T23:18:46.455631"}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""Create a reviewable developer queue from canonical cycle proposals.
The agent is intentionally proposal-first: it may prepare documentation andquality-work artifacts, but it never edits production code or merges a change."""from __future__ import annotations
import jsonimport osfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
MAX_REPORTS = 100MAX_PROPOSALS = 50
def _safe(value: Any, limit: int = 500) -> str: text = " ".join(str(value or "").split()) return text[:limit]
def collect(root: Path) -> list[dict[str, str]]: proposals: list[dict[str, str]] = [] reports = sorted((root / "reports").glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True) for report_path in reports[:MAX_REPORTS]: try: report = json.loads(report_path.read_text(encoding="utf-8")) except (OSError, ValueError): continue governance = report.get("governance") if isinstance(report, dict) else {} candidates = governance.get("open_proposals", []) if isinstance(governance, dict) else [] if not isinstance(candidates, list): continue for item in candidates: if not isinstance(item, dict): continue proposals.append({ "title": _safe(item.get("title", "Untitled proposal"), 180), "rationale": _safe(item.get("rationale", item.get("reason", ""))), "impact": _safe(item.get("impact_area", item.get("area", "quality")), 120), "source": report_path.name, }) if len(proposals) >= MAX_PROPOSALS: return proposals return proposals
def render(proposals: list[dict[str, str]]) -> str: now = datetime.now(timezone.utc).isoformat() lines = [ "# Autonomous Developer Queue", "", f"Generated at `{now}`.", "", "> This is a review queue, not an authorization to change production code. Every implementation must pass CI and receive human review through a pull request.", "", ] if not proposals: lines.append("No new reviewable proposals were found.") return "\n".join(lines) + "\n" lines.extend(["| Priority | Proposal | Impact | Source |", "|---:|---|---|---|"]) for index, proposal in enumerate(proposals, start=1): title = proposal["title"].replace("|", "-") impact = proposal["impact"].replace("|", "-") source = proposal["source"].replace("|", "-") lines.append(f"| {index} | {title} | {impact} | `{source}` |") if proposal["rationale"]: lines.append(f"| | Rationale: {proposal['rationale'].replace('|', '-') } | | |") lines.extend([ "", "## Required review gates", "", "1. Confirm the proposal is within peaceful civilian-energy scope.", "2. Add or update deterministic tests before implementation.", "3. Run safety, health, compile and regression checks.", "4. Require human approval before merge or any external write.", ]) return "\n".join(lines) + "\n"
def main() -> int: root = Path(os.getenv("NI_PROJECT_ROOT", Path.cwd())).resolve() output = root / "reports" / "developer_queue.md" output.parent.mkdir(parents=True, exist_ok=True) output.write_text(render(collect(root)), encoding="utf-8") print(output) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142"""Run one bounded autonomous research tick.
The scheduler calls this script. It performs one canonical cycle only and exits;it does not become an unbounded daemon and it never publishes secrets."""from __future__ import annotations
import osimport sysfrom pathlib import Path
from core.autonomy_control import guard, record_event, single_run_lockfrom core.runtime import build_runtime
def main() -> int: root = Path(os.getenv("NI_PROJECT_ROOT", Path.cwd())).resolve() stop_code = guard(root) if stop_code: return stop_code try: with single_run_lock(root): _, loop, _, settings = build_runtime() result = loop.run_cycle(developer_mode=settings.developer_mode) payload = result.to_dict() record_event( root, "cycle_completed", cycle_id=payload.get("cycle_id"), minted=bool(payload.get("minted")), provider=payload.get("answer", {}).get("provider"), ) print(payload.get("cycle_id", "cycle-complete")) return 0 except Exception as exc: record_event(root, "cycle_failed", error_type=type(exc).__name__) print("autonomous cycle failed safely", file=sys.stderr) return 1
if __name__ == "__main__": raise SystemExit(main())__pycache__/app.cpython-311.pyc
__pycache__/core_hf.cpython-311.pyc
core/autonomy_control.pyAdded+78
knowledge_base/knowledge_graph.json+4-4
knowledge_base/virtual_ledger.json+10-10
scripts/autonomous_developer.pyAdded+93
scripts/autonomy_tick.pyAdded+42