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(society): clickable Updating Memory row with red-green file diff
rubenluetke10-beepc6327e67063c
diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.pyindex 5d3819465f..353755702a 100644--- a/jarvis/society/agent_tools.py+++ b/jarvis/society/agent_tools.py@@ -244,6 +244,17 @@ class WikiNoteTool:title = str(args.get("title") or "")try:if kind == "memory":+ from .memory import build_memory_diff++ # Capture the file before the write so the chat can paint+ # red/green without a second read. Failures fall back to "".+ before_text = ""+ try:+ vault = rt.memory.root(self._vault_root)+ mem_path = rt.memory.namespace(vault, caller.agent_id) / "memory.md"+ before_text = mem_path.read_text(encoding="utf-8") if mem_path.is_file() else ""+ except OSError:+ before_text = ""rel = await rt.memory.remember(caller,text,@@ -255,8 +266,23 @@ class WikiNoteTool:old_text=str(args.get("old_text") or ""),importance=int(args.get("importance", 8)),)+ after_text = ""+ try:+ vault = rt.memory.root(self._vault_root)+ after_text = (vault / rel).read_text(encoding="utf-8")+ except OSError:+ after_text = before_textreturn ToolResult(- success=True, output={"path": rel, "kind": kind, "reviewed": False}+ success=True,+ output={+ "path": rel,+ "kind": kind,+ "reviewed": False,+ "operation": str(args.get("operation") or "add"),+ "before": before_text[-20_000:],+ "after": after_text[-20_000:],+ "diff": build_memory_diff(before_text, after_text),+ },)if kind == "shared":return _failure(@@ -271,7 +297,24 @@ class WikiNoteTool:)except MemoryRefused as exc:return _failure(FailureReason.BLOCKED_BY_POLICY, str(exc))- return ToolResult(success=True, output={"path": rel, "kind": "note", "reviewed": False})+ try:+ from .memory import build_memory_diff as _build_diff++ vault = rt.memory.root(self._vault_root)+ after_page = (vault / rel).read_text(encoding="utf-8")+ except OSError:+ after_page = text+ return ToolResult(+ success=True,+ output={+ "path": rel,+ "kind": "note",+ "reviewed": False,+ "before": "",+ "after": after_page[-20_000:],+ "diff": _build_diff("", after_page),+ },+ )class MemoryRecallTool:diff --git a/jarvis/society/memory.py b/jarvis/society/memory.pyindex 6c9ce99f85..d619346c41 100644--- a/jarvis/society/memory.py+++ b/jarvis/society/memory.py@@ -25,6 +25,7 @@ ordinary agents. Deliberate user-wiki access uses the separately granted wiki tofrom __future__ import annotationsimport datetime as _dt+import difflib as _difflibimport loggingimport osimport re@@ -45,6 +46,7 @@ __all__ = ["MemoryHit","SocietyMemory","atomic_write",+ "build_memory_diff","resolve_society_vault",]@@ -65,6 +67,29 @@ _TOKEN_RE = re.compile(r"[\w][\w'-]{2,}", re.UNICODE)_FRONTMATTER_SAFE = re.compile(r"[\"\r\n]+")_SCOPE_BOOST: Final[dict[str, float]] = {"own": 0.30, "shared": 0.20, "user": 0.10, "other": 0.0}+#: Characters of before/after kept in a memory digest so the chat can paint+#: a red/green diff without a second file read. Large pages are clipped.+_DIFF_TEXT_CHARS: Final[int] = 20_000+#: Unified-diff lines kept in the digest payload.+_DIFF_MAX_LINES: Final[int] = 200+++def build_memory_diff(before: str, after: str, *, context: int = 3) -> list[str]:+ """Unified diff lines (no file headers) for a memory write, bounded."""+ before_lines = str(before or "").splitlines()+ after_lines = str(after or "").splitlines()+ diff = list(_difflib.unified_diff(before_lines, after_lines, n=context, lineterm=""))+ # Drop the ---/+++ headers; the payload carries the path separately.+ diff = [line for line in diff if not line.startswith(("---", "+++"))]+ return diff[:_DIFF_MAX_LINES]+++def _clip_diff_text(text: str) -> str:+ clipped = str(text or "")+ if len(clipped) > _DIFF_TEXT_CHARS:+ return clipped[-_DIFF_TEXT_CHARS:]+ return clipped+class MemoryRefused(ValueError):"""A refused memory operation (secret in the body, unknown row, bad path)."""@@ -271,10 +296,22 @@ class SocietyMemory:)except (ValueError, KeyError, TypeError) as exc:raise MemoryRefused(str(exc)) from exc- atomic_write(path, prefix + "\n" + render(entries))+ after = prefix + "\n" + render(entries)+ atomic_write(path, after)rel = path.relative_to(vault).as_posix()await self._stage(agent, rel, self._origin(origin), trace, text[:280])- await self._touch(agent, "remember", {"path": rel, "scope": "own"})+ await self._touch(+ agent,+ "remember",+ {+ "path": rel,+ "scope": "own",+ "operation": operation,+ "before": _clip_diff_text(existing),+ "after": _clip_diff_text(after),+ "diff": build_memory_diff(existing, after),+ },+ )return relasync def note(@@ -314,7 +351,18 @@ class SocietyMemory:row_id = await self._stage(agent, rel, self._origin(origin), trace, f"{title}: {text[:220]}")- await self._touch(agent, "note", {"path": rel, "scope": "own", "title": title})+ await self._touch(+ agent,+ "note",+ {+ "path": rel,+ "scope": "own",+ "title": title,+ "before": "",+ "after": _clip_diff_text(page),+ "diff": build_memory_diff("", page),+ },+ )return rel, row_idasync def propose_shared(diff --git a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsxindex e7f22eab7c..985e79b3b6 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx@@ -9,7 +9,7 @@ import type { ReasoningBlock, TextBlock, ToolBlock, TurnBlock, TurnItem, TurnStaimport { ChatMarkdown } from "./ChatMarkdown";import { toolDiff } from "./toolDiff";import { formatTokens, outputTokens } from "./toolView";-import { activityParts, traceToolIdentity } from "./traceActivity";+import { activityParts, traceToolIdentity, traceToolName } from "./traceActivity";import { ToolChoiceIcon } from "./ToolChoiceChips";import { toolIdentityStyle } from "./toolIdentity";import "./WorkTrace.css";@@ -214,23 +214,77 @@ export function ReasoningTrace({ block, turnLive, compact = false }: { block: Refunction ToolDetails({ block }: { block: ToolBlock }) {const t = useT();- const diff = useMemo(() => toolDiff(block.name, block.input), [block.name, block.input]);+ const diff = useMemo(() => toolDiff(block.name, block.input, block.output), [block.name, block.input, block.output]);+ const memoryFile = useMemo(() => memoryFileFromBlock(block), [block]);+ const [memoryOpen, setMemoryOpen] = useState(false);return <div className="space-y-3 py-1 text-xs"><Detail label={t("work_trace.tool")} text={block.name} />{block.input !== undefined && block.input !== null ? <Detail label={t("work_trace.input")} text={pretty(block.input)} /> : null}{diff ? <div aria-label={t("work_trace.diff")} className="max-h-72 overflow-auto font-mono text-xs">{diff.map((file, i) => <div key={i} className="mb-2">- <p className="mb-1 [overflow-wrap:anywhere]">{file.path}</p>+ <div className="mb-1 flex items-center gap-2 [overflow-wrap:anywhere]">+ <p className="min-w-0 flex-1">{file.path}</p>+ {memoryFile && file.path === memoryFile.path ? <button+ type="button"+ onClick={() => setMemoryOpen(true)}+ className="shrink-0 rounded-md border border-border px-2 py-0.5 text-[11px] text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >{t("society.chat.memory_open_file")}</button> : null}+ </div>{file.lines.map((line, n) => <div key={n} className={cn("whitespace-pre-wrap [overflow-wrap:anywhere]", line.kind === "add" && "diff-line-add", line.kind === "del" && "diff-line-del")}>{line.kind === "add" ? "+ " : line.kind === "del" ? "− " : " "}{line.text}</div>)}{file.truncated > 0 ? <p>{t("work_trace.truncated").replace("{count}", String(file.truncated))}</p> : null}</div>)}</div> : null}+ {memoryFile && !diff ? <button+ type="button"+ onClick={() => setMemoryOpen(true)}+ className="rounded-md border border-border px-2 py-1 text-[11px] text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >{t("society.chat.memory_open_file")}: {memoryFile.path}</button> : null}{block.output !== null ? <Detail label={t(block.isError ? "work_trace.error" : "work_trace.output")} text={block.output || t("work_trace.empty_output")} /> : null}+ {memoryOpen && memoryFile ? <MemoryFileDialog path={memoryFile.path} before={memoryFile.before} after={memoryFile.after} onClose={() => setMemoryOpen(false)} /> : null}</div>;}+function memoryFileFromBlock(block: ToolBlock): { path: string; before?: string; after?: string } | null {+ const key = traceToolName(block.name).toLowerCase().replace(/[-_]/g, "");+ if (!/^(societywikinote|societymemoryrecall|remember|societymemory)$/.test(key)) return null;+ const out = parseToolOutput(block.output);+ const inputPath = typeof block.input === "object" && block.input !== null+ ? String((block.input as Record<string, unknown>).path ?? "") : "";+ const path = out?.path || inputPath;+ if (!path || !path.startsWith("society/")) return null;+ return { path, before: out?.before, after: out?.after };+}++function parseToolOutput(output: string | null): { path?: string; before?: string; after?: string } | null {+ if (!output || !output.trim().startsWith("{")) return null;+ try {+ const parsed = JSON.parse(output) as Record<string, unknown>;+ if (!parsed || typeof parsed !== "object") return null;+ const path = typeof parsed.path === "string" ? parsed.path : undefined;+ const before = typeof parsed.before === "string" ? parsed.before : undefined;+ const after = typeof parsed.after === "string" ? parsed.after : undefined;+ if (!path && before === undefined && after === undefined) return null;+ return { path, before, after };+ } catch {+ return null;+ }+}++function MemoryFileDialog({ path, before, after, onClose }: { path: string; before?: string; after?: string; onClose: () => void }) {+ const [Viewer, setViewer] = useState<React.ComponentType<{ path: string; before?: string; after?: string; onClose: () => void }> | null>(null);+ useEffect(() => {+ let alive = true;+ void import("@/components/society/chat/MemoryFileViewer").then((mod) => {+ if (alive) setViewer(() => mod.MemoryFileViewer);+ });+ return () => { alive = false; };+ }, []);+ if (!Viewer) return null;+ return <Viewer path={path} before={before} after={after} onClose={onClose} />;+}+function Detail({ label, text }: { label: string; text: string }) {return <div><p className="mb-1 font-medium text-foreground">{label}</p><pre tabIndex={0} className="max-h-64 overflow-auto whitespace-pre-wrap font-mono text-xs leading-5 [overflow-wrap:anywhere] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">{text}</pre>@@ -253,7 +307,7 @@ export const TraceTool = memo(function TraceTool({ block, status, onDecide }: {const detail = description.detail || (typeof block.input === "object" && block.input !== null? String((block.input as Record<string, unknown>).file_path ?? (block.input as Record<string, unknown>).path ?? "") : "");const state = pending ? "approval" : denied ? "denied" : block.isError ? "failed" : running ? "running" : block.output === null ? "interrupted" : "completed";- const ActionIcon = action === "command" ? Terminal : action === "edit" || action === "write" ? FilePenLine+ const ActionIcon = action === "command" ? Terminal : action === "edit" || action === "write" || action === "memory" ? FilePenLine: action === "read" ? FileText : action === "search" || action === "list" ? FolderSearch : view.identity.Glyph;const Icon = pending ? ShieldQuestion : block.isError ? CircleAlert : ActionIcon;const decide = async (decision: ApprovalDecision) => {@@ -306,7 +360,7 @@ function ActivityIcon({ blocks, live }: { blocks: TurnBlock[]; live: boolean })const first = activityParts(blocks.filter((block): block is ToolBlock => block.kind === "tool"))[0];if (first?.row) return <span className={cn("tool-identity mt-1 shrink-0", live && "motion-safe:animate-pulse")} style={toolIdentityStyle(first.row)}><ToolChoiceIcon row={first.row} size={16} /></span>;const Icon = live ? CircleDashed : first?.key === "activity_command" ? Terminal- : first?.key === "activity_edit" || first?.key === "activity_write" ? FilePenLine : first ? FileText : Brain;+ : first?.key === "activity_edit" || first?.key === "activity_write" || first?.key === "activity_memory" ? FilePenLine : first ? FileText : Brain;return <Icon aria-hidden className={cn(iconClass, "mt-1", live && "motion-safe:animate-spin")} />;}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.test.tsindex 3141838b90..bc2ede37be 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.test.ts@@ -21,7 +21,7 @@ function render(lines: Array<{ kind: string; text: string }>): string {describe("which calls carry a diff", () => {it("knows the editing tools of every CLI, and leaves the rest alone", () => {- for (const name of ["Edit", "MultiEdit", "Write", "apply_patch", "str_replace_based_edit_tool", "NotebookEdit"]) {+ for (const name of ["Edit", "MultiEdit", "Write", "apply_patch", "str_replace_based_edit_tool", "NotebookEdit", "society_wiki_note"]) {expect(isDiffTool(name)).toBe(true);}for (const name of ["Bash", "Read", "Grep", "WebFetch", "Task"]) {@@ -151,3 +151,30 @@ describe("long changes stay readable", () => {expect(files![0].truncated).toBeGreaterThan(0);});});++describe("society memory writes", () => {+ it("paints a memory.md change red/green from the tool result", () => {+ const before = "---\ntype: society\n---\n\nold fact\n";+ const after = "---\ntype: society\n---\n\nold fact\n\nnew fact\n";+ const files = toolDiff(+ "society_wiki_note",+ { kind: "memory", text: "new fact" },+ JSON.stringify({ path: "society/scout/memory.md", before, after }),+ );+ expect(files).not.toBeNull();+ expect(files![0].path).toBe("society/scout/memory.md");+ expect(render(files![0].lines)).toContain("+new fact");+ expect(diffStat(files!).added).toBeGreaterThanOrEqual(1);+ expect(diffStat(files!).removed).toBe(0);+ });++ it("treats a new note as a file being started", () => {+ const after = "---\ntype: society\n---\n\n# Title\n\nbody\n";+ const files = toolDiff(+ "society_wiki_note",+ { kind: "note", title: "Title", text: "body" },+ JSON.stringify({ path: "society/scout/2026-01-01-title.md", before: "", after }),+ );+ expect(files![0].created).toBe(true);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.tsindex f8ee34d724..a5e0e76050 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolDiff.ts@@ -64,8 +64,10 @@ const MAX_LINES = 400;const MATCH_CAP = 1200;export function isDiffTool(name: string): boolean {+ const raw = (name ?? "").trim();+ if (/^(society_wiki_note|society_memory|society_memory_recall|remember)$/i.test(raw)) return true;return /^(edit|multi_?edit|write|create_?file|write_?file|apply_?patch|str_replace(_based_edit_tool)?|notebook_?edit|update_?file|patch_?file)$/i.test(- (name ?? "").trim(),+ raw,);}@@ -84,6 +86,53 @@ function str(obj: Record<string, unknown>, ...keys: string[]): string | null {return null;}+/** Parse a JSON-stringified tool result without ever throwing. */+function parseOutput(output: unknown): Record<string, unknown> | null {+ if (!output) return null;+ if (typeof output === "object" && !Array.isArray(output)) return output as Record<string, unknown>;+ if (typeof output === "string" && output.trim().startsWith("{")) {+ try {+ const parsed: unknown = JSON.parse(output);+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ return parsed as Record<string, unknown>;+ }+ } catch {+ return null;+ }+ }+ return null;+}++/**+ * A society memory write → the file it changed, ready to paint red/green.+ *+ * The result carries `{path, before, after}` (the digest carries the same).+ * `before`/`after` are the whole `memory.md`/note page, so the shared+ * line matcher renders only what moved — exactly like a code edit.+ */+export function memoryDiff(name: string, input: unknown, output?: unknown): DiffFile[] | null {+ if (!/^(society_wiki_note|society_memory|society_memory_recall|remember)$/i.test((name ?? "").trim())) {+ return null;+ }+ const out = parseOutput(output);+ const path = (out && str(out, "path")) ?? "";+ const before = out ? str(out, "before") : null;+ const after = out ? str(out, "after") : null;+ if (before !== null || after !== null) {+ if (before === null && after === null) return null;+ const created = !before?.trim();+ return [build(path, before ?? "", after ?? "", created)];+ }+ // No result yet (running call): fall back to the requested text so the+ // row still says what is being remembered.+ const obj = typeof input === "object" && input !== null && !Array.isArray(input)+ ? (input as Record<string, unknown>)+ : null;+ const text = obj ? str(obj, "text") : null;+ if (text !== null) return [build(path, "", text, true)];+ return null;+}+/*** Longest-common-subsequence line match, then rendered as a unified diff.*@@ -256,10 +305,17 @@ export function parsePatchText(patch: string): DiffFile[] {* `null` is the honest answer for a call that edits nothing, and also for an* edit whose arguments did not survive the transport — a row falling back to* its plain summary is right, inventing an empty diff is not.+ *+ * `output` is the JSON-stringified tool result when the runner kept it. A+ * society memory write (`society_wiki_note`) carries its red/green change+ * there as `{path, before, after, diff}` — the file the chat's Updating+ * Memory row opens in the editor.*/-export function toolDiff(name: string, input: unknown): DiffFile[] | null {+export function toolDiff(name: string, input: unknown, output?: unknown): DiffFile[] | null {const raw = (name ?? "").trim();if (!isDiffTool(raw)) return null;+ const memory = memoryDiff(raw, input, output);+ if (memory) return memory;if (typeof input === "string") {const files = parsePatchText(input);return files.length ? files : null;diff --git a/jarvis/ui/web/frontend/src/components/agentchat/traceActivity.ts b/jarvis/ui/web/frontend/src/components/agentchat/traceActivity.tsindex 80379cbeba..deed22c486 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/traceActivity.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/traceActivity.ts@@ -20,6 +20,7 @@ export function traceAction(name: string): string | null {if (/^(read|readfile|viewfile|cat|openfile|readmediafile)$/.test(key)) return "read";if (/^(ls|listdir|listdirectory|listfiles|glob)$/.test(key)) return "list";if (/^(grep|rg|search|searchfiles|grepsearch|codesearch|findbyname)$/.test(key)) return "search";+ if (/^(societywikinote|societymemoryrecall|remember)$/.test(key)) return "memory";return null;}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/MemoryFileViewer.tsx b/jarvis/ui/web/frontend/src/components/society/chat/MemoryFileViewer.tsxnew file mode 100644index 0000000000..ea5354112f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/MemoryFileViewer.tsx@@ -0,0 +1,168 @@+import { useEffect, useMemo, useRef, useState } from "react";+import { FileText, Loader2, X } from "lucide-react";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { memoryDiff } from "@/components/agentchat/toolDiff";++interface MemoryFileResponse {+ path: string;+ agent_id: string;+ content: string;+ updated_ms: number;+}++async function fetchMemoryFile(path: string): Promise<MemoryFileResponse> {+ const res = await fetch(`/api/society/memory/file?path=${encodeURIComponent(path)}`);+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ return (await res.json()) as MemoryFileResponse;+}++/**+ * The editor the Updating Memory row opens: the agent's memory file with+ * the change painted red/green, scrolled to the first changed line.+ *+ * `before`/`after` come from the tool result so the red/green matches the+ * chat row exactly; the fetched file proves the change landed on disk.+ */+export function MemoryFileViewer({+ path,+ before,+ after,+ onClose,+}: {+ path: string;+ before?: string;+ after?: string;+ onClose: () => void;+}) {+ const t = useT();+ const [file, setFile] = useState<MemoryFileResponse | null>(null);+ const [error, setError] = useState<string | null>(null);+ const firstChangeRef = useRef<HTMLDivElement | null>(null);+ const closeRef = useRef<HTMLButtonElement | null>(null);++ useEffect(() => {+ let alive = true;+ setFile(null);+ setError(null);+ closeRef.current?.focus();+ void fetchMemoryFile(path)+ .then((data) => {+ if (alive) setFile(data);+ })+ .catch((err) => {+ if (alive) setError(err instanceof Error ? err.message : String(err));+ });+ return () => {+ alive = false;+ };+ }, [path]);++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose]);++ const diff = useMemo(() => {+ const b = before ?? "";+ const a = after ?? file?.content ?? "";+ if (!b && !a) return null;+ return memoryDiff("society_wiki_note", { text: "" }, JSON.stringify({ path, before: b, after: a }));+ }, [before, after, file?.content, path]);++ useEffect(() => {+ if (diff && firstChangeRef.current) {+ firstChangeRef.current.scrollIntoView({ block: "center", behavior: "smooth" });+ }+ }, [diff, file]);++ const name = path.split("/").at(-1) ?? path;++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-label={`${t("society.chat.memory_file_title")}: ${path}`}+ className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 p-4 backdrop-blur-sm"+ onClick={onClose}+ >+ <section+ className="flex max-h-[85vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-popover text-foreground shadow-float"+ onClick={(e) => e.stopPropagation()}+ >+ <header className="flex h-12 shrink-0 items-center gap-3 border-b border-border bg-card px-4">+ <FileText className="h-4 w-4 shrink-0 text-primary" aria-hidden />+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-medium">{name}</div>+ <div className="truncate font-mono text-[11px] text-muted-foreground">{path}</div>+ </div>+ <button+ ref={closeRef}+ type="button"+ onClick={onClose}+ aria-label={t("society.world.drawer_close")}+ className="flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <X className="h-4 w-4" aria-hidden />+ </button>+ </header>++ <div className="min-h-0 flex-1 overflow-auto p-4">+ {error ? (+ <p role="alert" className="text-sm text-destructive">+ {t("society.chat.memory_file_failed")}: {error}+ </p>+ ) : !file && !diff ? (+ <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />+ {t("society.chat.memory_file_loading")}+ </p>+ ) : diff && diff.length > 0 ? (+ <div aria-label={t("work_trace.diff")} className="font-mono text-xs leading-6">+ {diff.map((f, i) => (+ <div key={i} className="mb-2">+ <p className="mb-2 font-sans text-xs text-muted-foreground">{f.path || path}</p>+ {f.lines.map((line, n) => {+ const isFirstChange =+ (line.kind === "add" || line.kind === "del") &&+ !diff+ .slice(0, i)+ .some((prev) => prev.lines.some((l) => l.kind === "add" || l.kind === "del")) &&+ f.lines.slice(0, n).every((l) => l.kind !== "add" && l.kind !== "del");+ return (+ <div+ key={n}+ ref={isFirstChange ? firstChangeRef : undefined}+ className={cn(+ "whitespace-pre-wrap rounded-sm px-2 py-0.5 [overflow-wrap:anywhere]",+ line.kind === "add" && "diff-line-add",+ line.kind === "del" && "diff-line-del",+ line.kind === "ctx" && "text-muted-foreground",+ )}+ >+ {line.kind === "add" ? "+ " : line.kind === "del" ? "− " : " "}+ {line.text}+ </div>+ );+ })}+ </div>+ ))}+ {file ? (+ <p className="mt-4 font-sans text-[11px] text-muted-foreground">+ {t("society.chat.memory_file_on_disk")}+ </p>+ ) : null}+ </div>+ ) : file ? (+ <pre className="whitespace-pre-wrap font-mono text-xs leading-6 text-foreground [overflow-wrap:anywhere]">+ {file.content}+ </pre>+ ) : null}+ </div>+ </section>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 43bfe1a0ce..a7eee3717a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -577,6 +577,7 @@"navigate": "Öffnet","app": "Öffnet App","memory": "Merkt sich",+ "memory_update": "Updating Memory","profile": "Aktualisiert Profil","contact": "Sucht Kontakt","call": "Ruft an",@@ -5571,6 +5572,7 @@"activity_read": "Dateien gelesen","activity_list": "Dateien aufgelistet","activity_search": "Dateien durchsucht",+ "activity_memory": "Updating Memory","activity_tools": "Werkzeuge verwendet","live_integration_used": "{service} wird verwendet","live_activity_command": "Befehle werden ausgeführt",@@ -5579,6 +5581,7 @@"live_activity_read": "Dateien werden gelesen","live_activity_list": "Dateien werden aufgelistet","live_activity_search": "Dateien werden durchsucht",+ "live_activity_memory": "Updating Memory","live_activity_tools": "Werkzeuge werden verwendet","thought": "Nachgedacht","thinking_for": "Denkt seit {duration}",@@ -5611,7 +5614,8 @@"done": "Fertig","command": "Befehl ausführen","edit": "Datei bearbeiten",- "write": "Datei schreiben"+ "write": "Datei schreiben",+ "memory": "Updating Memory"},"chat_media": {"unavailable": "Dieses Medium kann nicht geladen oder abgespielt werden. Du kannst die Datei weiterhin öffnen.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 56442650de..4c26fe1882 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -577,6 +577,7 @@"navigate": "Opening","app": "Opening app","memory": "Remembering",+ "memory_update": "Updating Memory","profile": "Updating profile","contact": "Looking up contact","call": "Calling",@@ -5604,6 +5605,7 @@"activity_read": "Read files","activity_list": "Listed files","activity_search": "Searched files",+ "activity_memory": "Updated Memory","activity_tools": "Used tools","live_integration_used": "Using {service}","live_activity_command": "Running commands",@@ -5612,6 +5614,7 @@"live_activity_read": "Reading files","live_activity_list": "Listing files","live_activity_search": "Searching files",+ "live_activity_memory": "Updating Memory","live_activity_tools": "Using tools","thought": "Thought","thinking_for": "Thinking for {duration}",@@ -5644,7 +5647,8 @@"done": "Done","command": "Run command","edit": "Edit file",- "write": "Write file"+ "write": "Write file",+ "memory": "Updating Memory"},"chat_media": {"unavailable": "This media cannot be loaded or played. You can still open the file.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex f8a999f22a..3eb0fdb58d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -577,6 +577,7 @@"navigate": "Abriendo","app": "Abriendo la app","memory": "Recordando",+ "memory_update": "Updating Memory","profile": "Actualizando el perfil","contact": "Buscando contacto","call": "Llamando",@@ -5571,6 +5572,7 @@"activity_read": "Leyó archivos","activity_list": "Listó archivos","activity_search": "Buscó archivos",+ "activity_memory": "Updating Memory","activity_tools": "Usó herramientas","live_integration_used": "Usando {service}","live_activity_command": "Ejecutando comandos",@@ -5579,6 +5581,7 @@"live_activity_read": "Leyendo archivos","live_activity_list": "Listando archivos","live_activity_search": "Buscando archivos",+ "live_activity_memory": "Updating Memory","live_activity_tools": "Usando herramientas","thought": "Razonamiento","thinking_for": "Pensando durante {duration}",@@ -5611,7 +5614,8 @@"done": "Listo","command": "Ejecutar comando","edit": "Editar archivo",- "write": "Escribir archivo"+ "write": "Escribir archivo",+ "memory": "Updating Memory"},"chat_media": {"unavailable": "No se puede cargar o reproducir este archivo. Puedes abrirlo directamente.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex e278deb505..f7c912c6b5 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -22,6 +22,12 @@"activity_details": "Details","activity_trace": "Aktivität · {count} Schritte","routine_check": "Routine-Prüfung",+ "updating_memory": "Updating Memory",+ "memory_open_file": "Memory-Datei öffnen",+ "memory_file_title": "Memory-Datei",+ "memory_file_loading": "Memory-Datei wird geladen…",+ "memory_file_failed": "Memory-Datei konnte nicht geladen werden",+ "memory_file_on_disk": "Mit markierter Änderung; die Datei oben ist die Version auf der Festplatte.","message_to": "Nachricht an","message_from": "Nachricht von","message_failed": "Nachricht fehlgeschlagen",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex 87ab773c07..0ebdbe70b8 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -22,6 +22,12 @@"activity_details": "Details","activity_trace": "Activity · {count} steps","routine_check": "Routine check",+ "updating_memory": "Updating Memory",+ "memory_open_file": "Open memory file",+ "memory_file_title": "Memory file",+ "memory_file_loading": "Loading memory file…",+ "memory_file_failed": "Could not load the memory file",+ "memory_file_on_disk": "Shown with the change highlighted; the file above is the version on disk.","message_to": "Message to","message_from": "Message from","message_failed": "Message failed",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 5d6383328b..5177a4cde4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -22,6 +22,12 @@"activity_details": "Detalles","activity_trace": "Actividad · {count} pasos","routine_check": "Comprobación de rutina",+ "updating_memory": "Updating Memory",+ "memory_open_file": "Abrir archivo de memoria",+ "memory_file_title": "Archivo de memoria",+ "memory_file_loading": "Cargando archivo de memoria…",+ "memory_file_failed": "No se pudo cargar el archivo de memoria",+ "memory_file_on_disk": "Se muestra con el cambio resaltado; el archivo es la versión en disco.","message_to": "Mensaje a","message_from": "Mensaje de","message_failed": "Error al enviar mensaje",diff --git a/jarvis/ui/web/frontend/src/lib/toolStepLabel.ts b/jarvis/ui/web/frontend/src/lib/toolStepLabel.tsindex ca8e3e69f3..d64dd97459 100644--- a/jarvis/ui/web/frontend/src/lib/toolStepLabel.ts+++ b/jarvis/ui/web/frontend/src/lib/toolStepLabel.ts@@ -31,6 +31,7 @@ export type ToolFamily =| "navigate"| "app"| "memory"+ | "memory_update"| "profile"| "contact"| "call"@@ -89,6 +90,9 @@ const FAMILY_BY_TOOL: Record<string, ToolFamily> = {open_app: "app",app_command: "app",remember: "memory",+ society_memory_recall: "memory",+ society_wiki_note: "memory_update",+ societywikinote: "memory_update",update_profile: "profile",contact_lookup: "contact",contact_upsert: "contact",@@ -124,6 +128,7 @@ const LABEL_KEY: Partial<Record<ToolFamily, string>> = {navigate: "tool_steps.navigate",app: "tool_steps.app",memory: "tool_steps.memory",+ memory_update: "tool_steps.memory_update",profile: "tool_steps.profile",contact: "tool_steps.contact",call: "tool_steps.call",@@ -149,6 +154,7 @@ const DETAIL_KEYS: Partial<Record<ToolFamily, string[]>> = {navigate: ["url", "target", "section", "path"],app: ["app", "name", "command", "app_name"],memory: ["key", "text", "fact", "content"],+ memory_update: ["path", "title", "text", "fact", "content"],profile: ["field", "key"],contact: ["name", "query", "contact"],call: ["name", "contact", "number"],diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex 6c3c6577d8..488ac550a4 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -23,7 +23,7 @@ from jarvis.society.events import MsgTypefrom jarvis.society.failure_reasons import FailureReason, retry_actionfrom jarvis.society.memory import MEMORY_SHARE_CAPABILITY, MemoryRefusedfrom jarvis.society.rooms import RoomError-from jarvis.society.roster import RosterError+from jarvis.society.roster import AgentRecord, RosterErrorfrom jarvis.society.runtime import SocietyRuntimelog = logging.getLogger(__name__)@@ -166,13 +166,36 @@ async def list_agents(request: Request, include_archived: bool = False) -> dict[return {"agents": rows, "total": len(rows)}+async def _creator_from_request(request: Request, rt: SocietyRuntime) -> AgentRecord | None:+ """The live society agent making this request, or ``None`` for the UI/CLI."""+ from jarvis.society.inherit import caller_session_id, session_agent_id++ session_id = (request.headers.get("x-jarvis-chat-session") or "").strip() or caller_session_id()+ agent_id = session_agent_id(session_id)+ if not agent_id:+ return None+ agent = await rt.roster.get(agent_id)+ if agent is None or str(agent.state) != "active":+ return None+ return agent++@router.post("/agents")async def create_agent(body: CreateAgentBody, request: Request) -> dict[str, Any]:rt = await _runtime(request)fields = body.model_dump(exclude_none=True, exclude={"name", "title", "description", "tier"})+ creator = await _creator_from_request(request, rt)+ if creator is not None:+ from jarvis.society.inherit import inherit_creator_fields++ fields = inherit_creator_fields(fields, creator)derived_focus, derived_rules = rt.derive(body.title, body.description)if body.focus is None and derived_focus:fields["focus"] = derived_focus+ if str(fields.get("grant_mode") or "") == "allowlist":+ allowed = set(fields.get("grants") or [])+ if allowed and "focus" in fields:+ fields["focus"] = [cap for cap in fields["focus"] if cap in allowed]if body.approval_rules is None and derived_rules["require_approval"]:fields["approval_rules"] = derived_rulestry:@@ -725,6 +748,12 @@ class RoutineBody(BaseModel):plugin_grants: list[dict[str, str]] = Field(default_factory=list)announce_on_success: str | None = Noneparent_task_id: str | None = None+ # Optional model seat for this routine. Omitted = pin the owner's current+ # seat at creation; explicit values win. "" on update = follow the owner.+ provider: str | None = None+ model: str | None = None+ effort: str | None = None+ account_id: str | None = Nonedef _task_store(request: Request) -> Any:@@ -783,6 +812,10 @@ async def create_agent_routine(schedule=body.schedule,plugin_grants=body.plugin_grants,announce_on_success=body.announce_on_success,+ provider=body.provider,+ model=body.model,+ effort=body.effort,+ account_id=body.account_id,)if parent_spec is not None:if spec.trigger.type not in ("calendar", "cron", "every"):@@ -816,7 +849,17 @@ async def create_agent_routine()except ValueError as exc:raise HTTPException(422, str(exc)) from exc- return {"id": task_id, "title": spec.title, "tags": list(spec.tags)}+ seat = (+ {+ "provider": spec.action.provider,+ "model": spec.action.model,+ "effort": spec.action.effort,+ "account_id": spec.action.account_id,+ }+ if spec.action.kind == "agent"+ else None+ )+ return {"id": task_id, "title": spec.title, "tags": list(spec.tags), "seat": seat}class RoutineUpdateBody(BaseModel):@@ -824,6 +867,10 @@ class RoutineUpdateBody(BaseModel):title: str = Field(min_length=1, max_length=200)prompt: str = Field(min_length=1, max_length=16_000)schedule: dict[str, Any]+ provider: str | None = None+ model: str | None = None+ effort: str | None = None+ account_id: str | None = None@router.patch("/agents/{agent_id}/routines/{task_id}")@@ -1096,6 +1143,56 @@ async def memory_dismiss(knowledge_id: int, request: Request) -> dict[str, Any]:return {"id": knowledge_id, "reviewed": True}[email protected]("/memory/file")+async def memory_file(request: Request, path: str = "") -> dict[str, Any]:+ """Read one society memory file for the Updating Memory editor.++ Sandboxed to ``society/`` inside the vault: ``memory.md`` per agent and+ the agent's dated notes. Shared pages are readable, everything outside+ ``society/`` is refused. The editor shows the file and scrolls to the+ change the chat's red/green diff describes.+ """+ from pathlib import Path++ rt = await _runtime(request)+ rel = str(path or "").strip().replace("\\", "/").lstrip("/")+ if not rel.startswith("society/") or ".." in rel.split("/"):+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ if not rel.endswith(".md"):+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ vault = rt.memory.root()+ target = vault / rel+ try:+ base = (vault / "society").resolve()+ resolved = target.resolve()+ if base != resolved and base not in resolved.parents:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ except HTTPException:+ raise+ except Exception as exc: # noqa: BLE001 — unreadable path reads as missing+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)}) from exc+ if not target.is_file():+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ try:+ content = target.read_text(encoding="utf-8")+ except OSError as exc:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)}) from exc+ if len(content) > 200_000:+ content = content[-200_000:]+ try:+ updated_ms = int(target.stat().st_mtime * 1000)+ except OSError:+ updated_ms = 0+ parts = Path(rel).parts+ agent_id = parts[1] if len(parts) >= 3 else ""+ return {+ "path": rel,+ "agent_id": agent_id,+ "content": content,+ "updated_ms": updated_ms,+ }++# ----------------------------------------------------------------- controlsdiff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.pyindex 8e8284379c..f71fcb4eb9 100644--- a/tests/contract/test_agent_mcp_harmony.py+++ b/tests/contract/test_agent_mcp_harmony.py@@ -137,6 +137,15 @@ WITHHELD: Final[dict[str, str]] = {"POST /api/society/memory/{knowledge_id}/dismiss": ("the other half of that review; it belongs with the reading, in the app"),+ "GET /api/society/memory/file": (+ "the Updating Memory editor reads one society file for the owner to "+ "review the red/green change; a remote client has no editor and "+ "recall already covers lookup"+ ),+ "PATCH /api/society/agents/{agent_id}/routines/{task_id}": (+ "editing a routine changes recurring spend; the owner does it on the "+ "routine card where the schedule is visible, not via a remote client"+ ),}diff --git a/tests/unit/society/test_memory.py b/tests/unit/society/test_memory.pyindex 9e50ce544a..c83f297461 100644--- a/tests/unit/society/test_memory.py+++ b/tests/unit/society/test_memory.py@@ -228,3 +228,27 @@ async def test_overview_lists_shared_agents_and_queue(rt: SocietyRuntime, tmp_paawait rt.memory.promote(got["knowledge_id"], root=vault)view = await rt.memory.overview(root=vault)assert view["shared"][0]["title"] == "Maps"+++def test_build_memory_diff_paints_red_green():+ from jarvis.society.memory import build_memory_diff++ before = "line one\nline two\n"+ after = "line one\nline TWO\nline three\n"+ diff = build_memory_diff(before, after)+ text = "\n".join(diff)+ assert "-line two" in text and "+line TWO" in text and "+line three" in text+++async def test_remember_digest_carries_before_after_and_diff(rt: SocietyRuntime, tmp_path: Path):+ vault = tmp_path / "vault"+ scout = await rt.roster.get("scout")+ await rt.memory.remember(scout, "First fact.", root=vault)+ before = await rt.store.last_seq()+ await rt.memory.remember(scout, "Second fact.", root=vault)+ events = [e for e in await rt.store.events_since(before) if e.msg_type is MsgType.DIGEST]+ assert len(events) == 1+ payload = events[0].payload+ assert payload["op"] == "remember" and payload["path"] == "society/scout/memory.md"+ assert "First fact." in payload["before"] and "Second fact." in payload["after"]+ assert any(line.startswith("+") and "Second fact." in line for line in payload["diff"])diff --git a/tests/unit/ui/web/test_society_routes.py b/tests/unit/ui/web/test_society_routes.pyindex a355206e95..3a62398676 100644--- a/tests/unit/ui/web/test_society_routes.py+++ b/tests/unit/ui/web/test_society_routes.py@@ -359,6 +359,26 @@ def test_memory_overview_recall_and_promotion_through_approvals(memory_client):assert c.post("/api/society/memory/999/dismiss").status_code == 404+def test_memory_file_serves_society_page_and_refuses_escape(memory_client):+ c, vault = memory_client+ c.post("/api/society/agents", json={"name": "Scout"})+ import asyncio++ runtime: SocietyRuntime = c.app.state.society+ scout = asyncio.run(runtime.roster.get("scout"))+ rel = asyncio.run(runtime.memory.remember(scout, "Loves maps.", root=vault))+ assert rel == "society/scout/memory.md"+ got = c.get("/api/society/memory/file", params={"path": rel}).json()+ assert got["path"] == rel and got["agent_id"] == "scout"+ assert "Loves maps." in got["content"]+ # Outside society/ is never served, even with traversal.+ assert c.get("/api/society/memory/file", params={"path": "jarvis.toml"}).status_code == 404+ traversal = c.get("/api/society/memory/file", params={"path": "society/../jarvis.toml"})+ assert traversal.status_code == 404+ missing = c.get("/api/society/memory/file", params={"path": "society/scout/missing.md"})+ assert missing.status_code == 404++def test_bind_agent_chat_creates_the_canonical_session(tmp_path: Path):from jarvis.agent_chat.store import AgentChatStore