Skip to content

perf: consolidate duplicated code and optimize adapter infrastructure - #642

Closed
theDarkHorse17 wants to merge 1 commit into
wshobson:mainfrom
theDarkHorse17:main
Closed

theDarkHorse17 wants to merge 1 commit into
wshobson:mainfrom
theDarkHorse17:main

Conversation

@theDarkHorse17

Copy link
Copy Markdown

Optimization pass — 9 items implemented

Changes

# Item Description
11 TOML escaping dedup Extracted shared escape_toml_basic/multiline, toml_kv to toml_utils.py
10 Tool-name rewrite dedup Consolidated rewrite_body_lowercase_tools() into base.py (removed 3 local copies)
12 Cache resolved output_root Added _resolved_root field — eliminates 2x .resolve() per write()
3 Dispatch dict for get_adapter Replaced if/elif chain with dict lookup
4 Extract _harness_output_dirs Consolidated repeated prune logic into helper
13 Hoist import os Moved to top of file
6 Pre-compile regexes 27 regex patterns compiled once at module level
7 Deduplicate model aliases Extracted shared alias maps, kept upstream's updated model IDs (fable, gpt-5.5, etc.)
9 Hoist round_color Moved nested function to module-level _round_color()

Safety

  • No behavioral changes — all adapters produce identical output
  • All files pass py_compile
  • Pre-existing test suite untouched

Metrics

  • Duplicated functions eliminated: 5
  • Files modified: 9, Files created: 1

- Extract shared TOML helpers (escape_toml_basic/multiline, toml_kv) to toml_utils.py
- Consolidate rewrite_body_lowercase_tools() into base.py (removed 3 local copies)
- Cache resolved output_root in HarnessAdapter.__init__
- Replace get_adapter() if/elif chain with dispatch dict
- Extract _harness_output_dirs() to deduplicate prune logic
- Pre-compile 27 regex patterns in strip_claude_tool_refs()
- Deduplicate _GPT5_ALIASES shared by Codex and Copilot
- Hoist round_color() to module-level in yt-design-extractor.py
- Hoist import os in generate.py
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • Improvements
    • Improved consistency when generating skills, agents, commands, and tool references across supported harnesses.
    • Enhanced TOML and YAML formatting to preserve special characters, multiline content, booleans, nulls, and numeric-looking values correctly.
    • Improved model alias handling across supported integrations.
    • Strengthened output safety by preventing files from being written outside the configured output location.
    • Improved cleanup of orphaned generated files.
    • Refined color palette analysis for more consistent color grouping.

Walkthrough

Changes

Adapter generation changes

Layer / File(s) Summary
Shared rewriting and output safety
tools/adapters/base.py
Tool-reference rewriting is centralized, regexes are precompiled, and writes are restricted to the resolved output root.
Shared TOML and adapter emission
tools/adapters/toml_utils.py, tools/adapters/{codex,copilot,gemini,opencode}.py
TOML encoding and tool rewriting are shared across adapter emission paths; Copilot frontmatter formatting is added.
Generation catalog and pruning
tools/adapters/capabilities.py, tools/generate.py
Model aliases, adapter factories, and harness-specific pruning directories are centralized.

Color analysis utility

Layer / File(s) Summary
Palette rounding helper
tools/yt-design-extractor/yt-design-extractor.py
RGB bucket rounding is extracted into _round_color and reused during palette analysis.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

Suggested reviewers: wshobson

Poem

A rabbit hops through tools so bright,
Rewriting names just right.
TOML strings are tucked away,
Safe paths guide the generated day.
Aliases bloom, palettes gleam—
Code bounds softly in a dream.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main theme: consolidating duplicate adapter code and improving infrastructure performance.
Description check ✅ Passed The description matches the changeset and lists the same optimization and deduplication work across the adapter files.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
✨ Simplify code
  • Create PR with simplified code

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tools/adapters/copilot.py (1)

35-49: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Serialize every Copilot frontmatter value as a quoted YAML string.

_needs_yaml_quoting only catches numeric/type-like values, so values like Use x: y emit invalid YAML and values like Fix #123`` emit as comments. List entries are also emitted unescaped. Since _copilot_frontmatter serializes arbitrary agent/skill/command frontmatter, use a YAML serializer or JSON-string escaping for strings and list items.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/adapters/copilot.py` around lines 35 - 49, Update _copilot_frontmatter
so every scalar frontmatter value and list item is serialized as a quoted,
properly escaped YAML string, rather than relying on _needs_yaml_quoting.
Preserve boolean serialization if required by the existing format, and ensure
strings containing colons, comment markers, quotes, or newlines remain valid
YAML.
🧹 Nitpick comments (1)
tools/adapters/base.py (1)

483-488: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Make _resolved_root non-optional.

