Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(soul): the SOUL.md section shows the assistant's whole profile
rubenluetke10-beepd429b2be6e76
diff --git a/jarvis/live/session.py b/jarvis/live/session.pyindex 2051e222bd..193edda172 100644--- a/jarvis/live/session.py+++ b/jarvis/live/session.py@@ -39,7 +39,29 @@ def _identity(config: Any) -> str:except Exception: # noqa: BLE001 — never block a call on the identity blocklog.warning("live voice: identity block unavailable", exc_info=True)return ""- return identity + _memory()+ return identity + _instructions(config) + _memory()+++#: Same cap as the realtime engines' preferences block: a pathological file+#: must never bloat the session instructions.+_INSTRUCTIONS_MAX_CHARS = 64_000+++def _instructions(config: Any) -> str:+ """The user's standing instructions (``<Name>.md``); ``""`` on a fault.++ The typed brain and the realtime engines already honour this file; a+ GPT-Live call did not, so the model could neither follow it nor say what+ was in it when asked (2026-10-02).+ """+ try:+ from jarvis.brain.agent_instructions import render_for_prompt++ block = render_for_prompt(config, max_chars=_INSTRUCTIONS_MAX_CHARS)+ except Exception: # noqa: BLE001 — never block a call on the instructions file+ log.warning("live voice: standing instructions unavailable", exc_info=True)+ return ""+ return "\n\n" + block if block else ""def _memory() -> str:diff --git a/jarvis/memory/soul.py b/jarvis/memory/soul.pyindex 0767487a6a..8e5d0e74cc 100644--- a/jarvis/memory/soul.py+++ b/jarvis/memory/soul.py@@ -100,6 +100,27 @@ class Soul:passraise+ # ── body ─────────────────────────────────────────────────────────────++ @property+ def body(self) -> str:+ """The Markdown under the frontmatter, as the person edits it."""+ return self._body++ def set_body(self, text: str) -> bool:+ """Replace the hand-written Markdown; True when it changed.++ The frontmatter is kept. The managed parts (name line, learned+ section) are whatever the new text says; the next name sync and the+ next learned note restore them if the person removed them.+ """+ body = (text or "").replace("\r\n", "\n").strip()+ body = body + "\n" if body else ""+ if body == self._body:+ return False+ self._body = body+ return True+# ── name ─────────────────────────────────────────────────────────────@propertydiff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex d5bfaa3b54..bc1386c4d6 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -166,7 +166,7 @@"group_tools": "Werkzeuge","group_you": "Du","group_system": "System",- "agent_instructions": "{name}.md",+ "agent_instructions": "SOUL.md","appshots": "Appshots","shortcuts": "Tastenkürzel","pets": "Meine Pets",@@ -179,23 +179,75 @@"voice_language": "Sprache","voice_api_keys": "API-Keys"},- "agent_instructions": {- "subtitle": "Deine persönlichen Präferenzen, wie der Assistent mit dir arbeitet — Ton, Sprache, Voreinstellungen, dauerhafte Fakten. Getrennt vom System-Prompt und hebelt niemals Sicherheit oder Bestätigungen aus.",- "active_badge": "Aktiv",- "empty_badge": "Leer",- "editor_label": "Deine Anweisungen (Markdown)",- "placeholder": "Schreibe deine persönlichen Präferenzen…",- "chars": "{0} Zeichen",- "empty_hint": "Leer - Speichern leert die Datei, oder lade die Vorlage.",- "save": "Anweisungen speichern",- "saving": "Speichern…",- "saved": "Anweisungen gespeichert",+ "soul_view": {+ "subtitle": "Das Profil von {name}: Charakter, Gedächtnis und jede Datei, die {name} über sich und über dich liest.",+ "reload": "Neu laden",+ "hero_role": "Dein Assistent in {0}",+ "hero_role_unnamed": "Dein Assistent in {0}. Wähle ein Aktivierungswort, um ihm einen Namen zu geben.",+ "learning_on": "Lernt",+ "learning_off": "Lernen pausiert",+ "learning_on_hint": "{name} schreibt und korrigiert die eigenen Notizen, während ihr sprecht.",+ "learning_off_hint": "Die Lernschleife läuft in dieser Sitzung nicht, deshalb lassen sich Notizen gerade nicht vergessen.",+ "stat_wake": "Aktivierungswort",+ "stat_wake_sub": "gibt {name} den Namen",+ "stat_self": "Über sich",+ "stat_memory": "Gedächtnis",+ "stat_notes": "Notizen",+ "stat_updated": "Letzte Änderung",+ "files_title": "Dateien",+ "files_description": "{name} liest sie zu Beginn jedes Gesprächs.",+ "file_role_soul": "Charakter: wer {name} ist, Ton und Grenzen",+ "file_role_instructions": "Deine Anweisungen: wie {name} mit dir arbeiten soll",+ "file_role_memory": "Gedächtnis: was du dir merken lassen hast, und eigene Arbeitsnotizen",+ "file_role_user": "Über dich: was {name} über dich bemerkt hat",+ "file_by_assistant": "Von {name} geschrieben",+ "file_missing": "Noch nicht angelegt",+ "file_entries": "{0} Notizen",+ "file_chars": "{0} Zeichen",+ "file_updated": "geändert {0}",+ "character_title": "Wer {name} ist",+ "character_description": "Aus SOUL.md. Der Name folgt immer dem Aktivierungswort.",+ "character_edit": "SOUL.md bearbeiten",+ "character_empty": "SOUL.md beschreibt noch keinen Charakter.",+ "character_missing": "SOUL.md wurde noch nicht angelegt. Sie entsteht beim ersten Start des Assistenten.",+ "tone_title": "Ton",+ "limits_title": "Grenzen",+ "notes_title": "Was {name} gelernt hat",+ "notes_description": "Notizen, die {name} selbst führt. Vergisst du eine, fehlt sie ab dem nächsten Gespräch.",+ "tab_self": "Über sich",+ "tab_memory": "Gedächtnis",+ "tab_user": "Über dich",+ "empty_soul": "Noch nichts. Sag {name}, wie du es haben willst, und {name} schreibt die Notiz selbst.",+ "empty_memory": "Noch nichts. Sag \"merk dir ...\", und es landet hier.",+ "empty_user": "Noch nichts. Was {name} über dich bemerkt, erscheint hier nach Gesprächen.",+ "explicit_badge": "Von dir",+ "forget": "Vergessen",+ "forget_done": "Vergessen",+ "forget_needs_loop": "Notizen lassen sich nur vergessen, während die Lernschleife läuft.",+ "activity_title": "Letzte Änderungen",+ "activity_description": "Jede Notiz, die {name} hinzugefügt, geändert oder entfernt hat, die neueste zuerst.",+ "activity_empty": "Noch keine Änderungen.",+ "op_add": "Hinzugefügt",+ "op_replace": "Geändert",+ "op_remove": "Entfernt",+ "back": "Zurück zu SOUL.md",+ "editor_label": "{0} (Markdown)",+ "soul_placeholder": "Beschreibe, wer {name} ist: Rolle, Stimmung, Ton, Grenzen...",+ "instructions_placeholder": "Schreib, wie {name} mit dir arbeiten soll...",+ "save": "Speichern",+ "saving": "Speichern...",+ "saved": "Gespeichert",+ "cleared": "Anweisungen geleert","revert": "Verwerfen",- "reset": "Leeren",- "reset_done": "Anweisungen geleert",+ "clear": "Leeren",+ "unsaved": "Ungespeicherte Änderungen",+ "chars": "{0} Zeichen","load_template": "Mit Vorlage starten",- "write_from_scratch": "Selbst schreiben",- "applies_next_turn": "Gilt ab der nächsten Antwort deines Assistenten — kein Neustart nötig."+ "soul_note": "Gilt ab der nächsten Antwort von {name}, ohne Neustart. Die Zeile Name folgt dem Aktivierungswort, und {name} ergänzt gelernte Notizen am Ende selbst.",+ "instructions_note": "Gilt ab der nächsten Antwort von {name}, ohne Neustart. Deine Anweisungen prägen Ton, Sprache und Voreinstellungen; Sicherheitsregeln und Bestätigungen heben sie nie auf.",+ "notebook_note": "{name} schreibt diese Datei selbst. Hier kannst du einzelne Notizen vergessen; um eine zu ändern, sag es {name} einfach.",+ "error_title": "Das Profil konnte nicht geladen werden",+ "retry": "Erneut versuchen"},"extensions": {"group_label": "Anpassen",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 3c95824533..aa40d05198 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -166,7 +166,7 @@"group_tools": "Tools","group_you": "You","group_system": "System",- "agent_instructions": "{name}.md",+ "agent_instructions": "SOUL.md","appshots": "Appshots","shortcuts": "Keyboard shortcuts","pets": "My Pets",@@ -179,23 +179,75 @@"voice_language": "Language","voice_api_keys": "API Keys"},- "agent_instructions": {- "subtitle": "Your personal preferences for how the assistant works with you — tone, language, defaults, standing facts. Separate from the System Prompt, and it never overrides safety or confirmations.",- "active_badge": "Active",- "empty_badge": "Empty",- "editor_label": "Your instructions (Markdown)",- "placeholder": "Write your personal preferences…",+ "soul_view": {+ "subtitle": "{name}'s profile: the character, and every file {name} reads about itself and about you.",+ "reload": "Reload",+ "hero_role": "Your assistant in {0}",+ "hero_role_unnamed": "Your assistant in {0}. Pick a wake word to give it a name.",+ "learning_on": "Learning",+ "learning_off": "Learning paused",+ "learning_on_hint": "{name} writes and corrects its notes while you talk.",+ "learning_off_hint": "The learning loop is not running in this session, so notes cannot be forgotten right now.",+ "stat_wake": "Wake word",+ "stat_wake_sub": "gives {name} its name",+ "stat_self": "About itself",+ "stat_memory": "Memory",+ "stat_notes": "notes",+ "stat_updated": "Last change",+ "files_title": "Files",+ "files_description": "{name} reads these at the start of every conversation.",+ "file_role_soul": "Character: who {name} is, its tone and its limits",+ "file_role_instructions": "Your instructions: how {name} should work with you",+ "file_role_memory": "Memory: what you asked it to remember, and its working notes",+ "file_role_user": "About you: what {name} has noticed about you",+ "file_by_assistant": "Written by {name}",+ "file_missing": "Not created yet",+ "file_entries": "{0} notes",+ "file_chars": "{0} characters",+ "file_updated": "updated {0}",+ "character_title": "Who {name} is",+ "character_description": "From SOUL.md. The name always follows the wake word.",+ "character_edit": "Edit SOUL.md",+ "character_empty": "SOUL.md does not describe a character yet.",+ "character_missing": "SOUL.md has not been created yet. It appears after the first start of the assistant.",+ "tone_title": "Tone",+ "limits_title": "Limits",+ "notes_title": "What {name} has learned",+ "notes_description": "Notes it keeps by itself. Forget one and it is gone from the next conversation.",+ "tab_self": "About itself",+ "tab_memory": "Memory",+ "tab_user": "About you",+ "empty_soul": "Nothing yet. Tell {name} how it should be, and it writes the note itself.",+ "empty_memory": "Nothing yet. Say \"remember ...\" and it lands here.",+ "empty_user": "Nothing yet. What {name} notices about you appears here after conversations.",+ "explicit_badge": "You asked",+ "forget": "Forget",+ "forget_done": "Forgotten",+ "forget_needs_loop": "Notes can only be forgotten while the learning loop runs.",+ "activity_title": "Recent changes",+ "activity_description": "Every note {name} added, changed or removed, newest first.",+ "activity_empty": "No changes yet.",+ "op_add": "Added",+ "op_replace": "Changed",+ "op_remove": "Removed",+ "back": "Back to SOUL.md",+ "editor_label": "{0} (Markdown)",+ "soul_placeholder": "Describe who {name} is: role, vibe, tone, limits...",+ "instructions_placeholder": "Write how {name} should work with you...",+ "save": "Save",+ "saving": "Saving...",+ "saved": "Saved",+ "cleared": "Instructions cleared",+ "revert": "Revert",+ "clear": "Clear",+ "unsaved": "Unsaved changes","chars": "{0} characters",- "empty_hint": "Empty - save to clear the file, or start from the template.",- "save": "Save instructions",- "saving": "Saving…",- "saved": "Instructions saved",- "revert": "Revert changes",- "reset": "Clear",- "reset_done": "Instructions cleared","load_template": "Start from template",- "write_from_scratch": "Write from scratch",- "applies_next_turn": "Applies on your assistant's next message — no restart needed."+ "soul_note": "Applies on {name}'s next message, no restart needed. The Name line follows the wake word, and {name} adds its learned notes at the end by itself.",+ "instructions_note": "Applies on {name}'s next message, no restart needed. Your instructions shape tone, language and defaults; they never override safety rules or confirmations.",+ "notebook_note": "{name} writes this file itself. You can forget single notes here; to change one, just tell {name}.",+ "error_title": "The profile could not be loaded",+ "retry": "Try again"},"extensions": {"group_label": "Customize",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 9870a7ed65..f647d57078 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -166,7 +166,7 @@"group_tools": "Herramientas","group_you": "Tú","group_system": "Sistema",- "agent_instructions": "{name}.md",+ "agent_instructions": "SOUL.md","appshots": "Appshots","shortcuts": "Atajos de teclado","pets": "Mis mascotas",@@ -179,23 +179,75 @@"voice_language": "Idioma","voice_api_keys": "Claves API"},- "agent_instructions": {- "subtitle": "Tus preferencias personales sobre cómo el asistente trabaja contigo — tono, idioma, valores por defecto, hechos permanentes. Separado del System Prompt y nunca anula la seguridad ni las confirmaciones.",- "active_badge": "Activo",- "empty_badge": "Vacío",- "editor_label": "Tus instrucciones (Markdown)",- "placeholder": "Escribe tus preferencias personales…",+ "soul_view": {+ "subtitle": "El perfil de {name}: quién es y cada archivo que lee sobre sí mismo y sobre ti.",+ "reload": "Recargar",+ "hero_role": "Tu asistente en {0}",+ "hero_role_unnamed": "Tu asistente en {0}. Elige una palabra de activación para darle un nombre.",+ "learning_on": "Aprendiendo",+ "learning_off": "Aprendizaje en pausa",+ "learning_on_hint": "{name} escribe y corrige sus notas mientras habláis.",+ "learning_off_hint": "El ciclo de aprendizaje no se está ejecutando en esta sesión, así que ahora no se pueden olvidar notas.",+ "stat_wake": "Palabra de activación",+ "stat_wake_sub": "da a {name} su nombre",+ "stat_self": "Sobre sí",+ "stat_memory": "Memoria",+ "stat_notes": "notas",+ "stat_updated": "Último cambio",+ "files_title": "Archivos",+ "files_description": "{name} los lee al empezar cada conversación.",+ "file_role_soul": "Carácter: quién es {name}, su tono y sus límites",+ "file_role_instructions": "Tus instrucciones: cómo debe trabajar {name} contigo",+ "file_role_memory": "Memoria: lo que le pediste recordar y sus notas de trabajo",+ "file_role_user": "Sobre ti: lo que {name} ha notado de ti",+ "file_by_assistant": "Escrito por {name}",+ "file_missing": "Aún no creado",+ "file_entries": "{0} notas",+ "file_chars": "{0} caracteres",+ "file_updated": "actualizado {0}",+ "character_title": "Quién es {name}",+ "character_description": "De SOUL.md. El nombre siempre sigue a la palabra de activación.",+ "character_edit": "Editar SOUL.md",+ "character_empty": "SOUL.md aún no describe un carácter.",+ "character_missing": "SOUL.md aún no se ha creado. Aparece tras el primer inicio del asistente.",+ "tone_title": "Tono",+ "limits_title": "Límites",+ "notes_title": "Lo que {name} ha aprendido",+ "notes_description": "Notas que lleva por sí mismo. Si olvidas una, desaparece desde la próxima conversación.",+ "tab_self": "Sobre sí",+ "tab_memory": "Memoria",+ "tab_user": "Sobre ti",+ "empty_soul": "Nada aún. Dile a {name} cómo quieres que sea y {name} escribirá la nota.",+ "empty_memory": "Nada aún. Di \"recuerda ...\" y aparecerá aquí.",+ "empty_user": "Nada aún. Lo que {name} note de ti aparecerá aquí tras las conversaciones.",+ "explicit_badge": "Lo pediste",+ "forget": "Olvidar",+ "forget_done": "Olvidado",+ "forget_needs_loop": "Las notas solo se pueden olvidar mientras el ciclo de aprendizaje está activo.",+ "activity_title": "Cambios recientes",+ "activity_description": "Cada nota que {name} añadió, cambió o quitó, la más reciente primero.",+ "activity_empty": "Aún no hay cambios.",+ "op_add": "Añadida",+ "op_replace": "Cambiada",+ "op_remove": "Quitada",+ "back": "Volver a SOUL.md",+ "editor_label": "{0} (Markdown)",+ "soul_placeholder": "Describe quién es {name}: rol, estilo, tono, límites...",+ "instructions_placeholder": "Escribe cómo debe trabajar {name} contigo...",+ "save": "Guardar",+ "saving": "Guardando...",+ "saved": "Guardado",+ "cleared": "Instrucciones borradas",+ "revert": "Descartar",+ "clear": "Borrar",+ "unsaved": "Cambios sin guardar","chars": "{0} caracteres",- "empty_hint": "Vacío - guarda para vaciar el archivo o carga la plantilla.",- "save": "Guardar instrucciones",- "saving": "Guardando…",- "saved": "Instrucciones guardadas",- "revert": "Descartar cambios",- "reset": "Vaciar",- "reset_done": "Instrucciones vaciadas",- "load_template": "Empezar con plantilla",- "write_from_scratch": "Escribir desde cero",- "applies_next_turn": "Se aplica en el próximo mensaje de tu asistente — sin reinicio."+ "load_template": "Empezar con la plantilla",+ "soul_note": "Se aplica en el próximo mensaje de {name}, sin reiniciar. La línea Name sigue a la palabra de activación, y {name} añade sus notas aprendidas al final por sí mismo.",+ "instructions_note": "Se aplica en el próximo mensaje de {name}, sin reiniciar. Tus instrucciones definen tono, idioma y valores por defecto; nunca anulan las reglas de seguridad ni las confirmaciones.",+ "notebook_note": "{name} escribe este archivo por sí mismo. Aquí puedes olvidar notas sueltas; para cambiar una, díselo a {name}.",+ "error_title": "No se pudo cargar el perfil",+ "retry": "Reintentar"},"extensions": {"group_label": "Personalizar",diff --git a/jarvis/ui/web/frontend/src/lib/quickSwitch.ts b/jarvis/ui/web/frontend/src/lib/quickSwitch.tsindex 494d77d9aa..76db044222 100644--- a/jarvis/ui/web/frontend/src/lib/quickSwitch.ts+++ b/jarvis/ui/web/frontend/src/lib/quickSwitch.ts@@ -82,7 +82,7 @@ const ALIASES: Partial<Record<string, readonly string[]>> = {sessions: ["transcripts", "recordings", "history"],run_inspector: ["runs", "debug", "trace"],computers: ["servers", "ssh", "vps", "remote", "machines"],- "agent-instructions": ["instructions", "system prompt", "agents md", "claude md"],+ "agent-instructions": ["soul", "soul md", "character", "persona", "instructions", "memory md", "agents md"],marketplace: ["store", "shop", "install"],board: ["stats", "dashboard", "activity"],docs: ["documentation", "help", "manual"],diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.tsindex 7d6d0b2142..84280aac92 100644--- a/jarvis/ui/web/frontend/src/store/events.ts+++ b/jarvis/ui/web/frontend/src/store/events.ts@@ -246,7 +246,7 @@ export const SECTION_LABELS: Record<SectionId, string> = {taskbar: "Taskbar",contacts: "Contacts",feedback: "Feedback",- "agent-instructions": "Agent Instructions",+ "agent-instructions": "SOUL.md",appshots: "Appshots",shortcuts: "Keyboard shortcuts",pets: "My Pets",diff --git a/jarvis/ui/web/frontend/src/views/AgentInstructionsView.test.tsx b/jarvis/ui/web/frontend/src/views/AgentInstructionsView.test.tsxdeleted file mode 100644index 32b695d480..0000000000--- a/jarvis/ui/web/frontend/src/views/AgentInstructionsView.test.tsx+++ /dev/null@@ -1,145 +0,0 @@-import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it, vi } from "vitest";-import { AgentInstructionsView } from "./AgentInstructionsView";--const STATE = {- content: "Be terse.",- exists: true,- filename: "Ruben.md",- template: "# How Ruben works with me\n## Do\n- ",- char_count: 9,-};--const EMPTY_STATE = {- content: "",- exists: false,- filename: "Ruben.md",- template: "# How Ruben works with me\n## Do\n- ",- char_count: 0,-};--afterEach(() => vi.restoreAllMocks());--describe("AgentInstructionsView", () => {- it("renders the dynamic filename and loads the content", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({ ok: true, json: async () => STATE }),- );- render(<AgentInstructionsView />);- await waitFor(() =>- expect(- (screen.getByTestId("agent-instructions-editor") as HTMLTextAreaElement).value,- ).toBe("Be terse."),- );- expect(screen.getByText("Ruben.md").textContent).toBe("Ruben.md");- });-- it("PUTs the draft on save", async () => {- const fetchMock = vi- .fn()- .mockResolvedValueOnce({ ok: true, json: async () => EMPTY_STATE })- .mockResolvedValueOnce({- ok: true,- json: async () => ({- ...STATE,- content: EMPTY_STATE.template,- ok: true,- restart_required: false,- }),- });- vi.stubGlobal("fetch", fetchMock);- render(<AgentInstructionsView />);- const editor = await screen.findByTestId("agent-instructions-editor");- const template = screen- .getByText("Start from template")- .closest("button") as HTMLButtonElement;- await waitFor(() => expect(template.disabled).toBe(false));- fireEvent.click(template);- await waitFor(() =>- expect((editor as HTMLTextAreaElement).value).toBe(EMPTY_STATE.template),- );- const save = screen.getByText("Save instructions").closest("button") as HTMLButtonElement;- await waitFor(() => expect(save.disabled).toBe(false));- fireEvent.click(save);- await waitFor(() => {- const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");- expect(put).toBeTruthy();- expect(put![0]).toBe("/api/settings/agent-instructions");- expect(JSON.parse((put![1] as RequestInit).body as string)).toEqual({- content: EMPTY_STATE.template,- });- });- });-- it("clears saved instructions only when the empty draft is saved", async () => {- const fetchMock = vi- .fn()- .mockResolvedValueOnce({ ok: true, json: async () => STATE })- .mockResolvedValueOnce({- ok: true,- json: async () => ({ ...EMPTY_STATE, ok: true, removed: true, restart_required: false }),- });- vi.stubGlobal("fetch", fetchMock);- render(<AgentInstructionsView />);- const editor = await screen.findByTestId("agent-instructions-editor");- fireEvent.change(editor, { target: { value: "" } });-- const save = screen.getByText("Save instructions").closest("button") as HTMLButtonElement;- expect(save.disabled).toBe(false);- fireEvent.click(save);-- await waitFor(() => {- const del = fetchMock.mock.calls.find(([, opts]) => opts?.method === "DELETE");- expect(del).toBeTruthy();- expect(del![0]).toBe("/api/settings/agent-instructions");- });- });-- it("loads the starter template into an empty editor", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({ ok: true, json: async () => EMPTY_STATE }),- );- render(<AgentInstructionsView />);- const template = screen- .getByText("Start from template")- .closest("button") as HTMLButtonElement;- await waitFor(() => expect(template.disabled).toBe(false));- fireEvent.click(template);- await waitFor(() =>- expect(- (screen.getByTestId("agent-instructions-editor") as HTMLTextAreaElement).value,- ).toBe(EMPTY_STATE.template),- );- });-- it("reverts unsaved changes without deleting the saved instructions", async () => {- const fetchMock = vi.fn().mockResolvedValueOnce({ ok: true, json: async () => STATE });- vi.stubGlobal("fetch", fetchMock);- render(<AgentInstructionsView />);- const editor = await screen.findByTestId("agent-instructions-editor");- await waitFor(() =>- expect((editor as HTMLTextAreaElement).value).toBe(STATE.content),- );- fireEvent.change(editor, { target: { value: "Changed then regret" } });- fireEvent.click(screen.getByText("Revert changes"));-- expect((editor as HTMLTextAreaElement).value).toBe("Be terse.");- expect(fetchMock.mock.calls.some(([, opts]) => opts?.method === "DELETE")).toBe(false);- });-- it("disables Save until the draft changes", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({ ok: true, json: async () => STATE }),- );- render(<AgentInstructionsView />);- const editor = await screen.findByTestId("agent-instructions-editor");- await waitFor(() =>- expect((editor as HTMLTextAreaElement).value).toBe(STATE.content),- );- const save = screen.getByText("Save instructions").closest("button") as HTMLButtonElement;- expect(save.disabled).toBe(true);- });-});diff --git a/jarvis/ui/web/frontend/src/views/AgentInstructionsView.tsx b/jarvis/ui/web/frontend/src/views/AgentInstructionsView.tsxdeleted file mode 100644index 4a6c6a537f..0000000000--- a/jarvis/ui/web/frontend/src/views/AgentInstructionsView.tsx+++ /dev/null@@ -1,162 +0,0 @@-import { useEffect, useRef, useState } from "react";-import { FilePlus2, PenLine, RotateCcw, Save, ScrollText } from "lucide-react";-import { Badge } from "@/components/ui/badge";-import { Button } from "@/components/ui/button";-import { Card } from "@/components/ui/card";-import { EmptyState } from "@/components/ui/empty-state";-import { Textarea } from "@/components/ui/textarea";-import { PageHeader } from "@/components/layout/PageHeader";-import { useAgentInstructions } from "@/hooks/useAgentInstructions";-import { useEventStore } from "@/store/events";-import { useT } from "@/i18n";--/**- * The assistant's standing instructions — one markdown file, edited in place.- *- * A PageHeader named after the file, the content capped at the reading- * measure, and the editor as ONE card: the textarea, a character count, and- * a sticky action row at its foot. Empty, the card opens with an EmptyState- * offering the template or a blank page; the textarea stays mounted so the- * page never swaps its editor out from under a keyboard.- */-export function AgentInstructionsView() {- const t = useT();- const { config, loading, error, save } = useAgentInstructions();- const pushToast = useEventStore((s) => s.pushToast);- const editorRef = useRef<HTMLTextAreaElement>(null);-- const [draft, setDraft] = useState("");- const [saving, setSaving] = useState(false);- // "Write from scratch" hides the empty state for this visit even though the- // draft is still blank — the user asked for the blank page.- const [writing, setWriting] = useState(false);-- useEffect(() => {- if (config) setDraft(config.content ?? "");- }, [config]);-- const filename = config?.filename ?? "…";- const exists = !!config?.exists;- const dirty = !!config && draft !== (config.content ?? "");- const canRevert = dirty;- const trimmedEmpty = draft.trim().length === 0;- // Also while loading: the template button must be the same element before- // and after the config lands, so a click queued on it is never lost.- const showEmpty = trimmedEmpty && !writing;-- async function onSave() {- if (!dirty) return;- setSaving(true);- try {- await save(draft);- pushToast("success", t("agent_instructions.saved"));- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setSaving(false);- }- }-- function onRevert() {- if (config) setDraft(config.content ?? "");- }-- function onLoadTemplate() {- if (config?.template) setDraft(config.template);- }-- function onWriteFromScratch() {- setWriting(true);- requestAnimationFrame(() => editorRef.current?.focus());- }-- return (- <div className="flex h-full flex-col overflow-y-auto px-8 pb-6">- <div className="mx-auto w-full max-w-3xl">- <PageHeader- icon={<ScrollText />}- title={filename}- description={t("agent_instructions.subtitle")}- actions={- !exists ? (- <Badge variant="secondary">{t("agent_instructions.empty_badge")}</Badge>- ) : undefined- }- />-- {error && <p className="mb-4 text-sm text-destructive">{error}</p>}-- <Card className="flex flex-col overflow-hidden">- <label className="sr-only" htmlFor="agent-instructions-editor">- {t("agent_instructions.editor_label")}- </label>- {showEmpty && (- <EmptyState- icon={<ScrollText />}- title={t("agent_instructions.empty_badge")}- description={t("agent_instructions.empty_hint")}- actions={- <>- <Button onClick={onLoadTemplate} disabled={!config?.template}>- <FilePlus2 />- {t("agent_instructions.load_template")}- </Button>- <Button variant="outline" onClick={onWriteFromScratch}>- <PenLine />- {t("agent_instructions.write_from_scratch")}- </Button>- </>- }- />- )}- <Textarea- id="agent-instructions-editor"- ref={editorRef}- data-testid="agent-instructions-editor"- value={draft}- onChange={(e) => setDraft(e.target.value)}- onFocus={() => setWriting(true)}- disabled={loading}- spellCheck={false}- placeholder={t("agent_instructions.placeholder")}- className={- showEmpty- ? "sr-only"- : "min-h-[60vh] resize-y rounded-none border-0 p-5 text-base leading-7 focus-visible:ring-0 focus-visible:ring-offset-0"- }- />- {/* Sticky action row: count left, Save + Revert right. */}- <div className="sticky bottom-0 flex items-center justify-between gap-3 border-t border-border bg-card px-5 py-3">- <span className="text-sm tabular-nums text-foreground-faint">- {t("agent_instructions.chars").replace("{0}", String(draft.length))}- </span>- <div className="flex items-center gap-2">- {!showEmpty && (- <Button- variant="ghost"- onClick={onLoadTemplate}- disabled={loading || !config?.template}- >- <FilePlus2 />- {t("agent_instructions.load_template")}- </Button>- )}- <Button variant="ghost" onClick={onRevert} disabled={loading || !canRevert}>- <RotateCcw />- {t("agent_instructions.revert")}- </Button>- <Button onClick={onSave} disabled={saving || loading || !dirty}>- <Save />- {saving ? t("agent_instructions.saving") : t("agent_instructions.save")}- </Button>- </div>- </div>- </Card>-- <p className="mt-3 text-sm text-muted-foreground">- {t("agent_instructions.applies_next_turn")}- </p>- </div>- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx b/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsxindex 37ecbfee6c..e6603e6a3e 100644--- a/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx@@ -69,8 +69,8 @@ vi.mock("@/views/SettingsView", () => ({),}));vi.mock("@/views/ProfileView", () => ({ ProfileView: stub("TAB_PROFILE") }));-vi.mock("@/views/AgentInstructionsView", () => ({- AgentInstructionsView: stub("TAB_INSTRUCTIONS"),+vi.mock("@/views/SoulView", () => ({+ SoulView: stub("TAB_INSTRUCTIONS"),}));vi.mock("@/views/contacts/ContactsView", () => ({ContactsView: stub("TAB_CONTACTS"),diff --git a/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx b/jarvis/ui/web/frontend/src/views/SettingsHubView.tsxindex 63e82f54bb..da43b35a5e 100644--- a/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx@@ -23,7 +23,7 @@ import { cn } from "@/lib/utils";* (General · System · Activity) and the selected section on the right:** General: Settings, Keyboard shortcuts, Appshots, My Pets, Profile,- * {name}.md, Contacts, Socials+ * SOUL.md, Contacts, Socials* System: Computers, API Keys, Local models, Jarvis actions* Activity: Spend, Feedback*@@ -35,8 +35,7 @@ import { cn } from "@/lib/utils";* exactly like MainView used to map them to standalone views.** Labels, icons and grouping resolve from `NAV_GROUPS` (via `resolveNavLabel`,- * so the `{name}.md` token and all three locales behave exactly like the- * sidebar rows did) — no second hand-written list to drift (AP-4).+ * so all three locales behave exactly like the sidebar rows did) — no second hand-written list to drift (AP-4).** Tab contents stay code-split one `lazy` boundary per view, so opening the* hub still only pays for the shell plus the visible tab.@@ -48,10 +47,8 @@ const SettingsTab = lazy(() =>const ProfileTab = lazy(() =>import("@/views/ProfileView").then((m) => ({ default: m.ProfileView })),);-const InstructionsTab = lazy(() =>- import("@/views/AgentInstructionsView").then((m) => ({- default: m.AgentInstructionsView,- })),+const SoulTab = lazy(() =>+ import("@/views/SoulView").then((m) => ({ default: m.SoulView })),);const ContactsTab = lazy(() =>import("@/views/contacts/ContactsView").then((m) => ({@@ -144,7 +141,7 @@ const HUB_NAV_GROUPS: readonly { labelKey: string; ids: readonly HubNavId[] }[]const TAB_CONTENT: Record<HubNavId | "telephony-setup", LazyExoticComponent<ComponentType>> = {settings: SettingsTab,profile: ProfileTab,- "agent-instructions": InstructionsTab,+ "agent-instructions": SoulTab,contacts: ContactsTab,socials: SocialsTab,apikeys: ApiKeysTab,diff --git a/jarvis/ui/web/frontend/src/views/SoulView.test.tsx b/jarvis/ui/web/frontend/src/views/SoulView.test.tsxnew file mode 100644index 0000000000..f7302feda9--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/SoulView.test.tsx@@ -0,0 +1,230 @@+/**+ * Component tests for the SOUL.md section — the assistant's own profile.+ *+ * What these pin: the page is called SOUL.md (never "{name}.md", which a live+ * call confused with the character file), it lists every file the assistant+ * reads, its character comes from SOUL.md as rows, explicit memories say so,+ * a note can be forgotten only while the learning loop runs, and the files+ * open in place — SOUL.md and the instructions as editors that save to their+ * own endpoints.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import { SoulView } from "@/views/SoulView";+import type { SoulProfile } from "@/views/soul/api";++function renderWithClient(node: React.ReactNode) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },+ });+ return render(<QueryClientProvider client={client}>{node}</QueryClientProvider>);+}++function profile(overrides: Partial<SoulProfile> = {}): SoulProfile {+ return {+ name: "George",+ named: true,+ product: "Personal Jarvis",+ wake_phrase: "Hey George",+ learning: true,+ files: [+ {+ id: "soul",+ filename: "SOUL.md",+ exists: true,+ editable: true,+ updated_ms: Date.now(),+ chars: 120,+ content: "# My own persona\n\n## Who I am\n\n- **Name:** George\n- **Vibe:** Dry and direct.\n",+ character: {+ who: [+ { label: "Role", text: "Personal voice assistant." },+ { label: "Vibe", text: "Dry and direct." },+ ],+ tone: [{ label: "", text: "No corporate-speak." }],+ limits: [{ label: "", text: "No made-up facts." }],+ },+ learned: [{ id: "s1", text: "Answers in short spoken sentences.", importance: 5, origin: "review", explicit: false }],+ name_in_file: "George",+ },+ {+ id: "instructions",+ filename: "George.md",+ exists: true,+ editable: true,+ updated_ms: Date.now(),+ chars: 21,+ content: "Call me Ruben, please.",+ template: "# How George should work with me\n",+ },+ {+ id: "memory",+ filename: "MEMORY.md",+ exists: true,+ editable: false,+ updated_ms: Date.now(),+ chars: 60,+ entries: [+ {+ id: "m1",+ text: "2026-10-02 (asked to remember): The sister is called Lena.",+ importance: 10,+ origin: "user",+ explicit: true,+ },+ ],+ },+ { id: "user", filename: "USER.md", exists: false, editable: false, updated_ms: null, chars: 0, entries: [] },+ ],+ activity: [+ {+ ts: "2026-10-02T10:00:10+0200",+ source: "remember tool",+ target: "memory",+ operation: "add",+ text: "2026-10-02 (asked to remember): The sister is called Lena.",+ evidence: "merk dir das",+ },+ ],+ ...overrides,+ };+}++type Handler = (init?: RequestInit) => { status?: number; body: unknown };++function installFetch(routes: Record<string, Handler>) {+ const calls: { url: string; init?: RequestInit }[] = [];+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ calls.push({ url, init });+ const key = `${init?.method ?? "GET"} ${url}`;+ const handler = routes[key];+ if (!handler) throw new Error(`unexpected fetch ${key}`);+ const { status = 200, body } = handler(init);+ return {+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+ } as Response;+ });+ (globalThis as unknown as { fetch: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;+ return calls;+}++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe("SoulView", () => {+ it("is called SOUL.md and lists every file the assistant reads", async () => {+ installFetch({ "GET /api/soul": () => ({ body: profile() }) });+ renderWithClient(<SoulView />);++ expect(await screen.findByTestId("soul-hero")).toBeTruthy();+ expect(screen.getByRole("heading", { level: 1 }).textContent).toBe("SOUL.md");+ expect(screen.getByText("Hey George")).toBeTruthy();+ expect(screen.getByTestId("soul-vibe").textContent).toBe("Dry and direct.");++ const files = screen.getByTestId("soul-files");+ for (const name of ["SOUL.md", "George.md", "MEMORY.md", "USER.md"]) {+ expect(within(files).getByText(name)).toBeTruthy();+ }+ expect(within(screen.getByTestId("soul-file-user")).getByText(/Not created yet/)).toBeTruthy();+ });++ it("shows the character from SOUL.md and an explicit memory as one", async () => {+ installFetch({ "GET /api/soul": () => ({ body: profile() }) });+ renderWithClient(<SoulView />);++ const character = await screen.findByTestId("soul-character");+ expect(within(character).getByText("Personal voice assistant.")).toBeTruthy();+ expect(within(character).getByText("No corporate-speak.")).toBeTruthy();++ const notes = screen.getByTestId("soul-notes");+ expect(within(notes).getByText("Answers in short spoken sentences.")).toBeTruthy();+ fireEvent.click(within(notes).getByRole("button", { name: /^Memory/ }));+ expect(within(notes).getByText("The sister is called Lena.")).toBeTruthy();+ expect(within(notes).getByText("You asked")).toBeTruthy();++ const activity = screen.getByTestId("soul-activity");+ expect(within(activity).getByText("“merk dir das”")).toBeTruthy();+ });++ it("forgets a note through the soul endpoint", async () => {+ const calls = installFetch({+ "GET /api/soul": () => ({ body: profile() }),+ "DELETE /api/soul/entries/soul/s1": () => ({+ body: profile({ files: profile().files.map((f) => (f.id === "soul" ? { ...f, learned: [] } : f)) }),+ }),+ });+ renderWithClient(<SoulView />);++ const notes = await screen.findByTestId("soul-notes");+ fireEvent.click(within(notes).getByRole("button", { name: /Forget: Answers/ }));+ await waitFor(() => expect(within(notes).getByTestId("soul-notes-empty-soul")).toBeTruthy());+ expect(calls.some((c) => c.url === "/api/soul/entries/soul/s1" && c.init?.method === "DELETE")).toBe(true);+ });++ it("cannot forget while the learning loop is off", async () => {+ installFetch({ "GET /api/soul": () => ({ body: profile({ learning: false }) }) });+ renderWithClient(<SoulView />);++ const notes = await screen.findByTestId("soul-notes");+ const forget = within(notes).getByRole("button", { name: /Forget: Answers/ }) as HTMLButtonElement;+ expect(forget.disabled).toBe(true);+ expect(screen.getByTestId("soul-learning").textContent).toBe("Learning paused");+ });++ it("opens SOUL.md as an editor that saves to /api/soul/file", async () => {+ const calls = installFetch({+ "GET /api/soul": () => ({ body: profile() }),+ "PUT /api/soul/file": () => ({ body: profile() }),+ });+ renderWithClient(<SoulView />);++ fireEvent.click(await screen.findByTestId("soul-file-soul"));+ const editor = (await screen.findByTestId("soul-file-editor")) as HTMLTextAreaElement;+ expect(editor.value).toContain("## Who I am");+ const save = screen.getByTestId("soul-file-save") as HTMLButtonElement;+ expect(save.disabled).toBe(true);++ fireEvent.change(editor, { target: { value: `${editor.value}\n- **Humor:** dry` } });+ fireEvent.click(save);+ await waitFor(() => expect(calls.some((c) => c.url === "/api/soul/file")).toBe(true));+ const put = calls.find((c) => c.url === "/api/soul/file");+ expect(JSON.parse(String(put?.init?.body)).content).toContain("- **Humor:** dry");++ fireEvent.click(screen.getByTestId("soul-back"));+ expect(await screen.findByTestId("soul-hero")).toBeTruthy();+ });++ it("saves the instructions file to the agent-instructions endpoint", async () => {+ const calls = installFetch({+ "GET /api/soul": () => ({ body: profile() }),+ "PUT /api/settings/agent-instructions": () => ({ body: { ok: true } }),+ });+ renderWithClient(<SoulView />);++ fireEvent.click(await screen.findByTestId("soul-file-instructions"));+ const editor = (await screen.findByTestId("soul-file-editor")) as HTMLTextAreaElement;+ expect(editor.value).toBe("Call me Ruben, please.");+ fireEvent.change(editor, { target: { value: "Call me Ruben. Answer in German." } });+ fireEvent.click(screen.getByTestId("soul-file-save"));+ await waitFor(() =>+ expect(calls.some((c) => c.url === "/api/settings/agent-instructions" && c.init?.method === "PUT")).toBe(true),+ );+ });++ it("shows a notebook as its notes, not as an editor", async () => {+ installFetch({ "GET /api/soul": () => ({ body: profile() }) });+ renderWithClient(<SoulView />);++ fireEvent.click(await screen.findByTestId("soul-file-memory"));+ const page = await screen.findByTestId("soul-page-memory");+ expect(within(page).getByText("The sister is called Lena.")).toBeTruthy();+ expect(screen.queryByTestId("soul-file-editor")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/views/SoulView.tsx b/jarvis/ui/web/frontend/src/views/SoulView.tsxnew file mode 100644index 0000000000..30aa73763d--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/SoulView.tsx@@ -0,0 +1,153 @@+/**+ * SoulView — the assistant's own profile, named after its character file.+ *+ * Until 2026-10-02 this section was an editor for one file named after the+ * assistant ("George.md"), and a live call could not tell that file from+ * SOUL.md. Now the section is SOUL.md, and it shows every file that shapes+ * the assistant, in one column read top to bottom:+ *+ * ┌────────────────────────────────────────────────────────────┐+ * │ Mark · name · what it is · its vibe │+ * │ Wake word │ About itself │ Memory │ Last change │+ * ├────────────────────────────────────────────────────────────┤+ * │ Files — SOUL.md, the instructions, MEMORY.md, USER.md │+ * ├────────────────────────────────────────────────────────────┤+ * │ Who {name} is — role, vibe, tone, limits (from SOUL.md) │+ * ├────────────────────────────────────────────────────────────┤+ * │ What it has learned — about itself · memory · about you │+ * ├────────────────────────────────────────────────────────────┤+ * │ Recent changes — the learning ledger, newest first │+ * └────────────────────────────────────────────────────────────┘+ *+ * A file opens in place as a sub-page with a back link, like USER.md on the+ * Profile page: the files are the source behind the page, not peers of it.+ */+import { useEffect, useRef, useState } from "react";+import { AlertTriangle, RefreshCw, Sparkles } from "lucide-react";++import { PageHeader } from "@/components/layout/PageHeader";+import { Button } from "@/components/ui/button";+import { EmptyState } from "@/components/ui/empty-state";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { ActivityGroup } from "@/views/soul/ActivityGroup";+import { CharacterGroup } from "@/views/soul/CharacterGroup";+import { fileOf, useSoulProfile, type SoulFileId } from "@/views/soul/api";+import { FileList } from "@/views/soul/FileList";+import { FilePage } from "@/views/soul/FilePage";+import { NotesGroup } from "@/views/soul/NotesGroup";+import { SoulHero } from "@/views/soul/SoulHero";++/** The reading column — the same measure as the Profile page. */+const COLUMN = "mx-auto w-full max-w-[760px]";++export function SoulView() {+ const t = useT();+ const { data, isLoading, error, refetch, isRefetching } = useSoulProfile();+ const [open, setOpen] = useState<SoulFileId | null>(null);++ // Switching between the page and a file starts at the top.+ const scrollRef = useRef<HTMLDivElement | null>(null);+ useEffect(() => {+ scrollRef.current?.scrollTo?.({ top: 0 });+ }, [open]);++ const openFile = open && data ? data.files.find((f) => f.id === open) : undefined;++ return (+ <div+ ref={scrollRef}+ className="flex h-full flex-col overflow-y-auto bg-background px-8 pb-10 scrollbar-jarvis"+ >+ <div className={COLUMN}>+ <PageHeader+ icon={<Sparkles />}+ title="SOUL.md"+ description={t("soul_view.subtitle")}+ actions={+ <Button+ type="button"+ size="icon"+ variant="ghost"+ className="text-muted-foreground"+ onClick={() => void refetch()}+ disabled={isRefetching}+ title={t("soul_view.reload")}+ aria-label={t("soul_view.reload")}+ >+ <RefreshCw className={cn(isRefetching && "animate-spin")} />+ </Button>+ }+ />++ {isLoading && <SoulSkeleton label={t("common.loading")} />}++ {error && (+ <EmptyState+ icon={<AlertTriangle />}+ title={t("soul_view.error_title")}+ description={error.message}+ actions={+ <Button type="button" variant="outline" onClick={() => void refetch()}>+ {t("soul_view.retry")}+ </Button>+ }+ />+ )}++ {data && openFile && (+ <FilePage file={openFile} canForget={data.learning} onBack={() => setOpen(null)} />+ )}++ {data && !openFile && (+ <div className="flex flex-col gap-10">+ <SoulHero profile={data} />+ <FileList files={data.files} onOpen={setOpen} />+ <CharacterGroup soul={fileOf(data, "soul")} onEdit={() => setOpen("soul")} />+ <NotesGroup profile={data} />+ <ActivityGroup activity={data.activity} />+ </div>+ )}+ </div>+ </div>+ );+}++/** The real layout at its real height; no zero stands in for a missing figure. */+function SoulSkeleton({ label }: { label: string }) {+ return (+ <div role="status" aria-busy="true" aria-label={label} className="flex flex-col gap-10">+ <div className="rounded-xl border border-border bg-card">+ <div className="flex items-center gap-5 p-6">+ <div className="h-20 w-20 shrink-0 animate-pulse rounded-2xl bg-secondary" />+ <div className="flex min-w-0 flex-1 flex-col gap-2.5">+ <div className="h-6 w-40 max-w-full animate-pulse rounded-md bg-secondary" />+ <div className="h-3.5 w-64 max-w-full animate-pulse rounded-full bg-secondary" />+ </div>+ </div>+ <div className="grid grid-cols-2 border-t border-border sm:grid-cols-4">+ {[0, 1, 2, 3].map((i) => (+ <div key={i} className="px-5 py-4">+ <div className="h-3 w-16 animate-pulse rounded-full bg-secondary" />+ <div className="mt-2 h-5 w-20 animate-pulse rounded-md bg-secondary" />+ </div>+ ))}+ </div>+ </div>+ <div className="flex flex-col gap-3">+ <div className="h-5 w-24 animate-pulse rounded-md bg-secondary" />+ <div className="divide-y divide-border rounded-xl border border-border bg-card">+ {[0, 1, 2, 3].map((j) => (+ <div key={j} className="flex items-center gap-4 px-5 py-4">+ <div className="h-9 w-9 animate-pulse rounded-lg bg-secondary" />+ <div className="flex flex-1 flex-col gap-2">+ <div className="h-3.5 w-24 animate-pulse rounded-full bg-secondary" />+ <div className="h-3 w-56 max-w-full animate-pulse rounded-full bg-secondary" />+ </div>+ </div>+ ))}+ </div>+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts b/jarvis/ui/web/frontend/src/views/settings/settingsSearch.tsindex 5ad1478bea..77777243e9 100644--- a/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts+++ b/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts@@ -25,7 +25,7 @@ const SEARCH_GROUPS = [const SEARCH_PAGES = [{ id: "profile", keys: ["profile_view"] },- { id: "agent-instructions", keys: ["agent_instructions"] },+ { id: "agent-instructions", keys: ["soul_view"] },{ id: "contacts", keys: ["contacts"] },{ id: "socials", keys: ["socials"] },{ id: "apikeys", keys: ["apikeys_view", "apikeys_voice", "apikeys_model", "apikeys_cu_model"] },diff --git a/jarvis/ui/web/frontend/src/views/soul/ActivityGroup.tsx b/jarvis/ui/web/frontend/src/views/soul/ActivityGroup.tsxnew file mode 100644index 0000000000..dcc9eeb947--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/soul/ActivityGroup.tsx@@ -0,0 +1,91 @@+/**+ * Recent changes: every note the assistant added, changed or removed, newest+ * first, read from the learning ledger. Each line names the file, what+ * happened and when, and quotes what the person said when there is a quote —+ * so "why does it think that?" has an answer on the page.+ */+import { Minus, PencilLine, Plus } from "lucide-react";+import type { ReactNode } from "react";++import { useT, useUiLanguage } from "@/i18n";+import { cn } from "@/lib/utils";+import { ProfileGroup } from "@/views/profile/ProfileGroup";+import type { SoulActivity } from "@/views/soul/api";+import { parseLedgerTime, whenShort } from "@/views/soul/format";+import { splitDated } from "@/views/soul/NotesGroup";++const FILE_OF_TARGET: Record<string, string> = {+ soul: "SOUL.md",+ memory: "MEMORY.md",+ user: "USER.md",+};++const OP_ICON: Record<string, ReactNode> = {+ add: <Plus />,+ replace: <PencilLine />,+ remove: <Minus />,+};++export function ActivityGroup({ activity }: { activity: readonly SoulActivity[] }) {+ const t = useT();+ const lang = useUiLanguage();++ return (+ <ProfileGroup+ testId="soul-activity"+ title={t("soul_view.activity_title")}+ description={t("soul_view.activity_description")}+ >+ {activity.length === 0 ? (+ <p className="px-5 py-5 text-base text-muted-foreground">{t("soul_view.activity_empty")}</p>+ ) : (+ <ol className="px-5 py-2">+ {activity.map((item, i) => {+ const op = OP_ICON[item.operation] ? item.operation : "add";+ const when = whenShort(parseLedgerTime(item.ts), lang);+ const last = i === activity.length - 1;+ return (+ <li key={`${item.ts}-${i}`} className="relative flex gap-4 py-3">+ {!last && (+ <span aria-hidden className="absolute left-3 top-10 bottom-0 w-px bg-border" />+ )}+ <span+ aria-hidden+ className={cn(+ "relative flex h-6 w-6 shrink-0 items-center justify-center rounded-full border [&>svg]:h-3.5 [&>svg]:w-3.5",+ op === "remove"+ ? "border-border bg-secondary text-muted-foreground"+ : "border-accent/20 bg-accent-soft text-accent",+ )}+ >+ {OP_ICON[op]}+ </span>+ <div className="min-w-0 flex-1">+ <p+ className={cn(+ "text-base leading-6",+ op === "remove" ? "text-muted-foreground line-through decoration-foreground-faint" : "text-foreground",+ )}+ >+ {splitDated(item.text).body || "–"}+ </p>+ <p className="mt-0.5 text-sm text-muted-foreground">+ <span className="font-mono">{FILE_OF_TARGET[item.target] ?? item.target}</span>+ {" · "}+ {t(`soul_view.op_${op}`)}+ {when && ` · ${when}`}+ </p>+ {item.evidence && item.evidence !== "[withheld]" && (+ <p className="mt-1.5 border-l-2 border-border pl-3 text-sm italic text-muted-foreground">+ “{item.evidence}”+ </p>+ )}+ </div>+ </li>+ );+ })}+ </ol>+ )}+ </ProfileGroup>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/soul/CharacterGroup.tsx b/jarvis/ui/web/frontend/src/views/soul/CharacterGroup.tsxnew file mode 100644index 0000000000..7b79f2c451--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/soul/CharacterGroup.tsx@@ -0,0 +1,82 @@+/**+ * Who the assistant is, read straight out of SOUL.md: its role and vibe as+ * label/value rows, then its tone rules and limits as short lists. The name+ * is not repeated here — it follows the wake word and already heads the page.+ */+import { Pencil } from "lucide-react";++import { Button } from "@/components/ui/button";+import { useT } from "@/i18n";+import { ProfileGroup } from "@/views/profile/ProfileGroup";+import type { CharacterFile, SoulRow } from "@/views/soul/api";++/** Inline Markdown emphasis is file syntax, not something to show. */+export function plain(text: string): string {+ return text.replace(/\*\*(.+?)\*\*/g, "$1").replace(/(^|\s)_(.+?)_(?=\s|$)/g, "$1$2").trim();+}++function RuleList({ title, rows }: { title: string; rows: SoulRow[] }) {+ return (+ <div className="px-5 py-4">+ <h3 className="text-base font-medium text-foreground">{title}</h3>+ <ul className="mt-2.5 flex flex-col gap-2">+ {rows.map((row, i) => (+ <li key={i} className="flex gap-3 text-base leading-6 text-muted-foreground">+ <span aria-hidden className="mt-2.5 h-1 w-1 shrink-0 rounded-full bg-foreground-faint" />+ <span className="min-w-0">+ {row.label && <span className="font-medium text-foreground">{plain(row.label)}: </span>}+ {plain(row.text)}+ </span>+ </li>+ ))}+ </ul>+ </div>+ );+}++export function CharacterGroup({ soul, onEdit }: { soul: CharacterFile | undefined; onEdit: () => void }) {+ const t = useT();+ const who = soul?.character.who ?? [];+ const tone = soul?.character.tone ?? [];+ const limits = soul?.character.limits ?? [];+ const empty = who.length + tone.length + limits.length === 0;++ return (+ <ProfileGroup+ testId="soul-character"+ title={t("soul_view.character_title")}+ description={t("soul_view.character_description")}+ aside={+ soul?.exists ? (+ <Button type="button" size="sm" variant="outline" onClick={onEdit}>+ <Pencil aria-hidden />+ {t("soul_view.character_edit")}+ </Button>+ ) : undefined+ }+ >+ {empty ? (+ <p className="px-5 py-4 text-base text-muted-foreground">+ {t(soul?.exists ? "soul_view.character_empty" : "soul_view.character_missing")}+ </p>+ ) : (+ <>+ {who.length > 0 && (+ <dl className="px-5 py-4">+ {who.map((row, i) => (+ <div key={i} className="flex flex-col gap-0.5 py-1.5 sm:flex-row sm:gap-6">+ <dt className="shrink-0 text-base font-medium text-foreground sm:w-28">+ {plain(row.label) || "·"}+ </dt>+ <dd className="min-w-0 text-base leading-6 text-muted-foreground">{plain(row.text)}</dd>+ </div>+ ))}+ </dl>+ )}+ {tone.length > 0 && <RuleList title={t("soul_view.tone_title")} rows={tone} />}+ {limits.length > 0 && <RuleList title={t("soul_view.limits_title")} rows={limits} />}+ </>+ )}+ </ProfileGroup>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/soul/FileList.tsx b/jarvis/ui/web/frontend/src/views/soul/FileList.tsxnew file mode 100644index 0000000000..1dc4440cbf--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/soul/FileList.tsx@@ -0,0 +1,102 @@+/**+ * The files behind the assistant — one row each, in the order it reads them:+ * its character, the person's instructions, its memory, its notes about the+ * person. A row says what the file is FOR in plain words, how full it is and+ * when it last changed, and opens the file in place.+ */+import { Brain, ChevronRight, ScrollText, Sparkles, UserRound } from "lucide-react";+import type { ReactNode } from "react";++import { Badge } from "@/components/ui/badge";+import { useT, useUiLanguage } from "@/i18n";+import { ProfileGroup } from "@/views/profile/ProfileGroup";+import type { SoulFile, SoulFileId } from "@/views/soul/api";+import { relativeDay } from "@/views/soul/format";++export const FILE_ICON: Record<SoulFileId, ReactNode> = {+ soul: <Sparkles />,+ instructions: <ScrollText />,+ memory: <Brain />,+ user: <UserRound />,+};++export function FileIcon({ id, size = "md" }: { id: SoulFileId; size?: "md" | "lg" }) {+ return (+ <span+ aria-hidden+ className={+ size === "lg"+ ? "flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-border bg-secondary text-muted-foreground [&>svg]:h-5 [&>svg]:w-5"+ : "flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border bg-secondary text-muted-foreground [&>svg]:h-4 [&>svg]:w-4"+ }+ >+ {FILE_ICON[id]}+ </span>+ );+}++/** "12 notes · updated today", or why there is nothing to show. */+export function useFileMeta(): (file: SoulFile) => string {+ const t = useT();+ const lang = useUiLanguage();+ return (file) => {+ if (!file.exists) return t("soul_view.file_missing");+ const size =+ "entries" in file+ ? t("soul_view.file_entries").replace("{0}", String(file.entries.length))+ : t("soul_view.file_chars").replace("{0}", file.chars.toLocaleString(lang));+ const when = relativeDay(file.updated_ms, lang);+ return when ? `${size} · ${t("soul_view.file_updated").replace("{0}", when)}` : size;+ };+}++export function FileList({+ files,+ onOpen,+}: {+ files: readonly SoulFile[];+ onOpen: (id: SoulFileId) => void;+}) {+ const t = useT();+ const meta = useFileMeta();++ return (+ <ProfileGroup+ testId="soul-files"+ title={t("soul_view.files_title")}+ description={t("soul_view.files_description")}+ >+ {files.map((file) => (+ <button+ key={file.id}+ type="button"+ data-testid={`soul-file-${file.id}`}+ onClick={() => onOpen(file.id)}+ className="group flex w-full items-center gap-4 px-5 py-4 text-left transition-colors hover:bg-secondary/60 focus-visible:bg-secondary/60 focus-visible:outline-none"+ >+ <FileIcon id={file.id} />+ <span className="min-w-0 flex-1">+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate font-mono text-sm font-semibold text-foreground-strong">+ {file.filename}+ </span>+ {!file.editable && (+ <Badge variant="secondary">{t("soul_view.file_by_assistant")}</Badge>+ )}+ </span>+ <span className="mt-0.5 block truncate text-sm text-muted-foreground">+ {t(`soul_view.file_role_${file.id}`)}+ </span>+ </span>+ <span className="hidden shrink-0 text-sm tabular-nums text-foreground-faint sm:block">+ {meta(file)}+ </span>+ <ChevronRight+ aria-hidden+ className="h-4 w-4 shrink-0 text-foreground-faint transition-colors group-hover:text-foreground"+ />+ </button>+ ))}+ </ProfileGroup>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/soul/FilePage.tsx b/jarvis/ui/web/frontend/src/views/soul/FilePage.tsxnew file mode 100644index 0000000000..0a5062cb8a--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/soul/FilePage.tsx@@ -0,0 +1,192 @@+/**+ * One of the assistant's files, opened in place with a back link.+ *+ * SOUL.md and the standing instructions are the person's to write: one card+ * with the editor (it scrolls inside itself) and the action row under it. MEMORY.md and+ * USER.md are written by the assistant itself: they open as their notes, each+ * of which can be forgotten, with one line saying how to change them.+ */+import { ArrowLeft, Eraser, FilePlus2, Info, RotateCcw, Save } from "lucide-react";+import { useEffect, useState, type ReactNode } from "react";++import { Button } from "@/components/ui/button";+import { Textarea } from "@/components/ui/textarea";+import { useT, useUiLanguage } from "@/i18n";+import { useEventStore } from "@/store/events";+import {+ useSaveInstructions,+ useSaveSoul,+ type CharacterFile,+ type InstructionsFile,+ type NotebookFile,+ type SoulFile,+} from "@/views/soul/api";+import { FileIcon, useFileMeta } from "@/views/soul/FileList";+import { NoteList } from "@/views/soul/NotesGroup";++function Header({ file }: { file: SoulFile }) {+ const t = useT();+ const meta = useFileMeta();+ return (+ <div className="flex items-center gap-4 px-1">+ <FileIcon id={file.id} size="lg" />+ <div className="min-w-0 flex-1">+ <h2 className="truncate font-mono text-lg font-semibold text-foreground-strong">{file.filename}</h2>+ <p className="truncate text-base text-muted-foreground">{t(`soul_view.file_role_${file.id}`)}</p>+ </div>+ <span className="hidden shrink-0 text-sm tabular-nums text-foreground-faint sm:block">{meta(file)}</span>+ </div>+ );+}++function Note({ children }: { children: string }) {+ return (+ <p className="flex items-start gap-2 px-1 text-sm text-muted-foreground">+ <Info aria-hidden className="mt-0.5 h-4 w-4 shrink-0" />+ <span>{children}</span>+ </p>+ );+}++function Editor({ file }: { file: CharacterFile | InstructionsFile }) {+ const t = useT();+ const lang = useUiLanguage();+ const pushToast = useEventStore((s) => s.pushToast);+ const saveSoul = useSaveSoul();+ const saveInstructions = useSaveInstructions();+ const [draft, setDraft] = useState(file.content);++ // A save (or a write from elsewhere) brings new content: take it.+ useEffect(() => setDraft(file.content), [file.content]);++ const isSoul = file.id === "soul";+ const saving = saveSoul.isPending || saveInstructions.isPending;+ const dirty = draft !== file.content;+ const template = file.id === "instructions" ? file.template : "";+ // SOUL.md can never be saved empty; the instructions file is cleared that way.+ const canSave = dirty && !saving && (!isSoul || draft.trim().length > 0);++ const onSave = () => {+ const done = {+ onSuccess: () =>+ pushToast(+ "success",+ t(!isSoul && !draft.trim() ? "soul_view.cleared" : "soul_view.saved"),+ ),+ onError: (e: Error) => pushToast("error", e.message),+ };+ if (isSoul) saveSoul.mutate(draft, done);+ else saveInstructions.mutate(draft, done);+ };++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-col rounded-xl border border-border bg-card">+ <label className="sr-only" htmlFor="soul-file-editor">+ {t("soul_view.editor_label").replace("{0}", file.filename)}+ </label>+ <Textarea+ id="soul-file-editor"+ data-testid="soul-file-editor"+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if ((e.ctrlKey || e.metaKey) && e.key === "s") {+ e.preventDefault();+ if (canSave) onSave();+ }+ }}+ spellCheck={false}+ placeholder={t(isSoul ? "soul_view.soul_placeholder" : "soul_view.instructions_placeholder")}+ className="h-[46vh] min-h-[300px] resize-none rounded-none rounded-t-xl border-0 bg-card p-5 font-mono text-sm leading-6 focus-visible:ring-0 focus-visible:ring-offset-0"+ />+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-b-xl border-t border-border bg-card px-5 py-3">+ <span className="text-sm tabular-nums text-foreground-faint">+ {dirty ? t("soul_view.unsaved") : t("soul_view.chars").replace("{0}", draft.length.toLocaleString(lang))}+ </span>+ <div className="flex items-center gap-2">+ {template && !draft.trim() && (+ <Button type="button" variant="ghost" onClick={() => setDraft(template)}>+ <FilePlus2 aria-hidden />+ {t("soul_view.load_template")}+ </Button>+ )}+ {!isSoul && file.exists && draft.trim() && !dirty && (+ <Button type="button" variant="ghost" onClick={() => setDraft("")}>+ <Eraser aria-hidden />+ {t("soul_view.clear")}+ </Button>+ )}+ <Button type="button" variant="ghost" disabled={!dirty || saving} onClick={() => setDraft(file.content)}>+ <RotateCcw aria-hidden />+ {t("soul_view.revert")}+ </Button>+ <Button type="button" disabled={!canSave} onClick={onSave} data-testid="soul-file-save">+ <Save aria-hidden />+ {saving ? t("soul_view.saving") : t("soul_view.save")}+ </Button>+ </div>+ </div>+ </div>+ <Note>{t(isSoul ? "soul_view.soul_note" : "soul_view.instructions_note")}</Note>+ </div>+ );+}++function Notebook({ file, canForget }: { file: NotebookFile; canForget: boolean }) {+ const t = useT();+ return (+ <div className="flex flex-col gap-3">+ <div className="overflow-hidden rounded-xl border border-border bg-card">+ <NoteList+ target={file.id}+ entries={file.entries}+ canForget={canForget}+ emptyText={t(`soul_view.empty_${file.id}`)}+ />+ </div>+ <Note>{t("soul_view.notebook_note")}</Note>+ </div>+ );+}++function isNotebook(file: SoulFile): file is NotebookFile {+ return file.id === "memory" || file.id === "user";+}++export function FilePage({+ file,+ canForget,+ onBack,+}: {+ file: SoulFile;+ canForget: boolean;+ onBack: () => void;+}) {+ const t = useT();+ let body: ReactNode;+ if (isNotebook(file)) {+ body = <Notebook file={file} canForget={canForget} />;+ } else if (file.exists || file.id === "instructions") {+ body = <Editor key={file.id} file={file} />;+ } else {+ body = <p className="px-1 text-base text-muted-foreground">{t("soul_view.character_missing")}</p>;+ }+ return (+ <div data-testid={`soul-page-${file.id}`} className="flex flex-col gap-5">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="self-start text-muted-foreground"+ onClick={onBack}+ data-testid="soul-back"+ >+ <ArrowLeft aria-hidden />+ {t("soul_view.back")}+ </Button>+ <Header file={file} />+ {body}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/soul/NotesGroup.tsx b/jarvis/ui/web/frontend/src/views/soul/NotesGroup.tsxnew file mode 100644index 0000000000..7154cb6a2b--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/soul/NotesGroup.tsx@@ -0,0 +1,142 @@+/**+ * What the assistant has learned, in its own three notebooks: about itself+ * (SOUL.md's learned section), its memory (MEMORY.md) and about the person+ * (USER.md). One group with an underline tab per notebook, so the page stays+ * one screen tall however much it has learned.+ *+ * A note can be forgotten. The learning ledger keeps the old text, so that is+ * an undoable act on the backend's side, and the button says "Forget" rather+ * than "Delete". It needs the learning loop running in this session; without+ * it the button is disabled and says why.+ */+import { X } from "lucide-react";+import { useState } from "react";++import { TabBar } from "@/components/layout/SectionTabBar";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { useT, useUiLanguage } from "@/i18n";+import { useEventStore } from "@/store/events";+import { fileOf, useForgetNote, type NoteTarget, type SoulEntry, type SoulProfile } from "@/views/soul/api";+import { relativeDay } from "@/views/soul/format";++/**+ * An explicit note is stored as "2026-10-02 (asked to remember): text" so the+ * prompt reads it in context; the page shows the text and the date apart.+ */+export function splitDated(text: string): { body: string; dateMs: number | null } {+ const m = /^(\d{4}-\d{2}-\d{2}) \([^)]*\): ([\s\S]*)$/.exec(text);+ if (!m) return { body: text, dateMs: null };+ const [y, mo, d] = m[1].split("-").map(Number);+ return { body: m[2], dateMs: new Date(y, mo - 1, d).getTime() };+}++export function NoteList({+ target,+ entries,+ canForget,+ emptyText,+}: {+ target: NoteTarget;+ entries: readonly SoulEntry[];+ canForget: boolean;+ emptyText: string;+}) {+ const t = useT();+ const lang = useUiLanguage();+ const pushToast = useEventStore((s) => s.pushToast);+ const forget = useForgetNote();++ if (entries.length === 0) {+ return (+ <p data-testid={`soul-notes-empty-${target}`} className="px-5 py-5 text-base text-muted-foreground">+ {emptyText}+ </p>+ );+ }++ return (+ <ul data-testid={`soul-notes-${target}`} className="divide-y divide-border">+ {entries.map((entry) => {+ const busy = forget.isPending && forget.variables?.id === entry.id;+ const { body, dateMs } = splitDated(entry.text);+ const date = relativeDay(dateMs, lang);+ return (+ <li key={entry.id} className="group flex items-start gap-3 px-5 py-3.5">+ <div className="min-w-0 flex-1">+ <p className="whitespace-pre-line text-base leading-6 text-foreground">{body}</p>+ {(entry.explicit || date) && (+ <p className="mt-1.5 flex items-center gap-2 text-sm text-muted-foreground">+ {entry.explicit && <Badge variant="accent">{t("soul_view.explicit_badge")}</Badge>}+ {date && <span>{date}</span>}+ </p>+ )}+ </div>+ <Button+ type="button"+ size="icon"+ variant="ghost"+ disabled={!canForget || busy}+ title={canForget ? t("soul_view.forget") : t("soul_view.forget_needs_loop")}+ aria-label={`${t("soul_view.forget")}: ${entry.text.slice(0, 60)}`}+ onClick={() =>+ forget.mutate(+ { target, id: entry.id },+ {+ onSuccess: () => pushToast("success", t("soul_view.forget_done")),+ onError: (e) => pushToast("error", e.message),+ },+ )+ }+ className="h-8 w-8 shrink-0 text-muted-foreground opacity-0 transition-opacity focus-visible:opacity-100 group-hover:opacity-100 disabled:group-hover:opacity-40"+ >+ <X />+ </Button>+ </li>+ );+ })}+ </ul>+ );+}++type Tab = NoteTarget;++export function NotesGroup({ profile }: { profile: SoulProfile }) {+ const t = useT();+ const [tab, setTab] = useState<Tab>("soul");++ const lists: Record<Tab, SoulEntry[]> = {+ soul: fileOf(profile, "soul")?.learned ?? [],+ memory: fileOf(profile, "memory")?.entries ?? [],+ user: fileOf(profile, "user")?.entries ?? [],+ };+ const title = t("soul_view.notes_title");++ return (+ <section data-testid="soul-notes" aria-label={title} className="flex flex-col gap-3">+ <div className="px-1">+ <h2 className="text-lg font-semibold text-foreground-strong">{title}</h2>+ <p className="mt-0.5 text-base text-muted-foreground">{t("soul_view.notes_description")}</p>+ </div>+ <div className="overflow-hidden rounded-xl border border-border bg-card">+ <TabBar+ className="px-5"+ active={tab}+ onChange={(id) => setTab(id as Tab)}+ tabs={[+ { id: "soul", label: t("soul_view.tab_self"), count: lists.soul.length },+ { id: "memory", label: t("soul_view.tab_memory"), count: lists.memory.length },+ { id: "user", label: t("soul_view.tab_user"), count: lists.user.length },+ ]}+ />+ <NoteList+ key={tab}+ target={tab}+ entries={lists[tab]}+ canForget={profile.learning}+ emptyText={t(`soul_view.empty_${tab}`)}+ />+ </div>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/soul/SoulHero.tsx b/jarvis/ui/web/frontend/src/views/soul/SoulHero.tsxnew file mode 100644index 0000000000..4e9823d04b--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/soul/SoulHero.tsx@@ -0,0 +1,90 @@+/**+ * The top of the SOUL.md page: the assistant itself.+ *+ * Its mark (the pet the person chose, alive and following the voice), its+ * name, what it is, and the one line of its own vibe from SOUL.md. Below,+ * four figures from the real files. Nothing here is invented: a missing+ * vibe is left out, and a figure without a source shows a dash.+ */+import { PetMark } from "@/components/pets/PetMark";+import { Badge } from "@/components/ui/badge";+import { useT, useUiLanguage } from "@/i18n";+import { fileOf, type SoulProfile } from "@/views/soul/api";+import { newest, relativeDay } from "@/views/soul/format";++function Stat({ label, value, sub }: { label: string; value: string; sub?: string | null }) {+ return (+ <div className="min-w-0 px-5 py-4">+ <p className="truncate text-sm text-muted-foreground">{label}</p>+ <p className="mt-0.5 truncate text-lg font-semibold tabular-nums text-foreground-strong">{value}</p>+ {sub && <p className="truncate text-sm text-muted-foreground">{sub}</p>}+ </div>+ );+}++/** "**Vibe:** Helpful but…" from the character rows, without its label. */+function vibeOf(profile: SoulProfile): string | null {+ const who = fileOf(profile, "soul")?.character.who ?? [];+ const row = who.find((r) => /^(vibe|stimmung|vibra)$/i.test(r.label));+ return row?.text.trim() || null;+}++export function SoulHero({ profile }: { profile: SoulProfile }) {+ const t = useT();+ const lang = useUiLanguage();++ const soul = fileOf(profile, "soul");+ const memory = fileOf(profile, "memory");+ const vibe = vibeOf(profile);+ const lastChange = relativeDay(newest(profile.files.map((f) => f.updated_ms)), lang);+ const learned = soul?.learned.length ?? 0;+ const remembered = memory?.entries.length ?? 0;++ return (+ <section+ data-testid="soul-hero"+ aria-label={profile.name}+ className="overflow-hidden rounded-xl border border-border bg-card"+ >+ <div className="flex items-center gap-5 p-6">+ <div className="flex h-20 w-20 shrink-0 items-center justify-center rounded-2xl border border-border bg-secondary">+ <PetMark size={56} reactive label={profile.name} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-2.5">+ <h2 className="truncate text-2xl font-semibold text-foreground-strong">{profile.name}</h2>+ <Badge+ variant={profile.learning ? "success" : "secondary"}+ title={t(profile.learning ? "soul_view.learning_on_hint" : "soul_view.learning_off_hint")}+ data-testid="soul-learning"+ >+ {t(profile.learning ? "soul_view.learning_on" : "soul_view.learning_off")}+ </Badge>+ </div>+ <p className="mt-0.5 truncate text-base text-muted-foreground">+ {t(profile.named ? "soul_view.hero_role" : "soul_view.hero_role_unnamed").replace(+ "{0}",+ profile.product,+ )}+ </p>+ {vibe && (+ <p data-testid="soul-vibe" className="mt-2 text-base leading-6 text-foreground">+ {vibe}+ </p>+ )}+ </div>+ </div>++ <div className="grid grid-cols-2 border-t border-border sm:grid-cols-4 [&>*]:border-border [&>*:nth-child(even)]:border-l sm:[&>*:not(:first-child)]:border-l [&>*:nth-child(n+3)]:border-t sm:[&>*:nth-child(n+3)]:border-t-0">+ <Stat+ label={t("soul_view.stat_wake")}+ value={profile.wake_phrase || "–"}+ sub={profile.wake_phrase ? t("soul_view.stat_wake_sub") : null}+ />+ <Stat label={t("soul_view.stat_self")} value={String(learned)} sub={t("soul_view.stat_notes")} />+ <Stat label={t("soul_view.stat_memory")} value={String(remembered)} sub={t("soul_view.stat_notes")} />+ <Stat label={t("soul_view.stat_updated")} value={lastChange ?? "–"} />+ </div>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/soul/api.ts b/jarvis/ui/web/frontend/src/views/soul/api.tsnew file mode 100644index 0000000000..6431c9746f--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/soul/api.ts@@ -0,0 +1,158 @@+/**+ * The SOUL.md page's data layer — the shapes `soul_routes.py` returns and the+ * three writes the page makes (save SOUL.md, save or clear the standing+ * instructions, forget one note).+ *+ * Every write answers with the whole profile, so the page swaps it in place+ * and never shows a stale count next to a fresh list.+ */+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";++// ----------------------------------------------------------------------+// Response shapes — mirror jarvis/ui/web/soul_routes.py+// ----------------------------------------------------------------------++export type SoulFileId = "soul" | "instructions" | "memory" | "user";+export type NoteTarget = "soul" | "memory" | "user";++export interface SoulEntry {+ id: string;+ text: string;+ importance: number;+ origin: string;+ /** The person asked for it ("remember …"), as opposed to a review's inference. */+ explicit: boolean;+}++export interface SoulRow {+ label: string;+ text: string;+}++interface FileBase {+ filename: string;+ exists: boolean;+ editable: boolean;+ updated_ms: number | null;+ chars: number;+}++export interface CharacterFile extends FileBase {+ id: "soul";+ content: string;+ character: { who: SoulRow[]; tone: SoulRow[]; limits: SoulRow[] };+ learned: SoulEntry[];+ name_in_file: string;+}++export interface InstructionsFile extends FileBase {+ id: "instructions";+ content: string;+ template: string;+}++export interface NotebookFile extends FileBase {+ id: "memory" | "user";+ entries: SoulEntry[];+}++export type SoulFile = CharacterFile | InstructionsFile | NotebookFile;++export interface SoulActivity {+ ts: string;+ source: string;+ target: string;+ operation: string;+ text: string;+ evidence: string;+}++export interface SoulProfile {+ name: string;+ named: boolean;+ product: string;+ wake_phrase: string;+ /** The learning loop runs in this session — notes can be forgotten. */+ learning: boolean;+ files: SoulFile[];+ activity: SoulActivity[];+}++export const SOUL_QUERY_KEY = ["soul"] as const;++async function request<T>(url: string, init?: RequestInit): Promise<T> {+ const res = await fetch(url, init);+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ const detail = (body as { detail?: unknown }).detail;+ throw new Error(typeof detail === "string" ? detail : `HTTP ${res.status}`);+ }+ return body as T;+}++export function useSoulProfile() {+ return useQuery<SoulProfile, Error>({+ queryKey: SOUL_QUERY_KEY,+ queryFn: () => request<SoulProfile>("/api/soul"),+ retry: false,+ });+}++interface FileById {+ soul: CharacterFile;+ instructions: InstructionsFile;+ memory: NotebookFile;+ user: NotebookFile;+}++/** The one file of each kind; `undefined` while the profile is loading. */+export function fileOf<K extends SoulFileId>(+ profile: SoulProfile | undefined,+ id: K,+): FileById[K] | undefined {+ return profile?.files.find((f) => f.id === id) as FileById[K] | undefined;+}++export function useSaveSoul() {+ const client = useQueryClient();+ return useMutation<SoulProfile, Error, string>({+ mutationFn: (content) =>+ request<SoulProfile>("/api/soul/file", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ content }),+ }),+ onSuccess: (profile) => client.setQueryData(SOUL_QUERY_KEY, profile),+ });+}++/** Saves the standing instructions; an empty text clears the file. */+export function useSaveInstructions() {+ const client = useQueryClient();+ return useMutation<unknown, Error, string>({+ mutationFn: (content) =>+ request(+ "/api/settings/agent-instructions",+ content.trim()+ ? {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ content }),+ }+ : { method: "DELETE" },+ ),+ onSuccess: () => client.invalidateQueries({ queryKey: SOUL_QUERY_KEY }),+ });+}++export function useForgetNote() {+ const client = useQueryClient();+ return useMutation<SoulProfile, Error, { target: NoteTarget; id: string }>({+ mutationFn: ({ target, id }) =>+ request<SoulProfile>(+ `/api/soul/entries/${encodeURIComponent(target)}/${encodeURIComponent(id)}`,+ { method: "DELETE" },+ ),+ onSuccess: (profile) => client.setQueryData(SOUL_QUERY_KEY, profile),+ });+}diff --git a/jarvis/ui/web/frontend/src/views/soul/format.ts b/jarvis/ui/web/frontend/src/views/soul/format.tsnew file mode 100644index 0000000000..274ee46095--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/soul/format.ts@@ -0,0 +1,49 @@+/**+ * Small, pure formatting helpers for the SOUL.md page — dates the way a+ * person says them ("today", "3 days ago") and the ledger's timestamps.+ */+import type { UiLanguage } from "@/i18n";++const DAY_MS = 86_400_000;++/**+ * The learning ledger writes `2026-10-02T10:00:10+0200` (strftime `%z`, no+ * colon), which not every engine parses; this adds the colon.+ */+export function parseLedgerTime(ts: string): number | null {+ if (!ts) return null;+ const normalized = ts.replace(/([+-]\d{2})(\d{2})$/, "$1:$2");+ const ms = Date.parse(normalized);+ return Number.isNaN(ms) ? null : ms;+}++/** "today", "yesterday", "3 days ago"; a plain date past a month. */+export function relativeDay(ms: number | null, lang: UiLanguage, now: number = Date.now()): string | null {+ if (ms === null) return null;+ const startOf = (t: number) => {+ const d = new Date(t);+ d.setHours(0, 0, 0, 0);+ return d.getTime();+ };+ const days = Math.round((startOf(now) - startOf(ms)) / DAY_MS);+ if (days >= 0 && days <= 30) {+ return new Intl.RelativeTimeFormat(lang, { numeric: "auto" }).format(-days, "day");+ }+ return new Date(ms).toLocaleDateString(lang, { day: "numeric", month: "short", year: "numeric" });+}++/** A time of day for an entry from today, else the relative day. */+export function whenShort(ms: number | null, lang: UiLanguage, now: number = Date.now()): string | null {+ if (ms === null) return null;+ const sameDay = new Date(ms).toDateString() === new Date(now).toDateString();+ if (sameDay) {+ return new Date(ms).toLocaleTimeString(lang, { hour: "2-digit", minute: "2-digit" });+ }+ return relativeDay(ms, lang, now);+}++/** The newest of several file times; `null` when none is known. */+export function newest(times: readonly (number | null | undefined)[]): number | null {+ const known = times.filter((t): t is number => typeof t === "number");+ return known.length ? Math.max(...known) : null;+}diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex a732561c40..22d0472129 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -396,6 +396,7 @@ class WebServer:from .self_mod_routes import router as self_mod_routerfrom .sessions_routes import router as sessions_routerfrom .settings_routes import router as settings_router+ from .soul_routes import router as soul_routerfrom .setup_report_routes import router as setup_report_routerfrom .setup_routes import router as setup_routerfrom .skills_routes import router as skills_router@@ -469,6 +470,7 @@ class WebServer:app.include_router(desktop_router)app.include_router(profile_router)app.include_router(settings_router)+ app.include_router(soul_router)app.include_router(permissions_router)# In-app updater (GET status / POST apply). Managed-install only — see# jarvis/ui/web/update_routes.py; refuses to self-reset a dev checkout.diff --git a/jarvis/ui/web/soul_routes.py b/jarvis/ui/web/soul_routes.pynew file mode 100644index 0000000000..16a87d87f0--- /dev/null+++ b/jarvis/ui/web/soul_routes.py@@ -0,0 +1,311 @@+"""REST API for the SOUL.md section — the assistant's own profile.++The section shows every file that shapes who the assistant is, in one place:++* ``SOUL.md`` (``data/workspace/SOUL.md``) — its character: name, role, tone,+ limits, and the notes it keeps about itself (``update_soul``);+* the standing instructions the person writes for it+ (``data/agent_instructions/<Name>.md``, edited through+ ``/api/settings/agent-instructions``);+* ``MEMORY.md`` and ``USER.md`` in the vault (``society/jarvis/``) — what it+ was asked to remember, its working notes, and what it noticed about the+ person (``jarvis.memory.learning.notebook``).++Endpoints:+ GET /api/soul → the whole profile+ PUT /api/soul/file → save SOUL.md's Markdown+ DELETE /api/soul/entries/{target}/{entry_id} → forget one learned note++Reads never create a file: a fresh install shows the files as missing+rather than seeding them from a GET.+"""++from __future__ import annotations++import json+import logging+from pathlib import Path+from typing import Any, Literal++from fastapi import APIRouter, HTTPException, Request+from pydantic import BaseModel, Field++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api/soul", tags=["soul"])++#: How many recent learning-ledger lines the activity list shows.+_ACTIVITY_LIMIT = 12+#: Longest quote of what the person said that one activity line carries.+_EVIDENCE_CHARS = 220+#: The ledger rotates at 256 KB; reading its tail is enough for the list.+_LEDGER_TAIL_BYTES = 64 * 1024+++class SoulBody(BaseModel):+ # The Markdown under the frontmatter. Empty is refused: SOUL.md is the+ # assistant's identity and the page has no "delete" for it.+ content: str = Field(..., min_length=1)+++def _config(request: Request) -> Any:+ return getattr(request.app.state, "config", None) or getattr(request.app.state, "cfg", None)+++def _mtime_ms(path: Path) -> int | None:+ try:+ return int(path.stat().st_mtime * 1000)+ except OSError:+ return None+++def _entry(entry: Any) -> dict[str, Any]:+ from jarvis.memory.learning.notebook import EXPLICIT_ORIGIN++ return {+ "id": entry.id,+ "text": entry.text,+ "importance": entry.importance,+ "origin": entry.origin,+ "explicit": entry.origin == EXPLICIT_ORIGIN,+ }+++def _labelled(lines: list[str]) -> list[dict[str, str]]:+ """``- **Role:** text`` bullets as ``{label, text}``; plain bullets keep no label."""+ out: list[dict[str, str]] = []+ for line in lines:+ text = line.strip()+ if text[:2] in ("- ", "* "):+ text = text[2:].strip()+ label = ""+ if text.startswith("**") and ":**" in text:+ label, text = text[2:].split(":**", 1)+ label, text = label.strip(), text.strip()+ elif text.startswith("**") and text.count("**") >= 2:+ label, text = text[2:].split("**", 1)+ label, text = label.strip().rstrip(":"), text.strip().lstrip(":").strip()+ if text or label:+ out.append({"label": label, "text": text})+ return out+++def _soul_file(path: Path) -> dict[str, Any]:+ from jarvis.memory.soul import Soul++ base: dict[str, Any] = {+ "id": "soul",+ "filename": path.name,+ "exists": path.is_file(),+ "editable": True,+ "updated_ms": _mtime_ms(path),+ "content": "",+ "chars": 0,+ "character": {"who": [], "tone": [], "limits": []},+ "learned": [],+ "name_in_file": "",+ }+ if not base["exists"]:+ return base+ try:+ soul = Soul.load(path)+ except (OSError, ValueError):+ log.warning("soul: SOUL.md could not be read", exc_info=True)+ base["exists"] = False+ return base+ sections = soul.sections()+ base.update(+ content=soul.body,+ chars=len(soul.body),+ character={key: _labelled(lines) for key, lines in sections.items()},+ learned=[_entry(e) for e in soul.learned()],+ name_in_file=soul.name,+ )+ return base+++def _instructions_file(config: Any) -> dict[str, Any]:+ from jarvis.brain import agent_instructions++ path = agent_instructions.instructions_path(config)+ content = agent_instructions.read_agent_instructions(config) or ""+ return {+ "id": "instructions",+ "filename": path.name,+ "exists": bool(content),+ "editable": True,+ "updated_ms": _mtime_ms(path) if content else None,+ "content": content,+ "chars": len(content),+ "template": agent_instructions.seed_template(config),+ }+++def _notebook_folder(config: Any) -> Path | None:+ from jarvis.memory.learning.notebook import OWNER_ID+ from jarvis.society.memory import resolve_society_vault+ from jarvis.society.memory_books import folder_for++ try:+ return folder_for(resolve_society_vault(config), OWNER_ID)+ except Exception: # noqa: BLE001 — no vault means no notebooks to show, not a failure+ log.debug("soul: the notebook folder is unavailable", exc_info=True)+ return None+++def _book_file(folder: Path | None, target: str) -> dict[str, Any]:+ from jarvis.society.memory_books import FILES, body+ from jarvis.society.notebook import parse++ filename = FILES[target]+ path = folder / filename if folder is not None else None+ base: dict[str, Any] = {+ "id": target,+ "filename": filename,+ "exists": bool(path and path.is_file()),+ "editable": False,+ "updated_ms": _mtime_ms(path) if path else None,+ "entries": [],+ "chars": 0,+ }+ if not base["exists"] or path is None:+ return base+ try:+ entries = parse(body(path.read_text(encoding="utf-8")))+ except (OSError, ValueError):+ log.warning("soul: %s could not be read", filename, exc_info=True)+ return base+ # Newest first: the page answers "what did it learn lately" before "since when".+ ordered = sorted(entries, key=lambda e: e.revision, reverse=True)+ base["entries"] = [_entry(e) for e in ordered]+ base["chars"] = sum(len(e.text) for e in entries)+ return base+++def _activity(folder: Path | None) -> list[dict[str, Any]]:+ """The most recent learning-ledger lines, newest first."""+ from jarvis.memory.learning.notebook import LEDGER_NAME++ if folder is None:+ return []+ ledger = folder / LEDGER_NAME+ try:+ with ledger.open("rb") as handle:+ handle.seek(0, 2)+ size = handle.tell()+ handle.seek(max(0, size - _LEDGER_TAIL_BYTES))+ tail = handle.read().decode("utf-8", errors="replace")+ except OSError:+ return []+ lines = tail.splitlines()+ if size > _LEDGER_TAIL_BYTES and lines:+ lines = lines[1:] # the first line of a mid-file tail is cut off+ out: list[dict[str, Any]] = []+ for line in reversed(lines):+ try:+ record = json.loads(line)+ except ValueError:+ continue+ if not isinstance(record, dict):+ continue+ operation = str(record.get("operation", ""))+ text = str(record.get("before" if operation == "remove" else "after", "") or "")+ evidence = str(record.get("evidence", "") or "")+ if len(evidence) > _EVIDENCE_CHARS:+ evidence = evidence[: _EVIDENCE_CHARS - 1].rstrip() + "…"+ out.append(+ {+ "ts": str(record.get("ts", "")),+ "source": str(record.get("source", "")),+ "target": str(record.get("target", "")),+ "operation": operation,+ "text": text,+ "evidence": evidence,+ }+ )+ if len(out) >= _ACTIVITY_LIMIT:+ break+ return out+++def _wake_phrase(config: Any) -> str:+ trigger = getattr(config, "trigger", None)+ wake_word = getattr(trigger, "wake_word", None) if trigger is not None else None+ return str(getattr(wake_word, "phrase", "") or "") if wake_word is not None else ""+++def _payload(request: Request) -> dict[str, Any]:+ from jarvis.brain.assistant_name import DEFAULT_ASSISTANT_NAME, resolve_assistant_name+ from jarvis.brain.identity import PRODUCT_NAME, soul_path+ from jarvis.memory.learning import notebook as notebook_module++ config = _config(request)+ try:+ name = resolve_assistant_name(config)+ except Exception: # noqa: BLE001 — the page still renders with the fallback name+ log.debug("soul: assistant name unavailable", exc_info=True)+ name = DEFAULT_ASSISTANT_NAME+ folder = _notebook_folder(config)+ return {+ "name": name,+ "named": name != DEFAULT_ASSISTANT_NAME,+ "product": PRODUCT_NAME,+ "wake_phrase": _wake_phrase(config),+ "learning": notebook_module.active() is not None,+ "files": [+ _soul_file(soul_path()),+ _instructions_file(config),+ _book_file(folder, "memory"),+ _book_file(folder, "user"),+ ],+ "activity": _activity(folder),+ }++[email protected]("", summary="The assistant's profile: SOUL.md and every file that shapes it")+def get_soul(request: Request) -> dict[str, Any]:+ return _payload(request)++[email protected]("/file", summary="Save SOUL.md")+def put_soul(body: SoulBody, request: Request) -> dict[str, Any]:+ """Write SOUL.md's Markdown under its lock; the next prompt reads it."""+ from jarvis.brain.identity import soul_path+ from jarvis.memory.soul import edit_soul++ if not body.content.strip():+ raise HTTPException(status_code=400, detail="SOUL.md must not be empty.")+ path = soul_path()+ if not path.is_file():+ raise HTTPException(status_code=404, detail="SOUL.md does not exist yet.")+ try:+ edit_soul(path, lambda soul: soul.set_body(body.content))+ except TimeoutError as exc:+ raise HTTPException(status_code=409, detail="SOUL.md is busy; try again.") from exc+ except OSError as exc:+ raise HTTPException(status_code=500, detail=f"Could not save: {exc}") from exc+ return {"ok": True, **_payload(request)}++[email protected]("/entries/{target}/{entry_id}", summary="Forget one learned note")+def forget_entry(+ target: Literal["soul", "memory", "user"], entry_id: str, request: Request+) -> dict[str, Any]:+ """Remove one note; the learning ledger keeps its old text, so it is recoverable."""+ from jarvis.memory.learning import notebook as notebook_module++ notebook = notebook_module.active()+ if notebook is None:+ raise HTTPException(+ status_code=503, detail="The learning loop is not running in this session."+ )+ try:+ notebook.apply(+ target=target,+ operation="remove",+ entry_id=entry_id,+ source="soul page: forgotten by the user",+ )+ except ValueError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ return {"ok": True, **_payload(request)}diff --git a/tests/integration/test_soul_routes.py b/tests/integration/test_soul_routes.pynew file mode 100644index 0000000000..c05b2bd1ad--- /dev/null+++ b/tests/integration/test_soul_routes.py@@ -0,0 +1,157 @@+"""Integration tests for /api/soul — the assistant's profile page.++Real files under ``tmp_path``: SOUL.md in the data dir, the instructions file+next to it, and the notebooks in a throwaway vault. No provider, no mocks.+"""++from __future__ import annotations++import json+from collections.abc import Iterator+from pathlib import Path++import pytest+from fastapi.testclient import TestClient++import jarvis.core.config as core_config+import jarvis.society.memory as society_memory+from jarvis.brain import agent_instructions, identity+from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+from jarvis.memory.learning import notebook as notebook_module+from jarvis.memory.learning.notebook import JarvisNotebook+from jarvis.memory.soul import Soul+from jarvis.memory.templates import render_soul_md+from jarvis.ui.web.server import WebServer++[email protected](autouse=True)+def _isolate(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:+ monkeypatch.setattr(core_config, "DATA_DIR", tmp_path / "data")+ monkeypatch.setattr(society_memory, "resolve_society_vault", lambda cfg: tmp_path / "vault")+ notebook_module.set_active(None)+ identity.invalidate_cache()+ yield+ notebook_module.set_active(None)+++def server() -> WebServer:+ cfg = JarvisConfig()+ cfg.ui.dev_mode = True+ bus = EventBus()+ s = WebServer(cfg, bus=bus)+ s.app.state.config = cfg+ s.app.state.bus = bus+ return s+++def _write_soul(text: str | None = None) -> Path:+ path = identity.soul_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text if text is not None else render_soul_md(), encoding="utf-8")+ return path+++def _files(body: dict) -> dict[str, dict]:+ return {f["id"]: f for f in body["files"]}+++def test_a_fresh_install_lists_every_file_as_missing_and_creates_none(+ server: WebServer, tmp_path: Path+) -> None:+ with TestClient(server.app) as client:+ body = client.get("/api/soul").json()+ files = _files(body)+ assert list(files) == ["soul", "instructions", "memory", "user"]+ assert all(not f["exists"] for f in files.values())+ assert files["soul"]["filename"] == "SOUL.md"+ assert files["instructions"]["filename"] == agent_instructions.instructions_filename(+ server.app.state.config+ )+ assert files["instructions"]["template"].strip()+ assert body["activity"] == []+ assert body["learning"] is False+ # A GET never seeds anything.+ assert not (tmp_path / "vault").exists()+ assert not identity.soul_path().exists()+++def test_the_character_is_split_into_labelled_rows(server: WebServer) -> None:+ _write_soul()+ with TestClient(server.app) as client:+ soul = _files(client.get("/api/soul").json())["soul"]+ assert soul["exists"] is True and soul["editable"] is True+ who = {row["label"]: row["text"] for row in soul["character"]["who"]}+ assert "Role" in who and "Vibe" in who+ # The name line is managed by the wake word, so it is not a character row.+ assert "Name" not in who+ assert soul["character"]["tone"] and soul["character"]["limits"]+ assert "## Who I am" in soul["content"]+ assert not soul["content"].startswith("---") # the frontmatter stays out of the editor+++def test_saving_soul_md_keeps_the_frontmatter_and_the_learned_notes(server: WebServer) -> None:+ path = _write_soul()+ soul = Soul.load(path)+ soul.append_calibration("Answers in short spoken sentences.")+ soul.save()+ edited = Soul.load(path).body.replace(+ "Helpful but not obsequious.", "Calm, warm and to the point."+ )+ with TestClient(server.app) as client:+ resp = client.put("/api/soul/file", json={"content": edited})+ assert resp.status_code == 200+ saved = _files(resp.json())["soul"]+ assert "Calm, warm and to the point." in saved["content"]+ assert [e["text"] for e in saved["learned"]] == ["Answers in short spoken sentences."]+ raw = path.read_text(encoding="utf-8")+ assert raw.startswith("---") and "subject_type: agent" in raw+ # The prompt sees the edit on its next build.+ identity.invalidate_cache()+ assert "Calm, warm and to the point." in identity.character_block(path=path)+++def test_saving_refuses_an_empty_or_missing_soul(server: WebServer) -> None:+ with TestClient(server.app) as client:+ assert client.put("/api/soul/file", json={"content": "x"}).status_code == 404+ _write_soul()+ assert client.put("/api/soul/file", json={"content": " "}).status_code == 400+++def test_notebooks_and_activity_come_from_the_vault(server: WebServer, tmp_path: Path) -> None:+ book = JarvisNotebook(tmp_path / "vault")+ book.keep_explicit("Ruben's sister is called Lena.", via_tool=True, evidence="merk dir das")+ book.apply(target="user", operation="add", text="The user prefers short answers.")+ with TestClient(server.app) as client:+ body = client.get("/api/soul").json()+ files = _files(body)+ memory = files["memory"]["entries"]+ assert len(memory) == 1 and memory[0]["explicit"] is True+ assert "Lena" in memory[0]["text"]+ assert [e["text"] for e in files["user"]["entries"]] == ["The user prefers short answers."]+ assert files["memory"]["editable"] is False+ # Newest first, with what the person said.+ assert [a["target"] for a in body["activity"]] == ["user", "memory"]+ assert body["activity"][1]["evidence"] == "merk dir das"+++def test_forgetting_a_note_needs_the_running_loop_and_is_ledgered(+ server: WebServer, tmp_path: Path+) -> None:+ book = JarvisNotebook(tmp_path / "vault")+ book.apply(target="memory", operation="add", text="Builds Personal Jarvis.")+ entry_id = book.entries()["memory"][0].id+ with TestClient(server.app) as client:+ assert client.delete(f"/api/soul/entries/memory/{entry_id}").status_code == 503+ notebook_module.set_active(book)+ assert client.delete("/api/soul/entries/memory/nope").status_code == 404+ assert client.delete(f"/api/soul/entries/bogus/{entry_id}").status_code == 422+ resp = client.delete(f"/api/soul/entries/memory/{entry_id}")+ assert resp.status_code == 200+ assert _files(resp.json())["memory"]["entries"] == []+ assert resp.json()["activity"][0]["operation"] == "remove"+ assert resp.json()["activity"][0]["text"] == "Builds Personal Jarvis."+ ledger = (book.folder / notebook_module.LEDGER_NAME).read_text(encoding="utf-8")+ last = json.loads(ledger.strip().splitlines()[-1])+ assert last["source"] == "soul page: forgotten by the user"diff --git a/tests/unit/brain/test_identity.py b/tests/unit/brain/test_identity.pyindex 0cf72ed8f7..8d31d51e81 100644--- a/tests/unit/brain/test_identity.py+++ b/tests/unit/brain/test_identity.py@@ -109,3 +109,19 @@ def test_the_realtime_instructions_open_with_the_identity() -> None:for compact in (False, True):text = _session_instructions("en", identity=block, compact=compact)assert text.startswith(block)+++def test_a_gpt_live_call_carries_the_standing_instructions(tmp_path: Path, monkeypatch) -> None:+ # The live call answered "I have not seen a George.md" (2026-10-02):+ # GPT-Live never received the instructions file the other surfaces read.+ import jarvis.core.config as core_config+ from jarvis.brain import agent_instructions+ from jarvis.live.session import _identity++ monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)+ config = _config("Hey George")+ agent_instructions.save_agent_instructions(config, "Call me Ruben. Answer in German.")+ text = _identity(config)+ assert text.startswith("YOUR NAME IS GEORGE")+ assert "(from George.md)" in text+ assert "Call me Ruben. Answer in German." in text