@m13v/s4l 1.7.5-rc.48 → 1.7.5-rc.6

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 (61) hide show
  1. package/mcp/dist/index.js +103 -576
  2. package/mcp/dist/panel.html +3 -2
  3. package/mcp/dist/runtime.js +12 -116
  4. package/mcp/dist/setup.js +5 -142
  5. package/mcp/dist/telemetry.js +3 -13
  6. package/mcp/dist/version.js +1 -7
  7. package/mcp/dist/version.json +2 -2
  8. package/mcp/manifest.json +2 -2
  9. package/mcp/menubar/s4l_card.py +77 -431
  10. package/mcp/menubar/s4l_menubar.py +185 -459
  11. package/mcp/menubar/s4l_state.py +190 -138
  12. package/mcp/package.json +1 -1
  13. package/mcp/shared/onboarding-ledger.cjs +4 -63
  14. package/package.json +1 -2
  15. package/scripts/active_experiments.py +7 -24
  16. package/scripts/claude_job.py +1 -4
  17. package/scripts/config.py +2 -20
  18. package/scripts/counterparty_history.py +6 -44
  19. package/scripts/engagement_styles.py +47 -32
  20. package/scripts/feedback_digest.py +27 -85
  21. package/scripts/learned_preferences.py +14 -37
  22. package/scripts/merge_review_queue.py +1 -34
  23. package/scripts/post_reddit.py +37 -168
  24. package/scripts/reddit_browser.py +63 -62
  25. package/scripts/reddit_browser_fetch.py +64 -151
  26. package/scripts/release-mcpb.sh +2 -83
  27. package/scripts/reset-test-machine.sh +7 -13
  28. package/scripts/scan_twitter_thread_followups.py +1 -7
  29. package/scripts/scan_x_profile.py +8 -33
  30. package/scripts/score_twitter_candidates.py +5 -19
  31. package/scripts/setup_twitter_auth.py +3 -27
  32. package/scripts/snapshot.py +5 -103
  33. package/scripts/stats.py +13 -37
  34. package/scripts/twitter_browser.py +352 -49
  35. package/scripts/twitter_post_plan.py +2 -29
  36. package/scripts/twitter_scan.py +10 -75
  37. package/scripts/voice_exemplars.py +15 -51
  38. package/skill/audit-reddit-resurrect.sh +2 -5
  39. package/skill/dm-outreach-reddit.sh +2 -5
  40. package/skill/engage-dm-replies.sh +2 -10
  41. package/skill/engage-reddit.sh +2 -5
  42. package/skill/lib/browser-launch.sh +1 -6
  43. package/skill/lib/harness-common.sh +2 -118
  44. package/skill/lib/linkedin-backend.sh +0 -18
  45. package/skill/lib/reddit-backend.sh +0 -21
  46. package/skill/link-edit-reddit.sh +2 -5
  47. package/skill/lock.sh +0 -57
  48. package/skill/run-reddit-search-launchd.sh +1 -4
  49. package/skill/run-reddit-search.sh +4 -31
  50. package/skill/run-reddit-threads.sh +2 -5
  51. package/skill/run-twitter-cycle.sh +137 -449
  52. package/mcp/dist/redditAuth.js +0 -115
  53. package/mcp/menubar/s4l_card_canvas.py +0 -712
  54. package/scripts/browser_mutex.py +0 -316
  55. package/scripts/engagement_signal_feedback.py +0 -256
  56. package/scripts/platform_strike_events.py +0 -232
  57. package/scripts/preview_expiry_card.py +0 -50
  58. package/scripts/setup_reddit_auth.py +0 -925
  59. package/scripts/test_no_silent_fallbacks.py +0 -281
  60. package/scripts/trigger_promo_lane_test.sh +0 -91
  61. package/scripts/twitter_prompt_sandbox.py +0 -163
package/mcp/dist/index.js CHANGED
@@ -20,9 +20,8 @@ import os from "node:os";
20
20
  import path from "node:path";
21
21
  import fs from "node:fs";
22
22
  import { repoDir, runPython, run, readPlan, writePlan, planPath, } from "./repo.js";
23
- import { applySetup, resolveProject, hasReadyProject, personaReady, listManagedProjectStatus, listProjectSettings, ensureShortLinksDefault, ensurePersonaProject, findPersonaProject, REQUIRED_FIELDS, RECOMMENDED_FIELDS, configPath, ensureConfigInStateDir, normalizeStringList, recordRedditAccount, } from "./setup.js";
23
+ import { applySetup, resolveProject, hasReadyProject, personaReady, listManagedProjectStatus, listProjectSettings, ensureShortLinksDefault, ensurePersonaProject, findPersonaProject, REQUIRED_FIELDS, RECOMMENDED_FIELDS, configPath, normalizeStringList, } from "./setup.js";
24
24
  import { xStatus, xConnect, xDetectSources, xScanProfile, summarizeXAuth } from "./twitterAuth.js";
25
- import { redditStatus, redditConnect, redditDetectSources, summarizeRedditAuth, } from "./redditAuth.js";
26
25
  import { startProvisioning, isProvisioning, readProgress, runtimeReady, readRuntime, resolvePython, resolveChrome, ensureMenubar, menubarRunning, clearMenubarStop, ensurePipelineCurrent, ensureRuntimeProvisioned, ensureHarnessPatched, retryProvisionIfStalled, } from "./runtime.js";
27
26
  import { blockOnboardingMilestone, completeOnboardingMilestone, ensureDoctorPhase, onboardingLedger, onboardingSnapshot, recordOnboardingAttempt, runDoctorPhase, } from "./onboarding.js";
28
27
  import { VERSION, versionStatus, latestPublishedVersion } from "./version.js";
@@ -69,17 +68,6 @@ const PHASE1_TASK_ID = "saps-phase1-query"; // legacy (was: "twitter-query" only
69
68
  const PHASE2B_TASK_ID = "saps-phase2b-draft"; // legacy (was: "twitter-prep" only)
70
69
  const TWITTER_AUTOPILOT_LABEL = "com.m13v.social-twitter-cycle";
71
70
  const TWITTER_AUTOPILOT_PLIST = path.join(os.homedir(), "Library", "LaunchAgents", `${TWITTER_AUTOPILOT_LABEL}.plist`);
72
- // Reddit discovery kicker (optional platform, 2026-07-15). Runs the SAME
73
- // launchd label the operator Mac has used by hand since May
74
- // (com.m13v.social-reddit-search) so there is one canonical name fleet-wide,
75
- // but ensureRedditKickerInstalled() refuses to touch a plist whose program
76
- // path points outside the managed package (the operator's hand-built plist
77
- // stays untouched). Installed only when reddit is connected AND a project is
78
- // configured; never part of onboarding completion.
79
- const REDDIT_SEARCH_LABEL = "com.m13v.social-reddit-search";
80
- const REDDIT_SEARCH_PLIST = path.join(os.homedir(), "Library", "LaunchAgents", `${REDDIT_SEARCH_LABEL}.plist`);
81
- const REDDIT_SEARCH_INTERVAL_SECS = 900;
82
- const REDDIT_CDP_URL_DEFAULT = "http://127.0.0.1:9557";
83
71
  // Self-healing reaper for leaked Claude agent-mode worker sessions. The queue
84
72
  // autopilot fires two scheduled tasks every ~1 min; each fire spawns a ~200 MB
85
73
  // `claude` agent-mode session that finishes its one queue turn but never exits
