@m13v/s4l 1.7.12-rc.12 → 1.7.12-rc.14
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.
- package/mcp/dist/version.json +2 -2
- package/mcp/manifest.json +1 -1
- package/mcp/package.json +1 -1
- package/package.json +1 -1
- package/scripts/author_history_block.py +4 -7
- package/scripts/context_mining.py +50 -33
- package/scripts/enrich_twitter_candidates.py +7 -0
- package/scripts/feedback_digest.py +7 -7
- package/scripts/fetch_twitter_t1.py +8 -2
- package/scripts/post_reddit.py +3 -8
- package/scripts/scan_x_profile.py +1 -1
- package/scripts/twitter_cycle_helper.py +14 -8
- package/scripts/twitter_scan.py +92 -0
- package/scripts/voice_exemplars.py +2 -2
- package/skill/run-twitter-cycle.sh +12 -5
package/mcp/dist/version.json
CHANGED
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.
|
|
5
|
+
"version": "1.7.12-rc.14",
|
|
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.
|
|
3
|
+
"version": "1.7.12-rc.14",
|
|
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.
|
|
3
|
+
"version": "1.7.12-rc.14",
|
|
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",
|
|
@@ -238,11 +238,8 @@ def fetch(platform, author, days=30, limit=5):
|
|
|
238
238
|
return []
|
|
239
239
|
|
|
240
240
|
|
|
241
|
-
def
|
|
242
|
-
|
|
243
|
-
if len(s) <= n:
|
|
244
|
-
return s
|
|
245
|
-
return s[: n - 3].rstrip() + "..."
|
|
241
|
+
def _flat(s):
|
|
242
|
+
return (s or "").replace("\n", " ").replace("\r", " ").strip()
|
|
246
243
|
|
|
247
244
|
|
|
248
245
|
def format_block(rows, author, platform, days):
|
|
@@ -292,7 +289,7 @@ def format_block(rows, author, platform, days):
|
|
|
292
289
|
our_content_clean = _strip_active_campaign_suffixes(
|
|
293
290
|
our_content, suffix_strip_list
|
|
294
291
|
)
|
|
295
|
-
ours =
|
|
292
|
+
ours = _flat(our_content_clean)
|
|
296
293
|
eng_bits = []
|
|
297
294
|
if upvotes:
|
|
298
295
|
eng_bits.append(f"likes={upvotes}")
|
|
@@ -303,7 +300,7 @@ def format_block(rows, author, platform, days):
|
|
|
303
300
|
eng_str = (" [" + ", ".join(eng_bits) + "]") if eng_bits else " [no engagement]"
|
|
304
301
|
lines.append(f"- {date} ({proj}): \"{ours}\"{eng_str}")
|
|
305
302
|
if their_first_reply:
|
|
306
|
-
tr =
|
|
303
|
+
tr = _flat(their_first_reply)
|
|
307
304
|
lines.append(f" -> they replied: \"{tr}\"")
|
|
308
305
|
lines.append(
|
|
309
306
|
"Use as SOFT CONTEXT only: vary angle, avoid repeating phrasing or "
|
|
@@ -84,10 +84,10 @@ def ledger_path() -> Path:
|
|
|
84
84
|
# ---------------------------------------------------------------- gathering
|
|
85
85
|
|
|
86
86
|
MIN_HUMAN_MSGS = 2
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
DEFAULT_TOTAL_BUDGET =
|
|
87
|
+
# No per-message or per-session caps (2026-11-17): transcripts go in whole.
|
|
88
|
+
# The budgets below only decide how many sessions share ONE job; a window that
|
|
89
|
+
# does not fit is split across more jobs, never trimmed.
|
|
90
|
+
DEFAULT_TOTAL_BUDGET = 400_000 # chars per job (~100k tokens); uncapped sessions need room
|
|
91
91
|
|
|
92
92
|
# cwd substrings that mark a session as S4L's own automation, never mined
|
|
93
93
|
EXCLUDED_CWD_MARKERS = (".s4l-worker", ".saps-worker")
|
|
@@ -186,7 +186,7 @@ def _compact_session(path: Path) -> dict | None:
|
|
|
186
186
|
if not text:
|
|
187
187
|
continue
|
|
188
188
|
human_count += 1
|
|
189
|
-
turns.append("USER: " + text
|
|
189
|
+
turns.append("USER: " + text)
|
|
190
190
|
elif d.get("type") == "assistant" and role == "assistant":
|
|
191
191
|
text = _text_blocks(msg.get("content"))
|
|
192
192
|
if not text:
|
|
@@ -194,7 +194,7 @@ def _compact_session(path: Path) -> dict | None:
|
|
|
194
194
|
text = text.strip()
|
|
195
195
|
if len(text) < 40: # skip one-liner tool narration
|
|
196
196
|
continue
|
|
197
|
-
turns.append("ASSISTANT: " + text
|
|
197
|
+
turns.append("ASSISTANT: " + text)
|
|
198
198
|
except OSError:
|
|
199
199
|
return None
|
|
200
200
|
|
|
@@ -204,10 +204,6 @@ def _compact_session(path: Path) -> dict | None:
|
|
|
204
204
|
return None
|
|
205
205
|
|
|
206
206
|
body = "\n\n".join(turns)
|
|
207
|
-
if len(body) > PER_SESSION_CAP:
|
|
208
|
-
# keep the head and the tail; the middle is elided
|
|
209
|
-
half = PER_SESSION_CAP // 2
|
|
210
|
-
body = body[:half] + "\n\n[... middle of session elided ...]\n\n" + body[-half:]
|
|
211
207
|
return {
|
|
212
208
|
"session_id": path.stem,
|
|
213
209
|
"path": str(path),
|
|
@@ -351,7 +347,7 @@ def build_prompt(sessions: list[dict], pending_props: list[dict] | None = None)
|
|
|
351
347
|
{"status": r.get("status"), "gist": _gist(r)} for r in read_ledger()[-60:]
|
|
352
348
|
] + [{"status": "pending", "gist": _gist(p)} for p in (pending_props or [])]
|
|
353
349
|
considered_block = (
|
|
354
|
-
"\n".join(f"- ({r['status']}) {r['gist']
|
|
350
|
+
"\n".join(f"- ({r['status']}) {r['gist']}" for r in considered)
|
|
355
351
|
if considered
|
|
356
352
|
else "(nothing has been considered yet)"
|
|
357
353
|
)
|
|
@@ -565,7 +561,7 @@ def cmd_review(_ns) -> int:
|
|
|
565
561
|
if p.get("action") == "revise" and p.get("revises_line"):
|
|
566
562
|
n = p["revises_line"]
|
|
567
563
|
old = corpus_lines[n - 1] if 0 < n <= len(corpus_lines) else "(missing line)"
|
|
568
|
-
head += f" REVISES [{n}]: {old
|
|
564
|
+
head += f" REVISES [{n}]: {old}"
|
|
569
565
|
else:
|
|
570
566
|
head += " ADD"
|
|
571
567
|
print(head)
|
|
@@ -652,12 +648,11 @@ def _decide(ids: list[str], status: str) -> int:
|
|
|
652
648
|
# scripts/draft_prompt_core.py (recent_work_block, persona lane only).
|
|
653
649
|
|
|
654
650
|
DIGEST_DAYS = 2
|
|
655
|
-
DIGEST_BUDGET =
|
|
656
|
-
DIGEST_PER_SESSION_CAP = 3_500
|
|
651
|
+
DIGEST_BUDGET = 400_000 # chars per job (~100k tokens)
|
|
657
652
|
DIGEST_MAX_AGE_HOURS = 48 # older than this: not used at all
|
|
658
653
|
DIGEST_REFRESH_HOURS = 6 # cycle kicks a background refresh past this
|
|
659
654
|
DIGEST_RETRY_COOLDOWN_S = 3600 # min gap between attempts (success or not)
|
|
660
|
-
MAX_RECENT_WORK_QUERIES =
|
|
655
|
+
MAX_RECENT_WORK_QUERIES = 4 # per cycle; X search is budgeted (twitter_scan.py)
|
|
661
656
|
RECENT_WORK_TOPIC_PREFIX = "recent work: "
|
|
662
657
|
|
|
663
658
|
DIGEST_SCHEMA = {
|
|
@@ -841,26 +836,43 @@ def run_digest(ns) -> int:
|
|
|
841
836
|
if not sessions:
|
|
842
837
|
print("[digest] no eligible human sessions in window", file=sys.stderr)
|
|
843
838
|
return 1
|
|
844
|
-
#
|
|
845
|
-
#
|
|
846
|
-
for
|
|
847
|
-
|
|
848
|
-
half = DIGEST_PER_SESSION_CAP // 2
|
|
849
|
-
s["body"] = s["body"][:half] + "\n\n[... elided ...]\n\n" + s["body"][-half:]
|
|
850
|
-
batch = chunk_by_budget(sessions, DIGEST_BUDGET)[0]
|
|
839
|
+
# Every session goes in whole. A window bigger than one job's budget
|
|
840
|
+
# is split across jobs and the items are merged, so nothing is trimmed
|
|
841
|
+
# and nothing is dropped for being older than the newest few sessions.
|
|
842
|
+
batches = chunk_by_budget(sessions, DIGEST_BUDGET)
|
|
851
843
|
print(f"[digest] {datetime.now().isoformat(timespec='seconds')} "
|
|
852
|
-
f"{len(sessions)} sessions in {ns.days}d,
|
|
844
|
+
f"{len(sessions)} sessions in {ns.days}d, "
|
|
845
|
+
f"{sum(len(s['body']) for s in sessions):,} chars -> {len(batches)} job(s)",
|
|
853
846
|
file=sys.stderr)
|
|
854
|
-
prompt = build_digest_prompt(batch)
|
|
855
847
|
if ns.dry_run:
|
|
856
848
|
out = state_dir() / "recent_work.last_prompt.txt"
|
|
849
|
+
prompt = build_digest_prompt(batches[0])
|
|
857
850
|
out.write_text(prompt)
|
|
858
|
-
|
|
851
|
+
for n, b in enumerate(batches, 1):
|
|
852
|
+
print(f"[digest] job {n}/{len(batches)}: {len(b)} sessions, "
|
|
853
|
+
f"{sum(len(s['body']) for s in b):,} chars", file=sys.stderr)
|
|
854
|
+
print(f"[digest] dry-run: job-1 prompt ({len(prompt):,} chars) -> {out}", file=sys.stderr)
|
|
859
855
|
return 0
|
|
860
|
-
|
|
861
|
-
|
|
856
|
+
items: list[dict] = []
|
|
857
|
+
seen_titles: set[str] = set()
|
|
858
|
+
digested: list[dict] = []
|
|
859
|
+
for n, batch in enumerate(batches, 1):
|
|
860
|
+
obj = _run_digest_job(build_digest_prompt(batch), ns.timeout)
|
|
861
|
+
if obj is None:
|
|
862
|
+
print(f"[digest] job {n}/{len(batches)} failed; continuing", file=sys.stderr)
|
|
863
|
+
continue
|
|
864
|
+
digested.extend(batch)
|
|
865
|
+
for i in (obj.get("items") or []):
|
|
866
|
+
if not (isinstance(i, dict) and i.get("title")):
|
|
867
|
+
continue
|
|
868
|
+
key = " ".join(str(i["title"]).lower().split())
|
|
869
|
+
if key in seen_titles:
|
|
870
|
+
continue
|
|
871
|
+
seen_titles.add(key)
|
|
872
|
+
items.append(i)
|
|
873
|
+
if not digested:
|
|
862
874
|
return 1
|
|
863
|
-
|
|
875
|
+
batch = digested
|
|
864
876
|
payload = {
|
|
865
877
|
"generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
866
878
|
"window_days": ns.days,
|
|
@@ -956,11 +968,16 @@ def recent_work_block() -> str:
|
|
|
956
968
|
return ""
|
|
957
969
|
lines = [
|
|
958
970
|
"## RECENT WORK (what the account holder actually did in the last few days)",
|
|
959
|
-
"First-hand, current, and true.
|
|
960
|
-
f"\"{RECENT_WORK_TOPIC_PREFIX.strip()}\"
|
|
961
|
-
"
|
|
962
|
-
"
|
|
963
|
-
"
|
|
971
|
+
"First-hand, current, and true. A candidate whose `Search query` starts with "
|
|
972
|
+
f"\"{RECENT_WORK_TOPIC_PREFIX.strip()}\" was found by a keyword search for the matching item "
|
|
973
|
+
"below, so the keyword match is NOT evidence of fit. Use an item ONLY when the thread "
|
|
974
|
+
"itself is about that item's subject (the same problem, tool, or claim), so the story "
|
|
975
|
+
"answers what the author actually said. If the thread only shares a keyword (a "
|
|
976
|
+
"changelog, a launch, a product pitch, a different problem), REJECT the candidate as "
|
|
977
|
+
"off-topic instead of bending the story to fit; the reviewer rejects those every time. "
|
|
978
|
+
"Tell each story at most ONCE: if your recent replies already used an item's anecdote, "
|
|
979
|
+
"do not reuse it. Cite only the specifics listed here; do not embellish numbers or "
|
|
980
|
+
"invent outcomes. Never name private people or clients.",
|
|
964
981
|
"",
|
|
965
982
|
]
|
|
966
983
|
for it in items:
|
|
@@ -54,6 +54,13 @@ def enrich_one(tweet):
|
|
|
54
54
|
tweet["replies"] = t.get("replies", tweet.get("replies", 0))
|
|
55
55
|
tweet["bookmarks"] = t.get("bookmarks", tweet.get("bookmarks", 0))
|
|
56
56
|
tweet["handle"] = author.get("screen_name", handle)
|
|
57
|
+
# Full post body. The browser scrape reads X's search-result card,
|
|
58
|
+
# which X collapses behind "Show more" (~280 chars) for long posts, so
|
|
59
|
+
# the scraped text stops mid-sentence. fxtwitter returns the whole
|
|
60
|
+
# post; take it whenever it is present so the drafter reads all of it.
|
|
61
|
+
full_text = (t.get("text") or "").strip()
|
|
62
|
+
if full_text:
|
|
63
|
+
tweet["text"] = full_text
|
|
57
64
|
|
|
58
65
|
tweet["tweet_url"] = url
|
|
59
66
|
tweet.setdefault("text", tweet.get("tweetText", tweet.get("tweet_text", "")))
|
|
@@ -199,21 +199,21 @@ def _event_line(e: dict) -> str:
|
|
|
199
199
|
label = ("moderation context"
|
|
200
200
|
if str(e.get("decision") or "").startswith("platform_")
|
|
201
201
|
else "user note")
|
|
202
|
-
line += f"\n {label}: {note
|
|
202
|
+
line += f"\n {label}: {note}"
|
|
203
203
|
tweet = (e.get("tweet_text") or "").strip()
|
|
204
204
|
if tweet:
|
|
205
|
-
line += f"\n their post was: {tweet
|
|
205
|
+
line += f"\n their post was: {tweet}"
|
|
206
206
|
draft = (e.get("draft_text") or "").strip()
|
|
207
207
|
original = (e.get("original_text") or "").strip()
|
|
208
208
|
if original and draft and original != draft:
|
|
209
209
|
# Edited approval: show the diff pair, the strongest style evidence
|
|
210
210
|
# we have (draft_text carries the FINAL text the user actually posted).
|
|
211
|
-
line += f"\n our ORIGINAL draft was: {original
|
|
212
|
-
line += f"\n user REWROTE it to: {draft
|
|
211
|
+
line += f"\n our ORIGINAL draft was: {original}"
|
|
212
|
+
line += f"\n user REWROTE it to: {draft}"
|
|
213
213
|
elif draft:
|
|
214
|
-
line += f"\n our draft was: {draft
|
|
214
|
+
line += f"\n our draft was: {draft}"
|
|
215
215
|
if dc and show_unchosen:
|
|
216
|
-
line += f"\n the draft they did NOT pick was: {(dc.get('unchosen_text') or '')
|
|
216
|
+
line += f"\n the draft they did NOT pick was: {(dc.get('unchosen_text') or '')}"
|
|
217
217
|
if dc.get("style") or dc.get("unchosen_style"):
|
|
218
218
|
line += (
|
|
219
219
|
f"\n styles: picked={dc.get('style') or '?'}"
|
|
@@ -256,7 +256,7 @@ def build_prompt(project: dict, events: list[dict], overall_events: list[dict] |
|
|
|
256
256
|
overall_block = ""
|
|
257
257
|
if overall_events:
|
|
258
258
|
notes = "\n".join(
|
|
259
|
-
f"{i + 1}. {(e.get('reject_note') or '').strip()
|
|
259
|
+
f"{i + 1}. {(e.get('reject_note') or '').strip()}"
|
|
260
260
|
for i, e in enumerate(overall_events)
|
|
261
261
|
)
|
|
262
262
|
overall_block = (
|
|
@@ -95,7 +95,12 @@ def main():
|
|
|
95
95
|
"bookmarks": t.get("bookmarks", 0),
|
|
96
96
|
}
|
|
97
97
|
t0 = {"likes": l0 or 0, "retweets": r0 or 0, "replies": p0 or 0, "views": v0 or 0, "bookmarks": b0 or 0}
|
|
98
|
-
|
|
98
|
+
# Full tweet body. The scan reads X's search-result card, which X
|
|
99
|
+
# collapses behind "Show more" for long posts (~280 chars), so the
|
|
100
|
+
# stored tweet_text is cut mid-sentence. fxtwitter returns the whole
|
|
101
|
+
# post, so restamp it here and the drafter reads the real thing.
|
|
102
|
+
full_text = (t.get("text") or "").strip()
|
|
103
|
+
return (cid, url, t1, compute_delta(t0, t1), full_text)
|
|
99
104
|
|
|
100
105
|
with ThreadPoolExecutor(max_workers=8) as ex:
|
|
101
106
|
results = list(ex.map(fetch_row, rows))
|
|
@@ -103,12 +108,13 @@ def main():
|
|
|
103
108
|
for result in results:
|
|
104
109
|
if result is None:
|
|
105
110
|
continue
|
|
106
|
-
cid, url, t1, delta = result
|
|
111
|
+
cid, url, t1, delta, full_text = result
|
|
107
112
|
try:
|
|
108
113
|
api_patch(
|
|
109
114
|
"/api/v1/twitter-candidates/by-id",
|
|
110
115
|
{
|
|
111
116
|
"id": cid,
|
|
117
|
+
**({"tweet_text": full_text} if full_text else {}),
|
|
112
118
|
"action": "set_t1",
|
|
113
119
|
"likes_t1": t1["likes"],
|
|
114
120
|
"retweets_t1": t1["retweets"],
|
package/scripts/post_reddit.py
CHANGED
|
@@ -1212,11 +1212,6 @@ no candidate lines, no commentary about thread content (you don't see any).
|
|
|
1212
1212
|
"""
|
|
1213
1213
|
|
|
1214
1214
|
|
|
1215
|
-
def _truncate(s, n):
|
|
1216
|
-
s = s or ""
|
|
1217
|
-
return s if len(s) <= n else s[:n] + "..."
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
1215
|
def _prefetch_thread_digests(candidates, reddit_username=None):
|
|
1221
1216
|
"""Pre-fetch thread content for the draft prompt (2026-07-14).
|
|
1222
1217
|
|
|
@@ -1268,15 +1263,15 @@ def _prefetch_thread_digests(candidates, reddit_username=None):
|
|
|
1268
1263
|
]
|
|
1269
1264
|
selftext = (thread.get("selftext") or "").strip()
|
|
1270
1265
|
if selftext:
|
|
1271
|
-
lines.append(
|
|
1266
|
+
lines.append(selftext)
|
|
1272
1267
|
already = False
|
|
1273
1268
|
if comments:
|
|
1274
1269
|
lines.append("top comments:")
|
|
1275
|
-
for cm in comments
|
|
1270
|
+
for cm in comments:
|
|
1276
1271
|
author = cm.get("author") or ""
|
|
1277
1272
|
if our_name and author.lower() == our_name:
|
|
1278
1273
|
already = True
|
|
1279
|
-
body =
|
|
1274
|
+
body = (cm.get("body") or "").strip().replace("\n", " ")
|
|
1280
1275
|
lines.append(f" u/{author} ({cm.get('score', 0)}): {body}")
|
|
1281
1276
|
if already:
|
|
1282
1277
|
lines.append("NOTE: one of OUR accounts already commented in this"
|
|
@@ -230,7 +230,7 @@ _TIMELINE_JS_TMPL = r"""(function(){
|
|
|
230
230
|
// reply in the same conversation cell; remember it. On the posts tab it
|
|
231
231
|
// is a repost/quote we simply skip (WITH_PARENTS=false there).
|
|
232
232
|
if(WITH_PARENTS && text){
|
|
233
|
-
lastOther={author:'@'+authorHandle,text:text
|
|
233
|
+
lastOther={author:'@'+authorHandle,text:text,url:url};
|
|
234
234
|
}
|
|
235
235
|
continue;
|
|
236
236
|
}
|
|
@@ -163,10 +163,14 @@ def cmd_stamp_cycle_variant(batch_id: str, variant: str) -> int:
|
|
|
163
163
|
|
|
164
164
|
def _sanitize(s) -> str:
|
|
165
165
|
"""Mirror the SQL `REPLACE(REPLACE(..., E'\n', ' '), E'\r', ' ')` so a
|
|
166
|
-
multi-line tweet/draft body doesn't break the pipe-delimited row format.
|
|
166
|
+
multi-line tweet/draft body doesn't break the pipe-delimited row format.
|
|
167
|
+
|
|
168
|
+
A literal "|" is swapped for the look-alike "\u2502": the cycle shell
|
|
169
|
+
splits each row on "|", so a pipe inside the tweet used to cut the text
|
|
170
|
+
there and shift every later column."""
|
|
167
171
|
if s is None:
|
|
168
172
|
return ""
|
|
169
|
-
return str(s).replace("\n", " ").replace("\r", " ")
|
|
173
|
+
return str(s).replace("\n", " ").replace("\r", " ").replace("|", "\u2502")
|
|
170
174
|
|
|
171
175
|
|
|
172
176
|
def cmd_candidates(batch_id: str) -> int:
|
|
@@ -238,14 +242,16 @@ def cmd_candidates(batch_id: str) -> int:
|
|
|
238
242
|
return (int(r.get("likes") or 0) >= 1
|
|
239
243
|
or int(r.get("author_followers") or 0) >= 1000)
|
|
240
244
|
|
|
245
|
+
# The floor applies to EVERY recent-work row, inside the top 25 too: in a
|
|
246
|
+
# low-virality pool the top 25 is effectively everything, so a 7-follower,
|
|
247
|
+
# 0-like reply was reaching the drafter (2026-11-17).
|
|
248
|
+
def _is_rw(r):
|
|
249
|
+
return str(r.get("search_topic") or "").startswith("recent work: ")
|
|
250
|
+
|
|
251
|
+
rows = [r for r in rows if not _is_rw(r) or _rw_floor(r)]
|
|
241
252
|
top = rows[:25]
|
|
242
253
|
top_ids = {r.get("id") for r in top}
|
|
243
|
-
extra = [
|
|
244
|
-
r for r in rows
|
|
245
|
-
if r.get("id") not in top_ids
|
|
246
|
-
and str(r.get("search_topic") or "").startswith("recent work: ")
|
|
247
|
-
and _rw_floor(r)
|
|
248
|
-
][:5]
|
|
254
|
+
extra = [r for r in rows if r.get("id") not in top_ids and _is_rw(r)][:5]
|
|
249
255
|
rows = top + extra
|
|
250
256
|
|
|
251
257
|
for r in rows:
|
package/scripts/twitter_scan.py
CHANGED
|
@@ -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:
|
|
@@ -170,7 +170,7 @@ def format_examples(scan: dict, top: int, min_chars: int) -> list[str]:
|
|
|
170
170
|
note = _stats_note(r, total, "replies")
|
|
171
171
|
parent = r.get("parent") or {}
|
|
172
172
|
if parent.get("text"):
|
|
173
|
-
ptxt = " ".join(parent["text"].split())
|
|
173
|
+
ptxt = " ".join(parent["text"].split())
|
|
174
174
|
note += f'; replying to {parent.get("author") or "someone"}: "{ptxt}"'
|
|
175
175
|
out.append(f'"{text}" (their real reply, {note})')
|
|
176
176
|
return out
|
|
@@ -200,7 +200,7 @@ def format_corpus_section(scan: dict, top: int, min_chars: int) -> str:
|
|
|
200
200
|
for r in replies:
|
|
201
201
|
parent = r.get("parent") or {}
|
|
202
202
|
if parent.get("text"):
|
|
203
|
-
ptxt = " ".join(parent["text"].split())
|
|
203
|
+
ptxt = " ".join(parent["text"].split())
|
|
204
204
|
lines.append(f'- {parent.get("author") or "someone"} wrote: "{ptxt}"')
|
|
205
205
|
lines.append(f" their reply ({_stats_note(r, int(counts.get('comments') or len(replies)), 'replies')}): {r.get('text', '').strip()}")
|
|
206
206
|
else:
|
|
@@ -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
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
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)"
|