-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathl1_auto_commit_push.py
More file actions
executable file
·212 lines (179 loc) · 7.03 KB
/
l1_auto_commit_push.py
File metadata and controls
executable file
·212 lines (179 loc) · 7.03 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
#!/usr/bin/env python3
# @bigd-hook-meta
# name: l1_auto_commit_push
# fires_on: PostToolUse
# relevant_intents: [git, sync, code, memory]
# irrelevant_intents: [bigd, telegram, docx, x_tweet, debug]
# cost_score: 1
# always_fire: false
"""L1 sync layer: auto-commit + push the just-edited file to its repo.
Fires after Write / Edit / NotebookEdit. If the changed file lives inside one
of the 5 always-synced repos, runs `git add <file> && git commit && git push`
asynchronously (fire-and-forget). Never blocks the tool.
Scope: 5 repos only (matches L2 sync_mac_vps.sh).
Granularity: just the changed file (narrow blast radius).
Push: yes, immediate (per Bernard 2026-04-27).
L1 owns per-write commits; L2 (sync_mac_vps.sh) still handles batch pushes
for files outside this hook's path (e.g. files written without a tool, or
backlog dirty state). L3 circuit-breaker (TBD) will pause L1 on repeated
push failures.
"""
import json
import subprocess
import sys
import time
from pathlib import Path
HOME = Path.home()
REPOS = {
"memory": HOME / ".claude" / "projects" / "-Users-bernard" / "memory",
"nardoworld": HOME / "NardoWorld",
"telegram-claude-bot": HOME / "telegram-claude-bot",
"claude-skills": HOME / ".claude" / "skills",
"claude-quality-gate": HOME / ".claude" / "hooks",
}
# Any other git repo can opt into L1 by placing this marker file at its root.
# Marker contents are ignored for now; presence alone is the signal.
OPT_IN_MARKER = ".claude-l1-sync"
LOG = Path("/tmp/l1_auto_commit_push.log")
def log(msg: str) -> None:
ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
try:
with LOG.open("a") as f:
f.write(f"[{ts}] {msg}\n")
except Exception:
pass
def find_repo(file_path: Path):
"""Locate the repo for a file. Eligibility:
1. Path lives under one of the hardcoded REPOS (always-on set), OR
2. Path lives under a git repo with the OPT_IN_MARKER at its root.
Returns (label, repo_root) or (None, None).
"""
try:
resolved = file_path.resolve()
except Exception:
return None, None
for label, root in REPOS.items():
try:
resolved.relative_to(root.resolve())
return label, root
except ValueError:
continue
# Walk up looking for .git AND the opt-in marker.
for parent in [resolved] + list(resolved.parents):
if (parent / ".git").exists() and (parent / OPT_IN_MARKER).exists():
return parent.name, parent
if (parent / ".git").exists():
return None, None # repo found but not opted-in
return None, None
def run(cmd, cwd):
return subprocess.run(
cmd, cwd=str(cwd), capture_output=True, text=True, timeout=10
)
def main() -> int:
try:
payload = json.load(sys.stdin)
except Exception as e:
log(f"stdin parse failed: {e}")
return 0
tool_input = payload.get("tool_input", {}) or {}
file_path_str = tool_input.get("file_path") or tool_input.get("notebook_path") or ""
if not file_path_str:
return 0
file_path = Path(file_path_str)
if not file_path.exists():
return 0
label, repo_root = find_repo(file_path)
if not repo_root:
return 0
# Refuse to act on a repo that's mid-rebase / merge / cherry-pick / revert.
# The L2 sync script (sync_mac_vps.sh) has the same guard; mirroring here so
# auto-commits don't corrupt an in-progress operation.
git_dir = repo_root / ".git"
if (
(git_dir / "rebase-merge").is_dir()
or (git_dir / "rebase-apply").is_dir()
or (git_dir / "MERGE_HEAD").is_file()
or (git_dir / "CHERRY_PICK_HEAD").is_file()
or (git_dir / "REVERT_HEAD").is_file()
):
log(f"[{label}] SKIP rebase/merge/cherry-pick/revert in progress")
return 0
try:
rel = file_path.resolve().relative_to(repo_root.resolve())
except Exception:
return 0
# Skip git-internal + ignored files
if str(rel).startswith(".git/"):
return 0
check = run(["git", "check-ignore", "-q", str(rel)], repo_root)
if check.returncode == 0:
return 0
# Stage just this file. If nothing changed, exit clean.
add = run(["git", "add", "--", str(rel)], repo_root)
if add.returncode != 0:
log(f"[{label}] git add failed: {add.stderr.strip()}")
return 0
diff = run(["git", "diff", "--cached", "--quiet"], repo_root)
if diff.returncode == 0:
return 0
ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
msg = f"l1-auto: {rel} @ {ts}"
commit = run(["git", "commit", "-m", msg, "--", str(rel)], repo_root)
if commit.returncode != 0:
log(f"[{label}] commit failed: {commit.stderr.strip() or commit.stdout.strip()}")
return 0
log(f"[{label}] committed {rel}")
# L3 breaker: skip push if repo is currently tripped.
breaker = "/Users/bernard/.claude/scripts/sync_breaker.py"
gate = "/Users/bernard/.claude/scripts/gated_push.py"
repo_str = str(repo_root)
tripped = run(["python3", breaker, "check", repo_str], repo_root)
if tripped.returncode != 0:
log(f"[{label}] SKIP push — breaker TRIPPED (run sync_breaker.py reset to clear)")
return 0
# Anti-stampede: skip push if another L1 push for this repo is in flight.
# Prevents the racing-push problem when many edits happen quickly + each
# spawns its own gated_push, all fighting over the same remote
# (esp. expensive when remote is slow/transcontinental like Vultr-London).
# Lock file: /tmp/l1_push_<label>.lock — Popen-side touches+removes.
lock_path = Path(f"/tmp/l1_push_{label}.lock")
if lock_path.exists():
# Stale-lock guard: ignore lock older than 600s (push hung/crashed).
try:
age = time.time() - lock_path.stat().st_mtime
except Exception:
age = 0
if age < 600:
log(f"[{label}] SKIP push — another L1 push in flight (lock age {age:.0f}s)")
return 0
log(f"[{label}] removing stale lock (age {age:.0f}s)")
try:
lock_path.unlink()
except Exception:
pass
# Async gated push: scans diff for credential leaks before pushing to
# github.com remotes; non-github remotes (Hel/London bare) bypass scan.
# Breaker success/failure recorded inside gated_push.
push_log = f"/tmp/l1_push_{label}.log"
# Wrap with lock-file create+remove so subsequent L1 invocations can detect.
# `trap` ensures lock is cleared even if push fails or is killed.
cmd = (
f"trap 'rm -f {lock_path}' EXIT; "
f"touch {lock_path}; "
f"python3 {gate} {repo_str!r} >> {push_log} 2>&1"
)
try:
subprocess.Popen(
cmd,
shell=True,
cwd=str(repo_root),
start_new_session=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except Exception as e:
log(f"[{label}] push spawn failed: {e}")
return 0
if __name__ == "__main__":
sys.exit(main())