@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
@@ -249,11 +249,13 @@ def set_split(value) -> float:
249
249
  def get_draft_only() -> bool:
250
250
  """Whether every cycle stops at review cards (DEFAULT: True).
251
251
 
252
- False (operator opt-out via `draft-only off`) means promotion-lane cycles
253
- POST autonomously behind the rolling virality bar. Persona-lane cycles are
254
- unaffected either way: they always stay draft-only so the user's own voice
255
- keeps human review. Reads the retired `autopilot` key (inverted) from
256
- mode.json files written before the 2026-07-06 rename.
252
+ False (operator opt-out via `draft-only off`) means EVERY lane (promotion
253
+ AND personal_brand) POSTs autonomously; promotion additionally runs behind
254
+ the rolling virality bar. As of 2026-07-08 this is a single global switch,
255
+ not promotion-only: see skill/run-draft-and-publish.sh's DRAFT_ONLY_FLAG
256
+ gate, which applies this value uniformly across lanes. Reads the retired
257
+ `autopilot` key (inverted) from mode.json files written before the
258
+ 2026-07-06 rename.
257
259
  """
258
260
  try:
259
261
  data = json.loads(mode_file().read_text())
@@ -56,6 +56,14 @@ SECRET_PATTERNS = [
56
56
  # Absolute home path leak. Placeholder forms (/Users/<you>, /Users/USERNAME) pass.
57
57
  HOME_PATH_RE = re.compile(r"/Users/(?!<|USER|USERNAME|you\b|me\b|name\b)[a-z0-9._-]{2,}", re.I)
58
58
 
59
+
60
+ def _home_path_exempt(path: str) -> bool:
61
+ """launchd .plist files legitimately require absolute paths — launchd does not
62
+ expand ~ or $HOME in ProgramArguments/StandardOutPath/etc. The repo already
63
+ tracks 70+ of them, so exempt this file class from the absolute-home-path rule.
64
+ Secrets, PII, and image checks still apply."""
65
+ return path.startswith("launchd/") and path.endswith(".plist")
66
+
59
67
  IMAGE_EXT = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".heic", ".bmp", ".tiff"}
60
68
 
61
69
 
@@ -146,7 +154,7 @@ def scan(paths: list[str], staged: bool) -> tuple[list[str], list[str]]:
146
154
  if deny_re and deny_re.search(text):
147
155
  m = deny_re.search(text)
148
156
  hard.append(f"{path}:{lineno}: PII denylist match ('{m.group(0)}')")
149
- if HOME_PATH_RE.search(text):
157
+ if HOME_PATH_RE.search(text) and not _home_path_exempt(path):
150
158
  m = HOME_PATH_RE.search(text)
