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): agents learn - a finished task becomes the agent's own active skill
rubenluetke10-beepb43a32d97eb8
diff --git a/jarvis/agent_chat/events.py b/jarvis/agent_chat/events.pyindex 663d0dd064..b4f410e803 100644--- a/jarvis/agent_chat/events.py+++ b/jarvis/agent_chat/events.py@@ -29,6 +29,7 @@ Kinds (``payload`` keys in brackets):status: done | cancelled | error``session_updated`` [title?, provider?, model?, effort?, cwd?, permission_mode?]``error`` [turn_id?, message]+``notice`` [kind, ...] — a system line outside a turn``text_delta`` / ``reasoning_delta`` / ``reasoning_started`` / ``usage_delta``are the transient kinds: the finished block carries the whole text and thediff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.pyindex e2c53689fa..36969dc25e 100644--- a/jarvis/agent_chat/service.py+++ b/jarvis/agent_chat/service.py@@ -274,6 +274,12 @@ class AgentChatService:if not subs:self._subscribers.pop(session_id, None)+ async def post_notice(self, session_id: str, payload: dict[str, Any]) -> None:+ """A system line in a session's timeline that is not a turn: the agent+ society posts learned skills, login requests and queued approvals here.+ Stored like any event (kind ``notice``) so a reopened chat still shows it."""+ await self._emit(session_id, make_event("notice", dict(payload)))+async def _emit(self, session_id: str, event: dict[str, Any]) -> None:stored = self.store.append_event(session_id, event)for q in list(self._subscribers.get(session_id, ())):diff --git a/jarvis/society/learning.py b/jarvis/society/learning.pynew file mode 100644index 0000000000..2c81cd3403--- /dev/null+++ b/jarvis/society/learning.py@@ -0,0 +1,377 @@+"""Self-learning: an agent turns finished work into skills of its own.++Maintainer decision (2026-09-02): learning is automatic. After a finished+task the agent's turn is digested (task, tool steps, final answer) and,+when the digest shows a repeatable procedure, a ``SKILL.md`` is authored+through the existing skill creator and written into the agent's OWN skill+namespace — ``DATA_DIR/society/<agent_id>/skills/<slug>/`` — where it is+**active for that agent at once**: the briefing lists it, and+``society_run_skill`` runs it. The global user skill registry never gets+an active skill from here: promotion copies the folder with ``state: draft``+(AP-15 stays for everything Jarvis itself fires).++Off the critical path by construction: the pass is an asyncio task started+after the RESULT is on the board, capped per agent and day, and every+failure is a log line, never a broken turn. Web-derived text never becomes+a skill body verbatim — the creator sees the agent's own summary, and the+draft passes the skill linter before the file lands.+"""++from __future__ import annotations++import logging+import os+import shutil+from collections.abc import Callable+from dataclasses import dataclass, field+from datetime import UTC, datetime+from pathlib import Path+from typing import Any, Final++from jarvis.core.protocols import ToolResult++from .events import MsgType, SocietyEnvelope, now_ms+from .failure_reasons import FailureReason, retry_action+from .roster import AgentRecord, AgentState++log = logging.getLogger(__name__)++__all__ = [+ "RUN_SKILL_TOOL_NAME",+ "AgentSkills",+ "LearningPass",+ "RunLearnedSkillTool",+ "TurnDigest",+ "should_learn",+]++RUN_SKILL_TOOL_NAME: Final[str] = "society_run_skill"+DEFAULT_DAILY_CAP: Final[int] = 3+MIN_TOOL_STEPS: Final[int] = 2+_META_PREFIX: Final[str] = "learn:"+_DIGEST_CHARS: Final[int] = 4_000+++@dataclass(slots=True)+class TurnDigest:+ """What the learner sees of a finished turn — names and summaries, never+ raw tool output (web content stays out of skills)."""++ task: str+ final_text: str+ tool_steps: list[str] = field(default_factory=list)+ status: str = "done"+ origin: str = "agent" # agent | web++ def render(self) -> str:+ steps = "\n".join(f"- {s}" for s in self.tool_steps[:30]) or "- (no tool steps)"+ text = (+ f"Task:\n{self.task.strip()}\n\nTool steps taken:\n{steps}\n\n"+ f"Outcome:\n{self.final_text.strip()}"+ )+ return text[:_DIGEST_CHARS]+++def should_learn(digest: TurnDigest, *, min_steps: int = MIN_TOOL_STEPS) -> bool:+ """Deterministic pre-filter before any model call: only finished turns+ with a real procedure (enough tool steps) are worth a skill."""+ if digest.status != "done":+ return False+ if len(digest.tool_steps) < min_steps:+ return False+ return bool(digest.task.strip()) and bool(digest.final_text.strip())+++def _day_key(agent_id: str, now: int | None = None) -> str:+ day = datetime.fromtimestamp((now or now_ms()) / 1000, tz=UTC).date().isoformat()+ return f"{_META_PREFIX}{agent_id}:{day}"+++class AgentSkills:+ """One agent's private skill namespace and its registry (lazy, no watcher)."""++ def __init__(self, data_dir: Path, agent_id: str) -> None:+ self.agent_id = agent_id+ self.root = Path(data_dir) / "society" / agent_id / "skills"+ self._registry: Any | None = None++ @property+ def registry(self) -> Any:+ if self._registry is None:+ from jarvis.skills.registry import SkillRegistry++ self.root.mkdir(parents=True, exist_ok=True)+ self._registry = SkillRegistry(self.root, bus=None)+ self._registry.reload_sync()+ return self._registry++ def reload(self) -> None:+ if self._registry is not None:+ self._registry.reload_sync()++ def list_active(self) -> list[Any]:+ try:+ return list(self.registry.list_active())+ except Exception: # noqa: BLE001 — a broken skill folder costs the listing only+ log.warning("society skills: registry for %s unreadable", self.agent_id, exc_info=True)+ return []++ def get(self, slug: str) -> Any | None:+ try:+ return self.registry.resolve(slug)+ except Exception: # noqa: BLE001 — unknown or broken+ return None++ def activate(self, skill_dir: Path) -> None:+ """Flip a freshly authored draft to active — inside THIS namespace only."""+ from jarvis.skills.registry import _rewrite_state_in_frontmatter++ skill_md = skill_dir / "SKILL.md"+ text = skill_md.read_text(encoding="utf-8")+ skill_md.write_text(+ _rewrite_state_in_frontmatter(text, "active"), encoding="utf-8", newline="\n"+ )+ self.reload()++ def promote_to_global(self, slug: str) -> Path:+ """Copy the skill into the user's global skills dir as a DRAFT (AP-15)."""+ from jarvis.skills.bootstrap import ensure_user_skills_dir+ from jarvis.skills.registry import _rewrite_state_in_frontmatter++ skill = self.get(slug)+ if skill is None:+ raise KeyError(slug)+ src = Path(skill.path).parent if Path(skill.path).is_file() else Path(skill.path)+ target = ensure_user_skills_dir() / f"{self.agent_id}-{src.name}"+ if target.exists():+ raise FileExistsError(str(target))+ shutil.copytree(src, target)+ skill_md = target / "SKILL.md"+ skill_md.write_text(+ _rewrite_state_in_frontmatter(skill_md.read_text(encoding="utf-8"), "draft"),+ encoding="utf-8",+ newline="\n",+ )+ return target++ def summaries(self) -> list[dict[str, str]]:+ out: list[dict[str, str]] = []+ for skill in self.list_active():+ fm = getattr(skill, "frontmatter", None)+ name = str(getattr(fm, "name", None) or Path(str(skill.path)).parent.name)+ out.append(+ {+ "slug": Path(str(skill.path)).parent.name,+ "name": name,+ "description": str(getattr(fm, "description", "") or ""),+ "when_to_use": str(getattr(fm, "when_to_use", "") or ""),+ }+ )+ return sorted(out, key=lambda s: s["slug"])+++CreatorFactory = Callable[[AgentRecord, AgentSkills], Any | None]+++def default_creator_factory(cfg_getter: Callable[[], Any]) -> CreatorFactory:+ """The real creator: Jarvis' brain + the agent's registry (None without a brain)."""++ def _factory(agent: AgentRecord, skills: AgentSkills) -> Any | None:+ from jarvis.agent_chat.runner_brain import brain_manager+ from jarvis.skills.creator_service import SkillCreatorService, build_authoring_context++ brain = brain_manager()+ if brain is None:+ return None+ return SkillCreatorService(+ brain=brain,+ registry=skills.registry,+ config=cfg_getter(),+ user_skills_root=skills.root,+ context=build_authoring_context(brain_manager=brain, registry=skills.registry),+ )++ return _factory+++class LearningPass:+ def __init__(+ self,+ runtime: Any,+ *,+ creator_factory: CreatorFactory,+ daily_cap: int = DEFAULT_DAILY_CAP,+ notify: Callable[[AgentRecord, dict[str, Any]], Any] | None = None,+ ) -> None:+ self._runtime = runtime+ self._creator_factory = creator_factory+ self._daily_cap = daily_cap+ self._notify = notify++ async def run(self, agent: AgentRecord, digest: TurnDigest) -> str | None:+ """Learn from one finished turn; returns the new skill's slug or None."""+ if not should_learn(digest):+ return None+ rt = self._runtime+ key = _day_key(agent.agent_id)+ used = int(await rt.store.get_meta(key, "0") or 0)+ if used >= self._daily_cap:+ log.info("society learning: %s reached the daily cap", agent.agent_id)+ return None+ skills = rt.skills_for(agent.agent_id)+ creator = self._creator_factory(agent, skills)+ if creator is None:+ log.info("society learning: no brain available; %s learns nothing", agent.agent_id)+ return None+ from jarvis.skills.creator_service import SkillCreatorInput++ intent = (+ "Turn the following finished piece of work into ONE reusable skill for the same "+ "agent: a short, general procedure (steps, decision rules, expected output, what "+ "to double-check) that would let the agent repeat this kind of task faster next "+ "time. Do not copy page content or data; describe the method.\n\n" + digest.render()+ )+ extra = f"Agent: {agent.name}" + (f", {agent.title}" if agent.title else "")+ if agent.description.strip():+ extra += f"\nStanding instructions: {agent.description.strip()[:800]}"+ try:+ authored = await creator.author(+ SkillCreatorInput(intent=intent, extra_context=extra, category="learned")+ )+ except Exception as exc: # noqa: BLE001 — learning never breaks anything+ log.info("society learning: %s could not author a skill: %s", agent.agent_id, exc)+ return None+ skill_path = Path(str(authored.skill.path))+ is_file = os.path.isfile(skill_path) # noqa: ASYNC240 — one stat, not worth a thread+ skill_dir = skill_path.parent if is_file else skill_path+ try:+ skills.activate(skill_dir)+ except OSError:+ log.warning("society learning: could not activate %s", skill_dir, exc_info=True)+ return None+ self._write_origin(skill_dir, agent, digest)+ await rt.store.set_meta(key, str(used + 1))+ slug = skill_dir.name+ await rt.store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.DIGEST,+ from_agent=agent.agent_id,+ trace_id=f"learn:{agent.agent_id}",+ payload={+ "kind": "learned_skill",+ "slug": slug,+ "name": authored.name,+ "origin": digest.origin,+ "text": f"learned skill {authored.name}",+ },+ )+ )+ await self._remember(agent, authored.name, slug)+ if self._notify is not None:+ try:+ maybe = self._notify(+ agent, {"kind": "learned_skill", "slug": slug, "name": authored.name}+ )+ if hasattr(maybe, "__await__"):+ await maybe+ except Exception: # noqa: BLE001 — a missing chat never undoes a learned skill+ log.debug("society learning: notice not delivered", exc_info=True)+ return slug++ @staticmethod+ def _write_origin(skill_dir: Path, agent: AgentRecord, digest: TurnDigest) -> None:+ try:+ from jarvis.skills.origin import SkillOrigin, write_origin++ write_origin(+ skill_dir,+ SkillOrigin(+ source=f"society:{agent.agent_id}",+ source_id=digest.origin,+ installed_at=datetime.now(tz=UTC).isoformat(timespec="seconds"),+ ),+ )+ except Exception: # noqa: BLE001 — the receipt is bookkeeping+ log.debug("society learning: origin receipt not written", exc_info=True)++ async def _remember(self, agent: AgentRecord, name: str, slug: str) -> None:+ """One line on the agent's memory page per learned skill."""+ try:+ from .agent_tools import WikiNoteTool+ from .surface import _vault_root++ tool = WikiNoteTool(+ self._runtime, agent.agent_id, vault_root=_vault_root(self._runtime._get_cfg())+ )+ await tool.execute(+ {"kind": "memory", "text": f"Learned skill `{slug}` ({name}).", "origin": "agent"},+ None,+ )+ except Exception: # noqa: BLE001 — the wiki line is a courtesy+ log.debug("society learning: memory line not written", exc_info=True)+++class RunLearnedSkillTool:+ """Load one of the agent's own learned skills as instructions to follow."""++ name: str = RUN_SKILL_TOOL_NAME+ risk_tier: str = "monitor"+ description: str = (+ "Load one of YOUR learned skills by name and follow its instructions with your own "+ "tools (listed under 'Your learned skills'). Use it when the current task matches a "+ "skill's purpose. Returns the instructions; it does not run anything by itself."+ )+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {"skill": {"type": "string", "description": "The skill's slug or name."}},+ "required": ["skill"],+ }+ yields_instructions_only: bool = True++ def __init__(self, runtime: Any, agent_id: str) -> None:+ self._runtime = runtime+ self._agent_id = agent_id++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ from jarvis.skills.runner import SkillRunner++ rt = self._runtime+ caller = await rt.roster.get(self._agent_id)+ if caller is None or caller.state is not AgentState.ACTIVE:+ return ToolResult(success=False, output=None, error="caller is not an active agent")+ key = str(args.get("skill") or "").strip()+ if not key:+ return ToolResult(success=False, output=None, error="skill is required")+ skills = rt.skills_for(caller.agent_id)+ skill = skills.get(key)+ if skill is None:+ known = ", ".join(s["slug"] for s in skills.summaries()) or "none"+ return ToolResult(+ success=False,+ output={"reason": str(FailureReason.TARGET_UNKNOWN), "known": known},+ error=f"{FailureReason.TARGET_UNKNOWN}: no learned skill {key!r} (known: {known})",+ )+ try:+ runner = SkillRunner(skills.registry, {}, None, None)+ instructions = runner.render_instructions(skill, args={})+ except Exception as exc: # noqa: BLE001 — a broken skill is reported, not raised+ return ToolResult(+ success=False,+ output={"reason": str(FailureReason.INTERNAL_ERROR)},+ error=f"skill could not be rendered: {exc}",+ )+ directive = (+ "These are your own learned skill's instructions. Follow them now, step by step, "+ "with your available tools; report a step as done only after its tool call "+ "succeeded, and say plainly when a step could not run."+ )+ return ToolResult(+ success=True,+ output={"skill": Path(str(skill.path)).parent.name, "instructions": instructions},+ error=None,+ artifacts=(directive,),+ )+++def retry_hint(reason: FailureReason) -> str:+ return str(retry_action(reason))diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.pyindex 4f95038b7e..e95f41d183 100644--- a/jarvis/society/runtime.py+++ b/jarvis/society/runtime.py@@ -29,6 +29,7 @@ from .browser.session import BrowserJobsfrom .capabilities import CapabilityRow, build_catalogfrom .events import MsgType, RoomState, SocietyEnvelope, Tierfrom .focus import derive_approval_rules, derive_focus+from .learning import AgentSkills, LearningPass, TurnDigest, default_creator_factoryfrom .rooms import Roomsfrom .roster import LEAD_AGENT_ID, AgentRecord, Rosterfrom .scheduler import DeliverHook, SocietyScheduler@@ -113,6 +114,12 @@ class SocietyRuntime:#: Roster rows the society surface read for a turn - the sync tool#: filter reads them here (the briefing fills the cache first).self._agent_cache: dict[str, AgentRecord] = {}+ self._skills: dict[str, AgentSkills] = {}+ self.learning = LearningPass(+ self,+ creator_factory=default_creator_factory(self._get_cfg),+ notify=self._notify_chat,+ )self._started = False# ------------------------------------------------------------ lifecycle@@ -152,6 +159,25 @@ class SocietyRuntime:if current_runtime() is self:set_current_runtime(None)+ def skills_for(self, agent_id: str) -> AgentSkills:+ """The agent's private skill namespace (lazy registry)."""+ skills = self._skills.get(agent_id)+ if skills is None:+ skills = AgentSkills(self._data_dir, agent_id)+ self._skills[agent_id] = skills+ return skills++ async def _notify_chat(self, agent: AgentRecord, payload: dict[str, Any]) -> None:+ """A society notice in the agent's own chat (learned skill, login needed)."""+ svc = self._get_chat()+ post = getattr(svc, "post_notice", None)+ if svc is None or post is None:+ return+ session = svc.store.get_session(agent.session_id)+ if session is None:+ return+ await post(agent.session_id, payload)+def cache_agent(self, agent: AgentRecord) -> None:self._agent_cache[agent.agent_id] = agent@@ -250,6 +276,8 @@ class SocietyRuntime:final_text = ""status = "done"error = ""+ tool_steps: list[str] = []+ used_browser = Falsetry:while True:event = await queue.get()@@ -259,6 +287,12 @@ class SocietyRuntime:continueif kind == "assistant_text":final_text = str(payload.get("text") or final_text)+ elif kind == "tool_call":+ name = str(payload.get("name") or payload.get("tool") or "tool")+ summary = str(payload.get("summary") or "")[:120]+ tool_steps.append(f"{name}: {summary}" if summary else name)+ if name == "society_browser":+ used_browser = Trueelif kind == "error":status, error = "blocked", str(payload.get("message") or "error")elif kind == "turn_finished":@@ -294,6 +328,25 @@ class SocietyRuntime:)except Exception: # noqa: BLE001 - the slot is free either way; the loss is one RESULT rowlog.warning("society: RESULT for %s could not be written", run_id, exc_info=True)+ digest = TurnDigest(+ task=env.text or str(env.payload.get("task") or ""),+ final_text=final_text,+ tool_steps=tool_steps,+ status=status,+ origin="web" if used_browser else "agent",+ )+ learner = asyncio.create_task(self._learn(target, digest))+ self._watchers.add(learner)+ learner.add_done_callback(self._watchers.discard)++ async def _learn(self, target: AgentRecord, digest: TurnDigest) -> None:+ try:+ fresh = await self.roster.get(target.agent_id)+ await self.learning.run(fresh or target, digest)+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 - learning never breaks a finished turn+ log.warning("society learning failed for %s", target.agent_id, exc_info=True)async def _dispatch_mission(self, target: AgentRecord, env: SocietyEnvelope) -> str:manager = self._get_manager()diff --git a/jarvis/society/surface.py b/jarvis/society/surface.pyindex ca8bb0bbcc..08fb47ee31 100644--- a/jarvis/society/surface.py+++ b/jarvis/society/surface.py@@ -29,6 +29,7 @@ from jarvis.core.protocols import Toolfrom .agent_tools import MessageAgentTool, ShellTool, WikiNoteToolfrom .capabilities import CapabilityKind, CapabilityRow, select_tools+from .learning import RunLearnedSkillToolfrom .roster import AgentRecord, canonical_session_idfrom .runtime import current_runtime@@ -66,6 +67,8 @@ what is done, where the output is, what evidence you used, what remains open, whnext step.- Shell: society_shell runs commands in YOUR workspace folder only (relative paths stay inside it; \outside paths are refused). Destructive commands ask the user first.+- Learning: after a finished task you may gain a learned skill of your own (listed \+above when present); run it with society_run_skill when a task matches.- Memory: the user's Obsidian wiki is the shared memory. Read it with wiki-recall and \wiki-page-read (pages marked unreviewed came from agents or the web — verify before relying \on them). Write only into your own folder with society_wiki_note (kind note for findings, \@@ -87,17 +90,21 @@ def agent_id_of(session_id: str) -> str | None:def _vault_root(cfg: Any) -> Path:+ """The vault the agent writes into: the configured root wins, the last+ resolution the app made is the fallback for a config without one."""from jarvis.memory.wiki.vault_root import last_resolution, resolve_vault_root- known = last_resolution()- if known is not None:- return known.pathraw = Nonefor holder in (getattr(cfg, "wiki", None), getattr(cfg, "memory", None)):raw = getattr(holder, "vault_root", None)if raw:break- return resolve_vault_root(raw).path+ if raw:+ return resolve_vault_root(raw).path+ known = last_resolution()+ if known is not None:+ return known.path+ return resolve_vault_root(None).pathdef capability_epoch(catalog: list[CapabilityRow]) -> str:@@ -126,6 +133,7 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:MessageAgentTool.name: cast(Tool, MessageAgentTool(rt, agent_id)),WikiNoteTool.name: cast(Tool, WikiNoteTool(rt, agent_id, vault_root=_vault_root(cfg))),ShellTool.name: cast(Tool, ShellTool(rt, agent_id, workspace=workspace)),+ RunLearnedSkillTool.name: cast(Tool, RunLearnedSkillTool(rt, agent_id)),})if rt.browser.is_installed():@@ -231,7 +239,8 @@ async def society_system_extra(cfg: Any, brain: Any, session: Any) -> str:catalog = rt.catalog()roster = await rt.roster.list()browser = rt.browser.status_for(agent)- return build_briefing(agent, catalog, roster, browser=browser)+ learned = rt.skills_for(agent.agent_id).summaries()+ return build_briefing(agent, catalog, roster, browser=browser, learned=learned)# ------------------------------------------------------------------ briefing@@ -253,6 +262,7 @@ def build_briefing(roster: list[AgentRecord],*,browser: dict[str, Any] | None = None,+ learned: list[dict[str, str]] | None = None,) -> str:"""The per-agent system-prompt addendum (agent-definition §3.3).@@ -310,6 +320,16 @@ def build_briefing(parts.append("\n".join(hands))parts.append(_browser_line(browser))+ if learned:+ lines = ["## Your learned skills (run one with society_run_skill)"]+ for item in learned:+ line = f"- {item['slug']}"+ if item.get("description"):+ line += f": {item['description']}"+ if item.get("when_to_use"):+ line += f" (use when: {item['when_to_use']})"+ lines.append(line)+ parts.append("\n".join(lines))parts.append(_ECOSYSTEM_CARD)mates = [a for a in roster if a.agent_id != agent.agent_id and str(a.state) == "active"]diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex 9ced4757a7..2168fbceb5 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -380,6 +380,36 @@ async def apply_seed_proposals(body: ApplySeedsBody, request: Request) -> dict[sreturn {"agents": created, "total": len(created)}+# ------------------------------------------------------------------ skills++[email protected]("/agents/{agent_id}/skills")+async def list_agent_skills(agent_id: str, request: Request) -> dict[str, Any]:+ """The agent's own learned skills (active for the agent, drafts for Jarvis)."""+ rt = await _runtime(request)+ agent = await rt.roster.resolve(agent_id)+ if agent is None:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ skills = rt.skills_for(agent.agent_id)+ return {"skills": skills.summaries(), "root": str(skills.root)}++[email protected]("/agents/{agent_id}/skills/{slug}/promote")+async def promote_agent_skill(agent_id: str, slug: str, request: Request) -> dict[str, Any]:+ """Copy a learned skill into the user's global skills as a DRAFT (AP-15)."""+ rt = await _runtime(request)+ agent = await rt.roster.resolve(agent_id)+ if agent is None:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ try:+ target = rt.skills_for(agent.agent_id).promote_to_global(slug)+ except KeyError as exc:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)}) from exc+ except FileExistsError as exc:+ raise HTTPException(409, {"reason": str(FailureReason.BLOCKED_BY_POLICY)}) from exc+ return {"promoted": str(target), "state": "draft"}++# ----------------------------------------------------------------- browserdiff --git a/tests/unit/society/test_learning.py b/tests/unit/society/test_learning.pynew file mode 100644index 0000000000..a17a467167--- /dev/null+++ b/tests/unit/society/test_learning.py@@ -0,0 +1,238 @@+"""Automatic learning: a finished turn becomes the agent's own active skill."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace+from uuid import uuid4++import pytest++from jarvis.society.events import MsgType+from jarvis.society.learning import (+ AgentSkills,+ LearningPass,+ RunLearnedSkillTool,+ TurnDigest,+ should_learn,+)+from jarvis.society.runtime import SocietyRuntime++CTX = SimpleNamespace(trace_id=uuid4(), user_utterance="", config={}, memory_read=None)++SKILL_MD = """---+schema_version: 1+name: {name}+version: 0.1.0+description: {description}+category: learned+state: draft+when_to_use: when the user asks for a thumbnail+---++# {name}++1. Look at the last five thumbnails.+2. Note the shared style.+3. Produce a new one in that style.+"""+++class FakeCreator:+ """Writes a real SKILL.md into the agent's registry root like the creator does."""++ def __init__(self, skills: AgentSkills, *, fail: bool = False) -> None:+ self.skills = skills+ self.fail = fail+ self.calls: list[str] = []++ async def author(self, inp):+ self.calls.append(inp.intent)+ if self.fail:+ raise RuntimeError("no brain")+ slug = "thumbnail-style"+ folder = self.skills.root / slug+ folder.mkdir(parents=True, exist_ok=True)+ (folder / "SKILL.md").write_text(+ SKILL_MD.format(name="Thumbnail style", description="Reproduce the channel look"),+ encoding="utf-8",+ )+ skill = SimpleNamespace(path=folder / "SKILL.md")+ return SimpleNamespace(skill=skill, name="Thumbnail style", slug=slug)+++DIGEST = TurnDigest(+ task="Analyze my last five YouTube thumbnails and describe the style.",+ final_text="They share a red accent, big face, three words. Done.",+ tool_steps=["society_browser: youtube.com/@me", "society_wiki_note: style notes"],+)+++def test_should_learn_filter():+ assert should_learn(DIGEST)+ assert not should_learn(TurnDigest(task="x", final_text="y", tool_steps=["a"]))+ assert not should_learn(+ TurnDigest(task="x", final_text="y", tool_steps=["a", "b"], status="blocked")+ )+ assert not should_learn(TurnDigest(task="", final_text="y", tool_steps=["a", "b"]))+++async def rt(tmp_path: Path):+ runtime = SocietyRuntime(+ tmp_path,+ seed_starter_team=False,+ cfg=lambda: SimpleNamespace(+ memory=SimpleNamespace(data_dir=str(tmp_path)),+ wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")),+ ),+ )+ await runtime.ensure_started()+ await runtime.roster.create(name="Tuber", title="YouTube analyst")+ try:+ yield runtime+ finally:+ await runtime.close()+++async def test_learned_skill_is_active_for_the_agent_only(rt: SocietyRuntime, tmp_path: Path):+ notices: list[dict] = []+ creators: list[FakeCreator] = []++ def factory(agent, skills):+ creator = FakeCreator(skills)+ creators.append(creator)+ return creator++ async def notify(agent, payload):+ notices.append(payload)++ learner = LearningPass(rt, creator_factory=factory, notify=notify)+ tuber = await rt.roster.get("tuber")+ slug = await learner.run(tuber, DIGEST)+ assert slug == "thumbnail-style"+ assert "Standing instructions" not in creators[0].calls[0] # empty description → omitted+ assert "Do not copy page content" in creators[0].calls[0]++ skills = rt.skills_for("tuber")+ summaries = skills.summaries()+ assert [s["slug"] for s in summaries] == ["thumbnail-style"]+ text = (skills.root / "thumbnail-style" / "SKILL.md").read_text(encoding="utf-8")+ assert "state: active" in text+ # Board + chat notice + memory line.+ digest = [e for e in await rt.store.events_since(0) if e.msg_type is MsgType.DIGEST]+ assert digest[-1].payload["kind"] == "learned_skill"+ assert notices == [{"kind": "learned_skill", "slug": slug, "name": "Thumbnail style"}]+ memory = tmp_path / "vault" / "society" / "tuber" / "memory.md"+ assert memory.is_file() and "thumbnail-style" in memory.read_text(encoding="utf-8")+ # The global user skills dir is untouched until promotion.+ from jarvis.skills.bootstrap import ensure_user_skills_dir++ assert not any(p.name.startswith("tuber-") for p in ensure_user_skills_dir().iterdir())+++async def test_run_learned_skill_tool_and_briefing(rt: SocietyRuntime, tmp_path: Path):+ learner = LearningPass(rt, creator_factory=lambda a, s: FakeCreator(s))+ tuber = await rt.roster.get("tuber")+ await learner.run(tuber, DIGEST)+ tool = RunLearnedSkillTool(rt, "tuber")+ res = await tool.execute({"skill": "thumbnail-style"}, CTX)+ assert res.success, res.error+ assert "Look at the last five thumbnails" in res.output["instructions"]+ assert res.artifacts and "learned skill" in res.artifacts[0]+ missing = await tool.execute({"skill": "nope"}, CTX)+ assert missing.success is False and "thumbnail-style" in missing.output["known"]++ from jarvis.society.surface import society_system_extra++ session = SimpleNamespace(+ session_id="society:tuber", cwd=str(tmp_path / "ws"), permission_mode="ask"+ )+ briefing = await society_system_extra(rt._get_cfg(), None, session) # noqa: SLF001+ assert "## Your learned skills" in briefing+ assert "- thumbnail-style: Reproduce the channel look (use when: when the user asks" in briefing+++async def test_daily_cap_and_creator_failure(rt: SocietyRuntime):+ tuber = await rt.roster.get("tuber")+ failing = LearningPass(rt, creator_factory=lambda a, s: FakeCreator(s, fail=True))+ assert await failing.run(tuber, DIGEST) is None+ capped = LearningPass(rt, creator_factory=lambda a, s: FakeCreator(s), daily_cap=1)+ assert await capped.run(tuber, DIGEST) == "thumbnail-style"+ assert await capped.run(tuber, DIGEST) is None # cap reached for today+ none = LearningPass(rt, creator_factory=lambda a, s: None)+ assert await none.run(tuber, DIGEST) is None+++async def test_promote_copies_as_draft(rt: SocietyRuntime, tmp_path: Path, monkeypatch):+ import jarvis.skills.bootstrap as bootstrap++ user_dir = tmp_path / "user-skills"+ user_dir.mkdir()+ monkeypatch.setattr(bootstrap, "ensure_user_skills_dir", lambda: user_dir)+ learner = LearningPass(rt, creator_factory=lambda a, s: FakeCreator(s))+ tuber = await rt.roster.get("tuber")+ await learner.run(tuber, DIGEST)+ target = rt.skills_for("tuber").promote_to_global("thumbnail-style")+ assert target == user_dir / "tuber-thumbnail-style"+ assert "state: draft" in (target / "SKILL.md").read_text(encoding="utf-8")+ with pytest.raises(FileExistsError):+ rt.skills_for("tuber").promote_to_global("thumbnail-style")+ with pytest.raises(KeyError):+ rt.skills_for("tuber").promote_to_global("ghost")+++async def test_watch_turn_feeds_the_learner(tmp_path: Path):+ """The end of a chat-run assignment digests the turn and learns off-path."""+ import asyncio++ from jarvis.agent_chat.store import AgentChatStore+ from jarvis.society.events import SocietyEnvelope+ from tests.unit.society.test_chat_binding import FakeTurnService++ svc = FakeTurnService(AgentChatStore(tmp_path / "agent_chat.db"))+ cfg = SimpleNamespace(+ memory=SimpleNamespace(data_dir=str(tmp_path)),+ wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")),+ )+ rt = SocietyRuntime(+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg+ )+ await rt.ensure_started()+ seen: list[TurnDigest] = []++ class Spy:+ async def run(self, agent, digest):+ seen.append(digest)+ return None++ rt.learning = Spy() # type: ignore[assignment]+ try:+ await rt.roster.create(name="Tuber", provider="openai")+ await rt.say(+ from_agent="user", to_agent="tuber", text="Study my thumbnails", msg_type=MsgType.ASSIGN+ )+ for q in list(svc.queues.get("society:tuber", [])):+ q.put_nowait(+ {+ "kind": "tool_call",+ "payload": {+ "turn_id": "turn-1",+ "name": "society_browser",+ "summary": "youtube",+ },+ }+ )+ q.put_nowait({"kind": "tool_call", "payload": {"turn_id": "turn-1", "name": "Read"}})+ await svc.finish("society:tuber", "Red accent, big face.")+ for _ in range(40):+ await asyncio.sleep(0.05)+ if seen:+ break+ assert len(seen) == 1+ assert seen[0].tool_steps == ["society_browser: youtube", "Read"]+ assert seen[0].origin == "web" and seen[0].status == "done"+ assert seen[0].task == "Study my thumbnails"+ assert isinstance((await rt.store.events_since(0))[-1], SocietyEnvelope)+ finally:+ await rt.close()diff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.pyindex 354f94b072..7e5d8a5929 100644--- a/tests/unit/society/test_surface.py+++ b/tests/unit/society/test_surface.py@@ -9,6 +9,7 @@ import pytestfrom jarvis.society import runtime as runtime_modfrom jarvis.society.agent_tools import MESSAGE_TOOL_NAME, SHELL_TOOL_NAME, WIKI_NOTE_TOOL_NAME+from jarvis.society.learning import RUN_SKILL_TOOL_NAMEfrom jarvis.society.runtime import SocietyRuntimefrom jarvis.society.surface import (agent_id_of,@@ -19,8 +20,7 @@ from jarvis.society.surface import (society_tools,)--FOLDER = ["Read", "Write", "Edit", "Ls", "Glob", "Grep"]+FOLDER = ["Read", "Write", "Edit", "Ls", "Glob", "Grep", RUN_SKILL_TOOL_NAME]def _tool(name: str, desc: str = "x.") -> SimpleNamespace: