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

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.
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.7.12-rc.11",
3
- "installedAt": "2026-11-17T23:53:27.779Z"
2
+ "version": "1.7.12-rc.13",
3
+ "installedAt": "2026-11-18T03:38:05.021Z"
4
4
  }
package/mcp/manifest.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "dxt_version": "0.1",
3
3
  "name": "social-autoposter",
4
4
  "display_name": "S4L",
5
- "version": "1.7.12-rc.11",
5
+ "version": "1.7.12-rc.13",
6
6
  "description": "Draft, review, approve, and autopilot X/Twitter posts.",
7
7
  "long_description": "## **⚠️ The disclaimer above is generic Claude boilerplate.** Anthropic shows the same warning on every plugin regardless of what it does; any plugin has the same level of access as any app you download from the internet.\n\nS4L is an open source product developed by Mediar.ai Incorporated, a VC-backed San Francisco-based startup.\n\nTo get started:\n\n1\\. Copy this prompt: **Set me up on S4L plugin end to end**\n\n2\\. Quit with CMD+Q, reopen Claude, paste into a new chat.\n\nWhat happens next:\n\n* About every 5 minutes S4L scans X for posts that match your topics and drafts replies in your voice.\n* Drafts show up as review cards, usually the first within a few minutes. Nothing is posted automatically; you approve each one.\n* Posting autopilot stays off until you explicitly turn it on.",
