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(verse): show George's memory writes in his thought bubble
rubenluetke10-beepd9fc4929098d
diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex d006a10fb6..7168a84f21 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -640,6 +640,22 @@ class MemoryUpdated(Event):operation: str = "put" # "put" | "forget"+@dataclass(frozen=True, slots=True)+class MemoryFileWrite(Event):+ """An agent's persistent memory file is being written, or the write settled.++ Published by ``jarvis.memory.write_feedback`` around the real write:+ ``pending`` first, then ``saved`` only after the file was replaced on+ disk, ``unchanged`` for a no-op, ``failed`` when the write raised. Both+ steps share ``update_id``. Carries no path, entry text or error detail.+ """+ update_id: str = ""+ agent_id: str = ""+ file: str = "" # bare name, e.g. "MEMORY.md"; "" when not known yet+ phase: str = "pending" # pending | saved | unchanged | failed+ operation: str = "edit" # add | replace | remove | edit++@dataclass(frozen=True, slots=True)class ProfileUpdated(Event):"""The Curator wrote a fact to USER.md / people/*.md.diff --git a/jarvis/friends/status_filter.py b/jarvis/friends/status_filter.pyindex 34b7e62438..9d67f63beb 100644--- a/jarvis/friends/status_filter.py+++ b/jarvis/friends/status_filter.py@@ -91,6 +91,7 @@ HARD_BLACKLIST: frozenset[str] = frozenset("ErrorOccurred",# Memory mutations"MemoryUpdated",+ "MemoryFileWrite",})diff --git a/jarvis/memory/learning/loop.py b/jarvis/memory/learning/loop.pyindex 0fc3a23e02..9141b2ebb5 100644--- a/jarvis/memory/learning/loop.py+++ b/jarvis/memory/learning/loop.py@@ -560,6 +560,7 @@ def start_learning(config: Any, bus: Any) -> JarvisLearningLoop | None:from jarvis.memory.learning import notebook as notebook_modulefrom jarvis.memory.learning.review import ModelReviewer+ _connect_write_feedback(bus)cfg = config.memory.learningif not cfg.enabled:notebook_module.set_active(None)@@ -585,11 +586,28 @@ def start_learning(config: Any, bus: Any) -> JarvisLearningLoop | None:return _loop+def _connect_write_feedback(bus: Any) -> None:+ """Show Jarvis' memory writes in the UI (``MemoryFileWrite`` on ``bus``).++ Wired even when learning is off: the remember and update_soul tools still+ write memory files then, and the person should see those writes too.+ """+ from jarvis.memory import write_feedback++ try:+ write_feedback.connect(bus)+ except RuntimeError:+ # No running event loop (a synchronous test harness): nothing to show it on.+ log.debug("learning: memory write receipts not wired (no running loop)")++async def stop_learning() -> None:global _loop+ from jarvis.memory import write_feedbackfrom jarvis.memory.learning import notebook as notebook_moduleloop, _loop = _loop, Nonenotebook_module.set_active(None)+ write_feedback.disconnect()if loop is not None:await loop.stop()diff --git a/jarvis/memory/learning/notebook.py b/jarvis/memory/learning/notebook.pyindex d990d62460..d13198a48f 100644--- a/jarvis/memory/learning/notebook.py+++ b/jarvis/memory/learning/notebook.py@@ -150,6 +150,15 @@ class JarvisNotebook:books[SOUL] = self._soul_entries()return books+ def _file_name(self, target: str) -> str:+ """The real file a target is kept in, as the UI may name it."""+ from jarvis.memory.workspace import SOUL_MD+ from jarvis.society.memory_books import FILES++ if target == SOUL:+ return self.soul_path.name if self.soul_path is not None else SOUL_MD+ return FILES[target]+def _soul_entries(self) -> list[Any]:from jarvis.memory.soul import Soul@@ -201,6 +210,7 @@ class JarvisNotebook:Every applied change is appended to a ledger with its old and new text,so nothing the loop replaces or removes is ever unrecoverable."""+ from jarvis.memory.write_feedback import announce_writefrom jarvis.society.memory_books import edit_bookif target not in TARGETS:@@ -220,33 +230,41 @@ class JarvisNotebook:if grown > budget * _HARD_LIMIT and grown > used:raise ValueError(f"the {target} notebook is full; consolidate first")if target == SOUL:- if not self._edit_soul(- text, operation=operation, entry_id=entry_id, importance=importance, origin=origin- ):- return None- after = text if operation != "remove" else ""- change = Change(target, operation, entry_id, before, after)- self._append_ledger(change, evidence=evidence, source=source)- return change- for attempt in range(_REPLACE_ATTEMPTS):- try:- result = edit_book(- self._vault,- self._owner,+ with announce_write(OWNER_ID, self._file_name(SOUL), operation=operation) as receipt:+ receipt.changed = self._edit_soul(text,- target=target,operation=operation,entry_id=entry_id,- importance=max(1, min(10, int(importance))),+ importance=importance,origin=origin,)- break- except PermissionError:- # Windows refuses to replace a file another process (a virus- # scanner, the search indexer, Obsidian) has open for a moment.- if attempt == _REPLACE_ATTEMPTS - 1:- raise- time.sleep(0.05 * (attempt + 1))+ if not receipt.changed:+ return None+ after = text if operation != "remove" else ""+ change = Change(target, operation, entry_id, before, after)+ self._append_ledger(change, evidence=evidence, source=source)+ return change+ with announce_write(OWNER_ID, self._file_name(target), operation=operation) as receipt:+ for attempt in range(_REPLACE_ATTEMPTS):+ try:+ result = edit_book(+ self._vault,+ self._owner,+ text,+ target=target,+ operation=operation,+ entry_id=entry_id,+ importance=max(1, min(10, int(importance))),+ origin=origin,+ )+ break+ except PermissionError:+ # Windows refuses to replace a file another process (a virus+ # scanner, the search indexer, Obsidian) has open for a moment.+ if attempt == _REPLACE_ATTEMPTS - 1:+ raise+ time.sleep(0.05 * (attempt + 1))+ receipt.changed = result.changedif not result.changed:return Nonechange = Change(target, operation, entry_id, before, text if operation != "remove" else "")diff --git a/jarvis/memory/write_feedback.py b/jarvis/memory/write_feedback.pynew file mode 100644index 0000000000..b8a1a09707--- /dev/null+++ b/jarvis/memory/write_feedback.py@@ -0,0 +1,145 @@+"""Visible receipts for an agent's persistent memory writes.++A write to one of an agent's memory files (``MEMORY.md``, ``USER.md``,+``SOUL.md``, the legacy ``core_memory.json``) announces itself in up to two+steps that share one ``update_id``:++* ``pending`` — the write is about to start; nothing is saved yet;+* ``saved`` — the file was replaced on disk (only after the write returned);+* ``unchanged`` — the write finished but changed nothing (a duplicate);+* ``failed`` — the write raised; whatever the file held before still holds.++The UI (the lead pet's thought bubble in the Jarvis Verse) shows "Updating+memory · MEMORY.md" for ``pending`` and claims success only on ``saved``.++Only the bare file name, the agent id and the operation cross this boundary —+never a path, the entry text or an error message — so the event is safe to+forward to every open window.++This module is low-level on purpose (no bus import): the memory layers call+:func:`announce_write`; the app wires a sink with :func:`connect` once its+event loop and bus exist. Without a sink every call is a cheap no-op, so a+headless test or a CLI write never needs a bus.+"""++from __future__ import annotations++import asyncio+import logging+import re+import threading+import uuid+from collections.abc import Callable, Iterator+from contextlib import contextmanager+from dataclasses import dataclass+from typing import Any, Final++log = logging.getLogger(__name__)++PHASES: Final[tuple[str, ...]] = ("pending", "saved", "unchanged", "failed")+#: A memory file is a bare name like ``MEMORY.md``; anything else is dropped.+_FILE_NAME: Final = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")+_AGENT_ID: Final = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,79}$")+_OPERATIONS: Final[frozenset[str]] = frozenset({"add", "replace", "remove", "edit"})++Sink = Callable[[str, str, str, str, str], None]+"""``sink(update_id, agent_id, file, phase, operation)``."""++_sink: Sink | None = None+_sink_lock = threading.Lock()+++def safe_file_name(name: str) -> str:+ """The bare file name of ``name``, or ``""`` when it is not one we can show."""+ base = str(name or "").replace("\\", "/").rsplit("/", 1)[-1]+ return base if _FILE_NAME.match(base) and base not in {".", ".."} else ""+++def set_sink(sink: Sink | None) -> None:+ global _sink+ with _sink_lock:+ _sink = sink+++def _emit(update_id: str, agent_id: str, file: str, phase: str, operation: str) -> None:+ sink = _sink+ if sink is None:+ return+ try:+ sink(update_id, agent_id, file, phase, operation)+ except Exception: # noqa: BLE001 — a receipt must never fail or undo the write it describes+ log.debug("memory write receipt not delivered (%s)", phase, exc_info=True)+++@dataclass+class WriteReceipt:+ """Filled in by the writer inside :func:`announce_write`."""++ #: Set to ``False`` when the write turned out to change nothing.+ changed: bool = True+ #: Set when the target file is only known after the write (auto-classified).+ file: str = ""+++@contextmanager+def announce_write(agent_id: str, file: str, *, operation: str = "edit") -> Iterator[WriteReceipt]:+ """Announce one memory write around the code that performs it.++ ``pending`` goes out before the body runs; ``saved`` / ``unchanged`` only+ after it returned, ``failed`` when it raised (the exception propagates+ unchanged). An agent id or file name that does not look like one is never+ forwarded; the write itself always runs.+ """+ receipt = WriteReceipt(file=safe_file_name(file))+ agent = str(agent_id or "")+ op = operation if operation in _OPERATIONS else "edit"+ if _sink is None or not _AGENT_ID.match(agent):+ yield receipt+ return+ update_id = uuid.uuid4().hex+ _emit(update_id, agent, receipt.file, "pending", op)+ try:+ yield receipt+ except BaseException:+ _emit(update_id, agent, safe_file_name(receipt.file), "failed", op)+ raise+ settled = "saved" if receipt.changed else "unchanged"+ _emit(update_id, agent, safe_file_name(receipt.file), settled, op)+++def connect(bus: Any, loop: asyncio.AbstractEventLoop | None = None) -> None:+ """Publish every receipt as a ``MemoryFileWrite`` event on ``bus``.++ Thread-safe: memory writes run in worker threads (``asyncio.to_thread``),+ so each event is handed to ``loop`` in call order. A closed loop (shutdown)+ drops the receipt quietly — nobody is left to show it.+ """+ from jarvis.core.events import MemoryFileWrite++ target = loop or asyncio.get_running_loop()+ pending: set[asyncio.Future[Any]] = set()++ def _publish(event: Any) -> None:+ task = asyncio.ensure_future(bus.publish(event))+ pending.add(task)+ task.add_done_callback(pending.discard)++ def _sink_impl(update_id: str, agent_id: str, file: str, phase: str, operation: str) -> None:+ event = MemoryFileWrite(+ source_layer="memory.write_feedback",+ update_id=update_id,+ agent_id=agent_id,+ file=file,+ phase=phase,+ operation=operation,+ )+ try:+ target.call_soon_threadsafe(_publish, event)+ except RuntimeError:+ log.debug("memory write receipt dropped: the event loop is closed")++ set_sink(_sink_impl)+++def disconnect() -> None:+ set_sink(None)diff --git a/jarvis/plugins/tool/remember.py b/jarvis/plugins/tool/remember.pyindex 14e67fba64..0286d50488 100644--- a/jarvis/plugins/tool/remember.py+++ b/jarvis/plugins/tool/remember.py@@ -65,10 +65,13 @@ class RememberTool:@staticmethodasync def _legacy(fact: str, category: str) -> ToolResult:from jarvis.memory import CORE_MEMORY_FILENAME, CoreMemory+ from jarvis.memory.learning.notebook import OWNER_ID+ from jarvis.memory.write_feedback import announce_writedef _write() -> None:- mem = CoreMemory.load(DATA_DIR / CORE_MEMORY_FILENAME)- mem.add_fact(fact, category=category or "general")+ with announce_write(OWNER_ID, CORE_MEMORY_FILENAME, operation="add"):+ mem = CoreMemory.load(DATA_DIR / CORE_MEMORY_FILENAME)+ mem.add_fact(fact, category=category or "general")try:await asyncio.to_thread(_write)diff --git a/jarvis/plugins/tool/update_soul.py b/jarvis/plugins/tool/update_soul.pyindex 42da262090..2d4c3c89e7 100644--- a/jarvis/plugins/tool/update_soul.py+++ b/jarvis/plugins/tool/update_soul.py@@ -105,7 +105,9 @@ class UpdateSoulTool:@staticmethoddef _write_directly(path: Any, operation: str, note: str, entry_id: str) -> bool:"""Without the learning loop: the same change, under SOUL.md's lock."""+ from jarvis.memory.learning.notebook import OWNER_IDfrom jarvis.memory.soul import edit_soul+ from jarvis.memory.write_feedback import announce_writefrom jarvis.society.notebook import changedef mutate(soul: Any) -> bool:@@ -119,4 +121,6 @@ class UpdateSoulTool:soul.set_learned(updated)return True- return edit_soul(path, mutate)+ with announce_write(OWNER_ID, path.name, operation=operation) as receipt:+ receipt.changed = edit_soul(path, mutate)+ return receipt.changeddiff --git a/jarvis/society/memory.py b/jarvis/society/memory.pyindex eee834a595..9ac55b1dd1 100644--- a/jarvis/society/memory.py+++ b/jarvis/society/memory.py@@ -278,7 +278,9 @@ class SocietyMemory:"""Write one notebook under its lock and return the actual before/after receipt."""from filelock import Timeout- from .memory_books import PROMPT_BUDGETS, edit_book+ from jarvis.memory.write_feedback import announce_write++ from .memory_books import FILES, PROMPT_BUDGETS, classify, edit_bookfrom .notebook import readable_documenttext = str(text or "").strip()@@ -287,18 +289,22 @@ class SocietyMemory:if _contains_secret(text):raise MemoryRefused("memory never holds a secret")vault = self.root(root).resolve()+ # The file is known up front unless an edit must first find its entry.+ expected = FILES.get(target or (classify(text) if operation == "add" else ""), "")try:- result = edit_book(- vault,- agent,- text,- target=target,- operation=operation,- entry_id=entry_id,- old_text=old_text,- importance=max(0, min(10, int(importance))),- origin=self._origin(origin),- )+ with announce_write(agent.agent_id, expected, operation=operation) as written:+ result = edit_book(+ vault,+ agent,+ text,+ target=target,+ operation=operation,+ entry_id=entry_id,+ old_text=old_text,+ importance=max(0, min(10, int(importance))),+ origin=self._origin(origin),+ )+ written.file, written.changed = result.path.name, result.changedexcept (ValueError, KeyError, TypeError, Timeout) as exc:raise MemoryRefused(str(exc)) from excrel = result.path.relative_to(vault).as_posix()diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.memory.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.memory.test.tsxnew file mode 100644index 0000000000..2c6cfa2d95--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.memory.test.tsx@@ -0,0 +1,124 @@+/**+ * The lead pet's thought bubble shows its memory receipts end to end: a+ * `MemoryFileWrite` payload in the store becomes "Updating memory · MEMORY.md",+ * then "Saved to MEMORY.md" — and nothing claims "saved" without a receipt.+ */+import type { ReactNode } from "react";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { act, createRoot, extend, type ReconcilerRoot } from "@react-three/fiber";+import { cleanup, render, screen } from "@testing-library/react";+import * as THREE from "three";+import { loadLocaleChunk, setUiLanguage } from "@/i18n";+import { useMemoryWrites } from "@/store/memoryWrites";+import type { SocietyAgent } from "../data";+import { AgentBubble } from "./OfficeBubbles";+import { useOfficeTalk } from "./officeTalk";++/** What the in-world `<Html>` would put on screen, captured per render. */+const shown: { current: ReactNode } = { current: null };+vi.mock("@react-three/drei", async (original) => ({+ ...await original<typeof import("@react-three/drei")>(),+ Html: ({ children }: { children: ReactNode }) => { shown.current = children; return null; },+}));++extend(THREE);+let root: ReconcilerRoot<HTMLCanvasElement> | null = null;++function fakeRenderer(canvas: HTMLCanvasElement) {+ const noop = () => undefined;+ return {+ domElement: canvas, render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,+ getPixelRatio: () => 1, shadowMap: { enabled: false, type: 0, needsUpdate: false },+ xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },+ outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,+ info: { render: {}, memory: {} },+ };+}++const lead = { agentId: "jarvis", name: "George", tier: "lead", state: "idle", chatSessionId: null } as SocietyAgent;+const scout = { agentId: "scout", name: "Scout", tier: "specialist", state: "idle", chatSessionId: null } as SocietyAgent;++async function bubbleOf(agent: SocietyAgent, lines: { kind: "agent" | "tool"; text: string }[] = []) {+ shown.current = null;+ const canvas = document.createElement("canvas");+ root = root ?? createRoot(canvas);+ root.configure({+ gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<ReconcilerRoot<HTMLCanvasElement>["configure"]>[0]>["gl"],+ frameloop: "never", size: { width: 100, height: 100, top: 0, left: 0 },+ });+ await act(async () => {+ root?.render(<AgentBubble agent={agent} lines={lines as never} selected={false} height={1} onSelect={() => undefined} />);+ });+ cleanup();+ if (shown.current) render(<>{shown.current}</>);+ return shown.current;+}++function receipt(phase: string, file = "MEMORY.md", id = "u1", agent = "jarvis") {+ act(() => useMemoryWrites.getState().receive({ update_id: id, agent_id: agent, file, phase, operation: "add" }));+}++beforeAll(async () => {+ setUiLanguage("en");+ await loadLocaleChunk("society");+});++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);+ useMemoryWrites.getState().reset();+ useOfficeTalk.setState({ agentId: null });+});++afterEach(async () => {+ await act(async () => root?.unmount());+ root = null;+ cleanup();+ useMemoryWrites.getState().reset();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("the lead's memory receipt", () => {+ it("names the file while writing and claims saved only after the receipt", async () => {+ receipt("pending");+ await bubbleOf(lead);+ const row = screen.getByRole("status");+ expect(row.dataset.phase).toBe("pending");+ expect(row.textContent).toMatch(/MEMORY\.md/);+ expect(row.textContent).toBe("Updating memory · MEMORY.md");++ receipt("saved");+ await bubbleOf(lead);+ expect(screen.getByRole("status").dataset.phase).toBe("saved");+ expect(screen.getByRole("status").textContent).toBe("Saved to MEMORY.md");+ });++ it("shows a failed write as failed", async () => {+ receipt("pending", "SOUL.md");+ receipt("failed", "SOUL.md");+ await bubbleOf(lead);+ expect(screen.getByRole("status").dataset.phase).toBe("failed");+ expect(screen.getByRole("status").textContent).toMatch(/SOUL\.md/);+ });++ it("keeps the agent's own thought and adds the memory line under it", async () => {+ receipt("pending", "USER.md");+ await bubbleOf({ ...lead, state: "working" }, [{ kind: "agent", text: "Checking the calendar" }]);+ expect(screen.getByText(/Checking the calendar/)).toBeTruthy();+ expect(screen.getByRole("status").textContent).toMatch(/USER\.md/);+ });++ it("leaves the bubble empty again when the write changed nothing", async () => {+ receipt("pending");+ receipt("unchanged");+ expect(await bubbleOf(lead)).toBeNull();+ });++ it("never draws a memory line over another agent", async () => {+ receipt("pending", "MEMORY.md", "u2", "scout");+ expect(await bubbleOf(scout)).toBeNull();+ receipt("pending", "MEMORY.md", "u3", "jarvis");+ expect(await bubbleOf(scout)).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsxindex 19b5a71780..1d931abbb7 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx@@ -10,14 +10,17 @@import { useEffect, useMemo, useRef, useState } from "react";import { Html } from "@react-three/drei";import { useFrame } from "@react-three/fiber";+import { AlertTriangle, Check, LoaderCircle } from "lucide-react";import { Vector3, type Group } from "three";import { useT } from "@/i18n";import { useEventStore } from "@/store/events";+import { memoryNoteFor, useMemoryWrites, type MemoryWrite } from "@/store/memoryWrites";import type { SocietyAgent } from "../data";import type { ChatLine } from "./deskChat";import { player } from "./officeStore";import { plateScale } from "./OfficeAgents";import { useGigiErrands } from "./gigiErrands";+import { memoryLine, type MemoryLabels, type MemoryLine } from "./memoryBubble";import {ambientBubble, bubbleText, conversationBubble, itemsFor, PLAYER_LINE_MS, REPLY_LINGER_MS, talkStoreFor, useOfficeTalk,type Bubble, type BubbleLabels,@@ -39,6 +42,37 @@ export function useBubbleLabels(): BubbleLabels {}), [t]);}+export function useMemoryLabels(): MemoryLabels {+ const t = useT();+ return useMemo(() => ({+ updating: t("society.office.memory_updating"),+ updatingFile: t("society.office.memory_updating_file"),+ saved: t("society.office.memory_saved"),+ savedFile: t("society.office.memory_saved_file"),+ failed: t("society.office.memory_failed"),+ failedFile: t("society.office.memory_failed_file"),+ }), [t]);+}++const NO_WRITES: Record<string, MemoryWrite> = {};++/**+ * The lead's memory receipt (George writing MEMORY.md, USER.md, SOUL.md …)+ * as one bubble line. Only the lead shows it; other agents keep their bubbles.+ */+function useMemoryLine(agent: SocietyAgent): MemoryLine | null {+ const labels = useMemoryLabels();+ const writes = useMemoryWrites((s) => (agent.tier === "lead" ? s.writes : NO_WRITES));+ const own = useMemo(() => Object.values(writes).filter((w) => w.agentId === agent.agentId), [writes, agent.agentId]);+ const now = useClock(own.length > 0);+ if (own.length === 0) return null;+ // A receipt that arrived after the last tick is newer than `now`: it counts as just now.+ const note = memoryNoteFor(writes, agent.agentId, Math.max(now, ...own.map((w) => w.atMs)));+ return note ? memoryLine(note, labels) : null;+}++const MEMORY_ICON = { pending: LoaderCircle, saved: Check, failed: AlertTriangle } as const;+/** Gigi's side of an errand ("on my way to Nora", then the task) and the recipient's "Got it". */function useErrandBubble(agent: SocietyAgent): Bubble | null {const t = useT();@@ -67,8 +101,10 @@ function useClock(active: boolean): number {}/** The bubble itself, anchored `height` metres above its parent group. */-export function BubbleView({ bubble, height, range = Infinity, onClick }: {+export function BubbleView({ bubble, height, range = Infinity, onClick, memory }: {bubble: Bubble; height: number; range?: number; onClick?: () => void;+ /** The lead's memory receipt, shown as its own line under the bubble text. */+ memory?: MemoryLine | null;}) {const anchor = useRef<Group>(null);const box = useRef<HTMLDivElement>(null);@@ -93,7 +129,10 @@ export function BubbleView({ bubble, height, range = Infinity, onClick }: {<div ref={box} className="office-bubble" data-kind={bubble.kind} data-live={bubble.live || undefined} data-office-uirole={onClick ? "button" : undefined} onClick={onClick ? (e) => { e.stopPropagation(); onClick(); } : undefined}style={{ pointerEvents: onClick ? "auto" : "none" }}>- <p>{bubble.text}{bubble.live && bubble.kind !== "ask" ? <span className="office-bubble-dots" aria-hidden><i /><i /><i /></span> : null}</p>+ {bubble.text+ ? <p>{bubble.text}{bubble.live && bubble.kind !== "ask" ? <span className="office-bubble-dots" aria-hidden><i /><i /><i /></span> : null}</p>+ : null}+ {memory ? <MemoryRow line={memory} /> : null}{bubble.kind === "thought"? <span className="office-bubble-puffs" aria-hidden><i /><i /></span>: <span className="office-bubble-tail" aria-hidden />}@@ -103,6 +142,16 @@ export function BubbleView({ bubble, height, range = Infinity, onClick }: {);}+function MemoryRow({ line }: { line: MemoryLine }) {+ const Icon = MEMORY_ICON[line.phase];+ return (+ <span className="office-bubble-memory" data-phase={line.phase} role="status" aria-live="polite">+ <Icon aria-hidden strokeWidth={2.4} />+ <span className="office-bubble-memory-text">{line.text}</span>+ </span>+ );+}+/*** The agent's bubble: its live conversation when the person talks to it,* otherwise what it is busy with (from the desk-monitor tail).@@ -123,12 +172,17 @@ export function AgentBubble({ agent, lines, selected, height, onSelect }: {const now = useClock(lingering);const open = () => onSelect(agent.agentId);const errand = useErrandBubble(agent);- if (errand) return <BubbleView bubble={errand} height={height} onClick={open} />;+ const memory = useMemoryLine(agent);+ if (errand) return <BubbleView bubble={errand} height={height} onClick={open} memory={memory} />;if (talk && (talk.live || selected || now - talk.atMs < REPLY_LINGER_MS)) {- return <BubbleView bubble={talk} height={height} onClick={open} />;+ return <BubbleView bubble={talk} height={height} onClick={open} memory={memory} />;}const ambient = ambientBubble(agent.state, lines, labels);- return ambient ? <BubbleView bubble={ambient} height={height} range={AMBIENT_RANGE_M} onClick={open} /> : null;+ if (ambient) return <BubbleView bubble={ambient} height={height} range={memory ? Infinity : AMBIENT_RANGE_M} onClick={open} memory={memory} />;+ // Nothing else to say: the memory receipt alone fills the thought cloud.+ return memory+ ? <BubbleView bubble={{ kind: "thought", text: "", live: false, atMs: 0 }} height={height} onClick={open} memory={memory} />+ : null;}/** The person's own words over their character: the live transcript while speaking, then the sent line. */diff --git a/jarvis/ui/web/frontend/src/components/society/office/memoryBubble.test.ts b/jarvis/ui/web/frontend/src/components/society/office/memoryBubble.test.tsnew file mode 100644index 0000000000..dbb6af4ae3--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/memoryBubble.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from "vitest";+import { memoryLine, type MemoryLabels } from "./memoryBubble";++const LABELS: MemoryLabels = {+ updating: "Updating memory", updatingFile: "Updating memory · {0}",+ saved: "Memory saved", savedFile: "Saved to {0}",+ failed: "Memory not saved", failedFile: "Couldn't save {0}",+};++describe("memoryLine", () => {+ it("names the file being written", () => {+ expect(memoryLine({ phase: "pending", files: ["MEMORY.md"], atMs: 0 }, LABELS)).toEqual({ phase: "pending", text: "Updating memory · MEMORY.md" });+ });++ it("names every file of concurrent writes", () => {+ expect(memoryLine({ phase: "saved", files: ["USER.md", "SOUL.md"], atMs: 0 }, LABELS).text).toBe("Saved to USER.md, SOUL.md");+ });++ it("falls back to a plain line while the file is not known", () => {+ expect(memoryLine({ phase: "pending", files: [], atMs: 0 }, LABELS).text).toBe("Updating memory");+ expect(memoryLine({ phase: "failed", files: [], atMs: 0 }, LABELS).text).toBe("Memory not saved");+ });++ it("states a failure as a failure", () => {+ expect(memoryLine({ phase: "failed", files: ["SOUL.md"], atMs: 0 }, LABELS)).toEqual({ phase: "failed", text: "Couldn't save SOUL.md" });+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/memoryBubble.ts b/jarvis/ui/web/frontend/src/components/society/office/memoryBubble.tsnew file mode 100644index 0000000000..f02fe58e80--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/memoryBubble.ts@@ -0,0 +1,24 @@+/**+ * The memory line in the lead pet's thought bubble: "Updating memory ·+ * MEMORY.md" while a write is pending, "Saved to MEMORY.md" only after the+ * backend confirmed the file on disk, "Couldn't save MEMORY.md" when it+ * failed. Pure, tested in `memoryBubble.test.ts`; the receipts themselves+ * live in `store/memoryWrites.ts`.+ */+import type { MemoryNote, MemoryWritePhase } from "@/store/memoryWrites";++export interface MemoryLabels {+ updating: string; updatingFile: string;+ saved: string; savedFile: string;+ failed: string; failedFile: string;+}++export interface MemoryLine { phase: MemoryWritePhase; text: string }++export function memoryLine(note: MemoryNote, labels: MemoryLabels): MemoryLine {+ const files = note.files.join(", ");+ const [plain, named] = note.phase === "pending"+ ? [labels.updating, labels.updatingFile]+ : note.phase === "saved" ? [labels.saved, labels.savedFile] : [labels.failed, labels.failedFile];+ return { phase: note.phase, text: files ? named.replace("{0}", files) : plain };+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeTalk.css b/jarvis/ui/web/frontend/src/components/society/office/officeTalk.cssindex c03e91d300..1d57eca7b1 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeTalk.css+++ b/jarvis/ui/web/frontend/src/components/society/office/officeTalk.css@@ -23,6 +23,16 @@@keyframes office-bubble-dot { 0%, 80%, 100% { opacity:.25; transform:translateY(0); } 40% { opacity:1; transform:translateY(-2px); } }@keyframes office-bubble-pop { from { opacity:0; margin-bottom:-6px; } to { opacity:1; margin-bottom:0; } }@media (prefers-reduced-motion:reduce) { .office-bubble, .office-bubble-dots i { animation:none; } .office-bubble-dots i { opacity:.7; } }+/* The lead's memory receipt: which file it is writing, then whether it saved. In-world colours, like the bubble. */+.office-bubble-memory { display:flex; align-items:center; gap:5px; margin-top:5px; padding-top:5px; border-top:1px dashed #94a3b8; color:#334155; font-size:11px; font-style:normal; font-weight:600; line-height:1.3; }+.office-bubble-memory:first-child { margin-top:0; padding-top:0; border-top:0; }+.office-bubble-memory svg { flex:none; width:12px; height:12px; }+.office-bubble-memory-text { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }+.office-bubble-memory[data-phase="pending"] svg { animation:office-bubble-spin 1s linear infinite; }+.office-bubble-memory[data-phase="saved"] { color:#15803d; }+.office-bubble-memory[data-phase="failed"] { color:#be123c; }+@keyframes office-bubble-spin { to { transform:rotate(360deg); } }+@media (prefers-reduced-motion:reduce) { .office-bubble-memory[data-phase="pending"] svg { animation:none; } }/* ---- the walkie-talkie panel ------------------------------------------ */.office-talk { gap:0; }diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.tsindex 249fa995e0..451dd6fb20 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts@@ -26,6 +26,7 @@ import {} from "@/store/commandActivity";import { handleAppshotEditRequest } from "@/store/appshotEditor";import { useDeckStore } from "@/store/deck";+import { MEMORY_WRITE_EVENT, useMemoryWrites } from "@/store/memoryWrites";import { useHomeStore } from "@/store/home";import { PANE_ACTIVITY_EVENT } from "@/store/workspacePanes";import { WSAudioLevel, WSEventEnvelope, WSWelcome } from "@/schema/ws";@@ -345,6 +346,12 @@ export function useWebSocket(): void {void queryClient.invalidateQueries({ queryKey: petKeys.all });}+ // An agent's memory file is being written, or the write settled: the+ // lead pet's thought bubble names the file (store/memoryWrites).+ if (env.event_name === MEMORY_WRITE_EVENT) {+ useMemoryWrites.getState().receive(env.payload);+ }+if (env.event_name === "TranscriptionUpdate") {const p = env.payload as { text?: string; is_final?: boolean };if (typeof p.text === "string") {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex b673ce580a..56182d049a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -1118,6 +1118,12 @@"bubble_approval": "Ich brauche dein OK.","bubble_waiting": "Wartet auf dich","bubble_listening": "Hört zu",+ "memory_updating": "Aktualisiere Gedächtnis",+ "memory_updating_file": "Aktualisiere Gedächtnis · {0}",+ "memory_saved": "Gedächtnis gespeichert",+ "memory_saved_file": "In {0} gespeichert",+ "memory_failed": "Gedächtnis nicht gespeichert",+ "memory_failed_file": "{0} nicht gespeichert","talk_log": "Gespräch mit {0}","talk_empty": "Sag {0}, was zu tun ist – T oder das Mikrofon halten und sprechen, oder tippen.","talk_placeholder": "Nachricht an {0}",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex 22a58e4f44..88784b558c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -1118,6 +1118,12 @@"bubble_approval": "I need your OK.","bubble_waiting": "Waiting for you","bubble_listening": "Listening",+ "memory_updating": "Updating memory",+ "memory_updating_file": "Updating memory · {0}",+ "memory_saved": "Memory saved",+ "memory_saved_file": "Saved to {0}",+ "memory_failed": "Memory not saved",+ "memory_failed_file": "Couldn't save {0}","talk_log": "Conversation with {0}","talk_empty": "Say what {0} should do — hold T or the microphone and speak, or type.","talk_placeholder": "Message {0}",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex f9ebb3c945..aa958512a4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -1118,6 +1118,12 @@"bubble_approval": "Necesito tu visto bueno.","bubble_waiting": "Te está esperando","bubble_listening": "Escuchando",+ "memory_updating": "Actualizando memoria",+ "memory_updating_file": "Actualizando memoria · {0}",+ "memory_saved": "Memoria guardada",+ "memory_saved_file": "Guardado en {0}",+ "memory_failed": "Memoria no guardada",+ "memory_failed_file": "No se pudo guardar {0}","talk_log": "Conversación con {0}","talk_empty": "Dile a {0} qué hacer: mantén T o el micrófono y habla, o escribe.","talk_placeholder": "Mensaje para {0}",diff --git a/jarvis/ui/web/frontend/src/store/memoryWrites.test.ts b/jarvis/ui/web/frontend/src/store/memoryWrites.test.tsnew file mode 100644index 0000000000..afd6c70807--- /dev/null+++ b/jarvis/ui/web/frontend/src/store/memoryWrites.test.ts@@ -0,0 +1,99 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ applyMemoryWrite, FAILED_SHOW_MS, memoryNoteFor, nextExpiryIn, PENDING_STALE_MS, SAVED_SHOW_MS, useMemoryWrites,+ type MemoryWritesState,+} from "./memoryWrites";++const EMPTY: MemoryWritesState = { writes: {}, settled: {} };++function receipt(phase: string, patch: Record<string, unknown> = {}) {+ return { update_id: "u1", agent_id: "jarvis", file: "MEMORY.md", phase, operation: "add", ...patch };+}++function run(steps: [string, Record<string, unknown>?, number?][]): MemoryWritesState {+ return steps.reduce((s, [phase, patch, at]) => applyMemoryWrite(s, receipt(phase, patch), at ?? 1_000), EMPTY);+}++describe("applyMemoryWrite", () => {+ it("records a pending write and settles it as saved under the same id", () => {+ const pending = run([["pending"]]);+ expect(memoryNoteFor(pending.writes, "jarvis", 1_000)).toEqual({ phase: "pending", files: ["MEMORY.md"], atMs: 1_000 });+ const saved = applyMemoryWrite(pending, receipt("saved"), 1_200);+ expect(memoryNoteFor(saved.writes, "jarvis", 1_200)).toEqual({ phase: "saved", files: ["MEMORY.md"], atMs: 1_200 });+ });++ it("ignores a pending receipt that arrives after its write settled", () => {+ const state = run([["saved", {}, 1_000], ["pending", {}, 1_100]]);+ expect(memoryNoteFor(state.writes, "jarvis", 1_100)?.phase).toBe("saved");+ });++ it("drops a write that changed nothing without ever claiming saved", () => {+ const state = run([["pending"], ["unchanged"]]);+ expect(memoryNoteFor(state.writes, "jarvis", 1_000)).toBeNull();+ });++ it("keeps the file a pending receipt named when the settle receipt has none", () => {+ const state = run([["pending", { file: "USER.md" }], ["saved", { file: "" }]]);+ expect(memoryNoteFor(state.writes, "jarvis", 1_000)?.files).toEqual(["USER.md"]);+ });++ it("lets an unconfirmed pending write go stale instead of turning it into saved", () => {+ const state = run([["pending"]]);+ expect(memoryNoteFor(state.writes, "jarvis", 1_000 + PENDING_STALE_MS - 1)?.phase).toBe("pending");+ expect(memoryNoteFor(state.writes, "jarvis", 1_000 + PENDING_STALE_MS)).toBeNull();+ });++ it("shows saved and failed only briefly", () => {+ const saved = run([["saved"]]);+ expect(memoryNoteFor(saved.writes, "jarvis", 1_000 + SAVED_SHOW_MS)).toBeNull();+ const failed = run([["failed"]]);+ expect(memoryNoteFor(failed.writes, "jarvis", 1_000 + FAILED_SHOW_MS - 1)?.phase).toBe("failed");+ });++ it("refuses malformed payloads and never shows a path", () => {+ expect(applyMemoryWrite(EMPTY, null, 1)).toBe(EMPTY);+ expect(applyMemoryWrite(EMPTY, receipt("exploded"), 1)).toBe(EMPTY);+ expect(applyMemoryWrite(EMPTY, receipt("pending", { update_id: "" }), 1)).toBe(EMPTY);+ const pathy = applyMemoryWrite(EMPTY, receipt("pending", { file: "C:\\Users\\x\\MEMORY.md" }), 1);+ expect(memoryNoteFor(pathy.writes, "jarvis", 1)).toEqual({ phase: "pending", files: [], atMs: 1 });+ });+});++describe("memoryNoteFor with concurrent writes", () => {+ it("lists every file still being written", () => {+ const state = run([["pending", { update_id: "a" }, 1_000], ["pending", { update_id: "b", file: "SOUL.md" }, 1_100]]);+ expect(memoryNoteFor(state.writes, "jarvis", 1_100)).toMatchObject({ phase: "pending", files: ["MEMORY.md", "SOUL.md"] });+ });++ it("keeps writing ahead of an earlier success on another file", () => {+ const state = run([["saved", { update_id: "a" }, 1_000], ["pending", { update_id: "b", file: "USER.md" }, 1_100]]);+ expect(memoryNoteFor(state.writes, "jarvis", 1_100)).toMatchObject({ phase: "pending", files: ["USER.md"] });+ });++ it("never lets a later success hide a failure", () => {+ const state = run([["failed", { update_id: "a", file: "SOUL.md" }, 1_000], ["saved", { update_id: "b" }, 1_100]]);+ expect(memoryNoteFor(state.writes, "jarvis", 1_100)).toMatchObject({ phase: "failed", files: ["SOUL.md"] });+ });++ it("only reports the asked agent's writes", () => {+ const state = run([["pending", { agent_id: "scout" }]]);+ expect(memoryNoteFor(state.writes, "jarvis", 1_000)).toBeNull();+ });+});++describe("useMemoryWrites", () => {+ afterEach(() => {+ useMemoryWrites.getState().reset();+ vi.useRealTimers();+ });++ it("clears expired receipts on its own", () => {+ vi.useFakeTimers();+ vi.setSystemTime(10_000);+ useMemoryWrites.getState().receive(receipt("saved"));+ expect(Object.keys(useMemoryWrites.getState().writes)).toEqual(["u1"]);+ expect(nextExpiryIn(useMemoryWrites.getState().writes, Date.now())).toBe(SAVED_SHOW_MS);+ vi.advanceTimersByTime(SAVED_SHOW_MS + 100);+ expect(useMemoryWrites.getState().writes).toEqual({});+ });+});diff --git a/jarvis/ui/web/frontend/src/store/memoryWrites.ts b/jarvis/ui/web/frontend/src/store/memoryWrites.tsnew file mode 100644index 0000000000..66cbfccc40--- /dev/null+++ b/jarvis/ui/web/frontend/src/store/memoryWrites.ts@@ -0,0 +1,169 @@+/**+ * Live memory-write receipts from the backend (`MemoryFileWrite`, see+ * `jarvis/memory/write_feedback.py`), for the lead pet's thought bubble.+ *+ * One write arrives as `pending` and then settles as `saved`, `unchanged` or+ * `failed`, both steps sharing `update_id`. "Saved" is only ever shown after a+ * `saved` receipt: a pending write whose receipt never comes (a dropped socket,+ * a crashed backend) goes stale and disappears without claiming anything.+ * Receipts may arrive out of order; a late `pending` for an already settled+ * write is ignored.+ *+ * The reducer and the bubble selector are pure (`memoryWrites.test.ts`).+ */+import { create } from "zustand";++export const MEMORY_WRITE_EVENT = "MemoryFileWrite";++/** A pending write with no receipt after this long is treated as unconfirmed and hidden. */+export const PENDING_STALE_MS = 30_000;+/** How long "Saved to MEMORY.md" stays visible. */+export const SAVED_SHOW_MS = 4_000;+/** How long a failed write stays visible. */+export const FAILED_SHOW_MS = 8_000;+/** Settled ids are remembered this long so a late `pending` cannot revive them. */+const SETTLED_MEMORY_MS = 60_000;+const MAX_WRITES = 32;++const FILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;++export type MemoryWritePhase = "pending" | "saved" | "failed";++export interface MemoryWrite {+ id: string;+ agentId: string;+ /** Bare file name ("MEMORY.md"), or "" while the backend does not know it yet. */+ file: string;+ phase: MemoryWritePhase;+ /** When this phase began (client clock). */+ atMs: number;+}++export interface MemoryWritesState {+ writes: Record<string, MemoryWrite>;+ /** update id → when it settled. */+ settled: Record<string, number>;+}++interface Receipt { id: string; agentId: string; file: string; phase: MemoryWritePhase | "unchanged" }++function parseReceipt(payload: unknown): Receipt | null {+ if (!payload || typeof payload !== "object") return null;+ const p = payload as Record<string, unknown>;+ const id = typeof p.update_id === "string" ? p.update_id : "";+ const agentId = typeof p.agent_id === "string" ? p.agent_id : "";+ const rawFile = typeof p.file === "string" ? p.file : "";+ const phase = p.phase;+ if (!id || !agentId) return null;+ if (phase !== "pending" && phase !== "saved" && phase !== "failed" && phase !== "unchanged") return null;+ return { id, agentId, file: FILE_NAME.test(rawFile) ? rawFile : "", phase };+}++function visibleFor(write: MemoryWrite): number {+ if (write.phase === "pending") return PENDING_STALE_MS;+ return write.phase === "saved" ? SAVED_SHOW_MS : FAILED_SHOW_MS;+}++/** Drops expired writes and old settled ids. */+export function pruneMemoryWrites(state: MemoryWritesState, nowMs: number): MemoryWritesState {+ const writes = Object.fromEntries(+ Object.entries(state.writes).filter(([, w]) => nowMs - w.atMs < visibleFor(w)),+ );+ const settled = Object.fromEntries(+ Object.entries(state.settled).filter(([, at]) => nowMs - at < SETTLED_MEMORY_MS),+ );+ return { writes, settled };+}++/** Applies one `MemoryFileWrite` payload; malformed payloads change nothing. */+export function applyMemoryWrite(state: MemoryWritesState, payload: unknown, nowMs: number): MemoryWritesState {+ const receipt = parseReceipt(payload);+ if (!receipt) return state;+ const base = pruneMemoryWrites(state, nowMs);+ const writes = { ...base.writes };+ const settled = { ...base.settled };+ const known = writes[receipt.id];+ if (receipt.phase === "pending") {+ if (settled[receipt.id] !== undefined || known) return base;+ writes[receipt.id] = { id: receipt.id, agentId: receipt.agentId, file: receipt.file, phase: "pending", atMs: nowMs };+ } else {+ settled[receipt.id] = nowMs;+ if (receipt.phase === "unchanged") delete writes[receipt.id];+ else writes[receipt.id] = {+ id: receipt.id, agentId: receipt.agentId, file: receipt.file || known?.file || "", phase: receipt.phase, atMs: nowMs,+ };+ }+ const ids = Object.keys(writes);+ if (ids.length > MAX_WRITES) {+ ids.sort((a, b) => writes[a].atMs - writes[b].atMs);+ for (const id of ids.slice(0, ids.length - MAX_WRITES)) delete writes[id];+ }+ return { writes, settled };+}++/** What one agent's bubble says about its memory right now. */+export interface MemoryNote {+ phase: MemoryWritePhase;+ /** Distinct file names involved, oldest write first; may be empty. */+ files: string[];+ /** Latest change; the bubble re-renders until it expires. */+ atMs: number;+}++/**+ * Pending writes win (the agent is still writing), then a visible failure —+ * a later success on another file must not hide it — then "saved". Several+ * files in the same phase are listed together, so concurrent writes never+ * hide each other.+ */+export function memoryNoteFor(writes: Record<string, MemoryWrite>, agentId: string, nowMs: number): MemoryNote | null {+ const live = Object.values(writes)+ .filter((w) => w.agentId === agentId && nowMs - w.atMs < visibleFor(w))+ .sort((a, b) => a.atMs - b.atMs);+ if (live.length === 0) return null;+ const phase: MemoryWritePhase = (["pending", "failed", "saved"] as const).find((p) => live.some((w) => w.phase === p)) ?? "saved";+ const group = live.filter((w) => w.phase === phase);+ const files = [...new Set(group.map((w) => w.file).filter(Boolean))];+ return { phase, files, atMs: Math.max(...group.map((w) => w.atMs)) };+}++/** Milliseconds until the next write expires, or null when none is shown. */+export function nextExpiryIn(writes: Record<string, MemoryWrite>, nowMs: number): number | null {+ const left = Object.values(writes).map((w) => w.atMs + visibleFor(w) - nowMs);+ return left.length > 0 ? Math.max(0, Math.min(...left)) : null;+}++interface MemoryWritesStore extends MemoryWritesState {+ receive: (payload: unknown, nowMs?: number) => void;+ reset: () => void;+}++let sweep: ReturnType<typeof setTimeout> | null = null;++export const useMemoryWrites = create<MemoryWritesStore>((set, get) => {+ /** Expired receipts leave the store on their own, so no bubble keeps a stale line or a ticking clock. */+ const schedule = () => {+ if (sweep !== null) clearTimeout(sweep);+ sweep = null;+ const wait = nextExpiryIn(get().writes, Date.now());+ if (wait === null) return;+ sweep = setTimeout(() => {+ sweep = null;+ set((s) => pruneMemoryWrites(s, Date.now()));+ schedule();+ }, wait + 50);+ };+ return {+ writes: {},+ settled: {},+ receive: (payload, nowMs = Date.now()) => {+ set((s) => applyMemoryWrite(s, payload, nowMs));+ schedule();+ },+ reset: () => {+ if (sweep !== null) clearTimeout(sweep);+ sweep = null;+ set({ writes: {}, settled: {} });+ },+ };+});diff --git a/tests/unit/memory/test_write_feedback.py b/tests/unit/memory/test_write_feedback.pynew file mode 100644index 0000000000..f783f488fd--- /dev/null+++ b/tests/unit/memory/test_write_feedback.py@@ -0,0 +1,207 @@+"""Memory write receipts: pending before the write, saved only after it persisted.++Real files under ``tmp_path`` and a recording sink; no provider, no mocks.+"""++from __future__ import annotations++import asyncio+import threading+from pathlib import Path+from typing import Any++import pytest++from jarvis.core.bus import EventBus+from jarvis.core.events import Event, MemoryFileWrite+from jarvis.memory import write_feedback+from jarvis.memory.learning import notebook as notebook_module+from jarvis.memory.learning.notebook import OWNER_ID, JarvisNotebook+from jarvis.memory.templates import render_soul_md+from jarvis.ui.web.schema import event_to_ws_envelope++PLAIN_FACT = "The user likes short answers in the morning."+++class RecordingSink:+ def __init__(self, inspect: Path | None = None) -> None:+ self.calls: list[tuple[str, str, str, str, str]] = []+ self.content_when: dict[str, str] = {}+ self._inspect = inspect++ def __call__(self, update_id: str, agent_id: str, file: str, phase: str, op: str) -> None:+ self.calls.append((update_id, agent_id, file, phase, op))+ if self._inspect is not None:+ path = self._inspect+ self.content_when[phase] = path.read_text(encoding="utf-8") if path.is_file() else ""++ def phases(self) -> list[tuple[str, str]]:+ return [(file, phase) for _id, _agent, file, phase, _op in self.calls]++[email protected](autouse=True)+def _isolated():+ write_feedback.disconnect()+ notebook_module.set_active(None)+ yield+ write_feedback.disconnect()+ notebook_module.set_active(None)+++def book(tmp_path: Path) -> JarvisNotebook:+ soul = tmp_path / "workspace" / "SOUL.md"+ soul.parent.mkdir()+ soul.write_text(render_soul_md(), encoding="utf-8")+ return JarvisNotebook(tmp_path / "vault", name="George", soul_path=soul)+++def test_without_a_sink_the_write_runs_and_nothing_is_announced():+ with write_feedback.announce_write("jarvis", "MEMORY.md", operation="add") as receipt:+ receipt.changed = True+ assert receipt.file == "MEMORY.md"+++def test_saved_is_announced_only_after_the_file_holds_the_entry(book: JarvisNotebook):+ memory = book.paths()["memory"]+ sink = RecordingSink(inspect=memory)+ write_feedback.set_sink(sink)++ book.apply(target="memory", operation="add", text=PLAIN_FACT)++ assert sink.phases() == [("MEMORY.md", "pending"), ("MEMORY.md", "saved")]+ assert PLAIN_FACT not in sink.content_when["pending"]+ assert PLAIN_FACT in sink.content_when["saved"]+ first, second = sink.calls+ assert first[0] == second[0] and len(first[0]) == 32 # one update id for both steps+ assert first[1] == OWNER_ID and first[4] == "add"+++def test_each_target_names_its_real_file(book: JarvisNotebook):+ sink = RecordingSink()+ write_feedback.set_sink(sink)+ book.apply(target="user", operation="add", text="The user is called Ruben.")+ book.apply(target="soul", operation="add", text="The assistant keeps jokes dry.")+ saved = [file for file, phase in sink.phases() if phase == "saved"]+ assert saved == ["USER.md", "SOUL.md"]+++def test_a_duplicate_settles_as_unchanged_never_saved(book: JarvisNotebook):+ book.apply(target="memory", operation="add", text=PLAIN_FACT)+ sink = RecordingSink()+ write_feedback.set_sink(sink)+ assert book.apply(target="memory", operation="add", text=PLAIN_FACT) is None+ assert sink.phases() == [("MEMORY.md", "pending"), ("MEMORY.md", "unchanged")]+++def test_a_failed_write_is_announced_as_failed_and_still_raises(tmp_path: Path):+ missing = tmp_path / "workspace" / "SOUL.md" # never created: the write must fail+ book = JarvisNotebook(tmp_path / "vault", name="George", soul_path=missing)+ sink = RecordingSink()+ write_feedback.set_sink(sink)+ with pytest.raises(FileNotFoundError):+ book.apply(target="soul", operation="add", text="The assistant is calm.")+ assert sink.phases() == [("SOUL.md", "pending"), ("SOUL.md", "failed")]+++def test_a_refused_change_announces_nothing(book: JarvisNotebook):+ sink = RecordingSink()+ write_feedback.set_sink(sink)+ with pytest.raises(ValueError):+ book.apply(target="memory", operation="remove", entry_id="does-not-exist")+ assert sink.calls == []+++def test_a_broken_sink_never_breaks_the_write(book: JarvisNotebook):+ def boom(*_args: Any) -> None:+ raise RuntimeError("ui gone")++ write_feedback.set_sink(boom)+ change = book.apply(target="memory", operation="add", text=PLAIN_FACT)+ assert change is not None+ assert PLAIN_FACT in book.paths()["memory"].read_text(encoding="utf-8")+++ ("raw", "shown"),+ [+ ("MEMORY.md", "MEMORY.md"),+ ("C:\\Users\\someone\\vault\\society\\jarvis\\USER.md", "USER.md"),+ ("/home/someone/data/workspace/SOUL.md", "SOUL.md"),+ ("", ""),+ ("..", ""),+ ("bad name with spaces.md", ""),+ ],+)+def test_only_a_bare_file_name_ever_leaves(raw: str, shown: str):+ assert write_feedback.safe_file_name(raw) == shown+++def test_a_malformed_agent_id_is_never_forwarded():+ sink = RecordingSink()+ write_feedback.set_sink(sink)+ with write_feedback.announce_write("../etc", "MEMORY.md"):+ pass+ assert sink.calls == []+++async def test_connect_publishes_ordered_events_from_a_worker_thread(book: JarvisNotebook):+ bus = EventBus()+ seen: list[Event] = []++ async def record(event: Event) -> None:+ seen.append(event)++ bus.subscribe(MemoryFileWrite, record)+ write_feedback.connect(bus)++ worker = threading.Thread(+ target=book.apply, kwargs={"target": "memory", "operation": "add", "text": PLAIN_FACT}+ )+ worker.start()+ await asyncio.to_thread(worker.join)+ for _ in range(50):+ if len(seen) >= 2:+ break+ await asyncio.sleep(0.01)++ assert [e.phase for e in seen] == ["pending", "saved"] # type: ignore[attr-defined]+ envelope = event_to_ws_envelope(seen[1])+ assert envelope["event_name"] == "MemoryFileWrite"+ assert set(envelope["payload"]) == {"update_id", "agent_id", "file", "phase", "operation"}+ assert envelope["payload"]["file"] == "MEMORY.md"+ assert PLAIN_FACT not in str(envelope)+++async def test_remember_tool_announces_the_memory_file(book: JarvisNotebook):+ from types import SimpleNamespace++ from jarvis.plugins.tool.remember import RememberTool++ notebook_module.set_active(book)+ sink = RecordingSink()+ write_feedback.set_sink(sink)+ result = await RememberTool().execute(+ {"fact": "Ruben's sister is called Mia."}, SimpleNamespace(user_utterance="")+ )+ assert result.success+ assert sink.phases() == [("MEMORY.md", "pending"), ("MEMORY.md", "saved")]+++async def test_an_agent_notebook_write_names_its_file(tmp_path: Path):+ from jarvis.society.runtime import SocietyRuntime++ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)+ await runtime.ensure_started()+ try:+ await runtime.roster.create(name="Scout")+ scout = await runtime.roster.get("scout")+ sink = RecordingSink()+ write_feedback.set_sink(sink)+ await runtime.memory.remember(+ scout, "The user deploys on Fridays.", target="memory", root=tmp_path / "vault"+ )+ assert sink.phases() == [("MEMORY.md", "pending"), ("MEMORY.md", "saved")]+ assert {call[1] for call in sink.calls} == {"scout"}+ finally:+ await runtime.close()