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.
Files changed (43) hide show
  1. lockmaster/__init__.py +3 -0
  2. lockmaster/__main__.py +3 -0
  3. lockmaster/cli.py +225 -0
  4. lockmaster/config.py +195 -0
  5. lockmaster/doctor.py +146 -0
  6. lockmaster/drivers.py +93 -0
  7. lockmaster/generated.py +65 -0
  8. lockmaster/git.py +102 -0
  9. lockmaster/install.py +229 -0
  10. lockmaster/kit/claude/hooks/auto-land.py +286 -0
  11. lockmaster/kit/claude/hooks/block-main.py +174 -0
  12. lockmaster/kit/claude/hooks/claim-guard.py +133 -0
  13. lockmaster/kit/claude/hooks/disk-budget.py +199 -0
  14. lockmaster/kit/claude/hooks/guard-open-work-inbox.sh +17 -0
  15. lockmaster/kit/claude/hooks/inject-inbox.sh +54 -0
  16. lockmaster/kit/claude/hooks/now-ledger.py +371 -0
  17. lockmaster/kit/claude/hooks/release-locks.sh +34 -0
  18. lockmaster/kit/claude/hooks/require-progress.sh +15 -0
  19. lockmaster/kit/claude/hooks/session-lock.sh +58 -0
  20. lockmaster/kit/claude/hooks/stop-if-blocked.sh +20 -0
  21. lockmaster/kit/claude/hooks/work-files.py +128 -0
  22. lockmaster/kit/claude/hooks/worktree-cleanup.py +159 -0
  23. lockmaster/kit/claude/settings.json +197 -0
  24. lockmaster/kit/claude/skills/docket/SKILL.md +89 -0
  25. lockmaster/kit/claude/skills/landing/SKILL.md +68 -0
  26. lockmaster/kit/work/BACKLOG.md +12 -0
  27. lockmaster/kit/work/INTERVIEW.md +22 -0
  28. lockmaster/kit/work/LESSONS.md +12 -0
  29. lockmaster/kit/work/MACHINE.md +20 -0
  30. lockmaster/kit/work/OPEN-WORK.md +24 -0
  31. lockmaster/kit/work/WORKLOG.md +24 -0
  32. lockmaster/land.py +1328 -0
  33. lockmaster/merge.py +99 -0
  34. lockmaster/now.py +92 -0
  35. lockmaster/repo.py +268 -0
  36. lockmaster/status.py +119 -0
  37. lockmaster/surface.py +102 -0
  38. lockmaster-0.0.1.dist-info/METADATA +130 -0
  39. lockmaster-0.0.1.dist-info/RECORD +43 -0
  40. lockmaster-0.0.1.dist-info/WHEEL +5 -0
  41. lockmaster-0.0.1.dist-info/entry_points.txt +2 -0
  42. lockmaster-0.0.1.dist-info/licenses/LICENSE +23 -0
  43. lockmaster-0.0.1.dist-info/top_level.txt +1 -0
