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
fix(self-build): observe the prompts typed into panes and keep tests out of live data (#867)
Ruben Lütke50b96cef9073
diff --git a/docs/self-build-code.md b/docs/self-build-code.mdindex 307a72c3be..07b49670f8 100644--- a/docs/self-build-code.md+++ b/docs/self-build-code.md@@ -44,6 +44,12 @@ only when all of these hold:- the person works on it: opened in the IDE in the last 45 days, or their owncommits are among the recent ones.+The status (`GET /api/self-build`, `status.code`) carries the last pass:+which repositories were polled and, per reason, how many library projects were+not (for example `Dodaios' own source`), so a library without another project+of the person's says why nothing is polled. A change in that answer is logged+once.+Each repository is asked for issues at most every 30 minutes. Triage(`triage.py`) is plain Python. An issue is a candidate when it is open andunassigned; the person wrote it or it carries an agent label (`agent`,diff --git a/docs/self-build.md b/docs/self-build.mdindex 17ae36eb65..c21faf0ffa 100644--- a/docs/self-build.md+++ b/docs/self-build.md@@ -89,9 +89,10 @@ and one undoer for each of the four kinds, and the event subscriptions below.| `loop.py` | event intake, the gate, the decide queue, use counting, maintenance |**Observe.** Inputs are finished voice turns (`VoiceTurnCompleted`), the-person's own typed turns in the Jarvis chat and agent chats (the chat-surfaces' completion hook; turns an agent or routine started are dropped), and-the prompts the person types to coding agents in the IDE (channel `pane`).+person's own typed turns in the Jarvis chat, agent chats, the IDE's side chat+(channel `side`) and the IDE's agent chat (channel `pane`) (the chat surfaces'+completion hook; turns an agent or routine started are dropped), and the+prompts the person gives coding agents in the IDE (channel `pane`).Only the person's words are stored; tool names are kept as context, and theassistant's answer is read once for memory use (below), never stored.Requests are grouped by six-letter stems of their content words (the skill@@ -126,8 +127,27 @@ contents is skipped. The route tells the loop when such a prompt was stored,and each pass reads a history file from where the last one stopped, so aprompt is filed once; the maintenance pass catches a missed notice. While theloop is paused or off the read position still moves, so nothing typed then is-filed later. Prompts typed straight into a terminal (not through the app) are-not in the history and are not counted.+filed later.++**Prompts typed into a pane.** Most work in the IDE is typed or dictated+straight into a pane's terminal, which the prompt history does not see. A+Claude pane reports each prompt its CLI accepts through a `UserPromptSubmit`+hook (`agentic_ide/claude_session_hook.py`, next to the session hook; it+prints nothing, because that hook's output would join the prompt) into+`<pane>.prompts.jsonl` in the panes' state folder. Such a prompt is the+person's only when they pressed Enter in that pane's own window before it+(within 30 minutes: a prompt typed while the agent works is reported when its+turn starts); each Enter confirms one prompt. A prompt that matches one the+IDE itself sent to the pane (its prompt history) is skipped, as are slash+commands, shell lines, machine-made messages and steering with fewer than+three content words ("continue"). Other coding CLIs have no such hook; their+directly typed prompts are not counted.++Read offsets are kept per file; offsets of files that are gone or untouched+for longer than the 28-day window are pruned in the maintenance pass, and+files that old get none. The prompt history and the panes' state folder are+per instance, so a dev instance never feeds the main app's loop, and the test+suite redirects both.**Agent chats.** A request typed to a society agent is filed like any otherturn and also counts as a use of a self-built agent. Whose need it is followsdiff --git a/dodaios/agent_chat/surface_kits.py b/dodaios/agent_chat/surface_kits.pyindex 4ed9f6f03a..68c71ec689 100644--- a/dodaios/agent_chat/surface_kits.py+++ b/dodaios/agent_chat/surface_kits.py@@ -223,6 +223,14 @@ async def _jarvis_completed(session: Any, completion: ChatCompletion) -> None:await self_build_observe(session, completion, surface="jarvis")+async def _person_chat_completed(session: Any, completion: ChatCompletion) -> None:+ """The IDE's agent chat and side chat: the person's typed turns feed the+ self-building loop (lazy, a no-op when off)."""+ from dodaios.self_build.app import chat_turn_completed as self_build_observe++ await self_build_observe(session, completion, surface=str(getattr(session, "surface", "")))++def _society_history_start(session: Any) -> int:from dodaios.agent_chat.service import session_runnerfrom dodaios.society.runtime import current_runtime@@ -255,7 +263,7 @@ def _only_local_models(tools: dict[str, Tool]) -> dict[str, Tool]:# ── the table ─────────────────────────────────────────────────────────────_KITS: Final[dict[str, SurfaceKit]] = {- "agent": SurfaceKit(surface="agent", turn_prompts=True),+ "agent": SurfaceKit(surface="agent", turn_prompts=True, turn_completed=_person_chat_completed),"jarvis": SurfaceKit(surface="jarvis",brain_runner=True,@@ -332,6 +340,7 @@ _KITS: Final[dict[str, SurfaceKit]] = {cli_seats=True,plain_chat=_side_chat,workspace_dir=_chat_workspace,+ turn_completed=_person_chat_completed,),}diff --git a/dodaios/agentic_ide/claude_session_hook.py b/dodaios/agentic_ide/claude_session_hook.pyindex 9f93350206..0a06b75e3f 100644--- a/dodaios/agentic_ide/claude_session_hook.py+++ b/dodaios/agentic_ide/claude_session_hook.py@@ -1,4 +1,4 @@-"""Claude Code ``SessionStart`` hook: remember which conversation a pane is on.+"""Claude Code hooks of a pane: its conversation, and the prompts typed into it.Why this exists: a pane is resumed after a reboot through the conversation idit was launched with (``--session-id``). But that id is not stable for the@@ -14,6 +14,14 @@ CLI, and ``JARVIS_PANE_SESSIONS_DIR`` says where to write. One small JSON fileper pane, written atomically; the registry reads it before saving and beforeresuming (:mod:`dodaios.agentic_ide.session`).+The same script is the pane's ``UserPromptSubmit`` hook: every prompt the CLI+accepts is appended to ``<pane>.prompts.jsonl`` beside the session record.+The self-building loop reads those rows, and counts one only when the person+pressed Enter in the pane's own window right before it (``self_build/loop.py``):+a prompt Jarvis or an agent sent is not the person's. The hook prints nothing+on stdout, because Claude Code adds a ``UserPromptSubmit`` hook's stdout to the+prompt.+Deliberately stdlib-only and run as a plain script (not ``python -m``), so itstarts in tens of milliseconds and cannot slow the CLI's startup down, and itnever fails loudly: a hook that errors would print into the agent's pane.@@ -29,6 +37,12 @@ from pathlib import PathPANE_ENV = "JARVIS_PANE_ID"DIR_ENV = "JARVIS_PANE_SESSIONS_DIR"+#: The file of typed prompts beside a pane's session record.+PROMPTS_SUFFIX = ".prompts.jsonl"+#: A prompts file is started over past this size; the reader notices the shrink.+PROMPTS_MAX_BYTES = 256 * 1024+#: Characters of one prompt kept.+PROMPT_MAX_CHARS = 4000def _safe_name(pane_id: str) -> str:@@ -59,6 +73,36 @@ def record(pane_id: str, directory: Path, payload: dict) -> Path | None:return target+def prompts_file(pane_id: str, directory: Path) -> Path | None:+ name = _safe_name(pane_id)+ return directory / f"{name}{PROMPTS_SUFFIX}" if name else None+++def record_prompt(pane_id: str, directory: Path, payload: dict) -> Path | None:+ """Append the prompt the CLI just accepted; None when there is none."""+ prompt = str(payload.get("prompt") or "").strip()+ target = prompts_file(pane_id, directory)+ if not prompt or target is None:+ return None+ directory.mkdir(parents=True, exist_ok=True)+ try:+ if target.stat().st_size > PROMPTS_MAX_BYTES:+ target.unlink()+ except FileNotFoundError: # the pane's first prompt: there is no file to start over+ pass+ line = json.dumps(+ {+ "at": time.time(),+ "prompt": prompt[:PROMPT_MAX_CHARS],+ "session_id": str(payload.get("session_id") or ""),+ },+ ensure_ascii=False,+ )+ with target.open("a", encoding="utf-8", newline="\n") as handle:+ handle.write(line + "\n")+ return target++def main() -> int:pane_id = os.environ.get(PANE_ENV, "")directory = os.environ.get(DIR_ENV, "")@@ -67,7 +111,10 @@ def main() -> int:try:payload = json.loads(sys.stdin.read() or "{}")if isinstance(payload, dict):- record(pane_id, Path(directory), payload)+ if payload.get("hook_event_name") == "UserPromptSubmit":+ record_prompt(pane_id, Path(directory), payload)+ else:+ record(pane_id, Path(directory), payload)except Exception as exc: # noqa: BLE001 - a hook must never break the agent's start# Quiet on purpose, but not silent: stderr lands in Claude Code's own# hook log (``--debug``), never on the pane.diff --git a/dodaios/agentic_ide/pane_sessions.py b/dodaios/agentic_ide/pane_sessions.pyindex 1802fdabdb..9af115a745 100644--- a/dodaios/agentic_ide/pane_sessions.py+++ b/dodaios/agentic_ide/pane_sessions.py@@ -51,14 +51,15 @@ def settings_file() -> Path:# Forward slashes: Claude Code runs hook commands through bash on some# installs and cmd on others; a quoted forward-slash path works in both.command = f'"{_interpreter().as_posix()}" "{script.as_posix()}"'+ hook = [{"hooks": [{"type": "command", "command": command, "timeout": 10}]}]settings = {# No renderer override: a pane runs Claude Code the way the person set# it up. Forcing the classic renderer (for an exact scrollbar) made new# panes look cramped next to full-screen ones (reported 2026-10-20);# on the full-screen renderer the scrollbar falls back to app mode.- "hooks": {- "SessionStart": [{"hooks": [{"type": "command", "command": command, "timeout": 10}]}]- }+ # ``UserPromptSubmit`` records the prompts typed into the pane for the+ # self-building loop (docs/self-build.md); it prints nothing.+ "hooks": {"SessionStart": hook, "UserPromptSubmit": hook}}target = _state_dir().parent / "claude_session_hook.settings.json"text = json.dumps(settings, indent=2)@@ -100,6 +101,11 @@ def latest_session(pane_id: str) -> tuple[str, float] | None:return session_id, at+def prompts_dir() -> Path:+ """Where the panes' typed-prompt files live (``<pane>.prompts.jsonl``)."""+ return _state_dir()++def forget(pane_id: str) -> None:"""Drop a closed pane's record."""name = "".join(ch for ch in pane_id if ch.isalnum() or ch in "-_")[:80]@@ -113,4 +119,4 @@ def forget(pane_id: str) -> None:logger.debug("Agentic IDE: pane session record not removed: {}", exc)-__all__ = ["forget", "latest_session", "launch_wiring", "settings_file"]+__all__ = ["forget", "latest_session", "launch_wiring", "prompts_dir", "settings_file"]diff --git a/dodaios/agentic_ide/prompt_history.py b/dodaios/agentic_ide/prompt_history.pyindex fbca90aa08..03cad1889a 100644--- a/dodaios/agentic_ide/prompt_history.py+++ b/dodaios/agentic_ide/prompt_history.py@@ -92,9 +92,13 @@ def store_dir() -> Path:def _store_dir() -> Path:+ from dodaios.core.instance import current_instancefrom dodaios.core.paths import user_data_dir- return user_data_dir() / "agentic_ide" / "prompt_history"+ # Per instance: a dev instance's panes are not the main app's, and the+ # main app's self-building loop reads this folder as the person's prompts.+ suffix = current_instance().state_file_suffix+ return user_data_dir() / "agentic_ide" / f"prompt_history{suffix}"def path_for(history_id: str) -> Path:diff --git a/dodaios/self_build/app.py b/dodaios/self_build/app.pyindex 8c16c035ec..eb00adad6e 100644--- a/dodaios/self_build/app.py+++ b/dodaios/self_build/app.py@@ -62,6 +62,12 @@ def _pane_history() -> Path:return store_dir()+def _pane_typed() -> Path:+ from dodaios.agentic_ide.pane_sessions import prompts_dir++ return prompts_dir()++def install_in_app(service: Any, app_state: Any, bus: Any) -> SelfBuildLoop:"""Register the four builders and start observing (idempotent)."""existing = current()@@ -78,6 +84,7 @@ def install_in_app(service: Any, app_state: Any, bus: Any) -> SelfBuildLoop:society=_society_accessor(app_state),agent_skills=_agent_skills,pane_history=_pane_history,+ pane_typed=_pane_typed,)return install(service, env=env, bus=bus)@@ -96,6 +103,21 @@ def pane_prompt_recorded(history_id: str) -> None:log.warning("self_build: pane prompt not observed", exc_info=True)+def pane_keyboard_submit(history_id: str) -> None:+ """The person pressed Enter in a pane's own window; a no-op when off.++ The prompt the pane's CLI reports next (its ``UserPromptSubmit`` hook) is+ then the person's. Never raises into the terminal socket.+ """+ loop = current()+ if loop is None:+ return+ try:+ loop.pane_keyboard_submit(history_id)+ except Exception: # noqa: BLE001 - observation must never break typing+ log.warning("self_build: pane keystroke not observed", exc_info=True)++async def chat_turn_completed(session: Any, completion: Any, *, surface: str) -> None:"""The chat surfaces' hook (``agent_chat/surface_kits.py``); a no-op when off.diff --git a/dodaios/self_build/builders.py b/dodaios/self_build/builders.pyindex cae94c955a..8589266e38 100644--- a/dodaios/self_build/builders.py+++ b/dodaios/self_build/builders.py@@ -91,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+ #: The folder of the prompts Claude panes report as typed+ #: (``<pane>.prompts.jsonl``, ``agentic_ide/claude_session_hook.py``).+ pane_typed: 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 = Nonediff --git a/dodaios/self_build/code/intake.py b/dodaios/self_build/code/intake.pyindex 78b6d87a1c..94536cf74c 100644--- a/dodaios/self_build/code/intake.py+++ b/dodaios/self_build/code/intake.py@@ -106,25 +106,47 @@ def _brief(ctx: Context, folder: str, repo: str) -> Brief:return brief-def owned_projects(ctx: Context, who: Viewer) -> list[OwnedProject]:- """Blocking: git calls and brief refreshes for the person's own projects."""+def owned_projects(+ ctx: Context, who: Viewer, skipped: dict[str, int] | None = None+) -> list[OwnedProject]:+ """Blocking: git calls and brief refreshes for the person's own projects.++ ``skipped`` counts why each other library project is not polled.+ """out: list[OwnedProject] = []seen: set[str] = set()cutoff = time.time() - RECENT_DAYS * 86_400+ why = skipped if skipped is not None else {}++ def skip(reason: str) -> None:+ why[reason] = why.get(reason, 0) + 1+for project in ctx.projects():if getattr(project, "scratch", False) or getattr(project, "archived", False):+ skip("scratch or archived")continuefolder = _repo_root(str(getattr(project, "path", "") or ""))- if not folder or folder.lower() in seen:+ if not folder:+ skip("not a git repository")+ continue+ if folder.lower() in seen:continueseen.add(folder.lower())repo = repo_of(folder)- if not repo or not who.owns(repo) or is_dodaios_source(folder, ctx.dodaios_root):+ if not repo:+ skip("no GitHub origin")+ continue+ if not who.owns(repo):+ skip("not the person's repository")+ continue+ if is_dodaios_source(folder, ctx.dodaios_root):+ skip("Dodaios' own source")continuebrief = _brief(ctx, folder, repo)recent = float(getattr(project, "last_opened_at", 0) or 0) >= cutoffmine = bool((brief.parts.get("activity") or {}).get("person_active"))if not (recent or mine):+ skip("not worked on lately")continueout.append(OwnedProject(diff --git a/dodaios/self_build/code/loop.py b/dodaios/self_build/code/loop.pyindex 6c9195f6ae..1f3a5be716 100644--- a/dodaios/self_build/code/loop.py+++ b/dodaios/self_build/code/loop.py@@ -56,6 +56,9 @@ class CodeLoop:self._building: asyncio.Task[None] | None = Noneself._building_id = ""self._wake: asyncio.Event | None = None+ #: What the last pass did (``/api/self-build`` status ``code``).+ self.last_pass: dict[str, Any] = {}+ self._said: tuple[Any, ...] = ()# ------------------------------------------------------------ wiring@@ -124,7 +127,31 @@ class CodeLoop:# ------------------------------------------------------------ one pass+ def state(self) -> dict[str, Any]:+ """The last pass, for the status line: why nothing is polled is visible."""+ return dict(self.last_pass)+async def tick(self) -> dict[str, Any]:+ try:+ summary = await self._tick()+ except Exception as exc:+ self.last_pass = {"at_ms": now_ms(), "error": str(exc)[:300]}+ raise+ self.last_pass = {"at_ms": now_ms(), **summary}+ said = (summary.get("skipped"), tuple(summary.get("projects") or ()))+ if said != self._said:+ self._said = said+ if summary.get("skipped"):+ logger.info("self-build code: pass skipped: {}", summary["skipped"])+ elif not summary.get("projects"):+ logger.info(+ "self-build code: no project to poll ({})", summary.get("not_polled") or {}+ )+ else:+ logger.info("self-build code: polling {}", ", ".join(summary["projects"]))+ return summary++ async def _tick(self) -> dict[str, Any]:ctx = self.ctxcfg = ctx.config()if policy.autonomy(cfg, Kind.CODE) == policy.Autonomy.OFF:@@ -138,8 +165,10 @@ class CodeLoop:if who is None:summary["skipped"] = "github account unknown"return summary- projects = await asyncio.to_thread(intake.owned_projects, ctx, who)+ not_polled: dict[str, int] = {}+ projects = await asyncio.to_thread(intake.owned_projects, ctx, who, not_polled)summary["projects"] = [p.repo for p in projects]+ summary["not_polled"] = not_polledsummary["opened"] = await intake.intake(ctx, projects, who)summary["build"] = await self._maybe_build()return summary@@ -298,4 +327,5 @@ def install(service: Any, app_state: Any = None) -> CodeLoop:loop = CodeLoop(ctx)loop.attach()loop.start()+ service.code_loop = loopreturn loopdiff --git a/dodaios/self_build/loop.py b/dodaios/self_build/loop.pyindex e0c9635aae..45fb061b72 100644--- a/dodaios/self_build/loop.py+++ b/dodaios/self_build/loop.py@@ -3,12 +3,16 @@Wiring (all event-driven; nothing here runs on a timer that wakes a model):* **Observe.** Finished voice turns (``VoiceTurnCompleted``), the person's- own typed turns in the Jarvis chat and in agent chats (the chat surfaces'- completion hooks), and the prompts the person typed to coding agents in the- IDE (``agentic_ide/prompt_history.py`` rows marked ``origin: person``) go- to the :class:`~.miner.Miner`. Turns an agent or a routine started, and- prompts the brain or an agent sent to a pane, are dropped. Each turn costs- one SQLite insert.+ own typed turns in the Jarvis chat, in agent chats, in the IDE's agent chat+ and side chat (the chat surfaces' completion hooks), and the prompts the+ person gave coding agents in the IDE go to the :class:`~.miner.Miner`. A+ pane prompt is the person's when it came from the prompt bar+ (``agentic_ide/prompt_history.py`` rows marked ``origin: person``) or was+ typed into a Claude pane itself: the CLI reports it through its+ ``UserPromptSubmit`` hook (``agentic_ide/claude_session_hook.py``) and the+ person pressed Enter in that pane's window just before. Turns an agent or a+ routine started, and prompts the brain or an agent sent to a pane, are+ dropped. Each turn costs one SQLite insert.* **Gate.** A need that crossed its threshold is checked without a model:an open build, a rejected or archived one, a recent "build nothing", earlierfailed proofs, an installed skill that already serves it, and@@ -55,7 +59,7 @@ from . import brain, decide, judge, policyfrom .builders import KINDS, Builders, Env, need_jsonfrom .decide import Verdictfrom .ledger import now_ms-from .miner import PANE, WINDOW_DAYS, Miner, Need, Observation+from .miner import PANE, WINDOW_DAYS, Miner, Need, Observation, stemsfrom .records import BuildRecord, Kind, Outcome, State, caller_forfrom .signals import SignalStore, TurnRow@@ -88,6 +92,29 @@ ROUTINE_REACH_MS: Final[int] = 24 * 3_600_000_DONE: Final[frozenset[str]] = frozenset({"done", "ok", "completed"})#: Channels whose prompt carries the assistant's notebook (a memory can be used there)._NOTEBOOK_CHANNELS: Final[frozenset[str]] = frozenset({"voice", "chat"})+#: Channels whose turns go through the assistant's skill router.+_ROUTED_CHANNELS: Final[frozenset[str]] = frozenset({"voice", "chat"})+#: Chat surfaces whose typed turns are the person's, and the channel each is filed under.+#: The IDE's agent chat hands work to a coding agent, like a pane prompt.+CHAT_CHANNELS: Final[dict[str, str]] = {+ "jarvis": "chat",+ "society": "agent",+ "side": "side",+ "agent": PANE,+}+#: A prompt a Claude pane reports counts when the person pressed Enter in that+#: pane at most this long before (a prompt typed while the agent works is+#: queued by the CLI and reported when its turn starts).+TYPED_CONFIRM_S: Final[float] = 30 * 60.0+#: The CLI reports a prompt a moment after Enter: the pane is read this much later.+TYPED_READ_DELAY_S: Final[float] = 3.0+#: Enter presses remembered per pane (each confirms one reported prompt).+TYPED_KEEP: Final[int] = 32+#: A typed pane prompt needs this many content words to describe a task+#: ("continue", "yes do it" are steering, not a need).+TYPED_MIN_STEMS: Final[int] = 3+#: A prompt Jarvis or an agent sent to the pane is recognised within this long.+INJECTED_MATCH_S: Final[float] = 10 * 60.0_current: SelfBuildLoop | None = None@@ -128,6 +155,8 @@ class SelfBuildLoop:self._memory_hits: dict[str, tuple[str, int]] = {}#: One reader of the IDE's prompt histories at a time.self._pane_lock = asyncio.Lock()+ #: pane history id -> times the person pressed Enter in its window.+ self._keyboard: dict[str, list[float]] = {}#: Model calls made by the decide step (diagnostics and tests).self.decide_calls = 0@@ -268,16 +297,20 @@ class SelfBuildLoop:for e in eventsif e.get("kind") == "assistant_text")+ channel = CHAT_CHANNELS.get(surface)+ if channel is None:+ return # a surface nobody types to as themselvesagent_id = ""if surface == "society":from dodaios.society.surface import agent_id_ofagent_id = agent_id_of(str(session.session_id)) or ""+ channel = "agent" if agent_id else "chat"self._spawn(self.observe(Observation(text=text,- channel="agent" if agent_id else "chat",+ channel=channel,conversation=f"chat:{session.session_id}",tools=tuple(t for t in tools if t),failed=(bool(status) and status not in _DONE) or errors,@@ -537,7 +570,11 @@ class SelfBuildLoop:return [str(s.name) for s in self._installed_skills()]def _served(self, need: Need) -> str | None:- return judge.served_by(self._installed_skills(), [t.text for t in need.turns])+ """The installed skill that already catches the need, judged on the turns+ where the assistant's skill router runs: a coding agent in a pane or in+ the IDE's agent chat never routes to Dodaios' skills."""+ said = [t.text for t in need.turns if t.channel in _ROUTED_CHANNELS]+ return judge.served_by(self._installed_skills(), said) if said else Nonedef _served_by_agents(self, need: Need) -> tuple[str, str] | None:"""``(agent id, skill name)`` when an agent in the need's chats has a skill for it."""@@ -691,9 +728,15 @@ class SelfBuildLoop:found: list[Observation] = []for path in files:key = f"pane:{path.name}"+ try:+ stat = path.stat()+ except OSError: # gone or locked: the next pass reads it+ continue+ if paths is None and stat.st_mtime * 1000 < cutoff:+ continue # nothing in it is recent enough to count: no offset keptoffset = int(self.store.get_meta(key, "0") or 0)try:- size = path.stat().st_size+ size = stat.st_sizeif size < offset:offset = 0 # the file was replaced: read it againif size == offset:@@ -731,6 +774,159 @@ class SelfBuildLoop:)return found+ # ------------------------------------------------------------ prompts typed into a pane++ def pane_keyboard_submit(self, history_id: str) -> None:+ """The person pressed Enter in a pane's window: read what its CLI reports next."""+ if not history_id:+ return+ presses = self._keyboard.pop(history_id, [])+ presses.append(time.time())+ self._keyboard[history_id] = presses[-TYPED_KEEP:]+ while len(self._keyboard) > 256: # panes long closed+ self._keyboard.pop(next(iter(self._keyboard)))+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError: # no loop: the maintenance pass reads it+ return+ loop.call_later(+ TYPED_READ_DELAY_S,+ lambda: self._spawn(self.ingest_typed_prompts([history_id]), "typed-prompts"),+ )++ async def ingest_typed_prompts(self, panes: list[str] | None = None) -> int:+ """File the prompts Claude panes reported that the person typed there.++ ``panes`` ``None`` reads every pane the person pressed Enter in lately.+ A reported prompt counts when an Enter press in the pane's own window+ came before it (each press confirms one prompt), it is not a prompt+ the prompt bar, Jarvis or an agent sent (those are in the pane's prompt+ history), and it describes a task rather than steering one.+ """+ async with self._pane_lock:+ found = await asyncio.to_thread(self._read_typed_prompts, panes)+ if not found or not self._active():+ return 0+ for obs in sorted(found, key=lambda o: o.ts_ms):+ await self.observe(obs)+ return len(found)++ def _read_typed_prompts(self, panes: list[str] | None) -> list[Observation]:+ from dodaios.agentic_ide.claude_session_hook import prompts_file+ from dodaios.agentic_ide.prompt_history import path_for++ folder = self.builders.env.pane_typed()+ if folder is None:+ return []+ cutoff = now_ms() - WINDOW_DAYS * _DAY_MS+ found: list[Observation] = []+ for history_id in list(self._keyboard) if panes is None else panes:+ path = prompts_file(history_id, folder)+ if path is None:+ continue+ key = f"typed:{path.name}"+ offset = int(self.store.get_meta(key, "0") or 0)+ try:+ size = path.stat().st_size+ if size < offset:+ offset = 0 # the hook started the file over+ if size == offset:+ continue+ with path.open("rb") as handle:+ handle.seek(offset)+ data = handle.read()+ except OSError: # not written yet, or locked: the next pass reads it+ continue+ end = data.rfind(b"\n")+ if end < 0:+ continue+ chunk = data[: end + 1]+ self.store.set_meta(key, str(offset + len(chunk)))+ sent = self._sent_to_pane(history_id)+ conversation = f"pane:{path_for(history_id).stem[:16]}"+ for line in chunk.splitlines():+ try:+ row = json.loads(line)+ at = float(row.get("at") or 0.0)+ text = " ".join(str(row.get("prompt") or "").split())+ except (ValueError, TypeError, AttributeError): # a damaged row says nothing+ continue+ if not self._confirmed(history_id, at):+ continue # no Enter of the person came before it+ if not text or text[0] in "/!<" or int(at * 1000) < cutoff:+ continue # a command, a shell line, machine-made, or too old+ if any(+ abs(at - when) <= INJECTED_MATCH_S and _same_text(text, other)+ for when, other in sent+ ):+ continue # the prompt bar, Jarvis or an agent sent it+ if len(stems(text)) < TYPED_MIN_STEMS:+ continue+ found.append(+ Observation(+ text=text,+ channel=PANE,+ conversation=conversation,+ ts_ms=int(at * 1000),+ ref=f"pane-typed:{conversation[5:]}:{int(at * 1000)}",+ )+ )+ return found++ def _confirmed(self, history_id: str, at: float) -> bool:+ """Take the newest Enter press that came before ``at`` (and every older one)."""+ presses = self._keyboard.get(history_id) or []+ before = [p for p in presses if at - TYPED_CONFIRM_S <= p <= at + 2.0]+ if not before:+ return False+ newest = max(before)+ self._keyboard[history_id] = [p for p in presses if p > newest]+ return True++ def _sent_to_pane(self, history_id: str) -> list[tuple[float, str]]:+ """``(at, text)`` of every prompt the IDE itself sent to the pane (its prompt history)."""+ from dodaios.agentic_ide.prompt_history import PromptHistoryEntry, path_for++ folder = self.builders.env.pane_history()+ if folder is None:+ return []+ path = folder / path_for(history_id).name+ sent: list[tuple[float, str]] = []+ try:+ lines = path.read_bytes().splitlines()+ except OSError: # no prompt was ever sent through the IDE+ return []+ for line in lines[-200:]:+ try:+ entry = PromptHistoryEntry.from_dict(json.loads(line))+ except (ValueError, UnicodeDecodeError): # a damaged row says nothing+ continue+ if entry is not None:+ sent.append((entry.at, entry.text))+ if entry.typed:+ sent.append((entry.at, entry.typed))+ return sent++ def _prune_offsets(self) -> int:+ """Forget read offsets of pane files that are gone or older than the window. Blocking."""+ cutoff = now_ms() - WINDOW_DAYS * _DAY_MS+ stale: list[str] = []+ for prefix, folder in (+ ("pane:", self.builders.env.pane_history()),+ ("typed:", self.builders.env.pane_typed()),+ ):+ for key in self.store.meta_keys(prefix):+ if folder is None:+ stale.append(key)+ continue+ try:+ if (folder / key[len(prefix) :]).stat().st_mtime * 1000 >= cutoff:+ continue+ except OSError: # the file is gone+ pass+ stale.append(key)+ return self.store.delete_meta(stale)+def _live_for(self, signature: str) -> list[BuildRecord]:return [r for r in self.ledger.ever_for(signature) if r.state in (State.TRIAL, State.KEPT)]@@ -793,6 +989,10 @@ class SelfBuildLoop:await asyncio.to_thread(self.store.fill_clocks)# Pane prompts whose notice was missed (the app was busy or restarting).await self.ingest_pane_prompts()+ await self.ingest_typed_prompts()+ # Offsets of pane files that are gone or too old to count: the IDE+ # keeps a history file per pane ever opened.+ await asyncio.to_thread(self._prune_offsets)kept = await asyncio.to_thread(self.ledger.list, states=[State.KEPT], kinds=KINDS)for record in kept:last = max(record.last_used_ms, record.trial_started_ms, record.created_ms)@@ -843,6 +1043,16 @@ def _dodaios_idle_s() -> float | None:return presence.idle_s()+def _same_text(left: str, right: str) -> bool:+ """One prompt, as the IDE sent it and as the CLI reported it back."""+ a = " ".join(left.split()).casefold()+ b = " ".join(right.split()).casefold()+ if not a or not b:+ return False+ head = min(len(a), len(b), 200)+ return a == b or a[:head] == b[:head]++def _fields(obs: Observation) -> dict[str, Any]:return {name: getattr(obs, name) for name in Observation.__dataclass_fields__}diff --git a/dodaios/self_build/service.py b/dodaios/self_build/service.pyindex 1d23af7de2..147c4d0f7a 100644--- a/dodaios/self_build/service.py+++ b/dodaios/self_build/service.py@@ -52,6 +52,8 @@ class SelfBuild:self._tasks: set[asyncio.Task[None]] = set()self._sweeper: asyncio.Task[None] | None = Noneself.undo = UndoRegistry()+ #: The code builder's pass (``code/loop.py``), once installed.+ self.code_loop: Any = Noneself.ledger = BuildLedger(Path(data_dir) / DB_NAME, on_change=self._changed)# ------------------------------------------------------------ wiring@@ -84,6 +86,7 @@ class SelfBuild:"silent": policy.silent(self.ledger, cfg),"autonomy": {kind.value: policy.autonomy(cfg, kind).value for kind in Kind},"builders": sorted(kind.value for kind in self._builders),+ "code": self.code_loop.state() if self.code_loop is not None else {},}# ------------------------------------------------------------ person's actionsdiff --git a/dodaios/self_build/signals.py b/dodaios/self_build/signals.pyindex f920f3c8e4..2fdfc7b18c 100644--- a/dodaios/self_build/signals.py+++ b/dodaios/self_build/signals.py@@ -495,6 +495,23 @@ class SignalStore:self.set_meta(f"{key}:used", str(used + 1))return True+ def meta_keys(self, prefix: str) -> list[str]:+ """Every meta key that starts with ``prefix``."""+ with self._lock:+ rows = self._conn.execute(+ "SELECT key FROM meta WHERE substr(key, 1, ?) = ?", (len(prefix), prefix)+ ).fetchall()+ return [str(r[0]) for r in rows]++ def delete_meta(self, keys: Iterable[str]) -> int:+ values = [(k,) for k in keys]+ if not values:+ return 0+ with self._lock:+ self._conn.executemany("DELETE FROM meta WHERE key = ?", values)+ self._conn.commit()+ return len(values)+def get_meta(self, key: str, default: str = "") -> str:with self._lock:row = self._conn.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone()diff --git a/dodaios/ui/web/agentic_ide_routes.py b/dodaios/ui/web/agentic_ide_routes.pyindex df7777a2bd..d5c506a678 100644--- a/dodaios/ui/web/agentic_ide_routes.py+++ b/dodaios/ui/web/agentic_ide_routes.py@@ -144,7 +144,7 @@ from dodaios.agentic_ide.session import (terminals_added_event,workspace_changed_event,)-from dodaios.agentic_ide.terminal_input import is_terminal_report_only+from dodaios.agentic_ide.terminal_input import classify_terminal_input, is_terminal_report_onlyfrom dodaios.agentic_ide.workspace_view import (WORKSPACE_VIEWS,view_from_legacy_chat_flag,@@ -5843,9 +5843,16 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:term.name,)else:- registry.write(term.key, data, pane_workspace)+ pasting = term.bracketed_paste_active+ written = registry.write(term.key, data, pane_workspace)# The pane's own viewer: the person at the keyboard.presence.note(presence.PANE)+ if written and classify_terminal_input(data, pasting)[0]:+ # The person pressed Enter here: the prompt the pane's+ # CLI reports next is theirs (self-building loop).+ from dodaios.self_build.app import pane_keyboard_submit++ pane_keyboard_submit(term.history_id)elif kind == "r":# ``on_output`` identifies THIS socket. A pane open in two# places has two viewers and one pseudo-terminal, so a sizediff --git a/tests/conftest.py b/tests/conftest.pyindex fabceb24ff..830f3d10cf 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -144,11 +144,17 @@ def _agentic_ide_history_in_tmp(tmp_path_factory, monkeypatch): # noqa: ANN001protects the developer's data; the rule itself is verified against the realtemp directory in ``test_recents_scratch_folders.py``."""- from dodaios.agentic_ide import recents, resume_store+ from dodaios.agentic_ide import pane_sessions, prompt_history, recents, resume_storeroot = tmp_path_factory.mktemp("agentic-ide-history")monkeypatch.setattr(recents, "_store_path", lambda: root / "recents.json")monkeypatch.setattr(resume_store, "_store_path", lambda: root / "last_session.json")+ # The per-pane prompt histories and the panes' hook records: the running+ # app's self-building loop reads both as the person's own prompts. A run+ # of the IDE suites once left 20,000 history files there, six of them+ # marked as typed by the person, and the live app filed them as turns.+ monkeypatch.setattr(prompt_history, "_store_dir", lambda: root / "prompt_history")+ monkeypatch.setattr(pane_sessions, "_state_dir", lambda: root / "pane_sessions")monkeypatch.setattr(recents, "_temp_roots", list)yield rootdiff --git a/tests/unit/agentic_ide/test_pane_enter_reaches_self_build.py b/tests/unit/agentic_ide/test_pane_enter_reaches_self_build.pynew file mode 100644index 0000000000..2a7196f7f0--- /dev/null+++ b/tests/unit/agentic_ide/test_pane_enter_reaches_self_build.py@@ -0,0 +1,72 @@+"""Enter pressed in a pane's own window tells the self-building loop.++The prompt a Claude pane reports next is then the person's (docs/self-build.md,+"Prompts typed into a pane"). Typing without Enter, and a newline inside a+bracketed paste, press nothing.+"""++from __future__ import annotations++import time+from collections.abc import Iterator+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from dodaios.agentic_ide import session as session_mod+from dodaios.agentic_ide.session import Registry+from tests.fakes.fake_pty_manager import FakePtyManager+++def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ reg = Registry(pty_manager=FakePtyManager())+ monkeypatch.setattr(session_mod, "get_registry", lambda: reg)+ from dodaios.ui.web import agentic_ide_routes++ monkeypatch.setattr(agentic_ide_routes, "get_registry", lambda: reg)+ monkeypatch.setattr(agentic_ide_routes, "credentials_valid", lambda _scope: True)+ return reg+++def presses(monkeypatch: pytest.MonkeyPatch) -> list[str]:+ from dodaios.self_build import app++ seen: list[str] = []+ monkeypatch.setattr(app, "pane_keyboard_submit", seen.append)+ return seen+++def client(registry: Registry) -> Iterator[TestClient]:+ from dodaios.ui.web.agentic_ide_routes import router++ api = FastAPI()+ api.include_router(router)+ with TestClient(api) as ready:+ yield ready+++def _wait(predicate: object, timeout: float = 3.0) -> bool:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate(): # type: ignore[operator]+ return True+ time.sleep(0.02)+ return False+++def test_enter_in_the_pane_window_is_reported_and_typing_is_not(+ client: TestClient, registry: Registry, presses: list[str], tmp_path: Path+) -> None:+ session = client.portal.call(registry.start, str(tmp_path), [{"agent": "claude"}])+ term = session.terminals[0]+ with client.websocket_connect(f"/api/agentic-ide/pty/T1?workspace={session.id}") as socket:+ socket.send_json({"t": "i", "d": "count the lines"})+ socket.send_json({"t": "i", "d": "\x1b[200~line one\nline two\x1b[201~"})+ socket.send_json({"t": "i", "d": "\r"})+ assert _wait(lambda: presses == [term.history_id]), pressesdiff --git a/tests/unit/self_build/test_self_build_code.py b/tests/unit/self_build/test_self_build_code.pyindex d6f8a6287c..e9f28c5eee 100644--- a/tests/unit/self_build/test_self_build_code.py+++ b/tests/unit/self_build/test_self_build_code.py@@ -886,3 +886,26 @@ def test_github_not_answering_the_recheck_keeps_the_case_waiting(world: World) -del world.github.fresh[1]world.tick()assert world.service.ledger.get(record.id).state == State.PROVING+++# ------------------------------------------------------------------ why nothing is polled+++def test_a_library_of_only_dodaios_says_why_nothing_is_polled(world: World) -> None:+ (world.work / "dodaios" / "self_build").mkdir(parents=True) # Dodaios' own source+ world.loop.ctx.brief_checked.clear()+ world.service.code_loop = world.loop+ summary = world.tick()+ assert summary["projects"] == [] and summary["opened"] == 0+ assert summary["not_polled"] == {"Dodaios' own source": 1}+ status = world.service.status()["code"]+ assert status["not_polled"] == {"Dodaios' own source": 1} and status["at_ms"] > 0+ assert world.github.calls == ["viewer"] # no repository was asked for issues+++def test_the_status_carries_the_last_pass(world: World) -> None:+ world.service.code_loop = world.loop+ assert world.service.status()["code"] == {}+ world.tick()+ status = world.service.status()["code"]+ assert status["projects"] == ["me/proj"] and status["not_polled"] == {}diff --git a/tests/unit/self_build/test_self_build_typed_inputs.py b/tests/unit/self_build/test_self_build_typed_inputs.pynew file mode 100644index 0000000000..ddeaa2b7e9--- /dev/null+++ b/tests/unit/self_build/test_self_build_typed_inputs.py@@ -0,0 +1,342 @@+"""What the person really does in the app reaches the loop.++The maintainer works in the IDE: prompts typed or dictated straight into a+Claude pane, the side chat, the agent chat. Before this, only the prompt bar+counted, so weeks of work left the loop with nothing to look at.++* A prompt a Claude pane reports (its ``UserPromptSubmit`` hook) is the+ person's when they pressed Enter in that pane's window first, it is not a+ prompt the IDE itself sent, and it describes a task.+* The side chat and the IDE's agent chat feed the loop; a surface nobody types+ to as themselves does not.+* Read offsets of pane files that are gone or too old are pruned, and files+ too old to count get none.+"""++from __future__ import annotations++import asyncio+import json+import os+import time+from dataclasses import asdict+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from dodaios.agentic_ide import claude_session_hook+from dodaios.agentic_ide.prompt_history import PromptHistoryEntry, path_for+from dodaios.self_build import Kind, State, loop++from .test_self_build_inputs import PANE_ANSWER, PROMPT+from .test_self_build_loop import _days_ago, _person_zone # noqa: F401 - autouse fixture++PANE = "7f3c2a90b1d24e6f8a5b0c1d2e3f4a5b"+++def typed(world: Any, tmp_path: Path) -> Path:+ folder = tmp_path / "pane_sessions"+ history = tmp_path / "prompt_history"+ world.loop.builders.env.pane_typed = lambda: folder+ world.loop.builders.env.pane_history = lambda: history+ world.configure(skill="suggest")+ return folder+++def _report(folder: Path, prompt: str, at: float, pane: str = PANE) -> None:+ """What the pane's hook writes when the CLI accepts a prompt."""+ path = claude_session_hook.prompts_file(pane, folder)+ assert path is not None+ folder.mkdir(parents=True, exist_ok=True)+ with path.open("a", encoding="utf-8", newline="\n") as handle:+ handle.write(json.dumps({"at": at, "prompt": prompt, "session_id": "s"}) + "\n")+++def _enter(world: Any, at: float, pane: str = PANE) -> None:+ """The person pressed Enter in the pane's window at ``at``."""+ world.loop._keyboard.setdefault(pane, []).append(at)+++async def test_a_prompt_typed_into_a_pane_on_three_days_becomes_one_proposal(+ world: Any, typed: Path+) -> None:+ world.brain.answers = [PANE_ANSWER]+ for day in (6, 4, 2):+ at = _days_ago(day, 10) / 1000+ _enter(world, at - 0.2)+ _report(typed, PROMPT, at)+ assert await world.loop.ingest_typed_prompts([PANE]) == 3+ assert await world.loop.ingest_typed_prompts([PANE]) == 0 # read once+ turns = world.loop.store.recent_turns(since_ms=0)+ assert {t.channel for t in turns} == {"pane"} and len(turns) == 3+ assert turns[0].conversation == f"pane:{path_for(PANE).stem[:16]}"+ (card,) = await world.loop.run_queue()+ assert card.kind == Kind.SKILL and card.state == State.PROPOSED+++async def test_a_reported_prompt_without_the_persons_enter_is_not_theirs(+ world: Any, typed: Path+) -> None:+ at = _days_ago(1, 10) / 1000+ _report(typed, PROMPT, at)+ _enter(world, at + 60) # an Enter AFTER the prompt confirms nothing earlier+ assert await world.loop.ingest_typed_prompts([PANE]) == 0+ assert world.loop.store.recent_turns(since_ms=0) == []+++async def test_one_enter_confirms_one_prompt(world: Any, typed: Path) -> None:+ at = _days_ago(1, 10) / 1000+ _enter(world, at - 1)+ _report(typed, PROMPT, at)+ _report(typed, "rebuild the whole frontend bundle and redeploy it", at + 5)+ assert await world.loop.ingest_typed_prompts([PANE]) == 1+++async def test_a_prompt_the_ide_sent_is_not_the_persons_even_after_enter(+ world: Any, typed: Path, tmp_path: Path+) -> None:+ at = _days_ago(1, 10) / 1000+ history = tmp_path / "prompt_history"+ history.mkdir(parents=True)+ entry = PromptHistoryEntry("x", 1, f"{PROMPT}\n\nThe repo uses pytest.", at - 2, False)+ (history / path_for(PANE).name).write_text(json.dumps(asdict(entry)) + "\n", encoding="utf-8")+ # The person pressed Enter on a brief Jarvis left unsubmitted in the box.+ _enter(world, at - 0.5)+ _report(typed, f"{PROMPT}\n\nThe repo uses pytest.", at)+ assert await world.loop.ingest_typed_prompts([PANE]) == 0+++ "prompt",+ [+ "continue please", # steering, not a task+ "/clear",+ "!git status --short --branch now",+ "<teammate-message from='lead'>run the whole test suite</teammate-message>",+ ],+)+async def test_commands_and_steering_are_not_needs(world: Any, typed: Path, prompt: str) -> None:+ at = _days_ago(1, 10) / 1000+ _enter(world, at - 0.5)+ _report(typed, prompt, at)+ assert await world.loop.ingest_typed_prompts([PANE]) == 0+++async def test_enter_in_a_pane_reads_it_a_moment_later(+ world: Any, typed: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(loop, "TYPED_READ_DELAY_S", 0.0)+ world.loop._maintained = time.monotonic() # no maintenance pass+ world.loop.pane_keyboard_submit(PANE)+ _report(typed, PROMPT, time.time() + 0.1)+ for _ in range(50):+ await world.loop.drain()+ if world.loop.store.recent_turns(since_ms=0):+ break+ await asyncio.sleep(0.02)+ (turn,) = world.loop.store.recent_turns(since_ms=0)+ assert turn.text == PROMPT and turn.channel == "pane"+++async def test_the_maintenance_pass_reads_panes_the_person_typed_in(+ world: Any, typed: Path+) -> None:+ at = time.time() - 30+ _enter(world, at - 1)+ _report(typed, PROMPT, at)+ await world.loop.maintain()+ assert [t.text for t in world.loop.store.recent_turns(since_ms=0)] == [PROMPT]+++# ------------------------------------------------------------------ chat surfaces+++def _completion(text: str) -> Any:+ return SimpleNamespace(+ turn=SimpleNamespace(direct_user=True, user_text=text, turn_id="t1"),+ events_json=json.dumps(+ [+ {"kind": "user_message", "payload": {"text": text + "\n\nFiles...", "typed": text}},+ {"kind": "turn_finished", "payload": {"status": "done"}},+ ]+ ),+ )++[email protected](("surface", "channel"), [("side", "side"), ("agent", "pane")])+async def test_the_side_chat_and_the_agent_chat_are_the_person(+ world: Any, surface: str, channel: str+) -> None:+ text = "what does this queued sign on github mean"+ await world.loop.chat_turn_completed(+ SimpleNamespace(session_id="s1"), _completion(text), surface=surface+ )+ await world.loop.drain()+ (turn,) = world.loop.store.recent_turns(since_ms=0)+ assert turn.channel == channel and turn.text == text+++async def test_a_surface_nobody_types_to_as_themselves_is_not_filed(world: Any) -> None:+ await world.loop.chat_turn_completed(+ SimpleNamespace(session_id="s2"),+ _completion("set up the local model server for me"),+ surface="local-models",+ )+ await world.loop.drain()+ assert world.loop.store.recent_turns(since_ms=0) == []+++def test_the_ide_chats_carry_the_completion_hook() -> None:+ from dodaios.agent_chat.surface_kits import kit_for++ for surface in ("agent", "side", "jarvis", "society"):+ assert kit_for(surface).turn_completed is not None, surface+++# ------------------------------------------------------------------ offsets stay bounded+++async def test_offsets_of_gone_and_old_pane_files_are_pruned(world: Any, typed: Path) -> None:+ history = world.loop.builders.env.pane_history()+ history.mkdir(parents=True, exist_ok=True)+ fresh = history / "fresh.jsonl"+ old = history / "old.jsonl"+ for path in (fresh, old):+ path.write_text('{"id": "x"}\n', encoding="utf-8")+ month_ago = time.time() - 40 * 86_400+ os.utime(old, (month_ago, month_ago))+ store = world.loop.store+ for name in ("fresh.jsonl", "old.jsonl", "gone.jsonl"):+ store.set_meta(f"pane:{name}", "12")+ store.set_meta("typed:gone.prompts.jsonl", "40")+ store.set_meta("decide:day", "1") # not an offset: kept++ assert await asyncio.to_thread(world.loop._prune_offsets) == 3+ assert store.meta_keys("pane:") == ["pane:fresh.jsonl"]+ assert store.meta_keys("typed:") == []+ assert store.get_meta("decide:day") == "1"+++async def test_pane_files_too_old_to_count_get_no_offset(world: Any, typed: Path) -> None:+ history = world.loop.builders.env.pane_history()+ history.mkdir(parents=True, exist_ok=True)+ old = history / "old.jsonl"+ old.write_text('{"id": "x", "text": "t", "at": 1.0, "sequence": 1}\n', encoding="utf-8")+ month_ago = time.time() - 40 * 86_400+ os.utime(old, (month_ago, month_ago))+ assert await world.loop.ingest_pane_prompts() == 0+ assert world.loop.store.meta_keys("pane:") == []+++# ------------------------------------------------------------------ the hook itself+++def test_the_hook_appends_a_typed_prompt_and_prints_nothing(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+) -> None:+ import io++ monkeypatch.setenv(claude_session_hook.PANE_ENV, PANE)+ monkeypatch.setenv(claude_session_hook.DIR_ENV, str(tmp_path))+ payload = {"hook_event_name": "UserPromptSubmit", "prompt": PROMPT, "session_id": "abc"}+ monkeypatch.setattr("sys.stdin", io.StringIO(json.dumps(payload)))+ assert claude_session_hook.main() == 0+ # Claude Code adds this hook's stdout to the prompt: it must stay empty.+ assert capsys.readouterr().out == ""+ path = claude_session_hook.prompts_file(PANE, tmp_path)+ (row,) = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()]+ assert row["prompt"] == PROMPT and row["session_id"] == "abc"+ # The session record is not touched by a prompt.+ assert not (tmp_path / f"{PANE}.json").exists()+++def test_the_hook_starts_a_full_prompts_file_over(tmp_path: Path) -> None:+ path = claude_session_hook.prompts_file(PANE, tmp_path)+ path.write_text("x" * (claude_session_hook.PROMPTS_MAX_BYTES + 1), encoding="utf-8")+ claude_session_hook.record_prompt(PANE, tmp_path, {"prompt": PROMPT})+ assert path.stat().st_size < 1_000+++def test_the_pane_settings_add_the_prompt_hook() -> None:+ from dodaios.agentic_ide import pane_sessions++ argv, _env = pane_sessions.launch_wiring("pane-typed")+ settings = json.loads(Path(argv[1]).read_text(encoding="utf-8"))+ (entry,) = settings["hooks"]["UserPromptSubmit"]+ assert "claude_session_hook.py" in entry["hooks"][0]["command"]+++# ------------------------------------------------------------------ no test writes the live data+++def test_tests_never_write_the_real_prompt_history() -> None:+ from dodaios.agentic_ide import pane_sessions, prompt_history+ from dodaios.core.paths import user_data_dir++ real = user_data_dir().resolve()+ for folder in (prompt_history.store_dir(), pane_sessions.prompts_dir()):+ assert not folder.resolve().is_relative_to(real), folder+++def test_a_dev_instance_keeps_its_own_prompt_history(monkeypatch: pytest.MonkeyPatch) -> None:+ from dodaios.agentic_ide import prompt_history+ from dodaios.core import instance++ monkeypatch.undo() # the real resolver, not the test redirect+ dev = SimpleNamespace(state_file_suffix=".dev")+ monkeypatch.setattr(instance, "current_instance", lambda: dev)+ assert prompt_history._store_dir().name == "prompt_history.dev"+++# ------------------------------------------------------------------ served by a skill+++async def test_coding_agent_turns_are_not_served_by_an_assistant_skill(+ world: Any, typed: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A skill the assistant's router would pick says nothing about work a+ coding agent did: found live, the GitHub plugin's skill 'served' a request+ to count a checkout's lines and no proposal was made."""+ from dodaios.self_build import judge++ asked: list[list[str]] = []++ def router(_installed: Any, said: list[str]) -> str:+ asked.append(said)+ return "plugin-github"++ monkeypatch.setattr(judge, "served_by", router)+ world.brain.answers = [PANE_ANSWER]+ for day in (6, 4, 2):+ at = _days_ago(day, 10) / 1000+ _enter(world, at - 0.2)+ _report(typed, PROMPT, at)+ await world.loop.ingest_typed_prompts([PANE])+ (card,) = await world.loop.run_queue()+ assert card.kind == Kind.SKILL and asked == []+++# ------------------------------------------------------------------ voice+++async def test_a_finished_voice_turn_on_the_bus_is_filed(world: Any) -> None:+ """The event every voice path publishes reaches the miner over the app's bus."""+ from dodaios.core.events import VoiceTurnCompleted++ await world.bus.publish(+ VoiceTurnCompleted(+ session_id="call-1",+ turn_id="t1",+ user_text="what is on my calendar for tomorrow morning",+ user_lang="en",+ jarvis_text="Two meetings.",+ tool_calls=("calendar_list",),+ )+ )+ await world.loop.drain()+ (turn,) = world.loop.store.recent_turns(since_ms=0)+ assert turn.channel == "voice" and turn.conversation == "voice:call-1"+ assert turn.tools == ("calendar_list",) and turn.ref == "voice:call-1/t1"