8
8
  "author": {
package/mcp/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@m13v/s4l-mcp",
3
- "version": "1.7.12-rc.11",
3
+ "version": "1.7.12-rc.13",
4
4
  "private": true,
5
5
  "description": "Desktop MCP client for social-autoposter (X/Twitter rail): manual draft/review/approve loop, autopilot control, and stats. Thin wrapper over the existing pipeline scripts.",
6
6
  "license": "MIT",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@m13v/s4l",
3
- "version": "1.7.12-rc.11",
3
+ "version": "1.7.12-rc.13",
4
4
  "description": "Automated social posting pipeline for Reddit, X/Twitter, LinkedIn, and Moltbook. Install as a Claude Code agent skill.",
5
5
  "bin": {
6
6
  "social-autoposter": "bin/cli.js",
@@ -657,7 +657,7 @@ DIGEST_PER_SESSION_CAP = 3_500
657
657
  DIGEST_MAX_AGE_HOURS = 48 # older than this: not used at all
658
658
  DIGEST_REFRESH_HOURS = 6 # cycle kicks a background refresh past this
659
659
  DIGEST_RETRY_COOLDOWN_S = 3600 # min gap between attempts (success or not)
660
- MAX_RECENT_WORK_QUERIES = 8
660
+ MAX_RECENT_WORK_QUERIES = 4 # per cycle; X search is budgeted (twitter_scan.py)
661
661
  RECENT_WORK_TOPIC_PREFIX = "recent work: "
662
662
 
663
663
  DIGEST_SCHEMA = {
@@ -756,7 +756,11 @@ NEVER include (drop the item, or describe it generically):
756
756
  - what: 1-2 sentences, plain first person, what they did and why.
757
757
  - specifics: the concrete details a reply can cite truthfully (numbers, tools, the exact failure, the outcome). Only facts stated in the transcripts.
758
758
  - angle: one sentence on the opinion or lesson they could credibly share in a public thread about this.
759
- - queries: 1-3 X search queries that find recent public posts by OTHER people discussing this problem space (not this founder's products by name). Plain keyword style, use quotes for phrases and OR for variants, end each with lang:en. No since:, no min_faves:, no from:. Broad enough to return results within a few hours, specific enough that the founder's experience is relevant to what comes back. Example: "\\"claude code\\" (subagents OR \\"parallel agents\\") lang:en"
759
+ - queries: 2-3 X search queries that find recent public posts by OTHER people discussing this problem space (not this founder's products by name). These run against only the last ~6 hours of X, so they must be BROAD:
760
+ - Each query combines at most TWO concepts. Never AND three groups together; "(a OR b) (c OR d) (e OR f)" returns nothing.
761
+ - When the work involved a specific named thing people tweet about (a benchmark, model, tool, library, company, launch), make one query just that name, e.g. "AutomationBench lang:en". Named things find the best threads.
762
+ - Use quotes for multi-word phrases and OR for variants. End each with lang:en. No since:, no min_faves:, no from:.
763
+ Good: "\\"agent memory\\" benchmark lang:en", "\\"claude code\\" subagents lang:en", "SWE-bench lang:en". Bad: "\\"CLAUDE.md\\" (memory OR context) (eval OR benchmark) lang:en" (three concepts, zero results).
760
764
 
761
765
  # Transcripts ({len(sessions)} sessions, most recent first)
762
766
 
@@ -892,28 +896,54 @@ def recent_work_queries(projects: list) -> list[dict]:
892
896
  names = {(p or {}).get("name") for p in projects if isinstance(p, dict)}
893
897
  if not persona or persona not in names:
894
898
  return []
895
- out, seen = [], set()
896
- # round-robin across items so one item can't eat the whole cap
899
+ # Interleave items (round-robin) into one deduped list, then serve a
900
+ # rotating window of MAX_RECENT_WORK_QUERIES per cycle so EVERY digest
901
+ # query runs, not just the first 8 (2026-11-17: 8 of 16 never ran).
897
902
  item_queries = [
898
903
  [(it["title"], q) for q in (it.get("queries") or []) if isinstance(q, str) and q.strip()]
899
904
  for it in digest.get("items") or []
900
905
  ]
901
- while len(out) < MAX_RECENT_WORK_QUERIES and any(item_queries):
906
+ flat, seen = [], set()
907
+ while any(item_queries):
902
908
  for qs in item_queries:
903
- if not qs or len(out) >= MAX_RECENT_WORK_QUERIES:
909
+ if not qs:
904
910
  continue
905
911
  title, q = qs.pop(0)
906
912
  key = " ".join(q.lower().split())
907
913
  if key in seen:
908
914
  continue
909
915
  seen.add(key)
910
- out.append({
911
- "project": persona,
912
- "query": q.strip(),
913
- "search_topic": (RECENT_WORK_TOPIC_PREFIX + title)[:120],
914
- "likes": 0, "clicks": 0, "posts": 0,
915
- })
916
- return out
916
+ flat.append((title, q.strip()))
917
+ if not flat:
918
+ return []
919
+ window = _rotate_window(len(flat), digest.get("generated_at", ""))
920
+ return [
921
+ {
922
+ "project": persona,
923
+ "query": flat[i][1],
924
+ "search_topic": (RECENT_WORK_TOPIC_PREFIX + flat[i][0])[:120],
925
+ "likes": 0, "clicks": 0, "posts": 0,
926
+ }
927
+ for i in window
928
+ ]
929
+
930
+
931
+ def _rotate_window(n: int, digest_id: str) -> list[int]:
932
+ """Indices for this cycle's window and advance the cursor. The cursor
933
+ resets whenever a new digest is generated."""
934
+ path = state_dir() / "recent_work.cursor.json"
935
+ try:
936
+ cur = json.loads(path.read_text())
937
+ start = int(cur.get("next", 0)) if cur.get("digest") == digest_id else 0
938
+ except Exception:
939
+ start = 0
940
+ k = min(MAX_RECENT_WORK_QUERIES, n)
941
+ idx = [(start + j) % n for j in range(k)]
942
+ try:
943
+ path.write_text(json.dumps({"digest": digest_id, "next": (start + k) % n}))
944
+ except OSError:
945
+ pass
946
+ return idx
917
947
 
918
948
 
919
949
  def recent_work_block() -> str:
@@ -926,11 +956,16 @@ def recent_work_block() -> str:
926
956
  return ""
927
957
  lines = [
928
958
  "## RECENT WORK (what the account holder actually did in the last few days)",
929
- "First-hand, current, and true. When a candidate's `Search query` starts with "
930
- f"\"{RECENT_WORK_TOPIC_PREFIX.strip()}\", it was found BECAUSE of the matching item below: "
931
- "ground the reply in that item's specifics. For any other candidate, use an item only "
932
- "if it genuinely fits the thread; never force it. Cite only the specifics listed here; "
933
- "do not embellish numbers or invent outcomes. Never name private people or clients.",
959
+ "First-hand, current, and true. A candidate whose `Search query` starts with "
960
+ f"\"{RECENT_WORK_TOPIC_PREFIX.strip()}\" was found by a keyword search for the matching item "
961
+ "below, so the keyword match is NOT evidence of fit. Use an item ONLY when the thread "
962
+ "itself is about that item's subject (the same problem, tool, or claim), so the story "
963
+ "answers what the author actually said. If the thread only shares a keyword (a "
964
+ "changelog, a launch, a product pitch, a different problem), REJECT the candidate as "
965
+ "off-topic instead of bending the story to fit; the reviewer rejects those every time. "
966
+ "Tell each story at most ONCE: if your recent replies already used an item's anecdote, "
967
+ "do not reuse it. Cite only the specifics listed here; do not embellish numbers or "
968
+ "invent outcomes. Never name private people or clients.",
934
969
  "",
935
970
  ]
936
971
  for it in items:
@@ -228,7 +228,27 @@ def cmd_candidates(batch_id: str) -> int:
228
228
  return -1.0
229
229
 
230
230
  rows.sort(key=composite, reverse=True)
231
- rows = rows[:25]
231
+ # Recent-work candidates (2026-11-17, personal_brand + recent_work_context
232
+ # flag; see scripts/context_mining.py) are found by relevance to what the
233
+ # user just did, so they are low-virality by nature and would never make
234
+ # the top 25. Carry up to RECENT_WORK_EXTRA of them past the cap, subject
235
+ # to a small reach floor (>=1 like OR author >=1k followers). The cycle's
236
+ # virality prefilter and plan-parse bar exempt the same topic prefix.
237
+ def _rw_floor(r):
238
+ return (int(r.get("likes") or 0) >= 1
239
+ or int(r.get("author_followers") or 0) >= 1000)
240
+
241
+ # The floor applies to EVERY recent-work row, inside the top 25 too: in a
242
+ # low-virality pool the top 25 is effectively everything, so a 7-follower,
243
+ # 0-like reply was reaching the drafter (2026-11-17).
244
+ def _is_rw(r):
245
+ return str(r.get("search_topic") or "").startswith("recent work: ")
246
+
247
+ rows = [r for r in rows if not _is_rw(r) or _rw_floor(r)]
248
+ top = rows[:25]
249
+ top_ids = {r.get("id") for r in top}
250
+ extra = [r for r in rows if r.get("id") not in top_ids and _is_rw(r)][:5]
251
+ rows = top + extra
232
252
 
233
253
  for r in rows:
234
254
  cols = [
@@ -319,6 +319,73 @@ from stall_guard import stall_guard # noqa: E402
319
319
 
320
320
  _SCAN_DEADLINE_OVERRIDE = os.environ.get("S4L_SCAN_QUERY_DEADLINE_S")
321
321
 
322
+ # --- X search rate limit (2026-11-17) ----------------------------------------
323
+ # X's web search is rate-limited per account. Measured over 30h of this
324
+ # sidecar: blackouts begin after ~60-90 searches in the trailing 15 min and
325
+ # last ~7 min (median; p75 7.6, max 38). During one, the search page renders
326
+ # "Something went wrong. Try reloading." with zero articles, which scan() used
327
+ # to count as a genuine 0-result query: the cycle kept firing every remaining
328
+ # query into the error, 35-68% of searches per busy hour came back blank, and
329
+ # each blank was logged as a DUD query (poisoning the dud list, and the invent
330
+ # supply test, which also calls scan()). Now:
331
+ # * a pacing budget (BUDGET per trailing 15 min, shared by every caller via
332
+ # a state file) skips searches before they would trip the limit;
333
+ # * the error page is detected and starts a COOLDOWN; searches inside it are
334
+ # skipped without navigating;
335
+ # * skipped / rate-limited searches return [] and write NO scan record, so
336
+ # they are never logged as attempts or duds.
337
+ _X_SEARCH_STATE = pathlib.Path(
338
+ os.environ.get("S4L_STATE_DIR") or (pathlib.Path.home() / ".social-autoposter-mcp")
339
+ ) / "x-search-budget.json"
340
+ _X_SEARCH_BUDGET_15M = int(os.environ.get("S4L_X_SEARCH_BUDGET_15M") or "50")
341
+ _X_SEARCH_COOLDOWN_S = int(os.environ.get("S4L_X_SEARCH_COOLDOWN_S") or "600")
342
+ _X_ERROR_JS = (
343
+ "(() => { const m = document.querySelector('main') || document.body;"
344
+ " const t = m ? m.innerText : '';"
345
+ " return /Something went wrong|Rate limit exceeded|Try reloading/i.test(t)"
346
+ " && document.querySelectorAll('article').length === 0; })()"
347
+ )
348
+
349
+
350
+ def _budget_load() -> dict:
351
+ try:
352
+ d = json.loads(_X_SEARCH_STATE.read_text())
353
+ return d if isinstance(d, dict) else {}
354
+ except Exception:
355
+ return {}
356
+
357
+
358
+ def _budget_save(d: dict) -> None:
359
+ try:
360
+ _X_SEARCH_STATE.parent.mkdir(parents=True, exist_ok=True)
361
+ tmp = _X_SEARCH_STATE.with_suffix(".json.tmp")
362
+ tmp.write_text(json.dumps(d))
363
+ tmp.replace(_X_SEARCH_STATE)
364
+ except OSError:
365
+ pass # fail-open: pacing is protective, never on the data path
366
+
367
+
368
+ def _budget_block_reason(now: float):
369
+ """'cooldown' / 'budget' when this search must be skipped, else None."""
370
+ d = _budget_load()
371
+ if now < float(d.get("cooldown_until") or 0):
372
+ return "cooldown"
373
+ recent = [t for t in (d.get("recent") or []) if now - t < 900]
374
+ if len(recent) >= _X_SEARCH_BUDGET_15M:
375
+ return "budget"
376
+ return None
377
+
378
+
379
+ def _budget_record(now: float, rate_limited: bool) -> None:
380
+ d = _budget_load()
381
+ recent = [t for t in (d.get("recent") or []) if now - t < 900]
382
+ recent.append(now)
383
+ d["recent"] = recent
384
+ if rate_limited:
385
+ d["cooldown_until"] = now + _X_SEARCH_COOLDOWN_S
386
+ d["last_rate_limited_at"] = now
387
+ _budget_save(d)
388
+
322
389
 
323
390
  def scan(
324
391
  query: str,
@@ -350,6 +417,16 @@ def _scan_inner(
350
417
  ) -> list:
351
418
  skip = {str(s) for s in (skip_ids or [])}
352
419
  url = _build_url(query, int(freshness_hours))
420
+
421
+ blocked = _budget_block_reason(time.time())
422
+ if blocked:
423
+ print(f"[x_search_{blocked}] skipped q={query[:60]!r} (no navigation, no attempt logged)",
424
+ file=sys.stderr, flush=True)
425
+ _write_sidecar({"ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "ts_epoch": int(time.time()),
426
+ "query": query, "project": project, "skipped": blocked,
427
+ "batch_id": os.environ.get("BATCH_ID")})
428
+ return []
429
+
353
430
  _navigate(url)
354
431
  wait_for_load(timeout=15.0)
355
432
  # X lazy-loads the result list; settle briefly before scraping. Matches
@@ -360,6 +437,21 @@ def _scan_inner(
360
437
  tweets = raw if isinstance(raw, list) else []
361
438
  pre_count = len(tweets)
362
439
 
440
+ rate_limited = False
441
+ if pre_count == 0:
442
+ try:
443
+ rate_limited = bool(js(_X_ERROR_JS))
444
+ except Exception:
445
+ rate_limited = False
446
+ _budget_record(time.time(), rate_limited)
447
+ if rate_limited:
448
+ print(f"[x_search_rate_limited] X error page on q={query[:60]!r}; cooling down "
449
+ f"{_X_SEARCH_COOLDOWN_S}s, attempt not logged", file=sys.stderr, flush=True)
450
+ _write_sidecar({"ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "ts_epoch": int(time.time()),
451
+ "query": query, "project": project, "url": url, "pre_count": 0,
452
+ "rate_limited": True, "batch_id": os.environ.get("BATCH_ID")})
453
+ return []
454
+
363
455
  cap_epoch = int(time.time()) - int(freshness_hours) * 3600
364
456
  fresh = []
365
457
  for t in tweets:
@@ -1202,14 +1202,21 @@ else
1202
1202
  # kicked here too: detached, flag-gated, no-op unless >6h stale.
1203
1203
  python3 "$REPO_DIR/scripts/context_mining.py" digest --if-stale-hours 6 --background >>"$LOG_FILE" 2>&1 || true
1204
1204
  _RW_QUERIES=$(echo "$PROJECTS_JSON" | python3 "$REPO_DIR/scripts/context_mining.py" queries 2>>"$LOG_FILE" || echo "[]")
1205
+ # Bank rotation (2026-11-17): twitter_scan.scan() now paces X searches to a
1206
+ # per-15-min budget and skips the rest of a cycle's queries once it is
1207
+ # spent or X shows its rate-limit error page. A fixed order would starve
1208
+ # the same bank tail every cycle, so rotate the bank's start point by
1209
+ # wall-clock (4-min steps, about one cycle). Recent-work queries stay first.
1205
1210
  _RW_N=$(RW="$_RW_QUERIES" QT="$QUERIES_TMP" python3 -c '
1206
- import json, os
1211
+ import json, os, time
1207
1212
  try: rw = json.loads(os.environ.get("RW") or "[]")
1208
1213
  except Exception: rw = []
1209
- if rw:
1210
- try: bank = json.load(open(os.environ["QT"]))
1211
- except Exception: bank = []
1212
- json.dump(rw + bank, open(os.environ["QT"], "w"))
1214
+ try: bank = json.load(open(os.environ["QT"]))
1215
+ except Exception: bank = []
1216
+ if bank:
1217
+ k = int(time.time() // 240) % len(bank)
1218
+ bank = bank[k:] + bank[:k]
1219
+ json.dump(rw + bank, open(os.environ["QT"], "w"))
1213
1220
  print(len(rw))
1214
1221
  ' 2>>"$LOG_FILE" || echo 0)
1215
1222
  [ "${_RW_N:-0}" -gt 0 ] && log "Phase 1 (bank): +${_RW_N} recent-work queries prepended (personal_brand, recent_work_context on)"
@@ -1775,7 +1782,12 @@ else
1775
1782
  fi
1776
1783
  if [ -n "$VIRALITY_THRESHOLD" ] && [ -n "$CANDIDATES" ]; then
1777
1784
  _VF_TOTAL=$(printf '%s\n' "$CANDIDATES" | grep -c '^[0-9]' || true)
1778
- CANDIDATES=$(printf '%s\n' "$CANDIDATES" | awk -F'|' -v b="$VIRALITY_THRESHOLD" '$1 ~ /^[0-9]+$/ && NF>=5 && $5+0 >= b+0')
1785
+ # Recent-work exemption (2026-11-17): rows whose search_topic (col 8)
1786
+ # starts with "recent work: " came from the user's own recent sessions
1787
+ # (personal_brand lane, recent_work_context flag) and are gated on
1788
+ # relevance, not virality; twitter_cycle_helper.py already applied their
1789
+ # reach floor. Everything else still has to clear the bar.
1790
+ CANDIDATES=$(printf '%s\n' "$CANDIDATES" | awk -F'|' -v b="$VIRALITY_THRESHOLD" '$1 ~ /^[0-9]+$/ && NF>=5 && ($5+0 >= b+0 || (NF>=8 && index($8, "recent work: ") == 1))')
1779
1791
  _VF_KEPT=$(printf '%s\n' "$CANDIDATES" | grep -c '^[0-9]' || true)
1780
1792
  log "[virality_prefilter] kept ${_VF_KEPT:-0} of ${_VF_TOTAL:-0} candidate(s) at/above bar=$VIRALITY_THRESHOLD; below-bar rows stay pending and are never sent to the drafter"
1781
1793
  fi
@@ -2412,11 +2424,23 @@ rejected = so.get('rejected', []) if isinstance(so, dict) else []
2412
2424
  # (pipe cols: id|url|author|text|virality|delta|...). Shared by the top-N cap
2413
2425
  # and the rolling virality bar below.
2414
2426
  _vir = {}
2427
+ _rw_ids = set()
2415
2428
  for _ln in (os.environ.get('S4L_CAND_VIR', '') or '').splitlines():
2416
2429
  _p = _ln.split('|')
2417
2430
  if len(_p) >= 5 and _p[0].isdigit():
2418
2431
  try: _vir[int(_p[0])] = float(_p[4] or 0)
2419
2432
  except Exception: pass
2433
+ if len(_p) >= 8 and _p[7].startswith('recent work: '):
2434
+ _rw_ids.add(int(_p[0]))
2435
+ # RECENT-WORK LANE (2026-11-17): picks found via the user's own recent-work
2436
+ # queries (search_topic 'recent work: ...', personal_brand + recent_work_context
2437
+ # flag) are set aside BEFORE the top-N cap and the virality bar, then the best
2438
+ # ONE is added back after both. They are gated on relevance (the drafter
2439
+ # already chose them), not virality, and never compete with or displace the
2440
+ # regular top-N pick. Extra recent-work picks stay 'pending' like deferrals.
2441
+ _rw_picks = [c for c in candidates if c.get('candidate_id') in _rw_ids]
2442
+ candidates = [c for c in candidates if c.get('candidate_id') not in _rw_ids]
2443
+ _rw_picks.sort(key=lambda c: _vir.get(c.get('candidate_id'), 0.0), reverse=True)
2420
2444
  # TOP-N POST CAP (2026-06-29): keep only the highest-Virality on-brand pick(s).
2421
2445
  # S4L_POST_TOP_N=0 disables the cap (env opt-out only; the cap applies to both
2422
2446
  # autopilot and DRAFT_ONLY lanes as of 2026-06-30). Truncated picks are dropped
@@ -2442,6 +2466,10 @@ if _bar and candidates:
2442
2466
  candidates = _kept
2443
2467
  except Exception:
2444
2468
  pass
2469
+ if _rw_picks:
2470
+ candidates = candidates + _rw_picks[:1]
2471
+ _deferred += len(_rw_picks) - 1
2472
+ print(f'prep: recent-work lane kept 1 of {len(_rw_picks)} pick(s) outside the top-N cap and virality bar', file=sys.stderr)
2445
2473
  # The picker assignment travels through the plan envelope so
2446
2474
  # twitter_post_plan.py can call validate_or_register(...) with the
2447
2475
  # original (assigned_style, assigned_mode) and coerce USE-mode drift