Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions ai_sync/tidy.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,38 @@
CORE_BUDGET_CHARS = 26000 # the core layer's rule text; about 7,000 tokens at the 2026-11-08 mix
DEFAULT_GLOBS = ["~/.claude/projects/*/*.jsonl"]
_RID = re.compile(r"\bR-\d{3,}\b")
_LEGACY = re.compile(
r"^(?:- )?(?:\[(R-\d{3,})\]\s*)?\d{4}-\d{2}-\d{2} \d{2}:\d{2} \S+ \([^\n]*?\):\s*(.*)$")
BULK = 40 # a file naming more distinct rule IDs than this is rule maintenance, not use


def _norm(s: str) -> str:
return " ".join(re.sub(r"[`'\"()(),,.;;::]", " ", s.lower()).split())


def _parse(rule: str) -> rulespec.Spec | None:
"""Read current rules and the timestamp-prefixed bullets written in hubs without topics.

Legacy reasons are history, not part of When/Do/Not. Keep this compatibility read local to tidy:
it does not rewrite stored rules or relax the current interface-shape lint.
"""
spec = rulespec.parse(rule)
if spec:
return spec
legacy = _LEGACY.match(rule.strip())
if not legacy:
return None
body = legacy.group(2)
# Match rulecheck.body's legacy convention: the final Reason: is the appended metadata,
# so a Reason: label earlier in the action is not mistaken for the end of that action.
reason = body.rfind(" Reason:")
if reason >= 0:
body = body[:reason]
return rulespec.parse(f"[{legacy.group(1)}] {body}" if legacy.group(1) else body)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve tag-like parentheses in legacy rule bodies

For timestamp-prefixed rules written by collab.rule_add whose final action is, for example, Do: notify (owner of the service) without a trailing full stop, rulespec.parse calls rulespec.split and strips (owner of the service) as though it were a current-format source tag. The resulting action is just notify: an equivalent topic-format rule is missed, while a plain Do: notify rule instead receives a 1.0 duplicate score. Parse the already-extracted legacy body without applying current-format source-tag stripping.

Useful? React with 👍 / 👎.



def duplicates(rules: list[str]) -> list[dict]:
specs = [(r, rulespec.parse(r)) for r in rules]
specs = [(r, _parse(r)) for r in rules]
specs = [(r, s) for r, s in specs if s]
out = []
for i in range(len(specs)):
Expand All @@ -49,9 +72,8 @@ def duplicates(rules: list[str]) -> list[dict]:


def not_compared(rules: list[str]) -> list[str]:
"""IDs of the rules `duplicates` cannot read: it compares only rules in the When/Do/Not shape with the
`(YYYY-MM-DD · agent, project)` tag at the end, so any other rule is left out of the check without a word."""
return [rulespec.split(r)[0] for r in rules if not rulespec.parse(r)]
"""IDs of rules whose When/Do/Not fields `duplicates` cannot read."""
return [rulespec.split(r)[0] for r in rules if not _parse(r)]


