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/collab.py
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
"""aisync collaboration layer: shared rules any agent can update, claims, progress fan-out, report.
|
|
2
|
+
|
|
3
|
+
What: the pieces that make the hub the one core every agent follows.
|
|
4
|
+
- rule_add: any agent (Claude Code, Codex, Cursor, ...) adds a shared rule with one command; it
|
|
5
|
+
lands in preferences.md (the truth) and the next cycle copies it to every tool.
|
|
6
|
+
- harvest_rules: new timestamped entries in the "## Meta rule" section of the AGENTS.md of each
|
|
7
|
+
repo listed in `rule_sources` are imported automatically, so a rule an agent wrote there (and
|
|
8
|
+
forgot to `aisync rule add`) still reaches every tool.
|
|
9
|
+
- claims: "I am working on these files of this repo now", with a TTL; overlaps warn.
|
|
10
|
+
- render_progress: the rules pointer + live progress written into files each tool auto-loads
|
|
11
|
+
(e.g. a block in ~/.codex/AGENTS.md), so an agent sees it without being told to look.
|
|
12
|
+
- report: read-only self-check (unattributed commits, silent tools, missing projects, stale
|
|
13
|
+
blockers, failures). It only reports; it never changes a rule by itself.
|
|
14
|
+
Why: one shared rule set that any agent can update and every agent obeys.
|
|
15
|
+
How: every function here is called from core.run_cycle (isolated steps) or from the CLI.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from datetime import datetime, timedelta
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from . import core, ruleids
|
|
24
|
+
|
|
25
|
+
RULES_HEAD = "### Rules added by agents (via aisync, newest last)"
|
|
26
|
+
META_HEAD = "## Meta rule"
|
|
27
|
+
_ENTRY = re.compile(r"^- (\d{4}-\d{2}-\d{2} \d{2}:\d{2} [A-Z]{2,5}):\s*(.*)$")
|
|
28
|
+
CLAIM_TTL_MIN = 120
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _norm(text: str) -> str:
|
|
32
|
+
return re.sub(r"[^a-z0-9\u4e00-\u9fff]+", "", text.lower())
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _stamp() -> str:
|
|
36
|
+
return datetime.now().astimezone().strftime("%Y-%m-%d %H:%M %Z")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _tilde(p: Path | str) -> str:
|
|
40
|
+
return str(p).replace(str(Path.home()), "~", 1)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# ───────────────────────────── shared rules ─────────────────────────────
|
|
44
|
+
|
|
45
|
+
def rule_lines(block: str) -> list[str]:
|
|
46
|
+
return [l for l in block.splitlines() if l.startswith("- ")]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _insert_rule(cfg: core.Config, bullet: str, key_text: str) -> str:
|
|
50
|
+
"""Append one bullet, with the next free ID, inside the owner-preferences block.
|
|
51
|
+
Returns the bullet as written, or "" if an equal rule exists."""
|
|
52
|
+
path = cfg.root / "preferences.md"
|
|
53
|
+
text = path.read_text()
|
|
54
|
+
block = core.extract_block(text)
|
|
55
|
+
if block is None:
|
|
56
|
+
raise ValueError("preferences.md has no owner-preferences block")
|
|
57
|
+
key = _norm(key_text)[:60]
|
|
58
|
+
if key and any(key in _norm(l) for l in rule_lines(block)):
|
|
59
|
+
return ""
|
|
60
|
+
bullet = ruleids.with_id(bullet, ruleids.next_id(cfg))
|
|
61
|
+
body = block[: -len(core.BLOCK_END)].rstrip("\n")
|
|
62
|
+
if RULES_HEAD not in body:
|
|
63
|
+
body += f"\n\n{RULES_HEAD}\n"
|
|
64
|
+
new_block = body + "\n" + bullet + "\n" + core.BLOCK_END
|
|
65
|
+
core.atomic_write(path, core.replace_block(text, new_block))
|
|
66
|
+
return bullet
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
SUPERSEDED_HEAD = "### 已取代"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def topics(block: str) -> list[str]:
|
|
73
|
+
"""Topic headings of a tidied rules block (### headings other than 已取代 and the legacy list)."""
|
|
74
|
+
return [l[4:].strip() for l in block.splitlines()
|
|
75
|
+
if l.startswith("### ") and l.strip() != SUPERSEDED_HEAD and l.strip() != RULES_HEAD]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _sentences(text: str) -> int:
|
|
79
|
+
"""Sentence ends are . ! ? followed by a space or the end, and 。!? anywhere. A dot inside a file name or date
|
|
80
|
+
(x.env, x_autopilot.py, 2026-10-27) and semicolons do not end a sentence (2026-10-27: three false rejections)."""
|
|
81
|
+
return len([x for x in re.split(r"(?<=[.!?])(?=\s|$)\s*|(?<=[。!?])\s*", text) if x.strip()])
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _insert_topic_rule(cfg: core.Config, topic: str, bullet: str, key_text: str, replaces: str, new_name: str) -> dict:
|
|
85
|
+
"""Put a rule at the top of its topic with the next free ID; the rule it replaces (given by ID like R-087,
|
|
86
|
+
or by a piece of its text) moves to rules-archive.md with its retired date and the new rule's ID."""
|
|
87
|
+
path = cfg.root / "preferences.md"
|
|
88
|
+
text = path.read_text()
|
|
89
|
+
block = core.extract_block(text)
|
|
90
|
+
if block is None:
|
|
91
|
+
raise ValueError("preferences.md has no owner-preferences block")
|
|
92
|
+
names = topics(block)
|
|
93
|
+
hit = [t for t in names if topic.lower() in t.lower()]
|
|
94
|
+
if len(hit) != 1:
|
|
95
|
+
raise ValueError(f"--topic must match exactly one topic; topics: {' | '.join(names)}")
|
|
96
|
+
lines = block.splitlines()
|
|
97
|
+
span = None
|
|
98
|
+
if replaces:
|
|
99
|
+
rid = ruleids.is_id(replaces)
|
|
100
|
+
cur = [i for i, l in enumerate(lines) if l.startswith("- ") and not _in_superseded(lines, i)
|
|
101
|
+
and (ruleids.bullet_id(l) == rid if rid else replaces in l)]
|
|
102
|
+
if len(cur) != 1:
|
|
103
|
+
what = f"rule {rid}" if rid else "current rule"
|
|
104
|
+
raise ValueError(f"--replaces must match exactly one {what} (matched {len(cur)})")
|
|
105
|
+
i = cur[0]
|
|
106
|
+
end = i + 1
|
|
107
|
+
while end < len(lines) and lines[end].startswith(" ") and lines[end].strip():
|
|
108
|
+
end += 1
|
|
109
|
+
span = (i, end)
|
|
110
|
+
# Duplicate check: only current rules count, minus the one being replaced. A revision usually
|
|
111
|
+
# keeps the old rule's opening words, and 已取代 lines are history, not rules.
|
|
112
|
+
key = _norm(key_text)[:60]
|
|
113
|
+
live = [l for k, l in enumerate(lines) if l.startswith("- ") and not _in_superseded(lines, k)
|
|
114
|
+
and not (span and span[0] <= k < span[1])]
|
|
115
|
+
if key and any(key in _norm(l) for l in live):
|
|
116
|
+
return {"added": False, "moved": None}
|
|
117
|
+
new_id = ruleids.next_id(cfg)
|
|
118
|
+
bullet = ruleids.with_id(bullet, new_id)
|
|
119
|
+
moved = None
|
|
120
|
+
if span:
|
|
121
|
+
i, end = span
|
|
122
|
+
old = " ".join(x.strip() for x in lines[i:end])
|
|
123
|
+
if not ruleids.bullet_id(old): # a rule written before IDs existed gets one on the way out
|
|
124
|
+
old = ruleids.with_id(old, ruleids.next_id(cfg))
|
|
125
|
+
day = f"{datetime.now().astimezone():%Y-%m-%d}"
|
|
126
|
+
moved = ruleids.archive_line(old, day, new_id, note=f" 被 {new_id}「{new_name}」取代({day})")
|
|
127
|
+
del lines[i:end]
|
|
128
|
+
h = lines.index(f"### {hit[0]}")
|
|
129
|
+
lines.insert(h + 1, bullet)
|
|
130
|
+
if moved:
|
|
131
|
+
ruleids.archive_add(cfg, [moved]) # history first: a crash in between never loses the old text
|
|
132
|
+
core.atomic_write(path, core.replace_block(text, "\n".join(lines)))
|
|
133
|
+
return {"added": True, "moved": moved, "id": new_id, "bullet": bullet}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _in_superseded(lines: list[str], i: int) -> bool:
|
|
137
|
+
for l in reversed(lines[:i]):
|
|
138
|
+
if l.startswith("### "):
|
|
139
|
+
return l.strip() == SUPERSEDED_HEAD
|
|
140
|
+
return False
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def rule_add(cfg: core.Config, *, agent: str, text: str, reason: str = "", project: str = "",
|
|
144
|
+
topic: str = "", replaces: str = "", enforced_by: str = "", judgment_only: str = "",
|
|
145
|
+
planned: str = "", size: str = "") -> dict:
|
|
146
|
+
"""Add a shared rule.
|
|
147
|
+
|
|
148
|
+
Once preferences.md is grouped into topics, the writing standard applies:
|
|
149
|
+
pick a topic, write only the current rule in at most three sentences, end with the source tag,
|
|
150
|
+
and move the rule it replaces (by ID or text) into rules-archive.md in the same write. Every new rule
|
|
151
|
+
gets the next free ID. The reason goes to the journal only.
|
|
152
|
+
Before the tidy (no topic headings) it appends to the legacy list as before.
|
|
153
|
+
A new rule may name what enforces it (enforced_by paths, a judgment_only reason, or the planned check that is
|
|
154
|
+
not written yet; one of them is required with `require_enforcer = true`); it is written to
|
|
155
|
+
rules-enforcement.toml under the new ID, never into the rules block.
|
|
156
|
+
"""
|
|
157
|
+
from . import enforcement
|
|
158
|
+
agent, text = (agent or "").strip(), " ".join((text or "").split())
|
|
159
|
+
if not agent:
|
|
160
|
+
raise ValueError("agent is required (pass --agent or set AISYNC_AGENT)")
|
|
161
|
+
if len(text) < 8:
|
|
162
|
+
raise ValueError("rule text is too short")
|
|
163
|
+
entry = (enforcement.check_args(enforced_by, judgment_only, planned, size)
|
|
164
|
+
if cfg.require_enforcer or enforced_by or judgment_only or planned else None) # optional unless require_enforcer
|
|
165
|
+
old_id = ruleids.is_id(replaces) if replaces else None
|
|
166
|
+
old_plan = enforcement.load(cfg).get(old_id, {}) if old_id else {}
|
|
167
|
+
if old_plan.get("planned") and (entry or {}).get("judgment_only"): # a replacement must not drop a planned check
|
|
168
|
+
raise ValueError(f"{old_id} has a planned check ({str(old_plan['planned'])[:80]}); the rule that replaces it "
|
|
169
|
+
"keeps it: pass --planned \"<the check>\" --size S|M|L, or --enforced-by <path>")
|
|
170
|
+
if (old_plan.get("planned") and (entry or {}).get("planned") # nor postpone it: a larger size moves the due day
|
|
171
|
+
and enforcement.SIZES[entry["size"]] > enforcement.SIZES.get(str(old_plan.get("size", "")), 0)):
|
|
172
|
+
raise ValueError(f"{old_id} is planned {old_plan.get('size', '?')} since {old_plan.get('since', '?')}; a rule that "
|
|
173
|
+
f"replaces it keeps that size (pass --size {old_plan.get('size', 'S')}). To move the due day "
|
|
174
|
+
"afterwards: aisync rule enforce <new id> --planned \"<the check>\" --size <larger> --reason \"<why>\"")
|
|
175
|
+
who = agent + (f", {project}" if project else "")
|
|
176
|
+
block = core.extract_block((cfg.root / "preferences.md").read_text()) or ""
|
|
177
|
+
if topics(block):
|
|
178
|
+
if not topic:
|
|
179
|
+
raise ValueError(f"--topic is required; topics: {' | '.join(topics(block))}")
|
|
180
|
+
if _sentences(text) > 3 and not cfg.rule_spec:
|
|
181
|
+
raise ValueError("a rule is at most three sentences; put the why in --reason")
|
|
182
|
+
if cfg.rule_spec:
|
|
183
|
+
from . import rulespec
|
|
184
|
+
bad = rulespec.problems(text, need_id=False, need_tag=False)
|
|
185
|
+
if bad:
|
|
186
|
+
raise ValueError("rule is not an interface (" + "; ".join(bad) + "); write "
|
|
187
|
+
"'When: <trigger>. Do: <action>. Not: <forbidden>.' or pass --when/--do/--not")
|
|
188
|
+
bullet = f"- {text.rstrip()} ({datetime.now().astimezone():%Y-%m-%d} · {who})"
|
|
189
|
+
with core.locked(cfg):
|
|
190
|
+
rep = _insert_topic_rule(cfg, topic, bullet, text, replaces, text[:30])
|
|
191
|
+
added = rep["added"]
|
|
192
|
+
bullet = rep.get("bullet", bullet)
|
|
193
|
+
else:
|
|
194
|
+
bullet = f"- {_stamp()} ({who}): {text}" + (f" Reason: {' '.join(reason.split())}" if reason.strip() else "")
|
|
195
|
+
with core.locked(cfg):
|
|
196
|
+
written = _insert_rule(cfg, bullet, text)
|
|
197
|
+
added, bullet, rep = bool(written), written or bullet, {"moved": None}
|
|
198
|
+
if added and entry is not None:
|
|
199
|
+
with core.locked(cfg):
|
|
200
|
+
moved_id = ruleids.bullet_id(rep["moved"]) if rep.get("moved") else None
|
|
201
|
+
was = enforcement.load(cfg).get(moved_id, {}) if moved_id else {}
|
|
202
|
+
if was.get("planned") and entry.get("planned"): # the clock of a replaced rule keeps running
|
|
203
|
+
entry["since"] = min(str(entry["since"]), str(was.get("since") or entry["since"]))
|
|
204
|
+
if enforcement.SIZES[entry["size"]] > enforcement.SIZES.get(str(was.get("size", "")), 1 << 30):
|
|
205
|
+
entry["size"] = was["size"] # replaced by a piece of its text: the size cannot grow here
|
|
206
|
+
elif was.get("planned") and entry.get("judgment_only"): # replaced by a piece of its text: leave a trace
|
|
207
|
+
entry["note"] = (f"replaces {moved_id}, which had a planned check "
|
|
208
|
+
f"({was.get('size', '?')}, since {was.get('since', '?')}): {was['planned']}")
|
|
209
|
+
enforcement.put(cfg, ruleids.bullet_id(bullet), entry)
|
|
210
|
+
if added:
|
|
211
|
+
why = f" Reason: {' '.join(reason.split())}" if reason.strip() and topics(block) else ""
|
|
212
|
+
core.append_event(cfg, agent=agent, kind="rule_change", project=project,
|
|
213
|
+
summary=f"shared rule added: [{ruleids.bullet_id(bullet)}] {text}{why}"
|
|
214
|
+
+ (f" (replaces [{ruleids.bullet_id(rep['moved'])}])" if rep.get("moved") else ""),
|
|
215
|
+
files=["preferences.md"] + ([ruleids.ARCHIVE] if rep.get("moved") else []))
|
|
216
|
+
return {"added": added, "rule": bullet, "moved": rep.get("moved"), "id": ruleids.bullet_id(bullet) if added else None}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def rule_list(cfg: core.Config, archived: bool = False) -> list[str]:
|
|
220
|
+
"""Current rules (each starts with its ID), or the retired ones from rules-archive.md."""
|
|
221
|
+
if archived:
|
|
222
|
+
return ruleids.archive_entries(cfg)
|
|
223
|
+
block = core.extract_block((cfg.root / "preferences.md").read_text()) or ""
|
|
224
|
+
return rule_lines(block)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
# ───────────────────────────── rules written in repo AGENTS.md ─────────────────────────────
|
|
228
|
+
|
|
229
|
+
def rule_source_files(cfg: core.Config) -> list[Path]:
|
|
230
|
+
"""AGENTS.md of every checkout/worktree of each rule-source repo (main checkout + *.wt-*)."""
|
|
231
|
+
out = []
|
|
232
|
+
for proj in core.project_list(cfg):
|
|
233
|
+
for repo in cfg.rule_sources:
|
|
234
|
+
if proj.name == repo or proj.name.startswith(repo + "."):
|
|
235
|
+
if (proj / "AGENTS.md").exists():
|
|
236
|
+
out.append(proj / "AGENTS.md")
|
|
237
|
+
return out
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def parse_meta_entries(text: str) -> list[tuple[str, str]]:
|
|
241
|
+
"""(timestamp, full text) for each `- YYYY-MM-DD HH:MM TZ: ...` bullet under '## Meta rule'."""
|
|
242
|
+
entries, inside, cur = [], False, None
|
|
243
|
+
for line in text.splitlines():
|
|
244
|
+
if line.startswith("## "):
|
|
245
|
+
inside = line.startswith(META_HEAD)
|
|
246
|
+
if cur:
|
|
247
|
+
entries.append(cur)
|
|
248
|
+
cur = None
|
|
249
|
+
continue
|
|
250
|
+
if not inside:
|
|
251
|
+
continue
|
|
252
|
+
m = _ENTRY.match(line)
|
|
253
|
+
if m:
|
|
254
|
+
if cur:
|
|
255
|
+
entries.append(cur)
|
|
256
|
+
cur = [m.group(1), m.group(2)]
|
|
257
|
+
elif cur and line.startswith(" ") and line.strip():
|
|
258
|
+
cur[1] += " " + line.strip()
|
|
259
|
+
elif cur and not line.strip():
|
|
260
|
+
entries.append(cur)
|
|
261
|
+
cur = None
|
|
262
|
+
if cur:
|
|
263
|
+
entries.append(cur)
|
|
264
|
+
return [(ts, " ".join(t.split())) for ts, t in entries]
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _first_sentence(text: str, n: int = 220) -> str:
|
|
268
|
+
m = re.match(r"(.+?[.;。])(\s|$)", text)
|
|
269
|
+
s = m.group(1) if m else text
|
|
270
|
+
return s if len(s) <= n else s[: n - 1] + "…"
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def harvest_rules(cfg: core.Config) -> dict:
|
|
274
|
+
"""Import NEW meta-rule entries. A repo seen for the first time only records what exists."""
|
|
275
|
+
st = core.load_json(cfg.state / "rule_sources.json", {"repos": [], "seen": []})
|
|
276
|
+
seen, repos = set(st["seen"]), set(st["repos"])
|
|
277
|
+
rep = {"files": 0, "imported": [], "errors": []}
|
|
278
|
+
first_sight = set()
|
|
279
|
+
for path in rule_source_files(cfg):
|
|
280
|
+
repo = path.parent.name.split(".")[0]
|
|
281
|
+
try:
|
|
282
|
+
entries = parse_meta_entries(path.read_text())
|
|
283
|
+
except OSError as ex:
|
|
284
|
+
rep["errors"].append(f"{path.parent.name}: {type(ex).__name__}")
|
|
285
|
+
continue
|
|
286
|
+
rep["files"] += 1
|
|
287
|
+
if repo not in repos:
|
|
288
|
+
first_sight.add(repo)
|
|
289
|
+
for ts, text in entries:
|
|
290
|
+
key = core._h(ts + _norm(text)[:40])
|
|
291
|
+
if key in seen:
|
|
292
|
+
continue
|
|
293
|
+
seen.add(key)
|
|
294
|
+
if repo in repos: # an entry that appeared after we started watching
|
|
295
|
+
summary = _first_sentence(text)
|
|
296
|
+
main = path.parent.parent / repo # worktrees come and go; point at the main checkout
|
|
297
|
+
src = main / "AGENTS.md" if (main / "AGENTS.md").exists() else path
|
|
298
|
+
bullet = f"- {ts} (from {repo} AGENTS.md): {summary} Full text: `{_tilde(src)}`."
|
|
299
|
+
with core.locked(cfg):
|
|
300
|
+
added = _insert_rule(cfg, bullet, summary)
|
|
301
|
+
if added: # imports are never blocked; they count as none until someone says
|
|
302
|
+
from . import enforcement
|
|
303
|
+
enforcement.put(cfg, ruleids.bullet_id(added),
|
|
304
|
+
{"none": f"imported from {repo} AGENTS.md without an enforcer"})
|
|
305
|
+
if added:
|
|
306
|
+
core.append_event(cfg, agent=f"repo:{repo}", kind="rule_change", project=repo,
|
|
307
|
+
summary=f"shared rule imported from {repo} AGENTS.md: {summary}",
|
|
308
|
+
files=["preferences.md"])
|
|
309
|
+
rep["imported"].append(summary)
|
|
310
|
+
repos |= first_sight
|
|
311
|
+
core.save_json(cfg.state / "rule_sources.json", {"repos": sorted(repos), "seen": sorted(seen)})
|
|
312
|
+
return rep
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
# ───────────────────────────── claims (who is working where, now) ─────────────────────────────
|
|
316
|
+
|
|
317
|
+
def _now() -> datetime:
|
|
318
|
+
return datetime.now().astimezone()
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def load_claims(cfg: core.Config) -> list[dict]:
|
|
322
|
+
now = _now()
|
|
323
|
+
out = []
|
|
324
|
+
for c in core.load_json(cfg.state / "claims.json", []):
|
|
325
|
+
try:
|
|
326
|
+
if datetime.fromisoformat(c["expires"]) > now:
|
|
327
|
+
out.append(c)
|
|
328
|
+
except (KeyError, ValueError):
|
|
329
|
+
continue
|
|
330
|
+
return out
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _overlaps(a: dict, b: dict) -> bool:
|
|
334
|
+
if a["project"] != b["project"] or a["agent"] == b["agent"]:
|
|
335
|
+
return False
|
|
336
|
+
fa, fb = set(a.get("files") or []), set(b.get("files") or [])
|
|
337
|
+
if not fa or not fb: # a claim on the whole repo overlaps everything
|
|
338
|
+
return True
|
|
339
|
+
return bool(fa & fb) or any(x.rstrip("/") + "/" in y or y.rstrip("/") + "/" in x for x in fa for y in fb)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def find_overlaps(cfg: core.Config, agent: str, project: str, files) -> list[dict]:
|
|
343
|
+
probe = {"agent": agent, "project": project, "files": list(files or [])}
|
|
344
|
+
return [c for c in load_claims(cfg) if _overlaps(probe, c)]
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def claim(cfg: core.Config, *, agent: str, project: str, summary: str, files=(), ttl_min: int = CLAIM_TTL_MIN) -> dict:
|
|
348
|
+
if not (agent and project and summary):
|
|
349
|
+
raise ValueError("claim needs --agent, --project and --summary")
|
|
350
|
+
files = [str(f) for f in files]
|
|
351
|
+
with core.locked(cfg):
|
|
352
|
+
claims = [c for c in load_claims(cfg) if not (c["agent"] == agent and c["project"] == project)]
|
|
353
|
+
new = {"agent": agent, "project": project, "files": files, "summary": summary.strip(),
|
|
354
|
+
"since": core.now_iso(), "expires": (_now() + timedelta(minutes=ttl_min)).isoformat(timespec="seconds")}
|
|
355
|
+
overlaps = [c for c in claims if _overlaps(new, c)]
|
|
356
|
+
claims.append(new)
|
|
357
|
+
core.save_json(cfg.state / "claims.json", claims)
|
|
358
|
+
core.append_event(cfg, agent=agent, kind="claim", project=project, summary=f"claimed: {summary}", files=files,
|
|
359
|
+
refs={"overlap_with": ",".join(sorted({c['agent'] for c in overlaps}))} if overlaps else {})
|
|
360
|
+
return {"claim": new, "overlaps": overlaps}
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def release(cfg: core.Config, *, agent: str, project: str = "") -> list[dict]:
|
|
364
|
+
with core.locked(cfg):
|
|
365
|
+
claims = load_claims(cfg)
|
|
366
|
+
gone = [c for c in claims if c["agent"] == agent and (not project or c["project"] == project)]
|
|
367
|
+
core.save_json(cfg.state / "claims.json", [c for c in claims if c not in gone])
|
|
368
|
+
for c in gone:
|
|
369
|
+
core.append_event(cfg, agent=agent, kind="release", project=c["project"], summary=f"released: {c['summary']}")
|
|
370
|
+
return gone
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
# ───────────────────────────── self-check report (read-only) ─────────────────────────────
|
|
374
|
+
|
|
375
|
+
def report(cfg: core.Config, days: int = 7) -> dict:
|
|
376
|
+
"""Counts + plain hints. Never acts on them: too little data makes auto-tuning learn noise."""
|
|
377
|
+
since = _now() - timedelta(days=days)
|
|
378
|
+
events = []
|
|
379
|
+
for e in core.read_events(cfg):
|
|
380
|
+
try:
|
|
381
|
+
if datetime.fromisoformat(e["ts"]) >= since:
|
|
382
|
+
events.append(e)
|
|
383
|
+
except (KeyError, ValueError):
|
|
384
|
+
continue
|
|
385
|
+
per_agent, unattributed, no_project, commits_by = {}, {}, 0, {}
|
|
386
|
+
for e in events:
|
|
387
|
+
a = e.get("agent", "?")
|
|
388
|
+
per_agent.setdefault(a, {}).setdefault(e.get("kind", "?"), 0)
|
|
389
|
+
per_agent[a][e.get("kind", "?")] += 1
|
|
390
|
+
if e.get("kind") == "commit":
|
|
391
|
+
commits_by[a] = commits_by.get(a, 0) + 1
|
|
392
|
+
if a.startswith("git:"):
|
|
393
|
+
unattributed[a[4:]] = unattributed.get(a[4:], 0) + 1
|
|
394
|
+
elif not e.get("project") and not a.startswith("repo:"):
|
|
395
|
+
no_project += 1
|
|
396
|
+
runs = [r for r in core.read_runs(cfg, 500) if "steps" in r]
|
|
397
|
+
failed = sum(1 for r in runs if not r.get("ok"))
|
|
398
|
+
cur = core.build_current(core.read_events(cfg))
|
|
399
|
+
stale = [b for b in cur["open_blocked"] if b.get("ts") and datetime.fromisoformat(b["ts"]) < _now() - timedelta(hours=24)]
|
|
400
|
+
hints = []
|
|
401
|
+
for author, n in sorted(unattributed.items(), key=lambda kv: -kv[1]):
|
|
402
|
+
hints.append(f"{n} commit(s) by git author '{author}' name no tool: add an `Agent: <tool>` trailer to commits")
|
|
403
|
+
for tool in cfg.roster:
|
|
404
|
+
if tool not in per_agent:
|
|
405
|
+
hints.append(f"{tool} logged nothing in {days} days: it may not be reading {_tilde(cfg.root / 'agents.md')}")
|
|
406
|
+
elif per_agent[tool].get("commit") and not any(k for k in per_agent[tool] if k not in ("commit", "claim", "release")):
|
|
407
|
+
hints.append(f"{tool} committed but never ran `aisync log`")
|
|
408
|
+
if no_project:
|
|
409
|
+
hints.append(f"{no_project} event(s) without --project")
|
|
410
|
+
if stale:
|
|
411
|
+
hints.append(f"{len(stale)} blocker(s) open for more than 24 h")
|
|
412
|
+
if failed:
|
|
413
|
+
hints.append(f"{failed} of {len(runs)} sync cycles failed: see `aisync status`")
|
|
414
|
+
conf = core.load_json(cfg.state / "conflicts.json", {})
|
|
415
|
+
if conf:
|
|
416
|
+
hints.append(f"rule conflict open in {', '.join(conf)}: `aisync resolve`")
|
|
417
|
+
return {"days": days, "events": len(events), "per_agent": per_agent, "unattributed_commits": unattributed,
|
|
418
|
+
"events_without_project": no_project, "stale_blockers": len(stale), "cycles": len(runs),
|
|
419
|
+
"failed_cycles": failed, "open_conflicts": sorted(conf), "rules": len(rule_list(cfg)), "hints": hints}
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
# ───────────────────────────── progress fan-out to files tools auto-load ─────────────────────────────
|
|
423
|
+
|
|
424
|
+
def progress_text(cfg: core.Config, cur: dict, claims: list[dict], hints: list[str]) -> str:
|
|
425
|
+
lines = [core.PROG_START,
|
|
426
|
+
f"## Live progress of all AI tools (aisync, auto-generated {core.now_iso()}, do not edit)",
|
|
427
|
+
"",
|
|
428
|
+
f"Shared rules: `{_tilde(cfg.root / 'preferences.md')}` (every agent follows them; change one with "
|
|
429
|
+
f"`aisync rule add --agent <tool> \"...\"`). Full hub page: `{_tilde(cfg.root / 'agents.md')}`.", ""]
|
|
430
|
+
if claims:
|
|
431
|
+
lines.append("**Working right now** (do not edit these files without coordinating)")
|
|
432
|
+
lines += [f"- {c['agent']} @ {c['project']}: {core._short(c['summary'], 90)}"
|
|
433
|
+
f"{' [' + ', '.join(c['files'][:6]) + ']' if c['files'] else ' [whole repo]'} until {c['expires'][11:16]}"
|
|
434
|
+
for c in claims]
|
|
435
|
+
lines.append("")
|
|
436
|
+
lines.append("**Last seen per agent**")
|
|
437
|
+
for a, e in sorted(cur["agents"].items(), key=lambda kv: kv[1]["ts"] or "", reverse=True)[:8]:
|
|
438
|
+
lines.append(f"- {a} {e['ts']} · {e['project'] or '-'}: {core._short(e['summary'], 100)}")
|
|
439
|
+
lines += ["", "**Latest**"] + [f"- {e['ts']} · {e['agent']} · {e['kind']} · {e['project'] or '-'}: {core._short(e['summary'], 100)}"
|
|
440
|
+
for e in reversed(cur["tail"][-6:])]
|
|
441
|
+
if hints:
|
|
442
|
+
lines += ["", "**Hints from the self-check** (`aisync report`)"] + [f"- {h}" for h in hints[:4]]
|
|
443
|
+
lines.append(core.PROG_END)
|
|
444
|
+
return "\n".join(lines)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _body(section: str) -> list[str]:
|
|
448
|
+
"""Section minus its timestamped header line, for change detection."""
|
|
449
|
+
return [l for l in section.splitlines() if "auto-generated" not in l]
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def render_progress(cfg: core.Config) -> dict:
|
|
453
|
+
cur = core.build_current(core.read_events(cfg))
|
|
454
|
+
section = progress_text(cfg, cur, load_claims(cfg), report(cfg)["hints"])
|
|
455
|
+
rep = {"updated": [], "errors": []}
|
|
456
|
+
for t in cfg.progress_targets:
|
|
457
|
+
try:
|
|
458
|
+
if t.mode == "file":
|
|
459
|
+
old = t.path.read_text() if t.path.exists() else ""
|
|
460
|
+
if _body(old) != _body(section + "\n"):
|
|
461
|
+
core.atomic_write(t.path, section + "\n")
|
|
462
|
+
rep["updated"].append(t.label)
|
|
463
|
+
continue
|
|
464
|
+
text = t.path.read_text()
|
|
465
|
+
s, e = text.find(core.PROG_START), text.find(core.PROG_END)
|
|
466
|
+
if s < 0 or e < 0:
|
|
467
|
+
new = text.rstrip("\n") + "\n\n" + section + "\n"
|
|
468
|
+
else:
|
|
469
|
+
if _body(text[s:e + len(core.PROG_END)]) == _body(section):
|
|
470
|
+
continue
|
|
471
|
+
new = text[:s] + section + text[e + len(core.PROG_END):]
|
|
472
|
+
core.atomic_write(t.path, new)
|
|
473
|
+
rep["updated"].append(t.label)
|
|
474
|
+
except OSError as ex:
|
|
475
|
+
rep["errors"].append(f"{t.label}: {type(ex).__name__}") # one bad target never blocks the rest
|
|
476
|
+
return rep
|