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/__init__.py +2 -0
- ai_sync/__main__.py +5 -0
- ai_sync/board.py +285 -0
- ai_sync/cli.py +932 -0
- ai_sync/collab.py +476 -0
- ai_sync/core.py +974 -0
- ai_sync/demo.py +285 -0
- ai_sync/enforcement.py +328 -0
- ai_sync/gate.py +265 -0
- ai_sync/guard.py +390 -0
- ai_sync/hooks.py +577 -0
- ai_sync/instincts.py +113 -0
- ai_sync/landq.py +182 -0
- ai_sync/layers.py +113 -0
- ai_sync/mcp_server.py +134 -0
- ai_sync/nonvacuous.py +110 -0
- ai_sync/rulecheck.py +153 -0
- ai_sync/ruleids.py +162 -0
- ai_sync/rulespec.py +202 -0
- ai_sync/tidy.py +145 -0
- ai_sync/ui.py +162 -0
- ai_sync/update.py +73 -0
- ai_sync/watch.py +191 -0
- ai_sync/webinbox.py +173 -0
- ai_sync/worktree.py +168 -0
- aisync_cli-0.2.7.dist-info/METADATA +308 -0
- aisync_cli-0.2.7.dist-info/RECORD +31 -0
- aisync_cli-0.2.7.dist-info/WHEEL +5 -0
- aisync_cli-0.2.7.dist-info/entry_points.txt +2 -0
- aisync_cli-0.2.7.dist-info/licenses/LICENSE +21 -0
- aisync_cli-0.2.7.dist-info/top_level.txt +1 -0
ai_sync/instincts.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""instincts: the habits that grew out of past mistakes, injected into every session by the hook.
|
|
2
|
+
|
|
3
|
+
What: an optional habit file (`instincts_path` in config.toml) with one numbered line per habit, each
|
|
4
|
+
pointing back at an EB-id in an optional error log (`errors_path`, headings "### EB-NNN title").
|
|
5
|
+
`aisync hook` injects the whole file at SessionStart and only new lines afterwards.
|
|
6
|
+
Why: a lesson file nobody reads does nothing; injected, every new session starts with it.
|
|
7
|
+
How: both paths are off by default (empty). Reads are plain file reads, no git, no scanning. Adding a line
|
|
8
|
+
only writes the file and the journal; committing is the caller's job.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import difflib
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from . import core
|
|
18
|
+
|
|
19
|
+
LINE_RE = re.compile(r"^\s*(\d+)\.\s+\S")
|
|
20
|
+
EB_RE = re.compile(r"^EB-\d+$")
|
|
21
|
+
HEAD_RE = re.compile(r"^#{1,6}\s*(EB-\d+)\b", re.M)
|
|
22
|
+
CONFLICT_RE = re.compile(r"^(<<<<<<<|=======$|>>>>>>>)", re.M)
|
|
23
|
+
SAME = 0.8 # a new habit this close to an existing one is a repeat (one habit was once added 9 times)
|
|
24
|
+
SAME_EB = 0.6 # with the same EB id, this close is enough (0.45 flagged two unrelated short habits)
|
|
25
|
+
MAX_PER_EB = 2 # one mistake grows at most two habits; a third means sharpen one of them
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _habit(line: str) -> str:
|
|
29
|
+
"""'12. text(EB-001)' -> 'text'."""
|
|
30
|
+
return re.sub(r"(EB-\d+)|\(EB-\d+\)", "", re.sub(r"^\s*\d+\.\s+", "", line)).strip(" 。.")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def repeat_of(lines: list[str], text: str, eb: str) -> str:
|
|
34
|
+
"""The existing habit line `text` repeats, or ''."""
|
|
35
|
+
new = _habit(text)
|
|
36
|
+
for l in lines:
|
|
37
|
+
r = difflib.SequenceMatcher(None, _habit(l), new).ratio()
|
|
38
|
+
if r >= SAME or (eb and eb in l and r >= SAME_EB):
|
|
39
|
+
return l
|
|
40
|
+
return ""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def instincts_path(cfg: core.Config) -> Path | None:
|
|
44
|
+
return Path(cfg.instincts_path).expanduser() if cfg.instincts_path else None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def errors_path(cfg: core.Config) -> Path | None:
|
|
48
|
+
return Path(cfg.errors_path).expanduser() if cfg.errors_path else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def read(cfg: core.Config) -> tuple[str, list[str], str]:
|
|
52
|
+
"""(full text, numbered habit lines, error). error is '' when the file was read or the feature is off."""
|
|
53
|
+
p = instincts_path(cfg)
|
|
54
|
+
if p is None:
|
|
55
|
+
return "", [], ""
|
|
56
|
+
try:
|
|
57
|
+
text = p.read_text()
|
|
58
|
+
except OSError as ex:
|
|
59
|
+
return "", [], f"{p}: {type(ex).__name__}"
|
|
60
|
+
return text, [l.rstrip() for l in text.splitlines() if LINE_RE.match(l)], ""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def inject_text(text: str, err: str, new: list[str] | None = None) -> str:
|
|
64
|
+
if err:
|
|
65
|
+
return f"[aisync] instincts file unreadable: {err}"
|
|
66
|
+
if new is not None:
|
|
67
|
+
return ("[aisync] NEW instinct(s) added to the habit list, follow them from now on:\n" + "\n".join(new)) if new else ""
|
|
68
|
+
if not text.strip():
|
|
69
|
+
return ""
|
|
70
|
+
return ("[aisync] Instincts (habits grown from past mistakes; each line points at an EB id in the error bank; "
|
|
71
|
+
"source: instincts.md; after each step add one with `aisync instinct add \"...\" --from EB-xxx`):\n"
|
|
72
|
+
+ text.strip())
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def error_ids(cfg: core.Config) -> set[str] | None:
|
|
76
|
+
"""EB ids in the error log; None when no error log is configured (then any EB-nnn is accepted)."""
|
|
77
|
+
p = errors_path(cfg)
|
|
78
|
+
return None if p is None else set(HEAD_RE.findall(p.read_text()))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def add(cfg: core.Config, *, agent: str, text: str, eb: str) -> dict:
|
|
82
|
+
text = " ".join((text or "").split())
|
|
83
|
+
if not text:
|
|
84
|
+
raise ValueError("give the habit as one sentence")
|
|
85
|
+
if not EB_RE.match(eb or ""):
|
|
86
|
+
raise ValueError(f"--from must look like EB-023, got {eb!r}")
|
|
87
|
+
try:
|
|
88
|
+
known = error_ids(cfg)
|
|
89
|
+
except OSError as ex:
|
|
90
|
+
raise ValueError(f"cannot read the error bank {errors_path(cfg)}: {type(ex).__name__}") from ex
|
|
91
|
+
if known is not None and eb not in known:
|
|
92
|
+
raise ValueError(f"{eb} is not in {errors_path(cfg)}; record the mistake there first")
|
|
93
|
+
p = instincts_path(cfg)
|
|
94
|
+
if p is None:
|
|
95
|
+
raise ValueError("no habit file configured: set instincts_path in config.toml")
|
|
96
|
+
try:
|
|
97
|
+
old = p.read_text()
|
|
98
|
+
except OSError as ex:
|
|
99
|
+
raise ValueError(f"cannot read {p}: {type(ex).__name__}") from ex
|
|
100
|
+
if CONFLICT_RE.search(old):
|
|
101
|
+
raise ValueError(f"{p} has unresolved git conflict markers; resolve them before adding a habit")
|
|
102
|
+
dup = repeat_of([l for l in old.splitlines() if LINE_RE.match(l)], text, eb)
|
|
103
|
+
if dup:
|
|
104
|
+
raise ValueError(f"this habit is already on the list: {dup.strip()}; sharpen that line instead of adding a copy")
|
|
105
|
+
same_eb = [l for l in old.splitlines() if LINE_RE.match(l) and (f"{eb})" in l or f"({eb})" in l)]
|
|
106
|
+
if len(same_eb) >= MAX_PER_EB:
|
|
107
|
+
raise ValueError(f"{eb} already has {len(same_eb)} habits (at most {MAX_PER_EB}); sharpen one of them instead")
|
|
108
|
+
nums = [int(m.group(1)) for l in old.splitlines() if (m := LINE_RE.match(l))]
|
|
109
|
+
line = f"{max(nums, default=0) + 1}. {text}({eb})"
|
|
110
|
+
core.atomic_write(p, old.rstrip("\n") + "\n" + line + "\n")
|
|
111
|
+
ev = core.append_event(cfg, agent=agent, kind="note", project="instincts", files=[str(p)],
|
|
112
|
+
summary=f"instinct added: {line}", refs={"eb": eb})
|
|
113
|
+
return {"line": line, "path": str(p), "event": ev["id"]}
|
ai_sync/landq.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Per-repo landing queue for main (merge queue, 2026-11-02).
|
|
2
|
+
|
|
3
|
+
Why: with a fast suite of 1-3 minutes, pushers to a busy main (background jobs) lost the race again and again: each one
|
|
4
|
+
rebased, checked, and found main had moved during its own check (nonvacuous lost 5 times in a row).
|
|
5
|
+
What: one lock per repo, ~/.ai-sync/state/land/<repo-key>.lock, an flock on that file plus a JSON line naming the
|
|
6
|
+
holder (pid, session, since, token). `aisync wt land` holds it across fetch -> rebase -> check -> push; the pre-push
|
|
7
|
+
gate holds it for a plain `git push` to main from the check until that `git push` process exits. Waiters print
|
|
8
|
+
"排队中,前面是 <holder>" and wait up to WAIT_MIN. The kernel drops an flock when its holder dies; a holder still
|
|
9
|
+
alive after STALE_MIN is taken over (its lock file is unlinked, the next one starts on a fresh file).
|
|
10
|
+
A push made by the holder itself (wt land's own `git push`) carries GATE_LAND_TOKEN, so its hook does not queue
|
|
11
|
+
behind its own lock.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import datetime as dt
|
|
16
|
+
import fcntl
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
import time
|
|
23
|
+
import uuid
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
WAIT_MIN = 20
|
|
27
|
+
STALE_MIN = 15
|
|
28
|
+
TOKEN_ENV = "GATE_LAND_TOKEN"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def lock_dir() -> Path:
|
|
32
|
+
from . import gate
|
|
33
|
+
return gate.state_dir() / "land"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def repo_key(repo, remote: str = "origin") -> str:
|
|
37
|
+
"""One key per place main lives: the remote's URL, so every clone and worktree pushing to the same GitHub repo
|
|
38
|
+
queues together (git@example.com:owner/repo.git and https://example.com/owner/repo share one key). Without that remote: the
|
|
39
|
+
repository itself, shared by its main checkout and all its worktrees."""
|
|
40
|
+
url = subprocess.run(["git", "-C", str(repo), "remote", "get-url", remote], capture_output=True,
|
|
41
|
+
text=True).stdout.strip()
|
|
42
|
+
if not url and ("/" in remote or ":" in remote):
|
|
43
|
+
url = remote # git push <url> passes the URL itself
|
|
44
|
+
if url:
|
|
45
|
+
m = re.match(r"^(?:[a-z+]+://)?(?:[^@/]+@)?([^:/]+)[:/](.+?)(?:\.git)?/?$", url)
|
|
46
|
+
local = url.startswith(("/", ".", "file://")) or os.path.exists(os.path.join(str(repo), url))
|
|
47
|
+
name = os.path.realpath(os.path.join(str(repo), url.removeprefix("file://"))) if local or not m \
|
|
48
|
+
else f"{m.group(1)}/{m.group(2)}"
|
|
49
|
+
else:
|
|
50
|
+
common = subprocess.run(["git", "-C", str(repo), "rev-parse", "--path-format=absolute", "--git-common-dir"],
|
|
51
|
+
capture_output=True, text=True).stdout.strip() or str(repo)
|
|
52
|
+
name = os.path.realpath(common[:-5] if common.endswith("/.git") else common)
|
|
53
|
+
return re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("_")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _now() -> dt.datetime:
|
|
57
|
+
return dt.datetime.now().astimezone()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _holder(path: Path) -> dict:
|
|
61
|
+
try:
|
|
62
|
+
return json.loads(path.read_text() or "{}")
|
|
63
|
+
except (OSError, ValueError):
|
|
64
|
+
return {}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _alive(pid) -> bool:
|
|
68
|
+
try:
|
|
69
|
+
os.kill(int(pid), 0)
|
|
70
|
+
return True
|
|
71
|
+
except (OSError, ValueError, TypeError):
|
|
72
|
+
return False
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def describe(h: dict) -> str:
|
|
76
|
+
return (f"{h.get('who') or '?'}(pid {h.get('pid')},{str(h.get('since', '?'))[11:19]} 起)" if h else "未知持有者")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Lock:
|
|
80
|
+
"""Context manager. `fd` stays open while held; release() closes it (which drops the flock)."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, repo, who: str, wait_min: float = WAIT_MIN, stale_min: float = STALE_MIN, say=None,
|
|
83
|
+
poll: float = 1.0, remote: str = "origin"):
|
|
84
|
+
self.path = lock_dir() / f"{repo_key(repo, remote)}.lock"
|
|
85
|
+
self.who, self.wait_min, self.stale_min, self.poll = who, wait_min, stale_min, poll
|
|
86
|
+
self.say = say or (lambda m: print(m, file=sys.stderr))
|
|
87
|
+
self.fd: int | None = None
|
|
88
|
+
self.token = uuid.uuid4().hex
|
|
89
|
+
|
|
90
|
+
def acquire(self) -> bool:
|
|
91
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
deadline, told = time.monotonic() + self.wait_min * 60, ""
|
|
93
|
+
while True:
|
|
94
|
+
fd = os.open(self.path, os.O_RDWR | os.O_CREAT, 0o644)
|
|
95
|
+
try:
|
|
96
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
97
|
+
except BlockingIOError:
|
|
98
|
+
os.close(fd)
|
|
99
|
+
h = _holder(self.path)
|
|
100
|
+
if self._stale(h):
|
|
101
|
+
self.say(f"【落地队列】{describe(h)} 持锁超过 {self.stale_min:g} 分钟,接管")
|
|
102
|
+
try:
|
|
103
|
+
self.path.unlink() # the old holder keeps a lock on a file nobody opens any more
|
|
104
|
+
except FileNotFoundError:
|
|
105
|
+
pass
|
|
106
|
+
continue
|
|
107
|
+
if time.monotonic() > deadline:
|
|
108
|
+
self.say(f"【落地队列】排队超过 {self.wait_min:g} 分钟,放弃;前面是 {describe(h)}")
|
|
109
|
+
return False
|
|
110
|
+
if describe(h) != told:
|
|
111
|
+
told = describe(h)
|
|
112
|
+
self.say(f"【落地队列】排队中,前面是 {told}")
|
|
113
|
+
time.sleep(self.poll)
|
|
114
|
+
continue
|
|
115
|
+
if not os.path.exists(self.path) or os.fstat(fd).st_ino != os.stat(self.path).st_ino:
|
|
116
|
+
os.close(fd) # taken over and replaced between open and flock: try the new file
|
|
117
|
+
continue
|
|
118
|
+
os.ftruncate(fd, 0)
|
|
119
|
+
os.write(fd, json.dumps({"who": self.who, "pid": os.getpid(), "since": _now().isoformat(timespec="seconds"),
|
|
120
|
+
"token": self.token}).encode())
|
|
121
|
+
self.fd = fd
|
|
122
|
+
return True
|
|
123
|
+
|
|
124
|
+
def _stale(self, h: dict) -> bool:
|
|
125
|
+
try:
|
|
126
|
+
since = dt.datetime.fromisoformat(h["since"])
|
|
127
|
+
except (KeyError, ValueError, TypeError):
|
|
128
|
+
return False # unknown age: keep waiting, the deadline still applies
|
|
129
|
+
return (_now() - since).total_seconds() > self.stale_min * 60
|
|
130
|
+
|
|
131
|
+
def set_pid(self, pid: int) -> None:
|
|
132
|
+
"""Name a different process as the holder (the `git push` the gate keeps the lock for)."""
|
|
133
|
+
if self.fd is not None:
|
|
134
|
+
h = _holder(self.path)
|
|
135
|
+
h["pid"] = pid
|
|
136
|
+
os.ftruncate(self.fd, 0)
|
|
137
|
+
os.lseek(self.fd, 0, 0)
|
|
138
|
+
os.write(self.fd, json.dumps(h).encode())
|
|
139
|
+
|
|
140
|
+
def release(self) -> None:
|
|
141
|
+
if self.fd is not None:
|
|
142
|
+
try:
|
|
143
|
+
if _holder(self.path).get("token") == self.token:
|
|
144
|
+
os.ftruncate(self.fd, 0)
|
|
145
|
+
except OSError:
|
|
146
|
+
pass
|
|
147
|
+
os.close(self.fd)
|
|
148
|
+
self.fd = None
|
|
149
|
+
|
|
150
|
+
def __enter__(self):
|
|
151
|
+
if not self.acquire():
|
|
152
|
+
raise TimeoutError(f"landing queue for {self.path.name}: waited {self.wait_min:g} min")
|
|
153
|
+
return self
|
|
154
|
+
|
|
155
|
+
def __exit__(self, *exc):
|
|
156
|
+
self.release()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def held_by_caller(repo, remote: str = "origin") -> bool:
|
|
160
|
+
"""True when this process runs on behalf of the current holder (its token is in our environment)."""
|
|
161
|
+
tok = os.environ.get(TOKEN_ENV)
|
|
162
|
+
return bool(tok) and _holder(lock_dir() / f"{repo_key(repo, remote)}.lock").get("token") == tok
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def hand_to_process(lock: Lock, pid: int, max_min: float = 10) -> None:
|
|
166
|
+
"""Keep the flock until `pid` (the `git push` that runs our hook) exits, then let it go: a detached child
|
|
167
|
+
inherits the lock's file descriptor and polls the pid; the caller's own copy is closed."""
|
|
168
|
+
if lock.fd is None:
|
|
169
|
+
return
|
|
170
|
+
lock.set_pid(pid)
|
|
171
|
+
code = ("import os,sys,time\n"
|
|
172
|
+
"fd,pid,end=int(sys.argv[1]),int(sys.argv[2]),time.monotonic()+float(sys.argv[3])*60\n"
|
|
173
|
+
"while time.monotonic()<end:\n"
|
|
174
|
+
" try: os.kill(pid,0)\n"
|
|
175
|
+
" except OSError: break\n"
|
|
176
|
+
" time.sleep(0.5)\n"
|
|
177
|
+
"os.ftruncate(fd,0); os.close(fd)\n")
|
|
178
|
+
subprocess.Popen([sys.executable, "-c", code, str(lock.fd), str(pid), str(max_min)], pass_fds=(lock.fd,),
|
|
179
|
+
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
180
|
+
start_new_session=True)
|
|
181
|
+
os.close(lock.fd)
|
|
182
|
+
lock.fd = None
|
ai_sync/layers.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""layers: the desk and the shelf. A layered target loads only the core topics; the rest are fetched on demand.
|
|
2
|
+
|
|
3
|
+
What: a [[target]] with `layer = "core"` gets the rules block with the topics named in `core_topics` in full and
|
|
4
|
+
every other topic folded to one line that says how to get it. The prompt hook (`aisync hook`) injects a
|
|
5
|
+
folded topic the first time a prompt or a tool call in that session touches one of its keywords.
|
|
6
|
+
Why: 2026-11-08: the always-loaded rules were 20,673 tokens, two thirds of it about one area at a time
|
|
7
|
+
(deploys, docs, posts, scheduled jobs); a long block also dilutes attention on the rules that matter.
|
|
8
|
+
How: `core_topics` and `[shelf]` (topic prefix -> keywords) live in config.toml. A folded copy that someone
|
|
9
|
+
edits is merged back with the truth's folded sections first, so adopting the edit never deletes rules.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
|
|
15
|
+
from . import core
|
|
16
|
+
|
|
17
|
+
FOLD = "_Shelved: {n} rules, injected when your work touches {kw}. Read them now: `aisync rule list --topic \"{topic}\"`._"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def sections(block: str) -> tuple[list[str], list[tuple[str, list[str]]], list[str]]:
|
|
21
|
+
"""(head lines, [(### heading, body lines)], tail lines) of a rules block."""
|
|
22
|
+
lines = block.split("\n")
|
|
23
|
+
head, secs, tail = [], [], []
|
|
24
|
+
cur = None
|
|
25
|
+
for l in lines:
|
|
26
|
+
if l.startswith(core.BLOCK_END):
|
|
27
|
+
tail.append(l)
|
|
28
|
+
cur = None
|
|
29
|
+
continue
|
|
30
|
+
if tail:
|
|
31
|
+
tail.append(l)
|
|
32
|
+
elif l.startswith("### "):
|
|
33
|
+
cur = (l, [])
|
|
34
|
+
secs.append(cur)
|
|
35
|
+
elif cur is None:
|
|
36
|
+
head.append(l)
|
|
37
|
+
else:
|
|
38
|
+
cur[1].append(l)
|
|
39
|
+
return head, secs, tail
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def topic(heading: str) -> str:
|
|
43
|
+
return heading[4:].strip()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def is_core(name: str, core_topics: list[str]) -> bool:
|
|
47
|
+
return any(name.startswith(c) for c in core_topics)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def keywords(name: str, shelf: dict[str, list[str]]) -> list[str]:
|
|
51
|
+
"""Configured keywords for a topic, else the words of its heading (split on punctuation)."""
|
|
52
|
+
for prefix, kws in shelf.items():
|
|
53
|
+
if name.startswith(prefix):
|
|
54
|
+
return [k for k in kws if k]
|
|
55
|
+
return [w for w in re.split(r"[\s、,,()()/与和]+", name) if len(w) >= 2]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def core_view(truth: str, core_topics: list[str], shelf: dict[str, list[str]]) -> str:
|
|
59
|
+
"""The block a layered target carries: core topics in full, every other topic folded to one line."""
|
|
60
|
+
head, secs, tail = sections(truth)
|
|
61
|
+
out = list(head)
|
|
62
|
+
for h, body in secs:
|
|
63
|
+
name = topic(h)
|
|
64
|
+
out.append(h)
|
|
65
|
+
if is_core(name, core_topics):
|
|
66
|
+
out += body
|
|
67
|
+
else:
|
|
68
|
+
n = sum(1 for l in body if l.startswith("- "))
|
|
69
|
+
kw = ", ".join(keywords(name, shelf)[:8]) or name
|
|
70
|
+
out += [FOLD.format(n=n, kw=kw, topic=name.split("(")[0]), ""]
|
|
71
|
+
return "\n".join(out + tail)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def merge_back(copy: str, truth: str, core_topics: list[str]) -> str:
|
|
75
|
+
"""An edited layered copy as a full block: its own core sections, the truth's folded ones."""
|
|
76
|
+
_, tsecs, _ = sections(truth)
|
|
77
|
+
full = {topic(h): body for h, body in tsecs}
|
|
78
|
+
head, secs, tail = sections(copy)
|
|
79
|
+
out = list(head)
|
|
80
|
+
for h, body in secs:
|
|
81
|
+
name = topic(h)
|
|
82
|
+
out.append(h)
|
|
83
|
+
out += body if is_core(name, core_topics) else full.get(name, body)
|
|
84
|
+
return "\n".join(out + tail)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def topic_rules(truth: str, prefix: str) -> list[str]:
|
|
88
|
+
"""The rule lines of the topics whose heading starts with prefix."""
|
|
89
|
+
_, secs, _ = sections(truth)
|
|
90
|
+
return [l for h, body in secs if topic(h).startswith(prefix) for l in body if l.startswith("- ")]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def matches(text: str, truth: str, core_topics: list[str], shelf: dict[str, list[str]]) -> list[str]:
|
|
94
|
+
"""Folded topics whose keywords appear in text (case-insensitive), in block order."""
|
|
95
|
+
low = (text or "").lower()
|
|
96
|
+
if not low:
|
|
97
|
+
return []
|
|
98
|
+
_, secs, _ = sections(truth)
|
|
99
|
+
hit = []
|
|
100
|
+
for h, _ in secs:
|
|
101
|
+
name = topic(h)
|
|
102
|
+
if is_core(name, core_topics):
|
|
103
|
+
continue
|
|
104
|
+
if any(_has(low, k.lower()) for k in keywords(name, shelf)):
|
|
105
|
+
hit.append(name)
|
|
106
|
+
return hit
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _has(low: str, kw: str) -> bool:
|
|
110
|
+
"""ASCII keywords match whole words ('pr' is not in 'prompt'); others (Chinese) match as substrings."""
|
|
111
|
+
if kw.isascii() and re.match(r"^[a-z0-9]", kw):
|
|
112
|
+
return re.search(r"(?<![a-z0-9])" + re.escape(kw) + r"(?![a-z0-9])", low) is not None
|
|
113
|
+
return kw in low
|
ai_sync/mcp_server.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""mcp_server: ai-sync as an MCP server, so any agent that speaks MCP can use the hub without hooks or file edits.
|
|
2
|
+
|
|
3
|
+
What: `aisync mcp` serves eight tools over stdio: rules, rule_add, log, claim, release, news, status, tidy.
|
|
4
|
+
Why: owner 2026-11-08: any AI agent should be able to use ai-sync at a glance, not only the tools we wrote
|
|
5
|
+
adapters for. The three universal doors are AGENTS.md (a [[target]] file), the CLI, and this server.
|
|
6
|
+
How: the tool functions below are plain Python over collab/core (tested without MCP installed); build() wraps
|
|
7
|
+
them with the official SDK's MCPServer (`pip install 'aisync-cli[mcp]'`, mcp>=2.3). Nothing here prints to
|
|
8
|
+
stdout outside the protocol.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from . import collab, core
|
|
13
|
+
|
|
14
|
+
INSTRUCTIONS = (
|
|
15
|
+
"ai-sync: shared rules, a hash-chained journal and file claims for every AI agent on this machine. "
|
|
16
|
+
"Start with `rules` (core rules; pass a topic to read a folded one) and `news`. Before editing files other agents "
|
|
17
|
+
"may touch, `claim` them (overlaps come back so you can stop); `release` when done. After each unit of work, "
|
|
18
|
+
"`log` one line. When the owner states a rule for all AIs, `rule_add` it as When/Do/Not."
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _cfg() -> core.Config:
|
|
23
|
+
return core.load_config()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def rules(topic: str = "") -> str:
|
|
27
|
+
"""The shared rules: the core layer (or all rules when nothing is layered); with topic, that topic's rules."""
|
|
28
|
+
from . import layers
|
|
29
|
+
cfg = _cfg()
|
|
30
|
+
truth = core.extract_block((cfg.root / "preferences.md").read_text()) or ""
|
|
31
|
+
if topic:
|
|
32
|
+
found = layers.topic_rules(truth, topic)
|
|
33
|
+
return "\n".join(found) if found else f"no topic starts with {topic!r}"
|
|
34
|
+
if cfg.core_topics:
|
|
35
|
+
return layers.core_view(core.strip_superseded(truth), cfg.core_topics, cfg.shelf)
|
|
36
|
+
return core.strip_superseded(truth)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def rule_add(agent: str, when: str, do: str, topic: str, reason: str, not_: str = "", project: str = "",
|
|
40
|
+
enforced_by: str = "", judgment_only: str = "", replaces: str = "", planned: str = "",
|
|
41
|
+
size: str = "") -> str:
|
|
42
|
+
"""Add a shared rule in the When/Do/Not shape. Needs enforced_by (paths), judgment_only (why no code can), or
|
|
43
|
+
planned (the check to write) with size S, M or L."""
|
|
44
|
+
from . import rulespec
|
|
45
|
+
try:
|
|
46
|
+
rep = collab.rule_add(_cfg(), agent=agent, text=rulespec.compose(when, do, not_), reason=reason,
|
|
47
|
+
project=project, topic=topic, replaces=replaces, enforced_by=enforced_by,
|
|
48
|
+
judgment_only=judgment_only, planned=planned, size=size)
|
|
49
|
+
except ValueError as ex:
|
|
50
|
+
return f"refused: {ex}"
|
|
51
|
+
return f"added {rep['id']}: {rep['rule']}" if rep["added"] else "an equal rule already exists; nothing changed"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def log(agent: str, project: str, summary: str, kind: str = "dev_log", files: str = "") -> str:
|
|
55
|
+
"""Append one event to the journal (kinds: dev_log, decision, blocked, unblocked, rule_change, note)."""
|
|
56
|
+
try:
|
|
57
|
+
ev = core.append_event(_cfg(), agent=agent, kind=kind, project=project, summary=summary,
|
|
58
|
+
files=[f.strip() for f in files.split(",") if f.strip()])
|
|
59
|
+
except ValueError as ex:
|
|
60
|
+
return f"refused: {ex}"
|
|
61
|
+
return f"logged {ev['id']}"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def claim(agent: str, project: str, summary: str, files: str = "") -> str:
|
|
65
|
+
"""Claim files (comma-separated; empty = whole repo) before editing. Overlaps with other agents come back."""
|
|
66
|
+
try:
|
|
67
|
+
rep = collab.claim(_cfg(), agent=agent, project=project, summary=summary,
|
|
68
|
+
files=[f.strip() for f in files.split(",") if f.strip()])
|
|
69
|
+
except ValueError as ex:
|
|
70
|
+
return f"refused: {ex}"
|
|
71
|
+
c = rep["claim"]
|
|
72
|
+
msg = f"claimed {project} {c['files'] or '[whole repo]'} until {c['expires'][11:16]}"
|
|
73
|
+
if rep["overlaps"]:
|
|
74
|
+
msg += "; OVERLAP with " + ", ".join(f"{o['agent']} ({o['summary']})" for o in rep["overlaps"]) + ": coordinate or pick other work"
|
|
75
|
+
return msg
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def release(agent: str, project: str = "") -> str:
|
|
79
|
+
"""Release your claims (all of them, or one project's)."""
|
|
80
|
+
gone = collab.release(_cfg(), agent=agent, project=project)
|
|
81
|
+
return f"released {len(gone)} claim(s)"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def news(agent: str, session: str = "mcp") -> str:
|
|
85
|
+
"""What other agents did and which rules changed since this session last asked ('' = nothing new)."""
|
|
86
|
+
from . import hooks
|
|
87
|
+
rep = hooks.news(_cfg(), agent, session)
|
|
88
|
+
if rep["first"]:
|
|
89
|
+
return "cursor set; ask again later for news (call status for the current picture)"
|
|
90
|
+
return hooks.news_text(rep) or "nothing new"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def status() -> str:
|
|
94
|
+
"""Live progress: who is doing what, claims, open blockers, latest events."""
|
|
95
|
+
cfg = _cfg()
|
|
96
|
+
prog = core.progress_now(cfg)
|
|
97
|
+
if prog:
|
|
98
|
+
return prog
|
|
99
|
+
cur = core.build_current(core.read_events(cfg))
|
|
100
|
+
return collab.progress_text(cfg, cur, collab.load_claims(cfg), collab.report(cfg)["hints"])
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def tidy() -> str:
|
|
104
|
+
"""The rules clerk's proposals (duplicates, rules not cited lately, core budget, gaps). Proposals only."""
|
|
105
|
+
from datetime import datetime
|
|
106
|
+
from . import tidy as t
|
|
107
|
+
cfg = _cfg()
|
|
108
|
+
return t.render(t.report(cfg), f"{datetime.now().astimezone():%Y-%m-%d}")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
TOOLS = (rules, rule_add, log, claim, release, news, status, tidy)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def build():
|
|
115
|
+
"""The MCPServer with every tool registered (needs `pip install 'aisync-cli[mcp]'`)."""
|
|
116
|
+
try:
|
|
117
|
+
from mcp.server.mcpserver import MCPServer
|
|
118
|
+
except ImportError as ex: # mcp missing or a 1.x install
|
|
119
|
+
raise RuntimeError("the MCP server needs the official SDK: pip install 'aisync-cli[mcp]' (mcp>=2.3)") from ex
|
|
120
|
+
server = MCPServer("aisync", instructions=INSTRUCTIONS)
|
|
121
|
+
for fn in TOOLS:
|
|
122
|
+
server.tool(name=fn.__name__.rstrip("_"), description=fn.__doc__)(fn)
|
|
123
|
+
return server
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main() -> int:
|
|
127
|
+
try:
|
|
128
|
+
server = build()
|
|
129
|
+
except RuntimeError as ex:
|
|
130
|
+
import sys
|
|
131
|
+
print(f"error: {ex}", file=sys.stderr)
|
|
132
|
+
return 2
|
|
133
|
+
server.run("stdio")
|
|
134
|
+
return 0
|
ai_sync/nonvacuous.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Non-vacuous checkers: a checker that checked nothing must fail, never pass.
|
|
2
|
+
|
|
3
|
+
Once a sync checker read retired rules from a section that had just moved into rules-archive.md, found 0
|
|
4
|
+
and said ok. `aisync rulecheck` and `aisync status` now count what they compared and call guard(), which returns
|
|
5
|
+
problems when a count is 0, or fell by more than half since the last recorded run. A deliberate drop is accepted once
|
|
6
|
+
with a reason that is logged (`--accept-drop "<reason>"`, or `python3 -m ai_sync.nonvacuous accept <checker> --reason R`).
|
|
7
|
+
A zero is never accepted.
|
|
8
|
+
|
|
9
|
+
State: <hub>/state/checker_counts.json and checker_drops.jsonl (the hub's state/ is git-ignored);
|
|
10
|
+
AISYNC_CHECK_COUNTS points the counts file elsewhere.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import datetime as dt
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
def state_file(home: Path | None = None) -> Path:
|
|
22
|
+
if os.environ.get("AISYNC_CHECK_COUNTS"):
|
|
23
|
+
return Path(os.environ["AISYNC_CHECK_COUNTS"])
|
|
24
|
+
home = home or Path(os.environ.get("AISYNC_HOME", "~/.ai-sync")).expanduser()
|
|
25
|
+
return home / "state" / "checker_counts.json"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _load(path: Path) -> dict:
|
|
29
|
+
try:
|
|
30
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
31
|
+
return data if isinstance(data, dict) else {}
|
|
32
|
+
except (OSError, ValueError):
|
|
33
|
+
return {}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _save(path: Path, data: dict) -> None:
|
|
37
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
tmp = path.with_name(path.name + ".tmp") # temp + rename: a crash never leaves half a file
|
|
39
|
+
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1, sort_keys=True), encoding="utf-8")
|
|
40
|
+
tmp.replace(path)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _now() -> str:
|
|
44
|
+
return dt.datetime.now().astimezone().isoformat(timespec="seconds")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def summary(counts: dict[str, int]) -> str:
|
|
48
|
+
"""One line for the checker to print, e.g. checked: rules 120, archive 14."""
|
|
49
|
+
return "checked: " + ", ".join(f"{k} {v}" for k, v in counts.items())
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def guard(checker: str, counts: dict[str, int], accept_drop: str | None = None, state: Path | None = None) -> list[str]:
|
|
53
|
+
"""Problems (one per bad count). Good counts are remembered; a refused drop keeps the old baseline,
|
|
54
|
+
so the checker keeps failing until the drop is fixed or accepted."""
|
|
55
|
+
path = state or state_file()
|
|
56
|
+
data = _load(path)
|
|
57
|
+
last = data.get("counts", {}).get(checker, {})
|
|
58
|
+
pending = data.get("accept", {}).get(checker)
|
|
59
|
+
reason = accept_drop or (pending or {}).get("reason")
|
|
60
|
+
probs, drops = [], []
|
|
61
|
+
for name, n in counts.items():
|
|
62
|
+
if n <= 0:
|
|
63
|
+
probs.append(f"{checker}: {name} checked nothing (0), so the check proved nothing; what it checks may have moved or be read from the wrong place")
|
|
64
|
+
continue
|
|
65
|
+
before = last.get(name)
|
|
66
|
+
if isinstance(before, int) and n * 2 < before:
|
|
67
|
+
drops.append((name, before, n))
|
|
68
|
+
for name, before, n in drops:
|
|
69
|
+
if not reason:
|
|
70
|
+
probs.append(f"{checker}: {name} checked only {n}, last time {before}: more than half fewer; "
|
|
71
|
+
f"if that is on purpose pass --accept-drop \"why\", or run python3 -m ai_sync.nonvacuous accept {checker} --reason \"why\"")
|
|
72
|
+
if probs:
|
|
73
|
+
return probs
|
|
74
|
+
if drops:
|
|
75
|
+
with path.with_name("checker_drops.jsonl").open("a", encoding="utf-8") as f:
|
|
76
|
+
for name, before, n in drops:
|
|
77
|
+
f.write(json.dumps({"ts": _now(), "checker": checker, "count": name, "from": before, "to": n,
|
|
78
|
+
"reason": reason}, ensure_ascii=False) + "\n")
|
|
79
|
+
data.setdefault("counts", {})[checker] = {**{k: v for k, v in last.items() if k not in counts and k != "_at"},
|
|
80
|
+
**counts, "_at": _now()}
|
|
81
|
+
if pending:
|
|
82
|
+
data["accept"].pop(checker, None)
|
|
83
|
+
_save(path, data)
|
|
84
|
+
return []
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def main(argv: list[str] | None = None) -> int:
|
|
88
|
+
ap = argparse.ArgumentParser(description="Non-vacuous checker counts.")
|
|
89
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
90
|
+
sub.add_parser("show")
|
|
91
|
+
acc = sub.add_parser("accept", help="accept the next drop of one checker, with a reason")
|
|
92
|
+
acc.add_argument("checker")
|
|
93
|
+
acc.add_argument("--reason", required=True)
|
|
94
|
+
a = ap.parse_args(argv)
|
|
95
|
+
path = state_file()
|
|
96
|
+
data = _load(path)
|
|
97
|
+
if a.cmd == "show":
|
|
98
|
+
print(json.dumps(data, ensure_ascii=False, indent=1, sort_keys=True))
|
|
99
|
+
return 0
|
|
100
|
+
if not a.reason.strip():
|
|
101
|
+
print("the reason must not be empty")
|
|
102
|
+
return 2
|
|
103
|
+
data.setdefault("accept", {})[a.checker] = {"reason": a.reason.strip(), "ts": _now()}
|
|
104
|
+
_save(path, data)
|
|
105
|
+
print(f"{a.checker}: the next drop is accepted (reason: {a.reason.strip()}) and logged in {path.with_name('checker_drops.jsonl')}")
|
|
106
|
+
return 0
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
if __name__ == "__main__":
|
|
110
|
+
sys.exit(main())
|