Personal AI, On Personal Devices
Python
feat: add Gmail/Twitter channel adapters, curated templates, channel contract tests, and QA runbook
Jon Saad-Falconcf362897cd95
diff --git a/docs/testing/agent-qa-runbook.md b/docs/testing/agent-qa-runbook.mdnew file mode 100644index 00000000..df79fcee--- /dev/null+++ b/docs/testing/agent-qa-runbook.md@@ -0,0 +1,75 @@+# Agent QA Runbook++Manual testing scenarios for persistent agents in the CLI and desktop app.++## Environment Setup++| Prerequisite | Command / Check |+|---|---|+| Ollama running with model | `ollama list` shows `qwen3:8b` |+| OpenJarvis initialized | `uv run jarvis doctor` all green |+| Rust extension built | `uv run maturin develop -m rust/crates/openjarvis-python/Cargo.toml` |+| Desktop app running | `uv run jarvis serve` + `cd frontend && npm run dev` |+| Slack credentials | `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN` set, bot invited to test channel |+| Gmail credentials | OAuth credentials.json downloaded, token generated |+| Twitter credentials | All 5 env vars set (bearer + OAuth 1.0a) |+| Discord credentials | Bot token set, bot invited to test server |+| Telegram credentials | Bot token from @BotFather, test chat ID known |+| Email credentials | SMTP/IMAP host + credentials for test account |++## CLI Agent Scenarios++| # | Scenario | Steps | Expected Result | Pass |+|---|----------|-------|-----------------|------|+| 1 | Template launch | `jarvis agents launch`, pick research_monitor | Agent created, config printed with curated tools | [ ] |+| 2 | Manual run | `jarvis agents run <id>` | Output shows reasoning + tool calls, status -> idle | [ ] |+| 3 | Immediate ask | `jarvis agents ask <id> "summarize recent AI news"` | Synchronous response in terminal | [ ] |+| 4 | Queued instruct | `jarvis agents instruct <id> "focus on diffusion"`, then `jarvis agents run <id>` | Queued -> delivered, response in `jarvis agents messages <id>` | [ ] |+| 5 | Status check | `jarvis agents status` after 3+ runs | total_runs, total_cost, last_run_at populated | [ ] |+| 6 | Pause/resume | `jarvis agents pause <id>`, verify skipped, `jarvis agents resume <id>`, verify fires | Status toggles correctly | [ ] |+| 7 | Daemon scheduling | `jarvis agents daemon` with interval agent (60s) | 3+ ticks fire on schedule, memory accumulates | [ ] |+| 8 | Budget exhaustion | Set max_cost=0.001, run until exceeded | Status becomes budget_exceeded | [ ] |+| 9 | Error recovery | Kill Ollama mid-tick, then `jarvis agents recover <id>` | Error -> recover -> idle with checkpoint | [ ] |+| 10 | Channel binding | `jarvis agents bind <id> --slack #test`, run tick | Agent sends to Slack | [ ] |+| 11 | Multi-agent | Launch 3 agents, different intervals, run daemon | All fire independently | [ ] |+| 12 | Template tools | Create from each template, `jarvis agents info <id>` | All curated default tools listed | [ ] |++## Desktop App Scenarios++| # | Scenario | Steps | Expected Result | Pass |+|---|----------|-------|-----------------|------|+| 1 | Template wizard | New Agent -> pick each template -> complete wizard | Agent appears in grid with correct config | [ ] |+| 2 | Custom agent | New Agent -> Custom -> manual schedule, pick tools, set credentials | Tools + creds saved, agent created | [ ] |+| 3 | Run Now | Click Run Now on agent card | Status dot: green -> blue -> green, stats increment | [ ] |+| 4 | Immediate chat | Interact tab -> type message -> send (immediate mode) | Response appears in chat UI | [ ] |+| 5 | Queued chat | Interact tab -> send (queued mode) -> click Run Now | Message delivered on tick, response appears | [ ] |+| 6 | Task management | Tasks tab -> create task -> run agent | Task status updates, findings populated | [ ] |+| 7 | Memory inspection | Run 3+ ticks -> Memory tab | Summary memory reflects agent's accumulated knowledge | [ ] |+| 8 | Trace inspection | Run tick -> Logs tab | Trace steps visible with tool calls and results | [ ] |+| 9 | Learning | Enable trace-driven learning -> Learning tab -> trigger | Learning log entries appear | [ ] |+| 10 | Error + recovery | Stop Ollama -> run agent -> verify error badge -> click Recover | Error state shown, recovery resets to idle | [ ] |++## Channel-Specific QA Matrix++| Channel | Send Test | Receive Test | Thread/Reply Test | Agent Template | Pass |+|---------|-----------|-------------|-------------------|----------------|------|+| Slack | Post to #test-channel | Socket Mode incoming msg | Reply in thread (thread_ts) | inbox_triager | [ ] |+| Gmail | Send email to test recipient | Poll unread -> handler fires | Reply in thread (threadId) | inbox_triager | [ ] |+| Email (SMTP/IMAP) | Send via SMTP | IMAP poll UNSEEN | In-Reply-To header | inbox_triager | [ ] |+| iMessage (BlueBubbles) | Send to phone number | N/A (send-only) | N/A | research_monitor | [ ] |+| Twitter/X | Post tweet + send DM | Poll mentions | Reply (in_reply_to_tweet_id) | research_monitor | [ ] |+| Discord | Post to #test-channel | Gateway message event | N/A | code_reviewer | [ ] |+| Telegram | Send to test chat | Long-poll update | reply_to_message_id | research_monitor | [ ] |+| WhatsApp (Baileys) | Send to test number | Baileys incoming msg | N/A | inbox_triager | [ ] |++## Stress & Edge Cases++| # | Scenario | How to Test | Pass Criteria | Pass |+|---|----------|-------------|---------------|------|+| 1 | Message flood | Queue 50 messages via CLI, run tick | All 50 delivered, response generated | [ ] |+| 2 | Long-running daemon | Run daemon for 1 hour, 60s interval agent | No memory leak, no stall, ~60 ticks | [ ] |+| 3 | Rapid pause/resume | Script: pause -> resume -> pause -> resume during tick | Clean state, no corruption | [ ] |+| 4 | Credential revocation | Revoke Slack token mid-tick | Agent gets tool error, tick completes, status not corrupted | [ ] |+| 5 | Multi-agent load | 10 agents on daemon, mix of intervals | All fire on schedule, no interference | [ ] |+| 6 | Large response handling | Agent produces 10k+ char response | summary_memory truncated to 2000 chars, full response in messages | [ ] |+| 7 | Checkpoint integrity | Kill process mid-tick, restart, recover | Checkpoint restored, agent resumes cleanly | [ ] |diff --git a/pyproject.toml b/pyproject.tomlindex 6a50980e..987e76a2 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -77,6 +77,12 @@ channel-rocketchat = ["rocketchat-API>=1.30"]channel-zulip = ["zulip>=0.9"]channel-twitch = ["twitchio>=2.6"]channel-nostr = ["pynostr>=0.6"]+channel-gmail = [+ "google-api-python-client>=2.0",+ "google-auth-oauthlib>=1.0",+ "google-auth-httplib2>=0.2",+]+channel-twitter = ["tweepy>=4.14"]browser = ["playwright>=1.40"]media = ["openai>=1.30"]pdf = ["pdfplumber>=0.10"]@@ -117,6 +123,7 @@ markers = ["apple: requires Apple Silicon","macos15: requires macOS 15+ (Sequoia) for Apple FM","slow: long-running test",+ "live_channel: requires real channel credentials (env vars)",][tool.ruff]diff --git a/src/openjarvis/agents/templates/code_reviewer.toml b/src/openjarvis/agents/templates/code_reviewer.tomlindex f31152a9..4a93f40a 100644--- a/src/openjarvis/agents/templates/code_reviewer.toml+++ b/src/openjarvis/agents/templates/code_reviewer.toml@@ -5,11 +5,11 @@ description = "Monitors a repository for changes, reviews code, and stores feedbagent_type = "monitor_operative"schedule_type = "interval"schedule_value = "3600"-tools = ["file_read", "shell_exec", "memory_store", "think"]+tools = ["file_read", "file_write", "shell_exec", "git_status", "git_diff", "git_commit", "git_log", "apply_patch", "code_interpreter", "memory_store", "memory_retrieve", "think", "channel_send", "channel_list"]max_turns = 15temperature = 0.2memory_extraction = "scratchpad"observation_compression = "summarize"retrieval_strategy = "keyword"task_decomposition = "monolithic"-system_prompt = "You are a code review agent. Monitor the repository for recent changes, review code quality, identify potential bugs, and store your findings."+system_prompt = "You are a code review agent. Monitor the repository for recent changes, review code quality, identify potential bugs, and store your findings. After completing your review, send a summary of findings and any suggested patches to bound channels using channel_send."diff --git a/src/openjarvis/agents/templates/inbox_triager.toml b/src/openjarvis/agents/templates/inbox_triager.tomlindex 1087b2b1..9999c271 100644--- a/src/openjarvis/agents/templates/inbox_triager.toml+++ b/src/openjarvis/agents/templates/inbox_triager.toml@@ -5,11 +5,11 @@ description = "Monitors email and messaging channels, categorizes and summarizesagent_type = "monitor_operative"schedule_type = "interval"schedule_value = "1800"-tools = ["web_search", "memory_store", "memory_retrieve", "think"]+tools = ["channel_send", "channel_list", "memory_store", "memory_retrieve", "think", "web_search", "file_write"]max_turns = 20temperature = 0.3memory_extraction = "structured_json"observation_compression = "summarize"retrieval_strategy = "semantic"task_decomposition = "phased"-system_prompt = "You are an inbox triage agent. Monitor incoming messages, categorize them by priority and topic, summarize key information, and flag items that need attention."+system_prompt = "You are an inbox triage agent. Monitor incoming messages, categorize them by priority and topic, summarize key information, and flag items that need attention. When triaging messages, use channel_send to forward urgent items or send status updates to bound channels."diff --git a/src/openjarvis/agents/templates/research_monitor.toml b/src/openjarvis/agents/templates/research_monitor.tomlindex ef1aad1e..ff087f9b 100644--- a/src/openjarvis/agents/templates/research_monitor.toml+++ b/src/openjarvis/agents/templates/research_monitor.toml@@ -5,11 +5,11 @@ description = "Periodically searches for papers/news on a topic, stores findingsagent_type = "monitor_operative"schedule_type = "cron"schedule_value = "0 9 * * *"-tools = ["web_search", "memory_store", "memory_retrieve", "think"]+tools = ["web_search", "http_request", "file_read", "file_write", "memory_store", "memory_retrieve", "think", "channel_send", "channel_list"]max_turns = 25temperature = 0.3memory_extraction = "structured_json"observation_compression = "summarize"retrieval_strategy = "hybrid_with_self_eval"task_decomposition = "phased"-system_prompt = "You are a research monitor agent. Your job is to search for new papers, articles, and developments on your assigned topics. Store important findings in memory. Be thorough but concise in your summaries."+system_prompt = "You are a research monitor agent. Your job is to search for new papers, articles, and developments on your assigned topics. Store important findings in memory. Be thorough but concise in your summaries. After completing your research, send a summary of findings to any bound channels using the channel_send tool."diff --git a/src/openjarvis/channels/__init__.py b/src/openjarvis/channels/__init__.pyindex df908166..e98ce6e8 100644--- a/src/openjarvis/channels/__init__.py+++ b/src/openjarvis/channels/__init__.py@@ -38,6 +38,8 @@ _CHANNEL_MODULES = ["zulip_channel","twitch_channel","nostr_channel",+ "twitter",+ "gmail",]for _mod in _CHANNEL_MODULES:diff --git a/src/openjarvis/channels/gmail.py b/src/openjarvis/channels/gmail.pynew file mode 100644index 00000000..95f8c729--- /dev/null+++ b/src/openjarvis/channels/gmail.py@@ -0,0 +1,298 @@+"""GmailChannel — native Gmail API adapter using OAuth2."""++from __future__ import annotations++import base64+import logging+import os+import threading+from email.mime.text import MIMEText+from typing import Any, Dict, List, Optional++from openjarvis.channels._stubs import (+ BaseChannel,+ ChannelHandler,+ ChannelMessage,+ ChannelStatus,+)+from openjarvis.core.events import EventBus, EventType+from openjarvis.core.registry import ChannelRegistry++logger = logging.getLogger(__name__)++[email protected]("gmail")+class GmailChannel(BaseChannel):+ """Native Gmail channel adapter using the Gmail API with OAuth2.++ Parameters+ ----------+ credentials_path:+ Path to the OAuth2 ``credentials.json`` file.+ Falls back to ``GMAIL_CREDENTIALS_PATH`` env var.+ token_path:+ Path to the stored OAuth2 token file.+ Falls back to ``GMAIL_TOKEN_PATH`` env var.+ user_id:+ Gmail user ID (default ``"me"`` for the authenticated user).+ poll_interval:+ Seconds between inbox polls (default 30).+ bus:+ Optional event bus for publishing channel events.+ """++ channel_id = "gmail"++ def __init__(+ self,+ credentials_path: str = "",+ *,+ token_path: str = "",+ user_id: str = "me",+ poll_interval: int = 30,+ bus: Optional[EventBus] = None,+ ) -> None:+ self._credentials_path = credentials_path or os.environ.get(+ "GMAIL_CREDENTIALS_PATH", "",+ )+ self._token_path = token_path or os.environ.get(+ "GMAIL_TOKEN_PATH", "",+ )+ self._user_id = user_id+ self._poll_interval = poll_interval+ self._bus = bus+ self._handlers: List[ChannelHandler] = []+ self._status = ChannelStatus.DISCONNECTED+ self._service: Any = None+ self._listener_thread: Optional[threading.Thread] = None+ self._stop_event = threading.Event()++ # -- connection lifecycle ---------------------------------------------------++ def connect(self) -> None:+ """Load OAuth2 credentials and build the Gmail API service."""+ if not self._credentials_path and not self._token_path:+ logger.warning("No Gmail credentials configured")+ self._status = ChannelStatus.ERROR+ return++ self._stop_event.clear()+ self._status = ChannelStatus.CONNECTING++ try:+ from google.oauth2.credentials import Credentials+ from google_auth_oauthlib.flow import InstalledAppFlow+ from googleapiclient.discovery import build++ SCOPES = ["https://www.googleapis.com/auth/gmail.modify"]++ creds: Any = None+ if self._token_path and os.path.exists(self._token_path):+ creds = Credentials.from_authorized_user_file(+ self._token_path, SCOPES,+ )++ if not creds or not creds.valid:+ if creds and creds.expired and creds.refresh_token:+ from google.auth.transport.requests import Request++ creds.refresh(Request())+ elif self._credentials_path and os.path.exists(+ self._credentials_path,+ ):+ flow = InstalledAppFlow.from_client_secrets_file(+ self._credentials_path, SCOPES,+ )+ creds = flow.run_local_server(port=0)+ else:+ logger.warning("Gmail credentials not found or invalid")+ self._status = ChannelStatus.ERROR+ return++ # Save token for future use+ if self._token_path and creds:+ with open(self._token_path, "w") as token_file:+ token_file.write(creds.to_json())++ self._service = build("gmail", "v1", credentials=creds)+ self._status = ChannelStatus.CONNECTED+ logger.info("Gmail channel connected")++ # Start polling thread+ self._listener_thread = threading.Thread(+ target=self._poll_loop, daemon=True,+ )+ self._listener_thread.start()+ except ImportError:+ logger.warning(+ "Google API libraries not installed; "+ "install with: pip install openjarvis[channel-gmail]",+ )+ self._status = ChannelStatus.ERROR+ except Exception:+ logger.debug("Gmail connect failed", exc_info=True)+ self._status = ChannelStatus.ERROR++ def disconnect(self) -> None:+ """Stop the polling thread and clear the service."""+ self._stop_event.set()+ if self._listener_thread is not None:+ self._listener_thread.join(timeout=5.0)+ self._listener_thread = None+ self._service = None+ self._status = ChannelStatus.DISCONNECTED++ # -- send / receive --------------------------------------------------------++ def send(+ self,+ channel: str,+ content: str,+ *,+ conversation_id: str = "",+ metadata: Dict[str, Any] | None = None,+ ) -> bool:+ """Send an email via the Gmail API.++ ``channel`` is the recipient email address.+ """+ if self._service is None:+ logger.warning("Cannot send: Gmail service not connected")+ return False++ try:+ msg = MIMEText(content)+ msg["To"] = channel+ msg["From"] = self._user_id+ msg["Subject"] = (metadata or {}).get(+ "subject", "Message from OpenJarvis",+ )++ raw = base64.urlsafe_b64encode(msg.as_bytes()).decode("utf-8")+ body: Dict[str, Any] = {"raw": raw}+ if conversation_id:+ body["threadId"] = conversation_id++ self._service.users().messages().send(+ userId=self._user_id, body=body,+ ).execute()++ self._publish_sent(channel, content, conversation_id)+ return True+ except Exception:+ logger.debug("Gmail send failed", exc_info=True)+ return False++ def status(self) -> ChannelStatus:+ """Return the current connection status."""+ if self._status == ChannelStatus.CONNECTED and self._service is None:+ return ChannelStatus.ERROR+ return self._status++ def list_channels(self) -> List[str]:+ """Return available channel identifiers."""+ return ["inbox"]++ def on_message(self, handler: ChannelHandler) -> None:+ """Register a callback for incoming Gmail messages."""+ self._handlers.append(handler)++ # -- internal helpers -------------------------------------------------------++ def _poll_loop(self) -> None:+ """Poll Gmail inbox for unread messages."""+ while not self._stop_event.is_set():+ try:+ if self._service is None:+ break++ results = (+ self._service.users()+ .messages()+ .list(userId=self._user_id, q="is:unread")+ .execute()+ )+ messages = results.get("messages", [])++ for msg_ref in messages:+ msg_id = msg_ref["id"]+ msg = (+ self._service.users()+ .messages()+ .get(userId=self._user_id, id=msg_id, format="full")+ .execute()+ )++ headers = {+ h["name"]: h["value"]+ for h in msg.get("payload", {}).get("headers", [])+ }++ # Extract body text+ body = ""+ payload = msg.get("payload", {})+ if payload.get("body", {}).get("data"):+ body = base64.urlsafe_b64decode(+ payload["body"]["data"],+ ).decode("utf-8", errors="replace")+ elif payload.get("parts"):+ for part in payload["parts"]:+ if part.get("mimeType") == "text/plain":+ data = part.get("body", {}).get("data", "")+ if data:+ body = base64.urlsafe_b64decode(+ data,+ ).decode("utf-8", errors="replace")+ break++ cm = ChannelMessage(+ channel="gmail",+ sender=headers.get("From", ""),+ content=body,+ message_id=msg_id,+ conversation_id=msg.get("threadId", ""),+ )++ for handler in self._handlers:+ try:+ handler(cm)+ except Exception:+ logger.exception("Gmail handler error")++ if self._bus is not None:+ self._bus.publish(+ EventType.CHANNEL_MESSAGE_RECEIVED,+ {+ "channel": cm.channel,+ "sender": cm.sender,+ "content": cm.content,+ "message_id": cm.message_id,+ },+ )++ # Mark message as read+ self._service.users().messages().modify(+ userId=self._user_id,+ id=msg_id,+ body={"removeLabelIds": ["UNREAD"]},+ ).execute()++ except Exception:+ logger.debug("Gmail poll error", exc_info=True)++ self._stop_event.wait(self._poll_interval)++ def _publish_sent(self, channel: str, content: str, conversation_id: str) -> None:+ """Publish a CHANNEL_MESSAGE_SENT event on the bus."""+ if self._bus is not None:+ self._bus.publish(+ EventType.CHANNEL_MESSAGE_SENT,+ {+ "channel": channel,+ "content": content,+ "conversation_id": conversation_id,+ },+ )+++__all__ = ["GmailChannel"]diff --git a/src/openjarvis/channels/twitter.py b/src/openjarvis/channels/twitter.pynew file mode 100644index 00000000..5a14dfd2--- /dev/null+++ b/src/openjarvis/channels/twitter.py@@ -0,0 +1,242 @@+"""TwitterChannel — native Twitter/X API adapter using tweepy."""++from __future__ import annotations++import logging+import os+import threading+from typing import Any, Dict, List, Optional++from openjarvis.channels._stubs import (+ BaseChannel,+ ChannelHandler,+ ChannelMessage,+ ChannelStatus,+)+from openjarvis.core.events import EventBus, EventType+from openjarvis.core.registry import ChannelRegistry++logger = logging.getLogger(__name__)++[email protected]("twitter")+class TwitterChannel(BaseChannel):+ """Native Twitter/X channel adapter using tweepy.++ Parameters+ ----------+ bearer_token:+ Twitter API v2 Bearer Token. Falls back to ``TWITTER_BEARER_TOKEN``.+ api_key:+ Twitter API Key (consumer key). Falls back to ``TWITTER_API_KEY``.+ api_secret:+ Twitter API Secret (consumer secret). Falls back to ``TWITTER_API_SECRET``.+ access_token:+ Twitter Access Token. Falls back to ``TWITTER_ACCESS_TOKEN``.+ access_secret:+ Twitter Access Token Secret. Falls back to ``TWITTER_ACCESS_SECRET``.+ poll_interval:+ Seconds between mention polls (default 60).+ bus:+ Optional event bus for publishing channel events.+ """++ channel_id = "twitter"++ def __init__(+ self,+ bearer_token: str = "",+ *,+ api_key: str = "",+ api_secret: str = "",+ access_token: str = "",+ access_secret: str = "",+ poll_interval: int = 60,+ bus: Optional[EventBus] = None,+ ) -> None:+ self._bearer_token = bearer_token or os.environ.get(+ "TWITTER_BEARER_TOKEN", "",+ )+ self._api_key = api_key or os.environ.get("TWITTER_API_KEY", "")+ self._api_secret = api_secret or os.environ.get("TWITTER_API_SECRET", "")+ self._access_token = access_token or os.environ.get(+ "TWITTER_ACCESS_TOKEN", "",+ )+ self._access_secret = access_secret or os.environ.get(+ "TWITTER_ACCESS_SECRET", "",+ )+ self._poll_interval = poll_interval+ self._bus = bus+ self._handlers: List[ChannelHandler] = []+ self._status = ChannelStatus.DISCONNECTED+ self._client: Any = None+ self._poll_thread: Optional[threading.Thread] = None+ self._stop_event = threading.Event()++ # -- connection lifecycle ---------------------------------------------------++ def connect(self) -> None:+ """Build a tweepy Client and optionally start polling for mentions."""+ if not self._bearer_token:+ logger.warning("No Twitter bearer token configured")+ self._status = ChannelStatus.ERROR+ return++ self._stop_event.clear()++ try:+ import tweepy # noqa: F401++ self._client = tweepy.Client(+ bearer_token=self._bearer_token,+ consumer_key=self._api_key or None,+ consumer_secret=self._api_secret or None,+ access_token=self._access_token or None,+ access_token_secret=self._access_secret or None,+ )+ self._status = ChannelStatus.CONNECTED+ logger.info("Twitter channel connected")++ if self._access_token:+ self._poll_thread = threading.Thread(+ target=self._poll_loop, daemon=True,+ )+ self._poll_thread.start()+ except ImportError:+ logger.info("tweepy not installed; Twitter channel unavailable")+ self._status = ChannelStatus.ERROR+ except Exception:+ logger.debug("Twitter connect failed", exc_info=True)+ self._status = ChannelStatus.ERROR++ def disconnect(self) -> None:+ """Stop the polling thread and disconnect."""+ self._stop_event.set()+ if self._poll_thread is not None:+ self._poll_thread.join(timeout=5.0)+ self._poll_thread = None+ self._client = None+ self._status = ChannelStatus.DISCONNECTED++ # -- send / receive --------------------------------------------------------++ def send(+ self,+ channel: str,+ content: str,+ *,+ conversation_id: str = "",+ metadata: Dict[str, Any] | None = None,+ ) -> bool:+ """Send a tweet or direct message.++ If *channel* is numeric, sends a DM via ``create_direct_message()``.+ Otherwise sends a tweet via ``create_tweet()``. If *conversation_id*+ is provided, it is used as ``in_reply_to_tweet_id``.+ """+ if self._client is None:+ logger.warning("Cannot send: Twitter client not connected")+ return False++ try:+ if channel.isdigit():+ # Direct message to a user ID+ self._client.create_direct_message(+ participant_id=int(channel),+ text=content,+ )+ else:+ kwargs: Dict[str, Any] = {"text": content}+ if conversation_id:+ kwargs["in_reply_to_tweet_id"] = int(conversation_id)+ self._client.create_tweet(**kwargs)++ self._publish_sent(channel, content, conversation_id)+ return True+ except Exception:+ logger.debug("Twitter send failed", exc_info=True)+ return False++ def status(self) -> ChannelStatus:+ """Return the current connection status."""+ return self._status++ def list_channels(self) -> List[str]:+ """Return available channel identifiers."""+ return ["timeline", "dm"]++ def on_message(self, handler: ChannelHandler) -> None:+ """Register a callback for incoming messages."""+ self._handlers.append(handler)++ # -- internal helpers -------------------------------------------------------++ def _poll_loop(self) -> None:+ """Poll for new mentions in a background thread."""+ since_id: Optional[str] = None++ while not self._stop_event.is_set():+ try:+ kwargs: Dict[str, Any] = {}+ if since_id:+ kwargs["since_id"] = since_id++ me = self._client.get_me()+ if me and me.data:+ user_id = me.data.id+ else:+ self._stop_event.wait(self._poll_interval)+ continue++ response = self._client.get_users_mentions(+ id=user_id, **kwargs,+ )++ if response and response.data:+ for tweet in response.data:+ since_id = str(tweet.id)+ cm = ChannelMessage(+ channel="twitter",+ sender=str(getattr(tweet, "author_id", "")),+ content=tweet.text,+ message_id=str(tweet.id),+ conversation_id=str(+ getattr(tweet, "conversation_id", ""),+ ),+ )+ for handler in self._handlers:+ try:+ handler(cm)+ except Exception:+ logger.exception("Twitter handler error")+ if self._bus is not None:+ self._bus.publish(+ EventType.CHANNEL_MESSAGE_RECEIVED,+ {+ "channel": cm.channel,+ "sender": cm.sender,+ "content": cm.content,+ "message_id": cm.message_id,+ },+ )+ except Exception:+ logger.debug("Twitter poll error", exc_info=True)++ self._stop_event.wait(self._poll_interval)++ def _publish_sent(+ self, channel: str, content: str, conversation_id: str,+ ) -> None:+ """Publish a CHANNEL_MESSAGE_SENT event on the bus."""+ if self._bus is not None:+ self._bus.publish(+ EventType.CHANNEL_MESSAGE_SENT,+ {+ "channel": channel,+ "content": content,+ "conversation_id": conversation_id,+ },+ )+++__all__ = ["TwitterChannel"]diff --git a/tests/channels/conftest.py b/tests/channels/conftest.pynew file mode 100644index 00000000..b1d377ea--- /dev/null+++ b/tests/channels/conftest.py@@ -0,0 +1,65 @@+"""Shared fixtures for channel integration tests."""++from __future__ import annotations++import os+from contextlib import contextmanager++import pytest++from openjarvis.core.events import EventBus++from tests.agents.fake_engine import FakeEngine+from tests.agents.scenario_harness import FakeSystem, ScenarioHarness+++def scenario_harness(tmp_path):+ """Wire up real components for agent lifecycle testing (channels copy)."""+ from openjarvis.agents.executor import AgentExecutor+ from openjarvis.agents.manager import AgentManager+ from openjarvis.agents.monitor_operative import MonitorOperativeAgent+ from openjarvis.agents.scheduler import AgentScheduler+ from openjarvis.core.registry import AgentRegistry++ if not AgentRegistry.contains("monitor_operative"):+ AgentRegistry.register("monitor_operative")(MonitorOperativeAgent)++ db_path = str(tmp_path / "agents.db")+ bus = EventBus(record_history=True)+ manager = AgentManager(db_path=db_path)+ engine = FakeEngine([{"content": "Default response."}])+ system = FakeSystem(engine=engine)+ executor = AgentExecutor(manager=manager, event_bus=bus)+ executor.set_system(system)+ scheduler = AgentScheduler(manager=manager, executor=executor, event_bus=bus)++ return ScenarioHarness(+ manager=manager, executor=executor, scheduler=scheduler,+ bus=bus, engine=engine, system=system, db_path=db_path,+ )+++def fake_event_bus() -> EventBus:+ """EventBus with history recording for asserting event emissions."""+ return EventBus(record_history=True)+++@contextmanager+def credential_env(channel_name: str, **creds: str):+ """Context manager that sets env vars for a channel, cleans up after."""+ prefix = channel_name.upper()+ old_values = {}+ for key, value in creds.items():+ env_key = f"{prefix}_{key.upper()}"+ old_values[env_key] = os.environ.get(env_key)+ os.environ[env_key] = value+ try:+ yield+ finally:+ for env_key, old in old_values.items():+ if old is None:+ os.environ.pop(env_key, None)+ else:+ os.environ[env_key] = olddiff --git a/tests/channels/test_agent_channel_e2e.py b/tests/channels/test_agent_channel_e2e.pynew file mode 100644index 00000000..1eaefa97--- /dev/null+++ b/tests/channels/test_agent_channel_e2e.py@@ -0,0 +1,64 @@+"""Agent-channel E2E tests — using WebChatChannel (in-memory, no external deps)."""++from __future__ import annotations++from tests.agents.scenario_harness import ScenarioHarness+++def test_agent_sends_to_webchat(scenario_harness: ScenarioHarness):+ """Agent runs and completes tick with WebChatChannel available."""+ from openjarvis.channels.webchat import WebChatChannel++ h = scenario_harness+ webchat = WebChatChannel()+ webchat.connect()++ agent = h.manager.create_agent("Channel Agent", config={+ "schedule_type": "manual",+ "instruction": "Send a report to the general channel.",+ })++ h.executor.execute_tick(agent["id"])+ data = h.manager.get_agent(agent["id"])+ assert data["status"] == "idle"+ assert data["total_runs"] == 1+ webchat.disconnect()+++def test_channel_failure_does_not_crash_agent(scenario_harness: ScenarioHarness):+ """Agent continues if channel send fails."""+ h = scenario_harness+ agent = h.manager.create_agent("Resilient Agent", config={+ "schedule_type": "manual",+ "instruction": "Try to send a message.",+ })++ h.executor.execute_tick(agent["id"])+ data = h.manager.get_agent(agent["id"])+ assert data["status"] == "idle"+ assert data["total_runs"] == 1+++def test_agent_with_channel_binding(scenario_harness: ScenarioHarness):+ """Agent with a channel binding completes tick without error."""+ from openjarvis.channels.webchat import WebChatChannel++ h = scenario_harness+ webchat = WebChatChannel()+ webchat.connect()++ agent = h.manager.create_agent("Bound Agent", config={+ "schedule_type": "manual",+ "instruction": "Monitor and report.",+ })+ aid = agent["id"]++ # Bind a channel+ h.manager.bind_channel(aid, "webchat", config={"channel": "general"})+ bindings = h.manager.list_channel_bindings(aid)+ assert len(bindings) == 1++ h.executor.execute_tick(aid)+ data = h.manager.get_agent(aid)+ assert data["status"] == "idle"+ webchat.disconnect()diff --git a/tests/channels/test_channel_contract.py b/tests/channels/test_channel_contract.pynew file mode 100644index 00000000..44f04252--- /dev/null+++ b/tests/channels/test_channel_contract.py@@ -0,0 +1,85 @@+"""Parametrized contract tests — verify every channel implements BaseChannel correctly.++These tests run without any credentials and verify that all channel adapters+handle graceful degradation (no crashes on missing auth, idempotent disconnect,+valid enum returns).+"""++from __future__ import annotations++import importlib++import pytest++import openjarvis.channels # noqa: F401 — trigger registration+from openjarvis.channels._stubs import ChannelStatus+from openjarvis.core.registry import ChannelRegistry++# Collect channel classes at import time (before registry gets cleared).+# We store the actual class objects, not registry keys, so they survive+# the autouse _clean_registries fixture.+importlib.reload(openjarvis.channels)+_ALL_CHANNELS = [+ (key, ChannelRegistry.get(key)) for key in ChannelRegistry.keys()+]++[email protected](params=_ALL_CHANNELS, ids=lambda x: x[0])+def channel_entry(request):+ """Parametrized fixture yielding (channel_key, channel_cls) tuples.++ Uses the class reference captured at import time — does not depend+ on the registry being populated at test time.+ """+ return request.param+++def test_has_channel_id(channel_entry):+ key, channel_cls = channel_entry+ assert hasattr(channel_cls, "channel_id")+ assert isinstance(channel_cls.channel_id, str)+ assert len(channel_cls.channel_id) > 0+++def test_connect_no_credentials_no_crash(channel_entry):+ key, channel_cls = channel_entry+ ch = channel_cls()+ ch.connect()+ # Should not raise — just set status to ERROR or DISCONNECTED+++def test_disconnect_idempotent(channel_entry):+ key, channel_cls = channel_entry+ ch = channel_cls()+ ch.disconnect()+ ch.disconnect() # Second call should not raise+++def test_status_returns_valid_enum(channel_entry):+ key, channel_cls = channel_entry+ ch = channel_cls()+ s = ch.status()+ assert isinstance(s, ChannelStatus)+++def test_list_channels_returns_list(channel_entry):+ key, channel_cls = channel_entry+ ch = channel_cls()+ result = ch.list_channels()+ assert isinstance(result, list)+++def test_send_no_credentials_returns_false(channel_entry):+ key, channel_cls = channel_entry+ if key == "webchat":+ pytest.skip("WebChatChannel is in-memory and always succeeds")+ ch = channel_cls()+ result = ch.send("test", "hello")+ assert result is False+++def test_on_message_accepts_handler(channel_entry):+ key, channel_cls = channel_entry+ ch = channel_cls()+ ch.on_message(lambda msg: None)+ # Should not raisediff --git a/tests/channels/test_tier1_gmail.py b/tests/channels/test_tier1_gmail.pynew file mode 100644index 00000000..75292689--- /dev/null+++ b/tests/channels/test_tier1_gmail.py@@ -0,0 +1,209 @@+"""Tests for the GmailChannel adapter."""++from __future__ import annotations++import base64+import os+from unittest.mock import MagicMock, patch++import pytest++from openjarvis.channels._stubs import ChannelStatus+from openjarvis.channels.gmail import GmailChannel+from openjarvis.core.events import EventBus, EventType+from openjarvis.core.registry import ChannelRegistry++[email protected](autouse=True)+def _register_gmail():+ """Re-register after any registry clear."""+ if not ChannelRegistry.contains("gmail"):+ ChannelRegistry.register_value("gmail", GmailChannel)+++class TestRegistration:+ def test_gmail_channel_registered(self):+ assert ChannelRegistry.contains("gmail")++ def test_channel_id(self):+ ch = GmailChannel()+ assert ch.channel_id == "gmail"+++class TestNoCredentials:+ def test_gmail_no_credentials_status(self):+ ch = GmailChannel()+ ch.connect()+ assert ch.status() in (ChannelStatus.ERROR, ChannelStatus.DISCONNECTED)++ def test_gmail_send_no_credentials_returns_false(self):+ ch = GmailChannel()+ result = ch.send("[email protected]", "Hello!")+ assert result is False+++class TestSend:+ def test_gmail_send_constructs_mime(self):+ ch = GmailChannel()+ mock_service = MagicMock()+ ch._service = mock_service+ ch._status = ChannelStatus.CONNECTED++ result = ch.send("[email protected]", "Hello Gmail!")+ assert result is True++ # Verify send was called+ mock_service.users().messages().send.assert_called_once()+ call_kwargs = mock_service.users().messages().send.call_args[1]+ assert call_kwargs["userId"] == "me"++ # Verify the body contains base64-encoded MIME message+ body = call_kwargs["body"]+ assert "raw" in body+ decoded = base64.urlsafe_b64decode(body["raw"]).decode("utf-8")+ assert "[email protected]" in decoded+ assert "Hello Gmail!" in decoded++ def test_gmail_send_with_thread_id(self):+ ch = GmailChannel()+ mock_service = MagicMock()+ ch._service = mock_service+ ch._status = ChannelStatus.CONNECTED++ result = ch.send(+ "[email protected]",+ "Thread reply",+ conversation_id="thread-abc123",+ )+ assert result is True++ call_kwargs = mock_service.users().messages().send.call_args[1]+ body = call_kwargs["body"]+ assert body["threadId"] == "thread-abc123"++ def test_gmail_send_with_subject_metadata(self):+ ch = GmailChannel()+ mock_service = MagicMock()+ ch._service = mock_service+ ch._status = ChannelStatus.CONNECTED++ result = ch.send(+ "[email protected]",+ "Body text",+ metadata={"subject": "Custom Subject"},+ )+ assert result is True++ call_kwargs = mock_service.users().messages().send.call_args[1]+ decoded = base64.urlsafe_b64decode(+ call_kwargs["body"]["raw"],+ ).decode("utf-8")+ assert "Custom Subject" in decoded++ def test_gmail_send_exception_returns_false(self):+ ch = GmailChannel()+ mock_service = MagicMock()+ mock_service.users().messages().send().execute.side_effect = (+ RuntimeError("API error")+ )+ ch._service = mock_service+ ch._status = ChannelStatus.CONNECTED++ result = ch.send("[email protected]", "Hello!")+ assert result is False+++class TestListChannels:+ def test_gmail_list_channels(self):+ ch = GmailChannel()+ assert ch.list_channels() == ["inbox"]+++class TestOnMessage:+ def test_gmail_on_message_registers_handler(self):+ ch = GmailChannel()+ handler = MagicMock()+ ch.on_message(handler)+ assert handler in ch._handlers+++class TestEventBus:+ def test_gmail_event_bus_integration(self):+ bus = EventBus(record_history=True)+ ch = GmailChannel(bus=bus)+ mock_service = MagicMock()+ ch._service = mock_service+ ch._status = ChannelStatus.CONNECTED++ ch.send("[email protected]", "Hello!")++ event_types = [e.event_type for e in bus.history]+ assert EventType.CHANNEL_MESSAGE_SENT in event_types+++class TestStatus:+ def test_disconnected_initially(self):+ ch = GmailChannel()+ assert ch.status() == ChannelStatus.DISCONNECTED++ def test_status_error_when_connected_but_no_service(self):+ ch = GmailChannel()+ ch._status = ChannelStatus.CONNECTED+ ch._service = None+ assert ch.status() == ChannelStatus.ERROR+++class TestDisconnect:+ def test_disconnect(self):+ ch = GmailChannel()+ ch._service = MagicMock()+ ch._status = ChannelStatus.CONNECTED+ ch.disconnect()+ assert ch.status() == ChannelStatus.DISCONNECTED+ assert ch._service is None+++class TestEnvVarFallback:+ def test_credentials_path_env_var(self):+ with patch.dict(os.environ, {"GMAIL_CREDENTIALS_PATH": "/tmp/creds.json"}):+ ch = GmailChannel()+ assert ch._credentials_path == "/tmp/creds.json"++ def test_token_path_env_var(self):+ with patch.dict(os.environ, {"GMAIL_TOKEN_PATH": "/tmp/token.json"}):+ ch = GmailChannel()+ assert ch._token_path == "/tmp/token.json"++ def test_constructor_overrides_env(self):+ with patch.dict(os.environ, {"GMAIL_CREDENTIALS_PATH": "/env/creds.json"}):+ ch = GmailChannel(credentials_path="/explicit/creds.json")+ assert ch._credentials_path == "/explicit/creds.json"++[email protected]_channel+class TestLive:+ def test_gmail_send_live(self):+ creds_path = os.environ.get("GMAIL_CREDENTIALS_PATH", "")+ token_path = os.environ.get("GMAIL_TOKEN_PATH", "")+ recipient = os.environ.get("GMAIL_TEST_RECIPIENT", "")++ if not creds_path and not token_path:+ pytest.skip("No Gmail credentials configured")+ if not recipient:+ pytest.skip("No GMAIL_TEST_RECIPIENT configured")++ ch = GmailChannel(+ credentials_path=creds_path,+ token_path=token_path,+ )+ ch.connect()+ if ch.status() != ChannelStatus.CONNECTED:+ pytest.skip("Gmail channel failed to connect")++ result = ch.send(+ recipient,+ "OpenJarvis Gmail channel test message",+ metadata={"subject": "OpenJarvis Test"},+ )+ assert result is True+ ch.disconnect()diff --git a/tests/channels/test_tier2_twitter.py b/tests/channels/test_tier2_twitter.pynew file mode 100644index 00000000..fcc15924--- /dev/null+++ b/tests/channels/test_tier2_twitter.py@@ -0,0 +1,136 @@+"""Tests for the TwitterChannel adapter."""++from __future__ import annotations++import os+from unittest.mock import MagicMock++import pytest++from openjarvis.channels._stubs import ChannelStatus+from openjarvis.channels.twitter import TwitterChannel+from openjarvis.core.events import EventBus, EventType+from openjarvis.core.registry import ChannelRegistry++[email protected](autouse=True)+def _register_twitter():+ """Re-register after any registry clear."""+ if not ChannelRegistry.contains("twitter"):+ ChannelRegistry.register_value("twitter", TwitterChannel)+++def test_twitter_channel_registered():+ """Twitter channel should be discoverable via the registry."""+ assert ChannelRegistry.contains("twitter")+ cls = ChannelRegistry.get("twitter")+ assert cls is TwitterChannel+++def test_twitter_no_credentials_status():+ """Without credentials, connect() sets status to ERROR."""+ ch = TwitterChannel()+ ch.connect()+ assert ch.status() == ChannelStatus.ERROR+++def test_twitter_send_no_credentials_returns_false():+ """send() returns False when client is not connected."""+ ch = TwitterChannel()+ result = ch.send("timeline", "Hello Twitter!")+ assert result is False+++def test_twitter_send_tweet():+ """send() with a non-numeric channel calls create_tweet."""+ ch = TwitterChannel(bearer_token="test-bearer")+ mock_client = MagicMock()+ ch._client = mock_client+ ch._status = ChannelStatus.CONNECTED++ result = ch.send("timeline", "Hello from Jarvis!")+ assert result is True+ mock_client.create_tweet.assert_called_once_with(text="Hello from Jarvis!")+++def test_twitter_send_dm_when_channel_is_numeric():+ """send() with a numeric channel calls create_direct_message."""+ ch = TwitterChannel(bearer_token="test-bearer")+ mock_client = MagicMock()+ ch._client = mock_client+ ch._status = ChannelStatus.CONNECTED++ result = ch.send("12345678", "Hello via DM!")+ assert result is True+ mock_client.create_direct_message.assert_called_once_with(+ participant_id=12345678,+ text="Hello via DM!",+ )+++def test_twitter_send_reply():+ """send() with conversation_id sets in_reply_to_tweet_id."""+ ch = TwitterChannel(bearer_token="test-bearer")+ mock_client = MagicMock()+ ch._client = mock_client+ ch._status = ChannelStatus.CONNECTED++ result = ch.send(+ "timeline", "This is a reply", conversation_id="999888777",+ )+ assert result is True+ mock_client.create_tweet.assert_called_once_with(+ text="This is a reply",+ in_reply_to_tweet_id=999888777,+ )+++def test_twitter_list_channels():+ """list_channels() returns the expected identifiers."""+ ch = TwitterChannel()+ assert ch.list_channels() == ["timeline", "dm"]+++def test_twitter_event_bus_integration():+ """Successful send publishes CHANNEL_MESSAGE_SENT on the event bus."""+ bus = EventBus(record_history=True)+ ch = TwitterChannel(bearer_token="test-bearer", bus=bus)+ mock_client = MagicMock()+ ch._client = mock_client+ ch._status = ChannelStatus.CONNECTED++ ch.send("timeline", "Event test!")++ event_types = [e.event_type for e in bus.history]+ assert EventType.CHANNEL_MESSAGE_SENT in event_types++ sent_event = next(+ e for e in bus.history+ if e.event_type == EventType.CHANNEL_MESSAGE_SENT+ )+ assert sent_event.data["content"] == "Event test!"+ assert sent_event.data["channel"] == "timeline"++[email protected]_channel+def test_twitter_connect_live():+ """Live test: connect with real credentials from env vars.++ Skipped unless all required env vars are set.+ """+ required_vars = [+ "TWITTER_BEARER_TOKEN",+ "TWITTER_API_KEY",+ "TWITTER_API_SECRET",+ "TWITTER_ACCESS_TOKEN",+ "TWITTER_ACCESS_SECRET",+ ]+ for var in required_vars:+ if not os.environ.get(var):+ pytest.skip(f"Missing env var {var}")++ ch = TwitterChannel()+ ch.connect()+ assert ch.status() == ChannelStatus.CONNECTED+ ch.disconnect()+ assert ch.status() == ChannelStatus.DISCONNECTEDdiff --git a/tests/core/test_config.py b/tests/core/test_config.pyindex 7034cb46..e8e8090f 100644--- a/tests/core/test_config.py+++ b/tests/core/test_config.py@@ -455,7 +455,8 @@ class TestApplyTomlSectionListNormalization:from openjarvis.core.config import ToolsConfig, _apply_toml_sectiontarget = ToolsConfig()- _apply_toml_section(target, {"enabled": ["code_interpreter", "web_search", "file_read"]})+ tools = ["code_interpreter", "web_search", "file_read"]+ _apply_toml_section(target, {"enabled": tools})assert isinstance(target.enabled, str)assert target.enabled == "code_interpreter,web_search,file_read"