151
159
  (hard if staged else soft).append(
152
160
  f"{path}:{lineno}: absolute home path ('{m.group(0)}...')"
@@ -7,27 +7,41 @@ schedule state from HERE so the two surfaces can never drift. Previously the sam
7
7
  ~40-line algorithm was hand-maintained in both languages.
8
8
 
9
9
  The data source is the host's scheduled-task registries on disk:
10
- ~/Library/Application Support/Claude/claude-code-sessions/*/*/scheduled-tasks.json
10
+ ~/Library/Application Support/Claude/claude-code-sessions/<account-uuid>/*/scheduled-tasks.json
11
11
  A complete worker set must be present: the universal s4l-worker task (or its short-lived
12
12
  staging predecessor saps-worker), or the
13
13
  legacy pair (saps-phase1-query + saps-phase2b-draft) on pre-universal installs.
14
- The LIVE account is the registry whose tasks have the freshest lastRunAt (only
15
- the active account's scheduler advances it, so this is robust across the
16
- session-id churn that Claude restarts cause).
14
+ The LIVE account for each Claude* root is read from THAT root's config.json ->
15
+ lastKnownAccountUuid (see _active_registry_glob_patterns) — NOT inferred by
16
+ picking whichever registry has the freshest lastRunAt. An account switch
17
+ leaves the previous account's scheduled-tasks.json sitting untouched on disk
18
+ under its OWN account-uuid directory; picking "freshest lastRunAt across every
19
+ account this machine has ever logged into" can pick that orphaned registry
20
+ right back up and read a genuinely missing schedule (zero tasks for the
21
+ account actually logged in) as merely 'stalled' (found 2026-07-08: a box's
22
+ active account had NO scheduled-tasks.json anywhere, while a different,
23
+ no-longer-active account's directory still had s4l-worker enabled with a
24
+ lastRunAt from hours earlier — every "just restart Claude" attempt was
25
+ guaranteed to do nothing, because there was never anything registered for the
26
+ account that was actually running).
17
27
 
18
28
  States:
19
29
  'ok' — a complete worker set present, enabled, and FIRING (lastRunAt
20
- within FIRING_WINDOW seconds).
21
- 'disabled' — present but a worker task is disabled.
22
- 'stalled' — present AND enabled somewhere, but lastRunAt is stale: the host
23
- scheduler stopped launching it. Two known causes: the Claude
24
- Desktop warm-session wedge (finished worker sessions never exit,
25
- the overlap guard skips every fire; full app restart fixes it —
26
- Karol, 2026-07-06) or an account switch orphaning the registry.
27
- UI should offer "Restart Claude Desktop" FIRST, re-arm second.
28
- 'missing' — no registry contains a complete worker set at all (deleted /
29
- never scheduled) -> the dashboard offers "Set up draft schedule".
30
- Consumers that predate 'stalled' treated both cases as 'missing';
30
+ within FIRING_WINDOW seconds), for the ACTIVE account.
31
+ 'disabled' — present but a worker task is disabled, for the ACTIVE account.
32
+ 'stalled' — present AND enabled for the ACTIVE account, but lastRunAt is
33
+ stale: the host scheduler stopped launching it for THIS
34
+ account. Known cause: the Claude Desktop warm-session wedge
35
+ (finished worker sessions never exit, the overlap guard skips
36
+ every fire; full app restart fixes it — Karol, 2026-07-06).
37
+ Account-switch orphaning is no longer a 'stalled' cause — it
38
+ now correctly resolves to 'missing' (below), since the account
39
+ scoping means an orphaned OTHER account's registry is never
40
+ consulted for the active account's health.
41
+ 'missing' — the ACTIVE account has no registry with a complete worker set
42
+ (deleted / never scheduled / orphaned by an account switch)
43
+ -> the dashboard offers "Set up draft schedule". Consumers
44
+ that predate 'stalled' treated both cases as 'missing';
31
45
  anything gating on == 'ok' is unaffected.
32
46
 
33
47
  stdlib-only on purpose, so the MCP can run it with system python3 before the
@@ -90,16 +104,66 @@ CREATED_GRACE = 900
90
104
  # "Claude*" (not "Claude"): the host app can run with a custom --user-data-dir
91
105
  # (per-account dirs like "Claude-mediar" on multi-account machines), and the
92
106
  # registry lands under THAT dir while plain "Claude/" has no claude-code-sessions
93
- # at all. The freshest-lastRunAt selection in compute() already picks the live
94
- # registry among however many dirs match, so widening the glob is safe; the
95
- # plain-"Claude" glob read a hard "missing" forever on such machines even while
96
- # both worker tasks fired every minute (found 2026-07-02 during onboarding).
107
+ # at all. UNSCOPED across every account under each root — deliberately, this is
108
+ # also imported by callers that need to see EVERY account's registries (e.g. the
109
+ # menu bar's relocation/legacy-consolidation sweep, which must find and clean up
110
+ # old accounts' leftover tasks, not just the live one). compute()/_detail() do
111
+ # NOT use this directly by default any more — see _active_registry_glob_patterns.
97
112
  SCHED_REGISTRY_GLOB = os.path.join(
98
113
  os.path.expanduser("~"), "Library", "Application Support", "Claude*",
99
114
  "claude-code-sessions", "*", "*", "scheduled-tasks.json",
100
115
  )
101
116
 
102
117
 
118
+ def _config_json_paths():
119
+ """One config.json per Claude* root (multi-account machines can run
120
+ several distinct --user-data-dir roots, e.g. Claude-mediar, each a
121
+ separate host app instance with its own logged-in account)."""
122
+ return glob.glob(os.path.join(
123
+ os.path.expanduser("~"), "Library", "Application Support", "Claude*",
124
+ "config.json",
125
+ ))
126
+
127
+
128
+ def _active_account_uuid(config_path):
129
+ """The account currently logged into the Claude* root config_path lives
130
+ under, or None if config.json is missing/unreadable/predates this field."""
131
+ try:
132
+ with open(config_path) as fh:
133
+ d = json.load(fh)
134
+ u = d.get("lastKnownAccountUuid")
135
+ return u if isinstance(u, str) and u else None
136
+ except Exception:
137
+ return None
138
+
139
+
140
+ def _active_registry_glob_patterns():
141
+ """One glob pattern per Claude* root, scoped to ONLY the account that root
142
+ is currently logged into (verified 2026-07-08: claude-code-sessions/<uuid>/
143
+ is keyed by account — lastKnownAccountUuid in that root's config.json
144
+ matches the top-level directory local-agent-mode-sessions/<uuid>/ actually
145
+ running under, and a different, no-longer-active account's own <uuid>/
146
+ directory sits untouched alongside it). Falls back to the OLD
147
+ every-account-under-this-root pattern for a root whose config.json doesn't
148
+ resolve an account, so an unusual/older install never regresses to a blind
149
+ 'missing' just because this field happens to be absent."""
150
+ patterns = []
151
+ for cfg in _config_json_paths():
152
+ root = os.path.dirname(cfg)
153
+ uuid = _active_account_uuid(cfg)
154
+ if uuid:
155
+ patterns.append(os.path.join(
156
+ root, "claude-code-sessions", uuid, "*", "scheduled-tasks.json"
157
+ ))
158
+ else:
159
+ patterns.append(os.path.join(
160
+ root, "claude-code-sessions", "*", "*", "scheduled-tasks.json"
161
+ ))
162
+ # No Claude* root found at all (host app never launched here) -> fall back
163
+ # to the unscoped glob so callers still see SOMETHING rather than nothing.
164
+ return patterns or [SCHED_REGISTRY_GLOB]
165
+
166
+
103
167
  def _iso_to_epoch(s):
104
168
  if not s:
105
169
  return None
@@ -120,37 +184,45 @@ def _ms_to_epoch(ms):
120
184
  return None
121
185
 
122
186
 
123
- def compute(glob_pattern: str = SCHED_REGISTRY_GLOB) -> str:
124
- """Return 'ok' | 'disabled' | 'stalled' | 'missing' for the draft schedule."""
187
+ def compute(glob_pattern: str | None = None) -> str:
188
+ """Return 'ok' | 'disabled' | 'stalled' | 'missing' for the draft schedule.
189
+
190
+ With no argument (every real caller), scans ONLY the active account's
191
+ registries via _active_registry_glob_patterns() — see its docstring and
192
+ the module docstring for why. Pass an explicit glob_pattern to scan a
193
+ literal pattern instead (e.g. a test fixture dir); this bypasses account
194
+ scoping entirely, matching the old unconditional behavior."""
195
+ patterns = [glob_pattern] if glob_pattern is not None else _active_registry_glob_patterns()
125
196
  newest_epoch, newest_enabled = None, False
126
197
  # Track the freshest just-created, enabled, never-yet-fired task so a schedule
127
198
  # the user only moments ago set up doesn't read as "missing" before its first
128
199
  # fire lands (see CREATED_GRACE).
129
200
  newest_fresh_created = None
130
201
  any_present, any_enabled = False, False
131
- for f in glob.glob(glob_pattern):
132
- try:
133
- with open(f) as fh:
134
- d = json.load(fh)
135
- except Exception:
136
- continue
137
- by_id = {t.get("id"): t for t in (d.get("scheduledTasks") or [])}
138
- recs = _registry_worker_recs(by_id)
139
- if recs is None:
140
- continue
141
- any_present = True
142
- enabled = all(r.get("enabled") for r in recs)
143
- any_enabled = any_enabled or enabled
144
- epochs = [_iso_to_epoch(r.get("lastRunAt")) for r in recs]
145
- e = max([x for x in epochs if x is not None], default=None)
146
- if e is not None and (newest_epoch is None or e > newest_epoch):
147
- newest_epoch, newest_enabled = e, enabled
148
- # Freshly scheduled + enabled + not yet fired anywhere in this registry.
149
- if enabled and e is None:
150
- created = [_ms_to_epoch(r.get("createdAt")) for r in recs]
151
- c = min([x for x in created if x is not None], default=None)
152
- if c is not None and (newest_fresh_created is None or c > newest_fresh_created):
153
- newest_fresh_created = c
202
+ for pattern in patterns:
203
+ for f in glob.glob(pattern):
204
+ try:
205
+ with open(f) as fh:
206
+ d = json.load(fh)
207
+ except Exception:
208
+ continue
209
+ by_id = {t.get("id"): t for t in (d.get("scheduledTasks") or [])}
210
+ recs = _registry_worker_recs(by_id)
211
+ if recs is None:
212
+ continue
213
+ any_present = True
214
+ enabled = all(r.get("enabled") for r in recs)
215
+ any_enabled = any_enabled or enabled
216
+ epochs = [_iso_to_epoch(r.get("lastRunAt")) for r in recs]
217
+ e = max([x for x in epochs if x is not None], default=None)
218
+ if e is not None and (newest_epoch is None or e > newest_epoch):
219
+ newest_epoch, newest_enabled = e, enabled
220
+ # Freshly scheduled + enabled + not yet fired anywhere in this registry.
221
+ if enabled and e is None:
222
+ created = [_ms_to_epoch(r.get("createdAt")) for r in recs]
223
+ c = min([x for x in created if x is not None], default=None)
224
+ if c is not None and (newest_fresh_created is None or c > newest_fresh_created):
225
+ newest_fresh_created = c
154
226
  # Firing recently => the live account's schedule is active and healthy.
155
227
  if newest_epoch is not None and (time.time() - newest_epoch) <= FIRING_WINDOW:
156
228
  return "ok" if newest_enabled else "disabled"
@@ -158,9 +230,11 @@ def compute(glob_pattern: str = SCHED_REGISTRY_GLOB) -> str:
158
230
  # Suppresses the false ⚠ right after the user sets up the draft schedule.
159
231
  if newest_fresh_created is not None and (time.time() - newest_fresh_created) <= CREATED_GRACE:
160
232
  return "ok"
161
- # Not firing anywhere. Registered-but-disabled => disabled; registered and
162
- # enabled but the host stopped launching it => stalled (Desktop scheduler
163
- # wedge or account-switch orphan); absent everywhere => missing.
233
+ # Not firing anywhere for the active account. Registered-but-disabled =>
234
+ # disabled; registered and enabled but the host stopped launching it =>
235
+ # stalled (Desktop scheduler wedge, SAME account); absent for the active
236
+ # account entirely (never scheduled, or orphaned by an account switch) =>
237
+ # missing.
164
238
  if any_present and not any_enabled:
165
239
  return "disabled"
166
240
  if any_present and any_enabled:
@@ -168,29 +242,32 @@ def compute(glob_pattern: str = SCHED_REGISTRY_GLOB) -> str:
168
242
  return "missing"
169
243
 
170
244
 
171
- def _detail(glob_pattern: str = SCHED_REGISTRY_GLOB) -> dict:
172
- """Cheap diagnostics for the JSON output: which registries the glob saw and
173
- which contain both worker tasks, with each one's freshest lastRunAt age.
174
- This is what makes a 'missing' verdict debuggable from a log line instead of
175
- requiring filesystem forensics (the 2026-07-02 rotated-dir bug hid here)."""
245
+ def _detail(glob_pattern: str | None = None) -> dict:
246
+ """Cheap diagnostics for the JSON output: which registries the glob(s) saw
247
+ and which contain both worker tasks, with each one's freshest lastRunAt
248
+ age. This is what makes a 'missing' verdict debuggable from a log line
249
+ instead of requiring filesystem forensics (the 2026-07-02 rotated-dir bug,
250
+ and the 2026-07-08 wrong-account bug, both hid here)."""
251
+ patterns = [glob_pattern] if glob_pattern is not None else _active_registry_glob_patterns()
176
252
  regs = []
177
- for f in glob.glob(glob_pattern):
178
- entry = {"path": f, "has_workers": False, "last_run_age_s": None}
179
- try:
180
- with open(f) as fh:
181
- d = json.load(fh)
182
- by_id = {t.get("id"): t for t in (d.get("scheduledTasks") or [])}
183
- recs = _registry_worker_recs(by_id)
184
- if recs is not None:
185
- entry["has_workers"] = True
186
- epochs = [_iso_to_epoch(r.get("lastRunAt")) for r in recs]
187
- e = max([x for x in epochs if x is not None], default=None)
188
- if e is not None:
189
- entry["last_run_age_s"] = int(time.time() - e)
190
- except Exception as exc:
191
- entry["error"] = str(exc)
192
- regs.append(entry)
193
- return {"glob": glob_pattern, "registries": regs}
253
+ for pattern in patterns:
254
+ for f in glob.glob(pattern):
255
+ entry = {"path": f, "has_workers": False, "last_run_age_s": None}
256
+ try:
257
+ with open(f) as fh:
258
+ d = json.load(fh)
259
+ by_id = {t.get("id"): t for t in (d.get("scheduledTasks") or [])}
260
+ recs = _registry_worker_recs(by_id)
261
+ if recs is not None:
262
+ entry["has_workers"] = True
263
+ epochs = [_iso_to_epoch(r.get("lastRunAt")) for r in recs]
264
+ e = max([x for x in epochs if x is not None], default=None)
265
+ if e is not None:
266
+ entry["last_run_age_s"] = int(time.time() - e)
267
+ except Exception as exc:
268
+ entry["error"] = str(exc)
269
+ regs.append(entry)
270
+ return {"glob": patterns, "registries": regs}
194
271
 
195
272
 
196
273
  def main() -> int:
@@ -0,0 +1,276 @@
1
+ #!/usr/bin/env python3
2
+ """Scheduled-task registry self-heal, run ONLY while Claude Desktop is DOWN
3
+ (the running app caches the registry in memory and clobbers a live edit on
4
+ its next fire).
5
+
6
+ WHY THIS IS A STANDALONE SCRIPT, NOT JUST A MENU BAR METHOD (2026-07-08):
7
+ this logic used to live only as mcp/menubar/s4l_menubar.py::_rewrite_scheduled_task_cwd,
8
+ called in-process from _mcpb_update_work and _relocate_restart_work. Both of
9
+ those run INSIDE the already-executing (old) menu bar process, BEFORE that
10
+ process quits and relaunches with the just-downloaded new code — Python does
11
+ not hot-reload an already-imported module just because newer .py files landed
12
+ on disk mid-run. So a fix shipped to that method would only ever take effect
13
+ on the update AFTER the one that shipped it: found on a real test box where a
14
+ newly-added fix (creating a missing registry) silently did nothing during the
15
+ very update that shipped it, because the self-heal call that fired still ran
16
+ the OLD in-process code.
17
+
18
+ The fix: unpack THIS script fresh from the just-downloaded bundle's embedded
19
+ pipeline.tgz and run it as a NEW subprocess (see the callers in
20
+ mcp/menubar/s4l_menubar.py) — a subprocess always imports whatever is on disk
21
+ at invocation time, so it can never be stale the way an in-process call can.
22
+ mcp/menubar/s4l_menubar.py::_rewrite_scheduled_task_cwd now delegates to
23
+ heal() here for in-process callers where staleness isn't the concern (kept for
24
+ back-compat rather than hunting down every caller).
25
+
26
+ stdlib-only on purpose, matching scripts/schedule_state.py's pattern.
27
+ Run as a script -> heals, then prints {"ok": true, ...} as JSON.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import glob
32
+ import json
33
+ import os
34
+ import shutil
35
+ import sys
36
+ import tempfile
37
+ import time
38
+
39
+ import schedule_state # noqa: E402 (lives next to this file in scripts/)
40
+
41
+ WORKER_TASK_ID = "s4l-worker"
42
+ WORKER_TASK_IDS = ("s4l-worker", "saps-worker", "saps-phase1-query", "saps-phase2b-draft")
43
+ LEGACY_WORKER_TASK_IDS = ("saps-worker", "saps-phase1-query", "saps-phase2b-draft")
44
+ DEPRECATED_TASK_IDS = ("social-autoposter-autopilot",)
45
+ WORKER_CWD = os.path.join(os.path.expanduser("~"), ".s4l-worker")
46
+
47
+ # Kept in sync with SCHED_REGISTRY_GLOB in mcp/menubar/s4l_menubar.py,
48
+ # scripts/schedule_state.py, scripts/scheduled_tasks_snapshot.py, and
49
+ # queueWorkerCwd()/QUEUE_WORKERS in mcp/src/index.ts (same constant,
50
+ # necessarily duplicated across languages/processes -- pre-existing pattern).
51
+ SCHED_REGISTRY_GLOB = os.path.join(
52
+ os.path.expanduser("~"), "Library", "Application Support", "Claude*",
53
+ "claude-code-sessions", "*", "*", "scheduled-tasks.json",
54
+ )
55
+
56
+
57
+ def _ensure_worker_skill_md() -> bool:
58
+ """Make sure ~/.claude/scheduled-tasks/s4l-worker/SKILL.md exists before we
59
+ register a task that points at it. The MCP writes it on every boot
60
+ (create-if-missing), so normally this is a no-op; as a belt-and-suspenders
61
+ fallback we clone a legacy worker's file and fix the frontmatter name."""
62
+ base = os.path.join(os.path.expanduser("~"), ".claude", "scheduled-tasks")
63
+ dst = os.path.join(base, WORKER_TASK_ID, "SKILL.md")
64
+ if os.path.exists(dst):
65
+ return True
66
+ for tid in LEGACY_WORKER_TASK_IDS:
67
+ src = os.path.join(base, tid, "SKILL.md")
68
+ try:
69
+ with open(src) as fh:
70
+ body = fh.read()
71
+ except Exception:
72
+ continue
73
+ try:
74
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
75
+ with open(dst, "w") as fh:
76
+ fh.write(body.replace(f"name: {tid}", f"name: {WORKER_TASK_ID}", 1))
77
+ return True
78
+ except Exception:
79
+ continue
80
+ return False
81
+
82
+
83
+ def heal() -> dict:
84
+ """Five fixes in one pass, across every scheduled-tasks.json:
85
+ 1. Point worker tasks' cwd at ~/.s4l-worker.
86
+ 2. REMOVE the deprecated single autopilot task.
87
+ 3. CONSOLIDATE every legacy worker entry into ONE s4l-worker entry (the
88
+ universal type-blind worker): drop the legacy entries and, if no
89
+ s4l-worker is registered there yet, add one inheriting the legacy
90
+ cron/enabled state. Migration path for pre-universal-queue installs.
91
+ 4. ENSURE an enabled s4l-worker entry exists in EVERY account registry
92
+ that already has a scheduled-tasks.json (the account-switch orphan
93
+ heal, 2026-07-06): switching Claude accounts leaves the task under
94
+ the old account's registry and the new account never fires it.
95
+ Writing the record into every EXISTING registry while Claude is down
96
+ means whichever account the user logs into has the task; copies
97
+ under logged-out accounts are inert. Guarded by user intent: if ANY
98
+ registry holds an explicitly DISABLED worker copy, the user turned
99
+ it off -- add nothing anywhere. (The Quit flow deletes the SKILL.md
100
+ dirs, so worker_skill_ok also gates this from resurrecting a quit
101
+ install.) This restores the June 27 direct-write re-arm (45f1c45d)
102
+ with the targeting problem dissolved by writing everywhere instead
103
+ of guessing the live account.
104
+ 5. CREATE a fresh registry for the active account when it has NONE at
105
+ all (2026-07-08): fix 4 only edits files the glob finds -- it can
106
+ never create one where none exists. An account that's never had a
107
+ scheduled-tasks.json (just switched into, never scheduled on this
108
+ box) got nothing written despite fix 4 running: found on a real test
109
+ box where the active account's entire claude-code-sessions/<uuid>/
110
+ tree held zero registry files. Resolves the active account via
111
+ schedule_state.py's config.json lookup (lastKnownAccountUuid,
112
+ verified correct against real installs 2026-07-08) and writes a
113
+ fresh worker entry into its most-recently-touched EXISTING session
114
+ directory (never fabricates a new directory). Same user-intent and
115
+ worker_skill_ok guards as fix 4.
116
+ Best-effort: never raises. Returns a small summary dict for logging."""
117
+ summary = {"ok": True, "edited": [], "created": [], "error": None}
118
+ try:
119
+ os.makedirs(WORKER_CWD, exist_ok=True)
120
+ except Exception:
121
+ pass
122
+ worker_skill_ok = _ensure_worker_skill_md()
123
+
124
+ # Pre-scan for user intent + a template: an explicitly disabled worker
125
+ # copy anywhere means the user opted out -- never re-add. Otherwise clone
126
+ # cron from an existing record so the shape matches what the host wrote.
127
+ any_disabled = False
128
+ tmpl_cron = "* * * * *"
129
+ try:
130
+ for f in glob.glob(SCHED_REGISTRY_GLOB):
131
+ try:
132
+ with open(f) as fh:
133
+ d = json.load(fh)
134
+ except Exception:
135
+ continue
136
+ for t in (d.get("scheduledTasks") or []):
137
+ if t.get("id") in WORKER_TASK_IDS:
138
+ if not t.get("enabled", True):
139
+ any_disabled = True
140
+ if t.get("cronExpression"):
141
+ tmpl_cron = t.get("cronExpression")
142
+ except Exception:
143
+ pass
144
+
145
+ # Fixes 1-4: edit every EXISTING registry file the glob finds.
146
+ try:
147
+ for f in glob.glob(SCHED_REGISTRY_GLOB):
148
+ try:
149
+ with open(f) as fh:
150
+ d = json.load(fh)
151
+ except Exception:
152
+ continue
153
+ tasks = d.get("scheduledTasks") or []
154
+ legacy = [t for t in tasks if t.get("id") in LEGACY_WORKER_TASK_IDS]
155
+ has_worker = any(t.get("id") == WORKER_TASK_ID for t in tasks)
156
+ new_tasks = []
157
+ dirty = False
158
+ for t in tasks:
159
+ tid = t.get("id")
160
+ if tid in DEPRECATED_TASK_IDS:
161
+ dirty = True # drop it
162
+ continue
163
+ if tid in LEGACY_WORKER_TASK_IDS and worker_skill_ok:
164
+ dirty = True # consolidated into s4l-worker below
165
+ continue
166
+ if tid in WORKER_TASK_IDS and t.get("cwd") != WORKER_CWD:
167
+ t["cwd"] = WORKER_CWD
168
+ dirty = True
169
+ new_tasks.append(t)
170
+ add_worker = worker_skill_ok and not has_worker and (
171
+ legacy # fix 3: legacy consolidation
172
+ or not any_disabled # fix 4: orphan heal (user intent guard)
173
+ )
174
+ if add_worker:
175
+ tmpl = legacy[0] if legacy else {}
176
+ new_tasks.append({
177
+ "id": WORKER_TASK_ID,
178
+ "cronExpression": tmpl.get("cronExpression") or tmpl_cron,
179
+ "enabled": bool(tmpl.get("enabled", True)),
180
+ "filePath": os.path.join(
181
+ os.path.expanduser("~"), ".claude",
182
+ "scheduled-tasks", WORKER_TASK_ID, "SKILL.md",
183
+ ),
184
+ # Fresh createdAt keeps schedule_state's CREATED_GRACE
185
+ # treating the never-yet-fired task as "ok" until its
186
+ # first fire lands (no ⚠ flap during the restart).
187
+ "createdAt": int(time.time() * 1000),
188
+ "cwd": WORKER_CWD,
189
+ })
190
+ dirty = True
191
+ if not dirty:
192
+ continue
193
+ d["scheduledTasks"] = new_tasks
194
+ try:
195
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(f))
196
+ with os.fdopen(fd, "w") as fh:
197
+ json.dump(d, fh, indent=2)
198
+ os.replace(tmp, f)
199
+ summary["edited"].append(f)
200
+ except Exception:
201
+ pass
202
+ except Exception as e:
203
+ summary["error"] = str(e)
204
+
205
+ # Fix 5: create a fresh registry for the active account when it has none.
206
+ try:
207
+ if worker_skill_ok and not any_disabled:
208
+ for cfg in schedule_state._config_json_paths():
209
+ root = os.path.dirname(cfg)
210
+ uuid = schedule_state._active_account_uuid(cfg)
211
+ if not uuid:
212
+ continue
213
+ account_dir = os.path.join(root, "claude-code-sessions", uuid)
214
+ existing = glob.glob(os.path.join(account_dir, "*", "scheduled-tasks.json"))
215
+ if existing:
216
+ continue # fixes 1-4 above already cover this account
217
+ session_dirs = [
218
+ p for p in glob.glob(os.path.join(account_dir, "*"))
219
+ if os.path.isdir(p)
220
+ ]
221
+ if not session_dirs:
222
+ continue # Desktop has never created a session for this
223
+ # account on this box -- nowhere safe to write
224
+ # Most-recently-touched session dir is the best available
225
+ # guess for "the one Desktop is actively using".
226
+ target_dir = max(session_dirs, key=lambda p: os.path.getmtime(p))
227
+ target_file = os.path.join(target_dir, "scheduled-tasks.json")
228
+ new_entry = {
229
+ "id": WORKER_TASK_ID,
230
+ "cronExpression": tmpl_cron,
231
+ "enabled": True,
232
+ "filePath": os.path.join(
233
+ os.path.expanduser("~"), ".claude",
234
+ "scheduled-tasks", WORKER_TASK_ID, "SKILL.md",
235
+ ),
236
+ "createdAt": int(time.time() * 1000),
237
+ "cwd": WORKER_CWD,
238
+ }
239
+ try:
240
+ fd, tmp = tempfile.mkstemp(dir=target_dir)
241
+ with os.fdopen(fd, "w") as fh:
242
+ json.dump(
243
+ {"scheduledTasks": [new_entry], "recordedSkips": []},
244
+ fh, indent=2,
245
+ )
246
+ os.replace(tmp, target_file)
247
+ summary["created"].append(target_file)
248
+ except Exception:
249
+ pass
250
+ except Exception as e:
251
+ summary["error"] = summary["error"] or str(e)
252
+
253
+ # Remove retired tasks' on-disk SKILL.md dirs too, so they can't be
254
+ # re-registered from a stale prompt file (and the MCP's boot refresh
255
+ # stops resurrecting the legacy prompts).
256
+ try:
257
+ retired = list(DEPRECATED_TASK_IDS)
258
+ if worker_skill_ok:
259
+ retired += list(LEGACY_WORKER_TASK_IDS)
260
+ for tid in retired:
261
+ shutil.rmtree(os.path.join(os.path.expanduser("~"), ".claude",
262
+ "scheduled-tasks", tid), ignore_errors=True)
263
+ except Exception:
264
+ pass
265
+
266
+ return summary
267
+
268
+
269
+ def main() -> int:
270
+ out = heal()
271
+ print(json.dumps(out))
272
+ return 0
273
+
274
+
275
+ if __name__ == "__main__":
276
+ sys.exit(main())