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/worktree.py ADDED
@@ -0,0 +1,168 @@
1
+ """One-command worktree route for an interactive Claude Code session (lock fix, 2026-10-31 step 3).
2
+
3
+ Why: when a repo's main checkout is leased by another session, the guard tells this session to work in its own
4
+ worktree. That used to be four hand-typed git commands. Now it is one command each way.
5
+ What: `aisync wt start --key <repo> --session <id>` creates <repo>-wt/<id8> on branch wt/<id8> and prints its path.
6
+ `aisync wt land --key <repo> --session <id>` rebases the branch on GitHub's main and pushes it there FIRST,
7
+ then fast-forwards the local main to GitHub's main, then removes the worktree, its branch, and its lease.
8
+ The local main never merges anything by itself (2026-11-02: a local merge plus a different merge on GitHub
9
+ split a shared main in two). Repos without an origin remote keep the old local ff-only route.
10
+ A repo with check.sh must pass `./check.sh --fast` on the rebased commit before the push (gate.py); on a
11
+ failure nothing is pushed and the worktree stays. Fetch -> rebase -> check -> push runs inside the repo's
12
+ landing queue (landq.py), so a lander never loses the race to someone who pushed during its check.
13
+ Read-only use of the main checkout is never blocked by this module; it only ever writes to its own worktree
14
+ and to the landing step.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import subprocess
20
+ from pathlib import Path
21
+
22
+ from . import core, gate, guard, landq
23
+
24
+
25
+ def path_for(key: str, session: str) -> Path:
26
+ return Path(f"{key}-wt") / session[:8]
27
+
28
+
29
+ def branch_for(session: str) -> str:
30
+ return f"wt/{session[:8]}"
31
+
32
+
33
+ # git stash is one list shared by every worktree of a repo: on 2026-11-02 one session popped another's WIP
34
+ NO_STASH = "do not use git stash; commit WIP on your wt branch instead(stash 是所有 worktree 共用的,会被别的会话弹走)"
35
+
36
+ SHARED_IGNORED = ("state", ".venv") # git-ignored runtime folders symlinked from the main checkout (same as jobs/bg_worktree.py)
37
+ _LEFTOVER_OK = ("state", ".venv", "state/", ".venv/")
38
+
39
+
40
+ def _git(repo, *args: str, timeout: int = 120) -> subprocess.CompletedProcess:
41
+ return subprocess.run(["git", "-C", str(repo), *args], capture_output=True, text=True, timeout=timeout)
42
+
43
+
44
+ def start(key: str, session: str) -> tuple[bool, str]:
45
+ """Create (or reuse) the session's worktree. Returns (ok, path or error)."""
46
+ wt, br = path_for(key, session), branch_for(session)
47
+ if wt.exists():
48
+ return True, str(wt)
49
+ if not (Path(key) / ".git").exists():
50
+ return False, f"{key} 不是 git 仓库根目录"
51
+ wt.parent.mkdir(parents=True, exist_ok=True)
52
+ has_branch = _git(key, "show-ref", "--verify", "--quiet", f"refs/heads/{br}").returncode == 0
53
+ base = "HEAD"
54
+ if _has_origin(key) and _git(key, "fetch", "--quiet", "origin").returncode == 0 \
55
+ and _git(key, "rev-parse", "--verify", "--quiet", "origin/main").returncode == 0:
56
+ base = "origin/main" # start from GitHub's truth, not from a local main that may lag or have split
57
+ args = ["worktree", "add", str(wt), br] if has_branch else ["worktree", "add", "-b", br, str(wt), base]
58
+ r = _git(key, *args)
59
+ if r.returncode == 0:
60
+ for item in SHARED_IGNORED:
61
+ src, dst = Path(key) / item, wt / item
62
+ if src.exists() and not dst.exists() and not dst.is_symlink():
63
+ dst.symlink_to(src)
64
+ return (r.returncode == 0, str(wt) if r.returncode == 0 else (r.stderr or r.stdout).strip()[-300:])
65
+
66
+
67
+ def _has_origin(repo) -> bool:
68
+ return _git(repo, "remote", "get-url", "origin").returncode == 0
69
+
70
+
71
+ def _cleanup(key: str, wt: Path, br: str, cfg: core.Config | None) -> None:
72
+ _git(key, "worktree", "remove", "--force", str(wt))
73
+ _git(key, "branch", "-D", br)
74
+ guard.release(cfg or core.load_config(), key=str(wt)) # its own lease, if any
75
+
76
+
77
+ def _follow_origin(key: str) -> str:
78
+ """Fast-forward the local main to origin/main; never merge, never reset. Returns a note for the message."""
79
+ if _git(key, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip() != "main":
80
+ return ";本机不在 main 上,未跟进"
81
+ _git(key, "fetch", "--quiet", "origin")
82
+ if _git(key, "merge", "--ff-only", "origin/main").returncode == 0:
83
+ return ",本机 main 已跟上 GitHub"
84
+ return ";本机 main 无法快进到 GitHub(分叉或有冲突的未提交改动),GitHub 已是最新,本机需要单独修"
85
+
86
+
87
+ def land(key: str, session: str, cfg: core.Config | None = None, attempts: int = 3) -> tuple[bool, str]:
88
+ """Land the session's branch on GitHub's main, then let the local main follow. Returns (ok, message).
89
+ ok is True only when the commits are on origin/main (or there was nothing to land)."""
90
+ wt, br = path_for(key, session), branch_for(session)
91
+ if not wt.exists():
92
+ return False, f"没有 worktree:{wt}(先运行 aisync wt start)"
93
+ dirty = [ln for ln in _git(wt, "status", "--porcelain").stdout.splitlines() if ln[3:].strip() not in _LEFTOVER_OK]
94
+ if dirty:
95
+ return False, f"{wt} 还有未提交的改动:先在里面 commit,再落地"
96
+ if not _has_origin(key):
97
+ return _land_local(key, wt, br, cfg)
98
+ lock = landq.Lock(key, f"wt land {Path(key).name} {session[:8]}")
99
+ if not lock.acquire(): # merge queue: fetch -> rebase -> check -> push, one lander at a time
100
+ return False, f"落地队列排了 {landq.WAIT_MIN} 分钟还没轮到,未落地,worktree 保留在 {wt}"
101
+ try:
102
+ return _land_queued(key, wt, br, cfg, attempts, lock)
103
+ finally:
104
+ lock.release()
105
+
106
+
107
+ def _land_queued(key: str, wt: Path, br: str, cfg: core.Config | None, attempts: int,
108
+ lock: "landq.Lock") -> tuple[bool, str]:
109
+ for _ in range(attempts):
110
+ if _git(wt, "fetch", "--quiet", "origin").returncode != 0:
111
+ return False, f"连不上 GitHub,未落地,worktree 保留在 {wt}"
112
+ ahead = _git(wt, "rev-list", "--count", f"origin/main..{br}").stdout.strip()
113
+ if ahead in ("", "0"):
114
+ note = _follow_origin(key)
115
+ _cleanup(key, wt, br, cfg)
116
+ return True, "没有新提交,只清理" + note
117
+ rb = _git(wt, "rebase", "origin/main")
118
+ if rb.returncode != 0:
119
+ _git(wt, "rebase", "--abort")
120
+ return False, f"与 GitHub 上的 main 冲突,未落地,worktree 保留在 {wt}:{(rb.stderr or rb.stdout).strip()[-200:]}"
121
+ refused = _gate(wt)
122
+ if refused:
123
+ return False, refused
124
+ push = subprocess.run(["git", "-C", str(wt), "push", "origin", "HEAD:main"], capture_output=True, text=True,
125
+ timeout=600, env={**os.environ, landq.TOKEN_ENV: lock.token}) # its hook skips the queue
126
+ if push.returncode == 0:
127
+ note = _follow_origin(key)
128
+ _cleanup(key, wt, br, cfg)
129
+ return True, f"已落地 {ahead} 个提交,已推送到 GitHub" + note
130
+ return False, f"推送 {attempts} 次都被拒(GitHub 上的 main 一直在变或拒收),未落地,worktree 保留在 {wt}"
131
+
132
+
133
+ def _gate(wt: Path) -> str:
134
+ """Run the repo's `check.sh --fast` on the rebased HEAD before it may reach main (push gate, 2026-11-02).
135
+ Returns "" when it passed or the repo has no check.sh, else the refusal message (the worktree is kept)."""
136
+ sha = _git(wt, "rev-parse", "HEAD").stdout.strip()
137
+ if _git(wt, "cat-file", "-e", f"{sha}:check.sh").returncode != 0:
138
+ return ""
139
+ base = _git(wt, "rev-parse", "--verify", "--quiet", "origin/main").stdout.strip() or None
140
+ ok, out, secs = gate.check_commit(wt, sha, base)
141
+ if ok:
142
+ return ""
143
+ lines = ";".join(gate.failed_tests(out)[:5])
144
+ log = gate.state_dir() / "gate_logs" / f"{sha}.log"
145
+ return f"check.sh --fast 没过({secs:.0f} 秒),未落地,worktree 保留在 {wt}:{lines};完整输出:{log}"
146
+
147
+
148
+ def _land_local(key: str, wt: Path, br: str, cfg: core.Config | None) -> tuple[bool, str]:
149
+ """Old route for a repo with no origin remote: ff-only merge into the local main (rebasing once)."""
150
+ base = _git(key, "rev-parse", "HEAD").stdout.strip()
151
+ ahead = _git(key, "rev-list", "--count", f"{base}..{br}").stdout.strip()
152
+ if ahead in ("", "0"):
153
+ _cleanup(key, wt, br, cfg)
154
+ return True, "没有新提交,只清理"
155
+ refused = _gate(wt)
156
+ if refused:
157
+ return False, refused
158
+ ok = _git(key, "merge", "--ff-only", br).returncode == 0
159
+ if not ok:
160
+ rb = _git(wt, "rebase", "main")
161
+ if rb.returncode != 0:
162
+ _git(wt, "rebase", "--abort")
163
+ return False, f"与 main 冲突,未落地,worktree 保留在 {wt}:{(rb.stderr or rb.stdout).strip()[-200:]}"
164
+ ok = _git(key, "merge", "--ff-only", br).returncode == 0
165
+ if not ok:
166
+ return False, f"无法快进 main,未落地,worktree 保留在 {wt}"
167
+ _cleanup(key, wt, br, cfg)
168
+ return True, f"已落地 {ahead} 个提交"
@@ -0,0 +1,308 @@
1
+ Metadata-Version: 2.4
2
+ Name: aisync-cli
3
+ Version: 0.2.7
4
+ Summary: Multi-agent context management, coordination and observability for AI coding agents: shared rules written as When/Do/Not interfaces, a hash-chained journal, file claims, layered rule loading and mid-session news hooks for Claude Code, Codex and Cursor, plus an MCP server for any agent.
5
+ License: MIT
6
+ Project-URL: Homepage, https://maxont.github.io/aisync
7
+ Project-URL: Source, https://github.com/MaxonT/aisync
8
+ Keywords: ai,agents,agents-md,multi-agent,claude-code,codex,cursor,coordination,mcp,developer-tools,cli
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: MacOS
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Environment :: Console
14
+ Classifier: Topic :: Software Development
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: mcp
19
+ Requires-Dist: mcp<3,>=2.3; extra == "mcp"
20
+ Dynamic: license-file
21
+
22
+
23
+
24
+
25
+
26
+
27
+ <div align="center">
28
+
29
+ <img src="docs/assets/banner.svg" width="100%" alt="aisync: Multi-Agent Context Management, Coordination & Observability"/>
30
+
31
+ # aisync: Multi-Agent Context Management, Coordination & Observability
32
+
33
+ **One local hub for developers working with multiple AI coding agents: share the right context, coordinate concurrent work, and verify what happened.**
34
+
35
+ aisync is **agent-agnostic at its core**. It provides native hooks for Claude Code, Codex and Cursor, and exposes its hub to other agents through a CLI, MCP server, or shared instruction files. These three native integrations are **not** a limit on which agents can use aisync.
36
+
37
+ [![ci](https://github.com/MaxonT/aisync/actions/workflows/ci.yml/badge.svg)](https://github.com/MaxonT/aisync/actions/workflows/ci.yml)
38
+ [![release](https://img.shields.io/github/v/release/MaxonT/aisync)](https://github.com/MaxonT/aisync/releases)
39
+ ![python](https://img.shields.io/badge/python-3.11%2B-blue)
40
+ ![deps](https://img.shields.io/badge/dependencies-0-brightgreen)
41
+ ![license](https://img.shields.io/badge/license-MIT-green)
42
+ [![GitHub stars](https://img.shields.io/github/stars/MaxonT/aisync.svg?style=social)](https://github.com/MaxonT/aisync/stargazers)
43
+
44
+ **English** · [中文](README.zh-CN.md) · [Website](https://maxont.github.io/aisync/) · [Demo status board](https://maxont.github.io/aisync/board/)
45
+
46
+ </div>
47
+
48
+ > [!NOTE]
49
+ > **Multiple coding agents should not have to work with isolated rules, conflicting file ownership, and disconnected histories.**
50
+ > aisync is a **local, verifiable hub** (`~/.ai-sync/`, a git repo) designed for multi-agent workflows:
51
+ >
52
+ > - **Context management:** share and 3-way-sync rules; load core context up front and inject relevant context on demand, including mid-session updates where hooks are available.
53
+ > - **Multi-agent coordination:** declare file claims, detect overlapping claims (exit code 3), release ownership, and surface blockers and other agents' activity.
54
+ > - **Observability & verification:** inspect agent activity, blockers, and health through the journal, status reports, and board; `aisync verify` checks the journal's hash chain for tampering.
55
+ >
56
+ > File claims are **cooperative**, not OS-enforced locks: agents must use the claim protocol. Hash-chain verification detects changes to recorded events; it does not prove every claimed action occurred.
57
+
58
+ ## Who it's for
59
+
60
+ Developers running **two or more AI coding agents** across one or multiple repositories—especially when agents work concurrently, hand tasks off, or need a shared record of decisions and blockers. aisync is not another coding agent or a task orchestrator: it is the **shared context and coordination layer** those agents can use.
61
+
62
+ ## See it
63
+
64
+ <div align="center">
65
+
66
+ ### The Agent Swarm Floor
67
+
68
+ <img width="705" height="875" alt="cover" src="https://github.com/user-attachments/assets/cee23378-2379-49a5-960b-ac63764bb95f" />
69
+
70
+
71
+
72
+ https://github.com/user-attachments/assets/f741ef6f-0c10-46f4-8c94-769c6e02d30e
73
+
74
+
75
+
76
+
77
+ ## Integrations: native hooks are not the compatibility boundary
78
+
79
+ | Integration | Who can use it | What to expect |
80
+ |---|---|---|
81
+ | **Native hooks** | Claude Code, Codex, Cursor | Automatic context and news delivery at supported hook events, plus access to aisync's coordination and journal commands |
82
+ | **MCP server** | MCP-compatible agents | Exposes rules, rule additions, logging, claims, releases, news, status and tidy; an agent must invoke the tools |
83
+ | **CLI** | Agents that can run shell commands | Direct access to hub operations such as `aisync claim`, `aisync news`, `aisync log` and `aisync verify` |
84
+ | **Shared instruction files** | Agents that read supported instruction files | Standing rules and context only; not automatic mid-session news or file-claim enforcement |
85
+
86
+ **Compatibility is not equivalent to automatic integration.** For agents without native hooks, features depend on the agent's MCP/CLI usage and configuration. aisync does not automatically intercept all edits or guarantee every agent will honor file claims.
87
+
88
+ <p align="center"><img src="docs/assets/cli.png" alt="Running aisync in a terminal: a gradient AISYNC pixel logo, then every command grouped as start, every session, look around, keep the rules lean, keep it running" width="720"></p>
89
+
90
+ ## Install
91
+
92
+ **Give it to your AI.** It reads the page, does a dry run first and asks before it changes anything:
93
+
94
+ ```text
95
+ Read https://maxont.github.io/aisync/install and install aisync for me.
96
+ ```
97
+
98
+ **Or in a terminal.** It installs with uv, pipx or pip and never edits your shell config:
99
+
100
+ ```bash
101
+ curl -fsSL https://maxont.github.io/aisync/install.sh | bash
102
+ ```
103
+
104
+ Needs Python 3.11+ and git, on macOS or Linux. Nothing else: aisync uses only the standard library.
105
+
106
+
107
+ ### Two agents, one file
108
+
109
+ <img src="docs/assets/demo.gif" width="100%" alt="A real terminal: aisync demo prints a hub's status, claude-code claims app/api/refunds.py, codex claims the same file and is refused with OVERLAP and exit 3, codex logs a blocker, claude-code hears it through aisync news, releases the file, and codex's claim then succeeds"/>
110
+
111
+ <sub>A real terminal run: `aisync demo` (synthetic data), then two tools reach for the same file.
112
+ Step by step: [how it works](https://maxont.github.io/aisync/how-it-works/) · the same demo hub as a
113
+ [status board](https://maxont.github.io/aisync/board/).</sub>
114
+
115
+ </div>
116
+
117
+ | Multi-agent need | What aisync provides |
118
+ |---|---|
119
+ | **Context management** | 3-way-synced rules, layered rule loading and relevant mid-session news via hooks |
120
+ | **Multi-agent coordination** | Cooperative file claims and releases, overlap detection (exit 3), blockers and activity updates |
121
+ | **Observability & verification** | Hash-chained event journal, `aisync verify`, `status`, `report`, `tail` and a static `board` |
122
+
123
+ aisync also does the rules part: one rules block copied into every tool's own rule file, synced 3-way, conflicts never overwritten.
124
+
125
+ **Dogfooded:** 6,700+ journal events from 7 AI tools over 4 weeks.
126
+
127
+ ## Why not just AGENTS.md?
128
+
129
+ Keep AGENTS.md for a repo's standing instructions. aisync sits beside it and covers what a single file cannot: the context that changes while agents work.
130
+
131
+ | | AGENTS.md | aisync |
132
+ |---|---|---|
133
+ | Scope | Standing instructions for agents working in a repo | A shared hub across configured agents and repositories |
134
+ | When it is read | When a session starts | At start, and mid-session through hooks |
135
+ | Who is editing what | Not covered | Cooperative claims: an overlap returns exit 3 to the caller |
136
+ | Tamper evidence | Not provided by the file format | Hash-chained journal: `aisync verify` detects alterations to recorded events |
137
+ | Context per session | Whole file, every time | Triggered rules only: always-loaded rules 20,673 → 7,876 tokens* |
138
+
139
+ <sub>\* Measured once on one author's own hub (2026-11-08), always-loaded rules before and after layered loading. One machine, not a benchmark: your numbers will differ. `aisync tidy` reports your own rule budget and uncited rules.</sub>
140
+
141
+ ## Use it
142
+
143
+ ```bash
144
+ aisync demo # a throwaway hub with a synthetic two-week journal
145
+ aisync init # create ~/.ai-sync (or wherever AISYNC_HOME points)
146
+ aisync install-hooks # shows every tool config change as a diff, then asks
147
+ aisync watch & # event-driven sync loop (or run `aisync sync` by hand)
148
+ ```
149
+
150
+ What an agent does during a session:
151
+
152
+ ```bash
153
+ aisync claim -a codex -p api -f app/payments/ -m "SDK upgrade" # 3 = taken
154
+ aisync log -a codex -p api -m "SDK 5.0, retries kept"
155
+ aisync rule add -a codex --when "changing an API" --do "add a contract test"
156
+ aisync release -a codex -p api
157
+ ```
158
+
159
+ | Command | What it does |
160
+ |---|---|
161
+ | `init` | create the hub: shared rules, journal, config, local git repo |
162
+ | `log` | append one event (`dev_log`, `decision`, `blocked`, `unblocked`, `rule_change`, `note`) |
163
+ | `rule add` / `rule list` | any agent adds a shared rule (`--when/--do/--not`, `--topic`, `--replaces R-012`); every tool's copy gets it on the next sync |
164
+ | `rule lint` / `rule rewrite` / `rule enforcement` | rules not in the When/Do/Not shape / rewrite them by ID without losing a fact / which test or hook keeps each rule |
165
+ | `rule enforce` | say what keeps an existing rule: `rule enforce R-012 --enforced-by tests/test_x.py`, `--judgment-only "<why>"`, or `--planned "<the check to write>" --size S\|M\|L` for a check that is possible and not written yet. `rule enforcement` then lists every open one with its next step: an enforcer file that is gone, a plan past its due days (S 7, M 30, L 90), a rule with no plan. A plan's clock only runs: a later date, a larger size or a switch to judgment-only needs `--reason` and stays on record |
166
+ | `tidy` | rules clerk: likely duplicates, rules nobody cited lately, core layer over budget; proposals only, you tick them |
167
+ | `rulecheck` | prove a rules cleanup lost no hard fact (paths, numbers, commands, IDs) |
168
+ | `instinct` | optional habit list grown from past mistakes, injected into every session |
169
+ | `gate` | push-time test gate: `gate check` runs `./check.sh --fast` on a commit; the git pre-push hook calls `gate pre-push` (opt-in, see below) |
170
+ | `web-inbox` | import web-Claude events from the `web-inbox` branch now (`--no-fetch` uses the last fetched copy) |
171
+ | `guard` | Claude Code hook: one session per repo; denies an edit when another session holds the repo (opt-in, see below) |
172
+ | `lease` | who holds which repo (`lease status`), or free one by hand (`lease release --key`) |
173
+ | `wt` | a session's own git worktree: `wt start` opens it; `wt land` lands it on main and needs `--yes` (without it: a dry run) |
174
+ | `mcp` | serve the hub to any MCP agent over stdio (`pip install 'aisync-cli[mcp]'`) |
175
+ | `claim` / `release` / `claims` | who is working on which files right now; overlap = exit 3 |
176
+ | `news` | what other tools did since this session last looked |
177
+ | `hook <tool>` | entry point for Claude Code, Codex and Cursor hooks (reads hook JSON, never fails) |
178
+ | `install-hooks` | wire the hooks, seed the rules block, add the git `Agent:` trailer hook; diff first, asks before writing (`--dry-run`, `--yes`) |
179
+ | `status` | health, conflicts, claims, blockers, metrics (exit 1 when something needs you) |
180
+ | `board` | write the hub as one static HTML page: claims, blockers, who did what, timeline |
181
+ | `report` | read-only self-check: silent tools, commits without an `Agent:` trailer, stale blockers |
182
+ | `tail` | latest journal events |
183
+ | `verify` | check the hash chain |
184
+ | `sync` / `watch` | run one sync cycle / the debounced, event-driven loop |
185
+ | `resolve` / `resume` | rule on a rule conflict / clear failure counters after a pause |
186
+ | `demo` | the throwaway hub shown above |
187
+ | `version` / `-v` / `-V` / `--version` | print the version |
188
+ | `help [command]` | this screen, or one command's options (`aisync help log`) |
189
+ | `update` | check GitHub for a newer release and print the command that upgrades (uv, pipx, install.sh, brew or pip); it never installs by itself |
190
+ | `doctor` | check python, git, the hub folder and the journal chain (exit 1 on any failure) |
191
+
192
+ ## New in 0.2.0: rules as interfaces, loaded in layers
193
+
194
+ A rules file grows until every session pays for it and nobody reads it. 0.2.0 treats a rule like an API:
195
+
196
+ - **When / Do / Not.** Each rule is one line with a stable ID: `[R-087] When: <trigger>. Do: <action>. Not: <forbidden>.`
197
+ The why goes to the journal, not the rule. `rule_spec = true` refuses anything else; `rule lint` lists misfits;
198
+ `rule rewrite` reshapes old rules by ID and refuses a rewrite that drops a path, number or command.
199
+ - **Layers.** Mark a tool copy `layer = "core"`: it carries `core_topics` in full and every other topic as one line.
200
+ When a prompt or tool call touches a topic's keywords (`[shelf]`), the hook injects that topic once per session.
201
+ On the author's own hub this cut the always-loaded rules from 20,673 to 7,876 tokens; replaying 7 days of
202
+ transcripts, 98.9% of the 189 times a folded rule was cited, it had been injected before the citation.
203
+ - **A stable prefix.** `progress_file` moves the live progress table out of the shared page, so the page stays
204
+ byte-identical and prompt caches keep hitting: the next session after a journal event read 61,151 cached tokens
205
+ instead of 13,060.
206
+ - **A clerk, not a janitor.** `aisync tidy` proposes (duplicates, uncited rules, budget overruns) and never edits;
207
+ a replaced rule moves to `rules-archive.md` with its ID, nothing is deleted.
208
+ - **Any agent.** Three doors: the AGENTS.md page, the CLI, and `aisync mcp` (tools: rules, rule_add, log, claim,
209
+ release, news, status, tidy). The core stays standard-library only; the MCP SDK is the optional `aisync-cli[mcp]` extra.
210
+
211
+ ## How it works
212
+
213
+ <p align="center"><img src="docs/assets/how-it-works.gif" width="100%" alt="Six steps: tool A claims a file, tool B is refused with exit 3, B logs a blocker, a hook tells A mid-session, A releases, B proceeds"/></p>
214
+ <p align="center"><sub><a href="https://maxont.github.io/aisync/how-it-works/">Step through it at your own pace</a> (play, pause, ← →)</sub></p>
215
+
216
+ A sync cycle is `harvest` (new git commits in watched repos become journal events, attributed by
217
+ their `Agent:` trailer) → `rules` (new entries in repos you list in `rule_sources`) → `distribute`
218
+ (3-way sync of the rules block into each tool file) → `render` (progress page) → `flush` (commit the
219
+ hub, optional push). Each step is isolated: one failure never blocks the others.
220
+
221
+ The rules block is synced 3-way. If only the truth changed, copies are overwritten (with a backup).
222
+ If one copy was edited and nobody else changed anything, the edit is adopted everywhere. If both
223
+ sides changed, nothing is overwritten: it becomes a conflict for you to resolve.
224
+
225
+ Reliability and observability: timeouts and retries with backoff on every git call, failure
226
+ isolation per step and per project, auto-pause after `fail_threshold` failures in a row with an
227
+ `ALERT.md` and a desktop notification, a per-cycle run log (`state/runs.jsonl`), hook call stats and
228
+ `aisync status` for all of it.
229
+
230
+ ## Configuration
231
+
232
+ `~/.ai-sync/config.toml` (set `AISYNC_HOME` to put the hub anywhere):
233
+
234
+ ```toml
235
+ roster = ["claude-code", "codex", "cursor"] # tools `report` expects to hear from
236
+ scan_dirs = ["~/projects"] # every git repo inside is watched
237
+ rule_sources = [] # repos whose AGENTS.md "## Meta rule" feeds shared rules
238
+ remote = "" # e.g. "origin" to also push the hub
239
+
240
+ progress_file = "progress.md" # keep agents.md byte-stable; hooks inject progress at session start
241
+ rule_spec = true # rule add only accepts When/Do/Not rules
242
+ require_enforcer = false # true: every new rule names --enforced-by or --judgment-only
243
+ core_topics = ["Safety", "Meta"] # topic headings a layered copy carries in full
244
+ instincts_path = "" # optional habit file injected at session start
245
+ tidy_daily = false # the watcher starts one `aisync tidy --write` a day
246
+ tidy_usage_globs = [] # files whose R-### mentions count as a rule being used
247
+ gate_hook = false # opt-in: the git pre-push hook runs the test gate (gate.py)
248
+ guard_hook = false # opt-in: Claude Code runs the one-session-per-repo guard (guard.py)
249
+ web_inbox_secs = 0 # 0 = off; else poll the web-inbox branch this often
250
+
251
+ [shelf] # folded topic -> keywords that pull it into a session
252
+ Deploys = ["deploy", "terraform", "rollback"]
253
+
254
+ [[target]] # files carrying the shared-rules block
255
+ label = "claude-code"
256
+ path = "~/.claude/CLAUDE.md"
257
+ layer = "core" # optional: fold non-core topics, inject them on demand
258
+ ```
259
+
260
+ To keep `aisync watch` running, start it from your login items, a systemd user unit or a launchd
261
+ agent that runs `aisync watch`; create `~/.ai-sync/STOP` to stop it cleanly.
262
+
263
+ **Opt-in features (all off by default).** `gate_hook`, `guard_hook` and `web_inbox_secs` change behavior outside the hub,
264
+ so nothing turns on until you set them. The guard can deny edits: if a session is locked out, run
265
+ `aisync lease status`, and once the holder session has ended, `aisync lease release --key <repo>`. To undo the guard,
266
+ delete the `PreToolUse` and `SessionEnd` entries whose command ends in ` guard` from `~/.claude/settings.json`.
267
+
268
+ ## Standing on the shoulders of
269
+
270
+ > aisync: Multi-Agent Context Management, Coordination & Observability. AGENTS.md was the starting idea.
271
+
272
+ | Project | How it shaped aisync |
273
+ |---|---|
274
+ | [![AGENTS.md stars](https://img.shields.io/github/stars/agentsmd/agents.md?style=social&label=AGENTS.md)](https://github.com/agentsmd/agents.md) | The starting idea: one plain-text instruction file every agent reads, no SDK. aisync keeps that shape for shared rules (one rules block copied into each tool's own AGENTS.md / CLAUDE.md) and adds what a static file cannot say: who is editing what right now, and what changed since the session started. |
275
+ | [![Claude Code stars](https://img.shields.io/github/stars/anthropics/claude-code?style=social&label=Claude%20Code)](https://github.com/anthropics/claude-code) | Mid-session news rides on Claude Code hooks: `aisync install-hooks` adds SessionStart, UserPromptSubmit and PostToolUse entries to ~/.claude/settings.json, and `aisync hook claude-code` answers with hookSpecificOutput.additionalContext only when another tool changed something. |
276
+ | [![Codex stars](https://img.shields.io/github/stars/openai/codex?style=social&label=Codex)](https://github.com/openai/codex) | Codex reads ~/.codex/AGENTS.md, which is where aisync seeds the shared rules block, and its hooks.json takes the same SessionStart / UserPromptSubmit / PostToolUse events, so `aisync hook codex` reuses the Claude Code reply format. |
277
+ | [Cursor](https://cursor.com/docs/agent/hooks) | Cursor hooks (~/.cursor/hooks.json) deliver the rules and progress at sessionStart and the news after each postToolUse through additional_context, because Cursor's User Rules live inside the app instead of a file aisync could sync. |
278
+ | [![git stars](https://img.shields.io/github/stars/git/git?style=social&label=git)](https://github.com/git/git) | The journal borrows git's hash chain: every event stores the id of the one before it and its own id is a SHA-256 of that link plus its body, so `aisync verify` spots any edited, lost or reordered line. The hub itself is a local git repo. |
279
+
280
+ aisync is an independent project, not affiliated with the projects above.
281
+
282
+ ## Development
283
+
284
+ ```bash
285
+ python3 -m unittest discover -s tests # includes wheel -> venv -> demo
286
+ ```
287
+
288
+ The images are generated: the terminal GIF is a recorded real run of
289
+ [`.github/refine/demo-terminal.json`](.github/refine/demo-terminal.json), the how-it-works animation
290
+ comes from [`.github/refine/how-it-works.stages.json`](.github/refine/how-it-works.stages.json), and the
291
+ credits above from [`.github/refine/lineage.json`](.github/refine/lineage.json). All demo data is synthetic.
292
+
293
+ MIT licensed.
294
+
295
+
296
+ ## More Videos if you like!
297
+
298
+ https://github.com/user-attachments/assets/5ea7928b-4985-4700-8551-90477a84df40
299
+
300
+ https://github.com/user-attachments/assets/91385ac4-714c-4a16-908b-1859ef1c78e2
301
+
302
+
303
+ https://github.com/user-attachments/assets/bf661d5c-b7b1-4876-8469-2e11dd95b232
304
+
305
+
306
+
307
+ https://github.com/user-attachments/assets/d32f3abd-2986-4fbf-83a2-be287f0185a7
308
+
@@ -0,0 +1,31 @@
1
+ ai_sync/__init__.py,sha256=iCVfhTh5i5GOAUzpr-tQrRLwqVx-NkDhXK1LmqQmkbs,144
2
+ ai_sync/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ ai_sync/board.py,sha256=pXIUJPyaqKRxJY8TNOuTNJOxbnKxcPYoSQ28WT8LSnc,15934
4
+ ai_sync/cli.py,sha256=l3HnFz0konXYqz-O5RPuRZq9SUuq-uRTISzvmGx0YMQ,46965
5
+ ai_sync/collab.py,sha256=tRpv8sAbH_JtQ9zo3lqY3ZmSMYmdMgUiQsT_gLH-0iQ,25211
6
+ ai_sync/core.py,sha256=V0UEiAfEcaeAB4ysccSLXvxQgFI3Y-d6D-8gI5EWT94,45954
7
+ ai_sync/demo.py,sha256=CA3ZjPZSBYapllrDDUN__xSM4ndzArMO2xv63RLrPH4,18929
8
+ ai_sync/enforcement.py,sha256=QWKIcrMYnpBCEb9lNZzdAxnl_JeUqGS9Uaxi8wrC_4E,17038
9
+ ai_sync/gate.py,sha256=BbrDBJAOVJ5wsFOn9l86D0-kCLHUFh65y0H1Z8RF7tA,13106
10
+ ai_sync/guard.py,sha256=Da8IjCOP2usWA6PytKKaWFqszeYKZqZgkizz5Wvow84,18839
11
+ ai_sync/hooks.py,sha256=EFBK_KN2erUeKshG1jLqvsw-H-aECBUPdX9WNZEoVIc,26841
12
+ ai_sync/instincts.py,sha256=zfvIxhVbVQDBKcm5M3w_CZww0918xroMfrD6KHPEc7k,5274
13
+ ai_sync/landq.py,sha256=LcCCzTYN96BFKAS0uZmkCocODrmHm4NKJFs4WbqACNs,8071
14
+ ai_sync/layers.py,sha256=ST_Aq0HjWq-1P53E7j8Cdw9ldMNbo-YxTqQf5H15MKQ,4477
15
+ ai_sync/mcp_server.py,sha256=u3aHnRx7nGTfs_SttveWGAvt3zkTx3lrpEUXswelc7w,6045
16
+ ai_sync/nonvacuous.py,sha256=AGw2Qt3UEHh10XIaLXQT4kB5_dsMm2H5QJFPMXboJIY,4805
17
+ ai_sync/rulecheck.py,sha256=UICGmOoXRT0rZaAeiSu5MmhxwGXngDzgxLE7QO-lluA,7140
18
+ ai_sync/ruleids.py,sha256=RUStiknw9r-NGWyu0UWnt57ojVx-hMis0p5X3jfy6T4,6942
19
+ ai_sync/rulespec.py,sha256=G90apC3JNaGh-uY9vediYxuhWCTb31UlOdvfrciwIyo,9571
20
+ ai_sync/tidy.py,sha256=zEVclAtyZXKUdugVUQRDbNBsUv07OXXcrD2kP6FNCV8,7606
21
+ ai_sync/ui.py,sha256=EJ-fpPNtvwS2OL5WzVgWF5UpxABJuuz_yX0dwusO3AI,6968
22
+ ai_sync/update.py,sha256=DqjcGx1CKPtRfWWgvQWMDX0pY2f0m5yoo8G28_rjZZQ,3036
23
+ ai_sync/watch.py,sha256=rhvAGlglH4aYoo6o5XLX3Xntx_IR9sUGw96i8ZfxSiw,8072
24
+ ai_sync/webinbox.py,sha256=qTEGHvTSTLjuloTQMEh9eV6mT97kQ6jAoqrpb53-Azk,8058
25
+ ai_sync/worktree.py,sha256=iQIB8p7tEJYwp10t-U8h2gjrTcYQWIMWPZgdeij9t4U,8992
26
+ aisync_cli-0.2.7.dist-info/licenses/LICENSE,sha256=H_Y0QHR38Vk118dzlGmqmqb3IfSWMI3vzmv-efGpyGA,1075
27
+ aisync_cli-0.2.7.dist-info/METADATA,sha256=0Dpf8Wex5nNfVB0364znt9A4luYAW1EHk7MGSUPT1vk,20591
28
+ aisync_cli-0.2.7.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
29
+ aisync_cli-0.2.7.dist-info/entry_points.txt,sha256=-WOd-2oPlrFJNPlux987w-qSkcKm-De7rPk0TFnvx94,44
30
+ aisync_cli-0.2.7.dist-info/top_level.txt,sha256=wbSmfhevvmgfI1u4xftdv_9UTSRFUbFhVU55tvzUBYM,8
31
+ aisync_cli-0.2.7.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ aisync = ai_sync.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 the aisync authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ ai_sync