Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Changelog

## Unreleased
- **Leave-by times from Apple Maps** (optional). Set `eta_from` to where your trips start, and the briefing shows when to leave for each event with a place, using Apple Maps' travel time for arriving at its start. Traffic is predicted for that time: the same 23 km test route between two public places took 34 minutes arriving at a weekday rush hour and 19 minutes early on a Sunday. It reads every calendar the Calendar app has, skips online, declined and all-day events, and makes at most 12 lookups a day, refreshing one in the two hours before an event. The cache holds no places or titles. `ek eta` does the lookup and `ek events` now gives each event's map location when it has one. Tested: 12 tests with a stand-in for ek, and real lookups by address, by place name, by coordinates and by transit. Not tested: a real day's events from your calendar.
- **A fast Skylight sync for groceries and chores, without Claude** (optional, off until you turn it on). Every 2 minutes it brings the grocery list and the chores linked in `data/chore-map.json` into step with Reminders, both ways: a change on one side is copied, done beats not-done, the newer rename wins when both sides say when, and deletions never cross. It never creates, dates or reschedules a chore. The Skylight login lives in the Keychain. Setup is in docs/SETUP.md §3. Tested: 42 tests for the matching and conflict rules, chores by date and the connection to skylight-mcp (against a stand-in). Not tested: a real Skylight account, which waits on the Keychain login.
- **`ek add-list --title T`** adds a Reminders list. Tested: it refuses a name that already exists. Not tested: adding one, so as not to change a real Reminders account.

Expand Down
6 changes: 6 additions & 0 deletions docs/SETUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ the top of `engine/tools/skylight_sync.py`.
4. `python3 engine/tools/skylight_sync.py status` shows the last pass and any alert. If Skylight asks you to sign in again, the
sync stops until you've done that and run `python3 engine/tools/skylight_sync.py resume`.

**Leave-by times** (optional): set `"eta_from"` in config.json to where your trips start, as an address or `LAT,LON`.
The evening briefing then shows "Leave by" for tomorrow's events that have a place, from Apple Maps travel times with
traffic predicted for when you need to arrive. No key or account. Your starting point and event places go only to Apple.
At most 12 lookups a day (`eta_daily_lookups`), plus 10 minutes for parking (`eta_buffer_minutes`). Try it with
`python3 engine/tools/eta.py day`.

**Things 3 migration:** nothing to install. `/migrate` reads Things read-only. Things is never changed.