lockmaster/merge.py ADDED
@@ -0,0 +1,99 @@
1
+ """The structural merge drivers — SR-ARCHITECTURE decision 10.
2
+
3
+ append-newest-first a worklog: both sides' new entries, the newer on top
4
+ table-rows a queue or table: both sides' new rows, a row both added kept once
5
+ append a lessons file: both sides' additions, in landing order
6
+
7
+ Git runs a driver as `merge.py <driver> %O %A %B %P` (ancestor, ours, theirs,
8
+ path) and reads the result from %A. When both sides only inserted lines at the
9
+ same place, the insertions are kept, one after the other. Every other overlap
10
+ goes to `git merge-file`, so a true conflict still conflicts: conflict markers
11
+ in %A and a non-zero exit. A driver never silently picks a side (W-03 hazard).
12
+
13
+ During a landing, "ours" is `main` and "theirs" is the change being landed, so
14
+ theirs is the newer side.
15
+
16
+ Standard library only, and importable without the rest of the package: git
17
+ calls this file directly.
18
+ """
19
+ import difflib
20
+ import subprocess
21
+ import sys
22
+
23
+ DRIVERS = ("append-newest-first", "table-rows", "append")
24
+
25
+
26
+ def _hunks(base, side):
27
+ sm = difflib.SequenceMatcher(None, base, side, autojunk=False)
28
+ return [(i1, i2, side[j1:j2]) for tag, i1, i2, j1, j2 in sm.get_opcodes() if tag != "equal"]
29
+
30
+
31
+ def merge_lines(driver, base, ours, theirs):
32
+ """The merged lines, or None when the two sides overlap in a way only a
33
+ three-way text merge (and maybe a person) can settle."""
34
+ if driver not in DRIVERS:
35
+ raise ValueError("no such driver: " + driver)
36
+ tagged = sorted([(h, "o") for h in _hunks(base, ours)] + [(h, "t") for h in _hunks(base, theirs)],
37
+ key=lambda x: (x[0][0], x[0][1]))
38
+ # Group hunks whose base ranges touch or overlap (closed intervals, as diff3 does).
39
+ groups = []
40
+ for h, side in tagged:
41
+ if groups and h[0] <= groups[-1]["end"]:
42
+ groups[-1]["items"].append((h, side))
43
+ groups[-1]["end"] = max(groups[-1]["end"], h[1])
44
+ else:
45
+ groups.append({"start": h[0], "end": h[1], "items": [(h, side)]})
46
+ out, pos = [], 0
47
+ for g in groups:
48
+ items = g["items"]
49
+ sides = {s for _, s in items}
50
+ if len(sides) == 1:
51
+ # One side only: apply its hunks in order.
52
+ for (i1, i2, lines), _ in items:
53
+ out += base[pos:i1] + lines
54
+ pos = i2
55
+ continue
56
+ if len(items) != 2:
57
+ return None
58
+ (a1, a2, a), (b1, b2, b) = (h for h, _ in items)
59
+ if (a1, a2, a) == (b1, b2, b):
60
+ out += base[pos:a1] + a # both made the same change
61
+ pos = a2
62
+ continue
63
+ if not (a1 == a2 == b1 == b2):
64
+ return None # an edit or deletion overlapping the other side
65
+ o = next(h for h, s in items if s == "o")[2]
66
+ t = next(h for h, s in items if s == "t")[2]
67
+ if driver == "table-rows":
68
+ t = [l for l in t if l not in o]
69
+ first, second = (t, o) if driver == "append-newest-first" else (o, t)
70
+ out += base[pos:a1] + first + second
71
+ pos = a1
72
+ return out + base[pos:]
73
+
74
+
75
+ def _read(path):
76
+ with open(path, "rb") as fh:
77
+ return fh.read().decode("utf-8", "surrogateescape").splitlines(True)
78
+
79
+
80
+ def main(argv):
81
+ if len(argv) < 4 or argv[0] not in DRIVERS:
82
+ print("usage: merge.py {" + "|".join(DRIVERS) + "} %O %A %B [%P]", file=sys.stderr)
83
+ return 2
84
+ driver, base_p, ours_p, theirs_p = argv[:4]
85
+ label = argv[4] if len(argv) > 4 else ours_p
86
+ merged = merge_lines(driver, _read(base_p), _read(ours_p), _read(theirs_p))
87
+ if merged is not None:
88
+ with open(ours_p, "wb") as fh:
89
+ fh.write("".join(merged).encode("utf-8", "surrogateescape"))
90
+ return 0
91
+ # Not a pure insertion on both sides: git's own three-way merge decides,
92
+ # and leaves conflict markers in %A when it cannot.
93
+ r = subprocess.run(["git", "merge-file", "-L", label + " (main)", "-L", label + " (base)",
94
+ "-L", label + " (change)", ours_p, base_p, theirs_p])
95
+ return 0 if r.returncode == 0 else 1
96
+
97
+
98
+ if __name__ == "__main__":
99
+ sys.exit(main(sys.argv[1:]))
lockmaster/now.py ADDED
@@ -0,0 +1,92 @@
1
+ """`work/NOW.md` as a generated view — SR-ARCHITECTURE decision 14, SR-WORK-NOW decisions 2-5.
2
+
3
+ The sessions in `## In flight` are the sessions' own (now-ledger.py adds and
4
+ closes them, a Cowork session by hand). What is computed is everything else:
5
+ a resource row whose path is gone leaves, and the file is always written in
6
+ one canonical shape. `render` is that computation; `lockmaster status --now`
7
+ prints it, every landing writes it, and the kit's now-ledger.py writes
8
+ through it, so NOW.md equals `lockmaster status --now` after each of them.
9
+ """
10
+ import os
11
+ import re
12
+ from pathlib import Path
13
+
14
+ FLIGHT_HEAD = "| session | surface | started | working on |"
15
+ RES_HEAD = "| kind | where | host | session | created |"
16
+ # Rows whose `where` is a path on this host: dropped once the path is gone.
17
+ PATH_KINDS = {"worktree", "files", "folder", "dir", "clone", "build"}
18
+ DEFAULT_HEAD = """---
19
+ type: Pointer
20
+ description: "Only what is being worked on right now: one row per live session, plus what those sessions created and have not yet cleaned. Empty when nothing is running."
21
+ ---
22
+
23
+ # NOW
24
+ """
25
+
26
+
27
+ def cells(line):
28
+ return [c.strip() for c in line.strip().strip("|").split("|")]
29
+
30
+
31
+ def parse(text):
32
+ """(prose before the tables, flight rows, resource rows) — rows as cell lists."""
33
+ head, _, _ = text.partition("## In flight")
34
+ flight, res, section = [], [], None
35
+ for line in text.splitlines():
36
+ if line.startswith("## In flight"):
37
+ section = flight
38
+ elif line.startswith("## Resources"):
39
+ section = res
40
+ elif section is not None and line.startswith("|") and not line.startswith("|---"):
41
+ c = cells(line)
42
+ if c[0] in ("session", "kind"):
43
+ continue
44
+ section.append(c)
45
+ return (head.rstrip() + "\n") if head.strip() else DEFAULT_HEAD, flight, res
46
+
47
+
48
+ def where_path(cell, root):
49
+ m = re.search(r"`([^`]+)`", cell)
50
+ if not m:
51
+ return None
52
+ p = Path(m.group(1).rstrip("/"))
53
+ return p if p.is_absolute() else Path(root) / p
54
+
55
+
56
+ def normalise(res, root):
57
+ return [r for r in res if not (r and r[0] in PATH_KINDS and len(r) > 1
58
+ and (p := where_path(r[1], root)) is not None and not p.exists())]
59
+
60
+
61
+ def format_now(head, flight, res):
62
+ def table(header, rows, n):
63
+ out = [header, "|" + "---|" * n]
64
+ out += ["| " + " | ".join((list(r) + [""] * n)[:n]) + " |" for r in rows]
65
+ return "\n".join(out)
66
+
67
+ return "{}\n## In flight\n\n{}\n\n## Resources this session created\n\n{}\n".format(
68
+ head, table(FLIGHT_HEAD, flight, 4), table(RES_HEAD, res, 5))
69
+
70
+
71
+ def render(text, root):
72
+ """NOW.md's text as it should be, given its current text."""
73
+ head, flight, res = parse(text)
74
+ return format_now(head, flight, normalise(res, root))
75
+
76
+
77
+ def now_path(root):
78
+ return Path(root) / "work" / "NOW.md"
79
+
80
+
81
+ def write_if_present(repo):
82
+ """Rewrite work/NOW.md in the primary checkout, when the repository keeps one."""
83
+ path = now_path(repo.root)
84
+ if not path.is_file():
85
+ return False
86
+ text = path.read_text(encoding="utf-8")
87
+ new = render(text, repo.root)
88
+ if new != text:
89
+ tmp = path.with_name(".NOW.md.tmp")
90
+ tmp.write_text(new, encoding="utf-8")
91
+ os.replace(str(tmp), str(path))
92
+ return True
lockmaster/repo.py ADDED
@@ -0,0 +1,268 @@
1
+ """The repository, lockmaster's state and the land lock — SR-ARCHITECTURE decisions 3, 4 and 7.
2
+
3
+ State lives at `$(git rev-parse --git-common-dir)/lockmaster/`: shared by every
4
+ worktree, never committed, gone with the clone. A change is one JSON file in
5
+ `changes/`; the land lock is a `mkdir` mutex holding the lander's pid.
6
+ """
7
+ import fnmatch
8
+ import json
9
+ import os
10
+ import re
11
+ import shlex
12
+ import stat
13
+ import time
14
+ from pathlib import Path
15
+
16
+ from lockmaster import config as config_mod
17
+ from lockmaster import git
18
+
19
+ ITEM_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
20
+ WORKTREES_DIR = ".claude/worktrees"
21
+
22
+ # A change's status, in the order it moves through them. WAITING (W-10): the
23
+ # landing commit is made and checked, and only uncommitted edits in main's
24
+ # checkout stop the fast-forward; it lands by itself once they clear.
25
+ OPEN, QUEUED, LANDING, LANDED, RED, ABANDONED = "open", "queued", "landing", "landed", "red", "abandoned"
26
+ WAITING = "waiting"
27
+ LIVE = (OPEN, QUEUED, LANDING, WAITING, RED)
28
+
29
+ # SR-ARCHITECTURE decision 18: the hooks that can refuse a step. A repository's
30
+ # post-* hooks (a re-index, a notification) are side effects of a person's or an
31
+ # agent's own git step; lockmaster's steps leave them out. What a landing must
32
+ # produce, it produces through [generated].
33
+ GATE_HOOKS = ("applypatch-msg", "pre-applypatch", "pre-commit", "pre-merge-commit",
34
+ "prepare-commit-msg", "commit-msg", "pre-rebase", "pre-push")
35
+ FORWARDER = """#!/bin/sh
36
+ # Written by lockmaster (SR-ARCHITECTURE decision 18): while lockmaster runs git,
37
+ # the repository's gate hooks run and its post-* hooks do not. Rewritten each run.
38
+ hook={}
39
+ [ -x "$hook" ] || exit 0
40
+ exec "$hook" "$@"
41
+ """
42
+
43
+
44
+ class LockmasterError(Exception):
45
+ """A refusal lockmaster explains to the person or agent who asked."""
46
+
47
+
48
+ class Repo:
49
+ def __init__(self, cwd="."):
50
+ cwd = Path(cwd).resolve()
51
+ code, top, _ = git.run(["rev-parse", "--show-toplevel"], cwd, check=False)
52
+ if code != 0:
53
+ raise LockmasterError("not inside a git repository: " + str(cwd))
54
+ self.cwd = cwd
55
+ self.toplevel = Path(top.strip())
56
+ common = Path(git.out(["rev-parse", "--git-common-dir"], cwd))
57
+ self.common = (cwd / common).resolve() if not common.is_absolute() else common
58
+ # The primary worktree is the first `git worktree list` entry.
59
+ self.root = Path(git.worktrees(cwd)[0]["path"])
60
+ self.state = self.common / "lockmaster"
61
+ self.changes_dir = self.state / "changes"
62
+ self._gate_hooks_only()
63
+ self.config = config_mod.load(self.root / config_mod.FILENAME)
64
+ self.main = self.config.main
65
+
66
+ def _gate_hooks_only(self):
67
+ """Point every git step lockmaster runs at forwarders for the repository's
68
+ gate hooks only (decision 18)."""
69
+ git.HOOKS = []
70
+ code, val, _ = git.run(["config", "--get", "core.hooksPath"], self.root, check=False)
71
+ real = Path(os.path.expanduser(val.strip())) if code == 0 and val.strip() else self.common / "hooks"
72
+ if not real.is_absolute():
73
+ real = self.root / real
74
+ hooks = self.state / "hooks"
75
+ try:
76
+ hooks.mkdir(parents=True, exist_ok=True)
77
+ for name in GATE_HOOKS:
78
+ f = hooks / name
79
+ text = FORWARDER.format(shlex.quote(str(real / name)))
80
+ if not f.is_file() or f.read_text(encoding="utf-8") != text:
81
+ f.write_text(text, encoding="utf-8")
82
+ f.chmod(f.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
83
+ except OSError:
84
+ return # cannot write the forwarders: run the repository's hooks as they are
85
+ git.HOOKS = ["-c", "core.hooksPath=" + str(hooks)]
86
+
87
+ # ------------------------------------------------------------ changes
88
+
89
+ def change_path(self, item):
90
+ return self.changes_dir / (item + ".json")
91
+
92
+ def load(self, item):
93
+ try:
94
+ with open(str(self.change_path(item)), encoding="utf-8") as fh:
95
+ return json.load(fh)
96
+ except FileNotFoundError:
97
+ return None
98
+
99
+ def save(self, change):
100
+ self.changes_dir.mkdir(parents=True, exist_ok=True)
101
+ change["updated"] = time.time()
102
+ path = self.change_path(change["item"])
103
+ tmp = path.with_name(path.name + ".tmp{}".format(os.getpid()))
104
+ tmp.write_text(json.dumps(change, indent=2, sort_keys=True) + "\n", encoding="utf-8")
105
+ os.replace(str(tmp), str(path))
106
+
107
+ def changes(self):
108
+ if not self.changes_dir.is_dir():
109
+ return []
110
+ out = []
111
+ for f in sorted(self.changes_dir.glob("*.json")):
112
+ try:
113
+ out.append(json.loads(f.read_text(encoding="utf-8")))
114
+ except (OSError, ValueError):
115
+ continue
116
+ return out
117
+
118
+ def current_change(self, item=None):
119
+ """The change named `item`, or the one whose worktree holds the cwd."""
120
+ if item:
121
+ change = self.load(item)
122
+ if change is None:
123
+ raise LockmasterError("no change " + item + " — `lockmaster start " + item + " --paths …` first")
124
+ return change
125
+ here = os.path.realpath(str(self.cwd))
126
+ for change in self.changes():
127
+ wt = os.path.realpath(change.get("worktree", ""))
128
+ if change["status"] in LIVE and (here == wt or here.startswith(wt + os.sep)):
129
+ return change
130
+ raise LockmasterError("not inside a change's worktree; name the item (--item W-nn)")
131
+
132
+ def change_holding(self, path):
133
+ """The live change whose worktree holds `path`, or None."""
134
+ here = os.path.realpath(str(path))
135
+ for change in self.changes():
136
+ wt = os.path.realpath(change.get("worktree", ""))
137
+ if change["status"] in LIVE and (here == wt or here.startswith(wt + os.sep)):
138
+ return change
139
+ return None
140
+
141
+ def worktree_for(self, item):
142
+ return self.root / WORKTREES_DIR / item
143
+
144
+ def exclude_worktrees(self):
145
+ """Keep `.claude/worktrees/` out of the primary checkout's status,
146
+ locally (`info/exclude`), so no tracked file has to change."""
147
+ info = self.common / "info"
148
+ info.mkdir(exist_ok=True)
149
+ exclude = info / "exclude"
150
+ text = exclude.read_text(encoding="utf-8") if exclude.exists() else ""
151
+ line = "/" + WORKTREES_DIR + "/"
152
+ if line not in text.split("\n"):
153
+ with exclude.open("a", encoding="utf-8") as fh:
154
+ fh.write(("" if text.endswith("\n") or not text else "\n") + line + "\n")
155
+
156
+
157
+ # ---------------------------------------------------------------- claims
158
+
159
+ def norm(path):
160
+ p = path.replace("\\", "/").strip()
161
+ while p.startswith("./"):
162
+ p = p[2:]
163
+ return p.rstrip("/") if p not in ("", "/") else p
164
+
165
+
166
+ def claimed(path, claims):
167
+ """A path is claimed when a claim names it, a directory above it, or a glob matching it."""
168
+ path = norm(path)
169
+ for c in claims:
170
+ c = norm(c)
171
+ if c in ("", ".", "*", "**"):
172
+ return True
173
+ if path == c or path.startswith(c + "/"):
174
+ return True
175
+ if any(ch in c for ch in "*?[") and (fnmatch.fnmatchcase(path, c) or fnmatch.fnmatchcase(path, c + "/*")):
176
+ return True
177
+ return False
178
+
179
+
180
+ def matches(path, pattern):
181
+ """For [generated] and [merge]: a path equals the pattern, sits under it, or matches its glob."""
182
+ return claimed(path, [pattern])
183
+
184
+
185
+ # ---------------------------------------------------------------- the land lock
186
+
187
+ def pid_alive(pid):
188
+ if os.name == "nt": # os.kill(pid, 0) would send CTRL_C_EVENT on Windows
189
+ import ctypes
190
+ handle = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
191
+ if not handle:
192
+ return False
193
+ code = ctypes.c_ulong()
194
+ ctypes.windll.kernel32.GetExitCodeProcess(handle, ctypes.byref(code))
195
+ ctypes.windll.kernel32.CloseHandle(handle)
196
+ return code.value == 259 # STILL_ACTIVE
197
+ try:
198
+ os.kill(pid, 0)
199
+ except ProcessLookupError:
200
+ return False
201
+ except PermissionError:
202
+ return True
203
+ except OSError:
204
+ return False
205
+ return True
206
+
207
+
208
+ class LandLock:
209
+ """Decision 7: one lander at a time. A `mkdir` mutex; its `pid` file names
210
+ the holder. A lock whose holder is dead is stale: it is moved aside
211
+ (atomically, so only one lander wins it) and taken."""
212
+
213
+ def __init__(self, repo, name="land.lock"):
214
+ self.dir = repo.state / name
215
+ self.held = False
216
+
217
+ def holder(self):
218
+ try:
219
+ return int((self.dir / "pid").read_text().strip())
220
+ except (OSError, ValueError):
221
+ return None
222
+
223
+ def stale(self):
224
+ if not self.dir.is_dir():
225
+ return False
226
+ pid = self.holder()
227
+ if pid is None:
228
+ # Created but no pid yet: stale only once it is old.
229
+ try:
230
+ return time.time() - self.dir.stat().st_mtime > 60
231
+ except OSError:
232
+ return False
233
+ return not pid_alive(pid)
234
+
235
+ def acquire(self):
236
+ self.dir.parent.mkdir(parents=True, exist_ok=True)
237
+ for _ in range(2):
238
+ try:
239
+ self.dir.mkdir()
240
+ except FileExistsError:
241
+ if not self.stale():
242
+ return False
243
+ aside = self.dir.with_name("{}.stale.{}.{}".format(self.dir.name, os.getpid(), int(time.time())))
244
+ try:
245
+ os.rename(str(self.dir), str(aside))
246
+ except OSError:
247
+ return False
248
+ for f in aside.iterdir():
249
+ f.unlink()
250
+ aside.rmdir()
251
+ continue
252
+ (self.dir / "pid").write_text(str(os.getpid()))
253
+ self.held = True
254
+ return True
255
+ return False
256
+
257
+ def release(self):
258
+ if not self.held:
259
+ return
260
+ try:
261
+ (self.dir / "pid").unlink()
262
+ except OSError:
263
+ pass
264
+ try:
265
+ self.dir.rmdir()
266
+ except OSError:
267
+ pass
268
+ self.held = False
lockmaster/status.py ADDED
@@ -0,0 +1,119 @@
1
+ """`lockmaster status` — SR-ARCHITECTURE decision 14: what is live, from git
2
+ and lockmaster's state, never from a hand-edited file.
3
+
4
+ sessions work/NOW.md's In flight rows, with each one's last heartbeat
5
+ changes every live change: status, branch, worktree, claim
6
+ worktrees every git worktree, and the change it belongs to
7
+ disk the project's size against work/MACHINE.md's budget (SR-LAW-2)
8
+ """
9
+ import json
10
+ import os
11
+ import re
12
+ import time
13
+ from pathlib import Path
14
+
15
+ from lockmaster import git
16
+ from lockmaster import now as now_mod
17
+ from lockmaster.repo import LIVE
18
+
19
+ BUDGET_RE = re.compile(r"^\|\s*budget\s*\|\s*([0-9.]+)\s*GB", re.M)
20
+
21
+
22
+ def disk_bytes(root):
23
+ total = 0
24
+ for d, dirs, files in os.walk(str(root)):
25
+ for f in files:
26
+ try:
27
+ total += os.lstat(os.path.join(d, f)).st_size
28
+ except OSError:
29
+ pass
30
+ return total
31
+
32
+
33
+ def budget_gb(root):
34
+ try:
35
+ m = BUDGET_RE.search((Path(root) / "work" / "MACHINE.md").read_text(encoding="utf-8"))
36
+ except OSError:
37
+ return None
38
+ return float(m.group(1)) if m else None
39
+
40
+
41
+ def heartbeat(root, sid):
42
+ f = Path(root) / ".claude" / ".sessions" / (re.sub(r"[^A-Za-z0-9_.-]", "_", sid) + ".json")
43
+ try:
44
+ return json.loads(f.read_text(encoding="utf-8")).get("beat")
45
+ except (OSError, ValueError):
46
+ return None
47
+
48
+
49
+ def ago(t):
50
+ s = int(time.time() - t)
51
+ for unit, n in (("d", 86400), ("h", 3600), ("m", 60)):
52
+ if s >= n:
53
+ return "{}{} ago".format(s // n, unit)
54
+ return "{}s ago".format(s)
55
+
56
+
57
+ def human(n):
58
+ for unit in ("B", "KB", "MB", "GB"):
59
+ if n < 1024 or unit == "GB":
60
+ return "{:.1f} {}".format(n, unit) if unit != "B" else "{} B".format(n)
61
+ n /= 1024.0
62
+
63
+
64
+ def report(repo):
65
+ lines = []
66
+ now_file = now_mod.now_path(repo.root)
67
+ lines.append("sessions")
68
+ if now_file.is_file():
69
+ _, flight, _ = now_mod.parse(now_file.read_text(encoding="utf-8"))
70
+ for r in flight:
71
+ sid = r[0].strip("`")
72
+ beat = heartbeat(repo.root, sid)
73
+ lines.append(" {} · {} · started {} · {} · {}".format(
74
+ sid, r[1] if len(r) > 1 else "", r[2] if len(r) > 2 else "",
75
+ (r[3] if len(r) > 3 and r[3] else "(working on: empty)"),
76
+ "heartbeat " + ago(beat) if beat else "no heartbeat"))
77
+ if not flight:
78
+ lines.append(" none")
79
+ else:
80
+ lines.append(" (no work/NOW.md)")
81
+
82
+ lines.append("changes")
83
+ live = [c for c in repo.changes() if c["status"] in LIVE]
84
+ for c in sorted(live, key=lambda c: c["item"]):
85
+ lines.append(" {} {} {} {} · claims {}".format(c["item"], c["status"], c["branch"], c["worktree"],
86
+ ", ".join(c["paths"])))
87
+ if c.get("reason"):
88
+ lines.append(" " + c["reason"].splitlines()[0])
89
+ if not live:
90
+ lines.append(" none")
91
+
92
+ from lockmaster import land
93
+ overlaps = land.checkout_overlaps(repo)
94
+ if overlaps: # W-10: the clash, before the landing
95
+ lines.append("main's checkout")
96
+ for item, st, paths in overlaps:
97
+ lines.append(" uncommitted {} — claimed by {} ({}): its landing waits until they are "
98
+ "committed, saved or undone".format(", ".join(paths), item, st))
99
+
100
+ lines.append("worktrees")
101
+ by_path = {os.path.realpath(c["worktree"]): c for c in live}
102
+ for t in git.worktrees(repo.root):
103
+ c = by_path.get(os.path.realpath(t["path"]))
104
+ label = "main checkout" if os.path.realpath(t["path"]) == os.path.realpath(str(repo.root)) else (
105
+ "change " + c["item"] if c else "not a live change's")
106
+ lines.append(" {} [{}] {}".format(t["path"], t["branch"] or "detached", label))
107
+
108
+ size, gb = disk_bytes(repo.root), budget_gb(repo.root)
109
+ if gb:
110
+ lines.append("disk\n {} of the {:g} GB budget ({:.0f} %)".format(human(size), gb, 100.0 * size / (gb * 1024 ** 3)))
111
+ else:
112
+ lines.append("disk\n {} (no budget row in work/MACHINE.md)".format(human(size)))
113
+ return lines
114
+
115
+
116
+ def now_text(repo):
117
+ path = now_mod.now_path(repo.root)
118
+ text = path.read_text(encoding="utf-8") if path.is_file() else ""
119
+ return now_mod.render(text, repo.root)
lockmaster/surface.py ADDED
@@ -0,0 +1,102 @@
1
+ """Can this surface commit? — SR-ARCHITECTURE decision 19.
2
+
3
+ A landing writes git's lock files and removes them, creates worktrees and
4
+ prunes the ones whose paths are gone. Two surfaces cannot do that safely:
5
+
6
+ - **a shell that cannot unlink** (the Cowork bridge until the decider allows
7
+ deletes): git's own lock files are left behind and every git write fails;
8
+ - **a checkout mounted from elsewhere** (the Cowork bridge sees the Mac's
9
+ repository under another path): the host's worktrees look missing from
10
+ here, so a `git worktree prune` here would cut them off.
11
+
12
+ On such a surface lockmaster commits nothing: `lockmaster save` hands the
13
+ edits to the next surface that can (`handoff`, `pickup` in land.py).
14
+
15
+ `home` is the primary checkout's path on the surface that commits, kept at
16
+ `<git-common-dir>/lockmaster/home`. When it is not yet written, it is read off
17
+ the worktree paths of lockmaster's own changes.
18
+ """
19
+ import os
20
+ from pathlib import Path
21
+
22
+ from lockmaster import git
23
+ from lockmaster.repo import WORKTREES_DIR
24
+
25
+ PROBE = "probe"
26
+ HOME = "home"
27
+
28
+
29
+ def can_unlink(repo):
30
+ """Write a probe file in the state directory and remove it. The probe has
31
+ one fixed name, so a surface that cannot remove it leaves one file, never
32
+ a pile."""
33
+ repo.state.mkdir(parents=True, exist_ok=True)
34
+ probe = repo.state / PROBE
35
+ try:
36
+ probe.write_text("lockmaster probe\n", encoding="utf-8")
37
+ except OSError:
38
+ return False
39
+ try:
40
+ probe.unlink()
41
+ except OSError:
42
+ return False
43
+ return True
44
+
45
+
46
+ def recorded_home(repo):
47
+ """The primary checkout's path where lockmaster committed, or None."""
48
+ try:
49
+ text = (repo.state / HOME).read_text(encoding="utf-8").strip()
50
+ if text:
51
+ return text
52
+ except OSError:
53
+ pass
54
+ tail = Path(WORKTREES_DIR).parts
55
+ for change in repo.changes():
56
+ wt = Path(change.get("worktree") or "")
57
+ parts = wt.parts
58
+ if len(parts) > len(tail) + 1 and parts[-len(tail) - 1:-1] == tail:
59
+ return str(Path(*parts[:-len(tail) - 1]))
60
+ return None
61
+
62
+
63
+ def foreign(repo):
64
+ """The reason this checkout is another host's, seen through a mount; or None.
65
+
66
+ Only evidence counts: git lists worktrees that do not exist here, outside
67
+ this checkout, under the recorded home or at a `.claude/worktrees/` path —
68
+ the ones a prune from this surface would cut off. A worktree of this
69
+ checkout's own that was deleted by hand is not evidence."""
70
+ here = os.path.realpath(str(repo.root))
71
+ home = recorded_home(repo)
72
+ if home and os.path.realpath(home) == here:
73
+ home = None
74
+ marker = "/" + WORKTREES_DIR + "/"
75
+ cut = []
76
+ for t in git.worktrees(repo.root):
77
+ p = t["path"]
78
+ if os.path.isdir(p) or os.path.realpath(p) == here or p.startswith(here + "/"):
79
+ continue
80
+ if (home and (p == home or p.startswith(home.rstrip("/") + "/"))) or marker in p:
81
+ cut.append(p)
82
+ if not cut:
83
+ return None
84
+ where = home or os.path.dirname(cut[0].split(marker)[0] + "/") or cut[0]
85
+ return ("this checkout ({}) is {} seen from another machine; {} of its worktree{} would be "
86
+ "cut off by a landing here").format(here, where, len(cut), "s" * (len(cut) != 1))
87
+
88
+
89
+ def can_commit(repo):
90
+ """(True, "") on a surface that may land; else (False, the reason)."""
91
+ if not can_unlink(repo):
92
+ return False, "this shell cannot remove files, so git cannot commit here"
93
+ why = foreign(repo)
94
+ if why:
95
+ return False, why
96
+ home = repo.state / HOME
97
+ try:
98
+ if not home.is_file(): # written once: a later surface never moves it
99
+ home.write_text(os.path.realpath(str(repo.root)) + "\n", encoding="utf-8")
100
+ except OSError:
101
+ pass
102
+ return True, ""