Repository navigation
Expand file tree
/
Copy pathproactive_engine.py
More file actions
2380 lines (2097 loc) · 104 KB
/
Copy pathproactive_engine.py
File metadata and controls
2380 lines (2097 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Orb Proactive Engine — data collection + planned execution.
Flow:
1. Cheap detectors run every 15s (zero AI): log events, fire unambiguous alerts.
2. Twice a day, at fixed clock times (default 6am + 6pm — see _SYNTHESIS_HOURS),
ONE big synthesis call on a stronger model (Sonnet — see synthesis_brain_fn)
reads every data source and outputs a PLAN:
- Scheduled push notifications (title, body, time)
- Notes/reminders to save immediately (no phone needed)
- Calendar events worth adding (queued, applied next time the phone connects)
- Up to 2 optional self-review times if warranted
- Self-modification proposals
3. A scheduler loop (60s, zero AI) fires the plan items at the right times.
4. Self-scheduled extra reviews (from #2's additional_reviews) run on the cheap
router (Haiku -> free backends) — smaller interstitial checks, not full
re-synthesis, budget-capped separately from the two big calls.
AI call budget per day:
- 2 synthesis reviews (6am, 6pm — Sonnet)
- Up to 2 extra self-scheduled reviews (Haiku router)
= max 4 model calls/day from the proactive engine, often fewer
Hard safety boundary (2026-07-01, per ninjahawk — see PROACTIVE_BRAIN.md): the
review is a FIXED JSON PLAN, never a tool-calling agent loop. It structurally
cannot write files, delete anything, or run arbitrary commands — the action
surface is exactly the fields in the plan schema below (notifications, notes,
calendar_events, additional_reviews, proposals) and nothing else, enforced by
what _apply_plan() reads, not by asking the model nicely. This matters because
the 6am run happens while ninjahawk is asleep with nobody to catch a mistake
live — the safety property needs to be structural, not just promised.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import re
import subprocess
import time
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import Callable
import psutil
log = logging.getLogger("orb.proactive")
_DATA_DIR = Path(__file__).parent / "data"
_DATA_DIR.mkdir(parents=True, exist_ok=True)
_EVENTS_LOG = _DATA_DIR / "events.jsonl"
_NOTIF_LOG = _DATA_DIR / "notification_log.jsonl"
_CONTEXT_FILE = _DATA_DIR / "proactive_context.json"
_PLAN_FILE = _DATA_DIR / "active_plan.json"
_PROPOSALS_FILE = _DATA_DIR / "proposals.json"
_SESSIONS_DIR = Path.home() / "Desktop" / "orb_sessions"
_MAX_EXTRA_REVIEWS = int(os.getenv("ORB_MAX_EXTRA_REVIEWS", "2"))
# Fixed clock-time synthesis hours, not a rolling interval — "6am and 6pm",
# not "every 12h from whenever the server happened to start". Comma-separated
# 24h-clock hours.
_SYNTHESIS_HOURS = sorted({
int(h.strip()) for h in os.getenv("ORB_SYNTHESIS_HOURS", "6,18").split(",") if h.strip()
})
# Hard-recurring 6h high-bar scan (2026-07-20). The old design was a self-
# rescheduling kind=task: each run had to re-arm +6h. When one link failed to
# re-schedule, the chain silently died (~29h gap after 7/19 15:46). This is now
# engine-owned like _SYNTHESIS_HOURS — a single miss cannot kill the cadence.
# Kill switch: ORB_SIX_HOUR_SCAN=0. Interval hours: ORB_SIX_HOUR_INTERVAL_H.
_SIX_HOUR_ENABLED = os.getenv("ORB_SIX_HOUR_SCAN", "1") != "0"
_SIX_HOUR_INTERVAL_S = max(0.25, float(os.getenv("ORB_SIX_HOUR_INTERVAL_H", "6"))) * 3600.0
_SIX_HOUR_TITLE = "6h proactive check"
_JOB_APPS_FILE = _DATA_DIR / "job_applications.json"
_PENDING_CALENDAR_FILE = _DATA_DIR / "pending_calendar_actions.json"
# Known project dirs — used for staleness + git activity. Operator-specific
# config, not source (moved to env 2026-07-03 for the OSS snapshot):
# ORB_PROJECT_DIRS is a JSON list of [label, path] pairs ("~" expands).
# Unset = no project tracking, the right default for a fresh install.
def _project_dirs_from_env() -> list[tuple[str, Path]]:
raw = os.getenv("ORB_PROJECT_DIRS", "")
if not raw:
return []
try:
return [(str(label), Path(os.path.expanduser(str(p))))
for label, p in json.loads(raw)]
except Exception:
log.warning("[proactive] bad ORB_PROJECT_DIRS "
"(want JSON [[label, path], ...]) — project tracking off")
return []
_PROJECT_DIRS = _project_dirs_from_env()
_synthesis_fired_dates: dict[int, str] = {} # hour -> "YYYY-MM-DD" last fired
# Wired by server_win.py
_push_fn: Callable | None = None
_smart_brain_fn: Callable | None = None # cheap tier (Haiku router) — self-scheduled extras
_synthesis_brain_fn: Callable | None = None # strong tier (Sonnet) — the 6am/6pm big synthesis
_screenshot_fn: Callable | None = None # async fn() -> bool; broadcasts a live
# screenshot to connected mobile clients
# Latest connector context from the phone (calendar, reminders, contacts).
# Updated by server_win.py whenever {type:"context"} arrives over WS.
_connector_context: str = ""
_connector_updated_at: str = ""
def wire(push_fn: Callable, smart_brain_fn: Callable | None = None,
screenshot_fn: Callable | None = None,
synthesis_brain_fn: Callable | None = None) -> None:
global _push_fn, _smart_brain_fn, _screenshot_fn, _synthesis_brain_fn
_screenshot_fn = screenshot_fn
_push_fn = push_fn
_smart_brain_fn = smart_brain_fn
# Falls back to the cheap tier if the caller doesn't wire a dedicated
# synthesis brain — keeps this optional so nothing breaks if unset.
_synthesis_brain_fn = synthesis_brain_fn or smart_brain_fn
def update_connector_context(text: str) -> None:
"""Called by server_win.py whenever the phone sends fresh connector data."""
global _connector_context, _connector_updated_at
_connector_context = (text or "").strip()
_connector_updated_at = datetime.now().isoformat(timespec="seconds")
# ── Scheduled plan ────────────────────────────────────────────────────────────
@dataclass
class ScheduledItem:
fire_at: datetime
kind: str # "notification" | "review"
title: str = ""
body: str = ""
notif_kind: str = "info"
reason: str = ""
fired: bool = False
attach_screenshot: bool = False # model decides a screenshot would help this land
source: str = "plan" # "plan" = synthesis-owned (replaced wholesale each run)
# "user" = explicitly scheduled (tool/API) — the model
# may NOT clear these; see _apply_plan + schedule_notification
_schedule: list[ScheduledItem] = []
_last_review_at: float = 0.0
_last_six_hour_at: float = 0.0 # unix; hard-recurring 6h scan clock (persisted)
_extra_reviews_today: int = 0
_extra_reviews_date: str = "" # YYYY-MM-DD — resets daily
_current_brief: str = "" # last review's 2-3 sentence summary — persisted so
# GET /api/proactive/status has something to show,
# not just re-derivable from a one-time push notification
def _reset_daily_extras_if_needed() -> None:
global _extra_reviews_today, _extra_reviews_date
today = datetime.now().strftime("%Y-%m-%d")
if _extra_reviews_date != today:
_extra_reviews_today = 0
_extra_reviews_date = today
def _save_plan() -> None:
items = [
{
"fire_at": item.fire_at.isoformat(),
"kind": item.kind,
"title": item.title,
"body": item.body,
"notif_kind": item.notif_kind,
"reason": item.reason,
"fired": item.fired,
"attach_screenshot": item.attach_screenshot,
"source": item.source,
}
for item in _schedule
]
_PLAN_FILE.write_text(
json.dumps({"saved_at": datetime.now().isoformat(), "brief": _current_brief,
"last_review_at": _last_review_at,
"last_six_hour_at": _last_six_hour_at,
"items": items}, ensure_ascii=False),
encoding="utf-8",
)
def _load_plan() -> None:
"""Restore scheduled items from disk after a server restart."""
global _schedule, _current_brief, _last_review_at, _last_six_hour_at
if not _PLAN_FILE.exists():
return
try:
data = json.loads(_PLAN_FILE.read_text(encoding="utf-8"))
_current_brief = data.get("brief", "")
# Persisted so a restart doesn't reset the synthesis lookback to the
# 24h fallback (bit the first manual run, 2026-07-01 23:42).
_last_review_at = float(data.get("last_review_at") or 0.0) or _last_review_at
# Hard-recurring 6h clock. Prefer the dedicated field; fall back to the
# last fired "6h proactive check" task timestamp so a first load after
# this ship doesn't re-fire instantly if one ran recently.
raw_six = data.get("last_six_hour_at")
if raw_six:
_last_six_hour_at = float(raw_six)
elif not _last_six_hour_at:
for d in data.get("items", []):
if (d.get("kind") == "task"
and "6h proactive" in (d.get("title") or "").lower()
and d.get("fired")):
try:
ts = datetime.fromisoformat(d["fire_at"]).timestamp()
if ts > _last_six_hour_at:
_last_six_hour_at = ts
except Exception:
pass
now = datetime.now()
restored = []
dropped = 0
# Past-due grace (2026-07-03): the PC was off 04:00→17:00 and the day's
# 10:00/14:00 user reminders were silently DROPPED here at boot —
# "backend off at fire time = reminder evaporates" is exactly the
# failure class the reminders rebuild exists to kill. Unfired items
# missed by less than the grace window are restored and fire on the
# first tick, honestly marked late; only genuinely stale ones drop.
grace = timedelta(hours=float(os.getenv("ORB_SCHED_GRACE_H", "18")))
for d in data.get("items", []):
fire_at = datetime.fromisoformat(d["fire_at"])
if d.get("fired"):
continue
body = d.get("body", "")
if fire_at <= now:
if now - fire_at > grace:
dropped += 1
continue
if d.get("kind") == "notification" and now - fire_at > timedelta(minutes=10):
# Only mark genuinely-late deliveries — a quick restart that
# reloads an item a minute past due shouldn't sound dramatic
# (live 17:36: a fresh reminder double-tagged by a restart).
body = (f"{body} " if body else "") + (
f"(late — this was due {fire_at:%H:%M} while the backend was off)")
restored.append(ScheduledItem(
fire_at=fire_at, kind=d["kind"],
title=d.get("title", ""), body=body,
notif_kind=d.get("notif_kind", "info"),
reason=d.get("reason", ""),
attach_screenshot=d.get("attach_screenshot", False),
source=d.get("source", "plan"),
))
_schedule = restored
log.info(f"[proactive] restored {len(restored)} scheduled items from disk"
+ (f" ({dropped} stale past-due dropped)" if dropped else ""))
except Exception as e:
log.warning(f"[proactive] could not restore plan: {e}")
def _parse_time(t: str) -> datetime | None:
"""Parse HH:MM (today) or ISO datetime string into a datetime."""
now = datetime.now()
t = t.strip()
if re.match(r"^\d{1,2}:\d{2}$", t):
h, m = map(int, t.split(":"))
candidate = now.replace(hour=h, minute=m, second=0, microsecond=0)
if candidate <= now:
candidate += timedelta(days=1)
return candidate
try:
return datetime.fromisoformat(t)
except Exception:
return None
# ── User-scheduled reminders (first-class, 2026-07-03) ───────────────────────
# Born the night grok tried to schedule a week of job reminders by writing a
# loader script against active_plan.json — and lost the race with _save_plan's
# minutely rewrite (external file edits CANNOT stick while the engine runs;
# the in-memory _schedule is the source of truth). Tools and endpoints call
# these functions in-process instead: no file race, restart-safe via the same
# active_plan.json persistence, and source="user" survives _apply_plan.
def schedule_notification(time_str: str, title: str, body: str = "",
notif_kind: str = "info") -> str:
"""Schedule a push notification. time_str: HH:MM (next occurrence) or an
ISO datetime like 2026-07-04T10:00. Returns a human-readable outcome."""
fire_at = _parse_time(time_str or "")
if fire_at is None:
return (f"Could not parse time '{time_str}' — use HH:MM for the next "
"occurrence, or an ISO datetime like 2026-07-04T10:00.")
now = datetime.now()
if fire_at <= now:
return f"{fire_at.isoformat(timespec='minutes')} is in the past — nothing scheduled."
_schedule.append(ScheduledItem(
fire_at=fire_at, kind="notification",
title=(title or "Reminder").strip(), body=(body or "").strip(),
notif_kind=(notif_kind or "info").strip(), source="user"))
_save_plan()
log.info(f"[proactive] user reminder scheduled: '{title}' at "
f"{fire_at.isoformat(timespec='minutes')}")
stamp = f"{fire_at:%a %b} {fire_at.day}, {fire_at:%H:%M}"
return f"Scheduled — '{(title or 'Reminder').strip()}' will fire {stamp}."
def list_scheduled() -> list[dict]:
"""All unfired future scheduled items (notifications AND the synthesis's
review check-ins), soonest first."""
now = datetime.now()
return [
{"fire_at": item.fire_at.isoformat(timespec="minutes"), "kind": item.kind,
"title": item.title, "body": item.body, "source": item.source,
"reason": item.reason}
for item in sorted(_schedule, key=lambda i: i.fire_at)
if not item.fired and item.fire_at > now
]
def cancel_scheduled(query: str) -> list[str]:
"""Cancel unfired future NOTIFICATION items whose title or body contains
query (case-insensitive). Review items are deliberately untouchable here —
they're the synthesis's own check-ins, not user reminders. Returns the
descriptions of what was cancelled (empty list = nothing matched)."""
global _schedule
q = (query or "").strip().lower()
if not q:
return []
now = datetime.now()
keep, removed = [], []
for item in _schedule:
if (not item.fired and item.fire_at > now and item.kind in ("notification", "task")
and (q in item.title.lower() or q in item.body.lower())):
removed.append(f"'{item.title}' @ {item.fire_at.isoformat(timespec='minutes')}")
else:
keep.append(item)
if removed:
_schedule = keep
_save_plan()
log.info(f"[proactive] cancelled {len(removed)} scheduled item(s) matching '{query}'")
return removed
_PENDING_TASKS: set = set() # refs to fired background task coroutines so they aren't GC'd
def schedule_task(time_str: str, title: str, task: str) -> str:
"""Schedule AUTONOMOUS WORK for a future time — not just a reminder. When it
fires, the engine actually runs `task` on Claude (real file access) and pushes
the RESULT. This is the difference between reminding the user to do something and
Orb doing it and reporting back (the 2026-07-06 gap: schedule_notification only
pushes the instruction text, it never does the work). time_str: HH:MM or ISO."""
fire_at = _parse_time(time_str or "")
if fire_at is None:
return (f"Could not parse time '{time_str}' — use HH:MM or an ISO datetime "
"like 2026-07-06T15:00.")
if not (task or "").strip():
return "Give me the actual task to run — what should I do at that time?"
now = datetime.now()
if fire_at <= now:
return f"{fire_at.isoformat(timespec='minutes')} is in the past — nothing scheduled."
_schedule.append(ScheduledItem(
fire_at=fire_at, kind="task",
title=(title or "Scheduled task").strip(), body=task.strip(), source="user"))
_save_plan()
stamp = f"{fire_at:%a %b} {fire_at.day}, {fire_at:%H:%M}"
log.info(f"[proactive] task scheduled: '{title}' at {fire_at.isoformat(timespec='minutes')}")
return (f"Scheduled the task '{(title or 'task').strip()}' to run {stamp} — I'll "
"actually do it then and send you the result.")
async def _run_scheduled_task(task: str) -> str:
"""DO a scheduled task: run it on Claude with full tool access (reads files,
analyses, writes) and return the result. Spawned OFF the scheduler tick so a
long task never blocks the 60s loop. The executor behind schedule_task."""
import shutil
if not shutil.which("claude"):
return "Couldn't run the task — the Claude CLI isn't available."
model = os.environ.get("ORB_TASK_MODEL", "sonnet")
desktop = os.path.join(os.path.expanduser("~"), "Desktop")
try:
proc = await asyncio.create_subprocess_exec(
"claude", "-p", task, "--permission-mode", "bypassPermissions", "--model", model,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=desktop)
except Exception as e:
return f"Couldn't start the task: {e}"
try:
out, _ = await asyncio.wait_for(proc.communicate(), timeout=300.0)
return out.decode("utf-8", "ignore").strip() or "Finished the task, but it produced no output."
except asyncio.TimeoutError:
try:
proc.kill()
except Exception:
pass
return "The task ran past five minutes and I stopped it — it may need to be smaller."
except Exception as e:
return f"The task hit an error: {e}"
async def _run_and_push_task(title: str, task: str) -> None:
"""Run a scheduled task and push the REAL result (never just the instruction).
The full result is also saved to Desktop/Orb_Files so it survives the push
banner's length trim and Orb can read it back later."""
result = await _run_scheduled_task(task)
try:
outdir = os.path.join(os.path.expanduser("~"), "Desktop", "Orb_Files")
os.makedirs(outdir, exist_ok=True)
safe = "".join(c if (c.isalnum() or c in " -_") else "_"
for c in (title or "task"))[:50].strip() or "task"
with open(os.path.join(outdir, f"orb_task_{safe}.md"), "w", encoding="utf-8") as f:
f.write(f"# {title}\n\n{result}\n")
except Exception:
pass
if _push_fn:
await _push_fn(title or "Task done", result, "info",
source="scheduled-task", dedupe=False)
async def _apply_plan(plan: dict) -> None:
"""Parse the model's plan output and add items to the schedule. The ONLY
thing this function is capable of doing is what's read below — that's the
real safety boundary (see module docstring), not a prompt promise."""
global _schedule
now = datetime.now()
# Clear unfired future items from the OLD PLAN before applying the new one
# — but only the plan's own: user-scheduled reminders (source="user") are
# not the model's to clear. Without this guard the 06:00 synthesis would
# have silently wiped the 21 job-application reminders scheduled 07-03.
_schedule = [item for item in _schedule if item.fired or item.source == "user"]
added_notifications = 0
added_reviews = 0
suppressed = 0
# Muted-topics gate (2026-07-20): a durable suppression list the model is
# told about but which is ALSO enforced here in code — a notification whose
# title/body hits a muted topic is dropped and logged, never scheduled.
try:
from otools.muted_topics import block_reason as _muted_reason
except Exception:
_muted_reason = lambda *a: ""
for n in plan.get("notifications", []):
reason = _muted_reason(f"{n.get('title', '')} {n.get('body', '')}")
if reason:
suppressed += 1
log.info(f"[proactive] muted notification dropped ({reason}): {n.get('title', '')[:50]}")
continue
fire_at = _parse_time(n.get("time", ""))
if fire_at and fire_at > now:
_schedule.append(ScheduledItem(
fire_at=fire_at, kind="notification",
title=n.get("title", "Orb"),
body=n.get("body", ""),
notif_kind=n.get("kind", "info"),
attach_screenshot=bool(n.get("attach_screenshot", False)),
))
added_notifications += 1
_reset_daily_extras_if_needed()
remaining_slots = _MAX_EXTRA_REVIEWS - _extra_reviews_today
for r in plan.get("additional_reviews", [])[:remaining_slots]:
fire_at = _parse_time(r.get("time", ""))
if fire_at and fire_at > now:
_schedule.append(ScheduledItem(
fire_at=fire_at, kind="review",
reason=r.get("reason", ""),
))
added_reviews += 1
_schedule.sort(key=lambda x: x.fire_at)
_save_plan()
# Notes — local, no phone needed, applied immediately (max 5, matches the
# other list caps in this schema).
added_notes = 0
try:
from otools.notes_tool import add_note
for n in plan.get("notes", [])[:5]:
text = (n.get("text") or "").strip()
if not text:
continue
reason = _muted_reason(text)
if reason:
suppressed += 1
log.info(f"[proactive] muted note dropped ({reason}): {text[:50]}")
continue
await add_note(text, tag="proactive")
added_notes += 1
except Exception as e:
log.warning(f"[proactive] note apply failed: {e}")
# Calendar events — phone-side, queued, applied opportunistically (see
# queue_calendar_events's docstring for why this can't be immediate).
added_calendar = queue_calendar_events(plan.get("calendar_events", []))
log.info(f"[proactive] plan applied: {added_notifications} notifications, {added_reviews} extra "
f"reviews, {added_notes} notes, {added_calendar} calendar event(s) queued"
+ (f", {suppressed} suppressed (muted topics)" if suppressed else ""))
# ── Event log ─────────────────────────────────────────────────────────────────
def log_event(type_: str, **kwargs) -> None:
entry = {"ts": datetime.now().isoformat(timespec="seconds"), "type": type_, **kwargs}
try:
with _EVENTS_LOG.open("a", encoding="utf-8") as f:
f.write(json.dumps(entry) + "\n")
except Exception:
pass
def _read_events(since_hours: float) -> list[dict]:
if not _EVENTS_LOG.exists():
return []
cutoff = datetime.now() - timedelta(hours=since_hours)
out = []
for line in _EVENTS_LOG.read_text(encoding="utf-8").splitlines():
try:
e = json.loads(line)
if datetime.fromisoformat(e["ts"]) >= cutoff:
out.append(e)
except Exception:
pass
return out
def _trim_events_log(keep_days: int = 7) -> None:
if not _EVENTS_LOG.exists():
return
cutoff = datetime.now() - timedelta(days=keep_days)
kept = [
line for line in _EVENTS_LOG.read_text(encoding="utf-8").splitlines()
if line.strip() and datetime.fromisoformat(json.loads(line)["ts"]) >= cutoff
]
_EVENTS_LOG.write_text("\n".join(kept) + "\n", encoding="utf-8")
# ── Context store ─────────────────────────────────────────────────────────────
def update_context(key: str, value: str) -> None:
ctx: dict = {}
if _CONTEXT_FILE.exists():
try:
ctx = json.loads(_CONTEXT_FILE.read_text(encoding="utf-8"))
except Exception:
pass
ctx[key] = {"value": value, "updated": datetime.now().isoformat(timespec="seconds")}
_CONTEXT_FILE.write_text(json.dumps(ctx, indent=2, ensure_ascii=False), encoding="utf-8")
def get_context() -> dict:
if not _CONTEXT_FILE.exists():
return {}
try:
return json.loads(_CONTEXT_FILE.read_text(encoding="utf-8"))
except Exception:
return {}
# ── Notification log ──────────────────────────────────────────────────────────
def log_notification(title: str, body: str, kind: str, source: str,
notif_id: str = "", delivered: bool | None = None,
session: str | None = None, topic_key: str = "") -> None:
"""One canonical entry per push. `notif_id` is what the phone's tap feedback
(/api/notification/feedback) matches on — entries logged without it can never
learn from opens, which is exactly what happened before 2026-07-01: every
entry lacked an id, so record_feedback never matched anything. `topic_key` is
stored so an open can reset that topic's read-the-room backoff (2026-07-14)."""
entry = {
"ts": datetime.now().isoformat(timespec="seconds"),
"title": title, "body": body, "kind": kind, "source": source,
"opened": None,
}
if notif_id:
entry["id"] = notif_id
if delivered is not None:
entry["delivered"] = delivered
if session:
entry["session"] = session
if topic_key:
entry["topic_key"] = topic_key
with _NOTIF_LOG.open("a", encoding="utf-8") as f:
f.write(json.dumps(entry) + "\n")
def topic_key_for_notif(notif_id: str) -> str:
"""Look up the topic_key logged for a notification id (for engagement reset)."""
if not notif_id or not _NOTIF_LOG.exists():
return ""
for line in reversed(_NOTIF_LOG.read_text(encoding="utf-8").splitlines()):
try:
e = json.loads(line)
if e.get("id") == notif_id:
return e.get("topic_key", "")
except Exception:
pass
return ""
def record_feedback(notif_id: str, opened: bool) -> None:
if not _NOTIF_LOG.exists():
return
lines = _NOTIF_LOG.read_text(encoding="utf-8").splitlines()
updated = []
for l in lines:
if not l.strip():
continue
try:
e = json.loads(l)
if e.get("id") == notif_id:
e["opened"] = opened
l = json.dumps(e)
except Exception:
pass
updated.append(l)
_NOTIF_LOG.write_text("\n".join(updated) + "\n", encoding="utf-8")
def _read_notifications(since_hours: float) -> list[dict]:
if not _NOTIF_LOG.exists():
return []
cutoff = datetime.now() - timedelta(hours=since_hours)
out = []
for line in _NOTIF_LOG.read_text(encoding="utf-8").splitlines():
try:
e = json.loads(line)
if datetime.fromisoformat(e["ts"]) >= cutoff:
out.append(e)
except Exception:
pass
return out
# ── Git activity ──────────────────────────────────────────────────────────────
def _git_activity(since_hours: float) -> str:
lines = []
for name, path in _PROJECT_DIRS:
p = Path(path) if not isinstance(path, Path) else path
if not p.is_dir() or not (p / ".git").exists():
continue
try:
r = subprocess.run(
["git", "-C", str(p), "log",
# int, not float: git's date parser silently matches NOTHING on
# "--since=6.0 hours ago" — this block was empty on every call
# until the mind's first wake asserted "no commits" and got
# fact-checked (2026-07-02).
f"--since={max(1, int(round(since_hours)))} hours ago",
"--oneline", "--no-merges"],
capture_output=True, text=True, timeout=5,
)
commits = [l.strip() for l in r.stdout.strip().splitlines() if l.strip()]
if commits:
lines.append(f" {name}: {len(commits)} commit(s) — {commits[0][:70]}")
except Exception:
pass
# Other branches/machines, fetched from origin — the iMac's work is
# invisible to local HEAD. Feeds the mind AND the synthesis (both call
# this one function).
remote = _remote_git_activity(since_hours)
if remote:
lines.append(" — on other branches/machines (fetched from origin; "
"e.g. the iMac's iOS work):")
lines.append(remote)
return "\n".join(lines) if lines else " (no recent commits — local branches or fetched remotes)"
# Throttle the network fetch, not the read: the mind wakes several times a day
# and the synthesis twice — refreshing origin refs every ~20 min is plenty,
# and a skipped fetch still reads the last-fetched refs (slightly stale beats
# blind).
_LAST_REMOTE_FETCH: dict[str, float] = {}
_REMOTE_FETCH_MIN_GAP_S = 20 * 60
def _remote_git_activity(since_hours: float) -> str:
"""Recent commits on remote branches OTHER than the local upstream.
Exists because of a proven blind spot (2026-07-02): the 18:02 synthesis
brief claimed 'iOS blockers haven't visibly moved' on a day the iMac
shipped two TestFlight builds — this PC's git view was local-HEAD-only.
A failed/offline fetch degrades to whatever refs the last fetch left."""
lines = []
since = f"--since={max(1, int(round(since_hours)))} hours ago"
cutoff = time.time() - since_hours * 3600
for name, path in _PROJECT_DIRS:
p = Path(path) if not isinstance(path, Path) else path
if not p.is_dir() or not (p / ".git").exists():
continue
try:
remotes = subprocess.run(["git", "-C", str(p), "remote"],
capture_output=True, text=True, timeout=5)
if not remotes.stdout.strip():
continue
now_m = time.monotonic()
if now_m - _LAST_REMOTE_FETCH.get(str(p), 0.0) > _REMOTE_FETCH_MIN_GAP_S:
_LAST_REMOTE_FETCH[str(p)] = now_m
subprocess.run(["git", "-C", str(p), "fetch", "--all", "--quiet", "--prune"],
capture_output=True, text=True, timeout=25)
up = subprocess.run(["git", "-C", str(p), "rev-parse", "--abbrev-ref", "@{u}"],
capture_output=True, text=True, timeout=5)
upstream = up.stdout.strip() if up.returncode == 0 else ""
refs = subprocess.run(
["git", "-C", str(p), "for-each-ref", "refs/remotes",
"--sort=-committerdate",
"--format=%(refname:short)|%(committerdate:unix)"],
capture_output=True, text=True, timeout=5)
for ref_line in refs.stdout.strip().splitlines():
try:
ref, unix = ref_line.rsplit("|", 1)
if float(unix) < cutoff:
break # sorted newest-first — the rest are older
except ValueError:
continue
if ref == upstream or ref.endswith("/HEAD"):
continue
lg = subprocess.run(
["git", "-C", str(p), "log", ref, since, "--oneline", "--no-merges"],
capture_output=True, text=True, timeout=5)
commits = [l.strip() for l in lg.stdout.strip().splitlines() if l.strip()]
if commits:
latest = commits[0].split(" ", 1)[-1][:90]
lines.append(f" {name} {ref}: {len(commits)} commit(s) — {latest}")
except Exception:
pass
return "\n".join(lines)
def _uncommitted_work_summary() -> str:
"""Per-project: uncommitted changes + unpushed commits sitting locally.
Added 2026-07-01 after finding 31 real files of working code sitting
uncommitted for an extended stretch across this exact set of projects —
genuinely useful to surface ('you have real work sitting unprotected'),
zero new dependencies, all local git."""
lines = []
for name, path in _PROJECT_DIRS:
p = Path(path) if not isinstance(path, Path) else path
if not p.is_dir() or not (p / ".git").exists():
continue
try:
dirty = subprocess.run(
["git", "-C", str(p), "status", "--porcelain"],
capture_output=True, text=True, timeout=5,
)
dirty_count = len([l for l in dirty.stdout.splitlines() if l.strip()])
ahead = subprocess.run(
["git", "-C", str(p), "rev-list", "--count", "@{u}..HEAD"],
capture_output=True, text=True, timeout=5,
)
ahead_count = int(ahead.stdout.strip()) if ahead.returncode == 0 and ahead.stdout.strip().isdigit() else 0
if dirty_count or ahead_count:
bits = []
if dirty_count:
bits.append(f"{dirty_count} uncommitted file(s)")
if ahead_count:
bits.append(f"{ahead_count} unpushed commit(s)")
lines.append(f" {name}: {', '.join(bits)}")
except Exception:
pass
return "\n".join(lines) if lines else " (everything committed and pushed)"
# ── Failure telemetry ─────────────────────────────────────────────────────────
def _failure_telemetry_block(since_hours: float) -> str:
"""Dropped balls in the window — tool errors, dead/empty turns, timeouts.
Orb's own introspection ask (2026-07-02): 'tool errors and empty turns
should be logged somewhere the morning synthesis reads — right now nobody
counts dropped balls but the user.' Zero-LLM: tallies markers the activity
log already records."""
path = _DATA_DIR / "session_activity.jsonl"
if not path.exists():
return " (no activity log)"
cutoff = datetime.now() - timedelta(hours=since_hours)
counts: dict[str, int] = {}
examples: list[str] = []
try:
for line in path.read_text(encoding="utf-8").splitlines():
try:
e = json.loads(line)
if datetime.fromisoformat(e.get("ts", "")) < cutoff:
continue
except Exception:
continue
kind = e.get("kind", "")
text = str(e.get("text") or "")
fail = None
if kind == "turn_error":
fail = "dead_turn"
elif kind == "tool_result" and text.startswith("[tool error]"):
fail = f"tool_error:{e.get('tool', '?')}"
elif kind in ("tool_result", "lifecycle") and "timed out" in text.lower():
fail = f"timeout:{e.get('tool') or e.get('session') or '?'}"
if fail:
counts[fail] = counts.get(fail, 0) + 1
if len(examples) < 3:
examples.append(f" [{e.get('ts', '')[11:16]}] {fail}: {text[:90]}")
except Exception:
return " (activity log unreadable)"
if not counts:
return " (none — clean window)"
head = ", ".join(f"{k} ×{v}" for k, v in sorted(counts.items(), key=lambda kv: -kv[1]))
return " " + head + ("\n" + "\n".join(examples) if examples else "")
# ── Job application tracker ───────────────────────────────────────────────────
def _job_apps_summary() -> str:
if not _JOB_APPS_FILE.exists():
return " (no applications on file)"
try:
apps = json.loads(_JOB_APPS_FILE.read_text(encoding="utf-8"))
except Exception:
return " (could not read)"
lines = []
for a in apps:
try:
last = datetime.fromisoformat(a.get("last_contact", a.get("applied_date", "2026-01-01")))
days = (datetime.now() - last).days
except Exception:
days = "?"
status = a.get("status", "applied")
role = f" ({a['role']})" if a.get("role") and a["role"] != "Unknown" else ""
note = f" — {a['notes']}" if a.get("notes") else ""
lines.append(f" {a['company']}{role}: {status}, last contact {days}d ago{note}")
return "\n".join(lines) if lines else " (empty)"
def update_job_application(company: str, status: str = "", notes: str = "") -> str:
"""Update a job application record. Called by Orb tools or voice commands."""
try:
apps = json.loads(_JOB_APPS_FILE.read_text(encoding="utf-8")) if _JOB_APPS_FILE.exists() else []
except Exception:
apps = []
now_iso = datetime.now().strftime("%Y-%m-%d")
found = False
for a in apps:
if a["company"].lower() == company.lower():
a["last_contact"] = now_iso
if status:
a["status"] = status
if notes:
a["notes"] = notes
found = True
break
if not found:
apps.append({"company": company, "role": "Unknown",
"applied_date": now_iso, "last_contact": now_iso,
"status": status or "applied", "notes": notes})
_JOB_APPS_FILE.write_text(json.dumps(apps, indent=2, ensure_ascii=False), encoding="utf-8")
return f"Updated {company}: {status or 'contact logged'}"
# ── Staleness (file mod times) ────────────────────────────────────────────────
def _project_staleness() -> str:
lines = []
for name, path in _PROJECT_DIRS:
p = Path(path) if not isinstance(path, Path) else path
if p.is_file():
try:
days = (time.time() - p.stat().st_mtime) / 86400
lines.append(f" {name}: {days:.1f} days ago")
except Exception:
pass
elif p.is_dir():
try:
most_recent = max(
(f.stat().st_mtime for f in p.rglob("*") if f.is_file()),
default=0.0,
)
days = (time.time() - most_recent) / 86400
lines.append(f" {name}: {days:.1f} days ago")
except Exception:
pass
return "\n".join(lines) if lines else " (none)"
# ── Fresh external pulls (weather/news) — cheap, keyless, pulled AT review ────
# time rather than hourly-watched like data_watcher's stock targets: these are
# "what's true right now", not a time series to find patterns in.
async def _weather_block() -> str:
try:
from otools.weather_tool import get_weather
return " " + (await get_weather()).replace("\n", " ")
except Exception:
return " (unavailable)"
async def _tech_news_block() -> str:
try:
from otools.news_tool import get_news
return " " + (await get_news("tech", 3)).replace("\n", " ")
except Exception:
return " (unavailable)"
async def _mail_block(limit: int = 5) -> str:
"""Targeted Gmail summary (off-device data). His inbox runs thousands of
unread, so recency/unread is pure noise — Gmail's Primary category plus a
job-signal search is the signal (switched 2026-07-02 after the first live
run proved 'latest unread' was all newsletters). Dormant until
GMAIL_APP_PASSWORD exists; IMAP is blocking so it runs threaded."""
try:
from otools.mail_tool import configured, primary_recent, job_signals
if not configured():
return " (not configured — GMAIL_APP_PASSWORD not set; not an event, don't surface it)"
prim = await asyncio.to_thread(primary_recent, limit)
jobs = await asyncio.to_thread(job_signals, limit)
except Exception as e:
return f" (unavailable — {str(e)[:80]})"
lines = [" PRIMARY inbox, last 24h: " + (f"{len(prim)} message(s)" if prim else "nothing new")]
lines += [f" {r['from'][:44]} — {r['subject'][:72]}" for r in prim]
lines.append(" JOB-HUNT signals, last 48h: " + ("" if jobs else "none"))
lines += [f" {r['from'][:44]} — {r['subject'][:72]}" for r in jobs]
return "\n".join(lines)
def _missions_block() -> str:
"""The user's declared week-scale goals — the interpretive frame the
synthesis weighs every other data source against. As of 2026-07-20 each
mission carries a surfacing mode: SILENT missions are background context
ONLY (never a nudge/note/push, even when stale); only ACTIVE-DRIVE missions
may be surfaced. The marker is shown so the model honors the distinction."""
try:
from otools.missions_tool import active_missions, render_line, mission_surface, SURFACE_ACTIVE_DRIVE
acts = active_missions()
except Exception:
return " (unavailable)"
if not acts:
return " (none set — the add_mission tool creates them)"
lines = [" • " + render_line(m, show_surface=True) for m in acts[:8]]
n_drive = sum(1 for m in acts if mission_surface(m) == SURFACE_ACTIVE_DRIVE)
header = (
" RULE: [silent] missions are BACKGROUND CONTEXT ONLY — use them to interpret "
"what he's doing, but a stale silent mission must NEVER become a notification, "
"note, or push. Only [ACTIVE-DRIVE] missions may be proactively surfaced."
f" ({n_drive} active-drive right now.)\n"
)
return header + "\n".join(lines)
def _ignored_topics_block(days: float = 7.0, min_sends: int = 3) -> str:
"""Topics the user has been shown repeatedly and NEVER opened — the
generation-layer 'read the room' signal (2026-07-14). The synthesis must
not keep manufacturing these; his 07-14 complaint was 231 pushes / 3%
opened, 'reminds me of the same thing over and over.' Grouped by topic_key
(new entries) or source/title (older), counting sends vs opens."""
try:
rows = _read_notifications(days * 24)
except Exception:
return " (none tracked)"
agg: dict[str, dict] = {}
for r in rows:
key = r.get("topic_key") or r.get("source") or ""
if not key or key in ("push", "reply-fallback", "api"):
continue # skip generic/direct-answer buckets
a = agg.setdefault(key, {"sends": 0, "opens": 0, "last": ""})
a["sends"] += 1
if r.get("opened") is True:
a["opens"] += 1
a["last"] = (r.get("body") or "")[:50]
ignored = [(k, v) for k, v in agg.items()
if v["sends"] >= min_sends and v["opens"] == 0]
ignored.sort(key=lambda kv: kv[1]["sends"], reverse=True)
if not ignored:
return " (none — nothing is being over-sent)"
return "\n".join(
f" {k}: sent {v['sends']}x, opened 0x — e.g. \"{v['last']}\" → STOP re-raising unless it materially escalated"
for k, v in ignored[:8])
def _notes_block(limit: int = 8) -> str:
"""Recent saved notes, newest first. Past reviews' own notes land in the
same file, so reading them back also stops duplicate note-saving."""
try:
from otools.notes_tool import recent_notes
notes = recent_notes(limit)
except Exception:
return " (unavailable)"
if not notes:
return " (none)"
return "\n".join(
f" [{(n.get('ts') or '')[:16]}] {(n.get('text') or '')[:120]}"
for n in notes[::-1])
def _day_rhythm_block(events: list[dict]) -> str:
"""Distill raw window_changed events into how the period actually went —
active span, where the time went, what's on screen now. Zero-LLM;
approximate by nature (dwell is inferred from switch-to-switch gaps,
discounted by the idle time recorded at each switch)."""
wins = []
for e in events:
if e.get("type") != "window_changed" or not e.get("title"):