Skip to content

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.

feat(dictation): Prompt Mode is one instruction and one worked example again

rubenluetke10-beepfa1a43ba3306
diff --git a/jarvis/agentic_ide/prompt_blueprint.py b/jarvis/agentic_ide/prompt_blueprint.py
index 95569f2dbf..fa8f58c261 100644
--- a/jarvis/agentic_ide/prompt_blueprint.py
+++ b/jarvis/agentic_ide/prompt_blueprint.py
@@ -106,11 +106,16 @@ _SKELETON = """\
- <an observable outcome the user actually stated>\
"""
-# The two rules every prompt-writing surface shares — the Agentic IDE composer
-# here and the dictation Prompt Mode (``jarvis.dictation.prompt_mode``). ONE
-# text each, imported by both: a rule spelled twice is how "goal, not route"
-# ends up meaning something subtly different depending on whether the prompt
-# was spoken at a pane or dictated into a field.
+# The two rules the composer states once each, so "goal, not route" cannot
+# come to mean two subtly different things across the kinds below.
+#
+# The dictation Prompt Mode used to import both. It no longer does (v5,
+# 2026-08-27), and the difference is what each surface writes FOR: the
+# composer briefs an agent already running in the user's repository, where a
+# guessed implementation gets built; Prompt Mode writes a prompt the user
+# pastes wherever they like, and its instruction is deliberately one paragraph
+# — the rules it had accumulated were making its prompts worse, not better.
+# Both still refuse to invent what was not said; only this one says it here.
GOAL_NOT_IMPLEMENTATION_RULE = """\
Give the agent the GOAL, the CONTEXT and the CONSTRAINTS - never the \
implementation. Which approach, which mechanism, which order are its decisions, \
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index af6f2bdeba..cddcfd290b 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -3592,19 +3592,18 @@ class DictationConfig(BaseModel):
# Prompt Mode — a dictation comes out as the prompt for a coding agent
# ------------------------------------------------------------------
- #: Rewrite every dictation into a finished prompt for an AI coding agent:
- #: plain text, in the language it was spoken, sounding like a person
- #: talking — the goal, the stated context and constraints, every task
- #: that was dictated, nothing invented. The Agentic IDE's own prompt
- #: doctrine (``jarvis/agentic_ide/prompt_blueprint.py``) applied to a
- #: transcript. It runs on the polish pass's own fast model chain
- #: (``polish_provider``), asking for the family's stronger fast model,
- #: and makes that model work through a written analysis of the transcript
- #: before it composes anything — the ``<analysis>``/``<prompt>`` answer in
- #: ``jarvis/dictation/prompt_mode.py``. That analysis is what the bar of
- #: "about 5-7 s of thinking" actually buys: a model spends time by
- #: emitting tokens, and one asked for the message directly writes a first
- #: draft in under a second.
+ #: Turn every dictation into the finished prompt it is asking for: the
+ #: goal, the stated context and constraints and every dictated task,
+ #: written up the way a good prompt is written — a role, the task, the
+ #: guardrails, the output format — in the language it was spoken, with
+ #: nothing invented. It runs on the polish pass's own fast model chain
+ #: (``polish_provider``), asking for the family's stronger fast model.
+ #:
+ #: One call, one instruction, one worked example
+ #: (``jarvis/dictation/prompt_mode.py``). Earlier revisions grew a rule
+ #: per defect until they mostly told a capable model what it was not
+ #: allowed to write — including markdown and headings, which is what a
+ #: good prompt is made of. That is deliberately gone.
#:
#: Outranks the polish and translate passes while on — a prompt is
#: already restructured, so neither has anything left to do. When no
@@ -3616,13 +3615,12 @@ class DictationConfig(BaseModel):
prompt_mode: bool = False
#: Wall-clock ceiling for one Prompt Mode call, from the finished
- #: transcript. Far longer than the polish pass's 1.2 s: the call carries a
- #: written analysis of the transcript in front of the message, which is
- #: where the thinking happens, and a real dictation spends 6-9 s on the
- #: pair. 12 s leaves room for that without cutting the answer off as it
- #: starts writing; below 4 s the analysis cannot finish and the pass only
- #: ever times out, and 20 s is as far as it may be pushed before this
- #: stops being dictation. Clamped, never rejected (AP-16).
+ #: transcript. A safety net, not a target: the fast chain answers in 2-6 s
+ #: depending on the provider's hardware, and 12 s only has to keep a long
+ #: prompt on a slower family from being cut off (a truncated one is
+ #: rejected and costs the whole pass). Below 4 s the pass only ever times
+ #: out, which is worse than being off; 20 s is as far as it may be pushed
+ #: before this stops being dictation. Clamped, never rejected (AP-16).
prompt_mode_timeout_ms: int = Field(default=12_000, ge=4_000, le=20_000)
@field_validator("paste_chord", mode="before")
diff --git a/jarvis/dictation/prompt_mode.py b/jarvis/dictation/prompt_mode.py
index 505a7e1aa4..7e532d3898 100644
--- a/jarvis/dictation/prompt_mode.py
+++ b/jarvis/dictation/prompt_mode.py
@@ -1,65 +1,56 @@
-"""Prompt Mode — a dictation comes out as the prompt a coding agent should get.
+"""Prompt Mode — a dictation comes out as the prompt the user asked for.
What it is
----------
-The user holds the dictation key, describes a task in their own words — half
-sentences, false starts, several small tasks in one breath — and what lands
-in the field is a finished prompt for an AI coding agent: the situation they
-described, the goal, the constraints that were stated, and nothing invented.
-Plain text, in the language they spoke, in the user's own words wherever
-those already carry the meaning. It is the Agentic IDE's prompt doctrine
-(:mod:`jarvis.agentic_ide.prompt_blueprint`) aimed at a transcript instead of
-a pane.
-
-Two phases, because thinking is the only thing that buys quality
-----------------------------------------------------------------
-The maintainer's bar is that the writer THINKS for about 5-7 s before it
-answers, and that the answer be worth the wait (2026-08-27). A language model
-does not think by waiting; it thinks by emitting tokens. v3 asked for the
-finished message directly, so a fast model wrote it in 0.4-0.9 s — measured
-live — and the quality was the quality of a first draft: concrete detail from
-the transcript dropped, the speaker's own wording replaced with a writer's
-wording, several dictated tasks folded into one.
-
-So the answer is now two blocks in one call. ``<analysis>`` is a working pass
-the model must complete first: count the tasks, inventory every literal the
-user said, name the situation, the limits and the wording that has to survive.
-``<prompt>`` is the message, written against that inventory. The analysis is
-thrown away — it never reaches the user — and its whole purpose is that the
-model has read the transcript properly by the time it writes. It also costs
-the seconds the bar asks for: an inventory of a real dictation is 300-900
-tokens, which is where the 5-7 s comes from, on any provider rather than only
-on the ones that expose a thinking budget.
-
-Why it still rides the polish pass's fast chain
------------------------------------------------
-The chain in :mod:`jarvis.dictation.polish_client` is the only lane on this
-host that reaches a model at all without a cold start, and Prompt Mode asks
-it for the family's STRONGER fast model — the one the translate pass uses
+The user holds the dictation key and says what they want, in their own words —
+half sentences, false starts, several small tasks in one breath. What lands in
+the field is the finished prompt: what they described, worked up into
+something an AI model can act on, in the language they spoke.
+
+The instruction, and why it is short
+------------------------------------
+This module is one instruction and one worked example. That is a deliberate
+correction of v2-v4, which grew into eleven thousand characters of rules — no
+markdown, no headings, plain paragraphs, keep the register, six of these,
+seven of those — and each rule narrowed what the writer was allowed to
+produce. The maintainer's own reference run is the argument (2026-08-27): he
+said "kannst du mir bitte ein Prompt schreiben" to Gemini, with no rules at
+all, and got back a structured, professional prompt with a role, a workflow
+and quality criteria. That is the output this feature is for, and every rule
+that forbade markdown or headings was forbidding exactly it.
+
+So: say what the job is, show one run of it, and let the model write. The
+example carries what a page of rules used to, because a shown run outweighs a
+written rule — measured on this very prompt, where a rule about language lost
+to an example in the other language.
+
+What is guarded and what is not
+-------------------------------
+Not guarded: shape. A prompt may be markdown, may carry headings, lists,
+sections and a role line — that is what a good prompt looks like, and v3's
+``markdown`` rejection was this feature refusing its own purpose.
+
+Guarded: fidelity and damage. The message must not be empty, must not stop
+mid-sentence, must carry every literal the user spoke and every protected
+spelling, and must not collapse to a fraction of what was said. All
+deterministic, all fail-open — a rejection delivers the transcript to the
+ordinary passes, and the raw words are never lost.
+
+Then two deterministic finishes: typographic debris a fast model leaves in
+identifiers is normalised, and a courtesy sign-off is cut, because what the
+user pastes into a model should end on its last piece of substance.
+
+Where it runs
+-------------
+On the polish pass's own chain (:mod:`jarvis.dictation.polish_client`), asking
+for the family's stronger fast model — the one the translate pass uses
(``gemini-3.7-flash`` on Google, ``gpt-oss-120b`` on Groq and Cerebras,
-``gpt-5.4-mini`` on OpenAI). A thinking-grade API model or a subscription CLI
-would spend 15-30 s and stop being dictation.
-
-What it keeps from the polish pass and what it does not
--------------------------------------------------------
-Kept: the shape. Never raises, never loses text, one status per attempt,
-fail-open to the ordinary passes, the fenced user message that keeps a
-dictation shaped like an instruction from becoming one
-(:func:`jarvis.dictation.polish_prompt.build_polish_user_message`), the
-protected-terms block, the breaker.
-
-Not kept: the polish pass's drift guards. They measure how far the words
-moved, and here they are allowed to move. Prompt Mode guards the two things
-that can still go wrong — the SHAPE of the answer (not empty, not markdown,
-not cut off) and its FIDELITY to the transcript (every literal the user
-spoke still present, and the message not collapsed to a fraction of what was
-said). Then it finishes deterministically: typographic debris a fast model
-leaves behind is normalised, and a courtesy sign-off the model tacked on is
-cut, because the message ends on its last piece of substance.
-
-Ships OFF. Unlike the formatter it changes WHAT the text says, on purpose,
-and sends the words to a cloud model on most installs (the polish pass's
-on-device rule still applies: a local recognizer keeps the chain local).
+``gpt-5.4-mini`` on OpenAI). One call, no scratchpad, no second pass: writing
+a prompt is one job, and a model that is good at it does it in one go.
+
+Ships OFF. It changes WHAT the text says, on purpose, and sends the words to a
+cloud model on most installs (the polish pass's on-device rule still applies:
+a local recognizer keeps the chain local).
Pure orchestration — the imports that cost anything are inside the function
(AP-26), so ``import jarvis.dictation.prompt_mode`` is free on the boot path.
@@ -74,11 +65,7 @@ import time
from collections.abc import Sequence
from typing import Any, Final
-from jarvis.agentic_ide.prompt_blueprint import (
- FORBIDDEN_SUBJECTS_RULE,
- GOAL_NOT_IMPLEMENTATION_RULE,
- looks_truncated,
-)
+from jarvis.agentic_ide.prompt_blueprint import looks_truncated
from jarvis.dictation.polish import PolishOutcome
from jarvis.dictation.polish_prompt import (
build_polish_user_message,
@@ -91,98 +78,63 @@ log = logging.getLogger(__name__)
#: behaviour, for the same reason ``POLISH_PROMPT_VERSION`` exists: a quality
#: regression must be attributable to a prompt revision, not a provider.
#:
-#: v2: plain text instead of the markdown skeleton, the transcript's own
-#: language instead of English, a spoken register (the humanizer rules, cut
-#: to the six that matter at this latency), and an explicit rule that several
-#: tasks spoken at once all survive. Measured live 2026-08-24: v1 answered
-#: with ``## Task`` headings in English and folded two dictated tasks into one.
-#:
-#: v3: the shape of a professional request (situation, goal, limits, thanks)
-#: as paragraphs without labels, "fix what exists" instead of "implement",
-#: one statement per fact (no restating "make sure" sentences), a courteous
-#: register with the transcript-language word bans, plain typography, a
-#: closing line of thanks, and two worked examples. Measured live 2026-08-27
-#: on the fast chain: v2 dropped the observed symptom ("shows done while it
-#: is still working"), turned a broken existing indicator into "implement an
-#: indicator", padded with a "Stelle sicher" restatement of the sentence
-#: before, and wrote U+2011 non-breaking hyphens into identifiers.
+#: v2-v4 are one arc and one mistake. v2 replaced v1's markdown skeleton with
+#: plain text in the spoken language; v3 added the shape of a courteous
+#: request and a closing line of thanks; v4 added a written analysis, a draft
+#: and a read-back, to make the writer spend the 5-7 s the maintainer had
+#: asked for. Each revision answered a real defect and each one added rules,
+#: until the instruction was eleven thousand characters that told a capable
+#: model mostly what it was NOT allowed to write.
#:
-#: v4: the two-phase answer (``<analysis>`` then ``<prompt>``), fidelity to
-#: the speaker's own words as the DEFAULT rather than one rule among many,
-#: and no closing line at all. Measured live 2026-08-27: v3 answered in under
-#: a second — no pass over the transcript worth the name — reworded phrasing
-#: the user had chosen deliberately, thinned the context they had given, and
-#: closed every message with a sign-off the receiving agent has no use for.
+#: v5 throws that away. The maintainer's reference run settled it
+#: (2026-08-27): a dictation handed to Gemini with no instruction beyond
+#: "write me a prompt" came back as a structured professional prompt — role,
+#: workflow, quality criteria, markdown — which is precisely the output v3's
+#: ``markdown`` guard rejected and v3's rules forbade. So the instruction is
+#: one paragraph and one worked example (that same run), the shape guards are
+#: gone, and the analysis/draft/read-back ceremony is gone with them: it made
+#: the pass slower and dearer to enforce a narrowness nobody wanted.
#:
-#: The language rule is a POINT OF THE ANALYSIS and both worked examples are
-#: shown, one German and one English. A first cut of v4 kept only the English
-#: pair, trusting the written rule to carry the language; measured live on
-#: Groq the same day, a German dictation came back as a fluent English
-#: message. A shown example outweighs a written rule, so the examples have to
-#: disagree with each other about language for the rule to be readable at
-#: all — and naming the language in writing before composing is what makes
-#: the model commit to it.
-PROMPT_MODE_PROMPT_VERSION: Final[int] = 4
+#: What survives from v4 is what was never about shape: the fidelity guards
+#: (a literal the user spoke must be in the prompt, the prompt must not
+#: collapse to a fraction of the transcript) and the sign-off trim.
+PROMPT_MODE_PROMPT_VERSION: Final[int] = 5
#: The status a successful Prompt Mode delivery reports on the history row.
#: Lives in ``POLISH_STATUSES`` (the shared vocabulary) — restated here as a
#: named constant so call sites compare against a name, not a string literal.
STATUS_PROMPTED: Final[str] = "prompted"
-# The ceiling and its bounds. The bar is that the writer spends about 5-7 s
-# thinking; the two-phase answer is what makes it spend them, and a ceiling
-# has to clear that plus the request itself. 12 s is the hard stop — a long
-# dictation with a full inventory lands at 6-9 s and must not be cut off at
-# the moment it starts writing the message. 4 s is as low as anyone may set
-# it before the analysis phase can no longer finish (below that the pass only
-# ever times out, which is worse than being off), and 20 s is as far as it
-# may be pushed before the feature stops being dictation.
+# One call, one prompt written. The bound is a safety net, not a target: the
+# fast chain answers in 2-6 s depending on the provider's hardware, and 12 s
+# leaves room for a long dictation on a slower family without ever cutting an
+# answer off mid-prompt. 4 s is the floor (below it the pass only ever times
+# out, which is worse than being off) and 20 s the ceiling before this stops
+# being dictation.
_DEFAULT_TIMEOUT_MS: Final[int] = 12_000
_MIN_TIMEOUT_MS: Final[int] = 4_000
_MAX_TIMEOUT_MS: Final[int] = 20_000
-# The budget covers ALL THREE blocks: the analysis (300-900 tokens on a real
-# dictation), the draft, and the message the read-back corrects. Generous on
-# purpose — a cut-off answer is rejected as truncated and costs the whole
-# pass. Temperature 0: this is rewriting, not writing.
-_MAX_OUTPUT_TOKENS: Final[int] = 4_000
+# A written-out prompt with a role, sections and format rules is long — the
+# reference run is about 700 tokens — and a cut-off one is rejected as
+# truncated and costs the whole pass. Temperature 0: the job is well defined.
+_MAX_OUTPUT_TOKENS: Final[int] = 3_000
_TEMPERATURE: Final[float] = 0.0
-# The three blocks of the answer. Parsed with tolerant regexes rather than an
-# XML parser: the content is prose the model wrote, it may contain a stray
-# angle bracket, and a strict parser would throw away a perfectly good message
-# over one. Case-insensitive and whitespace-tolerant for the same reason — a
-# fast model writes ``<Prompt>`` often enough to matter.
-#
-# ``<prompt>`` is LAST in the answer, so the regex takes the last one: a model
-# that names the tag inside its analysis ("...then the <prompt> block...")
-# would otherwise hand us its worksheet.
-_ANALYSIS_BLOCK_RE: Final[re.Pattern[str]] = re.compile(
- r"<\s*analysis\s*>(.*?)<\s*/\s*analysis\s*>", re.IGNORECASE | re.DOTALL
-)
+# The one piece of structure asked of the model, and the only reason for it:
+# a model handed this job likes to introduce it ("Hier ist ein System-Prompt
+# für deinen Auto-Prompting-Modus" — the reference run's own first line). The
+# tag is a fence around the deliverable, not a scratchpad and not a schema.
_PROMPT_OPEN_RE: Final[re.Pattern[str]] = re.compile(r"<\s*prompt\s*>", re.IGNORECASE)
_PROMPT_CLOSE_RE: Final[re.Pattern[str]] = re.compile(r"<\s*/\s*prompt\s*>", re.IGNORECASE)
-# The fallbacks, most recent boundary first: everything after the draft is the
-# corrected message, everything after the analysis is at worst draft + message.
-_CLOSE_FALLBACKS: Final[tuple[re.Pattern[str], ...]] = (
- re.compile(r"<\s*/\s*draft\s*>", re.IGNORECASE),
- re.compile(r"<\s*/\s*analysis\s*>", re.IGNORECASE),
-)
-# Any leftover tag of ours the model echoed inside the message it wrote.
-_OUR_TAGS_RE: Final[re.Pattern[str]] = re.compile(
- r"<\s*/?\s*(?:analysis|draft|prompt)\s*>", re.IGNORECASE
-)
-
-# A courtesy sign-off. v3 guaranteed one in code; v4 removes it, and this cuts
-# the one a model adds on its own — the message ends on its last piece of
-# substance, because the reader is a coding agent that gains nothing from
-# being thanked.
-#
-# It comes in two shapes and both have been measured live on 2026-08-27: a
-# line of its own ("...\n\nDanke!") and a sentence tacked onto the end of the
-# last paragraph ("...lasse ihn unverändert. Danke dir."). Same vocabulary,
-# two anchors — the second one needs a sentence boundary in front of it, which
-# also keeps a message that IS a thank-you from being erased.
+_OUR_TAGS_RE: Final[re.Pattern[str]] = re.compile(r"<\s*/?\s*prompt\s*>", re.IGNORECASE)
+
+# A courtesy sign-off, in the two shapes measured live on 2026-08-27: a line
+# of its own ("...\n\nDanke!") and a sentence tacked onto the last paragraph
+# ("...lasse ihn unverändert. Danke dir."). Same vocabulary, two anchors — the
+# second needs a sentence boundary in front of it, which also keeps a message
+# that IS a thank-you from being erased. The reader is a model; a courtesy
+# line is noise it has to step over.
_SIGN_OFF_WORDS: Final[str] = (
r"(?:thanks?|thank\s+you|dank(?:e|esch[öo]n)?|gracias|merci|grazie|obrigad[oa]|"
r"bedankt|tak|tack|takk|kiitos|dzi[eę]kuj[eę]|d[ěe]kuji|спасибо|ありがとう|谢谢|"
@@ -197,285 +149,134 @@ _SIGN_OFF_SENTENCE_RE: Final[re.Pattern[str]] = re.compile(
re.IGNORECASE,
)
-# The composer's two shared rules plus what a transcript-only, latency-bound
-# pass needs on top. No skeleton for the message: the answer is prose, and a
-# model handed a skeleton reproduces it. The ANALYSIS does get a skeleton,
-# for the opposite reason — it exists to be worked through, item by item.
-_SYSTEM_PROMPT: Final[str] = f"""\
-You turn a spoken, dictated instruction into the message a person would type \
-to an AI coding agent. The user will paste what you write into that agent \
-themselves, so it has to read like a well-written request from a colleague: \
-complete, calm, and no longer than it needs to be.
-
-ANSWER IN THREE BLOCKS, IN THIS ORDER, AND NEVER SKIP ONE.
-
-<analysis>
-...your working pass over the transcript, worked through item by item...
-</analysis>
-<draft>
-...your first version of the message...
-</draft>
-<prompt>
-...the message again, corrected by the read-back, and nothing else...
-</prompt>
-
-PHASE 1 - THE ANALYSIS. Work through all seven points below in writing before \
-you compose a single sentence of the message. This is not a summary and it is \
-not for the user; nobody will read it. It exists so that you have actually \
-been through the transcript by the time you write. Take the time it needs - a \
-careful pass here is the whole difference between a message that carries what \
-the user said and one that carries your impression of it.
-
-1. LANGUAGE. Name the language the transcript is in, and quote the four or \
-five words that told you. THE MESSAGE IS WRITTEN IN THAT LANGUAGE, whatever \
-language these instructions or the examples below happen to be in. A German \
-transcript gets a German message, a Spanish one a Spanish message. Note also \
-which form of address the user used, and whether that language distinguishes \
-a familiar from a formal "you".
-2. TASKS. Number every separate thing the user asked for, in the order \
-spoken. People dictate two, three, five small tasks in one breath, and the \
-small one is dropped far more often than the big one. Write the count.
-3. LITERALS. List every file name, folder, path, symbol, function, class, \
-setting, product name, error message, quoted string, number, version and \
-proper name the user said - exactly as they said it. Each of these must \
-appear in the message, spelled the same way.
-4. THE SITUATION. What does the user see, what did they expect instead, and \
-where does it happen? Quote the transcript verbatim for each of those, in the \
-transcript's own language. This is the most valuable thing a transcript holds \
-and the first thing a hasty writer throws away.
-5. LIMITS. Every restriction, preference, exclusion or bound they stated, each \
-one quoted verbatim: "only", "never", "not the live app", "keep the wording", \
-"for now", a deadline, a scope they drew.
-6. WORDING TO KEEP. Quote the phrases the user chose that carry meaning and \
-must survive into the message unchanged - a term of art, a name they use for \
-something, a distinction they drew, a word they repeated, a hedge like "I \
-think" that must not harden into a finding. Beside each, name what would be \
-lost if you replaced it with a synonym.
-7. NOT SAID. What is missing, ambiguous, or a pointer you cannot resolve \
-("that one", "the second option"). These are left OUT of the message. Never \
-guess a file, a cause or a mechanism to fill a gap.
-
-PHASE 2 - THE DRAFT. Write the message against the analysis, in the \
-``<draft>`` block. This is a first version, not the answer.
-
-PHASE 3 - THE READ-BACK. Go through the draft once against the seven \
-questions below and write the corrected message into the ``<prompt>`` block. \
-When the draft was already right, the two blocks are simply the same text - \
-that is a fine outcome and not a reason to change anything for the sake of \
-it. Do NOT write out what you found; the corrections go into the message, not \
-next to it.
-
-a. Is it in the language from point 1?
-b. Is every task from point 2 there, none merged and none dropped?
-c. Is every literal from point 3 there, spelled the way the user said it?
-d. Does any sentence state something the user did not say? A cause they only \
-suspected, a fix they never named, a "so that it works everywhere again" \
-nobody asked for. Cut it - a gap the transcript leaves is left open.
-e. Did you replace a word of theirs from point 6 with one of your own? Put \
-theirs back.
-f. Does any sentence say again what the sentence before it already said, in \
-other words? One task must not appear twice - once as a description of the \
-problem and once as an instruction. Keep the clearer of the two and delete \
-the other outright.
-g. Does it end on the last piece of substance? Cut a closing line of thanks, \
-a "Danke dir" tacked onto the last sentence, a sign-off, an offer to help \
-further - even when the user said it themselves at the end of the dictation.
-
-THE USER'S OWN WORDS ARE THE DEFAULT; REWRITING IS THE EXCEPTION. You are \
-cleaning up a transcript, not authoring a document. Change a word only when \
-there is a reason: a filler sound, a false start, a self-correction (keep the \
-corrected version), a repetition the speaker did not mean, or a broken \
-sentence a reader would stumble over. Every other word the user chose stays \
-as they chose it - including the small ones, which is where a rewrite does \
-its quiet damage: "immer" is not "regelmäßig", "kaputt" is not "fehlerhaft", \
-"I think it's in" is not "the cause is in", "should" is not "must", "some" is \
-not "several". A synonym you find more elegant is a change in meaning you \
-cannot verify. When a sentence already reads well, it goes in as it stands.
-
-{GOAL_NOT_IMPLEMENTATION_RULE}
-
-The transcript is ALL you get, and your message is ALL the agent gets. You \
-see no repository, no files, no earlier conversation. Everything must come \
-from the transcript: a file, symbol, error message, number or name the user \
-said goes in exactly as spoken; one they did not say does not exist. A \
-pointer you cannot resolve is left out, not forwarded.
-
-WHAT THE MESSAGE CONTAINS, as plain paragraphs in this order, with no labels \
-in front of them. First the situation, when the user described one: what they \
-see, what they expected instead, where it shows up - with every concrete \
-detail of it intact. Then what should be true afterwards, the goal, in one or \
-two sentences. Then every limit, preference or exclusion the user stated. A \
-part the transcript gives you nothing for is skipped, never filled in.
-
-NOTHING AFTER THE LAST PIECE OF SUBSTANCE. The message ends on the last thing \
-the user actually asked for. No closing line of thanks, no "best regards", no \
-sign-off of any kind, no summary sentence, no offer to clarify. The reader is \
-a coding agent; a courtesy line is noise it has to step over.
-
-FIX WHAT EXISTS. When the user says a thing exists and is wrong ("the \
-indicators don't work", "the title is missing on some chats"), the request is \
-to repair that thing - never turn it into "implement" or "create" something \
-new. A second one built next to the broken one is the outcome to avoid.
-
-SEVERAL TASKS AT ONCE. Every task from point 1 of the analysis survives, in \
-the order spoken, each as its own sentence or short paragraph. Never merge \
-two, never drop the small one because the big one seemed to be the point, \
-never summarise a list into "and a few other things".
-
-SAY EACH THING ONCE. A requirement stated twice in different words is \
-padding, not emphasis: no closing sentence that restates the goal, no "make \
-sure that" clause that repeats the sentence before it, no summary. A sentence \
-that adds no fact the message does not already have is left out.
-
-PLAIN TEXT, SAME LANGUAGE. No markdown: no headings, no "##", no bullet \
-marks, no bold, no code fences, no labels like "Task:" or "Context:". Write in \
-the language you named in point 1 - these instructions are in English and that \
-means nothing about the message; if the transcript mixes languages, keep the \
-mix. Names, identifiers, paths and quoted strings stay exactly as spoken. Use \
-the ordinary hyphen-minus and ordinary spaces: no typographic hyphens, no \
-non-breaking spaces, no two spaces at the end of a line.
-
-SOUND LIKE THE PERSON WHO SPOKE, writing to a colleague - not like a ticket \
-and not like a document:
-- Short, direct sentences. Say the thing, then stop.
-- Courteous where the speaker was courteous: their "please", their "I would \
-like", kept where they said it and not added where they did not.
-- Address the agent the way the user did. In a language that distinguishes a \
-familiar from a formal "you", keep the user's form and never switch to the \
-formal one on your own; a transcript that shows neither gets the familiar one.
-- Everyday words. No "utilize", "leverage", "ensure", "make sure", "robust", \
-"seamless", "comprehensive", "delve" - and not their equivalents in the \
-transcript's language either.
-- No sets of three for rhythm, no "not only ... but also", no dash-heavy \
-asides.
-
-Drop filler sounds, false starts and self-corrections, and any clause \
-addressing the assistant or the agent by name. State what "done" looks like \
-only when the user said it. The ``<prompt>`` block holds ONLY the message: no \
-preamble, no quotes, no comment of your own.
-
-{FORBIDDEN_SUBJECTS_RULE}
-
-Two worked examples, one per language, because THE MESSAGE FOLLOWS THE \
-TRANSCRIPT AND NOT THE EXAMPLE. Measured live 2026-08-27: with only the \
-English pair shown, a German dictation came back as an English message. The \
-analyses are shown short here; yours is as long as the transcript needs.
-
-Transcript: "okay so um the login page is broken again when you type a wrong \
-password it just shows a blank screen instead of the error message i think \
-it's in the auth handler file can you have a look and fix it so the message \
-shows up like it used to and also rename the save button to submit"
-Answer:
-<analysis>
-1. LANGUAGE: English ("okay so um", "can you have a look"). The message is \
-written in English. Informal, second person.
-2. TASKS (2): (a) fix the blank screen on a wrong password so the error \
-message shows again; (b) rename the save button to submit.
-3. LITERALS: "login page", "auth handler file", "save", "submit", "wrong \
-password", "blank screen", "error message".
-4. SITUATION: "it just shows a blank screen instead of the error message", on \
-a wrong password. "broken again" and "like it used to" say it worked before.
-5. LIMITS: none stated.
-6. WORDING TO KEEP: "broken again" (not "is failing" - it has failed before); \
-"I think it's in" (a guess, not a finding - "the cause is in" would send the \
-agent off certain about something the user only suspects); "like it used to" \
-(names the old behaviour as the target).
-7. NOT SAID: which file exactly, what changed, no repro steps beyond the \
-wrong password.
-</analysis>
-<draft>
-The login page is failing again: on a wrong password the error message does \
-not appear and the screen stays blank. The cause is in the auth handler file.
-
-Please fix it so the error message is shown again and users get proper \
-feedback on a failed login.
-
-Also, please rename the save button to submit.
-</draft>
-<prompt>
-The login page is broken again: when you type a wrong password it just shows \
-a blank screen instead of the error message. I think it's in the auth handler \
-file.
-
-Please have a look and fix it so the error message shows up like it used to.
-
-Also, please rename the save button to submit.
-</prompt>
-
-Transcript: "ähm also die Indikatoren funktionieren nicht mehr richtig ich \
-möchte dass man sieht ob die Session gerade arbeitet oder nicht weil es ist \
-zum Beispiel so dass angezeigt wird sie ist fertig obwohl sie noch arbeitet \
-oder andersrum und live aktualisieren tun die sich auch nicht"
+# The instruction. Short on purpose — see the module docstring and the version
+# note above. The example is the maintainer's own reference run: his dictated
+# transcript, and the prompt Gemini wrote for it when asked for nothing but a
+# prompt. It is the specification; everything above it is context for reading
+# it.
+_SYSTEM_PROMPT: Final[str] = """\
+A user is dictating to Jarvis Voice. They want every transcript of theirs \
+turned automatically into a finished, professional prompt for an AI model - \
+that is the whole feature, and you are the part of it that writes.
+
+Below is one transcript. Write the prompt it is asking for.
+
+Take what they said as the brief: their goal, the context and constraints \
+they stated, every separate task they mentioned. Everything comes from the \
+transcript - a file, name, number, quoted string or error message they said \
+goes in exactly as spoken, one they did not say does not exist, and a gap \
+they left is left open rather than guessed at. Drop the filler sounds, the \
+false starts and the self-corrections; keep the corrected version.
+
+WRITE IT IN THE LANGUAGE THE USER SPOKE. These instructions are in English \
+and that says nothing about your answer: a German transcript gets a German \
+prompt, a Spanish one a Spanish prompt, and that includes the headings and \
+the section names, not just the sentences between them. A transcript that \
+mixes languages keeps the mix.
+
+Structure it the way a good prompt is structured and use whatever serves that \
+- a role and system context, the task and the outcome it has to reach, the \
+context and guardrails, the output format, headings, lists, markdown, \
+sections. Be concrete rather than adjectival: "a markdown table with the \
+columns X, Y, Z", never "make it good".
+
+Put the prompt, and nothing else, between <prompt> and </prompt>. No \
+introduction of your own in front of it, no comment after it, and no closing \
+line of thanks - it ends on its last piece of substance.
+
+Here is one run of this job, from a dictated transcript to the prompt written \
+for it.
+
+Transcript: "Hallo, kannst du mir bitte ein Prompt schreiben? Und zwar möchte \
+ich, dass du es hier verbesserst. Ich möchte, dass du bitte für mich einen \
+Deep Dive machst und mir dabei hilfst, den Modus, welchen wir eingebaut haben \
+in Jarvis Voice, diesen Auto-Prompt-Modus zu verbessern, dass die Prompts \
+besser geschrieben werden, in einem professionelleren Stil. Ich möchte, dass. \
+Sich das Modell, und zwar das Tool-Modell, welches damit verbunden wird, mehr \
+darüber nachdenkt und den Prompt nicht zu schnell schreibt. Mit einer \
+Nachdenkzeit von 5 bis 7 Sekunden, dass wirklich ein guter Prompt geschrieben \
+wird, aber auch nicht zu lange nachgedacht wird. Es muss halt eine gute \
+Mischung darin entstehen. Diese Prompt sollen in einem guten und \
+professionellen Modell professionellen Stil geschrieben sein."
Answer:
-<analysis>
-1. LANGUAGE: German ("ähm also", "ich möchte dass", "oder andersrum"). The \
-message is written in German. "du"-Form is not shown either way, so the \
-familiar form is used.
-2. TASKS (1): repair the session indicators.
-3. LITERALS: "Indikatoren", "Session".
-4. SITUATION: "angezeigt wird sie ist fertig obwohl sie noch arbeitet oder \
-andersrum", and "live aktualisieren tun die sich auch nicht".
-5. LIMITS: none stated.
-6. WORDING TO KEEP: "funktionieren nicht mehr richtig" - they EXIST and are \
-broken, so this is a repair and never "implementiere Indikatoren"; "live" is \
-the user's word for the update behaviour.
-7. NOT SAID: since when, which screen, no file named.
-</analysis>
-<draft>
-Die Statusanzeigen der Sessions sind fehlerhaft: Eine laufende Session wird \
-als abgeschlossen dargestellt und umgekehrt, und eine Aktualisierung in \
-Echtzeit findet nicht statt.
-
-Bitte implementiere eine zuverlässige Anzeige des Session-Status, die sich \
-automatisch aktualisiert, damit die Übersicht wieder verwendbar ist.
-</draft>
<prompt>
-Die Indikatoren, die anzeigen, ob eine Session gerade arbeitet, funktionieren \
-nicht mehr richtig: Eine Session wird als fertig angezeigt, obwohl sie noch \
-arbeitet, und andersrum. Live aktualisieren sie sich auch nicht.
-
-Bitte bring die Indikatoren wieder in Ordnung, sodass man sieht, ob eine \
-Session gerade arbeitet, und sodass sie sich live aktualisieren.
+Du bist der spezialisierte Prompt-Engineering-Core für Jarvis Voice. Deine \
+Aufgabe ist es, rohe, unpräzise oder gesprochene Nutzeranweisungen in \
+hochgradig strukturierte, professionelle und präzise Prompts zu \
+transformieren.
+
+Bevor du die finale Antwort ausgibst, MUSST du einen strukturierten \
+Denkprozess (Reasoning Step) durchlaufen, um den Prompt systematisch zu \
+optimieren.
+
+### ARBEITSABLAUF (2-Phasen-Prozess)
+
+Führe bei jeder Anfrage ausnahmslos folgende zwei Schritte aus:
+
+#### PHASE 1: <thinking> (Tiefenanalyse & Konstruktion)
+Nutze diese Phase, um den Kontext systematisch zu durchdenken:
+1. **Intenterkennung:** Was ist das eigentliche Kernziel des Nutzers hinter \
+der gesprochenen Eingabe?
+2. **Kontext- & Rollenbestimmung:** Welche Rolle/Expertise passt am besten zu \
+diesem Ziel?
+3. **Strukturelle Mängel & Lücken:** Welche Parameter fehlen (Format, \
+Tonalität, Einschränkungen, Zielgruppe)?
+4. **Optimierungsstrategie:** Wie muss der Prompt formuliert werden, um \
+Fehlinterpretationen zu minimieren und maximale Detailtiefe zu sichern?
+
+#### PHASE 2: <optimized_prompt> (Finale Ausgabe)
+Gib ausschließlich den fertigen, sofort einsatzbereiten Prompt aus. Dieser \
+muss folgenden Aufbau haben:
+- **Rolle / Systemkontext:** Definition der Persona und des Wissensbereichs.
+- **Aufgabe & Zielsetzung:** Glasklare Beschreibung des Outputs.
+- **Kontext & Richtlinien:** Wichtige Rahmenbedingungen, Einschränkungen und \
+Do's/Don'ts.
+- **Formatierungs- & Strukturvorgaben:** Exakte Vorgabe von \
+Markdown-Elementen, Tabellen oder Codeblöcken.
+- **Input-Variable / Platzhalter:** Wo die tatsächlichen Nutzerdaten \
+eingefügt werden.
+
+### QUALITÄTSKRITERIEN FÜR DEN FINALEN PROMPT
+
+* **Präzision statt Floskeln:** Keine vagen Adjektive ("mache es gut"), \
+sondern konkrete Handlungsanweisungen ("nutze eine Markdown-Tabelle mit \
+Spalten X, Y, Z").
+* **Professioneller Tonfall:** Formuliere den Prompt in einem klaren, \
+autoritativen und direktiven Ton.
+* **Kein Meta-Gerede:** Schreibe in Phase 2 keine Einleitung wie "Hier ist \
+dein Prompt" - starte direkt mit dem Prompt-Inhalt.
</prompt>\
"""
-# What a plain-text answer must not contain. Headings and fences are the v1
-# failure; bold and bullet marks are the shape a model slides back into when
-# it is told "structure" without "prose". Checked against the MESSAGE only —
-# the analysis is a numbered list by design and never reaches this.
-_MARKDOWN_RE: Final[re.Pattern[str]] = re.compile(r"(?m)^\s*(#{1,6}\s|```|[-*]\s|\d+[.)]\s)|\*\*")
-
# Typographic debris a fast model writes into identifiers and paths. Measured
# live 2026-08-27: gpt-oss on the fast chain joined "Jarvis‑Bar" and
-# "Self‑Hosted" with U+2011 (non-breaking hyphen), which a grep for "Self-Hosted"
-# in the receiving agent never matches. The whole hyphen block maps to the
-# hyphen-minus when it sits inside a word; a spaced dash stays a spaced dash
-# so an aside the model wrote as " – " is not turned into " - " by force.
+# "Self‑Hosted" with U+2011 (non-breaking hyphen), which a grep for
+# "Self-Hosted" in the receiving model never matches. The whole hyphen block
+# maps to the hyphen-minus when it sits inside a word; a spaced dash stays a
+# spaced dash so an aside written as " – " is not turned into " - " by force.
_TIGHT_HYPHEN_RE: Final[re.Pattern[str]] = re.compile(r"(?<=\w)[‐‑‒–—](?=\w)")
_LOOSE_HYPHEN_RE: Final[re.Pattern[str]] = re.compile(r"[‐‑]")
-_SPECIAL_SPACE_RE: Final[re.Pattern[str]] = re.compile(r"[    ​]")
+_SPECIAL_SPACE_RE: Final[re.Pattern[str]] = re.compile(r"[ ​]")
_TRAILING_WS_RE: Final[re.Pattern[str]] = re.compile(r"[ \t]+$", re.MULTILINE)
_BLANK_RUN_RE: Final[re.Pattern[str]] = re.compile(r"\n{3,}")
# --- Fidelity guards -------------------------------------------------------
#
-# The polish pass measures how far the words moved. Here they are allowed to
-# move, so what is measured instead is what got LOST. Two things, both
-# deterministic, both cheap, both fail-open:
+# The polish pass measures how far the words moved. Here they are supposed to
+# move — a prompt is not a tidied transcript — so what is measured instead is
+# what got LOST. Two things, both deterministic, both cheap, both fail-open:
#
-# * a literal the user spoke that the message does not carry, and
-# * a message so much shorter than the transcript that context was thinned
-# rather than tightened.
+# * a literal the user spoke that the prompt does not carry, and
+# * a prompt so much shorter than the transcript that context was thinned.
#
-# Neither judges style. A rewrite that keeps every literal and most of the
-# substance passes, however differently it reads — that judgement is the
-# model's, and the prompt above is where it is made.
+# Neither has an opinion about shape or style. That is the model's judgement,
+# and the instruction above is where it is made.
# What counts as a literal worth carrying: an identifier or path
# (``auth_handler``, ``src/app.ts``, ``JarvisBar``), a version or number of
# two digits or more, and anything the user put in quotes. Deliberately NOT
-# ordinary words: the message is allowed to rephrase prose, and a guard over
-# every noun would reject every honest rewrite.
+# ordinary words: the prompt is a rewrite, and a guard over every noun would
+# reject every honest one.
_IDENTIFIER_RE: Final[re.Pattern[str]] = re.compile(
r"""
\b(?:
@@ -490,25 +291,24 @@ _IDENTIFIER_RE: Final[re.Pattern[str]] = re.compile(
_NUMBER_RE: Final[re.Pattern[str]] = re.compile(r"\b\d{2,}(?:[.,]\d+)*\b")
# Double quotes only. A lone ``'`` is an apostrophe far more often than a
# quotation mark in a transcript ("it's", "don't"), and treating one as an
-# opening quote turns the rest of the sentence into a "literal" that the
-# message is then required to reproduce word for word.
+# opening quote turns the rest of the sentence into a "literal" the prompt is
+# then required to reproduce word for word.
_QUOTED_RE: Final[re.Pattern[str]] = re.compile("[\"“„«]([^\"“”„«»\n]{2,60})[\"”»]")
-#: How many of the transcript's literals may go missing before the message is
+#: How many of the transcript's literals may go missing before the prompt is
#: rejected. Not zero: a recognizer writes the same spoken name two ways in
#: one breath ("JarvisBar", "Jarvis Bar"), and rejecting on one of those costs
-#: a good message. One is a slip; a quarter of them is a writer that stopped
+#: a good prompt. One is a slip; a quarter of them is a writer that stopped
#: reading.
_MAX_LOST_LITERALS: Final[int] = 1
_LOST_LITERAL_SHARE: Final[float] = 0.25
-#: How far the message may shrink against the transcript before it counts as
-#: thinned rather than tightened, and the shortest transcript this is measured
-#: on at all. A dictation is 25-40 % filler, so a healthy message lands around
-#: 60-80 % of the spoken word count; under 40 % something the user said is
-#: simply not in there. Short transcripts are exempt — "fix the typo on the
-#: login page" is a complete request at eight words and its message is allowed
-#: to be shorter still.
+#: How far the prompt may shrink against the transcript before it counts as
+#: thinned, and the shortest transcript this is measured on at all. A written
+#: prompt is normally LONGER than what was dictated, so this only ever fires
+#: on a writer that summarised instead of writing. Short transcripts are
+#: exempt: "fix the typo on the login page" is a complete brief at eight
+#: words and its prompt may be shorter still.
_MIN_LENGTH_SHARE: Final[float] = 0.40
_MIN_MEASURED_WORDS: Final[int] = 30
@@ -532,61 +332,35 @@ def build_prompt_mode_prompt(protected_terms: Sequence[str] = ()) -> str:
def extract_prompt_block(answer: str) -> str:
- """The message out of a three-block answer, tolerant of a ragged one.
-
- In order of preference: the content of the LAST ``<prompt>`` (closing tag
- optional, because a model that ran out of budget still wrote a usable
- message up to that point — the truncation guard is what decides whether it
- is usable); otherwise everything after ``</draft>`` and then everything
- after ``</analysis>``, which is the same message with an opening tag
- forgotten; otherwise the whole answer, on the assumption that the model
- ignored the block instruction and wrote the message directly. That last
- case then faces the same guards as before, so a model that answers with
- its worksheet is caught by the markdown guard rather than handing the user
- a numbered list.
-
- Whatever comes out is stripped of any of our own tags the model echoed
- inside it.
+ """The prompt out of the answer, tolerant of a ragged one.
+
+ The LAST opening tag wins and the closing one is optional: a model that
+ names the tag while introducing itself would otherwise hand over its
+ introduction, and one that ran out of budget still wrote a usable prompt
+ up to where it stopped — the truncation guard is what decides whether it
+ is usable. An answer with no tag at all is taken whole, on the assumption
+ that the model simply wrote the prompt directly, which is a fine thing to
+ have done.
+
+ Whatever comes out is stripped of any of our own tags echoed inside it.
"""
body = str(answer or "").strip()
if not body:
return ""
opens = list(_PROMPT_OPEN_RE.finditer(body))
- if opens:
- # The LAST opening tag, not the last complete block: a model that
- # names the tag while thinking ("...then I fill the <prompt> block...")
- # opens one inside its analysis and never closes it, and a match that
- # started there would swallow the draft along with the message.
- rest = body[opens[-1].end() :]
- close = _PROMPT_CLOSE_RE.search(rest)
- return _OUR_TAGS_RE.sub("", rest[: close.start()] if close else rest).strip()
- for pattern in _CLOSE_FALLBACKS:
- closes = list(pattern.finditer(body))
- if closes:
- return _OUR_TAGS_RE.sub("", body[closes[-1].end() :]).strip()
- return _OUR_TAGS_RE.sub("", body).strip()
-
-
-def analysis_word_count(answer: str) -> int:
- """How many words the model spent on its working pass.
-
- Not a guard — nothing is rejected for a thin analysis, because a short
- transcript deserves a short one. It is logged, so "the writer answered in
- 400 ms again" is a question the log can answer without a live capture.
- """
- match = _ANALYSIS_BLOCK_RE.search(str(answer or ""))
- if not match:
- return 0
- return len(_WORD_RE.findall(match.group(1)))
+ if not opens:
+ return _OUR_TAGS_RE.sub("", body).strip()
+ rest = body[opens[-1].end() :]
+ close = _PROMPT_CLOSE_RE.search(rest)
+ return _OUR_TAGS_RE.sub("", rest[: close.start()] if close else rest).strip()
def normalize_prompt_text(text: str) -> str:
- """Undo the typographic debris a fast model leaves in a plain-text prompt.
+ """Undo the typographic debris a fast model leaves behind.
Deterministic and lossless in meaning: a non-breaking hyphen inside a word
becomes the hyphen-minus the user's keyboard produces, special spaces
- become spaces, trailing spaces on a line go (two of them are a markdown
- line break, which the answer must not carry), and runs of blank lines
+ become spaces, trailing spaces on a line go, and runs of blank lines
collapse to one paragraph break. Runs BEFORE the guards, so a protected
spelling the model wrote with a U+2011 still counts as present.
"""
@@ -614,16 +388,15 @@ def ends_with_sign_off(text: str) -> bool:
def strip_closing_sign_off(text: str) -> str:
"""*text* with a trailing courtesy line or sentence removed.
- The prompt asks for a message that ends on its substance; this is the
- guarantee, the way ``ensure_closing_thanks`` was the guarantee of the
- opposite in v3. Loops, because a model that writes "Danke!" under "Viele
- Grüße" has written two, and because cutting the last line can expose
- another underneath it. Never strips the whole message: a line of thanks
- that is all there is stays, and a sentence is only cut when a finished
- sentence stands in front of it.
+ The instruction asks for a prompt that ends on its substance; this is the
+ guarantee. Loops, because a model that writes "Danke!" under "Viele Grüße"
+ has written two, and because cutting the last line can expose another
+ underneath it. Never strips the whole thing: a line of thanks that is all
+ there is stays, and a sentence is only cut when a finished sentence stands
+ in front of it.
Runs AFTER the truncation guard, for the reason that guard exists — a
- message that stopped mid-sentence must be caught as damage, not tidied.
+ prompt that stopped mid-sentence must be caught as damage, not tidied.
"""
body = str(text or "").strip()
while True:
@@ -642,7 +415,7 @@ def strip_closing_sign_off(text: str) -> str:
def transcript_literals(text: str) -> list[str]:
- """The literals in *text* a faithful message has to carry.
+ """The literals in *text* a faithful prompt has to carry.
Identifiers and paths, numbers of two digits or more, and quoted spans.
Case is preserved in what comes back (the caller folds it) so a log line
@@ -662,18 +435,18 @@ def transcript_literals(text: str) -> list[str]:
def lost_literals(raw: str, prompt: str) -> list[str]:
- """Which of the transcript's literals the message does not carry."""
+ """Which of the transcript's literals the prompt does not carry."""
target = str(prompt or "").casefold()
return [token for token in transcript_literals(raw) if token.casefold() not in target]
def looks_thinned(raw: str, prompt: str) -> bool:
- """True when the message is too short to still hold what was dictated.
+ """True when the prompt is too short to still hold what was dictated.
A word-count proxy, and only over transcripts long enough for the ratio to
- mean anything. It catches the failure the maintainer reported — a message
- that reads well and quietly leaves out half of what was said — without
- having any opinion about wording.
+ mean anything. A written prompt is normally longer than the dictation, so
+ this fires on a writer that summarised rather than wrote — without having
+ any opinion about wording.
"""
spoken = len(_WORD_RE.findall(str(raw or "")))
if spoken < _MIN_MEASURED_WORDS:
@@ -685,31 +458,26 @@ def looks_thinned(raw: str, prompt: str) -> bool:
def prompt_guard_reason(raw: str, prompt: str, *, protected: Sequence[str] = ()) -> str:
"""Why *prompt* must not be delivered, or ``""`` when it may.
- Structural and factual, never stylistic. The drift guards of the polish
- pass measure how far the words moved, and here they are ALLOWED to move;
- what can still go wrong is the shape of the answer and its fidelity to
- what was said:
+ Damage and fidelity, never shape. A prompt is allowed to be markdown, to
+ carry headings, sections and a role line — v3 rejected exactly that as
+ ``markdown``, which was this feature refusing its own purpose. What is
+ still worth catching:
* ``empty`` — nothing came back worth pasting.
- * ``markdown`` — a heading, a fence, bold or a list mark. The answer is
- pasted into a chat box as a message; markdown there is the v1 defect,
- and it is also what a leaked analysis looks like.
* ``truncated`` — stopped mid-sentence. Reads as complete, is not.
* ``lost_protected_term`` — a spelling the user protected was in the
transcript and is not in the prompt. The dictionary exists because the
recognizer gets these wrong; a writer that drops one has undone that.
* ``dropped_detail`` — file names, identifiers, numbers or quoted strings
- the user spoke are missing from the message. The agent is sent looking
- for something the user had already named.
- * ``dropped_context`` — the message is under 40 % of the spoken word
- count. A dictation is filler-heavy, but not that filler-heavy: what is
- gone is context, not padding.
+ the user spoke are missing. The model is sent looking for something the
+ user had already named.
+ * ``dropped_context`` — under 40 % of the spoken word count. A written
+ prompt is normally longer than the dictation; this short means the
+ writer summarised instead.
"""
body = (prompt or "").strip()
if not body:
return "empty"
- if _MARKDOWN_RE.search(body):
- return "markdown"
if looks_truncated(body):
return "truncated"
source = (raw or "").casefold()
@@ -751,7 +519,7 @@ async def compose_prompt(
timeout_s: float | None = None,
language: str = "",
) -> PolishOutcome:
- """Turn *raw* into an agent prompt. Never raises, never loses text.
+ """Turn *raw* into the prompt it is asking for. Never raises, never loses text.
Returns a :class:`~jarvis.dictation.polish.PolishOutcome` so the delivery
path, the history row and the settings screen read Prompt Mode through the
@@ -760,16 +528,15 @@ async def compose_prompt(
status — the caller then falls through to whatever it would have done
without this feature, which is the polish pass.
- ``language`` is the resolved dictation language. Since v4 the message
- carries no generated closing line, so nothing here has to be written in
- it; the parameter stays because every caller passes it and because the
+ ``language`` is the resolved dictation language. The prompt is written in
+ the transcript's own language by the instruction, so nothing here depends
+ on it; the parameter stays because every caller passes it and because the
language belongs in the log line when a delivery has to be explained.
The model is the polish pass's own chain (``[dictation].polish_provider``
and its ``auto`` order), asked for the family's stronger fast model — the
- one the translate pass uses — because turning speech into a brief asks
- more of a model than punctuating it, and that model still answers inside
- the ceiling with an analysis in front of it.
+ one the translate pass uses — because writing a prompt asks more of a
+ model than punctuating a sentence.
"""
started = time.perf_counter()
source = str(raw or "")
@@ -848,30 +615,23 @@ async def compose_prompt(
await breaker.record_success()
- # How long the writer spent thinking, in the only unit that measures
- # it: words it wrote before it started answering. A run that reports 0
- # here is a model that skipped the analysis, which is the v3 behaviour
- # and the thing to watch for after a provider change.
- thought_words = analysis_word_count(answer)
prompt = normalize_prompt_text(extract_prompt_block(answer))
reason = prompt_guard_reason(source, prompt, protected=protected_terms)
if reason:
log.info(
- "dictation prompt mode answer from %r rejected (%s, %d analysis words); "
- "delivering the transcript to the ordinary passes.",
+ "dictation prompt mode answer from %r rejected (%s); delivering the "
+ "transcript to the ordinary passes.",
attempt.provider,
reason,
- thought_words,
)
return _result(
"rejected_drift", provider=attempt.provider, model=attempt.model, reason=reason
)
log.debug(
- "dictation prompt mode composed a message from %r after %d analysis words "
- "(language %r).",
+ "dictation prompt mode wrote a %d-word prompt on %r (language %r).",
+ len(_WORD_RE.findall(prompt)),
attempt.provider,
- thought_words,
language or "auto",
)
return _result(
@@ -912,7 +672,7 @@ async def _call_chain(
max_output_tokens=_MAX_OUTPUT_TOKENS,
temperature=_TEMPERATURE,
# The family's stronger fast model, exactly as the translate pass asks
- # for it: a brief is a rewrite, not a repunctuation.
+ # for it: writing a prompt is a rewrite, not a repunctuation.
translating=True,
)
@@ -920,7 +680,6 @@ async def _call_chain(
__all__ = [
"PROMPT_MODE_PROMPT_VERSION",
"STATUS_PROMPTED",
- "analysis_word_count",
"build_prompt_mode_prompt",
"compose_prompt",
"ends_with_sign_off",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 97ac44e048..0b2a7116c6 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -422,8 +422,8 @@
},
"prompt_mode": {
"title": "Prompt-Modus",
- "description": "Sag in deinen Worten und in jeder Sprache, was erledigt werden soll. Im Feld landet ein fertiger Prompt für einen KI-Coding-Agenten, so formuliert, wie du es sagen würdest: das Ziel, das du beschrieben hast, der Kontext und die Grenzen, die du genannt hast, und jede Aufgabe, die du erwähnt hast — nichts erfunden, nichts weggelassen, und deine eigene Wortwahl bleibt überall dort stehen, wo sie die Sache schon gesagt hat.",
- "sends_text": "Dein Transkript geht an dasselbe schnelle Modell wie das Aufräumen der Formulierung oben. Dieses Modell arbeitet zuerst schriftlich durch, was du gesagt hast — jede Aufgabe, jeden Datei- und Eigennamen, die Situation, die du beschrieben hast, die Grenzen, die du gezogen hast — und schreibt erst danach den Prompt. Deshalb dauert das hier ein paar Sekunden statt eines Augenblicks, und genau das kaufst du dir mit der Wartezeit. Zurück kommt Klartext in der Sprache, in der du gesprochen hast; dein Rohtext bleibt immer in deinem Verlauf.",
+ "description": "Sag in deinen Worten und in jeder Sprache, was erledigt werden soll. Im Feld landet der fertige Prompt: dein Ziel, der Kontext und die Grenzen, die du genannt hast, und jede Aufgabe, die du erwähnt hast — ausformuliert, wie ein guter Prompt aufgebaut ist: eine Rolle, die Aufgabe, die Leitplanken, das Ausgabeformat. Nichts erfunden, nichts weggelassen, und in der Sprache, in der du gesprochen hast.",
+ "sends_text": "Dein Transkript geht an dasselbe schnelle Modell wie das Aufräumen der Formulierung oben und kommt als ausformulierter Prompt zurück — meist innerhalb weniger Sekunden. Dein Rohtext bleibt immer in deinem Verlauf.",
"outranks": "Solange das an ist, treten das Aufräumen der Formulierung und die Übersetzung zurück: Der Prompt ist bereits neu strukturiert. Antwortet kein Modell rechtzeitig, kommt dieses Diktat so an, als wäre der Prompt-Modus aus.",
"writer_hint": "Welches Modell schreibt: der Anbieter, der oben unter „Formulierung aufräumen“ gewählt ist."
},
@@ -573,7 +573,7 @@
"composer_hint": "Enter sendet · Shift+Enter für eine neue Zeile",
"model_hint": "Verwendetes Modell — zum Ändern klicken",
"prompt_mode_pill": "Prompt",
- "prompt_mode_on": "Prompt-Modus ist an — jedes Diktat kommt als fertiger Prompt für einen Coding-Agenten an, in deinen eigenen Worten. Das Modell liest dein Transkript erst durch, bevor es antwortet; das dauert ein paar Sekunden. Klicken zum Ausschalten.",
+ "prompt_mode_on": "Prompt-Modus ist an — jedes Diktat kommt als ausformulierter Prompt für ein KI-Modell an, in der Sprache, in der du gesprochen hast. Klicken zum Ausschalten.",
"prompt_mode_off": "Prompt-Modus ist aus — Diktate kommen so an, wie gesprochen. Klicken, damit jedes Diktat zu einem fertigen Prompt für einen Coding-Agenten wird.",
"prompt_mode_failed": "Der Prompt-Modus konnte nicht umgeschaltet werden.",
"theme_to_light": "Zum hellen Modus wechseln",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index e20c3c3ecb..a97a007013 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -422,8 +422,8 @@
},
"prompt_mode": {
"title": "Prompt Mode",
- "description": "Say what you want done, in your own words and in any language. What lands in the field is a finished prompt for an AI coding agent, written the way you would say it: the goal you described, the context and limits you stated, and every task you mentioned — nothing made up, nothing dropped, and your own wording left standing wherever it already said the thing.",
- "sends_text": "Your transcript goes to the same fast model as the wording clean-up above. That model first works through what you said in writing — every task, every file and name, the situation you described, the limits you drew — and only then writes the prompt. That is why this one takes a few seconds instead of an instant, and it is what the extra wait buys. It comes back as plain text in the language you spoke, and your raw text is always kept in your history.",
+ "description": "Say what you want done, in your own words and in any language. What lands in the field is the finished prompt: your goal, the context and limits you stated and every task you mentioned, written up the way a good prompt is written — a role, the task, the guardrails, the output format. Nothing made up, nothing dropped, and in the language you spoke.",
+ "sends_text": "Your transcript goes to the same fast model as the wording clean-up above and comes back as the written-out prompt, usually within a few seconds. Your raw text is always kept in your history.",
"outranks": "While this is on, the wording clean-up and the translation step back: the prompt is already restructured. If no model answers in time, this dictation is delivered as it would be with Prompt Mode off.",
"writer_hint": "Which model writes it: the provider picked under \"Clean up my wording\" above."
},
@@ -573,7 +573,7 @@
"composer_hint": "Enter to send · Shift+Enter for a new line",
"model_hint": "Model in use — click to change it",
"prompt_mode_pill": "Prompt",
- "prompt_mode_on": "Prompt Mode is on — every dictation comes out as a finished prompt for a coding agent, in your own words. The writer reads your transcript through before it answers, so this takes a few seconds. Click to switch it off.",
+ "prompt_mode_on": "Prompt Mode is on — every dictation comes out as a written-out prompt for an AI model, in the language you spoke. Click to switch it off.",
"prompt_mode_off": "Prompt Mode is off — dictations arrive as spoken. Click to turn every dictation into a finished prompt for a coding agent.",
"prompt_mode_failed": "Prompt Mode could not be switched.",
"theme_to_light": "Switch to light mode",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index b34b2a2c94..eb89e6162a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -422,8 +422,8 @@
},
"prompt_mode": {
"title": "Modo prompt",
- "description": "Di con tus palabras y en cualquier idioma qué quieres que se haga. En el campo aparece un prompt terminado para un agente de programación con IA, redactado como tú lo dirías: el objetivo que describiste, el contexto y los límites que mencionaste, y cada tarea que nombraste, sin nada inventado ni omitido, y con tus propias palabras intactas allí donde ya decían la cosa.",
- "sends_text": "Tu transcripción va al mismo modelo rápido que la limpieza de redacción de arriba. Ese modelo repasa primero por escrito lo que dijiste — cada tarea, cada archivo y nombre, la situación que describiste, los límites que pusiste — y solo después escribe el prompt. Por eso este tarda unos segundos en lugar de un instante, y eso es lo que compra la espera. Vuelve como texto sin formato en el idioma en que hablaste; tu texto original siempre se guarda en tu historial.",
+ "description": "Di con tus palabras y en cualquier idioma qué quieres que se haga. En el campo aparece el prompt terminado: tu objetivo, el contexto y los límites que mencionaste y cada tarea que nombraste, redactados como se redacta un buen prompt — un rol, la tarea, las restricciones, el formato de salida. Sin nada inventado ni omitido, y en el idioma en que hablaste.",
+ "sends_text": "Tu transcripción va al mismo modelo rápido que la limpieza de redacción de arriba y vuelve como el prompt ya redactado, normalmente en pocos segundos. Tu texto original siempre se guarda en tu historial.",
"outranks": "Mientras esté activo, la limpieza de redacción y la traducción pasan a segundo plano: el prompt ya viene reestructurado. Si ningún modelo responde a tiempo, este dictado llega como si el modo prompt estuviera apagado.",
"writer_hint": "Qué modelo lo escribe: el proveedor elegido arriba en «Limpiar mi redacción»."
},
@@ -573,7 +573,7 @@
"composer_hint": "Enter envía · Shift+Enter para una nueva línea",
"model_hint": "Modelo en uso — haz clic para cambiarlo",
"prompt_mode_pill": "Prompt",
- "prompt_mode_on": "El modo Prompt está activado: cada dictado llega como un prompt terminado para un agente de código, con tus propias palabras. El modelo lee tu transcripción entera antes de responder, así que tarda unos segundos. Haz clic para desactivarlo.",
+ "prompt_mode_on": "El modo Prompt está activado: cada dictado llega como un prompt ya redactado para un modelo de IA, en el idioma en que hablaste. Haz clic para desactivarlo.",
"prompt_mode_off": "El modo Prompt está desactivado: los dictados llegan tal como se dijeron. Haz clic para convertir cada dictado en un prompt terminado para un agente de código.",
"prompt_mode_failed": "No se pudo cambiar el modo Prompt.",
"theme_to_light": "Cambiar al modo claro",
diff --git a/tests/unit/dictation/test_prompt_mode.py b/tests/unit/dictation/test_prompt_mode.py
index 9ef2317942..08e7b5db0f 100644
--- a/tests/unit/dictation/test_prompt_mode.py
+++ b/tests/unit/dictation/test_prompt_mode.py
@@ -1,29 +1,25 @@
-"""Prompt Mode — a dictation comes out as the prompt a coding agent should get.
-
-Five things are worth pinning, and none of them is "the model writes well":
-
-1. **The doctrine is SHARED, not copied.** The Agentic IDE's composer and this
- pass must ask for the same thing — goal not route, no verification
- ritual, no reasoning echo — so the two rule texts are imported from the
- blueprint and asserted to be the very same strings.
-2. **The writer THINKS before it answers (v4, 2026-08-27).** A model spends
- time by emitting tokens, so the answer is three blocks: a written pass over
- the transcript, a draft, and the message the read-back corrects. Only the
- last one is delivered, and a model that skips the first is the v3 defect
- this revision exists to fix. Measured live the same day: 5.2 s on
- gemini-3.5-flash-lite, which is the bar, against 0.4-0.9 s for v3.
-3. **The maintainer's bar: plain text, the transcript's language, the
- speaker's own words, several tasks dictated at once all surviving, and
- nothing after the last piece of substance.** Each is a rule in the prompt
- or a guard on the answer, asserted here so a later revision cannot quietly
- drop one.
+"""Prompt Mode — a dictation comes out as the prompt the user asked for.
+
+The thing this file mostly exists to prevent is the arc v2-v4 already ran
+once: a real defect gets seen, a rule is added, the rule narrows what the
+writer may produce, and eleven thousand characters later the instruction is a
+list of prohibitions handed to a model that was perfectly capable without
+them. So:
+
+1. **The instruction stays short and stays permissive.** Its length is
+ asserted. A prompt may be markdown, may have headings, sections and a role
+ line — that is what a good prompt looks like, and v3's ``markdown``
+ rejection was this feature refusing its own purpose.
+2. **The worked example IS the specification.** It is the maintainer's own
+ reference run (2026-08-27), and a shown run outweighs a written rule —
+ measured on this very prompt, where a rule about language lost to an
+ example in the other language.
+3. **The guards are damage and fidelity, never shape.** Empty, truncated, a
+ literal the user spoke gone missing, a prompt collapsed to a fraction of
+ the transcript. Nothing about style, structure or register.
4. **Fail-open in every direction.** Off, empty, no provider, a provider that
- dies, a provider that is slow, an answer that is debris: each one hands the
- user their own words back with a status that says why.
-5. **The guards are structural and factual, never stylistic.** The polish
- pass's drift bands would reject every correct prompt (the words are
- SUPPOSED to move), so this pass judges the shape of the answer and what it
- LOST — a literal the user spoke, or half the context they gave.
+ dies, one that is slow, an answer that is debris: each hands the user their
+ own words back with a status that says why.
No network: the chain walk is replaced by a fake through ``monkeypatch``,
never ``unittest.mock``.
@@ -36,14 +32,12 @@ from typing import Any
import pytest
-from jarvis.agentic_ide import prompt_blueprint
from jarvis.core.config import DictationConfig
from jarvis.core.config_writer import DICTATION_SETTING_KEYS
from jarvis.dictation import polish, prompt_mode
from jarvis.dictation.polish import POLISH_STATUSES
from jarvis.dictation.prompt_mode import (
STATUS_PROMPTED,
- analysis_word_count,
build_prompt_mode_prompt,
compose_prompt,
ends_with_sign_off,
@@ -64,34 +58,22 @@ RAW = (
"it shows a blank screen i think it's in AuthHandler can you fix it and also "
"rename the save button to submit"
)
+#: What the writer is supposed to produce: a structured prompt, markdown and
+#: all. Under v3 this exact answer was rejected as ``markdown``.
GOOD = (
- "The login page is broken again. When you type a wrong password it shows a "
- "blank screen instead of the error message. I think it's in AuthHandler, "
- "please fix that.\n\n"
- "Also rename the save button to submit."
-)
-#: What the draft looked like before the read-back: the hedge hardened into a
-#: finding, and a promise the transcript never made.
-DRAFT = (
- "The login page is failing again. The cause is in AuthHandler.\n\n"
- "Also rename the save button to submit, so the wording is consistent "
- "everywhere."
-)
-ANALYSIS = (
- "1. LANGUAGE: English. The message is written in English.\n"
- "2. TASKS (2): fix the blank screen; rename the save button to submit.\n"
- "3. LITERALS: login page, AuthHandler, save, submit.\n"
- "4. SITUATION: a wrong password shows a blank screen.\n"
- "5. LIMITS: none stated.\n"
- "6. WORDING TO KEEP: broken again, I think it's in.\n"
- "7. NOT SAID: which file exactly."
-)
-#: What a well-behaved model returns: the working pass, a draft, the message.
-ANSWER = (
- f"<analysis>\n{ANALYSIS}\n</analysis>\n"
- f"<draft>\n{DRAFT}\n</draft>\n"
- f"<prompt>\n{GOOD}\n</prompt>"
+ "# Role\n"
+ "You are an experienced web developer working on this application's "
+ "authentication flow.\n\n"
+ "# Task\n"
+ "1. The login page is broken again: typing a wrong password shows a blank "
+ "screen instead of the error message. The user suspects AuthHandler. Find "
+ "the cause and fix it so the error message is shown again.\n"
+ "2. Rename the save button to submit.\n\n"
+ "# Output format\n"
+ "Present the diff per file, with a short note on what caused the blank "
+ "screen."
)
+ANSWER = f"<prompt>\n{GOOD}\n</prompt>"
class FakeChain:
@@ -142,266 +124,168 @@ def _install(monkeypatch: pytest.MonkeyPatch, chain: FakeChain) -> FakeChain:
# --------------------------------------------------------------------------- #
-# The doctrine is shared with the Agentic IDE composer
+# The instruction: short, permissive, and taught by its example
# --------------------------------------------------------------------------- #
-def test_the_prompt_carries_the_blueprints_rules_verbatim() -> None:
- system = build_prompt_mode_prompt()
- assert prompt_blueprint.GOAL_NOT_IMPLEMENTATION_RULE in system
- assert prompt_blueprint.FORBIDDEN_SUBJECTS_RULE in system
- composer = prompt_blueprint.system_prompt("implement")
- assert prompt_blueprint.GOAL_NOT_IMPLEMENTATION_RULE in composer
- assert prompt_blueprint.FORBIDDEN_SUBJECTS_RULE in composer
-
-
-# --------------------------------------------------------------------------- #
-# v4: the writer thinks before it answers
-# --------------------------------------------------------------------------- #
-
-
-def test_the_prompt_demands_an_analysis_and_a_read_back() -> None:
- """The whole point of v4. v3 asked for the message directly and a fast
- model wrote it in under a second — no pass over the transcript at all."""
- system = build_prompt_mode_prompt()
- assert "ANSWER IN THREE BLOCKS" in system
- assert "NEVER SKIP ONE" in system
- for tag in ("<analysis>", "</analysis>", "<draft>", "</draft>",
- "<prompt>", "</prompt>"):
- assert tag in system, tag
- assert "PHASE 1 - THE ANALYSIS" in system
- assert "PHASE 2 - THE DRAFT" in system
- assert "PHASE 3 - THE READ-BACK" in system
+def test_the_instruction_stays_short() -> None:
+ """v4's was 13 207 characters of mostly prohibitions and produced worse
+ prompts than a plain "write me a prompt" did. A number is a blunt guard,
+ but it is the one that catches the failure this revision undid: the
+ instruction growing a rule per defect until it fences the writer in."""
+ assert len(prompt_mode._SYSTEM_PROMPT) < 6_000
-def test_the_analysis_names_all_seven_points_it_must_work_through() -> None:
+def test_the_instruction_says_what_the_job_is() -> None:
system = build_prompt_mode_prompt()
- for point in ("1. LANGUAGE", "2. TASKS", "3. LITERALS", "4. THE SITUATION",
- "5. LIMITS", "6. WORDING TO KEEP", "7. NOT SAID"):
- assert point in system, point
- assert "before you compose a single sentence" in system
+ assert "turned automatically into a finished, professional prompt" in system
+ assert "Write the prompt it is asking for" in system
-def test_the_read_back_asks_the_six_questions_that_catch_the_known_failures() -> None:
- """Each one is a defect measured live rather than a checklist item: the
- wrong language, a merged task, a dropped file name, a claim the user never
- made, a word swapped for a synonym, a courtesy line."""
+def test_nothing_in_the_instruction_forbids_the_shape_of_a_good_prompt() -> None:
+ """The v3 rules, each of which forbade part of the maintainer's own
+ reference output. None of them may come back."""
system = build_prompt_mode_prompt()
- assert "Is it in the language from point 1?" in system
- assert "none merged and none dropped" in system
- assert "spelled the way the user said it" in system
- assert "state something the user did not say" in system
- assert "Put theirs back" in system
- assert "say again what the sentence before it already said" in system
- assert "Cut a closing line of thanks" in system
- # ...including one the user said themselves; the reader is an agent.
- assert "even when the user said it themselves" in system
- # The read-back is a correction, not a report the user has to read past.
- assert "not next to it" in system
-
-
-def test_the_language_rule_is_a_point_of_the_analysis() -> None:
- """Measured live 2026-08-27: with the rule written but not worked through,
- and only an English example shown, a German dictation came back English."""
+ for banned in (
+ "PLAIN TEXT",
+ "No markdown",
+ "no headings",
+ "no bullet marks",
+ "no code fences",
+ "SOUND LIKE",
+ "Everyday words",
+ ):
+ assert banned not in system, banned
+ # ...and it says the opposite out loud.
+ assert "headings, lists, markdown, sections" in system
+
+
+def test_the_instruction_keeps_what_was_never_about_shape() -> None:
+ """Fidelity to the transcript and no closing line: the two things the
+ maintainer actually asked for."""
system = build_prompt_mode_prompt()
- assert "THE MESSAGE IS WRITTEN IN THAT LANGUAGE" in system
- assert "A German transcript gets a German message" in system
- assert "these instructions are in English and that means nothing" in system
+ assert "goes in exactly as spoken" in system
+ assert "does not exist" in system
+ assert "left open rather than guessed at" in system
+ assert "no closing line of thanks" in system
-def test_only_the_final_message_is_delivered() -> None:
- assert extract_prompt_block(ANSWER) == GOOD
-
-
-def test_the_draft_is_never_delivered() -> None:
- """It is the version the read-back exists to correct. Handing it over
- would make the whole third phase decorative."""
- out = extract_prompt_block(ANSWER)
- assert "The cause is in" not in out
- assert "so the wording is consistent everywhere" not in out
-
-
-def test_a_forgotten_opening_tag_still_yields_the_final_message() -> None:
- """A fast model drops a tag often enough to matter; everything after the
- draft is the corrected message either way."""
- ragged = f"<analysis>\n{ANALYSIS}\n</analysis>\n<draft>\n{DRAFT}\n</draft>\n{GOOD}"
- assert extract_prompt_block(ragged) == GOOD
-
-
-def test_a_missing_closing_tag_still_yields_the_message() -> None:
- """The answer ran out of budget mid-message. What it wrote comes out and
- faces the truncation guard, which is the thing that decides."""
- cut = f"<analysis>\n{ANALYSIS}\n</analysis>\n<draft>\n{DRAFT}\n</draft>\n<prompt>\n{GOOD}"
- assert extract_prompt_block(cut) == GOOD
+def test_the_language_rule_is_loud_because_the_example_is_german() -> None:
+ """Measured live 2026-08-27: a quiet "write it in the language of the
+ transcript" lost to an English instruction and produced an English prompt
+ for a German dictation, twice."""
+ system = build_prompt_mode_prompt()
+ assert "WRITE IT IN THE LANGUAGE THE USER SPOKE" in system
+ assert "These instructions are in English and that says nothing" in system
+ assert "includes the headings and the section names" in system
-def test_the_tag_named_inside_the_analysis_does_not_win() -> None:
- """A model that writes "...then the <prompt> block..." while thinking would
- otherwise hand us its worksheet. The LAST block is the answer."""
- chatty = (
- "<analysis>\n1. LANGUAGE: English. Next I fill the <prompt> block.\n</analysis>\n"
- f"<draft>\n{DRAFT}\n</draft>\n<prompt>\n{GOOD}\n</prompt>"
- )
- assert extract_prompt_block(chatty) == GOOD
+def test_the_worked_example_is_the_maintainers_reference_run() -> None:
+ """One run, shown whole: his dictated transcript and the prompt that was
+ written for it. It carries what a page of rules used to."""
+ system = build_prompt_mode_prompt()
+ assert system.count("Transcript: ") == 1
+ assert "kannst du mir bitte ein Prompt schreiben" in system
+ assert "Du bist der spezialisierte Prompt-Engineering-Core" in system
+ # The example output is exactly the shape v3 would have thrown away.
+ assert "### ARBEITSABLAUF" in system
+ assert "**Rolle / Systemkontext:**" in system
-def test_an_answer_with_no_blocks_at_all_is_taken_whole() -> None:
- """The v3 shape. It is not thrown away — it faces the same guards it
- always faced, so a good message still gets through."""
- assert extract_prompt_block(GOOD) == GOOD
+def test_the_prompt_version_names_the_v5_revision() -> None:
+ assert prompt_mode.PROMPT_MODE_PROMPT_VERSION == 5
-def test_the_analysis_is_measured_so_a_skipped_one_is_visible() -> None:
- assert analysis_word_count(ANSWER) > 20
- assert analysis_word_count(GOOD) == 0
+def test_protected_terms_are_listed_in_the_shared_block() -> None:
+ system = build_prompt_mode_prompt(["Jarvis", "AuthHandler", "", "jarvis"])
+ assert "<protected terms" in system
+ assert "AuthHandler" in system
# --------------------------------------------------------------------------- #
-# The maintainer's bar, as rules in the prompt
+# Getting the prompt out of the answer
# --------------------------------------------------------------------------- #
-def test_the_prompt_asks_for_plain_text_in_the_spoken_language() -> None:
- system = build_prompt_mode_prompt()
- assert "PLAIN TEXT, SAME LANGUAGE" in system
- assert "No markdown" in system
- assert "language the transcript is in" in system
- # v1 asked for English and a markdown skeleton; neither may come back.
- assert "ENGLISH" not in system
- assert "## Task" not in system
-
-
-def test_the_prompt_makes_the_speakers_own_words_the_default() -> None:
- """v4's second half: v3 reworded phrasing the user had chosen, down to
- the small words, and called it polish."""
- system = build_prompt_mode_prompt()
- assert "THE USER'S OWN WORDS ARE THE DEFAULT" in system
- assert "REWRITING IS THE EXCEPTION" in system
- assert "including the small ones" in system
- assert "A synonym you find more elegant is a change in meaning" in system
-
-
-def test_the_prompt_asks_for_the_speakers_own_register() -> None:
- system = build_prompt_mode_prompt()
- assert "SOUND LIKE THE PERSON WHO SPOKE" in system
- # Measured live 2026-08-27: the fast chain answered a "du" transcript with
- # "Bitte prüfen Sie" — the formal form the user never used.
- assert "Address the agent the way the user did" in system
- assert "never switch to the formal one" in system
- assert "Everyday words" in system
- assert "No sets of three" in system
- # Courtesy is mirrored, never manufactured.
- assert "not added where they did not" in system
-
-
-def test_the_prompt_forbids_a_closing_line() -> None:
- """v3 guaranteed a line of thanks in code; v4 removes it. The reader is a
- coding agent, and the maintainer asked for it gone (2026-08-27)."""
- system = build_prompt_mode_prompt()
- assert "NOTHING AFTER THE LAST PIECE OF SUBSTANCE" in system
- assert "No closing line of thanks" in system
- assert "no sign-off of any kind" in system
- # The v3 rule and its worked examples must not survive anywhere.
- assert "one short line of thanks on its own line" not in system
- assert "\nDanke!\n" not in system
+def test_the_fenced_prompt_is_what_is_delivered() -> None:
+ assert extract_prompt_block(ANSWER) == GOOD
-def test_the_prompt_describes_the_shape_of_the_message() -> None:
- system = build_prompt_mode_prompt()
- assert "WHAT THE MESSAGE CONTAINS" in system
- assert "with no labels in front of them" in system
- assert "every concrete detail of it intact" in system
- assert "FIX WHAT EXISTS" in system
- assert "SAY EACH THING ONCE" in system
- assert "no typographic hyphens" in system
-
-
-def test_the_prompt_shows_one_worked_answer_per_language_it_ships_for() -> None:
- """A shown example outweighs a written rule, so the examples have to
- DISAGREE about language for the language rule to be readable at all. With
- only the English pair, a German dictation came back English (live,
- 2026-08-27). Each shows the full three-block shape, draft included."""
- system = build_prompt_mode_prompt()
- assert system.count("Transcript: ") == 2
- assert system.count("Answer:\n<analysis>") == 2
- # The closing tag, not the opening one: the phase description names
- # ``<draft>`` in running text as well, and only a real block closes.
- assert system.count("</draft>") == 3, "one per example plus the shape itself"
- assert "1. LANGUAGE: German" in system
- assert "1. LANGUAGE: English" in system
- # The examples are the LAST thing the model reads before the protected
- # terms — nothing may follow them and dilute the shape they set.
- assert prompt_mode._SYSTEM_PROMPT.rstrip().endswith("</prompt>")
-
-
-def test_each_shown_draft_carries_the_defect_its_read_back_removes() -> None:
- """An example whose draft already equals its message teaches nothing about
- the third phase. The English pair hardens a hedge into a finding; the
- German one turns a repair into "implementiere"."""
- system = build_prompt_mode_prompt()
- assert "The cause is in the auth handler file" in system
- assert "Bitte implementiere eine zuverlässige Anzeige" in system
- # ...and neither survives into the message beside it.
- assert "I think it's in the auth handler" in system
- assert "Bitte bring die Indikatoren wieder in Ordnung" in system
+def test_an_introduction_in_front_of_the_fence_is_dropped() -> None:
+ """The one reason the fence exists. The reference run's own first line was
+ "Hier ist ein System-Prompt für deinen Auto-Prompting-Modus" — a model
+ handed this job likes to introduce its work."""
+ chatty = f"Hier ist ein System-Prompt für deinen Auto-Prompting-Modus.\n\n{ANSWER}"
+ assert extract_prompt_block(chatty) == GOOD
-def test_the_prompt_version_names_the_v4_revision() -> None:
- assert prompt_mode.PROMPT_MODE_PROMPT_VERSION == 4
+def test_the_last_opening_tag_wins() -> None:
+ """A model that names the tag while introducing itself would otherwise
+ hand over the introduction."""
+ chatty = f"I will now fill the <prompt> tag as asked.\n{ANSWER}"
+ assert extract_prompt_block(chatty) == GOOD
-def test_the_prompt_keeps_every_task_dictated_at_once() -> None:
- system = build_prompt_mode_prompt()
- assert "SEVERAL TASKS AT ONCE" in system
- assert "Every task from point 1 of the analysis survives" in system
- assert "Never merge two" in system
+def test_a_missing_closing_tag_still_yields_the_prompt() -> None:
+ """It ran out of budget. What it wrote comes out and faces the truncation
+ guard, which is the thing that decides whether it is usable."""
+ assert extract_prompt_block(f"<prompt>\n{GOOD}") == GOOD
-def test_the_prompt_never_presumes_a_workspace() -> None:
- system = build_prompt_mode_prompt()
- assert "## Key files" not in system
- assert "WORKSPACE" not in system
- assert "@path" not in system
+def test_an_answer_with_no_fence_is_taken_whole() -> None:
+ """The model simply wrote the prompt, which is a fine thing to have done."""
+ assert extract_prompt_block(GOOD) == GOOD
-def test_protected_terms_are_listed_in_the_shared_block() -> None:
- system = build_prompt_mode_prompt(["Jarvis", "AuthHandler", "", "jarvis"])
- assert "<protected terms" in system
- assert "AuthHandler" in system
- assert system.count("Jarvis") + system.count("jarvis") == 1
+def test_an_empty_answer_yields_nothing() -> None:
+ assert extract_prompt_block(" ") == ""
# --------------------------------------------------------------------------- #
-# Structural guards
+# Guards: damage and fidelity, never shape
# --------------------------------------------------------------------------- #
-def test_a_good_prompt_passes() -> None:
+def test_a_structured_markdown_prompt_passes() -> None:
+ """The headline of v5. Under v3 this same answer was ``markdown`` and the
+ user got their raw transcript instead of the prompt they asked for."""
assert prompt_guard_reason(RAW, GOOD) == ""
-def test_an_empty_answer_is_rejected() -> None:
+#: The same brief in five shapes. Only the formatting differs — each carries
+#: AuthHandler and enough of the transcript to clear the fidelity guards, so a
+#: rejection here can only be about shape, which is the thing v5 stopped
+#: judging.
+_SHAPES = [
+ "# Role\nYou are a web developer working on the login flow.\n\n# Task\n"
+ "Fix the blank screen AuthHandler shows on a wrong password, so the error "
+ "message appears again, and rename the save button to submit.",
+ "- The login page shows a blank screen on a wrong password instead of the "
+ "error message; the user suspects AuthHandler. Find the cause and fix it.\n"
+ "- Rename the save button to submit.",
+ "**Task**: fix the blank screen that AuthHandler shows on a wrong password "
+ "so the error message appears again, and **rename** the save button to "
+ "submit.",
+ "1. Fix the blank screen on a wrong password, which the user suspects is in "
+ "AuthHandler, so the error message shows again.\n"
+ "2. Rename the save button to submit.",
+ "Fix the blank screen on a wrong password so the error message shows again. "
+ "The user suspects this file:\n\n```\nAuthHandler\n```\n\n"
+ "Then rename the save button to submit.",
+]
+
+
[email protected]("answer", _SHAPES)
+def test_no_shape_is_rejected_any_more(answer: str) -> None:
+ assert prompt_guard_reason(RAW, answer) == ""
+
+
+def test_an_empty_prompt_is_rejected() -> None:
assert prompt_guard_reason(RAW, " ") == "empty"
- "answer",
- [
- "## Task\nFix the login page.",
- "Fix the login page.\n\n```\nAuthHandler\n```",
- "**Task**: fix the login page.",
- "- fix the login page\n- rename the button",
- "1. fix the login page\n2. rename the button",
- ],
-)
-def test_markdown_is_rejected(answer: str) -> None:
- """v1 answered with headings; the answer is pasted as a chat message. It
- is also what a leaked analysis looks like, which is the v4 way to fail."""
- assert prompt_guard_reason(RAW, answer) == "markdown"
-
-
def test_a_prompt_that_stops_mid_sentence_is_truncated() -> None:
- assert prompt_guard_reason(RAW, "Fix the login page so that") == "truncated"
+ assert prompt_guard_reason(RAW, "Fix the AuthHandler login page so that") == "truncated"
def test_a_dropped_protected_spelling_is_rejected() -> None:
@@ -410,43 +294,34 @@ def test_a_dropped_protected_spelling_is_rejected() -> None:
assert prompt_guard_reason(RAW, without, protected=["Nova"]) == ""
-# --------------------------------------------------------------------------- #
-# Fidelity guards — what the message LOST, never how it reads
-# --------------------------------------------------------------------------- #
-
-
def test_the_literals_of_a_transcript_are_its_identifiers_numbers_and_quotes() -> None:
spoken = (
'change src/auth/handler.ts and AuthHandler so the retry_count is 30 '
'and the button says "Sign in"'
)
found = {token.casefold() for token in transcript_literals(spoken)}
- assert "src/auth/handler.ts" in found
- assert "authhandler" in found
- assert "retry_count" in found
- assert "30" in found
- assert "sign in" in found
+ assert {"src/auth/handler.ts", "authhandler", "retry_count", "30", "sign in"} <= found
def test_an_apostrophe_is_never_read_as_an_opening_quote() -> None:
""""it's" and "don't" in one sentence would otherwise turn everything
- between them into a literal the message has to reproduce verbatim."""
+ between them into a literal the prompt has to reproduce verbatim."""
assert transcript_literals("it's broken and i don't know why") == []
def test_ordinary_words_are_not_literals() -> None:
- """The message is allowed to rephrase prose. A guard over every noun would
- reject every honest rewrite, which is the opposite of the point."""
+ """A prompt is a rewrite. A guard over every noun would reject every
+ honest one, which is the opposite of the point."""
assert transcript_literals("please fix the login page it is broken") == []
-def test_a_message_that_drops_the_files_the_user_named_is_rejected() -> None:
+def test_a_prompt_that_drops_the_files_the_user_named_is_rejected() -> None:
spoken = (
"please fix src/auth/handler.ts and also AuthHandler and the retry_count "
"setting and the timeout_ms value, they are all wrong since yesterday"
)
vague = (
- "Please fix the authentication code, some settings in there are wrong "
+ "# Task\nFix the authentication code. Some settings in there are wrong "
"since yesterday and need to be corrected so that logging in works again."
)
assert len(lost_literals(spoken, vague)) >= 4
@@ -455,43 +330,35 @@ def test_a_message_that_drops_the_files_the_user_named_is_rejected() -> None:
def test_one_missing_literal_is_a_slip_not_a_rejection() -> None:
"""A recognizer writes the same spoken name two ways in one breath;
- rejecting on one of those costs a good message."""
+ rejecting on one of those costs a good prompt."""
spoken = (
"please fix src/auth/handler.ts and AuthHandler and the retry_count "
"setting, the login has been broken since yesterday afternoon"
)
almost = (
- "Please fix src/auth/handler.ts and the retry_count setting. The login "
+ "# Task\nFix src/auth/handler.ts and the retry_count setting. The login "
"has been broken since yesterday afternoon and needs to work again."
)
assert lost_literals(spoken, almost) == ["AuthHandler"]
assert prompt_guard_reason(spoken, almost) == ""
-def test_a_message_collapsed_to_a_fraction_of_the_transcript_is_rejected() -> None:
- """The failure the maintainer reported: it reads well and quietly leaves
- out half of what was said."""
+def test_a_prompt_collapsed_to_a_fraction_of_the_transcript_is_rejected() -> None:
+ """A written prompt is normally LONGER than the dictation, so this only
+ fires on a writer that summarised instead of writing."""
spoken = (
"so the indicators that show whether a session is working or finished "
"are wrong again, a working session shows up as finished and the other "
"way round, and they never update live either, that has been the case "
"since the last update and it makes the whole overview useless to me"
)
- thin = "Please fix the session indicators."
+ thin = "Fix the session indicators."
assert looks_thinned(spoken, thin) is True
assert prompt_guard_reason(spoken, thin) == "dropped_context"
def test_a_short_transcript_is_never_measured_for_thinning() -> None:
- """"fix the typo on the login page" is a complete request at seven words,
- and its message is allowed to be shorter still."""
- assert looks_thinned("fix the typo on the login page", "Please fix the typo.") is False
-
-
-def test_a_tightened_message_is_not_a_thinned_one() -> None:
- """A dictation is 25-40 % filler. Cutting that is the job, not the defect."""
- assert looks_thinned(RAW, GOOD) is False
- assert prompt_guard_reason(RAW, GOOD) == ""
+ assert looks_thinned("fix the typo on the login page", "Fix the typo.") is False
# --------------------------------------------------------------------------- #
@@ -507,18 +374,7 @@ async def test_a_prompt_is_delivered_with_the_prompted_status(
assert out.status == STATUS_PROMPTED
assert out.text == GOOD
assert (out.provider, out.model) == ("fake-family", "fake-model")
- assert len(chain.calls) == 1
-
-
-async def test_the_analysis_never_reaches_the_user(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """It is a working pass, not an answer. A user who sees "1. TASKS (2)" in
- their text field has been handed the model's scratchpad."""
- _install(monkeypatch, FakeChain())
- out = await compose_prompt(RAW, cfg=_cfg())
- assert "TASKS" not in out.text
- assert "<analysis>" not in out.text and "<prompt>" not in out.text
+ assert len(chain.calls) == 1, "one call — no scratchpad pass, no second opinion"
async def test_the_transcript_travels_fenced_in_the_user_message(
@@ -531,19 +387,16 @@ async def test_the_transcript_travels_fenced_in_the_user_message(
assert "<<<BEGIN TRANSCRIPT>>>" in call["user"] and RAW in call["user"]
-def test_the_budget_covers_the_analysis_as_well_as_the_message() -> None:
- """Both blocks come out of ONE token budget, so it has to be generous
- enough that a full inventory does not cut the message off — a message that
- stops mid-sentence is rejected and costs the whole pass.
-
- Pinned by reading the source, like ``translating=True`` below: the fake
+def test_the_budget_fits_a_written_out_prompt() -> None:
+ """Pinned by reading the source, like ``translating=True`` below: the fake
chain replaces ``_call_chain`` itself, which is where these are passed on.
- """
+ The reference output alone is about 700 tokens, and a cut-off prompt is
+ rejected as truncated and costs the whole pass."""
import inspect
source = inspect.getsource(prompt_mode._call_chain)
assert "max_output_tokens=_MAX_OUTPUT_TOKENS" in source
- assert prompt_mode._MAX_OUTPUT_TOKENS >= 4_000
+ assert prompt_mode._MAX_OUTPUT_TOKENS >= 3_000
assert prompt_mode._TEMPERATURE == 0.0
@@ -592,31 +445,10 @@ async def test_a_slow_chain_hits_the_ceiling(monkeypatch: pytest.MonkeyPatch) ->
assert (out.status, out.text, out.reason) == ("timeout", RAW, "deadline")
-async def test_debris_from_the_chain_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
- _install(monkeypatch, FakeChain(answer="## Task\nfix it"))
+async def test_a_truncated_answer_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
+ _install(monkeypatch, FakeChain(answer="<prompt>\n# Task\nFix the AuthHandler so that"))
out = await compose_prompt(RAW, cfg=_cfg())
- assert (out.status, out.text, out.reason) == ("rejected_drift", RAW, "markdown")
-
-
-async def test_an_answer_that_is_only_an_analysis_is_rejected(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """The model worked and then forgot to write the message. Nothing follows
- the analysis, so nothing is delivered — the user gets their own words, not
- the model's numbered worksheet."""
- _install(monkeypatch, FakeChain(answer=f"<analysis>\n{ANALYSIS}\n</analysis>"))
- out = await compose_prompt(RAW, cfg=_cfg())
- assert (out.status, out.text, out.reason) == ("rejected_drift", RAW, "empty")
-
-
-async def test_an_analysis_written_without_its_tags_is_rejected(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """The other way to leak a worksheet: no tags at all, so the whole answer
- is taken as the message and the markdown guard catches the numbering."""
- _install(monkeypatch, FakeChain(answer=ANALYSIS))
- out = await compose_prompt(RAW, cfg=_cfg())
- assert (out.status, out.text, out.reason) == ("rejected_drift", RAW, "markdown")
+ assert (out.status, out.text, out.reason) == ("rejected_drift", RAW, "truncated")
async def test_a_raising_chain_is_a_provider_error(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -639,9 +471,9 @@ async def test_the_chain_is_asked_for_the_stronger_fast_model() -> None:
def test_ships_off_with_a_twelve_second_ceiling() -> None:
- """v4 raised it from 6 s: the call now carries a written pass over the
- transcript in front of the message, and a real dictation spends 6-9 s on
- the pair."""
+ """The ceiling is a safety net, not a target: the fast chain answers in
+ 2-6 s depending on the provider's hardware, and the bound only has to keep
+ a long prompt on a slower family from being cut off."""
cfg = DictationConfig()
assert cfg.prompt_mode is False
assert cfg.prompt_mode_timeout_ms == 12_000
@@ -659,12 +491,6 @@ def test_the_ceiling_is_clamped_never_rejected(value: Any, expected_ms: int) ->
assert timeout_budget_s(cfg) == expected_ms / 1000
-def test_the_floor_leaves_room_for_the_analysis() -> None:
- """Below the floor the analysis cannot finish, so the pass would only ever
- time out — which is strictly worse than the switch being off."""
- assert timeout_budget_s(DictationConfig(prompt_mode_timeout_ms=500)) >= 4.0
-
-
def test_the_keys_persist_and_reach_the_settings_route() -> None:
for key in ("prompt_mode", "prompt_mode_timeout_ms"):
assert key in DICTATION_SETTING_KEYS, key
@@ -684,15 +510,13 @@ def test_prompted_is_part_of_the_shared_status_vocabulary() -> None:
def test_non_breaking_hyphens_inside_words_become_hyphen_minus() -> None:
"""Measured live 2026-08-27: "Jarvis‑Bar" and "Self‑Hosted" came back with
U+2011, which no grep for the spoken spelling ever matches."""
- assert normalize_prompt_text("Jarvis‑Bar and Self‑Hosted") == (
- "Jarvis-Bar and Self-Hosted"
- )
+ assert normalize_prompt_text("Jarvis‑Bar and Self‑Hosted") == "Jarvis-Bar and Self-Hosted"
assert normalize_prompt_text("Prompt‐Modus") == "Prompt-Modus"
assert normalize_prompt_text("Prompt–Modus") == "Prompt-Modus"
def test_a_spaced_dash_is_left_alone() -> None:
- """An aside the model wrote as " – " is punctuation, not an identifier."""
+ """An aside written as " – " is punctuation, not an identifier."""
assert normalize_prompt_text("fix it – today") == "fix it – today"
@@ -715,42 +539,39 @@ async def test_normalisation_runs_before_the_protected_term_guard(
# --------------------------------------------------------------------------- #
-# The closing line — asked away in the prompt, cut in code
+# The closing line — asked away in the instruction, cut in code
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize(
"closing",
- ["Danke!", "Vielen Dank!", "Thanks!", "Thank you.", "Thanks a lot.", "¡Gracias!",
- "Best regards", "Cheers", "Viele Grüße"],
+ ["Danke!", "Vielen Dank!", "Thanks!", "Thank you.", "¡Gracias!", "Best regards",
+ "Cheers", "Viele Grüße"],
)
def test_a_short_courtesy_line_is_recognised(closing: str) -> None:
- assert ends_with_sign_off(f"Fix the login page.\n\n{closing}") is True
+ assert ends_with_sign_off(f"# Task\nFix the login page.\n\n{closing}") is True
@pytest.mark.parametrize(
"last_line",
[
- "Please fix the login page.",
+ "Present the diff per file.",
"Danke für den Hinweis, aber die Seite ist trotzdem kaputt und zeigt nichts an.",
"",
],
)
def test_a_line_that_merely_mentions_thanks_is_not_a_sign_off(last_line: str) -> None:
- assert ends_with_sign_off(f"Fix the login page.\n\n{last_line}") is False
+ assert ends_with_sign_off(f"# Task\nFix the login page.\n\n{last_line}") is False
def test_a_trailing_thanks_is_cut() -> None:
- assert strip_closing_sign_off("Bitte repariere die Seite.\n\nDanke!") == (
- "Bitte repariere die Seite."
- )
- assert strip_closing_sign_off("Please fix the page.\n\nThanks!") == "Please fix the page."
+ assert strip_closing_sign_off("# Task\nFix the page.\n\nDanke!") == "# Task\nFix the page."
@pytest.mark.parametrize(
("written", "kept"),
[
- ("Bitte setze retry_count auf 10. Danke dir.", "Bitte setze retry_count auf 10."),
+ ("Setze retry_count auf 10. Danke dir.", "Setze retry_count auf 10."),
("Fix it. Thanks a lot!", "Fix it."),
("Please have a look. Thanks in advance.", "Please have a look."),
],
@@ -765,13 +586,10 @@ def test_a_thanks_tacked_onto_the_last_sentence_is_cut(written: str, kept: str)
def test_a_stacked_sign_off_is_cut_to_the_last_piece_of_substance() -> None:
- """A model that writes "Danke!" under "Viele Grüße" has written two."""
- assert strip_closing_sign_off("Bitte repariere die Seite.\n\nViele Grüße\n\nDanke!") == (
- "Bitte repariere die Seite."
- )
+ assert strip_closing_sign_off("Fix the page.\n\nViele Grüße\n\nDanke!") == "Fix the page."
-def test_a_message_without_a_sign_off_is_untouched() -> None:
+def test_a_prompt_without_a_sign_off_is_untouched() -> None:
assert strip_closing_sign_off(GOOD) == GOOD
@@ -783,21 +601,18 @@ def test_a_one_line_message_is_never_stripped_to_nothing() -> None:
async def test_a_model_that_still_signs_off_is_trimmed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """The prompt asks for no closing line; this is the guarantee, the way
- ``ensure_closing_thanks`` was the guarantee of the opposite in v3."""
signed = ANSWER.replace(f"{GOOD}\n</prompt>", f"{GOOD}\n\nDanke!\n</prompt>")
_install(monkeypatch, FakeChain(answer=signed))
out = await compose_prompt(RAW, cfg=_cfg(), language="de")
assert out.status == STATUS_PROMPTED
assert out.text == GOOD
- assert not out.text.endswith("Danke!")
async def test_the_trim_never_masks_a_truncated_answer(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """The truncation guard runs first, so a message that stopped mid-sentence
+ """The truncation guard runs first, so a prompt that stopped mid-sentence
is caught as damage rather than tidied into looking finished."""
- _install(monkeypatch, FakeChain(answer="Fix the login page so that"))
+ _install(monkeypatch, FakeChain(answer="# Task\nFix the AuthHandler page so that"))
out = await compose_prompt(RAW, cfg=_cfg(), language="en")
assert (out.status, out.text, out.reason) == ("rejected_drift", RAW, "truncated")