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/hooks.py ADDED
@@ -0,0 +1,577 @@
1
+ """aisync hooks: keep every running agent posted mid-session, and attribute every commit.
2
+
3
+ What: three gaps the session-start rules page cannot close on its own.
4
+ - news: what the OTHER tools did since this session last looked (new events, new shared rules).
5
+ `aisync hook <tool>` is wired into each tool's own hook system, so a running Claude Code, Codex
6
+ or Cursor session gets the news injected into its context without asking. Nothing new = no
7
+ output, so a quiet hub costs zero tokens.
8
+ - commit trailer: a global git `commit-msg` hook adds `Agent: <tool>` when the commit comes from
9
+ an AI tool (detected from the environment the tool's shell inherits). Repo-local hooks still
10
+ run: every hook name chains to `.git/hooks/<name>`.
11
+ - delivery: Cursor gets the shared rules + progress from its sessionStart hook (its User Rules
12
+ live inside the app); file-based tools get the rules block seeded into their rule file.
13
+ Why: people run several AI tools at once; one of them changing something must reach the others.
14
+ How: every hook call is fail-open (never blocks the tool, always exits 0), has its own cursor
15
+ file per session, and is logged to state/hooks.jsonl so `aisync status` can show it.
16
+ Installing is two-phase: `plan_install` computes every change as a diff, nothing is written
17
+ until the user says yes (`aisync install-hooks` asks; `--dry-run` only shows).
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import difflib
22
+ import json
23
+ import os
24
+ import re
25
+ import shutil
26
+ import stat
27
+ import subprocess
28
+ import sys
29
+ import time
30
+ from dataclasses import dataclass
31
+ from datetime import datetime, timedelta
32
+ from pathlib import Path
33
+ from typing import Callable
34
+
35
+ from . import collab, core, instincts
36
+
37
+ NEWS_MAX_EVENTS = 12
38
+ NEWS_MAX_RULES = 8 # new rules shown in full per injection; the rest are counted
39
+ NEWS_FULL_REWORDED = 3 # more reworded rules than this are listed by ID only
40
+ NEWS_MAX_CHARS = 6000 # hard cap on one news injection
41
+ CURSOR_TTL_DAYS = 7
42
+ HOOK_LOG_MAX_BYTES = 2 * 1024 * 1024
43
+ HOOK_TIMEOUT_SECS = 5
44
+ # SessionStart sets the cursor; UserPromptSubmit and PostToolUse (after every tool call, so a long
45
+ # task hears news too) inject. Same events for Claude Code and Codex.
46
+ NESTED_EVENTS = ("SessionStart", "UserPromptSubmit", "PostToolUse")
47
+
48
+ # Which tool is committing? First match wins; explicit beats inferred, a nested tool beats its host
49
+ # (Claude Code started inside Cursor's terminal has both CLAUDECODE and Cursor's bundle id).
50
+ DETECT = (
51
+ ("AISYNC_AGENT", None, None),
52
+ ("CLAUDECODE", "1", "claude-code"),
53
+ ("CODEX_SHELL", "1", "codex"),
54
+ ("CODEX_THREAD_ID", None, "codex"),
55
+ ("CURSOR_AGENT", "1", "cursor"),
56
+ ("__CFBundleIdentifier", "com.openai.codex", "codex"),
57
+ ("__CFBundleIdentifier", "com.todesktop.230313mzl4w4u92", "cursor"),
58
+ ("__CFBundleIdentifier", "com.trae.app", "trae"),
59
+ )
60
+
61
+
62
+ def detect_agent(env: dict | None = None) -> str:
63
+ env = os.environ if env is None else env
64
+ for key, want, agent in DETECT:
65
+ val = env.get(key, "")
66
+ if val and (want is None or val == want):
67
+ return agent or val.strip()
68
+ return ""
69
+
70
+
71
+ # ───────────────────────────── news since this session last looked ─────────────────────────────
72
+
73
+ def _cursor_path(cfg: core.Config, agent: str, session: str) -> Path:
74
+ safe = re.sub(r"[^A-Za-z0-9_.-]+", "_", f"{agent}-{session or 'default'}")[:120]
75
+ return cfg.state / "cursors" / f"{safe}.json"
76
+
77
+
78
+ def _rules(cfg: core.Config) -> list[str]:
79
+ block = core.extract_block((cfg.root / "preferences.md").read_text()) or ""
80
+ return collab.rule_lines(block)
81
+
82
+
83
+ def _prune_cursors(cfg: core.Config) -> None:
84
+ cutoff = time.time() - CURSOR_TTL_DAYS * 86400
85
+ for p in (cfg.state / "cursors").glob("*.json"):
86
+ try:
87
+ if p.stat().st_mtime < cutoff:
88
+ p.unlink()
89
+ except OSError:
90
+ pass
91
+
92
+
93
+ def news(cfg: core.Config, agent: str, session: str = "", init_only: bool = False) -> dict:
94
+ """New events from other agents + new shared rules since this session's cursor.
95
+
96
+ The first call of a session only sets the cursor (the session already loaded the full
97
+ progress page at start). `init_only` does the same on purpose (SessionStart hooks).
98
+ """
99
+ events = core.read_events(cfg)
100
+ rules = _rules(cfg)
101
+ path = _cursor_path(cfg, agent, session)
102
+ cur = core.load_json(path, None)
103
+ fresh, new_rules, new_inst, reworded = [], [], [], []
104
+ itext, ilines, ierr = instincts.read(cfg)
105
+ if cur is not None and not init_only:
106
+ seen = cur.get("seen", 0)
107
+ if seen > len(events): # journal was reset: start over, report nothing old
108
+ seen = len(events)
109
+ fresh = [e for e in events[seen:] if e.get("agent") != agent]
110
+ old = {core._drop_ids(r) for r in cur.get("rules", [])}
111
+ new_rules = [r for r in rules if core._drop_ids(r) not in old] # a rule that only gained its ID is not news
112
+ old_ids = {_rid(r) for r in cur.get("rules", [])} - {""}
113
+ reworded = [r for r in new_rules if _rid(r) in old_ids] # same ID, new words: not a new rule
114
+ new_rules = [r for r in new_rules if _rid(r) not in old_ids]
115
+ if "instincts" in cur and not ierr: # old cursors without the key: nothing to compare, say nothing
116
+ seen_inst = {_habit(l) for l in cur["instincts"]} # renumbering a line is not news
117
+ new_inst = [l for l in ilines if _habit(l) not in seen_inst]
118
+ prev = cur or {}
119
+ keep = prev.get("instincts", ilines) if ierr else ilines # an unreadable file keeps what was seen
120
+ err_changed = bool(ierr) and ierr != prev.get("instincts_err", "") and cur is not None and not init_only
121
+ path.parent.mkdir(parents=True, exist_ok=True)
122
+ core.save_json(path, {"seen": len(events), "rules": rules, "ts": core.now_iso(), "agent": agent,
123
+ "instincts": keep, "instincts_err": ierr})
124
+ _prune_cursors(cfg)
125
+ return {"events": fresh, "new_rules": new_rules, "reworded_rules": reworded, "first": cur is None, "new_instincts": new_inst,
126
+ "instincts_text": itext, "instincts_err": ierr, "instincts_err_new": err_changed}
127
+
128
+
129
+ SHELF_MAX_CHARS = 5000 # one shelved-topic injection; a bigger topic is cut with a pointer
130
+
131
+
132
+ def shelf_text(cfg: core.Config, tool: str, session: str, payload: dict) -> str:
133
+ """Shelved topics this prompt or tool call touches and this session has not been given yet (layers.py)."""
134
+ if not cfg.core_topics or not any(t.label == tool and t.layer == "core" for t in cfg.targets):
135
+ return ""
136
+ from . import layers
137
+ probe = " ".join(str(payload.get(k) or "") for k in ("prompt", "tool_name"))
138
+ ti = payload.get("tool_input")
139
+ if isinstance(ti, dict):
140
+ probe += " " + " ".join(str(v) for v in ti.values() if isinstance(v, (str, int)))[:4000]
141
+ truth = core.extract_block((cfg.root / "preferences.md").read_text()) or ""
142
+ hit = layers.matches(probe, truth, cfg.core_topics, cfg.shelf)
143
+ if not hit:
144
+ return ""
145
+ path = cfg.state / "shelf" / f"{tool}-{re.sub(r'[^A-Za-z0-9_.-]', '_', session or 'none')[:60]}.json"
146
+ seen = set(core.load_json(path, {}).get("topics", []))
147
+ new = [t for t in hit if t not in seen]
148
+ if not new:
149
+ return ""
150
+ path.parent.mkdir(parents=True, exist_ok=True)
151
+ core.save_json(path, {"topics": sorted(seen | set(new)), "ts": core.now_iso()})
152
+ out = []
153
+ for name in new:
154
+ rules = layers.topic_rules(truth, name)
155
+ out.append(f"[aisync] Shelved rules now in play ({name}, {len(rules)} rules; your work touched it):\n" + "\n".join(rules))
156
+ text = "\n\n".join(out)
157
+ if len(text) > SHELF_MAX_CHARS:
158
+ text = text[:SHELF_MAX_CHARS].rstrip() + "\n(cut: `aisync rule list --topic \"<topic>\"` for the rest)"
159
+ return text
160
+
161
+
162
+ def news_text(rep: dict) -> str:
163
+ extra = []
164
+ if rep.get("new_instincts"):
165
+ extra.append(instincts.inject_text("", "", rep["new_instincts"]))
166
+ if rep.get("instincts_err_new"):
167
+ extra.append(instincts.inject_text("", rep["instincts_err"]))
168
+ reworded = rep.get("reworded_rules", [])
169
+ if not rep["events"] and not rep["new_rules"] and not reworded:
170
+ return _cap("\n".join(extra))
171
+ out = ["[aisync] While you were working, other AI tools changed things:"]
172
+ if rep["new_rules"]:
173
+ out.append("NEW shared rule(s), follow them from now on:")
174
+ out += [core._short(r, 600) for r in rep["new_rules"][:NEWS_MAX_RULES]]
175
+ if len(rep["new_rules"]) > NEWS_MAX_RULES:
176
+ out.append(f"(+{len(rep['new_rules']) - NEWS_MAX_RULES} more new rules: `aisync rule list`)")
177
+ if reworded and len(reworded) <= NEWS_FULL_REWORDED:
178
+ out.append("Reworded shared rule(s), same ID:")
179
+ out += [core._short(r, 600) for r in reworded]
180
+ elif reworded:
181
+ ids = ", ".join(_rid(r) for r in reworded[:30]) + (" …" if len(reworded) > 30 else "")
182
+ out.append(f"{len(reworded)} shared rules were reworded under the same IDs ({ids}); "
183
+ "reread one with `aisync rule list` when your work touches it.")
184
+ if rep["events"]:
185
+ shown = rep["events"][-NEWS_MAX_EVENTS:]
186
+ for e in shown:
187
+ files = f" [{', '.join(e.get('files', [])[:4])}]" if e.get("files") else ""
188
+ out.append(f"- {e.get('ts', '')[11:16]} {e.get('agent')} {e.get('kind')} "
189
+ f"@ {e.get('project') or '-'}: {core._short(e.get('summary', ''), 160)}{files}")
190
+ if len(rep["events"]) > len(shown):
191
+ out.append(f"(+{len(rep['events']) - len(shown)} older: `aisync tail -n 30`)")
192
+ out.append("If any of this touches files you are editing, coordinate (`aisync claims`) before going on.")
193
+ return _cap("\n".join(out + extra))
194
+
195
+
196
+ def _rid(rule: str) -> str:
197
+ m = re.match(r"^-?\s*\[(R-\d{3,})\]", rule)
198
+ return m.group(1) if m else ""
199
+
200
+
201
+ def _habit(line: str) -> str:
202
+ """An instinct line without its number: '12. text(EB-1)' -> 'text(EB-1)'."""
203
+ return re.sub(r"^\s*\d+\.\s+", "", line).strip()
204
+
205
+
206
+ def _cap(text: str) -> str:
207
+ """No injection grows past NEWS_MAX_CHARS (2026-11-08: one rules slim injected 48.9 KB into every session)."""
208
+ if len(text) <= NEWS_MAX_CHARS:
209
+ return text
210
+ return text[:NEWS_MAX_CHARS].rstrip() + f"\n(cut at {NEWS_MAX_CHARS} characters: `aisync news` or `aisync tail` for the rest)"
211
+
212
+
213
+ def brief_text(cfg: core.Config) -> str:
214
+ """Everything a tool without file-based rules needs at session start: rules + live progress."""
215
+ block = core.extract_block((cfg.root / "preferences.md").read_text()) or ""
216
+ block = "\n".join(l for l in block.splitlines() if not l.startswith("<!--"))
217
+ cur = core.build_current(core.read_events(cfg))
218
+ prog = collab.progress_text(cfg, cur, collab.load_claims(cfg), collab.report(cfg)["hints"])
219
+ prog = "\n".join(l for l in prog.splitlines() if not l.startswith("<!--"))
220
+ return (f"[aisync] Shared rules (every AI tool follows them; source {collab._tilde(cfg.root / 'preferences.md')}):\n"
221
+ f"{block.strip()}\n\n{prog.strip()}\n\n"
222
+ "Protocol: claim before editing (`aisync claim`), log after each unit of work "
223
+ "(`aisync log --agent cursor --project <repo> ...`), every commit ends with `Agent: cursor`.")
224
+
225
+
226
+ # ───────────────────────────── `aisync hook <tool>`: one entry for every tool ─────────────────────────────
227
+
228
+ def _log_hook(cfg: core.Config, rec: dict) -> None:
229
+ path = cfg.state / "hooks.jsonl"
230
+ try:
231
+ path.parent.mkdir(parents=True, exist_ok=True)
232
+ if path.exists() and path.stat().st_size > HOOK_LOG_MAX_BYTES:
233
+ path.replace(path.with_suffix(".jsonl.1"))
234
+ with open(path, "a") as fh:
235
+ fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
236
+ except OSError:
237
+ pass
238
+
239
+
240
+ def handle(tool: str, payload: dict, cfg: core.Config | None = None) -> str:
241
+ """Return what the tool's hook must print on stdout ('' = nothing). Never raises."""
242
+ t0 = time.monotonic()
243
+ event = payload.get("hook_event_name") or payload.get("hookEventName") or ""
244
+ session = str(payload.get("session_id") or payload.get("conversation_id") or payload.get("sessionId") or "")
245
+ rec = {"ts": core.now_iso(), "tool": tool, "event": event, "session": session[:40], "ok": True}
246
+ out = ""
247
+ try:
248
+ cfg = cfg or core.load_config()
249
+ start = event in ("SessionStart", "sessionStart")
250
+ rep = news(cfg, tool, session, init_only=start)
251
+ rec["events"], rec["rules"] = len(rep["events"]), len(rep["new_rules"])
252
+ rec["instincts"] = len(rep["new_instincts"])
253
+ parts = [instincts.inject_text(rep["instincts_text"], rep["instincts_err"])] # SessionStart: the whole file
254
+ if start and (prog := core.progress_now(cfg)): # progress_file mode: agents.md no longer carries it
255
+ parts.append("[aisync] Live progress (other AI tools, claims, blockers):\n" + prog)
256
+ full = "\n\n".join(p for p in parts if p)
257
+ if tool == "cursor":
258
+ if start:
259
+ out = json.dumps({"additional_context": brief_text(cfg) + "\n\n" + full,
260
+ "env": {"AISYNC_AGENT": "cursor"}}, ensure_ascii=False)
261
+ elif (text := news_text(rep)):
262
+ out = json.dumps({"additional_context": text}, ensure_ascii=False)
263
+ else: # claude-code, codex: same schema
264
+ text = full if start else news_text(rep)
265
+ shelf = "" if start else shelf_text(cfg, tool, session, payload)
266
+ rec["shelf"] = len(shelf)
267
+ text = "\n\n".join(x for x in (text, shelf) if x)
268
+ if text:
269
+ out = json.dumps({"hookSpecificOutput": {"hookEventName": event or "UserPromptSubmit",
270
+ "additionalContext": text}}, ensure_ascii=False)
271
+ except Exception as ex: # fail open: a hook must never break the tool
272
+ rec.update(ok=False, error=f"{type(ex).__name__}: {ex}"[:300])
273
+ out = ""
274
+ rec["chars"], rec["ms"] = len(out), int((time.monotonic() - t0) * 1000)
275
+ if cfg is not None:
276
+ _log_hook(cfg, rec)
277
+ return out
278
+
279
+
280
+ def hook_stats(cfg: core.Config, hours: int = 24) -> dict:
281
+ path = cfg.state / "hooks.jsonl"
282
+ since = datetime.now().astimezone() - timedelta(hours=hours)
283
+ per: dict[str, dict] = {}
284
+ if not path.exists():
285
+ return per
286
+ for line in path.read_text().splitlines():
287
+ try:
288
+ r = json.loads(line)
289
+ if datetime.fromisoformat(r["ts"]) < since:
290
+ continue
291
+ except (ValueError, KeyError):
292
+ continue
293
+ s = per.setdefault(r.get("tool", "?"), {"calls": 0, "errors": 0, "injected": 0, "ms": 0, "last": ""})
294
+ s["calls"] += 1
295
+ s["errors"] += 0 if r.get("ok") else 1
296
+ s["injected"] += 1 if r.get("chars") else 0
297
+ s["ms"] += r.get("ms", 0)
298
+ s["last"] = r["ts"]
299
+ for s in per.values():
300
+ s["avg_ms"] = s.pop("ms") // max(s["calls"], 1)
301
+ return per
302
+
303
+
304
+ # ───────────────────────────── installers ─────────────────────────────
305
+
306
+ def aisync_bin() -> str:
307
+ cand = Path(sys.executable).parent / "aisync"
308
+ if cand.exists():
309
+ return str(cand)
310
+ return shutil.which("aisync") or "aisync"
311
+
312
+
313
+ @dataclass
314
+ class Change:
315
+ """One planned edit to a file outside the hub. Nothing is written until `apply()`."""
316
+ tool: str
317
+ path: Path
318
+ old: str
319
+ new: str
320
+ note: str
321
+ apply: Callable[[], None]
322
+
323
+ def diff(self) -> str:
324
+ shown = collab._tilde(self.path)
325
+ return "".join(difflib.unified_diff(self.old.splitlines(True), self.new.splitlines(True),
326
+ fromfile=f"{shown} (now)", tofile=f"{shown} (after)"))
327
+
328
+
329
+ def _read(path: Path) -> str:
330
+ try:
331
+ return path.read_text()
332
+ except FileNotFoundError:
333
+ return ""
334
+
335
+
336
+ def _save_with_backup(path: Path, text: str) -> None:
337
+ if path.exists():
338
+ shutil.copy2(path, path.with_name(path.name + f".bak-aisync-{datetime.now():%Y%m%d-%H%M%S}"))
339
+ path.parent.mkdir(parents=True, exist_ok=True)
340
+ core.atomic_write(path, text)
341
+
342
+
343
+ def _plan_json(tool: str, path: Path, default: dict, mutate: Callable[[dict], list[str]]) -> Change | None:
344
+ old = _read(path)
345
+ data = json.loads(old) if old.strip() else dict(default) # invalid JSON raises: never clobber it
346
+ added = mutate(data)
347
+ if not added:
348
+ return None
349
+ new = json.dumps(data, ensure_ascii=False, indent=2) + "\n"
350
+ return Change(tool, path, old, new, "add hooks: " + ", ".join(added), lambda: _save_with_backup(path, new))
351
+
352
+
353
+ def _add_nested(hooks: dict, event: str, command: str, matcher: str = "") -> bool:
354
+ """Claude Code / Codex schema: {event: [{matcher?, hooks: [{type, command, timeout}]}]}. Idempotent."""
355
+ groups = hooks.setdefault(event, [])
356
+ if any(h.get("command") == command for g in groups for h in g.get("hooks", [])):
357
+ return False
358
+ group = {"hooks": [{"type": "command", "command": command, "timeout": HOOK_TIMEOUT_SECS}]}
359
+ if matcher:
360
+ group = {"matcher": matcher, **group}
361
+ groups.append(group)
362
+ return True
363
+
364
+
365
+ GUARD_MATCHER = "Edit|Write|MultiEdit|NotebookEdit|Bash"
366
+
367
+
368
+ def plan_claude(home: Path, bin_: str, guard: bool = False) -> Change | None:
369
+ """Claude Code hook entries. The guard (one session per repo) is added only when `guard` is True:
370
+ it can deny edits, so it is opt-in (config guard_hook = true). Undo: delete the PreToolUse and
371
+ SessionEnd entries whose command ends in ` guard` from ~/.claude/settings.json."""
372
+ cmd = f"{bin_} hook claude-code"
373
+ gcmd = f"{bin_} guard"
374
+
375
+ def mutate(d: dict) -> list[str]:
376
+ added = [e for e in NESTED_EVENTS if _add_nested(d.setdefault("hooks", {}), e, cmd)]
377
+ if guard:
378
+ if _add_nested(d["hooks"], "PreToolUse", gcmd, GUARD_MATCHER):
379
+ added.append("PreToolUse(guard)")
380
+ if _add_nested(d["hooks"], "SessionEnd", gcmd):
381
+ added.append("SessionEnd(guard)")
382
+ return added
383
+ return _plan_json("claude-code", home / ".claude" / "settings.json", {}, mutate)
384
+
385
+
386
+ def plan_codex(home: Path, bin_: str) -> Change | None:
387
+ cmd = f"{bin_} hook codex"
388
+ return _plan_json("codex", home / ".codex" / "hooks.json", {},
389
+ lambda d: [e for e in NESTED_EVENTS if _add_nested(d.setdefault("hooks", {}), e, cmd)])
390
+
391
+
392
+ def plan_cursor(home: Path, bin_: str) -> Change | None:
393
+ cmd = f"{bin_} hook cursor"
394
+
395
+ def mutate(data: dict) -> list[str]:
396
+ data.setdefault("version", 1)
397
+ hooks, added = data.setdefault("hooks", {}), []
398
+ for event in ("sessionStart", "postToolUse"):
399
+ lst = hooks.setdefault(event, [])
400
+ if not any(h.get("command") == cmd for h in lst):
401
+ lst.append({"command": cmd, "timeout": HOOK_TIMEOUT_SECS})
402
+ added.append(event)
403
+ return added
404
+ return _plan_json("cursor", home / ".cursor" / "hooks.json", {"version": 1}, mutate)
405
+
406
+
407
+ def plan_seed_block(cfg: core.Config, label: str, path: Path) -> Change | None:
408
+ """Put the shared-rules block into a target file that has none yet, so distribute can keep it in sync."""
409
+ old = _read(path)
410
+ if core.BLOCK_START in old:
411
+ return None
412
+ truth = core.extract_block((cfg.root / "preferences.md").read_text())
413
+ if truth is None:
414
+ raise ValueError("preferences.md has no owner-preferences block")
415
+ new = old.rstrip("\n") + ("\n\n" if old.strip() else "") + truth + "\n"
416
+ return Change(label, path, old, new, "seed the shared-rules block", lambda: core.atomic_write(path, new))
417
+
418
+
419
+ def _apply(change: Change | None) -> list[str]:
420
+ if change is None:
421
+ return []
422
+ change.apply()
423
+ return change.note.split(": ", 1)[-1].split(", ")
424
+
425
+
426
+ def install_claude(home: Path, bin_: str) -> list[str]:
427
+ return _apply(plan_claude(home, bin_))
428
+
429
+
430
+ def install_codex(home: Path, bin_: str) -> list[str]:
431
+ return _apply(plan_codex(home, bin_))
432
+
433
+
434
+ def install_cursor(home: Path, bin_: str) -> list[str]:
435
+ return _apply(plan_cursor(home, bin_))
436
+
437
+
438
+ def seed_block(cfg: core.Config, path: Path) -> bool:
439
+ return bool(_apply(plan_seed_block(cfg, "rules", path)))
440
+
441
+
442
+ # Git hook names that get a chaining stub, so a repo's own .git/hooks/* keep working.
443
+ GIT_HOOKS = ("applypatch-msg", "pre-applypatch", "post-applypatch", "pre-commit", "pre-merge-commit",
444
+ "prepare-commit-msg", "commit-msg", "post-commit", "pre-rebase", "post-checkout", "post-merge",
445
+ "pre-push", "post-rewrite", "pre-auto-gc", "push-to-checkout", "reference-transaction")
446
+
447
+ _CHAIN = """
448
+ # chain to the repo's own hook (core.hooksPath would otherwise hide it)
449
+ local_hook="$(git rev-parse --git-common-dir 2>/dev/null)/hooks/$(basename "$0")"
450
+ if [ -x "$local_hook" ]; then exec "$local_hook" "$@"; fi
451
+ exit 0
452
+ """
453
+
454
+ _COMMIT_MSG = """# aisync: add `Agent: <tool>` when an AI tool makes the commit; human commits stay untouched.
455
+ msg="$1"
456
+ agent="$({detect})"
457
+ if [ -n "$agent" ] && [ -f "$msg" ] && grep -qvE '^[[:space:]]*(#|$)' "$msg" \\
458
+ && ! grep -qi '^agent:' "$msg"; then
459
+ git interpret-trailers --in-place --trailer "Agent: $agent" "$msg" 2>/dev/null \\
460
+ || printf '\\nAgent: %s\\n' "$agent" >> "$msg"
461
+ fi
462
+ """
463
+
464
+
465
+ def _detect_sh() -> str:
466
+ parts = []
467
+ for key, want, agent in DETECT:
468
+ if agent is None:
469
+ parts.append(f'if [ -n "${{{key}:-}}" ]; then echo "${key}"')
470
+ elif want is None:
471
+ parts.append(f'elif [ -n "${{{key}:-}}" ]; then echo {agent}')
472
+ else:
473
+ parts.append(f'elif [ "${{{key}:-}}" = "{want}" ]; then echo {agent}')
474
+ return "; ".join(parts) + "; fi"
475
+
476
+
477
+ _PRE_PUSH = """# aisync push gate: a push to main of a repo with check.sh must pass `./check.sh --fast` (see ai_sync/gate.py).
478
+ stdin_file="$(mktemp "${{TMPDIR:-/tmp}}/aisync-prepush.XXXXXX")"
479
+ cat > "$stdin_file"
480
+ # exit 10 = the gate refused; any other failure is the gate itself breaking: then only main pushes of a
481
+ # repo with check.sh are held, so a broken aisync can never block every push on the machine.
482
+ if [ -z "${{GATE_ACTIVE:-}}" ]; then
483
+ rc=127
484
+ # GATE_PUSH_PID: the `git push` running this hook; the landing queue stays held until it exits
485
+ if [ -x "{bin}" ]; then GATE_PUSH_PID=$PPID "{bin}" gate pre-push "$@" < "$stdin_file"; rc=$?; fi
486
+ if [ "$rc" -eq 10 ]; then rm -f "$stdin_file"; exit 1; fi
487
+ if [ "$rc" -ne 0 ] && awk '$3 == "refs/heads/main" {{ f = 1 }} END {{ exit !f }}' "$stdin_file" \\
488
+ && [ -f "$(git rev-parse --show-toplevel)/check.sh" ]; then
489
+ echo "[push gate] the gate itself failed ({bin} exited ${{rc}}), cannot run check.sh; refusing the push to main" >&2
490
+ rm -f "$stdin_file"; exit 1
491
+ fi
492
+ fi
493
+ exec 3< "$stdin_file"; rm -f "$stdin_file"
494
+ local_hook="$(git rev-parse --git-common-dir 2>/dev/null)/hooks/$(basename "$0")"
495
+ if [ -x "$local_hook" ]; then exec "$local_hook" "$@" <&3; fi
496
+ exit 0
497
+ """
498
+
499
+
500
+ def _hook_body(name: str, gate: bool = False, bin_: str = "") -> str:
501
+ body = "#!/bin/sh\n# generated by `aisync install-hooks`; do not edit (re-run it instead)\n"
502
+ if name == "commit-msg":
503
+ body += _COMMIT_MSG.format(detect=_detect_sh())
504
+ if name == "pre-push" and gate:
505
+ return body + _PRE_PUSH.format(bin=bin_ or aisync_bin()) # chains to the repo's own hook itself
506
+ return body + _CHAIN
507
+
508
+
509
+ def write_git_hooks(dest: Path, gate: bool = False, bin_: str = "") -> list[str]:
510
+ dest.mkdir(parents=True, exist_ok=True)
511
+ written = []
512
+ for name in GIT_HOOKS:
513
+ body = _hook_body(name, gate=gate, bin_=bin_)
514
+ p = dest / name
515
+ if not p.exists() or p.read_text() != body:
516
+ p.write_text(body)
517
+ written.append(name)
518
+ p.chmod(p.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
519
+ return written
520
+
521
+
522
+ def _git_hooks_path() -> str:
523
+ return subprocess.run(["git", "config", "--global", "--get", "core.hooksPath"],
524
+ capture_output=True, text=True).stdout.strip()
525
+
526
+
527
+ def plan_git(cfg: core.Config) -> Change | None:
528
+ """Global `core.hooksPath` -> <hub>/githooks. Refuses to take over a hooksPath set by something else."""
529
+ dest = cfg.root / "githooks"
530
+ cur = _git_hooks_path()
531
+ if cur and Path(cur).expanduser() != dest:
532
+ raise ValueError(f"core.hooksPath already points at {cur}; not overriding it")
533
+ stale = [n for n in GIT_HOOKS if not (dest / n).exists()]
534
+ if cur and not stale and (dest / "commit-msg").read_text() == _hook_body("commit-msg"):
535
+ return None
536
+
537
+ def apply() -> None:
538
+ write_git_hooks(dest, gate=cfg.gate_hook)
539
+ if not cur:
540
+ subprocess.run(["git", "config", "--global", "core.hooksPath", str(dest)], check=True)
541
+ return Change("git", Path("~/.gitconfig").expanduser(),
542
+ f"[core]\n\thooksPath = {cur or '(unset)'}\n", f"[core]\n\thooksPath = {dest}\n",
543
+ f"global core.hooksPath -> {collab._tilde(dest)} ({len(GIT_HOOKS)} chaining hook stubs)", apply)
544
+
545
+
546
+ def install_git(cfg: core.Config) -> dict:
547
+ try:
548
+ change = plan_git(cfg)
549
+ except ValueError as ex:
550
+ return {"written": [], "hooksPath": _git_hooks_path(), "set": False, "error": str(ex)}
551
+ dest = cfg.root / "githooks"
552
+ was_set = bool(_git_hooks_path())
553
+ written = write_git_hooks(dest, gate=cfg.gate_hook)
554
+ if change is not None:
555
+ change.apply()
556
+ return {"written": written, "hooksPath": str(dest), "set": not was_set}
557
+
558
+
559
+ INSTALL_STEPS = ("claude-code", "codex", "cursor", "rules", "git")
560
+
561
+
562
+ def plan_install(cfg: core.Config, home: Path, bin_: str, want=INSTALL_STEPS) -> tuple[list[Change], list[str]]:
563
+ """Every change `install-hooks` would make, and the steps that cannot be done. Writes nothing."""
564
+ changes, errors = [], []
565
+ planners = {"claude-code": lambda: [plan_claude(home, bin_, guard=cfg.guard_hook)],
566
+ "codex": lambda: [plan_codex(home, bin_)],
567
+ "cursor": lambda: [plan_cursor(home, bin_)],
568
+ "rules": lambda: [plan_seed_block(cfg, t.label, t.path) for t in cfg.targets],
569
+ "git": lambda: [plan_git(cfg)]}
570
+ for step in INSTALL_STEPS:
571
+ if step not in want:
572
+ continue
573
+ try:
574
+ changes += [c for c in planners[step]() if c is not None]
575
+ except (OSError, ValueError) as ex:
576
+ errors.append(f"{step}: {ex}")
577
+ return changes, errors