@m13v/s4l 1.7.1-rc.9 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/mcp/dist/index.js +354 -24
  2. package/mcp/dist/panel.html +42 -31
  3. package/mcp/dist/product-link.html +1 -1
  4. package/mcp/dist/telemetry.js +80 -3
  5. package/mcp/dist/version.json +2 -2
  6. package/mcp/manifest.json +9 -1
  7. package/mcp/menubar/dashboard_server.py +12 -0
  8. package/mcp/menubar/s4l_card.py +539 -80
  9. package/mcp/menubar/s4l_menubar.py +299 -191
  10. package/mcp/menubar/s4l_state.py +228 -33
  11. package/mcp/package.json +1 -1
  12. package/package.json +4 -1
  13. package/scripts/active_users.py +3 -6
  14. package/scripts/autopilot_stall_watch.py +200 -16
  15. package/scripts/claude_job.py +6 -0
  16. package/scripts/feedback_digest.py +34 -6
  17. package/scripts/harness_overlay.py +45 -0
  18. package/scripts/identity.py +26 -0
  19. package/scripts/learned_preferences.py +241 -32
  20. package/scripts/link_tail.py +167 -91
  21. package/scripts/mark_event.py +128 -0
  22. package/scripts/memory_snapshot.py +27 -0
  23. package/scripts/merge_review_queue.py +42 -16
  24. package/scripts/pick_twitter_thread_target.py +1 -1
  25. package/scripts/s4l_mode.py +7 -5
  26. package/scripts/scan_pii.py +9 -1
  27. package/scripts/schedule_state.py +146 -69
  28. package/scripts/scheduled_task_selfheal.py +276 -0
  29. package/scripts/scheduled_tasks_snapshot.py +107 -0
  30. package/scripts/send_gmail_report.py +76 -0
  31. package/scripts/sentry_digest.py +81 -189
  32. package/scripts/sentry_init.py +43 -15
  33. package/scripts/snapshot.py +20 -0
  34. package/scripts/twitter_post_plan.py +39 -13
  35. package/skill/dm-outreach-twitter.sh +19 -0
  36. package/skill/engage-twitter.sh +27 -0
  37. package/skill/run-draft-and-publish.sh +13 -12
  38. package/skill/run-linkedin.sh +9 -1
  39. package/skill/run-twitter-cycle.sh +199 -27
  40. package/skill/sentry-digest.sh +125 -12
@@ -28,6 +28,50 @@ import tempfile
28
28
  import threading
29
29
  import time
30
30
 
31
+ # --- stderr timestamp wrapper -------------------------------------------------
32
+ # menubar.err.log (this process's stderr, redirected by the launchd plist) has
33
+ # never carried timestamps, so correlating a line like "[s4l-card] approved at
34
+ # level 1" with the UTC-stamped logs elsewhere (post-*.log, post-preempt-
35
+ # events.log, panel-events.log) meant guessing from file position alone
36
+ # (2026-07-08 forensics). Wrap sys.stderr once, here, before any other module
37
+ # gets a chance to print, so every line written to stderr for the rest of the
38
+ # process gets a leading UTC timestamp in the same format those other logs
39
+ # use — zero changes needed at any individual print()/write() call site
40
+ # (s4l_card._log, the many sys.stderr.write(...) calls in this file, rumps'/
41
+ # PyObjC's own warnings, …).
42
+ class _TimestampedStderr:
43
+ def __init__(self, stream):
44
+ self._stream = stream
45
+ self._newline_pending = True # True at the start of a fresh line
46
+
47
+ def write(self, data):
48
+ if not data:
49
+ return 0
50
+ ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
51
+ lines = data.split("\n")
52
+ out = []
53
+ for i, line in enumerate(lines):
54
+ if i > 0:
55
+ out.append("\n")
56
+ starts_new_line = i > 0 or self._newline_pending
57
+ if starts_new_line and line:
58
+ out.append(f"[{ts}] ")
59
+ out.append(line)
60
+ self._newline_pending = data.endswith("\n")
61
+ return self._stream.write("".join(out))
62
+
63
+ def flush(self):
64
+ self._stream.flush()
65
+
66
+ def isatty(self):
67
+ try:
68
+ return self._stream.isatty()
69
+ except Exception:
70
+ return False
71
+
72
+
73
+ sys.stderr = _TimestampedStderr(sys.stderr)
74
+
31
75
  # --- Sentry bootstrap --------------------------------------------------------
32
76
  # The menu bar runs as a standalone KeepAlive LaunchAgent off the owned venv,
33
77
  # a separate process from the MCP server, so it was a Sentry blind spot: a crash
