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(modes): the assistant gets a shelf of characters, one of them active

rubenluetke10-beepeb993c29b4e6
diff --git a/jarvis/brain/modes.py b/jarvis/brain/modes.py
new file mode 100644
index 0000000000..fbf9f1dfc8
--- /dev/null
+++ b/jarvis/brain/modes.py
@@ -0,0 +1,712 @@
+"""Assistant modes: a shelf of named characters, one of them active.
+
+A *mode* is how the assistant behaves — the difference between a butler who
+answers in one line and a friend who asks how your day went. Until now there
+was exactly one character (``JARVIS_PERSONA.md``) plus a single-slot override
+(``data/custom_system_prompt.md``). This module turns that one slot into a
+library.
+
+Why a mode is a LAYER, never a replacement
+------------------------------------------
+The packaged persona carries the rules that keep the assistant honest — never
+claim an action that did not happen, never read a path aloud, never invent a
+result. A mode that replaced the whole prompt would drop those rules the moment
+the user picked "Friend", and the failure would look like a personality quirk
+rather than the safety regression it is (the BUG-136 class: a spoken claim that
+ran ahead of reality).
+
+So a mode contributes only a *character block*, appended to the base persona by
+``persona_loader.load_effective_persona_prompt``. The base always wins on
+honesty; the mode decides tone, length, and how much the assistant volunteers.
+The ``assistant`` built-in contributes an EMPTY block on purpose: the default
+mode reproduces today's behaviour byte for byte, so shipping this feature
+changes nothing until the user chooses otherwise.
+
+Where a mode lives
+------------------
+Built-ins are packaged Markdown next to this file (``jarvis/brain/modes/``) —
+readable, forkable, and never written to at runtime. User modes are sidecar
+files under ``DATA_DIR/modes/``, exactly the arrangement
+``persona_loader.custom_prompt_path`` already uses, so "reset" is a delete and
+the packaged set is always recoverable.
+
+Which mode is active
+--------------------
+Two layers, and the split is the whole point:
+
+* ``[persona] active_mode`` in ``jarvis.toml`` — the user's deliberate choice.
+ Sticky, survives a restart, written only through ``config_writer``.
+* An in-memory *section override* — what the Agentic IDE section sets while it
+ is on screen. Deliberately NOT persisted: a mode that a screen switched on
+ must not outlive the process. That is precisely how coding mode became
+ permanently stuck (``AgenticIdeView`` switched it on and nothing ever switched
+ it off), and a non-persisted override makes that class of bug structurally
+ impossible — the worst case is one session, not forever.
+
+Five-layer enum discipline (``docs/anti-drift-three-layer.md``): ``VERBOSITIES``
+and ``PROACTIVITIES`` are the single source of truth here; the Pydantic Literals
+in ``jarvis/ui/web/modes_routes.py`` assert against these tuples at import time,
+and the TypeScript union mirrors them.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+import tempfile
+import threading
+from dataclasses import dataclass, replace
+from pathlib import Path
+
+log = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# Layer 0 — the single source of truth for every enum-like value below.
+# ---------------------------------------------------------------------------
+
+VERBOSITY_BRIEF = "brief"
+VERBOSITY_NORMAL = "normal"
+VERBOSITY_RICH = "rich"
+VERBOSITIES: tuple[str, ...] = (VERBOSITY_BRIEF, VERBOSITY_NORMAL, VERBOSITY_RICH)
+
+PROACTIVITY_REACTIVE = "reactive"
+PROACTIVITY_NORMAL = "normal"
+PROACTIVITY_FORWARD = "forward"
+PROACTIVITIES: tuple[str, ...] = (
+ PROACTIVITY_REACTIVE,
+ PROACTIVITY_NORMAL,
+ PROACTIVITY_FORWARD,
+)
+
+# Built-in slugs. Symbolic so a typo is an AttributeError at import, not a
+# silently missing mode weeks later (defence D1 of the anti-drift doc).
+MODE_ASSISTANT = "assistant"
+MODE_FRIEND = "friend"
+MODE_COACH = "coach"
+MODE_FOCUS = "focus"
+MODE_CODING = "coding"
+BUILTIN_SLUGS: tuple[str, ...] = (
+ MODE_ASSISTANT,
+ MODE_FRIEND,
+ MODE_COACH,
+ MODE_FOCUS,
+ MODE_CODING,
+)
+
+#: The mode in force when the user has never chosen one. Reproduces the
+#: pre-modes behaviour exactly (empty character block).
+DEFAULT_MODE = MODE_ASSISTANT
+
+#: Slug grammar. Restrictive on purpose: the slug becomes a FILE NAME written
+#: by an HTTP route and by a tool the realtime model can call, so anything that
+#: could escape ``modes_dir()`` — separators, dots, absolute paths, NTFS
+#: alternate data streams — must not survive validation.
+_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,47}$")
+
+#: Reserved on Windows regardless of extension; a mode called "con" would create
+#: a file nobody can delete afterwards.
+_WINDOWS_RESERVED = frozenset(
+ {"con", "prn", "aux", "nul"}
+ | {f"com{i}" for i in range(1, 10)}
+ | {f"lpt{i}" for i in range(1, 10)}
+)
+
+_MODE_FILE_SUFFIX = ".md"
+_PACKAGED_DIR_NAME = "modes"
+
+# Guards the in-memory section override. Voice turns, HTTP handlers and the UI
+# poll read it from different threads.
+_override_lock = threading.Lock()
+_section_override: str | None = None
+
+
+class ModeError(ValueError):
+ """A mode could not be resolved, validated, or written."""
+
+
+@dataclass(frozen=True)
+class Mode:
+ """One selectable character.
+
+ ``character`` is the block appended to the base persona — NOT a complete
+ system prompt. Empty means "add nothing", which is what ``assistant`` does.
+ """
+
+ slug: str
+ name: str
+ emoji: str
+ description: str
+ character: str
+ built_in: bool = False
+ #: TTS voice id this mode prefers. Empty keeps the configured voice — a
+ #: mode that named a voice the active provider does not have would
+ #: otherwise mute the assistant rather than merely sounding wrong.
+ voice: str = ""
+ verbosity: str = VERBOSITY_NORMAL
+ proactivity: str = PROACTIVITY_NORMAL
+
+ def to_payload(self) -> dict[str, object]:
+ """JSON-ready shape shared by the REST routes and the CLI."""
+ return {
+ "slug": self.slug,
+ "name": self.name,
+ "emoji": self.emoji,
+ "description": self.description,
+ "character": self.character,
+ "built_in": self.built_in,
+ "voice": self.voice,
+ "verbosity": self.verbosity,
+ "proactivity": self.proactivity,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Paths
+# ---------------------------------------------------------------------------
+
+
+def packaged_modes_dir() -> Path:
+ """Directory holding the shipped built-in mode files (read-only)."""
+ return Path(__file__).resolve().parent / _PACKAGED_DIR_NAME
+
+
+def modes_dir() -> Path:
+ """Directory holding the user's own modes.
+
+ Resolved at call time from ``jarvis.core.config.DATA_DIR`` — the same
+ convention ``persona_loader.custom_prompt_path`` follows — so tests can
+ redirect it and a headless install can relocate the whole data directory.
+ """
+ from jarvis.core import config as core_config
+
+ return core_config.DATA_DIR / _PACKAGED_DIR_NAME
+
+
+def _mode_path(slug: str) -> Path:
+ return modes_dir() / f"{slug}{_MODE_FILE_SUFFIX}"
+
+
+# ---------------------------------------------------------------------------
+# Validation
+# ---------------------------------------------------------------------------
+
+
+def normalize_slug(raw: str) -> str:
+ """Turn a human name into a safe slug, or raise ``ModeError``.
+
+ Accepts what a person types ("My Friend Mode") and returns ``my-friend-mode``.
+ Rejects anything that would not round-trip as a plain file name.
+ """
+ text = (raw or "").strip().lower()
+ # Path-shaped input is refused rather than repaired. Stripping the illegal
+ # characters below would already make traversal impossible (the grammar has
+ # no dots and no separators, so the result cannot leave ``modes_dir()``),
+ # but it would turn "/etc/passwd" into a mode cheerfully named "etcpasswd".
+ # This slug can arrive from a tool the realtime model calls; a caller that
+ # hands over a path has made a mistake and should hear about it.
+ if any(sep in text for sep in ("/", "\\", ":")) or ".." in text:
+ raise ModeError(f"{raw!r} looks like a path, not a mode name.")
+ text = text.replace("_", "-").replace(" ", "-")
+ # Drop everything outside the grammar rather than escaping it: a slug is a
+ # label, and a silently escaped one is unreadable in the UI and the CLI.
+ text = re.sub(r"[^a-z0-9-]", "", text)
+ text = re.sub(r"-{2,}", "-", text).strip("-")
+ if not text or not _SLUG_RE.match(text):
+ raise ModeError(
+ f"{raw!r} does not produce a usable mode id. Use letters, digits and "
+ "hyphens (1-48 characters)."
+ )
+ if text in _WINDOWS_RESERVED:
+ raise ModeError(f"{text!r} is a reserved device name on Windows. Pick another name.")
+ return text
+
+
+def _validate_choice(value: str, allowed: tuple[str, ...], field: str) -> str:
+ candidate = (value or "").strip().lower()
+ if not candidate:
+ return allowed[allowed.index("normal")] if "normal" in allowed else allowed[0]
+ if candidate not in allowed:
+ raise ModeError(f"{field} must be one of {', '.join(allowed)} — got {value!r}.")
+ return candidate
+
+
+# ---------------------------------------------------------------------------
+# Reading
+# ---------------------------------------------------------------------------
+
+
+def _parse_mode_file(path: Path, *, built_in: bool) -> Mode | None:
+ """Read one ``<slug>.md`` into a :class:`Mode`, or ``None`` when unusable.
+
+ A corrupt mode file degrades to "this mode does not exist" instead of
+ raising: the file sits in a user-writable directory, and one bad hand-edit
+ must not take down the mode list (or, through the persona layer, every turn).
+ """
+ try:
+ text = path.read_text(encoding="utf-8-sig")
+ except OSError as exc:
+ log.warning("Mode %s unreadable (%s) — skipped.", path.name, exc)
+ return None
+
+ from jarvis.memory.frontmatter import parse_frontmatter
+
+ meta, body = parse_frontmatter(text)
+ if not isinstance(meta, dict):
+ meta = {}
+ slug = path.stem.lower()
+ try:
+ slug = normalize_slug(slug)
+ except ModeError:
+ log.warning("Mode file %s has an unusable name — skipped.", path.name)
+ return None
+
+ def _str(key: str, default: str = "") -> str:
+ value = meta.get(key, default)
+ return value.strip() if isinstance(value, str) else default
+
+ try:
+ verbosity = _validate_choice(_str("verbosity"), VERBOSITIES, "verbosity")
+ proactivity = _validate_choice(_str("proactivity"), PROACTIVITIES, "proactivity")
+ except ModeError as exc:
+ # A hand-edited typo costs the knob, not the mode.
+ log.warning("Mode %s: %s — falling back to the normal setting.", slug, exc)
+ verbosity, proactivity = VERBOSITY_NORMAL, PROACTIVITY_NORMAL
+
+ return Mode(
+ slug=slug,
+ name=_str("name") or slug.replace("-", " ").title(),
+ emoji=_str("emoji"),
+ description=_str("description"),
+ character=body.strip(),
+ built_in=built_in,
+ voice=_str("voice"),
+ verbosity=verbosity,
+ proactivity=proactivity,
+ )
+
+
+def _read_dir(directory: Path, *, built_in: bool) -> dict[str, Mode]:
+ found: dict[str, Mode] = {}
+ try:
+ entries = sorted(directory.glob(f"*{_MODE_FILE_SUFFIX}"))
+ except OSError:
+ return found
+ for path in entries:
+ mode = _parse_mode_file(path, built_in=built_in)
+ if mode is not None:
+ found[mode.slug] = mode
+ return found
+
+
+def list_modes() -> tuple[Mode, ...]:
+ """Every available mode: built-ins first, then the user's own, A-Z.
+
+ A user file whose name collides with a built-in slug WINS — that is how
+ "copy a built-in and tweak it" works — but it keeps the ``built_in`` flag
+ so the UI can still offer "restore the original" rather than pretending the
+ packaged version is gone.
+ """
+ builtins = _read_dir(packaged_modes_dir(), built_in=True)
+ overrides = _read_dir(modes_dir(), built_in=False)
+
+ merged: dict[str, Mode] = dict(builtins)
+ for slug, mode in overrides.items():
+ merged[slug] = replace(mode, built_in=slug in builtins)
+
+ ordered = [merged[s] for s in BUILTIN_SLUGS if s in merged]
+ ordered.extend(
+ sorted(
+ (m for s, m in merged.items() if s not in BUILTIN_SLUGS),
+ key=lambda m: m.name.lower(),
+ )
+ )
+ return tuple(ordered)
+
+
+def get_mode(slug: str) -> Mode | None:
+ """One mode by slug, or ``None`` when there is no such mode."""
+ try:
+ wanted = normalize_slug(slug)
+ except ModeError:
+ return None
+ for mode in list_modes():
+ if mode.slug == wanted:
+ return mode
+ return None
+
+
+def has_user_copy(slug: str) -> bool:
+ """True when the user has their own file for this slug (built-in or not)."""
+ try:
+ return _mode_path(normalize_slug(slug)).is_file()
+ except (ModeError, OSError):
+ return False
+
+
+# ---------------------------------------------------------------------------
+# Which mode is active
+# ---------------------------------------------------------------------------
+
+
+def _configured_slug() -> str:
+ """The user's sticky choice from ``[persona] active_mode``."""
+ try:
+ from jarvis.core.config import get_config
+
+ raw = getattr(getattr(get_config(), "persona", None), "active_mode", "")
+ except Exception: # noqa: BLE001 - config unavailable mid-reload
+ return DEFAULT_MODE
+ slug = (raw or "").strip().lower()
+ return slug or DEFAULT_MODE
+
+
+def active_slug() -> str:
+ """The slug in force for this turn — section override first, then config.
+
+ Falls back to :data:`DEFAULT_MODE` when the stored slug names a mode that no
+ longer exists (deleted by hand, or a config carried to another machine).
+ Silence here would be wrong in the other direction: the user would keep
+ seeing a mode name the assistant is not actually running.
+ """
+ with _override_lock:
+ override = _section_override
+ candidate = override or _configured_slug()
+ if get_mode(candidate) is not None:
+ return candidate
+ if override is not None:
+ log.warning("Section override %r names no known mode — ignoring it.", override)
+ elif candidate != DEFAULT_MODE:
+ log.warning(
+ "Active mode %r no longer exists — falling back to %s.", candidate, DEFAULT_MODE
+ )
+ return DEFAULT_MODE
+
+
+def active_mode() -> Mode:
+ """The mode in force for this turn. Never ``None``."""
+ mode = get_mode(active_slug())
+ if mode is not None:
+ return mode
+ # Neither the chosen mode nor the packaged default could be read — a broken
+ # install. An empty character block is the honest answer: base persona only.
+ return Mode(
+ slug=DEFAULT_MODE,
+ name="Assistant",
+ emoji="",
+ description="",
+ character="",
+ built_in=True,
+ )
+
+
+def set_active(slug: str) -> Mode:
+ """Persist the user's mode choice. Applies on the next turn, no restart.
+
+ Raises ``ModeError`` when the slug names no known mode — writing a pointer
+ to a mode that does not exist would show a name in the UI that the assistant
+ is not running.
+ """
+ mode = get_mode(slug)
+ if mode is None:
+ raise ModeError(f"No mode called {slug!r}.")
+
+ from jarvis.core import config_writer
+
+ config_writer.set_active_mode(mode.slug)
+ log.info("Active mode set to %s.", mode.slug)
+ return mode
+
+
+def set_section_override(slug: str | None) -> str | None:
+ """Set (or clear with ``None``) the screen-scoped mode.
+
+ In-memory only, by design — see the module docstring. Returns the slug now
+ in force, so the caller can report what actually happened rather than what
+ it asked for.
+ """
+ global _section_override
+ if slug is None:
+ with _override_lock:
+ _section_override = None
+ return active_slug()
+ if get_mode(slug) is None:
+ raise ModeError(f"No mode called {slug!r}.")
+ with _override_lock:
+ _section_override = normalize_slug(slug)
+ return active_slug()
+
+
+def section_override() -> str | None:
+ """The screen-scoped mode currently in force, if any."""
+ with _override_lock:
+ return _section_override
+
+
+# ---------------------------------------------------------------------------
+# Writing
+# ---------------------------------------------------------------------------
+
+
+def _atomic_write(path: Path, text: str) -> None:
+ """Write UTF-8 without a BOM via tempfile + ``os.replace`` (AP-7)."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp_name = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.stem}.", suffix=".tmp")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh:
+ fh.write(text)
+ os.replace(tmp_name, path)
+ except BaseException:
+ try:
+ os.unlink(tmp_name)
+ except OSError:
+ pass
+ raise
+
+
+def save_mode(
+ *,
+ slug: str,
+ name: str,
+ character: str,
+ emoji: str = "",
+ description: str = "",
+ voice: str = "",
+ verbosity: str = VERBOSITY_NORMAL,
+ proactivity: str = PROACTIVITY_NORMAL,
+) -> Mode:
+ """Create or replace a user mode. Returns the mode as it was stored.
+
+ Editing a built-in is allowed and writes a user copy alongside the packaged
+ file; the packaged one is never touched, so ``restore_builtin`` is a delete.
+ """
+ safe_slug = normalize_slug(slug)
+ display = (name or "").strip() or safe_slug.replace("-", " ").title()
+ body = (character or "").strip()
+ if not body:
+ raise ModeError("A mode needs a character description — an empty one changes nothing.")
+
+ mode = Mode(
+ slug=safe_slug,
+ name=display,
+ emoji=(emoji or "").strip(),
+ description=(description or "").strip(),
+ character=body,
+ built_in=safe_slug in BUILTIN_SLUGS,
+ voice=(voice or "").strip(),
+ verbosity=_validate_choice(verbosity, VERBOSITIES, "verbosity"),
+ proactivity=_validate_choice(proactivity, PROACTIVITIES, "proactivity"),
+ )
+
+ from jarvis.memory.frontmatter import write_frontmatter
+
+ meta: dict[str, object] = {
+ "name": mode.name,
+ "emoji": mode.emoji,
+ "description": mode.description,
+ "voice": mode.voice,
+ "verbosity": mode.verbosity,
+ "proactivity": mode.proactivity,
+ }
+ _atomic_write(_mode_path(safe_slug), write_frontmatter(meta, mode.character))
+ log.info("Mode %s saved.", safe_slug)
+ return mode
+
+
+def delete_mode(slug: str) -> bool:
+ """Remove a user mode (or a user copy of a built-in). Idempotent.
+
+ Deleting the mode that is currently active resets the pointer to
+ :data:`DEFAULT_MODE` rather than leaving a dangling name on screen.
+ """
+ safe_slug = normalize_slug(slug)
+ if safe_slug in BUILTIN_SLUGS and not has_user_copy(safe_slug):
+ raise ModeError(f"{safe_slug!r} is a built-in mode and cannot be deleted.")
+
+ try:
+ _mode_path(safe_slug).unlink()
+ removed = True
+ except FileNotFoundError:
+ removed = False
+ except OSError as exc:
+ raise ModeError(f"Could not delete {safe_slug!r}: {exc}") from exc
+
+ if removed and _configured_slug() == safe_slug and get_mode(safe_slug) is None:
+ try:
+ from jarvis.core import config_writer
+
+ config_writer.set_active_mode(DEFAULT_MODE)
+ except Exception as exc: # noqa: BLE001 - the delete already happened
+ log.warning("Deleted the active mode but could not reset the pointer: %s", exc)
+ with _override_lock:
+ stale_override = _section_override == safe_slug
+ if stale_override:
+ set_section_override(None)
+ return removed
+
+
+def restore_builtin(slug: str) -> bool:
+ """Drop the user's copy of a built-in so the packaged version applies again."""
+ safe_slug = normalize_slug(slug)
+ if safe_slug not in BUILTIN_SLUGS:
+ raise ModeError(f"{safe_slug!r} is not a built-in mode.")
+ try:
+ _mode_path(safe_slug).unlink()
+ return True
+ except FileNotFoundError:
+ return False
+ except OSError as exc:
+ raise ModeError(f"Could not restore {safe_slug!r}: {exc}") from exc
+
+
+# ---------------------------------------------------------------------------
+# Migration from the single-slot custom prompt
+# ---------------------------------------------------------------------------
+
+MIGRATED_SLUG = "my-mode"
+
+
+def migrate_legacy_custom_prompt() -> str | None:
+ """Adopt an existing ``custom_system_prompt.md`` as a normal mode.
+
+ Runs at most once: the legacy file is left in place (so a downgrade still
+ works and nothing the user wrote is destroyed) and the copy is only made
+ when no mode with that slug exists yet. Returns the slug it created, or
+ ``None`` when there was nothing to migrate.
+
+ The migrated mode is NOT activated. The legacy file is still honoured by
+ ``persona_loader`` for exactly that reason — the user's words keep applying
+ either way, and the migration only makes them switchable.
+ """
+ from jarvis.brain import persona_loader
+
+ legacy = persona_loader.read_custom_prompt()
+ if not legacy:
+ return None
+ if _mode_path(MIGRATED_SLUG).is_file():
+ return None
+ try:
+ save_mode(
+ slug=MIGRATED_SLUG,
+ name="My Mode",
+ emoji="✍️",
+ description="The custom system prompt you wrote before modes existed.",
+ character=legacy,
+ )
+ except (ModeError, OSError) as exc:
+ log.warning("Could not migrate the custom system prompt into a mode: %s", exc)
+ return None
+ log.info("Migrated the custom system prompt into the %r mode.", MIGRATED_SLUG)
+ return MIGRATED_SLUG
+
+
+# ---------------------------------------------------------------------------
+# Compiling a mode into prompt text
+# ---------------------------------------------------------------------------
+
+_VERBOSITY_LINES = {
+ VERBOSITY_BRIEF: (
+ "Answer in as few words as carry the meaning — usually one or two "
+ "sentences. Do not summarise what you just did unless asked."
+ ),
+ VERBOSITY_NORMAL: "",
+ VERBOSITY_RICH: (
+ "Give the reasoning as well as the answer: what you considered, what you "
+ "ruled out, and why. Detail is welcome as long as every sentence earns "
+ "its place."
+ ),
+}
+
+_PROACTIVITY_LINES = {
+ PROACTIVITY_REACTIVE: (
+ "Answer what was asked and stop. Do not suggest next steps, do not offer "
+ "related work, and do not raise topics the user did not open."
+ ),
+ PROACTIVITY_NORMAL: "",
+ PROACTIVITY_FORWARD: (
+ "Think a step ahead: name the thing the user has not thought of yet, "
+ "flag what is about to become a problem, and offer the obvious next move."
+ ),
+}
+
+_BLOCK_HEADER = "ACTIVE MODE"
+
+
+def mode_prompt_block(mode: Mode) -> str:
+ """The text a mode contributes to the system prompt. ``""`` adds nothing.
+
+ Deliberately closes with a precedence line. Without it, a mode that says
+ "be casual and just go for it" reads as permission to skip the honesty rules
+ in the base persona, and the model has no way to know which instruction is
+ the standing one.
+ """
+ parts = [line for line in (mode.character.strip(),) if line]
+ for line in (
+ _VERBOSITY_LINES.get(mode.verbosity, ""),
+ _PROACTIVITY_LINES.get(mode.proactivity, ""),
+ ):
+ if line:
+ parts.append(line)
+ if not parts:
+ return ""
+
+ label = f"{mode.emoji} {mode.name}".strip() if mode.emoji else mode.name
+ body = "\n\n".join(parts)
+ return (
+ f"{_BLOCK_HEADER}: {label}\n"
+ "This is how you behave right now. It changes your tone, your length "
+ "and what you volunteer — it never overrides the rules above about "
+ "honesty, about only claiming actions you actually took, or about what "
+ "is safe to say out loud. Where this section and those rules disagree, "
+ f"those rules win.\n\n{body}"
+ )
+
+
+def active_prompt_block() -> str:
+ """The prompt contribution of whichever mode is active. Never raises."""
+ try:
+ return mode_prompt_block(active_mode())
+ except Exception as exc: # noqa: BLE001 - a mode must never break a turn
+ log.warning("Mode block unavailable (%s) — running the base persona.", exc)
+ return ""
+
+
+def active_voice() -> str:
+ """TTS voice the active mode prefers, or ``""`` to keep the configured one."""
+ try:
+ return active_mode().voice
+ except Exception: # noqa: BLE001 - never let a mode mute the assistant
+ return ""
+
+
+__all__ = [
+ "BUILTIN_SLUGS",
+ "DEFAULT_MODE",
+ "MODE_ASSISTANT",
+ "MODE_CODING",
+ "MODE_COACH",
+ "MODE_FOCUS",
+ "MODE_FRIEND",
+ "PROACTIVITIES",
+ "VERBOSITIES",
+ "Mode",
+ "ModeError",
+ "active_mode",
+ "active_prompt_block",
+ "active_slug",
+ "active_voice",
+ "delete_mode",
+ "get_mode",
+ "has_user_copy",
+ "list_modes",
+ "migrate_legacy_custom_prompt",
+ "mode_prompt_block",
+ "modes_dir",
+ "normalize_slug",
+ "packaged_modes_dir",
+ "restore_builtin",
+ "save_mode",
+ "section_override",
+ "set_active",
+ "set_section_override",
+]
diff --git a/jarvis/brain/modes/assistant.md b/jarvis/brain/modes/assistant.md
new file mode 100644
index 0000000000..5e7ddf9e79
--- /dev/null
+++ b/jarvis/brain/modes/assistant.md
@@ -0,0 +1,8 @@
+---
+name: Assistant
+emoji: 🎩
+description: Precise and quiet. Does the task, says what happened, stops.
+voice: ""
+verbosity: normal
+proactivity: normal
+---
diff --git a/jarvis/brain/modes/coach.md b/jarvis/brain/modes/coach.md
new file mode 100644
index 0000000000..60da7faed5
--- /dev/null
+++ b/jarvis/brain/modes/coach.md
@@ -0,0 +1,29 @@
+---
+name: Coach
+emoji: 🎯
+description: Holds you to what you said you would do. Checks in, no excuses.
+voice: ""
+verbosity: normal
+proactivity: forward
+---
+
+Your job is to keep the user moving toward what they said they wanted, not to
+make them comfortable.
+
+Hold the thread. When they told you a goal, a deadline, or a habit, bring it up
+again — at the start of a session, when they drift, and when they quietly drop
+it. "You said you would finish this by Friday. Where is it?" is a normal thing
+for you to say.
+
+Push on vagueness. "Soon", "I'll look into it", and "kind of" are not answers.
+Ask for the specific next action, who does it, and by when. If they cannot name
+one, help them cut the task down until they can.
+
+Do not accept an excuse at face value, and do not moralise about it either.
+Name what actually blocked them, ask what would remove that block, and move on.
+One question is worth more than a paragraph of encouragement.
+
+Give credit only when it is earned, and be specific about what earned it.
+Constant praise is noise; rare praise is information.
+
+Keep it short. A coach who lectures is being ignored.
diff --git a/jarvis/brain/modes/coding.md b/jarvis/brain/modes/coding.md
new file mode 100644
index 0000000000..e9342405be
--- /dev/null
+++ b/jarvis/brain/modes/coding.md
@@ -0,0 +1,29 @@
+---
+name: Coding
+emoji: 🖥️
+description: Terminal-aware. Talks about your open agents and what they are doing.
+voice: ""
+verbosity: normal
+proactivity: normal
+---
+
+The user is working in the Agentic IDE with terminals open, and you can see
+what is in them.
+
+Talk about the panes the way a colleague sitting next to them would: by
+call-sign, in the present tense, and about what is actually on screen. "Kai is
+still on the wake path, Nova finished and is waiting" beats any summary of what
+you assume is happening.
+
+When they hand work to a named agent, that is where it goes. Do not quietly
+start a background worker instead, and do not answer as though you had done the
+work yourself.
+
+Never report a pane as finished, started, or briefed unless the terminal
+content in front of you shows it. A pane with a brief still being composed is
+not a pane that has been briefed. When you do not know the state of something,
+say you will check rather than guessing — a wrong status here sends the user
+looking in the wrong place.
+
+Use their vocabulary: panes, terminals, call-signs, briefs. Keep answers short
+while work is running; they are reading output, not you.
diff --git a/jarvis/brain/modes/focus.md b/jarvis/brain/modes/focus.md
new file mode 100644
index 0000000000..f20e9bd7ad
--- /dev/null
+++ b/jarvis/brain/modes/focus.md
@@ -0,0 +1,27 @@
+---
+name: Focus
+emoji: 🔇
+description: One-line answers. Nothing volunteered. Get out of the way.
+voice: ""
+verbosity: brief
+proactivity: reactive
+---
+
+The user is concentrating on something that is not you. Cost them as little
+attention as possible.
+
+Answer in one line where one line is true. Two if it is not. Never three.
+
+No preamble, no restating the question, no summary at the end, no offer of
+further help. If the answer is a single word or a single number, that is the
+whole message.
+
+Volunteer nothing. No suggestions, no related information, no "you might also
+want to". If something genuinely urgent comes up — something breaking, or a
+mistake about to be made — say it in one sentence and stop.
+
+When a task takes a while, say nothing until it is done, then report the result
+in one line.
+
+If the honest answer is long, say the short version first and offer the rest in
+four words: "Want the full version?"
diff --git a/jarvis/brain/modes/friend.md b/jarvis/brain/modes/friend.md
new file mode 100644
index 0000000000..6e6bf114e1
--- /dev/null
+++ b/jarvis/brain/modes/friend.md
@@ -0,0 +1,31 @@
+---
+name: Friend
+emoji: 🫂
+description: Warm and casual. Has opinions, pushes back, asks how you are.
+voice: ""
+verbosity: normal
+proactivity: normal
+---
+
+You are talking to a friend, not serving a client. Drop the deference.
+
+Talk the way someone does who knows the user and likes them: contractions,
+short sentences, the occasional joke, no formal openings and no "certainly" or
+"of course". Never call them sir.
+
+Have actual opinions and say them first, before the caveats. When you think an
+idea is weak, say so plainly and say why — a friend who agrees with everything
+is no use to anyone. When you think it is good, say that too, without hedging
+it into mush.
+
+Notice the person, not just the task. If they sound tired, frustrated, or
+pleased with something, respond to that before the work. If they mention
+something from their life, remember it and come back to it later. Ask a real
+question now and then instead of only answering them.
+
+Small talk is allowed. Silence is allowed. You do not have to end every message
+with an offer to help.
+
+What does not change: when they ask you to do something, you do it properly and
+you tell them honestly how it went. Being warm never means softening bad news
+or pretending something worked.
diff --git a/jarvis/brain/persona_loader.py b/jarvis/brain/persona_loader.py
index 5f6ff0f08b..d2d6887265 100644
--- a/jarvis/brain/persona_loader.py
+++ b/jarvis/brain/persona_loader.py
@@ -175,12 +175,17 @@ def default_persona_prompt() -> str:
return load_persona_prompt()
-def load_effective_persona_prompt(*, compact: bool = False) -> str:
- """The persona block the brain should use: custom override if set, else default.
+def base_persona_prompt(*, compact: bool = False) -> str:
+ """The persona WITHOUT the active mode layered on: custom override, else default.
The custom override wins EVEN in compact mode — the user chose those
exact words for their assistant, and user autonomy outranks the latency
optimization (the trade-off is documented on the settings surface).
+
+ Callers that build the brain's prompt want
+ :func:`load_effective_persona_prompt` instead; this one exists for the
+ settings surface, which edits the base text and must not show the user a
+ mode block they cannot edit there.
"""
custom = read_custom_prompt()
if custom is not None:
@@ -190,6 +195,35 @@ def load_effective_persona_prompt(*, compact: bool = False) -> str:
return default_persona_prompt()
+def load_effective_persona_prompt(*, compact: bool = False) -> str:
+ """The full persona the brain should use: the base plus the active mode.
+
+ This is the ONE place the assistant's character is assembled, which is why
+ a mode switch reaches the typing brain (``BrainManager._build_system_prompt``)
+ and the speaking brain (``jarvis.realtime.session``) at the same moment and
+ without a restart — both read this function fresh on every turn.
+
+ The mode is appended, never substituted. The base carries the standing rules
+ about honesty and about what is safe to say aloud; a mode that replaced it
+ would drop those rules the moment somebody picked a chattier character, and
+ the regression would read as a personality quirk rather than a safety bug.
+
+ The default ``assistant`` mode contributes an empty block, so an install
+ that never touches modes produces byte-identical prompts to before.
+ """
+ base = base_persona_prompt(compact=compact)
+ try:
+ from .modes import active_prompt_block
+
+ block = active_prompt_block()
+ except Exception as exc: # noqa: BLE001 - a mode must never break a turn
+ log.warning("Mode layer unavailable (%s) — base persona only.", exc)
+ return base
+ if not block:
+ return base
+ return f"{base}\n\n{block}" if base else block
+
+
def save_custom_prompt(text: str) -> None:
"""Persist a custom system prompt atomically (tempfile + ``os.replace``).
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index b1a5933d6a..db6bdb5b55 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -246,6 +246,17 @@ class PersonaConfig(BaseModel):
# silently broken by a future base-class / project-wide model_config change.
model_config = ConfigDict(extra="ignore")
+ # Which assistant mode is active — the user's deliberate, sticky choice
+ # (``jarvis.brain.modes``). Deliberately a free string rather than a
+ # Literal: user-created modes are the point of the feature, so the closed
+ # set lives in ``modes.BUILTIN_SLUGS`` and an unknown value degrades to the
+ # default at read time instead of failing config validation at boot.
+ #
+ # NOT the whole story on purpose: the Agentic IDE's screen-scoped override
+ # is in-memory only and never reaches this file, so a mode a screen turned
+ # on can never outlive the process.
+ active_mode: str = "assistant"
+
class WakeWordConfig(BaseModel):
"""User-editable ``[trigger.wake_word]`` — the custom-wake-word config.
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index d10159e2cf..e9e2e6ff27 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -1202,6 +1202,22 @@ def set_overlay_style(style: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
_patch_table(path, "ui", "orb_style", style)
+def set_active_mode(slug: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Persist the active assistant mode to ``[persona] active_mode``.
+
+ ``slug`` is a mode id from ``jarvis.brain.modes`` — a built-in or one the
+ user created. Validation belongs to ``modes.set_active`` (it is the layer
+ that knows which modes exist); this function only writes.
+
+ TOML-only by design, same rationale as :func:`set_overlay_style`:
+ ``persona.active_mode`` is not in the drift-guard's reference snapshot, so
+ it is never reverted, and no ENV override reads it — a second layer would
+ be a lie about where the value lives. No restart is needed either way,
+ because the persona layer re-reads the pointer on every turn.
+ """
+ _patch_table(path, "persona", "active_mode", slug)
+
+
def set_computer_use_engine(engine: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the active Computer-Use engine to ``[computer_use] engine``.
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index cc9900f2ed..e51e0daf16 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -2031,7 +2031,10 @@ class SystemPromptBody(BaseModel):
def _system_prompt_payload() -> dict[str, object]:
from jarvis.brain import persona_loader
- content = persona_loader.load_effective_persona_prompt()
+ # The BASE persona, not the effective one: this editor writes the base text
+ # back, so showing the active mode's block here would let the user "edit" a
+ # block that the mode owns and then silently lose it on save.
+ content = persona_loader.base_persona_prompt()
return {
"content": content,
"is_custom": persona_loader.has_custom_prompt(),
diff --git a/pyproject.toml b/pyproject.toml
index c6e4865bd6..0ab955a431 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -776,6 +776,10 @@ jarvis = [
# allowlist (skills/authoring/draft_writer.py), Jarvis-Agent critic
# verdict JSON-schema (core/review/spawns.py).
"brain/JARVIS_PERSONA.md",
+ # Built-in assistant modes (brain/modes.py::packaged_modes_dir). Missing
+ # here, a wheel install would show an empty mode list and silently fall
+ # back to the base persona — the same class of bug as the note above.
+ "brain/modes/*.md",
"skills/safe_imports.txt",
"core/review/verdict_schema.json",
# Seed catalogs (CLI tools / skills / marketplace plugins) — named
diff --git a/tests/unit/brain/test_modes.py b/tests/unit/brain/test_modes.py
new file mode 100644
index 0000000000..2585466b5b
--- /dev/null
+++ b/tests/unit/brain/test_modes.py
@@ -0,0 +1,265 @@
+"""Assistant modes: a shelf of named characters, one of them active.
+
+Feature 2026-08-13. These lock the four contracts everything else depends on:
+
+1. The default mode changes NOTHING — an install that never opens the modes
+ screen produces the same system prompt as before the feature existed.
+2. A mode is layered on the base persona, never substituted for it, so the
+ honesty rules survive picking a chattier character.
+3. A slug becomes a file name, and it can arrive from a tool the realtime model
+ calls — so anything path-shaped is refused, not quietly repaired.
+4. The screen-scoped override is in-memory only. That is the structural reason
+ coding mode can no longer get permanently stuck (the pre-2026-08-13 bug:
+ ``AgenticIdeView`` switched it on and nothing ever switched it off).
+"""
+from __future__ import annotations
+
+import pytest
+
+import jarvis.core.config as core_config
+from jarvis.brain import modes, persona_loader
+
+
[email protected](autouse=True)
+def _isolate(tmp_path, monkeypatch: pytest.MonkeyPatch):
+ """User modes go to a throwaway dir; the active pointer never hits jarvis.toml."""
+ monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)
+ stored: dict[str, str] = {}
+ monkeypatch.setattr(modes, "_configured_slug", lambda: stored.get("slug", modes.DEFAULT_MODE))
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_active_mode",
+ lambda slug, **_kw: stored.__setitem__("slug", slug),
+ )
+ modes.set_section_override(None)
+ yield tmp_path
+ modes.set_section_override(None)
+
+
+# ---------------------------------------------------------------------------
+# The five built-ins
+# ---------------------------------------------------------------------------
+
+
+def test_all_five_builtins_ship_and_are_marked_built_in() -> None:
+ by_slug = {m.slug: m for m in modes.list_modes()}
+ assert set(modes.BUILTIN_SLUGS) <= by_slug.keys()
+ assert all(by_slug[s].built_in for s in modes.BUILTIN_SLUGS)
+
+
+def test_builtins_lead_the_list_in_declared_order() -> None:
+ """The switcher shows a stable shelf, not whatever the filesystem returned."""
+ listed = [m.slug for m in modes.list_modes()]
+ assert listed[: len(modes.BUILTIN_SLUGS)] == list(modes.BUILTIN_SLUGS)
+
+
+def test_every_builtin_carries_a_name_and_a_description() -> None:
+ """The switcher renders these; a blank card is indistinguishable from a bug."""
+ for mode in modes.list_modes():
+ assert mode.name.strip(), f"{mode.slug} has no name"
+ assert mode.description.strip(), f"{mode.slug} has no description"
+
+
+# ---------------------------------------------------------------------------
+# Contract 1: the default mode is a no-op
+# ---------------------------------------------------------------------------
+
+
+def test_default_mode_contributes_nothing() -> None:
+ assert modes.active_slug() == modes.MODE_ASSISTANT
+ assert modes.mode_prompt_block(modes.active_mode()) == ""
+
+
+def test_effective_persona_is_byte_identical_to_the_base_by_default() -> None:
+ """The whole feature must be invisible until the user chooses otherwise."""
+ assert persona_loader.load_effective_persona_prompt() == persona_loader.base_persona_prompt()
+
+
+# ---------------------------------------------------------------------------
+# Contract 2: layered, never substituted
+# ---------------------------------------------------------------------------
+
+
+def test_active_mode_is_appended_to_the_base_persona() -> None:
+ modes.set_active(modes.MODE_FRIEND)
+ base = persona_loader.base_persona_prompt()
+ effective = persona_loader.load_effective_persona_prompt()
+
+ assert effective.startswith(base), "the base persona must survive a mode switch"
+ assert len(effective) > len(base)
+ assert "Friend" in effective
+
+
+def test_mode_block_states_that_the_base_rules_win() -> None:
+ """Without this, 'be casual' reads as permission to skip the honesty rules."""
+ block = modes.mode_prompt_block(modes.get_mode(modes.MODE_FRIEND))
+ assert "those rules win" in block
+ assert "honesty" in block
+
+
+def test_custom_system_prompt_and_a_mode_compose() -> None:
+ """The legacy single-slot override is a BASE; a mode still layers on top."""
+ persona_loader.save_custom_prompt("You are MAX.")
+ modes.set_active(modes.MODE_COACH)
+ effective = persona_loader.load_effective_persona_prompt()
+ assert effective.startswith("You are MAX.")
+ assert "Coach" in effective
+
+
+def test_verbosity_and_proactivity_are_compiled_into_the_block() -> None:
+ block = modes.mode_prompt_block(modes.get_mode(modes.MODE_FOCUS))
+ assert "as few words" in block # verbosity: brief
+ assert "Answer what was asked and stop" in block # proactivity: reactive
+
+
+def test_normal_knobs_add_no_text() -> None:
+ """'Normal' means 'say nothing extra', not 'say the word normal'."""
+ mode = modes.Mode(slug="x", name="X", emoji="", description="", character="Be nice.")
+ block = modes.mode_prompt_block(mode)
+ assert block.rstrip().endswith("Be nice.")
+
+
+# ---------------------------------------------------------------------------
+# Contract 3: a slug is a file name
+# ---------------------------------------------------------------------------
+
+
+ "hostile",
+ ["../escape", "/etc/passwd", "..\\windows", "a:b", "..", "", "!!!", "con", "LPT1"],
+)
+def test_hostile_slugs_are_refused(hostile: str) -> None:
+ with pytest.raises(modes.ModeError):
+ modes.normalize_slug(hostile)
+
+
+ ("typed", "expected"),
+ [("Friend Mode", "friend-mode"), (" My Coach ", "my-coach"), ("a_b", "a-b")],
+)
+def test_human_names_become_readable_slugs(typed: str, expected: str) -> None:
+ assert modes.normalize_slug(typed) == expected
+
+
+def test_saved_mode_stays_inside_the_modes_directory(tmp_path) -> None:
+ modes.save_mode(slug="Pirate", name="Pirate", character="Speak like a pirate.")
+ written = list((tmp_path / "modes").glob("*.md"))
+ assert [p.name for p in written] == ["pirate.md"]
+
+
+def test_a_mode_needs_a_character() -> None:
+ with pytest.raises(modes.ModeError):
+ modes.save_mode(slug="empty", name="Empty", character=" ")
+
+
+# ---------------------------------------------------------------------------
+# Round trip, activation, deletion
+# ---------------------------------------------------------------------------
+
+
+def test_save_then_read_back_preserves_every_field() -> None:
+ modes.save_mode(
+ slug="pirate",
+ name="Pirate",
+ character="Speak like a pirate.",
+ emoji="🏴",
+ description="Arr.",
+ voice="alloy",
+ verbosity=modes.VERBOSITY_BRIEF,
+ proactivity=modes.PROACTIVITY_FORWARD,
+ )
+ back = modes.get_mode("pirate")
+ assert back is not None
+ assert (back.name, back.emoji, back.description) == ("Pirate", "🏴", "Arr.")
+ assert (back.voice, back.verbosity, back.proactivity) == (
+ "alloy",
+ modes.VERBOSITY_BRIEF,
+ modes.PROACTIVITY_FORWARD,
+ )
+ assert back.character == "Speak like a pirate."
+ assert back.built_in is False
+
+
+def test_activating_an_unknown_mode_raises() -> None:
+ with pytest.raises(modes.ModeError):
+ modes.set_active("no-such-mode")
+
+
+def test_builtins_cannot_be_deleted() -> None:
+ with pytest.raises(modes.ModeError):
+ modes.delete_mode(modes.MODE_FRIEND)
+
+
+def test_deleting_the_active_mode_falls_back_to_the_default() -> None:
+ modes.save_mode(slug="pirate", name="Pirate", character="Arr.")
+ modes.set_active("pirate")
+ assert modes.active_slug() == "pirate"
+ modes.delete_mode("pirate")
+ assert modes.active_slug() == modes.DEFAULT_MODE
+
+
+def test_a_user_copy_shadows_a_builtin_but_stays_restorable() -> None:
+ modes.save_mode(slug=modes.MODE_FRIEND, name="My Friend", character="Totally different.")
+ edited = modes.get_mode(modes.MODE_FRIEND)
+ assert edited is not None and edited.character == "Totally different."
+ assert edited.built_in is True, "still offers 'restore the original'"
+
+ assert modes.restore_builtin(modes.MODE_FRIEND) is True
+ restored = modes.get_mode(modes.MODE_FRIEND)
+ assert restored is not None and "not serving a client" in restored.character
+
+
+def test_a_stored_pointer_to_a_vanished_mode_degrades_to_the_default() -> None:
+ """A config carried to another machine must not name a mode that is not there."""
+ modes.save_mode(slug="pirate", name="Pirate", character="Arr.")
+ modes.set_active("pirate")
+ (core_config.DATA_DIR / "modes" / "pirate.md").unlink()
+ assert modes.active_slug() == modes.DEFAULT_MODE
+
+
+def test_a_corrupt_mode_file_is_skipped_not_fatal(tmp_path) -> None:
+ """One bad hand-edit must not take down the mode list, and through it every turn."""
+ (tmp_path / "modes").mkdir(parents=True, exist_ok=True)
+ (tmp_path / "modes" / "broken.md").write_text("---\nname: [unclosed\n", encoding="utf-8")
+ slugs = [m.slug for m in modes.list_modes()]
+ assert set(modes.BUILTIN_SLUGS) <= set(slugs)
+ assert persona_loader.load_effective_persona_prompt()
+
+
+# ---------------------------------------------------------------------------
+# Contract 4: the screen-scoped override never persists
+# ---------------------------------------------------------------------------
+
+
+def test_section_override_wins_over_the_stored_choice() -> None:
+ modes.set_active(modes.MODE_FRIEND)
+ modes.set_section_override(modes.MODE_CODING)
+ assert modes.active_slug() == modes.MODE_CODING
+
+
+def test_clearing_the_override_restores_the_users_own_choice() -> None:
+ """Leaving the Agentic IDE must not leave you in a mode you never picked."""
+ modes.set_active(modes.MODE_FRIEND)
+ modes.set_section_override(modes.MODE_CODING)
+ modes.set_section_override(None)
+ assert modes.active_slug() == modes.MODE_FRIEND
+
+
+def test_override_is_never_written_to_config(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The structural fix: a mode a screen turned on cannot outlive the process.
+
+ Guards the exact regression path — if someone ever "helpfully" persists the
+ section override, coding mode becomes sticky again and this test fails.
+ """
+ written: list[str] = []
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_active_mode",
+ lambda slug, **_kw: written.append(slug),
+ )
+ modes.set_section_override(modes.MODE_CODING)
+ assert modes.section_override() == modes.MODE_CODING
+ assert written == [], "the section override must never reach jarvis.toml"
+
+
+def test_override_naming_an_unknown_mode_raises() -> None:
+ with pytest.raises(modes.ModeError):
+ modes.set_section_override("no-such-mode")