Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(self-build): prove a drafted skill by running its steps read-only before it goes live (#793)
Ruben Lütkea54222dde0a7
diff --git a/docs/adr/0043-self-built-skills-go-live-on-trial.md b/docs/adr/0043-self-built-skills-go-live-on-trial.mdindex 6642efa47f..44c4cb93d2 100644--- a/docs/adr/0043-self-built-skills-go-live-on-trial.md+++ b/docs/adr/0043-self-built-skills-go-live-on-trial.md@@ -1,6 +1,6 @@# ADR-0043 — Skills the self-building loop proved go live on trial-**Status:** Accepted · **Date:** 2026-10-19+**Status:** Accepted · **Date:** 2026-10-19 · **Amended:** 2026-10-20 (execution proof)## Context@@ -37,7 +37,10 @@ Darwin Gödel Machine learned to game its own). <!-- i18n-allow: a proper name -(`dodaios.skills.eval_harness.route`) catches at least two thirds ofthem and fires on none of the person's other recent requests, theskill validator, the pre-promote lint and the duplicate check pass, and- it needs only tools the assistant used for those requests;+ it needs only tools the assistant used for those requests; and its+ steps, run read-only on one or two of those requests (see the+ amendment below), finish without a failed step, give an answer and+ reach the tools that answered the request the person accepted then;- `[self_build].skill` is `trial` or `full`, or the person accepted thebuild's card (which is itself the visible approval §6.7 asks for).2. **Every other path keeps the old rule.** Skills from an agent's own@@ -65,11 +68,46 @@ Darwin Gödel Machine learned to game its own). <!-- i18n-allow: a proper name -- A self-built skill can be wrong in a way the replay does not catch (itroutes correctly but its steps do a poor job). The trial bounds that: it islabelled, counted, corrected-against and archived when it does not help.-- The replay only proves routing and form. Executing the steps in a sandbox- would prove more but needs the full agent loop with tools; that is left- for a later change and the trial carries the risk meanwhile.+- The replay proves routing and form; the execution proof (amendment below)+ proves that the steps run. Neither proves that the answer is as good as+ the one the person accepted then: the person's answer text is not kept+ (the miner stores only their own words), so the comparison is structural.+ The trial carries the rest of the risk.- MASTERPLAN §6.7 and AP-SM6 now name this exception.+## Amendment 2026-10-20: the execution proof++The routing replay could pass a skill whose steps do not work. Before a skill+goes live, the builder now runs its steps (`dodaios/self_build/sandbox.py`):+the drafted body and one of the person's past requests, at most two requests,+newest first on different days, preferring ones the person accepted (answered,+not a correction, not corrected by their next turn).++- **Seat.** A signed-in subscription or a keyless local model, never a+ per-token key (rule 1). On a subscription the turn runs through the vendor+ CLI as an unattended scheduled task does: only the Dodaios gateway's tools+ (native tools isolated), the CLI's read-only permission mode, a tool scope+ of the tools the skill names plus the tools the assistant used for those+ requests, approvals denied. On a local model the tool loop runs in process+ with the same tools. Without either the build waits in `building`.+- **Side effects disabled.** Every call goes through `ToolExecutor` with the+ Plan-mode gate (`chat_read_only`): a tool runs only when its trusted+ metadata says it reads (`read_only` / `read_only_for_args`). Anything else+ is refused before it runs and recorded as *held back*. The working folder+ is a temporary directory, removed afterwards. Nothing is delivered.+- **Judge.** `judge.skill_execution`, deterministic Python over the recorded+ run: it finished, no step failed (a held-back step is reached, not+ failed), it answered, and it reached a tool family of the accepted answer+ when that answer used tools. A failure fails the build and records the+ lesson, like a failed replay.+- **Budget.** Each run takes one unit of the builder's existing daily budget+ (`DAILY_MODEL_CALLS`, six); no new budget was added. A run is one short+ tool loop (at most six rounds) and is attributed to the build in the cost+ ledger.++The decision above is unchanged: the judge still decides from recorded facts,+not from a model's verdict, and the builder cannot change what it checks.+## References- SkillsBench (2026): self-generated skills score below no skills.diff --git a/docs/self-build.md b/docs/self-build.mdindex 9bdd149ac2..af49d4b05e 100644--- a/docs/self-build.md+++ b/docs/self-build.md@@ -84,6 +84,7 @@ and one undoer for each of the four kinds, and the event subscriptions below.| `decide.py` | the one decide call: prompt, parse, the no-model fallback || `brain.py` | model access: signed-in subscriptions and local models only || `judge.py` | the proofs, pure Python |+| `sandbox.py` | runs a drafted skill's steps read-only on a past request (subscription or local seat, side-effect tools held back) || `builders.py` | build, undo, archive (dormant) and restore per kind || `loop.py` | event intake, the gate, the decide queue, use counting, maintenance |@@ -168,7 +169,7 @@ ledger; build calls `self_build:<id>`.| Kind | Built through | Proof | Archived means ||---|---|---|---|| memory | the learning notebook (`MEMORY.md`/`USER.md`) | the learning review's evidence check | entry removed, text kept |-| skill | the skill creator's writer, then the registry's `promote` ([ADR-0043](adr/0043-self-built-skills-go-live-on-trial.md)) | replay through the skill router, lint, duplicates, tools | switched off |+| skill | the skill creator's writer, then the registry's `promote` ([ADR-0043](adr/0043-self-built-skills-go-live-on-trial.md)) | replay through the skill router, lint, duplicates, tools; then its steps run read-only on one or two accepted requests (`sandbox.py`) | switched off || routine | a lead-owned Automations task on a subscription or local seat, no plugin grants, no announcement | schedule before 2/3 of the requests, grounded prompt, nothing outbound, a shadow run | paused || agent | `Roster.create` on a subscription or local seat | free name, clean instructions, focus from used tools, shadow answers | paused |diff --git a/dodaios/agent_chat/runner_cli.py b/dodaios/agent_chat/runner_cli.pyindex 9d1b76d485..df8e93a7bc 100644--- a/dodaios/agent_chat/runner_cli.py+++ b/dodaios/agent_chat/runner_cli.py@@ -3434,6 +3434,43 @@ def _agy_effective_effort(model: str, effort: str) -> str:return args[args.index("--effort") + 1] if "--effort" in args else ""+#: Codex features a task turn must not reach: only the Dodaios gateway's tools.+_CODEX_TASK_DISABLED: Final[tuple[str, ...]] = (+ "shell_tool",+ "apps",+ "hooks",+ "multi_agent",+ "browser_use",+ "web_search_request",+ "goals",+ "memories",+ "plugins",+ "computer_use",+ "image_generation",+ "multi_agent_v2",+)+++def isolate_task_tools(argv: list[str], runner: str) -> None:+ """Leave a task turn only the Dodaios gateway's tools (``gateway_only``), in place.++ An identity turn already carries some of codex's flags, and codex refuses+ a flag given twice, so each goes in once.+ """+ if runner == "claude-cli":+ argv += ["--tools", "", "--strict-mcp-config"]+ return+ if runner != "codex-cli":+ raise CliUnavailable("The selected runner cannot isolate task tools.")+ for flag in ("--ignore-user-config", "--ignore-rules"):+ if flag not in argv:+ argv.append(flag)+ disabled = {argv[i + 1] for i, arg in enumerate(argv[:-1]) if arg == "--disable"}+ for feature in _CODEX_TASK_DISABLED:+ if feature not in disabled:+ argv += ["--disable", feature]++async def _run_cli_once(handle: TurnHandle,user_text: str,@@ -3559,27 +3596,7 @@ async def _run_cli_once(plain_chat.attach_images, plan, runner, [Path(p) for p in images])if getattr(handle, "gateway_only", False):- if runner == "claude-cli":- plan.argv += ["--tools", "", "--strict-mcp-config"]- elif runner == "codex-cli":- plan.argv += ["--ignore-user-config", "--ignore-rules"]- for feature in (- "shell_tool",- "apps",- "hooks",- "multi_agent",- "browser_use",- "web_search_request",- "goals",- "memories",- "plugins",- "computer_use",- "image_generation",- "multi_agent_v2",- ):- plan.argv += ["--disable", feature]- else:- raise CliUnavailable("The selected runner cannot isolate task tools.")+ isolate_task_tools(plan.argv, runner)except CliUnavailable as exc:_release_plan(plan)return _Outcome("error", str(exc), {}, None, None)diff --git a/dodaios/self_build/builders.py b/dodaios/self_build/builders.pyindex c665843216..cae94c955a 100644--- a/dodaios/self_build/builders.py+++ b/dodaios/self_build/builders.py@@ -13,7 +13,8 @@ Each build runs the same stages on its ledger record:``building`` the spec exists (the decide step wrote it; for an accepted cardwritten without a model, it is written now). ``proving`` the judge(:mod:`.judge`) checks the spec, with a shadow run for routines and agents-that is produced on a subscription or local seat and delivered nowhere.+and a read-only run of a skill's steps (:mod:`.sandbox`), each produced on a+subscription or local seat and delivered nowhere.``trial`` the artefact is created, labelled as self-built and undoable. Afailed proof marks the build ``failed`` and records the lesson, so the samebuild is not tried again.@@ -57,9 +58,12 @@ _OTHER_REQUESTS: Final[int] = 60_DAY_MS: Final[int] = 86_400_000#: Shadow requests an agent must answer before it exists._AGENT_SHADOWS: Final[int] = 2-#: Model calls per day for writing specs and shadow runs (the decide step has-#: its own budget in loop.py). A routine costs one, an agent two.+#: Model calls per day for writing specs, shadow runs and skill replays (the+#: decide step has its own budget in loop.py). A routine costs one, an agent+#: two, a skill one per replay (at most :data:`SKILL_REPLAYS`).DAILY_MODEL_CALLS: Final[int] = 6+#: Past requests a drafted skill's steps are run on before it may go live.+SKILL_REPLAYS: Final[int] = 2ROUTINE_SHADOW_SYSTEM: Final[str] = ("You are running a scheduled routine for your user, as a dry run. Produce the result the "@@ -87,6 +91,9 @@ class Env:agent_skills: Callable[[str], list[Any]] = lambda _agent_id: []#: The folder of the IDE's per-pane prompt histories; ``None`` reads none.pane_history: Callable[[], Path | None] = lambda: None+ #: Runs a drafted skill's steps read-only on one request; ``None`` is+ #: :func:`.sandbox.run` (tests pass their own).+ run_skill: Callable[..., Awaitable[Any]] | None = Noneextra: dict[str, Any] = field(default_factory=dict)@@ -361,6 +368,14 @@ class Builders:)finally:await asyncio.to_thread(shutil.rmtree, scratch, True)+ if proof.passed:+ # Routing and form hold; now the steps themselves, read-only, on+ # requests the person made (may wait for a seat or the budget).+ runs, accepted = await self._execute_skill(record, need, draft)+ execution = judge.skill_execution(runs, accepted=accepted)+ proof = judge.Proof(+ execution.passed, proof.judge, f"{proof.detail}; {execution.detail}"+ )if not await self._prove(record, proof):returncreator = SkillCreatorService(registry=registry, bus=self.env.bus)@@ -396,6 +411,79 @@ class Builders:}await self._live(record, payload, payload, f"skill:{promoted.name}")+ async def _execute_skill(+ self, record: BuildRecord, need: Need, draft: dict[str, Any]+ ) -> tuple[list[Any], list[tuple[str, ...]]]:+ """Run the draft's steps read-only on up to :data:`SKILL_REPLAYS` past requests.++ Each run takes one unit of the daily build budget. Without a seat or+ budget for the first run the build waits (it stays ``building``).+ """+ from . import sandbox++ replays = await asyncio.to_thread(self._replays, need)+ tools = tuple(+ dict.fromkeys(+ [*draft["requires_tools"], *(t for turn in need.turns for t in turn.tools)]+ )+ )+ runner = self.env.run_skill or sandbox.run+ runs: list[Any] = []+ accepted: list[tuple[str, ...]] = []+ for turn in replays:+ if not await asyncio.to_thread(self.store.take_daily, "model_calls", DAILY_MODEL_CALLS):+ if runs:+ break+ raise Waiting("today's model budget for self-building is spent")+ try:+ with attributed(record.id):+ result = await runner(+ self.env.config(),+ skill_name=draft["name"],+ skill_body=draft["body"],+ request=turn.text,+ tools=tools,+ )+ except brain.BackgroundDeferred as exc:+ raise Waiting(str(exc)) from exc+ runs.append(result)+ accepted.append(turn.tools)+ return runs, accepted++ def _replays(self, need: Need) -> list[TurnRow]:+ """The requests to run a skill on: ones the person accepted, newest first.++ Accepted means answered (not failed), not itself a correction, and not+ corrected by the person's next turn in that conversation. A need made+ only of failures replays its newest failures: the steps must do better.+ """+ from .loop import CORRECTION_WINDOW_MS++ turns = sorted(need.turns, key=lambda t: t.ts_ms, reverse=True)+ accepted: list[TurnRow] = []+ for turn in turns:+ if turn.failed or turn.correction:+ continue+ after = self.store.turns_in(+ turn.conversation,+ since_ms=turn.ts_ms + 1,+ until_ms=turn.ts_ms + CORRECTION_WINDOW_MS,+ )+ if any(t.correction for t in after):+ continue+ accepted.append(turn)+ pool = accepted or turns+ picked: list[TurnRow] = []+ for turn in pool: # different days first: two replays of one morning say less+ if all(turn.day != p.day for p in picked):+ picked.append(turn)+ if len(picked) == SKILL_REPLAYS:+ return picked+ for turn in pool:+ if turn not in picked and len(picked) < SKILL_REPLAYS:+ picked.append(turn)+ return picked+def _candidate(self, scratch: Path, draft: dict[str, Any]) -> Any:"""The skill as it would load, parsed from a scratch copy (live state)."""from dodaios.skills.authoring.service import SkillCreateRequest, render_skill_md, slugifydiff --git a/dodaios/self_build/judge.py b/dodaios/self_build/judge.pyindex d1d1bb6df2..669f94d064 100644--- a/dodaios/self_build/judge.py+++ b/dodaios/self_build/judge.py@@ -14,7 +14,11 @@ What each kind must show (docs/self-build.md, "Prove"):* skill: a replay of the person's past requests through the production skillrouter: it must catch at least two thirds of them and fire on none of theperson's other recent requests, pass the skill validator, the pre-promote- lint and the duplicate check, and need only tools the assistant used;+ lint and the duplicate check, and need only tools the assistant used; then+ its steps, run read-only on one or two of those requests+ (:mod:`.sandbox`), must finish without a failed step, answer, and reach the+ tools that answered the request the person accepted then+ (:func:`skill_execution`);* routine: a calendar schedule that would have run before most of the pastrequests, a prompt grounded in them that asks for nothing outbound, and ashadow run that produced an answer;@@ -174,6 +178,53 @@ def skill()+def skill_execution(runs: list[Any], *, accepted: list[tuple[str, ...]]) -> Proof:+ """Compare read-only replays of a skill's steps with what the person accepted then.++ ``runs`` are :class:`.sandbox.Run` results, ``accepted`` the tools that+ answered each of those requests at the time (in the same order). The+ person's answer text is not kept (only their own words are), so what is+ compared is what can be: the replay finished, no step failed (a step held+ back because it would have had a side effect is reached, not failed), it+ produced an answer, and it reached at least one tool family of the+ accepted answer when that answer used tools.+ """+ from dodaios.self_build.miner import tool_family++ if not runs:+ return Proof.fail("skill", "the steps were not run on any past request")+ reached: list[str] = []+ held = 0+ for run, then in zip(runs, accepted, strict=False):+ quote = " ".join(str(run.request).split())[:60]+ if run.error:+ return Proof.fail("skill", f"the steps did not finish on {quote!r}: {run.error}")+ failed = [s for s in run.steps if not s.ok and not s.held]+ if failed:+ step = failed[0]+ detail = f": {step.error[:80]}" if step.error else ""+ return Proof.fail("skill", f"step {step.name!r} failed on {quote!r}{detail}")+ answer = " ".join(str(run.answer or "").split())+ if len(answer) < MIN_SHADOW_CHARS:+ return Proof.fail("skill", f"the steps gave no answer to {quote!r}")+ wanted = {tool_family(t) for t in then if t}+ used = {tool_family(s.name) for s in run.steps if s.name}+ if wanted and not wanted & used:+ return Proof.fail(+ "skill",+ f"the steps did not reach the tools the accepted answer to {quote!r} used "+ f"({', '.join(sorted(wanted))[:120]})",+ )+ reached += [s.name for s in run.steps if s.ok]+ held += sum(1 for s in run.steps if s.held)+ ran = ", ".join(dict.fromkeys(reached)) or "no tool"+ return Proof.ok(+ "skill",+ f"ran the steps read-only on {len(runs)} past request(s): {ran} ran, "+ f"{held} step(s) with side effects held back",+ )++def _fires(registry: Any, text: str, name: str) -> bool:from dodaios.skills.eval_harness import route@@ -382,4 +433,5 @@ __all__ = ["served_by","served_by_agent","skill",+ "skill_execution",]diff --git a/dodaios/self_build/sandbox.py b/dodaios/self_build/sandbox.pynew file mode 100644index 0000000000..a02bf227c3--- /dev/null+++ b/dodaios/self_build/sandbox.py@@ -0,0 +1,334 @@+"""Run a drafted skill's steps on a past request, read-only, before it may go live.++The routing replay (:func:`.judge.skill`) proves that a skill would catch the+person's requests; it says nothing about whether its steps work. This module+runs the steps: the drafted skill's body and one of the person's past requests+go to a model on a signed-in subscription or a keyless local seat, with the+tools the skill names (and the tools the assistant used for those requests)+offered through the app's own tool executor in read-only mode:++* Every call goes through ``ToolExecutor`` with ``chat_read_only`` set (the+ Plan-mode gate, ``core/tool_read_only.py``): a tool runs only when its+ trusted metadata says it reads (``read_only`` / ``read_only_for_args``).+ Anything else, a send, a write, a purchase, a post, is refused before it+ runs and recorded as *held back*: the step was reached, its side effect was+ not produced. Approvals are denied, never asked.+* The run's working folder is a fresh temporary directory, removed afterwards.+* On a subscription seat the turn runs through the vendor CLI with only the+ Dodaios gateway's tools (native tools isolated, ``gateway_only``), in the+ CLI's read-only permission mode, scoped to the named tools, exactly like an+ unattended scheduled task. On a local seat the model drives the tool loop in+ process.+* Nothing is delivered anywhere; the answer only goes to the judge.++What comes back is a :class:`Run`: the answer, every tool step (ran, failed or+held back) and whether the run itself finished. :func:`.judge.skill_execution`+compares it with what the person accepted then. Callers count each run against+the loop's daily build-call budget and wrap it in ``cost.attributed``.+"""++from __future__ import annotations++import asyncio+import logging+import re+import shutil+import tempfile+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Final+from uuid import uuid4++from . import brain++log = logging.getLogger(__name__)++#: Rounds of the in-process tool loop for one replay (a skill is a few steps).+MAX_ROUNDS: Final[int] = 6+#: A replay that takes longer than this failed.+TIMEOUT_S: Final[float] = 240.0+#: CLI runners that enforce a task's tool scope (``agent_chat/tasks.py``).+_SCOPED_RUNNERS: Final[frozenset[str]] = frozenset({"codex-cli", "claude-cli"})+#: The executor's refusal of a non-read tool in read-only mode.+HELD_MARKER: Final[str] = "permits reads only"++SYSTEM: Final[str] = (+ "You are testing a skill your user's assistant may adopt. Follow the skill's steps for the "+ "user's request below, as you would for real, using the tools offered. This is a dry run: "+ "tools that read work normally; any tool that would send, write, change, buy or post is "+ "held back and returns a refusal. When that happens, do not retry it or look for another "+ "way; note in one line what the step would have done and continue. End with the answer you "+ "would give the user, in the user's language."+)+++@dataclass(frozen=True, slots=True)+class Step:+ """One tool call of a replay."""++ name: str+ ok: bool+ #: Refused because it would have had a side effect: reached, not run.+ held: bool = False+ error: str = ""+++@dataclass(frozen=True, slots=True)+class Run:+ """One replay of a skill on one past request."""++ request: str+ answer: str+ steps: tuple[Step, ...] = ()+ #: Why the run itself did not finish (exception, timeout, a failed turn).+ error: str = ""+ seat: str = ""+++def prompt_for(skill_name: str, skill_body: str, request: str) -> str:+ return (+ f"# Skill: {skill_name}\n\n{skill_body.strip()}\n\n"+ f"# The user's request\n\n{request.strip()}"+ )+++def _canon(name: str) -> str:+ return re.sub(r"[^a-z0-9]", "", name.lower())+++def registered_name(called: str, allowed: tuple[str, ...]) -> str:+ """The registered tool a model's call names (CLIs prefix MCP tools, e.g. ``mcp__x__``)."""+ if called in allowed:+ return called+ bare = called.rsplit("__", 1)[-1] if called.startswith("mcp__") else called+ wanted = _canon(bare)+ for name in allowed:+ if _canon(name) == wanted:+ return name+ return called+++@dataclass+class _Recorder:+ """Wraps the app's executor: read-only, approvals denied, every call recorded."""++ executor: Any+ steps: list[Step] = field(default_factory=list)++ async def execute(self, tool: Any, args: dict[str, Any], **kwargs: Any) -> Any:+ from dodaios.core.protocols import ToolResult+ from dodaios.core.tool_read_only import allows_read++ name = str(getattr(tool, "name", "") or "")+ if not allows_read(tool, args):+ # Belt and braces: never handed to the executor at all.+ self.steps.append(Step(name, ok=False, held=True))+ return ToolResult(False, None, f"Held back in a dry run: this skill run {HELD_MARKER}")+ snapshot = dict(kwargs.pop("config_snapshot", None) or {})+ snapshot.update(+ {"chat_read_only": True, "unattended": True, "approval_surface": "unattended"}+ )+ result = await self.executor.execute(tool, args, config_snapshot=snapshot, **kwargs)+ error = str(getattr(result, "error", "") or "")+ held = HELD_MARKER in error+ self.steps.append(+ Step(name, ok=bool(getattr(result, "success", False)), held=held, error=error[:200])+ )+ return result+++def _live_tools() -> tuple[dict[str, Any], Any]:+ """The assistant's registered tools and its executor, or empty without a brain."""+ from dodaios.agent_chat.runner_brain import brain_manager++ manager = brain_manager()+ if manager is None:+ return {}, None+ return dict(getattr(manager, "_tools", {}) or {}), getattr(manager, "_tool_executor", None)+++async def run(+ config: Any,+ *,+ skill_name: str,+ skill_body: str,+ request: str,+ tools: tuple[str, ...],+) -> Run:+ """Replay the skill on ``request`` on the first seat that can drive tools.++ Raises :class:`brain.BackgroundDeferred` when no subscription or local seat+ can run it (nothing was billed); the build then waits.+ """+ live, executor = _live_tools()+ if executor is None:+ raise brain.BackgroundDeferred("the assistant's tools are not loaded yet")+ offered = {name: live[name] for name in tools if name in live}+ seats = await asyncio.to_thread(brain.seats, config)+ workdir = Path(tempfile.mkdtemp(prefix="dodaios-skill-proof-"))+ try:+ for seat in seats:+ if seat.billing.startswith("subscription"):+ from dodaios.core.task_agent import subscription_seat_off_loop++ pair = await subscription_seat_off_loop(seat.provider)+ if pair is None or pair[1] not in _SCOPED_RUNNERS:+ continue+ return await asyncio.wait_for(+ _run_cli(seat, pair, skill_name, skill_body, request, offered, workdir),+ timeout=TIMEOUT_S,+ )+ local = await asyncio.to_thread(brain._instantiate, seat)+ if local is None or not _calls_tools(local):+ continue+ return await asyncio.wait_for(+ _run_local(seat, local, skill_name, skill_body, request, offered, executor),+ timeout=TIMEOUT_S,+ )+ except TimeoutError: # not silent: the timeout is the failed proof the judge reports+ return Run(request, "", error=f"no answer within {TIMEOUT_S:.0f} s")+ finally:+ await asyncio.to_thread(shutil.rmtree, workdir, True)+ raise brain.BackgroundDeferred("no subscription or local seat can run a skill's steps")+++def _calls_tools(instance: Any) -> bool:+ probe = getattr(instance, "can_call_tools", None)+ if callable(probe):+ try:+ return bool(probe())+ except Exception: # noqa: BLE001 - an unanswerable probe means no tools+ log.debug("self_build: tool-calling probe of %s failed", instance, exc_info=True)+ return False+ return bool(getattr(instance, "supports_tools", False))+++async def _run_local(+ seat: Any,+ instance: Any,+ skill_name: str,+ skill_body: str,+ request: str,+ offered: dict[str, Any],+ executor: Any,+) -> Run:+ from dodaios.brain.iteration_budget import IterationBudget+ from dodaios.brain.tool_use_loop import ToolUseLoop+ from dodaios.core.protocols import BrainMessage++ recorder = _Recorder(executor)+ loop = ToolUseLoop(+ instance,+ offered,+ recorder, # type: ignore[arg-type]+ system_prompt=SYSTEM,+ budget=IterationBudget(max_turns=MAX_ROUNDS),+ max_tokens=2_000,+ tool_context={"delivery": "written", "unattended": True, "chat_read_only": True},+ )+ prompt = prompt_for(skill_name, skill_body, request)+ try:+ agg = await loop.run([BrainMessage(role="user", content=prompt)], user_utterance=request)+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - a run that breaks is the failed proof+ return Run(request, "", tuple(recorder.steps), f"{type(exc).__name__}", seat.provider)+ return Run(request, agg.text or "", tuple(recorder.steps), "", seat.provider)+++async def _run_cli(+ seat: Any,+ pair: tuple[str, str],+ skill_name: str,+ skill_body: str,+ request: str,+ offered: dict[str, Any],+ workdir: Path,+) -> Run:+ """An unattended, read-only CLI turn scoped to the offered tools (cf. ``agent_chat/tasks``)."""+ from dodaios.agent_chat.runner_api import TurnHandle+ from dodaios.agent_chat.runner_cli import run_cli_turn+ from dodaios.agent_chat.store import AgentChatSession+ from dodaios.core.protocols import ChatTurn, current_chat_turn+ from dodaios.core.task_agent import TaskToolScope, register_scope, release_scope+ from dodaios.core.tool_read_only import set_chat_read_only++ provider, runner = pair+ sid = "skill-proof-" + uuid4().hex+ trace = uuid4()+ allowed = tuple(offered)+ texts: list[str] = []+ calls: dict[str, str] = {}+ steps: list[Step] = []+ failure: list[str] = []++ async def emit(event: dict[str, Any]) -> None:+ kind = event.get("kind")+ payload = event.get("payload") or {}+ if kind == "assistant_text":+ texts.append(str(payload.get("text") or ""))+ elif kind == "tool_call":+ calls[str(payload.get("call_id") or "")] = registered_name(+ str(payload.get("name") or ""), allowed+ )+ elif kind == "tool_result":+ name = calls.pop(str(payload.get("call_id") or ""), "")+ output = str(payload.get("output") or payload.get("error") or "")+ error = bool(payload.get("is_error"))+ held = error and (HELD_MARKER in output or name not in allowed)+ steps.append(Step(name, ok=not error, held=held, error=output[:200] if error else ""))+ elif kind == "turn_finished" and payload.get("status") != "done":+ failure.append(str(payload.get("error") or payload.get("status") or "failed"))++ async def deny(*_args: Any) -> str:+ return "deny"++ session = AgentChatSession(+ sid,+ "Skill proof",+ provider,+ seat.model or "",+ "",+ str(workdir),+ "read-only",+ None,+ 0,+ 0,+ 0,+ "",+ surface="jarvis",+ )+ handle = TurnHandle(+ session=session,+ turn_id=str(trace),+ emit=emit,+ request_approval=deny,+ cancel=asyncio.Event(),+ trace_id=trace,+ surface="jarvis",+ gateway_only=True,+ )+ prompt = SYSTEM + "\n\n" + prompt_for(skill_name, skill_body, request)+ register_scope(sid, TaskToolScope(frozenset(allowed), trace, request))+ set_chat_read_only(sid, True)+ origin = current_chat_turn.set(ChatTurn(sid, str(trace), request, False, str(trace)))+ try:+ await run_cli_turn(handle, prompt, runner, identity=True)+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - a run that breaks is the failed proof+ failure.append(type(exc).__name__)+ finally:+ current_chat_turn.reset(origin)+ set_chat_read_only(sid, False)+ release_scope(sid)+ return Run(+ request,+ "\n".join(t for t in texts if t).strip(),+ tuple(steps),+ failure[-1] if failure else "",+ seat.provider,+ )+++__all__ = ["HELD_MARKER", "MAX_ROUNDS", "SYSTEM", "Run", "Step", "prompt_for", "run"]diff --git a/tests/unit/self_build/test_self_build_loop.py b/tests/unit/self_build/test_self_build_loop.pyindex 9883d22f22..ea5d61f764 100644--- a/tests/unit/self_build/test_self_build_loop.py+++ b/tests/unit/self_build/test_self_build_loop.py@@ -160,6 +160,19 @@ async def world(tmp_path: Path, fake_brain: FakeBrain):def switch(name: str, on: bool) -> None:skill_state[name] = "active" if on else "disabled"+ skill_runs: list[dict[str, Any]] = []++ async def run_skill(_config: Any, **kwargs: Any) -> Any:+ """The read-only replay of a skill's steps: every offered tool ran fine."""+ from dodaios.self_build.sandbox import Run, Step++ skill_runs.append(kwargs)+ return Run(+ kwargs["request"],+ "The latest CI run on main passed, nothing is failing.",+ tuple(Step(name, ok=True) for name in kwargs["tools"]),+ )+env = Env(config=lambda: config,data_dir=tmp_path,@@ -170,6 +183,7 @@ async def world(tmp_path: Path, fake_brain: FakeBrain):scheduler=lambda: scheduler,society=society,set_skill_on=switch,+ run_skill=run_skill,)the_loop = loop.install(service, env=env, bus=bus)world = SimpleNamespace(@@ -184,6 +198,8 @@ async def world(tmp_path: Path, fake_brain: FakeBrain):roster=roster,brain=fake_brain,skill_state=skill_state,+ skill_runs=skill_runs,+ env=env,)def configure(**changes: Any) -> None:diff --git a/tests/unit/self_build/test_self_build_skill_proof.py b/tests/unit/self_build/test_self_build_skill_proof.pynew file mode 100644index 0000000000..cc50f2e833--- /dev/null+++ b/tests/unit/self_build/test_self_build_skill_proof.py@@ -0,0 +1,377 @@+"""A drafted skill's steps run read-only on the person's past requests before it goes live."""++from __future__ import annotations++import asyncio+from collections.abc import AsyncIterator+from pathlib import Path+from typing import Any++import pytest++from dodaios.core.protocols import BrainDelta, BrainRequest, ToolResult+from dodaios.self_build import State, brain, builders, judge, sandbox+from dodaios.self_build.sandbox import Run, Step++from .test_self_build_loop import ( # noqa: F401 - _person_zone is an autouse fixture+ SKILL_ANSWER,+ _ask_for_status,+ _days_ago,+ _person_zone,+ _say,+ _settle,+)++TOOL = "mcp:github/list_runs"+++def _exists(path: str | Path) -> bool:+ return Path(path).exists()+++def _runner(world: Any, make: Any) -> list[dict[str, Any]]:+ calls: list[dict[str, Any]] = []++ async def run_skill(_config: Any, **kwargs: Any) -> Run:+ calls.append(kwargs)+ return make(kwargs)++ world.env.run_skill = run_skill+ return calls+++async def _built(world: Any) -> Any:+ world.brain.answers = [SKILL_ANSWER]+ await _ask_for_status(world)+ (opened,) = await world.loop.run_queue()+ return await _settle(world, opened.id)+++# ------------------------------------------------------------------ end to end+++async def test_a_skill_whose_steps_fail_in_the_sandbox_never_goes_on_trial(world: Any) -> None:+ _runner(+ world,+ lambda kw: Run(+ kw["request"], "Could not read the runs.", (Step(TOOL, False, error="403"),)+ ),+ )+ record = await _built(world)+ assert record.state == State.FAILED+ assert record.proof["passed"] is False+ assert "replay caught 3 of 3" in record.proof["detail"] # routing held, execution did not+ assert f"step {TOOL!r} failed" in record.proof["detail"]+ assert world.registry.list() == []+ assert world.loop.store.lessons(record.signature)[0][0] == "skill"+++async def test_a_run_that_does_not_finish_or_answer_fails(world: Any) -> None:+ _runner(world, lambda kw: Run(kw["request"], "", error="TimeoutError"))+ record = await _built(world)+ assert record.state == State.FAILED and "did not finish" in record.proof["detail"]+++async def test_steps_that_miss_the_tools_of_the_accepted_answer_fail(world: Any) -> None:+ _runner(+ world,+ lambda kw: Run(kw["request"], "I think the build is probably fine today.", ()),+ )+ record = await _built(world)+ assert record.state == State.FAILED+ assert "did not reach the tools" in record.proof["detail"]+++async def test_held_back_side_effects_do_not_fail_the_proof(world: Any) -> None:+ _runner(+ world,+ lambda kw: Run(+ kw["request"],+ "The latest run on main passed; I would have posted it to the team channel.",+ (Step(TOOL, True), Step("slack/post_message", False, held=True)),+ ),+ )+ record = await _built(world)+ assert record.state == State.TRIAL, record.note+ assert "ran the steps read-only on 2 past request(s)" in record.proof["detail"]+ assert "1 step(s) with side effects held back" not in record.proof["detail"] # two runs+ assert "2 step(s) with side effects held back" in record.proof["detail"]+++async def test_replays_use_accepted_requests_on_different_days(world: Any) -> None:+ calls = _runner(+ world,+ lambda kw: Run(kw["request"], "The latest run on main passed.", (Step(TOOL, True),)),+ )+ world.brain.answers = [SKILL_ANSWER]+ # The newest request was corrected by the person's next turn: not accepted.+ for days, hour in ((5, 9), (3, 14)):+ await _say(+ world,+ "Please check the build status of the dodaios repo",+ _days_ago(days, hour),+ tools=(TOOL,),+ )+ stamp = _days_ago(1, 17)+ await _say(+ world,+ "check the build status of the dodaios repo now",+ stamp,+ tools=(TOOL,),+ conversation="c",+ )+ await _say(world, "no, that's wrong, the other repository", stamp + 30_000, conversation="c")+ (opened,) = await world.loop.run_queue()+ record = await _settle(world, opened.id)+ assert record.state == State.TRIAL, record.note+ assert len(calls) == 2+ assert all(c["request"] == "Please check the build status of the dodaios repo" for c in calls)+ assert TOOL in calls[0]["tools"]+ assert calls[0]["skill_body"].startswith("## Check Build Status")+++async def test_without_budget_or_seat_the_skill_waits_in_building(world: Any, monkeypatch) -> None:+ async def no_seat(_config: Any, **_kwargs: Any) -> Run:+ raise brain.BackgroundDeferred("no seat can run a skill's steps")++ world.env.run_skill = no_seat+ world.brain.answers = [SKILL_ANSWER]+ await _ask_for_status(world)+ (opened,) = await world.loop.run_queue()+ for _ in range(25):+ await asyncio.sleep(0.02)+ record = world.service.ledger.get(opened.id)+ assert record.state == State.BUILDING and world.registry.list() == []++ monkeypatch.setattr(builders, "DAILY_MODEL_CALLS", 0)+ _runner(world, lambda kw: Run(kw["request"], "The latest run on main passed.", ()))+ await world.loop.builders.build(record)+ assert world.service.ledger.get(record.id).state == State.BUILDING+++def test_execution_judge_rules() -> None:+ ok = Run("check the build", "The latest run on main passed fine.", (Step(TOOL, True),))+ assert judge.skill_execution([ok], accepted=[(TOOL,)]).passed+ # The accepted answer used no tool: reaching none is fine.+ bare = Run("explain the build", "It compiles the sources and runs tests.", ())+ assert judge.skill_execution([bare], accepted=[()]).passed+ assert not judge.skill_execution([], accepted=[]).passed+ other = Run(+ "check the build", "Searched the web for it, all good.", (Step("web_search", True),)+ )+ assert not judge.skill_execution([other], accepted=[(TOOL,)]).passed+ # Same family, other operation: reached.+ sibling = Run("check", "The latest run on main passed.", (Step("mcp:github/get_run", True),))+ assert judge.skill_execution([sibling], accepted=[(TOOL,)]).passed+++# ------------------------------------------------------------------ the sandbox itself+++class _ReadTool:+ name = "wiki-recall"+ read_only = True+ schema: dict[str, Any] = {}+ description = "read the wiki"+++class _WriteTool:+ name = "send_email"+ schema: dict[str, Any] = {}+ description = "send an email"+++class _Executor:+ def __init__(self, result: ToolResult | None = None) -> None:+ self.calls: list[tuple[str, dict[str, Any]]] = []+ self.result = result or ToolResult(True, "the page says: CI is green")++ async def execute(self, tool: Any, args: dict[str, Any], **kwargs: Any) -> ToolResult:+ self.calls.append((tool.name, dict(kwargs.get("config_snapshot") or {})))+ return self.result+++async def test_the_recorder_runs_reads_and_holds_back_everything_else() -> None:+ executor = _Executor()+ recorder = sandbox._Recorder(executor)+ held = await recorder.execute(_WriteTool(), {"to": "x"}, config_snapshot={})+ assert held.success is False and sandbox.HELD_MARKER in held.error+ assert executor.calls == [] # never reached the executor+ await recorder.execute(_ReadTool(), {"q": "ci"}, config_snapshot={"cwd": "x"})+ ((name, snapshot),) = executor.calls+ assert name == "wiki-recall" and snapshot["chat_read_only"] is True+ assert snapshot["approval_surface"] == "unattended"+ assert [(s.name, s.ok, s.held) for s in recorder.steps] == [+ ("send_email", False, True),+ ("wiki-recall", True, False),+ ]+ refused = sandbox._Recorder(_Executor(ToolResult(False, None, "Plan mode permits reads only")))+ await refused.execute(_ReadTool(), {}, config_snapshot={})+ assert refused.steps[0].held and not refused.steps[0].ok+ broken = sandbox._Recorder(_Executor(ToolResult(False, None, "HTTP 500")))+ await broken.execute(_ReadTool(), {}, config_snapshot={})+ assert not broken.steps[0].held and broken.steps[0].error == "HTTP 500"+++class _ToolBrain:+ """Reads the wiki, tries to send an email, then answers."""++ name = "local"+ supports_tools = True+ supports_vision = False+ context_window = 32_000++ def __init__(self) -> None:+ self.requests: list[BrainRequest] = []++ def estimate_cost(self, _req: BrainRequest) -> float:+ return 0.0++ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:+ self.requests.append(req)+ if len(self.requests) == 1:+ yield BrainDelta(tool_call={"id": "a", "name": "wiki-recall", "input": {"q": "ci"}})+ yield BrainDelta(tool_call={"id": "b", "name": "send_email", "input": {"to": "x"}})+ yield BrainDelta(finish_reason="tool_use")+ return+ yield BrainDelta(content="CI is green on main. The email step was held back.")+ yield BrainDelta(finish_reason="stop")+++async def test_a_local_seat_drives_the_tool_loop_read_only(monkeypatch, tmp_path: Path) -> None:+ executor = _Executor()+ tools = {"wiki-recall": _ReadTool(), "send_email": _WriteTool(), "other": _ReadTool()}+ monkeypatch.setattr(sandbox, "_live_tools", lambda: (tools, executor))+ monkeypatch.setattr(brain, "seats", lambda _c: [brain.Seat("ollama", "m", "local")])+ fake = _ToolBrain()+ monkeypatch.setattr(brain, "_instantiate", lambda _seat: fake)+ made: list[str] = []+ real_mkdtemp = sandbox.tempfile.mkdtemp++ def mkdtemp(**kwargs: Any) -> str:+ made.append(real_mkdtemp(dir=tmp_path, **kwargs))+ return made[-1]++ monkeypatch.setattr(sandbox.tempfile, "mkdtemp", mkdtemp)+ run = await sandbox.run(+ None,+ skill_name="CI status",+ skill_body="1. Read the wiki page about CI.\n2. Email the team.",+ request="how is CI doing",+ tools=("wiki-recall", "send_email"),+ )+ assert run.error == "" and run.seat == "ollama"+ assert "CI is green" in run.answer+ assert [(s.name, s.ok, s.held) for s in run.steps] == [+ ("wiki-recall", True, False),+ ("send_email", False, True),+ ]+ assert [name for name, _ in executor.calls] == ["wiki-recall"]+ # Only the named tools were offered, and the working folder is gone.+ offered = {t["name"] for t in fake.requests[0].tools or ()} if fake.requests[0].tools else set()+ assert "other" not in offered+ assert made and not _exists(made[0])+++async def test_no_executor_or_no_seat_defers_and_bills_nothing(monkeypatch) -> None:+ monkeypatch.setattr(sandbox, "_live_tools", lambda: ({}, None))+ with pytest.raises(brain.BackgroundDeferred):+ await sandbox.run(None, skill_name="x", skill_body="1. x", request="x", tools=())+ monkeypatch.setattr(sandbox, "_live_tools", lambda: ({}, _Executor()))+ monkeypatch.setattr(brain, "seats", lambda _c: [])+ with pytest.raises(brain.BackgroundDeferred):+ await sandbox.run(None, skill_name="x", skill_body="1. x", request="x", tools=())+++async def test_a_subscription_seat_runs_a_scoped_read_only_cli_turn(monkeypatch) -> None:+ from dodaios.agent_chat import runner_cli+ from dodaios.core import task_agent, tool_read_only++ tools = {"wiki-recall": _ReadTool(), "send_email": _WriteTool()}+ monkeypatch.setattr(sandbox, "_live_tools", lambda: (tools, _Executor()))+ monkeypatch.setattr(brain, "seats", lambda _c: [brain.Seat("codex", None, "subscription")])++ async def seat(_provider: str) -> tuple[str, str]:+ return ("openai-codex", "codex-cli")++ monkeypatch.setattr(task_agent, "subscription_seat_off_loop", seat)+ seen: dict[str, Any] = {}++ async def fake_turn(handle: Any, prompt: str, runner: str, *, identity: bool = False) -> None:+ sid = handle.session.session_id+ seen.update(+ runner=runner,+ identity=identity,+ gateway_only=handle.gateway_only,+ mode=handle.session.permission_mode,+ cwd_exists=_exists(handle.session.cwd),+ cwd=handle.session.cwd,+ scope=task_agent.scope_for(sid),+ read_only=tool_read_only.chat_is_read_only(sid),+ prompt=prompt,+ )+ assert await handle.request_approval("send_email", "x", {}, "y") == "deny"+ emit = handle.emit+ refused = "Plan mode permits reads only"+ for kind, payload in (+ ("tool_call", {"call_id": "1", "name": "mcp__dodaios__wiki-recall"}),+ ("tool_result", {"call_id": "1", "output": "ok", "is_error": False}),+ ("tool_call", {"call_id": "2", "name": "mcp__dodaios__send_email"}),+ ("tool_result", {"call_id": "2", "output": refused, "is_error": True}),+ ):+ await emit({"kind": kind, "payload": payload})+ await emit({"kind": "assistant_text", "payload": {"text": "CI is green on main."}})+ await emit({"kind": "turn_finished", "payload": {"status": "done"}})++ monkeypatch.setattr(runner_cli, "run_cli_turn", fake_turn)+ run = await sandbox.run(+ None,+ skill_name="CI status",+ skill_body="1. Read the wiki.\n2. Email the team.",+ request="how is CI doing",+ tools=("wiki-recall", "send_email"),+ )+ assert seen["runner"] == "codex-cli" and seen["identity"] and seen["gateway_only"]+ assert seen["mode"] == "read-only" and seen["cwd_exists"] and seen["read_only"]+ assert seen["scope"].names == frozenset({"wiki-recall", "send_email"})+ assert "how is CI doing" in seen["prompt"] and "dry run" in seen["prompt"]+ assert not _exists(seen["cwd"]) # the temporary folder is gone+ sid_scopes = [s for s in task_agent._scopes if s.startswith("skill-proof-")]+ assert sid_scopes == [] # scope released+ assert run.error == "" and run.answer == "CI is green on main."+ assert [(s.name, s.ok, s.held) for s in run.steps] == [+ ("wiki-recall", True, False),+ ("send_email", False, True),+ ]+++def test_cli_tool_names_map_back_to_registered_names() -> None:+ allowed = ("mcp:github/list_runs", "wiki-recall")+ assert sandbox.registered_name("mcp__dodaios__wiki_recall", allowed) == "wiki-recall"+ assert sandbox.registered_name("wiki-recall", allowed) == "wiki-recall"+ assert sandbox.registered_name("mcp__dodaios__mcp_github_list_runs", allowed) == (+ "mcp:github/list_runs"+ )+ assert sandbox.registered_name("Bash", allowed) == "Bash"+++def test_the_daily_budget_covers_the_replays() -> None:+ assert builders.SKILL_REPLAYS <= builders.DAILY_MODEL_CALLS+ assert asyncio.iscoroutinefunction(sandbox.run)+++def test_a_codex_task_turn_with_identity_gives_each_flag_once() -> None:+ """Live 2026-10-20: identity + gateway_only passed --ignore-user-config twice; codex refused."""+ from dodaios.agent_chat.runner_cli import isolate_task_tools++ argv = ["codex", "exec", "--json", "--ignore-user-config", "--ignore-rules"]+ argv += ["--disable", "browser_use", "--disable", "plugins"]+ isolate_task_tools(argv, "codex-cli")+ assert argv.count("--ignore-user-config") == 1 and argv.count("--ignore-rules") == 1+ features = [argv[i + 1] for i, a in enumerate(argv[:-1]) if a == "--disable"]+ assert len(features) == len(set(features)) and "shell_tool" in features+ claude = ["claude", "-p"]+ isolate_task_tools(claude, "claude-cli")+ assert claude[-3:] == ["--tools", "", "--strict-mcp-config"]+ with pytest.raises(Exception, match="cannot isolate"):+ isolate_task_tools([], "agy-cli")