lockmaster 0.0.1__py3-none-any.whl
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.
- lockmaster/__init__.py +3 -0
- lockmaster/__main__.py +3 -0
- lockmaster/cli.py +225 -0
- lockmaster/config.py +195 -0
- lockmaster/doctor.py +146 -0
- lockmaster/drivers.py +93 -0
- lockmaster/generated.py +65 -0
- lockmaster/git.py +102 -0
- lockmaster/install.py +229 -0
- lockmaster/kit/claude/hooks/auto-land.py +286 -0
- lockmaster/kit/claude/hooks/block-main.py +174 -0
- lockmaster/kit/claude/hooks/claim-guard.py +133 -0
- lockmaster/kit/claude/hooks/disk-budget.py +199 -0
- lockmaster/kit/claude/hooks/guard-open-work-inbox.sh +17 -0
- lockmaster/kit/claude/hooks/inject-inbox.sh +54 -0
- lockmaster/kit/claude/hooks/now-ledger.py +371 -0
- lockmaster/kit/claude/hooks/release-locks.sh +34 -0
- lockmaster/kit/claude/hooks/require-progress.sh +15 -0
- lockmaster/kit/claude/hooks/session-lock.sh +58 -0
- lockmaster/kit/claude/hooks/stop-if-blocked.sh +20 -0
- lockmaster/kit/claude/hooks/work-files.py +128 -0
- lockmaster/kit/claude/hooks/worktree-cleanup.py +159 -0
- lockmaster/kit/claude/settings.json +197 -0
- lockmaster/kit/claude/skills/docket/SKILL.md +89 -0
- lockmaster/kit/claude/skills/landing/SKILL.md +68 -0
- lockmaster/kit/work/BACKLOG.md +12 -0
- lockmaster/kit/work/INTERVIEW.md +22 -0
- lockmaster/kit/work/LESSONS.md +12 -0
- lockmaster/kit/work/MACHINE.md +20 -0
- lockmaster/kit/work/OPEN-WORK.md +24 -0
- lockmaster/kit/work/WORKLOG.md +24 -0
- lockmaster/land.py +1328 -0
- lockmaster/merge.py +99 -0
- lockmaster/now.py +92 -0
- lockmaster/repo.py +268 -0
- lockmaster/status.py +119 -0
- lockmaster/surface.py +102 -0
- lockmaster-0.0.1.dist-info/METADATA +130 -0
- lockmaster-0.0.1.dist-info/RECORD +43 -0
- lockmaster-0.0.1.dist-info/WHEEL +5 -0
- lockmaster-0.0.1.dist-info/entry_points.txt +2 -0
- lockmaster-0.0.1.dist-info/licenses/LICENSE +23 -0
- lockmaster-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""NOW ledger — SR-WORK-NOW decisions 2-5: work/NOW.md holds only what is live.
|
|
3
|
+
|
|
4
|
+
start SessionStart add this session's row; close dead sessions
|
|
5
|
+
show UserPromptSubmit heartbeat; close dead sessions
|
|
6
|
+
sync PostToolUse heartbeat; list worktrees this session created,
|
|
7
|
+
drop path rows whose path is gone
|
|
8
|
+
stop Stop ask once for an empty `working on` cell
|
|
9
|
+
end SessionEnd clean or queue what the session left
|
|
10
|
+
(SR-WORK-CLEANUP), then remove its rows
|
|
11
|
+
|
|
12
|
+
A session is dead with no heartbeat for 6 hours; a row with no heartbeat at
|
|
13
|
+
all (a Cowork session's) once it started more than 6 hours ago. Hook input is
|
|
14
|
+
JSON on stdin; `show </dev/null` by hand closes dead sessions.
|
|
15
|
+
"""
|
|
16
|
+
import importlib.util
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import socket
|
|
21
|
+
import subprocess
|
|
22
|
+
import sys
|
|
23
|
+
import time
|
|
24
|
+
from datetime import date, datetime
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
ROOT = Path(__file__).resolve().parents[2]
|
|
28
|
+
NOW_MD = ROOT / "work" / "NOW.md"
|
|
29
|
+
TMP = ROOT / "work" / ".NOW.md.tmp"
|
|
30
|
+
LOCK = ROOT / ".claude" / ".now.lock"
|
|
31
|
+
SESSIONS = ROOT / ".claude" / ".sessions"
|
|
32
|
+
NUDGED = ROOT / ".claude" / ".now-nudged"
|
|
33
|
+
OPEN_WORK = ROOT / "work" / "OPEN-WORK.md"
|
|
34
|
+
DEAD_S = 6 * 3600
|
|
35
|
+
LOCK_S = 30
|
|
36
|
+
# Rows whose `where` is a path on this host: dropped once the path is gone.
|
|
37
|
+
PATH_KINDS = {"worktree", "files", "folder", "dir", "clone", "build"}
|
|
38
|
+
|
|
39
|
+
FLIGHT_HEAD = "| session | surface | started | working on |"
|
|
40
|
+
RES_HEAD = "| kind | where | host | session | created |"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# ---------------------------------------------------------------- NOW.md I/O
|
|
44
|
+
|
|
45
|
+
class Locked:
|
|
46
|
+
"""mkdir mutex on .claude/.now.lock; reclaimed after 30 seconds."""
|
|
47
|
+
|
|
48
|
+
def __enter__(self):
|
|
49
|
+
for _ in range(100):
|
|
50
|
+
try:
|
|
51
|
+
LOCK.mkdir()
|
|
52
|
+
return self
|
|
53
|
+
except FileExistsError:
|
|
54
|
+
try:
|
|
55
|
+
if time.time() - LOCK.stat().st_mtime > LOCK_S:
|
|
56
|
+
LOCK.rmdir()
|
|
57
|
+
continue
|
|
58
|
+
except OSError:
|
|
59
|
+
continue
|
|
60
|
+
time.sleep(0.1)
|
|
61
|
+
return self # never wedge a session on its own ledger
|
|
62
|
+
|
|
63
|
+
def __exit__(self, *_):
|
|
64
|
+
try:
|
|
65
|
+
LOCK.rmdir()
|
|
66
|
+
except OSError:
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def cells(line):
|
|
71
|
+
return [c.strip() for c in line.strip().strip("|").split("|")]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def read_now():
|
|
75
|
+
"""(prose_before_tables, flight_rows, resource_rows) — rows as cell lists."""
|
|
76
|
+
text = NOW_MD.read_text(encoding="utf-8")
|
|
77
|
+
head, _, _ = text.partition("## In flight")
|
|
78
|
+
flight, res, section = [], [], None
|
|
79
|
+
for line in text.splitlines():
|
|
80
|
+
if line.startswith("## In flight"):
|
|
81
|
+
section = flight
|
|
82
|
+
elif line.startswith("## Resources"):
|
|
83
|
+
section = res
|
|
84
|
+
elif section is not None and line.startswith("|") and not line.startswith("|---"):
|
|
85
|
+
c = cells(line)
|
|
86
|
+
if c[0] in ("session", "kind"):
|
|
87
|
+
continue
|
|
88
|
+
section.append(c)
|
|
89
|
+
return head.rstrip() + "\n", flight, res
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def renderer():
|
|
93
|
+
"""lockmaster's NOW.md renderer (`lockmaster.now`) when it is importable —
|
|
94
|
+
installed, or this repository's own src/ — so NOW.md always equals
|
|
95
|
+
`lockmaster status --now` (SR-ARCHITECTURE decision 14, W-07)."""
|
|
96
|
+
for extra in (None, ROOT / "src"):
|
|
97
|
+
if extra is not None:
|
|
98
|
+
if not (extra / "lockmaster" / "now.py").is_file():
|
|
99
|
+
continue
|
|
100
|
+
sys.path.insert(0, str(extra))
|
|
101
|
+
try:
|
|
102
|
+
from lockmaster import now
|
|
103
|
+
return now
|
|
104
|
+
except ImportError:
|
|
105
|
+
continue
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def write_now(head, flight, res):
|
|
110
|
+
mod = renderer()
|
|
111
|
+
if mod is not None:
|
|
112
|
+
text = mod.format_now(head, flight, mod.normalise(res, ROOT))
|
|
113
|
+
else:
|
|
114
|
+
# The same shape lockmaster.now writes, for a repo without lockmaster.
|
|
115
|
+
def table(header, rows, n):
|
|
116
|
+
out = [header, "|" + "---|" * n]
|
|
117
|
+
out += ["| " + " | ".join((r + [""] * n)[:n]) + " |" for r in rows]
|
|
118
|
+
return "\n".join(out)
|
|
119
|
+
|
|
120
|
+
res = [r for r in res if not (r[0] in PATH_KINDS and (p := where_path(r[1])) is not None
|
|
121
|
+
and not p.exists())]
|
|
122
|
+
text = (f"{head}\n## In flight\n\n{table(FLIGHT_HEAD, flight, 4)}\n\n"
|
|
123
|
+
f"## Resources this session created\n\n{table(RES_HEAD, res, 5)}\n")
|
|
124
|
+
TMP.write_text(text, encoding="utf-8")
|
|
125
|
+
os.replace(TMP, NOW_MD)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ---------------------------------------------------------------- sessions
|
|
129
|
+
|
|
130
|
+
def beat_file(sid):
|
|
131
|
+
return SESSIONS / f"{re.sub(r'[^A-Za-z0-9_.-]', '_', sid)}.json"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def beat(sid, **extra):
|
|
135
|
+
SESSIONS.mkdir(parents=True, exist_ok=True)
|
|
136
|
+
f = beat_file(sid)
|
|
137
|
+
try:
|
|
138
|
+
st = json.loads(f.read_text(encoding="utf-8"))
|
|
139
|
+
except (OSError, ValueError):
|
|
140
|
+
st = {"started": time.time(), "worktrees": worktree_paths()}
|
|
141
|
+
st.update(extra, beat=time.time())
|
|
142
|
+
f.write_text(json.dumps(st), encoding="utf-8")
|
|
143
|
+
return st
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def worktree_paths():
|
|
147
|
+
out = subprocess.run(["git", "worktree", "list", "--porcelain"], cwd=ROOT,
|
|
148
|
+
capture_output=True, text=True).stdout
|
|
149
|
+
paths = [l[9:] for l in out.splitlines() if l.startswith("worktree ")]
|
|
150
|
+
return [p for p in paths if os.path.realpath(p) != os.path.realpath(ROOT)]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def started_epoch(cell):
|
|
154
|
+
for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
|
155
|
+
try:
|
|
156
|
+
return datetime.strptime(cell.strip("` "), fmt).timestamp()
|
|
157
|
+
except ValueError:
|
|
158
|
+
pass
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def dead(row):
|
|
163
|
+
sid = row[0].strip("`")
|
|
164
|
+
f = beat_file(sid)
|
|
165
|
+
if f.exists():
|
|
166
|
+
try:
|
|
167
|
+
return time.time() - json.loads(f.read_text(encoding="utf-8"))["beat"] > DEAD_S
|
|
168
|
+
except (OSError, ValueError, KeyError):
|
|
169
|
+
return True
|
|
170
|
+
t = started_epoch(row[2]) if len(row) > 2 else None
|
|
171
|
+
return t is not None and time.time() - t > DEAD_S
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def where_path(cell):
|
|
175
|
+
m = re.search(r"`([^`]+)`", cell)
|
|
176
|
+
if not m:
|
|
177
|
+
return None
|
|
178
|
+
p = Path(m.group(1).rstrip("/"))
|
|
179
|
+
return p if p.is_absolute() else ROOT / p
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# ---------------------------------------------------------------- cleanup
|
|
183
|
+
|
|
184
|
+
def cleanup_module():
|
|
185
|
+
spec = importlib.util.spec_from_file_location(
|
|
186
|
+
"worktree_cleanup", Path(__file__).with_name("worktree-cleanup.py"))
|
|
187
|
+
mod = importlib.util.module_from_spec(spec)
|
|
188
|
+
spec.loader.exec_module(mod)
|
|
189
|
+
return mod
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def next_id():
|
|
193
|
+
seen = [0]
|
|
194
|
+
for d in (ROOT / "work" / "open", ROOT / "archive" / "open"):
|
|
195
|
+
seen += [int(m.group(1)) for f in d.glob("W-*.md")
|
|
196
|
+
if (m := re.match(r"W-(\d+)", f.name))]
|
|
197
|
+
for f in (OPEN_WORK, ROOT / "work" / "BACKLOG.md"):
|
|
198
|
+
try:
|
|
199
|
+
seen += [int(x) for x in re.findall(r"\bW-(\d+)\b", f.read_text(encoding="utf-8"))]
|
|
200
|
+
except OSError:
|
|
201
|
+
pass
|
|
202
|
+
return max(seen) + 1
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def file_item(ball, lane, title, body, sid):
|
|
206
|
+
"""One item file + one OPEN-WORK row (and, for red, an inbox row), in the
|
|
207
|
+
queue's own row style; the `### build (N)` count moves with the row."""
|
|
208
|
+
n = next_id()
|
|
209
|
+
wid, slug = f"W-{n:02d}", "session-cleanup"
|
|
210
|
+
today = date.today().isoformat()
|
|
211
|
+
by = "now-ledger.py (Claude Code)"
|
|
212
|
+
path = ROOT / "work" / "open" / f"{wid}-{slug}.md"
|
|
213
|
+
path.write_text(
|
|
214
|
+
f"---\ntype: Handoff\nname: {wid}\ndescription: \"{title}\"\nitem: {wid}\n"
|
|
215
|
+
f"filed: {today}\nfiled_by: \"{by}\"\n"
|
|
216
|
+
f"updated: {today}\nupdated_by: \"{by}\"\nball: {'arpit' if ball == '🔴' else lane}\n---\n\n"
|
|
217
|
+
f"# {wid} — {title}\n\n## At a glance\n\n| what | state |\n|---|---|\n"
|
|
218
|
+
f"| {title} | ⏳ |\n\nFiled at the end of session `{sid}`.\n\n{body}\n\n## Record affected\n\n"
|
|
219
|
+
f"No SR affected — the rule is SR-WORK-CLEANUP.\n",
|
|
220
|
+
encoding="utf-8")
|
|
221
|
+
text = OPEN_WORK.read_text(encoding="utf-8")
|
|
222
|
+
bullets = re.search(r"^- (🔴|🟣|🟡|🟢)", text, re.M) is not None
|
|
223
|
+
row = (f"- {ball} **{wid}** · `{lane}` — {title}." if bullets else f"{ball} **{wid}** `{lane}` {title}.") + \
|
|
224
|
+
f" Filed by {by}. [detail](open/{wid}-{slug}.md)"
|
|
225
|
+
|
|
226
|
+
def bump(m):
|
|
227
|
+
return f"{m.group(1)} ({int(m.group(2) or 0) + 1})\n\n{row}\n\n"
|
|
228
|
+
text, filed = re.subn(r"^(### (?:\S+ )?build)(?: \((\d+)\))?\n\n", bump, text, count=1, flags=re.M)
|
|
229
|
+
if filed: # `## Open items (N)` counts every row too (rule 37b)
|
|
230
|
+
text = re.sub(r"^(## Open items)(?: \((\d+)\))?$",
|
|
231
|
+
lambda m: f"{m.group(1)} ({int(m.group(2) or 0) + 1})", text, count=1, flags=re.M)
|
|
232
|
+
if ball == "🔴":
|
|
233
|
+
head = re.search(r"^## Blocked on [^\n]*\n\n(\| what[^\n]*)\n", text, re.M)
|
|
234
|
+
aged = head is not None and "| age |" in head.group(1)
|
|
235
|
+
inbox = (f"| 🔴 **{wid}** — keep or drop each worktree in [the item](open/{wid}-{slug}.md):"
|
|
236
|
+
f" removing it would lose data (SR-WORK-CLEANUP decision 3) | {today} |"
|
|
237
|
+
+ (" 0 d |" if aged else "") + "\n"
|
|
238
|
+
f"| ↳ **blocks:** nothing else in the queue | |" + (" |" if aged else "") + "\n")
|
|
239
|
+
text = re.sub(r"(^## Blocked on [^\n]*\n\n\| what[^\n]*\n\|---[^\n]*\n)",
|
|
240
|
+
lambda m: m.group(1) + inbox, text, count=1, flags=re.M)
|
|
241
|
+
text = re.sub(r"\n\*Empty since[^\n]*\n", "\n", text, count=1)
|
|
242
|
+
OPEN_WORK.write_text(text, encoding="utf-8")
|
|
243
|
+
return wid
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def close_session(sid, res):
|
|
247
|
+
"""SR-WORK-NOW decision 4: clean or queue what `sid` left; return the
|
|
248
|
+
resource rows that are not its."""
|
|
249
|
+
mine = [r for r in res if len(r) > 3 and r[3].strip("`") == sid]
|
|
250
|
+
keep = [r for r in res if r not in mine]
|
|
251
|
+
trees, other = [], []
|
|
252
|
+
for r in mine:
|
|
253
|
+
p = where_path(r[1])
|
|
254
|
+
if r[0] in PATH_KINDS and p is not None and not p.exists():
|
|
255
|
+
continue
|
|
256
|
+
(trees if r[0] == "worktree" and p is not None else other).append(r)
|
|
257
|
+
red = []
|
|
258
|
+
if trees:
|
|
259
|
+
try:
|
|
260
|
+
_, red = cleanup_module().sweep([str(where_path(r[1])) for r in trees], apply=True)
|
|
261
|
+
except Exception as e: # noqa: BLE001 — a failed check is red, the safe side
|
|
262
|
+
red = [(str(where_path(r[1])), [f"cleanup failed: {e}"]) for r in trees]
|
|
263
|
+
if red:
|
|
264
|
+
lines = "\n".join(f"- `{p}` — " + "; ".join(why) for p, why in red)
|
|
265
|
+
file_item("🔴", "arpit", f"Worktrees left by session {sid} would lose data if removed",
|
|
266
|
+
"These worktrees were left untouched. Rule per worktree: **keep** (merge it or"
|
|
267
|
+
" commit the files; the next cleanup removes it) or **drop** (only then may an"
|
|
268
|
+
" agent force the removal and delete the unmerged branch).\n\n" + lines, sid)
|
|
269
|
+
if other:
|
|
270
|
+
lines = "\n".join("- " + " · ".join(r) for r in other)
|
|
271
|
+
file_item("🟢", "agent", f"Clean up what session {sid} left",
|
|
272
|
+
"Clean each only if nothing is lost; otherwise turn this item red and put it"
|
|
273
|
+
" to the decider (SR-WORK-CLEANUP decision 7).\n\n" + lines, sid)
|
|
274
|
+
beat_file(sid).unlink(missing_ok=True)
|
|
275
|
+
return keep
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def reap(flight, res, me=None):
|
|
279
|
+
"""Close every dead session but `me`."""
|
|
280
|
+
for row in [r for r in flight if r[0].strip("`") != me and dead(r)]:
|
|
281
|
+
res = close_session(row[0].strip("`"), res)
|
|
282
|
+
flight.remove(row)
|
|
283
|
+
return flight, res
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
# ---------------------------------------------------------------- modes
|
|
287
|
+
|
|
288
|
+
def start(sid, _hook):
|
|
289
|
+
beat(sid)
|
|
290
|
+
with Locked():
|
|
291
|
+
head, flight, res = read_now()
|
|
292
|
+
flight, res = reap(flight, res, sid)
|
|
293
|
+
if not any(r[0].strip("`") == sid for r in flight):
|
|
294
|
+
flight.append([sid, "Claude Code", datetime.now().strftime("%Y-%m-%d %H:%M"), ""])
|
|
295
|
+
write_now(head, flight, res)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def show(sid, _hook):
|
|
299
|
+
if sid:
|
|
300
|
+
beat(sid)
|
|
301
|
+
with Locked():
|
|
302
|
+
head, flight, res = read_now()
|
|
303
|
+
n = (len(flight), len(res))
|
|
304
|
+
flight, res = reap(flight, res, sid)
|
|
305
|
+
if (len(flight), len(res)) != n:
|
|
306
|
+
write_now(head, flight, res)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def sync(sid, _hook):
|
|
310
|
+
st = beat(sid)
|
|
311
|
+
host = socket.gethostname().split(".")[0]
|
|
312
|
+
with Locked():
|
|
313
|
+
head, flight, res = read_now()
|
|
314
|
+
before = [list(r) for r in res]
|
|
315
|
+
listed = {os.path.realpath(str(p)) for r in res if (p := where_path(r[1]))}
|
|
316
|
+
for p in worktree_paths():
|
|
317
|
+
if p not in st.get("worktrees", []) and os.path.realpath(p) not in listed:
|
|
318
|
+
res.append(["worktree", f"`{p}`", host, sid, date.today().isoformat()])
|
|
319
|
+
res = [r for r in res if not (r[0] in PATH_KINDS and (p := where_path(r[1])) is not None
|
|
320
|
+
and not p.exists())]
|
|
321
|
+
if res != before:
|
|
322
|
+
write_now(head, flight, res)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def stop(sid, _hook):
|
|
326
|
+
_, flight, _ = read_now()
|
|
327
|
+
row = next((r for r in flight if r[0].strip("`") == sid), None)
|
|
328
|
+
if not row or (len(row) > 3 and row[3]):
|
|
329
|
+
return
|
|
330
|
+
seen = NUDGED.read_text(encoding="utf-8").split() if NUDGED.exists() else []
|
|
331
|
+
if sid in seen:
|
|
332
|
+
return
|
|
333
|
+
NUDGED.write_text(" ".join(seen + [sid]), encoding="utf-8")
|
|
334
|
+
print(json.dumps({"decision": "block", "reason":
|
|
335
|
+
f"work/NOW.md: this session's row ({sid}) has an empty `working on` cell."
|
|
336
|
+
" Fill it with what you are doing (the W-id when there is one), then stop"
|
|
337
|
+
" (SR-WORK-NOW decision 2)."}))
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def end(sid, _hook):
|
|
341
|
+
with Locked():
|
|
342
|
+
head, flight, res = read_now()
|
|
343
|
+
res = close_session(sid, res)
|
|
344
|
+
flight = [r for r in flight if r[0].strip("`") != sid]
|
|
345
|
+
flight, res = reap(flight, res, sid)
|
|
346
|
+
write_now(head, flight, res)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def main(argv):
|
|
350
|
+
if not NOW_MD.is_file():
|
|
351
|
+
return 0 # a repository without the work system has no NOW to keep (W-09)
|
|
352
|
+
mode = argv[0] if argv else "show"
|
|
353
|
+
fn = {"start": start, "show": show, "sync": sync, "stop": stop, "end": end}.get(mode)
|
|
354
|
+
if fn is None:
|
|
355
|
+
print(f"usage: now-ledger.py start|show|sync|stop|end (got {mode})", file=sys.stderr)
|
|
356
|
+
return 2
|
|
357
|
+
hook = {}
|
|
358
|
+
if not sys.stdin.isatty():
|
|
359
|
+
try:
|
|
360
|
+
hook = json.loads(sys.stdin.read() or "{}")
|
|
361
|
+
except ValueError:
|
|
362
|
+
hook = {}
|
|
363
|
+
sid = hook.get("session_id") or os.environ.get("CLAUDE_SESSION_ID", "")
|
|
364
|
+
if not sid and mode != "show":
|
|
365
|
+
return 0
|
|
366
|
+
fn(sid, hook)
|
|
367
|
+
return 0
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
if __name__ == "__main__":
|
|
371
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Stop / SessionEnd — SR-WORK-CLEANUP decisions 8-9: every lock a session takes
|
|
3
|
+
# is cleaned. Releases this session's per-asset write locks (session-lock.sh's),
|
|
4
|
+
# sweeps anyone's past the 900-second TTL,
|
|
5
|
+
# and removes git lock files older than 10 minutes while no git process runs.
|
|
6
|
+
set -uo pipefail
|
|
7
|
+
cd "$(dirname "$0")/../.." || exit 0
|
|
8
|
+
|
|
9
|
+
INPUT=$(cat 2>/dev/null || true)
|
|
10
|
+
ME=$(printf '%s' "$INPUT" | jq -r '.session_id // empty' 2>/dev/null)
|
|
11
|
+
ME="${ME:-${CLAUDE_SESSION_ID:-}}"
|
|
12
|
+
|
|
13
|
+
# Decision 8: this session's own write locks, and anyone's past the TTL.
|
|
14
|
+
NOW=$(date +%s); TTL=900
|
|
15
|
+
if [ -d .claude/.locks ]; then
|
|
16
|
+
for d in .claude/.locks/*/; do
|
|
17
|
+
[ -f "$d/owner" ] || continue
|
|
18
|
+
who=$(cut -d' ' -f1 "$d/owner"); when=$(cut -d' ' -f2 "$d/owner")
|
|
19
|
+
case "$when" in ''|*[!0-9]*) when=0 ;; esac
|
|
20
|
+
if { [ -n "$ME" ] && [ "$who" = "$ME" ]; } || [ $((NOW - when)) -gt $TTL ]; then rm -rf "$d"; fi
|
|
21
|
+
done
|
|
22
|
+
fi
|
|
23
|
+
|
|
24
|
+
# Decision 9: stale git locks — only while no git process runs.
|
|
25
|
+
GITDIR=$(git rev-parse --git-common-dir 2>/dev/null) || exit 0
|
|
26
|
+
pgrep -x git >/dev/null 2>&1 && exit 0
|
|
27
|
+
find "$GITDIR" -name '*.lock' -type f -mmin +10 -not -path '*/_stale_locks/*' 2>/dev/null |
|
|
28
|
+
while IFS= read -r f; do
|
|
29
|
+
rm -f "$f" 2>/dev/null && continue
|
|
30
|
+
# A surface that cannot unlink renames it aside instead.
|
|
31
|
+
mkdir -p "$GITDIR/_stale_locks" &&
|
|
32
|
+
mv "$f" "$GITDIR/_stale_locks/$(printf '%s' "${f#"$GITDIR"/}" | tr / _).$(date +%s)" 2>/dev/null
|
|
33
|
+
done
|
|
34
|
+
exit 0
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Stop hook — if the tree changed but work/NOW.md did not, the session worked
|
|
3
|
+
# silently. Nudge once, then relent.
|
|
4
|
+
set -uo pipefail
|
|
5
|
+
cd "$(dirname "$0")/../.." || exit 0
|
|
6
|
+
git rev-parse --git-dir >/dev/null 2>&1 || exit 0
|
|
7
|
+
[ -f work/NOW.md ] || exit 0 # a repository without the work system has no NOW to keep (W-09)
|
|
8
|
+
[ -n "$(git status --porcelain -- ':!work/NOW.md' 2>/dev/null)" ] || exit 0
|
|
9
|
+
[ -z "$(git status --porcelain -- work/NOW.md 2>/dev/null)" ] || exit 0
|
|
10
|
+
F=.claude/.progress-nudged
|
|
11
|
+
[ -f "$F" ] && exit 0
|
|
12
|
+
touch "$F"
|
|
13
|
+
jq -n '{hookSpecificOutput:{hookEventName:"Stop",decision:"block",
|
|
14
|
+
reason:"Files changed and work/NOW.md was never updated — the session worked without saying what it was doing. Write one line to work/NOW.md (or `idle` if you are stopping), state the transition, then stop."}}'
|
|
15
|
+
exit 0
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# PreToolUse(Write|Edit|MultiEdit|NotebookEdit) — per-asset write lock.
|
|
3
|
+
# Two sessions editing the SAME file is how a doc starts lying; two sessions
|
|
4
|
+
# editing DIFFERENT files run in parallel. mkdir is the mutex; TTL reclaims.
|
|
5
|
+
set -uo pipefail
|
|
6
|
+
cd "$(dirname "$0")/../.." || exit 0
|
|
7
|
+
|
|
8
|
+
LOCKS_DIR=.claude/.locks
|
|
9
|
+
mkdir -p "$LOCKS_DIR"
|
|
10
|
+
NOW=$(date +%s)
|
|
11
|
+
TTL=900
|
|
12
|
+
|
|
13
|
+
# Sweep every lock past its TTL (SR-WORK-CLEANUP decision 8).
|
|
14
|
+
for d in "$LOCKS_DIR"/*/; do
|
|
15
|
+
[ -f "$d/owner" ] || continue
|
|
16
|
+
[ $((NOW - $(cut -d' ' -f2 "$d/owner"))) -ge $TTL ] && rm -rf "$d"
|
|
17
|
+
done
|
|
18
|
+
|
|
19
|
+
INPUT=$(cat)
|
|
20
|
+
# The owner is the hook input's session_id: $PPID differs per tool call, so a
|
|
21
|
+
# session would otherwise lock itself out of the file it just wrote.
|
|
22
|
+
ME=$(printf '%s' "$INPUT" | jq -r '.session_id // empty' 2>/dev/null)
|
|
23
|
+
ME="${ME:-${CLAUDE_SESSION_ID:-$PPID}}"
|
|
24
|
+
FILE_PATH=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // .tool_input.notebook_path // empty' 2>/dev/null)
|
|
25
|
+
[ -z "$FILE_PATH" ] && exit 0
|
|
26
|
+
|
|
27
|
+
case "$FILE_PATH" in
|
|
28
|
+
/*) REL="${FILE_PATH#"$(pwd)"/}" ;;
|
|
29
|
+
*) REL="$FILE_PATH" ;;
|
|
30
|
+
esac
|
|
31
|
+
|
|
32
|
+
KEY=$(printf '%s' "$REL" | shasum -a 256 | cut -c1-16)
|
|
33
|
+
LOCKDIR="$LOCKS_DIR/$KEY"
|
|
34
|
+
OWNERFILE="$LOCKDIR/owner"
|
|
35
|
+
|
|
36
|
+
acquire() { echo "$ME $NOW $REL" > "$OWNERFILE"; }
|
|
37
|
+
|
|
38
|
+
if mkdir "$LOCKDIR" 2>/dev/null; then acquire; exit 0; fi
|
|
39
|
+
|
|
40
|
+
if [ -f "$OWNERFILE" ]; then
|
|
41
|
+
OWNER=$(cut -d' ' -f1 "$OWNERFILE"); WHEN=$(cut -d' ' -f2 "$OWNERFILE")
|
|
42
|
+
else
|
|
43
|
+
OWNER=""; WHEN=0
|
|
44
|
+
fi
|
|
45
|
+
|
|
46
|
+
if [ "$OWNER" = "$ME" ]; then acquire; exit 0; fi
|
|
47
|
+
|
|
48
|
+
if [ -n "$OWNER" ] && [ $((NOW - WHEN)) -lt $TTL ]; then
|
|
49
|
+
AGE=$((NOW - WHEN))
|
|
50
|
+
jq -n --arg o "$OWNER" --arg f "$REL" --arg age "$AGE" \
|
|
51
|
+
'{hookSpecificOutput:{hookEventName:"PreToolUse",
|
|
52
|
+
permissionDecision:"deny",
|
|
53
|
+
permissionDecisionReason:("Another Claude session (" + $o + ") is editing " + $f + " (touched " + $age + "s ago, lock TTL 900s). Do not write to " + $f + " — work on a different asset instead, or wait.")}}'
|
|
54
|
+
exit 0
|
|
55
|
+
fi
|
|
56
|
+
|
|
57
|
+
acquire
|
|
58
|
+
exit 0
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Stop hook — refuse to end a turn while a blocker is unsurfaced.
|
|
3
|
+
# Loop guard: three refusals, then let it stop and let the human read the file.
|
|
4
|
+
set -uo pipefail
|
|
5
|
+
cd "$(dirname "$0")/../.." || exit 0
|
|
6
|
+
B=work/BLOCKED.json
|
|
7
|
+
[ -s "$B" ] || exit 0
|
|
8
|
+
jq -e '.decision == "PROCEED"' "$B" >/dev/null 2>&1 && exit 0
|
|
9
|
+
jq -e '.surfaced == true' "$B" >/dev/null 2>&1 && exit 0
|
|
10
|
+
|
|
11
|
+
N=$(cat .claude/.stop-attempts 2>/dev/null || echo 0)
|
|
12
|
+
if [ "$N" -ge 3 ]; then rm -f .claude/.stop-attempts; exit 0; fi
|
|
13
|
+
echo $((N + 1)) > .claude/.stop-attempts
|
|
14
|
+
|
|
15
|
+
REASON=$(jq -r '"\(.decision): \(.reason)"' "$B" 2>/dev/null || echo "work/BLOCKED.json is unresolved")
|
|
16
|
+
DECIDER=$(git config user.name 2>/dev/null); DECIDER=${DECIDER:-the decider}
|
|
17
|
+
jq -n --arg r "$REASON" --arg d "$DECIDER" '{hookSpecificOutput:{hookEventName:"Stop",decision:"block",
|
|
18
|
+
reason:("A blocker is recorded and has not been surfaced to " + $d + " — " + $r +
|
|
19
|
+
" State it in one short paragraph, set .surfaced=true in work/BLOCKED.json, and stop. Do not work around it.")}}'
|
|
20
|
+
exit 0
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""The work files stay current — lockmaster's SR-LAW-10 decision 4, at the source (W-15).
|
|
3
|
+
|
|
4
|
+
edit PostToolUse(Write|Edit|MultiEdit|NotebookEdit) note the path this
|
|
5
|
+
session wrote, relative to its own checkout or worktree
|
|
6
|
+
stop Stop a session that wrote files outside `work/` and touched none of
|
|
7
|
+
work/WORKLOG.md, work/INTERVIEW.md, work/OPEN-WORK.md is told once,
|
|
8
|
+
before it stops, to update them in the same change
|
|
9
|
+
|
|
10
|
+
The notes live in git's own directory (`<git-common-dir>/lockmaster/sessions/`),
|
|
11
|
+
never in the tree. Whether a lesson, a machine quirk or a backlog row should
|
|
12
|
+
have been written is judgment; this hook does not judge it. A Stop reached
|
|
13
|
+
while already continuing for a Stop hook never blocks again. It never fails a
|
|
14
|
+
session. Python >= 3.9, standard library only; it does not need lockmaster.
|
|
15
|
+
"""
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
ROOT = Path(__file__).resolve().parents[2]
|
|
23
|
+
WATCHED = ("work/WORKLOG.md", "work/INTERVIEW.md", "work/OPEN-WORK.md")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def notes_file(sid):
|
|
27
|
+
try:
|
|
28
|
+
r = subprocess.run(["git", "rev-parse", "--git-common-dir"], cwd=str(ROOT), capture_output=True, text=True)
|
|
29
|
+
except OSError:
|
|
30
|
+
return None
|
|
31
|
+
if r.returncode != 0 or not r.stdout.strip():
|
|
32
|
+
return None
|
|
33
|
+
common = Path(r.stdout.strip())
|
|
34
|
+
common = common if common.is_absolute() else (ROOT / common).resolve()
|
|
35
|
+
safe = "".join(ch if ch.isalnum() or ch in "-_." else "_" for ch in sid)
|
|
36
|
+
return common / "lockmaster" / "sessions" / (safe + ".work-files.json")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def read(f):
|
|
40
|
+
try:
|
|
41
|
+
return json.loads(f.read_text(encoding="utf-8"))
|
|
42
|
+
except (OSError, ValueError):
|
|
43
|
+
return {"paths": []}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def write(f, notes):
|
|
47
|
+
f.parent.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
tmp = f.with_name(f.name + ".part")
|
|
49
|
+
tmp.write_text(json.dumps(notes, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
|
50
|
+
os.replace(str(tmp), str(f))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def relative(path):
|
|
54
|
+
"""`path` relative to the checkout or worktree holding it — this repository's
|
|
55
|
+
main checkout or one of its `.claude/worktrees/` — else None."""
|
|
56
|
+
root = os.path.realpath(str(ROOT))
|
|
57
|
+
full = os.path.realpath(str(path))
|
|
58
|
+
if not full.startswith(root + os.sep):
|
|
59
|
+
return None
|
|
60
|
+
rel = os.path.relpath(full, root).replace(os.sep, "/")
|
|
61
|
+
if rel.startswith(".claude/worktrees/"):
|
|
62
|
+
parts = rel.split("/")
|
|
63
|
+
if len(parts) < 4:
|
|
64
|
+
return None
|
|
65
|
+
rel = "/".join(parts[3:])
|
|
66
|
+
return rel
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def edit(sid, hook):
|
|
70
|
+
raw = (hook.get("tool_input") or {}).get("file_path") or (hook.get("tool_input") or {}).get("notebook_path")
|
|
71
|
+
f = notes_file(sid) if raw and sid else None
|
|
72
|
+
if f is None:
|
|
73
|
+
return None
|
|
74
|
+
p = Path(raw)
|
|
75
|
+
if not p.is_absolute():
|
|
76
|
+
p = Path(hook.get("cwd") or os.getcwd()) / p
|
|
77
|
+
rel = relative(p)
|
|
78
|
+
if rel is None:
|
|
79
|
+
return None
|
|
80
|
+
notes = read(f)
|
|
81
|
+
if rel not in notes["paths"]:
|
|
82
|
+
notes["paths"].append(rel)
|
|
83
|
+
write(f, notes)
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def stop(sid, hook):
|
|
88
|
+
f = notes_file(sid) if sid else None
|
|
89
|
+
if f is None or hook.get("stop_hook_active"):
|
|
90
|
+
return None
|
|
91
|
+
if not any((ROOT / w).is_file() for w in WATCHED):
|
|
92
|
+
return None # no work system here yet: `lockmaster doctor` names that (SR-LAW-10 decision 6)
|
|
93
|
+
notes = read(f)
|
|
94
|
+
paths = notes.get("paths") or []
|
|
95
|
+
outside = [p for p in paths if not p.startswith("work/")]
|
|
96
|
+
if not outside or any(p in WATCHED for p in paths) or notes.get("told"):
|
|
97
|
+
return None
|
|
98
|
+
notes["told"] = True
|
|
99
|
+
write(f, notes)
|
|
100
|
+
shown = ", ".join(outside[:5]) + (" and {} more".format(len(outside) - 5) if len(outside) > 5 else "")
|
|
101
|
+
return {"decision": "block", "reason": (
|
|
102
|
+
"This session changed {} but none of work/WORKLOG.md, work/INTERVIEW.md or work/OPEN-WORK.md. "
|
|
103
|
+
"The work files travel with the work they describe (lockmaster's L10): update the queue row, the "
|
|
104
|
+
"state of play and this session's worklog entry in the same change, then stop.").format(shown)}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def main(argv):
|
|
108
|
+
mode = argv[0] if argv else ""
|
|
109
|
+
fn = {"edit": edit, "stop": stop}.get(mode)
|
|
110
|
+
if fn is None:
|
|
111
|
+
print("usage: work-files.py edit|stop", file=sys.stderr)
|
|
112
|
+
return 0
|
|
113
|
+
try:
|
|
114
|
+
hook = json.loads(sys.stdin.read() or "{}") if not sys.stdin.isatty() else {}
|
|
115
|
+
except ValueError:
|
|
116
|
+
hook = {}
|
|
117
|
+
try:
|
|
118
|
+
result = fn(hook.get("session_id") or os.environ.get("CLAUDE_SESSION_ID", ""), hook)
|
|
119
|
+
except Exception as e: # noqa: BLE001 — never fail the session over a nudge
|
|
120
|
+
print("work-files.py {}: {}".format(mode, e), file=sys.stderr)
|
|
121
|
+
return 0
|
|
122
|
+
if result:
|
|
123
|
+
print(json.dumps(result))
|
|
124
|
+
return 0
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
if __name__ == "__main__":
|
|
128
|
+
sys.exit(main(sys.argv[1:]))
|