Repository navigation
Expand file tree
/
Copy pathn8n_codex_blog_runner.py
More file actions
417 lines (359 loc) · 17 KB
/
Copy pathn8n_codex_blog_runner.py
File metadata and controls
417 lines (359 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#!/usr/bin/env python3
"""Small local HTTP runner for n8n-triggered Codex blog generation."""
from __future__ import annotations
import json
import os
import re
import signal
import socketserver
import subprocess
import threading
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent
HOST = os.environ.get("BLOG_RUNNER_HOST", "127.0.0.1")
PORT = int(os.environ.get("BLOG_RUNNER_PORT", "8765"))
TOKEN = os.environ.get("BLOG_RUNNER_TOKEN", "")
TIMEOUT_SECONDS = int(os.environ.get("BLOG_RUNNER_TIMEOUT_SECONDS", "3600"))
VENV_DIR = REPO_ROOT / ".venv"
SYSTEM_PYTHON_BIN = os.environ.get("BLOG_RUNNER_SYSTEM_PYTHON", "/opt/homebrew/bin/python3")
PYTHON_BIN = os.environ.get("BLOG_RUNNER_PYTHON", str(VENV_DIR / "bin" / "python3"))
HUGO_BIN = os.environ.get("BLOG_RUNNER_HUGO", "/opt/homebrew/bin/hugo")
PUBLISH_BRANCH = os.environ.get("BLOG_RUNNER_PUBLISH_BRANCH", "main")
VALID_TRACKS = {"issue", "tech"}
_lock = threading.Lock()
class LocalThreadingHTTPServer(ThreadingHTTPServer):
def server_bind(self) -> None:
socketserver.TCPServer.server_bind(self)
host, port = self.server_address[:2]
self.server_name = str(host)
self.server_port = int(port)
def _terminate_process_group(process: subprocess.Popen, grace_seconds: float = 5.0) -> None:
if process.poll() is not None:
return
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
return
try:
process.wait(timeout=grace_seconds)
except subprocess.TimeoutExpired:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
return
process.wait(timeout=grace_seconds)
def _json_response(handler: BaseHTTPRequestHandler, status: int, payload: dict[str, Any]) -> None:
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json; charset=utf-8")
handler.send_header("Content-Length", str(len(data)))
handler.end_headers()
handler.wfile.write(data)
def _run_step(name: str, command: list[str], env: dict[str, str]) -> dict[str, Any]:
started_at = datetime.now(timezone.utc).isoformat()
process = subprocess.Popen(
command,
cwd=REPO_ROOT,
env=env,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
start_new_session=True,
)
try:
stdout, stderr = process.communicate(timeout=TIMEOUT_SECONDS)
except subprocess.TimeoutExpired as exc:
_terminate_process_group(process)
raise subprocess.TimeoutExpired(command, TIMEOUT_SECONDS) from exc
return {
"name": name,
"command": command,
"exitCode": process.returncode,
"startedAt": started_at,
"stdoutTail": stdout[-4000:],
"stderrTail": stderr[-4000:],
}
def _publish_paths(paths: list[str]) -> list[str]:
seen: set[str] = set()
safe_paths: list[str] = []
for value in paths:
path = Path(value)
resolved = path.resolve() if path.is_absolute() else (REPO_ROOT / path).resolve()
rel = resolved.relative_to(REPO_ROOT).as_posix()
if rel == ".git" or rel.startswith(".git/"):
raise ValueError(f"refusing to publish git internals: {rel}")
if rel not in seen and resolved.exists():
seen.add(rel)
safe_paths.append(rel)
return safe_paths
def _created_files(step: dict[str, Any]) -> list[str]:
stdout = str(step.get("stdoutTail") or "")
files = re.findall(r"^CREATED_FILE=(.+)$", stdout, flags=re.MULTILINE)
return _publish_paths(files)
def _collected_file(step: dict[str, Any]) -> str:
stdout = str(step.get("stdoutTail") or "")
match = re.search(r"^COLLECTED_FILE=(.+)$", stdout, flags=re.MULTILINE)
if not match:
return ""
files = _publish_paths([match.group(1)])
return files[0] if files else ""
def _collected_count(step: dict[str, Any]) -> int:
stdout = str(step.get("stdoutTail") or "")
match = re.search(r"^CANDIDATE_COUNT=(\d+)$", stdout, flags=re.MULTILINE)
return int(match.group(1)) if match else 0
def _frontmatter_value(lines: list[str], key: str) -> str:
prefix = f"{key}:"
for line in lines[:40]:
if line.startswith(prefix):
return line[len(prefix):].strip().strip('"')
return ""
def _latest_scores(count: int) -> list[str]:
path = SCRIPT_DIR / ".quality_history.jsonl"
scores: list[tuple[str, float]] = []
if path.exists():
for line in path.read_text(errors="replace").splitlines():
try:
item = json.loads(line)
except json.JSONDecodeError:
continue
if item.get("status") == "selected":
avg = (item.get("scores") or {}).get("avg")
if isinstance(avg, int | float):
scores.append((str(item.get("created_at") or ""), float(avg)))
return [f"{score:.1f}" for _, score in sorted(scores)[-count:]]
def _blog_alert(track: str, ok: bool, paths: list[str], *, failed_step: str = "", error: str = "") -> str:
posts = [Path(path) for path in _publish_paths(paths) if path.startswith("content/posts/")]
scores = _latest_scores(len(posts))
label = "Gnosys 이슈" if track == "issue" else "Gnosys 기술"
lines = [
f"{'✅' if ok else '❌'} {label} 자동 발행",
f"상태: {'성공' if ok else '실패'}",
f"점수: {', '.join(score + '점' for score in scores) if scores else 'runner 응답 점수 없음'}",
f"발행글: {len(posts)}개",
]
if failed_step:
lines.append(f"실패 단계: {failed_step}")
if error:
lines.append(f"오류: {error}")
for index, post in enumerate(posts, start=1):
content = (REPO_ROOT / post).read_text(errors="replace").splitlines()
title = _frontmatter_value(content, "title") or post.stem
description = _frontmatter_value(content, "description")
lines.append(f"\n{index}. {title}")
if description:
lines.append(f"요약: {description}")
lines.append(f"파일: {post.as_posix()}")
return "\n".join(lines)
def _collect_alert(
track: str,
ok: bool,
collected_file: str = "",
candidate_count: int = 0,
*,
failed_step: str = "",
error: str = "",
) -> str:
label = "Gnosys 이슈" if track == "issue" else "Gnosys 기술"
lines = [
f"{'✅' if ok else '❌'} {label} 후보 수집",
f"상태: {'성공' if ok else '실패'}",
f"후보: {candidate_count}개",
f"파일: {collected_file or '없음'}",
"발행글: 0개",
]
if failed_step:
lines.append(f"실패 단계: {failed_step}")
if error:
lines.append(f"오류: {error}")
return "\n".join(lines)
def _telegram_chat_id(token: str, env: dict[str, str]) -> str:
chat_id = env.get("TELEGRAM_CHAT_ID", "").strip()
if chat_id:
return chat_id
with urllib.request.urlopen(f"https://api.telegram.org/bot{token}/getUpdates", timeout=15) as response:
payload = json.loads(response.read().decode("utf-8"))
for update in reversed(payload.get("result") or []):
message = update.get("message") or update.get("edited_message") or update.get("channel_post")
chat = (message or {}).get("chat") or {}
if chat.get("id") is not None:
return str(chat["id"])
raise RuntimeError("TELEGRAM_CHAT_ID missing and no Telegram updates found; send /start to the bot first")
def _send_telegram_notification(track: str, paths: list[str], env: dict[str, str]) -> dict[str, Any]:
started_at = datetime.now(timezone.utc).isoformat()
token = env.get("TELEGRAM_BOT_TOKEN", "").strip()
if not token:
return {"name": "send telegram notification", "command": ["telegram", "sendMessage"], "exitCode": 1, "startedAt": started_at, "stdoutTail": "", "stderrTail": "TELEGRAM_BOT_TOKEN missing"}
text = _blog_alert(track, True, paths)
data = urllib.parse.urlencode({"chat_id": _telegram_chat_id(token, env), "text": text})
request = urllib.request.Request(f"https://api.telegram.org/bot{token}/sendMessage", data=data.encode("utf-8"))
with urllib.request.urlopen(request, timeout=15) as response:
response.read()
return {"name": "send telegram notification", "command": ["telegram", "sendMessage"], "exitCode": 0, "startedAt": started_at, "stdoutTail": text, "stderrTail": ""}
def _publish_blog_changes(track: str, paths: list[str], env: dict[str, str]) -> list[dict[str, Any]]:
publish_paths = _publish_paths(paths + ["scripts/.seen_articles.json", "scripts/.seen_articles_issue.json"])
timestamp = datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M %Z")
message = f"feat: publish n8n blog posts ({timestamp})"
body = f"- track: {track}\n- files: {', '.join(publish_paths)}"
steps = []
commands = [
("git configure bot", ["git", "config", "user.name", "n8n Blog Runner"]),
("git configure email", ["git", "config", "user.email", "bot@gnosyslambda.github.io"]),
("git fetch main", ["git", "fetch", "origin", f"{PUBLISH_BRANCH}:refs/remotes/origin/{PUBLISH_BRANCH}"]),
("verify fast-forward publish", ["git", "merge-base", "--is-ancestor", f"origin/{PUBLISH_BRANCH}", "HEAD"]),
("stage published files", ["git", "add", "--", *publish_paths]),
]
for name, command in commands:
step = _run_step(name, command, env)
steps.append(step)
if step["exitCode"] != 0:
return steps
check = _run_step("check staged changes", ["git", "diff", "--cached", "--quiet"], env)
steps.append(check)
if check["exitCode"] == 0:
return steps
if check["exitCode"] == 1:
check["exitCode"] = 0
check["stdoutTail"] = "staged changes present"
else:
return steps
for name, command in [
("commit published files", ["git", "commit", "-m", message, "-m", body]),
("push published files", ["git", "push", "origin", f"HEAD:{PUBLISH_BRANCH}"]),
]:
step = _run_step(name, command, env)
steps.append(step)
if step["exitCode"] != 0:
return steps
return steps
def run_blog_job(
force: bool = False,
track: str = "tech",
publish: bool = False,
notify: bool = False,
publish_paths: list[str] | None = None,
publish_only: bool = False,
collect_only: bool = False,
) -> tuple[int, dict[str, Any]]:
if not _lock.acquire(blocking=False):
return 409, {"ok": False, "error": "blog runner is already running"}
env = os.environ.copy()
env["PATH"] = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:" + env.get("PATH", "")
# Pin writing quality regardless of stale runner/launchd environment variables.
env["CODEX_MODEL"] = os.environ.get("BLOG_WRITER_MODEL", "gpt-5.6-sol")
env["CODEX_REASONING_EFFORT"] = os.environ.get("BLOG_WRITER_REASONING_EFFORT", "xhigh")
env["DAILY_POST_LIMIT"] = os.environ.get("BLOG_WRITER_DAILY_POST_LIMIT", "2")
env["BLOG_TRACK"] = track
if force:
env["FORCE_RUN"] = "1"
steps: list[dict[str, Any]] = []
try:
commands = []
if "BLOG_RUNNER_PYTHON" not in os.environ:
commands.append(("prepare python venv", [SYSTEM_PYTHON_BIN, "-m", "venv", str(VENV_DIR)]))
commands.append(("install dependencies", [PYTHON_BIN, "-m", "pip", "install", "-q", "-r", "scripts/requirements.txt"]))
if collect_only:
commands.append(("collect topic candidates", [PYTHON_BIN, "-B", "scripts/collect_topics.py", "--track", track]))
else:
commands.extend([
("verify humanizer gate", [PYTHON_BIN, "-B", "scripts/test_humanizer_gate.py"]),
("build hugo site", [HUGO_BIN, "--minify"]),
])
if not collect_only and not publish_only:
commands.insert(-1, ("write post with codex", [PYTHON_BIN, "scripts/trend_writer.py", "--track", track]))
for name, command in commands:
step = _run_step(name, command, env)
steps.append(step)
if step["exitCode"] != 0:
alert = _collect_alert(track, False, failed_step=name) if collect_only else _blog_alert(track, False, [], failed_step=name)
return 500, {"ok": False, "track": track, "collectOnly": collect_only, "failedStep": name, "alert": alert, "steps": steps}
if collect_only:
collect_step = next(step for step in steps if step["name"] == "collect topic candidates")
collected_file = _collected_file(collect_step)
candidate_count = _collected_count(collect_step)
return 200, {
"ok": True,
"track": track,
"collectOnly": True,
"collectedFile": collected_file,
"candidateCount": candidate_count,
"alert": _collect_alert(track, True, collected_file, candidate_count),
"steps": steps,
}
paths: list[str] = []
if publish or publish_only:
paths = list(publish_paths or [])
if not publish_only:
paths.extend(_created_files(next(step for step in steps if step["name"] == "write post with codex")))
for step in _publish_blog_changes(track, paths, env):
steps.append(step)
if step["exitCode"] != 0:
return 500, {"ok": False, "track": track, "failedStep": step["name"], "createdFiles": paths, "alert": _blog_alert(track, False, paths, failed_step=step["name"]), "steps": steps}
if notify:
step = _send_telegram_notification(track, paths, env)
steps.append(step)
if step["exitCode"] != 0:
return 500, {"ok": False, "track": track, "failedStep": step["name"], "createdFiles": paths, "alert": _blog_alert(track, False, paths, failed_step=step["name"]), "steps": steps}
return 200, {"ok": True, "track": track, "createdFiles": paths, "alert": _blog_alert(track, True, paths), "steps": steps}
except subprocess.TimeoutExpired as exc:
error = f"timeout after {TIMEOUT_SECONDS}s"
alert = _collect_alert(track, False, error=error) if collect_only else _blog_alert(track, False, [], error=error)
return 504, {"ok": False, "track": track, "collectOnly": collect_only, "error": error, "step": exc.cmd, "alert": alert, "steps": steps}
except Exception as exc:
alert = _collect_alert(track, False, error=str(exc)) if collect_only else _blog_alert(track, False, [], error=str(exc))
return 500, {"ok": False, "track": track, "collectOnly": collect_only, "error": str(exc), "alert": alert, "steps": steps}
finally:
_lock.release()
class BlogRunnerHandler(BaseHTTPRequestHandler):
def log_message(self, format: str, *args: object) -> None:
return
def do_GET(self) -> None:
if self.path != "/health":
_json_response(self, 404, {"ok": False, "error": "not found"})
return
_json_response(self, 200, {"ok": True, "service": "n8n-codex-blog-runner"})
def do_POST(self) -> None:
if self.path != "/run":
_json_response(self, 404, {"ok": False, "error": "not found"})
return
if TOKEN and self.headers.get("X-Blog-Runner-Token") != TOKEN:
_json_response(self, 401, {"ok": False, "error": "unauthorized"})
return
length = int(self.headers.get("Content-Length", "0") or "0")
raw_body = self.rfile.read(length).decode("utf-8") if length else ""
try:
body = json.loads(raw_body) if raw_body else {}
except json.JSONDecodeError:
body = {}
if not isinstance(body, dict):
body = {}
track = str(body.get("track") or "tech").strip().lower()
if track not in VALID_TRACKS:
_json_response(self, 400, {"ok": False, "error": f"invalid track: {track}"})
return
publish_paths = body.get("publishPaths") or []
if not isinstance(publish_paths, list):
publish_paths = []
status, payload = run_blog_job(
force=bool(body.get("force")),
track=track,
publish=bool(body.get("publish")),
notify=bool(body.get("notify")),
publish_only=bool(body.get("publishOnly")),
collect_only=bool(body.get("collectOnly")),
publish_paths=[str(path) for path in publish_paths],
)
_json_response(self, status, payload)
def main() -> None:
if HOST not in {"127.0.0.1", "localhost", "::1"} and not TOKEN:
raise SystemExit("BLOG_RUNNER_TOKEN is required when BLOG_RUNNER_HOST is not loopback")
server = LocalThreadingHTTPServer((HOST, PORT), BlogRunnerHandler)
print(f"n8n Codex blog runner listening on http://{HOST}:{PORT}", flush=True)
server.serve_forever()
if __name__ == "__main__":
main()