Jonathan Haas commited on
Commit ·
ebdf22f
1
Parent(s): 1ee9802
refactor: split runtime state and audit runtime helpers
Browse filesFiles changed (11)
- TODO.md+62-67
- src/jarvis/tools/services_audit_crypto_runtime.pyAdded+63
- src/jarvis/tools/services_audit_event_runtime.pyAdded+170
- src/jarvis/tools/services_audit_retention_runtime.pyAdded+104
- src/jarvis/tools/services_audit_runtime.py+46-413
- src/jarvis/tools/services_audit_sanitize_runtime.pyAdded+101
- src/jarvis/tools/services_runtime_state.py+24-488
- src/jarvis/tools/services_runtime_state_bind.pyAdded+194
- src/jarvis/tools/services_runtime_state_persistence.pyAdded+287
- src/jarvis/tools/services_runtime_state_reports.pyAdded+20
- tests/test_import_boundaries.py+9
123411 unmodified lines161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# Jarvis TODO — Wave 68 (Status/Governance/Recovery Runtime Decomposition)Last updated: 2026-02-2711 unmodified lines## A) Scope and baseline- [x] `W68-A01` Profile largest remaining runtime hotspots in `src/jarvis/tools`.- [x] `W68-A02` Select `services_status_runtime.py` for split.- [x] `W68-A03` Select `services_governance_runtime.py` for split.- [x] `W68-A04` Select `services_recovery_runtime.py` for split.- [x] `W68-A05` Keep import API stable for `services.py` callers.## B) Status runtime split- [x] `W68-B01` Create `services_status_snapshots_runtime.py`.- [x] `W68-B02` Move integration/identity/voice snapshot helpers.- [x] `W68-B03` Move observability/skills/expansion snapshot helpers.- [x] `W68-B04` Move `health_rollup` helper.- [x] `W68-B05` Create `services_status_scorecard_runtime.py`.- [x] `W68-B06` Move scorecard helpers (`score_label`, row extraction, p95, scorecard payload).- [x] `W68-B07` Reduce `services_status_runtime.py` to compatibility wrapper.## C) Governance runtime split- [x] `W68-C01` Create `services_governance_status_payload.py`.- [x] `W68-C02` Move tool-policy/scorecard-context payload helpers.- [x] `W68-C03` Create `services_governance_contract.py`.- [x] `W68-C04` Move system-status contract field map + payload helper.- [x] `W68-C05` Reduce `services_governance_runtime.py` to compatibility wrapper.## D) Recovery runtime split- [x] `W68-D01` Create `services_recovery_journal_runtime.py`.- [x] `W68-D02` Move journal read/write/start/finish helpers.- [x] `W68-D03` Move `RecoveryOperation` context manager and reconcile/status helpers.- [x] `W68-D04` Create `services_dead_letter_runtime.py`.- [x] `W68-D05` Move dead-letter read/write/enqueue/status helpers.- [x] `W68-D06` Create `services_recovery_response_runtime.py`.- [x] `W68-D07` Move tool-response text/success evaluators.- [x] `W68-D08` Reduce `services_recovery_runtime.py` to compatibility wrapper.## E) Boundaries and verification- [x] `W68-E01` Extend import-boundary coverage for new status runtime modules.- [x] `W68-E02` Extend import-boundary coverage for new governance runtime modules.- [x] `W68-E03` Extend import-boundary coverage for new recovery runtime modules.- [x] `W68-E04` Run focused lint for changed runtime files.- [x] `W68-E05` Run `uv run pytest -q tests/test_import_boundaries.py`.- [x] `W68-E06` Run targeted status/recovery governance tool tests.- [x] `W68-E07` Run full `make check`.- [x] `W68-E08` Run full `make security-gate`.- [x] `W68-E09` Run `./scripts/jarvis_readiness.sh fast`.## F) Release loop- [x] `W68-F01` Record wrapper reductions and extracted module counts.- [x] `W68-F02` Commit Wave 68 tranche.- [x] `W68-F03` Push Wave 68 to `origin/main`.---## Outcome snapshot (completed)- Wrapper concentration reductions:- `services_status_runtime.py`: `628 -> 33`- `services_governance_runtime.py`: `496 -> 17`- `services_recovery_runtime.py`: `419 -> 45`- New extracted modules:- `services_status_snapshots_runtime.py`- `services_status_scorecard_runtime.py`- `services_governance_status_payload.py`- `services_governance_contract.py`- `services_recovery_journal_runtime.py`- `services_dead_letter_runtime.py`- `services_recovery_response_runtime.py`- Validation status:- `uv run pytest -q tests/test_import_boundaries.py`: `135 passed`.- `uv run pytest -q tests/test_tools_services.py -k "system_status or jarvis_scorecard or dead_letter or recovery_journal"`: `9 passed`.- `make check`: `724 passed`.- `make security-gate`: `724 passed`; fault subset `3 passed`.- `./scripts/jarvis_readiness.sh fast`: pass; strict eval `159/159`.123411 unmodified lines16171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788# Jarvis TODO — Wave 69 (Runtime State + Audit Runtime Decomposition)Last updated: 2026-02-2711 unmodified lines## A) Scope and baseline- [x] `W69-A01` Profile remaining large runtime modules after Wave 68.- [x] `W69-A02` Select `services_runtime_state.py` for decomposition.- [x] `W69-A03` Select `services_audit_runtime.py` for decomposition.- [x] `W69-A04` Preserve `services.py` import contracts and helper names.- [x] `W69-A05` Keep behavior parity for bind/bootstrap, persistence, and audit flows.## B) Runtime state split- [x] `W69-B01` Create `services_runtime_state_bind.py`.- [x] `W69-B02` Move `bind_runtime_state` implementation.- [x] `W69-B03` Move `_reset_runtime_state` implementation into bind module scope.- [x] `W69-B04` Create `services_runtime_state_reports.py`.- [x] `W69-B05` Move `quality_reports_snapshot` implementation.- [x] `W69-B06` Move `append_quality_report` implementation.- [x] `W69-B07` Create `services_runtime_state_persistence.py`.- [x] `W69-B08` Move `json_safe_clone`/`replace_state_dict` helpers.- [x] `W69-B09` Move expansion payload/persist/load helpers.- [x] `W69-B10` Reduce `services_runtime_state.py` to compatibility wrapper.## C) Audit runtime split- [x] `W69-C01` Create `services_audit_crypto_runtime.py`.- [x] `W69-C02` Move audit encryption/decryption helpers.- [x] `W69-C03` Create `services_audit_event_runtime.py`.- [x] `W69-C04` Move audit outcome/reason/humanization helpers.- [x] `W69-C05` Move decision explanation + audit write/rotate helpers.- [x] `W69-C06` Create `services_audit_sanitize_runtime.py`.- [x] `W69-C07` Move redaction + metadata-only + inbound sanitizer helpers.- [x] `W69-C08` Create `services_audit_retention_runtime.py`.- [x] `W69-C09` Move audit status/prune/retention helpers.- [x] `W69-C10` Reduce `services_audit_runtime.py` to compatibility wrapper.## D) Boundary and quality verification- [x] `W69-D01` Extend import-boundary coverage for runtime-state split modules.- [x] `W69-D02` Extend import-boundary coverage for audit split modules.- [x] `W69-D03` Run focused lint on all changed runtime modules.- [x] `W69-D04` Run `uv run pytest -q tests/test_import_boundaries.py`.- [x] `W69-D05` Run targeted tools tests for audit + expansion/state status paths.- [x] `W69-D06` Run full `make check`.- [x] `W69-D07` Run full `make security-gate`.- [x] `W69-D08` Run `./scripts/jarvis_readiness.sh fast`.## E) Release loop- [x] `W69-E01` Record wrapper reduction deltas and new module inventory.- [x] `W69-E02` Commit Wave 69 tranche.- [x] `W69-E03` Push Wave 69 tranche to `origin/main`.---## Outcome snapshot (completed)- Wrapper concentration reductions:- `services_runtime_state.py`: `491 -> 27`- `services_audit_runtime.py`: `416 -> 49`- New extracted modules:- `services_runtime_state_bind.py`- `services_runtime_state_reports.py`- `services_runtime_state_persistence.py`- `services_audit_crypto_runtime.py`- `services_audit_event_runtime.py`- `services_audit_sanitize_runtime.py`- `services_audit_retention_runtime.py`- Validation status:- `uv run pytest -q tests/test_import_boundaries.py`: `144 passed`.- `uv run pytest -q tests/test_tools_services.py -k "audit_log or prune_audit_file or inbound_webhook_event or expansion_state_persists_across_bind or integration_hub_release_channel_actions or system_status"`: `18 passed`.- `make check`: `733 passed`.- `make security-gate`: `733 passed`; fault subset `3 passed`.- `./scripts/jarvis_readiness.sh fast`: pass; strict eval `159/159`.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""Audit encryption/decryption helpers for services domains."""
from __future__ import annotations
import base64import hashlibimport jsonfrom typing import Any
def configure_audit_encryption(services_module: Any, *, enabled: bool, key: str) -> None: s = services_module s._audit_encryption_enabled = bool(enabled) s._data_encryption_key = str(key or "").strip() if not s._audit_encryption_enabled: s._audit_fernet = None return if not s._data_encryption_key or s.Fernet is None: s._audit_fernet = None return candidate = s._data_encryption_key.encode("utf-8") try: s.Fernet(candidate) fernet_key = candidate except Exception: digest = hashlib.sha256(candidate).digest() fernet_key = base64.urlsafe_b64encode(digest) s._audit_fernet = s.Fernet(fernet_key)
def encrypt_audit_line(services_module: Any, payload: dict[str, Any]) -> str: s = services_module line = json.dumps(payload, default=str) if not s._audit_encryption_enabled or s._audit_fernet is None: return line token = s._audit_fernet.encrypt(line.encode("utf-8")).decode("utf-8") return json.dumps({"enc": token}, default=str)
def decode_audit_line(services_module: Any, line: str) -> dict[str, Any] | None: s = services_module text = line.strip() if not text: return None try: payload = json.loads(text) except Exception: return None if isinstance(payload, dict) and "enc" in payload: token = str(payload.get("enc", "")).strip() if not token or s._audit_fernet is None: return {"encrypted": True, "error": "missing_encryption_key"} try: raw = s._audit_fernet.decrypt(token.encode("utf-8")).decode("utf-8") except s.InvalidToken: return {"encrypted": True, "error": "invalid_token"} try: decrypted = json.loads(raw) except Exception: return {"encrypted": True, "error": "invalid_payload"} if isinstance(decrypted, dict): return decrypted return {"encrypted": True, "error": "invalid_payload"} return payload if isinstance(payload, dict) else None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""Audit event and decision logging helpers for services domains."""
from __future__ import annotations
import jsonimport timefrom typing import Any
from jarvis.tools.services_audit_crypto_runtime import encrypt_audit_linefrom jarvis.tools.services_audit_sanitize_runtime import ( metadata_only_audit_details, redact_sensitive_for_audit,)
def audit_outcome(details: dict[str, Any]) -> str: policy_decision = str(details.get("policy_decision", "")).strip().lower() result = str(details.get("result", "")).strip().lower() if policy_decision in {"denied", "blocked"}: return "blocked" if policy_decision in {"allowed", "execute"}: return "allowed" if policy_decision == "dry_run": return "dry_run" if policy_decision == "preview_required": return "preview_required" if result in {"denied", "blocked"}: return "blocked" if result in {"ok", "success", "delivered"}: return "allowed" if result in {"timeout", "cancelled", "network_client_error", "http_error", "api_error", "auth", "unexpected"}: return "failed" if result in {"missing_config", "missing_fields", "invalid_data", "invalid_json"}: return "failed" if result: return "observed" return "unknown"
def audit_reason_code(details: dict[str, Any]) -> str: reason = str(details.get("reason", "")).strip().lower() if reason: return reason policy_decision = str(details.get("policy_decision", "")).strip().lower() if policy_decision: return policy_decision result = str(details.get("result", "")).strip().lower() return result
def humanize_chain_token(token: str) -> str: text = str(token).strip() if not text: return "" if text.startswith("deny:"): reason = text.split(":", 1)[1].replace("_", " ") return f"deny ({reason})" if text.startswith("decision:"): reason = text.split(":", 1)[1].replace("_", " ") return f"decision ({reason})" if text.startswith("tool="): return f"tool {text.split('=', 1)[1]}" if text.startswith("requester="): return f"requester {text.split('=', 1)[1]}" if text.startswith("profile="): return f"profile {text.split('=', 1)[1]}" return text.replace("_", " ")
def audit_decision_explanation(services_module: Any, action: str, details: dict[str, Any]) -> str: s = services_module outcome = audit_outcome(details) reason_code = audit_reason_code(details) if outcome == "blocked": intro = "Blocked" elif outcome == "allowed": intro = "Allowed" elif outcome == "dry_run": intro = "Dry run" elif outcome == "preview_required": intro = "Preview required" elif outcome == "failed": intro = "Failed" elif outcome == "observed": intro = "Recorded" else: intro = "Logged"
reason_msg = s.AUDIT_REASON_MESSAGES.get(reason_code, "") if not reason_msg and reason_code: reason_msg = reason_code.replace("_", " ")
chain = details.get("decision_chain") chain_tokens = chain if isinstance(chain, list) else [] chain_hint = "" if chain_tokens: tail = [humanize_chain_token(item) for item in chain_tokens[-2:]] tail = [item for item in tail if item] if tail: chain_hint = f" Decision path: {' -> '.join(tail)}."
action_label = str(action).replace("_", " ").strip() or "action" if reason_msg: return f"{intro}: {action_label} was {reason_msg}.{chain_hint}".strip() return f"{intro}: {action_label} was processed.{chain_hint}".strip()
def audit(services_module: Any, action: str, details: dict[str, Any]) -> None: s = services_module enriched = {str(key): value for key, value in details.items()} if "requester_id" not in enriched: enriched["requester_id"] = s._identity_default_user if "requester_profile" not in enriched: enriched["requester_profile"] = s._identity_user_profiles.get( str(enriched["requester_id"]).strip().lower(), s._identity_default_profile, ) if "requester_trusted" not in enriched: requester = str(enriched["requester_id"]).strip().lower() enriched["requester_trusted"] = requester in s._identity_trusted_users or str( enriched["requester_profile"] ).strip().lower() == "trusted" if "speaker_verified" not in enriched: enriched["speaker_verified"] = False if "identity_source" not in enriched: enriched["identity_source"] = "default" if "decision_chain" not in enriched: enriched["decision_chain"] = ["identity_default_context"] if "decision_outcome" not in enriched: enriched["decision_outcome"] = audit_outcome(enriched) if "decision_reason" not in enriched: enriched["decision_reason"] = audit_reason_code(enriched) if "decision_explanation" not in enriched: enriched["decision_explanation"] = audit_decision_explanation(s, action, enriched)
metadata_only = metadata_only_audit_details(s, action, enriched) redacted = redact_sensitive_for_audit(s, metadata_only) details_json = json.dumps(redacted, default=str) entry = { "timestamp": time.time(), "action": action, **redacted, } try: rotate_audit_log_if_needed(s) with open(s.AUDIT_LOG, "a") as handle: handle.write(encrypt_audit_line(s, entry) + "\n") except OSError as exc: s.log.warning("Failed to write audit log: %s", exc) s.log.info("AUDIT: %s — %s", action, details_json)
def rotate_audit_log_if_needed(services_module: Any) -> None: s = services_module if s._audit_log_backups < 1: return try: if s.AUDIT_LOG.exists() and s.AUDIT_LOG.stat().st_size >= s._audit_log_max_bytes: for idx in range(s._audit_log_backups, 0, -1): src = s.AUDIT_LOG.with_name(f"{s.AUDIT_LOG.name}.{idx}") dst = s.AUDIT_LOG.with_name(f"{s.AUDIT_LOG.name}.{idx + 1}") if src.exists(): if idx == s._audit_log_backups: src.unlink(missing_ok=True) else: src.rename(dst) rotated = s.AUDIT_LOG.with_name(f"{s.AUDIT_LOG.name}.1") s.AUDIT_LOG.rename(rotated) except OSError as exc: s.log.warning("Failed to rotate audit log: %s", exc)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Audit status and retention helpers for services domains."""
from __future__ import annotations
import timefrom typing import Any
from jarvis.tools.services_audit_crypto_runtime import decode_audit_line
def audit_status(services_module: Any) -> dict[str, Any]: s = services_module try: exists = s.AUDIT_LOG.exists() size_bytes = s.AUDIT_LOG.stat().st_size if exists else 0 except OSError: exists = False size_bytes = 0 backups = [] for idx in range(1, s._audit_log_backups + 1): backup_path = s.AUDIT_LOG.with_name(f"{s.AUDIT_LOG.name}.{idx}") try: if backup_path.exists(): backups.append( { "path": str(backup_path), "size_bytes": int(backup_path.stat().st_size), } ) except OSError: continue return { "path": str(s.AUDIT_LOG), "exists": exists, "size_bytes": int(size_bytes), "max_bytes": int(s._audit_log_max_bytes), "encrypted": bool(s._audit_encryption_enabled and s._audit_fernet is not None), "encryption_configured": bool(s._audit_encryption_enabled), "backups": backups, "redaction_enabled": bool(s.SENSITIVE_AUDIT_KEY_TOKENS), "redaction_key_count": len(s.SENSITIVE_AUDIT_KEY_TOKENS), "metadata_only_actions": sorted(s.AUDIT_METADATA_ONLY_FORBIDDEN_FIELDS), }
def prune_audit_file(services_module: Any, path: Any, *, cutoff_ts: float) -> int: s = services_module if not path.exists(): return 0 try: lines = path.read_text().splitlines() except OSError: return 0 kept: list[str] = [] removed = 0 for line in lines: raw_line = line.strip() if not raw_line: continue payload = decode_audit_line(s, raw_line) if not isinstance(payload, dict): removed += 1 continue if payload.get("encrypted") is True and payload.get("error") in { "missing_encryption_key", "invalid_token", "invalid_payload", }: kept.append(raw_line) continue ts = payload.get("timestamp") if isinstance(ts, (int, float)) and float(ts) >= cutoff_ts: kept.append(raw_line) else: removed += 1 if removed <= 0: return 0 try: if kept: path.write_text("\n".join(kept) + "\n") else: path.unlink(missing_ok=True) except OSError: return 0 return removed
def apply_retention_policies(services_module: Any) -> None: s = services_module now = time.time() if s._memory is not None and s._memory_retention_days > 0.0: cutoff = now - (s._memory_retention_days * 86_400.0) try: s._memory.prune_retention(cutoff_ts=cutoff) except Exception: s.log.warning("Failed to apply memory retention policy", exc_info=True) if s._audit_retention_days > 0.0: cutoff = now - (s._audit_retention_days * 86_400.0) paths = [s.AUDIT_LOG] + [ s.AUDIT_LOG.with_name(f"{s.AUDIT_LOG.name}.{idx}") for idx in range(1, s._audit_log_backups + 1) ] for path in paths: removed = prune_audit_file(s, path, cutoff_ts=cutoff) if removed > 0: s.log.info("Applied audit retention policy to %s (removed=%d)", path, removed)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416"""Audit and redaction runtime helpers for services domains."""from __future__ import annotationsimport base64import hashlibimport jsonimport timefrom typing import Anydef configure_audit_encryption(services_module: Any, *, enabled: bool, key: str) -> None:s = services_modules._audit_encryption_enabled = bool(enabled)s._data_encryption_key = str(key or "").strip()if not s._audit_encryption_enabled:s._audit_fernet = Nonereturnif not s._data_encryption_key or s.Fernet is None:s._audit_fernet = Nonereturncandidate = s._data_encryption_key.encode("utf-8")try:s.Fernet(candidate)fernet_key = candidateexcept Exception:digest = hashlib.sha256(candidate).digest()fernet_key = base64.urlsafe_b64encode(digest)s._audit_fernet = s.Fernet(fernet_key)def encrypt_audit_line(services_module: Any, payload: dict[str, Any]) -> str:s = services_moduleline = json.dumps(payload, default=str)if not s._audit_encryption_enabled or s._audit_fernet is None:return linetoken = s._audit_fernet.encrypt(line.encode("utf-8")).decode("utf-8")return json.dumps({"enc": token}, default=str)def decode_audit_line(services_module: Any, line: str) -> dict[str, Any] | None:s = services_moduletext = line.strip()if not text:return Nonetry:payload = json.loads(text)except Exception:return Noneif isinstance(payload, dict) and "enc" in payload:token = str(payload.get("enc", "")).strip()if not token or s._audit_fernet is None:return {"encrypted": True, "error": "missing_encryption_key"}try:raw = s._audit_fernet.decrypt(token.encode("utf-8")).decode("utf-8")except s.InvalidToken:return {"encrypted": True, "error": "invalid_token"}try:decrypted = json.loads(raw)except Exception:return {"encrypted": True, "error": "invalid_payload"}if isinstance(decrypted, dict):return decryptedreturn {"encrypted": True, "error": "invalid_payload"}return payload if isinstance(payload, dict) else Nonedef audit_outcome(details: dict[str, Any]) -> str:policy_decision = str(details.get("policy_decision", "")).strip().lower()result = str(details.get("result", "")).strip().lower()if policy_decision in {"denied", "blocked"}:return "blocked"if policy_decision in {"allowed", "execute"}:return "allowed"if policy_decision == "dry_run":return "dry_run"if policy_decision == "preview_required":return "preview_required"if result in {"denied", "blocked"}:return "blocked"if result in {"ok", "success", "delivered"}:return "allowed"if result in {"timeout", "cancelled", "network_client_error", "http_error", "api_error", "auth", "unexpected"}:return "failed"if result in {"missing_config", "missing_fields", "invalid_data", "invalid_json"}:return "failed"if result:return "observed"return "unknown"def audit_reason_code(details: dict[str, Any]) -> str:reason = str(details.get("reason", "")).strip().lower()if reason:return reasonpolicy_decision = str(details.get("policy_decision", "")).strip().lower()if policy_decision:return policy_decisionresult = str(details.get("result", "")).strip().lower()return resultdef humanize_chain_token(token: str) -> str:text = str(token).strip()if not text:return ""if text.startswith("deny:"):reason = text.split(":", 1)[1].replace("_", " ")return f"deny ({reason})"if text.startswith("decision:"):reason = text.split(":", 1)[1].replace("_", " ")return f"decision ({reason})"if text.startswith("tool="):return f"tool {text.split('=', 1)[1]}"if text.startswith("requester="):return f"requester {text.split('=', 1)[1]}"if text.startswith("profile="):return f"profile {text.split('=', 1)[1]}"return text.replace("_", " ")def audit_decision_explanation(services_module: Any, action: str, details: dict[str, Any]) -> str:s = services_moduleoutcome = audit_outcome(details)reason_code = audit_reason_code(details)if outcome == "blocked":intro = "Blocked"elif outcome == "allowed":intro = "Allowed"elif outcome == "dry_run":intro = "Dry run"elif outcome == "preview_required":intro = "Preview required"elif outcome == "failed":intro = "Failed"elif outcome == "observed":intro = "Recorded"else:intro = "Logged"reason_msg = s.AUDIT_REASON_MESSAGES.get(reason_code, "")if not reason_msg and reason_code:reason_msg = reason_code.replace("_", " ")chain = details.get("decision_chain")chain_tokens = chain if isinstance(chain, list) else []chain_hint = ""if chain_tokens:tail = [humanize_chain_token(item) for item in chain_tokens[-2:]]tail = [item for item in tail if item]if tail:chain_hint = f" Decision path: {' -> '.join(tail)}."action_label = str(action).replace("_", " ").strip() or "action"if reason_msg:return f"{intro}: {action_label} was {reason_msg}.{chain_hint}".strip()return f"{intro}: {action_label} was processed.{chain_hint}".strip()def audit(services_module: Any, action: str, details: dict[str, Any]) -> None:s = services_moduleenriched = {str(key): value for key, value in details.items()}if "requester_id" not in enriched:enriched["requester_id"] = s._identity_default_userif "requester_profile" not in enriched:enriched["requester_profile"] = s._identity_user_profiles.get(str(enriched["requester_id"]).strip().lower(),s._identity_default_profile,)if "requester_trusted" not in enriched:requester = str(enriched["requester_id"]).strip().lower()enriched["requester_trusted"] = requester in s._identity_trusted_users or str(enriched["requester_profile"]).strip().lower() == "trusted"if "speaker_verified" not in enriched:enriched["speaker_verified"] = Falseif "identity_source" not in enriched:enriched["identity_source"] = "default"if "decision_chain" not in enriched:enriched["decision_chain"] = ["identity_default_context"]if "decision_outcome" not in enriched:enriched["decision_outcome"] = audit_outcome(enriched)if "decision_reason" not in enriched:enriched["decision_reason"] = audit_reason_code(enriched)if "decision_explanation" not in enriched:enriched["decision_explanation"] = audit_decision_explanation(s, action, enriched)metadata_only = metadata_only_audit_details(s, action, enriched)redacted = redact_sensitive_for_audit(s, metadata_only)details_json = json.dumps(redacted, default=str)entry = {"timestamp": time.time(),"action": action,**redacted,}try:rotate_audit_log_if_needed(s)with open(s.AUDIT_LOG, "a") as handle:handle.write(encrypt_audit_line(s, entry) + "\n")except OSError as exc:s.log.warning("Failed to write audit log: %s", exc)s.log.info("AUDIT: %s — %s", action, details_json)def rotate_audit_log_if_needed(services_module: Any) -> None:s = services_moduleif s._audit_log_backups < 1:returntry:if s.AUDIT_LOG.exists() and s.AUDIT_LOG.stat().st_size >= s._audit_log_max_bytes:for idx in range(s._audit_log_backups, 0, -1):src = s.AUDIT_LOG.with_name(f"{s.AUDIT_LOG.name}.{idx}")dst = s.AUDIT_LOG.with_name(f"{s.AUDIT_LOG.name}.{idx + 1}")if src.exists():if idx == s._audit_log_backups:src.unlink(missing_ok=True)else:src.rename(dst)rotated = s.AUDIT_LOG.with_name(f"{s.AUDIT_LOG.name}.1")s.AUDIT_LOG.rename(rotated)except OSError as exc:s.log.warning("Failed to rotate audit log: %s", exc)def redact_sensitive_for_audit(services_module: Any, value: Any, *, key_hint: str | None = None) -> Any:s = services_moduleif key_hint:lowered = key_hint.strip().lower()if any(token in lowered for token in s.SENSITIVE_AUDIT_KEY_TOKENS):return s.AUDIT_REDACTEDif isinstance(value, dict):return {str(key): redact_sensitive_for_audit(s, item, key_hint=str(key))for key, item in value.items()}if isinstance(value, list):return [redact_sensitive_for_audit(s, item, key_hint=key_hint) for item in value]return valuedef metadata_only_audit_details(services_module: Any,action: str,details: dict[str, Any],) -> dict[str, Any]:s = services_moduleforbidden = s.AUDIT_METADATA_ONLY_FORBIDDEN_FIELDS.get(action)if not forbidden:return {str(key): value for key, value in details.items()}sanitized: dict[str, Any] = {}for key, value in details.items():key_text = str(key)if key_text.strip().lower() in forbidden:continuesanitized[key_text] = valuereturn sanitizeddef sanitize_inbound_headers(services_module: Any, headers: dict[str, Any] | None) -> dict[str, str]:s = services_modulesanitized: dict[str, str] = {}for key, value in (headers or {}).items():key_text = str(key)lowered = key_text.strip().lower()value_text = str(value)if any(token in lowered for token in s.INBOUND_REDACT_HEADER_TOKENS):sanitized[key_text] = s.AUDIT_REDACTEDcontinuesanitized[key_text] = value_textreturn sanitizeddef sanitize_inbound_payload(services_module: Any,value: Any,*,key_hint: str | None = None,depth: int = 0,) -> Any:s = services_moduleif depth > 8:return "<max_depth>"if key_hint:lowered = key_hint.strip().lower()if any(token in lowered for token in s.SENSITIVE_AUDIT_KEY_TOKENS):return s.AUDIT_REDACTEDif isinstance(value, dict):out: dict[str, Any] = {}for idx, (key, item) in enumerate(value.items()):if idx >= s.INBOUND_MAX_COLLECTION_ITEMS:out["<truncated_keys>"] = max(0, len(value) - s.INBOUND_MAX_COLLECTION_ITEMS)breakkey_text = str(key)out[key_text] = sanitize_inbound_payload(s, item, key_hint=key_text, depth=depth + 1)return outif isinstance(value, list):limited = value[: s.INBOUND_MAX_COLLECTION_ITEMS]out = [sanitize_inbound_payload(s, item, key_hint=key_hint, depth=depth + 1) for item in limited]if len(value) > s.INBOUND_MAX_COLLECTION_ITEMS:out.append(f"<truncated_items:{len(value) - s.INBOUND_MAX_COLLECTION_ITEMS}>")return outif isinstance(value, str):if len(value) > s.INBOUND_MAX_STRING_CHARS:return value[: s.INBOUND_MAX_STRING_CHARS] + "...<truncated>"return valueif isinstance(value, (int, float, bool)) or value is None:return valuetext = str(value)if len(text) > s.INBOUND_MAX_STRING_CHARS:return text[: s.INBOUND_MAX_STRING_CHARS] + "...<truncated>"return textdef contains_pii(services_module: Any, text: str) -> bool:s = services_modulesample = text.strip()if not sample:return Falsereturn any(pattern.search(sample) is not None for pattern in s._PII_PATTERNS)def audit_status(services_module: Any) -> dict[str, Any]:s = services_moduletry:exists = s.AUDIT_LOG.exists()size_bytes = s.AUDIT_LOG.stat().st_size if exists else 0except OSError:exists = Falsesize_bytes = 0backups = []for idx in range(1, s._audit_log_backups + 1):backup_path = s.AUDIT_LOG.with_name(f"{s.AUDIT_LOG.name}.{idx}")try:if backup_path.exists():backups.append({"path": str(backup_path),"size_bytes": int(backup_path.stat().st_size),})except OSError:continuereturn {"path": str(s.AUDIT_LOG),"exists": exists,"size_bytes": int(size_bytes),"max_bytes": int(s._audit_log_max_bytes),"encrypted": bool(s._audit_encryption_enabled and s._audit_fernet is not None),"encryption_configured": bool(s._audit_encryption_enabled),"backups": backups,"redaction_enabled": bool(s.SENSITIVE_AUDIT_KEY_TOKENS),"redaction_key_count": len(s.SENSITIVE_AUDIT_KEY_TOKENS),"metadata_only_actions": sorted(s.AUDIT_METADATA_ONLY_FORBIDDEN_FIELDS),}def prune_audit_file(services_module: Any, path: Any, *, cutoff_ts: float) -> int:s = services_moduleif not path.exists():return 0try:lines = path.read_text().splitlines()except OSError:return 0kept: list[str] = []removed = 0for line in lines:raw_line = line.strip()if not raw_line:continuepayload = decode_audit_line(s, raw_line)if not isinstance(payload, dict):removed += 1continueif payload.get("encrypted") is True and payload.get("error") in {"missing_encryption_key","invalid_token","invalid_payload",}:kept.append(raw_line)continuets = payload.get("timestamp")if isinstance(ts, (int, float)) and float(ts) >= cutoff_ts:kept.append(raw_line)else:removed += 1if removed <= 0:return 0try:if kept:path.write_text("\n".join(kept) + "\n")else:path.unlink(missing_ok=True)except OSError:return 0return removeddef apply_retention_policies(services_module: Any) -> None:s = services_modulenow = time.time()if s._memory is not None and s._memory_retention_days > 0.0:cutoff = now - (s._memory_retention_days * 86_400.0)try:s._memory.prune_retention(cutoff_ts=cutoff)except Exception:s.log.warning("Failed to apply memory retention policy", exc_info=True)if s._audit_retention_days > 0.0:cutoff = now - (s._audit_retention_days * 86_400.0)paths = [s.AUDIT_LOG] + [s.AUDIT_LOG.with_name(f"{s.AUDIT_LOG.name}.{idx}") for idx in range(1, s._audit_log_backups + 1)]for path in paths:removed = prune_audit_file(s, path, cutoff_ts=cutoff)if removed > 0:s.log.info("Applied audit retention policy to %s (removed=%d)", path, removed)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Compatibility wrapper for audit and redaction runtime helpers."""from __future__ import annotationsfrom jarvis.tools.services_audit_crypto_runtime import (configure_audit_encryption,decode_audit_line,encrypt_audit_line,)from jarvis.tools.services_audit_event_runtime import (audit,audit_decision_explanation,audit_outcome,audit_reason_code,humanize_chain_token,rotate_audit_log_if_needed,)from jarvis.tools.services_audit_retention_runtime import (apply_retention_policies,audit_status,prune_audit_file,)from jarvis.tools.services_audit_sanitize_runtime import (contains_pii,metadata_only_audit_details,redact_sensitive_for_audit,sanitize_inbound_headers,sanitize_inbound_payload,)__all__ = ["apply_retention_policies","audit","audit_decision_explanation","audit_outcome","audit_reason_code","audit_status","configure_audit_encryption","contains_pii","decode_audit_line","encrypt_audit_line","humanize_chain_token","metadata_only_audit_details","prune_audit_file","redact_sensitive_for_audit","rotate_audit_log_if_needed","sanitize_inbound_headers","sanitize_inbound_payload",]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101"""Audit redaction and inbound-sanitization helpers for services domains."""
from __future__ import annotations
from typing import Any
def redact_sensitive_for_audit(services_module: Any, value: Any, *, key_hint: str | None = None) -> Any: s = services_module if key_hint: lowered = key_hint.strip().lower() if any(token in lowered for token in s.SENSITIVE_AUDIT_KEY_TOKENS): return s.AUDIT_REDACTED if isinstance(value, dict): return { str(key): redact_sensitive_for_audit(s, item, key_hint=str(key)) for key, item in value.items() } if isinstance(value, list): return [redact_sensitive_for_audit(s, item, key_hint=key_hint) for item in value] return value
def metadata_only_audit_details( services_module: Any, action: str, details: dict[str, Any],) -> dict[str, Any]: s = services_module forbidden = s.AUDIT_METADATA_ONLY_FORBIDDEN_FIELDS.get(action) if not forbidden: return {str(key): value for key, value in details.items()} sanitized: dict[str, Any] = {} for key, value in details.items(): key_text = str(key) if key_text.strip().lower() in forbidden: continue sanitized[key_text] = value return sanitized
def sanitize_inbound_headers(services_module: Any, headers: dict[str, Any] | None) -> dict[str, str]: s = services_module sanitized: dict[str, str] = {} for key, value in (headers or {}).items(): key_text = str(key) lowered = key_text.strip().lower() value_text = str(value) if any(token in lowered for token in s.INBOUND_REDACT_HEADER_TOKENS): sanitized[key_text] = s.AUDIT_REDACTED continue sanitized[key_text] = value_text return sanitized
def sanitize_inbound_payload( services_module: Any, value: Any, *, key_hint: str | None = None, depth: int = 0,) -> Any: s = services_module if depth > 8: return "<max_depth>" if key_hint: lowered = key_hint.strip().lower() if any(token in lowered for token in s.SENSITIVE_AUDIT_KEY_TOKENS): return s.AUDIT_REDACTED if isinstance(value, dict): out: dict[str, Any] = {} for idx, (key, item) in enumerate(value.items()): if idx >= s.INBOUND_MAX_COLLECTION_ITEMS: out["<truncated_keys>"] = max(0, len(value) - s.INBOUND_MAX_COLLECTION_ITEMS) break key_text = str(key) out[key_text] = sanitize_inbound_payload(s, item, key_hint=key_text, depth=depth + 1) return out if isinstance(value, list): limited = value[: s.INBOUND_MAX_COLLECTION_ITEMS] out = [sanitize_inbound_payload(s, item, key_hint=key_hint, depth=depth + 1) for item in limited] if len(value) > s.INBOUND_MAX_COLLECTION_ITEMS: out.append(f"<truncated_items:{len(value) - s.INBOUND_MAX_COLLECTION_ITEMS}>") return out if isinstance(value, str): if len(value) > s.INBOUND_MAX_STRING_CHARS: return value[: s.INBOUND_MAX_STRING_CHARS] + "...<truncated>" return value if isinstance(value, (int, float, bool)) or value is None: return value text = str(value) if len(text) > s.INBOUND_MAX_STRING_CHARS: return text[: s.INBOUND_MAX_STRING_CHARS] + "...<truncated>" return text
def contains_pii(services_module: Any, text: str) -> bool: s = services_module sample = text.strip() if not sample: return False return any(pattern.search(sample) is not None for pattern in s._PII_PATTERNS)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491"""Runtime bind/bootstrap and expansion-state helpers for services."""from __future__ import annotationsimport jsonimport timefrom pathlib import Pathfrom typing import Anydef bind_runtime_state(services_module: Any, config: Any, memory_store: Any | None = None) -> None:s = services_modules._config = configs._memory = memory_stores._audit_log_max_bytes = int(config.audit_log_max_bytes)s._audit_log_backups = int(config.audit_log_backups)s._home_permission_profile = str(getattr(config, "home_permission_profile", "control")).strip().lower()if s._home_permission_profile not in {"readonly", "control"}:s._home_permission_profile = "control"s._home_require_confirm_execute = bool(getattr(config, "home_require_confirm_execute", False))s._home_conversation_enabled = bool(getattr(config, "home_conversation_enabled", False))s._home_conversation_permission_profile = str(getattr(config, "home_conversation_permission_profile", "readonly")).strip().lower()if s._home_conversation_permission_profile not in {"readonly", "control"}:s._home_conversation_permission_profile = "readonly"s._todoist_permission_profile = str(getattr(config, "todoist_permission_profile", "control")).strip().lower()if s._todoist_permission_profile not in {"readonly", "control"}:s._todoist_permission_profile = "control"s._notification_permission_profile = str(getattr(config, "notification_permission_profile", "allow")).strip().lower()if s._notification_permission_profile not in {"off", "allow"}:s._notification_permission_profile = "allow"s._nudge_policy = str(getattr(config, "nudge_policy", "adaptive")).strip().lower()if s._nudge_policy not in {"interrupt", "defer", "adaptive"}:s._nudge_policy = "adaptive"s._nudge_quiet_hours_start = str(getattr(config, "nudge_quiet_hours_start", "22:00")).strip()s._nudge_quiet_hours_end = str(getattr(config, "nudge_quiet_hours_end", "07:00")).strip()s._email_permission_profile = str(getattr(config, "email_permission_profile", "readonly")).strip().lower()if s._email_permission_profile not in {"readonly", "control"}:s._email_permission_profile = "readonly"s._todoist_timeout_sec = float(getattr(config, "todoist_timeout_sec", 10.0))s._pushover_timeout_sec = float(getattr(config, "pushover_timeout_sec", 10.0))s._email_smtp_host = str(getattr(config, "email_smtp_host", "")).strip()s._email_smtp_port = int(getattr(config, "email_smtp_port", 587))s._email_smtp_username = str(getattr(config, "email_smtp_username", "")).strip()s._email_smtp_password = str(getattr(config, "email_smtp_password", "")).strip()s._email_from = str(getattr(config, "email_from", "")).strip()s._email_default_to = str(getattr(config, "email_default_to", "")).strip()s._email_use_tls = bool(getattr(config, "email_use_tls", True))s._email_timeout_sec = float(getattr(config, "email_timeout_sec", 10.0))s._notion_api_token = str(getattr(config, "notion_api_token", "")).strip()s._notion_database_id = str(getattr(config, "notion_database_id", "")).strip()s._weather_units = str(getattr(config, "weather_units", "metric")).strip().lower()if s._weather_units not in {"metric", "imperial"}:s._weather_units = "metric"s._weather_timeout_sec = float(getattr(config, "weather_timeout_sec", 8.0))s._webhook_allowlist = [str(host).strip().lower()for host in getattr(config, "webhook_allowlist", [])if str(host).strip()]s._webhook_auth_token = str(getattr(config, "webhook_auth_token", "")).strip()s._webhook_timeout_sec = float(getattr(config, "webhook_timeout_sec", 8.0))s._turn_timeout_listen_sec = float(getattr(config, "watchdog_listening_timeout_sec", 30.0))s._turn_timeout_think_sec = float(getattr(config, "watchdog_thinking_timeout_sec", 60.0))s._turn_timeout_speak_sec = float(getattr(config, "watchdog_speaking_timeout_sec", 45.0))s._turn_timeout_act_sec = float(getattr(config, "turn_timeout_act_sec", 30.0))s._slack_webhook_url = str(getattr(config, "slack_webhook_url", "")).strip()s._discord_webhook_url = str(getattr(config, "discord_webhook_url", "")).strip()s._identity_enforcement_enabled = bool(getattr(config, "identity_enforcement_enabled", False))s._identity_default_user = str(getattr(config, "identity_default_user", "owner")).strip().lower() or "owner"s._identity_default_profile = str(getattr(config, "identity_default_profile", "control")).strip().lower()if s._identity_default_profile not in {"deny", "readonly", "control", "trusted"}:s._identity_default_profile = "control"raw_profiles = getattr(config, "identity_user_profiles", {}) or {}if isinstance(raw_profiles, dict):s._identity_user_profiles = {str(user).strip().lower(): str(profile).strip().lower()for user, profile in raw_profiles.items()if str(user).strip()and str(profile).strip().lower() in {"deny", "readonly", "control", "trusted"}}else:s._identity_user_profiles = {}raw_trusted_users = getattr(config, "identity_trusted_users", []) or []s._identity_trusted_users = {str(user).strip().lower() for user in raw_trusted_users if str(user).strip()}s._identity_require_approval = bool(getattr(config, "identity_require_approval", True))s._identity_approval_code = str(getattr(config, "identity_approval_code", "")).strip()s._plan_preview_require_ack = bool(getattr(config, "plan_preview_require_ack", False))s._safe_mode_enabled = bool(getattr(config, "safe_mode_enabled", False))s._memory_retention_days = max(0.0, float(getattr(config, "memory_retention_days", 0.0)))s._audit_retention_days = max(0.0, float(getattr(config, "audit_retention_days", 0.0)))s._memory_pii_guardrails_enabled = bool(getattr(config, "memory_pii_guardrails_enabled", True))s._audit_encryption_enabled = bool(getattr(config, "audit_encryption_enabled", False))s._data_encryption_key = str(getattr(config, "data_encryption_key", "")).strip()s._recovery_journal_path = Path(str(getattr(config, "recovery_journal_path", str(s.DEFAULT_RECOVERY_JOURNAL)))).expanduser()s._dead_letter_queue_path = Path(str(getattr(config, "dead_letter_queue_path", str(s.DEFAULT_DEAD_LETTER_QUEUE)))).expanduser()s._expansion_state_path = Path(str(getattr(config, "expansion_state_path", str(s.DEFAULT_EXPANSION_STATE)))).expanduser()s._release_channel_config_path = Path(str(getattr(config, "release_channel_config_path", str(s.DEFAULT_RELEASE_CHANNEL_CONFIG)))).expanduser()s._quality_report_dir = Path(str(getattr(config, "quality_report_dir", str(s.QUALITY_REPORT_DIR_DEFAULT)))).expanduser()s._notes_capture_dir = Path(str(getattr(config, "notes_capture_dir", str(s.NOTES_CAPTURE_DIR_DEFAULT)))).expanduser()if not s._release_channel_config_path.is_absolute():s._release_channel_config_path = (Path.cwd() / s._release_channel_config_path).resolve()if not s._quality_report_dir.is_absolute():s._quality_report_dir = (Path.cwd() / s._quality_report_dir).resolve()if not s._notes_capture_dir.is_absolute():s._notes_capture_dir = (Path.cwd() / s._notes_capture_dir).resolve()s._configure_audit_encryption(enabled=s._audit_encryption_enabled, key=s._data_encryption_key)_reset_runtime_state(s)for integration in sorted(set(s.INTEGRATION_TOOL_MAP.values())):s._ensure_circuit_breaker_state(integration)load_expansion_state(s)s._recovery_reconcile_interrupted()s._load_timers_from_store()s._load_reminders_from_store()s._tool_allowlist = list(config.tool_allowlist)s._tool_denylist = list(config.tool_denylist)s.AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True)s._apply_retention_policies()def _reset_runtime_state(services_module: Any) -> None:s = services_modules._action_last_seen.clear()s._ha_state_cache.clear()s._timers.clear()s._timer_id_seq = 1s._reminders.clear()s._reminder_id_seq = 1s._email_history.clear()s._pending_plan_previews.clear()s._runtime_voice_state.clear()s._runtime_observability_state.clear()s._runtime_skills_state.clear()s._integration_circuit_breakers.clear()s._proactive_state["pending_follow_through"] = []s._proactive_state["digest_snoozed_until"] = 0.0s._proactive_state["last_briefing_at"] = 0.0s._proactive_state["last_digest_at"] = 0.0s._proactive_state["nudge_decisions_total"] = 0s._proactive_state["nudge_interrupt_total"] = 0s._proactive_state["nudge_notify_total"] = 0s._proactive_state["nudge_defer_total"] = 0s._proactive_state["nudge_deduped_total"] = 0s._proactive_state["last_nudge_decision_at"] = 0.0s._proactive_state["last_nudge_dedupe_at"] = 0.0s._proactive_state["nudge_recent_dispatches"] = []s._memory_partition_overlays.clear()s._memory_quality_last.clear()s._identity_trust_policies.clear()s._guest_sessions.clear()s._household_profiles.clear()s._home_area_policies.clear()s._home_task_runs.clear()s._home_automation_drafts.clear()s._home_automation_applied.clear()s._skill_quotas.clear()s._planner_task_graphs.clear()s._deferred_actions.clear()s._autonomy_checkpoints.clear()s._autonomy_cycle_history.clear()s._quality_reports.clear()s._micro_expression_library.clear()s._gaze_calibrations.clear()s._gesture_envelopes.clear()s._privacy_posture["state"] = "normal"s._privacy_posture["reason"] = "startup"s._privacy_posture["updated_at"] = 0.0s._motion_safety_envelope["updated_at"] = 0.0s._release_channel_state["active_channel"] = "dev"s._release_channel_state["last_check_at"] = 0.0s._release_channel_state["last_check_channel"] = ""s._release_channel_state["last_check_passed"] = Falses._release_channel_state["migration_checks"] = []s._home_task_seq = 1s._home_automation_seq = 1s._planner_task_seq = 1s._deferred_action_seq = 1def quality_reports_snapshot(services_module: Any, *, limit: int = 10) -> list[dict[str, Any]]:s = services_moduleif not s._quality_reports:return []capped = s._as_int(limit, 10, minimum=1, maximum=50)return [dict(item) for item in s._quality_reports[-capped:]][::-1]def append_quality_report(services_module: Any, report: dict[str, Any]) -> None:s = services_modules._quality_reports.append({str(key): value for key, value in report.items()})if len(s._quality_reports) > s.CACHED_QUALITY_REPORT_MAX:del s._quality_reports[: len(s._quality_reports) - s.CACHED_QUALITY_REPORT_MAX]s._persist_expansion_state()def json_safe_clone(value: Any) -> Any:if isinstance(value, dict):return {str(key): json_safe_clone(item) for key, item in value.items()}if isinstance(value, list):return [json_safe_clone(item) for item in value]if value is None or isinstance(value, (str, int, float, bool)):return valuereturn str(value)def replace_state_dict(services_module: Any, target: dict[str, Any], source: Any) -> None:s = services_moduletarget.clear()if not isinstance(source, dict):returntarget.update({str(key): s._json_safe_clone(value) for key, value in source.items()})def expansion_state_payload(services_module: Any) -> dict[str, Any]:s = services_modulereturn {"version": 1,"saved_at": time.time(),"proactive_state": s._json_safe_clone(s._proactive_state),"memory_partition_overlays": s._json_safe_clone(s._memory_partition_overlays),"memory_quality_last": s._json_safe_clone(s._memory_quality_last),"identity_trust_policies": s._json_safe_clone(s._identity_trust_policies),"guest_sessions": s._json_safe_clone(s._guest_sessions),"household_profiles": s._json_safe_clone(s._household_profiles),"home_area_policies": s._json_safe_clone(s._home_area_policies),"home_task_runs": s._json_safe_clone(s._home_task_runs),"home_task_seq": int(s._home_task_seq),"home_automation_drafts": s._json_safe_clone(s._home_automation_drafts),"home_automation_applied": s._json_safe_clone(s._home_automation_applied),"home_automation_seq": int(s._home_automation_seq),"skill_quotas": s._json_safe_clone(s._skill_quotas),"planner_task_graphs": s._json_safe_clone(s._planner_task_graphs),"planner_task_seq": int(s._planner_task_seq),"deferred_actions": s._json_safe_clone(s._deferred_actions),"deferred_action_seq": int(s._deferred_action_seq),"autonomy_checkpoints": s._json_safe_clone(s._autonomy_checkpoints),"autonomy_cycle_history": s._json_safe_clone(s._autonomy_cycle_history[-s.AUTONOMY_CYCLE_HISTORY_MAX :]),"quality_reports": s._json_safe_clone(s._quality_reports[-s.CACHED_QUALITY_REPORT_MAX :]),"micro_expression_library": s._json_safe_clone(s._micro_expression_library),"gaze_calibrations": s._json_safe_clone(s._gaze_calibrations),"gesture_envelopes": s._json_safe_clone(s._gesture_envelopes),"privacy_posture": s._json_safe_clone(s._privacy_posture),"motion_safety_envelope": s._json_safe_clone(s._motion_safety_envelope),"release_channel_state": s._json_safe_clone(s._release_channel_state),}def persist_expansion_state(services_module: Any) -> None:s = services_modulepath = s._expansion_state_pathpayload = expansion_state_payload(s)try:path.parent.mkdir(parents=True, exist_ok=True)path.write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8")except OSError:s.log.warning("Failed to persist expansion state", exc_info=True)def load_expansion_state(services_module: Any) -> None:s = services_modulepath = s._expansion_state_pathif not path.exists():returntry:payload = json.loads(path.read_text(encoding="utf-8"))except Exception:s.log.warning("Failed to load expansion state", exc_info=True)returnif not isinstance(payload, dict):returnproactive = payload.get("proactive_state")if isinstance(proactive, dict):pending = proactive.get("pending_follow_through")s._proactive_state["pending_follow_through"] = ([s._json_safe_clone(row) for row in pending if isinstance(row, dict)]if isinstance(pending, list)else [])s._proactive_state["digest_snoozed_until"] = s._as_float(proactive.get("digest_snoozed_until", 0.0),0.0,minimum=0.0,)s._proactive_state["last_briefing_at"] = s._as_float(proactive.get("last_briefing_at", 0.0),0.0,minimum=0.0,)s._proactive_state["last_digest_at"] = s._as_float(proactive.get("last_digest_at", 0.0),0.0,minimum=0.0,)s._proactive_state["nudge_decisions_total"] = s._as_int(proactive.get("nudge_decisions_total", 0),0,minimum=0,)s._proactive_state["nudge_interrupt_total"] = s._as_int(proactive.get("nudge_interrupt_total", 0),0,minimum=0,)s._proactive_state["nudge_notify_total"] = s._as_int(proactive.get("nudge_notify_total", 0),0,minimum=0,)s._proactive_state["nudge_defer_total"] = s._as_int(proactive.get("nudge_defer_total", 0),0,minimum=0,)s._proactive_state["nudge_deduped_total"] = s._as_int(proactive.get("nudge_deduped_total", 0),0,minimum=0,)s._proactive_state["last_nudge_decision_at"] = s._as_float(proactive.get("last_nudge_decision_at", 0.0),0.0,minimum=0.0,)s._proactive_state["last_nudge_dedupe_at"] = s._as_float(proactive.get("last_nudge_dedupe_at", 0.0),0.0,minimum=0.0,)recent_dispatches = proactive.get("nudge_recent_dispatches")s._proactive_state["nudge_recent_dispatches"] = []if isinstance(recent_dispatches, list):for row in recent_dispatches[-s.NUDGE_RECENT_DISPATCH_MAX :]:if not isinstance(row, dict):continuefingerprint = str(row.get("fingerprint", "")).strip()if not fingerprint:continuedispatched_at = s._as_float(row.get("dispatched_at", 0.0), 0.0, minimum=0.0)s._proactive_state["nudge_recent_dispatches"].append({"fingerprint": fingerprint, "dispatched_at": dispatched_at})replace_state_dict(s, s._memory_partition_overlays, payload.get("memory_partition_overlays"))replace_state_dict(s, s._memory_quality_last, payload.get("memory_quality_last"))replace_state_dict(s, s._identity_trust_policies, payload.get("identity_trust_policies"))replace_state_dict(s, s._household_profiles, payload.get("household_profiles"))replace_state_dict(s, s._home_area_policies, payload.get("home_area_policies"))replace_state_dict(s, s._home_task_runs, payload.get("home_task_runs"))replace_state_dict(s, s._home_automation_drafts, payload.get("home_automation_drafts"))replace_state_dict(s, s._home_automation_applied, payload.get("home_automation_applied"))replace_state_dict(s, s._skill_quotas, payload.get("skill_quotas"))replace_state_dict(s, s._planner_task_graphs, payload.get("planner_task_graphs"))replace_state_dict(s, s._deferred_actions, payload.get("deferred_actions"))replace_state_dict(s, s._autonomy_checkpoints, payload.get("autonomy_checkpoints"))replace_state_dict(s, s._micro_expression_library, payload.get("micro_expression_library"))replace_state_dict(s, s._gaze_calibrations, payload.get("gaze_calibrations"))replace_state_dict(s, s._gesture_envelopes, payload.get("gesture_envelopes"))autonomy_history = payload.get("autonomy_cycle_history")s._autonomy_cycle_history.clear()if isinstance(autonomy_history, list):for row in autonomy_history[-s.AUTONOMY_CYCLE_HISTORY_MAX :]:if isinstance(row, dict):s._autonomy_cycle_history.append({str(key): s._json_safe_clone(value) for key, value in row.items()})s._guest_sessions.clear()guest_sessions = payload.get("guest_sessions")if isinstance(guest_sessions, dict):now = time.time()for raw_token, raw_row in guest_sessions.items():token = str(raw_token).strip()if not token or not isinstance(raw_row, dict):continueexpires_at = s._as_float(raw_row.get("expires_at", 0.0), 0.0, minimum=0.0)if expires_at <= now:continueissued_at = s._as_float(raw_row.get("issued_at", 0.0), 0.0, minimum=0.0)guest_id = str(raw_row.get("guest_id", "guest")).strip().lower() or "guest"capabilities = sorted(set(s._as_str_list(raw_row.get("capabilities"), lower=True)))s._guest_sessions[token] = {"token": token,"guest_id": guest_id,"capabilities": capabilities,"issued_at": issued_at,"expires_at": expires_at,}quality_rows = payload.get("quality_reports")s._quality_reports.clear()if isinstance(quality_rows, list):for row in quality_rows[-s.CACHED_QUALITY_REPORT_MAX :]:if isinstance(row, dict):s._quality_reports.append({str(key): s._json_safe_clone(value) for key, value in row.items()})privacy_posture = payload.get("privacy_posture")if isinstance(privacy_posture, dict):s._privacy_posture["state"] = str(privacy_posture.get("state", "normal")).strip().lower() or "normal"s._privacy_posture["reason"] = str(privacy_posture.get("reason", "startup")).strip() or "startup"s._privacy_posture["updated_at"] = s._as_float(privacy_posture.get("updated_at", 0.0),0.0,minimum=0.0,)motion_envelope = payload.get("motion_safety_envelope")if isinstance(motion_envelope, dict):s._motion_safety_envelope["proximity_limit_cm"] = s._as_float(motion_envelope.get("proximity_limit_cm",s._motion_safety_envelope.get("proximity_limit_cm", 35.0),),s._as_float(s._motion_safety_envelope.get("proximity_limit_cm", 35.0), 35.0),minimum=5.0,maximum=300.0,)s._motion_safety_envelope["max_yaw_deg"] = s._as_float(motion_envelope.get("max_yaw_deg", s._motion_safety_envelope.get("max_yaw_deg", 45.0)),s._as_float(s._motion_safety_envelope.get("max_yaw_deg", 45.0), 45.0),minimum=0.0,maximum=180.0,)s._motion_safety_envelope["max_pitch_deg"] = s._as_float(motion_envelope.get("max_pitch_deg", s._motion_safety_envelope.get("max_pitch_deg", 20.0)),s._as_float(s._motion_safety_envelope.get("max_pitch_deg", 20.0), 20.0),minimum=0.0,maximum=90.0,)s._motion_safety_envelope["max_roll_deg"] = s._as_float(motion_envelope.get("max_roll_deg", s._motion_safety_envelope.get("max_roll_deg", 15.0)),s._as_float(s._motion_safety_envelope.get("max_roll_deg", 15.0), 15.0),minimum=0.0,maximum=90.0,)s._motion_safety_envelope["hardware_state"] = (str(motion_envelope.get("hardware_state", "normal")).strip().lower() or "normal")s._motion_safety_envelope["updated_at"] = s._as_float(motion_envelope.get("updated_at", 0.0),0.0,minimum=0.0,)release_state = payload.get("release_channel_state")if isinstance(release_state, dict):channel = str(release_state.get("active_channel", "dev")).strip().lower()if channel not in s.RELEASE_CHANNELS:channel = "dev"s._release_channel_state["active_channel"] = channels._release_channel_state["last_check_at"] = s._as_float(release_state.get("last_check_at", 0.0),0.0,minimum=0.0,)s._release_channel_state["last_check_channel"] = (str(release_state.get("last_check_channel", channel)).strip().lower() or channel)s._release_channel_state["last_check_passed"] = bool(release_state.get("last_check_passed", False))migration_checks = release_state.get("migration_checks")s._release_channel_state["migration_checks"] = ([s._json_safe_clone(row) for row in migration_checks if isinstance(row, dict)]if isinstance(migration_checks, list)else [])s._home_task_seq = s._as_int(payload.get("home_task_seq", 1), 1, minimum=1)s._home_automation_seq = s._as_int(payload.get("home_automation_seq", 1), 1, minimum=1)s._planner_task_seq = s._as_int(payload.get("planner_task_seq", 1), 1, minimum=1)s._deferred_action_seq = s._as_int(payload.get("deferred_action_seq", 1), 1, minimum=1)s._prune_guest_sessions()123456789101112131415161718192021222324252627"""Compatibility wrapper for runtime bind/bootstrap and expansion-state helpers."""from __future__ import annotationsfrom jarvis.tools.services_runtime_state_bind import bind_runtime_statefrom jarvis.tools.services_runtime_state_persistence import (expansion_state_payload,json_safe_clone,load_expansion_state,persist_expansion_state,replace_state_dict,)from jarvis.tools.services_runtime_state_reports import (append_quality_report,quality_reports_snapshot,)__all__ = ["append_quality_report","bind_runtime_state","expansion_state_payload","json_safe_clone","load_expansion_state","persist_expansion_state","quality_reports_snapshot","replace_state_dict",]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194"""Runtime state bind/bootstrap helpers for services."""
from __future__ import annotations
from pathlib import Pathfrom typing import Any
from jarvis.tools.services_runtime_state_persistence import load_expansion_state
def bind_runtime_state(services_module: Any, config: Any, memory_store: Any | None = None) -> None: s = services_module s._config = config s._memory = memory_store s._audit_log_max_bytes = int(config.audit_log_max_bytes) s._audit_log_backups = int(config.audit_log_backups) s._home_permission_profile = str(getattr(config, "home_permission_profile", "control")).strip().lower() if s._home_permission_profile not in {"readonly", "control"}: s._home_permission_profile = "control" s._home_require_confirm_execute = bool(getattr(config, "home_require_confirm_execute", False)) s._home_conversation_enabled = bool(getattr(config, "home_conversation_enabled", False)) s._home_conversation_permission_profile = str( getattr(config, "home_conversation_permission_profile", "readonly") ).strip().lower() if s._home_conversation_permission_profile not in {"readonly", "control"}: s._home_conversation_permission_profile = "readonly" s._todoist_permission_profile = str(getattr(config, "todoist_permission_profile", "control")).strip().lower() if s._todoist_permission_profile not in {"readonly", "control"}: s._todoist_permission_profile = "control" s._notification_permission_profile = str( getattr(config, "notification_permission_profile", "allow") ).strip().lower() if s._notification_permission_profile not in {"off", "allow"}: s._notification_permission_profile = "allow" s._nudge_policy = str(getattr(config, "nudge_policy", "adaptive")).strip().lower() if s._nudge_policy not in {"interrupt", "defer", "adaptive"}: s._nudge_policy = "adaptive" s._nudge_quiet_hours_start = str(getattr(config, "nudge_quiet_hours_start", "22:00")).strip() s._nudge_quiet_hours_end = str(getattr(config, "nudge_quiet_hours_end", "07:00")).strip() s._email_permission_profile = str(getattr(config, "email_permission_profile", "readonly")).strip().lower() if s._email_permission_profile not in {"readonly", "control"}: s._email_permission_profile = "readonly" s._todoist_timeout_sec = float(getattr(config, "todoist_timeout_sec", 10.0)) s._pushover_timeout_sec = float(getattr(config, "pushover_timeout_sec", 10.0)) s._email_smtp_host = str(getattr(config, "email_smtp_host", "")).strip() s._email_smtp_port = int(getattr(config, "email_smtp_port", 587)) s._email_smtp_username = str(getattr(config, "email_smtp_username", "")).strip() s._email_smtp_password = str(getattr(config, "email_smtp_password", "")).strip() s._email_from = str(getattr(config, "email_from", "")).strip() s._email_default_to = str(getattr(config, "email_default_to", "")).strip() s._email_use_tls = bool(getattr(config, "email_use_tls", True)) s._email_timeout_sec = float(getattr(config, "email_timeout_sec", 10.0)) s._notion_api_token = str(getattr(config, "notion_api_token", "")).strip() s._notion_database_id = str(getattr(config, "notion_database_id", "")).strip() s._weather_units = str(getattr(config, "weather_units", "metric")).strip().lower() if s._weather_units not in {"metric", "imperial"}: s._weather_units = "metric" s._weather_timeout_sec = float(getattr(config, "weather_timeout_sec", 8.0)) s._webhook_allowlist = [ str(host).strip().lower() for host in getattr(config, "webhook_allowlist", []) if str(host).strip() ] s._webhook_auth_token = str(getattr(config, "webhook_auth_token", "")).strip() s._webhook_timeout_sec = float(getattr(config, "webhook_timeout_sec", 8.0)) s._turn_timeout_listen_sec = float(getattr(config, "watchdog_listening_timeout_sec", 30.0)) s._turn_timeout_think_sec = float(getattr(config, "watchdog_thinking_timeout_sec", 60.0)) s._turn_timeout_speak_sec = float(getattr(config, "watchdog_speaking_timeout_sec", 45.0)) s._turn_timeout_act_sec = float(getattr(config, "turn_timeout_act_sec", 30.0)) s._slack_webhook_url = str(getattr(config, "slack_webhook_url", "")).strip() s._discord_webhook_url = str(getattr(config, "discord_webhook_url", "")).strip() s._identity_enforcement_enabled = bool(getattr(config, "identity_enforcement_enabled", False)) s._identity_default_user = str(getattr(config, "identity_default_user", "owner")).strip().lower() or "owner" s._identity_default_profile = str(getattr(config, "identity_default_profile", "control")).strip().lower() if s._identity_default_profile not in {"deny", "readonly", "control", "trusted"}: s._identity_default_profile = "control" raw_profiles = getattr(config, "identity_user_profiles", {}) or {} if isinstance(raw_profiles, dict): s._identity_user_profiles = { str(user).strip().lower(): str(profile).strip().lower() for user, profile in raw_profiles.items() if str(user).strip() and str(profile).strip().lower() in {"deny", "readonly", "control", "trusted"} } else: s._identity_user_profiles = {} raw_trusted_users = getattr(config, "identity_trusted_users", []) or [] s._identity_trusted_users = { str(user).strip().lower() for user in raw_trusted_users if str(user).strip() } s._identity_require_approval = bool(getattr(config, "identity_require_approval", True)) s._identity_approval_code = str(getattr(config, "identity_approval_code", "")).strip() s._plan_preview_require_ack = bool(getattr(config, "plan_preview_require_ack", False)) s._safe_mode_enabled = bool(getattr(config, "safe_mode_enabled", False)) s._memory_retention_days = max(0.0, float(getattr(config, "memory_retention_days", 0.0))) s._audit_retention_days = max(0.0, float(getattr(config, "audit_retention_days", 0.0))) s._memory_pii_guardrails_enabled = bool(getattr(config, "memory_pii_guardrails_enabled", True)) s._audit_encryption_enabled = bool(getattr(config, "audit_encryption_enabled", False)) s._data_encryption_key = str(getattr(config, "data_encryption_key", "")).strip() s._recovery_journal_path = Path( str(getattr(config, "recovery_journal_path", str(s.DEFAULT_RECOVERY_JOURNAL))) ).expanduser() s._dead_letter_queue_path = Path( str(getattr(config, "dead_letter_queue_path", str(s.DEFAULT_DEAD_LETTER_QUEUE))) ).expanduser() s._expansion_state_path = Path( str(getattr(config, "expansion_state_path", str(s.DEFAULT_EXPANSION_STATE))) ).expanduser() s._release_channel_config_path = Path( str(getattr(config, "release_channel_config_path", str(s.DEFAULT_RELEASE_CHANNEL_CONFIG))) ).expanduser() s._quality_report_dir = Path( str(getattr(config, "quality_report_dir", str(s.QUALITY_REPORT_DIR_DEFAULT))) ).expanduser() s._notes_capture_dir = Path( str(getattr(config, "notes_capture_dir", str(s.NOTES_CAPTURE_DIR_DEFAULT))) ).expanduser() if not s._release_channel_config_path.is_absolute(): s._release_channel_config_path = (Path.cwd() / s._release_channel_config_path).resolve() if not s._quality_report_dir.is_absolute(): s._quality_report_dir = (Path.cwd() / s._quality_report_dir).resolve() if not s._notes_capture_dir.is_absolute(): s._notes_capture_dir = (Path.cwd() / s._notes_capture_dir).resolve() s._configure_audit_encryption(enabled=s._audit_encryption_enabled, key=s._data_encryption_key) _reset_runtime_state(s) for integration in sorted(set(s.INTEGRATION_TOOL_MAP.values())): s._ensure_circuit_breaker_state(integration) load_expansion_state(s) s._recovery_reconcile_interrupted() s._load_timers_from_store() s._load_reminders_from_store() s._tool_allowlist = list(config.tool_allowlist) s._tool_denylist = list(config.tool_denylist) s.AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True) s._apply_retention_policies()
def _reset_runtime_state(services_module: Any) -> None: s = services_module s._action_last_seen.clear() s._ha_state_cache.clear() s._timers.clear() s._timer_id_seq = 1 s._reminders.clear() s._reminder_id_seq = 1 s._email_history.clear() s._pending_plan_previews.clear() s._runtime_voice_state.clear() s._runtime_observability_state.clear() s._runtime_skills_state.clear() s._integration_circuit_breakers.clear() s._proactive_state["pending_follow_through"] = [] s._proactive_state["digest_snoozed_until"] = 0.0 s._proactive_state["last_briefing_at"] = 0.0 s._proactive_state["last_digest_at"] = 0.0 s._proactive_state["nudge_decisions_total"] = 0 s._proactive_state["nudge_interrupt_total"] = 0 s._proactive_state["nudge_notify_total"] = 0 s._proactive_state["nudge_defer_total"] = 0 s._proactive_state["nudge_deduped_total"] = 0 s._proactive_state["last_nudge_decision_at"] = 0.0 s._proactive_state["last_nudge_dedupe_at"] = 0.0 s._proactive_state["nudge_recent_dispatches"] = [] s._memory_partition_overlays.clear() s._memory_quality_last.clear() s._identity_trust_policies.clear() s._guest_sessions.clear() s._household_profiles.clear() s._home_area_policies.clear() s._home_task_runs.clear() s._home_automation_drafts.clear() s._home_automation_applied.clear() s._skill_quotas.clear() s._planner_task_graphs.clear() s._deferred_actions.clear() s._autonomy_checkpoints.clear() s._autonomy_cycle_history.clear() s._quality_reports.clear() s._micro_expression_library.clear() s._gaze_calibrations.clear() s._gesture_envelopes.clear() s._privacy_posture["state"] = "normal" s._privacy_posture["reason"] = "startup" s._privacy_posture["updated_at"] = 0.0 s._motion_safety_envelope["updated_at"] = 0.0 s._release_channel_state["active_channel"] = "dev" s._release_channel_state["last_check_at"] = 0.0 s._release_channel_state["last_check_channel"] = "" s._release_channel_state["last_check_passed"] = False s._release_channel_state["migration_checks"] = [] s._home_task_seq = 1 s._home_automation_seq = 1 s._planner_task_seq = 1 s._deferred_action_seq = 1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287"""Runtime state serialization and persistence helpers for services."""
from __future__ import annotations
import jsonimport timefrom typing import Any
def json_safe_clone(value: Any) -> Any: if isinstance(value, dict): return {str(key): json_safe_clone(item) for key, item in value.items()} if isinstance(value, list): return [json_safe_clone(item) for item in value] if value is None or isinstance(value, (str, int, float, bool)): return value return str(value)
def replace_state_dict(services_module: Any, target: dict[str, Any], source: Any) -> None: s = services_module target.clear() if not isinstance(source, dict): return target.update({str(key): s._json_safe_clone(value) for key, value in source.items()})
def expansion_state_payload(services_module: Any) -> dict[str, Any]: s = services_module return { "version": 1, "saved_at": time.time(), "proactive_state": s._json_safe_clone(s._proactive_state), "memory_partition_overlays": s._json_safe_clone(s._memory_partition_overlays), "memory_quality_last": s._json_safe_clone(s._memory_quality_last), "identity_trust_policies": s._json_safe_clone(s._identity_trust_policies), "guest_sessions": s._json_safe_clone(s._guest_sessions), "household_profiles": s._json_safe_clone(s._household_profiles), "home_area_policies": s._json_safe_clone(s._home_area_policies), "home_task_runs": s._json_safe_clone(s._home_task_runs), "home_task_seq": int(s._home_task_seq), "home_automation_drafts": s._json_safe_clone(s._home_automation_drafts), "home_automation_applied": s._json_safe_clone(s._home_automation_applied), "home_automation_seq": int(s._home_automation_seq), "skill_quotas": s._json_safe_clone(s._skill_quotas), "planner_task_graphs": s._json_safe_clone(s._planner_task_graphs), "planner_task_seq": int(s._planner_task_seq), "deferred_actions": s._json_safe_clone(s._deferred_actions), "deferred_action_seq": int(s._deferred_action_seq), "autonomy_checkpoints": s._json_safe_clone(s._autonomy_checkpoints), "autonomy_cycle_history": s._json_safe_clone( s._autonomy_cycle_history[-s.AUTONOMY_CYCLE_HISTORY_MAX :] ), "quality_reports": s._json_safe_clone(s._quality_reports[-s.CACHED_QUALITY_REPORT_MAX :]), "micro_expression_library": s._json_safe_clone(s._micro_expression_library), "gaze_calibrations": s._json_safe_clone(s._gaze_calibrations), "gesture_envelopes": s._json_safe_clone(s._gesture_envelopes), "privacy_posture": s._json_safe_clone(s._privacy_posture), "motion_safety_envelope": s._json_safe_clone(s._motion_safety_envelope), "release_channel_state": s._json_safe_clone(s._release_channel_state), }
def persist_expansion_state(services_module: Any) -> None: s = services_module path = s._expansion_state_path payload = expansion_state_payload(s) try: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8") except OSError: s.log.warning("Failed to persist expansion state", exc_info=True)
def load_expansion_state(services_module: Any) -> None: s = services_module path = s._expansion_state_path if not path.exists(): return try: payload = json.loads(path.read_text(encoding="utf-8")) except Exception: s.log.warning("Failed to load expansion state", exc_info=True) return if not isinstance(payload, dict): return
proactive = payload.get("proactive_state") if isinstance(proactive, dict): pending = proactive.get("pending_follow_through") s._proactive_state["pending_follow_through"] = ( [s._json_safe_clone(row) for row in pending if isinstance(row, dict)] if isinstance(pending, list) else [] ) s._proactive_state["digest_snoozed_until"] = s._as_float( proactive.get("digest_snoozed_until", 0.0), 0.0, minimum=0.0, ) s._proactive_state["last_briefing_at"] = s._as_float( proactive.get("last_briefing_at", 0.0), 0.0, minimum=0.0, ) s._proactive_state["last_digest_at"] = s._as_float( proactive.get("last_digest_at", 0.0), 0.0, minimum=0.0, ) s._proactive_state["nudge_decisions_total"] = s._as_int( proactive.get("nudge_decisions_total", 0), 0, minimum=0, ) s._proactive_state["nudge_interrupt_total"] = s._as_int( proactive.get("nudge_interrupt_total", 0), 0, minimum=0, ) s._proactive_state["nudge_notify_total"] = s._as_int( proactive.get("nudge_notify_total", 0), 0, minimum=0, ) s._proactive_state["nudge_defer_total"] = s._as_int( proactive.get("nudge_defer_total", 0), 0, minimum=0, ) s._proactive_state["nudge_deduped_total"] = s._as_int( proactive.get("nudge_deduped_total", 0), 0, minimum=0, ) s._proactive_state["last_nudge_decision_at"] = s._as_float( proactive.get("last_nudge_decision_at", 0.0), 0.0, minimum=0.0, ) s._proactive_state["last_nudge_dedupe_at"] = s._as_float( proactive.get("last_nudge_dedupe_at", 0.0), 0.0, minimum=0.0, ) recent_dispatches = proactive.get("nudge_recent_dispatches") s._proactive_state["nudge_recent_dispatches"] = [] if isinstance(recent_dispatches, list): for row in recent_dispatches[-s.NUDGE_RECENT_DISPATCH_MAX :]: if not isinstance(row, dict): continue fingerprint = str(row.get("fingerprint", "")).strip() if not fingerprint: continue dispatched_at = s._as_float(row.get("dispatched_at", 0.0), 0.0, minimum=0.0) s._proactive_state["nudge_recent_dispatches"].append( {"fingerprint": fingerprint, "dispatched_at": dispatched_at} )
replace_state_dict(s, s._memory_partition_overlays, payload.get("memory_partition_overlays")) replace_state_dict(s, s._memory_quality_last, payload.get("memory_quality_last")) replace_state_dict(s, s._identity_trust_policies, payload.get("identity_trust_policies")) replace_state_dict(s, s._household_profiles, payload.get("household_profiles")) replace_state_dict(s, s._home_area_policies, payload.get("home_area_policies")) replace_state_dict(s, s._home_task_runs, payload.get("home_task_runs")) replace_state_dict(s, s._home_automation_drafts, payload.get("home_automation_drafts")) replace_state_dict(s, s._home_automation_applied, payload.get("home_automation_applied")) replace_state_dict(s, s._skill_quotas, payload.get("skill_quotas")) replace_state_dict(s, s._planner_task_graphs, payload.get("planner_task_graphs")) replace_state_dict(s, s._deferred_actions, payload.get("deferred_actions")) replace_state_dict(s, s._autonomy_checkpoints, payload.get("autonomy_checkpoints")) replace_state_dict(s, s._micro_expression_library, payload.get("micro_expression_library")) replace_state_dict(s, s._gaze_calibrations, payload.get("gaze_calibrations")) replace_state_dict(s, s._gesture_envelopes, payload.get("gesture_envelopes"))
autonomy_history = payload.get("autonomy_cycle_history") s._autonomy_cycle_history.clear() if isinstance(autonomy_history, list): for row in autonomy_history[-s.AUTONOMY_CYCLE_HISTORY_MAX :]: if isinstance(row, dict): s._autonomy_cycle_history.append( {str(key): s._json_safe_clone(value) for key, value in row.items()} )
s._guest_sessions.clear() guest_sessions = payload.get("guest_sessions") if isinstance(guest_sessions, dict): now = time.time() for raw_token, raw_row in guest_sessions.items(): token = str(raw_token).strip() if not token or not isinstance(raw_row, dict): continue expires_at = s._as_float(raw_row.get("expires_at", 0.0), 0.0, minimum=0.0) if expires_at <= now: continue issued_at = s._as_float(raw_row.get("issued_at", 0.0), 0.0, minimum=0.0) guest_id = str(raw_row.get("guest_id", "guest")).strip().lower() or "guest" capabilities = sorted(set(s._as_str_list(raw_row.get("capabilities"), lower=True))) s._guest_sessions[token] = { "token": token, "guest_id": guest_id, "capabilities": capabilities, "issued_at": issued_at, "expires_at": expires_at, }
quality_rows = payload.get("quality_reports") s._quality_reports.clear() if isinstance(quality_rows, list): for row in quality_rows[-s.CACHED_QUALITY_REPORT_MAX :]: if isinstance(row, dict): s._quality_reports.append({str(key): s._json_safe_clone(value) for key, value in row.items()})
privacy_posture = payload.get("privacy_posture") if isinstance(privacy_posture, dict): s._privacy_posture["state"] = str(privacy_posture.get("state", "normal")).strip().lower() or "normal" s._privacy_posture["reason"] = str(privacy_posture.get("reason", "startup")).strip() or "startup" s._privacy_posture["updated_at"] = s._as_float( privacy_posture.get("updated_at", 0.0), 0.0, minimum=0.0, )
motion_envelope = payload.get("motion_safety_envelope") if isinstance(motion_envelope, dict): s._motion_safety_envelope["proximity_limit_cm"] = s._as_float( motion_envelope.get( "proximity_limit_cm", s._motion_safety_envelope.get("proximity_limit_cm", 35.0), ), s._as_float(s._motion_safety_envelope.get("proximity_limit_cm", 35.0), 35.0), minimum=5.0, maximum=300.0, ) s._motion_safety_envelope["max_yaw_deg"] = s._as_float( motion_envelope.get("max_yaw_deg", s._motion_safety_envelope.get("max_yaw_deg", 45.0)), s._as_float(s._motion_safety_envelope.get("max_yaw_deg", 45.0), 45.0), minimum=0.0, maximum=180.0, ) s._motion_safety_envelope["max_pitch_deg"] = s._as_float( motion_envelope.get("max_pitch_deg", s._motion_safety_envelope.get("max_pitch_deg", 20.0)), s._as_float(s._motion_safety_envelope.get("max_pitch_deg", 20.0), 20.0), minimum=0.0, maximum=90.0, ) s._motion_safety_envelope["max_roll_deg"] = s._as_float( motion_envelope.get("max_roll_deg", s._motion_safety_envelope.get("max_roll_deg", 15.0)), s._as_float(s._motion_safety_envelope.get("max_roll_deg", 15.0), 15.0), minimum=0.0, maximum=90.0, ) s._motion_safety_envelope["hardware_state"] = ( str(motion_envelope.get("hardware_state", "normal")).strip().lower() or "normal" ) s._motion_safety_envelope["updated_at"] = s._as_float( motion_envelope.get("updated_at", 0.0), 0.0, minimum=0.0, )
release_state = payload.get("release_channel_state") if isinstance(release_state, dict): channel = str(release_state.get("active_channel", "dev")).strip().lower() if channel not in s.RELEASE_CHANNELS: channel = "dev" s._release_channel_state["active_channel"] = channel s._release_channel_state["last_check_at"] = s._as_float( release_state.get("last_check_at", 0.0), 0.0, minimum=0.0, ) s._release_channel_state["last_check_channel"] = ( str(release_state.get("last_check_channel", channel)).strip().lower() or channel ) s._release_channel_state["last_check_passed"] = bool(release_state.get("last_check_passed", False)) migration_checks = release_state.get("migration_checks") s._release_channel_state["migration_checks"] = ( [s._json_safe_clone(row) for row in migration_checks if isinstance(row, dict)] if isinstance(migration_checks, list) else [] )
s._home_task_seq = s._as_int(payload.get("home_task_seq", 1), 1, minimum=1) s._home_automation_seq = s._as_int(payload.get("home_automation_seq", 1), 1, minimum=1) s._planner_task_seq = s._as_int(payload.get("planner_task_seq", 1), 1, minimum=1) s._deferred_action_seq = s._as_int(payload.get("deferred_action_seq", 1), 1, minimum=1) s._prune_guest_sessions()1234567891011121314151617181920"""Quality-report runtime helpers for services."""
from __future__ import annotations
from typing import Any
def quality_reports_snapshot(services_module: Any, *, limit: int = 10) -> list[dict[str, Any]]: s = services_module if not s._quality_reports: return [] capped = s._as_int(limit, 10, minimum=1, maximum=50) return [dict(item) for item in s._quality_reports[-capped:]][::-1]
def append_quality_report(services_module: Any, report: dict[str, Any]) -> None: s = services_module s._quality_reports.append({str(key): value for key, value in report.items()}) if len(s._quality_reports) > s.CACHED_QUALITY_REPORT_MAX: del s._quality_reports[: len(s._quality_reports) - s.CACHED_QUALITY_REPORT_MAX] s._persist_expansion_state()29 unmodified lines30313233343529 unmodified lines("jarvis.tools.services_recovery_journal_runtime", "jarvis.tools.services"),("jarvis.tools.services_dead_letter_runtime", "jarvis.tools.services"),("jarvis.tools.services_recovery_response_runtime", "jarvis.tools.services"),("jarvis.tools.services_domains.trust_memory", "jarvis.tools.services"),("jarvis.tools.services_domains.trust_identity", "jarvis.tools.services"),("jarvis.tools.services_domains.home_state", "jarvis.tools.services"),29 unmodified lines30313233343536373839404142434429 unmodified lines("jarvis.tools.services_recovery_journal_runtime", "jarvis.tools.services"),("jarvis.tools.services_dead_letter_runtime", "jarvis.tools.services"),("jarvis.tools.services_recovery_response_runtime", "jarvis.tools.services"),("jarvis.tools.services_runtime_state", "jarvis.tools.services"),("jarvis.tools.services_runtime_state_bind", "jarvis.tools.services"),("jarvis.tools.services_runtime_state_reports", "jarvis.tools.services"),("jarvis.tools.services_runtime_state_persistence", "jarvis.tools.services"),("jarvis.tools.services_audit_runtime", "jarvis.tools.services"),("jarvis.tools.services_audit_crypto_runtime", "jarvis.tools.services"),("jarvis.tools.services_audit_event_runtime", "jarvis.tools.services"),("jarvis.tools.services_audit_sanitize_runtime", "jarvis.tools.services"),("jarvis.tools.services_audit_retention_runtime", "jarvis.tools.services"),("jarvis.tools.services_domains.trust_memory", "jarvis.tools.services"),("jarvis.tools.services_domains.trust_identity", "jarvis.tools.services"),("jarvis.tools.services_domains.home_state", "jarvis.tools.services"),
TODO.md+62-67
src/jarvis/tools/services_audit_crypto_runtime.pyAdded+63
src/jarvis/tools/services_audit_event_runtime.pyAdded+170
src/jarvis/tools/services_audit_retention_runtime.pyAdded+104
src/jarvis/tools/services_audit_runtime.py+46-413
src/jarvis/tools/services_audit_sanitize_runtime.pyAdded+101
src/jarvis/tools/services_runtime_state.py+24-488
src/jarvis/tools/services_runtime_state_bind.pyAdded+194
src/jarvis/tools/services_runtime_state_persistence.pyAdded+287
src/jarvis/tools/services_runtime_state_reports.pyAdded+20
tests/test_import_boundaries.py+9