Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(society): persist autonomous background tasks and routines (#480)

Ruben Lütke5c5b62741d98
diff --git a/jarvis/agent_chat/background_work.py b/jarvis/agent_chat/background_work.py
new file mode 100644
index 0000000000..80bc14d725
--- /dev/null
+++ b/jarvis/agent_chat/background_work.py
@@ -0,0 +1,51 @@
+"""Detect concrete future-work promises; scheduling is always a tool effect."""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+_PROMISE = re.compile(
+ r"\b(?:i(?:['’]ll| will)\s+(?:check|review|monitor|watch|research|report|follow)|"
+ r"ich\s+(?:werde|prüfe|schaue|kontrolliere|beobachte|melde)|" # i18n-allow
+ r"voy\s+a\s+(?:revisar|comprobar|vigilar))\b" # i18n-allow
+ r"[^.!?\n]{0,240}\b(?:later|tomorrow|daily|every|background|back|"
+ r"später|morgen|täglich|regelmäßig|hintergrund|wieder|luego|mañana)\b", # i18n-allow
+ re.I,
+)
+
+
+def promises_background_work(request: str, response: str) -> bool:
+ from jarvis.society.autonomous_routines import is_informational_request
+
+ if is_informational_request(request):
+ return False
+ return bool(_PROMISE.search(response))
+
+
+def without_background_promises(response: str) -> str:
+ """Keep already delivered findings when stripping an unsupported promise."""
+ clauses = re.split(r"(?<=[.!?])\s+|\n+", response)
+ return "\n".join(clause for clause in clauses if not _PROMISE.search(clause)).strip()
+
+
+async def has_scheduled_work(session_id: str, task_ids: set[str]) -> bool:
+ """A successful tool receipt is checked against its current durable state."""
+ if not task_ids:
+ return False
+ from jarvis.society.routines import is_agent_routine
+ from jarvis.society.runtime import current_runtime
+ from jarvis.society.surface import agent_id_of
+
+ runtime = current_runtime()
+ agent_id = agent_id_of(session_id)
+ if runtime is None or agent_id is None:
+ return False
+ store, _ = runtime.task_services()
+ if store is None:
+ return False
+ for task_id in task_ids:
+ row: dict[str, Any] | None = await store.get(task_id)
+ if row and row["state"] in {"scheduled", "running"} and is_agent_routine(row, agent_id):
+ return True
+ return False
diff --git a/jarvis/agent_chat/turn_completion.py b/jarvis/agent_chat/turn_completion.py
index 8fba2a56ec..8baad1a60a 100644
--- a/jarvis/agent_chat/turn_completion.py
+++ b/jarvis/agent_chat/turn_completion.py
@@ -65,7 +65,8 @@ def offer_instead_of_action(request: str, response: str) -> bool:
return False
answer = response.strip().lstrip("* ")
if re.match(
- r"(?:I can confirm|Ich kann best[aä]tigen|Puedo confirmar)\b", answer, re.I # i18n-allow: detect localized confirmation replies
+ r"(?:I can confirm|Ich kann best[aä]tigen|Puedo confirmar)\b", # i18n-allow
+ answer, re.I,
): # i18n-allow
return False
blocking_question = (
@@ -109,6 +110,9 @@ class TurnCompletion:
self.calls: dict[str, tuple[str, dict[str, Any]]] = {}
self.receipts = ToolRecovery()
self.did_work = False
+ self.background_corrected = False
+ self.background_unregistered = False
+ self.background_tasks: set[str] = set()
async def emit(self, event: dict[str, Any]) -> None:
payload = event.get("payload") or {}
@@ -126,11 +130,36 @@ class TurnCompletion:
self.receipts.observe(event)
if kind == "assistant_text":
self.last_text = str(payload.get("text") or "")
+ from .background_work import has_scheduled_work, promises_background_work
+
+ self.background_unregistered = (
+ promises_background_work(self.request, self.last_text)
+ and not await has_scheduled_work(
+ self.handle.session.session_id, self.background_tasks,
+ )
+ )
+ if self.background_unregistered:
+ from .background_work import without_background_promises
+
+ # Preserve findings; remove only unsupported future commitments.
+ await self.handle.emit({**event, "payload": {
+ **payload, "text": without_background_promises(self.last_text),
+ }})
+ return
elif kind == "tool_call":
name = str(payload.get("name") or "").rsplit("__", 1)[-1].lower()
self.calls[str(payload.get("call_id") or "")] = (name, payload.get("input") or {})
elif kind == "tool_result":
name, _ = self.calls.pop(str(payload.get("call_id") or ""), ("", {}))
+ if name == "society_propose_change" and not payload.get("is_error"):
+ output = payload.get("output")
+ if isinstance(output, str):
+ try:
+ output = json.loads(output)
+ except ValueError:
+ output = None # Non-JSON output cannot certify a stored task.
+ if isinstance(output, dict) and output.get("applied") and output.get("task_id"):
+ self.background_tasks.add(str(output["task_id"]))
if name and name not in _READS and not payload.get("is_error"):
self.did_work = True
await self.handle.emit(event)
@@ -181,6 +210,28 @@ class TurnCompletion:
+ "\nOriginal request:\n"
+ self.context
)
+ if self.background_unregistered:
+ if (
+ self.allow_correction and not self.background_corrected
+ and not self.receipts.declined and not self.receipts.blocked
+ and not self.service.pending_approvals(sid)
+ ):
+ self.background_corrected = True
+ return (
+ "Your last answer promised future work without a registered task. "
+ "Finish the work now, or register the goal-derived follow-up with "
+ "society_propose_change(kind=routine, mode=autonomous), quoting the "
+ "current user goal. Use a one-time trigger unless the goal needs "
+ "recurrence. Inspect existing routines first and preserve completed "
+ "effects. Confirm only the saved task's actual state and next run. "
+ "If scheduling is unavailable or excluded, explain that blocker "
+ "without promising future execution.\nOriginal request:\n" + self.context
+ )
+ self.finish_event["payload"].update(
+ status="error",
+ error="Future work was not registered; no later execution is confirmed",
+ )
+ return None
if (
self.allow_correction
and not self.corrected
diff --git a/jarvis/agent_runtimes/openclaw.py b/jarvis/agent_runtimes/openclaw.py
index 0da43a9833..68ae0f6f75 100644
--- a/jarvis/agent_runtimes/openclaw.py
+++ b/jarvis/agent_runtimes/openclaw.py
@@ -306,6 +306,13 @@ class OpenClawRuntime:
}
},
"session": {"reset": {"mode": "none"}},
+ # Jarvis owns scheduling and memory. The native memory plugin
+ # can create its own jobs even with heartbeat disabled.
+ "cron": {"enabled": False},
+ "plugins": {
+ "slots": {"memory": "none"},
+ "entries": {"memory-core": {"enabled": False}},
+ },
# Jarvis' tools offered directly, never behind OpenClaw's tool search
# (on by default for local models; smaller models miss deferred tools).
"tools": {"deny": denied, "exec": {"mode": exec_mode}, "toolSearch": False},
diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.py
index 98a8e6d2c5..d23f34c060 100644
--- a/jarvis/society/agent_tools.py
+++ b/jarvis/society/agent_tools.py
@@ -478,8 +478,8 @@ class MemoryRecallTool:
class ProposeChangeTool:
"""``society_propose_change`` — configuration by chat (agent-definition §3.5).
- An explicit current request can apply in this turn. Inferred changes
- park on a proposal card until confirmed; permission changes always do.
+ Goal-derived background work can apply autonomously in the user's turn.
+ Other inferred configuration changes and permission changes use a card.
"""
name: str = PROPOSE_TOOL_NAME
@@ -488,6 +488,13 @@ class ProposeChangeTool:
description: str = (
"Configure ONE aspect of how you work. Use mode=apply with an exact request_quote "
"for an explicitly requested change; otherwise mode=propose asks on a chat card. "
+ "For kind=routine, mode=autonomous registers useful background follow-ups or "
+ "recurring work derived from the user's goal, without requiring a request to "
+ "create a routine. Quote that goal in request_quote and explain why in reason. "
+ "Use a one-time trigger for one-time work. Register work BEFORE promising to "
+ "do it later; read back task_id, state and next_run. List existing work first "
+ "and update it instead of creating duplicates. Information questions, quotations "
+ "and hypothetical suggestions are not execution requests. Honor exclusions. "
"kind 'rule' adds a standing instruction (operation replace/remove uses old_text) to your "
"description ({text}); 'skill' saves the procedure you just used under a name "
"({name, goal, steps[], outcome}); 'routine' schedules recurring work "
@@ -503,7 +510,7 @@ class ProposeChangeTool:
"workflow chains. "
"Use society_routines for the source schema and available drivers before configuring one. "
"Call society_routines for existing schedules and supported event names/fields. "
- "routine operation update/pause/resume/delete uses task_id from society_routines; "
+ "routine operation update/pause/resume/cancel/delete uses task_id from society_routines; "
"update also requires title, prompt and schedule. "
"'approval_rule' changes what needs the user's approval ({require_approval[], "
"always_allow[]} of capability ids like plugin:gmail:send); 'focus' changes which "
@@ -522,8 +529,11 @@ class ProposeChangeTool:
"properties": {
"mode": {
"type": "string",
- "enum": ["propose", "apply"],
- "description": "apply for an explicit current user request; otherwise propose.",
+ "enum": ["propose", "apply", "autonomous"],
+ "description": (
+ "autonomous for goal-derived routine work; "
+ "apply for explicit configuration; otherwise propose."
+ ),
},
"request_quote": {
"type": "string",
@@ -583,7 +593,8 @@ class ProposeChangeTool:
# A long role text is a card, not an automatic change.
and len(str(payload.get("description") or "")) <= FRESH_IDENTITY_MAX_CHARS
)
- apply_now = fresh_apply or args.get("mode") == "apply"
+ autonomous = args.get("mode") == "autonomous"
+ apply_now = fresh_apply or args.get("mode") == "apply" or autonomous
if apply_now and not fresh_apply:
quote = str(args.get("request_quote") or "").strip()
if (
@@ -598,6 +609,14 @@ class ProposeChangeTool:
)
if kind == "approval_rule":
apply_now = False
+ if autonomous:
+ from .autonomous_routines import apply_autonomous_routine
+
+ if self._session_id and turn.session_id != self._session_id:
+ return _failure(
+ FailureReason.BLOCKED_BY_POLICY, "current chat does not own this call",
+ )
+ return await apply_autonomous_routine(rt, caller, turn, args)
try:
item = await propose(
rt,
@@ -633,7 +652,7 @@ class ProposeChangeTool:
def risk_tier_for_args(self, args: dict[str, Any]) -> str:
# An identity rewrites the standing instructions: never a silent "safe".
- if args.get("mode") == "apply" or str(args.get("kind") or "") == "identity":
+ if args.get("mode") in {"apply", "autonomous"} or str(args.get("kind") or "") == "identity":
return "monitor"
return "safe"
diff --git a/jarvis/society/autonomous_routines.py b/jarvis/society/autonomous_routines.py
new file mode 100644
index 0000000000..91206ece5c
--- /dev/null
+++ b/jarvis/society/autonomous_routines.py
@@ -0,0 +1,224 @@
+"""Persist goal-derived background work through the existing task scheduler.
+
+The model chooses useful follow-ups. This boundary requires trusted current
+user provenance, preserves cancellation tombstones, and reads back the stored
+task before acknowledging it. No scheduler or model call is created here.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+import sqlite3
+from typing import Any
+from uuid import NAMESPACE_URL, uuid5
+
+from jarvis.core.protocols import ChatTurn, ToolResult
+from jarvis.tasks.schema import RetryPolicy
+
+from .proposals import ProposalRefused, validate
+from .routines import (
+ MAX_ROUTINES_PER_AGENT,
+ build_task_spec,
+ count_routines,
+ manage_routine,
+ next_run_readback,
+)
+
+AUTONOMOUS_TAG = "autonomous"
+ORIGIN_SESSION_TAG = "origin-session:"
+ORIGIN_PERMISSION_TAG = "origin-permission:"
+log = logging.getLogger(__name__)
+
+_NO_BACKGROUND = re.compile(
+ r"\b(?:do not|don't|never)\s+(?:schedule|automate|create\s+(?:a\s+)?routine)|"
+ r"\b(?:no\s+(?:background|automation)|nur\s+jetzt|" # i18n-allow
+ r"keine?\s+(?:automatisierung|hintergrundarbeit)|" # i18n-allow
+ r"nicht\s+(?:automatisieren|planen)|no\s+automatices)\b", # i18n-allow
+ re.I,
+)
+_ONCE = re.compile(
+ r"\b(?:only\s+(?:once|this\s+time)|just\s+(?:once|today)|one.off|"
+ r"nur\s+(?:einmal|diesmal|heute)|einmalig|solo\s+una\s+vez|" # i18n-allow
+ r"no\s+routine|keine?\s+routine)\b", # i18n-allow
+ re.I,
+)
+_INFORMATION = re.compile(
+ r"^\s*(?:(?:please|bitte)\s+)?(?:explain|translate|quote|imagine|suppose|" # i18n-allow
+ r"what\s+(?:is|are|would)|how\s+(?:do|does|can|would)|"
+ r"if\s+(?:i|we|you)\s+(?:wanted|were|could|would)|"
+ r"erkl[aä]r\w*|[uü]bersetz\w*|zitiere|was\s+(?:ist|sind|w[aä]re)|" # i18n-allow
+ r"wie\s+(?:kann|geht|funktioniert)|" # i18n-allow
+ r"wenn\s+ich\b[^.!?]{0,80}\b(?:würde|wollte|könnte)|explica|traduce)\b", # i18n-allow
+ re.I,
+)
+
+
+def is_informational_request(text: str) -> bool:
+ text = text.strip()
+ return (
+ not text
+ or text.startswith(('"', "'", "“", "„", ">", "```"))
+ or bool(_INFORMATION.search(text))
+ )
+
+
+def request_refusal(text: str, *, recurring: bool) -> str | None:
+ """Backstop explicit exclusions; semantic task selection stays with the agent."""
+ text = text.strip()
+ if is_informational_request(text):
+ return "Information, quoted text and hypothetical requests do not authorize background work"
+ if _NO_BACKGROUND.search(text):
+ return "The current request excludes background work"
+ if recurring and _ONCE.search(text):
+ return "The current request is one-time work; use a one-time trigger"
+ return None
+
+
+async def readback(store: Any, task_id: str, *, reused: bool = False) -> ToolResult:
+ row = await store.get(task_id)
+ spec = await store.get_spec(task_id)
+ if row is None or spec is None:
+ return ToolResult(False, {}, "Scheduled task could not be read back")
+ trigger = spec.trigger.model_dump(mode="json")
+ return ToolResult(
+ True,
+ {
+ "applied": True,
+ "kind": "routine",
+ "task_id": task_id,
+ "state": row["state"],
+ "reused": reused,
+ "trigger": trigger,
+ "next_run": next_run_readback(row.get("due_at_ns"), trigger.get("timezone")),
+ "note": "Report this stored state; a paused or terminal task has not been restarted.",
+ },
+ )
+
+
+async def apply_autonomous_routine(
+ runtime: Any,
+ agent: Any,
+ turn: ChatTurn,
+ args: dict[str, Any],
+) -> ToolResult:
+ """Register a justified follow-up without a redundant configuration card."""
+ if args.get("kind") != "routine":
+ return ToolResult(False, {}, "Autonomous mode is only for tasks and routines")
+ reason = str(args.get("reason") or "").strip()[:600]
+ if not reason:
+ return ToolResult(False, {}, "Explain how this work advances the current user goal")
+ if len(str(args.get("request_quote") or "")) > 4000:
+ return ToolResult(False, {}, "Quote the relevant goal in at most 4000 characters")
+ raw = args.get("payload") or {}
+ if isinstance(raw, dict) and raw.get("operation", "create") in {"create", "update"}:
+ schedule = raw.get("schedule") or {}
+ if not isinstance(schedule, dict) or not (schedule.get("kind") or schedule.get("type")):
+ return ToolResult(False, {}, "Choose an explicit one-time or recurring trigger")
+ if (schedule.get("kind") or schedule.get("type")) == "every" and not schedule.get(
+ "interval_seconds"
+ ):
+ return ToolResult(False, {}, "An elapsed recurring schedule needs interval_seconds")
+ if raw.get("workflow_id"):
+ return ToolResult(
+ False, {}, "Native workflow configuration requires explicit apply mode"
+ )
+ try:
+ payload = validate("routine", args.get("payload"), catalog=runtime.catalog())
+ except (ProposalRefused, ValueError) as exc:
+ log.info("Autonomous routine validation refused (%s)", type(exc).__name__)
+ return ToolResult(False, {}, str(exc))
+ store, scheduler = runtime.task_services()
+ if store is None or scheduler is None:
+ return ToolResult(False, {}, "The task scheduler is unavailable; no work was registered")
+ operation = payload.get("operation", "create")
+ if operation != "create":
+ if is_informational_request(turn.user_text):
+ return ToolResult(False, {}, "An information question does not modify existing work")
+ if operation == "update":
+ refusal = request_refusal(
+ turn.user_text,
+ recurring=payload["schedule"]["kind"] not in {"at_time", "after_delay"},
+ )
+ if refusal:
+ return ToolResult(False, {}, refusal)
+ # Corrections and cancellations apply to existing owned work, even when
+ # the new message says not to schedule anything else.
+ try:
+ await manage_routine(agent, payload, store, scheduler)
+ except (ValueError, KeyError, RuntimeError) as exc:
+ log.info("Autonomous routine update refused (%s)", type(exc).__name__)
+ return ToolResult(False, {}, str(exc))
+ if operation == "delete" and await store.get(payload["task_id"]) is None:
+ return ToolResult(
+ True, {"applied": True, "task_id": payload["task_id"], "state": "deleted"}
+ )
+ return await readback(store, payload["task_id"])
+ schedule = payload["schedule"]
+ recurring = schedule["kind"] not in {"at_time", "after_delay"}
+ refusal = request_refusal(turn.user_text, recurring=recurring)
+ if refusal:
+ return ToolResult(False, {}, refusal)
+ try:
+ spec = build_task_spec(
+ agent,
+ title=payload["title"],
+ prompt=payload["prompt"],
+ schedule=schedule,
+ )
+ except (ValueError, KeyError) as exc:
+ log.info("Autonomous routine trigger refused (%s)", type(exc).__name__)
+ return ToolResult(False, {}, str(exc))
+ # A stable semantic key survives new turn ids, reconnects and process
+ # restarts. Never resurrect completed/cancelled work on duplicate delivery.
+ key = json.dumps(
+ {
+ "agent": agent.agent_id,
+ "goal": " ".join(str(args["request_quote"]).split()).casefold(),
+ "work": " ".join(payload["prompt"].split()).casefold(),
+ "schedule": spec.trigger.model_dump(mode="json"),
+ },
+ sort_keys=True,
+ ensure_ascii=False,
+ )
+ task_id = str(uuid5(NAMESPACE_URL, "jarvis:autonomous:" + key))
+ if await store.get(task_id) is not None:
+ return await readback(store, task_id, reused=True)
+ if await count_routines(store, agent.agent_id) >= MAX_ROUTINES_PER_AGENT:
+ return ToolResult(False, {}, "Routine cap reached")
+ # Provenance is part of the same durable task insert, not a second write
+ # which could be lost after scheduling. Existing task tags carry routing.
+ origin = json.dumps(
+ {
+ "session_id": turn.session_id,
+ "turn_id": turn.turn_id,
+ "request_quote": args["request_quote"],
+ "reason": reason,
+ },
+ ensure_ascii=False,
+ )
+ session = runtime.chat_service().store.get_session(turn.session_id)
+ if session is None:
+ return ToolResult(False, {}, "The originating chat is unavailable")
+ spec = spec.model_copy(
+ update={
+ "id": uuid5(NAMESPACE_URL, "jarvis:autonomous:" + key),
+ "tags": (
+ *spec.tags,
+ AUTONOMOUS_TAG,
+ ORIGIN_SESSION_TAG + turn.session_id,
+ ORIGIN_PERMISSION_TAG + session.permission_mode,
+ "origin:" + origin,
+ ),
+ "retry_policy": RetryPolicy(retry_on_interrupt=False),
+ }
+ )
+ try:
+ await scheduler.schedule(spec, trace_id=turn.trace_id)
+ except sqlite3.IntegrityError:
+ # Concurrent identical submissions race on the task's primary key.
+ if await store.get(task_id) is None:
+ raise
+ return await readback(store, task_id, reused=True)
+ return await readback(store, task_id)
diff --git a/jarvis/society/proposals.py b/jarvis/society/proposals.py
index 59933f8d82..9bd343120c 100644
--- a/jarvis/society/proposals.py
+++ b/jarvis/society/proposals.py
@@ -173,12 +173,12 @@ def validate(kind: str, payload: Any, *, catalog: list[CapabilityRow]) -> dict[s
return {"name": name, "goal": goal, "steps": steps, "outcome": outcome}
if kind == "routine":
operation = str(payload.get("operation") or "create")
- if operation not in {"create", "update", "pause", "resume", "delete"}:
+ if operation not in {"create", "update", "pause", "resume", "cancel", "delete"}:
raise ProposalRefused(FailureReason.BLOCKED_BY_POLICY, "unknown routine operation")
task_id = str(payload.get("task_id") or "").strip()
if operation != "create" and not task_id:
raise ProposalRefused(FailureReason.BLOCKED_BY_POLICY, "task_id is required")
- if operation in {"pause", "resume", "delete"}:
+ if operation in {"pause", "resume", "cancel", "delete"}:
return {"operation": operation, "task_id": task_id}
title = _text(payload.get("title"), limit=120)
prompt = _text(payload.get("prompt"), limit=_MAX_TEXT)
@@ -286,7 +286,7 @@ def summarize(kind: str, payload: dict[str, Any]) -> str:
operation = str(payload.get("operation") or "create")
line = (
f"{operation.capitalize()} routine {payload['task_id']}"
- if operation in {"pause", "resume", "delete"}
+ if operation in {"pause", "resume", "cancel", "delete"}
else f"Schedule '{payload.get('title', '')}' ({schedule.get('kind', 'every')})"
)
elif kind == "approval_rule":
@@ -571,7 +571,10 @@ async def apply(
except (ValueError, KeyError) as exc: # Return the invalid routine detail to the proposer.
return {"applied": False, "detail": f"invalid routine: {exc}", "kind": kind}
task_id = await create_routine(task_store, scheduler, spec)
- return {"applied": True, "detail": f"routine scheduled ({task_id})", "kind": kind}
+ return {
+ "applied": True, "detail": f"routine scheduled ({task_id})",
+ "kind": kind, "task_id": task_id,
+ }
if kind == "skill":
rt.background(_apply_skill_later(rt, agent, item, payload))
return {"applied": True, "detail": "authoring the skill", "kind": kind}
diff --git a/jarvis/society/routine_runner.py b/jarvis/society/routine_runner.py
index 7da9c3e14b..187cb68213 100644
--- a/jarvis/society/routine_runner.py
+++ b/jarvis/society/routine_runner.py
@@ -7,6 +7,8 @@ import logging
from typing import Any
from uuid import uuid4
+from jarvis.core.protocols import RoutineDeferred
+
from .chat_binding import SURFACE, _workspace, pair_for
from .routines import agent_id_from_tags, routine_seat
@@ -34,7 +36,7 @@ async def guard_owned_routine(runtime: Any, tags: tuple[str, ...]) -> Any:
return agent
-def _billed_via_api(provider: str) -> bool:
+def _billed_via_api(provider: str, account_id: str = "") -> bool:
"""Whether ``provider`` answers through an API key on the society surface.
CLI seats (subscriptions) and keyless local providers never touch an API
@@ -49,7 +51,9 @@ def _billed_via_api(provider: str) -> bool:
row = provider_row(provider)
if row is not None and bool(getattr(row, "keyless", False)):
return False
- return resolve_runner(provider, surface=SURFACE) in ("brain", "api", "unknown")
+ return resolve_runner(provider, surface=SURFACE, account_id=account_id) in (
+ "brain", "api", "unknown",
+ )
async def _subscription_seat(cfg: Any) -> tuple[str, str, str] | None:
@@ -165,6 +169,26 @@ async def run_owned_routine(
cfg = runtime.config()
provider, model, effort, account_id = await _seat_for_run(runtime, agent, task_id)
+ autonomous = "autonomous" in tags
+ if autonomous and _billed_via_api(provider, account_id):
+ raise RoutineDeferred(
+ "Background work is waiting for a subscription or local model on its owner's seat"
+ )
+ permission_mode = "bypass"
+ if autonomous:
+ from .autonomous_routines import ORIGIN_PERMISSION_TAG, ORIGIN_SESSION_TAG
+
+ origin_id = next((t[len(ORIGIN_SESSION_TAG):] for t in tags
+ if t.startswith(ORIGIN_SESSION_TAG)), "")
+ origin = service.store.get_session(origin_id)
+ saved_mode = next((t[len(ORIGIN_PERMISSION_TAG):] for t in tags
+ if t.startswith(ORIGIN_PERMISSION_TAG)), "ask")
+ if origin is None or origin.permission_mode in {"plan", "read-only"}:
+ raise RoutineDeferred("Background work is waiting for its originating chat permissions")
+ # Society chats share ask / accept-edits / bypass. Unknown modes are
+ # conservative; later permission expansion never widens the saved grant.
+ order = {"ask": 0, "accept-edits": 1, "bypass": 2}
+ permission_mode = min((saved_mode, origin.permission_mode), key=lambda m: order.get(m, -1))
session = service.store.create_session(
session_id=f"{agent.session_id}{ROUTINE_SESSION_MARKER}{task_id}:{uuid4().hex}",
surface=SURFACE,
@@ -173,7 +197,7 @@ async def run_owned_routine(
effort=effort or default_effort(provider),
account_id=account_id,
cwd=_workspace(cfg, agent),
- permission_mode="bypass",
+ permission_mode=permission_mode,
title=f"{agent.name} · Routine {task_id}",
runtime=_run_runtime(agent, provider),
)
@@ -205,13 +229,14 @@ async def run_owned_routine(
log.warning("society: routine card not posted for %s", agent.agent_id, exc_info=True)
task = (
f"Scheduled routine {task_id}. Follow your CURRENT standing instructions.\n"
- "This execution has its own background chat with bypass permissions.\n"
+ "This execution has its own background chat and must honor its permission limits.\n"
"Use your memory and conversation archive for prior results. For information watches, "
"check sources and dates, remember last-seen items, "
"and report only meaningful new findings.\n\n" + task
)
queue = service.subscribe(session.session_id)
answer = ""
+ read_failures = 0
try:
turn_id = await service.send(session.session_id, task, direct_user=False, routine_run=True)
while True:
@@ -219,8 +244,32 @@ async def run_owned_routine(
raise asyncio.CancelledError
try:
event = await asyncio.wait_for(queue.get(), timeout=0.25)
- except TimeoutError: # An empty poll window simply waits for the next event.
- continue
+ except TimeoutError:
+ # A subscriber queue is a projection; the durable terminal
+ # remains authoritative after a dropped notification.
+ reader = getattr(service.store, "turn_terminal", None)
+ if reader is None:
+ continue
+ try:
+ event = reader(session.session_id, turn_id)
+ if event is None:
+ read_failures = 0
+ continue
+ texts = [
+ str(e["payload"].get("text") or "")
+ for e in service.store.list_events(session.session_id)
+ if e["kind"] == "assistant_text"
+ and e["payload"].get("turn_id") == turn_id
+ ]
+ answer = "\n\n".join(texts) or answer
+ read_failures = 0
+ except Exception:
+ log.warning("routine: durable completion read failed", exc_info=True)
+ read_failures += 1
+ if read_failures < 3:
+ continue
+ await service.cancel(session.session_id)
+ raise RuntimeError("The routine completion store is unavailable") from None
payload = event.get("payload") or {}
if payload.get("turn_id") not in (None, turn_id):
continue
@@ -231,6 +280,8 @@ async def run_owned_routine(
raise asyncio.CancelledError
if payload.get("status") not in {"done", "ok", "completed"}:
raise RuntimeError(str(payload.get("error") or "The routine failed"))
+ if autonomous:
+ await _report_autonomous_result(runtime, agent, tags, task_id, answer)
return answer
except asyncio.CancelledError:
await service.cancel(session.session_id)
@@ -240,3 +291,28 @@ async def run_owned_routine(
raise RuntimeError(f"The routine chat failed: {exc}") from exc
finally:
service.unsubscribe(session.session_id, queue)
+
+
+async def _report_autonomous_result(
+ runtime: Any, agent: Any, tags: tuple[str, ...], task_id: str, answer: str,
+) -> None:
+ """Deliver the result to the originating chat without another model turn."""
+ from .autonomous_routines import ORIGIN_SESSION_TAG
+ from .surface import agent_id_of
+
+ origin = next((tag[len(ORIGIN_SESSION_TAG):] for tag in tags
+ if tag.startswith(ORIGIN_SESSION_TAG)), agent.session_id)
+ payload = {
+ "kind": "society_result", "status": "done", "text": answer,
+ "agent_id": agent.agent_id, "agent_name": agent.name,
+ "source": "routine", "task_id": task_id,
+ }
+ try:
+ service = runtime.chat_service()
+ if agent_id_of(origin) == agent.agent_id and service.store.get_session(origin):
+ await service.post_notice(origin, payload)
+ else:
+ await runtime.post_chat_notice(agent, payload)
+ except Exception:
+ # The task runner persists the answer independently of this projection.
+ log.warning("routine: result delivery failed for %s", task_id, exc_info=True)
diff --git a/jarvis/society/routines.py b/jarvis/society/routines.py
index ace634e247..c2753f7c6c 100644
--- a/jarvis/society/routines.py
+++ b/jarvis/society/routines.py
@@ -381,7 +381,11 @@ async def create_routine(task_store: Any, scheduler: Any | None, spec: TaskSpec)
async def count_routines(task_store: Any, agent_id: str) -> int:
- return len(await list_routines(task_store, agent_id))
+ # Completed follow-ups and cancellation receipts do not consume live slots.
+ terminal = {"completed", "cancelled", "failed", "interrupted"}
+ return sum(
+ row.get("state") not in terminal for row in await list_routines(task_store, agent_id)
+ )
MAX_ROUTINES_PER_AGENT: Final[int] = _MAX_ROUTINES
@@ -447,11 +451,16 @@ async def manage_routine(
await scheduler.pause(tid)
elif operation == "resume":
await scheduler.resume(tid)
+ elif operation == "cancel":
+ await scheduler.cancel_task(tid)
elif operation == "delete":
if row.get("state") == "running":
raise ValueError("Pause or cancel the running routine before deleting it")
await scheduler.cancel_task(tid)
- await task_store.delete(tid)
+ # Keep autonomous cancellation receipts so duplicate delivery cannot
+ # recreate a job the person stopped. Ordinary deletion is unchanged.
+ if "autonomous" not in _tags_of(row):
+ await task_store.delete(tid)
else:
raise ValueError("Unknown routine operation")
return f"Routine {tid}: {operation} applied"
diff --git a/jarvis/society/surface.py b/jarvis/society/surface.py
index 526e0efe7f..917d6d448c 100644
--- a/jarvis/society/surface.py
+++ b/jarvis/society/surface.py
@@ -124,6 +124,19 @@ society_wiki_note. Keep dated findings as kind note. Consolidate rather than dup
Search only your own notes with society_memory_recall. Other agents' notes and \
shared knowledge are not automatically available. Use separately granted wiki tools only \
when the task explicitly calls for the user's wiki. Never edit the user's own pages.
+- Autonomy: carry out the user's goal through its necessary steps without another start
+request. Decide optional details yourself. When useful work belongs later or in the
+background, register it with society_propose_change(kind=routine, mode=autonomous,
+request_quote=the user's goal, reason=why the follow-up advances it). You do not need
+the words "create a routine". Infer a suitable trigger from the conversation and
+existing integrations. Register and read back the task BEFORE promising a later
+check or result. Use after_delay/at_time for one-time work; recurring triggers only
+for a continuing need. Do not turn information questions, quotations, hypothetical
+examples or optional suggestions into jobs. Respect "only this time", "no routine"
+and cancellations. List existing work and update/pause/cancel it when the user changes
+scope; never recreate cancelled work. Missing timing that matters requires one
+question; optional preferences do not block execution. The same rules apply to all
+agent runtimes. Unattended runs must not create further routines on their own.
- Routines: recurring work runs from the Automations section as tasks tagged with your name; \
their results arrive in this chat.
Use society_routines to inspect existing routines and available event names/fields before
@@ -177,10 +190,11 @@ repeated autumn times run once. Missed runs while the app is offline are skipped
- Earlier conversations: use society_conversation_recall for old decisions and exact messages.
- Configuring yourself: when the user explicitly requests a rule, procedure or routine,
call society_propose_change with mode=apply and request_quote copied from this user's current
-request. Read the stored result before claiming success. For inferred suggestions use
-mode=propose. Permission changes always need confirmation. Rules support operation
+request. Read the stored result before claiming success. Goal-derived background work
+uses mode=autonomous; other inferred configuration suggestions use mode=propose.
+Permission changes always need confirmation. Rules support operation
add/replace/remove (old_text identifies the old rule); routines support
-create/update/pause/resume/delete (task_id identifies an existing routine).
+create/update/pause/resume/cancel/delete (task_id identifies an existing routine).
An explicit recurring-work request is an instruction to save a routine in this turn,
not an invitation to describe a plan or ask again whether to start. Inspect connected
accounts for missing details before asking. Optional preferences do not block scheduling.
diff --git a/jarvis/tasks/runner.py b/jarvis/tasks/runner.py
index 79215da089..7f474dbeba 100644
--- a/jarvis/tasks/runner.py
+++ b/jarvis/tasks/runner.py
@@ -206,6 +206,19 @@ class TaskRunner:
)
return
except Exception as exc: # noqa: BLE001
+ if isinstance(exc, RoutineDeferred) and "autonomous" in spec.tags:
+ # No provider turn or effect started. Keep the work visible
+ # and resumable without falling back to a paid provider.
+ await self._store.update_state(task_id, "paused", error=str(exc))
+ await self._store.append_step(
+ task_id, "log", {"event": "waiting", "reason": str(exc)}
+ )
+ if self._result_sink is not None:
+ try:
+ await self._result_sink(spec.tags, str(exc), "waiting")
+ except Exception:
+ log.warning("task %s: waiting notice failed", task_id, exc_info=True)
+ return
if isinstance(exc, RoutineDeferred) and ctx.get("hook_delivery_id"):
await self._store.update_state(task_id, "scheduled")
await self._store.append_step(
diff --git a/jarvis/tasks/scheduler.py b/jarvis/tasks/scheduler.py
index a2e1327e2c..51fdd1d21b 100644
--- a/jarvis/tasks/scheduler.py
+++ b/jarvis/tasks/scheduler.py
@@ -145,6 +145,8 @@ class TaskScheduler:
# Per-run cancel tokens (H-03): cancel_task() fires the token of a
# RUNNING task so its harness action stops; cleared in _safe_run.
self._running_tokens: dict[str, Any] = {}
+ # Retained after cancel/pause so an already queued firing is revalidated.
+ self._autonomous_ids: set[str] = set()
# ------------------------------------------------------------------
# Runner wiring (DI — the runner can be set after construction)
@@ -436,14 +438,18 @@ class TaskScheduler:
spec = await self._store.get_spec(task_id)
if spec is None:
raise TaskNotFound(task_id)
+ if "autonomous" in spec.tags:
+ self._autonomous_ids.add(task_id)
if spec.trigger.type == "source":
raise TaskStateConflict("Use the configured trigger input for this routine")
if spec.trigger.type in ("after_delay", "at_time"):
self._remove_from_memory(task_id)
- restore_state = "paused" if state == "paused" else None
+ restore_state = (
+ "paused" if state == "paused" and spec.trigger.type in PAUSABLE_TRIGGER_TYPES else None
+ )
await self._store.append_step(task_id, "log", {"event": "run_now"})
task_obj = asyncio.create_task(
- self._run_now_and_settle(task_id, restore_state),
+ self._run_now_and_settle(task_id, restore_state, allow_paused=state == "paused"),
name=f"task-run-now-{task_id}",
)
self._runner_tasks.add(task_obj)
@@ -453,8 +459,9 @@ class TaskScheduler:
self,
task_id: str,
restore_state: str | None,
+ *, allow_paused: bool = False,
) -> None:
- await self._safe_run(task_id, None)
+ await self._safe_run(task_id, None, allow_paused=allow_paused)
if restore_state is None:
return
# The runner leaves a recurring task as `scheduled` (or `failed`);
@@ -476,7 +483,9 @@ class TaskScheduler:
task = await self._store.get(task_id)
if task is None:
raise TaskNotFound(task_id)
- if task["trigger_type"] not in PAUSABLE_TRIGGER_TYPES:
+ spec = await self._store.get_spec(task_id)
+ autonomous = spec is not None and "autonomous" in spec.tags
+ if task["trigger_type"] not in PAUSABLE_TRIGGER_TYPES and not autonomous:
raise TaskStateConflict(
f"only recurring tasks can be paused (trigger={task['trigger_type']})"
)
@@ -497,7 +506,7 @@ class TaskScheduler:
current = await self._store.get(task_id)
if current is None:
raise TaskNotFound(task_id)
- if spec.trigger.type not in PAUSABLE_TRIGGER_TYPES:
+ if spec.trigger.type not in PAUSABLE_TRIGGER_TYPES and "autonomous" not in spec.tags:
raise TaskStateConflict("Routine updates require a recurring trigger")
await self._validate_source(spec)
was_paused = current["state"] == "paused"
@@ -533,8 +542,12 @@ class TaskScheduler:
if spec.trigger.type in ("every", "calendar", "cron"):
due = next_every_due_ns(spec, now)
await self._store.set_next_due(task_id, due)
+ elif spec.trigger.type in ("after_delay", "at_time"):
+ # Pausing a one-time follow-up must not restart its original delay.
+ due = task.get("due_at_ns")
await self._store.update_state(task_id, "scheduled")
await self._store.append_step(task_id, "log", {"event": "resumed"})
+ self._remove_from_memory(task_id)
self._register_in_memory(spec, task_id, stored_due_at_ns=due)
if notify_activation:
await self._bus.publish(
@@ -770,6 +783,8 @@ class TaskScheduler:
"""
if task_id in self._known:
return
+ if "autonomous" in spec.tags:
+ self._autonomous_ids.add(task_id)
trig = spec.trigger
if trig.type == "after_delay":
due = (
@@ -898,6 +913,14 @@ class TaskScheduler:
due, tid = heapq.heappop(self._heap)
self._known.discard(tid)
spec = await self._store.get_spec(tid)
+ if spec is not None and "autonomous" in spec.tags:
+ row = await self._store.get(tid)
+ if row is None or row["state"] != "scheduled":
+ if row and row["state"] == "running" and spec.trigger.type in (
+ "every", "calendar", "cron",
+ ):
+ await self._rearm_every(tid, spec, now_ns)
+ continue
if spec is not None and spec.trigger.type in ("every", "calendar", "cron"):
if is_missed(due, now_ns):
# The process lived but did not tick (machine asleep,
@@ -948,18 +971,28 @@ class TaskScheduler:
self._runner_tasks.add(task)
task.add_done_callback(self._runner_tasks.discard)
- async def _safe_run(self, task_id: str, trigger_event: dict[str, Any] | None = None) -> None:
+ async def _safe_run(
+ self, task_id: str, trigger_event: dict[str, Any] | None = None,
+ *, allow_paused: bool = False,
+ ) -> None:
# Per-run cancel token (deep-dive 2026-07-15, H-03): production runs
# used to pass NO token, so the runner's cancel probes were no-ops and
# a running harness action was unstoppable except via the global kill
# switch. cancel_task() fires this token for a single running task.
from jarvis.control.cancel import CancelToken # noqa: PLC0415
+ if task_id in self._running_tokens:
+ return # A queued/manual firing cannot overlap an already admitted run.
token = CancelToken()
self._running_tokens[task_id] = token
path = tuple((trigger_event or {}).get("__trigger_path") or current_trigger_path.get())
context_token = current_trigger_path.set(path + ("task:" + task_id,))
try:
+ if task_id in self._autonomous_ids:
+ row = await self._store.get(task_id)
+ allowed = {"scheduled", "paused"} if allow_paused else {"scheduled"}
+ if row is None or row["state"] not in allowed:
+ return
await self._runner.run( # type: ignore[union-attr]
task_id,
token,
diff --git a/scripts/verify_agent_autonomy.py b/scripts/verify_agent_autonomy.py
new file mode 100644
index 0000000000..2eee5f1a0d
--- /dev/null
+++ b/scripts/verify_agent_autonomy.py
@@ -0,0 +1,116 @@
+"""Verify autonomous work contracts without contacting a billed provider."""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+import tempfile
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # noqa: E402
+
+TESTS = [
+ "tests/unit/agent_runtimes/test_runtime_configs.py",
+ "tests/contract/test_agent_autonomy.py",
+ "tests/contract/test_routine_chats.py",
+ "tests/contract/test_calendar_routines.py",
+ "tests/unit/society/test_cli_routines.py",
+ "tests/unit/society/test_proposals.py",
+ "tests/unit/society/test_routines.py",
+ "tests/unit/agent_chat/test_turn_completion.py",
+ "tests/unit/tasks/test_scheduler.py",
+ "tests/unit/tasks/test_scheduler_automations.py",
+ "tests/unit/tasks/test_runner_agent_result.py",
+ "tests/unit/brain/test_routing.py",
+ "tests/unit/brain/test_output_filter.py",
+ "tests/unit/sessions/test_hangup_reason_parity.py",
+ "tests/unit/core/test_turn_language.py",
+]
+CONTRACTS = (
+ "test_one_time_commitment_is_durable_without_approval_card",
+ "test_inferred_recurring_goal_is_active_without_routine_keyword",
+ "test_conditional_instructions_are_not_hypothetical_questions",
+ "test_no_routine_still_allows_a_requested_one_time_followup",
+ "test_duplicate_delivery_and_restart_keep_id_and_original_deadline",
+ "test_pause_resume_update_to_one_time_and_cancel_preserve_identity",
+ "test_non_actions_and_explicit_exclusions_do_not_create_jobs",
+ "test_forged_background_and_read_only_requests_are_refused",
+ "test_interrupted_effects_are_not_replayed_at_restart",
+ "test_paid_owner_waits_without_starting_a_turn_or_fallback",
+ "test_runtime_run_reports_its_result_in_the_origin_chat",
+ "test_unregistered_promise_continues_then_fails_honestly",
+ "test_promise_needs_a_real_active_receipt_not_an_unrelated_tool",
+ "test_delete_retains_cancellation_receipt",
+ "test_concurrent_identical_calls_register_only_one_job",
+ "test_waiting_recurring_task_is_not_restarted_by_a_stale_heap_entry",
+ "test_permission_ceiling_prevents_autonomous_creation",
+ "test_provider_error_does_not_fall_back_or_claim_completion",
+)
+SOURCES = [
+ "jarvis/agent_runtimes/openclaw.py", "tests/unit/agent_runtimes/test_runtime_configs.py",
+ "jarvis/agent_chat/background_work.py",
+ "jarvis/agent_chat/turn_completion.py",
+ "jarvis/society/autonomous_routines.py",
+ "jarvis/society/agent_tools.py",
+ "jarvis/society/proposals.py",
+ "jarvis/society/routines.py",
+ "jarvis/society/routine_runner.py",
+ "jarvis/society/surface.py",
+ "jarvis/tasks/runner.py",
+ "jarvis/tasks/scheduler.py",
+ "tests/contract/test_agent_autonomy.py",
+ "scripts/verify_agent_autonomy.py",
+]
+
+
+def run(arguments: list[str]) -> int:
+ result = subprocess.run(
+ [sys.executable, *arguments],
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ check=False,
+ )
+ if result.returncode:
+ print(result.stdout)
+ print(result.stderr)
+ return result.returncode
+
+
+def main() -> int:
+ if hasattr(sys.stdout, "reconfigure"):
+ sys.stdout.reconfigure(encoding="utf-8")
+ if run(["-m", "ruff", "check", *SOURCES]):
+ return 1
+ with tempfile.TemporaryDirectory(prefix="jarvis-autonomy-proof-") as temporary:
+ report = Path(temporary) / "tests.xml"
+ if run(["-m", "pytest", *TESTS, "-q", "--tb=short", f"--junitxml={report}"]):
+ return 1
+ # This file was produced by our own pytest process in a fresh private directory.
+ cases = list(ET.parse(report).iter("testcase")) # noqa: S314
+ for runtime in ("jarvis", "hermes", "openclaw"):
+ for contract in CONTRACTS:
+ matched = [
+ c for c in cases if c.get("name", "").startswith(f"{contract}[{runtime}")
+ ]
+ if not matched or any(len(case) for case in matched):
+ print(f"Missing, skipped or failed contract: {contract}[{runtime}]")
+ return 1
+ print(f"Verified {len(cases)} tests; all three runtime contract matrices passed.")
+ print("Evidence: real MCP gates, SQLite and scheduler; scripted model/CLI transport.")
+ print(
+ "Installed providers, native runtime processes and active desktop are not certified here."
+ )
+ print("AGENT_AUTONOMY_OK")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/contract/test_agent_autonomy.py b/tests/contract/test_agent_autonomy.py
new file mode 100644
index 0000000000..acec8bb601
--- /dev/null
+++ b/tests/contract/test_agent_autonomy.py
@@ -0,0 +1,471 @@
+"""Goal-derived work crosses the real MCP gate, task store and scheduler.
+
+The model/CLI transport is scripted. These contracts do not claim installed
+provider or desktop execution; each runtime uses the same owned-tool boundary.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.agent_chat.tool_context import register_turn, unregister_turn
+from jarvis.agent_chat.turn_completion import TurnCompletion
+from jarvis.brain.tool_gateway import BrainSupervisorToolGateway
+from jarvis.core import runtime_refs
+from jarvis.core.bus import EventBus
+from jarvis.core.protocols import ChatTurn, current_chat_turn
+from jarvis.mcp.jarvis_tools_server import build_server
+from jarvis.society.routine_runner import run_owned_routine
+from jarvis.society.runtime import SocietyRuntime
+from jarvis.society.surface import tools_for_cli_session
+from jarvis.tasks.runner import TaskRunner
+from jarvis.tasks.scheduler import TaskScheduler
+from jarvis.tasks.store import TaskStore
+from tests.fakes.fake_agent_chat import FakeChatService
+from tests.unit.society.test_cli_routines import ExecutingFake, call
+
+
[email protected](params=["jarvis", "hermes", "openclaw"])
+async def world(request, tmp_path, monkeypatch):
+ w = SimpleNamespace(runtime_name=request.param)
+ w.clock = SimpleNamespace(now_ns=time.time_ns())
+ clock = SimpleNamespace(time_ns=lambda: w.clock.now_ns, monotonic=time.monotonic)
+ monkeypatch.setattr("jarvis.tasks.store.time", clock)
+ monkeypatch.setattr("jarvis.tasks.scheduler.time", clock)
+ w.store = AgentChatStore(tmp_path / "chat.db")
+ service = FakeChatService(w.store)
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path)))
+ w.rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: service, cfg=lambda: cfg
+ )
+ await w.rt.ensure_started()
+ agent, _ = await w.rt.roster.create(name="Scout", runtime=request.param, provider="ollama")
+ w.store.create_session(
+ session_id=agent.session_id,
+ surface="society",
+ provider="ollama",
+ model="scripted",
+ effort="",
+ cwd=str(tmp_path),
+ permission_mode="bypass",
+ runtime=request.param,
+ )
+ w.task_path = tmp_path / "autonomy.db"
+ w.tasks = TaskStore(w.task_path)
+ await w.tasks.init()
+ w.scheduler = TaskScheduler(store=w.tasks, bus=EventBus())
+ w.rt.task_services = lambda: (w.tasks, w.scheduler)
+ executor = ExecutingFake()
+ manager = SimpleNamespace(_tools={}, _tool_executor=executor, _config=cfg)
+
+ async def scoped(session_id, tools):
+ return await tools_for_cli_session(session_id, tools, manager)
+
+ w.gateway = BrainSupervisorToolGateway(manager, session_tools=scoped)
+ previous = runtime_refs.get_supervisor_tool_gateway()
+ runtime_refs.set_supervisor_tool_gateway(w.gateway)
+ w.server = build_server()
+ try:
+ yield w
+ finally:
+ runtime_refs.set_supervisor_tool_gateway(previous)
+ await w.scheduler.shutdown()
+ await w.tasks.close()
+ await w.rt.close()
+ w.store.close()
+
+
+def arguments(text="Keep me informed about this project", *, schedule=None, **payload):
+ return {
+ "mode": "autonomous",
+ "kind": "routine",
+ "request_quote": text,
+ "reason": "A follow-up keeps the requested project information current.",
+ "payload": {
+ "title": "Project follow-up",
+ "prompt": "Check the project and report new findings.",
+ "schedule": schedule or {"kind": "after_delay", "delay_seconds": 60},
+ **payload,
+ },
+ }
+
+
+async def submit(w, args, *, text=None, direct=True, turn_id="t1"):
+ origin = ChatTurn("society:scout", turn_id, text or args["request_quote"], direct, "trace")
+ token = current_chat_turn.set(origin)
+ registration = register_turn(origin.session_id)
+ current_chat_turn.reset(token)
+ try:
+ result = await call(w, "society_propose_change", args)
+ try:
+ return json.loads(result)
+ except ValueError:
+ return {"error": result}
+ finally:
+ unregister_turn(origin.session_id, registration)
+
+
+async def test_one_time_commitment_is_durable_without_approval_card(world):
+ result = await submit(world, arguments())
+ assert result.get("applied"), result
+ task_id = result["task_id"]
+ row = await world.tasks.get(task_id)
+ assert row["state"] == "scheduled" and result["next_run"]
+ assert task_id in world.scheduler._known
+ spec = await world.tasks.get_spec(task_id)
+ assert spec.trigger.type == "after_delay"
+ origin = json.loads(next(t[7:] for t in spec.tags if t.startswith("origin:")))
+ assert origin["turn_id"] == "t1" and origin["request_quote"] == arguments()["request_quote"]
+ assert not await world.rt.approvals.items(state="pending")
+ assert not any(n.get("kind") == "proposal" for _, n in world.rt.chat_service().notices)
+
+
+async def test_inferred_recurring_goal_is_active_without_routine_keyword(world):
+ result = await submit(world, arguments(schedule={"kind": "every", "interval_seconds": 3600}))
+ spec = await world.tasks.get_spec(result["task_id"])
+ assert spec.trigger.type == "every" and result["state"] == "scheduled"
+
+
+ "text",
+ [
+ "If the project changes, check it again and keep me informed",
+ "Wenn sich das Projekt ändert, prüfe es und halte mich auf dem Laufenden", # i18n-allow
+ ],
+)
+async def test_conditional_instructions_are_not_hypothetical_questions(world, text):
+ result = await submit(
+ world, arguments(text, schedule={"kind": "every", "interval_seconds": 60})
+ )
+ assert result.get("applied"), result
+
+
+async def test_no_routine_still_allows_a_requested_one_time_followup(world):
+ result = await submit(world, arguments("Check it later only once, no routine"))
+ assert result.get("applied"), result
+ assert result["trigger"]["type"] == "after_delay"
+
+
+async def test_duplicate_delivery_and_restart_keep_id_and_original_deadline(world):
+ first = await submit(world, arguments())
+ tid = first["task_id"]
+ deadline = (await world.tasks.get(tid))["due_at_ns"]
+ world.clock.now_ns += 20_000_000_000
+ await world.tasks.close()
+ world.tasks = TaskStore(world.task_path)
+ await world.tasks.init()
+ world.scheduler = TaskScheduler(store=world.tasks, bus=EventBus())
+ await world.scheduler.hydrate()
+ second = await submit(world, arguments(), turn_id="redelivery")
+ assert second["task_id"] == tid and second["reused"]
+ assert (await world.tasks.get(tid))["due_at_ns"] == deadline
+ assert len(await world.tasks.list()) == 1
+ assert world.scheduler._heap == [(deadline, tid)]
+
+
+async def test_pause_resume_update_to_one_time_and_cancel_preserve_identity(world):
+ original = arguments(schedule={"kind": "every", "interval_seconds": 3600})
+ tid = (await submit(world, original))["task_id"]
+ for operation, expected in [("pause", "paused"), ("resume", "scheduled")]:
+ outcome = await submit(world, arguments(operation=operation, task_id=tid))
+ assert outcome["state"] == expected
+ changed = await submit(
+ world,
+ arguments(
+ "Only this time",
+ operation="update",
+ task_id=tid,
+ schedule={"kind": "after_delay", "delay_seconds": 120},
+ ),
+ )
+ assert changed["task_id"] == tid and changed["trigger"]["type"] == "after_delay"
+ deadline = (await world.tasks.get(tid))["due_at_ns"]
+ await submit(world, arguments(operation="pause", task_id=tid))
+ await submit(world, arguments(operation="resume", task_id=tid))
+ assert (await world.tasks.get(tid))["due_at_ns"] == deadline
+ outcome = await submit(world, arguments("Stop that work", operation="cancel", task_id=tid))
+ assert outcome["state"] == "cancelled"
+ again = await submit(world, original)
+ assert again["state"] == "cancelled" and again["reused"]
+ assert tid not in world.scheduler._known
+
+
+ "text",
+ [
+ "Explain how to check the project later",
+ '"Check the project later"',
+ "If I wanted to monitor the project, what would happen?",
+ "Check this project but do not schedule anything",
+ "Nur diesmal prüfen", # i18n-allow: user input
+ ],
+)
+async def test_non_actions_and_explicit_exclusions_do_not_create_jobs(world, text):
+ result = await submit(
+ world, arguments(text, schedule={"kind": "every", "interval_seconds": 60})
+ )
+ assert not result.get("applied"), result
+ assert await world.tasks.list() == []
+
+
+async def test_forged_background_and_read_only_requests_are_refused(world):
+ result = await submit(world, arguments(), direct=False)
+ assert not result.get("applied"), result
+ result = await submit(world, arguments(), text="Unrelated current request")
+ assert not result.get("applied"), result
+ world.store.update_session("society:scout", permission_mode="plan")
+ result = await submit(world, arguments())
+ assert not result.get("applied"), result
+ assert await world.tasks.list() == []
+
+
+async def test_interrupted_effects_are_not_replayed_at_restart(world):
+ tid = (await submit(world, arguments()))["task_id"]
+ await world.tasks.update_state(tid, "running")
+ await world.tasks.append_step(tid, "log", {"event": "effect_started", "receipt": "r1"})
+ assert await world.tasks.cleanup_interrupted() == 1
+ restarted = TaskScheduler(store=world.tasks, bus=EventBus())
+ await restarted.hydrate()
+ assert tid not in restarted._known
+ assert (await submit(world, arguments()))["state"] == "interrupted"
+
+
+async def test_paid_owner_waits_without_starting_a_turn_or_fallback(world):
+ await world.rt.roster.update("scout", {"provider": "openai"})
+ tid = (await submit(world, arguments()))["task_id"]
+ notices = []
+
+ async def owned(task_id, tags, prompt, cancel):
+ return await run_owned_routine(world.rt, task_id, tags, prompt, cancel)
+
+ async def sink(tags, text, status):
+ notices.append((text, status))
+
+ runner = TaskRunner(
+ store=world.tasks,
+ bus=EventBus(),
+ harness_manager=None,
+ tts=None,
+ tool_executor=None,
+ tool_registry={},
+ owned_agent_runner=owned,
+ result_sink=sink,
+ )
+ await runner.run(tid)
+ row = await world.tasks.get(tid)
+ assert row["state"] == "paused" and "subscription" in row["last_error"]
+ assert notices[-1][1] == "waiting"
+ assert world.rt.chat_service().sent == []
+
+
[email protected]("paused", [False, True])
+async def test_runtime_run_reports_its_result_in_the_origin_chat(world, monkeypatch, paused):
+ tid = (await submit(world, arguments()))["task_id"]
+ service = world.rt.chat_service()
+ sent = []
+
+ async def scripted_send(session_id, text, **kwargs):
+ session = service.store.get_session(session_id)
+ sent.append(session.runtime or "jarvis")
+ assert kwargs == {"direct_user": False, "routine_run": True}
+ for event in [
+ {"kind": "tool_call", "payload": {"name": "read", "turn_id": "run"}},
+ {"kind": "tool_result", "payload": {"output": "checked", "turn_id": "run"}},
+ {
+ "kind": "assistant_text",
+ "payload": {"text": "Checked and compared the project.", "turn_id": "run"},
+ },
+ {"kind": "turn_finished", "payload": {"status": "done", "turn_id": "run"}},
+ ]:
+ for queue in service._subs.get(session_id, ()):
+ queue.put_nowait(event)
+ return "run"
+
+ monkeypatch.setattr(service, "send", scripted_send)
+
+ async def owned(task_id, tags, prompt, cancel):
+ return await run_owned_routine(world.rt, task_id, tags, prompt, cancel)
+
+ runner = TaskRunner(
+ store=world.tasks,
+ bus=EventBus(),
+ harness_manager=None,
+ tts=None,
+ tool_executor=None,
+ tool_registry={},
+ owned_agent_runner=owned,
+ )
+ world.scheduler.attach_runner(runner)
+ if paused:
+ await world.scheduler.pause(tid)
+ await world.scheduler.run_now(tid)
+ await asyncio.gather(*world.scheduler._runner_tasks)
+ assert (await world.tasks.get(tid))["state"] == "completed"
+ result = service.notices[-1][1]["text"]
+ assert result == "Checked and compared the project."
+ assert sent == [world.runtime_name]
+ notice = service.notices[-1]
+ assert notice[0] == "society:scout" and notice[1]["kind"] == "society_result"
+ assert notice[1]["task_id"] == tid and notice[1]["text"] == result
+
+
+async def test_unregistered_promise_continues_then_fails_honestly(world):
+ events = []
+
+ async def emit(event):
+ events.append(event)
+
+ service = SimpleNamespace(undelivered_questions=lambda *_: [], pending_approvals=lambda *_: [])
+ handle = SimpleNamespace(
+ session=world.store.get_session("society:scout"),
+ turn_id="t1",
+ cancel=asyncio.Event(),
+ emit=emit,
+ )
+ gate = TurnCompletion(service, handle, arguments()["request_quote"], allow_correction=True)
+ promise = {
+ "kind": "assistant_text",
+ "payload": {
+ "text": "The current version is available. I'll check again later and report back.",
+ },
+ }
+ await gate.emit(promise)
+ assert events[-1]["payload"]["text"] == "The current version is available."
+ await gate.emit({"kind": "turn_finished", "payload": {"status": "done"}})
+ assert "register" in await gate.next_prompt()
+ await gate.emit(promise)
+ await gate.emit({"kind": "turn_finished", "payload": {"status": "done"}})
+ assert await gate.next_prompt() is None
+ await gate.publish()
+ assert events[-1]["payload"]["status"] == "error"
+ assert await world.tasks.list() == [] # The prose guard never schedules work itself.
+
+
+async def test_promise_needs_a_real_active_receipt_not_an_unrelated_tool(world):
+ result = await submit(world, arguments())
+ events = []
+
+ async def emit(event):
+ events.append(event)
+
+ service = SimpleNamespace(undelivered_questions=lambda *_: [], pending_approvals=lambda *_: [])
+ handle = SimpleNamespace(
+ session=world.store.get_session("society:scout"),
+ turn_id="t1",
+ cancel=asyncio.Event(),
+ emit=emit,
+ )
+ gate = TurnCompletion(service, handle, arguments()["request_quote"], allow_correction=True)
+ await gate.emit(
+ {
+ "kind": "tool_call",
+ "payload": {
+ "call_id": "saved",
+ "name": "mcp__jarvis__society_propose_change",
+ "input": arguments(),
+ },
+ }
+ )
+ await gate.emit(
+ {
+ "kind": "tool_result",
+ "payload": {
+ "call_id": "saved",
+ "output": json.dumps(result),
+ "is_error": False,
+ },
+ }
+ )
+ promise = {"kind": "assistant_text", "payload": {"text": "I'll check again later."}}
+ await gate.emit(promise)
+ assert events[-1] == promise and not gate.background_unregistered
+ await world.scheduler.cancel_task(result["task_id"])
+ await gate.emit(promise)
+ assert gate.background_unregistered
+
+
+async def test_delete_retains_cancellation_receipt(world):
+ original = arguments()
+ tid = (await submit(world, original))["task_id"]
+ result = await submit(world, arguments("Delete that task", operation="delete", task_id=tid))
+ assert result["state"] == "cancelled"
+ again = await submit(world, original)
+ assert again["reused"] and again["state"] == "cancelled"
+
+
+async def test_concurrent_identical_calls_register_only_one_job(world):
+ args = arguments()
+ origin = ChatTurn("society:scout", "t1", args["request_quote"], True, "trace")
+ token = current_chat_turn.set(origin)
+ registration = register_turn(origin.session_id)
+ current_chat_turn.reset(token)
+ try:
+ responses = await asyncio.gather(
+ call(world, "society_propose_change", args),
+ call(world, "society_propose_change", args),
+ )
+ finally:
+ unregister_turn(origin.session_id, registration)
+ decoded = [json.loads(response) for response in responses]
+ assert all(r["applied"] for r in decoded)
+ assert len({r["task_id"] for r in decoded}) == 1
+ assert len(await world.tasks.list()) == 1
+
+
+async def test_waiting_recurring_task_is_not_restarted_by_a_stale_heap_entry(world):
+ tid = (await submit(world, arguments(schedule={"kind": "every", "interval_seconds": 60})))[
+ "task_id"
+ ]
+ calls = []
+
+ async def run(task_id, *_args, **_kwargs):
+ calls.append(task_id)
+
+ world.scheduler.attach_runner(SimpleNamespace(run=run))
+ await world.tasks.update_state(tid, "paused", error="Waiting for a subscription")
+ world.clock.now_ns += 60_000_000_000
+ await world.scheduler._drain_due_tasks(world.clock.now_ns)
+ await world.scheduler._safe_run(tid)
+ assert calls == [] and tid not in world.scheduler._known
+
+
+async def test_permission_ceiling_prevents_autonomous_creation(world):
+ await world.rt.roster.update("scout", {"permission_ceiling": "safe"})
+ result = await submit(world, arguments())
+ assert not result.get("applied"), result
+ assert await world.tasks.list() == []
+
+
+async def test_provider_error_does_not_fall_back_or_claim_completion(world, monkeypatch):
+ tid = (await submit(world, arguments()))["task_id"]
+ calls = []
+
+ async def unavailable(*_args, **_kwargs):
+ calls.append("provider")
+ raise RuntimeError("Subscription temporarily unavailable")
+
+ monkeypatch.setattr(world.rt.chat_service(), "send", unavailable)
+
+ async def owned(task_id, tags, prompt, cancel):
+ return await run_owned_routine(world.rt, task_id, tags, prompt, cancel)
+
+ runner = TaskRunner(
+ store=world.tasks,
+ bus=EventBus(),
+ harness_manager=None,
+ tts=None,
+ tool_executor=None,
+ tool_registry={},
+ owned_agent_runner=owned,
+ )
+ await runner.run(tid)
+ row = await world.tasks.get(tid)
+ assert row["state"] == "failed" and "unavailable" in row["last_error"]
+ assert calls == ["provider"]
+ assert not any(n.get("status") == "done" for _, n in world.rt.chat_service().notices)
diff --git a/tests/unit/agent_runtimes/test_runtime_configs.py b/tests/unit/agent_runtimes/test_runtime_configs.py
index 51e4c14c5b..3b823fcd5c 100644
--- a/tests/unit/agent_runtimes/test_runtime_configs.py
+++ b/tests/unit/agent_runtimes/test_runtime_configs.py
@@ -153,6 +153,9 @@ def test_openclaw_config_keeps_both_keys_out_of_the_file(tmp_path):
def test_openclaw_never_runs_background_turns_or_persona_files(tmp_path):
config = OpenClawRuntime().config_for(_turn(tmp_path), port=4321, token=_TOKEN)
+ assert config["cron"]["enabled"] is False
+ assert config["plugins"]["slots"]["memory"] == "none"
+ assert config["plugins"]["entries"]["memory-core"]["enabled"] is False
defaults = config["agents"]["defaults"]
assert defaults["heartbeat"] == {"every": "0m"}
assert defaults["skipBootstrap"] is True