Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
feat: lean CLAUDE.md by default + standalone variant for contributors (#923)
Louis Choquele3ed1f3207aa
diff --git a/AGENTS.md b/AGENTS.mdindex 5d69bf0dc..90920783e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -358,22 +358,3 @@ We use Material for MkDocs. All markdown in our docs must be compatible with Mat### MkDocs Markdown Requirements- Always add a blank line before any bullet lists or numbered lists in MkDocs markdown.--## Test-Driven Development Guide--This document outlines our test-driven development (TDD) process and the tools available for testing.--### TDD Cycle--1. **Write a Test First**--2. **Write the Code**- - Implement the minimum amount of code needed to pass the test- - Follow the project's coding standards- - Keep it simple - don't write more than needed--3. **Run Linting and Type Checking**--4. **Validate tests**--Remember: The key to TDD is writing the test first and letting it drive your implementation. Then, always run the full test suite and quality checks before considering a feature complete.diff --git a/CLAUDE.md b/CLAUDE.mdindex 645eace77..b0e1b0f01 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -137,174 +137,6 @@.venv/bin/pipelex-dev refresh-graph-ui-sri --mthds-ui-version 0.6.3 --elkjs-version 0.11.1```-## Coding Standards & Best Practices for Python Code--This document outlines the core coding standards, best practices, and quality control procedures for the codebase.--### Python Version Compatibility-- - The project supports Python 3.10+ (`requires-python = ">=3.10,<3.15"`). Never use features introduced after Python 3.10 without a compatibility fallback.- - Common pitfalls:- - `datetime.UTC` was added in Python 3.11. Use `datetime.timezone.utc` instead.- - `StrEnum` was added in Python 3.11. Always import it from `pipelex.types` which handles retrocompatibility.- - `type` statement (PEP 695) was added in Python 3.12. Use `TypeAlias` from `typing` instead.- - `ExceptionGroup` / `except*` was added in Python 3.11. Avoid unless using the `exceptiongroup` backport.--### Variables, loops and indexes-- - Variable names should have a minimum length of 3 characters. No exceptions: name your `for` loop indexes like `index_foobar`, your exceptions `exc` or more specific like `validation_error` when there are several layers of exceptions, and use `for key, value in ...` for key/value pairs.- - When looping on the keys of a dict, use `for key in the_dict` rather than `for key in the_dict.keys()` otherwise you won't pass linting.- - Avoid inline for loops, unless it's ultra-simple and holds on oneline.- - If you have a variable that will get its value differently through different code paths, declare it first with a type, e.g. `pipe_code: str` but DO NOT give it a default value like `pipe_code: str = ""` unless it's really justified. We want the variable to be unbound until all paths are covered, and the linters will help us avoid bugs this way.--### Enums and tests-- - When defining enums related to string values, always inherit from `StrEnum`- - When you need the enum value as a string, don't use `str(enum_var)` or `enum_var.value`, just use `enum_var` itself, that is the point of using StrEnum!- - Never test equality to an enum value: use match/case, even to single out 1 case out of 10 cases. To avoid heavy match/case code in awkward places, add @property methods to the enum class such as `is_foobar()`. This is to avoid bugs: when new enum values are added we want the linter to complain. Use the `|` operator to group cases- - As our match/case constructs over enums are always exhaustive, NEVER add a default `case _: ...`. Otherwise, you won't pass linting.- - `StrEnum` must be imported from `pipelex.types` (handles python retrocompatibility):- ```python- from pipelex.types import StrEnum- ```--### Optionals--- Don't write things like `a = b if b else c`, write `a = b or c` instead.--### Imports--#### **Imports at the top of the file**-- - Avoid as much as possible import statements outside of a module's top-level scope.- - Do not import libraries in functions or classes unless in very specific cases, to be discussed with the user, as they would required a `# noqa: ...` comment to pass linting- - Do not bother with ordering the imports or removing unused imports, our Ruff linter will handle it for us.- - `if TYPE_CHECKING:` blocks must always be the **last** block in the imports section, placed after all regular imports.--#### **Removing unused imports**-- - To remove unused imports, run `make fix-unused-imports` or `make fui` (shorthand). This is faster and cheaper than rewriting with LLM.--#### **No re-exports in `__init__.py`**-- - Do NOT fill `__init__.py` files with re-exports.- - Always use direct full-path imports everywhere. For example:--- **Logging and Pretty Printing**:-- - Both `log()` and `pretty_print()` can be imported from `pipelex` directly:- ```python- from pipelex import log, pretty_print-- log.info("Hello, world!")- ```- - Both have a title arg which is handy when logging/printing objects:-- ```python- log.verbose("Hello, world!", title="Your first Pipelex log")- pretty_print(output_object, title="Your first Pipelex output")- ```- - Both handle formatting json using Rich, pretty_print makes it prettier.--- **StrEnum and Self type**:-- - Both `StrEnum` and `Self` must be imported from `pipelex.types` (handles python retrocompatibility):- ```python- from pipelex.types import Self, StrEnum- ```--### Typing--#### **Always Use Type Hints**-- - Every function parameter must be typed- - Every function return must be typed- - Use type hints for all variables where type is not obvious- - Use dict, list, tuple types with lowercase first letter: dict[], list[], tuple[]- - Use type hints for all fields- - Use Field(default_factory=...) for mutable defaults- - Use `# pyright: ignore[specificError]` or `# type: ignore` only as a last resort. In particular, if you are sure about the type, you often solve issues by using cast() or creating a new typed variable.--#### **BaseModel / Pydantic Standards**-- - Use `BaseModel` and respect Pydantic v2 standards- - Use the modern `ConfigDict` when needed, e.g. `model_config = ConfigDict(extra="forbid", strict=True)`- - Keep models focused and single-purpose- - For list fields with non-string items in BaseModels, use `empty_list_factory_of()` to avoid linter complaints:- ```python- from pydantic import BaseModel, Field- from pipelex.tools.typing.pydantic_utils import empty_list_factory_of-- class MyModel(BaseModel):- names: list[str] = Field(default_factory=list) # OK for strings- numbers: list[int] = Field(default_factory=empty_list_factory_of(int), description="A list of numbers")- items: list[MyItem] = Field(default_factory=empty_list_factory_of(MyItem), description="A list of items")- ```--### Factory Pattern-- - Use factory pattern for object creation when dealing with multiple implementations- - Our factory methods are named `make_from_...` and such--### Protocols and Interfaces-- - When a getter (e.g. `get_report_delegate()`, `get_library_manager()`) returns a `Protocol` type, callers must only rely on methods declared on that `Protocol`. If you need to call a method that lives on a concrete implementation, **extend the `Protocol`** — do not work around it with `isinstance(...)` checks, `cast(...)`, or inline imports of the concrete class.- - When extending the `Protocol`, also update every implementation (including no-op / null implementations) so structural typing is satisfied. For implementations where the method has nothing to do, give it a `pass` body — that is the whole point of having a `Protocol` rather than a concrete base class.- - Smell to watch for: an inline `from ... import ConcreteImpl # noqa: PLC0415` followed by `if isinstance(delegate, ConcreteImpl): delegate.some_method(...)`. This is almost always a missing method on the `Protocol`. Promote it.- - Use `@override` (from `typing_extensions`) on every implementation of a `Protocol` method, so that signature drift between the `Protocol` and its implementations is caught by the type checker.--### Error Handling-- - Always catch exceptions at the place where you can add useful context to it.- - Use try/except blocks with specific exceptions- - Convert third-party exceptions to our custom ones except in pydantic validators where you can raise a ValueError or a TypeError- - **NEVER write `except Exception:` (or bare `except:`).** Catching the generic `Exception` is FORBIDDEN except in two cases, each of which REQUIRES a one-line comment directly under the `except` naming which case applies: **(1)** the absolute root of a CLI command or an API endpoint handler; **(2)** the wrapped call invokes genuinely unbounded code whose exception surface cannot be enumerated — a user-registered callback or function, dynamic plugin dispatch, or a third-party SDK with no documented exception types (this is only for genuinely open-ended surfaces; "I didn't look the exceptions up" does NOT qualify). There are NO other exceptions to this rule. The following are NOT valid justifications and the agent must reject them when tempted:- - "I want to log and re-raise" → just let it propagate; logging happens at the root.- - "I want to swallow it just in case" → don't. Unknown failures must surface.- - "I want to convert it to our error type" → only if you know which specific exception(s) the call can raise; catch those explicitly. Catching a project base class (`PipelexError`) or a package base (`CogtError`, `ToolError`) is acceptable when the operation legitimately fails in many domain-specific ways — that is still specific. Catching `Exception` is not.- - "The third-party lib isn't well typed" → look up the actual exceptions it raises and catch those by name.- - "It's safer this way" → it isn't. It hides bugs. Crashing loudly on an unexpected exception is the desired behavior.- If you find yourself writing `except Exception` outside the two cases above, STOP and ask the user before proceeding.- - **Do NOT add try/except speculatively.** Only add a `try`/`except` when (a) a specific exception type is documented or known to be raised by the call, AND (b) you have a concrete recovery path or a meaningful context to attach. Otherwise, let the error bubble up — that is the correct behavior, not a gap to fill.- - **Use `try`/`finally` (without `except`) for required cleanup.** When a piece of code MUST run on the way out — releasing a resource, closing a tracer, tearing down a library, clearing per-context state on a manager — put it in a `finally` block (or a `with`/context manager). This is the correct way to guarantee cleanup on both the happy path and the error path: it does NOT suppress the exception, it just ensures cleanup happens before the exception propagates. Do not invent an `except Exception` just to attach cleanup; use `finally` instead. Conversely, do not move cleanup into the success path "to keep things simple" — if it must run on errors too, it belongs in `finally`.- - When reviewing existing code, treat any `except Exception` you encounter as a bug to fix (replace it with the specific exception(s) actually raised, or remove the try/except entirely), not as a precedent to follow.- - Always add `from exc` to the exception raise statements- - Always write the error message as a variable before raising it, for cleaner error traces-- ```python- try:- self.models_manager.setup()- except RoutingProfileLibraryNotFoundError as exc:- msg = "The routing library could not be found, please call `pipelex init config` to create it"- raise PipelexSetupError(msg) from exc- ```--### Documentation--1. **Docstring Format**- ```python- def process_image(image_path: str, size: tuple[int, int]) -> bytes:- """Process and resize an image.-- Args:- image_path: Path to the source image- size: Tuple of (width, height) for resizing-- Returns:- Processed image as bytes- """- pass- ```--2. **Class Documentation**- ```python- class ImageProcessor:- """Handles image processing operations.-- Provides methods for resizing, converting, and optimizing images.- """- ```-## Standards related to developing the Pipelex codebase### Spec vs Blueprint Architecture@@ -324,88 +156,6 @@ When adding validation or fields, decide which layer they belong to. Language ru- If (and only if) you add some config that will clearly make sense for client projects to override, for instance if it's a case of user preference, then you can also add a copy of the settings to the project override config file `.pipelex/pipelex.toml`. NEVER add them commented out: commented-out TOML is never parsed or validated, so it rots silently when keys are refactored. Instead, write the actual default values (matching `pipelex/pipelex.toml`, even empty ones like `activity_queues = {}`) so the override file stays valid and behaves like setting nothing. Plain prose comments explaining the setting are fine — it's commented-out keys/values that are forbidden.- The different `pipelex.toml` files and the python model `configs.py` must be up to date with each other in terms of structure and attributes, otherwise the loading of teh config fails. To check quickly that you're good, just run `make tb` which tests the boot sequence, which includes the config loading.-## Writing tests--### Unit test generalities--NEVER USE unittest.mock. Instead YOU MUST USE pytest-mock: `from pytest_mock import MockerFixture`.-NEVER EVER put more than one TestClass into a test module.--#### Test file structure--- Name test files with `test_` prefix-- Place test files in the appropriate test category directory:- - `tests/unit/` - for unit tests that test individual functions/classes in isolation- - `tests/integration/` - for integration tests that test component interactions- - `tests/e2e/` - for end-to-end tests that test complete methods-- Do NOT add `__init__.py` files to test directories. Test directories do not need to be Python packages.-- Fixtures are defined in conftest.py modules at different levels of the hierarchy, their scope is handled by pytest-- Test data is placed inside test_data.py at different levels of the hierarchy, they must be imported with package paths from the root like `from tests.integration.pipelex.cogt.test_data`. Their content is all constants, regrouped inside classes to keep things tidy.-- Always put tests inside Test classes: 1 TestClass per module.-- NEVER EVER put more than one TestClass into a test module.-- Put fixtures into conftest.py files for easy sharing.--#### Markers--Apply the appropriate markers:-- "gha_disabled: will not be able to run properly on GitHub Actions"-- "llm: uses an LLM to generate text or objects"-- "img_gen: uses an image generation AI"-- "extract: uses text/image extraction from documents"-- "inference: uses either an LLM or an image generation AI"-- never add "@pytest.mark.dry_runnable" if you haven't set the "inference" marker--Several markers may be applied. For instance, if the test uses an LLM, then it uses inference, so you must mark with both `inference`and `llm`.--#### Important rules--- Never use the unittest.mock. Use pytest-mock.--#### Test Class Structure--- Always group the tests of a module into a test class:--```python[email protected](loop_scope="class")-class TestFooBar:- @pytest.mark.parametrize(- "topic, test_case_blueprint",- [- TestCases.CASE_1,- TestCases.CASE_2,- ],- )- async def test_pipe_processing(- self,- request: FixtureRequest,- topic: str,- test_case_blueprint: StuffBlueprint,- ):- # Test implementation-```--- Never more than 1 class per test module.-- When testing one method, if possible, limit the number of test functions, but with different test cases in parameters--#### Test Data Organization--- If it's not already there, create a `test_data.py` file in the proper test directory-- Note how we avoid initializing a default mutable value within a class instance, instead we use ClassVar.-- Also note that we provide a topic for the test case, which is purely for convenience.--### Best Practices for Testing--- Use strong asserts: test value, not just type and presence.-- Use parametrize for multiple test cases-- Test both success and failure cases-- Verify working memory state-- Check output structure and content-- Use meaningful test case names-- Include concise docstrings explaining test purpose but not on top of the file and not on top of the class.-- Log outputs for debugging-## Writing DocsWe use Material for MkDocs. All markdown in our docs must be compatible with Material for MkDocs and done using best practices to get the best results with Material for MkDocs.@@ -413,22 +163,3 @@ We use Material for MkDocs. All markdown in our docs must be compatible with Mat### MkDocs Markdown Requirements- Always add a blank line before any bullet lists or numbered lists in MkDocs markdown.--## Test-Driven Development Guide--This document outlines our test-driven development (TDD) process and the tools available for testing.--### TDD Cycle--1. **Write a Test First**--2. **Write the Code**- - Implement the minimum amount of code needed to pass the test- - Follow the project's coding standards- - Keep it simple - don't write more than needed--3. **Run Linting and Type Checking**--4. **Validate tests**--Remember: The key to TDD is writing the test first and letting it drive your implementation. Then, always run the full test suite and quality checks before considering a feature complete.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 06d4ff1b2..7a680801e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -72,6 +72,18 @@ We are open to contributions in all areas of our core Pipelex library:- Fill in required credentials (OPENAI_API_KEY, AWS_ACCESS_KEY_ID, etc.)- Never commit `.env`+## SWE Agent Rules++`CLAUDE.md` and `AGENTS.md` are regenerated from `pipelex/kit/agent_rules/` via `make rules`. The committed `CLAUDE.md` is **lean**: it omits the Python and pytest standards, which Pipelex maintainers get from their multi-repo workspace's `.claude/rules/` directory. `AGENTS.md` keeps the full set inline.++If you are contributing without that workspace and want a `CLAUDE.md` that includes the Python and pytest standards inline, run once:++```bash+make rules-claude-standalone+```++That overwrites `CLAUDE.md` with the full standalone version. Do not commit this regenerated file — the lean version is canonical in git.+## License* **CLA** – The first time you open a PR, the CLA-assistant bot will guide you through signing the Contributor License Agreement. The process signature uses the [CLA assistant lite](https://github.com/marketplace/actions/cla-assistant-lite).diff --git a/Makefile b/Makefileindex 6e25f0a80..5588f38b2 100644--- a/Makefile+++ b/Makefile@@ -66,6 +66,7 @@ make plxt-format - Format MTHDS/TOML/PLX files with plxtmake plxt-lint - Lint MTHDS/TOML/PLX files with plxtmake rules - Install agent rules for contributing to Pipelex+make rules-claude-standalone - Install a standalone CLAUDE.md (full ruleset, for contributors without the Pipelex workspace)make up-kit-configs - Update kit configs from .pipelex/make ukc - Shorthand -> up-kit-configsmake check-config-sync - Verify .pipelex and pipelex/kit/configs are in sync@@ -175,7 +176,7 @@ export HELP.PHONY: \all help env env-verbose check-uv check-uv-verbose lock install update build \format lint ruff-format ruff-lint pyright mypy pylint plxt plxt-format plxt-lint \- rules up-kit-configs ukc check-config-sync ccs check-rules check-urls cu insert-skeleton \+ rules rules-claude-standalone up-kit-configs ukc check-config-sync ccs check-rules check-urls cu insert-skeleton \cleanderived cleanenv cleanall \test test-xdist t test-quiet tq test-with-prints tp test-inference ti \test-llm tl test-img-gen tg test-extract te test-temporal ttm codex-tests gha-tests \@@ -277,6 +278,10 @@ rules: env$(call PRINT_TITLE,"Installing agent rules for contributing to Pipelex")$(VENV_PIPELEX_DEV) kit rules --set all+rules-claude-standalone: env+ $(call PRINT_TITLE,"Installing standalone CLAUDE.md with the full ruleset for contributors without the Pipelex workspace")+ $(VENV_PIPELEX_DEV) kit rules --set standalone --targets claude+check-rules: env$(call PRINT_TITLE,"Checking installed agent rules against templates")$(VENV_PIPELEX_DEV) check-rules --quietdiff --git a/pipelex/cli/dev_cli/commands/kit_cmd.py b/pipelex/cli/dev_cli/commands/kit_cmd.pyindex b223a7030..c0ee9a09a 100644--- a/pipelex/cli/dev_cli/commands/kit_cmd.py+++ b/pipelex/cli/dev_cli/commands/kit_cmd.py@@ -33,6 +33,7 @@ def _sync_agent_rules(agent_set: str | None,cleanup: bool,kit_index: KitIndex | None = None,+ targets_filter: list[AgentTarget] | None = None,) -> None:resolved_repo_root = repo_root if repo_root is not None else Path()loaded_kit_index = load_index() if kit_index is None else kit_index@@ -41,15 +42,24 @@ def _sync_agent_rules(config = get_config()preferred_targets: list[AgentTarget] = list(config.pipelex.kit_config.preferred_agent_targets)+ if targets_filter is not None:+ unknown = [target for target in targets_filter if target not in preferred_targets]+ if unknown:+ msg = f"--targets values {unknown} are not in preferred_agent_targets {preferred_targets}"+ raise PipelexCLIError(msg)+ targets_to_update: list[AgentTarget] = [target for target in preferred_targets if target in targets_filter]+ else:+ targets_to_update = list(preferred_targets)+# The config validator guarantees CURSOR cannot coexist with other targets,# so a simple membership check is enough to pick the branch.- if AgentTarget.CURSOR in preferred_targets:+ if AgentTarget.CURSOR in targets_to_update:typer.echo("Updating Cursor rules...")update_cursor_rules(resolved_repo_root, loaded_kit_index, agent_set=agent_set)else:all_targets = loaded_kit_index.agent_rules.targetsfiltered_targets: dict[str, Target] = {}- for target_key in preferred_targets:+ for target_key in targets_to_update:if target_key not in all_targets:msg = f"Target '{target_key}' not found in index.toml"raise PipelexCLIError(msg)@@ -65,6 +75,9 @@ def _sync_agent_rules(if cleanup:typer.echo("Cleaning up rules from other targets...")+ # Cleanup keep-set must always be the full preferred_targets configured by the user,+ # NOT the --targets subset — otherwise --targets=claude --cleanup would delete AGENTS.md+ # for a user whose config still prefers both claude and agents._cleanup_other_targets(repo_root=resolved_repo_root,kit_index=loaded_kit_index,@@ -85,7 +98,7 @@ def _cleanup_other_targets(For single-file targets: deletes the files entirely"""if AgentTarget.CURSOR not in preferred_targets:- remove_cursor_rules(repo_root)+ remove_cursor_rules(repo_root, kit_index=kit_index)all_targets = kit_index.agent_rules.targetstargets_to_clean: dict[str, Target] = {target_key: target for target_key, target in all_targets.items() if target_key not in preferred_targets}@@ -102,8 +115,27 @@ def agent_rules(repo_root: Annotated[Path | None, typer.Option("--repo-root", dir_okay=True, writable=True, help="Repository root directory")] = None,agent_set: Annotated[str | None, typer.Option("--set", help="Agent rule set to sync (use 'pipelex' for Pipelex repo)")] = None,cleanup: Annotated[bool, typer.Option("--cleanup", help="Delete Pipelex rules files from other agent targets")] = False,+ targets: Annotated[+ str | None,+ typer.Option(+ "--targets",+ help="Comma-separated subset of preferred_agent_targets to update (e.g. 'claude'). Defaults to all preferred targets.",+ ),+ ] = None,) -> None:try:+ targets_filter: list[AgentTarget] | None = None+ if targets is not None:+ try:+ targets_filter = [AgentTarget(item.strip()) for item in targets.split(",") if item.strip()]+ except ValueError as exc:+ valid_targets = list(AgentTarget)+ msg = f"Invalid --targets value: {exc}. Valid targets: {valid_targets}"+ raise PipelexCLIError(msg) from exc+ if not targets_filter:+ msg = "--targets must contain at least one target when provided"+ raise PipelexCLIError(msg)+make_pipelex_for_cli(context=ErrorContext.KIT)with get_telemetry_manager().telemetry_context():tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)@@ -113,6 +145,7 @@ def agent_rules(repo_root=repo_root,agent_set=agent_set,cleanup=cleanup,+ targets_filter=targets_filter,)except (PipelexError, OSError) as exc:diff --git a/pipelex/kit/agent_rules/tdd.md b/pipelex/kit/agent_rules/tdd.mddeleted file mode 100644index a7800b1bf..000000000--- a/pipelex/kit/agent_rules/tdd.md+++ /dev/null@@ -1,19 +0,0 @@-# Test-Driven Development Guide--This document outlines our test-driven development (TDD) process and the tools available for testing.--## TDD Cycle--1. **Write a Test First**--2. **Write the Code**- - Implement the minimum amount of code needed to pass the test- - Follow the project's coding standards- - Keep it simple - don't write more than needed--3. **Run Linting and Type Checking**--4. **Validate tests**--Remember: The key to TDD is writing the test first and letting it drive your implementation. Then, always run the full test suite and quality checks before considering a feature complete.-diff --git a/pipelex/kit/cursor_rules.py b/pipelex/kit/cursor_rules.pyindex 568e04ef7..da0ecfaa2 100644--- a/pipelex/kit/cursor_rules.py+++ b/pipelex/kit/cursor_rules.py@@ -1,15 +1,21 @@from collections.abc import Iterablefrom pathlib import Path-from typing import Any+from typing import Any, castimport typerimport yamlfrom pipelex.kit.exceptions import KitError+from pipelex.kit.index_loader import load_indexfrom pipelex.kit.index_models import KitIndexfrom pipelex.kit.paths import get_kit_agents_dirfrom pipelex.types import Traversable+# Marker written into the YAML front-matter of every Pipelex-generated .mdc file so the+# cleanup path can identify and remove stale files even after their source markdown has+# been removed from `pipelex/kit/agent_rules/`.+_PIPELEX_MARKER_KEY = "pipelex_managed"+def _iter_agent_files(agents_dir: Traversable) -> Iterable[tuple[str, str]]:"""Iterate over agent markdown files.@@ -42,9 +48,32 @@ def _front_matter_for(name: str, kit_index: KitIndex) -> dict[str, Any]:# Remove globs if it's an empty listif "globs" in base and base["globs"] == []:del base["globs"]+ base[_PIPELEX_MARKER_KEY] = Truereturn base+def _is_pipelex_managed(mdc_path: Path) -> bool:+ """Return True if the .mdc file's YAML front-matter carries the Pipelex marker."""+ try:+ text = mdc_path.read_text(encoding="utf-8")+ except OSError:+ return False+ if not text.startswith("---\n"):+ return False+ end = text.find("\n---\n", 4)+ if end == -1:+ return False+ block = text[4:end]+ try:+ parsed: Any = yaml.safe_load(block)+ except yaml.YAMLError:+ return False+ if not isinstance(parsed, dict):+ return False+ parsed_dict = cast("dict[str, Any]", parsed)+ return parsed_dict.get(_PIPELEX_MARKER_KEY) is True++def update_cursor_rules(repo_root: Path, kit_index: KitIndex, agent_set: str) -> None:"""Update Cursor .mdc rule files from agent markdown with YAML front-matter.@@ -81,11 +110,19 @@ def update_cursor_rules(repo_root: Path, kit_index: KitIndex, agent_set: str) ->typer.echo(f"⚪ Unchanged {out_path}")-def remove_cursor_rules(repo_root: Path) -> None:- """Remove Cursor .mdc files that correspond to agent markdown files.+def remove_cursor_rules(repo_root: Path, kit_index: KitIndex | None = None) -> None:+ """Remove Pipelex-generated Cursor .mdc files.++ Scans every .mdc file in `.cursor/rules/` and deletes the file when any of:+ - its YAML front-matter carries the Pipelex marker (`pipelex_managed: true`)+ - its stem matches a currently-known agent_rules source file (backward compat for+ files generated before the marker was introduced)+ - its stem appears in `agent_rules.deprecated_rule_stems` in the kit index (migration+ tombstones for sources removed across versions, e.g. `tdd`)Args:repo_root: Repository root directory+ kit_index: Kit index (loaded from index.toml if not provided)"""agents_dir = get_kit_agents_dir()out_dir = repo_root / ".cursor" / "rules"@@ -94,13 +131,18 @@ def remove_cursor_rules(repo_root: Path) -> None:typer.echo(f"⚠️ Directory {out_dir} does not exist - nothing to remove")return- removed_count = 0- for fname, _ in _iter_agent_files(agents_dir):- out_path = out_dir / (fname.removesuffix(".md") + ".mdc")+ loaded_index = kit_index if kit_index is not None else load_index()+ current_stems = {fname.removesuffix(".md") for fname, _ in _iter_agent_files(agents_dir)}+ deprecated_stems = set(loaded_index.agent_rules.deprecated_rule_stems)+ known_stems = current_stems | deprecated_stems- if out_path.exists():- out_path.unlink()- typer.echo(f"🗑️ Deleted {out_path}")+ removed_count = 0+ for mdc_path in sorted(out_dir.glob("*.mdc")):+ if not mdc_path.is_file():+ continue+ if _is_pipelex_managed(mdc_path) or mdc_path.stem in known_stems:+ mdc_path.unlink()+ typer.echo(f"🗑️ Deleted {mdc_path}")removed_count += 1if removed_count == 0:diff --git a/pipelex/kit/index.toml b/pipelex/kit/index.tomlindex 64673ed43..58410a850 100644--- a/pipelex/kit/index.toml+++ b/pipelex/kit/index.toml@@ -5,6 +5,10 @@ description = "Pipelex kit configuration for agent rules"[agent_rules]demote = 1default_set = "all"+# Tombstones: stems that used to ship as agent_rules sources but are no longer present.+# Cleanup uses this to remove stale generated artifacts (e.g. `.cursor/rules/<stem>.mdc`)+# from users upgrading across the removal.+deprecated_rule_stems = ["tdd"][agent_rules.sets]all = [@@ -13,7 +17,6 @@ all = ["pipelex_standards.md","pytest_standards.md","docs.md",- "tdd.md",][agent_rules.cursor.front_matter]@@ -39,10 +42,6 @@ globs = ["docs/**/*.md"]description = "Guidelines for running commands"alwaysApply = true-[agent_rules.cursor.files.tdd.front_matter]-description = "Guidelines for writing test-driven development code"-globs = []-[agent_rules.targets.agents]path = "AGENTS.md"@@ -53,8 +52,21 @@ all = ["pipelex_standards.md","pytest_standards.md","docs.md",- "tdd.md",][agent_rules.targets.claude]path = "CLAUDE.md"++[agent_rules.targets.claude.sets]+all = [+ "commands.md",+ "pipelex_standards.md",+ "docs.md",+]+standalone = [+ "commands.md",+ "python_standards.md",+ "pipelex_standards.md",+ "pytest_standards.md",+ "docs.md",+]diff --git a/pipelex/kit/index_models.py b/pipelex/kit/index_models.pyindex 6ea5261d8..a128b85a1 100644--- a/pipelex/kit/index_models.py+++ b/pipelex/kit/index_models.py@@ -33,6 +33,14 @@ class AgentRules(ConfigModel):demote: int = Field(default=1, description="Number of levels to demote headings when merging")cursor: CursorSpec = Field(description="Cursor rules export configuration")targets: dict[str, Target] = Field(description="Dictionary of single-file merge targets keyed by ID")+ deprecated_rule_stems: list[str] = Field(+ default_factory=list,+ description=(+ "Stems (filename without extension) of agent_rules sources that used to ship but are no longer "+ "present. The cleanup path uses this tombstone list to delete pre-existing generated artifacts "+ "(e.g. `.cursor/rules/<stem>.mdc`) for users upgrading from an older version of the kit."+ ),+ )class KitIndex(ConfigModel):diff --git a/tests/integration/pipelex/kit/test_remove_cursor_rules.py b/tests/integration/pipelex/kit/test_remove_cursor_rules.pynew file mode 100644index 000000000..8baee15a8--- /dev/null+++ b/tests/integration/pipelex/kit/test_remove_cursor_rules.py@@ -0,0 +1,68 @@+"""Regression tests for remove_cursor_rules cleanup behavior."""++from pathlib import Path++from pipelex.kit.cursor_rules import remove_cursor_rules+++class TestRemoveCursorRules:+ def test_removes_stale_pipelex_managed_file(self, tmp_path: Path):+ """A .mdc file with the `pipelex_managed: true` marker must be removed even when+ no corresponding source file exists under `pipelex/kit/agent_rules/` anymore.++ Regression test for the bug where removing a source file (e.g. `tdd.md`) would+ leave behind a stale `.cursor/rules/<name>.mdc` that the cleanup path could not+ discover because it only iterated currently-existing source files.+ """+ cursor_dir = tmp_path / ".cursor" / "rules"+ cursor_dir.mkdir(parents=True)++ stale_path = cursor_dir / "tdd.mdc"+ stale_path.write_text(+ "---\nalwaysApply: false\npipelex_managed: true\n---\n# TDD\n",+ encoding="utf-8",+ )+ user_path = cursor_dir / "user_custom.mdc"+ user_path.write_text("---\nalwaysApply: true\n---\n# my own rule\n", encoding="utf-8")++ remove_cursor_rules(tmp_path)++ assert not stale_path.exists(), "Stale Pipelex-managed .mdc must be deleted"+ assert user_path.exists(), "Unrelated user .mdc files must be preserved"++ def test_removes_current_source_file_without_marker(self, tmp_path: Path):+ """Files whose stem matches a currently-known agent_rules source must still be+ removed, even when they lack the `pipelex_managed` marker (backward compat for+ files generated before the marker existed).+ """+ cursor_dir = tmp_path / ".cursor" / "rules"+ cursor_dir.mkdir(parents=True)++ legacy_path = cursor_dir / "commands.mdc"+ legacy_path.write_text("---\nalwaysApply: true\n---\n# legacy\n", encoding="utf-8")++ remove_cursor_rules(tmp_path)++ assert not legacy_path.exists(), "Legacy unmarked .mdc matching a current source must still be deleted"++ def test_removes_legacy_tdd_mdc_without_marker(self, tmp_path: Path):+ """A pre-marker `tdd.mdc` whose source `tdd.md` has been removed from the kit+ must still be deleted via the declarative `deprecated_rule_stems` tombstone list.++ Migration regression test: existing Cursor users who ran sync before the+ `pipelex_managed` marker was introduced have stale `.cursor/rules/tdd.mdc` files.+ These have neither the marker nor a matching current source, so the only safe+ way to remove them is via an explicit deprecation list shipped with the kit.+ """+ cursor_dir = tmp_path / ".cursor" / "rules"+ cursor_dir.mkdir(parents=True)++ legacy_tdd = cursor_dir / "tdd.mdc"+ legacy_tdd.write_text(+ "---\nalwaysApply: false\ndescription: Test-Driven Development guide\n---\n# TDD\n",+ encoding="utf-8",+ )++ remove_cursor_rules(tmp_path)++ assert not legacy_tdd.exists(), "Legacy pre-marker tdd.mdc must be deleted via the deprecated stems list"diff --git a/tests/integration/pipelex/kit/test_sync_agent_rules_cleanup.py b/tests/integration/pipelex/kit/test_sync_agent_rules_cleanup.pynew file mode 100644index 000000000..923acfec2--- /dev/null+++ b/tests/integration/pipelex/kit/test_sync_agent_rules_cleanup.py@@ -0,0 +1,43 @@+"""Regression tests for _sync_agent_rules cleanup behavior."""++from pathlib import Path++from pytest_mock import MockerFixture++from pipelex.cli.dev_cli.commands import kit_cmd+from pipelex.kit.index_loader import load_index+from pipelex.system.configuration.configs import AgentTarget+++class TestSyncAgentRulesCleanup:+ def test_targets_filter_does_not_shrink_cleanup_keep_set(self, tmp_path: Path, mocker: MockerFixture):+ """`--targets=claude --cleanup` must not delete AGENTS.md when both targets remain configured.++ Regression test for the bug where _sync_agent_rules overwrote `preferred_targets`+ with the `--targets` subset, causing _cleanup_other_targets to receive a narrowed+ keep-set and delete still-configured rule files.+ """+ idx = load_index()+ repo_root = tmp_path / "repo"+ repo_root.mkdir()++ agents_path = repo_root / "AGENTS.md"+ claude_path = repo_root / "CLAUDE.md"+ agents_path.write_text("# AGENTS\n", encoding="utf-8")+ claude_path.write_text("# CLAUDE\n", encoding="utf-8")++ fake_config = mocker.MagicMock()+ fake_config.pipelex.kit_config.preferred_agent_targets = [AgentTarget.CLAUDE, AgentTarget.AGENTS]+ mocker.patch.object(kit_cmd, "get_config", return_value=fake_config)++ kit_cmd._sync_agent_rules( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]+ repo_root=repo_root,+ agent_set="all",+ cleanup=True,+ kit_index=idx,+ targets_filter=[AgentTarget.CLAUDE],+ )++ assert agents_path.exists(), "AGENTS.md must not be deleted when 'agents' is still in preferred_agent_targets"+ assert claude_path.exists(), "CLAUDE.md must be updated, not deleted"+ assert claude_path.read_text(encoding="utf-8").startswith("# Pipelex Coding Rules"), "CLAUDE.md should have been regenerated"diff --git a/tests/integration/pipelex/kit/test_target_set_overrides.py b/tests/integration/pipelex/kit/test_target_set_overrides.pynew file mode 100644index 000000000..5d9e0733c--- /dev/null+++ b/tests/integration/pipelex/kit/test_target_set_overrides.py@@ -0,0 +1,50 @@+"""Integration tests for per-target agent rule set overrides."""++from pipelex.kit.index_loader import load_index+from pipelex.kit.single_file_agent_rules import build_merged_rules++PYTHON_STANDARDS_HEADING = "## Coding Standards & Best Practices for Python Code"+PYTEST_STANDARDS_HEADING_LOWER = "## writing tests"+TDD_HEADING_LOWER = "## test-driven development"+++class TestTargetSetOverrides:+ def test_claude_default_set_is_lean(self):+ idx = load_index()+ claude_target = idx.agent_rules.targets["claude"]++ assert claude_target.sets is not None+ merged = build_merged_rules(idx, agent_set="all", file_list=claude_target.sets["all"])++ assert PYTHON_STANDARDS_HEADING not in merged+ assert PYTEST_STANDARDS_HEADING_LOWER not in merged.lower()+ assert TDD_HEADING_LOWER not in merged.lower()++ def test_claude_standalone_set_includes_python_and_pytest(self):+ idx = load_index()+ claude_target = idx.agent_rules.targets["claude"]++ assert claude_target.sets is not None+ merged = build_merged_rules(idx, agent_set="standalone", file_list=claude_target.sets["standalone"])++ assert PYTHON_STANDARDS_HEADING in merged+ assert "writing tests" in merged.lower()+ assert TDD_HEADING_LOWER not in merged.lower()++ def test_agents_set_keeps_python_and_pytest_without_tdd(self):+ idx = load_index()+ agents_target = idx.agent_rules.targets["agents"]++ assert agents_target.sets is not None+ merged = build_merged_rules(idx, agent_set="all", file_list=agents_target.sets["all"])++ assert PYTHON_STANDARDS_HEADING in merged+ assert "writing tests" in merged.lower()+ assert TDD_HEADING_LOWER not in merged.lower()++ def test_global_all_set_no_longer_includes_tdd(self):+ idx = load_index()++ assert "tdd.md" not in idx.agent_rules.sets["all"]+ merged = build_merged_rules(idx, agent_set="all")+ assert TDD_HEADING_LOWER not in merged.lower()