from __future__ import annotations
import logging
import json
import re
from typing import Dict, Any, Tuple, Optional

class NextStatePredictor:
	"""Next-state predictor for world model rollouts.

	Predicts observation changes and side effects from actions:
	- DOM: navigation, form states, click effects
	- CLI: commands, working directory, output types
	- Generic: action metadata and timestamps
	"""

	def predict_next(self, obs: Dict[str, Any], action: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
		try:
			obs_next: Dict[str, Any] = dict(obs or {})
			effects: Dict[str, Any] = {}


from __future__ import annotations
import logging

from typing import Any, Dict

# Minimal schema definition for WM dataset examples
# An example row looks like:
# {
#   "input": {"obs": str, "plan": str, "action": str, "effects": str},
#   "success": int (0/1),
#   "risk": float [0..1]
# }
SCHEMA: Dict[str, Any] = {
	"type": "object",
	"required": ["input", "success", "risk"],
	"properties": {
		"input": {
			"type": "object",
			"required": ["obs", "plan", "action"],
			"properties": {
				"obs": {"type": "string"},


from __future__ import annotations
import logging

from typing import Dict, Any, List, Optional, Tuple
from dataclasses import dataclass
from pathlib import Path

from .next_state import NextStatePredictor
from .api import WorldModelPrior

@dataclass
class RolloutConfig:
	"""Configuration for rollout simulation."""
	horizon: int = 3
	max_risk_threshold: float = 0.8
	min_success_prob: float = 0.2
	enable_early_stopping: bool = True
	track_state_changes: bool = True


from __future__ import annotations
import logging

from dataclasses import dataclass
from typing import Dict, Any, Optional, List

@dataclass
class RewardConfig:
	"""Configuration for reward shaping."""
	# Base rewards
	success_reward: float = 1.0
	failure_penalty: float = -0.5

	# Risk-based adjustments
	risk_penalty_factor: float = 0.3
	high_risk_threshold: float = 0.7

	# Complexity penalties
	file_count_penalty: float = 0.1
	loc_penalty: float = 0.05


import logging
from pathlib import Path
from typing import Optional
import subprocess

class Updater:
	def __init__(self, repo_root: Path, fast: bool = False) -> None:
		self.repo_root = repo_root
		self.fast = bool(fast)

	def _run(self, *args: str) -> int:
		cmd = ["make", "-C", str(self.repo_root)] + list(args)
		print("[Updater]", " ".join(cmd))
		return subprocess.call(cmd)

	def run(self) -> None:
		# 1) Verify traces (CLI + DOM)
		self._run("verify-hf-fast" if self.fast else "verify-hf")
		self._run("web-dom-verify")
		# 2) Build IL and merge repairs
		self._run("actuator-il")


from __future__ import annotations
import logging

from pathlib import Path
from typing import Dict, Optional

def pick_from_bank(root: Path, bank_name: Optional[str]) -> Dict[str, str]:
	"""Return an adapter mapping for roles (e.g., {"planner": dir, "verifier": dir}) from a named bank.

	If bank_name is None or missing, returns an empty mapping.
	"""
	if not bank_name:
		return {}
	try:
		from agi_dw.core.memory.service import get_adapter_bank  # type: ignore
		return get_adapter_bank(root, bank_name)
	except Exception:
		return {}


import logging
from typing import Any, Dict, List, Optional
import os

_MODEL_CACHE: Dict[str, "HFClient"] = {}

class HFClient:
	def __init__(self, model_id: str = "meta-llama/Llama-3.1-8B-Instruct", device_map: Optional[str] = "auto", torch_dtype: Optional[str] = None) -> None:
		try:
			import torch  # type: ignore
			from transformers import AutoModelForCausalLM, AutoTokenizer  # type: ignore
		except Exception as e:
			raise RuntimeError("transformers/torch not installed: pip install -r requirements.txt") from e
		self.model_id = model_id
		self.tokenizer = AutoTokenizer.from_pretrained(model_id)
		# Allow env overrides and torchrun rank binding
		env_device_map = os.environ.get("HF_DEVICE_MAP") or device_map
		try:
			# If running under torchrun and device_map wasn't explicitly set, bind to this rank's GPU
			if (env_device_map is None or str(env_device_map).strip().lower() == "auto") and os.environ.get("LOCAL_RANK") is not None:


from __future__ import annotations
import logging
import os

import threading
from pathlib import Path
from typing import Dict, Optional, Tuple, Any

class AdapterCache:
	"""
	Thread-safe cache for loading/retrieving LoRA/PEFT adapters on demand.
	Maintains a mapping (base_model_id, adapter_dir) -> (tokenizer, model).
	Caller owns inference usage; this class does not schedule devices.
	"""

	_lock = threading.Lock()
	_cache: Dict[Tuple[str, str], Tuple[Any, Any]] = {}

	@classmethod
	def get(cls, base_model: str, adapter_dir: str) -> Tuple[Any, Any]:


import logging
from typing import Any, Dict, Optional, List, Tuple
from pathlib import Path
from datetime import datetime

from agi_dw.core.llm.hf_client import HFClient
from agi_dw.core.utils.prompt_logger import PromptLogger, get_prompt_logger  # type: ignore
from agi_dw.core.ops.tracing import trace_span, meter_cost  # type: ignore
from agi_dw.tools.artifact_cache import is_enabled as cache_enabled, get_cached_text as cache_get, set_cached_text as cache_set  # type: ignore

try:
	import yaml  # type: ignore
except Exception:
	yaml = None

# Reuse actuator parsing/coercion to salvage slightly malformed outputs
try:
	from agi_dw.core.actuator.parse import coerce_flat_yaml  # type: ignore
except Exception:
	def coerce_flat_yaml(_: str) -> Dict[str, Any]:  # fallback no-op
		return {}


from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Optional

@dataclass
class VerifierServiceConfig:
	model: str
	backend: str = "hf"
	adapter_dir: Optional[str] = None
	adapter_bank: Optional[str] = None
	structured_mode: str = "json"
	timeout_sec: int = 30
	strict: bool = False
	calibrate: bool = False
	calib_model: Optional[str] = None
	log_prompts: bool = False


from __future__ import annotations
import logging

from typing import Dict, Any

class AgentRole:
	def act(self, context: Dict[str, Any]) -> Dict[str, Any]:  # noqa: D401
		"""Perform role-specific action given a context and return a message."""
		raise NotImplementedError

class WebBrowserRole(AgentRole):
	def __init__(self, t5_model_path: str, il_path: str | None = None) -> None:
		self.t5_model_path = t5_model_path
		self.il_path = il_path

	def act(self, context: Dict[str, Any]) -> Dict[str, Any]:
		from agi_dw.core.actuator.service import ActuatorConfig, RouterExtras, RepairConfig, select_action  # type: ignore
		obs = context.get("obs", {})
		plan = context.get("plan", {})


from typing import Dict, List
import math
import torch
import torch.nn as nn

from .curvature import update_curvature_diag, sophia_update_with_curv
from .bandit import UCB1

class MixtureMetaOptGrouped:
    def __init__(self, model: nn.Module, param_groups: List[Dict], gate: nn.Module, base_lr: float = 3e-4, base_wd: float = 0.01, device: str = "cuda"):
        self.model = model
        self.groups = param_groups
        self.gate = gate.to(device)
        self.base_lr = base_lr
        self.base_wd = base_wd
        self.device = device

        # per-param states
        self.st_adam: Dict[int, Dict[str, torch.Tensor]] = {}
        self.st_lion: Dict[int, Dict[str, torch.Tensor]] = {}


from typing import List, Dict, Any, Set
import torch.nn as nn

def make_param_groups(transformer_model: nn.Module) -> List[Dict[str, Any]]:
    """
    Build parameter groups for layer-wise gating.
    - Embeddings
    - Per transformer block (GPT-style `.h` or common `.layers`)
    - Output head
    - Misc (fallback)
    """
    groups: List[Dict[str, Any]] = []

    # Embeddings
    emb_params = []
    for n, p in transformer_model.named_parameters():
        if ("embed" in n) or ("wte" in n) or ("wpe" in n) or ("embeddings" in n):
            emb_params.append(p)
    if emb_params:
        groups.append({"name": "emb", "params": emb_params})


import torch
from typing import Dict

@torch.no_grad()
def update_curvature_diag(model: torch.nn.Module, curv_state: Dict[int, torch.Tensor], beta: float = 0.99, mode: str = "fisher", probe_prob: float = 0.05) -> None:
    """
    Maintain a diagonal curvature proxy per-parameter via EMA.

    - mode="fisher": update with on-policy gradient squares (Fisher diagonal proxy)
    - mode="hutch": occasionally nudge scale using a Hutchinson-like probe (stabilizer)
    """
    for i, p in enumerate(model.parameters()):
        if p.grad is None:
            continue
        g = p.grad.detach()
        h = curv_state.setdefault(id(p), torch.zeros_like(p))
        # Fisher diagonal EMA
        h.mul_(beta).addcmul_(g, g, value=(1.0 - beta))

        # Optional: cheap Hutchinson probe stabilizer (no closure to recompute grads here)


import math
from typing import List

class UCB1:
    def __init__(self, n_arms: int = 3):
        self.n: List[int] = [0] * n_arms
        self.value: List[float] = [0.0] * n_arms
        self.total: int = 0

    def select(self, c: float = 2.0) -> int:
        self.total += 1
        for a in range(len(self.n)):
            if self.n[a] == 0:
                return a
        ucb = [self.value[a] + c * math.sqrt(max(1.0, math.log(self.total)) / self.n[a]) for a in range(len(self.n))]
        return max(range(len(self.n)), key=lambda a: ucb[a])

    def update(self, arm: int, reward: float) -> None:
        self.n[arm] += 1
        n = self.n[arm]


import torch
import torch.nn as nn

class GateNetGrouped(nn.Module):
    def __init__(self, n_groups: int, hidden: int = 128):
        super().__init__()
        self.group_embed = nn.Embedding(n_groups, 16)
        self.mlp = nn.Sequential(
            nn.Linear(6 + 16, hidden), nn.GELU(),
            nn.Linear(hidden, hidden), nn.GELU(),
        )
        self.mix_head = nn.Linear(hidden, 3)  # AdamW, Lion, Sophia
        self.lrs_head = nn.Linear(hidden, 1)
        self.wds_head = nn.Linear(hidden, 1)

    def forward(self, feats: torch.Tensor, group_idx: torch.Tensor):
        # feats: [B, 6], group_idx: [B]
        ge = self.group_embed(group_idx)  # [B, 16]
        z = torch.cat([feats, ge], dim=-1)
        h = self.mlp(z)


from __future__ import annotations
import torch
from torch.nn.utils import clip_grad_norm_
from typing import Any, Dict

try:
    from transformers import Trainer  # type: ignore
except Exception:  # pragma: no cover
    Trainer = object  # type: ignore

from .group_utils import make_param_groups
from .gate_grouped import GateNetGrouped
from .metaopt_grouped import MixtureMetaOptGrouped

class MetaOptTrainer(Trainer):  # type: ignore
    """
    HuggingFace Trainer subclass that applies MixtureMetaOptGrouped instead of optimizer.step.
    - Computes loss and backward via standard Trainer infra (Accelerate-aware)
    - Clips grads, then calls meta-optimizer step
    - Skips the regular optimizer step when enabled


from .curvature import update_curvature_diag, sophia_update_with_curv  # noqa: F401
from .gate_grouped import GateNetGrouped  # noqa: F401
from .bandit import UCB1  # noqa: F401
from .metaopt_grouped import MixtureMetaOptGrouped  # noqa: F401
from .meta_reinforce import short_unroll_reinforce  # noqa: F401


import copy
import torch
import torch.nn.functional as F
from torch.nn.utils import clip_grad_norm_
from typing import Callable, Dict, Any

def clone_model_for_unroll(model: torch.nn.Module) -> torch.nn.Module:
    shadow = copy.deepcopy(model)
    for p in shadow.parameters():
        p.requires_grad_(True)
    return shadow

@torch.no_grad()
def _adamw_single(p: torch.Tensor, g: torch.Tensor, st: Dict[str, torch.Tensor], lr: float, wd: float) -> None:
    m = st.setdefault("m", torch.zeros_like(p))
    v = st.setdefault("v", torch.zeros_like(p))
    t = st.setdefault("t", 0) + 1
    st["t"] = t
    m.mul_(0.9).add_(g, alpha=0.1)


import logging
import json
import re
from typing import Any, Dict, List

try:
	import yaml  # type: ignore
except Exception:
	yaml = None

def parse_yaml_or_json(text: str) -> Dict[str, Any]:
	if yaml is not None:
		try:
			y = yaml.safe_load(text)
			if isinstance(y, dict):
				return y
		except Exception:
			pass
	text = text.strip()
	if text.startswith("{") and text.endswith("}"):


from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Optional, Tuple

from agi_dw.core.ops.tracing import trace_span  # type: ignore
from agi_dw.core.actuator.t5_actuator import ActuatorT5Predictor
from agi_dw.core.actuator.il_baseline import ActuatorILNearestNeighbor
from agi_dw.core.actuator.template_actuator import TemplateActuator
from agi_dw.core.actuator.two_head import (
	TwoHeadActuator,
	HeuristicToolClassifier,
	HeuristicSlotFiller,
	default_cli_templates,
)
from agi_dw.core.actuator.router import extract_router_features, get_task_success_threshold  # type: ignore
from agi_dw.core.actuator.parse import repair_cli_action, repair_dom_action

@dataclass


import logging
import json
from typing import Any, Dict

class TemplateActuator:
	def predict_action(self, obs: Dict[str, Any], plan: Dict[str, Any]) -> Dict[str, Any]:
		kind = (obs or {}).get("kind")
		content = ((obs or {}).get("content") or "").lower()
		cwd = ((obs or {}).get("meta") or {}).get("cwd", "")
		if kind == "cli":
			if content.startswith("count file lines"):
				return {"tool": "cli.run", "args": {"argv": ["wc", "-l", "docs/a.txt"], "cwd": cwd}}
			if content.startswith("count words"):
				return {"tool": "cli.run", "args": {"argv": ["wc", "-w", "docs/a.txt"], "cwd": cwd}}
			if content.startswith("count chars"):
				return {"tool": "cli.run", "args": {"argv": ["wc", "-m", "docs/a.txt"], "cwd": cwd}}
			if content.startswith("grep -i info"):
				return {"tool": "cli.run", "args": {"argv": ["grep", "-i", "info", "logs/app.log"], "cwd": cwd}}
			if content.startswith("grep error"):
				return {"tool": "cli.run", "args": {"argv": ["grep", "-n", "ERROR", "logs/app.log"], "cwd": cwd}}


import logging
import json
from pathlib import Path
from typing import Any, Dict, List, Tuple

from agi_dw.core.actuator.parse import parse_yaml_or_json, coerce_flat_yaml

class ActuatorILNearestNeighbor:
	def __init__(self, dataset_path: str) -> None:
		self.examples: List[Tuple[str, str]] = []  # (input_text, output_text)
		p = Path(dataset_path)
		if not p.exists():
			raise FileNotFoundError(f"IL dataset not found: {dataset_path}")
		for line in p.read_text(encoding="utf-8").splitlines():
			if not line.strip():
				continue
			obj = json.loads(line)
			self.examples.append((obj["input"], obj["output"]))
		if not self.examples:
			raise ValueError("IL dataset is empty")


import logging
from typing import List, Set, Dict, Optional
from transformers import LogitsProcessor
import torch
import re

class JsonSchemaLogitsProcessor(LogitsProcessor):
	"""
	Minimal schema-aware constrained decoding for JSON actions.
	Phase-1 structure:
	  {"tool": "<wc|grep|head|tail>", "args": {"argv": ["<string>", ...], "cwd": "<string>"}}

	Tiny JSON FSM + token masking.
	Allows only:
	  - structural tokens: { } [ ] : , "
	  - keys: "tool","args","argv","cwd"
	  - tool strings: "wc","grep","head","tail"
	  - common flags: "-l","-w","-m","-n","-c","-i"
	  - any quoted strings inside argv/cwd (we only gate the start of strings)
	Extend tools/flags via constructor sets.


import logging
from dataclasses import dataclass
from typing import Dict, Optional, List
from pathlib import Path
import re
import os
import fnmatch

@dataclass
class PatchAction:
	patch: str  # unified diff text
	cwd: Optional[str] = None

class PatchActuator:
	"""
	Unified-diff patch actuator.
	Applies unified diffs in a repo-agnostic sandbox/cwd with dry-run and safety validation.
	"""
	def __init__(self) -> None:


import logging
import json
from pathlib import Path
from typing import Any, Dict

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, LogitsProcessorList, NoBadWordsLogitsProcessor, RepetitionPenaltyLogitsProcessor
import torch
import re

from agi_dw.core.actuator.parse import parse_yaml_or_json, coerce_flat_yaml, parse_dom_pred_text
from agi_dw.core.actuator.json_constraints import JsonSchemaLogitsProcessor, DomJsonLogitsProcessor

CLI_INSTRUCTION = (
	'Actuator task: Return ONLY the CLI argv as a single space-separated string. '
	'Example: wc -l docs/a.txt. No quotes, no explanations, no extra text. Input follows:\n'
)

DOM_INSTRUCTION = (
	'DOM task: Return ONLY two tokens: the URL and the CSS selector, separated by a single space. '
	'Example: https://example.com h1. No quotes, no explanations, no extra text. Input follows:\n'


from __future__ import annotations

import logging
import json
from typing import Any, Dict, List, Optional
import math

def extract_router_features(obs: Dict[str, Any], plan: Dict[str, Any], extras: Optional[Dict[str, Any]] = None) -> Dict[str, float]:
	features: Dict[str, float] = {}
	plan_text = json.dumps(plan, ensure_ascii=False) if not isinstance(plan, str) else plan
	features["plan_len"] = float(len(plan_text))
	# Token stats
	tokens: List[str] = str(plan_text).split()
	features["plan_ws_tokens"] = float(len(tokens))
	unique_tokens = len(set(tokens)) if tokens else 0
	features["plan_unique_tokens"] = float(unique_tokens)
	# Simple token entropy over whitespace tokens
	if tokens:
		from collections import Counter
		cnt = Counter(tokens)


import logging
from dataclasses import dataclass
from typing import List, Dict, Optional

@dataclass
class Action:
	tool: str
	args: Dict

class TwoHeadActuator:
	"""
	Head-1: classify tool (wc|grep|head|tail).
	Head-2: choose argv template + fill slots {path,pattern,n}.
	"""

	def __init__(self, clf, slot_model, templates: Dict[str, List[str]]):
		self.clf = clf
		self.slot_model = slot_model
		self.templates = templates


from __future__ import annotations

import logging
import json
from pathlib import Path
from typing import Any, Dict, Optional

def _safe(val: Any) -> Any:
	try:
		json.dumps(val, ensure_ascii=False)
		return val
	except Exception:
		return str(val)

def code_patch_apply(repo_dir: str, args: Dict[str, Any]) -> Dict[str, Any]:
	from agi_dw.core.actuator.service import apply_code_patch  # type: ignore

	diff_text = str(args.get("diff", ""))
	branch = str(args.get("branch_name", "")) or None


import logging
import os
from pathlib import Path
from typing import Any, Dict

try:
	import yaml  # type: ignore
except Exception as e:
	yaml = None

DEFAULT_PATH = Path(__file__).resolve().parents[2] / "config" / "default.yaml"

def load_config(path: str | None = None) -> Dict[str, Any]:
	if yaml is None:
		raise RuntimeError("pyyaml not installed. pip install pyyaml")
	file_path = Path(path) if path else DEFAULT_PATH
	cfg: Dict[str, Any] = {}
	if file_path.exists():
		with open(file_path, "r", encoding="utf-8") as f:


from __future__ import annotations
import logging

from dataclasses import dataclass
from typing import Dict, List, Literal, TypedDict

Decision = Literal["approved", "denied", "modified", "deferred", "expired"]

class ActionPayload(TypedDict, total=False):
	id: str
	ts: str
	actor: str
	kind: Literal["code.patch", "cli.op"]
	preview_path: str
	risk: float
	allowlist_hit: bool
	files: List[str]
	added: int
	deleted: int


from __future__ import annotations

import logging
import json
import time
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Any, Dict, List, Optional
from datetime import datetime, timezone

@dataclass
class ApprovalItem:
	id: str
	ts: str
	status: str  # pending | approved | denied | modified | deferred
	kind: str  # code.patch | cli.op
	preview_path: str
	repo: str
	meta: Dict[str, Any]


from __future__ import annotations

import logging
import hashlib
import json
from dataclasses import dataclass, asdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict

@dataclass
class AuditRecord:
	ts: str
	action: str
	actor: str
	data: Dict[str, Any]
	prev_hash: str
	hash: str


from __future__ import annotations

import logging
from pathlib import Path
from typing import Dict, Any
import json
from agi_dw.tools.redaction import redact_text

def render_patch_preview(repo_dir: str | Path, diff_text: str, policy_meta: Dict[str, Any]) -> str:
	lines = []
	lines.append("=== PATCH PREVIEW ===")
	lines.append(f"repo: {Path(repo_dir).resolve()}")
	try:
		files = policy_meta.get("files") or []
		added = int(policy_meta.get("added", 0))
		deleted = int(policy_meta.get("deleted", 0))
		lines.append(f"files: {len(files)}")
		for fp in (files[:20] if isinstance(files, list) else []):
			lines.append(f"  - {fp}")
		lines.append(f"churn: +{added} / -{deleted}")


from __future__ import annotations
import logging

import hashlib
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Tuple, Any

import json

APPROVAL_DECISIONS = {"approved", "denied", "modified", "deferred", "expired"}

def _sanitize_diff_for_hash(diff_text: str) -> str:
	"""Keep only stable, schema-relevant lines for signature hashing."""
	kept: List[str] = []
	for line in (diff_text or "").splitlines():
		if line.startswith("diff --git") or line.startswith("index ") or line.startswith("--- ") or line.startswith("+++ ") or line.startswith("@@ "):
			kept.append(line)
		elif line.startswith("+") or line.startswith("-") or line.startswith(" "):


from __future__ import annotations

from typing import Any, Dict, Optional

from agi_dw.bench.web_dom.runner import fetch_text  # type: ignore

def dom_assert(url: str, selector: str, props: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
	"""Assert DOM properties for a selector on a URL.

	Currently supports matching substring of text via props={"text_contains": "..."}.
	Returns a report dict with fields: ok, url, selector, text, reason.
	"""
	res = fetch_text(url, selector)
	text = str(res.get("text", ""))
	ok = True
	reason = ""
	if props and "text_contains" in props:
		exp = str(props.get("text_contains", ""))
		if exp and exp not in text:
			ok = False


import json
from pathlib import Path
from typing import Dict, Any

class MetaController:
    """
    Monitors subsystem metrics and emits meta decisions (planning mode, temps, step budgets).
    """

    def __init__(self, root: Path) -> None:
        self.root = root
        self.state_path = root / "data" / "sandbox" / "tmp" / "meta_state.json"
        self.state_path.parent.mkdir(parents=True, exist_ok=True)

    def _read_json(self, p: Path) -> Dict[str, Any]:
        try:
            return json.loads(p.read_text(encoding="utf-8"))
        except Exception:
            return {}


from __future__ import annotations
import logging

from typing import Literal

SuiteName = Literal["humaneval", "mbpp"]

def build_prompt(suite: SuiteName, base: str) -> str:
    """Return a suite-specific instruction-prefixed prompt.

    Ensures the model outputs only Python code without fences or chatter.
    """
    common_hint = (
        "Complete the Python function from the given prompt by writing ONLY the function body. "
        "Rules: (1) Output only Python code, no fences or prose. (2) Do not add tests, asserts, prints, or a main. "
        "(3) Do not add imports or extra functions unless strictly necessary. (4) Do not rewrite the def line. "
        "(5) The first non-empty line of your output must be indented under the provided def.\n\n"
    )
    if suite == "humaneval":


import logging
import uuid
import random
from pathlib import Path
from typing import Dict, List, Tuple

from bench.common.safe_shell import SafeShellRunner
from bench.common.trace import build_trace, write_jsonl

def setup_count_lines(sandbox: Path) -> None:
	(sandbox / "docs").mkdir(exist_ok=True)
	(sandbox / "docs" / "a.txt").write_text("one\nTwo\nthree\n", encoding="utf-8")
	(sandbox / "docs" / "b.txt").write_text("alpha\nBeta\nGamma\n", encoding="utf-8")

def setup_grep_word(sandbox: Path) -> None:
	(sandbox / "logs").mkdir(exist_ok=True)
	(sandbox / "logs" / "app.log").write_text(
		"INFO start\nWARN cpu high\nERROR disk full\nINFO done\n",
		encoding="utf-8",


import logging
import os
from agi_dw.tools.artifact_cache import is_enabled as cache_enabled, get_cached_text as cache_get, set_cached_text as cache_set  # type: ignore
from typing import Dict, Any, List
from urllib.parse import urlparse
from agi_dw.core.ops.tracing import trace_span, meter_cost  # type: ignore

def _get_allowlist() -> List[str]:
	env = os.environ.get("AGI_DOM_ALLOWLIST", "")
	if env.strip():
		return [h.strip().lower() for h in env.split(",") if h.strip()]
	# Default allowlist for benchmark/demo stability
	return [
		"example.com",
		"www.iana.org",
		"iana.org",
		"en.wikipedia.org",
		"wikipedia.org",
		# Common documentation sites used in seeds
		"developer.mozilla.org",


import logging
from typing import Any, Dict, Optional, List, Tuple
from pathlib import Path
from datetime import datetime

from agi_dw.core.llm.hf_client import HFClient
from agi_dw.core.utils.prompt_logger import PromptLogger, get_prompt_logger  # type: ignore
from agi_dw.core.ops.tracing import trace_span, meter_cost  # type: ignore
from agi_dw.tools.artifact_cache import is_enabled as cache_enabled, get_cached_text as cache_get, set_cached_text as cache_set  # type: ignore

try:
	import yaml  # type: ignore
except Exception:
	yaml = None

# Reuse actuator parsing/coercion to salvage slightly malformed outputs
try:
	from agi_dw.core.actuator.parse import coerce_flat_yaml  # type: ignore
except Exception:
	def coerce_flat_yaml(_: str) -> Dict[str, Any]:  # fallback no-op
		return {}


from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, List, Tuple, Optional, Callable

import time
import hashlib

from agi_dw.bench.common.pipeline import (
	try_generate_python_body,
	looks_like_python_code,
	attach_adapter_from_args,
	parse_k_list,
	evaluate_samples,
	read_jsonl as _read_jsonl_shared,
	build_results_by_task as _build_results_by_task_shared,
	dedupe_by_passed as _dedupe_by_passed_shared,
	shard_task_ids,
	compute_sharded_outpath,
	write_trace,
	repair_code_failures,


from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, List, Tuple

def _read_jsonl(path: Path) -> List[Dict[str, Any]]:
	rows: List[Dict[str, Any]] = []
	if not path.exists():
		return rows
	with path.open("r", encoding="utf-8") as f:
		for line in f:
			li = line.strip()
			if not li:
				continue
			try:
				rows.append(__import__("json").loads(li))
			except Exception:
				continue
	return rows


from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, List, Optional, Protocol, Tuple

class BenchmarkAdapter(Protocol):
	"""Adapter interface to plug any benchmark into the universal harness.

	Required methods:
	- suite(): suite name used for traces and outputs
	- load_tasks(args): returns mapping task_id -> task payload
	- build_input(task_id, task): returns the user input string for the LLM
	- system_prompt(): returns the system prompt to use
	- sanitize_completion(text, prompt, task): cleans raw LLM output for evaluation
	- evaluate(samples_path, args, root, task_ids, tasks): returns (results_by_task, results_path or None)

	Optional methods:
	- env_modules(): list of python modules to fingerprint in env metadata
	- args_summary(args): dict of run args for run artifact
	"""


from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, Tuple, Callable, Optional, List

def load_registry(root: Path | None = None) -> Dict[str, Any]:
	root = root or Path(__file__).resolve().parents[2]
	# Root already points to the repo root (e.g., /data/agiattempt/agi_dw)
	# so the registry lives under bench/registry.json relative to it.
	reg_path = Path(root / "bench" / "registry.json")
	try:
		obj = __import__("json").loads(reg_path.read_text(encoding="utf-8"))
		return obj if isinstance(obj, dict) else {"version": 1, "suites": {}}
	except Exception:
		return {"version": 1, "suites": {}}

def resolve_entrypoint(fn_path: str) -> Callable[[Any], int]:
	"""Resolve 'module.sub:func' into a callable."""
	mod_str, func_str = fn_path.split(":", 1)


from __future__ import annotations

import json
import logging
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import hashlib
import os
from typing import Any, Dict, List, Optional, Callable, Tuple
from agi_dw.bench.common.pipeline import (
    try_generate_python_body,
    looks_like_python_code,
    attach_adapter_from_args,
    parse_k_list,
    evaluate_samples,
    read_jsonl as _read_jsonl_shared,
    build_results_by_task as _build_results_by_task_shared,
    dedupe_by_passed as _dedupe_by_passed_shared,
    shard_task_ids,
    compute_sharded_outpath,


from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, List, Tuple, Optional
from agi_dw.core.ops.tracing import trace_span, meter_cost  # type: ignore

def looks_like_python_code(body: str) -> bool:
	"""Heuristic filter to check that a generated body resembles Python code.

	Shared across benchmarks to keep generation sanity checks consistent.
	"""
	b = (body or "").strip()
	if not b:
		return False
	if (b.startswith('"""') and b.endswith('"""')) or (b.startswith("'''") and b.endswith("'''")):
		return False
	# avoid degenerate bodies
	if b == "pass":
		return False
	for tok in ("return ", "= ", "=\n", "for ", "while ", "if ", "elif ", "yield ", "try:", "except "):


import logging
import json
import os
import re
from pathlib import Path
from typing import Any, Dict, List, Set
import hashlib

def build_trace(task_id: str, obs: Dict[str, Any], plan: Dict[str, Any], action: Dict[str, Any], result: Dict[str, Any], reward: Dict[str, Any], critique: Dict[str, Any]) -> Dict[str, Any]:
	# Optionally carry intent fields if present (non-breaking for existing readers)
	intent = {}
	try:
		if isinstance(plan, dict):
			for k in ("intent_summary", "target_symbols", "constraints", "risk_budget"):
				if k in plan:
					intent[k] = plan.get(k)
		if isinstance(action, dict):
			ai = action.get("intent") if isinstance(action.get("intent"), dict) else {}
			if ai:
				intent.update({f"action_{k}": v for k, v in ai.items()})


import logging
import os
import re
import shlex
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Tuple, Iterable

ALLOWED_CMDS: Tuple[str, ...] = (
	"ls",
	"cat",
	"wc",
	"head",
	"tail",
	"grep",
	"cut",
	"sort",
	"uniq",
	"mkdir",


from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, List, Tuple, Optional

import time

from agi_dw.bench.common.adapters import BenchmarkAdapter

def run_with_adapter(args: Any, adapter: BenchmarkAdapter) -> int:
	"""Run a benchmark end-to-end using the provided adapter and shared harness utilities.

	This wires in our LLM client, caching, critic/verifier, tracing, and run artifacts.
	"""
	from agi_dw.bench.common.harness import get_llm_and_basics  # type: ignore
	from agi_dw.bench.common.pipeline import (
		init_trace_paths,
		build_env_fingerprint,
		seed_everything,
		get_shard_tag,


from fastapi import FastAPI, HTTPException, BackgroundTasks, Request, Depends
from fastapi.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from sqlalchemy.orm import Session
import database as db
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse, StreamingResponse, PlainTextResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
import ipaddress
from typing import Dict, List, Optional, Any, Union, AsyncGenerator, Set
from enum import Enum
import asyncio
import psutil
import os
import json
from datetime import datetime, timedelta
import subprocess
from typing import List, Dict, Optional
import logging


from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime, JSON, ForeignKey, Enum as SQLEnum, or_, desc, asc, case
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from typing import Tuple
from datetime import datetime
from typing import Optional, Dict, Any, List
import enum
import json
import os

# Create SQLite database engine
DATABASE_URL = "sqlite:///./dashboard.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})

# Create declarative base
Base = declarative_base()

class TaskStatus(str, enum.Enum):
    QUEUED = "queued"
    RUNNING = "running"
    COMPLETED = "completed"


from __future__ import annotations
import logging

import subprocess
from pathlib import Path
from typing import Dict, Any, List, Optional

def _exec(cmd: List[str], cwd: str | Path) -> tuple[int, str]:
	p = subprocess.Popen(cmd, cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
	out, _ = p.communicate()
	return p.returncode, out or ""

def run_flake8(repo_dir: str | Path, paths: Optional[List[str]] = None) -> Dict[str, Any]:
	repo = Path(repo_dir)
	cmd = ["flake8"] + (paths or ["."])
	code, out = _exec(cmd, repo)
	issues: List[Dict[str, Any]] = []
	for line in (out or "").splitlines():
		# format: path:line:col: code message


from __future__ import annotations
import logging

import argparse
import json
import shutil
import subprocess
from pathlib import Path
from typing import Any, Dict, List

def run(cmd: List[str], cwd: Path) -> Dict[str, Any]:
	p = subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True)
	return {
		"cmd": " ".join(cmd),
		"rc": p.returncode,
		"out": p.stdout,
		"err": p.stderr,
	}


from __future__ import annotations
import logging

import argparse
import ast
import json
from pathlib import Path
from typing import Any, Dict, List, Tuple

def scan_py(path: Path) -> Dict[str, Any]:
	text = path.read_text(encoding="utf-8", errors="ignore")
	try:
		tree = ast.parse(text, filename=str(path))
		defs: List[Dict[str, Any]] = []
		for node in ast.walk(tree):
			if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
				defs.append({
					"name": node.name,
					"kind": node.__class__.__name__,
					"lineno": getattr(node, "lineno", None),


from __future__ import annotations
import logging

import subprocess
from pathlib import Path
from typing import Dict, List, Optional

class LinterTool:
	"""Run flake8 and mypy if available; return structured results.

	Skips gracefully if tools are not installed.
	"""

	def __init__(self, cwd: str) -> None:
		self.cwd = Path(cwd)

	def _run(self, cmd: List[str], timeout: int = 300) -> subprocess.CompletedProcess:
		return subprocess.run(cmd, cwd=str(self.cwd), capture_output=True, text=True, timeout=timeout)

	def run_flake8(self, args: Optional[List[str]] = None, timeout: int = 300) -> Dict:


from __future__ import annotations
import logging

import re
from typing import Iterable

DEFAULT_PATTERNS: list[tuple[re.Pattern[str], str]] = [
	# API keys / tokens
	(re.compile(r"(?i)(api[_-]?key|token|secret)\s*[:=]\s*['\"]?[A-Za-z0-9_\-]{16,}['\"]?"), r"\1: [REDACTED]"),
	# JWTs (very rough)
	(re.compile(r"eyJ[0-9A-Za-z_-]+\.[0-9A-Za-z_-]+\.[0-9A-Za-z_-]+"), "[REDACTED_JWT]"),
	# Email addresses
	(re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"), "[REDACTED_EMAIL]"),
	# IPv4
	(re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"), "[REDACTED_IP]"),
]

def redact_text(text: str, patterns: Iterable[tuple[re.Pattern[str], str]] | None = None) -> str:
	out = text or ""


from __future__ import annotations
import logging

import re
from typing import Dict, Any, List

def classify_failures(stdout: str, stderr: str) -> Dict[str, Any]:
	text = (stdout or "") + "\n" + (stderr or "")
	categories: List[str] = []
	advice: List[str] = []

	def hit(rx: str) -> bool:
		return re.search(rx, text, re.IGNORECASE | re.MULTILINE) is not None

	# Import & module errors
	if hit(r"ModuleNotFoundError|No module named|ImportError: cannot import name"):
		categories.append("import_error")
		advice.append("Check PYTHONPATH and package installs; consider rewrite-imports to fix relative imports.")
	# Device / CUDA
	if hit(r"CUDA out of memory|device-side assert|RuntimeError: CUDA|torch\.cuda"):


from __future__ import annotations
import logging

from pathlib import Path
from typing import List, Tuple, Set
import ast

def validate_unified_diff_schema(diff_text: str) -> Tuple[bool, str]:
	try:
		lines = diff_text.splitlines()
		if not any(ln.startswith("diff --git ") for ln in lines):
			return False, "missing diff header"
		if not any(ln.startswith("--- a/") for ln in lines) or not any(ln.startswith("+++ b/") for ln in lines):
			return False, "missing file headers"
		if not any(ln.startswith("@@ ") for ln in lines):
			return False, "missing hunk headers"
		# Block binary diffs and mode/rename flags
		for ln in lines:
			l = ln.strip().lower()
			if l.startswith("binary files ") or l.startswith("gitattributes"):


from __future__ import annotations
import logging

from pathlib import Path
from typing import Dict, Any, List, Tuple
import os
import re
import fnmatch

def load_env_limits(strict_default: bool = True) -> Dict[str, int | bool | str]:
	strict = os.environ.get("AGI_PATCH_STRICT", "1" if strict_default else "0").strip() not in ("0", "false", "False")
	max_files = int(os.environ.get("AGI_PATCH_MAX_FILES", "10" if strict else "20") or ("10" if strict else "20"))
	max_added = int(os.environ.get("AGI_PATCH_MAX_ADDED", "400" if strict else "1000") or ("400" if strict else "1000"))
	max_deleted = int(os.environ.get("AGI_PATCH_MAX_DELETED", "200" if strict else "500") or ("200" if strict else "500"))
	allow_raw = os.environ.get("AGI_PATCH_ALLOW", "").strip()
	block_raw = os.environ.get("AGI_PATCH_BLOCK", "").strip()
	allow_patterns = [p.strip() for p in allow_raw.split(",") if p.strip()]
	block_patterns = [p.strip() for p in block_raw.split(",") if p.strip()]
	allow_mode = os.environ.get("AGI_PATCH_ALLOW_FILE_MODES", "0").strip() in ("1", "true", "True")
	allow_rename = os.environ.get("AGI_PATCH_ALLOW_RENAMES", "0").strip() in ("1", "true", "True")


from __future__ import annotations
import logging

import json
from pathlib import Path
from typing import Any, Dict, Iterable, List, Tuple

def read_jsonl(path: str | Path) -> Iterable[Dict[str, Any]]:
	p = Path(path)
	if not p.exists():
		return []
	with p.open("r", encoding="utf-8") as f:
		for line in f:
			s = line.strip()
			if not s:
				continue
			try:
				yield json.loads(s)
			except Exception:
				continue


from __future__ import annotations
import logging

import subprocess
import shlex
import time
from pathlib import Path
from typing import Dict, Any, List, Optional

def _run_cmd(cmd: List[str], cwd: str | Path) -> tuple[int, str]:
	start = time.time()
	try:
		p = subprocess.Popen(cmd, cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
		out, _ = p.communicate()
		elapsed = max(0.0, time.time() - start)
		return p.returncode, out or ""
	except Exception as e:
		elapsed = max(0.0, time.time() - start)
		return 127, f"[test-runner] failed to execute: {' '.join(cmd)}\n{e}"


from __future__ import annotations
import logging

from dataclasses import dataclass
from pathlib import Path
from typing import List, Dict, Any, Optional
import csv

@dataclass
class Sheet:
	name: str
	columns: List[str]
	rows: List[Dict[str, Any]]

def read_csv_sheet(path: str, name: Optional[str] = None) -> Sheet:
	p = Path(path)
	with p.open("r", encoding="utf-8") as f:
		reader = csv.DictReader(f)
		rows = [dict(r) for r in reader]


from __future__ import annotations
import logging

import json
import shutil
from pathlib import Path
from typing import Dict, Any, List
import os

def detect_languages(root: Path) -> List[str]:
	langs: List[str] = []
	# Python
	if any(root.rglob("*.py")):
		langs.append("python")
	# JavaScript (package.json or .js files)
	if any(root.rglob("package.json")) or any(root.rglob("*.js")):
		langs.append("javascript")
	# TypeScript (tsconfig.json or any .ts excluding .d.ts)
	if (root / "tsconfig.json").exists() or any(p.suffix == ".ts" and not p.name.endswith(".d.ts") for p in root.rglob("*.ts")):
		langs.append("typescript")


from __future__ import annotations
import logging

from pathlib import Path
from typing import List, Dict, Any
import subprocess
import argparse

def _allowed(path: Path, allow_globs: List[str], block_globs: List[str]) -> bool:
	from fnmatch import fnmatch
	sp = str(path)
	for g in block_globs:
		if fnmatch(sp, g):
			return False
	if not allow_globs:
		return True
	return any(fnmatch(sp, g) for g in allow_globs)

def validate_diff_policy(diff_text: str, allowed_exts: List[str] | None = None, max_hunk_lines: int = 1000, forbidden_patterns: List[str] | None = None) -> Dict[str, Any]:


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path

def validate_jsonl(path: Path, required_keys: list[str]) -> int:
	errs = 0
	for i, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
		try:
			obj = json.loads(line)
		except Exception:
			print(f"invalid json at {path}:{i}")
			errs += 1
			continue
		missing = [k for k in required_keys if k not in obj]
		if missing:
			print(f"missing keys {missing} at {path}:{i}")
			errs += 1


from __future__ import annotations
import logging

import argparse
import json
import os
import shlex
import subprocess
import sys
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict

def _now_iso() -> str:
	return datetime.now(timezone.utc).isoformat()

def _git_info(repo: Path) -> Dict[str, Any]:


from __future__ import annotations
import logging

import json
from pathlib import Path
from typing import Dict, Any, List

from agi_dw.tools.repo_manifest import generate_manifest
from agi_dw.tools.code_index import index_python_repo

def compact_code_index(idx: Dict[str, Any], root: Path) -> Dict[str, Any]:
	"""Create a compact, language-agnostic subset of the code index.

	Currently focuses on Python symbols. Safely caps long lists.
	"""
	max_items = 200
	files = list(idx.get("files", []))[:max_items]
	functions: Dict[str, List[Dict[str, Any]]] = {}
	classes: Dict[str, List[Dict[str, Any]]] = {}
	for fp in files:


from __future__ import annotations
import logging

import argparse
import json
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Any, Iterable, List

@dataclass
class CLIExample:
	goal: str
	cwd: str
	command_args: List[str]
	env_policy: dict[str, Any]

@dataclass
class HITLExample:
	preview: str


from __future__ import annotations
import logging

import os
import hashlib
from pathlib import Path
from typing import Optional
from datetime import datetime, timedelta

def _cache_root() -> Path:
	try:
		return Path(__file__).resolve().parents[1] / "data" / "cache"
	except Exception:
		return Path.cwd() / "data" / "cache"

def is_enabled(env_var: str = "AGI_ARTIFACT_CACHE") -> bool:
	try:
		v = os.environ.get(env_var, "0").strip()
		return v in ("1", "true", "True")


from __future__ import annotations
import logging

import subprocess
from pathlib import Path
from typing import Optional

class GitTool:
	"""Minimal git adapter with safe cwd and simple commands."""

	def __init__(self, cwd: str) -> None:
		self.cwd = Path(cwd)
		self.cwd.mkdir(parents=True, exist_ok=True)

	def _run(self, *args: str, timeout: int = 120) -> subprocess.CompletedProcess:
		return subprocess.run(["git", *args], cwd=str(self.cwd), capture_output=True, text=True, timeout=timeout)

	def clone(self, repo: str, dest: Optional[str] = None) -> subprocess.CompletedProcess:
		args = ["clone", repo]
		if dest:


from __future__ import annotations
import logging

import subprocess
from pathlib import Path
from typing import Dict, Any, List, Optional

def _git(cwd: str | Path, *args: str) -> tuple[int, str]:
	cmd = ["git"] + list(args)
	p = subprocess.Popen(cmd, cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
	out, _ = p.communicate()
	return p.returncode, out or ""

def clone(repo_url: str, dest_dir: str | Path) -> Dict[str, Any]:
	code, out = _git(Path("."), "clone", "--depth", "1", repo_url, str(dest_dir))
	return {"cmd": "git clone", "code": code, "output": out}

def checkout(repo_dir: str | Path, ref: str) -> Dict[str, Any]:


from __future__ import annotations
import logging

import json
from typing import Dict, Any, List

def rank_index_candidates(observation: Dict[str, Any], index_obj: Dict[str, Any], k: int) -> Dict[str, List[Dict[str, str]]]:
	"""Return top-k function/class candidates from a Python code index based on observation text.

	Scoring heuristic favors substring matches of symbol names in observation content/meta,
	with a slight bias toward shorter names.
	"""
	# Return empty when disabled or invalid inputs
	if not isinstance(observation, dict) or int(k) <= 0:
		return {}
	if not isinstance(index_obj, dict) or not index_obj.get("functions") and not index_obj.get("classes"):
		return {}
	text = (str(observation.get("content", "")) + " \n " + json.dumps(observation.get("meta", {}), ensure_ascii=False))
	text_lower = text.lower()
	func_hits: List[tuple[float, str, str]] = []


#!/usr/bin/env python3
from __future__ import annotations
import logging

import json
from pathlib import Path
from typing import Any, Dict

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    out = root / "data" / "sandbox" / "tmp" / "ir_snapshot.json"
    # Build on top of existing code index graph for now
    try:
        from agi_dw.tools.code_index import build_index  # type: ignore
        idx = build_index(root)
    except Exception:
        idx = {}
    ir = {
        "ok": True,
        "uast": {},  # placeholder for future multi-language UAST


import logging
import argparse
import json
from pathlib import Path

def main() -> int:
	ap = argparse.ArgumentParser(description="Emit a refactor plan to move scripts/* into scripts/<group>/")
	root = Path(__file__).resolve().parents[1]
	ap.add_argument("--audit", default=str(root / "data" / "ci" / "scripts_audit.json"))
	ap.add_argument("--out", default=str(root / "data" / "traces" / "scripts_refactor_plan.json"))
	ap.add_argument("--emit-shims-dir", default=str(root / "scripts" / "shims"))
	args = ap.parse_args()

	audit_path = Path(args.audit)
	audit = json.loads(audit_path.read_text(encoding="utf-8")) if audit_path.exists() else {}
	mapping = audit.get("proposed_mapping") or {}
	edits = []
	# Create group directories and move files
	created_dirs = set()
	for src, dst in mapping.items():


import logging
import argparse
import json
import re
from pathlib import Path
from typing import Dict, List, Tuple

SCRIPT_PATTERNS: List[Tuple[str, str]] = [
	(r"^(run_loop_|loop_|run-?loop-)", "loops"),
	(r"^(train_|trainer_|planner-|planner_|grpo|ppo)", "train"),
	(r"^(eval_|evaluate_|ci_assert_)", "eval"),
	(r"^(build_|build-)", "build"),
	(r"^(aggregate_|summarize_|dashboard|capabilities|report)", "dashboard"),
	(r"^(bench_|run_llm_|llm|lm_eval|code_review|run_.*bench|orchestrate_.*bench|.*_bench$)", "bench"),
	(r"^(seed_|verify_|validate_|unify_|dedupe_|snapshot_|registry_)", "data"),
	(r"^(docs_|generate_docs|run_docs)", "docs"),
	(r"^(devtools_|dev_|rewrite_|updater|task_scheduler|multi_agent|sandbox)", "devtools"),
	(r"^(router_|train_router|eval_router)", "router"),
]


import logging
import argparse
import json
from pathlib import Path

def build_minimal_makefile() -> str:
	# Minimal Makefile preserving env and modular includes; shims optional via REFAC_INCLUDE_SHIMS
	lines: list[str] = []
	lines.append("PYTHONPATH := /data/agiattempt")
	# Core defaults preserved from legacy Makefile
	lines.append("MODEL ?= gemma3:12b")
	lines.append("HF_MODEL ?= meta-llama/Llama-3.2-3B")
	lines.append("NGPU ?= 2")
	lines.append("TIMEOUT ?= 60")
	lines.append("VERIFY_ARGS ?=")
	lines.append("REPO ?= local:/data/agiattempt/agi_dw")
	lines.append("BASELINE_SUMMARY ?= data/dashboards/baseline_summary.json")
	lines.append("")
	# Data/paths used by modular targets
	lines.append("TRACES := data/traces/seed_os_cli.jsonl")


import logging
import argparse
import json
import os
import subprocess
from pathlib import Path

def run(cmd: list[str], cwd: Path) -> dict:
	try:
		out = subprocess.run(cmd, cwd=str(cwd), check=False, capture_output=True, text=True)
		return {
			"cmd": cmd,
			"returncode": out.returncode,
			"stdout": out.stdout.strip(),
			"stderr": out.stderr.strip(),
		}
	except Exception as e:
		return {"cmd": cmd, "error": str(e), "returncode": -1, "stdout": "", "stderr": ""}


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Dict, Any, List

def main() -> int:
    ap = argparse.ArgumentParser(description="Build deterministic PlanDAG from intent and code/policy graphs")
    root = Path(__file__).resolve().parents[2]
    ap.add_argument("--intent", default=str(root / "data" / "sandbox" / "plan" / "intent.json"))
    ap.add_argument("--out", default=str(root / "data" / "sandbox" / "plan" / "plan.json"))
    ap.add_argument("--max-pr-files", type=int, default=0, help="Override max files per PR (0 uses policies.yaml)")
    args = ap.parse_args()

    # Load inputs
    intent = json.loads(Path(args.intent).read_text(encoding="utf-8")) if Path(args.intent).exists() else {"intent": {}}
    idx_path = root / "data" / "sandbox" / "tmp" / "index.json"
    pol_path = root / "data" / "sandbox" / "config" / "policies.yaml"


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path

def main() -> int:
    ap = argparse.ArgumentParser(description="Render PlanDAG to markdown report (sandbox)")
    root = Path(__file__).resolve().parents[2]
    ap.add_argument("--plan", default=str(root / "data" / "sandbox" / "plan" / "plan.json"))
    ap.add_argument("--out", default=str(root / "data" / "sandbox" / "docs" / "reports" / "plan.md"))
    args = ap.parse_args()

    plan = json.loads(Path(args.plan).read_text(encoding="utf-8")) if Path(args.plan).exists() else {}
    overview = plan.get("plan", {}).get("overview", {})
    dag = plan.get("plan", {}).get("dag", [])
    prs = plan.get("plan", {}).get("prs", [])

    lines = ["# PlanDAG", "", f"Change kind: {overview.get('change_kind','refactor')}", "", "## DAG", ""]


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Dict, Any

def main() -> int:
    ap = argparse.ArgumentParser(description="Normalize raw spec text to structured intent")
    root = Path(__file__).resolve().parents[2]
    ap.add_argument("--spec", required=True, help="Raw spec text or path to file")
    ap.add_argument("--out", default=str(root / "data" / "sandbox" / "plan" / "intent.json"))
    args = ap.parse_args()

    raw = args.spec
    spec_text = raw
    p = Path(raw)
    if p.exists():
        spec_text = p.read_text(encoding="utf-8")


from __future__ import annotations

import logging
import argparse
import json
from pathlib import Path

EXAMPLES = [
    {
        "id": "make_flag_fix_limit",
        "category": "bench_infra",
        "problem": "Make target passes unsupported --max; script expects --limit",
        "files": ["Makefile"],
        "before": "--max ${MAX:-10}",
        "after": "--limit ${LIMIT:-10}",
        "verify": {
            "cmd": "make -C agi_dw -n bench.run.humaneval",
            "must_contain": ["--limit"],
        },
    },


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path

def main() -> int:
    ap = argparse.ArgumentParser(description="Convert SFT JSONL {prompt,response} to {input,output}")
    ap.add_argument("--in", dest="inp", required=True)
    ap.add_argument("--out", required=True)
    args = ap.parse_args()

    inp = Path(args.inp)
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)

    n = 0
    with inp.open("r", encoding="utf-8") as f, out.open("w", encoding="utf-8") as w:
        for line in f:


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Dict, Any, List

def load_jsonl(path: Path) -> List[Dict[str, Any]]:
    if not path.exists():
        return []
    rows: List[Dict[str, Any]] = []
    for line in path.read_text(encoding="utf-8").splitlines():
        s = line.strip()
        if not s:
            continue
        try:
            rows.append(json.loads(s))
        except Exception:
            continue


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Dict, Any, List

def main() -> int:
    ap = argparse.ArgumentParser(description="Generate IL traces (plan→patch→verify) for repo-level tasks (synthetic from bench-infra)")
    root = Path(__file__).resolve().parents[2]
    ap.add_argument("--tasks", default=str(root / "data" / "traces" / "benchinfra_tasks.jsonl"))
    ap.add_argument("--out", default=str(root / "data" / "sandbox" / "il_traces"))
    args = ap.parse_args()

    tasks_path = Path(args.tasks)
    out_dir = Path(args.out)
    out_dir.mkdir(parents=True, exist_ok=True)

    traces_path = out_dir / "il_traces.jsonl"


import torch
import torch.nn.functional as F
from torch.nn.utils import clip_grad_norm_
from typing import Iterable

from agi_dw.core.metaopt.group_utils import make_param_groups
from agi_dw.core.metaopt.gate_grouped import GateNetGrouped
from agi_dw.core.metaopt.metaopt_grouped import MixtureMetaOptGrouped

def integration_sketch(model: torch.nn.Module, loader: Iterable, val_loader: Iterable, device: str = "cuda") -> None:
    model.to(device)
    groups = make_param_groups(model)
    gate = GateNetGrouped(n_groups=len(groups), hidden=128)
    meta = MixtureMetaOptGrouped(model, groups, gate, base_lr=3e-4, base_wd=0.01, device=device)

    step = 0
    for batch in loader:
        step += 1
        x, y = batch
        x = x.to(device)


from __future__ import annotations
import logging

import argparse
from pathlib import Path

def main() -> int:
    ap = argparse.ArgumentParser(description="QLoRA SFT trainer for coder head (prompt->body)")
    root = Path(__file__).resolve().parents[1]
    ap.add_argument("--data", required=True, help="JSONL with {input,output}")
    ap.add_argument("--base-model", default="meta-llama/Llama-3.2-3B")
    ap.add_argument("--out", default=str(root / "models" / "coder_qlora"))
    ap.add_argument("--epochs", type=int, default=1)
    ap.add_argument("--bsz", type=int, default=4)
    ap.add_argument("--max-len", type=int, default=512)
    ap.add_argument("--metaopt", action="store_true", help="Enable meta-optimizer (MixtureMetaOptGrouped) during training")
    ap.add_argument("--meta-base-lr", type=float, default=3e-4)
    ap.add_argument("--meta-base-wd", type=float, default=0.01)
    args = ap.parse_args()


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Any, Dict

def count_lines(path: Path) -> int:
    if not path.exists():
        return 0
    try:
        return sum(1 for _ in path.open("r", encoding="utf-8"))
    except Exception:
        return 0

def main() -> int:
    ap = argparse.ArgumentParser(description="Tune heads for size/files/risk (heuristic)")
    root = Path(__file__).resolve().parents[2]


import logging
import argparse
import json
import re
from pathlib import Path
import os
from typing import Dict, List, Optional

from datasets import load_dataset
from transformers import (
	AutoModelForSeq2SeqLM,
	AutoTokenizer,
	DataCollatorForSeq2Seq,
	Seq2SeqTrainingArguments,
	Seq2SeqTrainer,
	EarlyStoppingCallback,
)
from transformers import set_seed
try:
	import torch  # type: ignore
except Exception:


import logging
import argparse
import json
from pathlib import Path
from typing import List, Dict

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score

DEFAULT_FEATURE_KEYS = [
	"plan_len",
	"plan_ws_tokens",
	"plan_unique_tokens",
	"plan_token_entropy",
	"obs_cli",
	"obs_dom",
	"num_subgoals",
	"kw_wc",
	"kw_grep",


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Any, Dict, List, Tuple

def _iter_rows(paths: List[str]) -> Tuple[int, List[Dict[str, Any]]]:
	try:
		from agi_dw.tools.ds_io import iter_rows as shared_iter  # type: ignore
		return shared_iter(paths)
	except Exception:
		rows: List[Dict[str, Any]] = []
		count = 0
		for p in (paths or []):
			dp = Path(p)
			if not dp.exists():
				continue
			with dp.open("r", encoding="utf-8") as f:


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Any, Dict, List

def _iter_jsonl(path: Path):
	if not path.exists():
		return
	with path.open("r", encoding="utf-8") as f:
		for line in f:
			s = line.strip()
			if not s:
				continue
			try:
				yield json.loads(s)
			except Exception:
				continue


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Dict, Any, List, Tuple

def _iter_rows(paths: List[str]) -> Tuple[int, List[Dict[str, Any]]]:
	# Back-compat shim; prefer shared IO
	try:
		from agi_dw.tools.ds_io import iter_rows as shared_iter  # type: ignore
		return shared_iter(paths)
	except Exception:
		rows: List[Dict[str, Any]] = []
		count = 0
		for p in (paths or []):
			dp = Path(p)
			if not dp.exists():
				continue


import logging
import argparse
from pathlib import Path

from datasets import load_dataset

def main() -> int:
	ap = argparse.ArgumentParser()
	root = Path(__file__).resolve().parents[1]
	ap.add_argument("--data", default=str(root / "data" / "skills" / "verifier_ds.jsonl"))
	ap.add_argument("--base-model", default="meta-llama/Llama-3.2-3B")
	ap.add_argument("--out", default=str(root / "models" / "verifier_qlora"))
	ap.add_argument("--epochs", type=int, default=1)
	ap.add_argument("--bsz", type=int, default=2)
	ap.add_argument("--max-len", type=int, default=512)
	ap.add_argument("--ewc-ref-adapter", default=None, help="Path to reference LoRA adapter to regularize towards")
	ap.add_argument("--ewc-lambda", type=float, default=0.0, help="Strength of EWC/L2 stability penalty (0 disables)")
	ap.add_argument("--ewc-fisher", default=None, help="Optional JSON mapping param_name->importance scalar for EWC")
	ap.add_argument("--metaopt", action="store_true", help="Enable meta-optimizer (MixtureMetaOptGrouped) during training")
	ap.add_argument("--meta-base-lr", type=float, default=3e-4)


import logging
import argparse
import json
from pathlib import Path
from typing import List, Dict

import numpy as np
from sklearn.isotonic import IsotonicRegression
from sklearn.metrics import roc_auc_score

def load_jsonl(path: Path) -> List[Dict]:
	rows: List[Dict] = []
	with path.open("r", encoding="utf-8") as f:
		for line in f:
			line = line.strip()
			if not line:
				continue
			try:
				rows.append(json.loads(line))
			except Exception:


import logging
import argparse
import json
from pathlib import Path
from typing import List, Dict, Tuple

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.metrics import roc_auc_score
from sklearn.isotonic import IsotonicRegression

def load_jsonl(path: Path) -> List[Dict]:
	rows: List[Dict] = []
	with path.open("r", encoding="utf-8") as f:
		for line in f:
			line = line.strip()
			if not line:
				continue
			try:


from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from datetime import datetime, timezone

def main(argv: list[str] | None = None) -> int:
	parser = argparse.ArgumentParser(description="Stub trainer for heads")
	parser.add_argument("--head", required=True, choices=["plan", "patch", "cli", "policy", "hitl", "critic"])
	parser.add_argument("--sft_root", default="/data/agiattempt/agi_dw/data/sft")
	parser.add_argument("--out_dir", default="/data/agiattempt/agi_dw/artifacts/heads")
	args = parser.parse_args(argv)

	out_dir = Path(args.out_dir) / args.head / datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
	out_dir.mkdir(parents=True, exist_ok=True)
	# Write a tiny checkpoint metadata file
	(out_dir / "checkpoint.meta.json").write_text(json.dumps({
		"head": args.head,


import logging
import argparse
import json
import random
import time
from pathlib import Path
from subprocess import run, PIPE  # type: ignore
from typing import Any, Dict, List, Tuple
import tempfile
import math
import numpy as np  # type: ignore

def run_loop_cli(root: Path, task: str, planner_backend: str, model: str, timeout: int, planner_candidates: int, extra_args: List[str] | None = None) -> Tuple[bool, Dict[str, Any]]:
	cmd = [
		"python3", str(root / "scripts" / "run_loop_oscli.py"),
		"--planner-backend", planner_backend,
		"--verifier-backend", planner_backend,
		"--planner-model", model,
		"--verifier-model", model,
		"--timeout", str(timeout),


from __future__ import annotations

import logging
import argparse
import json
import shlex
import subprocess
import os
from pathlib import Path
from typing import Dict, Any, List

def run_cmd(cmd: str, cwd: Path, extra_env: Dict[str, str] | None = None) -> str:
    try:
        parts = shlex.split(cmd)
        env = os.environ.copy()
        if extra_env:
            env.update(extra_env)
        out = subprocess.check_output(parts, cwd=str(cwd), stderr=subprocess.STDOUT, timeout=60, env=env)
        return out.decode("utf-8", errors="ignore")
    except subprocess.CalledProcessError as e:


import torch
import torch.nn.functional as F
from torch.nn.utils import clip_grad_norm_
from transformers import AutoModelForCausalLM, AutoTokenizer

from agi_dw.core.metaopt.group_utils import make_param_groups
from agi_dw.core.metaopt.gate_grouped import GateNetGrouped
from agi_dw.core.metaopt.metaopt_grouped import MixtureMetaOptGrouped

def hf_batchify(tokenizer, texts, block_size=1024, device="cuda"):
    ids = torch.tensor(tokenizer.encode("".join(texts)), dtype=torch.long, device=device)

    def next_batch(batch_size):
        ix = torch.randint(0, ids.size(0) - block_size - 1, (batch_size,), device=device)
        x = torch.stack([ids[i : i + block_size] for i in ix])
        y = torch.stack([ids[i + 1 : i + block_size + 1] for i in ix])
        return x, y

    return next_batch


from __future__ import annotations
import logging

import json
from pathlib import Path

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    out_path = root / "data" / "sandbox" / "tmp" / "trace_harvest.json"
    out = {
        "ok": True,
        "harvested": 0,
        "notes": "stub: collect traces from CI runs into datasets",
        "out": str(out_path),
    }
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"ok": True, "out": str(out_path)}))
    return 0


from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Dict

def scan_presence(root: Path) -> Dict[str, bool]:
    logging_found = False
    metrics_found = False
    traces_found = False
    for p in root.rglob("*.py"):
        try:
            text = p.read_text(encoding="utf-8", errors="ignore")
        except Exception:
            continue
        s = text
        if ("import logging" in s) or ("getLogger(" in s):
            logging_found = True
        if ("prometheus_client" in s) or ("statsd" in s) or ("meter." in s):
            metrics_found = True


from __future__ import annotations
import logging

import json
from pathlib import Path

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    out_path = root / "data" / "sandbox" / "tmp" / "plan_api_diff.json"
    out = {
        "ok": True,
        "api_diff": {
            "breaking": [],
            "additive": [],
            "deprecations": [],
        },
        "notes": "stub: diff OpenAPI/GraphQL/Proto when present",
        "out": str(out_path),
    }
    out_path.parent.mkdir(parents=True, exist_ok=True)


from __future__ import annotations
import logging

import json
from pathlib import Path

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    out_path = root / "data" / "sandbox" / "tmp" / "pattern_update.json"
    out = {
        "ok": True,
        "patterns": [],
        "notes": "stub: update pattern catalog entries from lessons learned",
        "out": str(out_path),
    }
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"ok": True, "out": str(out_path)}))
    return 0


from __future__ import annotations
import logging

import json
from pathlib import Path

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    out_path = root / "data" / "sandbox" / "tmp" / "error_budget.json"
    out = {
        "ok": True,
        "error_budget": {"burn": 0.0},
        "notes": "stub: compute error budget burn from SLO data",
        "out": str(out_path),
    }
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"ok": True, "out": str(out_path)}))
    return 0


from __future__ import annotations
import logging

import json
from pathlib import Path
import shutil
import subprocess

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    out_path = root / "data" / "sandbox" / "tmp" / "sbom.json"
    out = {"ok": True, "sbom": {"manifests": ["requirements.txt", "package.json", "uv.lock"]}, "out": str(out_path)}
    # Prefer CycloneDX if available
    try:
        if shutil.which("cyclonedx-py"):
            # Generate for Python requirements
            sbom_txt = subprocess.check_output(["cyclonedx-py", "--format", "json"], stderr=subprocess.STDOUT).decode("utf-8", errors="ignore")
            out["cyclonedx"] = True
            out_path.write_text(sbom_txt, encoding="utf-8")
            print(json.dumps({"ok": True, "out": str(out_path)}))


from __future__ import annotations
import logging

import json
from pathlib import Path
from typing import Any, Dict, List

def load_json(path: Path) -> Dict[str, Any]:
    if not path.exists():
        return {}
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return {}

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    idx_path = root / "data" / "sandbox" / "tmp" / "index.json"
    out_path = root / "data" / "sandbox" / "tmp" / "plan_risk.json"


from __future__ import annotations
import logging

import json
from pathlib import Path
import shutil
import subprocess

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    out_path = root / "data" / "sandbox" / "tmp" / "deps_audit.json"
    out = {"ok": True, "findings": [], "out": str(out_path)}
    # Prefer pip-audit if available
    try:
        if shutil.which("pip-audit"):
            res = subprocess.run(["pip-audit", "-f", "json"], capture_output=True, text=True)
            if res.returncode == 0 and res.stdout:
                data = json.loads(res.stdout)
                # Standardize findings
                for item in data if isinstance(data, list) else []:


from __future__ import annotations
import logging

import json
from pathlib import Path

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    out_path = root / "data" / "sandbox" / "tmp" / "trace_dataset_update.json"
    out = {
        "ok": True,
        "updated": True,
        "notes": "stub: merge new traces into SFT datasets",
        "out": str(out_path),
    }
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"ok": True, "out": str(out_path)}))
    return 0


from __future__ import annotations
import logging

import json
from pathlib import Path

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    out_path = root / "data" / "sandbox" / "tmp" / "deps_upgrade.json"
    out = {
        "ok": True,
        "planned": [],
        "notes": "stub: propose safe upgrades and open PRs",
        "out": str(out_path),
    }
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"ok": True, "out": str(out_path)}))
    return 0


from __future__ import annotations
import logging

import json
from pathlib import Path
from typing import Any, Dict

def _safe_load_yaml(path: Path) -> Dict[str, Any]:
    if not path.exists():
        return {}
    try:
        import yaml  # type: ignore
        data = yaml.safe_load(path.read_text(encoding="utf-8"))
        return data if isinstance(data, dict) else {}
    except Exception:
        return {}

def main() -> int:
    root = Path(__file__).resolve().parents[2]


from __future__ import annotations
import logging

import json
from pathlib import Path
from typing import Any, Dict, List, Tuple
import fnmatch

def load_json(path: Path) -> Dict[str, Any]:
    if not path.exists():
        return {}
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return {}

def load_codeowners(path: Path) -> List[Tuple[str, List[str]]]:
    rules: List[Tuple[str, List[str]]] = []
    if not path.exists():


#!/usr/bin/env python3
from __future__ import annotations
import logging

import json
from pathlib import Path
from typing import Any, Dict, List

def slice_ir(index: Dict[str, Any], files: List[str], max_chars: int = 8000) -> Dict[str, Any]:
    funcs = (index.get("functions") or {}) if isinstance(index, dict) else {}
    classes = (index.get("classes") or {}) if isinstance(index, dict) else {}
    calls = (index.get("calls") or {}) if isinstance(index, dict) else {}
    out: Dict[str, Any] = {"functions": {}, "classes": {}, "calls": {}}
    for fp in files:
        if fp in funcs:
            out["functions"][fp] = funcs[fp][:200]
        if fp in classes:
            out["classes"][fp] = classes[fp][:200]
        if fp in calls:
            out["calls"][fp] = calls[fp][:200]


from __future__ import annotations

import json
import os
import uuid
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Any, Dict, List, Optional

ROOT = Path(__file__).resolve().parents[2]

def ensure_dirs() -> None:
    for p in [
        ROOT / "data" / "foundry" / "backlog",
        ROOT / "data" / "foundry" / "repos",
        ROOT / "artifacts" / "foundry",
        ROOT / "data" / "traces" / "foundry_runs",
        ROOT / "data" / "sandbox" / "sft",
    ]:


#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
from pathlib import Path

from .common import ROOT, write_json

def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--tags", default="foundations/*")
    ap.add_argument("--run-id")
    args = ap.parse_args()
    out = ROOT / "data" / "sandbox" / "tmp" / "curriculum_update.json"
    out.parent.mkdir(parents=True, exist_ok=True)
    write_json(out, {"ok": True, "tags": args.tags})
    print(json.dumps({"ok": True, "out": str(out)}))
    return 0


#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import re
from pathlib import Path

from .common import ROOT, ensure_dirs, safe_slug

def parse_brief_yaml(path: Path) -> dict:
    # Minimal YAML reader for constrained brief format (keys, lists, scalars)
    text = path.read_text(encoding="utf-8")
    # Very naive; acceptable for initial bootstrap
    data: dict = {}
    stack = [data]
    indent_stack = [0]
    key_stack: list[str] = []
    for line in text.splitlines():
        if not line.strip() or line.strip().startswith("#"):


#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import shutil
import subprocess
from pathlib import Path

from .common import write_run_append

def run(cmd: str, cwd: Path) -> int:
    res = subprocess.run(cmd, shell=True, cwd=str(cwd))
    return int(res.returncode)

def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--repo", required=True)
    ap.add_argument("--run-id")


#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
from pathlib import Path

from .common import ROOT, write_json

def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--run-id", required=True)
    args = ap.parse_args()
    run_dir = ROOT / "data" / "traces" / "foundry_runs" / args.run_id
    run_dir.mkdir(parents=True, exist_ok=True)

    # Create placeholder unified traces and curated data updates
    unified = run_dir / "run.jsonl"
    pr_evidence = ROOT / "artifacts" / "foundry" / "default" / args.run_id / "pr_evidence.json"
    summary_md = ROOT / "artifacts" / "foundry" / "default" / args.run_id / "summary.md"


#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import subprocess
from datetime import datetime
from pathlib import Path

from .common import ROOT, ensure_dirs, write_run_append

def run(cmd: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
    return subprocess.run(cmd, shell=True, cwd=str(cwd) if cwd else None, capture_output=True, text=True)

def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=5)
    ap.add_argument("--k", type=int, default=2)
    ap.add_argument("--tags", default="foundations/*")


#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import subprocess
from pathlib import Path

from .common import write_run_append, ROOT

def run_cmd(cmd: str, cwd: Path) -> int:
    res = subprocess.run(cmd, shell=True, cwd=str(cwd))
    return int(res.returncode)

def minimal_attempt(repo: Path) -> dict:
    # No-op baseline solve: run tests
    rc = run_cmd("pytest -q", repo)
    return {"attempt_idx": 0, "rc": rc, "pass": rc == 0}


#!/usr/bin/env python3
from __future__ import annotations

import argparse
from datetime import datetime
from pathlib import Path

from .common import ROOT, RepoBrief, default_briefs, ensure_dirs

def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--tags", default="foundations/*")
    ap.add_argument("--n", type=int, default=5)
    ap.add_argument("--outdir", default=str(ROOT / "data" / "foundry" / "backlog"))
    args = ap.parse_args()

    ensure_dirs()
    outdir = Path(args.outdir)
    outdir.mkdir(parents=True, exist_ok=True)
    date_str = datetime.now().strftime("%Y-%m-%d")


#!/usr/bin/env python3
from __future__ import annotations
import logging

import json
from pathlib import Path
from typing import Dict, Any

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    pack_path = root / "data" / "sandbox" / "tmp" / "prompt_pack.json"
    out = root / "data" / "sandbox" / "tmp" / "name_api_synth.json"
    pack = json.loads(pack_path.read_text(encoding="utf-8")) if pack_path.exists() else {}
    # Minimal: propose a module/name tuple per file
    items = []
    for fp in (pack.get("files", []) if isinstance(pack, dict) else []):
        base = Path(fp).stem
        items.append({"file": fp, "proposed_name": f"{base}_adapter", "api": {"functions": []}})
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps({"ok": True, "items": items}, ensure_ascii=False, indent=2), encoding="utf-8")


#!/usr/bin/env python3
from __future__ import annotations
import logging

import json
from pathlib import Path

def main() -> int:
    root = Path(__file__).resolve().parents[2]
    ev = root / "artifacts" / "pr_evidence.json"
    out = root / "artifacts" / "pr_narrative.md"
    try:
        obj = json.loads(ev.read_text(encoding="utf-8")) if ev.exists() else {}
    except Exception:
        obj = {}
    lines = [
        "# PR Summary",
        f"Commit: {obj.get('commit','')}",
        f"Files changed: {obj.get('files_changed',0)}",
        f"Risk score: {obj.get('risk',0.0)}",


import logging
import argparse
import json
from pathlib import Path
from typing import Any, Dict, List

import sys

from agi_dw.core.verifier.llm_verifier import verify_trace_snippet

def process(
	in_jsonl: Path,
	out_jsonl: Path,
	model: str,
	timeout_sec: int,
	use_llm: bool,
	require_llm: bool,
	backend: str,
	log_prompts: bool,
	adapter_dir: str | None,


import logging
import json
from pathlib import Path
import sys

try:
	import jsonschema  # type: ignore
except Exception:
	jsonschema = None

def main() -> int:
	if len(sys.argv) < 2:
		print("Usage: validate_refactor_plan.py <refactor_plan.json>")
		return 2
	root = Path(__file__).resolve().parents[1]
	schema_path = root / "docs" / "schemas" / "refactor_plan.schema.json"
	plan_path = Path(sys.argv[1])
	if not schema_path.exists():
		print(f"Schema not found: {schema_path}")
		return 2


import logging
import argparse
import json
from pathlib import Path

def main() -> int:
	ap = argparse.ArgumentParser()
	root = Path(__file__).resolve().parents[1]
	ap.add_argument("--registry", default=str(root / "models" / "base_models.json"))
	ap.add_argument("--outdir", default=str(root / "models" / "bases"))
	args = ap.parse_args()

	reg_path = Path(args.registry)

	try:
		obj = json.loads(reg_path.read_text(encoding="utf-8"))
	except Exception:
		print("{}")
		return 0


#!/usr/bin/env python3
import logging
import argparse
import difflib
import json
import subprocess
import tempfile
from pathlib import Path

def parse_args():
	ap = argparse.ArgumentParser(description="Validate minimal patch compiles and tests pass in sandbox")
	ap.add_argument("--orig", required=True, help="Path to original code file")
	ap.add_argument("--edited", required=True, help="Path to edited code file")
	ap.add_argument("--tests", required=True, help="Path to tests file (asserts)")
	ap.add_argument("--timeout", type=int, default=12)
	ap.add_argument("--memmb", type=int, default=256)
	return ap.parse_args()

def main() -> int:


import logging
import argparse
from pathlib import Path

from bench.os_cli.tasks import generate_seed_traces

def main() -> None:
	root = Path(__file__).resolve().parents[1]
	ap = argparse.ArgumentParser()
	ap.add_argument("--episodes", type=int, default=20)
	ap.add_argument("--sandbox", default=str(root / "data" / "sandbox"))
	ap.add_argument("--out", default=str(root / "data" / "traces" / "seed_os_cli.jsonl"))
	args = ap.parse_args()

	total, path = generate_seed_traces(sandbox_dir=str(args.sandbox), out_jsonl=str(args.out), episodes=int(args.episodes))
	print(f"Generated {total} traces -> {path}")

if __name__ == "__main__":
	main()


import logging
import argparse
from pathlib import Path
from typing import List, Tuple, Dict, Any
from concurrent.futures import ThreadPoolExecutor, as_completed
try:
	import yaml  # type: ignore
except Exception:
	yaml = None

from agi_dw.bench.web_dom.runner import fetch_text, click_then_fetch, form_fill_fetch
from agi_dw.bench.common.trace import build_trace, write_jsonl

def main() -> None:
	parser = argparse.ArgumentParser()
	root = Path(__file__).resolve().parents[1]
	parser.add_argument("--out", default=str(root / "data" / "traces" / "web_dom.jsonl"))
	parser.add_argument("--seeds", default=str(root / "data" / "dom_seeds.yaml"))
	parser.add_argument("--workers", type=int, default=4)
	parser.add_argument("--reuse-browser", action="store_true")


import logging
import json
from pathlib import Path
from typing import Any, Dict

import sys

try:
	import jsonschema  # type: ignore
except Exception:
	jsonschema = None

def load_schema(root: Path) -> Dict[str, Any]:
	schema_path = root / "docs" / "schemas" / "trace.schema.json"
	return json.loads(schema_path.read_text(encoding="utf-8"))

def validate_file(schema: Dict[str, Any], jsonl_path: Path) -> int:
	if jsonschema is None:
		print("jsonschema not installed. Please pip install jsonschema.")


import logging
import argparse
import hashlib
import json
from pathlib import Path
from typing import Any, Dict, List

def sha256_file(path: Path) -> str:
	try:
		h = hashlib.sha256()
		with path.open("rb") as f:
			for chunk in iter(lambda: f.read(8192), b""):
				h.update(chunk)
		return h.hexdigest()
	except Exception:
		return ""

def list_dir_hash(root: Path) -> Dict[str, Any]:
	info: Dict[str, Any] = {"exists": root.exists(), "files": [], "digest": ""}


import logging
import json
from pathlib import Path
import sys

try:
	import jsonschema  # type: ignore
except Exception:
	jsonschema = None

def main() -> int:
	if len(sys.argv) < 2:
		print("Usage: validate_plan.py <plan.json>")
		return 2
	root = Path(__file__).resolve().parents[1]
	schema_path = root / "docs" / "schemas" / "plan.schema.json"
	plan_path = Path(sys.argv[1])

	if not schema_path.exists():
		print(f"Schema not found: {schema_path}")


import logging
import argparse
import json
from pathlib import Path
from typing import Any, Dict, Iterable, List

from agi_dw.bench.common.trace import write_jsonl

def iter_jsonl(path: Path) -> Iterable[Dict[str, Any]]:
	if not path.exists():
		return
	with path.open("r", encoding="utf-8") as f:
		for line in f:
			line = line.strip()
			if not line:
				continue
			try:
				yield json.loads(line)
			except Exception:
				continue


#!/usr/bin/env python3
import logging
import argparse
import json
import sys
from pathlib import Path
from typing import Any, Dict, List, Tuple

def load_json_with_dupe_detection(path: Path) -> Tuple[Dict[str, Any], List[str]]:
	dups: List[str] = []

	def hook(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]:
		seen: Dict[str, Any] = {}
		for k, v in pairs:
			if k in seen:
				dups.append(k)
			seen[k] = v  # keep last
		return seen

	obj = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=hook)


from __future__ import annotations
import logging

import json
import os
import subprocess
from datetime import datetime
from pathlib import Path
import importlib

def write_text(path: Path, text: str) -> None:
	path.parent.mkdir(parents=True, exist_ok=True)
	path.write_text(text, encoding="utf-8")

def run(cmd: list[str]) -> str:
	try:
		p = subprocess.run(cmd, capture_output=True, text=True, check=False)
		return (p.stdout or "") + ("\n" + p.stderr if p.stderr else "")
	except Exception as e:


def add(x, y):
	# Bug: should be x + y
	return x - y


from foo import add
def test_add():
	assert add(2, 3) == 5


#!/usr/bin/env python3
from __future__ import annotations
import logging

import argparse
import json
import math
import re
from pathlib import Path
from typing import Dict, Any, List, Tuple
import json
import sys
from pathlib import Path

TOKEN_RE = re.compile(r"[A-Za-z0-9_]+")

def tokenize(q: str) -> List[str]:
	return [t.lower() for t in TOKEN_RE.findall(q or "")]


#!/usr/bin/env python3
from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Dict, Any

def read_range(path: Path, start: int, end: int, max_bytes: int = 20000) -> Dict[str, Any]:
	if not path.exists() or not path.is_file():
		return {"ok": False, "error": "not_found", "path": str(path)}
	text = path.read_text(encoding="utf-8", errors="ignore")
	# Boundaries (1-based lines)
	lines = text.splitlines()
	n = len(lines)
	lo = max(1, int(start))
	hi = min(max(lo, int(end)), n)
	selected = "\n".join(lines[lo - 1:hi])
	if len(selected.encode("utf-8")) > max_bytes:


#!/usr/bin/env python3
from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Dict, Any, List

def summarize(question: str, snippets: List[Dict[str, Any]]) -> Dict[str, Any]:
	# Deterministic heuristic summary with basic de-dup and README preference
	parts: List[str] = []
	citations: List[Dict[str, Any]] = []
	seen: set[str] = set()
	# Prefer README/summary files first
	def rank(sn: Dict[str, Any]) -> tuple:
		p = str(sn.get("path", "")).lower()
		is_md = p.endswith(".md")
		is_readme = p.endswith("readme.md") or p.endswith("/readme")
		is_summary = p.endswith("summary.md")


#!/usr/bin/env python3
from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Any, Dict, List

TEMPLATE = (
	"You are a codebase QA model. Answer the user's QUESTION strictly based on the provided SNIPPETS.\n"
	"Rules:\n"
	"- Output ONLY a single JSON object with keys: answer (string), citations (list of objects with path,start,end).\n"
	"- The answer must be concise and faithful to the snippets; do not invent facts.\n"
	"- Every factual statement must be supported by at least one citation.\n"
	"- Citations must reference the given snippets' file paths and line ranges.\n"
	"- If evidence is insufficient, set answer to 'insufficient evidence' and citations to [].\n"
	"JSON schema:\n{\n  \"answer\": \"string\",\n  \"citations\": [{\"path\": \"/abs/path\", \"start\": 1, \"end\": 10}]\n}\n"
)


#!/usr/bin/env python3
from __future__ import annotations
import logging

import argparse
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any, Dict, List

def run_cmd(argv: List[str], cwd: Path | None = None) -> Dict[str, Any]:
	try:
		p = subprocess.run(argv, cwd=str(cwd) if cwd else None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
		return {"argv": argv, "rc": int(p.returncode), "stdout": p.stdout, "stderr": p.stderr}
	except Exception as e:
		return {"argv": argv, "rc": -1, "stdout": "", "stderr": str(e)}


#!/usr/bin/env python3
from __future__ import annotations
import logging

import argparse
import json
import os
from pathlib import Path
from typing import Dict, Any, List, Tuple

def _try_imports():
	try:
		from sentence_transformers import SentenceTransformer  # type: ignore
	except Exception as e:
		raise RuntimeError("sentence-transformers is required. pip install sentence-transformers") from e
	return SentenceTransformer

def iter_repo_files(root: Path, include_exts: List[str]) -> List[Path]:
	files: List[Path] = []


#!/usr/bin/env python3
from __future__ import annotations
import logging

import argparse
import json
import math
import os
import re
from pathlib import Path
from typing import Dict, Any, List, Tuple

TOKEN_RE = re.compile(r"[A-Za-z0-9_]+")

def iter_repo_files(root: Path, include_exts: List[str]) -> List[Path]:
	files: List[Path] = []
	for p in root.rglob("*"):
		if not p.is_file():
			continue


#!/usr/bin/env python3
from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Dict, Any

def main() -> int:
	ap = argparse.ArgumentParser(description="Minimal QA planner hook")
	root = Path(__file__).resolve().parents[2]
	ap.add_argument("--question", required=True)
	ap.add_argument("--bm25", default=str(root / "data" / "sandbox" / "tmp" / "bm25_index.json"))
	ap.add_argument("--embed", default=str(root / "data" / "sandbox" / "tmp" / "embed_index.json"))
	ap.add_argument("--k", type=int, default=20)
	ap.add_argument("--min-conf", type=float, default=0.6)
	args = ap.parse_args()

	# Heuristic: if both indexes exist, propose hybrid; else BM25 only


#!/usr/bin/env python3
from __future__ import annotations
import logging

import argparse
import json
from pathlib import Path
from typing import Dict, Any, List

def load_json_safe(p: Path) -> Dict[str, Any]:
	try:
		return json.loads(p.read_text(encoding="utf-8"))
	except Exception:
		return {}

def validate(citations: List[Dict[str, Any]], repo_root: Path, min_files: int = 1, min_lines_total: int = 20) -> Dict[str, Any]:
	ok = True
	checked: List[Dict[str, Any]] = []
	total_lines = 0


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.judge_longform')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.build.build_devtools_ds')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.data.verify_traces')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_dashboard_schema')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.emit_refactor_plan')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_scripts_alignment')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_planner_pref')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.pattern_based_expander')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.run_practice_suite')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.calibrate_planner_rerank')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.nightly_promotion')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.archive_makefile')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_code_quality')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_external')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.redteam_dom')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.data.validate_refactor_plan')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.bench.run_llm_bench')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.eval_probes')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.generate_router_negatives')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.generate_practice_curriculum')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.devtools.sandbox_exec')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.generate_curriculum')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.peek_actuator_preds')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.devtools.dev_loop_foreground')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.emit_plan')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_dom_verify')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_probes')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.build.build_actuator_il_splits')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_dashboard')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.build.build_balanced_traces')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.offpolicy_propose_repairs')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.build.build_wm_ds')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.promote_skills')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.count_models')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.loops.run_loop_webdom')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_code')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.train.train_actuator_il')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.init_llm_thresholds')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.run_external_bench')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_registry')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.devtools.dev_smoke')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.create_tiny_repos')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.data.snapshot_base_models')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.orchestrate_bench')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.build.build_actuator_il_combined')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.lint_code_samples')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.data.validate_patch_diff')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.create_comprehensive_dataset')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.loops.run_loop_dev')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.data.seed_traces')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.docs.generate_docs_index')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.nightly_il')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.update_all')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.ablate_wm_screen')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.run_code_bench')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.devtools.multi_agent_orchestrator')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_router_lift')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_router_metrics')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.data.seed_web_dom')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.move_completed_issues')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.eval.ci_assert_wm_planrank')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.train.train_router')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.devtools.rewrite_imports')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)


import logging
import importlib, sys
mod = importlib.import_module('scripts.misc.spreadsheet_demo')
sys.exit(getattr(mod, 'main', lambda:0)() if hasattr(mod, 'main') else 0)