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): precision mode — sharpen word choice, plainly

rubenluetke10-beep2147a6dd6077
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index c031509d07..1c83a93662 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2982,6 +2982,27 @@ class DictationConfig(BaseModel):
#: ever licenses a change of meaning.
polish_style: Literal["neutral", "messaging", "email"] = "neutral"
+ #: Also sharpen the WORD CHOICE, not just the writing. With this on the
+ #: pass may replace a vague placeholder with the specific word that was
+ #: meant ("the thing that holds the pipe" -> "the bracket") and collapse
+ #: padding into the plain verb ("make a decision" -> "decide"). The prompt
+ #: spends more words forbidding the ornate register than requesting
+ #: precision, because that is the documented failure direction: a model
+ #: asked to "improve wording" reaches for *utilize* and *facilitate*, which
+ #: is the opposite of the goal. Simple and exact, never impressive.
+ #:
+ #: Ships OFF, and unlike ``polish_style`` this is not a matter of taste —
+ #: it TRADES A GUARD. Rare-token preservation, the check that rejects an
+ #: answer in which an uncommon word silently vanished, cannot survive a
+ #: mode whose whole job is replacing uncommon words, so precision runs
+ #: against ``precision_drift_reason`` with that one check dropped. Every
+ #: other guard stands, protected terms included. A trade like that is the
+ #: user's to make deliberately, never one they inherit from a default.
+ #:
+ #: Applies to the translate pass too, through the same prompt clause, so
+ #: one switch means one thing whichever pass runs.
+ polish_precision: bool = False
+
# ------------------------------------------------------------------
# The translate pass — speak one language, deliver another
# ------------------------------------------------------------------
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 62bc3e0ba3..fe3f553937 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -869,6 +869,7 @@ DICTATION_SETTING_KEYS = (
"polish_drift_max_shrink",
"polish_drift_max_growth",
"polish_style",
+ "polish_precision",
# The translate pass. Same rule as the polish keys above: a key missing here
# is a switch the UI appears to save and loses on the next restart.
"translate",
diff --git a/jarvis/dictation/polish.py b/jarvis/dictation/polish.py
index a9c024b1ab..fb6ed839b3 100644
--- a/jarvis/dictation/polish.py
+++ b/jarvis/dictation/polish.py
@@ -20,6 +20,18 @@ guard set (``translate_drift_reason``) differ, and formatting happens inside the
SAME call so a translation costs one round trip, not two. ``translate_to``
selects the mode; :func:`resolve_translate_target` decides it.
+Precision mode rides on top of both
+-----------------------------------
+``[dictation].polish_precision`` licenses ONE further step in either pass:
+replacing a word with a more precise one that means the same thing. It is a
+prompt clause (:func:`jarvis.dictation.polish_prompt.precision_block`, shared by
+both prompts so the switch means one thing) plus a matched guard
+(``precision_drift_reason``), and the two must always travel together — the
+ordinary guard rejects a substitution as ``lost_term``, which is the answer this
+mode is built to produce. That guard trade is why it ships OFF: everything else
+in this module can be defaulted on because it only ever costs a formatting pass,
+and this one costs a check.
+
The contract, in one sentence
-----------------------------
**This pass can only ever be a no-op; it can never be a loss.**
@@ -99,6 +111,7 @@ from jarvis.dictation.polish_client import (
from jarvis.dictation.polish_guards import (
drift_reason,
normalize_for_compare,
+ precision_drift_reason,
translate_drift_reason,
)
from jarvis.dictation.polish_prompt import (
@@ -156,6 +169,25 @@ _DEFAULT_MAX_GROWTH = 1.20
_DEFAULT_TRANSLATE_MAX_SHRINK = 0.40
_DEFAULT_TRANSLATE_MAX_GROWTH = 2.50
+# Precision mode's own word-count band, and the reason it is not the polish one.
+# Substitution moves the count in BOTH directions and further than repunctuation
+# does: collapsing padding into a verb shortens ("make a decision" -> "decide",
+# "the list of stuff it needs to run" -> "its dependencies"), while naming a
+# thing the speaker described in a placeholder can lengthen. The polish ceiling
+# of 1.20 is tuned for a pass that may only ever shrink or stay flat, so reusing
+# it would reject correct answers by construction — the same mistake as running
+# a translation through the polish band.
+#
+# Still deliberately tight, and tighter than the translate band: growth is what
+# an answer, an explanation or a model that started embellishing looks like, and
+# ornamentation is precisely this mode's documented failure direction. Module
+# constants rather than config keys on purpose — the drift band is a safety
+# floor, not a preference, and this feature already asks the user to give up one
+# guard. Handing them a dial that quietly widens what is left would turn one
+# understood trade into an unbounded one (AP-31: no unread config switch).
+_DEFAULT_PRECISION_MAX_SHRINK = 0.45
+_DEFAULT_PRECISION_MAX_GROWTH = 1.35
+
#: The value ``[dictation].translate_target`` uses to mean "no fixed target".
#: Shared spelling with ``[dictation].language`` so one word means one thing
#: across the block.
@@ -260,6 +292,24 @@ def polish_enabled(cfg: Any) -> bool:
return bool(getattr(cfg, "polish", False))
+def precision_enabled(cfg: Any) -> bool:
+ """Whether the pass may also sharpen the WORD CHOICE. No I/O.
+
+ Ships OFF, and an absent key reads as OFF, for a stronger reason than the
+ translate switch has: this one trades away a guard. The rare-token check
+ that rejects an answer in which an uncommon word silently vanished cannot
+ coexist with a mode whose job is replacing uncommon words, so precision runs
+ against :func:`~jarvis.dictation.polish_guards.precision_drift_reason` with
+ that check dropped. Inheriting that from a default nobody chose is exactly
+ the class of surprise this package refuses to ship.
+
+ Read independently of :func:`polish_enabled` so the answer is the SAME
+ whichever pass is running — with the formatter off and a translation on,
+ precision still applies to the translation.
+ """
+ return bool(getattr(cfg, "polish_precision", False))
+
+
def translate_enabled(cfg: Any) -> bool:
"""Whether dictation is set to come out in a fixed language. No I/O.
@@ -419,13 +469,25 @@ async def polish_transcript(
budget_s = _timeout_budget(cfg, timeout_s)
attempt = _Attempt()
+ # Resolved ONCE and used for both the prompt and the guard below. Those
+ # two are a matched pair — the precision prompt licenses substitutions
+ # that the ordinary guard rejects — so reading the switch twice is how
+ # they end up disagreeing and the mode silently rejects its own correct
+ # answers.
+ precision = precision_enabled(cfg)
if translating:
system = build_translate_prompt(
- target_language=target, style=style, protected_terms=protected_terms
+ target_language=target,
+ style=style,
+ protected_terms=protected_terms,
+ precision=precision,
)
else:
system = build_polish_prompt(
- language=language, style=style, protected_terms=protected_terms
+ language=language,
+ style=style,
+ protected_terms=protected_terms,
+ precision=precision,
)
# The SAME fenced user message either way — the delimiter and the
# ``meta_output`` guard that watches for it are one mechanism, and a
@@ -568,6 +630,20 @@ async def polish_transcript(
hi=10.0,
),
)
+ elif precision:
+ # The matched guard for the precision prompt. Same checks as
+ # ``drift_reason`` minus rare-token preservation, which a mode built
+ # to replace uncommon words would fail on nearly every correct
+ # answer, and with its own word-count band — substitution moves the
+ # count in both directions where repunctuation only ever shrinks it.
+ reason = precision_drift_reason(
+ source,
+ polished,
+ language=language,
+ protected=protected_terms,
+ max_shrink=_DEFAULT_PRECISION_MAX_SHRINK,
+ max_growth=_DEFAULT_PRECISION_MAX_GROWTH,
+ )
else:
reason = drift_reason(
source,
@@ -830,6 +906,7 @@ __all__ = [
"aclose",
"polish_enabled",
"polish_transcript",
+ "precision_enabled",
"reset_polish_state",
"resolve_translate_target",
"translate_enabled",
diff --git a/jarvis/dictation/polish_guards.py b/jarvis/dictation/polish_guards.py
index 03c0b3bd1c..456c1b6d72 100644
--- a/jarvis/dictation/polish_guards.py
+++ b/jarvis/dictation/polish_guards.py
@@ -66,6 +66,30 @@ DRIFT_REASONS: Final[tuple[str, ...]] = (
"lost_term",
)
+#: Every reason :func:`precision_drift_reason` can return, plus ``""``.
+#:
+#: A STRICT SUBSET of :data:`DRIFT_REASONS` — same checks, same codes, same
+#: meanings, minus ``lost_term``'s rare-token half. Declared as its own tuple
+#: anyway, rather than reusing the one above, because the difference is the
+#: entire point of the mode: precision mode REPLACES uncommon words on purpose,
+#: so a guard that rejects an answer for having done so rejects the feature. A
+#: reader who sees this vocabulary knows immediately which protection was traded
+#: away, and a test can pin that the trade is exactly one check wide.
+#:
+#: ``lost_term`` survives, because it still fires for PROTECTED terms — names,
+#: the wake word, the STT dictionary. Those come from the user, not from a
+#: frequency table, and no amount of "sharpen the wording" licenses touching
+#: them.
+PRECISION_DRIFT_REASONS: Final[tuple[str, ...]] = (
+ "empty",
+ "meta_output",
+ "ratio_shrink",
+ "ratio_growth",
+ "language_flip",
+ "lost_number",
+ "lost_term",
+)
+
#: Every reason :func:`translate_drift_reason` can return, plus ``""``.
#:
#: Deliberately a SEPARATE vocabulary rather than an extension of the tuple
@@ -317,6 +341,48 @@ _COMMON_WORDS: Final[dict[str, frozenset[str]]] = {
for code, base in _COMMON_WORDS_BASE.items()
}
+# i18n-allow: number-word DATA (§1 list #3), same category as the tables above.
+#
+# The number words that mean a QUANTITY and nothing else — the only ones a guard
+# may insist on. Every member of ``_NUMBER_WORDS`` that also has a common
+# non-numeric sense is deliberately absent, because this check has no way to
+# tell the two apart and the module's rule is that silence beats a veto:
+#
+# * ordinals ("first", "erste", "primero") — a rewrite legitimately drops them
+# ("the first thing we need" -> "the requirement");
+# * fractions and vague amounts ("half", "quarter", "dozen", "halb", "viertel")
+# — "a quarter of the team" survives as "some of the team" in any faithful
+# sharpening, and "quarter" is also a period of the year;
+# * "one" / "uno" — far more often an impersonal pronoun or an article than the
+# number 1 ("one of the things", "one never knows").
+#
+# What is left is unambiguous: a speaker who said "three" and got back a text
+# with no three in it, in digits or in words, lost information.
+_QUANTITY_WORDS: Final[dict[str, frozenset[str]]] = {
+ "en": frozenset({
+ "zero", "two", "three", "four", "five", "six", "seven", "eight",
+ "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
+ "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "thirty",
+ "forty", "fifty", "sixty", "seventy", "eighty", "ninety", "hundred",
+ "thousand", "million", "billion",
+ }),
+ "de": frozenset({ # i18n-allow: German quantity words (§1 list #3)
+ "null", "zwei", "drei", "vier", "fünf", "sechs", "sieben", # i18n-allow
+ "acht", "neun", "zehn", "elf", "zwölf", "dreizehn", "vierzehn", # i18n-allow
+ "fünfzehn", "sechzehn", "siebzehn", "achtzehn", "neunzehn", # i18n-allow
+ "zwanzig", "dreißig", "dreissig", "vierzig", "fünfzig", # i18n-allow
+ "sechzig", "siebzig", "achtzig", "neunzig", "hundert", "tausend", # i18n-allow
+ "million", "millionen", # i18n-allow
+ }),
+ "es": frozenset({ # i18n-allow: Spanish quantity words (§1 list #3)
+ "cero", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", # i18n-allow
+ "nueve", "diez", "once", "doce", "trece", "catorce", "quince", # i18n-allow
+ "dieciséis", "diecisiete", "dieciocho", "diecinueve", "veinte", # i18n-allow
+ "treinta", "cuarenta", "cincuenta", "sesenta", "setenta", "ochenta", # i18n-allow
+ "noventa", "cien", "ciento", "mil", "millón", "millones", # i18n-allow
+ }),
+}
+
def normalize_for_compare(text: str) -> str:
"""Collapse *text* to the form used to decide "did anything change at all".
@@ -469,6 +535,49 @@ def _digit_runs(text: str) -> frozenset[str]:
return frozenset(_DIGIT_RUN_RE.findall(_DIGIT_SEPARATOR_RE.sub("", str(text or ""))))
+def _lost_quantity_word(raw: str, out: str, *, language: str) -> bool:
+ """Whether a spoken QUANTITY vanished without a digit taking its place.
+
+ The gap :func:`_digit_runs` cannot see. That check compares digits, so a
+ speaker who said "send it to three people" and got back "send it to the
+ team" loses the three silently: there was never a digit to miss, and
+ "three" is common vocabulary so the rare-token filter waves it through too.
+
+ Used ONLY by :func:`precision_drift_reason`, and that narrowness is the
+ point rather than an omission. In the ordinary polish pass the model is
+ forbidden from replacing words at all, so this failure needs a prompt
+ violation AND a second guard to already have missed it; in precision mode
+ replacing words is the licensed behaviour and the rare-token check that
+ backstopped it is gone, which is exactly when a quantity can walk out
+ unnoticed. Adding it to both would also change the verdict on transcripts
+ the ordinary guard has been passing correctly for months, for a failure it
+ is not exposed to.
+
+ A quantity is NOT lost when the answer carries it as a digit — "seven" ->
+ "7" is the normalization the whole feature exists to perform, so any digit
+ at all in the output excuses a vanished number word. That is deliberately
+ coarse: pairing each word with its value would need a spelled-number parser
+ per language, and getting it wrong rejects a correct answer.
+
+ Returns ``False`` for any language with no quantity table, like every other
+ frequency-driven check here.
+ """
+ quantities = _QUANTITY_WORDS.get(_language_key(language))
+ if not quantities:
+ return False
+ spoken = {token for token in _compare_tokens(raw) if token in quantities}
+ if not spoken:
+ return False
+ survivors = set(_compare_tokens(out))
+ vanished = spoken - survivors
+ if not vanished:
+ return False
+ # Any digit in the answer that the transcript did not already carry is a
+ # spelled number written out as a numeral. Which word became which digit is
+ # not worth resolving — see the docstring.
+ return not (_digit_runs(out) - _digit_runs(raw))
+
+
def _echoes_delimiter(raw: str, polished: str) -> bool:
"""True when the answer repeats the fence the transcript was sent inside.
@@ -502,6 +611,10 @@ def drift_reason(
) -> str:
"""``""`` when *polished* is safe to deliver; otherwise a short reason code.
+ The guard for the ORDINARY polish pass, where the model was told to change
+ how the text is written and nothing about which words it is made of. Every
+ check runs, the rare-token half of ``lost_term`` included.
+
The checks run cheapest-and-most-unambiguous first, and the returned code is
the FIRST one that fired — it is stored on the history row, so it has to name
the most informative cause rather than the last one evaluated. In particular
@@ -511,6 +624,88 @@ def drift_reason(
Every returned value is a member of :data:`DRIFT_REASONS`.
"""
+ return _polish_drift_reason(
+ raw,
+ polished,
+ language=language,
+ protected=protected,
+ max_shrink=max_shrink,
+ max_growth=max_growth,
+ preserve_rare_tokens=True,
+ )
+
+
+def precision_drift_reason(
+ raw: str,
+ polished: str,
+ *,
+ language: str,
+ protected: Sequence[str],
+ max_shrink: float,
+ max_growth: float,
+) -> str:
+ """The guard for a polish run with PRECISION MODE on.
+
+ Identical to :func:`drift_reason` in every check but one: the rare-token
+ half of ``lost_term`` is skipped. That check rejects an answer in which an
+ uncommon word from the transcript is gone and nothing in the output is a
+ repaired spelling of it — which is the exact shape of the substitution
+ precision mode exists to make ("the program is broken" -> "the application
+ is faulty" loses both ``program`` and ``broken``). Running precision answers
+ through the ordinary guard does not make them safer; it rejects nearly all
+ of them, and the user sees a switch that changes nothing.
+
+ What is traded away is real and worth naming: the rare-token check is the
+ strongest defence against a model quietly replacing a word it did not
+ understand. Everything that survives is what still means something once
+ substitution is licensed —
+
+ * ``empty`` / ``meta_output`` — the model started talking instead of writing;
+ * the word-count band — it may sharpen a sentence, not write a new one;
+ * ``language_flip`` — precision is not a licence to translate;
+ * ``lost_number`` — a quantity is never a wording choice;
+ * ``lost_term`` for PROTECTED terms — names, the wake word and the STT
+ dictionary come from the user, and no register change touches them.
+
+ That is also why the mode ships off and is a deliberate switch: the trade is
+ the user's to make, not ours to make for them.
+
+ Every returned value is a member of :data:`PRECISION_DRIFT_REASONS`.
+ """
+ return _polish_drift_reason(
+ raw,
+ polished,
+ language=language,
+ protected=protected,
+ max_shrink=max_shrink,
+ max_growth=max_growth,
+ preserve_rare_tokens=False,
+ )
+
+
+def _polish_drift_reason(
+ raw: str,
+ polished: str,
+ *,
+ language: str,
+ protected: Sequence[str],
+ max_shrink: float,
+ max_growth: float,
+ preserve_rare_tokens: bool,
+) -> str:
+ """The shared body of the two polish guards above.
+
+ Written once with a flag — deliberately unlike the polish/translate split,
+ which is two functions because those two disagree about what the job IS
+ (a language change is the defect in one and the whole point in the other).
+ These two agree about everything and differ by one check, so a second copy
+ would be an invitation for the checks to drift apart silently: the pair that
+ matters most, ``language_flip`` and the protected-term half of
+ ``lost_term``, must stay byte-identical in both modes.
+
+ The flag is keyword-only and has no default on purpose. Both callers state
+ which contract they want, at the call site, where a reader can see it.
+ """
if not str(polished or "").strip():
return "empty"
if _is_meta_output(raw, polished):
@@ -537,6 +732,14 @@ def drift_reason(
if _digit_runs(raw) - _digit_runs(polished):
return "lost_number"
+ # The spelled-out twin of the check above, and precision-only — see
+ # ``_lost_quantity_word`` for why the ordinary pass is not exposed to this
+ # failure and must not inherit the check.
+ if not preserve_rare_tokens and _lost_quantity_word(
+ raw, polished, language=raw_language if raw_language != "unknown" else language
+ ):
+ return "lost_number"
+
haystack = _token_haystack(polished)
raw_haystack = _token_haystack(raw)
for term in protected or ():
@@ -547,29 +750,38 @@ def drift_reason(
if needle in raw_haystack and needle not in haystack:
return "lost_term"
- # The frequency list has to describe the TEXT, not its label. Where the two
- # disagree the label loses, because trusting it fails silently and
- # completely: an English transcript looked up against the German word list
- # makes every ordinary English word "rare", so the guard fires on any
- # wording change at all and the dictation is delivered unpolished with
- # `rejected_drift` on the row and nothing saying why.
- #
- # The disagreement is real and has its own cause upstream — a segment-sized
- # upload lets Whisper re-decide the language, and on a short segment it
- # sometimes TRANSLATES rather than transcribes, so a row can carry a German
- # tag and an English transcript. That is fixed where it happens; this is the
- # guard declining to compound it. `raw_language` is already computed above,
- # so the correction costs nothing.
- lookup = raw_language if raw_language != "unknown" else language
- vanished = rare_tokens(raw, language=lookup) - rare_tokens(polished, language=lookup)
- if vanished:
- # A vanished rare token is only a LOSS when nothing in the answer stands
- # where it was. Where a corrected spelling does, it is the repair this
- # pass exists to make — see ``_was_repaired`` for why conflating the two
- # disarmed the guard on precisely the transcripts that needed it.
- out_tokens = _compare_tokens(polished)
- if any(not _was_repaired(token, out_tokens) for token in vanished):
- return "lost_term"
+ # Skipped entirely in precision mode, where replacing an uncommon word with
+ # a more precise one is the job rather than the defect. See
+ # :func:`precision_drift_reason` for what is traded away and what still
+ # covers it.
+ if preserve_rare_tokens:
+ # The frequency list has to describe the TEXT, not its label. Where the
+ # two disagree the label loses, because trusting it fails silently and
+ # completely: an English transcript looked up against the German word
+ # list makes every ordinary English word "rare", so the guard fires on
+ # any wording change at all and the dictation is delivered unpolished
+ # with `rejected_drift` on the row and nothing saying why.
+ #
+ # The disagreement is real and has its own cause upstream — a
+ # segment-sized upload lets Whisper re-decide the language, and on a
+ # short segment it sometimes TRANSLATES rather than transcribes, so a row
+ # can carry a German tag and an English transcript. That is fixed where
+ # it happens; this is the guard declining to compound it.
+ # `raw_language` is already computed above, so the correction costs
+ # nothing.
+ lookup = raw_language if raw_language != "unknown" else language
+ vanished = rare_tokens(raw, language=lookup) - rare_tokens(
+ polished, language=lookup
+ )
+ if vanished:
+ # A vanished rare token is only a LOSS when nothing in the answer
+ # stands where it was. Where a corrected spelling does, it is the
+ # repair this pass exists to make — see ``_was_repaired`` for why
+ # conflating the two disarmed the guard on precisely the transcripts
+ # that needed it.
+ out_tokens = _compare_tokens(polished)
+ if any(not _was_repaired(token, out_tokens) for token in vanished):
+ return "lost_term"
return ""
@@ -691,9 +903,11 @@ def translate_drift_reason(
__all__ = [
"DRIFT_REASONS",
+ "PRECISION_DRIFT_REASONS",
"TRANSLATE_DRIFT_REASONS",
"drift_reason",
"normalize_for_compare",
+ "precision_drift_reason",
"rare_tokens",
"translate_drift_reason",
]
diff --git a/jarvis/dictation/polish_prompt.py b/jarvis/dictation/polish_prompt.py
index 6bb2613488..b400d5bd63 100644
--- a/jarvis/dictation/polish_prompt.py
+++ b/jarvis/dictation/polish_prompt.py
@@ -38,7 +38,7 @@ from typing import Final
#: Bumped whenever the wording below changes in a way that could change model
#: behaviour. Stored alongside a polished transcript so a later quality
#: regression can be attributed to a prompt revision rather than a provider.
-POLISH_PROMPT_VERSION: Final[int] = 2
+POLISH_PROMPT_VERSION: Final[int] = 3
#: The delimiters that fence the untrusted transcript inside the user message.
#: Deliberately ugly and unlikely to be dictated by accident; deliberately
@@ -108,6 +108,63 @@ WHAT YOU MAY DO:
WHEN IN DOUBT, CHANGE NOTHING. Returning the input unchanged is always a
correct answer. Rewriting is the exception, not the default."""
+# ---------------------------------------------------------------------------
+# Precision mode — the OPTIONAL word-choice pass on top of the formatter
+# ---------------------------------------------------------------------------
+# The formatter above repairs how a sentence is WRITTEN and is forbidden from
+# touching which words it is made of. This block licenses exactly one further
+# step: replacing a word with a more precise one that means the same thing.
+#
+# It is appended, never merged, and it ships OFF. Two reasons, and both are the
+# whole design:
+#
+# 1. It weakens a guard. The ``lost_term`` rare-token check throws away any
+# answer in which an uncommon word from the transcript vanished — which is
+# precisely what a word replacement looks like from the outside. Precision
+# mode therefore runs against ``precision_drift_reason`` instead, which drops
+# that one check and keeps every other. A user who has not asked for this
+# must not silently lose the stronger guard.
+# 2. The failure direction is known and it is not subtle. Every model asked to
+# "improve wording" reaches for the ornate register — utilize, facilitate,
+# leverage, commence — because that is what its training data marks as
+# "better writing". That is the OPPOSITE of the goal here. So the block
+# spends more words forbidding ornamentation than requesting precision, and
+# the forbidden swaps are named literally rather than described: a model
+# given the rule "prefer plain words" still writes "utilize", and a model
+# given "'use' does not become 'utilize'" does not.
+#
+# The examples are English because the prompt is; the RULES are language-neutral
+# and the model applies them in whatever language it was handed (hard rule 2
+# above still governs, and precision mode never licenses a language change).
+_PRECISION_BLOCK: Final[str] = """\
+PRECISION MODE IS ON. On top of the rules above you may now also sharpen the
+WORD CHOICE:
+- Replace a vague placeholder with the specific word the speaker plainly meant
+ ("the thing that holds the pipe" -> "the bracket").
+- Replace a description of a thing that has an established name with that name
+ ("the list of stuff it needs to run" -> "its dependencies").
+- Cut hedges and empty intensifiers that carry no information ("kind of",
+ "sort of", "basically", "really", "very", "I mean", "you know").
+- Collapse padding into the plain verb ("make a decision" -> "decide",
+ "give an explanation" -> "explain", "is able to" -> "can").
+
+PLAIN, NOT ORNATE — this is the half that goes wrong, so it is a rule and not a
+preference:
+- NEVER swap a common word for a rarer one that means the same thing. "use"
+ does not become "utilize". "help" does not become "facilitate". "start" does
+ not become "commence". "about" does not become "regarding". "so" does not
+ become "consequently". A longer synonym is not a more precise word.
+- NEVER add adjectives, adverbs, metaphors, imagery or flourish. No sentence
+ becomes longer because the result sounds more impressive.
+- Keep the speaker's voice and register. Casual stays casual. Short sentences
+ stay short. You are making them CLEAR, not making them sound clever.
+
+MEANING STILL NEVER CHANGES, and that outranks every line above. A word is only
+more precise if it means the same thing. Where you are not certain what the
+speaker meant, keep their word exactly as they said it — a plain word the
+reader understands beats a sharp one that is wrong."""
+
+
# The language hint is phrased as a WEAK signal on purpose. The tag comes from
# a recognizer that is documented to echo a configured pin back at us (see
# jarvis/core/turn_language.py), so a hard "the input is German" line would tell
@@ -152,6 +209,19 @@ def style_line(style: object) -> str:
return _STYLE_LINES[normalize_style(style)]
+def precision_block() -> str:
+ """The precision-mode clause, ready to append to a system prompt.
+
+ Public and shared with the translate prompt for the same reason
+ :func:`build_protected_block` and :func:`style_line` are: what "sharpen the
+ wording" means to a model is ONE decision. A second copy is how the setting
+ ends up meaning something subtly different depending on whether a
+ translation was involved — and the user would have no way to tell, because
+ both paths report the same status on the same history row.
+ """
+ return _PRECISION_BLOCK
+
+
def build_protected_block(protected_terms: Sequence[str]) -> str:
"""The ``<protected terms>`` block, ready to append to a system prompt.
@@ -166,6 +236,7 @@ def build_polish_prompt(
language: str,
style: str,
protected_terms: Sequence[str],
+ precision: bool = False,
) -> str:
"""Assemble the system prompt for one polish call.
@@ -176,9 +247,21 @@ def build_polish_prompt(
``protected_terms`` are spellings the model must not "correct": the user's
STT dictionary, the wake word, their own name. They are listed, never
described, so the model has nothing to interpret.
+
+ ``precision`` appends the word-choice clause. It defaults to ``False`` so
+ that every existing caller keeps the strict formatter contract it was
+ written against — and so that a caller who forgets the argument gets the
+ SAFER prompt rather than the looser one. The caller that passes ``True``
+ must also switch to
+ :func:`jarvis.dictation.polish_guards.precision_drift_reason`; the two are
+ one decision, and the ordinary guard rejects most precision answers by
+ construction.
"""
parts: list[str] = [_SYSTEM_PROMPT]
+ if precision:
+ parts.append(_PRECISION_BLOCK)
+
hint_language = str(language or "").strip()
if hint_language and hint_language.lower() not in ("auto", "unknown"):
parts.append(_LANGUAGE_HINT.format(language=hint_language))
@@ -241,5 +324,6 @@ __all__ = [
"build_polish_user_message",
"build_protected_block",
"normalize_style",
+ "precision_block",
"style_line",
]
diff --git a/jarvis/dictation/translate_prompt.py b/jarvis/dictation/translate_prompt.py
index 62a40441d8..3aace9a6e7 100644
--- a/jarvis/dictation/translate_prompt.py
+++ b/jarvis/dictation/translate_prompt.py
@@ -37,11 +37,15 @@ from __future__ import annotations
from collections.abc import Sequence
from typing import Final
-from jarvis.dictation.polish_prompt import build_protected_block, style_line
+from jarvis.dictation.polish_prompt import (
+ build_protected_block,
+ precision_block,
+ style_line,
+)
#: Bumped whenever the wording below changes in a way that could change model
#: behaviour, exactly like ``POLISH_PROMPT_VERSION``.
-TRANSLATE_PROMPT_VERSION: Final[int] = 1
+TRANSLATE_PROMPT_VERSION: Final[int] = 2
#: English names for every code ``[dictation].translate_target`` accepts.
#:
@@ -115,6 +119,15 @@ HARD RULES — a violation makes your answer unusable:
4. WRITE IT, DO NOT GLOSS IT. Produce the natural {target} sentence a native
speaker would use to say the same thing, not a word-by-word rendering.
Keep the speaker's register: casual stays casual, formal stays formal.
+ RESTRUCTURE FREELY to get there. The word order, clause order and sentence
+ boundaries of the input carry no meaning and must not survive into {target}
+ when {target} would order them differently — split a long spoken sentence,
+ join two short ones, move the verb, drop a particle that has no {target}
+ equivalent. A sentence that is individually correct but still audibly
+ arranged like the source language has not been translated, only converted.
+ Read your answer back as if you had never seen the input: if it does not
+ sound like something a {target} speaker would have written unprompted,
+ write it again.
5. RETURN ONLY THE {target} TEXT. No preamble, no quotes, no explanation, no
markdown fences, no "Here is", and never the original text alongside it.
@@ -154,6 +167,7 @@ def build_translate_prompt(
target_language: str,
style: str,
protected_terms: Sequence[str],
+ precision: bool = False,
) -> str:
"""Assemble the system prompt for one translate call.
@@ -162,6 +176,13 @@ def build_translate_prompt(
(:func:`jarvis.dictation.polish.resolve_translate_target`), so by the time it
gets here the answer is always "yes, into this".
+ ``precision`` appends the SAME word-choice clause the polish prompt uses
+ (:func:`jarvis.dictation.polish_prompt.precision_block`), so one switch
+ means one thing whether or not a translation is involved. It needs no guard
+ change here, unlike on the polish side: ``translate_drift_reason`` already
+ drops rare-token preservation, because every content word is supposed to
+ change in a translation anyway.
+
The SOURCE language is deliberately not mentioned. The recognizer's tag is
documented-unreliable (it echoes a configured pin back at us, see
``jarvis/core/turn_language.py``), and unlike the polish pass — where a wrong
@@ -175,6 +196,9 @@ def build_translate_prompt(
target = language_display_name(target_language)
parts: list[str] = [_SYSTEM_PROMPT.format(target=target)]
+ if precision:
+ parts.append(precision_block())
+
register = style_line(style)
if register:
parts.append(register)
diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.py
index 9c5b66d12e..f50cb683a1 100644
--- a/jarvis/ui/web/dictation_routes.py
+++ b/jarvis/ui/web/dictation_routes.py
@@ -500,6 +500,17 @@ class SettingsBody(BaseModel):
default=None,
description="Register the polished text is written in",
)
+ polish_precision: bool | None = Field(
+ default=None,
+ description=(
+ "Also sharpen the word choice, not just the writing: a vague "
+ "placeholder becomes the specific word you meant, padding collapses "
+ "into the plain verb. Simple and exact, never ornate — it will not "
+ "reach for a longer synonym to sound impressive. In exchange it "
+ "relaxes one safety check (a rare word may now be replaced), so it "
+ "is off unless you turn it on. Applies to translated dictations too."
+ ),
+ )
# The translate pass. Same FastAPI trap as the polish keys above: an
# undeclared body key is dropped before the handler ever sees it.
translate: bool | None = Field(
@@ -1166,6 +1177,25 @@ _POLISH_SAMPLE = (
"about the rest tomorrow"
)
+#: The sample used INSTEAD when precision mode is on. The one above exercises
+#: the formatter and nothing else — it is already made of plain, specific words,
+#: so a precision run returns the same sentence the ordinary run does, and the
+#: user reads that as "the switch I just turned on does nothing" (AP-31). A dry
+#: run has to show the thing it is testing.
+#:
+#: Shaped like the defect precision mode exists for, and it still carries every
+#: defect the sample above does so the test never gets WEAKER when the mode is
+#: on: fillers, a lower-case restart, no punctuation, a spoken number. On top of
+#: those it adds what only precision may touch — two hedges ("basically",
+#: "kind of"), two padding constructions ("make a decision", "give an
+#: explanation") and one circumlocution for a thing that has a name ("the thing
+#: that stores all our customer data").
+_POLISH_PRECISION_SAMPLE = (
+ "so um i basically want to make a decision about the thing that stores "
+ "all our customer data and i think we should kind of give an explanation "
+ "to the three people who are in charge of it tomorrow"
+)
+
@router.post("/polish/test")
async def test_polish(request: Request) -> dict[str, Any]:
@@ -1186,6 +1216,7 @@ async def test_polish(request: Request) -> dict[str, Any]:
from jarvis.dictation.polish import (
polish_enabled,
polish_transcript,
+ precision_enabled,
resolve_translate_target,
)
@@ -1195,6 +1226,11 @@ async def test_polish(request: Request) -> dict[str, Any]:
# fixed sample is English, so a target of English exercises the
# already-in-target path, which is the honest answer for that setup.
translate_to = resolve_translate_target(cfg)
+ # The sample follows the mode, so the dry run always demonstrates the
+ # settings actually in force rather than a fixed subset of them.
+ sample = (
+ _POLISH_PRECISION_SAMPLE if precision_enabled(cfg) else _POLISH_SAMPLE
+ )
if not polish_enabled(cfg) and not translate_to:
# Reported rather than refused: "you switched it off" is a complete
# answer to "why is my dictation not being polished", and a 409 here
@@ -1205,8 +1241,8 @@ async def test_polish(request: Request) -> dict[str, Any]:
"model": "",
"latency_ms": 0,
"reason": "",
- "sample_in": _POLISH_SAMPLE,
- "sample_out": _POLISH_SAMPLE,
+ "sample_in": sample,
+ "sample_out": sample,
}
pipeline = _pipeline()
@@ -1219,7 +1255,7 @@ async def test_polish(request: Request) -> dict[str, Any]:
log.debug("polish test protected terms unavailable: %s", exc)
result = await polish_transcript(
- _POLISH_SAMPLE,
+ sample,
language="en",
cfg=cfg,
protected_terms=terms,
@@ -1235,6 +1271,6 @@ async def test_polish(request: Request) -> dict[str, Any]:
# next to the status because "rejected_drift" without "lost_term" tells
# a user nothing they can act on.
"reason": result.reason,
- "sample_in": _POLISH_SAMPLE,
+ "sample_in": sample,
"sample_out": result.text,
}
diff --git a/tests/unit/dictation/test_polish_precision.py b/tests/unit/dictation/test_polish_precision.py
new file mode 100644
index 0000000000..be6c5b88c6
--- /dev/null
+++ b/tests/unit/dictation/test_polish_precision.py
@@ -0,0 +1,478 @@
+"""Precision mode — the optional word-choice pass on top of the formatter.
+
+The mode is one prompt clause plus one matched guard, and the reason it needs
+its own test file is that those two must never be separated. The precision
+prompt licenses substitutions (``the program is broken`` -> ``the application
+is faulty``) that the ORDINARY guard rejects as ``lost_term``. Ship the prompt
+without the guard and the feature rejects nearly every one of its own correct
+answers; ship the guard without the prompt and an ordinary polish silently
+loses its strongest protection. So the pairing is asserted directly, in both
+directions, rather than left to a reader of two modules.
+
+The second theme is what precision mode is NOT allowed to cost. Dropping
+rare-token preservation is a real trade, and everything that still stands after
+it — protected terms, quantities, the language, the word-count band, the
+meta-output check — is pinned here so a later prompt revision cannot quietly
+widen the hole.
+
+No network: the pipeline tests use the same recording fake as
+``test_polish_pipeline.py``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+import pytest
+
+from jarvis.core.config import DictationConfig
+from jarvis.core.config_writer import DICTATION_SETTING_KEYS
+from jarvis.dictation import polish
+from jarvis.dictation.polish import polish_transcript, precision_enabled
+from jarvis.dictation.polish_client import POLISH_FAMILIES, PolishFamily
+from jarvis.dictation.polish_guards import (
+ DRIFT_REASONS,
+ PRECISION_DRIFT_REASONS,
+ drift_reason,
+ precision_drift_reason,
+)
+from jarvis.dictation.polish_prompt import (
+ build_polish_prompt,
+ precision_block,
+)
+from jarvis.dictation.translate_prompt import build_translate_prompt
+
+GROQ: PolishFamily = POLISH_FAMILIES[0]
+
+#: The substitution the mode exists for, and the exact shape the ordinary guard
+#: refuses: two uncommon words (``program``, ``broken``) are gone and nothing in
+#: the answer is a repaired spelling of either.
+SHARPEN_RAW = "the program is broken and we need to make a decision about it tomorrow"
+SHARPEN_OUT = "The application is faulty, and we need to decide about it tomorrow."
+
+# The bands the pass actually uses in each mode. Stated here rather than
+# imported so a change to either one has to be made deliberately in two places.
+POLISH_BAND = {"max_shrink": 0.55, "max_growth": 1.20}
+PRECISION_BAND = {"max_shrink": 0.45, "max_growth": 1.35}
+
+
+def _precision_verdict(raw: str, out: str, *, language: str = "en", **kw: Any) -> str:
+ protected = kw.pop("protected", ())
+ return precision_drift_reason(
+ raw, out, language=language, protected=list(protected), **PRECISION_BAND
+ )
+
+
+# --------------------------------------------------------------------------- #
+# The prompt clause
+# --------------------------------------------------------------------------- #
+
+
+def test_the_clause_is_absent_unless_it_is_asked_for() -> None:
+ """The default must be the strict formatter, for every existing caller."""
+ plain = build_polish_prompt(language="en", style="neutral", protected_terms=())
+
+ assert "PRECISION MODE IS ON" not in plain
+ # The word-choice licence must not leak in through some other line.
+ assert "sharpen" not in plain.lower()
+
+
+def test_the_clause_appears_when_it_is_asked_for() -> None:
+ sharpened = build_polish_prompt(
+ language="en", style="neutral", protected_terms=(), precision=True
+ )
+
+ assert "PRECISION MODE IS ON" in sharpened
+ # The hard rules it rides on top of are still there — precision EXTENDS the
+ # formatter contract, it does not replace it.
+ assert "MEANING NEVER CHANGES" in sharpened
+ assert "OUTPUT LANGUAGE = INPUT LANGUAGE" in sharpened
+
+
+def test_the_ornate_register_is_forbidden_by_name() -> None:
+ """The documented failure direction, pinned literally.
+
+ A model told only "prefer plain words" still writes "utilize". Naming the
+ swaps is what stops it, so the naming is the behaviour under test — not an
+ incidental wording choice a later edit may drop.
+ """
+ clause = precision_block()
+
+ for forbidden in ("utilize", "facilitate", "commence"):
+ assert forbidden in clause, f"the {forbidden!r} example carries the rule"
+ assert "PLAIN, NOT ORNATE" in clause
+ # And the licence is bounded by the thing that outranks it.
+ assert "MEANING STILL NEVER CHANGES" in clause
+
+
+def test_one_switch_means_one_thing_across_both_passes() -> None:
+ """The translate prompt appends the SAME clause, not a paraphrase of it.
+
+ Two copies is how the setting ends up meaning something subtly different
+ depending on whether a translation was involved — invisible to the user,
+ because both paths report the same status on the same history row.
+ """
+ translated = build_translate_prompt(
+ target_language="en", style="neutral", protected_terms=(), precision=True
+ )
+ polished = build_polish_prompt(
+ language="de", style="neutral", protected_terms=(), precision=True
+ )
+
+ clause = precision_block()
+ assert clause in translated
+ assert clause in polished
+
+
+def test_the_translate_prompt_is_unchanged_when_precision_is_off() -> None:
+ assert "PRECISION MODE IS ON" not in build_translate_prompt(
+ target_language="en", style="neutral", protected_terms=()
+ )
+
+
+# --------------------------------------------------------------------------- #
+# The guard pairing — the whole reason this file exists
+# --------------------------------------------------------------------------- #
+
+
+def test_the_ordinary_guard_rejects_what_precision_mode_produces() -> None:
+ """The failure this feature would have shipped with, stated out loud.
+
+ If this ever starts passing, the rare-token check has been weakened for
+ EVERY dictation and the precision guard has lost its reason to exist.
+ """
+ assert (
+ drift_reason(SHARPEN_RAW, SHARPEN_OUT, language="en", protected=[], **POLISH_BAND)
+ == "lost_term"
+ )
+
+
+def test_the_precision_guard_accepts_it() -> None:
+ assert _precision_verdict(SHARPEN_RAW, SHARPEN_OUT) == ""
+
+
+def test_precision_reasons_are_a_subset_of_the_ordinary_ones() -> None:
+ """Same vocabulary, never a code the history and the UI have not heard of."""
+ assert set(PRECISION_DRIFT_REASONS) <= set(DRIFT_REASONS)
+
+
+# --------------------------------------------------------------------------- #
+# What precision mode may NOT cost
+# --------------------------------------------------------------------------- #
+
+
+def test_a_protected_term_is_still_untouchable() -> None:
+ """Names, the wake word and the STT dictionary come from the USER.
+
+ They are not frequency data, so no amount of "sharpen the wording"
+ licenses replacing one.
+ """
+ assert (
+ _precision_verdict(
+ "call Anushka about the deployment tomorrow please",
+ "Call her about the deployment tomorrow.",
+ protected=["Anushka"],
+ )
+ == "lost_term"
+ )
+
+
+def test_a_spoken_quantity_may_not_be_dropped() -> None:
+ """The gap the digit check cannot see.
+
+ ``three`` is common vocabulary, so the rare-token filter waved it through
+ even before precision mode removed that filter — and there was never a digit
+ for ``lost_number`` to miss. With substitution licensed, this is how a
+ quantity walks out of a transcript unnoticed.
+ """
+ assert (
+ _precision_verdict(
+ "send it to three people on the team by friday morning",
+ "Send it to the team by Friday morning.",
+ )
+ == "lost_number"
+ )
+
+
+def test_a_quantity_written_as_a_numeral_is_not_a_loss() -> None:
+ """ "seven" -> "7" is the normalization the whole feature exists to make."""
+ assert (
+ _precision_verdict(
+ "send it to three people on the team by friday morning",
+ "Send it to 3 people on the team by Friday morning.",
+ )
+ == ""
+ )
+
+
+ ("raw", "out"),
+ [
+ # An ordinal legitimately disappears when a sentence is restructured.
+ (
+ "the first thing we really need here is basically a proper backup plan",
+ "What we need first is a proper backup plan for the server.",
+ ),
+ # "one" is far more often an article or an impersonal pronoun than a 1.
+ (
+ "one of the things we really need here is kind of a proper backup plan",
+ "One thing we need is a proper backup plan for the server.",
+ ),
+ ],
+)
+def test_ambiguous_number_words_never_veto_an_answer(raw: str, out: str) -> None:
+ """Silence beats a veto — the module's rule, applied to the quantity check.
+
+ Insisting on words that are only sometimes numbers would reject correct
+ sharpenings, and a rejected polish costs the user a usable transcript.
+ """
+ assert _precision_verdict(raw, out) != "lost_number"
+
+
+def test_precision_is_not_a_licence_to_translate() -> None:
+ # i18n-allow: a German transcript is the INPUT DATA this check needs — the
+ # guard can only catch a language flip if one language is not English.
+ assert (
+ _precision_verdict(
+ "wir sollten den Bericht am Dienstag verschicken", # i18n-allow
+ "We should send the report on Tuesday.",
+ language="de",
+ )
+ == "language_flip"
+ )
+
+
+def test_a_model_that_starts_talking_is_still_caught() -> None:
+ assert (
+ _precision_verdict(
+ "should we ship the report on tuesday or wednesday",
+ "Here is the improved version: We should ship on Wednesday.",
+ )
+ == "meta_output"
+ )
+
+
+def test_sharpening_may_not_become_writing() -> None:
+ """The band is wider than the polish one, and still a band."""
+ assert (
+ _precision_verdict(
+ "ship it tuesday",
+ "We should ship the report on Tuesday because the team agreed that "
+ "this is the best possible moment for absolutely everyone involved.",
+ )
+ == "ratio_growth"
+ )
+
+
+def test_a_language_with_no_quantity_table_is_a_no_op() -> None:
+ """~96 of the recognition languages have no table; none of them get a veto."""
+ assert (
+ _precision_verdict(
+ "wyslij to do trzech osob z zespolu do piatku",
+ "Wyslij to do zespolu do piatku w tym tygodniu.",
+ language="pl",
+ )
+ != "lost_number"
+ )
+
+
+def test_the_ordinary_pass_did_not_inherit_the_quantity_check() -> None:
+ """Precision-only, deliberately.
+
+ The ordinary prompt forbids replacing words at all, so this failure needs a
+ prompt violation to reach the guard in the first place — and adding the
+ check there would change the verdict on transcripts that have been passing
+ correctly for months.
+ """
+ assert (
+ drift_reason(
+ "send it to three people on the team by friday morning",
+ "Send it to the team by Friday morning.",
+ language="en",
+ protected=[],
+ **POLISH_BAND,
+ )
+ == ""
+ )
+
+
+# --------------------------------------------------------------------------- #
+# The switch
+# --------------------------------------------------------------------------- #
+
+
+def test_the_switch_ships_off() -> None:
+ """It trades a guard, so it is never inherited from a default."""
+ assert DictationConfig().polish_precision is False
+ assert precision_enabled(DictationConfig()) is False
+
+
+def test_an_older_config_reads_as_off() -> None:
+ """A jarvis.toml that predates the feature must not acquire it silently."""
+
+ class _Ancient:
+ polish = True
+
+ assert precision_enabled(_Ancient()) is False
+
+
+def test_the_switch_survives_a_restart() -> None:
+ """A key missing from the writer allowlist is a setting the UI loses.
+
+ The PUT validates against ``DictationConfig`` and then persists key by key
+ through ``set_dictation_setting``, which refuses anything not listed — so
+ the two have to agree or the save returns 200 and changes nothing.
+ """
+ assert "polish_precision" in DICTATION_SETTING_KEYS
+ assert "polish_precision" in DictationConfig.model_fields
+
+
+def test_the_rest_body_declares_the_key() -> None:
+ """FastAPI DROPS body keys a model does not declare — silently."""
+ from jarvis.ui.web.dictation_routes import SettingsBody
+
+ assert "polish_precision" in SettingsBody.model_fields
+
+
+# --------------------------------------------------------------------------- #
+# End to end, against a fake client
+# --------------------------------------------------------------------------- #
+
+
+@dataclass
+class _Cfg:
+ """Only the keys the pass reads — everything goes through ``getattr``."""
+
+ polish: bool = True
+ polish_precision: bool = False
+ polish_provider: str = "auto"
+ polish_model: str = ""
+ polish_timeout_ms: int = 1200
+ polish_max_input_chars: int = 0
+ polish_min_words: int = 4
+ polish_max_output_tokens: int = 1200
+ polish_temperature: float = 0.0
+ polish_drift_max_shrink: float = 0.55
+ polish_drift_max_growth: float = 1.20
+ polish_style: str = "neutral"
+
+
+@dataclass
+class _FakeClient:
+ reply: str | None = None
+ calls: list[dict[str, Any]] = field(default_factory=list)
+
+ async def complete(
+ self,
+ system: str,
+ user: str,
+ *,
+ max_output_tokens: int,
+ temperature: float,
+ timeout_s: float,
+ ) -> str | None:
+ self.calls.append({"system": system, "user": user})
+ return self.reply
+
+
[email protected](autouse=True)
+def _fresh_state() -> None:
+ polish.reset_polish_state()
+
+
+def _wire(monkeypatch: pytest.MonkeyPatch, client: _FakeClient) -> None:
+ monkeypatch.setattr(polish, "resolve_polish_chain", lambda cfg: (GROQ,))
+ monkeypatch.setattr(polish, "build_polish_client", lambda family, *, model: client)
+
+
+async def test_the_switch_reaches_the_prompt(monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _FakeClient(reply=SHARPEN_OUT)
+ _wire(monkeypatch, client)
+
+ await polish_transcript(SHARPEN_RAW, language="en", cfg=_Cfg(polish_precision=True))
+
+ assert "PRECISION MODE IS ON" in client.calls[0]["system"]
+
+
+async def test_the_switch_off_leaves_the_prompt_strict(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ client = _FakeClient(reply=SHARPEN_OUT)
+ _wire(monkeypatch, client)
+
+ await polish_transcript(SHARPEN_RAW, language="en", cfg=_Cfg())
+
+ assert "PRECISION MODE IS ON" not in client.calls[0]["system"]
+
+
+async def test_a_sharpened_answer_is_delivered(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The end-to-end proof that prompt and guard were switched together.
+
+ With the mode on, the same answer that the ordinary pass rejects arrives at
+ the user. This is the test that fails if a future edit turns the prompt on
+ and leaves the guard behind.
+ """
+ _wire(monkeypatch, _FakeClient(reply=SHARPEN_OUT))
+
+ outcome = await polish_transcript(SHARPEN_RAW, language="en", cfg=_Cfg(polish_precision=True))
+
+ assert outcome.status == "applied"
+ assert outcome.text == SHARPEN_OUT
+
+
+async def test_the_same_answer_is_refused_with_the_mode_off(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """And the user keeps their own words — the contract is unchanged."""
+ _wire(monkeypatch, _FakeClient(reply=SHARPEN_OUT))
+
+ outcome = await polish_transcript(SHARPEN_RAW, language="en", cfg=_Cfg())
+
+ assert outcome.status == "rejected_drift"
+ assert outcome.reason == "lost_term"
+ assert outcome.text == SHARPEN_RAW
+
+
+async def test_precision_applies_to_a_translation_too(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """One switch, one meaning, whichever pass runs."""
+ client = _FakeClient(reply="We should send the report on Tuesday.")
+ _wire(monkeypatch, client)
+
+ outcome = await polish_transcript(
+ # i18n-allow: the transcript being translated OUT of — a translation
+ # test needs a source language, and it cannot be the target.
+ "also wir sollten den Bericht am Dienstag verschicken", # i18n-allow
+ language="de",
+ cfg=_Cfg(polish_precision=True),
+ translate_to="en",
+ )
+
+ assert "PRECISION MODE IS ON" in client.calls[0]["system"]
+ assert outcome.status == "translated"
+
+
+async def test_a_precision_run_still_never_loses_the_text(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The one-sentence contract, re-asserted for the looser mode.
+
+ Relaxing a guard may not relax the promise: a rejected answer still returns
+ the speaker's own words, not the model's.
+ """
+ _wire(monkeypatch, _FakeClient(reply="Call her about the deployment tomorrow."))
+
+ outcome = await polish_transcript(
+ "call Anushka about the deployment tomorrow please",
+ language="en",
+ cfg=_Cfg(polish_precision=True),
+ protected_terms=["Anushka"],
+ )
+
+ assert outcome.status == "rejected_drift"
+ assert outcome.reason == "lost_term"
+ assert outcome.text == "call Anushka about the deployment tomorrow please"