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(agentic-ide): brief the pane on the WORK, not on writing a prompt
Ruben Lütke53815d97a68c
diff --git a/jarvis/agentic_ide/conversation.py b/jarvis/agentic_ide/conversation.pynew file mode 100644index 0000000000..bdd5b4b11e--- /dev/null+++ b/jarvis/agentic_ide/conversation.py@@ -0,0 +1,97 @@+"""The turns the spoken instruction came out of, bounded for a prompt writer.++A voice instruction to a pane is almost never self-contained. It is the LAST+sentence of a conversation, and it refers back into that conversation with the+shorthand people use when the other side was listening: "points two and three",+"the second one you suggested", "do that for the wake path as well". The prompt+writer used to receive only the sentence, so a back-reference had nothing to+resolve against and travelled through into the finished brief — measured live+2026-07-29, a brief handed to two coding agents read "Ensure that points 2 and 3+from the current context are specifically incorporated". The agents never see+"the current context": that instruction is unresolvable, and the substance the+user actually named (which happened to be the whole task) reached nobody.++So the last few turns travel with the instruction. Two properties decide the+shape:++* **Bounded, and bounded per message.** This rides on a call the user waits+ through, and a long assistant answer is exactly where an unbounded window+ would blow up. The middle of an over-long message is dropped rather than its+ end — the tail is where an answer names its conclusions, and a+ back-reference points at those at least as often as at the opening.+* **Oldest first, and honest about the roles.** The writer has to be able to+ tell what the user asked from what Jarvis answered, because "points two and+ three" points into Jarvis's answer, not the user's question.++Whatever language the conversation happened in is kept verbatim. It is input+DATA for the writer, not output: the brief the writer produces from it is+English like every other artifact (CLAUDE.md §1).+"""+from __future__ import annotations++from collections.abc import Iterable, Sequence++#: How many messages travel with the instruction. Two full exchanges: enough to+#: carry the answer a back-reference points at plus the question that produced+#: it, short of pasting a whole call into every composition.+MAX_MESSAGES = 4++#: Per-message ceiling. A spoken answer that lists four options runs to roughly+#: this length, and that answer IS the thing "points two and three" refers to,+#: so the bound has to clear it rather than cut it in half.+MAX_MESSAGE_CHARS = 1000++_ROLE_LABELS = {"user": "The user", "assistant": "Jarvis"}+++def _bounded(text: str) -> str:+ """``text`` within ``MAX_MESSAGE_CHARS``, keeping both ends when it is not."""+ cleaned = " ".join(str(text or "").split())+ if len(cleaned) <= MAX_MESSAGE_CHARS:+ return cleaned+ half = MAX_MESSAGE_CHARS // 2+ return f"{cleaned[:half]} […] {cleaned[-half:]}"+++def from_messages(+ messages: Iterable[object], *, exclude: str = ""+) -> tuple[tuple[str, str], ...]:+ """The recent conversation as ``(role, text)`` pairs, oldest first.++ Takes anything with ``role`` and ``content`` attributes — a+ ``BrainMessage``, a plain object, a stand-in in a test — because the history+ this reads from is provider-owned and its concrete type is not ours to pin.+ Anything that is not a plain user or assistant string is skipped: a tool+ result or an image block is not conversation the writer can use.++ ``exclude`` drops a trailing message equal to it. The instruction being+ composed is sometimes already appended to the history by the time this runs,+ and handing the writer the same sentence twice reads as the user having said+ it twice.+ """+ pairs: list[tuple[str, str]] = []+ for item in messages or ():+ role = getattr(item, "role", None)+ content = getattr(item, "content", None)+ if role not in _ROLE_LABELS or not isinstance(content, str):+ continue+ text = _bounded(content)+ if text:+ pairs.append((role, text))+ wanted = " ".join((exclude or "").split())+ if wanted and pairs and pairs[-1][1] == _bounded(wanted):+ pairs.pop()+ return tuple(pairs[-MAX_MESSAGES:])+++def render(turns: Sequence[tuple[str, str]]) -> str:+ """The conversation laid out for a writer, or ``""`` when there is none."""+ lines = [+ f"{_ROLE_LABELS[role]}: {text}"+ for role, text in turns or ()+ if role in _ROLE_LABELS and str(text or "").strip()+ ]+ return "\n".join(lines)+++__all__ = ["MAX_MESSAGES", "MAX_MESSAGE_CHARS", "from_messages", "render"]diff --git a/jarvis/agentic_ide/fanout.py b/jarvis/agentic_ide/fanout.pyindex cfe7dc0b36..15ac5c2f3e 100644--- a/jarvis/agentic_ide/fanout.py+++ b/jarvis/agentic_ide/fanout.py@@ -149,6 +149,7 @@ async def deliver(utterance: str,instruction: str | None = None,assignments: Mapping[str, str] | None = None,+ conversation: Sequence[tuple[str, str]] | None = None,compose: Callable[..., Awaitable[Any]] | None = None,send: Callable[[str, str], Awaitable[Any]] | None = None,limit: int = DEFAULT_CONCURRENCY,@@ -161,6 +162,11 @@ async def deliver(``instruction`` (or the raw utterance), which is the right behaviour for"Iris and Bruno, both of you analyse the codebase".+ ``conversation`` is the recent turns the order came out of, passed to every+ pane's composition so a back-reference ("above all points two and three")+ can be resolved into what it names. It is the same for all of them: they+ were all addressed by the same sentence.+``compose`` and ``send`` are injectable so this can be tested without a livePTY or a provider; production leaves them at their defaults.@@ -242,6 +248,7 @@ async def deliver(terminal_name=term.name,agent_display=AGENT_DISPLAY.get(term.agent, term.agent),instruction=own_instruction,+ conversation=tuple(conversation or ()),)except Exception as exc: # noqa: BLE001 - one pane must not sink the fleetlog.warning(diff --git a/jarvis/agentic_ide/prompt_blueprint.py b/jarvis/agentic_ide/prompt_blueprint.pyindex c9ad81e73e..a81b1d9b11 100644--- a/jarvis/agentic_ide/prompt_blueprint.py+++ b/jarvis/agentic_ide/prompt_blueprint.py@@ -14,6 +14,24 @@ made the receiving agent behave *worse*:Enumerated steps measurably REDUCE output quality on Fable 5, and leanersystem prompts score higher on agentic coding evaluations while costing afraction of the tokens.+* **The handover is not the work.** The instruction arrives as speech aimed at+ Jarvis, so it names the handover as well as the task: "prompt T2 and T3 to+ …", "write Alex the prompt for …", "tell Nova it should …". THIS BRIEF IS+ THAT PROMPT. Measured live 2026-07-29, on an order that translates as "write+ the prompt for T2 and T3, and make sure that …": the brief's ``## Task`` read+ "Create or update the system prompts for terminals T2 and T3" — two coding+ agents were sent off to write prompts for themselves, and the analysis the+ user actually asked for reached nobody. The work is what follows the+ handover; writing a prompt is the task only when the user is talking about+ prompt TEXT that lives in the repository.+* **Resolve what the agent cannot see.** A spoken instruction refers back into+ the conversation it came out of — "points two and three", "the second one",+ "do that for the wake path too" — and the agent receives the brief alone.+ The same live composition wrote "Ensure that points 2 and 3 from the current+ context are specifically incorporated": a pointer to something the recipient+ can never open, which is worth exactly as much as writing nothing. The+ recent turns travel with the instruction (``conversation``) so the reference+ can be replaced by what it stands for.* **Full specification up front.** Complete does not mean prescriptive: theagent should not have to come back with questions, which is a statementabout the CONTEXT it was handed, not about how many steps were dictated.@@ -51,7 +69,9 @@ resolved output language.from __future__ import annotationsimport re+from collections.abc import Sequence+from . import conversation as conversation_modulefrom .task_kind import (KIND_IMPLEMENT,KIND_INVESTIGATE,@@ -122,6 +142,24 @@ made against code it can see and you cannot; a solution you guess at gets builteven when it is wrong or already there. Say what must be true when it is done, \and leave the route open.+The user is SPEAKING to Jarvis about this agent, so their words name the \+handover as well as the work: "prompt T2 and T3 to ...", "write Alex the prompt \+for ...", "tell Nova it should ...". THE BRIEF YOU ARE WRITING IS THAT PROMPT. \+Never make prompt-writing the agent's task - a `## Task` reading "create the \+prompt for T2" sends the agent off to do your job and loses the one thing the \+user asked for. The work is whatever the sentence asks for AROUND the handover. \+(The exception is narrow and unmistakable: the user is talking about prompt \+text that lives in the repository as a file.)++The brief is ALL the agent gets. It sees no conversation, no earlier answer, no \+"context" of any kind, so anything the user said by pointing back - "points two \+and three", "the second option", "what you just suggested", "that one" - must \+be REPLACED by what it stands for, spelled out from the conversation you were \+given. A brief that forwards the pointer instead ("incorporate points 2 and 3 \+from the current context") gives the agent nothing it can act on. If a \+reference cannot be resolved from what you were given, write what IS known and \+leave the unresolvable part out rather than pointing at it.+Markdown, exactly this skeleton:{_SKELETON}@@ -299,12 +337,20 @@ def user_block(skeletons: dict[str, str],house_rules: str,attachments: list | None = None,+ conversation: Sequence[tuple[str, str]] | None = None,) -> str:"""Everything the composer knows, laid out for one model call.Longform data first, the request last: the documentation measures up to a30 % quality gain from putting the query at the end for multi-documentinputs, and the file outlines are exactly that.++ ``conversation`` is the handful of turns the instruction came out of, and it+ sits directly in front of the instruction rather than with the longform+ data: it is not reference material, it is what the sentence's pronouns and+ ordinals point AT. Without it "above all points two and three" is+ unresolvable and travels into the brief as a pointer the agent cannot+ follow (live 2026-07-29)."""parts: list[str] = []@@ -340,6 +386,14 @@ def user_block(+ candidate_block)+ spoken = conversation_module.render(conversation or ())+ if spoken:+ parts.append(+ "THE CONVERSATION THIS CAME OUT OF (oldest first; the agent will "+ "never see any of it, so resolve every back-reference against it)\n"+ + spoken+ )+parts.append(f"The user is talking to the coding agent {agent_display} running in a "f"terminal they call {terminal_name}."diff --git a/jarvis/agentic_ide/prompt_composer.py b/jarvis/agentic_ide/prompt_composer.pyindex 04a389e20d..74e06536b0 100644--- a/jarvis/agentic_ide/prompt_composer.py+++ b/jarvis/agentic_ide/prompt_composer.py@@ -551,6 +551,7 @@ async def _compose_once(context, # noqa: ANN001 - Awaitable[tuple[dict[str, str], str]]notify: Callable[[str, str], None],attachments: list,+ conversation: Sequence[tuple[str, str]],) -> str:"""Wait for the file material, then make the one writing call.@@ -586,6 +587,7 @@ async def _compose_once(skeletons=outlines,house_rules=house_rules,attachments=attachments,+ conversation=conversation,),on_first_delta=lambda: notify(STAGE_DRAFTING,@@ -639,6 +641,7 @@ async def compose(brain=None, # noqa: ANN001 - Brain, avoid an import cycleon_progress: ProgressSink | None = None,attachments: Sequence | None = None,+ conversation: Sequence[tuple[str, str]] | None = None,) -> ComposedPrompt:"""Build the prompt for ``terminal_name`` out of what the user said.@@ -654,6 +657,15 @@ async def compose(described the picture and the model that writes prose are separateproviders and having one without the other is ordinary.+ ``conversation`` is the last few turns as ``(role, text)`` pairs. A spoken+ instruction points back into them constantly ("above all points two and+ three"), and the agent receives the brief alone — so without them the+ writer has nothing to resolve the reference against and forwards it+ verbatim into a prompt nobody can act on (live 2026-07-29). Only the model+ layer uses+ them: the deterministic prompt states what the user said and never claims+ to have understood more than the sentence.+``on_progress`` receives a ``ComposeNotice`` at each beat of thecomposition; left None they are printed (see ``print_notice``). The typedprompt bar passes ``use_llm=False`` and gets no notices at all — nothing is@@ -670,6 +682,7 @@ async def compose(said = (utterance or "").strip()base_instruction = _clean_speech(instruction or said) or (instruction or said).strip()attached = list(attachments or [])+ spoken_before = tuple(conversation or ())if not said:return ComposedPrompt(text="", composed_by="raw", note="empty instruction")@@ -746,6 +759,7 @@ async def compose(context=context_task,notify=notify,attachments=attached,+ conversation=spoken_before,),timeout=COMPOSE_TIMEOUT_S,)diff --git a/jarvis/agentic_ide/work_split.py b/jarvis/agentic_ide/work_split.pyindex 50d7010edf..994bc8fed8 100644--- a/jarvis/agentic_ide/work_split.py+++ b/jarvis/agentic_ide/work_split.py@@ -36,6 +36,7 @@ from __future__ import annotationsimport asyncioimport jsonimport re+from collections.abc import Sequencefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any@@ -128,9 +129,31 @@ _SYSTEM_PROMPT = (def _user_block(- *, instruction: str, count: int, folder: str, areas: list[str], profile: list[str]+ *,+ instruction: str,+ count: int,+ folder: str,+ areas: list[str],+ profile: list[str],+ conversation: Sequence[tuple[str, str]] = (),) -> str:- lines = [+ """What the planner is handed. The conversation goes FIRST, and it matters.++ The goal arrives as one spoken sentence, and a spoken sentence points back+ at what was said before it — "split points two and three between them". A+ planner that only sees the sentence divides a goal it cannot read, so the+ turns it came out of are given ahead of it.+ """+ from . import conversation as conversation_module++ lines: list[str] = []+ spoken = conversation_module.render(conversation)+ if spoken:+ lines.append(+ "The conversation this order came out of (oldest first; the goal "+ "below refers back into it):\n" + spoken + "\n"+ )+ lines += [f"Overall goal: {instruction}",f"Number of agents: {count}",f"Repository: {Path(folder).name}",@@ -295,6 +318,7 @@ async def split(session: Any,count: int,brain: Any = None,+ conversation: Sequence[tuple[str, str]] | None = None,timeout_s: float = SPLIT_TIMEOUT_S,) -> WorkSplit:"""Divide ``instruction`` across ``count`` agents.@@ -302,6 +326,10 @@ async def split(``brain`` pins the planning model explicitly; left None a quality-tier modelis resolved and the deterministic split takes over when none is reachable.+ ``conversation`` is the recent turns, for the same reason the composer takes+ them: "split points two and three between you" names the work by pointing+ at an answer that is not in the sentence.+Never raises. Every failure path lands on the directory split, because"the fleet got a coarser plan" is a far better outcome than "your fiveagents did nothing".@@ -362,6 +390,7 @@ async def split(folder=folder,areas=areas,profile=profile_lines,+ conversation=tuple(conversation or ()),),),timeout=timeout_s,diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex b3f3c25916..5ac258b6e6 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -6042,6 +6042,7 @@ class BrainManager:found.instruction or user_text,session=session,count=len(names),+ conversation=self._agentic_ide_conversation(user_text),)assignments = {name: item.task@@ -6079,6 +6080,32 @@ class BrainManager:return f"{verdict} {question}" if verdict else questionreturn verdict+ def _agentic_ide_conversation(self, utterance: str) -> tuple[tuple[str, str], ...]:+ """The turns an addressed-pane instruction came out of, for the composer.++ A spoken order to a pane points back into the conversation constantly —+ "above all points two and three", "do that for the wake path too" — and+ the coding agent receives the composed brief and nothing else. Live+ 2026-07-29 that gap produced a brief instructing two agents to+ "incorporate points 2 and 3 from the current context": a pointer to+ something they can never open, so the substance of the order reached+ neither of them.++ Read through ``_active_turn_history`` rather than ``self._history``+ directly, because a realtime call keeps its own bounded context and+ hands it to the delegated turn — on that path the shared buffer is+ empty and this is the ONLY place the previous turns exist.+ """+ from jarvis.agentic_ide import conversation as ide_conversation++ try:+ return ide_conversation.from_messages(+ self._active_turn_history(), exclude=utterance+ )+ except Exception: # noqa: BLE001 - context is a bonus, never the turn+ log.debug("Agentic IDE: conversation context unavailable", exc_info=True)+ return ()+async def _deliver_agentic_ide_prompt(self,*,@@ -6121,6 +6148,7 @@ class BrainManager:utterance=utterance,instruction=instruction,assignments=assignments,+ conversation=self._agentic_ide_conversation(utterance),)except Exception: # noqa: BLE001 - never crash the turn over a panelog.warning("Agentic IDE fast-path failed", exc_info=True)@@ -6291,6 +6319,9 @@ class BrainManager:from jarvis.agentic_ide.fleet_actions import wait_for_prompt_readyinstruction = ide_intent.spawn_instruction(user_text)+ # Read once, up front: this runs as a background task that outlives the+ # turn, and the history it reads keeps moving underneath it.+ spoken_before = self._agentic_ide_conversation(user_text)assignments: dict[str, str] | None = Noneif len(names) > 1 and ide_intent.wants_split(user_text):try:@@ -6300,6 +6331,7 @@ class BrainManager:instruction,session=session,count=len(names),+ conversation=spoken_before,)assignments = {name: item.task@@ -6324,6 +6356,7 @@ class BrainManager:utterance=user_text,instruction=instruction,assignments=assignments,+ conversation=spoken_before,)log.info("Agentic IDE spawned-fleet briefing: %d of %d prompts delivered",diff --git a/tests/unit/agentic_ide/test_conversation_reaches_the_writer.py b/tests/unit/agentic_ide/test_conversation_reaches_the_writer.pynew file mode 100644index 0000000000..2d932d3700--- /dev/null+++ b/tests/unit/agentic_ide/test_conversation_reaches_the_writer.py@@ -0,0 +1,122 @@+"""The turns an order came out of must actually reach the writing model.++The rule that a back-reference has to be resolved is worthless if the thing it+resolves against never arrives. This walks the path the live 2026-07-29 failure+took — brain manager → fan-out → composer → the one model call — and pins that+the conversation survives every hop.+"""+from __future__ import annotations++from types import SimpleNamespace++from jarvis.agentic_ide import fanout, prompt_composer++# The live turns this bug was measured on, kept verbatim: they ARE the input+# under test, and a translated back-reference would not reproduce it.+_TURNS = (+ # i18n-allow: spoken input under test+ ("user", "wie können wir die Transkription schärfen?"),+ (+ # i18n-allow: spoken input under test+ "assistant",+ "Zweitens die VAD-Schwellenwerte optimieren, drittens ein "+ "Post-Processing-Modul nach dem STT.",+ ),+)+++class _CapturingBrain:+ """Answers with a valid brief and keeps what it was asked."""++ def __init__(self) -> None:+ self.system = ""+ self.user = ""++ async def complete(self, request: object): # noqa: ANN202 - test double+ from jarvis.core.protocols import BrainDelta++ self.system = str(getattr(request, "system", "") or "")+ self.user = "\n".join(+ str(getattr(m, "content", "") or "")+ for m in getattr(request, "messages", ())+ )+ yield BrainDelta(content="## Task\nSharpen the VAD thresholds.\n")+++def _session(tmp_path) -> object: # noqa: ANN001 - pytest tmp_path+ return SimpleNamespace(+ folder=str(tmp_path),+ profile=SimpleNamespace(+ instruction_files=[], summary_lines=lambda: ["Test workspace"]+ ),+ )+++async def test_the_composer_hands_the_conversation_to_the_writer(tmp_path) -> None: # noqa: ANN001+ brain = _CapturingBrain()++ result = await prompt_composer.compose(+ # i18n-allow: spoken input under test+ "mach für T2 den Prompt, vor allem Punkt zwei und drei",+ session=_session(tmp_path),+ terminal_name="T2",+ brain=brain,+ conversation=_TURNS,+ )++ assert result.composed_by == "llm"+ assert "VAD-Schwellenwerte" in brain.user+ assert "Post-Processing-Modul" in brain.user+ # And the rule that tells the writer what to do with it travels along.+ assert "The brief is ALL the agent gets" in " ".join(brain.system.split())+++async def test_a_composition_without_conversation_still_works(tmp_path) -> None: # noqa: ANN001+ """The first turn of a session has nothing to carry, and that is normal."""+ brain = _CapturingBrain()++ result = await prompt_composer.compose(+ "look at the wake word",+ session=_session(tmp_path),+ terminal_name="T2",+ brain=brain,+ )++ assert result.composed_by == "llm"+ assert "THE CONVERSATION" not in brain.user+++async def test_the_fan_out_gives_every_pane_the_same_conversation() -> None:+ """They were all addressed by one sentence, so they all get its context."""+ seen: dict[str, tuple] = {}++ async def compose(utterance: str, **kwargs) -> prompt_composer.ComposedPrompt:+ seen[kwargs["terminal_name"]] = tuple(kwargs.get("conversation") or ())+ return prompt_composer.ComposedPrompt(text=f"## Task\n{utterance}")++ async def send(name: str, text: str) -> SimpleNamespace: # noqa: ARG001+ return SimpleNamespace(submitted=True)++ terminals = [+ SimpleNamespace(name=name, agent="claude", status="live", pty_id="pty")+ for name in ("T2", "T3")+ ]+ session = SimpleNamespace(+ terminals=terminals,+ folder="/repo",+ find=lambda wanted: next(+ (t for t in terminals if t.name.casefold() == wanted.casefold()), None+ ),+ )++ result = await fanout.deliver(+ session=session,+ terminals=["T2", "T3"],+ utterance="prompt T2 and T3, above all points two and three",+ conversation=_TURNS,+ compose=compose,+ send=send,+ )++ assert result.all_delivered+ assert seen == {"T2": _TURNS, "T3": _TURNS}diff --git a/tests/unit/agentic_ide/test_prompt_handover_and_backreference.py b/tests/unit/agentic_ide/test_prompt_handover_and_backreference.pynew file mode 100644index 0000000000..cad83fc372--- /dev/null+++ b/tests/unit/agentic_ide/test_prompt_handover_and_backreference.py@@ -0,0 +1,202 @@+"""The two ways a spoken order lost its task on the way to a coding agent.++Both were measured on one live composition (2026-07-29). The user said, of a+transcription-quality discussion Jarvis had just answered with four numbered+levers: "mach bitte für T2 und T3 den Prompt … vor allen Dingen Punkt zwei und+drei". What the two panes received was a brief whose ``## Task`` read "Create or+update the system prompts for terminals T2 and T3" and whose acceptance+criteria asked them to incorporate "points 2 and 3 from the current context".++So the handover became the work, and the work became a pointer to something the+recipient cannot open. Neither agent could have done what was asked.++These tests pin the two rules and the plumbing that makes the second one+possible. Whether the writer model then obeys is a live question — but a rule+that is absent cannot be obeyed at all, and the conversation it needs was not+being passed to it in ANY form.+"""+from __future__ import annotations++import pytest++from jarvis.agentic_ide import conversation+from jarvis.agentic_ide.prompt_blueprint import system_prompt, user_block+from jarvis.agentic_ide.task_kind import (+ KIND_IMPLEMENT,+ KIND_INVESTIGATE,+ KIND_NEUTRAL,+ KIND_QUESTION,+ KIND_REVIEW,+)++_ALL_KINDS = (+ KIND_IMPLEMENT,+ KIND_REVIEW,+ KIND_INVESTIGATE,+ KIND_QUESTION,+ KIND_NEUTRAL,+)+++class _Message:+ """Stand-in for a ``BrainMessage``; the real history is provider-owned."""++ def __init__(self, role: str, content: object) -> None:+ self.role = role+ self.content = content+++# ------------------------------------------------- the handover is not the work[email protected]("kind", _ALL_KINDS)+def test_every_kind_says_the_brief_itself_is_the_prompt(kind):+ """"Prompt T2" asks for THIS brief — it is not a task about prompts."""+ text = " ".join(system_prompt(kind).split())+ assert "THE BRIEF YOU ARE WRITING IS THAT PROMPT" in text+ assert "Never make prompt-writing the agent's task" in text++[email protected]("kind", _ALL_KINDS)+def test_every_kind_keeps_the_one_case_where_prompts_are_the_task(kind):+ """A repo whose prompt TEXT is being edited is real work, not a handover."""+ text = " ".join(system_prompt(kind).split())+ assert "prompt text that lives in the repository as a file" in text+++# --------------------------------------------- back-references must be resolved[email protected]("kind", _ALL_KINDS)+def test_every_kind_demands_back_references_be_resolved(kind):+ text = " ".join(system_prompt(kind).split())+ assert "The brief is ALL the agent gets" in text+ assert "points two and three" in text+ assert "must be REPLACED by what it stands for" in text++[email protected]("kind", _ALL_KINDS)+def test_every_kind_says_what_to_do_with_an_unresolvable_reference(kind):+ """Leaving it out beats forwarding a pointer that resolves to nothing."""+ text = system_prompt(kind).replace("\n", " ")+ assert "cannot be resolved from what you were given" in text+++# ------------------------------------------------------ the conversation block+def test_user_block_carries_the_conversation_and_keeps_it_before_the_request():+ block = user_block(+ utterance="mach bitte für T2 und T3 den Prompt, vor allem Punkt zwei und drei",+ instruction="Punkt zwei und drei",+ terminal_name="T2",+ agent_display="Claude Code",+ profile_lines=["Folder: /repo"],+ candidates=["jarvis/stt.py"],+ skeletons={"jarvis/stt.py": "def transcribe(): ..."},+ house_rules="",+ conversation=(+ ("user", "wie können wir die Transkription schärfen?"),+ ("assistant", "Zweitens die VAD-Schwellenwerte, drittens ein Post-Processing-Modul."),+ ),+ )++ assert "VAD-Schwellenwerte" in block+ assert "Post-Processing-Modul" in block+ # It is context for the sentence, so it stands with it — after the outlines+ # and before the words it explains.+ assert block.index("FILE OUTLINES") < block.index("THE CONVERSATION THIS CAME OUT OF")+ assert block.index("THE CONVERSATION THIS CAME OUT OF") < block.index(+ "WHAT THE USER SAID"+ )+++def test_user_block_says_the_agent_never_sees_the_conversation():+ """The writer has to know the block is its job to resolve, not to forward."""+ block = user_block(+ utterance="do it",+ instruction="do it",+ terminal_name="T2",+ agent_display="Codex",+ profile_lines=[],+ candidates=[],+ skeletons={},+ house_rules="",+ conversation=(("assistant", "Four levers: one, two, three, four."),),+ )++ assert "the agent will never see any of it" in block.replace("\n", " ")+++def test_user_block_without_a_conversation_is_unchanged():+ """The common case — a first turn — must not gain an empty header."""+ block = user_block(+ utterance="do it",+ instruction="do it",+ terminal_name="T2",+ agent_display="Codex",+ profile_lines=[],+ candidates=[],+ skeletons={},+ house_rules="",+ conversation=(),+ )++ assert "THE CONVERSATION" not in block+++# ------------------------------------------------------- history normalisation+def test_from_messages_keeps_only_plain_user_and_assistant_text():+ turns = conversation.from_messages(+ [+ _Message("user", "first"),+ _Message("tool", "a tool result"),+ _Message("assistant", ["not", "a", "string"]),+ _Message("assistant", "second"),+ ]+ )++ assert turns == (("user", "first"), ("assistant", "second"))+++def test_from_messages_keeps_the_most_recent_window():+ turns = conversation.from_messages(+ [_Message("user", f"turn {i}") for i in range(conversation.MAX_MESSAGES + 3)]+ )++ assert len(turns) == conversation.MAX_MESSAGES+ assert turns[-1][1].endswith(str(conversation.MAX_MESSAGES + 2))+++def test_from_messages_drops_the_instruction_being_composed():+ """The live history may already hold the sentence we are composing from."""+ turns = conversation.from_messages(+ [_Message("user", "earlier"), _Message("user", " prompt T2 now ")],+ exclude="prompt T2 now",+ )++ assert turns == (("user", "earlier"),)+++def test_an_over_long_message_keeps_both_of_its_ends():+ """A back-reference points at an answer's conclusions as often as its start."""+ side = conversation.MAX_MESSAGE_CHARS+ body = "A" * side + "MIDDLE" + "Z" * side+ (role, text), = conversation.from_messages([_Message("assistant", body)])++ assert role == "assistant"+ assert text.startswith("A")+ assert text.endswith("Z")+ assert "MIDDLE" not in text+ assert len(text) <= conversation.MAX_MESSAGE_CHARS + 10+++def test_render_labels_who_said_what():+ """"Points two and three" points into Jarvis's answer, not the question."""+ out = conversation.render(+ (("user", "how do we sharpen it?"), ("assistant", "Four levers."))+ )++ assert out.splitlines() == [+ "The user: how do we sharpen it?",+ "Jarvis: Four levers.",+ ]+++def test_render_of_nothing_is_empty():+ assert conversation.render(()) == ""+ assert conversation.render((("user", " "),)) == ""