Jonathan Haas commited on
Commit ·
fb22b7f
1
Parent(s): 2ed7c3f
Harden HA conversation policy/taxonomy and persist timers
Browse filesFiles changed (12)
- .env.example+2
- README.md+2-1
- TODO.md+6-6
- docs/operations/error-taxonomy.md+12-12
- docs/operations/home-control-policy.md+4-1
- docs/operations/integration-policy.md+1-1
- src/jarvis/config.py+29
- src/jarvis/memory.py+127
- src/jarvis/tools/services.py+78-4
- tests/test_config.py+10
- tests/test_memory.py+45
- tests/test_tools_services.py+126-4
15 unmodified lines16171819202115 unmodified linesHOME_REQUIRE_CONFIRM_EXECUTE=false# Optional: enable Home Assistant conversation intent toolHOME_CONVERSATION_ENABLED=false# Todoist integration (optional)TODOIST_API_TOKEN=15 unmodified lines161718192021222315 unmodified linesHOME_REQUIRE_CONFIRM_EXECUTE=false# Optional: enable Home Assistant conversation intent toolHOME_CONVERSATION_ENABLED=false# Home Assistant conversation permission profile: readonly or controlHOME_CONVERSATION_PERMISSION_PROFILE=readonly# Todoist integration (optional)TODOIST_API_TOKEN=
82 unmodified lines8384858687887 unmodified lines9697989910010110282 unmodified lines# Optional: HOME_PERMISSION_PROFILE=readonly (state only) or control (default)# Optional: HOME_REQUIRE_CONFIRM_EXECUTE=true (require confirm=true on all executes)# Optional: HOME_CONVERSATION_ENABLED=true (enable HA conversation intent tool)# Optional: TODOIST_API_TOKEN / TODOIST_PROJECT_ID / TODOIST_PERMISSION_PROFILE# Optional: TODOIST_TIMEOUT_SEC=10.0 / PUSHOVER_TIMEOUT_SEC=10.0# Optional: PUSHOVER_API_TOKEN / PUSHOVER_USER_KEY / NOTIFICATION_PERMISSION_PROFILE7 unmodified lines- Integration runbook: [`docs/operations/integration-policy.md`](docs/operations/integration-policy.md).- Home Assistant conversation tool requires both:- `HOME_CONVERSATION_ENABLED=true`- `HOME_PERMISSION_PROFILE=control`- and tool argument `confirm=true`- Release checklist: [`docs/operations/release-checklist.md`](docs/operations/release-checklist.md).- Security maintenance: [`docs/operations/security-maintenance.md`](docs/operations/security-maintenance.md).82 unmodified lines838485868788897 unmodified lines97989910010110210382 unmodified lines# Optional: HOME_PERMISSION_PROFILE=readonly (state only) or control (default)# Optional: HOME_REQUIRE_CONFIRM_EXECUTE=true (require confirm=true on all executes)# Optional: HOME_CONVERSATION_ENABLED=true (enable HA conversation intent tool)# Optional: HOME_CONVERSATION_PERMISSION_PROFILE=readonly|control (default readonly)# Optional: TODOIST_API_TOKEN / TODOIST_PROJECT_ID / TODOIST_PERMISSION_PROFILE# Optional: TODOIST_TIMEOUT_SEC=10.0 / PUSHOVER_TIMEOUT_SEC=10.0# Optional: PUSHOVER_API_TOKEN / PUSHOVER_USER_KEY / NOTIFICATION_PERMISSION_PROFILE7 unmodified lines- Integration runbook: [`docs/operations/integration-policy.md`](docs/operations/integration-policy.md).- Home Assistant conversation tool requires both:- `HOME_CONVERSATION_ENABLED=true`- `HOME_CONVERSATION_PERMISSION_PROFILE=control`- and tool argument `confirm=true`- Release checklist: [`docs/operations/release-checklist.md`](docs/operations/release-checklist.md).- Security maintenance: [`docs/operations/security-maintenance.md`](docs/operations/security-maintenance.md).
39 unmodified lines40414243444546478 unmodified lines5657585960616293 unmodified lines15615715815916016116239 unmodified lines- [ ] `HA05` Add Home Assistant timer integration tool path.- [ ] `HA06` Add entity capability discovery helper for safer action planning.- [ ] `HA07` Add optional area-aware commands (room/area targeting helper).- [ ] `HA08` Add HA conversation error taxonomy mapping and tests.- [ ] `HA09` Add policy profile controls for HA intent tool (`readonly|control`).- [ ] `HA10` Add HA intent runbook section with safe rollout checklist.---8 unmodified lines- [ ] `PR06` Add optional reminder notifications via Pushover.- [ ] `PR07` Add calendar read integration (Google/ICS or HA calendar bridge).- [ ] `PR08` Add “next event” conversational helper tool.- [ ] `PR09` Add persistence layer for timers/reminders across restarts.- [ ] `PR10` Add productivity tool regression tests and edge-case parsing tests.---93 unmodified lines- [x] `E01` Implement `HA01` + `HA02` + `HA03` (Home Assistant conversation API tool + schema + mapping + tests).- [x] `E02` Implement `PR01` + `PR02` + `PR03` (timer create/list/cancel tools + tests + status exposure).- [ ] `E03` Implement `HA08` + `HA09` (policy and taxonomy mapping for HA intent tool).- [ ] `E04` Implement `PR09` (persist timer/reminder data in `MemoryStore`).- [ ] `E05` Implement `UX06` (structured status endpoint behavior contract).- [ ] `E06` Update README/runbooks for new tools and safe operating guidance.39 unmodified lines40414243444546478 unmodified lines5657585960616293 unmodified lines15615715815916016116239 unmodified lines- [ ] `HA05` Add Home Assistant timer integration tool path.- [ ] `HA06` Add entity capability discovery helper for safer action planning.- [ ] `HA07` Add optional area-aware commands (room/area targeting helper).- [x] `HA08` Add HA conversation error taxonomy mapping and tests.- [x] `HA09` Add policy profile controls for HA intent tool (`readonly|control`).- [ ] `HA10` Add HA intent runbook section with safe rollout checklist.---8 unmodified lines- [ ] `PR06` Add optional reminder notifications via Pushover.- [ ] `PR07` Add calendar read integration (Google/ICS or HA calendar bridge).- [ ] `PR08` Add “next event” conversational helper tool.- [x] `PR09` Add persistence layer for timers/reminders across restarts.- [ ] `PR10` Add productivity tool regression tests and edge-case parsing tests.---93 unmodified lines- [x] `E01` Implement `HA01` + `HA02` + `HA03` (Home Assistant conversation API tool + schema + mapping + tests).- [x] `E02` Implement `PR01` + `PR02` + `PR03` (timer create/list/cancel tools + tests + status exposure).- [x] `E03` Implement `HA08` + `HA09` (policy and taxonomy mapping for HA intent tool).- [x] `E04` Implement `PR09` (persist timer/reminder data in `MemoryStore`).- [ ] `E05` Implement `UX06` (structured status endpoint behavior contract).- [x] `E06` Update README/runbooks for new tools and safe operating guidance.
6 unmodified lines7891011121314151617181920212223242526272829303132336 unmodified lines| Error code | Owning tool families ||---|---|| `api_error` | `pushover_notify` || `auth` | `smart_home`, `smart_home_state`, `todoist_*`, `pushover_notify` || `cancelled` | `smart_home*`, `todoist_*`, `pushover_notify` || `http_error` | `smart_home*`, `todoist_*`, `pushover_notify` || `invalid_data` | `smart_home`, `task_plan_*`, `memory_*` || `invalid_json` | `smart_home*`, `todoist_*`, `pushover_notify` || `invalid_plan` | `task_plan_*` || `invalid_status` | `task_plan_update` || `invalid_steps` | `task_plan_create` || `missing_config` | `smart_home*`, `todoist_*`, `pushover_notify` || `missing_entity` | `smart_home_state` || `missing_fields` | `smart_home`, `todoist_add_task`, `pushover_notify` || `missing_plan` | `task_plan_*` || `missing_query` | `memory_search` || `missing_store` | `memory_*`, `task_plan_*` || `missing_text` | `memory_add` || `network_client_error` | `smart_home*`, `todoist_*`, `pushover_notify` || `not_found` | `smart_home*`, `task_plan_*` || `policy` | cross-cutting tool policy enforcement || `storage_error` | `memory_*`, `task_plan_*` || `summary_unavailable` | `tool_summary*`, `system_status` || `timeout` | `smart_home*`, `todoist_*`, `pushover_notify` || `unexpected` | cross-cutting runtime guard || `unknown_error` | fallback normalization bucket |6 unmodified lines7891011121314151617181920212223242526272829303132336 unmodified lines| Error code | Owning tool families ||---|---|| `api_error` | `pushover_notify` || `auth` | `smart_home`, `smart_home_state`, `home_assistant_conversation`, `todoist_*`, `pushover_notify` || `cancelled` | `smart_home*`, `home_assistant_conversation`, `todoist_*`, `pushover_notify` || `http_error` | `smart_home*`, `home_assistant_conversation`, `todoist_*`, `pushover_notify` || `invalid_data` | `smart_home`, `home_assistant_conversation`, `timer_*`, `task_plan_*`, `memory_*` || `invalid_json` | `smart_home*`, `home_assistant_conversation`, `todoist_*`, `pushover_notify` || `invalid_plan` | `task_plan_*` || `invalid_status` | `task_plan_update` || `invalid_steps` | `task_plan_create` || `missing_config` | `smart_home*`, `home_assistant_conversation`, `todoist_*`, `pushover_notify` || `missing_entity` | `smart_home_state` || `missing_fields` | `smart_home`, `home_assistant_conversation`, `timer_cancel`, `todoist_add_task`, `pushover_notify` || `missing_plan` | `task_plan_*` || `missing_query` | `memory_search` || `missing_store` | `memory_*`, `task_plan_*` || `missing_text` | `memory_add` || `network_client_error` | `smart_home*`, `home_assistant_conversation`, `todoist_*`, `pushover_notify` || `not_found` | `smart_home*`, `home_assistant_conversation`, `timer_cancel`, `task_plan_*` || `policy` | cross-cutting tool policy enforcement (`smart_home*`, `home_assistant_conversation`, allow/deny lists) || `storage_error` | `memory_*`, `task_plan_*`, `timer_*` || `summary_unavailable` | `tool_summary*`, `system_status` || `timeout` | `smart_home*`, `home_assistant_conversation`, `todoist_*`, `pushover_notify` || `unexpected` | cross-cutting runtime guard || `unknown_error` | fallback normalization bucket |
28 unmodified lines293031323334356 unmodified lines42434445464729 unmodified lines77787928 unmodified linesFor `home_assistant_conversation` requests:- Requires `HOME_CONVERSATION_ENABLED=true`.- Requires `HOME_PERMISSION_PROFILE=control`.- Requires tool argument `confirm=true` on every request.## 4) Transport/Service Validation6 unmodified lines- `system_status` includes:- tool allow/deny counts- active `home_permission_profile`### Redaction examplesInput payload:29 unmodified lines3. Ensure sensitive executes pass `confirm=true`.4. Verify `HASS_URL` and `HASS_TOKEN` are both set.5. If an execute is blocked, check whether an action cooldown is currently active.28 unmodified lines293031323334356 unmodified lines424344454647484929 unmodified lines7980818228 unmodified linesFor `home_assistant_conversation` requests:- Requires `HOME_CONVERSATION_ENABLED=true`.- Requires `HOME_CONVERSATION_PERMISSION_PROFILE=control`.- Requires tool argument `confirm=true` on every request.## 4) Transport/Service Validation6 unmodified lines- `system_status` includes:- tool allow/deny counts- active `home_permission_profile`- active `home_conversation_enabled`- active `home_conversation_permission_profile`### Redaction examplesInput payload:29 unmodified lines3. Ensure sensitive executes pass `confirm=true`.4. Verify `HASS_URL` and `HASS_TOKEN` are both set.5. If an execute is blocked, check whether an action cooldown is currently active.6. For `home_assistant_conversation`, verify `HOME_CONVERSATION_ENABLED=true`, `HOME_CONVERSATION_PERMISSION_PROFILE=control`, and `confirm=true`.
108 unmodified lines109110111112108 unmodified lines- `timer_create` accepts numeric seconds or compact durations (`90s`, `5m`, `1h 15m`).- `timer_list` reports current active timers and remaining time.- `timer_cancel` removes a timer by `timer_id` or exact `label`.- Timers are currently runtime-memory only and reset on process restart.108 unmodified lines109110111112108 unmodified lines- `timer_create` accepts numeric seconds or compact durations (`90s`, `5m`, `1h 15m`).- `timer_list` reports current active timers and remaining time.- `timer_cancel` removes a timer by `timer_id` or exact `label`.- Timers are persisted in the memory store when memory is enabled and are restored on restart.
124 unmodified lines12512612712812913046 unmodified lines1771781791801811828 unmodified lines19119219319419519624 unmodified lines22122222322422522621 unmodified lines248249250251252253124 unmodified lineshome_permission_profile: str = field(default_factory=lambda: os.environ.get("HOME_PERMISSION_PROFILE", "control"))home_require_confirm_execute: bool = field(default_factory=lambda: _env_bool("HOME_REQUIRE_CONFIRM_EXECUTE") or False)home_conversation_enabled: bool = field(default_factory=lambda: _env_bool("HOME_CONVERSATION_ENABLED") or False)todoist_api_token: str = field(default_factory=lambda: os.environ.get("TODOIST_API_TOKEN", ""))todoist_project_id: str = field(default_factory=lambda: os.environ.get("TODOIST_PROJECT_ID", ""))todoist_permission_profile: str = field(default_factory=lambda: os.environ.get("TODOIST_PERMISSION_PROFILE", "control"))46 unmodified linesself.backchannel_style = self._normalize_backchannel_style(self.backchannel_style)self.persona_style = self._normalize_persona_style(self.persona_style)self.home_permission_profile = self._normalize_home_permission_profile(self.home_permission_profile)self.todoist_permission_profile = self._normalize_todoist_permission_profile(self.todoist_permission_profile)self.notification_permission_profile = self._normalize_notification_permission_profile(self.notification_permission_profile)if _env_is_set("BACKCHANNEL_STYLE") and self.backchannel_style == "balanced":8 unmodified linesraw = os.environ.get("HOME_PERMISSION_PROFILE", "")if raw.strip().lower() not in {"readonly", "control"}:self.startup_warnings.append("HOME_PERMISSION_PROFILE invalid; using control.")if _env_is_set("TODOIST_PERMISSION_PROFILE") and self.todoist_permission_profile == "control":raw = os.environ.get("TODOIST_PERMISSION_PROFILE", "")if raw.strip().lower() not in {"readonly", "control"}:24 unmodified linesreturn normalizedreturn "control"@staticmethoddef _normalize_todoist_permission_profile(profile: str) -> str:normalized = (profile or "control").strip().lower()21 unmodified linesand not has_hass_token):warnings.append("HOME_PERMISSION_PROFILE=control set while HASS_URL/HASS_TOKEN are empty.")has_todoist_token = bool((self.todoist_api_token or "").strip())has_todoist_project = bool((self.todoist_project_id or "").strip())if has_todoist_project and not has_todoist_token:124 unmodified lines12512612712812913013113213346 unmodified lines1801811821831841851861871888 unmodified lines19719819920020120220320420520620720820924 unmodified lines23423523623723823924024124224324424524621 unmodified lines268269270271272273274275276277278279280281282124 unmodified lineshome_permission_profile: str = field(default_factory=lambda: os.environ.get("HOME_PERMISSION_PROFILE", "control"))home_require_confirm_execute: bool = field(default_factory=lambda: _env_bool("HOME_REQUIRE_CONFIRM_EXECUTE") or False)home_conversation_enabled: bool = field(default_factory=lambda: _env_bool("HOME_CONVERSATION_ENABLED") or False)home_conversation_permission_profile: str = field(default_factory=lambda: os.environ.get("HOME_CONVERSATION_PERMISSION_PROFILE", "readonly"))todoist_api_token: str = field(default_factory=lambda: os.environ.get("TODOIST_API_TOKEN", ""))todoist_project_id: str = field(default_factory=lambda: os.environ.get("TODOIST_PROJECT_ID", ""))todoist_permission_profile: str = field(default_factory=lambda: os.environ.get("TODOIST_PERMISSION_PROFILE", "control"))46 unmodified linesself.backchannel_style = self._normalize_backchannel_style(self.backchannel_style)self.persona_style = self._normalize_persona_style(self.persona_style)self.home_permission_profile = self._normalize_home_permission_profile(self.home_permission_profile)self.home_conversation_permission_profile = self._normalize_home_conversation_permission_profile(self.home_conversation_permission_profile)self.todoist_permission_profile = self._normalize_todoist_permission_profile(self.todoist_permission_profile)self.notification_permission_profile = self._normalize_notification_permission_profile(self.notification_permission_profile)if _env_is_set("BACKCHANNEL_STYLE") and self.backchannel_style == "balanced":8 unmodified linesraw = os.environ.get("HOME_PERMISSION_PROFILE", "")if raw.strip().lower() not in {"readonly", "control"}:self.startup_warnings.append("HOME_PERMISSION_PROFILE invalid; using control.")if (_env_is_set("HOME_CONVERSATION_PERMISSION_PROFILE")and self.home_conversation_permission_profile == "readonly"):raw = os.environ.get("HOME_CONVERSATION_PERMISSION_PROFILE", "")if raw.strip().lower() not in {"readonly", "control"}:self.startup_warnings.append("HOME_CONVERSATION_PERMISSION_PROFILE invalid; using readonly.")if _env_is_set("TODOIST_PERMISSION_PROFILE") and self.todoist_permission_profile == "control":raw = os.environ.get("TODOIST_PERMISSION_PROFILE", "")if raw.strip().lower() not in {"readonly", "control"}:24 unmodified linesreturn normalizedreturn "control"@staticmethoddef _normalize_home_conversation_permission_profile(profile: str) -> str:normalized = (profile or "readonly").strip().lower()if normalized in {"readonly", "control"}:return normalizedreturn "readonly"@staticmethoddef _normalize_todoist_permission_profile(profile: str) -> str:normalized = (profile or "control").strip().lower()21 unmodified linesand not has_hass_token):warnings.append("HOME_PERMISSION_PROFILE=control set while HASS_URL/HASS_TOKEN are empty.")if (_env_is_set("HOME_CONVERSATION_PERMISSION_PROFILE")and self.home_conversation_permission_profile == "control"and not has_hass_urland not has_hass_token):warnings.append("HOME_CONVERSATION_PERMISSION_PROFILE=control set while HASS_URL/HASS_TOKEN are empty.")has_todoist_token = bool((self.todoist_api_token or "").strip())has_todoist_project = bool((self.todoist_project_id or "").strip())if has_todoist_project and not has_todoist_token:
48 unmodified lines49505152535479 unmodified lines134135136137138139314 unmodified lines45445545645745845910 unmodified lines47047147247347447535 unmodified lines51151251351451551648 unmodified linesupdated_at: floatclass MemoryStore:def __init__(self, path: str) -> None:if path not in {":memory:", ""}:79 unmodified lines""")cur.execute("CREATE INDEX IF NOT EXISTS idx_memory_summaries_updated ON memory_summaries(updated_at DESC);")try:cur.execute("""314 unmodified linesupdated_at=float(row["updated_at"]),)def close(self) -> None:if self._closed:return10 unmodified lines"fts": self._fts_enabled,"vector": self._memory_enabled,"sources": source_counts,"last_warm": self._last_warm,"last_sync": self._last_sync,"last_optimize": self._last_optimize,35 unmodified linessource=str(row["source"]),)@staticmethoddef _normalize_limit(value: Any, *, default: int = 5) -> int:parsed = default48 unmodified lines495051525354555657585960616263646579 unmodified lines145146147148149150151152153154155156157158159160161162163164314 unmodified lines47948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257310 unmodified lines58458558658758858959035 unmodified lines62662762862963063163263363463563663763863964064164264348 unmodified linesupdated_at: float@dataclassclass TimerEntry:id: intcreated_at: floatdue_at: floatduration_sec: floatlabel: strstatus: strcancelled_at: float | Noneclass MemoryStore:def __init__(self, path: str) -> None:if path not in {":memory:", ""}:79 unmodified lines""")cur.execute("CREATE INDEX IF NOT EXISTS idx_memory_summaries_updated ON memory_summaries(updated_at DESC);")cur.execute("""CREATE TABLE IF NOT EXISTS timers (id INTEGER PRIMARY KEY AUTOINCREMENT,created_at REAL NOT NULL,due_at REAL NOT NULL,duration_sec REAL NOT NULL,label TEXT NOT NULL DEFAULT '',status TEXT NOT NULL DEFAULT 'active',cancelled_at REAL);""")cur.execute("CREATE INDEX IF NOT EXISTS idx_timers_status_due ON timers(status, due_at ASC);")try:cur.execute("""314 unmodified linesupdated_at=float(row["updated_at"]),)def add_timer(self,*,due_at: float,duration_sec: float,label: str = "",created_at: float | None = None,) -> int:if not math.isfinite(due_at):raise ValueError("due_at must be finite")if not math.isfinite(duration_sec) or duration_sec <= 0.0:raise ValueError("duration_sec must be > 0")created = time.time() if created_at is None else float(created_at)clean_label = label.strip()cur = self._conn.cursor()cur.execute("""INSERT INTO timers(created_at, due_at, duration_sec, label, status, cancelled_at)VALUES (?, ?, ?, ?, 'active', NULL)""",(created, float(due_at), float(duration_sec), clean_label),)self._conn.commit()return int(cur.lastrowid)def list_timers(self,*,status: str = "active",include_expired: bool = False,now: float | None = None,limit: int = 200,) -> list[TimerEntry]:clean_status = status.strip().lower()if clean_status not in {"active", "expired", "cancelled"}:raise ValueError("status must be active, expired, or cancelled")limit = self._normalize_limit(limit, default=200)cur = self._conn.cursor()params: list[Any] = [clean_status]where = "status = ?"if clean_status == "active" and not include_expired:now_ts = time.time() if now is None else float(now)where += " AND due_at > ?"params.append(now_ts)rows = cur.execute(f"SELECT * FROM timers WHERE {where} ORDER BY due_at ASC LIMIT ?",(*params, limit),).fetchall()return [self._row_to_timer(row) for row in rows]def expire_timers(self, *, now: float | None = None) -> int:now_ts = time.time() if now is None else float(now)with self._conn:cur = self._conn.cursor()cur.execute("""UPDATE timersSET status = 'expired'WHERE status = 'active' AND due_at <= ?""",(now_ts,),)return int(cur.rowcount)def cancel_timer(self, timer_id: int, *, cancelled_at: float | None = None) -> bool:cancelled = time.time() if cancelled_at is None else float(cancelled_at)with self._conn:cur = self._conn.cursor()cur.execute("""UPDATE timersSET status = 'cancelled', cancelled_at = ?WHERE id = ? AND status = 'active'""",(cancelled, int(timer_id)),)return cur.rowcount > 0def timer_counts(self) -> dict[str, int]:rows = self._conn.cursor().execute("SELECT status, COUNT(*) AS c FROM timers GROUP BY status",).fetchall()counts = {"active": 0, "expired": 0, "cancelled": 0}for row in rows:key = str(row["status"])if key in counts:counts[key] = int(row["c"])return countsdef close(self) -> None:if self._closed:return10 unmodified lines"fts": self._fts_enabled,"vector": self._memory_enabled,"sources": source_counts,"timers": self.timer_counts(),"last_warm": self._last_warm,"last_sync": self._last_sync,"last_optimize": self._last_optimize,35 unmodified linessource=str(row["source"]),)def _row_to_timer(self, row: sqlite3.Row) -> TimerEntry:cancelled_at = row["cancelled_at"]return TimerEntry(id=int(row["id"]),created_at=float(row["created_at"]),due_at=float(row["due_at"]),duration_sec=float(row["duration_sec"]),label=str(row["label"] or ""),status=str(row["status"]),cancelled_at=float(cancelled_at) if cancelled_at is not None else None,)@staticmethoddef _normalize_limit(value: Any, *, default: int = 5) -> int:parsed = default
66 unmodified lines676869707172271 unmodified lines3443453463473483496 unmodified lines3563573583593603618 unmodified lines370371372373374375362 unmodified lines73873974074174274314 unmodified lines758759760761762763349 unmodified lines1113111411151116111711181119112011211122496 unmodified lines161916201621162216231624382 unmodified lines2007200820092010201120122013201420152016201788 unmodified lines21062107210821092110211166 unmodified lines_home_permission_profile: str = "control"_home_require_confirm_execute: bool = False_home_conversation_enabled: bool = False_todoist_permission_profile: str = "control"_notification_permission_profile: str = "allow"_todoist_timeout_sec: float = 10.0271 unmodified linesdef bind(config: Config, memory_store: MemoryStore | None = None) -> None:global _config, _memory, _audit_log_max_bytes, _audit_log_backupsglobal _home_permission_profile, _home_require_confirm_execute, _home_conversation_enabledglobal _todoist_permission_profile, _notification_permission_profileglobal _todoist_timeout_sec, _pushover_timeout_secglobal _timer_id_seq6 unmodified lines_home_permission_profile = "control"_home_require_confirm_execute = bool(getattr(config, "home_require_confirm_execute", False))_home_conversation_enabled = bool(getattr(config, "home_conversation_enabled", False))_todoist_permission_profile = str(getattr(config, "todoist_permission_profile", "control")).strip().lower()if _todoist_permission_profile not in {"readonly", "control"}:_todoist_permission_profile = "control"8 unmodified lines_ha_state_cache.clear()_timers.clear()_timer_id_seq = 1global _tool_allowlist, _tool_denylist_tool_allowlist = list(config.tool_allowlist)_tool_denylist = list(config.tool_denylist)362 unmodified linesdef _prune_timers(now_mono: float | None = None) -> None:if not _timers:returncurrent = time.monotonic() if now_mono is None else now_mono14 unmodified lines}def _ha_headers() -> dict[str, str]:assert _config is not Nonereturn {"Authorization": f"Bearer {_config.hass_token}"}349 unmodified lines}]}if _home_permission_profile != "control":_record_service_error("home_assistant_conversation", start_time, "policy")_audit("home_assistant_conversation", {"result": "denied", "reason": "readonly_profile"})return {"content": [{"type": "text", "text": "Home Assistant conversation requires HOME_PERMISSION_PROFILE=control."}]}text = str(args.get("text", "")).strip()if not text:_record_service_error("home_assistant_conversation", start_time, "missing_fields")496 unmodified lines"home_permission_profile": _home_permission_profile,"home_require_confirm_execute": bool(_home_require_confirm_execute),"home_conversation_enabled": bool(_home_conversation_enabled),"todoist_permission_profile": _todoist_permission_profile,"notification_permission_profile": _notification_permission_profile,},382 unmodified lines_record_service_error("timer_create", start_time, "invalid_data")return {"content": [{"type": "text", "text": f"Too many active timers ({TIMER_MAX_ACTIVE} max)."}]}label = str(args.get("label", "")).strip()timer_id = _allocate_timer_id()now_wall = time.time()now_mono = time.monotonic()due_wall = now_wall + durationdue_mono = now_mono + duration_timers[timer_id] = {"id": timer_id,"label": label,88 unmodified linesif selected_id is None:_record_service_error("timer_cancel", start_time, "not_found")return {"content": [{"type": "text", "text": "Timer not found."}]}removed = _timers.pop(selected_id, None)if removed is None:_record_service_error("timer_cancel", start_time, "not_found")66 unmodified lines67686970717273271 unmodified lines3453463473483493503516 unmodified lines3583593603613623633643653663673688 unmodified lines377378379380381382383362 unmodified lines74674774874975075175275375475575614 unmodified lines771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807349 unmodified lines11571158115911601161116211631164116511661167116811691170117111721173496 unmodified lines1670167116721673167416751676382 unmodified lines20592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208288 unmodified lines21712172217321742175217621772178217921802181218221832184218566 unmodified lines_home_permission_profile: str = "control"_home_require_confirm_execute: bool = False_home_conversation_enabled: bool = False_home_conversation_permission_profile: str = "readonly"_todoist_permission_profile: str = "control"_notification_permission_profile: str = "allow"_todoist_timeout_sec: float = 10.0271 unmodified linesdef bind(config: Config, memory_store: MemoryStore | None = None) -> None:global _config, _memory, _audit_log_max_bytes, _audit_log_backupsglobal _home_permission_profile, _home_require_confirm_execute, _home_conversation_enabledglobal _home_conversation_permission_profileglobal _todoist_permission_profile, _notification_permission_profileglobal _todoist_timeout_sec, _pushover_timeout_secglobal _timer_id_seq6 unmodified lines_home_permission_profile = "control"_home_require_confirm_execute = bool(getattr(config, "home_require_confirm_execute", False))_home_conversation_enabled = bool(getattr(config, "home_conversation_enabled", False))_home_conversation_permission_profile = str(getattr(config, "home_conversation_permission_profile", "readonly")).strip().lower()if _home_conversation_permission_profile not in {"readonly", "control"}:_home_conversation_permission_profile = "readonly"_todoist_permission_profile = str(getattr(config, "todoist_permission_profile", "control")).strip().lower()if _todoist_permission_profile not in {"readonly", "control"}:_todoist_permission_profile = "control"8 unmodified lines_ha_state_cache.clear()_timers.clear()_timer_id_seq = 1_load_timers_from_store()global _tool_allowlist, _tool_denylist_tool_allowlist = list(config.tool_allowlist)_tool_denylist = list(config.tool_denylist)362 unmodified linesdef _prune_timers(now_mono: float | None = None) -> None:if _memory is not None:try:_memory.expire_timers(now=time.time())except Exception:log.warning("Failed to expire persisted timers", exc_info=True)if not _timers:returncurrent = time.monotonic() if now_mono is None else now_mono14 unmodified lines}def _load_timers_from_store() -> None:global _timer_id_seqif _memory is None:returnnow_wall = time.time()now_mono = time.monotonic()try:_memory.expire_timers(now=now_wall)rows = _memory.list_timers(status="active", include_expired=False, now=now_wall, limit=TIMER_MAX_ACTIVE)except Exception:log.warning("Failed to load persisted timers", exc_info=True)returnmax_id = 0for row in rows:remaining = float(row.due_at) - now_wallif remaining <= 0.0:continuetimer_id = int(row.id)max_id = max(max_id, timer_id)_timers[timer_id] = {"id": timer_id,"label": row.label,"duration_sec": float(row.duration_sec),"created_at": float(row.created_at),"due_at": float(row.due_at),"due_mono": now_mono + remaining,}if max_id >= _timer_id_seq:_timer_id_seq = max_id + 1def _ha_headers() -> dict[str, str]:assert _config is not Nonereturn {"Authorization": f"Bearer {_config.hass_token}"}349 unmodified lines}]}if _home_conversation_permission_profile != "control":_record_service_error("home_assistant_conversation", start_time, "policy")_audit("home_assistant_conversation", {"result": "denied", "reason": "conversation_readonly_profile"})return {"content": [{"type": "text","text": "Home Assistant conversation requires HOME_CONVERSATION_PERMISSION_PROFILE=control.",}]}text = str(args.get("text", "")).strip()if not text:_record_service_error("home_assistant_conversation", start_time, "missing_fields")496 unmodified lines"home_permission_profile": _home_permission_profile,"home_require_confirm_execute": bool(_home_require_confirm_execute),"home_conversation_enabled": bool(_home_conversation_enabled),"home_conversation_permission_profile": _home_conversation_permission_profile,"todoist_permission_profile": _todoist_permission_profile,"notification_permission_profile": _notification_permission_profile,},382 unmodified lines_record_service_error("timer_create", start_time, "invalid_data")return {"content": [{"type": "text", "text": f"Too many active timers ({TIMER_MAX_ACTIVE} max)."}]}label = str(args.get("label", "")).strip()now_wall = time.time()now_mono = time.monotonic()due_wall = now_wall + durationdue_mono = now_mono + durationtimer_id: intif _memory is not None:try:timer_id = _memory.add_timer(due_at=due_wall,duration_sec=duration,label=label,created_at=now_wall,)except Exception:_record_service_error("timer_create", start_time, "storage_error")return {"content": [{"type": "text", "text": "Timer create failed: persistent storage unavailable."}]}else:timer_id = _allocate_timer_id()_timers[timer_id] = {"id": timer_id,"label": label,88 unmodified linesif selected_id is None:_record_service_error("timer_cancel", start_time, "not_found")return {"content": [{"type": "text", "text": "Timer not found."}]}if _memory is not None:try:cancelled = _memory.cancel_timer(selected_id)except Exception:_record_service_error("timer_cancel", start_time, "storage_error")return {"content": [{"type": "text", "text": "Timer cancel failed: persistent storage unavailable."}]}if not cancelled:_record_service_error("timer_cancel", start_time, "not_found")return {"content": [{"type": "text", "text": "Timer not found."}]}removed = _timers.pop(selected_id, None)if removed is None:_record_service_error("timer_cancel", start_time, "not_found")
96 unmodified lines97989910010110227 unmodified lines13013113213313413511 unmodified lines14714814915015115289 unmodified lines2422432442452462476 unmodified lines25425525625725896 unmodified linesc = Config(home_permission_profile="execute-all")assert c.home_permission_profile == "control"def test_todoist_permission_profile_normalizes(self, monkeypatch):monkeypatch.setenv("ANTHROPIC_API_KEY", "test")from jarvis.config import Config27 unmodified linesmonkeypatch.setenv("HOME_REQUIRE_CONFIRM_EXECUTE", "sometimes")monkeypatch.setenv("HOME_CONVERSATION_ENABLED", "perhaps")monkeypatch.setenv("HOME_PERMISSION_PROFILE", "execute-all")monkeypatch.setenv("TODOIST_PERMISSION_PROFILE", "write-all")monkeypatch.setenv("NOTIFICATION_PERMISSION_PROFILE", "enabled")from jarvis.config import Config11 unmodified linesassert "HOME_REQUIRE_CONFIRM_EXECUTE invalid boolean" in textassert "HOME_CONVERSATION_ENABLED invalid boolean" in textassert "HOME_PERMISSION_PROFILE invalid" in textassert "TODOIST_PERMISSION_PROFILE invalid" in textassert "NOTIFICATION_PERMISSION_PROFILE invalid" in text89 unmodified linesdef test_startup_warning_for_permissive_profiles_without_credentials(self, monkeypatch):monkeypatch.setenv("ANTHROPIC_API_KEY", "test")monkeypatch.setenv("HOME_PERMISSION_PROFILE", "control")monkeypatch.setenv("TODOIST_PERMISSION_PROFILE", "control")monkeypatch.setenv("NOTIFICATION_PERMISSION_PROFILE", "allow")monkeypatch.delenv("HASS_URL", raising=False)6 unmodified linesc = Config()text = "\n".join(c.startup_warnings).lower()assert "home_permission_profile=control set while hass_url/hass_token are empty" in textassert "todoist_permission_profile=control set while todoist_api_token is empty" in textassert "notification_permission_profile=allow set while pushover credentials are empty" in text96 unmodified lines97989910010110210310410510610710827 unmodified lines13613713813914014114211 unmodified lines15415515615715815916089 unmodified lines2502512522532542552566 unmodified lines26326426526626726896 unmodified linesc = Config(home_permission_profile="execute-all")assert c.home_permission_profile == "control"def test_home_conversation_permission_profile_normalizes(self, monkeypatch):monkeypatch.setenv("ANTHROPIC_API_KEY", "test")from jarvis.config import Configc = Config(home_conversation_permission_profile="execute-all")assert c.home_conversation_permission_profile == "readonly"def test_todoist_permission_profile_normalizes(self, monkeypatch):monkeypatch.setenv("ANTHROPIC_API_KEY", "test")from jarvis.config import Config27 unmodified linesmonkeypatch.setenv("HOME_REQUIRE_CONFIRM_EXECUTE", "sometimes")monkeypatch.setenv("HOME_CONVERSATION_ENABLED", "perhaps")monkeypatch.setenv("HOME_PERMISSION_PROFILE", "execute-all")monkeypatch.setenv("HOME_CONVERSATION_PERMISSION_PROFILE", "execute-all")monkeypatch.setenv("TODOIST_PERMISSION_PROFILE", "write-all")monkeypatch.setenv("NOTIFICATION_PERMISSION_PROFILE", "enabled")from jarvis.config import Config11 unmodified linesassert "HOME_REQUIRE_CONFIRM_EXECUTE invalid boolean" in textassert "HOME_CONVERSATION_ENABLED invalid boolean" in textassert "HOME_PERMISSION_PROFILE invalid" in textassert "HOME_CONVERSATION_PERMISSION_PROFILE invalid" in textassert "TODOIST_PERMISSION_PROFILE invalid" in textassert "NOTIFICATION_PERMISSION_PROFILE invalid" in text89 unmodified linesdef test_startup_warning_for_permissive_profiles_without_credentials(self, monkeypatch):monkeypatch.setenv("ANTHROPIC_API_KEY", "test")monkeypatch.setenv("HOME_PERMISSION_PROFILE", "control")monkeypatch.setenv("HOME_CONVERSATION_PERMISSION_PROFILE", "control")monkeypatch.setenv("TODOIST_PERMISSION_PROFILE", "control")monkeypatch.setenv("NOTIFICATION_PERMISSION_PROFILE", "allow")monkeypatch.delenv("HASS_URL", raising=False)6 unmodified linesc = Config()text = "\n".join(c.startup_warnings).lower()assert "home_permission_profile=control set while hass_url/hass_token are empty" in textassert "home_conversation_permission_profile=control set while hass_url/hass_token are empty" in textassert "todoist_permission_profile=control set while todoist_api_token is empty" in textassert "notification_permission_profile=allow set while pushover credentials are empty" in text
205 unmodified lines206207208205 unmodified linesassert plan_status == "open"finally:store.close()205 unmodified lines206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253205 unmodified linesassert plan_status == "open"finally:store.close()def test_timer_store_lifecycle(tmp_path):store = MemoryStore(str(tmp_path / "memory.sqlite"))try:now = 1_700_000_000.0timer_id = store.add_timer(due_at=now + 120.0,duration_sec=120.0,label="tea",created_at=now,)active = store.list_timers(status="active", include_expired=False, now=now)assert [timer.id for timer in active] == [timer_id]assert active[0].label == "tea"assert store.cancel_timer(timer_id) is Trueassert store.cancel_timer(timer_id) is Falsecancelled = store.list_timers(status="cancelled")assert [timer.id for timer in cancelled] == [timer_id]finally:store.close()def test_expire_timers_moves_due_rows_to_expired(tmp_path):store = MemoryStore(str(tmp_path / "memory.sqlite"))try:now = 1_700_000_000.0_ = store.add_timer(due_at=now - 5.0,duration_sec=30.0,label="old",created_at=now - 35.0,)changed = store.expire_timers(now=now)assert changed == 1active = store.list_timers(status="active", include_expired=False, now=now)assert active == []expired = store.list_timers(status="expired")assert len(expired) == 1counts = store.timer_counts()assert counts["expired"] == 1assert counts["active"] == 0finally:store.close()
796 unmodified lines7977987998008018028 unmodified lines8118128138148158168178188198208218228238242 unmodified lines82782882983083183283326 unmodified lines8608618628638648658665 unmodified lines87287387487587687743 unmodified lines9219229239249259261140 unmodified lines206720682069207020712072313 unmodified lines238623872388796 unmodified linescfg = services._configassert cfg is not Nonecfg.home_conversation_enabled = Trueservices.bind(cfg)result = await services.home_assistant_conversation({8 unmodified linescfg = services._configassert cfg is not Nonecfg.home_conversation_enabled = Truecfg.home_permission_profile = "readonly"services.bind(cfg)result = await services.home_assistant_conversation({"text": "turn on kitchen lights","confirm": True,})assert "home_permission_profile=control" in result["content"][0]["text"].lower()@pytest.mark.asyncioasync def test_home_assistant_conversation_success(self, aiohttp_response, aiohttp_session_mock):2 unmodified linescfg = services._configassert cfg is not Nonecfg.home_conversation_enabled = Truecfg.home_permission_profile = "control"services.bind(cfg)response = aiohttp_response(26 unmodified linescfg = services._configassert cfg is not Nonecfg.home_conversation_enabled = Truecfg.home_permission_profile = "control"services.bind(cfg)response = aiohttp_response(status=200, json_data="not-a-dict")5 unmodified lines})assert "invalid home assistant conversation response" in result["content"][0]["text"].lower()@pytest.mark.asyncioasync def test_timer_create_list_cancel_lifecycle(self):from jarvis.tools import services43 unmodified lineshidden = await services.timer_list({})assert "no active timers" in hidden["content"][0]["text"].lower()@pytest.mark.asyncioasync def test_todoist_add_task_requires_config(self):from jarvis.tools import services1140 unmodified linesassert "tool_policy" in payloadassert isinstance(payload["tool_policy"]["home_require_confirm_execute"], bool)assert isinstance(payload["tool_policy"]["home_conversation_enabled"], bool)assert "memory" in payloadassert "audit" in payloadassert payload["audit"]["redaction_enabled"] is True313 unmodified lines}for code in critical_codes:assert code in script_text796 unmodified lines7977987998008018028038 unmodified lines8128138148158168178188198208218228238248252 unmodified lines82882983083183283383426 unmodified lines8618628638648658668675 unmodified lines87387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395443 unmodified lines998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401140 unmodified lines2181218221832184218521862187313 unmodified lines2501250225032504250525062507250825092510796 unmodified linescfg = services._configassert cfg is not Nonecfg.home_conversation_enabled = Truecfg.home_conversation_permission_profile = "control"services.bind(cfg)result = await services.home_assistant_conversation({8 unmodified linescfg = services._configassert cfg is not Nonecfg.home_conversation_enabled = Truecfg.home_conversation_permission_profile = "readonly"services.bind(cfg)result = await services.home_assistant_conversation({"text": "turn on kitchen lights","confirm": True,})assert "home_conversation_permission_profile=control" in result["content"][0]["text"].lower()@pytest.mark.asyncioasync def test_home_assistant_conversation_success(self, aiohttp_response, aiohttp_session_mock):2 unmodified linescfg = services._configassert cfg is not Nonecfg.home_conversation_enabled = Truecfg.home_conversation_permission_profile = "control"services.bind(cfg)response = aiohttp_response(26 unmodified linescfg = services._configassert cfg is not Nonecfg.home_conversation_enabled = Truecfg.home_conversation_permission_profile = "control"services.bind(cfg)response = aiohttp_response(status=200, json_data="not-a-dict")5 unmodified lines})assert "invalid home assistant conversation response" in result["content"][0]["text"].lower()@pytest.mark.asyncio@pytest.mark.parametrize(("status", "expected_text", "expected_detail"),[(401, "authentication failed", "auth"),(404, "endpoint not found", "not_found"),(500, "conversation error (500)", "http_error"),],)async def test_home_assistant_conversation_http_mappings(self,status,expected_text,expected_detail,aiohttp_response,aiohttp_session_mock,):from jarvis.tools import servicesfrom jarvis.tool_summary import list_summariescfg = services._configassert cfg is not Nonecfg.home_conversation_enabled = Truecfg.home_conversation_permission_profile = "control"services.bind(cfg)response = aiohttp_response(status=status, json_data={})with patch("aiohttp.ClientSession") as mock_session_cls:mock_session_cls.return_value = aiohttp_session_mock(post=response)result = await services.home_assistant_conversation({"text": "turn off the kitchen lights","confirm": True,})assert expected_text in result["content"][0]["text"].lower()summaries = list_summaries(25)assert any(item.get("name") == "home_assistant_conversation" and item.get("detail") == expected_detailfor item in summaries)@pytest.mark.asyncio@pytest.mark.parametrize(("side_effect", "expected_text", "expected_detail"),[(asyncio.TimeoutError(), "timed out", "timeout"),(asyncio.CancelledError(), "was cancelled", "cancelled"),(aiohttp.ClientError("boom"), "failed to reach", "network_client_error"),],)async def test_home_assistant_conversation_transport_error_mappings(self,side_effect,expected_text,expected_detail,):from jarvis.tools import servicesfrom jarvis.tool_summary import list_summariescfg = services._configassert cfg is not Nonecfg.home_conversation_enabled = Truecfg.home_conversation_permission_profile = "control"services.bind(cfg)with patch("aiohttp.ClientSession", side_effect=side_effect):result = await services.home_assistant_conversation({"text": "turn off the kitchen lights","confirm": True,})assert expected_text in result["content"][0]["text"].lower()summaries = list_summaries(25)assert any(item.get("name") == "home_assistant_conversation" and item.get("detail") == expected_detailfor item in summaries)@pytest.mark.asyncioasync def test_timer_create_list_cancel_lifecycle(self):from jarvis.tools import services43 unmodified lineshidden = await services.timer_list({})assert "no active timers" in hidden["content"][0]["text"].lower()@pytest.mark.asyncioasync def test_timer_persists_across_bind(self, tmp_path):from jarvis.config import Configfrom jarvis.memory import MemoryStorefrom jarvis.tools import servicescfg = Config()store = MemoryStore(str(tmp_path / "memory.sqlite"))services.bind(cfg, store)created = await services.timer_create({"duration": 600, "label": "persisted"})timer_id = int(created["content"][0]["text"].split()[1])services.bind(cfg, store)listed = await services.timer_list({})text = listed["content"][0]["text"].lower()assert "persisted" in textassert f"- {timer_id}" in text@pytest.mark.asyncioasync def test_timer_cancel_persists_across_bind(self, tmp_path):from jarvis.config import Configfrom jarvis.memory import MemoryStorefrom jarvis.tools import servicescfg = Config()store = MemoryStore(str(tmp_path / "memory.sqlite"))services.bind(cfg, store)created = await services.timer_create({"duration": 600, "label": "to-cancel"})timer_id = int(created["content"][0]["text"].split()[1])await services.timer_cancel({"timer_id": timer_id})services.bind(cfg, store)listed = await services.timer_list({})assert "no active timers" in listed["content"][0]["text"].lower()@pytest.mark.asyncioasync def test_todoist_add_task_requires_config(self):from jarvis.tools import services1140 unmodified linesassert "tool_policy" in payloadassert isinstance(payload["tool_policy"]["home_require_confirm_execute"], bool)assert isinstance(payload["tool_policy"]["home_conversation_enabled"], bool)assert payload["tool_policy"]["home_conversation_permission_profile"] in {"readonly", "control"}assert "memory" in payloadassert "audit" in payloadassert payload["audit"]["redaction_enabled"] is True313 unmodified lines}for code in critical_codes:assert code in script_textdef test_error_taxonomy_doc_mentions_home_assistant_conversation_and_timers(self):project_root = Path(__file__).resolve().parents[1]taxonomy_doc = (project_root / "docs" / "operations" / "error-taxonomy.md").read_text()assert "home_assistant_conversation" in taxonomy_docassert "timer_cancel" in taxonomy_docassert "timer_*" in taxonomy_doc
.env.example+2
README.md+2-1
TODO.md+6-6
docs/operations/error-taxonomy.md+12-12
docs/operations/home-control-policy.md+4-1
docs/operations/integration-policy.md+1-1
src/jarvis/config.py+29
src/jarvis/memory.py+127
src/jarvis/tools/services.py+78-4
tests/test_config.py+10
tests/test_memory.py+45
tests/test_tools_services.py+126-4