@m13v/s4l 1.7.12-rc.1 → 1.7.12-rc.11

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 (46) hide show
  1. package/browser-agent-configs/linkedin-harness-mcp.json +3 -1
  2. package/browser-agent-configs/twitter-harness-mcp.json +3 -1
  3. package/mcp/dist/index.js +234 -59
  4. package/mcp/dist/repo.js +65 -5
  5. package/mcp/dist/runtime.js +1 -1
  6. package/mcp/dist/setup.js +35 -28
  7. package/mcp/dist/version.json +2 -2
  8. package/mcp/manifest.json +1 -1
  9. package/mcp/menubar/s4l_menubar.py +151 -0
  10. package/mcp/menubar/s4l_state.py +122 -24
  11. package/mcp/package.json +1 -1
  12. package/package.json +18 -1
  13. package/scripts/angles.py +8 -0
  14. package/scripts/cdp_drive.py +102 -0
  15. package/scripts/cdp_ready_check.py +56 -9
  16. package/scripts/claude_job.py +25 -29
  17. package/scripts/config.py +51 -3
  18. package/scripts/context_mining.py +352 -0
  19. package/scripts/draft_prompt_core.py +31 -4
  20. package/scripts/dump_visitor_history.py +72 -0
  21. package/scripts/engage_github.py +62 -3
  22. package/scripts/harness_overlay.py +84 -39
  23. package/scripts/ingest_human_github_replies.py +205 -0
  24. package/scripts/invent_topics.py +10 -3
  25. package/scripts/pick_thread_target.py +4 -0
  26. package/scripts/pick_twitter_thread_target.py +4 -0
  27. package/scripts/post_reddit.py +40 -43
  28. package/scripts/project_topics.py +59 -1
  29. package/scripts/qualified_query_bank.py +53 -2
  30. package/scripts/reap_stale_claude_sessions.py +168 -6
  31. package/scripts/reddit_ban_check.py +28 -28
  32. package/scripts/reddit_query_bank.py +42 -2
  33. package/scripts/reply_db.py +19 -0
  34. package/scripts/s4l_box_update.sh +46 -4
  35. package/scripts/s4l_mode.py +41 -0
  36. package/scripts/scan_github_replies.py +34 -8
  37. package/scripts/schedule_state.py +14 -5
  38. package/scripts/scrape_linkedin_comment_stats.py +25 -7
  39. package/scripts/session_index_prune.py +214 -0
  40. package/scripts/update_linkedin_stats_from_feed.py +20 -1
  41. package/scripts/voice_exemplars.py +8 -3
  42. package/skill/check-web-chats.sh +45 -0
  43. package/skill/run-twitter-cycle.sh +27 -0
  44. package/skill/run-twitter-threads.sh +51 -0
  45. package/scripts/tlh_freshness_284.py +0 -134
  46. package/scripts/tlh_pick_248.py +0 -92
@@ -14,7 +14,9 @@
14
14
  "PATH": "__HOME__/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin",
15
15
  "BU_NAME": "linkedin-harness",
16
16
  "BH_PORT": "9556",
17
- "BH_PROFILE_NAME": "browser-harness-linkedin"
17
+ "BH_PROFILE_NAME": "browser-harness-linkedin",
18
+ "BH_WINDOW_POS": "3814,-1050",
19
+ "BH_WINDOW_SIZE": "1024,1013"
18
20
  }
19
21
  }
20
22
  }
@@ -11,7 +11,9 @@
11
11
  "__HOME__/.claude/mcp-servers/browser-harness/server.py"
12
12
  ],
13
13
  "env": {
14
- "PATH": "__HOME__/.local/bin:__NODE_BIN__:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
14
+ "PATH": "__HOME__/.local/bin:__NODE_BIN__:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin",
15
+ "BH_WINDOW_POS": "3042,-1032",
16
+ "BH_WINDOW_SIZE": "1024,1013"
15
17
  }
16
18
  }
17
19
  }
package/mcp/dist/index.js CHANGED
@@ -23,7 +23,7 @@ import { repoDir, runPython, run, readPlan, writePlan, planPath, TMP_DIR, } from
23
23
  import { applySetup, resolveProject, hasReadyProject, personaReady, listManagedProjectStatus, listProjectSettings, ensureShortLinksDefault, ensurePersonaProject, findPersonaProject, REQUIRED_FIELDS, RECOMMENDED_FIELDS, configPath, ensureConfigInStateDir, normalizeStringList, recordRedditAccount, } from "./setup.js";
24
24
  import { xStatus, xConnect, xDetectSources, xScanProfile, summarizeXAuth } from "./twitterAuth.js";
25
25
  import { redditStatus, redditConnect, redditDetectSources, summarizeRedditAuth, } from "./redditAuth.js";
26
- import { startProvisioning, isProvisioning, readProgress, runtimeReady, readRuntime, resolvePython, resolveChrome, ensureMenubar, menubarRunning, clearMenubarStop, ensurePipelineCurrent, ensureRuntimeProvisioned, ensureHarnessPatched, retryProvisionIfStalled, } from "./runtime.js";
26
+ import { startProvisioning, isProvisioning, readProgress, runtimeReady, readRuntime, resolvePython, resolveChrome, ensureMenubar, menubarRunning, clearMenubarStop, ensurePipelineCurrent, ensureRuntimeProvisioned, ensureHarnessPatched, retryProvisionIfStalled, menubarSourceDir, } from "./runtime.js";
27
27
  import { blockOnboardingMilestone, completeOnboardingMilestone, ensureDoctorPhase, onboardingLedger, onboardingSnapshot, recordOnboardingAttempt, runDoctorPhase, } from "./onboarding.js";