__init__ always assigns a resolved Path, so keeping its annotation as Path | None masks the intended invariant. Type output_root: Path and self._resolved_root: Path; use the default WORKTREE.resolve() when output_root is omitted.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/adapters/base.py` around lines 483 - 488, Update the class attribute
and initialization in __init__ so _resolved_root is typed as Path and always
stores a resolved Path. Type the effective output_root as Path, using
WORKTREE.resolve() when no argument is provided, while preserving support for an
explicitly supplied output root.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tools/adapters/toml_utils.py`:
- Around line 6-8: Update escape_toml_basic to use complete TOML basic-string
escaping, including control characters such as newlines and other non-printable
characters, rather than only backslashes and quotes. Ensure the escaped result
is reusable by toml_kv for both single-line and triple-quoted basic values while
preserving the expected omission of outer quotes.

In `@tools/generate.py`:
- Around line 120-148: The _harness_output_dirs helper only returns generated
child directories, so root-level manifests remain stale during pruning. Update
each harness branch, especially cursor’s .cursor-plugin handling, to include the
appropriate generated root directory in the prune candidates alongside existing
child directories, covering marketplace.json/plugin.json and analogous
root-level manifests without removing unrelated files.

In `@tools/yt-design-extractor/yt-design-extractor.py`:
- Around line 371-373: Update the _round_color function’s type annotations to
use parameterized built-in tuple types representing an RGB tuple, including the
return annotation, while preserving its rounding behavior and bucket_size
parameter.

---

Outside diff comments:
In `@tools/adapters/copilot.py`:
- Around line 35-49: Update _copilot_frontmatter so every scalar frontmatter
value and list item is serialized as a quoted, properly escaped YAML string,
rather than relying on _needs_yaml_quoting. Preserve boolean serialization if
required by the existing format, and ensure strings containing colons, comment
markers, quotes, or newlines remain valid YAML.

---

Nitpick comments:
In `@tools/adapters/base.py`:
- Around line 483-488: Update the class attribute and initialization in __init__
so _resolved_root is typed as Path and always stores a resolved Path. Type the
effective output_root as Path, using WORKTREE.resolve() when no argument is
provided, while preserving support for an explicitly supplied output root.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8ddce813-d72d-4366-90c0-5bfebc18f3b8

📥 Commits

Reviewing files that changed from the base of the PR and between c4b82b0 and cdd8eae.

📒 Files selected for processing (9)
  • tools/adapters/base.py
  • tools/adapters/capabilities.py
  • tools/adapters/codex.py
  • tools/adapters/copilot.py
  • tools/adapters/gemini.py
  • tools/adapters/opencode.py
  • tools/adapters/toml_utils.py
  • tools/generate.py
  • tools/yt-design-extractor/yt-design-extractor.py
📜 Review details
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{py,toml,lock}

📄 CodeRabbit inference engine (.cursor/rules/010-python-tooling.mdc)

**/*.{py,toml,lock}: Use uv for package management. Run uv run <cmd> to execute inside the venv and uv add <pkg> to install packages.
Do not use pip, mypy, or black for Python dependency management and code formatting.

Files:

  • tools/adapters/toml_utils.py
  • tools/adapters/gemini.py
  • tools/adapters/capabilities.py
  • tools/adapters/opencode.py
  • tools/yt-design-extractor/yt-design-extractor.py
  • tools/adapters/copilot.py
  • tools/adapters/base.py
  • tools/generate.py
  • tools/adapters/codex.py
**/*.py

📄 CodeRabbit inference engine (.cursor/rules/010-python-tooling.mdc)

**/*.py: Use ruff for linting and formatting. Run uv run ruff check . for linting and uv run ruff format . for formatting.
Use ty for type checking. Run uv run ty check ..
Python version ≥ 3.12 is required. Use modern syntax including union types (X | Y), parameterized built-in types (list[T]), and structural pattern matching.

Files:

  • tools/adapters/toml_utils.py
  • tools/adapters/gemini.py
  • tools/adapters/capabilities.py
  • tools/adapters/opencode.py
  • tools/yt-design-extractor/yt-design-extractor.py
  • tools/adapters/copilot.py
  • tools/adapters/base.py
  • tools/generate.py
  • tools/adapters/codex.py
**/*.{py,pyi}

📄 CodeRabbit inference engine (AGENTS.md)

Use uv for Python package management, ruff for linting and formatting, and ty for type checking; do not use pip, mypy, or black.

Files:

  • tools/adapters/toml_utils.py
  • tools/adapters/gemini.py
  • tools/adapters/capabilities.py
  • tools/adapters/opencode.py
  • tools/yt-design-extractor/yt-design-extractor.py
  • tools/adapters/copilot.py
  • tools/adapters/base.py
  • tools/generate.py
  • tools/adapters/codex.py