@@ -325,29 +313,23 @@ const server = new McpServer({
325
313
  "can run them hands-free on autopilot.\n\n" +
326
314
  "ONBOARDING IS A TERMINAL GOAL. When the user asks to set up, install, configure, or onboard " +
327
315
  "social-autoposter, keep taking the next safe action until the owned runtime is ready, a " +
328
- "project is fully configured with seeded search topics, AT LEAST ONE platform is connected " +
329
- "(ASK the user up front which platform(s) to connect — X, Reddit, or both — before connecting " +
330
- "anything; X is a reasonable default to SUGGEST, but do not connect it, or any platform, without " +
331
- "the user's answer. Connect exactly what they choose via project_config action:'connect_x' " +
332
- "and/or action:'connect_reddit'), AND " +
316
+ "project is fully configured with seeded search topics, X is connected with its real handle, AND " +
333
317
  "the two draft-autopilot scheduled tasks have been created via queue_setup and are firing " +
334
318
  "(see SCHEDULE THE AUTOPILOT below). The owned runtime (private Python + Chromium) provisions " +
335
319
  "ITSELF automatically on boot — you do NOT install it. Just poll runtime action:'status' until it " +
336
320
  "reports ready; only call runtime action:'install' or action:'doctor' to TROUBLESHOOT if status " +
337
321
  "shows the boot provision failed or stalled. Do not ask whether to inspect " +
338
- "status, repair a failed runtime, choose an auto-detected browser profile, scan the profile, " +
339
- "research the product website, save conservative inferred fields, or seed " +
322
+ "status, repair a failed runtime, choose an auto-detected browser profile, connect " +
323
+ "X, scan the profile, research the product website, save conservative inferred fields, or seed " +
340
324
  "topics. Do those things. The " +
341
325
  "explicit setup request authorizes runtime repair and importing ONLY x.com/" +
342
326
  "twitter.com session cookies into the managed browser: warn that macOS keychain prompts may " +
343
- "appear, then proceed without a separate yes/no turn. Besides the platform-choice question " +
344
- "above, ask at most one MORE bundled question, only " +
327
+ "appear, then proceed without a separate yes/no turn. Ask at most one bundled question, only " +
345
328
  "when no product can be identified from config, context, the X profile, or public research, " +
346
329
  "or pause for an unavoidable interactive login or OS prompt. Never auto-POST during setup. " +
347
330
  "DO schedule the draft autopilot as the final step (once running it only queues drafts for " +
348
331
  "approval, it never posts on its own). When setup reaches done (" +
349
- "runtime ready, a project configured with seeded topics, at least one platform connected, and the " +
350
- "two scheduled tasks " +
332
+ "runtime ready, a project configured with seeded topics, X connected, and the two scheduled tasks " +
351
333
  "created and firing), call the `dashboard` tool so the user " +
352
334
  "sees the finished setup rendered, then give " +
353
335
  "the completion summary.\n\n" +
@@ -369,16 +351,6 @@ const server = new McpServer({
369
351
  "old 'social-autoposter-autopilot' task — it is deprecated. Do NOT ask the user to review drafts " +
370
352
  "or pause for input mid-onboarding; once the tasks are created and firing, setup is done. If the " +
371
353
  "host exposes no create_scheduled_task tool, tell the user the autopilot couldn't be scheduled here.\n\n" +
372
- "REDDIT IS AN EQUAL PLATFORM CHOICE, ASKED ALONGSIDE X. Setup is complete with AT LEAST ONE " +
373
- "platform connected: X-only, Reddit-only, or both — whichever the user picked when you asked " +
374
- "up front. If they chose both, connect them one at a time (either order) in the same setup " +
375
- "flow. `project_config` action:'connect_reddit' imports the user's reddit.com session into the " +
376
- "autoposter's managed reddit browser, same confirm-first flow and keychain heads-up as " +
377
- "connect_x. Once connected, reddit discovery and drafting run on the same draft-only queue and " +
378
- "review cards as X; nothing posts without approval. If the result carries a `warning` (fresh or " +
379
- "low-karma account), relay it so the user knows AutoMod may gate early replies. Never make " +
380
- "either platform a requirement, and never nag a user who deliberately chose only one about the " +
381
- "other.\n\n" +
382
354
  "BE PROACTIVE ABOUT MARKETING MOMENTS. Whenever the user ships, finishes, merges, or releases " +
383
355
  "something worth talking about in this session (a new feature, a launch, a long-awaited fix, a " +
384
356
  "milestone), don't wait to be asked: point it out to the user — the draft autopilot runs " +
@@ -389,8 +361,7 @@ const server = new McpServer({
389
361
  "release, call the `runtime` tool (action:'version'). If `update_available` is true, tell the " +
390
362
  "user and offer to run `runtime` with action:'update'. The `project_config` tool's status also " +
391
363
  "surfaces `update_available` and an `update_hint`.\n\n" +
392
- "TYPICAL FLOW: ASK which platform(s) to connect (X, Reddit, or both) -> `project_config` " +
393
- "(connect the chosen platform(s) + scan the profile) -> `engagement_mode` (after the " +
364
+ "TYPICAL FLOW: `project_config` (connect X + scan the profile) -> `engagement_mode` (after the " +
394
365
  "profile scan: personal-brand is ON by default, so ASK the user the ONE question — do they ALSO " +
395
366
  "want to promote a product? — and call action:'set' with personal_brand:true and " +
396
367
  "promotion:true|false; this provisions the persona) -> IF they wanted promotion, `project_config` " +
@@ -856,7 +827,7 @@ function readConfiguredTwitterHandle() {
856
827
  if (env)
857
828
  return env;
858
829
  try {
859
- const cfg = JSON.parse(fs.readFileSync(configPath(), "utf-8"));
830
+ const cfg = JSON.parse(fs.readFileSync(path.join(repoDir(), "config.json"), "utf-8"));
860
831
  const h = cfg?.accounts?.twitter?.handle;
861
832
  const s = (typeof h === "string" ? h : "").trim().replace(/^@/, "");
862
833
  return s || null;
@@ -1011,27 +982,6 @@ async function postApproved(batchId, plan) {
1011
982
  plan = fresh;
1012
983
  }
1013
984
  }
1014
- // Arm the cross-instance posting flag HERE, before the Reddit drain, not just
1015
- // before the Twitter phase below. Root cause (found 2026-07-16): this flag
1016
- // used to get set only right before ensureTwitterBrowserForPost(), AFTER the
1017
- // whole Reddit drain loop above (one runPython("post_reddit.py") call per
1018
- // approved Reddit card, each with real CDP/browser overhead — a batch of a
1019
- // handful of cards routinely runs minutes). For that entire window this
1020
- // instance's isPeerDrainActive() reported false, so a SECOND MCP instance's
1021
- // postApproved() (e.g. a fresh one-shot worker boot running its own startup
1022
- // backlog drain) could pass the SAME gate check above and start its own
1023
- // drain concurrently. Both eventually reached their own Twitter phase and
1024
- // both spawned scripts/twitter_post_plan.py with S4L_LOCK_ROLE=post — the
1025
- // ONLY code path that ever sets that role. Two live "post" role holders
1026
- // can't preempt each other (browser_mutex.py case 6: correct, preempting a
1027
- // peer mid-post risks a double-post), so one always waited 45s and gave up
1028
- // — the "Twitter browser locked by session python:<pid> ... waited 45s,
1029
- // giving up" failures that silently killed 11 real approved drafts over
1030
- // 2026-07-15/16. Arming the flag for the FULL function closes that window:
1031
- // a peer's gate check now blocks for the entire drain, Reddit included, so
1032
- // only one instance ever reaches the Twitter phase at a time.
1033
- postingActive = true;
1034
- startPostingFlagHeartbeat();
1035
985
  // Post every card the user APPROVED that hasn't already landed or been ruled out.
1036
986
  // `approved` is now a DURABLE decision (sticky, never cleared by a later call), so
1037
987
  // filtering out posted/terminal here makes this idempotent: re-running it only
@@ -1050,11 +1000,8 @@ async function postApproved(batchId, plan) {
1050
1000
  delete c.discard_reason;
1051
1001
  }
1052
1002
  }
1053
- if (approved.length === 0) {
1054
- postingActive = false;
1055
- stopPostingFlagHeartbeat();
1003
+ if (approved.length === 0)
1056
1004
  return { attempted: 0, exit_code: 0, summary: "nothing approved" };
1057
- }
1058
1005
  // ---- Reddit cards (2026-07-14): drain them FIRST, independently ----------
1059
1006
  // A reddit card carries the verbatim draft decision (reddit_decision) plus
1060
1007
  // plan metadata (reddit_plan_meta), so approval reconstructs a one-decision
@@ -1067,179 +1014,84 @@ async function postApproved(batchId, plan) {
1067
1014
  const approvedTwitter = approved.filter((c) => c.platform !== "reddit");
1068
1015
  let redditPosted = 0;
1069
1016
  let redditFailed = 0;
1070
- let redditSkippedPeerDrain = false;
1071
1017
  if (approvedReddit.length) {
1072
- // Cross-instance drain gate (2026-07-14 drain storm): every one-shot MCP
1073
- // boot (the queue worker fires ~every minute; each boot runs the startup
1074
- // backlog drain) drained the SAME sticky approvals concurrently — 26
1075
- // drain plans in ~30 minutes, all fighting over the one reddit tab and
1076
- // false-positiving each other's posts. reddit-posting-active.json is the
1077
- // arbiter: post_reddit.py heartbeats it per row, and we stamp it around
1078
- // the whole drain here. A fresh flag (<120s) means a peer is mid-drain:
1079
- // leave the cards for it — approvals are sticky, nothing is lost.
1080
- const redditFlagPath = path.join(s4lStateDir(), "reddit-posting-active.json");
1081
- let redditPeerFresh = false;
1082
- try {
1083
- redditPeerFresh = Date.now() - fs.statSync(redditFlagPath).mtimeMs < 120_000;
1084
- }
1085
- catch {
1086
- redditPeerFresh = false;
1087
- }
1088
- const stampRedditFlag = () => {
1089
- try {
1090
- fs.writeFileSync(redditFlagPath, JSON.stringify({ pid: process.pid, hb: Math.floor(Date.now() / 1000) }));
1091
- }
1092
- catch {
1093
- /* best effort */
1018
+ for (const c of approvedReddit) {
1019
+ const cc = c;
1020
+ const dec = cc.reddit_decision;
1021
+ const meta = (cc.reddit_plan_meta || {});
1022
+ if (!dec) {
1023
+ c.terminal = true;
1024
+ c.terminal_reason = "reddit_decision_missing";
1025
+ redditFailed++;
1026
+ continue;
1094
1027
  }
1095
- };
1096
- if (redditPeerFresh) {
1097
- redditSkippedPeerDrain = true;
1098
- logPostEvent(`postApproved_reddit_skip batch=${batchId} reason=peer_drain_active cards=${approvedReddit.length}`);
1099
- }
1100
- else {
1101
- stampRedditFlag();
1028
+ const miniPlan = {
1029
+ project_name: meta.project_name || cc.matched_project,
1030
+ batch_id: cc.reddit_batch_id || meta.batch_id || "reddit-mcp-approval",
1031
+ phase: "draft",
1032
+ decisions: [dec],
1033
+ style_assignment: meta.style_assignment || {},
1034
+ generation_trace_path: meta.generation_trace_path,
1035
+ session_id: meta.session_id || meta.draft_session_id,
1036
+ };
1037
+ const tmpPlan = path.join(process.env.S4L_TMP_DIR || "/tmp", `reddit_mcp_post_${Date.now()}_${Math.floor(Math.random() * 1e6)}.json`);
1038
+ let r;
1102
1039
  try {
1103
- for (const c of approvedReddit) {
1104
- stampRedditFlag();
1105
- const cc = c;
1106
- const dec = cc.reddit_decision;
1107
- const meta = (cc.reddit_plan_meta || {});
1108
- if (!dec) {
1109
- c.terminal = true;
1110
- c.terminal_reason = "reddit_decision_missing";
1111
- redditFailed++;
1112
- continue;
1113
- }
1114
- // The card's reply_text is the CANONICAL text (post_drafts edits write
1115
- // there); the embedded decision still carries the draft-time original.
1116
- // Posting dec.text verbatim would silently discard a human edit.
1117
- const decPost = {
1118
- ...dec,
1119
- text: (typeof cc.reply_text === "string" && cc.reply_text.trim())
1120
- ? cc.reply_text
1121
- : dec.text,
1122
- };
1123
- if (cc.engagement_style)
1124
- decPost.engagement_style = cc.engagement_style;
1125
- // Two-draft cards (2026-07-15): a human draft-switch (see the generic
1126
- // edit-handling above, `if (e.variant && Array.isArray(c.drafts))`)
1127
- // stamps the CHOSEN draft's assigned_style/assigned_mode onto the card
1128
- // (cc). Forward both into decPost so post_reddit.py's _post_iteration
1129
- // validates/logs against whichever draft is ACTUALLY posting, not
1130
- // whichever was recommended at plan-write time — mirrors
1131
- // twitter_post_plan.py's identical per-candidate override.
1132
- if (cc.assigned_style !== undefined)
1133
- decPost.assigned_style = cc.assigned_style;
1134
- if (cc.assigned_mode !== undefined)
1135
- decPost.assigned_mode = cc.assigned_mode;
1136
- const miniPlan = {
1137
- project_name: meta.project_name || cc.matched_project,
1138
- batch_id: cc.reddit_batch_id || meta.batch_id || "reddit-mcp-approval",
1139
- phase: "draft",
1140
- decisions: [decPost],
1141
- style_assignment: meta.style_assignment || {},
1142
- generation_trace_path: meta.generation_trace_path,
1143
- session_id: meta.session_id || meta.draft_session_id,
1144
- };
1145
- const tmpPlan = path.join(process.env.S4L_TMP_DIR || "/tmp", `reddit_mcp_post_${Date.now()}_${Math.floor(Math.random() * 1e6)}.json`);
1146
- let r;
1147
- try {
1148
- fs.writeFileSync(tmpPlan, JSON.stringify(miniPlan));
1149
- r = await runPython("scripts/post_reddit.py", ["--phase", "post", "--in", tmpPlan], {
1150
- timeoutMs: 900_000,
1151
- env: {
1152
- REDDIT_CDP_URL: process.env.REDDIT_CDP_URL || "http://127.0.0.1:9557",
1153
- // Reviewed posts never get the active-campaign suffix (same rule
1154
- // as the twitter manual-approval path below).
1155
- S4L_SKIP_CAMPAIGN_SUFFIX: "1",
1156
- },
1157
- onLine: (line) => {
1158
- const t = line.replace(/\s+$/, "");
1159
- if (t.trim())
1160
- console.error(`[post-reddit] ${t}`);
1161
- },
1162
- });
1163
- }
1164
- catch (err) {
1165
- r = { code: -1, stdout: "", stderr: String(err) };
1166
- }
1167
- finally {
1168
- try {
1169
- fs.unlinkSync(tmpPlan);
1170
- }
1171
- catch {
1172
- /* best effort */
1173
- }
1174
- }
1175
- // post_reddit.py's summary marker: `[post_reddit] phase=post ... posted=N failed=M`
1176
- const out = `${r.stdout}\n${r.stderr}`;
1177
- const postedN = Number((/posted=(\d+)/.exec(out) || [])[1] || 0);
1178
- if (r.code === 0 && postedN > 0) {
1179
- c.posted = true;
1180
- c.terminal = false;
1181
- const urlMatch = /(https:\/\/(?:old\.|www\.)?reddit\.com\/r\/\S+)/.exec((/\[post_reddit\][^\n]*posted[^\n]*/i.exec(out) || [""])[0]);
1182
- if (urlMatch)
1183
- c.our_url = urlMatch[1];
1184
- redditPosted++;
1185
- }
1186
- else {
1187
- // Leave the approval sticky (approved && !posted && !terminal) so the
1188
- // next post_drafts call retries, mirroring twitter's failed-drain
1189
- // semantics; only stamp terminal on a conclusive CDP refusal. This
1190
- // list MUST stay a superset of post_reddit.py's own
1191
- // _PERMANENT_CDP_ERRORS (account_blocked_in_sub, no_permalink) —
1192
- // otherwise post_reddit.py already gives up on the row (marks the DB
1193
- // candidate permanently failed, e.g. adds the sub to
1194
- // subreddit_bans.comment_blocked) while this card stays non-terminal
1195
- // and the drain retries the same doomed post forever (found
1196
- // 2026-07-16: an approved r/tifu card retried every cycle for over
1197
- // an hour after the sub was already in subreddit_bans.comment_blocked).
1198
- const cdpReason = (/\[post_reddit\] CDP FAILED: ([a-z_]+)/.exec(out) || [])[1];
1199
- if (cdpReason &&
1200
- [
1201
- "thread_locked",
1202
- "thread_archived",
1203
- "thread_not_found",
1204
- "blocked_by_author",
1205
- "account_blocked_in_sub",
1206
- "no_permalink",
1207
- ].includes(cdpReason)) {
1208
- c.terminal = true;
1209
- c.terminal_reason = `reddit_${cdpReason}`;
1210
- }
1211
- redditFailed++;
1212
- }
1213
- }
1040
+ fs.writeFileSync(tmpPlan, JSON.stringify(miniPlan));
1041
+ r = await runPython("scripts/post_reddit.py", ["--phase", "post", "--in", tmpPlan], {
1042
+ timeoutMs: 900_000,
1043
+ env: {
1044
+ REDDIT_CDP_URL: process.env.REDDIT_CDP_URL || "http://127.0.0.1:9557",
1045
+ // Reviewed posts never get the active-campaign suffix (same rule
1046
+ // as the twitter manual-approval path below).
1047
+ S4L_SKIP_CAMPAIGN_SUFFIX: "1",
1048
+ },
1049
+ onLine: (line) => {
1050
+ const t = line.replace(/\s+$/, "");
1051
+ if (t.trim())
1052
+ console.error(`[post-reddit] ${t}`);
1053
+ },
1054
+ });
1055
+ }
1056
+ catch (err) {
1057
+ r = { code: -1, stdout: "", stderr: String(err) };
1214
1058
  }
1215
1059
  finally {
1216
- // Clear only OUR stamp; a peer that took over mid-drain keeps its own.
1217
1060
  try {
1218
- const cur = JSON.parse(fs.readFileSync(redditFlagPath, "utf-8"));
1219
- if (cur && cur.pid === process.pid)
1220
- fs.unlinkSync(redditFlagPath);
1061
+ fs.unlinkSync(tmpPlan);
1221
1062
  }
1222
1063
  catch {
1223
1064
  /* best effort */
1224
1065
  }
1225
1066
  }
1226
- logPostEvent(`postApproved_reddit batch=${batchId} attempted=${approvedReddit.length} posted=${redditPosted} failed=${redditFailed}`);
1067
+ // post_reddit.py's summary marker: `[post_reddit] phase=post ... posted=N failed=M`
1068
+ const out = `${r.stdout}\n${r.stderr}`;
1069
+ const postedN = Number((/posted=(\d+)/.exec(out) || [])[1] || 0);
1070
+ if (r.code === 0 && postedN > 0) {
1071
+ c.posted = true;
1072
+ c.terminal = false;
1073
+ const urlMatch = /(https:\/\/(?:old\.|www\.)?reddit\.com\/r\/\S+)/.exec((/\[post_reddit\][^\n]*posted[^\n]*/i.exec(out) || [""])[0]);
1074
+ if (urlMatch)
1075
+ c.our_url = urlMatch[1];
1076
+ redditPosted++;
1077
+ }
1078
+ else {
1079
+ // Leave the approval sticky (approved && !posted && !terminal) so the
1080
+ // next post_drafts call retries, mirroring twitter's failed-drain
1081
+ // semantics; only stamp terminal on a conclusive CDP refusal.
1082
+ const cdpReason = (/\[post_reddit\] CDP FAILED: ([a-z_]+)/.exec(out) || [])[1];
1083
+ if (cdpReason && ["thread_locked", "thread_archived", "thread_not_found", "blocked_by_author"].includes(cdpReason)) {
1084
+ c.terminal = true;
1085
+ c.terminal_reason = `reddit_${cdpReason}`;
1086
+ }
1087
+ redditFailed++;
1088
+ }
1227
1089
  }
1090
+ logPostEvent(`postApproved_reddit batch=${batchId} attempted=${approvedReddit.length} posted=${redditPosted} failed=${redditFailed}`);
1228
1091
  }
1229
1092
  if (approvedTwitter.length === 0) {
1230
1093
  // All-reddit batch: persist the stamps and return without touching the
1231
- // twitter preflight/lock path. Must clear the flag armed above ourselves —
1232
- // this branch never reaches the Twitter phase's scheduleShellLockRelease().
1233
- postingActive = false;
1234
- stopPostingFlagHeartbeat();
1235
- if (redditSkippedPeerDrain) {
1236
- return {
1237
- attempted: 0,
1238
- posted: 0,
1239
- exit_code: 0,
1240
- summary: "reddit: skipped (peer drain active); cards stay approved for the next drain",
1241
- };
1242
- }
1094
+ // twitter preflight/lock path.
1243
1095
  if (approvedReddit.length)
1244
1096
  mergeApprovedStampsIntoStore(batchId, plan, approvedReddit);
1245
1097
  return {
@@ -1257,8 +1109,6 @@ async function postApproved(batchId, plan) {
1257
1109
  if (!readConfiguredTwitterHandle())
1258
1110
  await ensurePostingHandle();
1259
1111
  if (!readConfiguredTwitterHandle()) {
1260
- postingActive = false;
1261
- stopPostingFlagHeartbeat();
1262
1112
  return {
1263
1113
  attempted: 0,
1264
1114
  exit_code: 0,
@@ -1459,31 +1309,11 @@ async function postApproved(batchId, plan) {
1459
1309
  c.our_url = r.our_url;
1460
1310
  touchedPlan = true;
1461
1311
  }
1462
- else if (r.outcome === "skipped") {
1463
- // twitter_post_plan.py only returns "skipped" for reasons it has
1464
- // already decided are conclusive (reply_restricted, tweet_unavailable,
1465
- // blocked_by_author, tweet_not_found, rate_limited, reply_box_not_found
1466
- // — see its own PERMANENT/skip comment) or a captured-URL edge case
1467
- // it explicitly doesn't want re-attempted (duplicate risk). Terminal
1468
- // is correct here.
1312
+ else if (r.outcome === "skipped" || r.outcome === "failed") {
1469
1313
  c.terminal = true;
1470
1314
  c.terminal_reason = r.reason || r.outcome;
1471
1315
  touchedPlan = true;
1472
1316
  }
1473
- else if (r.outcome === "failed") {
1474
- // "failed" is twitter_post_plan.py's catch-all for everything it did
1475
- // NOT classify as conclusive — timeouts, parse errors, exceptions,
1476
- // and browser_mutex contention ("Twitter browser locked by session
1477
- // ... waited 45s, giving up."). None of those mean the draft is
1478
- // doomed, only that this attempt didn't get a turn with the shared
1479
- // browser. Leave the card sticky (approved && !posted && !terminal)
1480
- // so the next post_drafts call retries it, mirroring Reddit's
1481
- // _TRANSIENT_CDP_ERRORS handling. Unconditionally marking terminal
1482
- // here (found 2026-07-16) silently and permanently discarded 7 real
1483
- // approved drafts on nothing worse than lock contention — Reddit's
1484
- // equivalent transient failures self-healed on the very next drain.
1485
- touchedPlan = true;
1486
- }
1487
1317
  });
1488
1318
  }
1489
1319
  else if (realPosted > 0 || (res.code === 0 && !summObj)) {
@@ -2024,16 +1854,12 @@ tool("project_config", {
2024
1854
  "products (call once per product, identified by name); fill or edit a project's fields " +
2025
1855
  "INCREMENTALLY across several calls — pass whatever you have, it merges and tells you what's " +
2026
1856
  "still missing.\n" +
2027
- "2) Connect X/Twitter (action:'connect_x'), ONLY once the user has told you they want X connected " +
2028
- "(the top-level setup flow asks which platform(s) — X, Reddit, or both — before this tool is " +
2029
- "called for either): the autoposter posts through its OWN managed Chrome, " +
1857
+ "2) Connect X/Twitter (action:'connect_x'): the autoposter posts through its OWN managed Chrome, " +
2030
1858
  "which needs your logged-in x.com session. This imports x.com/twitter.com cookies from your " +
2031
1859
  "everyday browser (Chrome/Arc/Brave/Edge, auto-detected) into that browser — nothing else is " +
2032
- "touched. Once the user has said they want X, briefly warn that macOS Safe " +
2033
- "Storage prompts may appear, then call action:'connect_x', confirm:true immediately — no further " +
2034
- "round-trip needed for THIS decision, it was already made. Use " +
2035
- "action:'detect_x_sources' first and choose its recommendation instead of asking the user which " +
2036
- "browser profile to import from.\n" +
1860
+ "touched. An explicit setup/connect request is authorization: briefly warn that macOS Safe " +
1861
+ "Storage prompts may appear, then call action:'connect_x', confirm:true immediately. Use " +
1862
+ "action:'detect_x_sources' first and choose its recommendation instead of asking the user.\n" +
2037
1863
  "Call with status:true (or no name) to list every configured project, its remaining fields, AND " +
2038
1864
  "whether X is connected. Use config, conversation context, profile_scan, and website research " +
2039
1865
  "before asking for fields. Ask only if no product can be identified or an interactive login is " +
@@ -2042,14 +1868,7 @@ tool("project_config", {
2042
1868
  inputSchema: {
2043
1869
  status: z.boolean().optional(),
2044
1870
  action: z
2045
- .enum([
2046
- "get",
2047
- "connect_x",
2048
- "detect_x_sources",
2049
- "profile_scan",
2050
- "connect_reddit",
2051
- "detect_reddit_sources",
2052
- ])
1871
+ .enum(["get", "connect_x", "detect_x_sources", "profile_scan"])
2053
1872
  .optional()
2054
1873
  .describe("get = read the CURRENT SAVED VALUES of every project's editable fields (website, " +
2055
1874
  "description, icp, voice, differentiator, search_topics, get_started_link, " +
@@ -2067,14 +1886,7 @@ tool("project_config", {
2067
1886
  "replies to build a 'grounding truth' corpus. Use it to draft voice/icp/search_topics in " +
2068
1887
  "the USER'S OWN register (their phrases, vibe, profession), then save a conservative best " +
2069
1888
  "draft without requiring a confirmation round-trip. Returns {profile, posts, comments, " +
2070
- "grounding_instructions}. " +
2071
- "connect_reddit = call ONLY once the user has said they want Reddit connected (setup " +
2072
- "completes with X-only, Reddit-only, or both — whichever they picked when asked up front; " +
2073
- "if X connection fails after they chose it, offer Reddit as a fallback): import/validate " +
2074
- "the user's reddit.com session in the " +
2075
- "autoposter's managed reddit browser, same confirm-first shape as connect_x. " +
2076
- "detect_reddit_sources = list the browsers/profiles the Reddit session can be imported " +
2077
- "from (read-only, no keychain prompt)."),
1889
+ "grounding_instructions}."),
2078
1890
  confirm: z
2079
1891
  .boolean()
2080
1892
  .optional()
@@ -2091,17 +1903,6 @@ tool("project_config", {
2091
1903
  "X login window and waits for them to log in. By default (false), connect_x does NOT pop a " +
2092
1904
  "browser window on an auto-import miss; it returns needs_login and you offer manual login as " +
2093
1905
  "an opt-in. The login window still opens automatically if the user DENIED the keychain prompt."),
2094
- reddit_source: z
2095
- .string()
2096
- .optional()
2097
- .describe("Optional browser profile to import the Reddit session from, e.g. 'arc:Default', " +
2098
- "'chrome:Profile 1'. Default: auto-detect the browser that holds a reddit.com session."),
2099
- reddit_manual_login: z
2100
- .boolean()
2101
- .optional()
2102
- .describe("Set true ONLY when the user explicitly wants to sign into Reddit by hand. Opens a focused " +
2103
- "Reddit login window in the autoposter's reddit browser and waits. Same opt-in discipline " +
2104
- "as x_manual_login."),
2105
1906
  name: z
2106
1907
  .string()
2107
1908
  .optional()
@@ -2271,130 +2072,6 @@ tool("project_config", {
2271
2072
  : "X is not connected yet. " + summarizeXAuth(r),
2272
2073
  });
2273
2074
  }
2274
- // ---- List Reddit import sources (read-only, no keychain prompt) --------
2275
- if (args.action === "detect_reddit_sources") {
2276
- const r = await redditDetectSources();
2277
- return jsonContent({
2278
- action: "detect_reddit_sources",
2279
- ok: r.ok,
2280
- sources: r.sources,
2281
- recommended: r.recommended,
2282
- error: r.error,
2283
- });
2284
- }
2285
- // ---- Connect Reddit: OPTIONAL platform, mirrors connect_x --------------
2286
- // Preview-or-run, same confirm-first shape as connect_x. Reddit is never
2287
- // required for onboarding completion; offer it only after X setup is done
2288
- // and the user wants it.
2289
- if (args.action === "connect_reddit") {
2290
- if (args.confirm !== true) {
2291
- // Cheap probe so the explanation reflects current state (no Chrome launch).
2292
- const cur = await redditStatus();
2293
- if (cur.connected) {
2294
- return jsonContent({
2295
- action: "connect_reddit",
2296
- already_connected: true,
2297
- state: cur.state,
2298
- username: cur.username,
2299
- note: "Reddit is already connected in the autoposter's reddit browser. Nothing to import.",
2300
- });
2301
- }
2302
- return jsonContent({
2303
- action: "connect_reddit",
2304
- requires_confirmation: true,
2305
- current_state: cur.state,
2306
- what_will_happen: "To engage on Reddit for you, the autoposter uses its OWN managed Google Chrome (separate " +
2307
- "from your everyday browser and from the X one). It needs your logged-in reddit.com " +
2308
- "session. If you confirm, it will: (1) start that managed reddit browser if it isn't " +
2309
- "running, (2) copy ONLY your reddit.com cookies (reddit_session, token_v2) from your " +
2310
- "everyday browser (Chrome/Arc/Brave/Edge, auto-detected) into it, and (3) verify you're " +
2311
- "logged in via Reddit's own me.json. No other site's cookies are read, and your passwords " +
2312
- "are never seen. If it can't import a valid session, a Chrome window will open for you to " +
2313
- "sign in once.",
2314
- keychain_prompt: "Reading the saved session requires macOS to unlock the browser's encrypted cookie store, so " +
2315
- "one or more keychain prompts will appear (“... wants to use your confidential information " +
2316
- "stored in '... Safe Storage' in your keychain”). This is expected. The user enters their Mac " +
2317
- "login password and clicks Allow (or Always Allow to avoid repeats). If they use more than one " +
2318
- "browser, the prompt can appear a few times, once per browser.",
2319
- say_to_user: "Heads up: your Mac will pop up a keychain prompt asking to use your browser's Safe Storage. " +
2320
- "That's just us reading your saved Reddit login, nothing else. Type your Mac login password and " +
2321
- "click Allow (or Always Allow). If you use more than one browser you may see it a couple of " +
2322
- "times, once per browser.",
2323
- how_to_proceed: "If the user explicitly requested connecting Reddit, relay the say_to_user line as a brief " +
2324
- "heads-up and immediately call project_config again with action:'connect_reddit', confirm:true; " +
2325
- "do not wait for another yes/no reply. Optionally pass a reddit_source from " +
2326
- "detect_reddit_sources. If the user only asked what connection would do, stop after this " +
2327
- "preview. Reddit is OPTIONAL: never treat it as required for setup completion.",
2328
- });
2329
- }
2330
- recordOnboardingAttempt("reddit_connected", {
2331
- state: args.reddit_source ? "source_selected" : "auto_detect",
2332
- });
2333
- const r = await redditConnect(args.reddit_source, args.reddit_manual_login);
2334
- let verified = false;
2335
- let configNote;
2336
- if (r.connected) {
2337
- completeOnboardingMilestone("reddit_connected", { state: r.state });
2338
- // Persist the discovered username through the server's config-write
2339
- // path (accounts.reddit.username, the field account_resolver reads),
2340
- // never overwriting a deliberately-set value.
2341
- if (r.username) {
2342
- const w = recordRedditAccount(r.username);
2343
- configNote = w.detail;
2344
- }
2345
- // Doctor-style persistence re-check before reddit_verified: a fresh
2346
- // read-only status probe confirms the session actually persisted
2347
- // (live me.json or the on-disk profile cookie row) rather than
2348
- // trusting the connect call's own success.
2349
- const recheck = await redditStatus();
2350
- if (recheck.connected) {
2351
- completeOnboardingMilestone("reddit_verified", { state: recheck.state });
2352
- verified = true;
2353
- }
2354
- else {
2355
- recordOnboardingAttempt("reddit_verified", {
2356
- state: recheck.state || "unverified",
2357
- });
2358
- }
2359
- // Reddit is live: install the discovery kicker (idempotent; gated on
2360
- // runtime + project readiness inside, and it never touches a
2361
- // hand-built plist pointing outside the managed package).
2362
- void ensureRedditKickerInstalled()
2363
- .then((res) => console.error(`[reddit-kicker] post-connect install: ${res.ok ? "ok" : "skip"} (${res.detail})`))
2364
- .catch((e) => console.error("[reddit-kicker] post-connect install failed:", e?.message || e));
2365
- }
2366
- else {
2367
- blockOnboardingMilestone("reddit_connected", `reddit_${r.state || "not_connected"}`, r.error || r.note || summarizeRedditAuth(r), { state: r.state || "not_connected" });
2368
- }
2369
- return jsonContent({
2370
- action: "connect_reddit",
2371
- connected: r.connected,
2372
- state: r.state,
2373
- username: r.username,
2374
- account_age_days: r.account_age_days,
2375
- comment_karma: r.comment_karma,
2376
- // Ready-to-relay expectation setter for fresh/low-karma accounts
2377
- // (AutoMod gates those in most subreddits). Advisory only; never a
2378
- // reason to block or undo the connect.
2379
- warning: r.warning,
2380
- verified,
2381
- config: configNote,
2382
- summary: summarizeRedditAuth(r),
2383
- note: r.note,
2384
- attempts: r.attempts,
2385
- onboarding: onboardingSnapshot(),
2386
- next_step: r.connected
2387
- ? "Reddit is connected. The reddit discovery job installs itself once a project is " +
2388
- "configured; drafts flow into the same review cards as X and nothing posts without " +
2389
- "approval." +
2390
- (r.warning ? " Relay the `warning` field to the user so expectations are set." : "")
2391
- : r.state === "needs_login"
2392
- ? "The user must finish signing in to reddit.com in the Chrome window that opened. Tell " +
2393
- "them that single required action, then call project_config action:'connect_reddit', " +
2394
- "confirm:true again."
2395
- : "Reddit is not connected yet. " + summarizeRedditAuth(r),
2396
- });
2397
- }
2398
2075
  // ---- Profile scan: grounding-truth corpus from the connected account ----
2399
2076
  // Reuses the authenticated managed-Chrome session (so it must run AFTER a
2400
2077
  // successful connect_x) to read the user's bio + recent posts + recent
@@ -2500,9 +2177,6 @@ tool("project_config", {
2500
2177
  const projects = Array.isArray(snap.projects) ? snap.projects : [];
2501
2178
  const rtReady = !!snap.runtime_ready;
2502
2179
  const xConnected = !!snap.x_connected;
2503
- const redditConnected = !!snap.reddit_connected;
2504
- // Any-of platform completion: X or Reddit satisfies the platform leg.
2505
- const anyPlatform = xConnected || redditConnected;
2506
2180
  const configured = (snap.projects_ready || 0) > 0;
2507
2181
  return jsonContent({
2508
2182
  configured,
@@ -2511,9 +2185,6 @@ tool("project_config", {
2511
2185
  x_connected: xConnected,
2512
2186
  x_state: snap.x_state,
2513
2187
  x_handle: snap.x_handle ?? null,
2514
- reddit_connected: redditConnected,
2515
- reddit_state: snap.reddit_state,
2516
- reddit_username: snap.reddit_username ?? null,
2517
2188
  setup_complete: !!snap.setup_complete,
2518
2189
  mcp_version: snap.version,
2519
2190
  latest_version: snap.latest_version,
@@ -2535,15 +2206,14 @@ tool("project_config", {
2535
2206
  ? "Runtime is not ready yet. It provisions automatically on boot — poll runtime action:'status' until ready (only call runtime action:'install' to retry if status shows the boot provision failed or stalled), then continue setup automatically."
2536
2207
  : projects.length === 0
2537
2208
  ? "No projects yet. Discover the product from conversation context and the connected X profile; research its website, infer a conservative complete project, and call project_config. Ask only if no product can be identified." +
2538
- (anyPlatform ? "" : " No platform is connected yet either. X is the default: detect_x_sources, warn about keychain prompts, then run connect_x with confirm:true without a separate permission turn. If the user prefers Reddit (or X can't be connected), connect_reddit works standalone.")
2209
+ (xConnected ? "" : " X is not connected yet either — detect_x_sources, warn about keychain prompts, then run connect_x with confirm:true without a separate permission turn.")
2539
2210
  : projects.every((p) => p.ready)
2540
- ? (anyPlatform
2541
- ? "All configured projects are ready and a platform is connected" +
2542
- (xConnected ? "" : " (Reddit; X was skipped, which is fine)") +
2543
- ". SCHEDULE THE AUTOPILOT: (1) call queue_setup and create each returned task with create_scheduled_task (prompt and notifyOnCompletion verbatim — notifyOnCompletion must be false; 'already exists' is fine, but then call update_scheduled_task with notifyOnCompletion:false to silence per-run notifications); (2) the autopilot then runs on its own (launchd kicker + queue worker). Call the `dashboard` tool to confirm the schedule is firing (schedule_state 'ok') — that is the terminal step; do NOT wait for or verify a draft card. Do NOT pause to ask the user to review drafts."
2544
- : "All configured projects are ready, but NO platform is connected yet; posting needs a logged-in session. X is the default: detect sources and run project_config action:'connect_x', confirm:true; do not ask whether to proceed. If the user prefers Reddit or X can't be connected, run action:'connect_reddit' instead; ONE connected platform completes setup.")
2211
+ ? (xConnected
2212
+ ? "All configured projects are ready and X is connected. SCHEDULE THE AUTOPILOT: (1) call queue_setup and create each returned task with create_scheduled_task (prompt and notifyOnCompletion verbatim — notifyOnCompletion must be false; 'already exists' is fine, but then call update_scheduled_task with notifyOnCompletion:false to silence per-run notifications); (2) the autopilot then runs on its own (launchd kicker + queue worker). Call the `dashboard` tool to confirm the schedule is firing (schedule_state 'ok') — that is the terminal step; do NOT wait for or verify a draft card. Do NOT pause to ask the user to review drafts."
2213
+ : "All configured projects are ready, but X is NOT connected — posting needs a logged-in " +
2214
+ "x.com session. Detect sources and run project_config action:'connect_x', confirm:true; do not ask whether to proceed.")
2545
2215
  : "Some projects are missing required fields (see each project's missing_required). Derive them from config, context, profile_scan, and website research, then call project_config again. Ask only if a required field is genuinely unknowable." +
2546
- (anyPlatform ? "" : " No platform is connected yet either; X is the default (connect_x with confirm:true), or connect_reddit if the user prefers Reddit."),
2216
+ (xConnected ? "" : " X is also not connected yet; detect sources and run connect_x with confirm:true."),
2547
2217
  });
2548
2218
  }
2549
2219
  // Apply mode (incremental): merge whatever fields were supplied onto the
@@ -2892,22 +2562,7 @@ tool("post_drafts", {
2892
2562
  warnings,
2893
2563
  });
2894
2564
  }
2895
- // postApproved now arms the cross-instance posting flag before the Reddit
2896
- // drain (see its own comment), not just before the Twitter phase. Every
2897
- // op inside that drain is already individually best-effort try/caught, so
2898
- // this is belt-and-suspenders: if something still throws past all of
2899
- // that, clear the flag before it escapes rather than leave this MCP
2900
- // instance's posting permanently gated behind a flag nothing will ever
2901
- // reset.
2902
- let result;
2903
- try {
2904
- result = await postApproved(batch_id, plan);
2905
- }
2906
- catch (e) {
2907
- postingActive = false;
2908
- stopPostingFlagHeartbeat();
2909
- throw e;
2910
- }
2565
+ const result = await postApproved(batch_id, plan);
2911
2566
  // Report the REAL posted count from the pipeline, not the approved count.
2912
2567
  // A run can approve N yet land 0 (browser/session failure); reporting
2913
2568
  // approve.size here told the agent "posted: N" on a total failure.
@@ -3159,9 +2814,9 @@ tool("posting_volume", {
3159
2814
  title: "Read or set posting volume (Aggressive / Steady / Chill)",
3160
2815
  description: "Read or set this install's posting-volume mode, the quality bar that decides how many drafts " +
3161
2816
  "per day the twitter cycle produces. Three modes, shown to users as Aggressive (~100+ posts/day), " +
3162
- "Steady (~30/day, the default every install starts on), and Chill (~5/day, only the very best " +
3163
- "candidates). Internally the modes are high|medium|low and both spellings are accepted. " +
3164
- "action:'get' returns the current mode plus per-mode estimated " +
2817
+ "Steady (~30/day), and Chill (~5/day, only the very best candidates); 'default' clears the " +
2818
+ "override so the cycle's built-in setting applies. Internally the modes are high|medium|low and " +
2819
+ "both spellings are accepted. action:'get' returns the current mode plus per-mode estimated " +
3165
2820
  "posts/day computed from this install's own recent candidate pool (show those numbers with the " +
3166
2821
  "Aggressive/Steady/Chill names when the user is choosing). Use when the user asks to post more, " +
3167
2822
  "post less, slow down, be more aggressive, chill out, raise the quality bar, or change posting " +
@@ -3170,9 +2825,9 @@ tool("posting_volume", {
3170
2825
  inputSchema: {
3171
2826
  action: z.enum(["get", "set"]).default("get").describe("get = read mode + rates; set = change it"),
3172
2827
  mode: z
3173
- .enum(["aggressive", "steady", "chill", "high", "medium", "low"])
2828
+ .enum(["aggressive", "steady", "chill", "high", "medium", "low", "default"])
3174
2829
  .optional()
3175
- .describe("Required for action:'set'. aggressive=high, steady=medium, chill=low."),
2830
+ .describe("Required for action:'set'. aggressive=high, steady=medium, chill=low; 'default' clears the override."),
3176
2831
  },
3177
2832
  }, async (args) => {
3178
2833
  const action = args.action || "get";
@@ -3180,7 +2835,7 @@ tool("posting_volume", {
3180
2835
  const ALIAS = { aggressive: "high", steady: "medium", chill: "low" };
3181
2836
  if (action === "set") {
3182
2837
  if (!args.mode) {
3183
- return jsonContent({ error: "mode is required for action:'set' (aggressive|steady|chill)" });
2838
+ return jsonContent({ error: "mode is required for action:'set' (aggressive|steady|chill|default)" });
3184
2839
  }
3185
2840
  const stored = ALIAS[String(args.mode)] || String(args.mode);
3186
2841
  const r = await runPython("scripts/s4l_posting_mode.py", ["set", stored], {
@@ -4093,101 +3748,6 @@ async function ensureQueueKickerInstalled() {
4093
3748
  return { ok: false, detail: e?.message || String(e) };
4094
3749
  }
4095
3750
  }
4096
- // ---- Reddit discovery kicker (optional platform) ----------------------------
4097
- // Mirrors ensureQueueKickerInstalled for the reddit lane: a 15-minute launchd
4098
- // job that runs skill/run-reddit-search-launchd.sh (the detach wrapper; the
4099
- // real cycle honors the global draft-only flag via s4l_mode.py, and its
4100
- // drafting turn rides the same s4l-worker queue as X). Gates:
4101
- // - runtime ready
4102
- // - reddit connected (connected OR connected_idle; the profile persists)
4103
- // - a managed project is configured and ready
4104
- // It is NEVER an onboarding requirement: installs that never connect reddit
4105
- // simply never get this plist.
4106
- //
4107
- // OPERATOR-MAC SAFETY: a hand-built com.m13v.social-reddit-search plist
4108
- // pointing at ~/social-autoposter (StartCalendarInterval, custom env) exists
4109
- // on the dev box. If an existing plist's program path is not the managed
4110
- // package's wrapper, we log and leave it completely alone: no rewrite, no
4111
- // reload, no unload.
4112
- async function ensureRedditKickerInstalled() {
4113
- try {
4114
- if (process.platform !== "darwin")
4115
- return { ok: false, detail: "not macOS" };
4116
- if (!runtimeReady())
4117
- return { ok: false, detail: "runtime not ready" };
4118
- const productReady = listManagedProjectStatus().some((p) => p.ready);
4119
- if (!productReady)
4120
- return { ok: false, detail: "no ready project yet" };
4121
- // Reddit session gate. status is read-only (never launches Chrome): a live
4122
- // me.json validation when the harness is up, the on-disk profile cookie
4123
- // check (connected_idle) when it isn't.
4124
- const rs = await redditStatus();
4125
- if (!rs.connected) {
4126
- return { ok: false, detail: `reddit not connected (${rs.state})` };
4127
- }
4128
- const managedWrapper = path.join(repoDir(), "skill", "run-reddit-search-launchd.sh");
4129
- // Foreign-plist guard BEFORE any write: if a plist already exists and its
4130
- // ProgramArguments do not point at the managed package's wrapper, it is a
4131
- // hand-built / operator arrangement. Leave it untouched.
4132
- let cur = null;
4133
- try {
4134
- cur = fs.readFileSync(REDDIT_SEARCH_PLIST, "utf-8");
4135
- }
4136
- catch {
4137
- cur = null;
4138
- }
4139
- if (cur !== null && !cur.includes(`<string>${managedWrapper}</string>`)) {
4140
- const msg = `existing ${REDDIT_SEARCH_LABEL} plist points outside the managed package; leaving it untouched`;
4141
- console.error(`[reddit-kicker] ${msg}`);
4142
- return { ok: true, detail: `skip: ${msg}` };
4143
- }
4144
- const logDir = path.join(repoDir(), "skill", "logs");
4145
- try {
4146
- fs.mkdirSync(logDir, { recursive: true });
4147
- }
4148
- catch {
4149
- /* best-effort */
4150
- }
4151
- const xml = plistXml({
4152
- label: REDDIT_SEARCH_LABEL,
4153
- programArgs: ["bash", managedWrapper],
4154
- intervalSecs: REDDIT_SEARCH_INTERVAL_SECS,
4155
- runAtLoad: false, // never fire a discovery cycle the instant Claude launches
4156
- stdoutLog: path.join(logDir, "launchd-reddit-search-stdout.log"),
4157
- stderrLog: path.join(logDir, "launchd-reddit-search-stderr.log"),
4158
- // S4L_REPO_DIR + S4L_PYTHON are baked by plistXml. State dir + CDP url
4159
- // pin the wrapper's children to the managed state and the harness port.
4160
- extraEnv: {
4161
- S4L_STATE_DIR: s4lStateDir(),
4162
- REDDIT_CDP_URL: REDDIT_CDP_URL_DEFAULT,
4163
- },
4164
- // The wrapper double-forks the real cycle into its own session already,
4165
- // but keep launchd away from the harness Chrome all the same.
4166
- abandonProcessGroup: true,
4167
- });
4168
- const uid = process.getuid ? process.getuid() : 0;
4169
- if (cur === xml) {
4170
- const res = await loadPlist(REDDIT_SEARCH_LABEL, REDDIT_SEARCH_PLIST, uid);
4171
- return { ok: true, detail: `current (load rc=${res.code})` };
4172
- }
4173
- if (cur !== null) {
4174
- await unloadPlist(REDDIT_SEARCH_LABEL, REDDIT_SEARCH_PLIST, uid);
4175
- }
4176
- fs.mkdirSync(path.dirname(REDDIT_SEARCH_PLIST), { recursive: true });
4177
- fs.writeFileSync(REDDIT_SEARCH_PLIST, xml, "utf-8");
4178
- const res = await loadPlist(REDDIT_SEARCH_LABEL, REDDIT_SEARCH_PLIST, uid);
4179
- // No first-run kickstart on purpose: reddit discovery is a background
4180
- // add-on, and the connect flow just finished using the harness browser.
4181
- // The first StartInterval tick (≤15 min) is soon enough.
4182
- return {
4183
- ok: true,
4184
- detail: cur === null ? "installed + loaded" : `rewritten + reloaded (rc=${res.code})`,
4185
- };
4186
- }
4187
- catch (e) {
4188
- return { ok: false, detail: e?.message || String(e) };
4189
- }
4190
- }
4191
3751
  // ---- launchd reaper: kill leaked agent-mode claude worker sessions ----------
4192
3752
  // Independent guardrail (NOT gated on a project being ready): the leak happens
4193
3753
  // whenever the scheduled-task workers fire, and a no-leak run is a cheap no-op.
@@ -4675,13 +4235,6 @@ async function buildSnapshot() {
4675
4235
  completeOnboardingMilestone("runtime_ready");
4676
4236
  if (snap.x_connected)
4677
4237
  completeOnboardingMilestone("x_connected", { state: snap.x_state || "connected" });
4678
- // Reddit (optional platform) heal: a live connected reading on a LATER poll
4679
- // is itself persistence evidence, so it may also complete reddit_verified
4680
- // for an install whose post-connect verify probe transiently failed.
4681
- if (snap.reddit_connected) {
4682
- completeOnboardingMilestone("reddit_connected", { state: snap.reddit_state || "connected" });
4683
- completeOnboardingMilestone("reddit_verified", { source: "live_snapshot" });
4684
- }
4685
4238
  if ((snap.projects_ready || 0) > 0)
4686
4239
  completeOnboardingMilestone("project_ready", { missing_count: 0 });
4687
4240
  if (snap.schedule_state === "ok")
@@ -5702,10 +5255,6 @@ async function drainApprovedBacklog() {
5702
5255
  }
5703
5256
  catch (e) {
5704
5257
  console.error("[post] drainApprovedBacklog error:", e?.message || e);
5705
- // Same reasoning as the other postApproved call site: don't let an
5706
- // escaped exception leave the cross-instance posting flag stuck true.
5707
- postingActive = false;
5708
- stopPostingFlagHeartbeat();
5709
5258
  }
5710
5259
  }
5711
5260
  async function main() {
@@ -5729,12 +5278,6 @@ async function main() {
5729
5278
  // disk, BEFORE serving, so the very first scan uses the shipped pipeline (not
5730
5279
  // the version first materialized at install). Synchronous + best-effort.
5731
5280
  ensurePipelineCurrent();
5732
- // Config's canonical home is the state dir (2026-07-13): migrate a legacy
5733
- // in-repo config.json up on first boot after update, keep the legacy path
5734
- // working via symlink, and self-heal a missing/wrong link on every boot.
5735
- // Must run AFTER ensurePipelineCurrent() so repoDir() points at the final
5736
- // materialized repo.
5737
- console.error(`[social-autoposter-mcp] config home: ${ensureConfigInStateDir()}`);
5738
5281
  // Deterministically provision the owned runtime on boot: whenever it isn't
5739
5282
  // ready (a fresh install, or one interrupted mid-way because a step failed or
5740
5283
  // Claude/the host died mid-install) kick the full install in the background
@@ -5790,17 +5333,6 @@ async function main() {
5790
5333
  else {
5791
5334
  console.error("[queue-worker] launchd kicker: skip (paused)");
5792
5335
  }
5793
- // Reddit discovery kicker (optional platform): installs only when reddit is
5794
- // connected AND a project is ready; a box that never connected reddit is a
5795
- // cheap no-op skip. Paused-gated like the X kicker (it produces drafts).
5796
- if (!isPaused()) {
5797
- void ensureRedditKickerInstalled()
5798
- .then((r) => console.error(`[reddit-kicker] launchd kicker: ${r.ok ? "ok" : "skip"} (${r.detail})`))
5799
- .catch((e) => console.error("[reddit-kicker] kicker install failed:", e?.message || e));
5800
- }
5801
- else {
5802
- console.error("[reddit-kicker] launchd kicker: skip (paused)");
5803
- }
5804
5336
  // Self-healing reaper for the agent-mode session leak the queue autopilot
5805
5337
  // produces (finished `claude` worker sessions Desktop never tears down). A
5806
5338
  // standalone guardrail; install unconditionally so it caps memory even on a
@@ -5977,22 +5509,17 @@ async function main() {
5977
5509
  void sendStateSnapshot("startup");
5978
5510
  const ss = setInterval(() => void sendStateSnapshot("interval"), 15 * 60_000);
5979
5511
  ss.unref();
5980
- // Voice-exemplar catch-up + periodic refresh, checked on every boot
5981
- // (2026-07-16, extended from the original one-shot-for-legacy-installs
5982
- // version): rescans the connected X profile and re-stores voice.examples +
5983
- // the persona_corpus.txt exemplar section whenever
5984
- // scripts/voice_exemplars.py's _needs_rescan() says so -- never scanned,
5985
- // scanned by an older SCANNER_VERSION (so a scraper fix like the 2026-07-15
5986
- // stall-detection bug reaches already-scanned installs on their next boot
5987
- // instead of silently never re-running), or the last scan is more than
5988
- // RESCAN_MAX_AGE_DAYS (14) old. Additive only (regenerates just its own
5989
- // marked corpus section; respects hand-written examples). Each boot is
5990
- // cheap when nothing needs it (stamped examples_scanned_at +
5991
- // examples_scanner_version make it a no-op until either goes stale), and
5992
- // when something DOES need it, it WAITS politely on the twitter-browser
5993
- // lock, polling while holding nothing, until cycles/DM runs free the
5994
- // browser, up to 12h before deferring to the next boot. Delayed so
5995
- // boot-time work (runtime provision, kicker install) settles first.
5512
+ // One-shot voice-exemplar catch-up for installs onboarded BEFORE the
5513
+ // exemplar feature: if the persona has no voice.examples_scanned_at, rescan
5514
+ // the connected X profile and store the top-performing replies as
5515
+ // voice.examples + the persona_corpus.txt exemplar section. Additive only
5516
+ // (regenerates just its own marked corpus section; respects hand-written
5517
+ // examples) and self-limiting (no cooldown by design: success stamps
5518
+ // examples_scanned_at which makes later boots a no-op, and until then it
5519
+ // WAITS politely on the twitter-browser lock, polling while holding
5520
+ // nothing, until cycles/DM runs free the browser, up to 12h before
5521
+ // deferring to the next boot). Delayed so boot-time work (runtime
5522
+ // provision, kicker install) settles first.
5996
5523
  const backfill = setTimeout(() => {
5997
5524
  if (isPaused())
5998
5525
  return;