aisync-cli 0.2.7__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.
ai_sync/gate.py ADDED
@@ -0,0 +1,265 @@
1
+ """Push-time test gate (presubmit / required check), approved by the owner, 2026-11-02:
2
+ "tests passing is the one hard standard; every change updates its tests".
3
+
4
+ Contract: a repo that ships an executable `check.sh` at its root opts in. `./check.sh --fast` is the quick suite
5
+ (aim under ~90 s), `./check.sh` the full one, exit 0 = pass.
6
+
7
+ What the git `pre-push` hook (`aisync gate pre-push`) does for every ref pushed to refs/heads/main of such a repo:
8
+ 1. "fix needs a test": a pushed commit whose subject starts with `fix`, in a range that changes code files but
9
+ no test files, is refused.
10
+ 2. The pushed commit is checked out into a temporary worktree (so uncommitted local files cannot make it pass)
11
+ and `./check.sh --fast` runs there with GATE_DIFF_BASE=<remote sha>, so check.sh can run diff-cover on the
12
+ changed lines. A failure refuses the push and prints which tests failed.
13
+ Pushes to any other branch, and repos without check.sh, are never blocked. GATE_BYPASS=<reason> lets one push
14
+ through; every bypass is appended to state/gate_bypass.jsonl and logged as a `blocked` event.
15
+ A sha that passed once is remembered in state/gate_pass/ (so `aisync wt land`, which checks before pushing, does
16
+ not pay twice). Nested runs (tests inside check.sh that push to throwaway repos) see GATE_ACTIVE and skip.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import datetime as dt
21
+ import json
22
+ import os
23
+ import re
24
+ import shutil
25
+ import subprocess
26
+ import tempfile
27
+ import time
28
+ from pathlib import Path
29
+
30
+ from . import core, landq
31
+
32
+ ZERO = "0" * 40
33
+ MAIN_REF = "refs/heads/main"
34
+ CHECK_TIMEOUT = 900
35
+ REFUSED = 10 # exit code of `aisync gate pre-push` when it refuses; other failures mean the gate broke
36
+ CODE_EXT = {".py", ".sh", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".go", ".rs", ".rb", ".swift",
37
+ ".gd", ".cs", ".java", ".c", ".cc", ".cpp", ".h", ".hpp"}
38
+ _TEST_DIRS = {"tests", "test", "__tests__", "spec"}
39
+
40
+
41
+ # git exports these to hooks; inherited by check.sh they would point its git calls at the pushing repo's
42
+ # index or folder instead of the clean checkout under test
43
+ _HOOK_GIT_ENV = {"GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_PREFIX", "GIT_COMMON_DIR",
44
+ "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_QUARANTINE_PATH"}
45
+
46
+
47
+ def _git(repo, *args: str, timeout: int = 120) -> subprocess.CompletedProcess:
48
+ env = {k: v for k, v in os.environ.items() if k not in _HOOK_GIT_ENV}
49
+ return subprocess.run(["git", "-C", str(repo), *args], capture_output=True, text=True, timeout=timeout,
50
+ env=env)
51
+
52
+
53
+ def is_test_file(path: str) -> bool:
54
+ p = Path(path)
55
+ name = p.name
56
+ return (bool(_TEST_DIRS & set(p.parts[:-1])) or name.startswith("test_") or name.endswith("_test.py")
57
+ or ".test." in name or ".spec." in name or name == "conftest.py")
58
+
59
+
60
+ def is_code_file(path: str) -> bool:
61
+ return Path(path).suffix in CODE_EXT and not is_test_file(path)
62
+
63
+
64
+ def fix_without_test(subjects: list[str], files: list[str]) -> list[str]:
65
+ """The `fix` subjects that break the rule; empty when the range is fine."""
66
+ fixes = [s for s in subjects if re.match(r"fix\b", s.strip(), re.I)]
67
+ if not fixes:
68
+ return []
69
+ if any(is_test_file(f) for f in files) or not any(is_code_file(f) for f in files):
70
+ return []
71
+ return fixes
72
+
73
+
74
+ def state_dir() -> Path:
75
+ """Where the gate keeps its pass cache, bypass log, gate logs and landing queue. AISYNC_STATE_DIR overrides it:
76
+ every test suite and demo sets it to a throwaway folder so they never write the live ~/.ai-sync/state
77
+ (GATE_STATE_DIR is the older name, still read)."""
78
+ override = os.environ.get("AISYNC_STATE_DIR") or os.environ.get("GATE_STATE_DIR")
79
+ if override:
80
+ return Path(override)
81
+ try:
82
+ root = core.load_config().root
83
+ except Exception: # noqa: BLE001 - the gate must still work without an ai-sync config
84
+ root = Path.home() / ".ai-sync"
85
+ return root / "state"
86
+
87
+
88
+ def _passed(sha: str) -> Path:
89
+ return state_dir() / "gate_pass" / sha
90
+
91
+
92
+ def failed_tests(output: str) -> list[str]:
93
+ lines = [ln.strip() for ln in output.splitlines()]
94
+ hits = [ln for ln in lines if re.match(r"(FAILED|ERROR) ", ln) or "Coverage is below" in ln
95
+ or ln.startswith("FAIL:") or ln.startswith("ERROR:") or ln.startswith("GATE-FAIL")]
96
+ return hits[:15] or [ln for ln in lines if ln][-12:]
97
+
98
+
99
+ def check_commit(repo, sha: str, base: str | None = None, timeout: int = CHECK_TIMEOUT) -> tuple[bool, str, float]:
100
+ """Run `./check.sh --fast` on a clean checkout of `sha`. Returns (ok, output, seconds)."""
101
+ tree = _git(repo, "rev-parse", "--verify", "--quiet", f"{sha}^{{tree}}").stdout.strip()
102
+ if _passed(sha).exists() or (tree and _passed(f"tree-{tree}").exists()):
103
+ return True, "(同一个提交或同一棵文件树之前已通过,跳过重跑)", 0.0
104
+ tmp = Path(tempfile.mkdtemp(prefix="gate-"))
105
+ wt = tmp / "src"
106
+ t0 = time.monotonic()
107
+ try:
108
+ add = _git(repo, "worktree", "add", "--detach", "--quiet", str(wt), sha)
109
+ if add.returncode != 0:
110
+ return False, f"GATE-FAIL 无法检出 {sha[:8]}:{(add.stderr or add.stdout).strip()[-300:]}", 0.0
111
+ if not os.access(wt / "check.sh", os.X_OK):
112
+ return False, "GATE-FAIL check.sh 不可执行(chmod +x check.sh 后提交)", 0.0
113
+ env = {k: v for k, v in os.environ.items() if k not in _HOOK_GIT_ENV and k != "GATE_BYPASS"}
114
+ env["GATE_ACTIVE"] = "1"
115
+ if base:
116
+ env["GATE_DIFF_BASE"] = base
117
+ try:
118
+ r = subprocess.run(["./check.sh", "--fast"], cwd=wt, env=env, capture_output=True, text=True,
119
+ timeout=timeout)
120
+ ok, out = r.returncode == 0, (r.stdout or "") + (r.stderr or "")
121
+ except subprocess.TimeoutExpired:
122
+ ok, out = False, f"GATE-FAIL check.sh --fast 超过 {timeout} 秒没跑完"
123
+ secs = time.monotonic() - t0
124
+ if not ok: # the whole output, traceback included, for whoever fixes it
125
+ log = state_dir() / "gate_logs" / f"{sha}.log"
126
+ log.parent.mkdir(parents=True, exist_ok=True)
127
+ log.write_text(out)
128
+ if ok:
129
+ rec = json.dumps({"repo": str(repo), "sha": sha, "secs": round(secs, 1),
130
+ "ts": dt.datetime.now().astimezone().isoformat(timespec="seconds")})
131
+ for key in [sha] + ([f"tree-{tree}"] if tree else []): # a rebase that changes nothing hits the tree
132
+ p = _passed(key)
133
+ p.parent.mkdir(parents=True, exist_ok=True)
134
+ p.write_text(rec)
135
+ return ok, out, secs
136
+ finally:
137
+ _git(repo, "worktree", "remove", "--force", str(wt))
138
+ _git(repo, "worktree", "prune")
139
+ shutil.rmtree(tmp, ignore_errors=True)
140
+
141
+
142
+ def _has_check(repo, sha: str) -> bool:
143
+ return _git(repo, "cat-file", "-e", f"{sha}:check.sh").returncode == 0
144
+
145
+
146
+ def _range(repo, remote: str, lsha: str, rsha: str) -> tuple[list[str], str | None]:
147
+ """Commits being pushed (newest first) and the base to diff against."""
148
+ if rsha != ZERO and _git(repo, "cat-file", "-e", f"{rsha}^{{commit}}").returncode == 0:
149
+ revs = _git(repo, "rev-list", f"{rsha}..{lsha}").stdout.split()
150
+ return revs, rsha
151
+ revs = _git(repo, "rev-list", lsha, "--not", f"--remotes={remote}").stdout.split()
152
+ if not revs:
153
+ return [], None
154
+ parent = _git(repo, "rev-parse", "--verify", "--quiet", f"{revs[-1]}^").stdout.strip()
155
+ return revs, parent or None
156
+
157
+
158
+ def _agent() -> str:
159
+ try:
160
+ from . import hooks
161
+ return hooks.detect_agent() or "unknown"
162
+ except Exception: # noqa: BLE001
163
+ return os.environ.get("AISYNC_AGENT") or "unknown"
164
+
165
+
166
+ def _is_temp_repo(repo: Path) -> bool:
167
+ """A repo in a temp dir is a demo or a test fixture (two 'queue demo seed' lines reached the live log on 11/02)."""
168
+ roots = {tempfile.gettempdir(), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders"}
169
+ real = os.path.realpath(repo)
170
+ return any(real == r or real.startswith(r.rstrip("/") + "/") for r in map(os.path.realpath, roots))
171
+
172
+
173
+ def record_bypass(repo: Path, sha: str, reason: str) -> None:
174
+ if _is_temp_repo(repo) and not (os.environ.get("AISYNC_STATE_DIR") or os.environ.get("GATE_STATE_DIR")):
175
+ return # no state dir of its own: it would write the live log and journal for a repo nobody keeps
176
+ rec = {"ts": dt.datetime.now().astimezone().isoformat(timespec="seconds"), "repo": str(repo),
177
+ "sha": sha, "reason": reason, "agent": _agent()}
178
+ p = state_dir() / "gate_bypass.jsonl"
179
+ p.parent.mkdir(parents=True, exist_ok=True)
180
+ with p.open("a") as fh:
181
+ fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
182
+ try:
183
+ core.append_event(core.load_config(), agent=rec["agent"], kind="blocked", project=repo.name,
184
+ summary=f"push gate bypassed for {repo.name} {sha[:8]} -> main: {reason}")
185
+ except Exception as ex: # noqa: BLE001 - the jsonl line is the record; the journal is best effort
186
+ print(f"【推送闸门】跳过已记入 {p},但 ai-sync 日志没写上:{ex}")
187
+
188
+
189
+ def pre_push(repo, remote: str, lines: list[str], say=print) -> int:
190
+ """The pre-push hook body. Returns the exit code (0 = let the push through)."""
191
+ if os.environ.get("GATE_ACTIVE"):
192
+ return 0
193
+ repo = Path(_git(repo, "rev-parse", "--show-toplevel").stdout.strip() or repo)
194
+ rc = 0
195
+ for line in lines:
196
+ parts = line.split()
197
+ if len(parts) != 4:
198
+ continue
199
+ _lref, lsha, rref, rsha = parts
200
+ if rref != MAIN_REF or lsha == ZERO or not _has_check(repo, lsha):
201
+ continue
202
+ reason = os.environ.get("GATE_BYPASS", "").strip()
203
+ if reason:
204
+ record_bypass(repo, lsha, reason)
205
+ say(f"【推送闸门】GATE_BYPASS 生效({reason}),{repo.name} {lsha[:8]} 未经测试放行,已记录")
206
+ continue
207
+ revs, base = _range(repo, remote, lsha, rsha)
208
+ if not revs:
209
+ continue
210
+ lock = None
211
+ if not landq.held_by_caller(repo, remote): # wt land already holds the queue for its own push
212
+ lock = landq.Lock(repo, f"git push {repo.name}({_agent()})", say=say, remote=remote)
213
+ if not lock.acquire():
214
+ say(f"【推送闸门】{repo.name} 的落地队列等了 {landq.WAIT_MIN} 分钟还没轮到,这次不推")
215
+ rc = 1
216
+ continue
217
+ try:
218
+ moved = _remote_moved(repo, remote, rsha)
219
+ if moved:
220
+ say(f"【推送闸门】拒绝推送 {repo.name} 到 main:远端 main 已经是 {moved[:8]},不是这次推送基于的版本,"
221
+ "先 fetch 并 rebase 再推(省掉一次注定被拒的检查)")
222
+ rc = 1
223
+ continue
224
+ if not _check_range(repo, lsha, revs, base, say):
225
+ rc = 1
226
+ continue
227
+ push_pid = os.environ.get("GATE_PUSH_PID", "")
228
+ if lock and push_pid.isdigit():
229
+ landq.hand_to_process(lock, int(push_pid)) # keep the queue until this git push has finished
230
+ finally:
231
+ if lock:
232
+ lock.release()
233
+ return rc
234
+
235
+
236
+ def _remote_moved(repo, remote: str, rsha: str) -> str:
237
+ """The remote main's sha when it is no longer the one this push expects, else ""."""
238
+ r = _git(repo, "ls-remote", remote, MAIN_REF, timeout=60)
239
+ now = (r.stdout.split() or [""])[0] if r.returncode == 0 else ""
240
+ expected = "" if rsha == ZERO else rsha
241
+ return now if r.returncode == 0 and now != expected else ""
242
+
243
+
244
+ def _check_range(repo: Path, lsha: str, revs: list[str], base: str | None, say) -> bool:
245
+ """Fix-needs-a-test, then ./check.sh --fast on a clean checkout. True = this range may land."""
246
+ subjects = [_git(repo, "log", "-1", "--format=%s", r).stdout.strip() for r in revs]
247
+ files = _git(repo, "diff", "--name-only", base, lsha).stdout.split() if base else \
248
+ _git(repo, "show", "--name-only", "--format=", *revs).stdout.split()
249
+ bad = fix_without_test(subjects, files)
250
+ if bad:
251
+ say(f"【推送闸门】拒绝推送 {repo.name} 到 main:修复提交改了代码却没改任何测试(修复必须带测试):"
252
+ + ";".join(bad[:3]))
253
+ return False
254
+ say(f"【推送闸门】{repo.name}:在干净检出的 {lsha[:8]} 上跑 ./check.sh --fast …")
255
+ ok, out, secs = check_commit(repo, lsha, base)
256
+ if ok:
257
+ say(f"【推送闸门】通过,用时 {secs:.0f} 秒")
258
+ return True
259
+ log = state_dir() / "gate_logs" / f"{lsha}.log"
260
+ say(f"【推送闸门】拒绝推送 {repo.name} 到 main:./check.sh --fast 没过({secs:.0f} 秒)。没过的项:")
261
+ for ln in failed_tests(out):
262
+ say(" " + ln)
263
+ say(f" 完整输出(含 traceback):{log}")
264
+ say(" 修好并带上测试后再推;紧急情况才用 GATE_BYPASS=<原因>(会记录)")
265
+ return False
ai_sync/guard.py ADDED
@@ -0,0 +1,390 @@
1
+ """ai-sync guard: one Claude Code session per repo at a time, enforced by a PreToolUse hook.
2
+
3
+ What: the first Claude Code session that edits a repo takes a lease on it; any OTHER session that tries
4
+ to edit or run a write command in that repo is denied, with who holds it and how to hand off.
5
+ The lease is refreshed on every edit, expires LEASE_TTL_MIN after the holder's last edit, and is
6
+ dropped when the holder session ends (SessionEnd hook).
7
+ Why: 2026-10-23 two Claude Code sessions worked the same ticket (X autopilot) without seeing each other
8
+ and nearly posted the same reply twice. Claims (`aisync claim`) are voluntary and keyed by agent
9
+ name, and every session is "claude-code", so sessions never saw each other's claims.
10
+ How: `aisync guard` reads the hook JSON on stdin. Key = the git root of the touched path (a worktree is
11
+ its own key, so worktree sessions never block each other); outside git, the file itself.
12
+ Shared append-only places (mailbox, ai-sync hub, scratch, tmp) are exempt. Any internal error
13
+ fails open: a bug in the guard must never stop work.
14
+ Headless: a scripted background run (`claude -p`, env AISYNC_HEADLESS set) takes over a lease whose holder has
15
+ not edited for HEADLESS_TAKEOVER_MIN minutes, so an idle interactive window never blocks the hourly
16
+ mail-ticket for the full LEASE_TTL_MIN (T-20261025-ROBUST 5). The takeover is logged in guard.jsonl.
17
+ Undo: remove the `aisync guard` entries from ~/.claude/settings.json (PreToolUse, SessionEnd).
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import re
24
+ import shlex
25
+ import subprocess
26
+ from datetime import datetime, timedelta
27
+ from pathlib import Path
28
+
29
+ from . import core
30
+
31
+ LEASE_TTL_MIN = 45
32
+ STALE_IDLE_MIN = 1 # decided 2026-11-01: no waiting; a holder with no work and no live process is released at once
33
+ HEADLESS_TAKEOVER_MIN = int(os.environ.get("AISYNC_HEADLESS_TAKEOVER_MIN", "15"))
34
+ EDIT_TOOLS = ("Edit", "Write", "MultiEdit", "NotebookEdit")
35
+ _DEFAULT_EXEMPT = ("~/.ai-sync", "~/.claude/projects",
36
+ "~/Library/Application Support/Claude", "~/Library/Logs", "/tmp", "/private/tmp",
37
+ "/private/var/folders", "/var/folders", "/dev")
38
+ # Bash commands that change files or git state. Read-only commands (ls, cat, git status/log/diff) pass.
39
+ # git's own options before the subcommand (git -C d, -c k=v, --no-pager, --git-dir d): a write behind any of them is still a write.
40
+ _GIT_VALUE = r"(?:\"[^\"]*\"|'[^']*'|\S+)"
41
+ _GIT_OPTS = rf"(?:(?:-C|-c|--git-dir|--work-tree|--namespace|--exec-path)\s+{_GIT_VALUE}\s+|--?[\w-]+(?:={_GIT_VALUE})?\s+)*"
42
+ _MUTATING = re.compile(
43
+ rf"\bgit\s+{_GIT_OPTS}(?:commit|push|pull|merge|rebase|reset|checkout|switch|restore|add|rm|mv|"
44
+ r"stash|cherry-pick|revert|tag|am|apply|clean)\b"
45
+ r"|\bsed\s+-i|\bperl\s+-p?i|\brm\s|\bmv\s|\bcp\s|\btee\b|\btouch\s|\bmkdir\s|\bpatch\b"
46
+ r"|(?:^|[^<>&0-9])>>?\s*(?!/dev/null)(?!&)\S")
47
+
48
+
49
+ def exempt_roots() -> list[Path]:
50
+ raw = os.environ.get("AISYNC_LEASE_EXEMPT")
51
+ items = raw.split(":") if raw is not None else list(_DEFAULT_EXEMPT)
52
+ return [Path(os.path.expanduser(p)).resolve() for p in items if p]
53
+
54
+
55
+ def _within(p: Path, root: Path) -> bool:
56
+ return p == root or root in p.parents
57
+
58
+
59
+ def key_for(path: str | Path, cwd: str = "") -> str | None:
60
+ """The lease key for a path: its git root, else the path itself; None when exempt."""
61
+ p = Path(os.path.expanduser(str(path)))
62
+ if not p.is_absolute():
63
+ p = Path(cwd or os.getcwd()) / p
64
+ p = p.resolve()
65
+ if any(_within(p, r) for r in exempt_roots()):
66
+ return None
67
+ for d in [p, *p.parents]:
68
+ if (d / ".git").exists():
69
+ return str(d)
70
+ return str(p)
71
+
72
+
73
+ # Landing a finished worktree branch into a held repo: git refuses a fast-forward that would overwrite the
74
+ # holder's uncommitted files, and a push only sends commits, so these never clobber the holder's work.
75
+ _LANDING = re.compile(rf"^\s*git\s+{_GIT_OPTS}(?:merge\s+--ff-only|pull\s+--ff-only|push)\b")
76
+ _SEGMENT = re.compile(r"&&|\|\||;|\n")
77
+
78
+
79
+ _GIT_VALUE_OPTS = {"-c", "-C", "--git-dir", "--work-tree", "--namespace", "--exec-path"}
80
+
81
+
82
+ def _is_git_c(words: list[str], i: int) -> bool:
83
+ """words[i] is git's own -C: only git's own options sit between it and the word git."""
84
+ j = i - 1
85
+ while j >= 0 and not words[j].endswith("git"):
86
+ if j > 0 and words[j - 1] in _GIT_VALUE_OPTS:
87
+ j -= 2
88
+ elif words[j].startswith("-"):
89
+ j -= 1
90
+ else:
91
+ return False
92
+ return j >= 0
93
+
94
+
95
+ def _seg_dirs(words: list[str]) -> list[str]:
96
+ return [words[i + 1].rstrip(";&|") for i, w in enumerate(words[:-1])
97
+ if w == "cd" or (w == "-C" and _is_git_c(words, i))]
98
+
99
+
100
+ def bash_targets(command: str, cwd: str) -> list[str]:
101
+ """Directories a mutating Bash command works in, per segment: its `cd X` / `git -C X`, else the last
102
+ `cd` before it, else the cwd. Landing segments (git merge --ff-only, pull --ff-only, push) lock nothing."""
103
+ if not _MUTATING.search(command or ""):
104
+ return []
105
+ dirs, here = [], cwd
106
+ for seg in _SEGMENT.split(command):
107
+ try:
108
+ words = shlex.split(seg, posix=True)
109
+ except ValueError:
110
+ words = seg.split()
111
+ own = _seg_dirs(words)
112
+ if _MUTATING.search(seg) and not _LANDING.search(seg):
113
+ gitc = [d for d in own if not (words and words[0] == "cd")]
114
+ dirs += gitc or ([here] if here else [])
115
+ if words and words[0] == "cd" and own:
116
+ d = os.path.expanduser(own[0])
117
+ here = d if os.path.isabs(d) else str(Path(here or ".") / d)
118
+ return dirs
119
+
120
+
121
+ def worktree_path(key: str, session: str) -> str:
122
+ return f"{key}-wt/{session[:8]}"
123
+
124
+
125
+ # ───────────────────────────── lease store ─────────────────────────────
126
+
127
+ def _path(cfg: core.Config) -> Path:
128
+ return cfg.state / "leases.json"
129
+
130
+
131
+ def _now() -> datetime:
132
+ return datetime.now().astimezone()
133
+
134
+
135
+ def load(cfg: core.Config) -> dict:
136
+ now, out = _now(), {}
137
+ for k, v in core.load_json(_path(cfg), {}).items():
138
+ try:
139
+ if datetime.fromisoformat(v["expires"]) > now:
140
+ out[k] = v
141
+ except (KeyError, TypeError, ValueError):
142
+ continue
143
+ return out
144
+
145
+
146
+ def headless() -> bool:
147
+ """True inside a scripted background run (the parent sets AISYNC_HEADLESS for its child)."""
148
+ return bool(os.environ.get("AISYNC_HEADLESS"))
149
+
150
+
151
+ def _holder_done(cur: dict, key: str, now: datetime) -> bool:
152
+ """True when the holder has no work left: idle for STALE_IDLE_MIN minutes, and either its working folder is gone
153
+ or it has no uncommitted change of its own. Such a lease is released at once, without asking anyone."""
154
+ try:
155
+ idle = now - datetime.fromisoformat(cur["last"])
156
+ except (KeyError, TypeError, ValueError):
157
+ return False
158
+ if idle < timedelta(minutes=STALE_IDLE_MIN):
159
+ return False
160
+ cwd = cur.get("cwd") or ""
161
+ if cwd and not Path(cwd).exists():
162
+ return True
163
+ if _scope_open(key, cur): # uncommitted work of its own (or state unreadable): keep
164
+ return False
165
+ return _holder_alive(cwd) is False
166
+
167
+
168
+ def _holder_alive(cwd: str, tries: int = 3) -> bool | None:
169
+ """Is a Claude Code process still working in `cwd`? True / False, or None when every read method failed.
170
+ Reads several ways and retries (decided 2026-11-01: a failed read is read again, never taken as a verdict)."""
171
+ if not cwd:
172
+ return False
173
+ import time as _t
174
+ for _ in range(tries):
175
+ for method in (_lsof_cwds, _ps_cwds):
176
+ found = method()
177
+ if found is None:
178
+ continue
179
+ return any(c == cwd or c.startswith(cwd.rstrip("/") + "/") for c in found)
180
+ _t.sleep(0.5)
181
+ return None
182
+
183
+
184
+ def _lsof_cwds() -> list[str] | None:
185
+ import subprocess
186
+ try:
187
+ out = subprocess.run(["lsof", "-a", "-c", "claude", "-d", "cwd", "-Fn"], capture_output=True, text=True, timeout=15).stdout
188
+ except (OSError, subprocess.SubprocessError):
189
+ return None
190
+ return [ln[1:] for ln in out.splitlines() if ln.startswith("n")]
191
+
192
+
193
+ def _ps_cwds() -> list[str] | None:
194
+ import subprocess
195
+ try:
196
+ pids = subprocess.run(["pgrep", "-x", "claude"], capture_output=True, text=True, timeout=10).stdout.split()
197
+ out: list[str] = []
198
+ for pid in pids:
199
+ r = subprocess.run(["lsof", "-a", "-p", pid, "-d", "cwd", "-Fn"], capture_output=True, text=True, timeout=10).stdout
200
+ out += [ln[1:] for ln in r.splitlines() if ln.startswith("n")]
201
+ return out
202
+ except (OSError, subprocess.SubprocessError):
203
+ return None
204
+
205
+
206
+ def acquire(cfg: core.Config, session: str, key: str, cwd: str = "", ttl_min: int = LEASE_TTL_MIN,
207
+ takeover_idle_min: int | None = None, touched: str = ""):
208
+ """Take or refresh the lease. Returns (True, lease) or (False, the other session's lease).
209
+ takeover_idle_min: take another session's lease when its last edit is at least that old."""
210
+ with core.locked(cfg):
211
+ leases = load(cfg)
212
+ cur = leases.get(key)
213
+ now = _now()
214
+ if cur and cur["session"] != session:
215
+ try:
216
+ idle = now - datetime.fromisoformat(cur["last"])
217
+ except (KeyError, TypeError, ValueError):
218
+ idle = timedelta(0)
219
+ stale = _holder_done(cur, key, now) # decided 2026-11-01: a holder with no work left never keeps the lock
220
+ if not stale and (takeover_idle_min is None or idle < timedelta(minutes=takeover_idle_min)):
221
+ return False, cur
222
+ if stale:
223
+ _log(cfg, session=session[:8], event="stale_takeover", key=key, holder=cur["session"][:8],
224
+ idle_min=int(idle.total_seconds() // 60), cwd=cur.get("cwd", ""))
225
+ cur = {"took_over_from": cur["session"]}
226
+ same = bool(cur) and cur.get("session") == session
227
+ files = set(cur.get("files", [])) if same else set()
228
+ if touched:
229
+ files.add(touched)
230
+ # Dirty lines that already existed when this lease began: someone else's work, not this session's.
231
+ baseline = cur.get("baseline") if same else (_status_lines(key) if (Path(key) / ".git").exists() else [])
232
+ lease = {"session": session, "since": (cur or {}).get("since") or now.isoformat(timespec="seconds"),
233
+ **({"took_over_from": cur["took_over_from"]} if cur and "took_over_from" in cur else {}),
234
+ "last": now.isoformat(timespec="seconds"), "cwd": cwd, "files": sorted(files),
235
+ "baseline": baseline,
236
+ "expires": (now + timedelta(minutes=ttl_min)).isoformat(timespec="seconds")}
237
+ leases[key] = lease
238
+ core.save_json(_path(cfg), leases)
239
+ return True, lease
240
+
241
+
242
+ def release(cfg: core.Config, *, session: str = "", key: str = "") -> list[str]:
243
+ key = str(Path(os.path.expanduser(key)).resolve()) if key else ""
244
+ with core.locked(cfg):
245
+ leases = load(cfg)
246
+ gone = [k for k, v in leases.items() if (key and k == key) or (session and v["session"] == session)]
247
+ for k in gone:
248
+ leases.pop(k)
249
+ core.save_json(_path(cfg), leases)
250
+ return gone
251
+
252
+
253
+ # ───────────────────────────── hook entry ─────────────────────────────
254
+
255
+ def _hm(iso: str) -> str:
256
+ return iso[11:16] if len(iso) >= 16 else iso
257
+
258
+
259
+ def _dirty(key: str, files: list[str]) -> bool:
260
+ """Uncommitted changes in `files` (or anywhere in the repo when none were recorded). Unknown counts as dirty."""
261
+ try:
262
+ r = subprocess.run(["git", "-C", key, "status", "--porcelain", "--"] + (files or ["."]),
263
+ capture_output=True, text=True, timeout=15)
264
+ except (OSError, subprocess.SubprocessError):
265
+ return True
266
+ return r.returncode != 0 or bool(r.stdout.strip())
267
+
268
+
269
+ def _status_lines(key: str) -> list[str] | None:
270
+ """`git status --porcelain` for the whole repo, or None when it cannot be read."""
271
+ try:
272
+ r = subprocess.run(["git", "-C", key, "status", "--porcelain"], capture_output=True, text=True, timeout=15)
273
+ except (OSError, subprocess.SubprocessError):
274
+ return None
275
+ return r.stdout.splitlines() if r.returncode == 0 else None
276
+
277
+
278
+ def _scope_open(key: str, v: dict) -> bool:
279
+ """True while the lease still guards uncommitted work of its session.
280
+ With recorded files (Edit/Write): open while any of them is dirty.
281
+ Bash-only lease (no recorded files): open only while the repo has dirty lines that were NOT dirty when the
282
+ lease began (`baseline`), so a colleague's unrelated uncommitted change never pins the lock. Unknown = open."""
283
+ files = v.get("files") or []
284
+ if files:
285
+ return _dirty(key, files)
286
+ now = _status_lines(key)
287
+ if now is None:
288
+ return True
289
+ return bool(set(now) - set(v.get("baseline") or []))
290
+
291
+
292
+ def release_finished(cfg: core.Config, *, session: str) -> list[str]:
293
+ """Scope end (Stop hook): drop this session's leases whose work is all committed.
294
+ A lease with edits still uncommitted stays until its TTL, so an unfinished change is never handed over."""
295
+ with core.locked(cfg):
296
+ leases = load(cfg)
297
+ gone = [k for k, v in leases.items() if v.get("session") == session and not _scope_open(k, v)]
298
+ for k in gone:
299
+ leases.pop(k)
300
+ if gone:
301
+ core.save_json(_path(cfg), leases)
302
+ return gone
303
+
304
+
305
+ def deny_reason(key: str, lease: dict, session: str = "") -> str:
306
+ msg = (f"【会话隔离】{key} 正被另一个 Claude Code 会话 {lease['session'][:8]} 占用"
307
+ f"({_hm(lease['since'])} 起,最近一次改动 {_hm(lease['last'])},没人再改的话 {_hm(lease['expires'])} 自动释放)。"
308
+ f"只读不受影响:看文件、grep/rg、git status/log/diff/show 照常可以用,只拦改动。")
309
+ if session and (Path(key) / ".git").exists():
310
+ wt = worktree_path(key, session)
311
+ return msg + (f"不用等:要改,就一条命令开自己的 worktree:`aisync wt start --key '{key}' --session {session}`,"
312
+ f"然后所有改动、测试、commit 都写在打印出来的路径下(它是单独的锁,{wt})。"
313
+ f"没做完的改动在 worktree 的分支上提交,不要用 git stash(所有 worktree 共用一个 stash)。"
314
+ f"做完一条命令落地并清理:`aisync wt land --key '{key}' --session {session}`。"
315
+ f"只有确认那个会话已经结束,才可以运行 `aisync lease release --key '{key}'` 并告诉用户。")
316
+ return msg + ("本会话不要改这里:换别的仓库或文件做;要交接就用 ListAgents 找到那个会话,用 SendMessage 商量。"
317
+ f"只有确认那个会话已经结束,才可以运行 `aisync lease release --key '{key}'` 并告诉用户。")
318
+
319
+
320
+ def _log(cfg: core.Config, **rec) -> None:
321
+ """One line per decision that touched a key, in state/guard.jsonl (`aisync lease status` reads it)."""
322
+ try:
323
+ path = cfg.state / "guard.jsonl"
324
+ if path.exists() and path.stat().st_size > 2 * 1024 * 1024:
325
+ path.replace(path.with_suffix(".jsonl.1"))
326
+ with open(path, "a") as fh:
327
+ fh.write(json.dumps({"ts": core.now_iso(), **rec}, ensure_ascii=False) + "\n")
328
+ except OSError:
329
+ pass
330
+
331
+
332
+ def handle(payload: dict, cfg: core.Config | None = None) -> str:
333
+ """Return the hook's stdout ('' = allow). Never raises."""
334
+ try:
335
+ event = payload.get("hook_event_name") or ""
336
+ session = str(payload.get("session_id") or "")
337
+ if not session:
338
+ return ""
339
+ cfg = cfg or core.load_config()
340
+ if event == "SessionEnd":
341
+ gone = release(cfg, session=session)
342
+ if gone:
343
+ _log(cfg, session=session[:8], event="SessionEnd", released=gone)
344
+ return ""
345
+ if event == "Stop":
346
+ gone = release_finished(cfg, session=session)
347
+ if gone:
348
+ _log(cfg, session=session[:8], event="Stop", released=gone, reason="scope-end")
349
+ return ""
350
+ if event != "PreToolUse":
351
+ return ""
352
+ tool, inp, cwd = payload.get("tool_name") or "", payload.get("tool_input") or {}, payload.get("cwd") or ""
353
+ if tool in EDIT_TOOLS:
354
+ paths = [inp.get("file_path") or inp.get("notebook_path") or ""]
355
+ elif tool == "Bash":
356
+ paths = bash_targets(str(inp.get("command") or ""), cwd)
357
+ else:
358
+ return ""
359
+ for p in filter(None, paths):
360
+ key = key_for(p, cwd)
361
+ if not key or (tool == "Bash" and not (Path(key) / ".git").exists()):
362
+ continue # Bash outside a repo: too coarse to lock a folder
363
+ bg = headless()
364
+ touched = str(Path(p) if Path(p).is_absolute() else Path(cwd or key) / p) if tool in EDIT_TOOLS else ""
365
+ ok, lease = acquire(cfg, session, key, cwd, takeover_idle_min=HEADLESS_TAKEOVER_MIN if bg else None,
366
+ touched=touched)
367
+ took = lease.get("took_over_from") if ok and lease.get("since") == lease.get("last") else None
368
+ _log(cfg, session=session[:8], tool=tool, key=key,
369
+ decision=("takeover" if took else "allow") if ok else "deny",
370
+ holder=(took or lease["session"])[:8], **({"headless": True} if bg else {}))
371
+ if not ok:
372
+ reason = deny_reason(key, lease, session)
373
+ if bg:
374
+ reason += (f"(后台任务:在信箱 log.md 写一行「<时间> | claude-code | blocked | <单号> | "
375
+ f"被前台会话 {lease['session'][:8]} 挡住 {key}」,这一项留着不勾,先做别的;"
376
+ f"它闲置满 {HEADLESS_TAKEOVER_MIN} 分钟后后台会自动接过来)")
377
+ return json.dumps({"hookSpecificOutput": {
378
+ "hookEventName": "PreToolUse", "permissionDecision": "deny",
379
+ "permissionDecisionReason": reason}}, ensure_ascii=False)
380
+ return ""
381
+ except Exception: # fail open
382
+ return ""
383
+
384
+
385
+ def status_text(cfg: core.Config) -> str:
386
+ leases = load(cfg)
387
+ if not leases:
388
+ return "no active session leases"
389
+ return "\n".join(f"{v['session'][:8]} {k} since {_hm(v['since'])} last {_hm(v['last'])} until {_hm(v['expires'])}"
390
+ for k, v in sorted(leases.items(), key=lambda kv: kv[1]["last"]))