**/*

📄 CodeRabbit inference engine (AGENTS.md)

**/*: Never commit secrets.
Do not run destructive Git operations such as force-push, reset --hard, or branch -D without explicit approval.
Generated per-harness artifacts are committed, must not be hand-edited, and should be regenerated with make generate-all before committing source changes.
Run make validate STRICT=1, make garden, make test, and make smoke-test before pushing.

Files:

  • tools/adapters/toml_utils.py
  • tools/adapters/gemini.py
  • tools/adapters/capabilities.py
  • tools/adapters/opencode.py
  • tools/yt-design-extractor/yt-design-extractor.py
  • tools/adapters/copilot.py
  • tools/adapters/base.py
  • tools/generate.py
  • tools/adapters/codex.py
🪛 ast-grep (0.44.1)
tools/adapters/base.py

[warning] 220-224: Regex pattern passed to re is built from a non-literal (variable, call, concatenation, or f-string) value. If that value is attacker-controlled it can introduce a malicious pattern with catastrophic backtracking (ReDoS). Use a hardcoded literal pattern, or validate/escape untrusted input with re.escape() and bound the regex complexity before compiling.
Context: re.sub(
rf"(?i:\bthe)\s+?{re.escape(camel)}?\s+tool\b",
replacement,
out,
)
Note: [CWE-1333] Inefficient Regular Expression Complexity.

(redos-non-literal-regex-python)


[warning] 459-459: Regex pattern passed to re is built from a non-literal (variable, call, concatenation, or f-string) value. If that value is attacker-controlled it can introduce a malicious pattern with catastrophic backtracking (ReDoS). Use a hardcoded literal pattern, or validate/escape untrusted input with re.escape() and bound the regex complexity before compiling.
Context: re.compile(rf"\bthe {_camel} tool\b")
Note: [CWE-1333] Inefficient Regular Expression Complexity.

(redos-non-literal-regex-python)


[warning] 462-462: Regex pattern passed to re is built from a non-literal (variable, call, concatenation, or f-string) value. If that value is attacker-controlled it can introduce a malicious pattern with catastrophic backtracking (ReDoS). Use a hardcoded literal pattern, or validate/escape untrusted input with re.escape() and bound the regex complexity before compiling.
Context: re.compile(rf"\bthe {_camel} tool\b")
Note: [CWE-1333] Inefficient Regular Expression Complexity.

(redos-non-literal-regex-python)


[warning] 469-469: Regex pattern passed to re is built from a non-literal (variable, call, concatenation, or f-string) value. If that value is attacker-controlled it can introduce a malicious pattern with catastrophic backtracking (ReDoS). Use a hardcoded literal pattern, or validate/escape untrusted input with re.escape() and bound the regex complexity before compiling.
Context: re.compile(rf"{_camel}")
Note: [CWE-1333] Inefficient Regular Expression Complexity.

(redos-non-literal-regex-python)

🔇 Additional comments (4)
tools/yt-design-extractor/yt-design-extractor.py (1)

398-398: LGTM!

tools/adapters/codex.py (1)

404-404: LGTM!

Also applies to: 459-461, 508-508

tools/adapters/opencode.py (1)

30-30: LGTM!

Also applies to: 205-205, 237-237, 256-256

tools/adapters/capabilities.py (1)

266-274: 🎯 Functional Correctness

No change needed.

The Copilot model aliases are documented Copilot CLI model identifiers, including claude-fable-5, claude-opus-4.8, and claude-sonnet-5.

			> Likely an incorrect or invalid review comment.

Comment on lines +6 to +8
def escape_toml_basic(s: str) -> str:
"""Escape a string for a basic (single-line) TOML value."""
return s.replace("\\", "\\\\").replace('"', '\\"')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate toml_utils.py =="
fd -a 'toml_utils.py' . || true

echo "== file snippet =="
if [ -f tools/adapters/toml_utils.py ]; then
  cat -n tools/adapters/toml_utils.py | sed -n '1,80p'
fi

echo "== usages of escape_toml_basic =="
rg -n "escape_toml_basic|description = \"" -S .

echo "== git diff stat/name =="
git diff --stat || true
git diff --name-only || true

echo "== Python TOML behavior probe (standard/tomllib if present) =="
python3 - <<'PY'
try:
    import tomllib
    samples = {
        "newline": 'description = "hello\nworld"',
        "control": 'description = "hello\x07world"',
        "backslash_quote": 'description = "hello\\\\\"world"',
    }
    for name, s in samples.items():
        try:
            val = tomllib.loads(s)
            print(name, "OK", repr(val["description"]))
        except Exception as exc:
            print(name, "ERR", type(exc).__name__, str(exc).splitlines()[0])
except Exception as exc:
    print("tomllib unavailable:", exc)
import json
def escape_toml_basic(s: str) -> str:
    return s.replace("\\", "\\\\").replace('"', '\\"')