@@ -224,6 +268,14 @@ MENUBAR_PLIST = os.path.join(
224
268
  # start actions (restart_menubar tool, queue_setup re-arm). Keep the filename in
225
269
  # sync with MENUBAR_STOP_FLAG in mcp/src/runtime.ts.
226
270
  STOP_FLAG = os.path.join(st.state_dir(), "stopped.flag")
271
+ # Pause sentinel (lighter than STOP_FLAG): while present, the pipeline daemons
272
+ # (kicker/reaper/stall-watch/memory-snapshot) stay unloaded and claude_job.py's
273
+ # `next` reports no work — but Claude Desktop, this tray, and the draft
274
+ # schedule registration are untouched. Written/cleared ONLY by the MCP's
275
+ # pause_s4l tool (see _pause_work below); this constant is read-only
276
+ # here, purely to render the menu label. Keep the filename in sync with
277
+ # pauseFlagPath() in mcp/src/index.ts.
278
+ PAUSE_FLAG = os.path.join(st.state_dir(), "paused.flag")
227
279
 
228
280
  # Autopilot scheduled tasks. Queue workers must RUN in a dedicated folder
229
281
  # (~/.s4l-worker) so their once-a-minute sessions don't flood the user's
@@ -284,6 +336,11 @@ REARM_PROMPT = (
284
336
  "If the task already exists, call update_scheduled_task with taskId s4l-worker and "
285
337
  "notifyOnCompletion false instead. "
286
338
  "Do not redo my X connection or project setup — only register the scheduled task. "
339
+ "Before calling create_scheduled_task/list_scheduled_tasks/update_scheduled_task, run "
340
+ "(via Bash, best-effort, ignore any error and continue if the path doesn't exist): "
341
+ "python3 ~/.social-autoposter-mcp/repo/package/scripts/mark_event.py start <that tool's name>; "
342
+ "immediately after it returns, run the same with 'end' instead of 'start'. This makes a hang "
343
+ "in that host tool directly observable instead of invisible. "
287
344
  "Keep replies short."
288
345
  )
289
346
  # Universal diagnose-and-heal prompt behind the ⚠ "Diagnose & fix" menu item. One
@@ -312,7 +369,11 @@ DIAGNOSE_PROMPT_TEMPLATE = (
312
369
  "to fix, say so in the report. "
313
370
  "(3) schedule missing/disabled — re-register via queue_setup or the host "
314
371
  "create_scheduled_task with notifyOnCompletion false and the prompt from "
315
- "~/.claude/scheduled-tasks/s4l-worker/SKILL.md.\n"
372
+ "~/.claude/scheduled-tasks/s4l-worker/SKILL.md. Before calling create_scheduled_task/"
373
+ "list_scheduled_tasks/update_scheduled_task, bracket it (Bash, best-effort, ignore if "
374
+ "missing): python3 ~/.social-autoposter-mcp/repo/package/scripts/mark_event.py start "
375
+ "<tool name>, then ...end <tool name> right after it returns — makes a hang in that "
376
+ "host tool directly observable.\n"
316
377
  "HARD RULE: fix state files only. Never edit, copy, or patch code in "
317
378
  "~/.social-autoposter-mcp or any extension bundle (hot patches are auto-reverted "
318
379
  "and mask the real bug).\n"
@@ -693,55 +754,27 @@ class S4LMenuBar(rumps.App):
693
754
  clipboard, open Claude, and tell the user to paste it. (The dashboard
694
755
  widget's button does this in one click via app.sendMessage — no paste.) We
695
756
  do NOT auto-type (focus/timing flaky) and do NOT write the registry directly
696
- (can't reliably target a just-switched-into account)."""
757
+ (can't reliably target a just-switched-into account).
758
+
759
+ The click itself is captured (mirroring _diagnose_fix) — previously this
760
+ button had NO telemetry at all, so a past incident (Karol, 2026-07-07)
761
+ could only establish "a human must have clicked SOMETHING" from the code
762
+ path, never which button or exactly when. The registry snapshot rides as
763
+ an extra so the pre-rearm state is on record without on-box forensics."""
764
+ sched = getattr(self, "_schedule_state_cache", "") or ""
765
+ _capture_msg(
766
+ "S4L rearm clicked",
767
+ phase="rearm",
768
+ surface="menubar",
769
+ schedule_state=sched or "unknown",
770
+ _extra={"registry": _registry_summary_for_capture()},
771
+ )
697
772
  self._clipboard_prompt(
698
773
  REARM_PROMPT,
699
774
  "Set up the draft schedule",
700
775
  "that schedules the draft tasks for this account",
701
776
  )
702
777
 
703
- def _restart_claude_fix(self, _=None):
704
- """One-click fix for schedule_state == 'stalled': fully quit and relaunch
705
- Claude Desktop. Fixes the warm-session scheduler wedge (finished worker
706
- sessions never exit, so the host's overlap guard skips every fire — a
707
- Claude Desktop platform bug; Karol, 2026-07-06). While Claude is down we
708
- also run the registry self-heal, which additionally repairs the
709
- account-switch orphan case, so this one click covers both known causes."""
710
- _activate_front()
711
- choice = _show_alert(
712
- title="Restart Claude Desktop?",
713
- message=(
714
- "Claude’s scheduler stopped running the draft tasks (a known "
715
- "Claude Desktop glitch). Restarting Claude fixes it — its window "
716
- "will close and reopen in a moment. Drafting resumes within a "
717
- "couple of minutes."
718
- ),
719
- ok="Restart Claude", cancel="Cancel",
720
- )
721
- if choice != 1:
722
- return
723
- _capture_msg(
724
- "S4L restart-claude-fix clicked",
725
- phase="draft_schedule",
726
- reason="stalled",
727
- _extra={"scheduled_tasks": _registry_summary_for_capture()},
728
- )
729
- self._notify("S4L", "Restarting Claude Desktop… drafts resume shortly.")
730
- threading.Thread(target=self._restart_claude_fix_work, daemon=True).start()
731
-
732
- def _restart_claude_fix_work(self):
733
- try:
734
- user_data_dirs = self._claude_user_data_dirs()
735
- self._quit_claude_and_wait()
736
- # Claude is down: safe window for registry edits. Runs the cwd fix,
737
- # legacy consolidation, AND the ensure-worker heal (orphan repair).
738
- self._rewrite_scheduled_task_cwd()
739
- self._relaunch_claude(user_data_dirs)
740
- self._sig = None
741
- except Exception as e:
742
- self._notify("S4L restart failed", str(e)[:140])
743
- _capture(e, phase="restart_claude_fix")
744
-
745
778
  # ---- schedule-state detection ----------------------------------------
746
779
  def _schedule_state(self):
747
780
  """Is the draft schedule registered AND running for the live account?
@@ -1103,6 +1136,40 @@ class S4LMenuBar(rumps.App):
1103
1136
  pass
1104
1137
  return False
1105
1138
 
1139
+ def _pause_toggle(self, _=None):
1140
+ """Pause/Resume: the lighter, fully reversible alternative to Quit. Stops
1141
+ S4L's own scan/draft/post pipeline (the launchd kicker + its support
1142
+ daemons) while leaving Claude Desktop, this tray, and the draft
1143
+ schedule registration alone — nothing is deleted, so it survives a
1144
+ Claude restart and Resume brings it right back. Runs the real
1145
+ launchctl work directly via st.pause_s4l()/resume_s4l() (this process
1146
+ already does its own launchctl calls elsewhere, e.g. _quit_work) so it
1147
+ works even when Claude Desktop is closed — no MCP/loopback round trip."""
1148
+ action = "resume" if os.path.exists(PAUSE_FLAG) else "pause"
1149
+ self._notify("S4L", "Resuming…" if action == "resume" else "Pausing…")
1150
+ threading.Thread(target=self._pause_work, args=(action,), daemon=True).start()
1151
+
1152
+ def _pause_work(self, action):
1153
+ res = st.pause_s4l() if action == "pause" else st.resume_s4l()
1154
+ ok = bool(res.get("ok"))
1155
+ if action == "pause":
1156
+ self._notify(
1157
+ "S4L",
1158
+ "S4L paused. Drafting and posting are stopped; Claude and the tray "
1159
+ "stay up. Click Resume S4L to start again."
1160
+ if ok else "Couldn't fully pause S4L — see logs.",
1161
+ )
1162
+ else:
1163
+ self._notify(
1164
+ "S4L", "S4L resumed." if ok else "Couldn't fully resume S4L — see logs."
1165
+ )
1166
+ self._sig = None
1167
+ try:
1168
+ self._tick(None)
1169
+ except Exception as e:
1170
+ sys.stderr.write(f"[s4l-menubar] pause toggle rebuild failed: {e}\n")
1171
+ sys.stderr.flush()
1172
+
1106
1173
  def _quit_app(self, _=None):
1107
1174
  """The single Quit path. Quitting stops the autopilot completely: the
1108
1175
  draft/query scheduled tasks are removed so they no longer fire, AND the
@@ -1456,7 +1523,11 @@ class S4LMenuBar(rumps.App):
1456
1523
  # `claude --resume` history. MUST happen while Claude is down (it caches
1457
1524
  # the registry in memory and clobbers live edits). See queueWorkerCwd()
1458
1525
  # in mcp/src/index.ts and the same routine in scripts/s4l_box_update.sh.
1459
- self._rewrite_scheduled_task_cwd()
1526
+ # _fresh (not the in-process call): this is a mid-update self-heal,
1527
+ # so it must run the code that was JUST downloaded, not whatever
1528
+ # this already-running (about to be replaced) process imported at
1529
+ # ITS OWN startup — see _rewrite_scheduled_task_cwd_fresh's docstring.
1530
+ self._rewrite_scheduled_task_cwd_fresh()
1460
1531
  if target:
1461
1532
  # The graceful quit can eat minutes; restart the verify clock
1462
1533
  # now that Claude is actually down so UPDATE_VERIFY_GRACE_SEC
@@ -1646,123 +1717,72 @@ class S4LMenuBar(rumps.App):
1646
1717
  def _rewrite_scheduled_task_cwd(self):
1647
1718
  """Registry self-heal, run ONLY while Claude is DOWN (the running app
1648
1719
  caches the registry in memory and clobbers a live edit on the next
1649
- fire). Four fixes in one pass, across every scheduled-tasks.json:
1650
- 1. Point worker tasks' cwd at ~/.s4l-worker.
1651
- 2. REMOVE the deprecated single autopilot task.
1652
- 3. CONSOLIDATE every legacy worker entry into ONE s4l-worker entry
1653
- (the universal type-blind worker): drop the legacy entries and,
1654
- if no s4l-worker is registered there yet, add one inheriting the
1655
- legacy cron/enabled state. This is the migration path for installs
1656
- that predate the universal queue.
1657
- 4. ENSURE an enabled s4l-worker entry exists in EVERY account registry
1658
- (the account-switch orphan heal, 2026-07-06): switching Claude
1659
- accounts leaves the task under the old account's registry and the
1660
- new account never fires it. Writing the record into every registry
1661
- while Claude is down means whichever account the user logs into has
1662
- the task; copies under logged-out accounts are inert. Guarded by
1663
- user intent: if ANY registry holds an explicitly DISABLED worker
1664
- copy, the user turned it off — we add nothing anywhere. (The Quit
1665
- flow deletes the SKILL.md dirs, so worker_skill_ok also gates this
1666
- from resurrecting a quit install.) This restores the June 27
1667
- direct-write re-arm (45f1c45d) with the targeting problem dissolved
1668
- by writing everywhere instead of guessing the live account.
1720
+ fire). Delegates to scripts/scheduled_task_selfheal.py::heal() — the
1721
+ single implementation, importable in-process (here) or runnable as a
1722
+ standalone subprocess (see _rewrite_scheduled_task_cwd_fresh below,
1723
+ used by the update/relocate flows specifically because THIS in-process
1724
+ call can only ever execute whatever code this already-running process
1725
+ imported at its own startup, which is stale mid-update; see that
1726
+ script's module docstring for the full story, 2026-07-08).
1669
1727
  Best-effort: never raises. Kept in sync with scripts/s4l_box_update.sh
1670
1728
  and queueWorkerCwd()/QUEUE_WORKERS in mcp/src/index.ts."""
1671
1729
  try:
1672
- os.makedirs(WORKER_CWD, exist_ok=True)
1730
+ import scheduled_task_selfheal
1731
+ scheduled_task_selfheal.heal()
1673
1732
  except Exception:
1674
1733
  pass
1675
- worker_skill_ok = self._ensure_worker_skill_md()
1676
- # Pre-scan for user intent + a template: an explicitly disabled worker
1677
- # copy anywhere means the user opted out — never re-add. Otherwise clone
1678
- # cron from an existing record so the shape matches what the host wrote.
1679
- any_disabled = False
1680
- tmpl_cron = "* * * * *"
1734
+
1735
+ def _fresh_pipeline_tmpdir(self):
1736
+ """Extract THIS UPDATE's embedded pipeline.tgz (already unpacked to
1737
+ self._ext_dir() by the caller) into a throwaway temp dir and return
1738
+ its root, or None on any failure. See _rewrite_scheduled_task_cwd_fresh
1739
+ for why this matters: a subprocess run from here always imports
1740
+ whatever is on disk at invocation time, so — unlike an in-process
1741
+ call on this already-running (and about to be replaced) process — it
1742
+ can never be stale."""
1681
1743
  try:
1682
- for f in glob.glob(SCHED_REGISTRY_GLOB):
1683
- try:
1684
- with open(f) as fh:
1685
- d = json.load(fh)
1686
- except Exception:
1687
- continue
1688
- for t in (d.get("scheduledTasks") or []):
1689
- if t.get("id") in WORKER_TASK_IDS:
1690
- if not t.get("enabled", True):
1691
- any_disabled = True
1692
- if t.get("cronExpression"):
1693
- tmpl_cron = t.get("cronExpression")
1744
+ pipeline_tgz = os.path.join(self._ext_dir(), "dist", "pipeline.tgz")
1745
+ if not os.path.exists(pipeline_tgz):
1746
+ return None
1747
+ tmpd = tempfile.mkdtemp(prefix="s4l-selfheal-")
1748
+ r = subprocess.run(["tar", "-xzf", pipeline_tgz, "-C", tmpd],
1749
+ capture_output=True, timeout=60)
1750
+ return tmpd if r.returncode == 0 else None
1694
1751
  except Exception:
1695
- pass
1696
- try:
1697
- for f in glob.glob(SCHED_REGISTRY_GLOB):
1698
- try:
1699
- with open(f) as fh:
1700
- d = json.load(fh)
1701
- except Exception:
1702
- continue
1703
- tasks = d.get("scheduledTasks") or []
1704
- legacy = [t for t in tasks if t.get("id") in LEGACY_WORKER_TASK_IDS]
1705
- has_worker = any(t.get("id") == WORKER_TASK_ID for t in tasks)
1706
- new_tasks = []
1707
- dirty = False
1708
- for t in tasks:
1709
- tid = t.get("id")
1710
- if tid in DEPRECATED_TASK_IDS:
1711
- dirty = True # drop it
1712
- continue
1713
- if tid in LEGACY_WORKER_TASK_IDS and worker_skill_ok:
1714
- dirty = True # consolidated into s4l-worker below
1715
- continue
1716
- if tid in WORKER_TASK_IDS and t.get("cwd") != WORKER_CWD:
1717
- t["cwd"] = WORKER_CWD
1718
- dirty = True
1719
- new_tasks.append(t)
1720
- add_worker = worker_skill_ok and not has_worker and (
1721
- legacy # fix 3: legacy consolidation
1722
- or not any_disabled # fix 4: orphan heal (user intent guard)
1723
- )
1724
- if add_worker:
1725
- tmpl = legacy[0] if legacy else {}
1726
- new_tasks.append({
1727
- "id": WORKER_TASK_ID,
1728
- "cronExpression": tmpl.get("cronExpression") or tmpl_cron,
1729
- "enabled": bool(tmpl.get("enabled", True)),
1730
- "filePath": os.path.join(
1731
- os.path.expanduser("~"), ".claude",
1732
- "scheduled-tasks", WORKER_TASK_ID, "SKILL.md",
1733
- ),
1734
- # Fresh createdAt keeps schedule_state's CREATED_GRACE
1735
- # treating the never-yet-fired task as "ok" until its
1736
- # first fire lands (no ⚠ flap during the restart).
1737
- "createdAt": int(time.time() * 1000),
1738
- "cwd": WORKER_CWD,
1739
- })
1740
- dirty = True
1741
- if not dirty:
1742
- continue
1743
- d["scheduledTasks"] = new_tasks
1744
- try:
1745
- fd, tmp = tempfile.mkstemp(dir=os.path.dirname(f))
1746
- with os.fdopen(fd, "w") as fh:
1747
- json.dump(d, fh, indent=2)
1748
- os.replace(tmp, f)
1749
- except Exception:
1750
- pass
1751
- except Exception:
1752
- pass
1753
- # Remove retired tasks' on-disk SKILL.md dirs too, so they can't be
1754
- # re-registered from a stale prompt file (and the MCP's boot refresh
1755
- # stops resurrecting the legacy prompts).
1752
+ return None
1753
+
1754
+ def _rewrite_scheduled_task_cwd_fresh(self):
1755
+ """Run the registry self-heal via a FRESH SUBPROCESS unpacked from the
1756
+ just-downloaded bundle, instead of self._rewrite_scheduled_task_cwd
1757
+ (in-process — can only ever run the code THIS process imported at ITS
1758
+ OWN startup). Found on a real test box (2026-07-08): a self-heal fix
1759
+ shipped in a release silently did nothing during the very update that
1760
+ shipped it, because _mcpb_update_work calls the self-heal BEFORE this
1761
+ process quits and relaunches with the new code — Python does not
1762
+ hot-reload an already-imported module just because newer .py files
1763
+ landed on disk mid-run. Every future fix to the self-heal logic would
1764
+ have hit this same "one version behind" bug via this call site.
1765
+ Falls back to the in-process call if extraction fails for any reason
1766
+ (best-effort; a same-version restart isn't stale anyway)."""
1767
+ tmpd = self._fresh_pipeline_tmpdir()
1768
+ if not tmpd:
1769
+ self._rewrite_scheduled_task_cwd()
1770
+ return
1756
1771
  try:
1757
- import shutil
1758
- retired = list(DEPRECATED_TASK_IDS)
1759
- if worker_skill_ok:
1760
- retired += list(LEGACY_WORKER_TASK_IDS)
1761
- for tid in retired:
1762
- shutil.rmtree(os.path.join(os.path.expanduser("~"), ".claude",
1763
- "scheduled-tasks", tid), ignore_errors=True)
1772
+ script = os.path.join(tmpd, "package", "scripts", "scheduled_task_selfheal.py")
1773
+ if not os.path.exists(script):
1774
+ self._rewrite_scheduled_task_cwd()
1775
+ return
1776
+ py = os.environ.get("S4L_PYTHON") or sys.executable or "python3"
1777
+ subprocess.run([py, script], capture_output=True, timeout=60)
1764
1778
  except Exception:
1765
- pass
1779
+ self._rewrite_scheduled_task_cwd()
1780
+ finally:
1781
+ try:
1782
+ import shutil
1783
+ shutil.rmtree(tmpd, ignore_errors=True)
1784
+ except Exception:
1785
+ pass
1766
1786
 
1767
1787
  def _maybe_relocate_tasks(self, _=None):
1768
1788
  """Timer callback: detect, then ASK. If the autopilot tasks are in the wrong
@@ -1828,7 +1848,12 @@ class S4LMenuBar(rumps.App):
1828
1848
  # wrong profile, which orphans these very tasks from the registry.
1829
1849
  user_data_dirs = self._claude_user_data_dirs()
1830
1850
  self._quit_claude_and_wait()
1831
- self._rewrite_scheduled_task_cwd()
1851
+ # _fresh here too (2026-07-08): no code update happens in this flow
1852
+ # today, so it behaves identically to the in-process call (safe
1853
+ # fallback either way) — used unconditionally at every quit-heal-
1854
+ # relaunch call site so this can never regress silently if that
1855
+ # ever changes, rather than reasoning per call site about staleness.
1856
+ self._rewrite_scheduled_task_cwd_fresh()
1832
1857
  self._relaunch_claude(user_data_dirs)
1833
1858
  time.sleep(8) # let Claude reload the registry before we re-check
1834
1859
  if not self._scheduled_task_cwd_needs_fix():
@@ -2246,10 +2271,14 @@ class S4LMenuBar(rumps.App):
2246
2271
  # never nag the user mid-onboarding — only the value is now always honest.
2247
2272
  schedule_state = self._schedule_state()
2248
2273
  self._schedule_state_cache = schedule_state
2249
- # 'stalled' (task present + enabled, host scheduler stopped launching it:
2250
- # the Desktop warm-session wedge or an account-switch orphan) needs
2251
- # attention just like missing/disabled, but its primary fix is a Claude
2252
- # Desktop restart, not re-arm (Karol, 2026-07-06).
2274
+ # 'stalled' (task present + enabled FOR THE ACTIVE ACCOUNT, host
2275
+ # scheduler stopped launching it: the Desktop warm-session wedge,
2276
+ # Karol 2026-07-06) needs attention just like missing/disabled.
2277
+ # schedule_state.py is account-scoped (2026-07-08): an account switch
2278
+ # now correctly resolves to 'missing' (the active account genuinely
2279
+ # has no registration), not 'stalled' — a stale OTHER account's
2280
+ # registry is never consulted for the active account's health, so
2281
+ # 'stalled' can no longer be misdiagnosed here.
2253
2282
  attention = setup_complete and schedule_state in ("missing", "disabled", "stalled")
2254
2283
  # Routines-lane rate limit (429): the draft tasks ARE registered and firing
2255
2284
  # for this account, but every run dies on a Claude rate limit, so nothing
@@ -2273,14 +2302,25 @@ class S4LMenuBar(rumps.App):
2273
2302
  # has been "drafting" past DRAFT_STUCK_SECONDS the worker keeps getting
2274
2303
  # killed mid-run (or never claims) and nothing is draining — flip to ⚠
2275
2304
  # instead of leaving the reassuring "drafting (8m)" spinner up. Skip when a
2276
- # more specific cause (rate limit) already owns the reason. Gated on
2277
- # schedule_state == "ok" (like the rate-limit check above): when the
2278
- # schedule is missing/disabled (e.g. orphaned by an account switch), the
2279
- # producer ALSO sits "drafting" forever, and without this gate draft_stuck
2280
- # shadowed the missing branch in _build_menu — the user saw "worker keeps
2281
- # getting killed" with NO Re-arm button instead of "Draft tasks aren't
2282
- # scheduled on this account" + the one-click fix (Karol, 2026-07-06).
2283
- if setup_complete and schedule_state == "ok" and self._stall_reason_info[0] != "rate_limited":
2305
+ # more specific cause (rate limit) already owns the reason.
2306
+ #
2307
+ # Gated on schedule_state in ("ok", "stalled"), NOT missing/disabled: when
2308
+ # the schedule is missing/disabled (e.g. orphaned by an account switch),
2309
+ # the producer ALSO sits "drafting" forever, and without excluding those two
2310
+ # draft_stuck shadowed the missing/disabled branch in _build_menu — the user
2311
+ # saw "worker keeps getting killed" with NO Re-arm button instead of "Draft
2312
+ # tasks aren't scheduled on this account" + the one-click fix (Karol,
2313
+ # 2026-07-06). "stalled" is deliberately included (2026-07-08): that
2314
+ # branch's fix (Set up draft schedule / re-arm) works for it too, but a
2315
+ # job that has sat this long — claimed-and-hung, OR never claimed at all
2316
+ # (see the ⧖ prefix check below) — is more specific, direct evidence
2317
+ # from the queue itself than the host's lastRunAt staleness, so it's
2318
+ # worth surfacing as its own reason even under "stalled".
2319
+ if (
2320
+ setup_complete
2321
+ and schedule_state in ("ok", "stalled")
2322
+ and self._stall_reason_info[0] != "rate_limited"
2323
+ ):
2284
2324
  _act = st.read_activity()
2285
2325
  if (
2286
2326
  _act
@@ -2333,6 +2373,19 @@ class S4LMenuBar(rumps.App):
2333
2373
  "Drafts can’t run — this Claude account hit its rate limit. "
2334
2374
  + (self._stall_reason_info[1] or "Wait for the limit to reset or switch account."),
2335
2375
  )
2376
+ elif self._stall_reason_info[0] == "draft_stuck":
2377
+ # Previously unhandled here: fell through to the final `else`
2378
+ # below and told the user to click "Set up draft schedule" — a
2379
+ # button that doesn't exist in the draft_stuck menu (only
2380
+ # Diagnose does). Fixed 2026-07-08 so the notification always
2381
+ # matches the one button the menu actually shows.
2382
+ _unclaimed = "⧖" in (self._stall_reason_info[1] or "")
2383
+ self._notify(
2384
+ "S4L drafts not completing",
2385
+ ("No worker is claiming draft jobs. " if _unclaimed else
2386
+ "A worker claimed a draft job and never finished it. ")
2387
+ + "Open the S4L menu → “Diagnose & fix in Claude…”.",
2388
+ )
2336
2389
  elif schedule_state == "disabled":
2337
2390
  self._notify(
2338
2391
  "S4L draft tasks disabled",
@@ -2343,8 +2396,8 @@ class S4LMenuBar(rumps.App):
2343
2396
  self._notify(
2344
2397
  "S4L drafts stopped",
2345
2398
  "Claude’s scheduler stopped running the draft tasks (a known "
2346
- "Claude Desktop glitch). Open the S4L menu → “Restart Claude "
2347
- "Desktop to fix”.",
2399
+ "Claude Desktop glitch). Open the S4L menu → “Set up draft "
2400
+ "schedule” to re-register it.",
2348
2401
  )
2349
2402
  else:
2350
2403
  self._notify(
@@ -2395,6 +2448,7 @@ class S4LMenuBar(rumps.App):
2395
2448
  attention,
2396
2449
  schedule_state,
2397
2450
  self._stall_reason_info,
2451
+ os.path.exists(PAUSE_FLAG),
2398
2452
  )
2399
2453
  if sig != self._sig:
2400
2454
  self._sig = sig
@@ -2770,22 +2824,45 @@ class S4LMenuBar(rumps.App):
2770
2824
  with self._review_lock:
2771
2825
  activity_label = self._posting_activity_label_locked()
2772
2826
  cl = [n] if decision.get("drop_link") else None
2773
- if decision.get("edited"):
2827
+ # Two-draft cards: a draft_variant means the human picked
2828
+ # (or kept) a specific slot on a dual-draft card, route
2829
+ # through edits=[...] even with no hand-typed change, so the
2830
+ # candidate's style/assigned_style/assigned_mode switch to
2831
+ # match whichever draft is actually posting (mcp/src/index.ts
2832
+ # post_drafts applies both from the same entry). Without
2833
+ # this, a card where the human accepted the recommended
2834
+ # draft as-is (edited=False) would still need its variant
2835
+ # tag carried through for consistency with a later switch.
2836
+ draft_variant = decision.get("draft_variant")
2837
+ if decision.get("edited") or draft_variant:
2838
+ edit = {"n": n, "text": decision.get("text") or ""}
2839
+ if draft_variant:
2840
+ edit["variant"] = draft_variant
2774
2841
  res = st.post_drafts(
2775
2842
  batch,
2776
- edits=[{"n": n, "text": decision.get("text") or ""}],
2843
+ edits=[edit],
2777
2844
  clear_link=cl,
2778
2845
  activity_label=activity_label,
2779
2846
  )
2780
2847
  else:
2781
2848
  res = st.post_drafts(batch, post=[n], clear_link=cl, activity_label=activity_label)
2782
2849
  if res is None:
2783
- # Loopback unreachable (Claude closed). Mark failed so the card
2784
- # falls back to manual review rather than silently vanishing.
2785
- st.approved_queue_set_status(batch, n, "failed", error="loopback_unreachable")
2786
- st.store_mark_post_failed(batch, n, decision.get("candidate_id"), "loopback_unreachable")
2850
+ # Loopback unreachable (Claude closed, mid-restart, or an
2851
+ # account switch tore down the old MCP server before a new
2852
+ # one registered). Unlike a real posting failure, nothing
2853
+ # was ever attempted here — post_drafts never reached a
2854
+ # server — so there's no double-post risk in retrying.
2855
+ # Deliberately do NOT call store_mark_post_failed / set
2856
+ # status "failed": both would exclude this card from
2857
+ # store_pending_posts()/approved_queue_pending(), which is
2858
+ # exactly what _resume_approved_queue() reads on the next
2859
+ # unreachable->reachable edge. Leaving it "queued" lets
2860
+ # that existing restart-recovery path retry it
2861
+ # automatically once a server re-registers, instead of
2862
+ # stranding it for manual dashboard retry.
2863
+ st.approved_queue_set_status(batch, n, "queued", error="loopback_unreachable")
2787
2864
  self._notify(
2788
- "S4L", "Couldn't post — open Claude Desktop and try the draft again."
2865
+ "S4L", "Server unreachable — will retry automatically once Claude Desktop reconnects."
2789
2866
  )
2790
2867
  else:
2791
2868
  posted = res.get("posted") if isinstance(res, dict) else None
@@ -2841,46 +2918,77 @@ class S4LMenuBar(rumps.App):
2841
2918
  items.append(header)
2842
2919
  items.append(rumps.separator)
2843
2920
 
2921
+ # Pause: the lighter, fully reversible alternative to Quit — stops
2922
+ # drafting/posting but leaves Claude Desktop, this tray, and the draft
2923
+ # schedule alone. Top of the menu: it's the primary control. See
2924
+ # _pause_toggle.
2925
+ if os.path.exists(PAUSE_FLAG):
2926
+ items.append(self._label("⏸ S4L is paused — drafting & posting stopped"))
2927
+ items.append(rumps.MenuItem("Resume S4L", callback=self._pause_toggle))
2928
+ else:
2929
+ items.append(rumps.MenuItem("Pause S4L", callback=self._pause_toggle))
2930
+ items.append(self._label(" stop drafting/posting, keep Claude + tray running"))
2931
+ items.append(rumps.separator)
2932
+
2844
2933
  # Attention = the draft schedule isn't running for THIS account (missing or
2845
2934
  # disabled). "Set up draft schedule" fixes it via host create_scheduled_task.
2846
2935
  # When the schedule IS firing (ok), attention is False and nothing shows here
2847
2936
  # — a firing autopilot reads as healthy even if no draft has drained yet.
2848
2937
  if attention:
2938
+ # Exactly ONE clickable action per ⚠ scenario, always — never stack a
2939
+ # specific fix next to the universal "Diagnose & fix" escape hatch.
2940
+ # Each branch below picks whichever single action is most relevant:
2941
+ # a known mechanical fix when one exists, or Diagnose when it doesn't
2942
+ # (2026-07-08, replacing the old "specific fix + Diagnose" pattern that
2943
+ # showed 2-3 buttons at once and confused which one to click).
2849
2944
  if self._stall_reason_info[0] == "rate_limited":
2850
2945
  # Routines fire but every run dies on a Claude rate limit (429).
2851
- # Re-arm can't fix this, so don't offer it — just say what's wrong.
2946
+ # Re-arm/restart can't fix this — Diagnose is the one relevant action.
2852
2947
  items.append(self._label("⚠ Claude rate-limited — drafts can’t run"))
2853
2948
  items.append(self._label(
2854
2949
  " " + (self._stall_reason_info[1] or "wait for reset or switch account")
2855
2950
  ))
2951
+ items.append(rumps.MenuItem("Diagnose & fix in Claude…", callback=self._diagnose_fix))
2856
2952
  elif self._stall_reason_info[0] == "draft_stuck":
2857
- # Routines fire and the producer keeps narrating "drafting" but the
2858
- # worker keeps getting killed mid-run / never returns a result. Don't
2859
- # offer Re-arm (routines are fine); state the real problem.
2860
- items.append(self._label("⚠ Draft not completing — worker keeps getting killed"))
2953
+ # Routines fire and the producer keeps narrating "drafting" but
2954
+ # nothing is finishing. Two different root causes share this one
2955
+ # reason code, and the label already tells us which: a '⧖' prefix
2956
+ # (see _label_elapsed_secs) means the job has sat in the pending
2957
+ # queue this whole time with no worker ever claiming it; no '⧖'
2958
+ # means something DID claim it and then hung or died mid-run.
2959
+ # Re-arm/restart can't fix either case — Diagnose is the one action.
2960
+ _unclaimed = "⧖" in (self._stall_reason_info[1] or "")
2961
+ items.append(self._label(
2962
+ "⚠ No worker is claiming draft jobs" if _unclaimed
2963
+ else "⚠ Draft not completing — worker keeps getting killed"
2964
+ ))
2861
2965
  items.append(self._label(
2862
2966
  " " + (self._stall_reason_info[1] or "drafting") + " — no result yet"
2863
2967
  ))
2968
+ items.append(rumps.MenuItem("Diagnose & fix in Claude…", callback=self._diagnose_fix))
2864
2969
  elif schedule_state == "disabled":
2865
2970
  items.append(self._label("⚠ Draft tasks are scheduled but disabled"))
2866
2971
  items.append(rumps.MenuItem("Set up draft schedule for this account", callback=self._rearm))
2867
2972
  elif schedule_state == "stalled":
2868
- # Task registered + enabled but the host stopped launching it: the
2869
- # Claude Desktop warm-session wedge (finished worker sessions never
2870
- # exit; the overlap guard skips every fire) or an account-switch
2871
- # orphan. A full Claude restart fixes the wedge and is harmless
2872
- # otherwise, so it's the PRIMARY action; re-arm stays as fallback
2873
- # for the orphan case (Karol, 2026-07-06).
2973
+ # Task registered + enabled FOR THE ACTIVE ACCOUNT (schedule_state.py
2974
+ # is account-scoped, 2026-07-08 — see its module docstring) but the
2975
+ # host stopped launching it: the Claude Desktop warm-session wedge
2976
+ # (finished worker sessions never exit; the overlap guard skips
2977
+ # every fire). Re-arm goes through the same real create_scheduled_task
2978
+ # path as onboarding — a verified fix the user has seen work —
2979
+ # rather than a silent Claude Desktop quit/relaunch with no visible
2980
+ # feedback, which field evidence (2026-07-08) showed doesn't
2981
+ # reliably clear the underlying stall (that field incident turned
2982
+ # out to be a DIFFERENT bug: schedule_state.py was reading a stale,
2983
+ # no-longer-active account's registry — now fixed, so "stalled"
2984
+ # here means what it says: same account, task present, just not
2985
+ # firing). Distinct label from the "aren't scheduled" case below
2986
+ # since the task DOES exist here; same one-click remedy either way.
2874
2987
  items.append(self._label("⚠ Drafts stopped — Claude’s scheduler is stuck"))
2875
- items.append(rumps.MenuItem("Restart Claude Desktop to fix", callback=self._restart_claude_fix))
2876
2988
  items.append(rumps.MenuItem("Set up draft schedule for this account", callback=self._rearm))
2877
2989
  else:
2878
2990
  items.append(self._label("⚠ Draft tasks aren’t scheduled on this account"))
2879
2991
  items.append(rumps.MenuItem("Set up draft schedule for this account", callback=self._rearm))
2880
- # Universal escape hatch for EVERY persistent ⚠ (the draft_stuck and
2881
- # rate_limited branches previously dead-ended with labels only): hand
2882
- # Claude a diagnose-and-heal prompt that also reports back to us.
2883
- items.append(rumps.MenuItem("Diagnose & fix in Claude…", callback=self._diagnose_fix))
2884
2992
  items.append(rumps.separator)
2885
2993
 
2886
2994
  if not runtime_ready: