diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0096-verify-built-in-os-everyday-tasks-night-shift.md b/capabilities/04-the-core-a-checked-entry-every-time/0096-verify-built-in-os-everyday-tasks-night-shift.md new file mode 100644 index 0000000000..7e042f20b7 --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0096-verify-built-in-os-everyday-tasks-night-shift.md @@ -0,0 +1 @@ +| Generate read-only OS `local-state` verification contracts for built-in everyday tasks (`macos_night_shift` via private `CoreBrightness`, `windows_night_light` via `HKCU` CloudStore `Data` byte 18 heuristic, and `macos_calendar_event` via EventKit `EKEventStore` matching exact title, local-timezone start/end, recurrence, and optional `event_uid`), wired into `openadapt quickstart --task night-shift` and `--task calendar-block` (with opt-in `--probe-baseline` and withheld revert contract when baseline is unreadable); unreadable or unsupported hosts fail closed as `INDETERMINATE` | Experimental | Unit-tested across all 3 probes (enabled/disabled, malformed bytes, missing/ambiguous calendars, unauthorized EventKit, aware timezone conversion, wrong OS -> fail-closed `INDETERMINATE`) and contract generation; live Windows and end-to-end macOS toggle runs not yet recorded | `openadapt quickstart --task`, [LOCAL_STATE_CHECKS.md](packages/flow/docs/LOCAL_STATE_CHECKS.md), `openadapt/quickstart/everyday.py`, `runtime/effects/local_state.py` | diff --git a/openadapt/cli.py b/openadapt/cli.py index ad6e329212..184db08e1d 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -880,6 +880,73 @@ def ask(prompt: str) -> str: default=None, help="With --own: your web app's address. Recording opens a browser window.", ) +@click.option( + "--task", + type=click.Choice(["night-shift", "calendar-block"]), + default=None, + help=( + "Built-in OS everyday task (no sample app, no login): " + "night-shift (macOS Night Shift / Windows Night Light) or " + "calendar-block (parameterized recurring Calendar block)." + ), +) +@click.option( + "--title", + default=None, + help="With --task calendar-block: Calendar event title.", +) +@click.option( + "--calendar", + "calendar_name", + default=None, + help="With --task calendar-block: macOS Calendar name (default: Calendar).", +) +@click.option( + "--start", + "start_iso", + default=None, + help="With --task calendar-block: ISO-8601 start timestamp.", +) +@click.option( + "--duration", + "duration_minutes", + type=int, + default=None, + help="With --task calendar-block: duration in minutes (default: 30).", +) +@click.option( + "--recurrence", + type=click.Choice(["none", "daily", "weekly", "weekdays"]), + default=None, + help="With --task calendar-block: recurrence cadence (default: weekly).", +) +@click.option( + "--event-uid", + default=None, + help=( + "With --task calendar-block: optional EventKit eventIdentifier to bind " + "forward and revert checks to one specific event (without --event-uid, " + "the check matches any event with the same calendar, title, time, and recurrence)." + ), +) +@click.option( + "--revert/--no-revert", + default=True, + show_default=True, + help=( + "With --task: write a revert_verify.yaml check file to run after undoing " + "the change (withheld when baseline is not confirmed or Night Shift baseline is unreadable)." + ), +) +@click.option( + "--probe-baseline", + is_flag=True, + default=False, + help=( + "With --task calendar-block: run an opt-in read-only macOS EventKit " + "baseline check (requires Calendars privacy permission)." + ), +) @click.option("--headed", is_flag=True, hidden=True) @click.option("--headless", is_flag=True, hidden=True) @click.option("--break-it", "break_it", is_flag=True, hidden=True) @@ -895,6 +962,15 @@ def quickstart( more: bool, own: bool, url: Optional[str], + task: Optional[str], + title: Optional[str], + calendar_name: Optional[str], + start_iso: Optional[str], + duration_minutes: Optional[int], + recurrence: Optional[str], + event_uid: Optional[str], + revert: bool, + probe_baseline: bool, headed: bool, headless: bool, break_it: bool, @@ -923,6 +999,62 @@ def quickstart( _require_supported_python() if url is not None and not own: raise click.UsageError("--url works with --own.") + calendar_opts_used = any( + opt is not None + for opt in ( + title, + calendar_name, + start_iso, + duration_minutes, + recurrence, + event_uid, + ) + ) + if (calendar_opts_used or probe_baseline) and task != "calendar-block": + raise click.UsageError( + "--title, --calendar, --start, --duration, --recurrence, --event-uid, " + "and --probe-baseline require --task calendar-block." + ) + if task is not None: + if own: + raise click.UsageError("--task cannot be combined with --own.") + from openadapt.quickstart.everyday import ( + DEFAULT_CALENDAR_NAME, + DEFAULT_CALENDAR_TITLE, + DEFAULT_DURATION_MINUTES, + DEFAULT_RECURRENCE, + EverydayTaskError, + run_everyday_task, + ) + + root = _quickstart_root(out) + try: + run_everyday_task( + task, + root, + title=title if title is not None else DEFAULT_CALENDAR_TITLE, + calendar_name=( + calendar_name + if calendar_name is not None + else DEFAULT_CALENDAR_NAME + ), + start_iso=start_iso, + duration_minutes=( + duration_minutes + if duration_minutes is not None + else DEFAULT_DURATION_MINUTES + ), + recurrence=( + recurrence if recurrence is not None else DEFAULT_RECURRENCE + ), + event_uid=event_uid, + revert=revert, + probe_baseline=probe_baseline, + say=click.echo, + ) + except EverydayTaskError as error: + raise click.ClickException(str(error)) from error + return if own: _quickstart_own(_quickstart_root(out), url, watch or headed) return diff --git a/openadapt/quickstart/everyday.py b/openadapt/quickstart/everyday.py new file mode 100644 index 0000000000..a45e3d9847 --- /dev/null +++ b/openadapt/quickstart/everyday.py @@ -0,0 +1,417 @@ +"""Built-in everyday OS quickstart tasks (zero sample apps, zero logins). + +Generates parameterized task definitions and read-only ``local-state`` +verification contract files (``verify.yaml`` and, when baseline state is known, +``revert_verify.yaml``) for: + +1. ``night-shift``: Toggle macOS Night Shift (``macos_night_shift``) or Windows + Night Light (``windows_night_light``). +2. ``calendar-block``: Schedule a Calendar block with parameterized title, + start/end time, duration, and recurrence (``macos_calendar_event`` via + macOS EventKit). + +This module only writes contract/parameter files (it does not mutate OS +settings or Calendar data, and does not run the change or revert itself). +For ``calendar-block``, baseline probing is opt-in (``probe_baseline=True``) +so running quickstart never queries EventKit without explicit user intent. +""" + +from __future__ import annotations + +import json +import sys +from dataclasses import dataclass +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any, Callable, Optional + +import yaml # type: ignore[import-untyped] + +EVERYDAY_TASKS = ("night-shift", "calendar-block") +VALID_RECURRENCES = ("none", "daily", "weekly", "weekdays") +DEFAULT_CALENDAR_TITLE = "OpenAdapt Focus Block" +DEFAULT_CALENDAR_NAME = "Calendar" +DEFAULT_DURATION_MINUTES = 30 +DEFAULT_RECURRENCE = "weekly" + + +class EverydayTaskError(Exception): + """Raised when an everyday quickstart task cannot be configured on this host.""" + + +@dataclass(frozen=True) +class EverydayTaskBundle: + """Generated contracts and read-only baseline snapshot for an everyday task.""" + + task: str + platform: str + out_dir: Path + verify_path: Path + revert_verify_path: Optional[Path] + params_path: Path + baseline_state: Optional[dict[str, Any]] + params: dict[str, Any] + revert: bool + + +def default_start_iso(now: Optional[datetime] = None) -> str: + """Return the next top-of-the-hour local timestamp as an ISO-8601 string.""" + ref = now or datetime.now() + next_hour = ref.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1) + return next_hour.isoformat(timespec="seconds") + + +def _parse_iso(value: str) -> datetime: + normalized = value[:-1] + "+00:00" if value.endswith("Z") else value + try: + return datetime.fromisoformat(normalized) + except ValueError as exc: + raise EverydayTaskError( + f"--start must be a valid ISO-8601 timestamp (got {value!r})" + ) from exc + + +def build_night_shift_contracts( + *, + platform: str, + baseline_enabled: Optional[bool] = None, + revert: bool = True, +) -> tuple[dict[str, Any], Optional[dict[str, Any]], dict[str, Any]]: + """Build forward and optional revert ``verify.yaml`` contracts for Night Shift/Light.""" + if platform == "darwin": + source_type = "macos_night_shift" + source_id = "night_shift" + label = "macOS Night Shift" + elif platform == "win32": + source_type = "windows_night_light" + source_id = "night_light" + label = "Windows Night Light" + else: + raise EverydayTaskError( + f"night-shift task supports macOS (Night Shift) and Windows (Night Light); " + f"unsupported platform {platform!r}" + ) + + target_enabled = (not baseline_enabled) if baseline_enabled is not None else True + # Never invent a revert baseline when the prior state is unreadable. + restore_enabled: Optional[bool] = ( + baseline_enabled if baseline_enabled is not None else None + ) + + def _contract(expected_enabled: bool) -> dict[str, Any]: + return { + "schema_version": "openadapt.verify/v1", + "minimum_effect_strength": "independent_system_of_record", + "verifier": { + "kind": "local-state", + "local_state": [{"type": source_type, "id": source_id}], + }, + "frame": {"target_fields": ["enabled", "value"]}, + "effects": [ + { + "kind": "field_equals", + "match": {"id": source_id}, + "field": "value", + "value": "true" if expected_enabled else "false", + } + ], + } + + forward = _contract(target_enabled) + revert_contract = ( + _contract(restore_enabled) if (revert and restore_enabled is not None) else None + ) + params: dict[str, Any] = { + "task": "night-shift", + "label": label, + "platform": platform, + "source_type": source_type, + "baseline_enabled": baseline_enabled, + "target_enabled": "true" if target_enabled else "false", + "restore_enabled": ( + ("true" if restore_enabled else "false") + if restore_enabled is not None + else None + ), + "revert": revert, + } + if revert and restore_enabled is None: + params["revert_withheld_reason"] = "baseline_indeterminate" + return forward, revert_contract, params + + +def build_calendar_block_contracts( + *, + title: str = DEFAULT_CALENDAR_TITLE, + calendar_name: str = DEFAULT_CALENDAR_NAME, + start_iso: Optional[str] = None, + duration_minutes: int = DEFAULT_DURATION_MINUTES, + recurrence: str = DEFAULT_RECURRENCE, + event_uid: Optional[str] = None, + platform: str = "darwin", + revert: bool = True, +) -> tuple[dict[str, Any], Optional[dict[str, Any]], dict[str, Any]]: + """Build parameterized forward and optional revert contracts for a Calendar block.""" + if platform != "darwin": + raise EverydayTaskError( + f"calendar-block local-state probe currently supports macOS EventKit; " + f"unsupported platform {platform!r}" + ) + if not title or not title.strip(): + raise EverydayTaskError("--title must be non-empty") + if not calendar_name or not calendar_name.strip(): + raise EverydayTaskError("--calendar must be non-empty") + if duration_minutes < 1 or duration_minutes > 480: + raise EverydayTaskError("--duration must be between 1 and 480 minutes") + if recurrence not in VALID_RECURRENCES: + raise EverydayTaskError( + f"--recurrence must be one of {', '.join(VALID_RECURRENCES)}" + ) + + resolved_start = start_iso or default_start_iso() + start_dt = _parse_iso(resolved_start) + end_dt = start_dt + timedelta(minutes=duration_minutes) + end_iso = end_dt.isoformat(timespec="seconds") + + source_spec: dict[str, Any] = { + "type": "macos_calendar_event", + "id": "calendar_block", + "calendar_name": calendar_name.strip(), + "title": title.strip(), + "start_iso": resolved_start, + "end_iso": end_iso, + "recurrence": recurrence, + } + if event_uid is not None and event_uid.strip(): + source_spec["event_uid"] = event_uid.strip() + + def _contract(expected_exists: bool) -> dict[str, Any]: + return { + "schema_version": "openadapt.verify/v1", + "minimum_effect_strength": "independent_system_of_record", + "verifier": { + "kind": "local-state", + "local_state": [source_spec], + }, + "frame": {"target_fields": ["present", "exists", "event_uid", "value"]}, + "effects": [ + { + "kind": "field_equals", + "match": {"id": "calendar_block"}, + "field": "value", + "value": "true" if expected_exists else "false", + } + ], + } + + forward = _contract(True) + revert_contract = _contract(False) if revert else None + params: dict[str, Any] = { + "task": "calendar-block", + "platform": platform, + "calendar_name": calendar_name.strip(), + "title": title.strip(), + "start_iso": resolved_start, + "end_iso": end_iso, + "duration_minutes": duration_minutes, + "recurrence": recurrence, + "event_uid": event_uid.strip() if event_uid and event_uid.strip() else None, + "revert": revert, + } + return forward, revert_contract, params + + +def _probe_baseline( + verify_doc: dict[str, Any], + *, + platform: str, + verifier_factory: Optional[Callable[..., Any]] = None, +) -> tuple[Optional[dict[str, Any]], Optional[str]]: + """Run the read-only ``local-state`` probe once without mutating OS state.""" + try: + from openadapt_flow.runtime.effects.local_state import LocalStateVerifier + from openadapt_flow.verify_run import VerifyConfig + except ImportError as exc: + return ( + None, + f"local_state verifier unavailable in installed openadapt-flow: {exc}", + ) + + cfg = VerifyConfig.model_validate(verify_doc) + sources = list(cfg.verifier.local_state or []) + if verifier_factory is not None: + verifier = verifier_factory(sources, platform=platform) + else: + verifier = LocalStateVerifier(sources, platform=platform) + records = verifier.read() + if records is None or not records: + return None, getattr(verifier, "last_error", "unreadable") + return records[0], None + + +def run_everyday_task( + task: str, + root: Path, + *, + title: str = DEFAULT_CALENDAR_TITLE, + calendar_name: str = DEFAULT_CALENDAR_NAME, + start_iso: Optional[str] = None, + duration_minutes: int = DEFAULT_DURATION_MINUTES, + recurrence: str = DEFAULT_RECURRENCE, + event_uid: Optional[str] = None, + revert: bool = True, + probe_baseline: bool = False, + platform: Optional[str] = None, + say: Callable[[str], None] = print, + verifier_factory: Optional[Callable[..., Any]] = None, +) -> EverydayTaskBundle: + """Write parameterized verify/revert contracts for a built-in everyday OS task into ``root``.""" + if task not in EVERYDAY_TASKS: + raise EverydayTaskError( + f"Unknown task {task!r}. Expected one of: {', '.join(EVERYDAY_TASKS)}" + ) + + active_platform = platform or sys.platform + baseline_state: Optional[dict[str, Any]] = None + probe_error: Optional[str] = None + probe_skipped = False + + if task == "night-shift": + # Probe baseline first so the forward target flips the actual current state. + probe_doc, _, _ = build_night_shift_contracts( + platform=active_platform, baseline_enabled=None, revert=revert + ) + baseline_state, probe_error = _probe_baseline( + probe_doc, platform=active_platform, verifier_factory=verifier_factory + ) + baseline_enabled = ( + bool(baseline_state["enabled"]) + if baseline_state is not None + and isinstance(baseline_state.get("enabled"), bool) + else None + ) + forward, revert_doc, params = build_night_shift_contracts( + platform=active_platform, + baseline_enabled=baseline_enabled, + revert=revert, + ) + else: + bound_uid = event_uid.strip() if event_uid and event_uid.strip() else None + forward, revert_doc, params = build_calendar_block_contracts( + title=title, + calendar_name=calendar_name, + start_iso=start_iso, + duration_minutes=duration_minutes, + recurrence=recurrence, + event_uid=bound_uid, + platform=active_platform, + revert=revert, + ) + if probe_baseline: + baseline_state, probe_error = _probe_baseline( + forward, platform=active_platform, verifier_factory=verifier_factory + ) + if baseline_state is not None and baseline_state.get("exists") is True: + raise EverydayTaskError( + "Refusing to generate calendar-block contracts: a matching event " + f"({title!r} at {params['start_iso']} in {calendar_name!r}) already " + "exists in the baseline. Choose a different --title or --start so " + "the revert check cannot target a pre-existing user event." + ) + else: + probe_skipped = True + + # Fail closed on calendar revert: only write revert_verify.yaml when an + # explicit event_uid is bound OR the baseline was explicitly probed and + # confirmed NOT_FOUND, so we never tell a user to delete an unverified + # pre-existing event. + baseline_confirmed_absent = ( + baseline_state is not None and baseline_state.get("exists") is False + ) + if ( + revert + and revert_doc is not None + and not (bound_uid or baseline_confirmed_absent) + ): + revert_doc = None + params["revert_withheld_reason"] = ( + "baseline_not_probed" if probe_skipped else "baseline_indeterminate" + ) + + root.mkdir(parents=True, exist_ok=True) + verify_path = root / "verify.yaml" + verify_path.write_text(yaml.safe_dump(forward, sort_keys=False), encoding="utf-8") + + revert_verify_path: Optional[Path] = None + if revert_doc is not None: + revert_verify_path = root / "revert_verify.yaml" + revert_verify_path.write_text( + yaml.safe_dump(revert_doc, sort_keys=False), encoding="utf-8" + ) + + params_path = root / "task.json" + params_path.write_text( + json.dumps(params, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + + say(f"Everyday task: {task} ({active_platform})") + if probe_skipped: + say( + " Baseline probe: skipped by default for calendar-block " + "(pass --probe-baseline to read macOS EventKit; requires Calendars permission)" + ) + elif baseline_state is not None: + say( + f" Baseline probe (read-only): {baseline_state['type']} -> " + f"value={baseline_state.get('value')}" + ) + else: + say( + f" Baseline probe (read-only): INDETERMINATE ({probe_error or 'unavailable'})" + ) + say(f" Verify contract written: {verify_path} (run via openadapt-flow verify-run)") + if revert_verify_path is not None: + say( + f" Revert contract written: {revert_verify_path} " + "(run via openadapt-flow verify-run after undoing the change)" + ) + elif revert and task == "night-shift": + say( + " Revert contract withheld: baseline was INDETERMINATE " + "(will not invent a prior Night Shift state)" + ) + elif revert and task == "calendar-block": + reason = params.get("revert_withheld_reason", "baseline_not_probed") + say( + f" Revert contract withheld ({reason}): pass --probe-baseline " + "(confirmed NOT_FOUND) or --event-uid to generate revert_verify.yaml" + ) + say(f" Task parameters: {params_path}") + + return EverydayTaskBundle( + task=task, + platform=active_platform, + out_dir=root, + verify_path=verify_path, + revert_verify_path=revert_verify_path, + params_path=params_path, + baseline_state=baseline_state, + params=params, + revert=revert, + ) + + +__all__ = [ + "DEFAULT_CALENDAR_NAME", + "DEFAULT_CALENDAR_TITLE", + "DEFAULT_DURATION_MINUTES", + "DEFAULT_RECURRENCE", + "EVERYDAY_TASKS", + "EverydayTaskBundle", + "EverydayTaskError", + "VALID_RECURRENCES", + "build_calendar_block_contracts", + "build_night_shift_contracts", + "default_start_iso", + "run_everyday_task", +] diff --git a/packages/flow/docs/LOCAL_STATE_CHECKS.md b/packages/flow/docs/LOCAL_STATE_CHECKS.md index fc692a9f29..a5c5cf72f5 100644 --- a/packages/flow/docs/LOCAL_STATE_CHECKS.md +++ b/packages/flow/docs/LOCAL_STATE_CHECKS.md @@ -17,6 +17,9 @@ rules. It never runs a command you supply, and it never writes. | `file` | A file's contents | Ordinary read-only file I/O | `present`, `size`, `sha256`, `text` (UTF-8, files up to 1 MiB) | | `macos_defaults` | One key in a preferences domain | `/usr/bin/defaults export -` (goes through `cfprefsd`, so it sees the current value). Unit-tested only so far; not yet run on a real Mac | `present`, `value`, `value_type` | | `windows_registry` | One registry value under `HKCU` or `HKLM` | `winreg` with `KEY_READ` access only | `present`, `value`, `value_type` | +| `macos_night_shift` | Current macOS Night Shift enabled state | Read-only `CBBlueLightClient.getBlueLightStatus:` via private `CoreBrightness` (`ctypes`/`libobjc`). Fails closed (`INDETERMINATE`) if unavailable; note private struct layout may change across macOS releases | `present`, `enabled`, `value` (`"true"`/`"false"`), `value_type` | +| `windows_night_light` | Current Windows Night Light enabled state | Read-only `winreg` (`KEY_READ`) read of `HKCU\...\bluelightreductionstate` `Data` bytes (byte 18 `0x15` enabled vs `0x13` disabled heuristic, unit-tested on synthetic blobs). Fails closed on missing or unexpected bytes | `present`, `enabled`, `value` (`"true"`/`"false"`), `value_type` | +| `macos_calendar_event` | Whether a macOS EventKit calendar event matching `(calendar_name, exact title, local start/end, recurrence, optional event_uid)` exists | Fixed read-only EventKit (`EKEventStore`) JXA probe via `/usr/bin/osascript -l JavaScript` with argv parameters (never launches or mutates Calendar.app). Fails closed if EventKit is unauthorized, calendar is missing, or multiple calendars share the name | `present`, `exists`, `event_uid`, `calendar_name`, `title`, `start_iso`, `end_iso`, `recurrence`, `value` (`"true"`/`"false"`), `value_type` | Each source becomes one record with the source's `id`, judged by the same effect kinds every other record check uses (`field_equals`, `record_written`). @@ -93,6 +96,9 @@ The examples live in [`examples/local_state/`](../examples/local_state/). | --- | --- | --- | | `notepad-save` | `~/openadapt-examples/note.txt`, text equals the note | End to end on Windows 11 in the lab: record, compile, replay, check `verified`. Turn Notepad's status bar off (View > Status bar) so replay can confirm the typing | | `windows-dark-mode` | `HKCU\...\Themes\Personalize` `AppsUseLightTheme` and `SystemUsesLightTheme` are `0` | Check only, on the real registry; see below | +| `macos-night-shift` | macOS Night Shift `enabled` state via private `CoreBrightness` | Unit-tested across platforms (fail-closed when unavailable); not yet recorded across an end-to-end toggle run | +| `windows-night-light` | Windows Night Light `Data` byte 18 (`0x15` vs `0x13`) | Unit-tested against synthetic CloudStore blobs; fail-closed on missing or unexpected bytes; not yet recorded on a live Windows host | +| `macos-calendar-block` | macOS EventKit event matching `(calendar_name, title, start_iso, end_iso, recurrence, event_uid)` | Fixed read-only EventKit JXA probe; unit-tested with fail-closed unauthorized/missing/ambiguous-calendar and timezone checks | TextEdit and macOS Dark Mode follow the same pattern (a `file` source; a `macos_defaults` source on `NSGlobalDomain` `AppleInterfaceStyle`). They have @@ -100,18 +106,19 @@ no example yet because they haven't been run on a Mac. ## What it can't check, and why -- **Night Shift (macOS).** Its state lives in CoreBrightness, a private - framework. There is no public API and no preference key that reliably - shows whether Night Shift is on now (the stored schedule is in a root-only - file and is not the current state). OpenAdapt can't check it, so there is - no Night Shift example. -- **Notes (macOS).** The supported ways to read a note are AppleScript and - Shortcuts. Both are scripts, not a typed read, and both need an Automation - consent prompt per app. The Notes database is private and protected by - Full Disk Access. There is no Notes source. -- **Calendar (macOS).** EventKit is a supported, public read API. It needs a - Calendar permission prompt and a PyObjC dependency that OpenAdapt doesn't - ship today. It is a candidate source, not built. +- **Notes (macOS).** The Notes database is private and protected by Full Disk + Access, and reading arbitrary note bodies via AppleScript needs per-app + Automation consent without a typed schema. There is no Notes source. +- **Calendar (macOS) without EventKit permission.** `macos_calendar_event` + uses a fixed read-only EventKit (`EKEventStore`) probe without launching + Calendar.app; if macOS Calendars privacy permission is not granted, the named + calendar does not exist, or multiple calendars share the name, it fails + closed as `INDETERMINATE`. In `openadapt quickstart --task calendar-block`, + baseline probing is opt-in (`--probe-baseline`). +- **Night Shift (macOS) on unsupported displays.** `macos_night_shift` reads + the private `CoreBrightness` framework (`CBBlueLightClient`); if the + framework or display capability is unavailable, it fails closed as + `INDETERMINATE`. - **Windows dark mode on an unactivated Windows.** Windows locks the Personalization pages until it is activated, so the setting can't be demonstrated through Settings there. The check itself reads the registry diff --git a/packages/flow/examples/local_state/macos-calendar-block/verify.yaml b/packages/flow/examples/local_state/macos-calendar-block/verify.yaml new file mode 100644 index 0000000000..e7cfc75cbd --- /dev/null +++ b/packages/flow/examples/local_state/macos-calendar-block/verify.yaml @@ -0,0 +1,21 @@ +# Check a macOS EventKit calendar event through a fixed, read-only EventKit probe. +# Verifies an event matching (calendar_name, exact title, start_iso, end_iso, recurrence). +schema_version: openadapt.verify/v1 +minimum_effect_strength: independent_system_of_record +verifier: + kind: local-state + local_state: + - type: macos_calendar_event + id: calendar_block + calendar_name: Calendar + title: OpenAdapt Focus Block + start_iso: "2026-11-24T10:00:00" + end_iso: "2026-11-24T10:30:00" + recurrence: weekly +frame: + target_fields: [present, exists, event_uid, value] +effects: + - kind: field_equals + match: {id: calendar_block} + field: value + value: "true" diff --git a/packages/flow/examples/local_state/macos-night-shift/verify.yaml b/packages/flow/examples/local_state/macos-night-shift/verify.yaml new file mode 100644 index 0000000000..68ff947e4d --- /dev/null +++ b/packages/flow/examples/local_state/macos-night-shift/verify.yaml @@ -0,0 +1,17 @@ +# Check a macOS Night Shift toggle through CoreBrightness (read-only). +# Compare the `value` field ("true" or "false") after toggling Night Shift +# in System Settings or Control Center. +schema_version: openadapt.verify/v1 +minimum_effect_strength: independent_system_of_record +verifier: + kind: local-state + local_state: + - type: macos_night_shift + id: night_shift +frame: + target_fields: [enabled, value] +effects: + - kind: field_equals + match: {id: night_shift} + field: value + value: {param: target_enabled} diff --git a/packages/flow/examples/local_state/windows-night-light/verify.yaml b/packages/flow/examples/local_state/windows-night-light/verify.yaml new file mode 100644 index 0000000000..5a569029b6 --- /dev/null +++ b/packages/flow/examples/local_state/windows-night-light/verify.yaml @@ -0,0 +1,17 @@ +# Check a Windows Night Light toggle through the HKCU CloudStore registry blob. +# Byte 18 is 0x15 when enabled and 0x13 when disabled; unexpected or missing +# bytes fail closed as INDETERMINATE. +schema_version: openadapt.verify/v1 +minimum_effect_strength: independent_system_of_record +verifier: + kind: local-state + local_state: + - type: windows_night_light + id: night_light +frame: + target_fields: [enabled, value] +effects: + - kind: field_equals + match: {id: night_light} + field: value + value: {param: target_enabled} diff --git a/packages/flow/openadapt_flow/local_state_sources.py b/packages/flow/openadapt_flow/local_state_sources.py index b4a00595b0..8d238ac8ff 100644 --- a/packages/flow/openadapt_flow/local_state_sources.py +++ b/packages/flow/openadapt_flow/local_state_sources.py @@ -9,14 +9,18 @@ from __future__ import annotations import re +from datetime import datetime from typing import Literal, Union -from pydantic import BaseModel, ConfigDict, Field, field_validator +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator __all__ = [ "FileSource", "LocalStateSource", + "MacosCalendarEventSource", "MacosDefaultsSource", + "MacosNightShiftSource", + "WindowsNightLightSource", "WindowsRegistrySource", ] @@ -93,4 +97,113 @@ def _check_path(cls, value: str) -> str: return value -LocalStateSource = Union[FileSource, MacosDefaultsSource, WindowsRegistrySource] +class MacosNightShiftSource(_Source): + """Current macOS Night Shift enabled state via CoreBrightness (read-only).""" + + type: Literal["macos_night_shift"] = "macos_night_shift" + + +class WindowsNightLightSource(_Source): + """Current Windows Night Light enabled state via CloudStore registry Data bytes.""" + + type: Literal["windows_night_light"] = "windows_night_light" + + +class MacosCalendarEventSource(_Source): + """Read-only check for a macOS EventKit calendar event. + + Matches exact calendar name (rejecting ambiguous duplicates), case-sensitive + title, local-timezone start/end time to the minute, recurrence cadence, and + optional ``event_uid``. + """ + + type: Literal["macos_calendar_event"] = "macos_calendar_event" + calendar_name: str = Field(min_length=1, max_length=255) + title: str = Field(min_length=1, max_length=255) + #: ISO-8601 start timestamp (e.g. ``2026-11-24T10:00:00`` or aware ``...Z``). + start_iso: str = Field(min_length=10, max_length=64) + #: Optional ISO-8601 end timestamp; when set, end time must also match to the minute. + end_iso: str | None = Field(default=None, min_length=10, max_length=64) + #: Expected recurrence cadence (``none``, ``daily``, ``weekly``, or ``weekdays``). + recurrence: Literal["none", "daily", "weekly", "weekdays"] = "none" + #: Optional EventKit event identifier to bind verification to one created event. + event_uid: str | None = Field(default=None, min_length=1, max_length=255) + + @field_validator("calendar_name", "title") + @classmethod + def _check_safe_text(cls, value: str) -> str: + if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in value): + raise ValueError( + "macos_calendar_event text fields must not contain control characters" + ) + return value + + @field_validator("event_uid") + @classmethod + def _check_event_uid(cls, value: str | None) -> str | None: + if value is None: + return None + if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in value): + raise ValueError( + "macos_calendar_event event_uid must not contain control characters" + ) + return value + + @field_validator("start_iso") + @classmethod + def _check_start_iso(cls, value: str) -> str: + normalized = value[:-1] + "+00:00" if value.endswith("Z") else value + try: + datetime.fromisoformat(normalized) + except ValueError as exc: + raise ValueError( + "macos_calendar_event start_iso must be a valid ISO-8601 timestamp" + ) from exc + return value + + @field_validator("end_iso") + @classmethod + def _check_end_iso(cls, value: str | None) -> str | None: + if value is None: + return None + normalized = value[:-1] + "+00:00" if value.endswith("Z") else value + try: + datetime.fromisoformat(normalized) + except ValueError as exc: + raise ValueError( + "macos_calendar_event end_iso must be a valid ISO-8601 timestamp" + ) from exc + return value + + @model_validator(mode="after") + def _check_end_after_start(self) -> "MacosCalendarEventSource": + if self.end_iso is not None: + s_norm = ( + self.start_iso[:-1] + "+00:00" + if self.start_iso.endswith("Z") + else self.start_iso + ) + e_norm = ( + self.end_iso[:-1] + "+00:00" + if self.end_iso.endswith("Z") + else self.end_iso + ) + s_dt = datetime.fromisoformat(s_norm) + e_dt = datetime.fromisoformat(e_norm) + if (s_dt.tzinfo is None) != (e_dt.tzinfo is None): + raise ValueError( + "macos_calendar_event start_iso and end_iso must both be naive or both be timezone-aware" + ) + if e_dt <= s_dt: + raise ValueError("macos_calendar_event end_iso must be after start_iso") + return self + + +LocalStateSource = Union[ + FileSource, + MacosDefaultsSource, + WindowsRegistrySource, + MacosNightShiftSource, + WindowsNightLightSource, + MacosCalendarEventSource, +] diff --git a/packages/flow/openadapt_flow/runtime/effects/local_state.py b/packages/flow/openadapt_flow/runtime/effects/local_state.py index da06f4beb4..bfd8f88dc1 100644 --- a/packages/flow/openadapt_flow/runtime/effects/local_state.py +++ b/packages/flow/openadapt_flow/runtime/effects/local_state.py @@ -58,12 +58,14 @@ from __future__ import annotations +import ctypes import hashlib import json import os import plistlib import stat import subprocess +from datetime import datetime from pathlib import Path from sys import platform as _SYS_PLATFORM from typing import Any, Callable, Optional @@ -71,7 +73,10 @@ from openadapt_flow.local_state_sources import ( # noqa: F401 - re-exported FileSource, LocalStateSource, + MacosCalendarEventSource, MacosDefaultsSource, + MacosNightShiftSource, + WindowsNightLightSource, WindowsRegistrySource, ) from openadapt_flow.runtime.effects.adapter import ( @@ -94,11 +99,240 @@ #: cannot substitute another program. DEFAULTS_BINARY = "/usr/bin/defaults" +#: The supported macOS AppleScript runner, used only with a fixed read-only +#: script and argv parameters (never interpolated user strings). +OSASCRIPT_BINARY = "/usr/bin/osascript" + +#: Fixed HKCU registry path holding Windows 10/11 Night Light CloudStore state. +WINDOWS_NIGHT_LIGHT_REG_PATH = ( + r"Software\Microsoft\Windows\CurrentVersion\CloudStore\Store" + r"\DefaultAccount\Current" + r"\default$windows.data.bluelightreduction.bluelightreductionstate" + r"\windows.data.bluelightreduction.bluelightreductionstate" +) +WINDOWS_NIGHT_LIGHT_VALUE_NAME = "Data" +_WINDOWS_NIGHT_LIGHT_STATE_BYTE_INDEX = 18 +_WINDOWS_NIGHT_LIGHT_ENABLED_BYTE = 0x15 +_WINDOWS_NIGHT_LIGHT_DISABLED_BYTE = 0x13 + +# Fixed read-only EventKit (OS framework) JXA script: receives +# (calendar_name, title, start_y, start_m, start_d, start_h, start_min, +# end_y, end_m, end_d, end_h, end_min, recurrence, event_uid) via argv. +# Reads the OS EKEventStore directly without naming or launching any app, and +# fails closed when EventKit access is not authorized or calendar names collide. +_MACOS_EVENTKIT_READ_SCRIPT = """ +ObjC.import('EventKit'); +ObjC.import('Foundation'); +function run(argv) { + var calName = argv[0]; + var targetTitle = argv[1]; + var sYear = parseInt(argv[2], 10); + var sMonth = parseInt(argv[3], 10); + var sDay = parseInt(argv[4], 10); + var sHour = parseInt(argv[5], 10); + var sMin = parseInt(argv[6], 10); + var hasEnd = argv[7] !== ''; + var eYear = hasEnd ? parseInt(argv[7], 10) : 0; + var eMonth = hasEnd ? parseInt(argv[8], 10) : 0; + var eDay = hasEnd ? parseInt(argv[9], 10) : 0; + var eHour = hasEnd ? parseInt(argv[10], 10) : 0; + var eMin = hasEnd ? parseInt(argv[11], 10) : 0; + var recurrence = argv[12] || 'none'; + var targetUid = argv[13] || ''; + + var auth = $.EKEventStore.authorizationStatusForEntityType(0); + // Require EKAuthorizationStatusFullAccess (3); write-only (4) cannot read events. + if (auth !== 3) { + return JSON.stringify({status: 'UNAUTHORIZED'}); + } + var store = $.EKEventStore.alloc.init; + var cals = store.calendarsForEntityType(0); + var matchedCals = []; + for (var i = 0; i < cals.count; i++) { + var c = cals.objectAtIndex(i); + if (ObjC.unwrap(c.title) === calName) { + matchedCals.push(c); + } + } + if (matchedCals.length === 0) { + return JSON.stringify({status: 'NO_CALENDAR'}); + } + if (matchedCals.length > 1) { + return JSON.stringify({status: 'AMBIGUOUS_CALENDAR'}); + } + + var startJs = new Date(sYear, sMonth - 1, sDay, sHour, sMin, 0); + var endJs = hasEnd + ? new Date(eYear, eMonth - 1, eDay, eHour, eMin, 0) + : new Date(startJs.getTime() + 3600000); + var winStart = $.NSDate.dateWithTimeIntervalSince1970((startJs.getTime() - 60000) / 1000.0); + var winEnd = $.NSDate.dateWithTimeIntervalSince1970((endJs.getTime() + 60000) / 1000.0); + var calArr = $.NSArray.arrayWithObject(matchedCals[0]); + var pred = store.predicateForEventsWithStartDateEndDateCalendars(winStart, winEnd, calArr); + var events = store.eventsMatchingPredicate(pred); + + function matchesRecurrence(ev, expected) { + var hasRules = Boolean(ev.hasRecurrenceRules); + if (expected === 'none') return !hasRules; + if (!hasRules) return false; + var rules = ev.recurrenceRules; + if (!rules || rules.count === 0) return false; + var rule = rules.objectAtIndex(0); + var freq = rule.frequency; + if (expected === 'daily') return freq === 0; + if (expected === 'weekly') return freq === 1; + if (expected === 'weekdays') { + if (freq !== 1) return false; + var days = rule.daysOfTheWeek; + if (!days || days.count !== 5) return false; + var seen = {}; + for (var d = 0; d < days.count; d++) { + seen[days.objectAtIndex(d).dayOfTheWeek] = true; + } + return Boolean(seen[2] && seen[3] && seen[4] && seen[5] && seen[6]); + } + return false; + } + + for (var j = 0; j < events.count; j++) { + var ev = events.objectAtIndex(j); + var title = ObjC.unwrap(ev.title); + if (title !== targetTitle) continue; + var uid = ObjC.unwrap(ev.eventIdentifier) || ''; + if (targetUid && uid !== targetUid) continue; + var sd = new Date(ev.startDate.timeIntervalSince1970 * 1000.0); + if ( + sd.getFullYear() !== sYear || + sd.getMonth() + 1 !== sMonth || + sd.getDate() !== sDay || + sd.getHours() !== sHour || + sd.getMinutes() !== sMin + ) { + continue; + } + if (hasEnd) { + var ed = new Date(ev.endDate.timeIntervalSince1970 * 1000.0); + if ( + ed.getFullYear() !== eYear || + ed.getMonth() + 1 !== eMonth || + ed.getDate() !== eDay || + ed.getHours() !== eHour || + ed.getMinutes() !== eMin + ) { + continue; + } + } + if (!matchesRecurrence(ev, recurrence)) continue; + return JSON.stringify({status: 'FOUND', event_uid: uid}); + } + return JSON.stringify({status: 'NOT_FOUND', event_uid: null}); +} +""".strip() + #: Registry hives a source may read. Per-user settings and machine settings; #: nothing else is needed for read-back. REGISTRY_HIVES = ("HKCU", "HKLM") Runner = Callable[[list[str]], "subprocess.CompletedProcess[bytes]"] +NightShiftReader = Callable[[], bool] + + +def parse_windows_night_light_bytes(raw: Any) -> bool: + """Decode Windows Night Light ``Data`` bytes into ``True``/``False``. + + Windows 10/11 stores the Night Light state in byte 18 of the CloudStore + ``Data`` blob: ``0x15`` when enabled, ``0x13`` when disabled. Any missing, + truncated, non-bytes, or unexpected byte pattern raises ``_Unreadable`` + (fail-closed). + """ + if not isinstance(raw, (bytes, bytearray)): + raise _Unreadable("windows_night_light Data value is not binary bytes") + if len(raw) <= _WINDOWS_NIGHT_LIGHT_STATE_BYTE_INDEX: + raise _Unreadable(f"windows_night_light Data blob too short ({len(raw)} bytes)") + state_byte = raw[_WINDOWS_NIGHT_LIGHT_STATE_BYTE_INDEX] + if state_byte == _WINDOWS_NIGHT_LIGHT_ENABLED_BYTE: + return True + if state_byte == _WINDOWS_NIGHT_LIGHT_DISABLED_BYTE: + return False + raise _Unreadable(f"windows_night_light unexpected state byte 0x{state_byte:02x}") + + +def _read_core_brightness_night_shift() -> bool: + """Read macOS Night Shift enabled state via CoreBrightness (read-only). + + Uses ``CBBlueLightClient.getBlueLightStatus:`` through ``libobjc.A.dylib`` + with zero writes and zero third-party dependencies. Raises ``_Unreadable`` + if the framework, class, or status query is unavailable. + """ + + class _CBTime(ctypes.Structure): + _fields_ = [("hour", ctypes.c_int), ("minute", ctypes.c_int)] + + class _CBSchedule(ctypes.Structure): + _fields_ = [("fromTime", _CBTime), ("toTime", _CBTime)] + + class _CBStatusData(ctypes.Structure): + _fields_ = [ + ("active", ctypes.c_bool), + ("enabled", ctypes.c_bool), + ("sunSchedulePermitted", ctypes.c_bool), + ("mode", ctypes.c_int), + ("schedule", _CBSchedule), + ("disableFlags", ctypes.c_ulonglong), + ("available", ctypes.c_bool), + ] + + try: + objc = ctypes.cdll.LoadLibrary("/usr/lib/libobjc.A.dylib") + ctypes.cdll.LoadLibrary( + "/System/Library/PrivateFrameworks/CoreBrightness.framework/CoreBrightness" + ) + except OSError as exc: + raise _Unreadable(f"CoreBrightness unavailable: {exc}") from exc + + objc.objc_getClass.argtypes = [ctypes.c_char_p] + objc.objc_getClass.restype = ctypes.c_void_p + objc.sel_registerName.argtypes = [ctypes.c_char_p] + objc.sel_registerName.restype = ctypes.c_void_p + + cls = objc.objc_getClass(b"CBBlueLightClient") + if not cls: + raise _Unreadable("CBBlueLightClient class not found") + + msg_send_id = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p)( + ("objc_msgSend", objc) + ) + msg_send_status = ctypes.CFUNCTYPE( + ctypes.c_bool, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.POINTER(_CBStatusData), + )(("objc_msgSend", objc)) + msg_send_void = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p)( + ("objc_msgSend", objc) + ) + + alloc_sel = objc.sel_registerName(b"alloc") + init_sel = objc.sel_registerName(b"init") + get_sel = objc.sel_registerName(b"getBlueLightStatus:") + release_sel = objc.sel_registerName(b"release") + + allocated = msg_send_id(cls, alloc_sel) + if not allocated: + raise _Unreadable("CBBlueLightClient alloc returned null") + client = msg_send_id(allocated, init_sel) + if not client: + raise _Unreadable("CBBlueLightClient init returned null") + try: + status = _CBStatusData() + ok = bool(msg_send_status(client, get_sel, ctypes.byref(status))) + if not ok: + raise _Unreadable("CBBlueLightClient.getBlueLightStatus: returned false") + if not status.available: + raise _Unreadable("Night Shift is not available on this display") + return bool(status.enabled) + finally: + msg_send_void(client, release_sel) class _Unreadable(Exception): @@ -175,6 +409,7 @@ def __init__( runner: Optional[Runner] = None, registry: Any = None, platform: Optional[str] = None, + night_shift_reader: Optional[NightShiftReader] = None, session: Any = None, ) -> None: if not sources: @@ -190,6 +425,9 @@ def __init__( self._runner = runner or _run self._registry = registry self._platform = platform or _SYS_PLATFORM + self._night_shift_reader = ( + night_shift_reader or _read_core_brightness_night_shift + ) #: Why the last read was unreadable, for the verdict's detail. self.last_error: Optional[str] = None @@ -333,6 +571,165 @@ def _read_registry(self, source: WindowsRegistrySource) -> dict[str, Any]: ) return record + def _read_macos_night_shift(self, source: MacosNightShiftSource) -> dict[str, Any]: + if self._platform != "darwin": + raise _Unreadable(f"{source.id}: macos_night_shift needs macOS") + try: + enabled = self._night_shift_reader() + except _Unreadable as exc: + raise _Unreadable(f"{source.id}: {exc}") from exc + except Exception as exc: # noqa: BLE001 - fail closed on any probe error + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + if not isinstance(enabled, bool): + raise _Unreadable(f"{source.id}: night shift reader did not return a bool") + return { + "id": source.id, + "type": source.type, + "present": True, + "enabled": enabled, + "value": value_text(enabled), + "value_type": "boolean", + } + + def _read_windows_night_light( + self, source: WindowsNightLightSource + ) -> dict[str, Any]: + try: + reg = self._winreg() + except _Unreadable as exc: + raise _Unreadable(f"{source.id}: {exc}") from exc + hive = reg.HKEY_CURRENT_USER + try: + key = reg.OpenKey(hive, WINDOWS_NIGHT_LIGHT_REG_PATH, 0, reg.KEY_READ) + except FileNotFoundError as exc: + raise _Unreadable( + f"{source.id}: Windows Night Light registry key does not exist" + ) from exc + except OSError as exc: + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + try: + with key: + value, _kind = reg.QueryValueEx(key, WINDOWS_NIGHT_LIGHT_VALUE_NAME) + except FileNotFoundError as exc: + raise _Unreadable( + f"{source.id}: Windows Night Light Data value missing" + ) from exc + except OSError as exc: + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + try: + enabled = parse_windows_night_light_bytes(value) + except _Unreadable as exc: + raise _Unreadable(f"{source.id}: {exc}") from exc + return { + "id": source.id, + "type": source.type, + "present": True, + "enabled": enabled, + "value": value_text(enabled), + "value_type": "boolean", + } + + def _read_macos_calendar_event( + self, source: MacosCalendarEventSource + ) -> dict[str, Any]: + if self._platform != "darwin": + raise _Unreadable(f"{source.id}: macos_calendar_event needs macOS") + + def _parse_local(iso_text: str, field_name: str) -> datetime: + normalized = ( + iso_text[:-1] + "+00:00" if iso_text.endswith("Z") else iso_text + ) + try: + parsed = datetime.fromisoformat(normalized) + except ValueError as exc: + raise _Unreadable(f"{source.id}: invalid {field_name}") from exc + # Convert timezone-aware timestamps to local system time so EventKit + # local wall-clock comparisons match regardless of input offset. + if parsed.tzinfo is not None: + parsed = parsed.astimezone() + return parsed + + start_dt = _parse_local(source.start_iso, "start_iso") + end_dt = ( + _parse_local(source.end_iso, "end_iso") + if source.end_iso is not None + else None + ) + argv = [ + OSASCRIPT_BINARY, + "-l", + "JavaScript", + "-e", + _MACOS_EVENTKIT_READ_SCRIPT, + "--", + source.calendar_name, + source.title, + str(start_dt.year), + str(start_dt.month), + str(start_dt.day), + str(start_dt.hour), + str(start_dt.minute), + str(end_dt.year) if end_dt is not None else "", + str(end_dt.month) if end_dt is not None else "", + str(end_dt.day) if end_dt is not None else "", + str(end_dt.hour) if end_dt is not None else "", + str(end_dt.minute) if end_dt is not None else "", + source.recurrence, + source.event_uid or "", + ] + try: + done = self._runner(argv) + except (OSError, subprocess.SubprocessError) as exc: + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + if done.returncode != 0: + raise _Unreadable(f"{source.id}: osascript exited {done.returncode}") + output = done.stdout.decode("utf-8", errors="replace").strip() + try: + payload = json.loads(output) + except json.JSONDecodeError as exc: + raise _Unreadable( + f"{source.id}: unexpected EventKit probe output {output!r}" + ) from exc + if not isinstance(payload, dict): + raise _Unreadable( + f"{source.id}: EventKit probe output is not a JSON object" + ) + status = payload.get("status") + if status == "UNAUTHORIZED": + raise _Unreadable( + f"{source.id}: macOS EventKit calendar access not authorized" + ) + if status == "NO_CALENDAR": + raise _Unreadable( + f"{source.id}: calendar {source.calendar_name!r} does not exist" + ) + if status == "AMBIGUOUS_CALENDAR": + raise _Unreadable( + f"{source.id}: multiple calendars named {source.calendar_name!r}; refusing ambiguous match" + ) + if status == "FOUND": + exists = True + elif status == "NOT_FOUND": + exists = False + else: + raise _Unreadable(f"{source.id}: unexpected EventKit status {status!r}") + raw_uid = payload.get("event_uid") + event_uid = str(raw_uid) if isinstance(raw_uid, str) and raw_uid else None + return { + "id": source.id, + "type": source.type, + "present": exists, + "exists": exists, + "event_uid": event_uid, + "calendar_name": source.calendar_name, + "title": source.title, + "start_iso": source.start_iso, + "end_iso": source.end_iso, + "recurrence": source.recurrence, + "value": value_text(exists), + "value_type": "boolean", + } + def read(self) -> Optional[list[dict[str, Any]]]: """One read of every source, or ``None`` when any source is unreadable.""" cache: dict[str, dict[str, Any]] = {} @@ -343,8 +740,18 @@ def read(self) -> Optional[list[dict[str, Any]]]: records.append(self._read_file(source)) elif isinstance(source, MacosDefaultsSource): records.append(self._read_defaults(source, cache)) - else: + elif isinstance(source, WindowsRegistrySource): records.append(self._read_registry(source)) + elif isinstance(source, MacosNightShiftSource): + records.append(self._read_macos_night_shift(source)) + elif isinstance(source, WindowsNightLightSource): + records.append(self._read_windows_night_light(source)) + elif isinstance(source, MacosCalendarEventSource): + records.append(self._read_macos_calendar_event(source)) + else: + raise _Unreadable( + f"unsupported local-state source type: {type(source).__name__}" + ) except _Unreadable as exc: self.last_error = str(exc) return None @@ -392,9 +799,16 @@ def verify( "FileSource", "LocalStateSource", "LocalStateVerifier", + "MacosCalendarEventSource", "MacosDefaultsSource", + "MacosNightShiftSource", + "OSASCRIPT_BINARY", "REGISTRY_HIVES", "TEXT_LIMIT", + "WINDOWS_NIGHT_LIGHT_REG_PATH", + "WINDOWS_NIGHT_LIGHT_VALUE_NAME", + "WindowsNightLightSource", "WindowsRegistrySource", + "parse_windows_night_light_bytes", "value_text", ] diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index e4cef9191e..afc8e9d081 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -1442,8 +1442,11 @@ "examples/claude-code-demo/policy.yaml", "examples/legacy_records/answers.demo.json", "examples/legacy_records/answers.ledger.demo.json", + "examples/local_state/macos-calendar-block/verify.yaml", + "examples/local_state/macos-night-shift/verify.yaml", "examples/local_state/notepad-save/verify.yaml", "examples/local_state/windows-dark-mode/verify.yaml", + "examples/local_state/windows-night-light/verify.yaml", "import_direction_debt.json", "import_layers.json", "import_layers_debt.json", diff --git a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json index 465fd41c4a..fb17d062c5 100644 --- a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json +++ b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json @@ -1069,7 +1069,7 @@ "type": "object" }, "AuthRef": { - "description": "A reference to an HTTP credential held OUTSIDE the config.\n\nExactly one auth style may be set:\n\n- ``bearer_env`` -- name of an env var holding a bearer token; resolves to\n ``Authorization: Bearer ``.\n- ``header`` + ``value_env`` -- an arbitrary auth header (e.g.\n ``X-API-Key``) whose VALUE comes from the named env var. Frappe-style\n ``Authorization: token :`` fits here too (put the whole\n value in the env var).\n- ``basic_env`` -- name of an env var holding ``user:password``; resolves\n to ``Authorization: Basic ``.\n\nNo field ever holds the secret itself -- only the env var NAME.", + "description": "A reference to an HTTP credential held OUTSIDE the config.\n\nExactly one auth style may be set:\n\n- ``bearer_env`` -- name of an env var holding a bearer token; resolves to\n ``Authorization: Bearer ``.\n- ``header`` + ``value_env`` -- an arbitrary auth header (e.g.\n ``X-API-Key``) whose VALUE comes from the named env var. Token-pair\n ``Authorization: token :`` fits here too (put the whole\n value in the env var).\n- ``basic_env`` -- name of an env var holding ``user:password``; resolves\n to ``Authorization: Basic ``.\n\nNo field ever holds the secret itself -- only the env var NAME.", "properties": { "bearer_env": { "anyOf": [ @@ -2413,7 +2413,10 @@ "discriminator": { "mapping": { "file": "#/$defs/FileSource", + "macos_calendar_event": "#/$defs/MacosCalendarEventSource", "macos_defaults": "#/$defs/MacosDefaultsSource", + "macos_night_shift": "#/$defs/MacosNightShiftSource", + "windows_night_light": "#/$defs/WindowsNightLightSource", "windows_registry": "#/$defs/WindowsRegistrySource" }, "propertyName": "type" @@ -2427,6 +2430,15 @@ }, { "$ref": "#/$defs/WindowsRegistrySource" + }, + { + "$ref": "#/$defs/MacosNightShiftSource" + }, + { + "$ref": "#/$defs/WindowsNightLightSource" + }, + { + "$ref": "#/$defs/MacosCalendarEventSource" } ] }, @@ -3247,6 +3259,87 @@ "title": "IdentitySection", "type": "object" }, + "MacosCalendarEventSource": { + "additionalProperties": false, + "description": "Read-only check for a macOS EventKit calendar event.\n\nMatches exact calendar name (rejecting ambiguous duplicates), case-sensitive\ntitle, local-timezone start/end time to the minute, recurrence cadence, and\noptional ``event_uid``.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "macos_calendar_event", + "default": "macos_calendar_event", + "title": "Type", + "type": "string" + }, + "calendar_name": { + "maxLength": 255, + "minLength": 1, + "title": "Calendar Name", + "type": "string" + }, + "title": { + "maxLength": 255, + "minLength": 1, + "title": "Title", + "type": "string" + }, + "start_iso": { + "maxLength": 64, + "minLength": 10, + "title": "Start Iso", + "type": "string" + }, + "end_iso": { + "anyOf": [ + { + "maxLength": 64, + "minLength": 10, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "End Iso" + }, + "recurrence": { + "default": "none", + "enum": [ + "none", + "daily", + "weekly", + "weekdays" + ], + "title": "Recurrence", + "type": "string" + }, + "event_uid": { + "anyOf": [ + { + "maxLength": 255, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Event Uid" + } + }, + "required": [ + "id", + "calendar_name", + "title", + "start_iso" + ], + "title": "MacosCalendarEventSource", + "type": "object" + }, "MacosDefaultsSource": { "additionalProperties": false, "description": "One key in a macOS preferences domain.", @@ -3280,6 +3373,27 @@ "title": "MacosDefaultsSource", "type": "object" }, + "MacosNightShiftSource": { + "additionalProperties": false, + "description": "Current macOS Night Shift enabled state via CoreBrightness (read-only).", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "macos_night_shift", + "default": "macos_night_shift", + "title": "Type", + "type": "string" + } + }, + "required": [ + "id" + ], + "title": "MacosNightShiftSource", + "type": "object" + }, "OpenStep": { "additionalProperties": false, "description": "Open the record from a results list: the one row showing the identity.", @@ -4811,6 +4925,27 @@ "title": "ValueExpr", "type": "object" }, + "WindowsNightLightSource": { + "additionalProperties": false, + "description": "Current Windows Night Light enabled state via CloudStore registry Data bytes.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "windows_night_light", + "default": "windows_night_light", + "title": "Type", + "type": "string" + } + }, + "required": [ + "id" + ], + "title": "WindowsNightLightSource", + "type": "object" + }, "WindowsRegistrySource": { "additionalProperties": false, "description": "One value in the Windows registry.", @@ -5110,7 +5245,7 @@ "validation": { "$defs": { "AuthRef": { - "description": "A reference to an HTTP credential held OUTSIDE the config.\n\nExactly one auth style may be set:\n\n- ``bearer_env`` -- name of an env var holding a bearer token; resolves to\n ``Authorization: Bearer ``.\n- ``header`` + ``value_env`` -- an arbitrary auth header (e.g.\n ``X-API-Key``) whose VALUE comes from the named env var. Frappe-style\n ``Authorization: token :`` fits here too (put the whole\n value in the env var).\n- ``basic_env`` -- name of an env var holding ``user:password``; resolves\n to ``Authorization: Basic ``.\n\nNo field ever holds the secret itself -- only the env var NAME.", + "description": "A reference to an HTTP credential held OUTSIDE the config.\n\nExactly one auth style may be set:\n\n- ``bearer_env`` -- name of an env var holding a bearer token; resolves to\n ``Authorization: Bearer ``.\n- ``header`` + ``value_env`` -- an arbitrary auth header (e.g.\n ``X-API-Key``) whose VALUE comes from the named env var. Token-pair\n ``Authorization: token :`` fits here too (put the whole\n value in the env var).\n- ``basic_env`` -- name of an env var holding ``user:password``; resolves\n to ``Authorization: Basic ``.\n\nNo field ever holds the secret itself -- only the env var NAME.", "properties": { "bearer_env": { "anyOf": [ @@ -6133,7 +6268,10 @@ "discriminator": { "mapping": { "file": "#/$defs/FileSource", + "macos_calendar_event": "#/$defs/MacosCalendarEventSource", "macos_defaults": "#/$defs/MacosDefaultsSource", + "macos_night_shift": "#/$defs/MacosNightShiftSource", + "windows_night_light": "#/$defs/WindowsNightLightSource", "windows_registry": "#/$defs/WindowsRegistrySource" }, "propertyName": "type" @@ -6147,6 +6285,15 @@ }, { "$ref": "#/$defs/WindowsRegistrySource" + }, + { + "$ref": "#/$defs/MacosNightShiftSource" + }, + { + "$ref": "#/$defs/WindowsNightLightSource" + }, + { + "$ref": "#/$defs/MacosCalendarEventSource" } ] }, @@ -6563,6 +6710,87 @@ "title": "HistoryView", "type": "object" }, + "MacosCalendarEventSource": { + "additionalProperties": false, + "description": "Read-only check for a macOS EventKit calendar event.\n\nMatches exact calendar name (rejecting ambiguous duplicates), case-sensitive\ntitle, local-timezone start/end time to the minute, recurrence cadence, and\noptional ``event_uid``.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "macos_calendar_event", + "default": "macos_calendar_event", + "title": "Type", + "type": "string" + }, + "calendar_name": { + "maxLength": 255, + "minLength": 1, + "title": "Calendar Name", + "type": "string" + }, + "title": { + "maxLength": 255, + "minLength": 1, + "title": "Title", + "type": "string" + }, + "start_iso": { + "maxLength": 64, + "minLength": 10, + "title": "Start Iso", + "type": "string" + }, + "end_iso": { + "anyOf": [ + { + "maxLength": 64, + "minLength": 10, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "End Iso" + }, + "recurrence": { + "default": "none", + "enum": [ + "none", + "daily", + "weekly", + "weekdays" + ], + "title": "Recurrence", + "type": "string" + }, + "event_uid": { + "anyOf": [ + { + "maxLength": 255, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Event Uid" + } + }, + "required": [ + "id", + "calendar_name", + "title", + "start_iso" + ], + "title": "MacosCalendarEventSource", + "type": "object" + }, "MacosDefaultsSource": { "additionalProperties": false, "description": "One key in a macOS preferences domain.", @@ -6596,6 +6824,27 @@ "title": "MacosDefaultsSource", "type": "object" }, + "MacosNightShiftSource": { + "additionalProperties": false, + "description": "Current macOS Night Shift enabled state via CoreBrightness (read-only).", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "macos_night_shift", + "default": "macos_night_shift", + "title": "Type", + "type": "string" + } + }, + "required": [ + "id" + ], + "title": "MacosNightShiftSource", + "type": "object" + }, "OpenStep": { "additionalProperties": false, "description": "Open the record from a results list: the one row showing the identity.", @@ -7456,6 +7705,27 @@ "title": "ValueExpr", "type": "object" }, + "WindowsNightLightSource": { + "additionalProperties": false, + "description": "Current Windows Night Light enabled state via CloudStore registry Data bytes.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "windows_night_light", + "default": "windows_night_light", + "title": "Type", + "type": "string" + } + }, + "required": [ + "id" + ], + "title": "WindowsNightLightSource", + "type": "object" + }, "WindowsRegistrySource": { "additionalProperties": false, "description": "One value in the Windows registry.", diff --git a/packages/flow/tests/test_everyday_local_state_probes.py b/packages/flow/tests/test_everyday_local_state_probes.py new file mode 100644 index 0000000000..4a34e2d440 --- /dev/null +++ b/packages/flow/tests/test_everyday_local_state_probes.py @@ -0,0 +1,524 @@ +"""Unit tests for read-only everyday OS local-state probes. + +Covers: +1. ``macos_night_shift`` (CoreBrightness ``CBBlueLightClient`` read-only probe) +2. ``windows_night_light`` (HKCU CloudStore ``Data`` bytes ``0x15`` vs ``0x13``) +3. ``macos_calendar_event`` (fixed read-only AppleScript probe via argv) + +Every probe is verified for valid states, malformed/missing inputs, and wrong-OS +fail-closed ``INDETERMINATE`` behavior. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from datetime import datetime +from pathlib import Path +from typing import Any + +import pytest + +from openadapt_flow.local_state_sources import ( + MacosCalendarEventSource, + MacosNightShiftSource, + WindowsNightLightSource, +) +from openadapt_flow.runtime.effects.effect import Effect, EffectKind, Verdict +from openadapt_flow.runtime.effects.local_state import ( + OSASCRIPT_BINARY, + WINDOWS_NIGHT_LIGHT_REG_PATH, + WINDOWS_NIGHT_LIGHT_VALUE_NAME, + LocalStateVerifier, + _Unreadable, + parse_windows_night_light_bytes, +) +from openadapt_flow.verify_run import VerifyConfig + + +class _FakeKey: + def __init__(self, values: dict[str, tuple[Any, int]]) -> None: + self._values = values + + def __enter__(self) -> "_FakeKey": + return self + + def __exit__(self, *args: object) -> None: + return None + + +class _FakeWinReg: + HKEY_CURRENT_USER = 1 + HKEY_LOCAL_MACHINE = 2 + KEY_READ = 0x20019 + REG_BINARY = 3 + + def __init__(self, tree: dict[tuple[int, str], dict[str, tuple[Any, int]]]) -> None: + self._tree = tree + + def OpenKey(self, hive: int, path: str, _reserved: int, access: int) -> _FakeKey: + assert access == self.KEY_READ, "registry reads must use KEY_READ only" + key = (hive, path) + if key not in self._tree: + raise FileNotFoundError(path) + return _FakeKey(self._tree[key]) + + def QueryValueEx(self, key: _FakeKey, name: str) -> tuple[Any, int]: + if name not in key._values: + raise FileNotFoundError(name) + return key._values[name] + + +def _make_cloudstore_blob(state_byte: int, length: int = 43) -> bytes: + buf = bytearray(length) + buf[0:4] = b"\x43\x42\x01\x00" + buf[18] = state_byte + if state_byte == 0x15 and length >= 25: + buf[23:25] = b"\x10\x00" + return bytes(buf) + + +# --- macos_night_shift ------------------------------------------------------ + + +def test_macos_night_shift_reads_enabled_and_disabled() -> None: + src = MacosNightShiftSource(id="ns") + v_on = LocalStateVerifier([src], platform="darwin", night_shift_reader=lambda: True) + rec_on = v_on.read() + assert rec_on == [ + { + "id": "ns", + "type": "macos_night_shift", + "present": True, + "enabled": True, + "value": "true", + "value_type": "boolean", + } + ] + + v_off = LocalStateVerifier( + [src], platform="darwin", night_shift_reader=lambda: False + ) + rec_off = v_off.read() + assert rec_off is not None + assert rec_off[0]["enabled"] is False + assert rec_off[0]["value"] == "false" + + +@pytest.mark.parametrize("bad_platform", ["linux", "win32"]) +def test_macos_night_shift_fails_closed_on_wrong_os(bad_platform: str) -> None: + src = MacosNightShiftSource(id="ns") + v = LocalStateVerifier( + [src], platform=bad_platform, night_shift_reader=lambda: True + ) + before = v.capture_pre_state() + assert before.reachable is False + assert v.read() is None + assert v.last_error is not None and "needs macOS" in v.last_error + + +def test_macos_night_shift_fails_closed_when_probe_unavailable() -> None: + src = MacosNightShiftSource(id="ns") + + def _boom() -> bool: + raise _Unreadable("CoreBrightness unavailable") + + v = LocalStateVerifier([src], platform="darwin", night_shift_reader=_boom) + before = v.capture_pre_state() + assert before.reachable is False + verdict = v.verify( + Effect( + kind=EffectKind.FIELD_EQUALS, + match={"id": "ns"}, + field="value", + value="true", + settle_timeout_s=0.0, + ), + before, + ) + assert verdict.confirmed is False + assert verdict.verdict == Verdict.INDETERMINATE + + +@pytest.mark.skipif( + sys.platform != "darwin" or os.environ.get("OPENADAPT_LIVE_OS_PROBES") != "1", + reason="opt-in macOS-only live CoreBrightness probe (set OPENADAPT_LIVE_OS_PROBES=1)", +) +def test_macos_night_shift_live_readonly_probe_on_mac() -> None: + """Exercise the real CoreBrightness ctypes reader read-only on macOS.""" + src = MacosNightShiftSource(id="ns") + v = LocalStateVerifier([src], platform="darwin") + records = v.read() + if records is None: + # On headless Macs without Night Shift hardware, probe must fail closed cleanly. + assert v.last_error is not None + else: + assert len(records) == 1 + assert isinstance(records[0]["enabled"], bool) + assert records[0]["value"] in ("true", "false") + + +# --- windows_night_light ---------------------------------------------------- + + +def test_parse_windows_night_light_bytes_valid_and_invalid() -> None: + assert parse_windows_night_light_bytes(_make_cloudstore_blob(0x15, 43)) is True + assert parse_windows_night_light_bytes(_make_cloudstore_blob(0x13, 41)) is False + + for bad in (b"", b"\x15" * 18, _make_cloudstore_blob(0x00, 41), "not-bytes", 123): + with pytest.raises(_Unreadable): + parse_windows_night_light_bytes(bad) + + +def test_windows_night_light_reads_enabled_and_disabled() -> None: + src = WindowsNightLightSource(id="nl") + reg_on = _FakeWinReg( + { + (_FakeWinReg.HKEY_CURRENT_USER, WINDOWS_NIGHT_LIGHT_REG_PATH): { + WINDOWS_NIGHT_LIGHT_VALUE_NAME: ( + _make_cloudstore_blob(0x15, 43), + _FakeWinReg.REG_BINARY, + ) + } + } + ) + v_on = LocalStateVerifier([src], platform="win32", registry=reg_on) + rec_on = v_on.read() + assert rec_on == [ + { + "id": "nl", + "type": "windows_night_light", + "present": True, + "enabled": True, + "value": "true", + "value_type": "boolean", + } + ] + + reg_off = _FakeWinReg( + { + (_FakeWinReg.HKEY_CURRENT_USER, WINDOWS_NIGHT_LIGHT_REG_PATH): { + WINDOWS_NIGHT_LIGHT_VALUE_NAME: ( + _make_cloudstore_blob(0x13, 41), + _FakeWinReg.REG_BINARY, + ) + } + } + ) + v_off = LocalStateVerifier([src], platform="win32", registry=reg_off) + rec_off = v_off.read() + assert rec_off is not None + assert rec_off[0]["enabled"] is False + assert rec_off[0]["value"] == "false" + + +def test_windows_night_light_fails_closed_on_missing_key_value_malformed_and_wrong_os() -> ( + None +): + src = WindowsNightLightSource(id="nl") + + # Wrong OS without injected registry + v_wrong_os = LocalStateVerifier([src], platform="darwin") + assert v_wrong_os.read() is None + + # Missing registry key + v_no_key = LocalStateVerifier([src], platform="win32", registry=_FakeWinReg({})) + assert v_no_key.read() is None + assert v_no_key.last_error is not None and "does not exist" in v_no_key.last_error + + # Missing Data value + v_no_val = LocalStateVerifier( + [src], + platform="win32", + registry=_FakeWinReg( + {(_FakeWinReg.HKEY_CURRENT_USER, WINDOWS_NIGHT_LIGHT_REG_PATH): {}} + ), + ) + assert v_no_val.read() is None + assert v_no_val.last_error is not None and "missing" in v_no_val.last_error + + # Malformed bytes -> INDETERMINATE + v_bad_bytes = LocalStateVerifier( + [src], + platform="win32", + registry=_FakeWinReg( + { + (_FakeWinReg.HKEY_CURRENT_USER, WINDOWS_NIGHT_LIGHT_REG_PATH): { + WINDOWS_NIGHT_LIGHT_VALUE_NAME: ( + _make_cloudstore_blob(0x99, 41), + _FakeWinReg.REG_BINARY, + ) + } + } + ), + ) + before = v_bad_bytes.capture_pre_state() + assert before.reachable is False + verdict = v_bad_bytes.verify( + Effect( + kind=EffectKind.FIELD_EQUALS, + match={"id": "nl"}, + field="value", + value="true", + settle_timeout_s=0.0, + ), + before, + ) + assert verdict.confirmed is False + assert verdict.verdict == Verdict.INDETERMINATE + + +# --- macos_calendar_event --------------------------------------------------- + + +def test_macos_calendar_event_found_not_found_timezone_and_argv_safety() -> None: + captured_argv: list[list[str]] = [] + + def _runner_found(argv: list[str]) -> subprocess.CompletedProcess[bytes]: + captured_argv.append(argv) + return subprocess.CompletedProcess( + argv, + 0, + json.dumps({"status": "FOUND", "event_uid": "evt-uid-1"}).encode(), + b"", + ) + + src = MacosCalendarEventSource( + id="cal", + calendar_name="Work", + title='Focus "Block" & Sync', + start_iso="2026-11-24T10:30:00", + end_iso="2026-11-24T11:00:00", + recurrence="weekly", + event_uid="evt-uid-1", + ) + v_found = LocalStateVerifier([src], platform="darwin", runner=_runner_found) + rec = v_found.read() + assert rec == [ + { + "id": "cal", + "type": "macos_calendar_event", + "present": True, + "exists": True, + "event_uid": "evt-uid-1", + "calendar_name": "Work", + "title": 'Focus "Block" & Sync', + "start_iso": "2026-11-24T10:30:00", + "end_iso": "2026-11-24T11:00:00", + "recurrence": "weekly", + "value": "true", + "value_type": "boolean", + } + ] + # Verify absolute osascript path, JXA EventKit (zero app names), and argv isolation + assert captured_argv[0][0:4] == [OSASCRIPT_BINARY, "-l", "JavaScript", "-e"] + assert 'tell application "Calendar"' not in captured_argv[0][4] + assert 'Focus "Block" & Sync' not in captured_argv[0][4] + assert captured_argv[0][5:] == [ + "--", + "Work", + 'Focus "Block" & Sync', + "2026", + "11", + "24", + "10", + "30", + "2026", + "11", + "24", + "11", + "0", + "weekly", + "evt-uid-1", + ] + + # Timezone-aware UTC timestamp must be converted to local system time before argv + utc_src = MacosCalendarEventSource( + id="cal_tz", + calendar_name="Work", + title="UTC Block", + start_iso="2026-11-24T15:00:00Z", + end_iso="2026-11-24T15:30:00Z", + ) + tz_argv: list[list[str]] = [] + + def _runner_tz(argv: list[str]) -> subprocess.CompletedProcess[bytes]: + tz_argv.append(argv) + return subprocess.CompletedProcess( + argv, + 0, + json.dumps({"status": "NOT_FOUND", "event_uid": None}).encode(), + b"", + ) + + v_tz = LocalStateVerifier([utc_src], platform="darwin", runner=_runner_tz) + rec_missing = v_tz.read() + assert rec_missing is not None + assert rec_missing[0]["present"] is False + assert rec_missing[0]["exists"] is False + assert rec_missing[0]["value"] == "false" + expected_local_start = datetime.fromisoformat( + "2026-11-24T15:00:00+00:00" + ).astimezone() + assert tz_argv[0][8:13] == [ + str(expected_local_start.year), + str(expected_local_start.month), + str(expected_local_start.day), + str(expected_local_start.hour), + str(expected_local_start.minute), + ] + + +def test_macos_calendar_event_fails_closed_on_errors_and_wrong_os() -> None: + src = MacosCalendarEventSource( + id="cal", + calendar_name="Calendar", + title="Standup", + start_iso="2026-11-24T09:00:00", + ) + + # Wrong OS + v_wrong = LocalStateVerifier( + [src], + platform="win32", + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"FOUND","event_uid":"u1"}\n', b"" + ), + ) + assert v_wrong.read() is None + + # Unauthorized EventKit + v_unauth = LocalStateVerifier( + [src], + platform="darwin", + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"UNAUTHORIZED"}\n', b"" + ), + ) + assert v_unauth.read() is None + assert v_unauth.last_error is not None and "not authorized" in v_unauth.last_error + + # Missing calendar container + v_no_cal = LocalStateVerifier( + [src], + platform="darwin", + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"NO_CALENDAR"}\n', b"" + ), + ) + assert v_no_cal.read() is None + assert v_no_cal.last_error is not None and "does not exist" in v_no_cal.last_error + + # Ambiguous duplicate calendar names + v_ambig = LocalStateVerifier( + [src], + platform="darwin", + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"AMBIGUOUS_CALENDAR"}\n', b"" + ), + ) + assert v_ambig.read() is None + assert v_ambig.last_error is not None and "multiple calendars" in v_ambig.last_error + + # osascript error + v_err = LocalStateVerifier( + [src], + platform="darwin", + runner=lambda argv: subprocess.CompletedProcess(argv, 1, b"", b"denied"), + ) + assert v_err.read() is None + + # Unexpected stdout + v_weird = LocalStateVerifier( + [src], + platform="darwin", + runner=lambda argv: subprocess.CompletedProcess(argv, 0, b"MAYBE\n", b""), + ) + assert v_weird.read() is None + + # EventKit JXA probe must require FullAccess (3) only — write-only (4) cannot read events + from openadapt_flow.runtime.effects.local_state import ( + _MACOS_EVENTKIT_READ_SCRIPT, + ) + + assert "if (auth !== 3)" in _MACOS_EVENTKIT_READ_SCRIPT + assert "auth !== 4" not in _MACOS_EVENTKIT_READ_SCRIPT + + +def test_macos_calendar_event_validation_rejects_bad_inputs() -> None: + with pytest.raises(ValueError, match="control characters"): + MacosCalendarEventSource( + id="cal", + calendar_name="Calendar\nBad", + title="Ok", + start_iso="2026-11-24T09:00:00", + ) + with pytest.raises(ValueError, match="ISO-8601"): + MacosCalendarEventSource( + id="cal", + calendar_name="Calendar", + title="Ok", + start_iso="not-a-timestamp", + ) + + +def test_verify_config_accepts_all_three_new_source_types(tmp_path: Path) -> None: + for doc in ( + { + "schema_version": "openadapt.verify/v1", + "verifier": { + "kind": "local-state", + "local_state": [{"type": "macos_night_shift", "id": "ns"}], + }, + "effects": [ + { + "kind": "field_equals", + "match": {"id": "ns"}, + "field": "value", + "value": "true", + } + ], + }, + { + "schema_version": "openadapt.verify/v1", + "verifier": { + "kind": "local-state", + "local_state": [{"type": "windows_night_light", "id": "nl"}], + }, + "effects": [ + { + "kind": "field_equals", + "match": {"id": "nl"}, + "field": "value", + "value": "false", + } + ], + }, + { + "schema_version": "openadapt.verify/v1", + "verifier": { + "kind": "local-state", + "local_state": [ + { + "type": "macos_calendar_event", + "id": "cal", + "calendar_name": "Calendar", + "title": "Deep Work", + "start_iso": "2026-11-24T10:00:00", + } + ], + }, + "effects": [ + { + "kind": "field_equals", + "match": {"id": "cal"}, + "field": "value", + "value": "true", + } + ], + }, + ): + cfg = VerifyConfig.model_validate(doc) + assert cfg.verifier.kind == "local-state" diff --git a/tests/test_everyday_quickstart.py b/tests/test_everyday_quickstart.py new file mode 100644 index 0000000000..fe02c9e575 --- /dev/null +++ b/tests/test_everyday_quickstart.py @@ -0,0 +1,317 @@ +"""Tests for ``openadapt quickstart --task night-shift`` and ``--task calendar-block``.""" + +from __future__ import annotations + +import json +import subprocess +from pathlib import Path + +import pytest +import yaml +from click.testing import CliRunner + +from openadapt.cli import main +from openadapt.quickstart.everyday import ( + EverydayTaskError, + build_calendar_block_contracts, + build_night_shift_contracts, + run_everyday_task, +) + +try: + from openadapt_flow.runtime.effects.local_state import LocalStateVerifier + from openadapt_flow.verify_run import VerifyConfig +except ImportError: # launcher CI installs released openadapt-flow without local_state + LocalStateVerifier = None # type: ignore[assignment] + VerifyConfig = None # type: ignore[assignment] + +_REQUIRES_LOCAL_STATE = pytest.mark.skipif( + LocalStateVerifier is None, + reason="openadapt_flow.runtime.effects.local_state not in installed openadapt-flow", +) + + +def test_build_night_shift_contracts_macos_and_windows_with_revert() -> None: + fwd_mac, rev_mac, params_mac = build_night_shift_contracts( + platform="darwin", baseline_enabled=False, revert=True + ) + assert fwd_mac["verifier"]["local_state"][0]["type"] == "macos_night_shift" + assert fwd_mac["effects"][0]["value"] == "true" + assert rev_mac is not None + assert rev_mac["effects"][0]["value"] == "false" + assert params_mac["target_enabled"] == "true" + assert params_mac["restore_enabled"] == "false" + if LocalStateVerifier is not None and VerifyConfig is not None: + VerifyConfig.model_validate(fwd_mac) + VerifyConfig.model_validate(rev_mac) + + fwd_win, rev_win, params_win = build_night_shift_contracts( + platform="win32", baseline_enabled=True, revert=False + ) + assert fwd_win["verifier"]["local_state"][0]["type"] == "windows_night_light" + assert fwd_win["effects"][0]["value"] == "false" + assert rev_win is None + assert params_win["revert"] is False + if LocalStateVerifier is not None and VerifyConfig is not None: + VerifyConfig.model_validate(fwd_win) + + # Unreadable baseline (None) must NOT invent a revert baseline + _fwd_unk, rev_unk, params_unk = build_night_shift_contracts( + platform="darwin", baseline_enabled=None, revert=True + ) + assert rev_unk is None + assert params_unk["restore_enabled"] is None + assert params_unk["revert_withheld_reason"] == "baseline_indeterminate" + + with pytest.raises(EverydayTaskError, match="unsupported platform"): + build_night_shift_contracts(platform="linux") + + +def test_build_calendar_block_contracts_parameterized_and_revert() -> None: + fwd, rev, params = build_calendar_block_contracts( + title="Weekly Architecture Review", + calendar_name="Engineering", + start_iso="2026-11-24T14:00:00", + duration_minutes=45, + recurrence="weekly", + platform="darwin", + revert=True, + ) + src = fwd["verifier"]["local_state"][0] + assert src["type"] == "macos_calendar_event" + assert src["calendar_name"] == "Engineering" + assert src["title"] == "Weekly Architecture Review" + assert src["start_iso"] == "2026-11-24T14:00:00" + assert fwd["effects"][0]["value"] == "true" + assert rev is not None + assert rev["effects"][0]["value"] == "false" + assert params["end_iso"] == "2026-11-24T14:45:00" + assert params["duration_minutes"] == 45 + assert params["recurrence"] == "weekly" + if LocalStateVerifier is not None and VerifyConfig is not None: + VerifyConfig.model_validate(fwd) + VerifyConfig.model_validate(rev) + + with pytest.raises(EverydayTaskError, match="duration"): + build_calendar_block_contracts(duration_minutes=0, platform="darwin") + with pytest.raises(EverydayTaskError, match="recurrence"): + build_calendar_block_contracts(recurrence="yearly", platform="darwin") + with pytest.raises(EverydayTaskError, match="unsupported platform"): + build_calendar_block_contracts(platform="linux") + + +@_REQUIRES_LOCAL_STATE +def test_run_everyday_task_night_shift_writes_contracts_and_probes_baseline( + tmp_path: Path, +) -> None: + lines: list[str] = [] + bundle = run_everyday_task( + "night-shift", + tmp_path / "ns", + platform="darwin", + revert=True, + say=lines.append, + verifier_factory=lambda sources, platform: LocalStateVerifier( + sources, platform=platform, night_shift_reader=lambda: False + ), + ) + assert bundle.baseline_state is not None + assert bundle.baseline_state["enabled"] is False + assert bundle.verify_path.is_file() + assert bundle.revert_verify_path is not None and bundle.revert_verify_path.is_file() + assert bundle.params_path.is_file() + + fwd = yaml.safe_load(bundle.verify_path.read_text(encoding="utf-8")) + rev = yaml.safe_load(bundle.revert_verify_path.read_text(encoding="utf-8")) + assert fwd["effects"][0]["value"] == "true" + assert rev["effects"][0]["value"] == "false" + assert any("Baseline probe (read-only)" in line for line in lines) + + +@_REQUIRES_LOCAL_STATE +def test_run_everyday_task_calendar_block_opt_in_probe_and_refuses_preexisting( + tmp_path: Path, +) -> None: + # 1. Default (probe_baseline=False) never invokes the EventKit probe + probe_called = False + + def _should_not_run(*_args: object, **_kwargs: object) -> object: + nonlocal probe_called + probe_called = True + raise AssertionError( + "baseline probe must not run by default for calendar-block" + ) + + bundle_default = run_everyday_task( + "calendar-block", + tmp_path / "cal-default", + title="Focus Sprint", + calendar_name="Work", + start_iso="2026-11-24T11:00:00", + duration_minutes=60, + recurrence="weekdays", + revert=True, + platform="darwin", + say=lambda _msg: None, + verifier_factory=_should_not_run, + ) + assert probe_called is False + assert bundle_default.baseline_state is None + params = json.loads(bundle_default.params_path.read_text(encoding="utf-8")) + assert params["title"] == "Focus Sprint" + assert params["end_iso"] == "2026-11-24T12:00:00" + assert params["recurrence"] == "weekdays" + assert params["revert_withheld_reason"] == "baseline_not_probed" + assert bundle_default.revert_verify_path is None + assert not (tmp_path / "cal-default" / "revert_verify.yaml").exists() + + # 1b. Explicit event_uid binds revert_verify.yaml even without --probe-baseline + bundle_uid = run_everyday_task( + "calendar-block", + tmp_path / "cal-uid", + title="Focus Sprint", + calendar_name="Work", + start_iso="2026-11-24T11:00:00", + duration_minutes=60, + recurrence="weekdays", + event_uid="EV-UID-123", + revert=True, + platform="darwin", + say=lambda _msg: None, + verifier_factory=_should_not_run, + ) + assert bundle_uid.revert_verify_path is not None + assert bundle_uid.revert_verify_path.is_file() + rev_uid_doc = yaml.safe_load( + bundle_uid.revert_verify_path.read_text(encoding="utf-8") + ) + assert rev_uid_doc["verifier"]["local_state"][0]["event_uid"] == "EV-UID-123" + + # 2. Opt-in probe_baseline=True with NOT_FOUND succeeds and writes revert_verify.yaml + bundle_probed = run_everyday_task( + "calendar-block", + tmp_path / "cal-probed", + title="Focus Sprint", + calendar_name="Work", + start_iso="2026-11-24T11:00:00", + duration_minutes=60, + recurrence="weekdays", + revert=True, + probe_baseline=True, + platform="darwin", + say=lambda _msg: None, + verifier_factory=lambda sources, platform: LocalStateVerifier( + sources, + platform=platform, + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"NOT_FOUND","event_uid":null}\n', b"" + ), + ), + ) + assert bundle_probed.baseline_state is not None + assert bundle_probed.baseline_state["exists"] is False + assert bundle_probed.revert_verify_path is not None + assert bundle_probed.revert_verify_path.is_file() + + # 2b. Opt-in probe_baseline=True returning INDETERMINATE (UNAUTHORIZED) withholds revert_verify.yaml + bundle_unauth = run_everyday_task( + "calendar-block", + tmp_path / "cal-unauth", + title="Focus Sprint", + calendar_name="Work", + start_iso="2026-11-24T11:00:00", + duration_minutes=60, + recurrence="weekdays", + revert=True, + probe_baseline=True, + platform="darwin", + say=lambda _msg: None, + verifier_factory=lambda sources, platform: LocalStateVerifier( + sources, + platform=platform, + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"UNAUTHORIZED"}\n', b"" + ), + ), + ) + assert bundle_unauth.baseline_state is None + assert bundle_unauth.revert_verify_path is None + unauth_params = json.loads(bundle_unauth.params_path.read_text(encoding="utf-8")) + assert unauth_params["revert_withheld_reason"] == "baseline_indeterminate" + + # 3. Opt-in probe_baseline=True when matching event ALREADY EXISTS refuses! + with pytest.raises(EverydayTaskError, match="already exists in the baseline"): + run_everyday_task( + "calendar-block", + tmp_path / "cal-existing", + title="Existing Meeting", + calendar_name="Work", + start_iso="2026-11-24T11:00:00", + duration_minutes=60, + recurrence="weekdays", + revert=True, + probe_baseline=True, + platform="darwin", + say=lambda _msg: None, + verifier_factory=lambda sources, platform: LocalStateVerifier( + sources, + platform=platform, + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"FOUND","event_uid":"existing-1"}\n', b"" + ), + ), + ) + + +def test_cli_quickstart_task_validation_and_invocation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + runner = CliRunner() + + # Calendar flags without --task calendar-block are rejected + bad = runner.invoke(main, ["quickstart", "--title", "Standup"]) + assert bad.exit_code != 0 + assert "--task calendar-block" in bad.output + + # --task combined with --own is rejected + bad_own = runner.invoke(main, ["quickstart", "--own", "--task", "night-shift"]) + assert bad_own.exit_code != 0 + assert "cannot be combined" in bad_own.output + + # Stub baseline probe so CLI invocation is deterministic on any OS + monkeypatch.setattr( + "openadapt.quickstart.everyday._probe_baseline", + lambda doc, platform, verifier_factory=None: ( + {"type": "macos_calendar_event", "value": "false", "exists": False}, + None, + ), + ) + monkeypatch.setattr("openadapt.quickstart.everyday.sys.platform", "darwin") + + out_dir = tmp_path / "cli-cal" + ok = runner.invoke( + main, + [ + "quickstart", + "--task", + "calendar-block", + "--title", + "Deep Work", + "--duration", + "45", + "--recurrence", + "daily", + "--start", + "2026-11-24T15:00:00", + "--probe-baseline", + "--out", + str(out_dir), + ], + ) + assert ok.exit_code == 0, ok.output + assert (out_dir / "verify.yaml").is_file() + assert (out_dir / "revert_verify.yaml").is_file() + params = json.loads((out_dir / "task.json").read_text(encoding="utf-8")) + assert params["title"] == "Deep Work" + assert params["end_iso"] == "2026-11-24T15:45:00" + assert params["recurrence"] == "daily"