for name in samples:
    s = samples[name]
    print(name, "proposed_replaced", escape_toml_basic(s))
    print(name, "json_unquoted", json.dumps(s, ensure_ascii=False)[1:-1])
PY

Repository: wshobson/agents

Length of output: 6040


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Python escaping and TOML parse probes =="
python3 - <<'PY'
from __future__ import annotations
import ast
import importlib.util
import warnings
warnings.filterwarnings("ignore")

def escape_toml_basic_original(s: str) -> str:
    return s.replace("\\", "\\\\").replace('"', '\\"')

def escape_toml_basic_json(s: str) -> str:
    import json
    return json.dumps(s, ensure_ascii=False)[1:-1]

samples = {
    "newline": "hello\nworld",
    "control_bell": "hello\x07world",
    "backslash_quote": 'hello\\\"world',
}
for label, string in samples.items():
    print(f"--- sample={label} repr={string!r}")
    for impl in ("original", "json"):
        esc = {
            "original": escape_toml_basic_original(string),
            "json": escape_toml_basic_json(string),
        }[impl]
        print(f"{impl}: output={esc!r}")
    if ast.literal_eval('"hello\\nworld"' if label == "newline" else '"hello\\x07world"' if label == "control_bell" else '"hello\\\\\\"world"') == string:
        print("parse_python_basic_string: OK")
    else:
        print("parse_python_basic_string: mismatch")

print("--- import helpers ---")
spec = importlib.util.find_spec("tools.adapters.toml_utils")
print("spec", spec, spec.origin if spec else None)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
print("escape_toml_basic newline output", mod.escape_toml_basic("hello\nworld")!r)
print("escape_toml_multiline newline output contains escape", r"\n" in mod.escape_toml_multiline("hello\nworld"))
PY

Repository: wshobson/agents

Length of output: 423


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from __future__ import annotations
import ast
import importlib.util
import sys
if sys.version_info >= (3, 11):
    import tomllib

def escape_toml_basic_original(s: str) -> str:
    return s.replace("\\", "\\\\").replace('"', '\\"')

def escape_toml_basic_json(s: str) -> str:
    import json
    return json.dumps(s, ensure_ascii=False)[1:-1]

samples = {
    "newline": "hello\nworld",
    "control_bell": "hello\x07world",
    "backslash_quote": 'hello\\\"world',
}
for label, string in samples.items:
    print(f"--- sample={label} repr={string!r}")
    for impl in ("original", "json"):
        esc = (
            escape_toml_basic_original(string)
            if impl == "original"
            else escape_toml_basic_json(string)
        )
        print(f"{impl}: output={esc!r}")
    try:
        if label == "control_bell":
            parsed = ast.literal_eval('"hello\\x07world"')
        else:
            parsed = ast.literal_eval(f'"{esc}"')
        print("parse_python_basic_string: OK=", parsed == string)
    except Exception as exc:
        print("parse_python_basic_string: ERR", type(exc).__name__, str(exc).splitlines()[0])

print("--- pyproject package version ---")
import tomllib
print(tomllib.loads('python_requires = "\n"' if '\n' in 'python_requires = "\n"' else 'hello'), "placeholder")

try:
    import tomllib
except Exception as e:
    print("tomllib unavailable:", e)
else:
    for label, string in samples.items():
        esc = escape_toml_basic_original(string)
        source = f'description = "{esc}"'
        try:
            print("tomllib original:", label, "OK=", tomllib.loads(source)["description"] == string)
        except Exception as exc:
            print("tomllib original:", label, type(exc).__name__, str(exc).splitlines()[0])
        esc = escape_toml_basic_json(string)
        source = f'description = "{esc}"'
        try:
            print("tomllib json:", label, "OK=", tomllib.loads(source)["description"] == string)
        except Exception as exc:
            print("tomllib json:", label, type(exc).__name__, str(exc).splitlines()[0])
PY

Repository: wshobson/agents

Length of output: 290


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from __future__ import annotations
import ast
import json
import importlib.util
import sys

def escape_toml_basic_original(s):
    return s.replace("\\", "\\\\").replace('"', '\\"')

def escape_toml_basic_json(s):
    return json.dumps(s, ensure_ascii=False)[1:-1]

samples = {
    "newline": "hello\nworld",
    "control_bell": "hello\x07world",
    "backslash_quote": 'hello\\\"world',
}
for label, string in samples.items():
    print(f"--- sample={label} repr={string!r}")
    for impl in ("original", "json"):
        esc = escape_toml_basic_original(string) if impl == "original" else escape_toml_basic_json(string)
        print(f"{impl}: {esc!r}")

    parsed = ast.literal_eval('"' + escape_toml_basic_json(string) + '"')
    print(f"parse_json_escaped_python_basic_string: {parsed == string}")

