-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlock.sh
More file actions
193 lines (181 loc) · 5.58 KB
/
Copy pathlock.sh
File metadata and controls
193 lines (181 loc) · 5.58 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
#!/bin/bash
# lock.sh — agent lock manager
# Usage:
# ./lock.sh acquire <file> <agent-slug> acquire lock before editing
# ./lock.sh release <file> <agent-slug> release lock after done
# ./lock.sh wait <file> <pane> <agent-slug> register as waiting
# ./lock.sh status show all locks and waiters
# ./lock.sh check <file> exit 0 if free, exit 1 if locked
# ./lock.sh heartbeat <file> <agent-slug> update heartbeat timestamp
# ./lock.sh cleanup remove stale locks (>15 min no heartbeat)
set -e
LOCK_FILE=".agent-locks.json"
STALE_MINUTES=15
# ensure lock file exists and is valid
if [ ! -f "$LOCK_FILE" ]; then
echo '{"schema_version":"1","locks":[],"waiting":[]}' > "$LOCK_FILE"
fi
# validate JSON before any operation
python3 -c "import json; json.load(open('$LOCK_FILE'))" 2>/dev/null || {
echo "⚠ $LOCK_FILE is corrupt. Resetting."
echo '{"schema_version":"1","locks":[],"waiting":[]}' > "$LOCK_FILE"
}
NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
case $1 in
acquire)
FILE=$2; AGENT=$3
if [ -z "$FILE" ] || [ -z "$AGENT" ]; then
echo "Usage: $0 acquire <file> <agent-slug>"; exit 1
fi
python3 - <<EOF
import json, sys
data = json.load(open("$LOCK_FILE"))
locks = data.get("locks", [])
# check if already locked by someone else
for l in locks:
if l["file"] == "$FILE" and l["agent"] != "$AGENT":
print(f"✗ LOCKED by {l['agent']} since {l['locked_since']}")
sys.exit(1)
# check if we already hold it
for l in locks:
if l["file"] == "$FILE" and l["agent"] == "$AGENT":
print(f"✓ Already held by $AGENT")
sys.exit(0)
# acquire
locks.append({
"file": "$FILE",
"agent": "$AGENT",
"locked_since": "$NOW",
"heartbeat": "$NOW",
"read_safe": False
})
data["locks"] = locks
# remove from waiting if present
data["waiting"] = [w for w in data.get("waiting", []) if not (w["file"] == "$FILE" and w["agent"] == "$AGENT")]
json.dump(data, open("$LOCK_FILE", "w"), indent=2)
print(f"✓ Lock acquired: $FILE by $AGENT")
EOF
;;
release)
FILE=$2; AGENT=$3
if [ -z "$FILE" ] || [ -z "$AGENT" ]; then
echo "Usage: $0 release <file> <agent-slug>"; exit 1
fi
python3 - <<EOF
import json
data = json.load(open("$LOCK_FILE"))
before = len(data.get("locks", []))
data["locks"] = [l for l in data.get("locks", []) if not (l["file"] == "$FILE" and l["agent"] == "$AGENT")]
after = len(data["locks"])
json.dump(data, open("$LOCK_FILE", "w"), indent=2)
if before > after:
print(f"✓ Lock released: $FILE by $AGENT")
else:
print(f"⚠ No lock found for $FILE by $AGENT (already released?)")
EOF
;;
wait)
FILE=$2; PANE=$3; AGENT=$4
if [ -z "$FILE" ] || [ -z "$PANE" ] || [ -z "$AGENT" ]; then
echo "Usage: $0 wait <file> <pane> <agent-slug>"; exit 1
fi
python3 - <<EOF
import json
data = json.load(open("$LOCK_FILE"))
waiting = data.get("waiting", [])
# avoid duplicate wait entries
for w in waiting:
if w["file"] == "$FILE" and w["agent"] == "$AGENT":
print(f"⚠ Already waiting for $FILE")
exit(0)
waiting.append({
"file": "$FILE",
"pane": "$PANE",
"agent": "$AGENT",
"waiting_since": "$NOW"
})
data["waiting"] = waiting
json.dump(data, open("$LOCK_FILE", "w"), indent=2)
print(f"✓ Registered as waiting: $AGENT waiting for $FILE (pane $PANE)")
print(f" Master watcher will resume you when the lock clears.")
EOF
;;
check)
FILE=$2
if [ -z "$FILE" ]; then
echo "Usage: $0 check <file>"; exit 1
fi
python3 - <<EOF
import json, sys
data = json.load(open("$LOCK_FILE"))
for l in data.get("locks", []):
if l["file"] == "$FILE":
print(f"LOCKED by {l['agent']} since {l['locked_since']}")
sys.exit(1)
print("FREE")
sys.exit(0)
EOF
;;
heartbeat)
FILE=$2; AGENT=$3
if [ -z "$FILE" ] || [ -z "$AGENT" ]; then
echo "Usage: $0 heartbeat <file> <agent-slug>"; exit 1
fi
python3 - <<EOF
import json
data = json.load(open("$LOCK_FILE"))
updated = False
for l in data.get("locks", []):
if l["file"] == "$FILE" and l["agent"] == "$AGENT":
l["heartbeat"] = "$NOW"
updated = True
json.dump(data, open("$LOCK_FILE", "w"), indent=2)
print(f"{'✓ Heartbeat updated' if updated else '⚠ Lock not found'}: $FILE by $AGENT")
EOF
;;
cleanup)
python3 - <<EOF
import json
from datetime import datetime, timezone, timedelta
data = json.load(open("$LOCK_FILE"))
cutoff = datetime.now(timezone.utc) - timedelta(minutes=$STALE_MINUTES)
stale = []
active = []
for l in data.get("locks", []):
ts_str = l.get("heartbeat") or l.get("locked_since", "")
try:
ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
if ts < cutoff:
stale.append(l)
else:
active.append(l)
except:
stale.append(l)
data["locks"] = active
json.dump(data, open("$LOCK_FILE", "w"), indent=2)
if stale:
for s in stale:
print(f"✓ Removed stale lock: {s['file']} by {s['agent']}")
else:
print("✓ No stale locks found.")
EOF
;;
status)
python3 - <<EOF
import json
data = json.load(open("$LOCK_FILE"))
locks = data.get("locks", [])
waiting = data.get("waiting", [])
print(f"=== Locks ({len(locks)}) ===")
for l in locks:
print(f" {l['file']} — held by {l['agent']} since {l['locked_since']}")
print(f"=== Waiting ({len(waiting)}) ===")
for w in waiting:
print(f" {w['file']} — {w['agent']} in pane {w['pane']} since {w['waiting_since']}")
EOF
;;
*)
echo "Usage: $0 <acquire|release|wait|check|heartbeat|cleanup|status> [args]"
exit 1
;;
esac