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/rulecheck.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""rulecheck: prove a tidy of the shared rules lost no hard fact.
|
|
2
|
+
|
|
3
|
+
A tidy may regroup, merge and shorten rules, but every hard fact of every old rule
|
|
4
|
+
(path, command, number with a unit, clock time, E/T/KPI-AMD id, URL, quoted words)
|
|
5
|
+
must still be in the current rules, or in the superseded list with the rule that
|
|
6
|
+
replaced it. One missing fact fails the check.
|
|
7
|
+
|
|
8
|
+
Superseded entries live under a heading that contains 「已取代」 (or "Superseded"), or, since
|
|
9
|
+
2026-11-02, in rules-archive.md beside the rules file; each entry must name its replacement with
|
|
10
|
+
「被 … 取代」 or "superseded by". A rule ID ([R-087]) of the old rules must still be on a current
|
|
11
|
+
rule or in the archive: IDs never disappear.
|
|
12
|
+
|
|
13
|
+
Non-vacuous: run() prints how many old rules, current rules and retired entries it read and fails
|
|
14
|
+
when one is 0 or fell by more than half since the last run (ai_sync/nonvacuous.py); 0 retired entries means the
|
|
15
|
+
retired rules moved and this check would compare against nothing. --accept-drop "<reason>" accepts a deliberate drop.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
START = "<!-- owner-preferences:start"
|
|
23
|
+
END = "<!-- owner-preferences:end -->"
|
|
24
|
+
|
|
25
|
+
# Real aisync subcommands: "aisync launch" in prose ("the aisync launch") is not a command.
|
|
26
|
+
_SUBCMDS = ("init|log|rule|claim|release|claims|report|status|tail|news|hook|install-hooks"
|
|
27
|
+
"|sync|watch|verify|resolve|rulecheck|resume|demo|board|mcp|tidy|instinct")
|
|
28
|
+
|
|
29
|
+
_FACTS = [
|
|
30
|
+
re.compile(r"`([^`\n]{2,})`"), # code and commands in backticks
|
|
31
|
+
re.compile(r"(?<![\w])(~?/[A-Za-z0-9_.\-@]+(?:/[A-Za-z0-9_.\-@]+)+/?|~/[A-Za-z0-9_.\-@]+)"), # paths: ~/x or two+ ASCII segments
|
|
32
|
+
re.compile(r"\b([\w.\-]+\.(?:py|md|json|toml|ts|jsonl|yaml|yml|plist|sh|svg|png|pdf))\b"),
|
|
33
|
+
re.compile(r"\b(E\d{3})\b"), # correction ids
|
|
34
|
+
re.compile(r"\b(EB-\d{3})\b"),
|
|
35
|
+
re.compile(r"\b(T-\d{8}-[\w-]+?)(?=[\s,。,;;))]|$)"), # ticket ids
|
|
36
|
+
re.compile(r"\b(KPI-AMD-\d{3}|XP-AMD-\d{3})\b"),
|
|
37
|
+
re.compile(r"(https?://[^\s))>]+)"),
|
|
38
|
+
re.compile(r"\b(\d{1,2}:\d{2})\b"), # clock times
|
|
39
|
+
re.compile(r"\b(\d+(?:\.\d+)?\s?(?:min|minutes|h|hours|days|MB|GB|%|分钟|小时|天|周|个|条|次|题|封|秒|s))(?![\w])"),
|
|
40
|
+
re.compile(r"(aisync (?:" + _SUBCMDS + r")(?: [a-z][\w-]*)?)\b"), # aisync subcommands (real ones only)
|
|
41
|
+
re.compile(r"(?<![\w/.~-])([a-z][a-z0-9]*(?:[_-][a-z0-9]+)+)(?![\w/-])"), # job, field and tool names
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
# "CORRECTION to the 2026-10-15 09:04 github1 naming rule", "Supersedes the 2026-10-23 11:44 borrow-first rule":
|
|
45
|
+
# pointers to another rule, which carries its own facts; a tidy drops this history narration.
|
|
46
|
+
_XREF = re.compile(r"(?i)\b(?:correction to|follow-up to|adds to|exception to|supersedes)\s+the\s+[^.;]{0,120}?\b(?:rule|entry)\b"
|
|
47
|
+
r"|\bthe\s+(?:\d{4}-\d{2}-\d{2}\s+)?\d{1,2}:\d{2}\b[^.;]{0,80}?\b(?:rule|entry)\b")
|
|
48
|
+
|
|
49
|
+
_RID = re.compile(r"^\[(R-\d{3,})\]\s*")
|
|
50
|
+
ARCHIVE = "rules-archive.md"
|
|
51
|
+
|
|
52
|
+
_HEAD = re.compile(r"^\d{4}-\d{2}-\d{2}(?: \d{2}:\d{2})?(?: [A-Z]{2,4})? \([^)]*\):\s*")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def body(rule: str) -> str:
|
|
56
|
+
"""The rule itself: without the 'date time TZ (agent, project):' header and the trailing Reason."""
|
|
57
|
+
rule = _XREF.sub("", _HEAD.sub("", _RID.sub("", rule)))
|
|
58
|
+
i = rule.rfind(" Reason:")
|
|
59
|
+
return rule[:i] if i != -1 else rule
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def block(text: str) -> str:
|
|
63
|
+
"""The owner-preferences block if markers exist, else the whole text."""
|
|
64
|
+
i, j = text.find(START), text.find(END)
|
|
65
|
+
return text[i:j] if i != -1 and j != -1 else text
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def rules(text: str) -> list[str]:
|
|
69
|
+
"""Top-level bullet rules of the block (continuation lines joined)."""
|
|
70
|
+
out: list[str] = []
|
|
71
|
+
for line in block(text).splitlines():
|
|
72
|
+
if line.startswith("- "):
|
|
73
|
+
out.append(line[2:].strip())
|
|
74
|
+
elif out and line.startswith(" ") and line.strip():
|
|
75
|
+
out[-1] += " " + line.strip()
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def facts(rule: str) -> set[str]:
|
|
80
|
+
found: set[str] = set()
|
|
81
|
+
rule = body(rule)
|
|
82
|
+
for rx in _FACTS:
|
|
83
|
+
for m in rx.finditer(rule):
|
|
84
|
+
f = m.group(1).strip().rstrip(".,;:。,;")
|
|
85
|
+
if len(f) >= 2:
|
|
86
|
+
found.add(f)
|
|
87
|
+
return found
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def split_superseded(text: str) -> tuple[str, list[str]]:
|
|
91
|
+
"""(current rules text, superseded entries)."""
|
|
92
|
+
lines = block(text).splitlines()
|
|
93
|
+
cur: list[str] = []
|
|
94
|
+
sup: list[str] = []
|
|
95
|
+
in_sup = False
|
|
96
|
+
for line in lines:
|
|
97
|
+
if line.startswith("#"):
|
|
98
|
+
in_sup = ("已取代" in line) or ("superseded" in line.lower())
|
|
99
|
+
if in_sup:
|
|
100
|
+
continue
|
|
101
|
+
(sup if in_sup else cur).append(line)
|
|
102
|
+
entries = rules("\n".join(sup))
|
|
103
|
+
return "\n".join(cur), entries
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _names_replacement(entry: str) -> bool:
|
|
107
|
+
return bool(re.search(r"被.+取代|superseded by", entry, re.I))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def check(before: str, after: str, archive: str = "") -> list[dict]:
|
|
111
|
+
"""Missing facts: [{rule, fact}] for every hard fact of `before` that `after` (plus the archive) lost."""
|
|
112
|
+
current, sup = split_superseded(after)
|
|
113
|
+
sup += rules(archive)
|
|
114
|
+
sup_ok = [e for e in sup if _names_replacement(e)]
|
|
115
|
+
kept_ids = {m.group(1) for r in rules(current) + sup if (m := _RID.match(r))}
|
|
116
|
+
missing = []
|
|
117
|
+
for r in rules(before):
|
|
118
|
+
m = _RID.match(r)
|
|
119
|
+
if m and m.group(1) not in kept_ids:
|
|
120
|
+
missing.append({"rule": r[:120], "fact": m.group(1)})
|
|
121
|
+
for f in sorted(facts(r)):
|
|
122
|
+
if f in current:
|
|
123
|
+
continue
|
|
124
|
+
if any(f in e for e in sup_ok):
|
|
125
|
+
continue
|
|
126
|
+
missing.append({"rule": r[:120], "fact": f})
|
|
127
|
+
return missing
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def counted(before: str, after: str, archive: str = "") -> dict[str, int]:
|
|
131
|
+
"""What check() really compared: old rules, current rules, retired entries (superseded section plus archive)."""
|
|
132
|
+
current, sup = split_superseded(after)
|
|
133
|
+
return {"old rules": len(rules(before)), "current rules": len(rules(current)), "retired entries": len(sup) + len(rules(archive))}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def run(before_path: str, after_path: str, archive_path: str | None = None, accept_drop: str | None = None) -> int:
|
|
137
|
+
"""archive_path defaults to rules-archive.md next to the after file, when it exists."""
|
|
138
|
+
from . import nonvacuous
|
|
139
|
+
after_p = Path(after_path).expanduser()
|
|
140
|
+
arch = Path(archive_path).expanduser() if archive_path else after_p.parent / ARCHIVE
|
|
141
|
+
before = Path(before_path).expanduser().read_text(encoding="utf-8")
|
|
142
|
+
after = after_p.read_text(encoding="utf-8")
|
|
143
|
+
archive = arch.read_text(encoding="utf-8") if arch.exists() else ""
|
|
144
|
+
miss = check(before, after, archive)
|
|
145
|
+
for m in miss:
|
|
146
|
+
print(f"MISSING {m['fact']!r} ← {m['rule']}")
|
|
147
|
+
counts = counted(before, after, archive)
|
|
148
|
+
vacuous = nonvacuous.guard("rulecheck", counts, accept_drop, nonvacuous.state_file(after_p.parent))
|
|
149
|
+
for v in vacuous:
|
|
150
|
+
print(f"VACUOUS {v}")
|
|
151
|
+
print(f"rulecheck: {counts['old rules']} old rules, {len(miss)} missing facts -> {'FAIL' if miss or vacuous else 'OK'}")
|
|
152
|
+
print(nonvacuous.summary(counts))
|
|
153
|
+
return 1 if miss or vacuous else 0
|
ai_sync/ruleids.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Stable rule IDs and the retired-rules archive (2026-11-02, owner: version management for the shared rules).
|
|
2
|
+
|
|
3
|
+
What: every active bullet of the owner-preferences block starts with an ID like [R-001]. IDs come from
|
|
4
|
+
one counter and are never reused. A replaced rule leaves the block and goes to rules-archive.md
|
|
5
|
+
beside preferences.md with its ID, full text and source tag, then
|
|
6
|
+
"· retired: <date> · replaced_by: <ID>" (unknown when the record does not say).
|
|
7
|
+
Why: rules can be named and replaced by ID, the history stays out of every tool's always-loaded copy,
|
|
8
|
+
and the history file keeps who replaced whom.
|
|
9
|
+
How: normalize() runs every cycle (core.run_cycle step "ids"): it numbers bullets that have no ID (a hand
|
|
10
|
+
edit adopted from a tool copy, an AGENTS.md import) and moves any "### 已取代" section into the archive.
|
|
11
|
+
collab.rule_add uses next_id() and archive_add() for new and replaced rules.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from datetime import datetime
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from . import core
|
|
20
|
+
|
|
21
|
+
ARCHIVE = "rules-archive.md"
|
|
22
|
+
SUPERSEDED_HEAD = "### 已取代"
|
|
23
|
+
_ID = re.compile(r"\[R-(\d{3,})\]")
|
|
24
|
+
_BULLET_ID = re.compile(r"^- \[(R-\d{3,})\] ")
|
|
25
|
+
_ID_ONLY = re.compile(r"^\[?(R-\d{3,})\]?$", re.I)
|
|
26
|
+
_META = re.compile(r" · retired: (\S+) · replaced_by: (\S+)$")
|
|
27
|
+
ARCHIVE_HEAD = """# Shared rules archive (retired rules)
|
|
28
|
+
|
|
29
|
+
Rules retired from the owner-preferences block of ~/.ai-sync/preferences.md, newest first. Each keeps its
|
|
30
|
+
ID (IDs are never reused), full text and source tag, then `· retired: <date> · replaced_by: <ID>`
|
|
31
|
+
(unknown when the old record does not say). Written by `aisync rule add --replaces`; read by
|
|
32
|
+
`aisync rule list --archived` and `aisync rulecheck`. Not loaded by any tool; the rules in force are only
|
|
33
|
+
the ones in preferences.md.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _norm(text: str) -> str:
|
|
38
|
+
return re.sub(r"[^a-z0-9一-鿿]+", "", text.lower())
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def archive_path(cfg: core.Config) -> Path:
|
|
42
|
+
return cfg.root / ARCHIVE
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def is_id(text: str) -> str | None:
|
|
46
|
+
"""'R-087' or '[r-087]' -> 'R-087'; anything else -> None."""
|
|
47
|
+
m = _ID_ONLY.match(text.strip())
|
|
48
|
+
return m.group(1).upper() if m else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def bullet_id(line: str) -> str | None:
|
|
52
|
+
m = _BULLET_ID.match(line)
|
|
53
|
+
return m.group(1) if m else None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def with_id(bullet: str, rid: str) -> str:
|
|
57
|
+
"""'- text' -> '- [R-001] text'."""
|
|
58
|
+
return f"- [{rid}] {bullet[2:]}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def archive_entries(cfg: core.Config) -> list[str]:
|
|
62
|
+
p = archive_path(cfg)
|
|
63
|
+
return [l for l in p.read_text().splitlines() if l.startswith("- ")] if p.exists() else []
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def next_id(cfg: core.Config) -> str:
|
|
67
|
+
"""Next free ID: above every ID in preferences.md, the archive and the counter. Call under core.locked."""
|
|
68
|
+
seen = [0]
|
|
69
|
+
for p in (cfg.root / "preferences.md", archive_path(cfg)):
|
|
70
|
+
if p.exists():
|
|
71
|
+
seen += [int(n) for n in _ID.findall(p.read_text())]
|
|
72
|
+
st = core.load_json(cfg.state / "rule_ids.json", {})
|
|
73
|
+
n = max(max(seen) + 1, int(st.get("next", 1)))
|
|
74
|
+
core.save_json(cfg.state / "rule_ids.json", {"next": n + 1, "ts": core.now_iso()})
|
|
75
|
+
return f"R-{n:03d}"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def archive_line(old_bullet: str, retired: str, replaced_by: str, note: str = "") -> str:
|
|
79
|
+
"""The archive entry: the old bullet as it was, an optional 被…取代 note, then the metadata."""
|
|
80
|
+
return f"{old_bullet.rstrip()}{note} · retired: {retired or 'unknown'} · replaced_by: {replaced_by or 'unknown'}"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def archive_add(cfg: core.Config, entries: list[str]) -> None:
|
|
84
|
+
"""Put entries at the top of the archive (newest first), in the given order. Call under core.locked."""
|
|
85
|
+
if not entries:
|
|
86
|
+
return
|
|
87
|
+
p = archive_path(cfg)
|
|
88
|
+
lines = p.read_text().splitlines() if p.exists() else ARCHIVE_HEAD.splitlines() + [""]
|
|
89
|
+
at = next((i for i, l in enumerate(lines) if l.startswith("- ")), len(lines))
|
|
90
|
+
lines[at:at] = entries
|
|
91
|
+
core.atomic_write(p, "\n".join(lines) + "\n")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _retired_date(entry: str) -> str:
|
|
95
|
+
m = re.search(r"取代((\d{4}-\d{2}-\d{2})", entry)
|
|
96
|
+
return m.group(1) if m else ""
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _replacement_key(entry: str) -> str:
|
|
100
|
+
"""The words inside 被「…」取代 (nested 「」 allowed), up to the first ;."""
|
|
101
|
+
end = entry.rfind("」取代")
|
|
102
|
+
start = entry.rfind("被「", 0, end) if end != -1 else -1
|
|
103
|
+
if start == -1:
|
|
104
|
+
return ""
|
|
105
|
+
return entry[start + 2:end].split(";")[0].rstrip("…")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _find(key: str, lines: list[str], skip: str = "") -> str:
|
|
109
|
+
"""ID of the one line containing key (normalized); '' when none or several."""
|
|
110
|
+
k = _norm(key)
|
|
111
|
+
if len(k) < 6:
|
|
112
|
+
return ""
|
|
113
|
+
hits = {bullet_id(l) for l in lines if k in _norm(l) and bullet_id(l) and bullet_id(l) != skip}
|
|
114
|
+
return hits.pop() if len(hits) == 1 else ""
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def normalize(cfg: core.Config) -> dict:
|
|
118
|
+
"""Number bullets without an ID; move a '### 已取代' section into the archive. Idempotent."""
|
|
119
|
+
path = cfg.root / "preferences.md"
|
|
120
|
+
rep = {"numbered": [], "archived": []}
|
|
121
|
+
with core.locked(cfg):
|
|
122
|
+
text = path.read_text()
|
|
123
|
+
block = core.extract_block(text)
|
|
124
|
+
if block is None:
|
|
125
|
+
return rep
|
|
126
|
+
lines = block.split("\n")
|
|
127
|
+
retired: list[str] = []
|
|
128
|
+
span = core._superseded_span(lines)
|
|
129
|
+
if span:
|
|
130
|
+
s, e = span
|
|
131
|
+
retired = [l for l in lines[s + 1:e] if l.startswith("- ")]
|
|
132
|
+
while s > 0 and lines[s - 1].strip() == "":
|
|
133
|
+
s -= 1
|
|
134
|
+
del lines[s:e]
|
|
135
|
+
for i, l in enumerate(lines):
|
|
136
|
+
if l.startswith("- ") and not bullet_id(l):
|
|
137
|
+
lines[i] = with_id(l, next_id(cfg))
|
|
138
|
+
rep["numbered"].append(bullet_id(lines[i]))
|
|
139
|
+
numbered = [with_id(l, next_id(cfg)) if not bullet_id(l) else l for l in retired]
|
|
140
|
+
active = [l for l in lines if bullet_id(l)]
|
|
141
|
+
entries = []
|
|
142
|
+
for l in numbered:
|
|
143
|
+
key = _replacement_key(l)
|
|
144
|
+
by = _find(key, active) or _find(key, numbered + archive_entries(cfg), skip=bullet_id(l)) if key else ""
|
|
145
|
+
entries.append(archive_line(l, _retired_date(l), by))
|
|
146
|
+
rep["archived"].append(bullet_id(l))
|
|
147
|
+
if not rep["numbered"] and not entries:
|
|
148
|
+
return rep
|
|
149
|
+
archive_add(cfg, entries) # history first: a crash in between never loses a rule's text
|
|
150
|
+
core.atomic_write(path, core.replace_block(text, "\n".join(lines)))
|
|
151
|
+
if rep["numbered"] or rep["archived"]:
|
|
152
|
+
core.append_event(cfg, agent="ai-sync", kind="rule_change",
|
|
153
|
+
summary=f"rule ids: numbered {len(rep['numbered'])} rule(s), "
|
|
154
|
+
f"moved {len(rep['archived'])} retired rule(s) to {ARCHIVE}",
|
|
155
|
+
files=["preferences.md", ARCHIVE])
|
|
156
|
+
return rep
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def parse_meta(entry: str) -> tuple[str, str]:
|
|
160
|
+
"""(retired, replaced_by) of an archive entry; ('', '') when it has no metadata."""
|
|
161
|
+
m = _META.search(entry)
|
|
162
|
+
return (m.group(1), m.group(2)) if m else ("", "")
|
ai_sync/rulespec.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""rulespec: every shared rule is an interface, not an essay (owner decision 2026-11-08).
|
|
2
|
+
|
|
3
|
+
A rule bullet has a fixed shape:
|
|
4
|
+
|
|
5
|
+
- [R-333] When: any deploy step. Do: the AI runs it step by step and checks after each. Not: a background run. (2026-11-02 · claude-code, ops-jobs)
|
|
6
|
+
|
|
7
|
+
An optional leading `Meta rule.` marks the few rules that rank above topic rules (R-005;
|
|
8
|
+
enforcement.py counts them by that prefix). `When:` (the trigger) and `Do:` (the action) are required, `Not:` (what it forbids) is optional, in that
|
|
9
|
+
order. The body (between the ID and the source tag) stays under MAX_BODY characters: why, history and full
|
|
10
|
+
quotes go to the journal (`--reason`) and the archive, and the source tag points there. What enforces a rule
|
|
11
|
+
lives in rules-enforcement.toml, not in the bullet. With `rule_spec = true` in config.toml, `aisync rule add`
|
|
12
|
+
refuses a rule in any other shape; `aisync rule lint` lists every rule that is not in this shape yet.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
MAX_BODY = 420 # characters between the ID and the source tag; 360 forced meaning loss on merged rules (2026-11-08)
|
|
20
|
+
|
|
21
|
+
_ID = re.compile(r"^\[(R-\d{3,})\]\s*")
|
|
22
|
+
_TAG = re.compile(r"\s*(\((?:\d{4}-\d{2}-\d{2}|owner)[^()]*(?:\([^()]*\)[^()]*)*\))\s*$")
|
|
23
|
+
_META = re.compile(r"^Meta rule[.:]?\s+")
|
|
24
|
+
_FIELD = re.compile(r"(?:(?<=\s)|^)(When|Do|Not):\s*")
|
|
25
|
+
# R-358: a rule does not rank itself. Only a claim about the rule's own rank counts ("the highest rule", "this rule
|
|
26
|
+
# has top priority", the label TOP PRIORITY, 最高优先级), read in When and Do: Not says what is forbidden, so naming the
|
|
27
|
+
# words there is not a claim. "choose the highest compatible version" is an ordinary rule.
|
|
28
|
+
_SELF_RANK = re.compile(
|
|
29
|
+
r"(?i:\b(?:this|the) (?:highest|top|first)(?:[- ]priority)? rule\b"
|
|
30
|
+
r"|\b(?:highest|top)[- ]priority rule\b"
|
|
31
|
+
r"|\bthis rule\b[^.。;;]{0,40}\b(?:highest|top priority|above all|overrides? (?:all|every))\b)"
|
|
32
|
+
r"|\bTOP PRIORITY\b|最高优先级|第一优先级")
|
|
33
|
+
# quoted text does not count. A single quote opens only after a space or bracket and closes before one, so the
|
|
34
|
+
# apostrophes of don't ... rule's are not a pair of quotes.
|
|
35
|
+
_QUOTED = re.compile(r"“[^”]*”|\"[^\"]*\"|「[^」]*」|‘[^’]*’|(?<![\w'])'[^']*'(?![\w'])")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Spec:
|
|
40
|
+
id: str
|
|
41
|
+
when: str
|
|
42
|
+
do: str
|
|
43
|
+
not_: str
|
|
44
|
+
tag: str
|
|
45
|
+
meta: bool = False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def split(rule: str) -> tuple[str, str, str]:
|
|
49
|
+
"""(id, body, tag) of a rule line without its leading '- '."""
|
|
50
|
+
rule = rule.strip()
|
|
51
|
+
if rule.startswith("- "):
|
|
52
|
+
rule = rule[2:]
|
|
53
|
+
m = _ID.match(rule)
|
|
54
|
+
rid = m.group(1) if m else ""
|
|
55
|
+
rest = rule[m.end():] if m else rule
|
|
56
|
+
t = _TAG.search(rest)
|
|
57
|
+
tag = t.group(1) if t else ""
|
|
58
|
+
body = rest[:t.start()] if t else rest
|
|
59
|
+
return rid, body.strip(), tag
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def fields(body: str) -> dict[str, str] | None:
|
|
63
|
+
"""{'When': .., 'Do': .., 'Not': ..} when the labels appear once each, in order; else None."""
|
|
64
|
+
body = _META.sub("", body, count=1)
|
|
65
|
+
hits = list(_FIELD.finditer(body))
|
|
66
|
+
names = [h.group(1) for h in hits]
|
|
67
|
+
if names not in (["When", "Do"], ["When", "Do", "Not"]) or hits[0].start() != 0:
|
|
68
|
+
return None
|
|
69
|
+
out = {}
|
|
70
|
+
for i, h in enumerate(hits):
|
|
71
|
+
end = hits[i + 1].start() if i + 1 < len(hits) else len(body)
|
|
72
|
+
out[h.group(1)] = body[h.end():end].strip()
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def parse(rule: str) -> Spec | None:
|
|
77
|
+
rid, body, tag = split(rule)
|
|
78
|
+
f = fields(body)
|
|
79
|
+
if f is None:
|
|
80
|
+
return None
|
|
81
|
+
return Spec(rid, f["When"], f["Do"], f.get("Not", ""), tag, bool(_META.match(body)))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def problems(rule: str, need_id: bool = True, need_tag: bool = True) -> list[str]:
|
|
85
|
+
"""What keeps a rule from the interface shape; [] when it fits."""
|
|
86
|
+
rid, body, tag = split(rule)
|
|
87
|
+
out = []
|
|
88
|
+
if need_id and not rid:
|
|
89
|
+
out.append("no [R-###] id")
|
|
90
|
+
f = fields(body)
|
|
91
|
+
if f is None:
|
|
92
|
+
out.append("not in the shape 'When: ... Do: ... [Not: ...]'")
|
|
93
|
+
else:
|
|
94
|
+
for k in ("When", "Do"):
|
|
95
|
+
if not f[k].strip(" .。;;"):
|
|
96
|
+
out.append(f"{k}: is empty")
|
|
97
|
+
claim = " ".join((f or {}).get(k, "") for k in ("When", "Do")) if f else body
|
|
98
|
+
if _SELF_RANK.search(_QUOTED.sub(" ", claim)):
|
|
99
|
+
out.append("ranks itself (the highest rule / TOP PRIORITY / 最高优先级, R-358): say what it does; "
|
|
100
|
+
"quoted words and the Not: part do not count")
|
|
101
|
+
if len(body) > MAX_BODY:
|
|
102
|
+
out.append(f"body is {len(body)} characters, over {MAX_BODY}: keep what to do, move the why to --reason")
|
|
103
|
+
if need_tag and not tag:
|
|
104
|
+
out.append("no source tag '(YYYY-MM-DD · agent, project)'")
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def compose(when: str, do: str, not_: str = "") -> str:
|
|
109
|
+
"""Rule text from the three fields, each ending in one full stop."""
|
|
110
|
+
def end(s: str) -> str:
|
|
111
|
+
s = " ".join(s.split()).rstrip(" .。;;")
|
|
112
|
+
return s + "."
|
|
113
|
+
if not when.strip() or not do.strip():
|
|
114
|
+
raise ValueError("--when and --do are both required")
|
|
115
|
+
text = f"When: {end(when)} Do: {end(do)}"
|
|
116
|
+
return text + (f" Not: {end(not_)}" if not_.strip() else "")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def lint(lines: list[str]) -> dict:
|
|
120
|
+
"""Count rules in and out of the shape; `bad` lists each one that is out, with its problems."""
|
|
121
|
+
bad = []
|
|
122
|
+
for r in lines:
|
|
123
|
+
p = problems(r)
|
|
124
|
+
if p:
|
|
125
|
+
bad.append({"id": split(r)[0], "problems": p, "rule": r[:100]})
|
|
126
|
+
return {"rules": len(lines), "fit": len(lines) - len(bad), "bad": bad}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def rewrite(cfg, bodies: dict[str, str], agent: str, why: str = "interface rewrite") -> dict:
|
|
130
|
+
"""Swap the body of each rule ID in `bodies` for its new interface text, keeping the ID and the source tag.
|
|
131
|
+
|
|
132
|
+
The old bullet goes to the top of rules-archive.md with 被 <same id> 取代. Stricter than rulecheck (which
|
|
133
|
+
accepts any fact still in the archive, and the archive holds the old text): every hard fact of the old rule
|
|
134
|
+
(rulecheck.facts) must be in its new text, unless the value is {"text": ..., "drop": {fact: reason}} and
|
|
135
|
+
names it, so history (when the owner said it) can go but a path, number or command cannot slip away.
|
|
136
|
+
Nothing is written when a new body is not in the interface shape, an ID is unknown or a fact is lost.
|
|
137
|
+
Returns {"rewritten": [...], "problems": {...}, "missing": [...], "dropped": {...}}.
|
|
138
|
+
"""
|
|
139
|
+
from datetime import datetime
|
|
140
|
+
from . import core, rulecheck, ruleids
|
|
141
|
+
p = cfg.root / "preferences.md"
|
|
142
|
+
day = f"{datetime.now().astimezone():%Y-%m-%d}"
|
|
143
|
+
with core.locked(cfg):
|
|
144
|
+
before = p.read_text()
|
|
145
|
+
lines = before.splitlines()
|
|
146
|
+
where = {split(l)[0]: i for i, l in enumerate(lines) if l.startswith("- [R-")}
|
|
147
|
+
probs, drops = {}, {}
|
|
148
|
+
norm = {}
|
|
149
|
+
for rid, v in bodies.items():
|
|
150
|
+
if isinstance(v, dict):
|
|
151
|
+
norm[rid] = str(v.get("text", ""))
|
|
152
|
+
drops[rid] = {str(k): str(r) for k, r in (v.get("drop") or {}).items()}
|
|
153
|
+
else:
|
|
154
|
+
norm[rid] = str(v)
|
|
155
|
+
bodies = norm
|
|
156
|
+
for rid, body in bodies.items():
|
|
157
|
+
if rid not in where:
|
|
158
|
+
probs[rid] = ["unknown rule id"]
|
|
159
|
+
continue
|
|
160
|
+
bad = problems(body, need_id=False, need_tag=False)
|
|
161
|
+
if bad:
|
|
162
|
+
probs[rid] = bad
|
|
163
|
+
if probs:
|
|
164
|
+
return {"rewritten": [], "problems": probs, "missing": [], "dropped": {}}
|
|
165
|
+
missing = []
|
|
166
|
+
for rid, body in bodies.items():
|
|
167
|
+
old = lines[where[rid]]
|
|
168
|
+
for f in sorted(rulecheck.facts(split(old)[1])): # the body only: the source tag is kept as is
|
|
169
|
+
if f not in body and f not in drops.get(rid, {}):
|
|
170
|
+
missing.append({"rule": old[:120], "fact": f})
|
|
171
|
+
if missing:
|
|
172
|
+
return {"rewritten": [], "problems": {}, "missing": missing, "dropped": {}}
|
|
173
|
+
archived, done = [], []
|
|
174
|
+
for rid, body in bodies.items():
|
|
175
|
+
i = where[rid]
|
|
176
|
+
old = lines[i]
|
|
177
|
+
tag = split(old)[2]
|
|
178
|
+
new = f"- [{rid}] {' '.join(body.split())} {tag}".rstrip()
|
|
179
|
+
if new == old:
|
|
180
|
+
continue
|
|
181
|
+
lines[i] = new
|
|
182
|
+
archived.append(ruleids.archive_line(old, day, rid, f" 被 {rid}「{body[:24]}」取代({day},{why})"))
|
|
183
|
+
done.append(rid)
|
|
184
|
+
after = "\n".join(lines) + ("\n" if before.endswith("\n") else "")
|
|
185
|
+
arch = ruleids.archive_path(cfg)
|
|
186
|
+
arch_text = "\n".join(archived) + "\n" + (arch.read_text() if arch.exists() else "")
|
|
187
|
+
missing = rulecheck.check(before, after, arch_text)
|
|
188
|
+
if missing:
|
|
189
|
+
return {"rewritten": [], "problems": {}, "missing": missing, "dropped": {}}
|
|
190
|
+
if done:
|
|
191
|
+
ruleids.archive_add(cfg, archived)
|
|
192
|
+
core.atomic_write(p, after)
|
|
193
|
+
if done:
|
|
194
|
+
core.append_event(cfg, agent=agent, kind="rule_change", project="ai-sync",
|
|
195
|
+
summary=f"{why}: {len(done)} rule(s) rewritten as When/Do/Not ({', '.join(done[:12])}"
|
|
196
|
+
+ (" …" if len(done) > 12 else "") + "); old text in rules-archive.md",
|
|
197
|
+
files=["preferences.md", ruleids.ARCHIVE])
|
|
198
|
+
for rid, d in drops.items():
|
|
199
|
+
if d and rid in done:
|
|
200
|
+
core.append_event(cfg, agent=agent, kind="note", project="ai-sync",
|
|
201
|
+
summary=f"{rid} interface rewrite dropped: " + "; ".join(f"{k} ({r})" for k, r in d.items()))
|
|
202
|
+
return {"rewritten": done, "problems": {}, "missing": [], "dropped": {k: v for k, v in drops.items() if v}}
|
ai_sync/tidy.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""tidy: the clerk that keeps the shared rules small. It proposes; the owner ticks; nothing changes by itself.
|
|
2
|
+
|
|
3
|
+
What: one report with four lists: rules that say the same thing (When and Do both close), rules nobody cited in
|
|
4
|
+
`unused_days`, the core layer over its budget, and rules out of shape or with no enforcer on record
|
|
5
|
+
(each with its planned check, or `no plan`), plus enforcer files that are gone.
|
|
6
|
+
Why: rules only grow (221 by 2026-11-08); a slim by hand happens once, a clerk keeps it small (owner 2026-11-08).
|
|
7
|
+
How: pure reads, no model, no network. Citations come from the journal plus files matched by `tidy_usage_globs`
|
|
8
|
+
(default: Claude Code transcripts). The report goes to <hub>/tidy/<date>.md with checkboxes, written once a day
|
|
9
|
+
by the watch cycle (R-045: a daily report with to-dos, even when empty); `aisync tidy` prints it now.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import difflib
|
|
14
|
+
import glob
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import time
|
|
18
|
+
from datetime import datetime
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from . import core, rulespec
|
|
22
|
+
|
|
23
|
+
SAME = 0.72 # When and Do both at least this close: a likely duplicate
|
|
24
|
+
UNUSED_DAYS = 30
|
|
25
|
+
CORE_BUDGET_CHARS = 26000 # the core layer's rule text; about 7,000 tokens at the 2026-11-08 mix
|
|
26
|
+
DEFAULT_GLOBS = ["~/.claude/projects/*/*.jsonl"]
|
|
27
|
+
_RID = re.compile(r"\bR-\d{3,}\b")
|
|
28
|
+
BULK = 40 # a file naming more distinct rule IDs than this is rule maintenance, not use
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _norm(s: str) -> str:
|
|
32
|
+
return " ".join(re.sub(r"[`'\"()(),,.;;::]", " ", s.lower()).split())
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def duplicates(rules: list[str]) -> list[dict]:
|
|
36
|
+
specs = [(r, rulespec.parse(r)) for r in rules]
|
|
37
|
+
specs = [(r, s) for r, s in specs if s]
|
|
38
|
+
out = []
|
|
39
|
+
for i in range(len(specs)):
|
|
40
|
+
for j in range(i + 1, len(specs)):
|
|
41
|
+
a, b = specs[i][1], specs[j][1]
|
|
42
|
+
w = difflib.SequenceMatcher(None, _norm(a.when), _norm(b.when)).ratio()
|
|
43
|
+
if w < SAME:
|
|
44
|
+
continue
|
|
45
|
+
d = difflib.SequenceMatcher(None, _norm(a.do), _norm(b.do)).ratio()
|
|
46
|
+
if d >= SAME:
|
|
47
|
+
out.append({"a": a.id, "b": b.id, "when": round(w, 2), "do": round(d, 2)})
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def citations(cfg: core.Config, days: int, globs: list[str] | None = None) -> dict[str, int]:
|
|
52
|
+
"""Rule ID -> times cited in the journal and the usage files of the last `days` days."""
|
|
53
|
+
since = time.time() - days * 86400
|
|
54
|
+
cut = datetime.fromtimestamp(since).astimezone().isoformat()
|
|
55
|
+
n: dict[str, int] = {}
|
|
56
|
+
for e in core.read_events(cfg):
|
|
57
|
+
if e.get("ts", "") >= cut:
|
|
58
|
+
for rid in _RID.findall(e.get("summary", "")):
|
|
59
|
+
n[rid] = n.get(rid, 0) + 1
|
|
60
|
+
for g in globs if globs is not None else cfg.tidy_usage_globs:
|
|
61
|
+
for f in glob.glob(os.path.expanduser(g)):
|
|
62
|
+
try:
|
|
63
|
+
if os.path.getmtime(f) < since:
|
|
64
|
+
continue
|
|
65
|
+
counts: dict[str, int] = {}
|
|
66
|
+
with open(f, errors="ignore") as fh: # line by line: one transcript can be hundreds of MB
|
|
67
|
+
for line in fh:
|
|
68
|
+
for rid in _RID.findall(line):
|
|
69
|
+
counts[rid] = counts.get(rid, 0) + 1
|
|
70
|
+
if len(counts) > BULK: # a slim or rewrite session cites every rule: not evidence of use
|
|
71
|
+
continue
|
|
72
|
+
for rid, k in counts.items():
|
|
73
|
+
n[rid] = n.get(rid, 0) + k
|
|
74
|
+
except OSError:
|
|
75
|
+
continue
|
|
76
|
+
return n
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def report(cfg: core.Config, globs: list[str] | None = None, days: int = UNUSED_DAYS) -> dict:
|
|
80
|
+
from . import collab, enforcement, layers
|
|
81
|
+
truth = core.extract_block((cfg.root / "preferences.md").read_text()) or ""
|
|
82
|
+
rules = collab.rule_lines(truth)
|
|
83
|
+
ids = [rulespec.split(r)[0] for r in rules]
|
|
84
|
+
cited = citations(cfg, days, globs)
|
|
85
|
+
unused = [rid for rid in ids if rid and not cited.get(rid)]
|
|
86
|
+
core_chars = 0
|
|
87
|
+
if cfg.core_topics:
|
|
88
|
+
_, secs, _ = layers.sections(truth)
|
|
89
|
+
core_chars = sum(len(l) for h, body in secs if layers.is_core(layers.topic(h), cfg.core_topics)
|
|
90
|
+
for l in body if l.startswith("- "))
|
|
91
|
+
budget = int(cfg.core_budget_chars or CORE_BUDGET_CHARS)
|
|
92
|
+
enf = enforcement.report(cfg) # one reading of the registry for both commands
|
|
93
|
+
plans = {p["id"]: p for p in enf["planned"] if p["kind"] == "none"}
|
|
94
|
+
no_enforcer = [rid for rid in ids if rid and (rid in plans or rid in enf["unplanned"])]
|
|
95
|
+
lint = rulespec.lint(rules)
|
|
96
|
+
return {"rules": len(rules), "duplicates": duplicates(rules), "unused": unused, "unused_days": days,
|
|
97
|
+
"core_chars": core_chars, "core_budget": budget, "over_budget": bool(cfg.core_topics) and core_chars > budget,
|
|
98
|
+
"out_of_shape": [b["id"] for b in lint["bad"]], "no_enforcer": no_enforcer, "plans": plans,
|
|
99
|
+
"enforcer_gone": enf["missing_paths"] + enf["relative_paths"]}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def render(rep: dict, day: str) -> str:
|
|
103
|
+
lines = [f"# Rules tidy {day}", "",
|
|
104
|
+
f"Checked {rep['rules']} rules. Proposals only: tick a box, then apply it with `aisync rule rewrite` "
|
|
105
|
+
"or `aisync rule add --replaces` (old text goes to rules-archive.md).", ""]
|
|
106
|
+
lines += [f"## Likely duplicates ({len(rep['duplicates'])})"]
|
|
107
|
+
lines += [f"- [ ] merge {d['a']} and {d['b']} (When {d['when']}, Do {d['do']})" for d in rep["duplicates"]] or ["- none"]
|
|
108
|
+
lines += ["", f"## Not cited in {rep['unused_days']} days ({len(rep['unused'])})",
|
|
109
|
+
"Candidates to move to a folded topic or retire; a rule that guards a rare event can stay."]
|
|
110
|
+
lines += [f"- [ ] {rid}" for rid in rep["unused"]] or ["- none"]
|
|
111
|
+
lines += ["", "## Core layer budget"]
|
|
112
|
+
if rep["core_budget"] and rep["core_chars"]:
|
|
113
|
+
mark = "OVER" if rep["over_budget"] else "ok"
|
|
114
|
+
lines.append(f"- {mark}: {rep['core_chars']} of {rep['core_budget']} characters"
|
|
115
|
+
+ (" -> [ ] fold or merge core rules" if rep["over_budget"] else ""))
|
|
116
|
+
else:
|
|
117
|
+
lines.append("- no layered target")
|
|
118
|
+
lines += ["", f"## Out of the When/Do/Not shape ({len(rep['out_of_shape'])})"]
|
|
119
|
+
lines += [f"- [ ] {rid or '(no id)'}" for rid in rep["out_of_shape"]] or ["- none"]
|
|
120
|
+
plans = rep.get("plans", {})
|
|
121
|
+
lines += ["", f"## No enforcer on record ({len(rep['no_enforcer'])})",
|
|
122
|
+
"A check is possible and not written. Write it, then `aisync rule enforce R-### --enforced-by <path>`; "
|
|
123
|
+
"a rule with no plan first gets `aisync rule enforce R-### --planned \"<the check>\" --size S|M|L`."]
|
|
124
|
+
for rid in rep["no_enforcer"]:
|
|
125
|
+
p = plans.get(rid)
|
|
126
|
+
lines.append(f"- [ ] {rid} planned {p['size']} since {p['since']}{' (OVERDUE)' if p['overdue'] else ''}: {p['check']}"
|
|
127
|
+
if p else f"- [ ] {rid} no plan")
|
|
128
|
+
if not rep["no_enforcer"]:
|
|
129
|
+
lines.append("- none")
|
|
130
|
+
gone = rep.get("enforcer_gone", [])
|
|
131
|
+
lines += ["", f"## Enforcer files gone ({len(gone)})",
|
|
132
|
+
"The registry names a file that is not there. `aisync rule enforcement` prints the fix for each."]
|
|
133
|
+
lines += [f"- [ ] {g['id']}: {g['path']}" for g in gone] or ["- none"]
|
|
134
|
+
return "\n".join(lines) + "\n"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def daily(cfg: core.Config, globs: list[str] | None = None) -> Path | None:
|
|
138
|
+
"""Write today's report once (the watch cycle calls this); None when it already exists."""
|
|
139
|
+
day = f"{datetime.now().astimezone():%Y-%m-%d}"
|
|
140
|
+
p = cfg.root / "tidy" / f"{day}.md"
|
|
141
|
+
if p.exists():
|
|
142
|
+
return None
|
|
143
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
144
|
+
core.atomic_write(p, render(report(cfg, globs), day))
|
|
145
|
+
return p
|