@m13v/s4l 1.7.12-rc.10 → 1.7.12-rc.12
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/index.js +79 -36
- package/mcp/dist/runtime.js +1 -1
- package/mcp/dist/version.json +2 -2
- package/mcp/manifest.json +1 -1
- package/mcp/menubar/s4l_menubar.py +5 -0
- package/mcp/menubar/s4l_state.py +122 -24
- package/mcp/package.json +1 -1
- package/package.json +1 -1
- package/scripts/claude_job.py +12 -0
- package/scripts/context_mining.py +382 -0
- package/scripts/draft_prompt_core.py +16 -2
- package/scripts/s4l_mode.py +41 -0
- package/scripts/schedule_state.py +5 -0
- package/scripts/twitter_cycle_helper.py +19 -1
- package/skill/run-twitter-cycle.sh +43 -1
- package/scripts/s4l_halt.sh +0 -102
package/mcp/dist/index.js
CHANGED
|
@@ -23,7 +23,7 @@ import { repoDir, runPython, run, readPlan, writePlan, planPath, TMP_DIR, } from
|
|
|
23
23
|
import { applySetup, resolveProject, hasReadyProject, personaReady, listManagedProjectStatus, listProjectSettings, ensureShortLinksDefault, ensurePersonaProject, findPersonaProject, REQUIRED_FIELDS, RECOMMENDED_FIELDS, configPath, ensureConfigInStateDir, normalizeStringList, recordRedditAccount, } from "./setup.js";
|
|
24
24
|
import { xStatus, xConnect, xDetectSources, xScanProfile, summarizeXAuth } from "./twitterAuth.js";
|
|
25
25
|
import { redditStatus, redditConnect, redditDetectSources, summarizeRedditAuth, } from "./redditAuth.js";
|
|
26
|
-
import { startProvisioning, isProvisioning, readProgress, runtimeReady, readRuntime, resolvePython, resolveChrome, ensureMenubar, menubarRunning, clearMenubarStop, ensurePipelineCurrent, ensureRuntimeProvisioned, ensureHarnessPatched, retryProvisionIfStalled, } from "./runtime.js";
|
|
26
|
+
import { startProvisioning, isProvisioning, readProgress, runtimeReady, readRuntime, resolvePython, resolveChrome, ensureMenubar, menubarRunning, clearMenubarStop, ensurePipelineCurrent, ensureRuntimeProvisioned, ensureHarnessPatched, retryProvisionIfStalled, menubarSourceDir, } from "./runtime.js";
|
|
27
27
|
import { blockOnboardingMilestone, completeOnboardingMilestone, ensureDoctorPhase, onboardingLedger, onboardingSnapshot, recordOnboardingAttempt, runDoctorPhase, } from "./onboarding.js";
|
|
28
28
|
import { VERSION, versionStatus, latestPublishedVersion } from "./version.js";
|
|
29
29
|
import { initSentry, sendHeartbeat, sendStateSnapshot, captureError, captureMessage, flushSentry, startLogStreaming, flushLogs, logLine, checkVersionChange } from "./telemetry.js";
|
|
@@ -3690,9 +3690,12 @@ tool("queue_setup", {
|
|
|
3690
3690
|
writeDraftProvider("claude-desktop-queue", "queue_setup(claude)");
|
|
3691
3691
|
ensureQueueWorkerToolsAllowed();
|
|
3692
3692
|
// Re-arming the autopilot is an explicit "start S4L" action: lift a prior
|
|
3693
|
-
// tray Quit
|
|
3694
|
-
// async — task specs must return
|
|
3693
|
+
// tray Quit (which is Pause + tray removal) so the pipeline and the review
|
|
3694
|
+
// cards come back. Best-effort and async — task specs must return
|
|
3695
|
+
// regardless of tray state.
|
|
3695
3696
|
clearMenubarStop();
|
|
3697
|
+
if (isPaused())
|
|
3698
|
+
void resumeS4L();
|
|
3696
3699
|
void ensureMenubar();
|
|
3697
3700
|
// Write each worker's canonical SKILL.md to disk NOW, before the agent calls
|
|
3698
3701
|
// create_scheduled_task. The host's create_scheduled_task can report a task
|
|
@@ -4854,6 +4857,10 @@ const PAUSE_TARGETS = [
|
|
|
4854
4857
|
{ tag: "claude-reaper", label: REAPER_LABEL, plist: REAPER_PLIST, ensure: ensureClaudeReaperInstalled },
|
|
4855
4858
|
{ tag: "stall-watch", label: STALL_WATCH_LABEL, plist: STALL_WATCH_PLIST, ensure: ensureStallWatchInstalled },
|
|
4856
4859
|
{ tag: "memory-snapshot", label: MEMORY_SNAPSHOT_LABEL, plist: MEMORY_SNAPSHOT_PLIST, ensure: ensureMemorySnapshotInstalled },
|
|
4860
|
+
// The harness overlay watcher attaches to the harness Chrome over CDP; with the
|
|
4861
|
+
// kickers unloaded it has nothing to show, and reinstalling it at every boot
|
|
4862
|
+
// while paused re-attached to a browser the user had deliberately stopped.
|
|
4863
|
+
{ tag: "overlay-watch", label: OVERLAY_WATCH_LABEL, plist: OVERLAY_WATCH_PLIST, ensure: ensureOverlayWatchInstalled },
|
|
4857
4864
|
];
|
|
4858
4865
|
// Mirror the pausable label set into the state dir for the menubar's Python
|
|
4859
4866
|
// pause/resume (which can't import this module). Written at boot and on every
|
|
@@ -4867,39 +4874,80 @@ function writePauseTargetsManifest() {
|
|
|
4867
4874
|
/* best-effort */
|
|
4868
4875
|
}
|
|
4869
4876
|
}
|
|
4870
|
-
|
|
4871
|
-
|
|
4872
|
-
|
|
4873
|
-
|
|
4877
|
+
// THE one stop switch is menubar/s4l_state.py pause_s4l()/resume_s4l(): the
|
|
4878
|
+
// tray and dashboard_server.py need it with Claude Desktop closed, so the
|
|
4879
|
+
// mechanics (flag, dynamic sweep of every S4L LaunchAgent, harness browsers)
|
|
4880
|
+
// live there once and this is a thin shell-out. PAUSE_TARGETS above is still
|
|
4881
|
+
// the registry it reads (via pause-targets.json) and the set Resume re-ensures
|
|
4882
|
+
// so each daemon's install gates re-apply.
|
|
4883
|
+
function runPauseSwitch(action) {
|
|
4884
|
+
const dir = menubarSourceDir();
|
|
4885
|
+
if (!dir)
|
|
4886
|
+
return { ok: false, detail: "menubar/s4l_state.py not found" };
|
|
4874
4887
|
try {
|
|
4875
|
-
|
|
4876
|
-
|
|
4888
|
+
const out = execFileSync(resolvePython(), [path.join(dir, "s4l_state.py"), action], {
|
|
4889
|
+
encoding: "utf-8",
|
|
4890
|
+
timeout: 120_000,
|
|
4891
|
+
env: { ...process.env, S4L_STATE_DIR: s4lStateDir() },
|
|
4892
|
+
});
|
|
4893
|
+
const res = JSON.parse(out.trim().split("\n").pop() || "{}");
|
|
4894
|
+
return { ok: !!res.ok, detail: String(res.detail || "") };
|
|
4877
4895
|
}
|
|
4878
4896
|
catch (e) {
|
|
4879
|
-
return { ok: false, detail: `
|
|
4880
|
-
}
|
|
4881
|
-
const uid = process.getuid ? process.getuid() : 0;
|
|
4882
|
-
const results = [];
|
|
4883
|
-
for (const { label, plist } of PAUSE_TARGETS) {
|
|
4884
|
-
try {
|
|
4885
|
-
const res = await unloadPlist(label, plist, uid);
|
|
4886
|
-
results.push(`${label}: unloaded (rc=${res.code})`);
|
|
4887
|
-
}
|
|
4888
|
-
catch (e) {
|
|
4889
|
-
results.push(`${label}: ${e?.message || e}`);
|
|
4890
|
-
}
|
|
4897
|
+
return { ok: false, detail: `s4l_state.py ${action}: ${e?.message || e}` };
|
|
4891
4898
|
}
|
|
4892
|
-
return { ok: true, detail: results.join("; ") };
|
|
4893
4899
|
}
|
|
4894
|
-
async function
|
|
4900
|
+
async function pauseS4L() {
|
|
4901
|
+
if (isPaused())
|
|
4902
|
+
return { ok: true, detail: "already paused" };
|
|
4903
|
+
writePauseTargetsManifest();
|
|
4904
|
+
return runPauseSwitch("pause");
|
|
4905
|
+
}
|
|
4906
|
+
// Resume only reloads launchd. Drafting ALSO needs the host's s4l-worker
|
|
4907
|
+
// scheduled task, which Resume cannot touch (only the host's scheduled-task
|
|
4908
|
+
// tools can). The task keeps firing through a pause, so a schedule that is not
|
|
4909
|
+
// 'ok' right after Resume is a real fault, never pause residue: without this
|
|
4910
|
+
// check Resume reported ok while cycles scanned, enqueued, and nothing drafted
|
|
4911
|
+
// (operator Mac, 2026-11-16: worker task disabled, read as 'stalled').
|
|
4912
|
+
async function draftScheduleAfterResume() {
|
|
4913
|
+
let state = "missing";
|
|
4914
|
+
let disabled = [];
|
|
4895
4915
|
try {
|
|
4896
|
-
|
|
4916
|
+
const res = await runPython("scripts/schedule_state.py", [], { timeoutMs: 15_000 });
|
|
4917
|
+
const parsed = JSON.parse(res.stdout.trim());
|
|
4918
|
+
if (["ok", "disabled", "stalled", "missing"].includes(parsed.state))
|
|
4919
|
+
state = parsed.state;
|
|
4920
|
+
disabled = (parsed.detail?.registries || [])
|
|
4921
|
+
.filter((r) => r.has_workers && r.enabled === false)
|
|
4922
|
+
.map((r) => String(r.path));
|
|
4897
4923
|
}
|
|
4898
4924
|
catch {
|
|
4899
|
-
/*
|
|
4900
|
-
}
|
|
4925
|
+
/* unreadable -> treated as missing, same as scheduleState() */
|
|
4926
|
+
}
|
|
4927
|
+
if (state === "ok")
|
|
4928
|
+
return { schedule_state: state };
|
|
4929
|
+
const why = disabled.length
|
|
4930
|
+
? `the s4l-worker scheduled task is DISABLED in ${disabled.join(", ")}`
|
|
4931
|
+
: state === "missing"
|
|
4932
|
+
? "no s4l-worker scheduled task is registered for the active Claude account"
|
|
4933
|
+
: state === "disabled"
|
|
4934
|
+
? "the s4l-worker scheduled task is disabled"
|
|
4935
|
+
: "the s4l-worker scheduled task is enabled but has not fired recently";
|
|
4936
|
+
return {
|
|
4937
|
+
schedule_state: state,
|
|
4938
|
+
warning: `Launchd lanes are resumed, but drafting is NOT: ${why}. Cycles will scan and enqueue ` +
|
|
4939
|
+
"jobs that nothing drafts until this is fixed.",
|
|
4940
|
+
next_step: state === "missing"
|
|
4941
|
+
? "Call queue_setup and create the returned task with create_scheduled_task."
|
|
4942
|
+
: "Call the host tool list_scheduled_tasks; if s4l-worker shows enabled:false, call " +
|
|
4943
|
+
"update_scheduled_task {taskId:'s4l-worker', enabled:true, notifyOnCompletion:false}. If it " +
|
|
4944
|
+
"is already enabled, the host scheduler is wedged: fully quit and reopen Claude Desktop. " +
|
|
4945
|
+
"Then call dashboard and confirm schedule_state 'ok'.",
|
|
4946
|
+
};
|
|
4947
|
+
}
|
|
4948
|
+
async function resumeS4L() {
|
|
4901
4949
|
writePauseTargetsManifest();
|
|
4902
|
-
const results = [];
|
|
4950
|
+
const results = [runPauseSwitch("resume").detail];
|
|
4903
4951
|
for (const t of PAUSE_TARGETS) {
|
|
4904
4952
|
try {
|
|
4905
4953
|
const r = await t.ensure();
|
|
@@ -4909,7 +4957,8 @@ async function resumeS4L() {
|
|
|
4909
4957
|
results.push(`${t.tag}: ${e?.message || e}`);
|
|
4910
4958
|
}
|
|
4911
4959
|
}
|
|
4912
|
-
|
|
4960
|
+
const sched = await draftScheduleAfterResume();
|
|
4961
|
+
return { ok: sched.schedule_state === "ok", detail: results.join("; "), ...sched };
|
|
4913
4962
|
}
|
|
4914
4963
|
// Install/refresh the on-screen overlay watcher launchd job. Promotes the
|
|
4915
4964
|
// harness status overlay from a best-effort, fired-from-other-tools nicety to a
|
|
@@ -6237,14 +6286,8 @@ async function main() {
|
|
|
6237
6286
|
void ensureFeedbackDigestInstalled()
|
|
6238
6287
|
.then((r) => console.error(`[feedback-digest] launchd digest: ${r.ok ? "ok" : "skip"} (${r.detail})`))
|
|
6239
6288
|
.catch((e) => console.error("[feedback-digest] digest install failed:", e?.message || e));
|
|
6240
|
-
//
|
|
6241
|
-
//
|
|
6242
|
-
// it died nothing respawned it and the overlay silently vanished. Install it as
|
|
6243
|
-
// a first-class self-healing launchd job (RunAtLoad + 60s idempotent re-invoke).
|
|
6244
|
-
// Best-effort; the overlay is a nicety and must never block boot.
|
|
6245
|
-
void ensureOverlayWatchInstalled()
|
|
6246
|
-
.then((r) => console.error(`[overlay-watch] launchd supervisor: ${r.ok ? "ok" : "skip"} (${r.detail})`))
|
|
6247
|
-
.catch((e) => console.error("[overlay-watch] supervisor install failed:", e?.message || e));
|
|
6289
|
+
// The on-screen overlay watcher supervisor (KeepAlive launchd job) is installed
|
|
6290
|
+
// through PAUSE_TARGETS above, so a Pause unloads it and a paused boot skips it.
|
|
6248
6291
|
// Silent daily self-updates are banned (user decision 2026-07-31): the job
|
|
6249
6292
|
// restarted Claude Desktop unattended. Clean it off every box that got it
|
|
6250
6293
|
// from v1.7.1..v1.7.7-rc.4. Best-effort; never blocks boot.
|
package/mcp/dist/runtime.js
CHANGED
|
@@ -1226,7 +1226,7 @@ async function provision(progress) {
|
|
|
1226
1226
|
// The bundled menu bar source: <ext>/menubar in a packed .mcpb (dist/runtime.js
|
|
1227
1227
|
// -> ../menubar), the same path for a tsc dev build (mcp/dist -> mcp/menubar),
|
|
1228
1228
|
// and the repo clone for an npm install.
|
|
1229
|
-
function menubarSourceDir() {
|
|
1229
|
+
export function menubarSourceDir() {
|
|
1230
1230
|
const candidates = [
|
|
1231
1231
|
path.join(__dirname, "..", "menubar"),
|
|
1232
1232
|
path.join(resolveRepoDir(), "mcp", "menubar"),
|
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.12",
|
|
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": {
|
|
@@ -1655,6 +1655,11 @@ class S4LMenuBar(rumps.App):
|
|
|
1655
1655
|
fh.write(f"user quit via menu bar at {time.strftime('%Y-%m-%dT%H:%M:%S%z')}\n")
|
|
1656
1656
|
except Exception as e:
|
|
1657
1657
|
_capture(e, action="quit_stop_flag")
|
|
1658
|
+
# Quit is Pause plus removing the tray: every S4L LaunchAgent and
|
|
1659
|
+
# harness browser goes down through the one switch
|
|
1660
|
+
# (st.pause_s4l) before Claude restarts, so the relaunched MCP
|
|
1661
|
+
# boots paused instead of reinstalling the pipeline daemons.
|
|
1662
|
+
st.pause_s4l()
|
|
1658
1663
|
self._quit_claude_and_wait()
|
|
1659
1664
|
self._remove_scheduled_tasks()
|
|
1660
1665
|
self._prune_session_index()
|
package/mcp/menubar/s4l_state.py
CHANGED
|
@@ -85,31 +85,39 @@ def state_dir() -> str:
|
|
|
85
85
|
)
|
|
86
86
|
|
|
87
87
|
|
|
88
|
-
# ---- pause/resume:
|
|
89
|
-
#
|
|
90
|
-
#
|
|
91
|
-
#
|
|
92
|
-
#
|
|
93
|
-
#
|
|
94
|
-
#
|
|
95
|
-
#
|
|
96
|
-
#
|
|
97
|
-
#
|
|
98
|
-
#
|
|
99
|
-
#
|
|
100
|
-
#
|
|
101
|
-
# (
|
|
102
|
-
#
|
|
103
|
-
#
|
|
104
|
-
#
|
|
105
|
-
#
|
|
88
|
+
# ---- pause/resume: THE one stop switch -------------------------------------
|
|
89
|
+
# One behaviour, implemented once. Pause stops all of S4L's background work:
|
|
90
|
+
# every loaded S4L LaunchAgent (index.ts's PAUSE_TARGETS pipeline daemons plus
|
|
91
|
+
# whatever fleet jobs a box carries: linkedin/github/instagram/stats/audits/
|
|
92
|
+
# backfills/browser-watch) except the tray + dashboard, then the harness
|
|
93
|
+
# browsers (Chrome on CDP 955x under ~/.claude/browser-profiles) and their
|
|
94
|
+
# browser_harness daemons: a harness window being activated over CDP is what
|
|
95
|
+
# yanks a fullscreen app out of focus (2026-11-05). Claude Desktop, the tray and
|
|
96
|
+
# the draft schedule registration stay up; claude_job.py's `next` sees the flag
|
|
97
|
+
# and reports no work; nothing is deleted. The labels actually unloaded are
|
|
98
|
+
# recorded in <state>/paused-labels.json so Resume reloads exactly that set
|
|
99
|
+
# (index.ts's resumeS4L then re-runs its PAUSE_TARGETS ensure*Installed() so
|
|
100
|
+
# their install gates re-apply). It lives HERE, not in index.ts, because the
|
|
101
|
+
# tray (s4l_menubar.py) and dashboard_server.py must work with Claude Desktop
|
|
102
|
+
# closed; the MCP's pause_s4l tool shells out to `python3 s4l_state.py
|
|
103
|
+
# pause|resume` so there is no second copy of the mechanics. Quit is Pause
|
|
104
|
+
# plus removing the tray; Uninstall is the wipe (reset-test-machine.sh).
|
|
105
|
+
# PAUSE_TARGET_LABELS mirrors index.ts PAUSE_TARGETS (written to
|
|
106
|
+
# <state>/pause-targets.json at every MCP boot); it is only the fallback for a
|
|
107
|
+
# box whose MCP never wrote the manifest.
|
|
106
108
|
PAUSE_TARGET_LABELS = (
|
|
107
109
|
AUTOPILOT_LABEL,
|
|
108
110
|
"com.m13v.social-reddit-search",
|
|
109
111
|
"com.m13v.social-claude-reaper",
|
|
110
112
|
"com.m13v.social-autopilot-stall-watch",
|
|
111
113
|
"com.m13v.social-memory-snapshot",
|
|
114
|
+
"com.m13v.social-overlay-watch",
|
|
112
115
|
)
|
|
116
|
+
# What counts as S4L's, by launchd label. The tray + dashboard ride through a pause.
|
|
117
|
+
PAUSE_LABEL_PREFIXES = ("com.m13v.social-", "com.m13v.s4l-")
|
|
118
|
+
PAUSE_LABEL_EXTRA = ("com.m13v.browser-watch", "com.m13v.gmail-dwd-keepalive-s4l")
|
|
119
|
+
PAUSE_KEEP = ("com.m13v.social-autoposter.menubar", "com.m13v.social-dashboard")
|
|
120
|
+
HARNESS_PROFILES_DIR = str(Path.home() / ".claude" / "browser-profiles") + "/"
|
|
113
121
|
|
|
114
122
|
|
|
115
123
|
def pause_target_labels() -> tuple:
|
|
@@ -130,10 +138,56 @@ def pause_flag_path() -> str:
|
|
|
130
138
|
return os.path.join(state_dir(), "paused.flag")
|
|
131
139
|
|
|
132
140
|
|
|
141
|
+
def paused_labels_path() -> str:
|
|
142
|
+
return os.path.join(state_dir(), "paused-labels.json")
|
|
143
|
+
|
|
144
|
+
|
|
133
145
|
def is_paused() -> bool:
|
|
134
146
|
return os.path.exists(pause_flag_path())
|
|
135
147
|
|
|
136
148
|
|
|
149
|
+
def _is_s4l_label(label: str) -> bool:
|
|
150
|
+
return label not in PAUSE_KEEP and (
|
|
151
|
+
label.startswith(PAUSE_LABEL_PREFIXES) or label in PAUSE_LABEL_EXTRA
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _loaded_labels() -> set:
|
|
156
|
+
try:
|
|
157
|
+
out = subprocess.run(["launchctl", "list"], capture_output=True, text=True, timeout=15).stdout
|
|
158
|
+
except Exception:
|
|
159
|
+
return set()
|
|
160
|
+
labels = set()
|
|
161
|
+
for line in out.splitlines():
|
|
162
|
+
parts = line.split()
|
|
163
|
+
if len(parts) >= 3:
|
|
164
|
+
labels.add(parts[2])
|
|
165
|
+
return labels
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _harness_pids() -> list:
|
|
169
|
+
"""Harness Chrome main processes (CDP 955x + a profile under
|
|
170
|
+
~/.claude/browser-profiles, not the Helper children) and browser_harness daemons."""
|
|
171
|
+
try:
|
|
172
|
+
out = subprocess.run(["ps", "-eo", "pid=,args="], capture_output=True, text=True, timeout=15).stdout
|
|
173
|
+
except Exception:
|
|
174
|
+
return []
|
|
175
|
+
pids = []
|
|
176
|
+
for line in out.splitlines():
|
|
177
|
+
parts = line.strip().split(None, 1)
|
|
178
|
+
if len(parts) < 2 or not parts[0].isdigit():
|
|
179
|
+
continue
|
|
180
|
+
pid, args = int(parts[0]), parts[1]
|
|
181
|
+
chrome = (
|
|
182
|
+
"remote-debugging-port=955" in args
|
|
183
|
+
and "--user-data-dir=" + HARNESS_PROFILES_DIR in args
|
|
184
|
+
and "Helper" not in args
|
|
185
|
+
)
|
|
186
|
+
if chrome or "browser_harness.daemon" in args:
|
|
187
|
+
pids.append(pid)
|
|
188
|
+
return pids
|
|
189
|
+
|
|
190
|
+
|
|
137
191
|
def pause_s4l() -> dict:
|
|
138
192
|
if is_paused():
|
|
139
193
|
return {"ok": True, "paused": True, "detail": "already paused"}
|
|
@@ -144,16 +198,35 @@ def pause_s4l() -> dict:
|
|
|
144
198
|
except Exception as e:
|
|
145
199
|
return {"ok": False, "paused": is_paused(), "detail": f"could not write pause flag: {e}"}
|
|
146
200
|
uid = os.getuid()
|
|
147
|
-
|
|
148
|
-
for
|
|
201
|
+
loaded = _loaded_labels()
|
|
202
|
+
labels = sorted(set(pause_target_labels()) | {l for l in loaded if _is_s4l_label(l)})
|
|
203
|
+
unloaded, results = [], []
|
|
204
|
+
for label in labels:
|
|
205
|
+
if label not in loaded:
|
|
206
|
+
continue
|
|
149
207
|
try:
|
|
150
208
|
subprocess.run(
|
|
151
209
|
["launchctl", "bootout", f"gui/{uid}/{label}"],
|
|
152
210
|
capture_output=True, timeout=15,
|
|
153
211
|
)
|
|
154
|
-
|
|
212
|
+
unloaded.append(label)
|
|
155
213
|
except Exception as e:
|
|
156
214
|
results.append(f"{label}: {e}")
|
|
215
|
+
try:
|
|
216
|
+
with open(paused_labels_path(), "w") as fh:
|
|
217
|
+
json.dump({"labels": unloaded}, fh)
|
|
218
|
+
fh.write("\n")
|
|
219
|
+
except Exception as e:
|
|
220
|
+
results.append(f"could not write paused-labels.json: {e}")
|
|
221
|
+
killed = []
|
|
222
|
+
for pid in _harness_pids():
|
|
223
|
+
try:
|
|
224
|
+
os.kill(pid, 15)
|
|
225
|
+
killed.append(pid)
|
|
226
|
+
except Exception:
|
|
227
|
+
pass
|
|
228
|
+
results.insert(0, f"unloaded {len(unloaded)} LaunchAgents")
|
|
229
|
+
results.append("harness processes stopped: " + (" ".join(map(str, killed)) if killed else "none"))
|
|
157
230
|
return {"ok": True, "paused": True, "detail": "; ".join(results)}
|
|
158
231
|
|
|
159
232
|
|
|
@@ -164,10 +237,19 @@ def resume_s4l() -> dict:
|
|
|
164
237
|
pass
|
|
165
238
|
except Exception:
|
|
166
239
|
pass
|
|
240
|
+
recorded = []
|
|
241
|
+
try:
|
|
242
|
+
data = json.loads(Path(paused_labels_path()).read_text())
|
|
243
|
+
recorded = [l for l in data.get("labels", []) if isinstance(l, str)]
|
|
244
|
+
except Exception:
|
|
245
|
+
pass
|
|
167
246
|
uid = os.getuid()
|
|
168
247
|
la_dir = str(Path.home() / "Library" / "LaunchAgents")
|
|
169
|
-
|
|
170
|
-
|
|
248
|
+
loaded = _loaded_labels()
|
|
249
|
+
reloaded, results = 0, []
|
|
250
|
+
for label in sorted(set(recorded) | set(pause_target_labels())):
|
|
251
|
+
if label in loaded:
|
|
252
|
+
continue
|
|
171
253
|
plist = os.path.join(la_dir, f"{label}.plist")
|
|
172
254
|
if not os.path.exists(plist):
|
|
173
255
|
results.append(f"{label}: no plist, skip")
|
|
@@ -178,9 +260,17 @@ def resume_s4l() -> dict:
|
|
|
178
260
|
["launchctl", "bootstrap", f"gui/{uid}", plist],
|
|
179
261
|
capture_output=True, timeout=15,
|
|
180
262
|
)
|
|
181
|
-
|
|
263
|
+
if r.returncode == 0:
|
|
264
|
+
reloaded += 1
|
|
265
|
+
else:
|
|
266
|
+
results.append(f"{label}: rc={r.returncode}")
|
|
182
267
|
except Exception as e:
|
|
183
268
|
results.append(f"{label}: {e}")
|
|
269
|
+
try:
|
|
270
|
+
os.remove(paused_labels_path())
|
|
271
|
+
except Exception:
|
|
272
|
+
pass
|
|
273
|
+
results.insert(0, f"reloaded {reloaded} LaunchAgents; harness browsers relaunch on demand")
|
|
184
274
|
return {"ok": True, "paused": is_paused(), "detail": "; ".join(results)}
|
|
185
275
|
|
|
186
276
|
|
|
@@ -1695,3 +1785,11 @@ def _outbox_remove(shipped_uuids, keep_only_valid=False):
|
|
|
1695
1785
|
os.replace(str(tmp), str(p))
|
|
1696
1786
|
except Exception:
|
|
1697
1787
|
pass
|
|
1788
|
+
|
|
1789
|
+
|
|
1790
|
+
# CLI for the MCP's pause_s4l tool (index.ts shells out here so the mechanics
|
|
1791
|
+
# above exist once): `python3 s4l_state.py pause|resume|status` prints one JSON line.
|
|
1792
|
+
if __name__ == "__main__":
|
|
1793
|
+
_cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
|
|
1794
|
+
_fn = {"pause": pause_s4l, "resume": resume_s4l}.get(_cmd)
|
|
1795
|
+
print(json.dumps(_fn() if _fn else {"ok": True, "paused": is_paused()}))
|
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.12",
|
|
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.12",
|
|
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",
|
package/scripts/claude_job.py
CHANGED
|
@@ -112,6 +112,10 @@ TAG_TO_TYPE = {
|
|
|
112
112
|
# TYPE_TO_WORKER_NOTES) because an installed-package worker claims with
|
|
113
113
|
# ITS copy of this map, which may predate this type.
|
|
114
114
|
"context-mining": "context-mining",
|
|
115
|
+
# Recent-work digest (2026-11-17): context_mining.py `digest`, same
|
|
116
|
+
# tool-free shape, different schema ({"items": [...]}), personal_brand
|
|
117
|
+
# lane only, behind the recent_work_context flag.
|
|
118
|
+
"recent-work": "recent-work",
|
|
115
119
|
}
|
|
116
120
|
|
|
117
121
|
# queue type -> (activity state, label) the menu bar shows while the job is in
|
|
@@ -129,6 +133,7 @@ TYPE_TO_ACTIVITY = {
|
|
|
129
133
|
# review card itself, not in the tray.
|
|
130
134
|
"reddit-draft": ("drafting", "draft"),
|
|
131
135
|
"context-mining": ("learning", "mining context"),
|
|
136
|
+
"recent-work": ("learning", "recent work"),
|
|
132
137
|
}
|
|
133
138
|
|
|
134
139
|
# queue type -> execution notes PREPENDED to the prompt sidecar at claim time.
|
|
@@ -184,6 +189,13 @@ TYPE_TO_WORKER_NOTES = {
|
|
|
184
189
|
"use tools. Read, then submit ONE result object matching the schema: "
|
|
185
190
|
"{\"proposals\": [...]}. An empty proposals list is a valid answer."
|
|
186
191
|
),
|
|
192
|
+
"recent-work": (
|
|
193
|
+
"WORKER EXECUTION NOTES (queue metadata; follow while executing the "
|
|
194
|
+
"prompt below): single-turn, tool-free job. Everything you need is "
|
|
195
|
+
"inlined in the prompt (recent transcripts). Never use tools. Read, "
|
|
196
|
+
"then submit ONE result object matching the schema: "
|
|
197
|
+
"{\"items\": [...]}. An empty items list is a valid answer."
|
|
198
|
+
),
|
|
187
199
|
}
|
|
188
200
|
|
|
189
201
|
|
|
@@ -631,6 +631,372 @@ def _decide(ids: list[str], status: str) -> int:
|
|
|
631
631
|
return 0
|
|
632
632
|
|
|
633
633
|
|
|
634
|
+
# --------------------------------------------------------- recent-work digest
|
|
635
|
+
#
|
|
636
|
+
# 2026-11-17: the original (Feb 2026) autoposter started every run from the
|
|
637
|
+
# user's recent Claude work (prompt-db), then searched for threads where that
|
|
638
|
+
# work fit. That was lost in the Mar 9 config-driven refactor. This brings it
|
|
639
|
+
# back for the personal_brand lane only, behind the `recent_work_context`
|
|
640
|
+
# flag in mode.json (s4l_mode.get_recent_work, DEFAULT OFF):
|
|
641
|
+
#
|
|
642
|
+
# digest one tool-free queue job over the last ~2 days of human sessions
|
|
643
|
+
# -> recent_work.json: shareable work items + X search queries.
|
|
644
|
+
# `--if-stale-hours N --background` is what the cycle calls every
|
|
645
|
+
# run: no-op unless the flag is on, the digest is stale, no refresh
|
|
646
|
+
# is in flight, and the last attempt was not in the past hour.
|
|
647
|
+
# queries read PROJECTS_JSON on stdin, emit extra Phase 1 queries (bank
|
|
648
|
+
# shape) for the persona project only; [] when off or stale.
|
|
649
|
+
# show print the current digest.
|
|
650
|
+
#
|
|
651
|
+
# Consumers: skill/run-twitter-cycle.sh (Phase 1 queries + refresh kick) and
|
|
652
|
+
# scripts/draft_prompt_core.py (recent_work_block, persona lane only).
|
|
653
|
+
|
|
654
|
+
DIGEST_DAYS = 2
|
|
655
|
+
DIGEST_BUDGET = 100_000
|
|
656
|
+
DIGEST_PER_SESSION_CAP = 3_500
|
|
657
|
+
DIGEST_MAX_AGE_HOURS = 48 # older than this: not used at all
|
|
658
|
+
DIGEST_REFRESH_HOURS = 6 # cycle kicks a background refresh past this
|
|
659
|
+
DIGEST_RETRY_COOLDOWN_S = 3600 # min gap between attempts (success or not)
|
|
660
|
+
MAX_RECENT_WORK_QUERIES = 8
|
|
661
|
+
RECENT_WORK_TOPIC_PREFIX = "recent work: "
|
|
662
|
+
|
|
663
|
+
DIGEST_SCHEMA = {
|
|
664
|
+
"type": "object",
|
|
665
|
+
"required": ["items"],
|
|
666
|
+
"properties": {
|
|
667
|
+
"items": {
|
|
668
|
+
"type": "array",
|
|
669
|
+
"items": {
|
|
670
|
+
"type": "object",
|
|
671
|
+
"required": ["title", "what", "specifics", "angle", "queries"],
|
|
672
|
+
"properties": {
|
|
673
|
+
"title": {"type": "string"},
|
|
674
|
+
"what": {"type": "string"},
|
|
675
|
+
"specifics": {"type": "string"},
|
|
676
|
+
"angle": {"type": "string"},
|
|
677
|
+
"queries": {"type": "array", "items": {"type": "string"}},
|
|
678
|
+
},
|
|
679
|
+
},
|
|
680
|
+
}
|
|
681
|
+
},
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def recent_work_enabled() -> bool:
|
|
686
|
+
try:
|
|
687
|
+
import s4l_mode # noqa: WPS433 (lives next to this file)
|
|
688
|
+
return s4l_mode.get_recent_work()
|
|
689
|
+
except Exception:
|
|
690
|
+
return False
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def digest_path() -> Path:
|
|
694
|
+
return state_dir() / "recent_work.json"
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def _digest_attempt_path() -> Path:
|
|
698
|
+
return state_dir() / "recent_work.attempt.json"
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
def _digest_lock_path() -> Path:
|
|
702
|
+
return state_dir() / "recent_work.lock"
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def load_digest(max_age_hours: float = DIGEST_MAX_AGE_HOURS) -> dict | None:
|
|
706
|
+
"""The current digest, or None when missing, unreadable, or too old."""
|
|
707
|
+
try:
|
|
708
|
+
d = json.loads(digest_path().read_text())
|
|
709
|
+
ts = datetime.fromisoformat(d["generated_at"])
|
|
710
|
+
except Exception:
|
|
711
|
+
return None
|
|
712
|
+
age_h = (datetime.now(timezone.utc) - ts).total_seconds() / 3600
|
|
713
|
+
if age_h > max_age_hours:
|
|
714
|
+
return None
|
|
715
|
+
d["age_hours"] = round(age_h, 1)
|
|
716
|
+
return d
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def _pid_alive(pid: int) -> bool:
|
|
720
|
+
try:
|
|
721
|
+
os.kill(pid, 0)
|
|
722
|
+
return True
|
|
723
|
+
except (OSError, ValueError):
|
|
724
|
+
return False
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def build_digest_prompt(sessions: list[dict]) -> str:
|
|
728
|
+
parts = [
|
|
729
|
+
f"### Session {s['session_id'][:8]} | {s['last_ts'][:16]} | cwd: {s['cwd']}\n\n{s['body']}"
|
|
730
|
+
for s in sessions
|
|
731
|
+
]
|
|
732
|
+
transcripts = "\n\n---\n\n".join(parts)
|
|
733
|
+
return f"""EXECUTION NOTES: this is a single-turn, tool-free job. Read everything below, then submit ONE result object matching the provided JSON schema: {{"items": [...]}}. Do not use any tools. Do not fetch anything. An empty items list is a valid answer.
|
|
734
|
+
|
|
735
|
+
# Role
|
|
736
|
+
|
|
737
|
+
You write the "recent work" digest for a personal-brand X account. The account holder is a solo founder who does almost all of their work through Claude sessions. Below are their own sessions from the last {DIGEST_DAYS} days (their messages near-verbatim, assistant replies trimmed). The digest has two consumers:
|
|
738
|
+
1. A thread finder that runs your search queries on X to find LIVE public conversations where this person's recent hands-on experience is genuinely relevant.
|
|
739
|
+
2. A reply drafter that grounds replies in what they actually did this week (real specifics, not invented ones).
|
|
740
|
+
|
|
741
|
+
# Pick 0-6 work items
|
|
742
|
+
|
|
743
|
+
An item is something they actually built, debugged, measured, decided, or learned in these sessions that a stranger in tech would find interesting. Prefer items with concrete specifics: numbers, timelines, failure modes, what was tried, what worked. Merge sessions about the same thing into one item. Skip trivial chores, pure ops noise, and anything only meaningful inside their codebase.
|
|
744
|
+
|
|
745
|
+
NEVER include (drop the item, or describe it generically):
|
|
746
|
+
- credentials, keys, tokens, account numbers, or anything resembling one
|
|
747
|
+
- names, handles, or identifying details of customers, users, clients, investors, or other private people
|
|
748
|
+
- fundraising, legal, immigration, personal finance, or health details
|
|
749
|
+
- security incidents in the founder's own products or accounts (leaked or abused keys, exposed endpoints, revoked tokens, breaches, abuse flags, billing spikes from abuse) and anything that reveals a still-exploitable weakness; drop these items entirely, do not genericize them
|
|
750
|
+
- client work that is not clearly the founder's own public product
|
|
751
|
+
- harness noise (usage banners, reminders, scheduler chatter)
|
|
752
|
+
|
|
753
|
+
# Fields
|
|
754
|
+
|
|
755
|
+
- title: short specific handle (max ~60 chars).
|
|
756
|
+
- what: 1-2 sentences, plain first person, what they did and why.
|
|
757
|
+
- specifics: the concrete details a reply can cite truthfully (numbers, tools, the exact failure, the outcome). Only facts stated in the transcripts.
|
|
758
|
+
- angle: one sentence on the opinion or lesson they could credibly share in a public thread about this.
|
|
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).
|
|
764
|
+
|
|
765
|
+
# Transcripts ({len(sessions)} sessions, most recent first)
|
|
766
|
+
|
|
767
|
+
{transcripts}
|
|
768
|
+
|
|
769
|
+
Submit the result object now."""
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
def _run_digest_job(prompt: str, timeout: int) -> dict | None:
|
|
773
|
+
schema_file = state_dir() / "recent_work.schema.json"
|
|
774
|
+
schema_file.write_text(json.dumps(DIGEST_SCHEMA))
|
|
775
|
+
env = dict(os.environ)
|
|
776
|
+
env["S4L_REPO_DIR"] = str(REPO_DIR)
|
|
777
|
+
cmd = ["bash", str(REPO_DIR / "scripts" / "run_claude.sh"), "recent-work",
|
|
778
|
+
"--json-schema", str(schema_file), "-p"]
|
|
779
|
+
try:
|
|
780
|
+
proc = subprocess.run(cmd, input=prompt, capture_output=True, text=True,
|
|
781
|
+
env=env, timeout=timeout + 120)
|
|
782
|
+
except subprocess.TimeoutExpired:
|
|
783
|
+
print("[digest] hard timeout waiting for the queue result", file=sys.stderr)
|
|
784
|
+
return None
|
|
785
|
+
if proc.returncode != 0:
|
|
786
|
+
print(f"[digest] provider failed rc={proc.returncode}", file=sys.stderr)
|
|
787
|
+
sys.stderr.write((proc.stderr or "")[-2000:] + "\n")
|
|
788
|
+
return None
|
|
789
|
+
try:
|
|
790
|
+
envelope = json.loads(proc.stdout[proc.stdout.index("{"):])
|
|
791
|
+
obj = envelope.get("structured_output")
|
|
792
|
+
if obj is None:
|
|
793
|
+
obj = json.loads(envelope.get("result") or "{}")
|
|
794
|
+
return obj if isinstance(obj, dict) else None
|
|
795
|
+
except Exception as e:
|
|
796
|
+
print(f"[digest] could not parse result envelope: {e}", file=sys.stderr)
|
|
797
|
+
return None
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def run_digest(ns) -> int:
|
|
801
|
+
if not recent_work_enabled() and not ns.force:
|
|
802
|
+
if ns.if_stale_hours is None: # stay silent on the per-cycle kick
|
|
803
|
+
print("[digest] recent_work_context flag is off; nothing to do", file=sys.stderr)
|
|
804
|
+
return 0
|
|
805
|
+
|
|
806
|
+
if ns.if_stale_hours is not None:
|
|
807
|
+
if load_digest(max_age_hours=ns.if_stale_hours) is not None:
|
|
808
|
+
return 0
|
|
809
|
+
try:
|
|
810
|
+
last = json.loads(_digest_attempt_path().read_text()).get("at", 0)
|
|
811
|
+
except Exception:
|
|
812
|
+
last = 0
|
|
813
|
+
if time.time() - last < DIGEST_RETRY_COOLDOWN_S:
|
|
814
|
+
return 0
|
|
815
|
+
|
|
816
|
+
lock = _digest_lock_path()
|
|
817
|
+
try:
|
|
818
|
+
held = int(lock.read_text().strip() or 0)
|
|
819
|
+
except Exception:
|
|
820
|
+
held = 0
|
|
821
|
+
if held and _pid_alive(held):
|
|
822
|
+
print(f"[digest] refresh already in flight (pid {held})", file=sys.stderr)
|
|
823
|
+
return 0
|
|
824
|
+
|
|
825
|
+
if ns.background:
|
|
826
|
+
_digest_attempt_path().write_text(json.dumps({"at": time.time()}))
|
|
827
|
+
log = open(state_dir() / "recent_work.log", "a")
|
|
828
|
+
child = subprocess.Popen(
|
|
829
|
+
[sys.executable, str(Path(__file__).resolve()), "digest",
|
|
830
|
+
"--days", str(ns.days), "--timeout", str(ns.timeout)]
|
|
831
|
+
+ (["--force"] if ns.force else []),
|
|
832
|
+
stdout=log, stderr=log, stdin=subprocess.DEVNULL, start_new_session=True,
|
|
833
|
+
)
|
|
834
|
+
print(f"[digest] background refresh started (pid {child.pid})", file=sys.stderr)
|
|
835
|
+
return 0
|
|
836
|
+
|
|
837
|
+
lock.write_text(str(os.getpid()))
|
|
838
|
+
_digest_attempt_path().write_text(json.dumps({"at": time.time()}))
|
|
839
|
+
try:
|
|
840
|
+
sessions = gather_sessions(ns.days)
|
|
841
|
+
if not sessions:
|
|
842
|
+
print("[digest] no eligible human sessions in window", file=sys.stderr)
|
|
843
|
+
return 1
|
|
844
|
+
# breadth over depth: trim each session (head + tail) so the whole
|
|
845
|
+
# window fits one job instead of only the newest few sessions
|
|
846
|
+
for s in sessions:
|
|
847
|
+
if len(s["body"]) > DIGEST_PER_SESSION_CAP:
|
|
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]
|
|
851
|
+
print(f"[digest] {datetime.now().isoformat(timespec='seconds')} "
|
|
852
|
+
f"{len(sessions)} sessions in {ns.days}d, digesting newest {len(batch)}",
|
|
853
|
+
file=sys.stderr)
|
|
854
|
+
prompt = build_digest_prompt(batch)
|
|
855
|
+
if ns.dry_run:
|
|
856
|
+
out = state_dir() / "recent_work.last_prompt.txt"
|
|
857
|
+
out.write_text(prompt)
|
|
858
|
+
print(f"[digest] dry-run: prompt ({len(prompt):,} chars) -> {out}", file=sys.stderr)
|
|
859
|
+
return 0
|
|
860
|
+
obj = _run_digest_job(prompt, ns.timeout)
|
|
861
|
+
if obj is None:
|
|
862
|
+
return 1
|
|
863
|
+
items = [i for i in (obj.get("items") or []) if isinstance(i, dict) and i.get("title")]
|
|
864
|
+
payload = {
|
|
865
|
+
"generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
866
|
+
"window_days": ns.days,
|
|
867
|
+
"sessions": [s["session_id"][:8] for s in batch],
|
|
868
|
+
"items": items,
|
|
869
|
+
}
|
|
870
|
+
tmp = digest_path().with_suffix(".json.tmp")
|
|
871
|
+
tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False))
|
|
872
|
+
tmp.replace(digest_path())
|
|
873
|
+
print(f"[digest] wrote {len(items)} items -> {digest_path()}", file=sys.stderr)
|
|
874
|
+
return 0
|
|
875
|
+
finally:
|
|
876
|
+
try:
|
|
877
|
+
lock.unlink()
|
|
878
|
+
except OSError:
|
|
879
|
+
pass
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
def recent_work_queries(projects: list) -> list[dict]:
|
|
883
|
+
"""Extra Phase 1 queries (qualified_query_bank shape) for the persona
|
|
884
|
+
project, or [] when the flag is off, the digest is stale, or no persona
|
|
885
|
+
project is in this cycle's selection."""
|
|
886
|
+
if not recent_work_enabled():
|
|
887
|
+
return []
|
|
888
|
+
digest = load_digest()
|
|
889
|
+
if not digest:
|
|
890
|
+
return []
|
|
891
|
+
try:
|
|
892
|
+
import s4l_mode # noqa: WPS433
|
|
893
|
+
persona = s4l_mode.persona_name()
|
|
894
|
+
except Exception:
|
|
895
|
+
persona = ""
|
|
896
|
+
names = {(p or {}).get("name") for p in projects if isinstance(p, dict)}
|
|
897
|
+
if not persona or persona not in names:
|
|
898
|
+
return []
|
|
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).
|
|
902
|
+
item_queries = [
|
|
903
|
+
[(it["title"], q) for q in (it.get("queries") or []) if isinstance(q, str) and q.strip()]
|
|
904
|
+
for it in digest.get("items") or []
|
|
905
|
+
]
|
|
906
|
+
flat, seen = [], set()
|
|
907
|
+
while any(item_queries):
|
|
908
|
+
for qs in item_queries:
|
|
909
|
+
if not qs:
|
|
910
|
+
continue
|
|
911
|
+
title, q = qs.pop(0)
|
|
912
|
+
key = " ".join(q.lower().split())
|
|
913
|
+
if key in seen:
|
|
914
|
+
continue
|
|
915
|
+
seen.add(key)
|
|
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
|
|
947
|
+
|
|
948
|
+
|
|
949
|
+
def recent_work_block() -> str:
|
|
950
|
+
"""Prompt block for persona-lane drafts, or '' when off / stale / empty."""
|
|
951
|
+
if not recent_work_enabled():
|
|
952
|
+
return ""
|
|
953
|
+
digest = load_digest()
|
|
954
|
+
items = (digest or {}).get("items") or []
|
|
955
|
+
if not items:
|
|
956
|
+
return ""
|
|
957
|
+
lines = [
|
|
958
|
+
"## RECENT WORK (what the account holder actually did in the last few days)",
|
|
959
|
+
"First-hand, current, and true. When a candidate's `Search query` starts with "
|
|
960
|
+
f"\"{RECENT_WORK_TOPIC_PREFIX.strip()}\", it was found BECAUSE of the matching item below: "
|
|
961
|
+
"ground the reply in that item's specifics. For any other candidate, use an item only "
|
|
962
|
+
"if it genuinely fits the thread; never force it. Cite only the specifics listed here; "
|
|
963
|
+
"do not embellish numbers or invent outcomes. Never name private people or clients.",
|
|
964
|
+
"",
|
|
965
|
+
]
|
|
966
|
+
for it in items:
|
|
967
|
+
lines.append(f"- {it.get('title', '').strip()}")
|
|
968
|
+
for key in ("what", "specifics", "angle"):
|
|
969
|
+
val = " ".join(str(it.get(key) or "").split())
|
|
970
|
+
if val:
|
|
971
|
+
lines.append(f" {key}: {val}")
|
|
972
|
+
return "\n".join(lines) + "\n"
|
|
973
|
+
|
|
974
|
+
|
|
975
|
+
def cmd_queries(ns) -> int:
|
|
976
|
+
try:
|
|
977
|
+
projects = json.loads(sys.stdin.read() or "[]")
|
|
978
|
+
except json.JSONDecodeError:
|
|
979
|
+
projects = []
|
|
980
|
+
qs = recent_work_queries(projects if isinstance(projects, list) else [])
|
|
981
|
+
json.dump(qs, sys.stdout, ensure_ascii=False)
|
|
982
|
+
print()
|
|
983
|
+
return 0
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
def cmd_show(_ns) -> int:
|
|
987
|
+
d = load_digest(max_age_hours=10**6)
|
|
988
|
+
print(f"flag recent_work_context: {'on' if recent_work_enabled() else 'off'}")
|
|
989
|
+
if not d:
|
|
990
|
+
print("no digest yet")
|
|
991
|
+
return 0
|
|
992
|
+
print(f"generated {d['generated_at']} ({d['age_hours']}h ago, used while <{DIGEST_MAX_AGE_HOURS}h)")
|
|
993
|
+
print(recent_work_block() or "(block empty: flag off, stale, or no items)")
|
|
994
|
+
for it in d.get("items") or []:
|
|
995
|
+
for q in it.get("queries") or []:
|
|
996
|
+
print(f" query: {q}")
|
|
997
|
+
return 0
|
|
998
|
+
|
|
999
|
+
|
|
634
1000
|
# ---------------------------------------------------------------------- CLI
|
|
635
1001
|
|
|
636
1002
|
|
|
@@ -656,6 +1022,22 @@ def main() -> int:
|
|
|
656
1022
|
s.add_argument("ids", nargs="+")
|
|
657
1023
|
s.set_defaults(func=lambda ns: _decide(ns.ids, "skipped"))
|
|
658
1024
|
|
|
1025
|
+
dg = sub.add_parser("digest", help="refresh the recent-work digest (flag-gated)")
|
|
1026
|
+
dg.add_argument("--days", type=int, default=DIGEST_DAYS)
|
|
1027
|
+
dg.add_argument("--timeout", type=int, default=1800)
|
|
1028
|
+
dg.add_argument("--if-stale-hours", type=float, default=None,
|
|
1029
|
+
help="no-op if the digest is younger than this, or an attempt ran in the last hour")
|
|
1030
|
+
dg.add_argument("--background", action="store_true", help="detach and return immediately")
|
|
1031
|
+
dg.add_argument("--force", action="store_true", help="run even with the flag off (testing)")
|
|
1032
|
+
dg.add_argument("--dry-run", action="store_true", help="build the prompt, don't enqueue")
|
|
1033
|
+
dg.set_defaults(func=run_digest)
|
|
1034
|
+
|
|
1035
|
+
qq = sub.add_parser("queries", help="PROJECTS_JSON on stdin -> recent-work Phase 1 queries")
|
|
1036
|
+
qq.set_defaults(func=cmd_queries)
|
|
1037
|
+
|
|
1038
|
+
sh = sub.add_parser("show", help="print the recent-work digest and block")
|
|
1039
|
+
sh.set_defaults(func=cmd_show)
|
|
1040
|
+
|
|
659
1041
|
ns = ap.parse_args()
|
|
660
1042
|
return ns.func(ns)
|
|
661
1043
|
|
|
@@ -271,6 +271,20 @@ def corpus_block():
|
|
|
271
271
|
return _CORPUS_HEADER + "\n" + content.rstrip("\n") + "\n"
|
|
272
272
|
|
|
273
273
|
|
|
274
|
+
def recent_work_block(lane):
|
|
275
|
+
"""RECENT WORK block (personal_brand lane only), appended after the
|
|
276
|
+
corpus. '' unless the recent_work_context flag is on and a fresh digest
|
|
277
|
+
exists; see scripts/context_mining.py. Never raises."""
|
|
278
|
+
if lane != "personal_brand":
|
|
279
|
+
return ""
|
|
280
|
+
try:
|
|
281
|
+
import context_mining
|
|
282
|
+
block = context_mining.recent_work_block()
|
|
283
|
+
except Exception:
|
|
284
|
+
return ""
|
|
285
|
+
return ("\n" + block) if block else ""
|
|
286
|
+
|
|
287
|
+
|
|
274
288
|
# Ops-only plumbing the drafter can never use. Denylist, not whitelist, on
|
|
275
289
|
# purpose: an unknown future MARKETING field should reach the drafter by
|
|
276
290
|
# default; add a key here only when it is provably non-drafting plumbing.
|
|
@@ -529,7 +543,7 @@ def render_twitter_prompt(ing):
|
|
|
529
543
|
.replace("@REPO_DIR@", ing["repo_dir"])
|
|
530
544
|
.replace("@CANDIDATE_BLOCK@", ing.get("candidate_block") or "")
|
|
531
545
|
.replace("@MEDIA_BLOCK@", ing.get("media_block") or "")
|
|
532
|
-
.replace("@CORPUS_BLOCK@", corpus_block())
|
|
546
|
+
.replace("@CORPUS_BLOCK@", corpus_block() + recent_work_block(lane))
|
|
533
547
|
.replace("@ALL_PROJECTS_JSON@", projects_json(lane=lane))
|
|
534
548
|
.replace("@GLOBAL_LEARNED_PREFS_JSON@", global_learned_prefs_json())
|
|
535
549
|
.replace("@BATCH_ID@", ing.get("batch_id") or "")
|
|
@@ -703,7 +717,7 @@ def render_reddit_prompt(ing):
|
|
|
703
717
|
.replace("@DRAFT_B_DIVERGENCE_NOTE@", draft_b_divergence_note(arm))
|
|
704
718
|
.replace("@CONTENT_ANGLE@", ing.get("content_angle") or "")
|
|
705
719
|
.replace("@CANDIDATES_BLOCK@", ing.get("candidates_block") or "")
|
|
706
|
-
.replace("@CORPUS_BLOCK@", corpus_block())
|
|
720
|
+
.replace("@CORPUS_BLOCK@", corpus_block() + recent_work_block(lane))
|
|
707
721
|
.replace("@PROJECT_JSON@", projects_json(lane=lane, only_project=ing.get("project_name")))
|
|
708
722
|
.replace("@GLOBAL_LEARNED_PREFS_JSON@", global_learned_prefs_json())
|
|
709
723
|
.replace("@REPO_DIR@", ing.get("repo_dir") or _repo_dir())
|
package/scripts/s4l_mode.py
CHANGED
|
@@ -57,6 +57,8 @@ Usage:
|
|
|
57
57
|
s4l_mode.py draft-only on|off # set the draft-only flag (operator-only)
|
|
58
58
|
s4l_mode.py split # print the personal-brand share (0.0-1.0)
|
|
59
59
|
s4l_mode.py split <value> # set it; accepts 70, 70%, or 0.7
|
|
60
|
+
s4l_mode.py recent-work # print 1|0 (recent-work context flag, default 0)
|
|
61
|
+
s4l_mode.py recent-work on|off # set it (operator-only, reads local transcripts)
|
|
60
62
|
|
|
61
63
|
Draft-only (2026-07-06, single global switch as of 2026-07-08): a third,
|
|
62
64
|
independent flag in mode.json, DEFAULT ON. While ON (the normal state), every
|
|
@@ -292,6 +294,38 @@ def set_draft_only(on: bool) -> bool:
|
|
|
292
294
|
return bool(on)
|
|
293
295
|
|
|
294
296
|
|
|
297
|
+
def get_recent_work() -> bool:
|
|
298
|
+
"""Recent-work context feature flag (2026-11-17), DEFAULT OFF.
|
|
299
|
+
|
|
300
|
+
When ON, scripts/context_mining.py keeps a short digest of what the user
|
|
301
|
+
shipped in their own recent Claude sessions, and the personal_brand lane
|
|
302
|
+
uses it twice: extra X discovery queries in run-twitter-cycle.sh Phase 1,
|
|
303
|
+
and a RECENT WORK block in persona draft prompts (draft_prompt_core.py).
|
|
304
|
+
Reads local transcripts, so it is operator opt-in only: no MCP tool param,
|
|
305
|
+
no menubar toggle; this CLI and mode.json are the only switch."""
|
|
306
|
+
try:
|
|
307
|
+
data = json.loads(mode_file().read_text())
|
|
308
|
+
return isinstance(data, dict) and _coerce_bool(data.get("recent_work_context", False))
|
|
309
|
+
except Exception:
|
|
310
|
+
return False
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def set_recent_work(on: bool) -> bool:
|
|
314
|
+
try:
|
|
315
|
+
payload = json.loads(mode_file().read_text())
|
|
316
|
+
if not isinstance(payload, dict):
|
|
317
|
+
payload = {}
|
|
318
|
+
except Exception:
|
|
319
|
+
payload = {}
|
|
320
|
+
payload["recent_work_context"] = bool(on)
|
|
321
|
+
d = state_dir()
|
|
322
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
323
|
+
tmp = mode_file().with_suffix(".json.tmp")
|
|
324
|
+
tmp.write_text(json.dumps(payload))
|
|
325
|
+
tmp.replace(mode_file())
|
|
326
|
+
return bool(on)
|
|
327
|
+
|
|
328
|
+
|
|
295
329
|
def set_mode(mode: str) -> str:
|
|
296
330
|
"""Legacy single-mode setter: turns the named lane ON and the other OFF."""
|
|
297
331
|
mode = (mode or "").strip()
|
|
@@ -484,6 +518,13 @@ def main(argv) -> int:
|
|
|
484
518
|
return 0
|
|
485
519
|
print("1" if get_draft_only() else "0")
|
|
486
520
|
return 0
|
|
521
|
+
if cmd == "recent-work":
|
|
522
|
+
# `recent-work` -> print 1|0; `recent-work on|off|1|0` -> set and print.
|
|
523
|
+
if len(argv) >= 2:
|
|
524
|
+
print("1" if set_recent_work(_coerce_bool(argv[1])) else "0")
|
|
525
|
+
return 0
|
|
526
|
+
print("1" if get_recent_work() else "0")
|
|
527
|
+
return 0
|
|
487
528
|
print(f"unknown command: {cmd}", file=sys.stderr)
|
|
488
529
|
return 2
|
|
489
530
|
|
|
@@ -309,6 +309,11 @@ def _detail(glob_pattern: str | None = None) -> dict:
|
|
|
309
309
|
recs = _registry_worker_recs(by_id)
|
|
310
310
|
if recs is not None:
|
|
311
311
|
entry["has_workers"] = True
|
|
312
|
+
# Surfaced so resume/dashboard can name a DISABLED worker
|
|
313
|
+
# task outright. compute() aggregates across every Claude*
|
|
314
|
+
# root, so one root's enabled-but-idle registry masks the
|
|
315
|
+
# live root's disabled task as merely 'stalled'.
|
|
316
|
+
entry["enabled"] = all(r.get("enabled") for r in recs)
|
|
312
317
|
epochs = [_iso_to_epoch(r.get("lastRunAt")) for r in recs]
|
|
313
318
|
e = max([x for x in epochs if x is not None], default=None)
|
|
314
319
|
if e is not None:
|
|
@@ -228,7 +228,25 @@ def cmd_candidates(batch_id: str) -> int:
|
|
|
228
228
|
return -1.0
|
|
229
229
|
|
|
230
230
|
rows.sort(key=composite, reverse=True)
|
|
231
|
-
|
|
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
|
+
top = rows[:25]
|
|
242
|
+
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]
|
|
249
|
+
rows = top + extra
|
|
232
250
|
|
|
233
251
|
for r in rows:
|
|
234
252
|
cols = [
|
|
@@ -1192,6 +1192,27 @@ if [ "$SCAN_ATTEMPT" -gt 1 ]; then
|
|
|
1192
1192
|
else
|
|
1193
1193
|
log "Phase 1 (bank): building qualified query bank from PROJECTS_JSON (deterministic, no Claude)..."
|
|
1194
1194
|
echo "$PROJECTS_JSON" | python3 "$REPO_DIR/scripts/qualified_query_bank.py" --from-projects-json > "$QUERIES_TMP" 2>>"$LOG_FILE"
|
|
1195
|
+
# Recent-work discovery (2026-11-17, personal_brand lane only, behind the
|
|
1196
|
+
# mode.json `recent_work_context` flag, DEFAULT OFF; see
|
|
1197
|
+
# scripts/context_mining.py). Prepends up to 8 queries drafted from the
|
|
1198
|
+
# user's own recent Claude sessions so the persona finds threads about
|
|
1199
|
+
# what they actually did this week (restores the Feb 2026 work-first
|
|
1200
|
+
# flow). Emits [] and changes nothing when the flag is off, the digest is
|
|
1201
|
+
# stale, or the persona isn't the picked project. The digest refresh is
|
|
1202
|
+
# kicked here too: detached, flag-gated, no-op unless >6h stale.
|
|
1203
|
+
python3 "$REPO_DIR/scripts/context_mining.py" digest --if-stale-hours 6 --background >>"$LOG_FILE" 2>&1 || true
|
|
1204
|
+
_RW_QUERIES=$(echo "$PROJECTS_JSON" | python3 "$REPO_DIR/scripts/context_mining.py" queries 2>>"$LOG_FILE" || echo "[]")
|
|
1205
|
+
_RW_N=$(RW="$_RW_QUERIES" QT="$QUERIES_TMP" python3 -c '
|
|
1206
|
+
import json, os
|
|
1207
|
+
try: rw = json.loads(os.environ.get("RW") or "[]")
|
|
1208
|
+
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"))
|
|
1213
|
+
print(len(rw))
|
|
1214
|
+
' 2>>"$LOG_FILE" || echo 0)
|
|
1215
|
+
[ "${_RW_N:-0}" -gt 0 ] && log "Phase 1 (bank): +${_RW_N} recent-work queries prepended (personal_brand, recent_work_context on)"
|
|
1195
1216
|
fi
|
|
1196
1217
|
|
|
1197
1218
|
QUERIES_COUNT=$(python3 -c "
|
|
@@ -1754,7 +1775,12 @@ else
|
|
|
1754
1775
|
fi
|
|
1755
1776
|
if [ -n "$VIRALITY_THRESHOLD" ] && [ -n "$CANDIDATES" ]; then
|
|
1756
1777
|
_VF_TOTAL=$(printf '%s\n' "$CANDIDATES" | grep -c '^[0-9]' || true)
|
|
1757
|
-
|
|
1778
|
+
# Recent-work exemption (2026-11-17): rows whose search_topic (col 8)
|
|
1779
|
+
# starts with "recent work: " came from the user's own recent sessions
|
|
1780
|
+
# (personal_brand lane, recent_work_context flag) and are gated on
|
|
1781
|
+
# relevance, not virality; twitter_cycle_helper.py already applied their
|
|
1782
|
+
# reach floor. Everything else still has to clear the bar.
|
|
1783
|
+
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))')
|
|
1758
1784
|
_VF_KEPT=$(printf '%s\n' "$CANDIDATES" | grep -c '^[0-9]' || true)
|
|
1759
1785
|
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"
|
|
1760
1786
|
fi
|
|
@@ -2391,11 +2417,23 @@ rejected = so.get('rejected', []) if isinstance(so, dict) else []
|
|
|
2391
2417
|
# (pipe cols: id|url|author|text|virality|delta|...). Shared by the top-N cap
|
|
2392
2418
|
# and the rolling virality bar below.
|
|
2393
2419
|
_vir = {}
|
|
2420
|
+
_rw_ids = set()
|
|
2394
2421
|
for _ln in (os.environ.get('S4L_CAND_VIR', '') or '').splitlines():
|
|
2395
2422
|
_p = _ln.split('|')
|
|
2396
2423
|
if len(_p) >= 5 and _p[0].isdigit():
|
|
2397
2424
|
try: _vir[int(_p[0])] = float(_p[4] or 0)
|
|
2398
2425
|
except Exception: pass
|
|
2426
|
+
if len(_p) >= 8 and _p[7].startswith('recent work: '):
|
|
2427
|
+
_rw_ids.add(int(_p[0]))
|
|
2428
|
+
# RECENT-WORK LANE (2026-11-17): picks found via the user's own recent-work
|
|
2429
|
+
# queries (search_topic 'recent work: ...', personal_brand + recent_work_context
|
|
2430
|
+
# flag) are set aside BEFORE the top-N cap and the virality bar, then the best
|
|
2431
|
+
# ONE is added back after both. They are gated on relevance (the drafter
|
|
2432
|
+
# already chose them), not virality, and never compete with or displace the
|
|
2433
|
+
# regular top-N pick. Extra recent-work picks stay 'pending' like deferrals.
|
|
2434
|
+
_rw_picks = [c for c in candidates if c.get('candidate_id') in _rw_ids]
|
|
2435
|
+
candidates = [c for c in candidates if c.get('candidate_id') not in _rw_ids]
|
|
2436
|
+
_rw_picks.sort(key=lambda c: _vir.get(c.get('candidate_id'), 0.0), reverse=True)
|
|
2399
2437
|
# TOP-N POST CAP (2026-06-29): keep only the highest-Virality on-brand pick(s).
|
|
2400
2438
|
# S4L_POST_TOP_N=0 disables the cap (env opt-out only; the cap applies to both
|
|
2401
2439
|
# autopilot and DRAFT_ONLY lanes as of 2026-06-30). Truncated picks are dropped
|
|
@@ -2421,6 +2459,10 @@ if _bar and candidates:
|
|
|
2421
2459
|
candidates = _kept
|
|
2422
2460
|
except Exception:
|
|
2423
2461
|
pass
|
|
2462
|
+
if _rw_picks:
|
|
2463
|
+
candidates = candidates + _rw_picks[:1]
|
|
2464
|
+
_deferred += len(_rw_picks) - 1
|
|
2465
|
+
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)
|
|
2424
2466
|
# The picker assignment travels through the plan envelope so
|
|
2425
2467
|
# twitter_post_plan.py can call validate_or_register(...) with the
|
|
2426
2468
|
# original (assigned_style, assigned_mode) and coerce USE-mode drift
|
package/scripts/s4l_halt.sh
DELETED
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bash
|
|
2
|
-
# s4l_halt.sh — FULL, reversible stop of S4L on a dev box (everything Pause leaves running).
|
|
3
|
-
#
|
|
4
|
-
# The product's Pause (pause_s4l / tray "Pause S4L") unloads only the five pipeline
|
|
5
|
-
# daemons in index.ts PAUSE_TARGETS. A dev box also carries the fleet jobs (linkedin,
|
|
6
|
-
# github, instagram, stats, audits, backfills, browser-watch, ...) plus the harness
|
|
7
|
-
# browsers and their daemons; those keep firing while "paused", and a harness Chrome
|
|
8
|
-
# being activated over CDP is what yanks a fullscreen app out of focus.
|
|
9
|
-
#
|
|
10
|
-
# halt write paused.flag (the SAME sentinel pause_s4l uses, so an MCP boot skips
|
|
11
|
-
# the pipeline daemons and claude_job.py reports "no work"), boot out EVERY
|
|
12
|
-
# loaded S4L LaunchAgent except the tray + dashboard, remember which ones
|
|
13
|
-
# were loaded in <state>/halt-manifest.txt, then quit the harness browsers
|
|
14
|
-
# (Chrome Beta on CDP 955x under ~/.claude/browser-profiles) and their
|
|
15
|
-
# browser_harness daemons. Nothing is deleted.
|
|
16
|
-
# resume bootstrap exactly the manifest's labels, drop the flag. Browsers relaunch
|
|
17
|
-
# on demand. Idempotent: already-loaded labels are skipped.
|
|
18
|
-
# status flag, loaded S4L labels, harness processes.
|
|
19
|
-
#
|
|
20
|
-
# Not covered (by design): the Claude-native s4l-worker scheduled task keeps firing
|
|
21
|
-
# every minute; it is headless and claude_job.py honours paused.flag, so it drains
|
|
22
|
-
# nothing. Disable it in Claude Desktop (Routines) if even that is unwanted.
|
|
23
|
-
set -euo pipefail
|
|
24
|
-
|
|
25
|
-
STATE="$HOME/.social-autoposter-mcp"
|
|
26
|
-
FLAG="$STATE/paused.flag"
|
|
27
|
-
MANIFEST="$STATE/halt-manifest.txt"
|
|
28
|
-
LA="$HOME/Library/LaunchAgents"
|
|
29
|
-
KEEP="com.m13v.social-autoposter.menubar com.m13v.social-dashboard"
|
|
30
|
-
UID_="$(id -u)"
|
|
31
|
-
|
|
32
|
-
# Every LaunchAgent label that belongs to S4L on this box, from the union of the
|
|
33
|
-
# plists on disk and the labels loaded in launchd (same dynamic sweep as
|
|
34
|
-
# reset-test-machine.sh; a hardcoded list missed new agents twice).
|
|
35
|
-
s4l_labels() {
|
|
36
|
-
{
|
|
37
|
-
for pl in "$LA"/com.m13v.social-*.plist "$LA"/com.m13v.s4l-*.plist \
|
|
38
|
-
"$LA"/com.m13v.browser-watch.plist "$LA"/com.m13v.gmail-dwd-keepalive-s4l.plist; do
|
|
39
|
-
[ -e "$pl" ] && basename "$pl" .plist
|
|
40
|
-
done
|
|
41
|
-
launchctl list 2>/dev/null | awk '$3 ~ /^com\.m13v\.(social-|s4l-|browser-watch$|gmail-dwd-keepalive-s4l$)/ {print $3}'
|
|
42
|
-
} | sort -u | while IFS= read -r l; do
|
|
43
|
-
case " $KEEP " in *" $l "*) ;; *) echo "$l" ;; esac
|
|
44
|
-
done
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
loaded() { launchctl list 2>/dev/null | awk -v l="$1" '$3==l' | grep -q .; }
|
|
48
|
-
|
|
49
|
-
# Harness Chrome main processes: CDP port 955x + a profile under ~/.claude/browser-profiles.
|
|
50
|
-
harness_browsers() {
|
|
51
|
-
ps -eo pid=,args= | awk -v home="$HOME" \
|
|
52
|
-
'/remote-debugging-port=955[0-9]/ && index($0, "--user-data-dir=" home "/.claude/browser-profiles/") && !/Helper/ {print $1}'
|
|
53
|
-
}
|
|
54
|
-
harness_daemons() { pgrep -f "browser_harness.daemon" || true; }
|
|
55
|
-
|
|
56
|
-
case "${1:-}" in
|
|
57
|
-
halt)
|
|
58
|
-
mkdir -p "$STATE"
|
|
59
|
-
[ -e "$FLAG" ] || echo "paused at $(date +%Y-%m-%dT%H:%M:%S%z) (s4l_halt)" > "$FLAG"
|
|
60
|
-
touch "$MANIFEST"
|
|
61
|
-
n=0
|
|
62
|
-
for l in $(s4l_labels); do
|
|
63
|
-
loaded "$l" || continue
|
|
64
|
-
grep -qx "$l" "$MANIFEST" || echo "$l" >> "$MANIFEST"
|
|
65
|
-
launchctl bootout "gui/$UID_/$l" >/dev/null 2>&1 || true
|
|
66
|
-
n=$((n + 1))
|
|
67
|
-
done
|
|
68
|
-
echo "booted out $n LaunchAgents (manifest: $MANIFEST, $(wc -l < "$MANIFEST" | tr -d ' ') total)"
|
|
69
|
-
b="$(harness_browsers)"; d="$(harness_daemons)"
|
|
70
|
-
[ -n "$b" ] && { echo "$b" | xargs kill 2>/dev/null || true; echo "quit harness browsers: $(echo $b)"; }
|
|
71
|
-
[ -n "$d" ] && { echo "$d" | xargs kill 2>/dev/null || true; echo "killed harness daemons: $(echo $d)"; }
|
|
72
|
-
echo "halted: paused.flag set, $( [ -z "$b$d" ] && echo 'no harness processes were running' || echo 'harness processes stopped')"
|
|
73
|
-
;;
|
|
74
|
-
resume)
|
|
75
|
-
rm -f "$FLAG"
|
|
76
|
-
n=0; skipped=0
|
|
77
|
-
if [ -s "$MANIFEST" ]; then
|
|
78
|
-
while IFS= read -r l; do
|
|
79
|
-
[ -n "$l" ] || continue
|
|
80
|
-
if loaded "$l"; then skipped=$((skipped + 1)); continue; fi
|
|
81
|
-
if [ -e "$LA/$l.plist" ]; then
|
|
82
|
-
launchctl bootstrap "gui/$UID_" "$LA/$l.plist" >/dev/null 2>&1 && n=$((n + 1)) || echo " ! could not bootstrap $l" >&2
|
|
83
|
-
else
|
|
84
|
-
echo " ! no plist for $l, skipped" >&2
|
|
85
|
-
fi
|
|
86
|
-
done < "$MANIFEST"
|
|
87
|
-
rm -f "$MANIFEST"
|
|
88
|
-
fi
|
|
89
|
-
echo "resumed: paused.flag cleared, $n LaunchAgents reloaded, $skipped already loaded; harness browsers relaunch on demand"
|
|
90
|
-
;;
|
|
91
|
-
status)
|
|
92
|
-
[ -e "$FLAG" ] && echo "paused.flag: SET ($(cat "$FLAG"))" || echo "paused.flag: absent"
|
|
93
|
-
l=0; for x in $(s4l_labels); do loaded "$x" && l=$((l + 1)); done
|
|
94
|
-
echo "S4L LaunchAgents loaded: $l of $(s4l_labels | wc -l | tr -d ' ') (tray + dashboard excluded)"
|
|
95
|
-
[ -s "$MANIFEST" ] && echo "halt manifest: $(wc -l < "$MANIFEST" | tr -d ' ') labels waiting for resume"
|
|
96
|
-
b="$(harness_browsers)"; d="$(harness_daemons)"
|
|
97
|
-
echo "harness browsers: ${b:-none}"
|
|
98
|
-
echo "harness daemons: ${d:-none}"
|
|
99
|
-
;;
|
|
100
|
-
*)
|
|
101
|
-
echo "usage: s4l_halt.sh {halt|resume|status}" >&2; exit 64 ;;
|
|
102
|
-
esac
|