def citations(cfg: core.Config, days: int, globs: list[str] | None = None) -> dict[str, int]:
Expand Down Expand Up @@ -114,8 +136,8 @@ def render(rep: dict, day: str) -> str:
lines += [f"- [ ] merge {d['a']} and {d['b']} (When {d['when']}, Do {d['do']})" for d in rep["duplicates"]] or ["- none"]
skipped = rep.get("not_compared", [])
if skipped:
lines.append(f"Not compared: {len(skipped)} of {rep['rules']} rules are not in the When/Do/Not shape with a "
"(YYYY-MM-DD · agent, project) tag at the end, so this check skipped them "
lines.append(f"Not compared: {len(skipped)} of {rep['rules']} rules have no readable When/Do/Not fields "
"in either the current or timestamp-prefixed format, so this check skipped them "
f"({', '.join(r or '(no id)' for r in skipped)}).")
lines += ["", f"## Not cited in {rep['unused_days']} days ({len(rep['unused'])})",
"Candidates to move to a folded topic or retire; a rule that guards a rare event can stay."]
Expand Down
67 changes: 58 additions & 9 deletions tests/test_tidy.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import os
from unittest import mock

from ai_sync import core, tidy
from ai_sync import collab, core, rulespec, tidy

from test_ai_sync import Base

Expand Down Expand Up @@ -51,24 +51,73 @@ def test_duplicates_unused_shape_and_enforcer(self):
self.assertIn("- [ ] merge R-101 and R-102", text)
self.assertIn("Checked 4 rules", text)

def test_rules_the_parser_cannot_read_are_reported_as_not_compared(self):
def test_legacy_rules_are_compared_with_each_other_and_topic_rules(self):
# a fresh hub has no topic headings, so `rule add` stores `- <stamp> (agent, project): When:... Reason:...`;
# the parser needs the (date · agent, project) tag at the end, so such rules never reached the duplicate check
# the leading stamp hid the When/Do fields, so such rules never reached the duplicate check
# and tidy said "Likely duplicates (0)" for two near-identical rules (aisync-cli 0.2.9)
self._rules([
"- [R-201] 2026-11-16 05:04 CST (claude-code, demo): When: a test fails. Do: fix the cause before committing. "
"Not: skipping the test. Reason: demo",
"- [R-202] 2026-11-16 05:04 CST (codex, demo): When: a test fails. Do: fix the cause, then commit. "
"Not: skipping the test. Reason: demo",
"- [R-203] When: a release is cut. Do: tag the commit. (2026-11-16 · cursor, demo)",
"- [R-203] When: a test fails. Do: fix the cause before committing. (2026-11-16 · cursor, demo)",
"- [R-204] 2026-11-16 05:04 CST (codex, demo): free text rule. Reason: demo",
])
rep = tidy.report(self.cfg, globs=[])
self.assertEqual(rep["duplicates"], [])
self.assertEqual(rep["not_compared"], ["R-201", "R-202"])
self.assertEqual([(d["a"], d["b"]) for d in rep["duplicates"]],
[("R-201", "R-202"), ("R-201", "R-203"), ("R-202", "R-203")])
self.assertEqual(rep["not_compared"], ["R-204"])
# Comparing legacy rules does not make them conform to the current writing standard.
self.assertEqual(rep["out_of_shape"], ["R-201", "R-202", "R-204"])
text = tidy.render(rep, "2026-11-16")
self.assertIn("## Likely duplicates (0)\n- none\n", text)
self.assertIn("Not compared: 2 of 3 rules", text)
self.assertIn("(YYYY-MM-DD · agent, project)", text)
self.assertIn("## Likely duplicates (3)\n", text)
self.assertIn("Not compared: 1 of 4 rules", text)

def test_rule_add_without_topics_reaches_duplicate_check(self):
# Base creates an ungrouped hub, as `aisync init` does.
for agent, action in [("claude-code", "fix the cause before committing"),
("codex", "fix the cause, then commit")]:
code, out = self.run_cli("rule", "add", "--agent", agent, "--project", "demo",
"--when", "a test fails", "--do", action,
"--not", "skipping the test", "--reason", "demo",
"--judgment-only", "nothing in code can check it")
self.assertEqual(code, 0, out)
added = [line for line in collab.rule_list(self.cfg) if "When: a test fails" in line]
self.assertEqual(len(added), 2)
before = (self.home / "preferences.md").read_text()
code, out = self.run_cli("tidy", "--json")
self.assertEqual(code, 0)
rep = json.loads(out)
self.assertEqual(len(rep["duplicates"]), 1)
self.assertEqual(set(rep["duplicates"][0][k] for k in ("a", "b")),
{rulespec.split(line)[0] for line in added})
self.assertEqual((self.home / "preferences.md").read_text(), before)

def test_legacy_reason_does_not_affect_duplicate_comparison(self):
self._rules([
"- [R-221] 2026-11-16 05:04 +0530 (codex): When: a test fails. Do: fix it. "
"Reason: When: checking a regression. Do: keep the traceback.",
"- [R-222] When: a test fails. Do: fix it. (2026-11-16 · cursor, demo)",
"- [R-223] 2026-11-16 05:04 UTC (codex): When: a test fails. Do: fix it.",
"- [R-224] random prefix: When: a test fails. Do: fix it.",
"- [R-225] 2026-11-16 05:04 UTC (codex): Do: fix it. When: a test fails.",
])
rep = tidy.report(self.cfg, globs=[])
self.assertEqual([(d["a"], d["b"]) for d in rep["duplicates"]],
[("R-221", "R-222"), ("R-221", "R-223"), ("R-222", "R-223")])
self.assertEqual(rep["not_compared"], ["R-224", "R-225"])

def test_legacy_reason_label_in_action_is_not_truncated(self):
self._rules([
"- [R-231] 2026-11-16 05:04 UTC (codex): When: a test fails. "
"Do: include Reason: the root cause and full remediation steps. Reason: owner asked",
"- [R-232] When: a test fails. Do: include Reason: the root cause and full remediation steps. "
"(2026-11-16 · cursor, demo)",
"- [R-233] When: a test fails. Do: include. (2026-11-16 · cursor, demo)",
])
rep = tidy.report(self.cfg, globs=[])
self.assertEqual([(d["a"], d["b"]) for d in rep["duplicates"]], [("R-231", "R-232")])
self.assertEqual(rep["not_compared"], [])

def test_nothing_is_reported_as_not_compared_when_every_rule_parses(self):
self._rules([
Expand Down
Loading