if sys.version_info >= (3, 11):
    import tomllib
    print("--- Python version", sys.version_info)
    for label, string in samples.items():
        esc = escape_toml_basic_original(string)
        try:
            out = tomllib.loads(f'description = "{esc}"')["description"]
            print("tomllib original", label, "OK", out == string)
        except Exception as exc:
            print("tomllib original", label, type(exc).__name__, str(exc).split(maxsplit=2)[0])
        esc = escape_toml_basic_json(string)
        try:
            out = tomllib.loads(f'description = "{esc}"')["description"]
            print("tomllib json", label, "OK", out == string)
        except Exception as exc:
            print("tomllib json", label, type(exc).__name__, str(exc).split(maxsplit=2)[0])

spec = importlib.util.find_spec("tools.adapters.toml_utils")
print("spec", spec.origin if spec else None)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
line = mod.escape_toml_basic("hello\nworld")
print("module newline escaped:", line, "contains newline?", "\n" in line)
PY

Repository: wshobson/agents

Length of output: 689


Escape additional TOML basic-string control characters.

escape_toml_basic only escapes backslash and quotes, but toml_kv still emits basic strings containing control characters like \n or \u0007. Use a full TOML/basic-string escape for both single-line and triple-quoted values, e.g. via json.dumps(...) minus the outer quotes where appropriate, instead of only the literal escapes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/adapters/toml_utils.py` around lines 6 - 8, Update escape_toml_basic to
use complete TOML basic-string escaping, including control characters such as
newlines and other non-printable characters, rather than only backslashes and
quotes. Ensure the escaped result is reusable by toml_kv for both single-line
and triple-quoted basic values while preserving the expected omission of outer
quotes.

Comment thread tools/generate.py
Comment on lines +120 to +148
def _harness_output_dirs(harness_id: str, output_root: Path) -> list[Path]:
"""Return directories whose files are adapter-generated (for pruning)."""
dirs: list[Path] = []
if harness_id == "codex":
d = output_root / ".codex"
if d.is_dir():
# All files (TOMLs, SKILL.md, references/details.md, _overflow.md, binary
# references mirrored verbatim) — anything the adapter wrote should be in
# the `written` set; anything else under .codex/ is orphaned.
candidates.extend(p for p in d.rglob("*") if p.is_file())
dirs.append(d)
elif harness_id == "opencode":
d = output_root / ".opencode"
if d.is_dir():
candidates.extend(p for p in d.rglob("*") if p.is_file())
dirs.append(d)
elif harness_id == "gemini":
for sub in ("commands", "agents", "skills"):
d = output_root / sub
if d.is_dir():
candidates.extend(p for p in d.rglob("*") if p.is_file())
dirs.append(d)
elif harness_id == "copilot":
for sub in ("agents", "skills"):
for sub in ("agents", "skills", "commands"):
d = output_root / ".copilot" / sub
if d.is_dir():
candidates.extend(p for p in d.rglob("*") if p.is_file())
d = output_root / ".copilot" / "commands"
if d.is_dir():
candidates.extend(p for p in d.rglob("*") if p.is_file())
dirs.append(d)
elif harness_id == "cursor":
# Both .cursor-plugin/plugins/*.json and .cursor/rules/*.mdc are adapter outputs.
for sub_path in (
output_root / ".cursor-plugin" / "plugins",
output_root / ".cursor" / "rules",
):
if sub_path.is_dir():
candidates.extend(p for p in sub_path.rglob("*") if p.is_file())
dirs.append(sub_path)
return dirs

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Include root-level generated manifests in prune candidates.

Cursor writes .cursor-plugin/marketplace.json and, when plugins exist, .cursor-plugin/plugin.json, but this helper only scans child directories. When the last plugin disappears, the stale plugin.json is never removed. Include .cursor-plugin itself (and the analogous root-level generated files for other harnesses) in the prune set.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/generate.py` around lines 120 - 148, The _harness_output_dirs helper
only returns generated child directories, so root-level manifests remain stale
during pruning. Update each harness branch, especially cursor’s .cursor-plugin
handling, to include the appropriate generated root directory in the prune
candidates alongside existing child directories, covering
marketplace.json/plugin.json and analogous root-level manifests without removing
unrelated files.