## 4. First run
Expand Down
5 changes: 4 additions & 1 deletion engine/RULES.md
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,10 @@ by scripts, so the note uses typed ☐ characters. Tell the user once: "change
4. Add a **🌙 Tomorrow** section to the Today note, short enough to read in 30 seconds:
```
## 🌙 Tomorrow · Wed Nov 4
📅 every event in time order (time · title · where), first one bolded; flag early starts, back-to-backs, travel time, free blocks ≥ 60 min
📅 every event in time order (time · title · where), first one bolded; flag early starts, back-to-backs, travel time, free blocks ≥ 60 min.
For travel time, run `python3 engine/tools/eta.py day --date <tomorrow>` and show its "Leave by" line under each event. Use only
the times it gives (from Apple Maps, with traffic predicted for the arrival time); never estimate one. If it says it needs
`eta_from` or hit its limit, say so once.
🔥 Top 3 · ⏰ Due · 🧹 Chores · ⏰ Alarms (§7c, flag mismatches)
💬 Still waiting: texts, email, Slack (count + top 3)
🎒 Prep tonight (only if needed) · ❓ Needs you
Expand Down
4 changes: 4 additions & 0 deletions engine/templates/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@
"skylight_todo_list": "To Do",
"skylight_grocery_list": "Grocery",
"skylight_sync": "off",
"eta_from": "",
"eta_transport": "car",
"eta_buffer_minutes": 10,
"eta_daily_lookups": 12,
"skylight_todo_categories": [
"#Home"
],
Expand Down
53 changes: 52 additions & 1 deletion engine/tools/ek.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,14 @@
// ek update --id ID [--title T] [--due D|--clear-due] [--notes N] [--list L] [--priority P]
// [--recur RRULE|--clear-recur] (replaces the repeat rule)
// ek delete --id ID --confirm (reminders only; prefer complete)
// ek eta (--to "address" | --to-geo LAT,LON) (--from "address" | --from-geo LAT,LON)
// [--arrive "2026-11-05 14:00"] [--transport car|walk|transit]
// Travel time from Apple Maps (no key, no account). With --arrive, Apple predicts traffic for that time.
// Addresses go only to Apple. Nothing is stored.
import Foundation
import EventKit
import MapKit
import CoreLocation

let store = EKEventStore()
var args = Array(CommandLine.arguments.dropFirst())
Expand Down Expand Up @@ -254,6 +260,7 @@ case "events":
["id": e.eventIdentifier ?? "", "title": e.title ?? "", "calendar": e.calendar?.title ?? "",
"start": iso(e.startDate), "end": iso(e.endDate), "all_day": e.isAllDay,
"location": e.location ?? "", "notes": String((e.notes ?? "").prefix(500)),
"geo": nn(e.structuredLocation?.geoLocation.map { ["lat": $0.coordinate.latitude, "lon": $0.coordinate.longitude] }),
"url": nn(e.url?.absoluteString), "recurring": e.hasRecurrenceRules,
"attendees": (e.attendees ?? []).count,
"organizer": nn(e.organizer?.name),
Expand Down Expand Up @@ -341,11 +348,55 @@ case "delete":
do { try store.remove(r, commit: true) } catch { fail("delete failed: \(error.localizedDescription)") }
emit(["deleted": true, "reminder": snapshot])

case "eta":
func waitFor<T>(_ start: (@escaping (T) -> Void) -> Void) -> T {
var out: T?
start { out = $0 }
let deadline = Date().addingTimeInterval(30)
while out == nil, Date() < deadline { RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.05)) }
guard let done = out else { fail("Apple Maps didn't answer within 30 seconds") }
return done
}
func place(_ name: String) -> MKMapItem {
if let g = opt(name + "-geo") {
let parts = g.split(separator: ",").compactMap { Double($0.trimmingCharacters(in: .whitespaces)) }
guard parts.count == 2, abs(parts[0]) <= 90, abs(parts[1]) <= 180 else { fail("--\(name)-geo must be LAT,LON") }
return MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: parts[0], longitude: parts[1])))
}
guard let address = opt(name), !address.isEmpty else { fail("--\(name) or --\(name)-geo is required") }
let found: ([CLPlacemark]?, Error?) = waitFor { done in CLGeocoder().geocodeAddressString(address) { done(($0, $1)) } }
if let mark = found.0?.first { return MKMapItem(placemark: MKPlacemark(placemark: mark)) }
// Calendar locations are often names ("Dentist", "Airport"), which the address lookup doesn't know. Search places.
let search = MKLocalSearch.Request()
search.naturalLanguageQuery = address
let hits: (MKLocalSearch.Response?, Error?) = waitFor { done in MKLocalSearch(request: search).start { done(($0, $1)) } }
guard let item = hits.0?.mapItems.first else { fail("Apple Maps couldn't find '\(address)'") }
return item
}
let request = MKDirections.Request()
request.source = place("from")
request.destination = place("to")
switch opt("transport") ?? "car" {
case "car": request.transportType = .automobile
case "walk": request.transportType = .walking
case "transit": request.transportType = .transit
default: fail("--transport must be car, walk or transit")
}
if let a = opt("arrive") {
guard let (d, _) = parseDate(a) else { fail("can't read --arrive '\(a)'") }
request.arrivalDate = d
}
let answer: (MKDirections.ETAResponse?, Error?) = waitFor { done in MKDirections(request: request).calculateETA { done(($0, $1)) } }
guard let eta = answer.0 else { fail("no route: \(answer.1?.localizedDescription ?? "unknown")") }
emit(["seconds": Int(eta.expectedTravelTime.rounded()), "minutes": Int((eta.expectedTravelTime / 60).rounded()),
"meters": Int(eta.distance.rounded()), "depart": iso(eta.expectedDepartureDate), "arrive": iso(eta.expectedArrivalDate),
"transport": opt("transport") ?? "car"])

default:
print("""
ek — Calendar & Reminders bridge. Commands:
access | calendars | events | add-event | lists | reminders | add-reminder |
complete | uncomplete | update | delete
complete | uncomplete | update | delete | add-list | eta
See the header of tools/ek.swift for options.
""")
}
161 changes: 161 additions & 0 deletions engine/tools/eta.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
#!/usr/bin/env python3
"""
eta.py: leave-by times for the day's events that have a place, from Apple Maps travel times (K660).

python3 engine/tools/eta.py day [--date YYYY-MM-DD] [--json]

It reads the day's events from every calendar on this Mac (bin/ek events, which includes every account the Calendar app
has), skips all-day, declined and online events and ones with no place, and asks Apple Maps how long the trip takes
when arriving at the event's start. Apple predicts traffic for that time (tested 2026-11-15: the same 23 km route took
34 minutes arriving at a weekday rush hour and 19 minutes early on a Sunday).

config.json:
"eta_from": where trips start, an address or "LAT,LON". Required; without it nothing is looked up.
"eta_transport": "car" (default), "walk" or "transit".
"eta_buffer_minutes": added to the travel time for parking and walking in (default 10).
"eta_daily_lookups": the most Apple Maps lookups a day (default 12).

Each event is looked up once a day, and again in the two hours before it if the last answer is over an hour old, so
traffic is fresh when it matters. Answers are kept in data/eta-cache.json. The starting point and event places go only
to Apple, through MapKit. Limits: every trip starts from "eta_from", not from the event before.
"""
from __future__ import annotations

import datetime as dt
import hashlib
import json
import os
import re
import subprocess
import sys
from pathlib import Path

WS = Path(os.environ.get("THESEUS_HOME") or Path(__file__).resolve().parents[2])
CACHE = WS / "data" / "eta-cache.json"
ONLINE = re.compile(r"(https?://|zoom\.us|meet\.google|teams\.microsoft|webex|facetime|\bonline\b|\bvirtual\b|\bphone\b|\bcall\b)", re.I)
DECLINED = 3 # EKParticipantStatus.declined


def load(path: Path, default):
try:
return json.loads(path.read_text())
except (OSError, ValueError):
return default


def ek(*args):
p = subprocess.run([str(WS / "bin/ek"), *args], capture_output=True, text=True, timeout=60)
if p.returncode != 0:
raise RuntimeError((p.stderr or p.stdout).strip()[:200])
return json.loads(p.stdout or "null")


def needs_trip(e: dict, origin: str) -> str | None:
"""Why an event needs no trip, or None if it does."""
loc = (e.get("location") or "").strip()
if e.get("all_day"):
return "all day"
if e.get("my_status") == DECLINED:
return "declined"
if not loc and not e.get("geo"):
return "no place"
if loc and ONLINE.search(loc):
return "online"
if loc and origin and loc.lower() == origin.strip().lower():
return "at the starting point"
return None


def key(e: dict, transport: str) -> str:
where = json.dumps(e.get("geo")) if e.get("geo") else (e.get("location") or "").strip().lower()
return hashlib.sha1(f"{where}|{e.get('start')}|{transport}".encode()).hexdigest()[:16]


def due(entry: dict | None, start: dt.datetime, now: dt.datetime) -> bool:
"""Look up again? Never looked up today, or within two hours of the start with an answer over an hour old."""
if not entry:
return True
asked = dt.datetime.fromisoformat(entry["at"])
return dt.timedelta(0) <= start - now <= dt.timedelta(hours=2) and now - asked > dt.timedelta(hours=1)


def lookup_args(e: dict, origin: str, transport: str) -> list[str]:
args = ["eta"]
args += ["--from-geo", origin] if re.fullmatch(r"\s*-?\d+(\.\d+)?\s*,\s*-?\d+(\.\d+)?\s*", origin) else ["--from", origin]
geo = e.get("geo")
args += ["--to-geo", f"{geo['lat']},{geo['lon']}"] if geo else ["--to", e["location"].strip()]
start = dt.datetime.fromisoformat(e["start"])
args += ["--arrive", start.strftime("%Y-%m-%d %H:%M"), "--transport", transport]
return args


def plan(day: dt.date, cfg: dict, now: dt.datetime | None = None, ask=ek) -> dict:
now = now or dt.datetime.now().astimezone()
origin = (cfg.get("eta_from") or "").strip()
if not origin:
return {"trips": [], "note": 'Set "eta_from" in config.json (an address or LAT,LON) for leave-by times.'}
transport = cfg.get("eta_transport") or "car"
buffer = int(cfg.get("eta_buffer_minutes", 10))
limit = int(cfg.get("eta_daily_lookups", 12))
cache = load(CACHE, {})
today = now.date().isoformat()
if cache.get("day") != today:
cache = {"day": today, "lookups": 0, "entries": {}}
events = ask("events", "--from", day.isoformat(), "--to", (day + dt.timedelta(days=1)).isoformat()) or []
trips, notes = [], []
for e in events:
if needs_trip(e, origin):
continue
start = dt.datetime.fromisoformat(e["start"])
if start < now:
continue
k = key(e, transport)
entry = cache["entries"].get(k)
if due(entry, start, now):
if cache["lookups"] >= limit:
notes.append(f"Reached today's {limit} Apple Maps lookups; '{e.get('title')}' uses an older answer or none.")
else:
cache["lookups"] += 1
try:
got = ask(*lookup_args(e, origin, transport))
entry = {"minutes": int(got["minutes"]), "at": now.isoformat(timespec="minutes")}
cache["entries"][k] = entry
except (RuntimeError, KeyError, TypeError, ValueError) as err:
notes.append(f"No travel time for '{e.get('title')}': {err}")
if not entry:
continue
leave = start - dt.timedelta(minutes=entry["minutes"] + buffer)
trips.append({"title": e.get("title") or "", "start": e["start"], "location": e.get("location") or "",
"minutes": entry["minutes"], "buffer": buffer, "leave_by": leave.isoformat(timespec="minutes"),
"checked": entry["at"], "late": leave < now})
CACHE.parent.mkdir(parents=True, exist_ok=True)
CACHE.write_text(json.dumps(cache, indent=1))
return {"trips": trips, "note": " ".join(notes) or None, "transport": transport}


def text(result: dict) -> str:
lines = []
for t in result["trips"]:
leave = dt.datetime.fromisoformat(t["leave_by"])
when = leave.strftime("%-I:%M %p").lower()
lines.append(f"{'⚠️ Leave now' if t['late'] else 'Leave by ' + when} for {t['title']} "
f"({t['minutes']} min {result.get('transport', 'car')} + {t['buffer']})")
if result.get("note"):
lines.append(result["note"])
return "\n".join(lines) or "No trips today."


def main(argv: list[str]) -> int:
if len(argv) < 2 or argv[1] != "day":
print(__doc__)
return 0 if len(argv) < 2 or argv[1] in ("-h", "--help") else 2
day = dt.date.today()
if "--date" in argv:
day = dt.date.fromisoformat(argv[argv.index("--date") + 1])
result = plan(day, load(WS / "config.json", {}))
print(json.dumps(result, indent=1, ensure_ascii=False) if "--json" in argv else text(result))
return 0


if __name__ == "__main__":
sys.exit(main(sys.argv))
1 change: 1 addition & 0 deletions scripts/ci-checks.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ swiftc -typecheck engine/tools/ek.swift
node --test apps/desktop/src/*.test.ts
PYTHONDONTWRITEBYTECODE=1 /usr/bin/python3 tests/test_engine.py
PYTHONDONTWRITEBYTECODE=1 /usr/bin/python3 tests/test_skylight_sync.py
PYTHONDONTWRITEBYTECODE=1 /usr/bin/python3 tests/test_eta.py
bash scripts/check-shared.sh
cmp <(sed '/^SRC=/d' install.sh) <(sed '/^SRC=/d' engine/install.sh) || { echo "install.sh and engine/install.sh differ"; exit 1; }
echo "✅ checks passed"
Loading
Loading