28
28
  import { VERSION, versionStatus, latestPublishedVersion } from "./version.js";
29
29
  import { initSentry, sendHeartbeat, sendStateSnapshot, captureError, captureMessage, flushSentry, startLogStreaming, flushLogs, logLine, checkVersionChange } from "./telemetry.js";
@@ -3690,9 +3690,12 @@ tool("queue_setup", {
3690
3690
  writeDraftProvider("claude-desktop-queue", "queue_setup(claude)");
3691
3691
  ensureQueueWorkerToolsAllowed();
3692
3692
  // Re-arming the autopilot is an explicit "start S4L" action: lift a prior
3693
- // tray Quit so the review cards have a surface again. Best-effort and
3694
- // async — task specs must return regardless of tray state.
3693
+ // tray Quit (which is Pause + tray removal) so the pipeline and the review
3694
+ // cards come back. Best-effort and async — task specs must return
3695
+ // regardless of tray state.
3695
3696
  clearMenubarStop();
3697
+ if (isPaused())
3698
+ void resumeS4L();
3696
3699
  void ensureMenubar();
3697
3700
  // Write each worker's canonical SKILL.md to disk NOW, before the agent calls
3698
3701
  // create_scheduled_task. The host's create_scheduled_task can report a task
@@ -3832,8 +3835,8 @@ async function autopilotLoaded() {
3832
3835
  // fires every minute, claims ONE job, runs the pipeline's own prompt as its
3833
3836
  // Claude turn, writes the result back, and stops.
3834
3837
  // ===========================================================================
3835
- const QUEUE_WORKER_PROMPT_VERSION = 9; // v9 (2026-07-17): poll window widened 240s -> 900s (see QUEUE_WORKER_POLL_SECONDS); version bump forces the prompt refresh that carries the new --wait-seconds onto existing installs. v8: worker polls internally (claude_job.py next --wait-seconds) instead of single-shot check-then-die. Empirically verified (2026-07-06) that a single long-running Bash call survives well past the host's ~90s between-tool-call inactivity kill — that timer only fires on MODEL silence, not on one in-flight tool call — so one Bash call can safely poll for QUEUE_WORKER_POLL_SECONDS before giving up. This cuts the every-minute spin-up-empty-then-die husk cycle down to roughly one session per poll window instead of one per cron tick. v7: universal type-blind worker. ONE task claims `--type any`; per-type execution notes (e.g. the v6 incremental-draft pacing for twitter-prep) moved into claude_job.py TYPE_TO_WORKER_NOTES and ride the prompt sidecar, so the worker prompt never mentions job types. Legacy per-type tasks get this same body on refresh and become interchangeable universal workers.
3836
- // v10 (PLANNED, NOT IMPLEMENTED): delegate the actual drafting to a fresh
3838
+ const QUEUE_WORKER_PROMPT_VERSION = 10; // v10 (2026-10-29): poll window 900s -> 540s so one `next` call fits inside the Bash tool's 600s default timeout, self-reap disabled (S4L_WORKER_SELF_REAP=0 on every claude_job call), and the session ends by archiving itself instead of a SIGTERM. v9 (2026-07-17): poll window widened 240s -> 900s; version bump forces the prompt refresh that carries the new --wait-seconds onto existing installs. v8: worker polls internally (claude_job.py next --wait-seconds) instead of single-shot check-then-die. Empirically verified (2026-07-06) that a single long-running Bash call survives well past the host's ~90s between-tool-call inactivity kill — that timer only fires on MODEL silence, not on one in-flight tool call — so one Bash call can safely poll for QUEUE_WORKER_POLL_SECONDS before giving up. This cuts the every-minute spin-up-empty-then-die husk cycle down to roughly one session per poll window instead of one per cron tick. v7: universal type-blind worker. ONE task claims `--type any`; per-type execution notes (e.g. the v6 incremental-draft pacing for twitter-prep) moved into claude_job.py TYPE_TO_WORKER_NOTES and ride the prompt sidecar, so the worker prompt never mentions job types. Legacy per-type tasks get this same body on refresh and become interchangeable universal workers.
3839
+ // v11 (PLANNED, NOT IMPLEMENTED): delegate the actual drafting to a fresh
3837
3840
  // sub-agent per claimed job (claim -> delegate -> wait -> claim next, looped
3838
3841
  // within one continuous worker session) instead of drafting inline. Validated
3839
3842
  // via throwaway probe tasks 2026-07-07/08 (10 loop iterations, ~210s of real
@@ -3842,10 +3845,19 @@ const QUEUE_WORKER_PROMPT_VERSION = 9; // v9 (2026-07-17): poll window widened 2
3842
3845
  // notification) or the host kills the whole parent+child chain in 1-3 min.
3843
3846
  // Never live-fire tested against a real production job. Full design, what's
3844
3847
  // validated vs not, and the implementation steps: docs/queue-worker-delegation-plan.md
3845
- // Bump this constant to 10 only once that plan is actually implemented.
3848
+ // Bump this constant to 11 only once that plan is actually implemented.
3846
3849
  const QUEUE_WORKER_PROMPT_MARKER = "s4l_queue_worker_prompt_version";
3847
3850
  // How long ONE `next --wait-seconds` call polls before giving up and exiting.
3848
- // 900s (15 min, per Matthew 2026-07-17, up from 240s): sits AT the single-
3851
+ // 540s (9 min, 2026-10-29, down from 900s): MUST stay below the Bash tool's
3852
+ // 600s default timeout. Measured on 2026-10-29 in Claude Desktop 4.29: the
3853
+ // 900s poll hit the 600s tool timeout on every empty cycle (81 of 106 runs
3854
+ // that day), the CLI then re-emitted a ~200KB prompt snapshot (a 7s
3855
+ // main-thread stall in the app), the poller kept running as an orphaned
3856
+ // background task for the remaining 300s, and its self-reap SIGTERM cost one
3857
+ // or two more 7s stalls plus an exit-143 re-attach. With the poll inside the
3858
+ // tool timeout the call returns normally, nothing is orphaned, and the worker
3859
+ // archives itself (step 5 of the prompt) at zero measured cost.
3860
+ // Earlier rationale (900s, per Matthew 2026-07-17, up from 240s): sits AT the single-
3849
3861
  // Bash-call survival ceiling verified live on 2026-07-06 (the host's ~90s
3850
3862
  // inactivity kill fires only on model silence, and one in-flight tool call
3851
3863
  // survived a full 900s probe). This covers the ~8min average real job
@@ -3861,7 +3873,7 @@ const QUEUE_WORKER_PROMPT_MARKER = "s4l_queue_worker_prompt_version";
3861
3873
  // poll window is legitimately still working, not a husk, and a too-tight
3862
3874
  // claim_grace would SIGTERM it mid-poll before it ever gets to claim.
3863
3875
  // (Bumped to 1020s alongside this change.)
3864
- const QUEUE_WORKER_POLL_SECONDS = 900;
3876
+ const QUEUE_WORKER_POLL_SECONDS = 540;
3865
3877
  // One spec per worker task. queueType MUST match scripts/claude_job.py TAG_TO_TYPE.
3866
3878
  const QUEUE_WORKERS = [
3867
3879
  { taskId: WORKER_TASK_ID, queueType: "any", human: "universal queue" },
@@ -3983,8 +3995,9 @@ function queueWorkerBody(spec) {
3983
3995
  `The deterministic pipeline runs on this Mac. When it needs a Claude turn it ` +
3984
3996
  `drops a job on a local file queue. Your only job: pick up the next job, do ` +
3985
3997
  `EXACTLY what its prompt says, hand the result back. You do this with Bash, ` +
3986
- `Read, and Write, and NOTHING else. This run is unattended — reaching for any ` +
3987
- `other tool, or trying to "investigate", STALLS it forever.`,
3998
+ `Read, and Write, and NOTHING else (except the single archive call in step 5). ` +
3999
+ `This run is unattended — reaching for any other tool, or trying to ` +
4000
+ `"investigate", STALLS it forever.`,
3988
4001
  ``,
3989
4002
  `PACING — CRITICAL: this unattended session is terminated ~90 seconds after ` +
3990
4003
  `your LAST tool call (a host inactivity timeout). That clock only runs BETWEEN ` +
@@ -4000,11 +4013,16 @@ function queueWorkerBody(spec) {
4000
4013
  `1. Look for the next job. Run this EXACT Bash command and let it run to ` +
4001
4014
  `completion — it polls internally for up to ${Math.round(QUEUE_WORKER_POLL_SECONDS / 60)} ` +
4002
4015
  `minutes before giving up, so it may take a while to return. That is normal: ` +
4003
- `do NOT interrupt it and do NOT make any other tool call while it is running.`,
4004
- ` ${py} ${job} next --type any --prompt-file --wait-seconds ${QUEUE_WORKER_POLL_SECONDS} --state-dir ${sd}`,
4016
+ `do NOT interrupt it and do NOT make any other tool call while it is running. ` +
4017
+ `Pass the Bash tool's timeout parameter as 600000 (its 10-minute maximum) so ` +
4018
+ `the call is never moved to the background. If the result nevertheless says ` +
4019
+ `the command was moved to the background (this happens when the Mac sleeps ` +
4020
+ `mid-poll; the timeout is wall-clock), do NOT wait for it: call TaskStop with ` +
4021
+ `the ID it gives you, report "no jobs" in one line, and go to step 5.`,
4022
+ ` S4L_WORKER_SELF_REAP=0 ${py} ${job} next --type any --prompt-file --wait-seconds ${QUEUE_WORKER_POLL_SECONDS} --state-dir ${sd}`,
4005
4023
  ` It prints one line of JSON once it returns. If it prints "{}" (empty), no ` +
4006
4024
  `job showed up during the whole poll window — report "no jobs" in one line ` +
4007
- `and STOP. You are done.`,
4025
+ `and go to step 5.`,
4008
4026
  `2. Otherwise it prints {"job_id":"...","prompt_file":"...","schema_file":...}. ` +
4009
4027
  `Use the Read tool to read prompt_file; it is the complete, self-contained ` +
4010
4028
  `instruction the pipeline wrote for you. If the Read result says it is partial ` +
@@ -4014,20 +4032,28 @@ function queueWorkerBody(spec) {
4014
4032
  `ONLY that JSON object — no prose, no markdown, no code fences.`,
4015
4033
  `3. Submit it. Write your JSON object to ${outDir}/out-<job_id>.json using the ` +
4016
4034
  `Write tool (substitute the real job_id), then run this EXACT Bash command:`,
4017
- ` ${py} ${job} result --job <job_id> --result-file ${outDir}/out-<job_id>.json --state-dir ${sd}`,
4035
+ ` S4L_WORKER_SELF_REAP=0 ${py} ${job} result --job <job_id> --result-file ${outDir}/out-<job_id>.json --state-dir ${sd}`,
4018
4036
  ` If it reports the result was rejected (bad JSON / missing keys), fix your JSON ` +
4019
4037
  `and submit again — at most twice. If it still fails, run ` +
4020
- `\`${py} ${job} result --job <job_id> --error --state-dir ${sd}\` (type a one-line ` +
4021
- `reason, then Ctrl-D) and STOP.`,
4022
- `4. Report in ONE short line what you did, then STOP. Do NOT claim another job, ` +
4023
- `do NOT loop, do NOT read other files, do NOT call any other tool.`,
4038
+ `\`S4L_WORKER_SELF_REAP=0 ${py} ${job} result --job <job_id> --error --state-dir ${sd}\` (type a one-line ` +
4039
+ `reason, then Ctrl-D) and go to step 5.`,
4040
+ `4. Report in ONE short line what you did. Do NOT claim another job, ` +
4041
+ `do NOT loop, do NOT read other files.`,
4042
+ `5. End this session yourself. Call ToolSearch with the query ` +
4043
+ `"select:mcp__ccd_session_mgmt__archive_session", then call ` +
4044
+ `mcp__ccd_session_mgmt__archive_session with session_id "self" and reason ` +
4045
+ `"s4l worker done". That archive call must be your very last tool call; it ` +
4046
+ `ends the session cleanly (no SIGTERM, no idle wait). If the tool is not ` +
4047
+ `available, just STOP.`,
4024
4048
  ``,
4025
4049
  `HARD RULES: use ONLY the Bash tool (to run claude_job.py AND any persist ` +
4026
4050
  `commands the job's prompt explicitly gives you), the Read tool (the ` +
4027
4051
  `prompt/schema sidecar + the SKILL/config files the prompt names), and the ` +
4028
- `Write tool (the result file). NEVER post, reply, open a browser, or run any ` +
4029
- `command the prompt does not explicitly give you. An empty queue is the ` +
4030
- `NORMAL, expected case most minutes — it is success, not a problem to debug.`,
4052
+ `Write tool (the result file), plus TaskStop ONLY for a backgrounded poll, and ` +
4053
+ `ToolSearch and mcp__ccd_session_mgmt__archive_session ONLY as the final step 5. NEVER post, ` +
4054
+ `reply, open a browser, or run any command the prompt does not explicitly ` +
4055
+ `give you. An empty queue is the NORMAL, expected case most minutes — it is ` +
4056
+ `success, not a problem to debug.`,
4031
4057
  ].join("\n");
4032
4058
  }
4033
4059
  // Full canonical SKILL.md (frontmatter + body + version marker) the MCP writes
@@ -4831,6 +4857,10 @@ const PAUSE_TARGETS = [
4831
4857
  { tag: "claude-reaper", label: REAPER_LABEL, plist: REAPER_PLIST, ensure: ensureClaudeReaperInstalled },
4832
4858
  { tag: "stall-watch", label: STALL_WATCH_LABEL, plist: STALL_WATCH_PLIST, ensure: ensureStallWatchInstalled },
4833
4859
  { tag: "memory-snapshot", label: MEMORY_SNAPSHOT_LABEL, plist: MEMORY_SNAPSHOT_PLIST, ensure: ensureMemorySnapshotInstalled },
4860
+ // The harness overlay watcher attaches to the harness Chrome over CDP; with the
4861
+ // kickers unloaded it has nothing to show, and reinstalling it at every boot
4862
+ // while paused re-attached to a browser the user had deliberately stopped.
4863
+ { tag: "overlay-watch", label: OVERLAY_WATCH_LABEL, plist: OVERLAY_WATCH_PLIST, ensure: ensureOverlayWatchInstalled },
4834
4864
  ];
4835
4865
  // Mirror the pausable label set into the state dir for the menubar's Python
4836
4866
  // pause/resume (which can't import this module). Written at boot and on every
@@ -4844,39 +4874,80 @@ function writePauseTargetsManifest() {
4844
4874
  /* best-effort */
4845
4875
  }
4846
4876
  }
4847
- async function pauseS4L() {
4848
- if (isPaused())
4849
- return { ok: true, detail: "already paused" };
4850
- writePauseTargetsManifest();
4877
+ // THE one stop switch is menubar/s4l_state.py pause_s4l()/resume_s4l(): the
4878
+ // tray and dashboard_server.py need it with Claude Desktop closed, so the
4879
+ // mechanics (flag, dynamic sweep of every S4L LaunchAgent, harness browsers)
4880
+ // live there once and this is a thin shell-out. PAUSE_TARGETS above is still
4881
+ // the registry it reads (via pause-targets.json) and the set Resume re-ensures
4882
+ // so each daemon's install gates re-apply.
4883
+ function runPauseSwitch(action) {
4884
+ const dir = menubarSourceDir();
4885
+ if (!dir)
4886
+ return { ok: false, detail: "menubar/s4l_state.py not found" };
4851
4887
  try {
4852
- fs.mkdirSync(path.dirname(pauseFlagPath()), { recursive: true });
4853
- fs.writeFileSync(pauseFlagPath(), `paused at ${new Date().toISOString()}\n`, "utf-8");
4888
+ const out = execFileSync(resolvePython(), [path.join(dir, "s4l_state.py"), action], {
4889
+ encoding: "utf-8",
4890
+ timeout: 120_000,
4891
+ env: { ...process.env, S4L_STATE_DIR: s4lStateDir() },
4892
+ });
4893
+ const res = JSON.parse(out.trim().split("\n").pop() || "{}");
4894
+ return { ok: !!res.ok, detail: String(res.detail || "") };
4854
4895
  }
4855
4896
  catch (e) {
4856
- return { ok: false, detail: `could not write pause flag: ${e?.message || e}` };
4897
+ return { ok: false, detail: `s4l_state.py ${action}: ${e?.message || e}` };
4857
4898
  }
4858
- const uid = process.getuid ? process.getuid() : 0;
4859
- const results = [];
4860
- for (const { label, plist } of PAUSE_TARGETS) {
4861
- try {
4862
- const res = await unloadPlist(label, plist, uid);
4863
- results.push(`${label}: unloaded (rc=${res.code})`);
4864
- }
4865
- catch (e) {
4866
- results.push(`${label}: ${e?.message || e}`);
4867
- }
4868
- }
4869
- return { ok: true, detail: results.join("; ") };
4870
4899
  }
4871
- async function resumeS4L() {
4900
+ async function pauseS4L() {
4901
+ if (isPaused())
4902
+ return { ok: true, detail: "already paused" };
4903
+ writePauseTargetsManifest();
4904
+ return runPauseSwitch("pause");
4905
+ }
4906
+ // Resume only reloads launchd. Drafting ALSO needs the host's s4l-worker
4907
+ // scheduled task, which Resume cannot touch (only the host's scheduled-task
4908
+ // tools can). The task keeps firing through a pause, so a schedule that is not
4909
+ // 'ok' right after Resume is a real fault, never pause residue: without this
4910
+ // check Resume reported ok while cycles scanned, enqueued, and nothing drafted
4911
+ // (operator Mac, 2026-11-16: worker task disabled, read as 'stalled').
4912
+ async function draftScheduleAfterResume() {
4913
+ let state = "missing";
4914
+ let disabled = [];
4872
4915
  try {
4873
- fs.rmSync(pauseFlagPath(), { force: true });
4916
+ const res = await runPython("scripts/schedule_state.py", [], { timeoutMs: 15_000 });
4917
+ const parsed = JSON.parse(res.stdout.trim());
4918
+ if (["ok", "disabled", "stalled", "missing"].includes(parsed.state))
4919
+ state = parsed.state;
4920
+ disabled = (parsed.detail?.registries || [])
4921
+ .filter((r) => r.has_workers && r.enabled === false)
4922
+ .map((r) => String(r.path));
4874
4923
  }
4875
4924
  catch {
4876
- /* best-effort */
4877
- }
4925
+ /* unreadable -> treated as missing, same as scheduleState() */
4926
+ }
4927
+ if (state === "ok")
4928
+ return { schedule_state: state };
4929
+ const why = disabled.length
4930
+ ? `the s4l-worker scheduled task is DISABLED in ${disabled.join(", ")}`
4931
+ : state === "missing"
4932
+ ? "no s4l-worker scheduled task is registered for the active Claude account"
4933
+ : state === "disabled"
4934
+ ? "the s4l-worker scheduled task is disabled"
4935
+ : "the s4l-worker scheduled task is enabled but has not fired recently";
4936
+ return {
4937
+ schedule_state: state,
4938
+ warning: `Launchd lanes are resumed, but drafting is NOT: ${why}. Cycles will scan and enqueue ` +
4939
+ "jobs that nothing drafts until this is fixed.",
4940
+ next_step: state === "missing"
4941
+ ? "Call queue_setup and create the returned task with create_scheduled_task."
4942
+ : "Call the host tool list_scheduled_tasks; if s4l-worker shows enabled:false, call " +
4943
+ "update_scheduled_task {taskId:'s4l-worker', enabled:true, notifyOnCompletion:false}. If it " +
4944
+ "is already enabled, the host scheduler is wedged: fully quit and reopen Claude Desktop. " +
4945
+ "Then call dashboard and confirm schedule_state 'ok'.",
4946
+ };
4947
+ }
4948
+ async function resumeS4L() {
4878
4949
  writePauseTargetsManifest();
4879
- const results = [];
4950
+ const results = [runPauseSwitch("resume").detail];
4880
4951
  for (const t of PAUSE_TARGETS) {
4881
4952
  try {
4882
4953
  const r = await t.ensure();
@@ -4886,7 +4957,8 @@ async function resumeS4L() {
4886
4957
  results.push(`${t.tag}: ${e?.message || e}`);
4887
4958
  }
4888
4959
  }
4889
- return { ok: true, detail: results.join("; ") };
4960
+ const sched = await draftScheduleAfterResume();
4961
+ return { ok: sched.schedule_state === "ok", detail: results.join("; "), ...sched };
4890
4962
  }
4891
4963
  // Install/refresh the on-screen overlay watcher launchd job. Promotes the
4892
4964
  // harness status overlay from a best-effort, fired-from-other-tools nicety to a
@@ -5271,6 +5343,43 @@ function readPanelEndpoint() {
5271
5343
  return null;
5272
5344
  }
5273
5345
  }
5346
+ // A live pid is not enough to trust panel-endpoint.json: the exit-hook unlink
5347
+ // never runs on SIGKILL, so the file can point at a dead pid that the OS later
5348
+ // RECYCLES for an unrelated process — kill(pid, 0) then reports "alive" and
5349
+ // every instance would cede forever (no panel owner, no heartbeat/relay owner)
5350
+ // until the squatter happens to exit. Accept the registration only when the
5351
+ // pid's command line actually looks like an S4L MCP server; on ps failure fall
5352
+ // back to liveness alone rather than stealing a possibly-valid slot.
5353
+ function isS4lServerPid(pid) {
5354
+ if (!isPidAlive(pid))
5355
+ return false;
5356
+ try {
5357
+ const cmd = execFileSync("ps", ["-o", "command=", "-p", String(pid)], {
5358
+ encoding: "utf-8",
5359
+ timeout: 4000,
5360
+ });
5361
+ return cmd.includes("dist/index.js") || cmd.includes("@m13v/s4l-mcp");
5362
+ }
5363
+ catch {
5364
+ return true;
5365
+ }
5366
+ }
5367
+ // True when this process should run per-INSTALL periodic work (heartbeat,
5368
+ // transcript/provider relays, state snapshots). Several server instances are
5369
+ // routinely alive at once (Desktop, Code side-panel, per-minute queue workers —
5370
+ // each boots its own copy via the ~/.claude.json registration), and before this
5371
+ // gate every one of them ran every timer: 16 concurrent instances meant 48
5372
+ // heartbeat python spawns per 15 min and a measured ~11k fs-events/sec from
5373
+ // duplicate relay scans. Reuse the panel-endpoint election writePanelUrl already
5374
+ // maintains: the registered live S4L-server pid is the designated worker; when
5375
+ // the file is absent, stale, or squatted, anyone may run the work (the 120s
5376
+ // reclaim tick will elect a new owner shortly).
5377
+ function isInstallTickOwner() {
5378
+ const existing = readPanelEndpoint();
5379
+ if (!existing?.pid || existing.pid === process.pid)
5380
+ return true;
5381
+ return !isS4lServerPid(existing.pid);
5382
+ }
5274
5383
  // Publish the loopback URL to stable files so out-of-process readers can find
5275
5384
  // the ephemeral port without scraping `lsof`:
5276
5385
  // - panel-url plain text, for the Claude Code side-panel reverse proxy.
@@ -5295,7 +5404,7 @@ function writePanelUrl(url) {
5295
5404
  fs.mkdirSync(dir, { recursive: true });
5296
5405
  fs.writeFileSync(path.join(dir, "panel-url"), url, "utf-8");
5297
5406
  const existing = readPanelEndpoint();
5298
- if (existing?.pid && existing.pid !== process.pid && isPidAlive(existing.pid)) {
5407
+ if (existing?.pid && existing.pid !== process.pid && isS4lServerPid(existing.pid)) {
5299
5408
  // Someone else already holds a live registration (most likely a longer-
5300
5409
  // lived session than us) — don't clobber it. Our own panel is still up
5301
5410
  // and fully usable via `url` for anything that already has it (e.g. this
@@ -6177,14 +6286,8 @@ async function main() {
6177
6286
  void ensureFeedbackDigestInstalled()
6178
6287
  .then((r) => console.error(`[feedback-digest] launchd digest: ${r.ok ? "ok" : "skip"} (${r.detail})`))
6179
6288
  .catch((e) => console.error("[feedback-digest] digest install failed:", e?.message || e));
6180
- // On-screen overlay watcher supervisor. The harness status overlay only renders
6181
- // while the watcher process is alive, and that watcher had no supervisor — when
6182
- // it died nothing respawned it and the overlay silently vanished. Install it as
6183
- // a first-class self-healing launchd job (RunAtLoad + 60s idempotent re-invoke).
6184
- // Best-effort; the overlay is a nicety and must never block boot.
6185
- void ensureOverlayWatchInstalled()
6186
- .then((r) => console.error(`[overlay-watch] launchd supervisor: ${r.ok ? "ok" : "skip"} (${r.detail})`))
6187
- .catch((e) => console.error("[overlay-watch] supervisor install failed:", e?.message || e));
6289
+ // The on-screen overlay watcher supervisor (KeepAlive launchd job) is installed
6290
+ // through PAUSE_TARGETS above, so a Pause unloads it and a paused boot skips it.
6188
6291
  // Silent daily self-updates are banned (user decision 2026-07-31): the job
6189
6292
  // restarted Claude Desktop unattended. Clean it off every box that got it
6190
6293
  // from v1.7.1..v1.7.7-rc.4. Best-effort; never blocks boot.
@@ -6212,6 +6315,67 @@ async function main() {
6212
6315
  const transport = new StdioServerTransport();
6213
6316
  await server.connect(transport);
6214
6317
  console.error(`[social-autoposter-mcp] connected. v=${VERSION} repo=${repoDir()}`);
6318
+ // Exit when the client goes away. The SDK's StdioServerTransport listens only
6319
+ // for stdin 'data'/'error' — never 'end'/'close' — so client death is invisible
6320
+ // to it, and the eagerly-started panel HTTP listener below holds the event loop
6321
+ // open forever. That combination orphaned 16 servers (33 GB RSS, duplicate
6322
+ // autopilot timers) on 2026-09-18: every client exit (clean close OR SIGKILL,
6323
+ // which just closes our stdin pipe) left a full server behind, reparented to
6324
+ // launchd. Handle EOF ourselves, plus signals, plus a ppid backstop for the
6325
+ // rare case where an inherited fd keeps the stdin pipe open past client death.
6326
+ let shutdownStarted = false;
6327
+ const exitNow = (reason) => {
6328
+ console.error(`[social-autoposter-mcp] client gone (${reason}); exiting`);
6329
+ try {
6330
+ localPanel?.server.close();
6331
+ }
6332
+ catch {
6333
+ /* best-effort */
6334
+ }
6335
+ process.exit(0);
6336
+ };
6337
+ const shutdown = (reason, force = false) => {
6338
+ if (shutdownStarted) {
6339
+ // A second signal while we wait out a drain means "stop now".
6340
+ if (force)
6341
+ exitNow(`${reason}, forced`);
6342
+ return;
6343
+ }
6344
+ shutdownStarted = true;
6345
+ if (!postingActive) {
6346
+ exitNow(reason);
6347
+ return;
6348
+ }
6349
+ // A posting drain is in flight: this process holds the shared
6350
+ // twitter-browser shell lock under its OWN pid while a python poster child
6351
+ // drives Chrome. Exiting now (a) lets the next per-minute cycle
6352
+ // stale-reclaim the lock mid-post and (b) crashes the poster on EPIPE
6353
+ // between a landed reply and its bookkeeping — the idempotent redrain then
6354
+ // double-posts. Wait for the drain to finish (the interval is deliberately
6355
+ // ref'd so it keeps the process alive), capped at the approve_drafts
6356
+ // worst-case timeout.
6357
+ console.error(`[social-autoposter-mcp] client gone (${reason}); waiting for in-flight posting drain before exit`);
6358
+ const started = Date.now();
6359
+ const wait = setInterval(() => {
6360
+ if (!postingActive || Date.now() - started > 2 * 3600_000) {
6361
+ clearInterval(wait);
6362
+ exitNow(`${reason}, drain done`);
6363
+ }
6364
+ }, 5_000);
6365
+ };
6366
+ process.stdin.on("end", () => shutdown("stdin end"));
6367
+ process.stdin.on("close", () => shutdown("stdin close"));
6368
+ process.on("SIGTERM", () => shutdown("SIGTERM", true));
6369
+ process.on("SIGINT", () => shutdown("SIGINT", true));
6370
+ // Skip the backstop when we were BORN with ppid 1 (a launchd-managed server is
6371
+ // legitimately parented to launchd; only a reparent-after-birth means orphaned).
6372
+ if (process.ppid !== 1) {
6373
+ const ppidWatch = setInterval(() => {
6374
+ if (process.ppid === 1)
6375
+ shutdown("orphaned (ppid=1)");
6376
+ }, 30_000);
6377
+ ppidWatch.unref();
6378
+ }
6215
6379
  // Eagerly start the loopback panel server so the Claude Code side panel (and any
6216
6380
  // reverse proxy in front of it) always has a backend to hit, without waiting for
6217
6381
  // a first `dashboard` call. Best-effort: a bind failure must never block boot.
@@ -6245,8 +6409,16 @@ async function main() {
6245
6409
  // (parity with the npx launchd heartbeat). Once on startup, then every 15m
6246
6410
  // while the desktop app keeps the server alive. unref() so it never holds the
6247
6411
  // process open past a normal exit.
6412
+ // Heartbeat + the relays + snapshots below are per-INSTALL work: gate every
6413
+ // tick on the panel-endpoint election (isInstallTickOwner) so N concurrent
6414
+ // instances produce 1x the spawns, not Nx. The startup heartbeat stays
6415
+ // unconditional — a fresh install must phone home before it ever wins an
6416
+ // election.
6248
6417
  void sendHeartbeat("startup");
6249
- const hb = setInterval(() => void sendHeartbeat("interval"), 15 * 60_000);
6418
+ const hb = setInterval(() => {
6419
+ if (isInstallTickOwner())
6420
+ void sendHeartbeat("interval");
6421
+ }, 15 * 60_000);
6250
6422
  hb.unref();
6251
6423
  // Ship Claude session transcripts (scheduled queue-worker runs + s4l repo
6252
6424
  // sessions) to the Cloud Logging relay so a user's session can be
@@ -6257,7 +6429,7 @@ async function main() {
6257
6429
  if ((process.env.S4L_TRANSCRIPT_RELAY ?? "1") !== "0") {
6258
6430
  let transcriptRelayRunning = false;
6259
6431
  const relayTranscripts = () => {
6260
- if (transcriptRelayRunning)
6432
+ if (transcriptRelayRunning || !isInstallTickOwner())
6261
6433
  return;
6262
6434
  transcriptRelayRunning = true;
6263
6435
  runPython("scripts/relay_session_transcripts.py", ["--max-lines", "600"], {
@@ -6283,7 +6455,7 @@ async function main() {
6283
6455
  if ((process.env.S4L_PROVIDER_LOG_RELAY ?? "1") !== "0") {
6284
6456
  let providerRelayRunning = false;
6285
6457
  const relayProviderLog = () => {
6286
- if (providerRelayRunning)
6458
+ if (providerRelayRunning || !isInstallTickOwner())
6287
6459
  return;
6288
6460
  providerRelayRunning = true;
6289
6461
  runPython("scripts/relay_provider_log.py", ["--max-lines", "500"], {
@@ -6306,7 +6478,10 @@ async function main() {
6306
6478
  // the recurring tick only POSTs when something actually changed; setup.ts
6307
6479
  // additionally fires it right after every config write.
6308
6480
  void sendStateSnapshot("startup");
6309
- const ss = setInterval(() => void sendStateSnapshot("interval"), 15 * 60_000);
6481
+ const ss = setInterval(() => {
6482
+ if (isInstallTickOwner())
6483
+ void sendStateSnapshot("interval");
6484
+ }, 15 * 60_000);
6310
6485
  ss.unref();
6311
6486
  // Voice-exemplar catch-up + periodic refresh, checked on every boot
6312
6487
  // (2026-07-16, extended from the original one-shot-for-legacy-installs
package/mcp/dist/repo.js CHANGED
@@ -85,6 +85,21 @@ export function run(cmd, args, opts = {}) {
85
85
  }
86
86
  let stdout = "";
87
87
  let stderr = "";
88
+ // Cap captured output to a tail. run() used to accumulate a child's full
89
+ // stdout+stderr unbounded for the child's lifetime; long-lived spawns (the
90
+ // 13h voice backfill) and stuck children pinned those strings and were the
91
+ // main driver of multi-GB server heaps. Callers that parse output read
92
+ // either whole small payloads or the LAST line, so keeping the tail
93
+ // preserves semantics. 8 MB per stream is far above any legitimate payload.
94
+ const MAX_CAPTURE_BYTES = 8 * 1024 * 1024;
95
+ const capTail = (s) => s.length > MAX_CAPTURE_BYTES ? s.slice(s.length - (MAX_CAPTURE_BYTES >> 1)) : s;
96
+ // The line-splitter buffers below only shed at '\n', so a child emitting
97
+ // long newline-free output (carriage-return progress bars, one huge line)
98
+ // would grow them unbounded for its lifetime — the same heap pathology the
99
+ // capture cap exists for. Keep only a tail of an oversized partial line
100
+ // (telemetry truncates lines to 8KB anyway).
101
+ const MAX_LINEBUF_BYTES = 1024 * 1024;
102
+ const capLineBuf = (buf) => buf.length > MAX_LINEBUF_BYTES ? buf.slice(-8192) : buf;
88
103
  // Per-stream partial-line buffers so onLine fires on whole lines only,
89
104
  // regardless of how the OS chunks the pipe reads.
90
105
  let outBuf = "";
@@ -104,7 +119,7 @@ export function run(cmd, args, opts = {}) {
104
119
  /* a progress sink must never break the wrapped command */
105
120
  }
106
121
  }
107
- return buf;
122
+ return capLineBuf(buf);
108
123
  };
109
124
  // Parallel whole-line splitter that tees to the telemetry sink (if any),
110
125
  // kept separate from the onLine pump so neither path can affect the other.
@@ -127,29 +142,56 @@ export function run(cmd, args, opts = {}) {
127
142
  /* the telemetry sink must never break the wrapped command */
128
143
  }
129
144
  }
130
- return buf;
145
+ return capLineBuf(buf);
131
146
  };
147
+ let settled = false;
132
148
  let timer;
149
+ let killTimer;
133
150
  if (opts.timeoutMs) {
134
151
  timer = setTimeout(() => {
135
152
  child.kill("SIGTERM");
153
+ // A child that ignores SIGTERM used to live (and hold its pipes and our
154
+ // buffers) forever. Escalate — but GENEROUSLY: children trap SIGTERM on
155
+ // purpose to finish critical bookkeeping (twitter_post_plan.py finishes
156
+ // the current candidate's post + recording, which can take minutes, so a
157
+ // fast SIGKILL would reopen the posted-but-unrecorded double-post
158
+ // window). 15 min covers every graceful path; only a truly wedged child
159
+ // gets hard-killed.
160
+ killTimer = setTimeout(() => {
161
+ try {
162
+ child.kill("SIGKILL");
163
+ }
164
+ catch {
165
+ /* already gone */
166
+ }
167
+ }, 15 * 60_000);
168
+ killTimer.unref();
136
169
  }, opts.timeoutMs);
137
170
  }
138
171
  child.stdout.on("data", (d) => {
172
+ if (settled)
173
+ return;
139
174
  const s = d.toString();
140
- stdout += s;
175
+ stdout = capTail(stdout + s);
141
176
  outBuf = pump(s, "stdout", outBuf);
142
177
  sinkOutBuf = sinkPump(s, "stdout", sinkOutBuf);
143
178
  });
144
179
  child.stderr.on("data", (d) => {
180
+ if (settled)
181
+ return;
145
182
  const s = d.toString();
146
- stderr += s;
183
+ stderr = capTail(stderr + s);
147
184
  errBuf = pump(s, "stderr", errBuf);
148
185
  sinkErrBuf = sinkPump(s, "stderr", sinkErrBuf);
149
186
  });
150
- child.on("close", (code) => {
187
+ const finish = (code) => {
188
+ if (settled)
189
+ return;
190
+ settled = true;
151
191
  if (timer)
152
192
  clearTimeout(timer);
193
+ if (killTimer)
194
+ clearTimeout(killTimer);
153
195
  // Flush any trailing partial line (output with no terminating newline).
154
196
  if (opts.onLine) {
155
197
  if (outBuf)
@@ -185,10 +227,28 @@ export function run(cmd, args, opts = {}) {
185
227
  }
186
228
  }
187
229
  resolve({ code: code ?? -1, stdout, stderr });
230
+ };
231
+ child.on("close", (code) => finish(code));
232
+ child.on("exit", (code) => {
233
+ // 'close' waits for the stdio pipes to drain, which never happens when a
234
+ // grandchild inherited them and outlives the child — the promise (and the
235
+ // captured output) then leaked for the grandchild's lifetime. After the
236
+ // child itself exits, give the pipes a grace to flush, then settle. The
237
+ // setImmediate hop matters: if the event loop was stalled past the grace
238
+ // by sync work, timers fire BEFORE the poll phase reads the data already
239
+ // sitting in the kernel buffer — hopping to the check phase lets those
240
+ // reads land first instead of truncating a successful child's output.
241
+ const drain = setTimeout(() => setImmediate(() => finish(code)), 10_000);
242
+ drain.unref();
188
243
  });
189
244
  child.on("error", (err) => {
245
+ if (settled)
246
+ return;
247
+ settled = true;
190
248
  if (timer)
191
249
  clearTimeout(timer);
250
+ if (killTimer)
251
+ clearTimeout(killTimer);
192
252
  resolve({ code: -1, stdout, stderr: stderr + String(err) });
193
253
  });
194
254
  });
@@ -1226,7 +1226,7 @@ async function provision(progress) {
1226
1226
  // The bundled menu bar source: <ext>/menubar in a packed .mcpb (dist/runtime.js
1227
1227
  // -> ../menubar), the same path for a tsc dev build (mcp/dist -> mcp/menubar),
1228
1228
  // and the repo clone for an npm install.
1229
- function menubarSourceDir() {
1229
+ export function menubarSourceDir() {
1230
1230
  const candidates = [
1231
1231
  path.join(__dirname, "..", "menubar"),
1232
1232
  path.join(resolveRepoDir(), "mcp", "menubar"),