Comment on lines +371 to +373
def _round_color(rgb: tuple, bucket_size: int = 32) -> tuple:
"""Round an RGB tuple to the nearest bucket for color clustering."""
return tuple((c // bucket_size) * bucket_size for c in rgb)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use parameterized tuple annotations.

Replace bare tuple annotations with the concrete RGB shape to comply with the project’s Python typing requirements.

Proposed fix
-def _round_color(rgb: tuple, bucket_size: int = 32) -> tuple:
+def _round_color(
+    rgb: tuple[int, int, int], bucket_size: int = 32
+) -> tuple[int, int, int]:

As per coding guidelines, Python code should use modern parameterized built-in types.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _round_color(rgb: tuple, bucket_size: int = 32) -> tuple:
"""Round an RGB tuple to the nearest bucket for color clustering."""
return tuple((c // bucket_size) * bucket_size for c in rgb)
def _round_color(
rgb: tuple[int, int, int], bucket_size: int = 32
) -> tuple[int, int, int]:
"""Round an RGB tuple to the nearest bucket for color clustering."""
return tuple((c // bucket_size) * bucket_size for c in rgb)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/yt-design-extractor/yt-design-extractor.py` around lines 371 - 373,
Update the _round_color function’s type annotations to use parameterized
built-in tuple types representing an RGB tuple, including the return annotation,
while preserving its rounding behavior and bucket_size parameter.

Source: Coding guidelines

@wshobson

Copy link
Copy Markdown
Owner

Keeping this open, but it cannot merge as written: the refactored strip_claude_tool_refs changes output, contradicting the 'no behavioral changes' claim. The pre-compiled patterns drop the backticks around replacements and ignore tool_case — "the Read tool" now becomes open instead of open, and Read becomes open instead of read. This path feeds Copilot command emission, and existing tests cover it (tools/tests/test_adapters.py:1036); run the full suite (make test), not just py_compile. The toml_utils.py extraction is the one piece worth keeping — consider trimming the PR to that.

@wshobson

Copy link
Copy Markdown
Owner

Closing this, for two reasons.

The first is that "no behavioral changes" doesn't hold. strip_claude_tool_refs comes out different in three ways: the replacements lose their surrounding backticks, tool_case="normal" now returns the lower-case verbs because the patterns are frozen at import time and only the first tuple slot is ever used, and `Grep` maps to rg instead of `grep`. Running both versions on the same input:

input    : Use the `Read` tool first, then the Bash tool. Prefer `Grep` over `Glob`.
main     : Use `open` first, then `shell`. Prefer `grep` over `glob`.
this PR  : Use open first, then shell. Prefer rg over glob.

Nothing caught it because that function has no test coverage. Its only caller is copilot.py, so Copilot artifacts are what would have quietly degraded.

The second is that the PR edits tools/adapters/gemini.py, which was deleted in 367cb6a when the Gemini CLI harness was replaced by Antigravity. That's most of why it's conflicting rather than just stale.

The _round_color hoist and the toml_utils.py extraction are both fine and I'd take them. If you want to redo this against current main, scoped to the mechanical wins, with characterization tests for strip_claude_tool_refs written first so any output change shows up, I'll review it.

@wshobson wshobson closed this Aug 22, 2026
wshobson added a commit that referenced this pull request Aug 23, 2026
…sts (#676)

* feat(garden): detect stale doc counts and diverged agent copies

Two checks close gaps that kept surfacing in PR review.

check_doc_counts compares the plugin/agent/skill/command totals quoted in
README.md and AGENTS.md against the live counts, at error severity. Only the
two canonical context files are scanned, because docs/ carries per-category
subtotals that legitimately differ. Plugins count marketplace entries rather
than plugins/ directories, so external git-subdir entries are included the way
the headline figure counts them. Four manual sync PRs (#522, #613, #615, #616)
existed because nothing caught this.

check_agent_divergence groups agent files by filename and compares bodies with
the plugin-namespaced frontmatter name normalized away. Without that
normalization no two copies can ever hash alike, which is why #643 read the
duplication as total divergence. Of 30 duplicated names, 19 are verbatim copies
and 11 have genuinely drifted. Verbatim copies are expected while plugins
install standalone, so they report as info; drifted bodies report as warning.

* test(adapters): pin strip_claude_tool_refs output

The method rewrites Claude tool names in Copilot command bodies and had no test
coverage, so a refactor could change its output silently. #642 did exactly that
while claiming no behavioral change: replacements lost their backticks,
tool_case=normal stopped returning 'read', and a bare `Grep` mapped to rg
instead of `grep`.

These assert the exact output for both tool_case values, both prose forms, and
every mapped tool.

* docs(contributing): rule out payment and access-control tooling in payloads

The commercial section covered funnels to paid products but not a payload that
sells something itself. #670 shipped a Telegram sales bot, USDT payment
verification, and a script granting GitHub collaborator access on payment.

* fix(garden): widen count matching and stop reporting verbatim agent copies

Review feedback on PR #676.

COUNT_RE required two digits, so a drop to single-digit totals would go
unnoticed. It now matches any decimal. It also missed `202 subagents` in the
cross-harness section of AGENTS.md, which is the same total under a different
name, so `subagents` is now an alias for the agent count.

check_agent_divergence no longer reports verbatim copies. A copy that matches
byte for byte once the namespaced name is normalized is expected, not drift,
and 19 info findings only added noise. The divergence warning still fires when
bodies actually differ.

* docs(contributing): distinguish payment machinery from payment guidance

The first wording banned 'payment processing ... tooling in a plugin payload',
which reads as barring the existing payment-processing plugin. That plugin is
Markdown-only guidance for building Stripe and PayPal integrations in the user's
own application, which was never the target.

The rule now turns on whether the payload runs a commercial transaction itself,
and names payment-processing as the reference example of what stays allowed.

* test(adapters): pin every tool mapping in both tool_case modes

Review nitpick on PR #676. The mapping loop ran only the default case. That
default is already `lower`, so the lower path was covered, but the assertion
did not say so and normal mode was pinned for Read alone.

The loop now asserts both modes for all nine tools, and a separate test pins
that the default is lower, which is what Copilot emission relies on.

* fix(garden): scope agent name normalization to the frontmatter block

Review feedback on PR #676. The substitution used a MULTILINE pattern with
count=1, which lands on the frontmatter name in every agent the repo has today
but would blank a body `name:` line in an agent whose frontmatter lacked one.

Normalization is now scoped to the opening frontmatter block, so a `name:` in
the body stays content and still counts toward a divergence. Three tests cover
differing body names, matching body names, and a file with no frontmatter.

No change to current output: still 11 divergent, 0 verbatim reported.

* fix(garden): match singular component nouns in doc counts

Review feedback on PR #676. COUNT_RE only matched plurals, so a total of one
written as `1 plugin` would not have been compared against anything.

Singular forms now resolve to the same key. Neither README.md nor AGENTS.md
contains a singular count today, so the live result is unchanged and the counts
check stays silent.

* fix(garden): treat an unreadable marketplace as an unknown plugin count

Review feedback on PR #676. A JSON syntax error in marketplace.json set the
plugin count to 0, so check_doc_counts flagged every documented plugin count as
stale and told the reader to write 0. The real parse error was reported once by
check_marketplace_consistency and buried under the noise.

The count is now None when the manifest is missing or unparseable, and the
comparison skips it. Other component counts are still checked.

* fix(garden): handle CRLF frontmatter and malformed marketplace shapes

Review feedback on PR #676, both confirmed by running them.

AGENT_FRONTMATTER_RE required LF delimiters and a newline after the closing
---, so a CRLF agent or one ending at its frontmatter got no normalization at
all and two copies read as divergent. Scoping normalization to the frontmatter
block in 4798d40 introduced that: the MULTILINE pattern it replaced matched
CRLF fine. The pattern now accepts \r?\n and a closing delimiter at EOF.

actual_counts() also assumed the manifest parsed to a mapping with a list under
plugins. A root of [] raised AttributeError and {"plugins": null} raised
TypeError, crashing the gardener rather than reporting an unknown count. The
shape is now checked before len().

Four regression tests. No repo agent uses CRLF today, so live output is
unchanged at 11 divergent.

* refactor(garden): compare agents through the shared frontmatter parser

Review rounds four and seven were both about my own frontmatter regex being
stricter than the files it reads. Rather than widen it a third time, agent
comparison now goes through parse_frontmatter, the same parser the adapters use,
and drops the plugin-namespaced name field.

A copy is judged on its frontmatter fields and body, so delimiter formatting no
longer decides drift. Verified locally across 16 input shapes: CRLF, BOM,
leading blank line, trailing space after a delimiter, closing --- at EOF, no
trailing newline, block scalars and inline lists all compare equal when only the
name differs, while body text, model tier, an added field, a differing body
name: line and files with no frontmatter still register as drift.

Real-repo output is unchanged: 11 divergent, 19 verbatim, same names and counts.

* fix(garden): read a thousands separator as one number

Found by a local battery over check_doc_counts rather than by review. COUNT_RE
matched bare digit runs, so `1,234 agents` matched the `234` and reported a
stale count of 234 at error severity. A comma-formatted total anywhere in
README.md or AGENTS.md would have failed CI with wrong advice.

The pattern now takes the whole number and strips separators before comparing,
so 1,234 reads as 1234 and is checked properly rather than skipped.

Also pinned that counts inside code fences are checked, because README.md
quotes the plugin total inside a bash fence.

* fix(garden): survive an unreadable file instead of killing the run

Pre-existing across the module, not new to this PR. Five of the seven checks
died with UnicodeDecodeError on a single non-UTF-8 file, and
check_oversized_context_files read without an encoding at all. One bad file took
down every other check's output with it.

All reads now go through read_text_or_none, which reports UNREADABLE_FILE
against that path and lets the rest of the run finish. actual_counts has no
Report to write to, so an unreadable manifest joins a malformed one as an
unknown count. Also drops the unused frontmatter binding in
check_codex_skill_caps.

Real-repo output is unchanged.

* fix(garden): keep body indentation, report an unreadable manifest, drop dead guard

Four review findings on PR #676, all confirmed by running them.

normalized_agent_text used body.strip(), so an indented body compared equal to
the same text unindented and real drift went unreported. Leading whitespace is
content in Markdown; only trailing whitespace is formatting. Now rstrip.

actual_counts read the manifest directly, so a non-UTF-8 marketplace.json
quietly became an unknown plugin count with no UNREADABLE_FILE finding. It now
takes the Report and reads through read_text_or_none like everything else.

check_dead_links kept a try/except OSError around the new reader, which already
catches OSError and returns None. Dead code, removed.

CONTRIBUTING's closing sentence narrowed the payment rule to running a
transaction, which would have permitted a tool that consumes an external payment
result and only flips access. Verification, entitlement checks and access
changes are now each covered on their own.

Battery re-run at 18 cases, all pass. Real-repo output unchanged at 11 divergent.

* fix(garden): keep indentation without frontmatter, reject malformed manifest entries

Three findings on PR #676, all reproduced first.

normalized_agent_text stripped leading whitespace before deciding whether
frontmatter existed, so two frontmatter-free agents differing only by
indentation compared equal. Blank lines ahead of a frontmatter block are
formatting; ahead of anything else they are body content. Same mistake as the
body.strip() fix in the previous commit, one level up.

A plugins list holding a non-object entry was counted as valid, letting garbage
drive an error-severity stale-count finding. The count is unknown unless every
entry is an object.

check_marketplace_consistency then crashed outright on that input with
AttributeError, and on a non-object root as well. Both now report
MARKETPLACE_SHAPE and carry on. That crash predates this PR.

* fix(garden): keep ty clean after the manifest shape guard

The isinstance narrowing added in aaf76f6 turned the entry from Any into
dict[Unknown, Unknown], so .get("name") failed with invalid-argument-type. Two
ty errors, which I pushed without reading the output. The entry is cast once
after the guard.

make lint is clean: ruff check, ruff format --check and ty all pass.

* fix(garden): match CRLF against LF, validate name, test the real Copilot path

Three findings on PR #676.

parse_frontmatter strips a leading newline but leaves the carriage return, so a
CRLF copy never matched its LF twin and reported false drift. My own CRLF test
missed it because it compared CRLF against CRLF, which passes without
normalizing anything. Body line endings are normalized now, newlines stripped
but never spaces so indentation stays content, and the test mixes the two
endings. A second test proves normalizing does not flatten real drift.

check_marketplace_consistency added entry['name'] to a set without checking its
type, so a list-valued name raised TypeError. It now reports MARKETPLACE_SHAPE.

test_lower_is_the_default_tool_case only protected the method default, while
Copilot's two call sites pass tool_case explicitly, so generated commands could
regress with the test green. Replaced with one that emits a command through
CopilotAdapter and asserts the rewritten body.

* fix(garden): strip closing-delimiter residue, assert Copilot output per file

Two findings on PR #676.

parse_frontmatter leaves the spaces from a `--- ` closing line at the head of
the body, so an agent whose closing delimiter carried a trailing space never
matched its clean twin. My earlier trailing-space test put the space on the
opening delimiter, which parse_frontmatter already tolerates, so it proved
nothing about this. Leading whitespace-only lines are now dropped as delimiter
residue while a line that starts with spaces then real text keeps its
indentation.

The Copilot integration test joined every emitted file, so one emitter could
regress to `read` while the other's `open` satisfied the assertion. It now
reads each command artifact separately and rejects `read`. Scoping that
exposed a second problem with my own test: it had asserted over every emitted
markdown file including the plugin index, which carries no command body and only
passed because the join diluted it.

* refactor(garden): one entry rule for both marketplace readers

Review feedback on PR #676. actual_counts counted {"name": ["bad"]} because it
is a dictionary, while check_marketplace_consistency rejected the same entry as
MARKETPLACE_SHAPE. A counts-only run could report a stale total from a manifest
the other check calls invalid.

Rather than copy the name rule into the second place, both now call
marketplace_entry_problem, which returns why an entry is unusable or None. That
also collapses the two near-identical report blocks in the consistency check
into one.

Parametrized coverage of the rule itself, plus a case proving a list-valued name
leaves the count unknown.

* style(tests): sort the doc_gardener test imports

I001 from adding marketplace_entry_problem to the import block in e7bd51c. I
pushed that commit without reading the ruff output, for the second time in this
review. Adding a pre-push habit of running make lint rather than eyeballing it.

* fix(garden): canonicalize nested frontmatter before hashing

Review feedback on PR #676. parse_frontmatter supports one-level mappings, and
repr preserves insertion order, so two agents whose metadata block listed the
same keys in a different order hashed differently and reported false drift. Only
the top-level keys were sorted.

Mapping keys are now sorted recursively. List order is left alone because it is
meaningful: reordering tools: [Read, Write] is a real change, and three tests
pin that distinction alongside a changed nested value still counting as drift.

No agent in the repo uses nested frontmatter today, so live output is unchanged
at 11 divergent. Skills do use it, and agents are free to.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants