diff --git a/README.cn.md b/README.cn.md index d0162a154..42f25f165 100644 --- a/README.cn.md +++ b/README.cn.md @@ -168,7 +168,7 @@ TUI 内:`Esc` 中断流式输出,`Ctrl+C` / `exit` 退出(配置与 GUI | | Claude Code | Codex | DeepSeek Harness | **EMRG** | **Grok Bot** | |---|---|---|---|---|---| | AI 驱动编程 | ✅ | ✅ | ✅ | ✅ | ✅ | -| 工具调用 (`bash`/`pwsh`、`read`、`write`、`edit`、`glob`、`grep`、`submit_rant`、`subagent`、`boss`) | ✅ | ✅ | ✅ | ✅ | ✅ | +| 工具调用 (`bash`/`pwsh`、`read`、`write`、`edit`、`glob`、`grep`、`submit_rant`、`subagent`) | ✅ | ✅ | ✅ | ✅ | ✅ | | 会话记忆与上下文 | ✅ | ✅ | ✅ | ✅ | ✅ | | `/` 命令自动补全 | ✅ | ✅ | ✅ | ✅ | ~ *@ mention 建议 + 命令面板* | | ESC 中断 | ✅ | ✅ | — | ✅ | ✅ | diff --git a/README.md b/README.md index 766ef5ada..27591c28f 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ In the TUI: `Esc` interrupts streaming, `Ctrl+C` / `exit` quits (config is share | | Claude Code | Codex | DeepSeek Harness | **EMRG** | **Grok Bot** | |---|---|---|---|---|---| | AI-powered coding | ✅ | ✅ | ✅ | ✅ | ✅ | -| Tool-calling (`bash`/`pwsh`, `read`, `write`, `edit`, `glob`, `grep`, `submit_rant`, `subagent`, `boss`) | ✅ | ✅ | ✅ | ✅ | ✅ | +| Tool-calling (`bash`/`pwsh`, `read`, `write`, `edit`, `glob`, `grep`, `submit_rant`, `subagent`) | ✅ | ✅ | ✅ | ✅ | ✅ | | Session memory & context | ✅ | ✅ | ✅ | ✅ | ✅ | | `/` command autocomplete | ✅ | ✅ | ✅ | ✅ | ~ *@ mention + command palette* | | ESC interrupt | ✅ | ✅ | — | ✅ | ✅ | diff --git a/emrg/server/agents.py b/emrg/server/agents.py index 724b65e99..03f905a60 100644 --- a/emrg/server/agents.py +++ b/emrg/server/agents.py @@ -43,8 +43,8 @@ under ``~/.emrg/sessions/``, beside the runtime configuration. That mixes "where this installation keeps its files" into "a directory someone works in", and the register is the second thing only; -* **any directory under an existing Agent's ``.emrg/``** — the sub-session slot, the - boss session, every directory the server derives. Those are that Agent's own +* **any directory under an existing Agent's ``.emrg/``** — the sub-session slot, and + every other directory the server derives. Those are that Agent's own bookkeeping, reached through its path; they are not directories a host opened, and a row for one would claim the bookkeeping is a workspace. The test is the path alone, so it needs no name, no flag and no knowledge of who created the session. @@ -219,7 +219,7 @@ def for_dir(self, cwd: str | os.PathLike[str]) -> dict: return row # A directory under an existing Agent's `.emrg/` is that Agent's bookkeeping - # (the sub-session slot, the boss session), not a directory a host opened. + # (the sub-session slot), not a directory a host opened. for row in rows: inner = os.path.join(row.get("path") or "", ".emrg") if base == inner or base.startswith(inner + os.sep): diff --git a/emrg/server/competition_prompt.md b/emrg/server/competition_prompt.md index 80e00d99d..f8be10614 100644 --- a/emrg/server/competition_prompt.md +++ b/emrg/server/competition_prompt.md @@ -35,8 +35,6 @@ These instructions amend this task for one installation; they are not a second t **Do not skip. Execute even if "everything looks fine".** -**The round's first step is to call `boss`** — a separate session that owns this task's direction while this one does the work — and to treat its answer as the round's stance; whatever the answer does not mention is still this session's to decide. A session that is not offered `boss` has no owner to ask, and carries on without one. - #### 0.1 Environment verification - **Browser first**: `browser-harness` (`BU_CDP_URL=http://127.0.0.1:57000`) reuses the host's already-logged-in browser. Competition platforms (Tianchi, Kaggle, DataFountain, HuggingFace) require login for rules pages, data download and submission — **the login state exists only in the real browser**. diff --git a/emrg/server/daemon.py b/emrg/server/daemon.py index 8b1b19465..610a76f9c 100644 --- a/emrg/server/daemon.py +++ b/emrg/server/daemon.py @@ -172,7 +172,6 @@ def resolve_client_tier(session, req_sandbox: str | None = None) -> str: from emrg.tools.grep_tool import GrepTool from emrg.tools.submit_rant_tool import SubmitRantTool from emrg.tools.subagent_tool import SubagentTool -from emrg.tools.boss_tool import BUSY_MARKER, REASK_WINDOW_S, BossTool from emrg.skills.loader import load_skills, load_skills_with_shadows from emrg.skills.registry import ensure_catalog_file, load_catalog_skills, skill_is_managed from emrg.server.rants import append_rant, list_rants @@ -227,18 +226,16 @@ def default_tool_names(platform_name: str | None = None) -> list[str]: def scheduled_task_tool_names(platform_name: str | None = None) -> list[str]: - """The tool names a scheduled task's round may use (issue #2465, #2467). - - A host conversation's set, plus ``boss`` — the owner role, which is the first - tool the split was built for and the reason it exists: adding it here alone is - what keeps it out of a conversation, with no second mechanism inside the tool - asking "who called me?". - - ``boss`` goes last so the shared prefix of the two lists is the whole of - ``default_tool_names``: a reader comparing them sees one append, not a - reshuffle. + """The tool names a scheduled task's round may use (issue #2465). + + The same set a host conversation is offered, stated here separately because it + is read in a different place — a round that inherited a conversation's list + would carry whatever that list happened to hold at the time. A tool offered to + one kind of turn and withheld from the other is a deliberate split rather than + an accident, so the test comparing the two lists makes the next one be written + down instead of appearing. """ - return default_tool_names(platform_name) + ["boss"] + return default_tool_names(platform_name) def effective_tool_names( @@ -777,7 +774,6 @@ def build_shell_tool( def build_tool_registry( sandbox_config: Optional[SandboxConfig] = None, run_subagent_cb=None, - run_boss_cb=None, platform_name: str | None = None, ) -> ToolRegistry: """The daemon's tool set, built in one place so that its size is a reading. @@ -816,10 +812,6 @@ def build_tool_registry( # The runner is the daemon's own method, so the tool has no path to the # session machinery of its own: everything that owns state stays there. tools.register(SubagentTool(run_subagent_cb)) - # Registered like any other tool and offered to scheduled tasks alone: which - # sessions may call it is `scheduled_task_tool_names()`'s fact, not this one's - # (issue #2467). - tools.register(BossTool(run_boss_cb)) return tools @@ -994,7 +986,7 @@ def __init__(self, llm_config: LlmConfig) -> None: # Build tool registry self.tools = build_tool_registry( - self._sandbox_config, self._run_subagent_tool, self._run_boss_tool, + self._sandbox_config, self._run_subagent_tool, ) logger.info("tools registered: %s", self.tools.names) @@ -3945,7 +3937,7 @@ def _get_or_create_session( ``register=False`` is for the one session that has no directory a host opened: the upgrade session runs in the installation's own work directory. Every other - server-created directory — the sub-session slot, the boss session — is declined + server-created directory — the sub-session slot — is declined by path instead, in `AgentRegistry.for_dir`. """ if register: @@ -4353,10 +4345,10 @@ def _inject_tool_arguments( model-supplied list would be a sandbox whose boundary the sandboxed decided — so whatever the session holds, including nothing, is what the call runs with. - * **the parent of a delegation is a fact, not a field.** ``subagent`` and - ``boss`` receive ``_parent_session_id``, ``_parent_cwd``, + * **the parent of a delegation is a fact, not a field.** ``subagent`` + receives ``_parent_session_id``, ``_parent_cwd``, ``_parent_tools`` and ``_parent_sandbox``, all of them unconditional - (issues #2451, #2465, #2467), for one reason in four parts: the child's + (issues #2451, #2465), for one reason in four parts: the child's slot is derived from the parent's id and cwd, so a caller naming its own would name a wrong one; the child inherits **this turn's** tool set, so a round that may not use a tool cannot hand it to a session it spawns; @@ -4448,9 +4440,9 @@ class rather than left anonymous. args["writable_grants"] = [ grant.as_wire() for grant in session.sandbox_grants ] - if tc_name in ("subagent", "boss"): + if tc_name == "subagent": # The parent's identity and cwd are facts the model must not choose - # (issue #2451, #2467): the slot is derived from both, so a caller that + # (issue #2451): the slot is derived from both, so a caller that # named its own would name a wrong one. Injected unconditionally, so a # value the model put in the call is replaced rather than honoured — the # same rule the writable roots follow, and for the same reason: the @@ -8085,289 +8077,6 @@ def _subagent_report( f"{answer}" ) - # ── The owner role (issue #2467) ─────────────────────────────────────── - - #: The fixed directory a task's owner session lives in, under the parent's - #: ``sub-agent/``. One owner per parent, so it is a name and not a slot: the - #: nine ``subagent`` slots are least-recently-closed and emptied on use, which - #: is right for a job that ends when it answers and wrong for a role that is - #: held across rounds. - BOSS_DIR = "sub-boss" - - async def _run_boss_tool( - self, *, parent_session_id: str, parent_cwd: str, - timeout_s: int, intent: str = "", parent_tools: list[str] | None = None, - parent_sandbox: str | None = None, - ) -> dict: - """Run the owner session for one `boss` call. Answers text or an error. - - The bound covers everything, as `subagent`'s does, and is read the same - way — by *whether the child finished*, not by catching a timeout: the tool - loop absorbs the cancellation it receives and returns normally, so a - cancelled owner would look like a finished one that said nothing. - - There is no slot to release: the directory is fixed and retained, so a - timed-out call leaves nothing occupied and the next call resumes the same - session. - """ - state: dict = {"child": None} - child_task = asyncio.create_task(self._run_boss_child( - parent_session_id=parent_session_id, - parent_cwd=parent_cwd, - intent=intent, - state=state, - parent_tools=parent_tools, - parent_sandbox=parent_sandbox, - )) - try: - done, _ = await asyncio.wait({child_task}, timeout=timeout_s) - except asyncio.CancelledError: - # The executor's own round was cancelled. The owner is not left running - # behind it — and, like the timeout below, this call delivered nothing, - # so it must not consume the window (issue #2499): the same session's - # next round would otherwise be refused for four hours by a call that - # never put a question to anyone. - child_task.cancel() - await asyncio.gather(child_task, return_exceptions=True) - self._unconsume_the_window(state) - raise - if done: - return child_task.result() - child_task.cancel() - await asyncio.gather(child_task, return_exceptions=True) - self._unconsume_the_window(state) - logger.warning( - "[boss] timed out after %ss: parent=%s child=%s", - timeout_s, parent_session_id, state["child"], - ) - return {"error": ( - f"boss: the owner did not answer within {timeout_s}s, so its turn was " - "cancelled. Nothing from it was delivered, and this call did not " - "consume the re-ask window, so retrying starts a turn. Raise " - "`timeout_s` if the owner needs longer to read this session's history. " - f"Owner session: {state['child']}." - )} - - @staticmethod - def _unconsume_the_window(state: dict) -> None: - """Put the owner clock back where this call found it (issue #2499). - - A call that delivered nothing must not consume the four-hour window. The - window exists because *a direction that was just given stands*; a call - cancelled by `timeout_s`, or with its own round, gave no direction, so a - stamp left standing refuses the retry the timeout error asks for and makes - that error's only remedy impossible to carry out. - - The stamp still goes down *before* the turn runs, and that is deliberate — - a turn that raised keeps it, because it ran and re-buying it is the cost - the window exists to prevent. So this restores rather than withholds: the - two outcomes are told apart here, one frame up, and not by moving the stamp. - """ - owner = state.get("owner") - if owner is None: - # Cancelled before the call got as far as stamping anything. - return - owner.set_boss_asked_at(state.get("asked_at_before")) - - async def _run_boss_child( - self, *, parent_session_id: str, parent_cwd: str, - intent: str, state: dict, parent_tools: list[str] | None = None, - parent_sandbox: str | None = None, - ) -> dict: - """The body of one owner call: open the retained session, run it, report.""" - started = time.monotonic() - parent = self._get_or_create_session(parent_session_id, Path(parent_cwd)) - - depth = parent.depth - if depth >= self.SUBAGENT_MAX_DEPTH: - logger.info( - "[boss] refused: delegation depth %d reached (parent=%s)", - depth, parent_session_id, - ) - return {"error": ( - f"boss: refused — this session is already {depth} delegations deep " - f"and the limit is {self.SUBAGENT_MAX_DEPTH}. Nothing was started. " - "An owner is asked for by the session that does the work, not by " - "one it has already delegated to." - )} - - # The id carries the parent's for the same reason a slot's does: the busy, - # cancel and turn tables are keyed by id across the whole daemon, so a - # fixed `boss` would make two tasks' owners indistinguishable there. - child_id = f"boss-{parent_session_id}" - state["child"] = child_id - parent_session_dir = session_dir(parent_cwd, parent_session_id) - # The cwd is two levels below the parent's session directory, which is how - # the owner derives the history it must read: `/sub-agent/sub-boss`. - boss_cwd = parent_session_dir / "sub-agent" / self.BOSS_DIR - boss_cwd.mkdir(parents=True, exist_ok=True) - parent_history = parent_session_dir / "history.jsonl" - - # Load-or-create, never delete: the retained session keeps its history, its - # memory and its own compaction between rounds. That is what makes the - # several thousand characters of mission a cost paid once rather than - # every round (issue #2467, requirement 3). - child = self._get_or_create_session(child_id, boss_cwd) - - # The quiet window (issue #2495). Direction does not change inside four - # hours, so a second call in that time would spend a whole owner turn to - # re-buy a judgement that cannot have moved. The clock is the owner - # session's own `meta.json`, so a restart neither resets nor forgets it, - # and it is read before anything is started: no turn, no prompt, no depth. - asked_at = time.time() - last_asked = child.boss_asked_at - if last_asked is not None and asked_at - last_asked < REASK_WINDOW_S: - free_at = last_asked + REASK_WINDOW_S - logger.info( - "[boss] busy: parent=%s child=%s remaining=%.0fs", - parent_session_id, child_id, free_at - asked_at, - ) - return {"text": self._boss_busy_report( - child_id, last_asked, free_at, free_at - asked_at, - )} - - # Stamped before the turn runs, never after it: a turn that dies mid-way - # must still leave the clock written, or the next call pays for the same - # judgement again with nothing to show for the first. - # - # Both halves are handed to the caller as well, because the two ways a - # call can end without answering are decided one frame up: `_run_boss_tool` - # holds the bound, and it is the only place that knows a turn was taken - # away rather than finished. Nothing here distinguishes them. - state["owner"] = child - state["asked_at_before"] = last_asked - child.set_boss_asked_at(asked_at) - - prompt = _get_jinja_env().get_template("boss.j2").render( - parent_history=str(parent_history), - parent_session=parent_session_id, - ) - - child.set_depth(depth + 1) - # The owner's tier is the parent's, never its own: authorization a caller - # can choose for the thing it is authorizing is not a boundary. - # Same rule as `subagent`: the session's own tier first, then the tier this - # turn runs under — the only one a scheduled task has. - child_tier = getattr(parent, "sandbox", None) or parent_sandbox - if child_tier: - child.set_sandbox(child_tier) - if parent.sandbox_grants: - try: - child.set_sandbox_grants(parent.sandbox_grants) - child.set_sandbox_withheld(parent.sandbox_withheld) - except (ValueError, OSError): - logger.warning("[boss] could not inherit the parent's writable grants") - - req = TaskRequest( - id=f"boss-{int(started * 1000)}", - session_id=child_id, - cwd=str(boss_cwd), - prompt=prompt, - timestamp="", - sandbox=child_tier, - # The owner inherits the executor's tool set the way any child does - # (#2465). It includes `boss` itself; the depth limit above is what - # bounds an owner that asks for an owner. - tools=parent_tools, - ) - assistants_before = sum( - 1 for r in child._read_history() if r.get("role") == "assistant" - ) - logger.info( - "[boss] start: parent=%s child=%s depth=%d intent=%s", - parent_session_id, child_id, depth + 1, - redact_string(intent) if intent else "-", - ) - - self._session_busy[child_id] = True - cancel_event = asyncio.Event() - self._session_cancel[child_id] = cancel_event - try: - await self._run_tool_loop_locked(req, None, child, cancel_event) - finally: - # "Closed" is the whole teardown, the memory write included — the same - # ordering the slot runners need, and here it is also what makes the - # next round read a settled history. - await self._await_memory_reflection(child_id) - self._session_busy[child_id] = False - self._session_cancel.pop(child_id, None) - - records = child._read_history() - rounds = max(0, sum( - 1 for r in records if r.get("role") == "assistant" - ) - assistants_before) - answer = "" - for record in reversed(records): - if record.get("role") != "assistant": - continue - content = record.get("content") - if isinstance(content, str) and content.strip(): - answer = content - break - elapsed = time.monotonic() - started - logger.info( - "[boss] done: child=%s rounds=%d elapsed=%.1fs", child_id, rounds, elapsed, - ) - return {"text": self._boss_report(child_id, boss_cwd, answer, rounds, elapsed)} - - @staticmethod - def _boss_report( - child_id: str, boss_cwd: Path, answer: str, rounds: int, elapsed: float, - ) -> str: - """What the executor's round receives: the stance, and where it came from. - - The cap is `_SUBAGENT_ANSWER_CHARS`, shared rather than duplicated: the two - subjects are one question — how much of a child session's answer reaches the - parent's round — and a second constant would be a second number to keep in - step with it. - """ - if not answer: - answer = "(the owner produced no answer)" - elif len(answer) > _SUBAGENT_ANSWER_CHARS: - answer = ( - answer[:_SUBAGENT_ANSWER_CHARS] - + f"\n\n… (truncated — the answer ran to {len(answer)} characters, " - f"the first {_SUBAGENT_ANSWER_CHARS} are shown)" - ) - return ( - "The owner answered. Treat this as this round's stance; anything it " - "does not mention is still yours to decide.\n" - f"- session: {child_id}\n" - f"- cwd: {boss_cwd}\n" - f"- rounds: {rounds}\n" - f"- elapsed: {elapsed:.1f}s\n\n" - f"{answer}" - ) - - @staticmethod - def _boss_busy_report( - child_id: str, last_asked: float, free_at: float, remaining: float, - ) -> str: - """The answer a call inside the quiet window gets: a notice, and no stance. - - An ordinary result rather than an error, because a busy owner is not a - failure of the round that asked — and its first line carries `BUSY_MARKER` - so that "the owner was left alone" is readable from the answer's shape. - The executor is told in as many words that no direction was decided, since - the tool otherwise promises every answer is a stance. - """ - def _stamp(when: float) -> str: - return datetime.fromtimestamp(when, tz=timezone.utc).strftime( - "%Y-%m-%dT%H:%M:%SZ" - ) - - return ( - f"{BUSY_MARKER} — the owner was left alone; this is not a stance.\n" - f"- owner session: {child_id}\n" - f"- last asked: {_stamp(last_asked)}\n" - f"- free at: {_stamp(free_at)}\n" - f"- remaining: {int(remaining)}s\n\n" - "No question was put to the owner this round, so no direction was " - "decided: carry on with the plan you already have, or finish and " - "report. Ask again once the window has passed if the direction " - "genuinely has to change." - ) - def _maybe_reflect_memory( self, session: Session, user_prompt: str, assistant_content: str, tool_names: list[str] | None = None, diff --git a/emrg/server/evolution_prompt.md b/emrg/server/evolution_prompt.md index 27bb0b0e0..8681e4984 100644 --- a/emrg/server/evolution_prompt.md +++ b/emrg/server/evolution_prompt.md @@ -29,8 +29,6 @@ You are EMRG's self-evolution module. **Every cycle executes the whole loop — Get able to work: gh installed, role known, source synced. -**The round's first step is to call `boss`** — a separate session that owns this task's direction while this one does the work — and to treat its answer as the round's stance; whatever the answer does not mention is still this session's to decide. A session that is not offered `boss` has no owner to ask, and carries on without one. - #### 0.1 GitHub CLI **Install gh CLI** (required for GitHub operations; install if missing): diff --git a/emrg/server/feishu_prompt.md b/emrg/server/feishu_prompt.md index 338bac789..22d5703ac 100644 --- a/emrg/server/feishu_prompt.md +++ b/emrg/server/feishu_prompt.md @@ -42,8 +42,6 @@ overrides it — and by nothing else. The cadence is not this round's to lower. ### 1. Read -**The round's first step is to call `boss`** — a separate session that owns this task's direction while this one does the work — and to treat its answer as the round's stance; whatever the answer does not mention is still this session's to decide. A session that is not offered `boss` has no owner to ask, and carries on without one. - Messages come from `lark-cli`, which speaks the Feishu IM API. If it is not on `PATH`, look in the usual install locations before calling it blocked. diff --git a/emrg/server/ios_app_prompt.md b/emrg/server/ios_app_prompt.md index 8d6179915..cd816bdea 100644 --- a/emrg/server/ios_app_prompt.md +++ b/emrg/server/ios_app_prompt.md @@ -30,8 +30,6 @@ These instructions amend this task for one installation; they are not a second t **Do not skip it, including the rounds where "everything looks fine".** -**The round's first step is to call `boss`** — a separate session that owns this task's direction while this one does the work — and to treat its answer as the round's stance; whatever the answer does not mention is still this session's to decide. A session that is not offered `boss` has no owner to ask, and carries on without one. - #### 0.1 Instance values come from `extra_prompt`, never from this file This template ships identically to every EMRG instance, so it carries **no instance-specific value at all**. Everything about *your* account is read from the task's `extra_prompt`, which the host writes into `tasks.yml`: the Apple developer team id, the App Store Connect API key's path and issuer id, which bundle-id prefix to use, the account an app's repository is created under and the directory that holds it, the budget, and any preference about which category to prefer or avoid. diff --git a/emrg/server/journal_prompt.md b/emrg/server/journal_prompt.md index 6e73eabc3..553d6ba62 100644 --- a/emrg/server/journal_prompt.md +++ b/emrg/server/journal_prompt.md @@ -42,8 +42,6 @@ These instructions amend this task for one installation; they are not a second t **Do not skip. Execute even if "everything looks fine".** -**The round's first step is to call `boss`** — a separate session that owns this task's direction while this one does the work — and to treat its answer as the round's stance; whatever the answer does not mention is still this session's to decide. A session that is not offered `boss` has no owner to ask, and carries on without one. - #### 0.1 Environment verification ```bash diff --git a/emrg/server/open_source_prompt.md b/emrg/server/open_source_prompt.md index 94fbe7109..388a2606f 100644 --- a/emrg/server/open_source_prompt.md +++ b/emrg/server/open_source_prompt.md @@ -31,8 +31,6 @@ These instructions amend this task for one installation; they are not a second t Get able to work: `gh` authenticated, the role known and locked, the source synced. -**The round's first step is to call `boss`** — a separate session that owns this task's direction while this one does the work — and to treat its answer as the round's stance; whatever the answer does not mention is still this session's to decide. A session that is not offered `boss` has no owner to ask, and carries on without one. - #### 0.1 GitHub CLI ```bash diff --git a/emrg/server/paper_prompt.md b/emrg/server/paper_prompt.md index b4557c6a2..6b0906ef4 100644 --- a/emrg/server/paper_prompt.md +++ b/emrg/server/paper_prompt.md @@ -18,8 +18,6 @@ These instructions amend this task for one installation; they are not a second t ### 0. Phase Assessment (MUST run first every cycle) -**The round's first step is to call `boss`** — a separate session that owns this task's direction while this one does the work — and to treat its answer as the round's stance; whatever the answer does not mention is still this session's to decide. A session that is not offered `boss` has no owner to ask, and carries on without one. - Paper writing has four qualitatively distinct phases, each with its own goals, loop logic, and exit conditions. **Before starting this round's work, first determine which phase you are in**: | Phase | Goal | Core Activity | Exit Condition | diff --git a/emrg/server/promote_prompt.md b/emrg/server/promote_prompt.md index fbb5c45e3..4a96f28d0 100644 --- a/emrg/server/promote_prompt.md +++ b/emrg/server/promote_prompt.md @@ -24,8 +24,6 @@ These instructions amend this task for one installation; they are not a second t Run this loop every round; never stop at "executed": -**The round's first step is to call `boss`** — a separate session that owns this task's direction while this one does the work — and to treat its answer as the round's stance; whatever the answer does not mention is still this session's to decide. A session that is not offered `boss` has no owner to ask, and carries on without one. - 1. **Plan** — set this round's promotion intent: promote what, where, to whom (answer §5 question 1 before acting) 2. **Do** — execute the Participatory Four Steps 3. **Check** — **actively measure the effect** with quantifiable signals: star/fork deltas, article/blog exposure & interaction, comment interaction rate, platform/search ranking, feedback collected (see §6). Read the numbers yourself — do not wait for the host to point them out diff --git a/emrg/server/prompts/boss.j2 b/emrg/server/prompts/boss.j2 deleted file mode 100644 index 80109e791..000000000 --- a/emrg/server/prompts/boss.j2 +++ /dev/null @@ -1,41 +0,0 @@ -{# The prompt a `boss` call hands its child session. - # - # A template rather than a string in the code, for the same reason - # `memory_compaction.j2` is one: the wording is the host's to edit, and the next - # call reads the new text without a restart. - # - # What it deliberately does NOT do is carry the mission. The parent cannot be - # asked for it: a parent writing the brief is the one thing this tool exists to - # avoid, because a brief is a summary and a summary loses the position. So the - # child is given the path to the parent's own history and told to read the - # mission there, where it is verbatim and complete. - #} -You are the owner of this task. The session that called you is the one doing the -work: it is the executor, and you set the direction. - -You are not told what the task is, and that is on purpose — a summary written by -the executor would be the executor's own reading of the task. Read it yourself: - -- **The mission** is the last record whose `role` is `user` in - `{{ parent_history }}`. That record is the whole task statement this run was - given, including anything appended to it. Nothing the executor says about the - mission replaces it; if the two disagree, the mission is right. -- **What has happened since** is the rest of that file: the tool calls, their - results, and what the executor concluded after each. Read its recent end. It is - long — read a window, not the whole file, and use `grep` when you know what you - are looking for. - -Then answer with a stance. You are not grading the work and not listing problems; -you are deciding how this task is to be handled now. - -- Say what the coming rounds should aim at, and what is not acceptable. -- Say what may be traded away and what may not. -- Say where to go next when the current way is exhausted. -- Be concrete enough that the executor can act on the answer without calling you - again for it. - -Write one short answer, in the imperative, addressed to the executor. Do not -restate the mission, do not narrate what you read, and do not hedge: an answer -that lists considerations without choosing between them leaves the executor where -it started. - diff --git a/emrg/session.py b/emrg/session.py index 427ff27b5..7d2e3142f 100644 --- a/emrg/session.py +++ b/emrg/session.py @@ -475,9 +475,9 @@ def session_dir(cwd: Path, session_id: str) -> Path: This is the one producer of ``/.emrg/sessions/``. The rule has more than one reader: ``Session`` fills the directory it computes here, and the daemon derives a *parent's* directory from it to place a child's cwd inside — - ``sub-agent/sub`` for a delegation, ``sub-agent/sub-boss`` for an owner. A - caller that has an id and a cwd but no handle asks this, so a layout change is an - edit in one place rather than a search for every copy of the expression. + ``sub-agent/sub`` for a delegation. A caller that has an id and a cwd but no + handle asks this, so a layout change is an edit in one place rather than a + search for every copy of the expression. The id is not validated here — ``is_safe_session_id`` decides that, and its caller decides whether an unsafe id is refused or merely not a directory (see its @@ -550,15 +550,6 @@ def __init__(self, session_id: str, agent: Agent | Path | str) -> None: # `subagent` call reads this, and a daemon restart must not reset the # count of a session that already exists on disk. self._depth: int = 0 - # When this session — acting as an owner — was last asked for a stance, in - # seconds since the epoch (issue #2495). An owner is left alone for - # `REASK_WINDOW_S` after a call, because direction does not change inside - # four hours and a second call buys the same judgement again. It lives in - # `meta.json` for the same reason `depth` does: the session is retained on - # disk, so a daemon restart that reset this clock would let the very next - # round re-buy a decision it already paid for. - self._boss_asked_at: float | None = None - # Lazy-initialized memory store self._memory_store = None @@ -698,15 +689,6 @@ def load(cls, session_id: str, cwd: Path) -> Session: # a JSON `true` in this field would then read as depth 1. if isinstance(stored_depth, int) and not isinstance(stored_depth, bool): session._depth = max(0, stored_depth) - stored_boss_asked_at = meta.get("boss_asked_at") - # The same care as `depth`: `True` is an int, and a JSON `true` here - # would read as the epoch's first second. Absent, malformed and - # non-numeric all mean "never asked", which is the state that permits - # a call — the safe direction for a value that only ever blocks one. - if isinstance(stored_boss_asked_at, (int, float)) and not isinstance( - stored_boss_asked_at, bool - ): - session._boss_asked_at = float(stored_boss_asked_at) logger.info("session loaded: %s (%d messages)", session_id, session._message_count) return session @@ -775,39 +757,6 @@ def set_depth(self, depth: int) -> None: self._save_meta() logger.info("session delegation depth set: %s -> %d", self.session_id, self._depth) - # ── The owner's clock ───────────────────────────────────── - - @property - def boss_asked_at(self) -> float | None: - """When this session was last asked for a stance, or ``None`` if never. - - Seconds since the epoch, so the quiet window's comparison is arithmetic - rather than a parse: a malformed instant would otherwise have to be told - apart from an absent one at the point where it decides something. - """ - return self._boss_asked_at - - def set_boss_asked_at(self, when: float | None) -> None: - """Persist the instant this session was last asked, into ``meta.json``. - - The only writer of the key, and it is called *before* the owner's turn - runs rather than after it: a stamp written on completion leaves a turn that - died looking like one that never happened, and the next call would then pay - for the same judgement a second time. - - ``None`` clears it, and the key leaves ``meta.json`` with it — the state a - session that was never asked is in. That is how a call which delivered - nothing gives the window back (issue #2499): the clock exists to make a - direction that *was* given stand, and a call that was cancelled gave none. - """ - self._boss_asked_at = None if when is None else float(when) - self._save_meta() - logger.info( - "session owner clock set: %s -> %s", - self.session_id, - "never" if self._boss_asked_at is None else f"{self._boss_asked_at:.0f}", - ) - # ── Sandbox tier ────────────────────────────────────────── @property @@ -1357,10 +1306,6 @@ def _save_meta_with_title(self, title: str | None) -> None: # key saying it is zero deep. if self._depth: meta["depth"] = self._depth - # Same rule again: a session that was never asked for a stance must not - # gain a key claiming one was. - if self._boss_asked_at is not None: - meta["boss_asked_at"] = self._boss_asked_at if title is not None: meta["title"] = title else: diff --git a/emrg/tools/boss_tool.py b/emrg/tools/boss_tool.py deleted file mode 100644 index aeb9079fd..000000000 --- a/emrg/tools/boss_tool.py +++ /dev/null @@ -1,205 +0,0 @@ -"""BossTool — the task's owner, in a session of its own, deciding the stance. - -Issue #2467. Every scheduled task is one agent that decides the direction and does -the work in the same round, and those two jobs pull against each other: the round -that must finish something now is the worst judge of whether it should be doing it -at all. Two ways of separating them were tried and both failed. Baking review -semantics into the generic ``subagent`` schema was refused — a general tool with a -special purpose is no longer general. Writing "call a subagent first and brief it -thus" into the templates ran at 16% → 56% → 31% of rounds, so the wording is not -the lever, and a parent-written brief is structurally wrong anyway: a brief is a -summary, and the position the owner exists to supply is what a summary drops. - -So the owner is a tool of its own, with three properties that make it one: - -**It reads the mission itself.** The child's cwd is -``/sub-agent/sub-boss``, so the parent's own session directory -is two levels up and its ``history.jsonl`` is right there — the last ``user`` -record is the entire task statement, ``extra_prompt`` included. The parent supplies -no steering text at all, not even a question: naming what the owner should judge is -choosing the direction, and a session that chose the question would be deciding how -its own work is judged. What the caller supplies is ``intent`` — the one-line reason -the log keeps — and nothing else. - -**It is left alone between calls.** Direction does not change inside four hours, so -a call in that window starts no turn and buys no judgement; it answers with -``BUSY_MARKER`` and the time the owner frees up, which is an ordinary result rather -than an error because a busy owner is not a failure of the round that asked. - -**It is not cleared between rounds.** The nine ``subagent`` slots are -least-recently-closed and emptied on use, which is right for a job that ends when -it answers. This one is a role held across rounds: emptied, it would re-read the -whole mission every round — paying for it again, and forgetting what it saw last -round. So it gets one fixed directory, ``sub-boss``, created on first use and -reused; it disappears with the parent's ``sub-agent/`` like anything else there. - -**It is offered to scheduled tasks and not to host conversations.** That is not -decided here and must not be: the tool is registered once, and -``scheduled_task_tool_names()`` in the daemon is the only list that names it. A -role inside the tool asking "who called me?" would be a second mechanism for a -fact the producer already knows. - -The bound (``timeout_s``, default as ``subagent``'s) covers the whole call, and a -timed-out call leaves nothing occupied, because there is no slot to occupy. The -depth limit is the delegation depth every child session carries: an owner that -delegates forever is bounded by the same rule as anything else it starts. -""" - -from __future__ import annotations - -from typing import Awaitable, Callable - -from emrg.server.tool_types import ToolDefinition, ToolResult -from emrg.tools.base import ToolExecutor - -#: The runner the daemon supplies: ``await runner(parent_session_id=…, -#: parent_cwd=…, timeout_s=…, intent=…, parent_tools=…, parent_sandbox=…)`` -#: answering either ``{"text": …}`` or ``{"error": …}``. ``parent_tools`` is the -#: parent turn's effective tool set (#2465), which the child inherits. -Runner = Callable[..., Awaitable[dict]] - -#: Generous enough for a real read of the parent's history, short enough that a -#: wedged owner session cannot hold the parent's round for ever. -DEFAULT_TIMEOUT_S = 600 - -#: How long an owner is left alone after a call (issue #2495). Direction does not -#: change inside four hours, so a second call in that window spends a full owner -#: turn to re-buy a judgement that cannot have changed. The constant lives here, -#: beside the description that tells the caller about it, so the advertised window -#: and the enforced one are one number: the daemon reads this same constant. -REASK_WINDOW_S = 4 * 60 * 60 - -#: What a busy answer opens with, so that "the owner was left alone" is readable -#: from the answer's shape rather than by running the prose through a reader. A -#: stance never begins with it. -BUSY_MARKER = "boss-busy-window" - - -class BossTool(ToolExecutor): - """Ask this task's owner session what the coming rounds' stance is.""" - - def __init__(self, runner: Runner) -> None: - self._runner = runner - - def definition(self) -> ToolDefinition: - return ToolDefinition( - name="boss", - description=( - "Ask the owner of this task what the coming rounds should do. The " - "owner is a separate session that holds the direction while this " - "session does the work: it reads this session's own history for " - "the mission and for what has happened, so you do not describe " - "either — and what you get back is a stance to treat as binding " - "for this round, not a list of problems to consider. Anything the " - "answer does not mention is still yours to decide. It is offered " - "to scheduled tasks only, keeps its memory across rounds, and its " - "round stands still until it answers. It is also left alone for " - f"{REASK_WINDOW_S // 3600}h after a call: an answer that opens with " - f"`{BUSY_MARKER}` is that notice, carries no stance, and means carry " - "on with your own round rather than waiting." - ), - parameters={ - "type": "object", - "properties": { - "timeout_s": { - "type": "integer", - "minimum": 1, - "description": ( - "Whole seconds the owner may run — at least 1, and a " - "value outside that is refused. When it is reached the " - "owner's turn is cancelled and an error is returned. " - f"Default {DEFAULT_TIMEOUT_S}." - ), - }, - "intent": { - "type": "string", - "description": ( - "One sentence on why the owner is being asked and what " - "the round needs from it; it is logged with the call." - ), - }, - }, - "required": ["intent"], - }, - ) - - async def execute(self, arguments: dict) -> ToolResult: - intent = arguments.get("intent") - if not isinstance(intent, str) or not intent.strip(): - return ToolResult( - name="boss", - content=( - "boss: `intent` is required and must not be empty — it is what " - "the log keeps of this call, and every tool call carries one." - ), - error=True, - ) - - timeout_s = arguments.get("timeout_s") - if timeout_s is None: - timeout_s = DEFAULT_TIMEOUT_S - if isinstance(timeout_s, bool) or not isinstance(timeout_s, int): - return ToolResult( - name="boss", - content=( - f"boss: `timeout_s` must be a whole number of seconds, so got " - f"{timeout_s!r}. It is the bound on the owner's run, and a " - "value from outside that domain is a caller error, not a " - "default." - ), - error=True, - ) - if timeout_s < 1: - return ToolResult( - name="boss", - content=( - f"boss: `timeout_s` must be at least 1, so got {timeout_s}. A " - "non-positive bound would cancel the owner before its first " - "round." - ), - error=True, - ) - - parent_session_id = arguments.get("_parent_session_id") or "" - parent_cwd = arguments.get("_parent_cwd") or "" - if not parent_session_id or not parent_cwd: - return ToolResult( - name="boss", - content=( - "boss: this call carries no parent session, so there is no " - "task for an owner to own. The daemon injects the parent's " - "session and cwd into every call it dispatches; a call without " - "them did not come from a daemon turn." - ), - error=True, - ) - - # The parent turn's tool set, injected by the daemon (#2465). A value that - # is not a list is "no statement", the same meaning the message field - # carries, so silence cannot be read two ways. - # The tier this turn is running under, injected by the daemon. A value that - # is not a non-empty string is "no statement": silence means the turn itself - # declared no tier, which the daemon reads as unconfined. - raw_parent_sandbox = arguments.get("_parent_sandbox") - parent_sandbox = ( - raw_parent_sandbox - if isinstance(raw_parent_sandbox, str) and raw_parent_sandbox else None - ) - - raw_parent_tools = arguments.get("_parent_tools") - parent_tools = ( - [str(name) for name in raw_parent_tools] - if isinstance(raw_parent_tools, list) else None - ) - - outcome = await self._runner( - parent_session_id=str(parent_session_id), - parent_cwd=str(parent_cwd), - timeout_s=int(timeout_s), - intent=intent, - parent_tools=parent_tools, - parent_sandbox=parent_sandbox, - ) - if outcome.get("error"): - return ToolResult(name="boss", content=outcome["error"], error=True) - return ToolResult(name="boss", content=outcome.get("text", "")) diff --git a/scripts/check-rant-citations.py b/scripts/check-rant-citations.py index f9db6492d..79d295a1b 100644 --- a/scripts/check-rant-citations.py +++ b/scripts/check-rant-citations.py @@ -170,7 +170,6 @@ class reads **45 sites over 30 distinct timestamps in 9 of the 12 files**, and 4 "emrg/server/promote_prompt.md", "emrg/server/self_media_prompt.md", # a task template (#2714) "emrg/server/paper_prompt.md", - "emrg/server/prompts/boss.j2", # rendered per `boss` call (#2467) "emrg/server/prompts/memory_compaction.j2", # rendered by daemon.COMPACTION_TEMPLATE "emrg/server/prompts/system.j2", "emrg/server/prompts/upgrade_prompt.j2", diff --git a/tests/test_agent_registry.py b/tests/test_agent_registry.py index e163f3be0..1c1ec091c 100644 --- a/tests/test_agent_registry.py +++ b/tests/test_agent_registry.py @@ -88,7 +88,7 @@ def test_a_subdirectory_of_a_registered_directory_gets_its_own_row(tmp_path): def test_a_directory_under_an_agents_emrg_is_not_registered(tmp_path): - """The sub-session slot and the boss session: that Agent's bookkeeping, not a workspace.""" + """The sub-session slot: that Agent's bookkeeping, not a workspace.""" reg = _registry(tmp_path) parent = tmp_path / "repo" parent.mkdir() diff --git a/tests/test_boss_tool.py b/tests/test_boss_tool.py deleted file mode 100644 index f748d8796..000000000 --- a/tests/test_boss_tool.py +++ /dev/null @@ -1,714 +0,0 @@ -"""The owner role is a tool, and its session is a role held across rounds (issue #2467). - -Every scheduled task is one agent that decides the direction and does the work in -the same round. Two cheaper ways of separating those jobs were tried and both -failed: review semantics baked into the generic ``subagent`` schema (refused — a -general tool with a special purpose is no longer general), and "call a subagent -first and brief it thus" written into the templates (16% → 56% → 31% of rounds, so -the wording is not the lever). A parent-written brief is structurally wrong in any -case: a brief is a summary, and the position the owner exists to supply is exactly -what a summary drops. - -What is asserted here, and why each arm is a separate subject: - -* **the roster** — ``boss`` is registered, is offered to a scheduled round, and is - **not** offered to a host conversation. That last fact is the tool's whole - authorization story: it lives in one whitelist and nowhere else, so a second - mechanism inside the tool asking "who called me?" would be a copy of a fact the - producer already holds; -* **the arguments** — ``intent`` is required, the schema carries no ``focus`` at - all, and every refusal names the parameter it refused; -* **the quiet window** — a second call inside four hours starts no owner turn and - says so in a shape a caller can detect; the clock is the session's own, so a - rebuilt session is still busy and a turn that died still leaves its stamp; -* **where the mission comes from** — driven for real: the owner's first request - does **not** contain the mission and its second one does, which can only happen - if the owner read the parent's history itself. A test that asserted the prompt - names the path would pass on a design where the parent still supplied the text; -* **the directory** — created on first use, reused on the next call (a marker - written inside survives), and gone with the parent's ``sub-agent/``; -* **the templates** — all eight task templates carry the same sentence, with a - control arm showing the guard goes red when one is stripped, and ``boss.j2`` is - a file the host edits rather than a string in the code. - -No daemon is started, stopped or restarted: the runners are called directly, and -only the LLM, the broadcast and the memory reflection are stubbed. -""" - -from __future__ import annotations - -import asyncio -import json -import time -from pathlib import Path - -import pytest - -from emrg.config import LlmConfig -from emrg.server import daemon as daemon_mod -from emrg.server.daemon import ( - EmrgServer, - _get_jinja_env, - build_tool_registry, - default_tool_names, - scheduled_task_tool_names, -) -from emrg.protocol import TaskRequest -from emrg.session import Session -from emrg.tools.boss_tool import ( - BUSY_MARKER, - DEFAULT_TIMEOUT_S, - REASK_WINDOW_S, - BossTool, -) - -REPO_ROOT = Path(__file__).resolve().parent.parent -PROMPTS = REPO_ROOT / "emrg" / "server" / "prompts" -TEMPLATES = ( - "evolution_prompt.md", - "paper_prompt.md", - "open_source_prompt.md", - "promote_prompt.md", - "journal_prompt.md", - "competition_prompt.md", - "ios_app_prompt.md", - "feishu_prompt.md", -) - -#: The sentence every task template must carry, verbatim. One string, so the guard -#: and the templates cannot drift apart by a word. -THE_ASK = "**The round's first step is to call `boss`**" - -#: A string that appears in the mission and nowhere else. What makes the "the owner -#: read it itself" arm possible: it can only reach the owner's second request -#: through the file. -MISSION_MARKER = "MISSION-ONLY-8f3a91c2" - - -# ── the roster ──────────────────────────────────────────────────────── - - -def test_boss_is_registered_and_offered_to_scheduled_rounds_alone(): - registry = build_tool_registry(None, None) - assert registry.get("boss") is not None, ( - "boss is in a whitelist but not registered — the whitelist and the " - "registration have drifted apart" - ) - assert "boss" in scheduled_task_tool_names(), ( - "the owner role is not offered to a scheduled round, so no task can ask for " - "one and the tool is dead weight" - ) - assert "boss" not in default_tool_names(), ( - "the owner role is offered to a host conversation: the split in the two " - "whitelists is the whole of its authorization, so this is a leak, not a " - "convenience" - ) - - -# ── the arguments ───────────────────────────────────────────────────── - - -class _Runner: - """Records what the tool handed the daemon, and answers with a stance.""" - - def __init__(self, answer: str = "a stance") -> None: - self.calls: list[dict] = [] - self._answer = answer - - async def __call__(self, **kwargs): - self.calls.append(kwargs) - return {"text": self._answer} - - -def _injected(**extra): - """The arguments the daemon injects, plus whatever a test adds.""" - args = { - "intent": "ask the owner where this round goes", - "_parent_session_id": "emrg-task", - "_parent_cwd": "/tmp/whatever", - } - args.update(extra) - return args - - -def test_the_owner_is_reached_with_the_injected_identity(): - runner = _Runner() - result = asyncio.run(BossTool(runner).execute(_injected())) - assert not result.error, result.content - assert result.content == "a stance" - call = runner.calls[0] - assert call["parent_session_id"] == "emrg-task" - assert call["parent_cwd"] == "/tmp/whatever" - assert call["timeout_s"] == DEFAULT_TIMEOUT_S - # No `prompt` is passed and none may be: the owner reads the mission itself, - # and a brief here is the thing this tool exists to replace. - assert "prompt" not in call - - -def test_a_call_without_intent_is_refused(): - runner = _Runner() - result = asyncio.run(BossTool(runner).execute({ - "_parent_session_id": "s", "_parent_cwd": "/tmp", - })) - assert result.error - assert "intent" in result.content - assert runner.calls == [], "the owner ran without the log keeping a reason" - - -def test_a_call_without_a_parent_session_is_refused(): - runner = _Runner() - result = asyncio.run(BossTool(runner).execute({"intent": "x"})) - assert result.error - assert "parent session" in result.content - assert runner.calls == [] - - -def test_the_schema_carries_no_focus_parameter(): - """Issue #2495: choosing the question is choosing the direction. - - Asserted on the schema rather than on behaviour, and the difference is the - guard: the tool ignores keys it does not know, so a test that passed `focus` in - and watched for no effect would stay green with the parameter restored. - """ - properties = BossTool(_Runner()).definition().parameters["properties"] - assert "focus" not in properties, ( - "the executor can still name what the owner should judge, which hands the " - "direction back to the session being directed" - ) - assert set(properties) == {"intent", "timeout_s"} - - -def test_the_runner_is_handed_no_focus(): - """The other half: a removed parameter leaves the call as well as the schema.""" - runner = _Runner() - asyncio.run(BossTool(runner).execute(_injected())) - assert "focus" not in runner.calls[0], ( - "the daemon is still handed a focus, so the parameter is only half gone" - ) - assert "prompt" not in runner.calls[0] - - -@pytest.mark.parametrize("bad", [True, "600", 0, -1, 1.5]) -def test_the_timeout_domain_is_refused(bad): - result = asyncio.run(BossTool(_Runner()).execute(_injected(timeout_s=bad))) - assert result.error, f"{bad!r} was accepted as a bound on the owner's run" - assert "timeout_s" in result.content - - -def test_an_error_from_the_runner_is_reported_as_an_error(): - class _Failing: - async def __call__(self, **kwargs): - return {"error": "boss: refused for a reason"} - - result = asyncio.run(BossTool(_Failing()).execute(_injected())) - assert result.error - assert "refused for a reason" in result.content - - -# ── the templates ───────────────────────────────────────────────────── - - -def _templates_missing_the_ask(texts: dict[str, str]) -> list[str]: - """Which of the eight task templates do not carry the sentence.""" - return sorted(name for name, text in texts.items() if THE_ASK not in text) - - -def _template_texts() -> dict[str, str]: - return { - name: (REPO_ROOT / "emrg" / "server" / name).read_text(encoding="utf-8") - for name in TEMPLATES - } - - -def test_every_task_template_asks_for_the_owner(): - missing = _templates_missing_the_ask(_template_texts()) - assert missing == [], ( - f"these templates never tell the round to ask its owner: {missing}" - ) - - -def test_the_template_guard_catches_a_stripped_sentence(): - """The control arm: a reading that is green whatever it is given measured nothing.""" - texts = _template_texts() - subject = "feishu_prompt.md" - texts[subject] = texts[subject].replace(THE_ASK, "") - assert _templates_missing_the_ask(texts) == [subject], ( - "the guard did not notice the sentence missing from one template, so the " - "green arm above says nothing about the other seven" - ) - - -def test_the_boss_template_is_a_file_the_host_edits(): - """No restart: the render reads the file, so an edit is live on the next call.""" - source = PROMPTS / "boss.j2" - assert source.is_file(), "boss.j2 must be a file in the prompts directory" - original = source.read_text(encoding="utf-8") - try: - rendered = _get_jinja_env().get_template("boss.j2").render( - parent_history="/tmp/session/history.jsonl", - ) - assert "/tmp/session/history.jsonl" in rendered, ( - "the template does not receive the path to the parent's history, so the " - "owner has no way to read the mission" - ) - - marker = "TEMPLATE-EDIT-IS-LIVE-4b7d" - source.write_text(original + "\n" + marker + "\n", encoding="utf-8") - again = _get_jinja_env().get_template("boss.j2").render( - parent_history="/tmp/session/history.jsonl", - ) - assert marker in again, ( - "an edit to boss.j2 did not reach the next render — the wording is the " - "host's, and a cached copy makes it the code's" - ) - finally: - source.write_text(original, encoding="utf-8") - - -# ── the session the owner runs in ───────────────────────────────────── - - -def _server(tmp_path, monkeypatch) -> EmrgServer: - monkeypatch.setattr(daemon_mod, "_PLANTED_FIRE_MARKER_PATH", tmp_path / "fire") - monkeypatch.setattr(daemon_mod, "_PLANTED_FIRE_ROUND_COMPLETE_PATH", tmp_path / "rc") - server = EmrgServer(LlmConfig(base_url="http://localhost", api_key="test")) - server._agents_log = tmp_path / "agents.yml" - server._maybe_reflect_memory = lambda *a, **k: None - return server - - -def _parent(tmp_path, session_id: str = "task-1") -> Session: - """A parent session whose history holds a mission nothing else carries.""" - parent = Session.create_with_id(session_id, tmp_path) - parent.append_message({ - "type": "message", "role": "user", - "content": f"{MISSION_MARKER} — do the task the host described.", - "timestamp": "2026-10-22T00:00:00", - }) - parent.append_message({ - "type": "message", "role": "assistant", "content": "round one done", - "timestamp": "2026-10-22T00:01:00", - }) - return parent - - -def _stub_the_loop(server: EmrgServer) -> list[dict]: - """Replace the owner's turn with a no-op that records the request it got.""" - seen: list[dict] = [] - - async def loop(req, ws, session, cancel_event, **kwargs): - seen.append({"prompt": req.prompt, "cwd": req.cwd, "session": session.session_id}) - - server._run_tool_loop_locked = loop - return seen - - -def _boss_cwd(tmp_path, session_id: str = "task-1") -> Path: - return ( - tmp_path / ".emrg" / "sessions" / session_id / "sub-agent" / "sub-boss" - ) - - -def _ask(server: EmrgServer, tmp_path, session_id: str = "task-1") -> dict: - return asyncio.run(server._run_boss_child( - parent_session_id=session_id, parent_cwd=str(tmp_path), - intent="ask", state={"child": None}, parent_tools=["read"], - )) - - -def test_the_owner_is_given_the_path_to_the_history_and_not_the_mission( - tmp_path, monkeypatch, -): - server = _server(tmp_path, monkeypatch) - _parent(tmp_path) - seen = _stub_the_loop(server) - - _ask(server, tmp_path) - - history = tmp_path / ".emrg" / "sessions" / "task-1" / "history.jsonl" - assert str(history) in seen[0]["prompt"], ( - "the owner was not told where the mission is, so it cannot read it" - ) - assert MISSION_MARKER not in seen[0]["prompt"], ( - "the mission reached the owner through the prompt: the executor is briefing " - "the owner again, which is the design this tool replaced" - ) - assert _boss_cwd(tmp_path).is_dir() - - -def test_the_owner_reads_the_mission_itself(tmp_path, monkeypatch): - """The real tool loop: the owner's second request carries the mission. - - That can only be true if the owner read the parent's history — the string - exists nowhere else — so this is the arm a prompt-shape assertion cannot reach. - """ - server = _server(tmp_path, monkeypatch) - _parent(tmp_path) - history = tmp_path / ".emrg" / "sessions" / "task-1" / "history.jsonl" - - seen: list[str] = [] - state = {"round": 0} - - async def fake_stream(messages, tools=None): - state["round"] += 1 - seen.append(json.dumps(messages, ensure_ascii=False)) - if state["round"] == 1: - yield { - "content": None, - "tool_calls": [{ - "index": 0, - "id": "call_0", - "function": { - "name": "read", - "arguments": json.dumps({ - "file_path": str(history), - "intent": "read the mission the task was given", - }), - }, - }], - "finish_reason": "tool_calls", - "usage": None, - } - else: - yield { - "content": "Aim at the mission; do not re-plan.", "tool_calls": None, - "finish_reason": "stop", - "usage": {"prompt_tokens": 1, "completion_tokens": 1}, - } - - async def fake_broadcast(session_id, payload): - pass - - server.llm.chat_stream = fake_stream - server._broadcast = fake_broadcast - - out = _ask(server, tmp_path) - - assert "Aim at the mission; do not re-plan." in out["text"], ( - f"the owner's answer did not reach the executor: {out!r}" - ) - assert MISSION_MARKER not in seen[0], ( - "the mission was in the owner's first request, which means the executor put " - "it there" - ) - assert MISSION_MARKER in seen[-1], ( - "the owner's second request does not carry the mission, so it never read the " - "parent's history — the one thing that separates this from a briefed subagent" - ) - - -def test_the_owner_session_is_reused_rather_than_rebuilt(tmp_path, monkeypatch): - server = _server(tmp_path, monkeypatch) - _parent(tmp_path) - _stub_the_loop(server) - - _ask(server, tmp_path) - marker = _boss_cwd(tmp_path) / ".emrg" / "sessions" / "boss-task-1" / "keep-me" - marker.parent.mkdir(parents=True, exist_ok=True) - marker.write_text("survives", encoding="utf-8") - - _ask(server, tmp_path) - - assert marker.read_text(encoding="utf-8") == "survives", ( - "the owner's session was cleared between calls: the role is held across " - "rounds, and a cleared one re-reads the whole mission every round" - ) - - -def test_the_owner_goes_away_with_the_parent(tmp_path, monkeypatch): - server = _server(tmp_path, monkeypatch) - _parent(tmp_path) - _stub_the_loop(server) - - _ask(server, tmp_path) - assert _boss_cwd(tmp_path).is_dir() - - # The parent's own teardown, not a hand-rolled rmtree: this is what a deleted - # session does, and the owner's directory sits under it. - Session.delete("task-1", tmp_path) - assert not _boss_cwd(tmp_path).exists(), ( - "the owner's directory outlived the session it belongs to" - ) - - -def test_the_depth_limit_bounds_an_owner_that_asks_for_an_owner(tmp_path, monkeypatch): - server = _server(tmp_path, monkeypatch) - parent = _parent(tmp_path) - parent.set_depth(server.SUBAGENT_MAX_DEPTH) - seen = _stub_the_loop(server) - - out = _ask(server, tmp_path) - - assert out.get("error"), "an owner was started past the delegation depth limit" - assert "delegations deep" in out["error"] - assert seen == [], "the refused call still ran a turn" - - -def test_an_owner_of_a_task_inherits_the_turns_tier(tmp_path, monkeypatch): - """The owner of a scheduled task runs where the task runs, not unconfined. - - A task's tier is resolved from `tasks.yml` into the request and never written - onto the session object, so an owner that read only the session inherited - nothing — and an owner with a wider tier than its executor is the one shape of - this bug that can act on the answer it then gives. Driven through - `_inject_tool_arguments` and then the tool, because the injection is the half - that was missing. - """ - server = _server(tmp_path, monkeypatch) - _stub_the_loop(server) - parent = Session.create_with_id("task-tier-owner", tmp_path) - assert parent.sandbox is None, ( - "this test models a scheduled task, whose tier lives on the request" - ) - req = TaskRequest( - id="owner-tier-turn", session_id=parent.session_id, cwd=str(tmp_path), - prompt="a task's tick", sandbox="read-only", - ) - - args = {"timeout_s": 10, "intent": "ask the owner"} - EmrgServer._inject_tool_arguments("boss", args, parent, req, None) - assert args.get("_parent_sandbox") == "read-only", ( - f"the turn's tier never reached the call: {args}" - ) - result = asyncio.run(BossTool(server._run_boss_tool).execute(args)) - assert not result.error, result.content - - owner = Session.load( - f"boss-{parent.session_id}", _boss_cwd(tmp_path, parent.session_id), - ) - assert owner.sandbox == "read-only", ( - "the owner of a confined task ran at a wider tier: an owner that may go " - "where its executor may not is the escape this inheritance refuses" - ) - - -# ── the quiet window (issue #2495) ──────────────────────────────────── - - -def test_the_quiet_window_is_four_hours(): - """The number the description advertises and the daemon enforces is one number.""" - assert REASK_WINDOW_S == 4 * 60 * 60, ( - "the window moved: the tool's own description is rendered from this " - "constant, so a second number here would be a second answer" - ) - - -def test_a_second_call_inside_the_window_starts_no_owner_turn(tmp_path, monkeypatch): - server = _server(tmp_path, monkeypatch) - seen = _stub_the_loop(server) - - first = _ask(server, tmp_path) - assert not first.get("error"), first - assert BUSY_MARKER not in first["text"], "the first call was answered as busy" - assert len(seen) == 1, "the first call must actually run the owner" - - second = _ask(server, tmp_path) - assert len(seen) == 1, ( - "a second owner turn started inside the window, which pays twice for a " - "judgement that cannot have changed" - ) - assert second["text"].startswith(BUSY_MARKER), second["text"][:80] - - -def test_the_busy_answer_is_a_result_and_says_no_stance_was_decided( - tmp_path, monkeypatch, -): - """A busy owner is not a failure, and the answer must not read as direction.""" - server = _server(tmp_path, monkeypatch) - _stub_the_loop(server) - _ask(server, tmp_path) - - busy = _ask(server, tmp_path) - assert "error" not in busy, ( - "a busy owner came back as an error, so a caller reads a normal wait as a " - "broken round" - ) - assert busy["text"].startswith(BUSY_MARKER) - assert "remaining:" in busy["text"], "the answer does not say how long the wait is" - assert "no direction was decided" in busy["text"], ( - "the answer does not say in as many words that this round has no stance, " - "and the tool otherwise promises every answer is one" - ) - - -def test_the_owner_is_asked_again_once_the_window_has_passed(tmp_path, monkeypatch): - """The window is a bound, not a permanent refusal at the other end.""" - server = _server(tmp_path, monkeypatch) - seen = _stub_the_loop(server) - _ask(server, tmp_path) - - owner = server._get_or_create_session("boss-task-1", _boss_cwd(tmp_path)) - owner.set_boss_asked_at(time.time() - REASK_WINDOW_S - 1) - - again = _ask(server, tmp_path) - assert len(seen) == 2, "the window refused a call that was outside it" - assert BUSY_MARKER not in again["text"] - - -def test_the_window_survives_a_rebuilt_session(tmp_path, monkeypatch): - """A daemon restart must not reset the clock: the owner session lives on disk.""" - first = _server(tmp_path, monkeypatch) - _stub_the_loop(first) - _ask(first, tmp_path) - - reopened = _server(tmp_path, monkeypatch) - seen = _stub_the_loop(reopened) - out = _ask(reopened, tmp_path) - - assert seen == [], "a rebuilt session forgot it had been asked, so it paid again" - assert out["text"].startswith(BUSY_MARKER) - - -def test_a_turn_that_died_still_leaves_the_clock(tmp_path, monkeypatch): - """The stamp is written before the turn runs, never after it.""" - server = _server(tmp_path, monkeypatch) - - async def dead_loop(*args, **kwargs): - raise RuntimeError("the owner died mid-turn") - - server._run_tool_loop_locked = dead_loop - with pytest.raises(RuntimeError): - _ask(server, tmp_path) - - seen = _stub_the_loop(server) - out = _ask(server, tmp_path) - assert seen == [], ( - "the clock was written only once the turn finished, so a turn that died " - "left no trace and the next call bought the same judgement again" - ) - assert out["text"].startswith(BUSY_MARKER) - - -def test_the_clock_is_written_by_its_own_setter(tmp_path): - """The value on disk is the setter's, not a neighbour's save carrying it along. - - Without this arm, deleting the setter's `_save_meta()` survives every test - above: `set_depth` saves the same `meta.json` immediately afterwards and takes - the new key with it, so the call path looks correct while the writer is broken. - Asserted on the file, because the file is the thing the restart reads. - """ - session = Session.create_with_id("boss-clock", tmp_path) - assert session.boss_asked_at is None, "a fresh session claims it was asked" - - session.set_boss_asked_at(1761000000.0) - - meta_path = tmp_path / ".emrg" / "sessions" / "boss-clock" / "meta.json" - meta = json.loads(meta_path.read_text(encoding="utf-8")) - assert meta.get("boss_asked_at") == 1761000000.0, ( - "the setter did not write the clock: on disk is where a restart reads it" - ) - assert session.boss_asked_at == 1761000000.0 - - -# ── a call that delivered nothing does not consume the window (issue #2499) ── -# -# The clock is stamped before the turn runs, so a turn that *died* keeps it — that -# guarantee is what `test_a_turn_that_died_still_leaves_the_clock` pins. The two -# branches below are the other case: the turn was taken away before it could -# answer, and a stamp left standing refuses the very retry the timeout error asks -# for. "Delivered nothing" and "died mid-way" are different outcomes, so they are -# told apart rather than the stamp moved wholesale to after the turn. - - -def _ask_with_timeout( - server: EmrgServer, tmp_path, timeout_s: int = 30, session_id: str = "task-1", -) -> dict: - """One whole `boss` call, bound included — the layer the timeout lives in.""" - return asyncio.run(server._run_boss_tool( - parent_session_id=session_id, parent_cwd=str(tmp_path), - timeout_s=timeout_s, intent="ask", parent_tools=["read"], - )) - - -def test_a_call_that_timed_out_does_not_consume_the_window(tmp_path, monkeypatch): - """Issue #2499: the retry a timeout error asks for must start a turn. - - Nothing was decided by a call that was cancelled, so there is no stance for - the window to protect — and the busy notice that a standing stamp would - produce tells the round to carry on as if one had been given. - """ - server = _server(tmp_path, monkeypatch) - - async def never_answers(req, ws, session, cancel_event, **kwargs): - await asyncio.sleep(3600) - - server._run_tool_loop_locked = never_answers - - timed_out = _ask_with_timeout(server, tmp_path, timeout_s=1) - assert timed_out.get("error"), ( - f"a call that never answered came back as a result: {timed_out}" - ) - assert "did not answer within" in timed_out["error"] - - seen = _stub_the_loop(server) - retry = _ask_with_timeout(server, tmp_path) - - assert len(seen) == 1, ( - "the retry after a timeout started no owner turn: the cancelled call " - "consumed the four-hour window, so `Raise timeout_s` — the only remedy the " - "error offers — cannot be carried out" - ) - assert BUSY_MARKER not in retry.get("text", ""), ( - "the retry was answered with the busy notice instead of a stance" - ) - - -def test_a_call_cancelled_with_its_round_does_not_consume_the_window( - tmp_path, monkeypatch, -): - """The round that asked was cancelled: same outcome, nothing delivered.""" - server = _server(tmp_path, monkeypatch) - started = asyncio.Event() - - async def never_answers(req, ws, session, cancel_event, **kwargs): - started.set() - await asyncio.sleep(3600) - - server._run_tool_loop_locked = never_answers - - async def scenario(): - task = asyncio.create_task(server._run_boss_tool( - parent_session_id="task-1", parent_cwd=str(tmp_path), - timeout_s=600, intent="ask", parent_tools=["read"], - )) - await asyncio.wait_for(started.wait(), timeout=5) - task.cancel() - with pytest.raises(asyncio.CancelledError): - await task - - asyncio.run(scenario()) - - owner = server._get_or_create_session("boss-task-1", _boss_cwd(tmp_path)) - assert owner.boss_asked_at is None, ( - "a call whose round was cancelled wrote the clock, so the same session's " - "next round is refused for four hours by a call that delivered nothing" - ) - meta_path = _boss_cwd(tmp_path).parent.parent / "meta.json" - meta = json.loads(meta_path.read_text(encoding="utf-8")) - assert "boss_asked_at" not in meta, ( - "the clock is still on disk, and on disk is what a restart reads" - ) - - -def test_a_call_that_answered_still_consumes_the_window(tmp_path, monkeypatch): - """The control: the window's own feature must survive the fix. - - Without this arm the timeout fix could be made by stamping only on delivery, - or by deleting the stamp — both of which would delete issue #2495's feature - and leave every test above green. - """ - server = _server(tmp_path, monkeypatch) - _stub_the_loop(server) - - answered = _ask_with_timeout(server, tmp_path) - assert not answered.get("error"), answered - assert "The owner answered" in answered["text"], answered["text"][:120] - - seen = _stub_the_loop(server) - second = _ask_with_timeout(server, tmp_path) - - assert seen == [], ( - "an owner that answered did not consume the window, so the second call " - "paid for the same judgement again" - ) - assert second["text"].startswith(BUSY_MARKER), second["text"][:80] diff --git a/tests/test_session_sandbox.py b/tests/test_session_sandbox.py index a14e2f906..9e81bcc60 100644 --- a/tests/test_session_sandbox.py +++ b/tests/test_session_sandbox.py @@ -209,8 +209,8 @@ def test_the_injection_documents_every_argument_it_writes(): Both directions are the guard, and neither is a behavioural claim: the injection's own behaviour is pinned by the tests that drive it - (``test_shell_tool_mount.py``, ``test_boss_tool.py``, - ``test_subagent_tool.py``). This one pins the map. + (``test_shell_tool_mount.py``, ``test_subagent_tool.py``). + This one pins the map. """ source = inspect.getsource(EmrgServer._inject_tool_arguments) written = set(re.findall(r'args\["(\w+)"\]\s*=', source)) diff --git a/tests/test_tool_argument_domains.py b/tests/test_tool_argument_domains.py index 4fb02edb5..45f882d76 100644 --- a/tests/test_tool_argument_domains.py +++ b/tests/test_tool_argument_domains.py @@ -41,7 +41,6 @@ from emrg.server import scheduler from emrg.tools import ( bash_tool_v2, - boss_tool, edit_tool, glob_tool, grep_tool, @@ -210,7 +209,6 @@ def test_a_positive_shell_timeout_still_runs(tmp_path): (bash_tool_v2.BashToolV2(), "timeout", ("positive",)), (pwsh_tool_v2.PwshToolV2(), "timeout", ("positive",)), (subagent_tool.SubagentTool(lambda **kwargs: None), "timeout_s", ("at least 1",)), - (boss_tool.BossTool(lambda **kwargs: None), "timeout_s", ("at least 1",)), ] @@ -410,7 +408,6 @@ def test_a_description_claim_nothing_reads_is_the_class_this_file_closes(): # The runner is never called: this sweep reads `definition()` only, and the tool # is here so its declared parameters are asked about like every other tool's. subagent_tool.SubagentTool(lambda **kwargs: None), - boss_tool.BossTool(lambda **kwargs: None), ] diff --git a/tests/test_tool_set_per_message.py b/tests/test_tool_set_per_message.py index d45b69879..9ea31a2cb 100644 --- a/tests/test_tool_set_per_message.py +++ b/tests/test_tool_set_per_message.py @@ -395,7 +395,7 @@ async def fake_chat(messages, tools=None): class _UnlistedTool: - """A registered tool no whitelist names — the shape a `boss`-style role has.""" + """A registered tool no whitelist names — the shape a role-only tool has.""" def __init__(self, name: str) -> None: self._name = name @@ -541,19 +541,16 @@ def test_the_scheduler_states_the_scheduled_task_set(tmp_path, monkeypatch): # websocket, a handler and a template, and test_scheduler.py already builds # all three for the neighbouring field (`input_history`). # - # The two sets were equal until #2467 gave scheduled rounds a tool a - # conversation must not have. What is asserted here is the **shape** of that - # difference rather than its contents: an equality against a literal would - # restate the implementation and go green on any change that kept the restatement - # in step, while the property below is the one that matters — the difference is - # exactly the owner role, and no tool is lost from either side. + # The two lists are one set. Each is stated in its own place so that a + # scheduled round carries the set someone chose for it rather than whatever a + # conversation happens to hold — but a tool offered to one kind of turn and + # withheld from the other is a deliberate split, not an accident of editing one + # list, so the assertion is equality and the next split has to be written here + # with its reason. A literal roster would be the wrong spelling: it restates the + # implementation and goes green on any change that kept the restatement in step. scheduled = set(scheduled_task_tool_names()) default = set(default_tool_names()) - assert scheduled - default == {"boss"}, ( - "the two sets differ by the owner role and nothing else (#2467); any other " - f"difference is a tool that silently appeared on one side: {scheduled - default}" - ) - assert not default - scheduled, ( - "a tool offered to a conversation must stay available to a scheduled round; " - f"these were dropped: {default - scheduled}" + assert scheduled == default, ( + "the two lists are one set; a tool on one side alone is a split nobody " + f"stated: {scheduled ^ default}" )