-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.py
More file actions
242 lines (196 loc) · 8.14 KB
/
lib.py
File metadata and controls
242 lines (196 loc) · 8.14 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
# Copyright (c) 2026 Nardo (nardovibecoding). AGPL-3.0 — see LICENSE
"""Shared library — pure Python functions usable by both MCP server and admin bot.
No MCP dependency. Import freely from any Python project:
from lib import content_capture, content_queue, session_checkpoint
"""
import os
import time
from collections import deque
from datetime import datetime
from pathlib import Path
# --- Paths ---
_vps_repo = os.environ.get("VPS_REPO_PATH", "")
CONTENT_DRAFTS = Path(_vps_repo) / "content_drafts" if _vps_repo else Path.home() / ".claude" / "content_drafts"
CONTENT_LOG = CONTENT_DRAFTS / "running_log.md"
QUEUE_FILE = CONTENT_DRAFTS / "queue.md"
CHECKPOINT_DIR = CONTENT_DRAFTS
# --- Session state (in-memory, resets on process restart) ---
session_actions = deque(maxlen=100)
# --- Content capture ---
def content_capture(moment: str, category: str = "insight") -> dict:
"""Save a content-worthy moment to the running draft log.
Args:
moment: the insight, discovery, result, or aha moment
category: one of: insight, result, code, number, journey, mistake
"""
ts = datetime.now().strftime("%Y-%m-%d %H:%M")
CONTENT_LOG.parent.mkdir(parents=True, exist_ok=True)
entry = f"\n## [{category}] {ts}\n{moment}\n"
with open(CONTENT_LOG, "a") as f:
f.write(entry)
return {"saved": True, "file": str(CONTENT_LOG), "category": category}
# --- Content queue ---
def content_queue(action: str = "list", tweet: str = "", priority: str = "normal") -> dict:
"""Manage tweet draft queue. Add drafts, list queue, get next to post.
Args:
action: "add", "list", "next", or "posted"
tweet: tweet text (required for "add")
priority: "high", "normal", "low" (for "add")
"""
QUEUE_FILE.parent.mkdir(parents=True, exist_ok=True)
if not QUEUE_FILE.exists():
QUEUE_FILE.write_text("# Tweet Queue\n\n")
content = QUEUE_FILE.read_text()
if action == "add":
if not tweet:
return {"error": "provide tweet text"}
ts = datetime.now().strftime("%Y-%m-%d %H:%M")
entry = f"\n### [{priority}] {ts}\n{tweet}\n"
with open(QUEUE_FILE, "a") as f:
f.write(entry)
items = content.count("### [")
return {"queued": True, "position": items + 1, "priority": priority}
elif action == "list":
items = []
for block in content.split("### [")[1:]:
prio = block.split("]")[0]
rest = block.split("]", 1)[1].strip()
date_line = rest.split("\n")[0].strip()
text = "\n".join(rest.split("\n")[1:]).strip()
items.append({"priority": prio, "date": date_line, "text": text[:200]})
return {"queue": items, "total": len(items)}
elif action == "next":
items = []
for block in content.split("### [")[1:]:
if "~~POSTED~~" in block:
continue
prio = block.split("]")[0]
rest = block.split("]", 1)[1].strip()
text = "\n".join(rest.split("\n")[1:]).strip()
prio_score = {"high": 3, "normal": 2, "low": 1}.get(prio, 0)
items.append({"priority": prio, "score": prio_score, "text": text})
if not items:
return {"queue_empty": True}
items.sort(key=lambda x: x["score"], reverse=True)
return {"next": items[0]["text"], "priority": items[0]["priority"], "remaining": len(items)}
elif action == "posted":
lines = content.splitlines()
for i, line in enumerate(lines):
if line.startswith("### [") and "~~POSTED~~" not in line:
lines[i] = line + " ~~POSTED~~"
QUEUE_FILE.write_text("\n".join(lines))
return {"marked": True}
return {"error": "no unposted items"}
return {"error": f"unknown action: {action}"}
# --- Session checkpoint ---
def session_checkpoint(summary: str, key_decisions: list = None, files_changed: list = None) -> dict:
"""Save session state to checkpoint file.
Args:
summary: what was accomplished (2-3 sentences)
key_decisions: important decisions made
files_changed: key files created or modified
"""
ts = datetime.now().strftime("%Y-%m-%d_%H%M")
CHECKPOINT_DIR.mkdir(parents=True, exist_ok=True)
checkpoint_path = CHECKPOINT_DIR / f"checkpoint_{ts}.md"
actions = list(session_actions)
file_content = f"""# Session Checkpoint — {ts}
## Summary
{summary}
## Key Decisions
{chr(10).join(f'- {d}' for d in (key_decisions or [])) or '(none)'}
## Files Changed
{chr(10).join(f'- {f}' for f in (files_changed or [])) or '(none)'}
## Session Actions ({len(actions)} total)
{chr(10).join(f'- [{a.get("action")}] {a.get("detail", "")}' for a in actions[-20:]) or '(none)'}
## Resume Context
Pick up from here next session. Key state:
- {summary}
"""
checkpoint_path.write_text(file_content)
if len(actions) > 10:
content_capture(moment=f"Productive session: {summary}", category="journey")
return {"saved": str(checkpoint_path), "actions_logged": len(actions)}
# --- Persistent audit log (P1 #6) ---
AUDIT_DIR = Path.home() / ".claude" / "audit"
_SESSION_ID = datetime.now().strftime("%Y%m%d_%H%M%S")
def _audit_append(action: str, detail: str):
"""Append a JSONL entry to the daily audit file."""
import json
AUDIT_DIR.mkdir(parents=True, exist_ok=True)
date_str = datetime.now().strftime("%Y-%m-%d")
audit_file = AUDIT_DIR / f"{date_str}.jsonl"
entry = json.dumps({
"timestamp": datetime.now().isoformat(),
"action": action,
"detail": detail,
"session": _SESSION_ID
})
with open(audit_file, "a") as f:
f.write(entry + "\n")
def audit_query(date: str = "", action_filter: str = "", limit: int = 50) -> dict:
"""Read audit log entries with optional filters.
Args:
date: filter by date (YYYY-MM-DD). Empty = today.
action_filter: filter by action type substring.
limit: max entries to return.
"""
import json
AUDIT_DIR.mkdir(parents=True, exist_ok=True)
if date:
files = [AUDIT_DIR / f"{date}.jsonl"]
else:
files = sorted(AUDIT_DIR.glob("*.jsonl"), reverse=True)
entries = []
for f in files:
if not f.exists():
continue
for line in f.read_text().splitlines():
line = line.strip()
if not line:
continue
try:
entry = json.loads(line)
except json.JSONDecodeError:
continue
if action_filter and action_filter not in entry.get("action", ""):
continue
entries.append(entry)
if len(entries) >= limit:
break
if len(entries) >= limit:
break
return {"entries": entries, "total": len(entries)}
# --- Session log ---
def session_log(action: str = "", detail: str = "", query: bool = False) -> dict:
"""Log a session action or query the log.
Args:
action: action type (e.g. "git_push", "file_edit", "agent_spawn")
detail: additional detail
query: if True, return the log instead of appending
"""
if query:
return {"actions": list(session_actions)[-20:]}
if action:
session_actions.append({
"action": action,
"detail": detail,
"timestamp": time.time()
})
# Also persist to audit log (P1 #6)
_audit_append(action, detail)
return {"logged": True, "total": len(session_actions)}
return {"error": "provide action or set query=True"}
# --- Git commit+push (async helper for admin bot) ---
def git_commit_push_async(message: str = "auto: content update"):
"""Commit and push content_drafts changes. Non-blocking."""
import subprocess
import threading
def _do():
repo = os.environ.get("VPS_REPO_PATH", "")
if not repo:
return
subprocess.run(["git", "-C", repo, "add", "content_drafts/"], capture_output=True)
subprocess.run(["git", "-C", repo, "commit", "-m", message], capture_output=True)
subprocess.run(["git", "-C", repo, "push"], capture_output=True)
threading.Thread(target=_do, daemon=True).start()