From a7c72a63c48130c6e65d5aca1b9d1dd9bc0ed5b9 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:35:20 -0600 Subject: [PATCH 01/10] chore(ai): Remove legacy .cursor/rules files why: Keep AGENTS.md, REVIEW.md, and .github/WRITING.md as the single authoritative agent and contributor instruction set. what: - Delete legacy .cursor/rules/*.mdc files --- .cursor/rules/avoid-debug-loops.mdc | 57 --------- .cursor/rules/dev-loop.mdc | 187 ---------------------------- .cursor/rules/git-commits.mdc | 95 -------------- .cursor/rules/notes-llms-txt.mdc | 42 ------- 4 files changed, 381 deletions(-) delete mode 100644 .cursor/rules/avoid-debug-loops.mdc delete mode 100644 .cursor/rules/dev-loop.mdc delete mode 100644 .cursor/rules/git-commits.mdc delete mode 100644 .cursor/rules/notes-llms-txt.mdc diff --git a/.cursor/rules/avoid-debug-loops.mdc b/.cursor/rules/avoid-debug-loops.mdc deleted file mode 100644 index 8a241ec99..000000000 --- a/.cursor/rules/avoid-debug-loops.mdc +++ /dev/null @@ -1,57 +0,0 @@ ---- -description: When stuck in debugging loops, break the cycle by minimizing to an MVP, removing debugging cruft, and documenting the issue completely for a fresh approach -globs: *.py -alwaysApply: true ---- -# Avoid Debug Loops - -When debugging becomes circular and unproductive, follow these steps: - -## Detection -- You have made multiple unsuccessful attempts to fix the same issue -- You are adding increasingly complex code to address errors -- Each fix creates new errors in a cascading pattern -- You are uncertain about the root cause after 2-3 iterations - -## Action Plan - -1. **Pause and acknowledge the loop** - - Explicitly state that you are in a potential debug loop - - Review what approaches have been tried and failed - -2. **Minimize to MVP** - - Remove all debugging cruft and experimental code - - Revert to the simplest version that demonstrates the issue - - Focus on isolating the core problem without added complexity - -3. **Comprehensive Documentation** - - Provide a clear summary of the issue - - Include minimal but complete code examples that reproduce the problem - - Document exact error messages and unexpected behaviors - - Explain your current understanding of potential causes - -4. **Format for Portability** - - Present the problem in quadruple backticks for easy copying: - -```` -# Problem Summary -[Concise explanation of the issue] - -## Minimal Reproduction Code -```python -# Minimal code example that reproduces the issue -``` - -## Error/Unexpected Output -``` -[Exact error messages or unexpected output] -``` - -## Failed Approaches -[Brief summary of approaches already tried] - -## Suspected Cause -[Your current hypothesis about what might be causing the issue] -```` - -This format enables the user to easily copy the entire problem statement into a fresh conversation for a clean-slate approach. diff --git a/.cursor/rules/dev-loop.mdc b/.cursor/rules/dev-loop.mdc deleted file mode 100644 index 7e9708101..000000000 --- a/.cursor/rules/dev-loop.mdc +++ /dev/null @@ -1,187 +0,0 @@ ---- -description: QA every edit -globs: *.py -alwaysApply: true ---- - -# Development Process - -## Project Stack - -The project uses the following tools and technologies: - -- **uv** - Python package management and virtual environments -- **ruff** - Fast Python linter and formatter -- **py.test** - Testing framework - - **pytest-watcher** - Continuous test runner -- **ty** - Static type checking -- **doctest** - Testing code examples in documentation - -## 1. Start with Formatting - -Format your code first: - -``` -uv run ruff format . -``` - -## 2. Run Tests - -Verify that your changes pass the tests: - -``` -uv run py.test -``` - -For continuous testing during development, use pytest-watcher: - -``` -# Watch all tests -uv run ptw . - -# Watch and run tests immediately, including doctests -uv run ptw . --now --doctest-modules - -# Watch specific files or directories -uv run ptw . --now --doctest-modules src/libtmux/_internal/ -``` - -## 3. Commit Initial Changes - -Make an atomic commit for your changes using conventional commits. -Use `@git-commits.mdc` for assistance with commit message standards. - -## 4. Run Linting and Type Checking - -Check and fix linting issues: - -``` -uv run ruff check . --fix --show-fixes -``` - -Check typings: - -``` -uv run ty check -``` - -## 5. Verify Tests Again - -Ensure tests still pass after linting and type fixes: - -``` -uv run py.test -``` - -## 6. Final Commit - -Make a final commit with any linting/typing fixes. -Use `@git-commits.mdc` for assistance with commit message standards. - -## Development Loop Guidelines - -If there are any failures at any step due to your edits, fix them before proceeding to the next step. - -## Python Code Standards - -### Docstring Guidelines - -For `src/**/*.py` files, follow these docstring guidelines: - -1. **Use reStructuredText format** for all docstrings. - ```python - """Short description of the function or class. - - Detailed description using reStructuredText format. - - Parameters - ---------- - param1 : type - Description of param1 - param2 : type - Description of param2 - - Returns - ------- - type - Description of return value - """ - ``` - -2. **Keep the main description on the first line** after the opening `"""`. - -3. **Use NumPy docstyle** for parameter and return value documentation. - -### Doctest Guidelines - -For doctests in `src/**/*.py` files: - -1. **Use narrative descriptions** for test sections rather than inline comments: - ```python - """Example function. - - Examples - -------- - Create an instance: - - >>> obj = ExampleClass() - - Verify a property: - - >>> obj.property - 'expected value' - """ - ``` - -2. **Move complex examples** to dedicated test files at `tests/examples//test_.py` if they require elaborate setup or multiple steps. - -3. **Utilize pytest fixtures** via `doctest_namespace` for more complex test scenarios: - ```python - """Example with fixture. - - Examples - -------- - >>> # doctest_namespace contains all pytest fixtures from conftest.py - >>> example_fixture = getfixture('example_fixture') - >>> example_fixture.method() - 'expected result' - """ - ``` - -4. **Keep doctests simple and focused** on demonstrating usage rather than comprehensive testing. - -5. **Add blank lines between test sections** for improved readability. - -6. **Test your doctests continuously** using pytest-watcher during development: - ``` - # Watch specific modules for doctest changes - uv run ptw . --now --doctest-modules src/path/to/module.py - ``` - -### Pytest Testing Guidelines - -1. **Use existing fixtures over mocks**: - - Use fixtures from conftest.py instead of `monkeypatch` and `MagicMock` when available - - For instance, if using libtmux, use provided fixtures: `server`, `session`, `window`, and `pane` - - Document in test docstrings why standard fixtures weren't used for exceptional cases - -2. **Preferred pytest patterns**: - - Use `tmp_path` (pathlib.Path) fixture over Python's `tempfile` - - Use `monkeypatch` fixture over `unittest.mock` - -### Import Guidelines - -1. **Prefer namespace imports**: - - Import modules and access attributes through the namespace instead of importing specific symbols - - Example: Use `import enum` and access `enum.Enum` instead of `from enum import Enum` - - This applies to standard library modules like `pathlib`, `os`, and similar cases - -2. **Standard aliases**: - - For `typing` module, use `import typing as t` - - Access typing elements via the namespace: `t.NamedTuple`, `t.TypedDict`, etc. - - Note primitive types like unions can be done via `|` pipes and primitive types like list and dict can be done via `list` and `dict` directly. - -3. **Benefits of namespace imports**: - - Improves code readability by making the source of symbols clear - - Reduces potential naming conflicts - - Makes import statements more maintainable diff --git a/.cursor/rules/git-commits.mdc b/.cursor/rules/git-commits.mdc deleted file mode 100644 index f9c0980db..000000000 --- a/.cursor/rules/git-commits.mdc +++ /dev/null @@ -1,95 +0,0 @@ ---- -description: git-commits: Git commit message standards and AI assistance -globs: git-commits: Git commit message standards and AI assistance | *.git/* .gitignore .github/* CHANGELOG.md CHANGES.md -alwaysApply: true ---- -# Optimized Git Commit Standards - -## Commit Message Format -``` -Component/File(commit-type[Subcomponent/method]): Concise description - -why: Explanation of necessity or impact. -what: -- Specific technical changes made -- Focused on a single topic - -refs: #issue-number, breaking changes, or relevant links -``` - -## Component Patterns -### General Code Changes -``` -Component/File(feat[method]): Add feature -Component/File(fix[method]): Fix bug -Component/File(refactor[method]): Code restructure -``` - -### Packages and Dependencies -| Language | Standard Packages | Dev Packages | Extras / Sub-packages | -|------------|------------------------------------|-------------------------------|-----------------------------------------------| -| General | `lang(deps):` | `lang(deps[dev]):` | | -| Python | `py(deps):` | `py(deps[dev]):` | `py(deps[extra]):` | -| JavaScript | `js(deps):` | `js(deps[dev]):` | `js(deps[subpackage]):`, `js(deps[dev{subpackage}]):` | - -#### Examples -- `py(deps[dev]): Update pytest to v8.1` -- `js(deps[ui-components]): Upgrade Button component package` -- `js(deps[dev{linting}]): Add ESLint plugin` - -### Documentation Changes -Prefix with `docs:` -``` -docs(Component/File[Subcomponent/method]): Update API usage guide -``` - -### Test Changes -Prefix with `tests:` -``` -tests(Component/File[Subcomponent/method]): Add edge case tests -``` - -## Commit Types Summary -- **feat**: New features or enhancements -- **fix**: Bug fixes -- **refactor**: Code restructuring without functional change -- **docs**: Documentation updates -- **chore**: Maintenance (dependencies, tooling, config) -- **test**: Test-related updates -- **style**: Code style and formatting - -## General Guidelines -- Subject line: Maximum 50 characters -- Body lines: Maximum 72 characters -- Use imperative mood (e.g., "Add", "Fix", not "Added", "Fixed") -- Limit to one topic per commit -- Separate subject from body with a blank line -- Mark breaking changes clearly: `BREAKING:` -- Use `See also:` to provide external references - -## AI Assistance Workflow in Cursor -- Stage changes with `git add` -- Use `@commit` to generate initial commit message -- Review and refine generated message -- Ensure adherence to these standards - -## Good Commit Example -``` -Pane(feat[capture_pane]): Add screenshot capture support - -why: Provide visual debugging capability -what: -- Implement capturePane method with image export -- Integrate with existing Pane component logic -- Document usage in Pane README - -refs: #485 -See also: https://example.com/docs/pane-capture -``` - -## Bad Commit Example -``` -fixed stuff and improved some functions -``` - -These guidelines ensure clear, consistent commit histories, facilitating easier code review and maintenance. \ No newline at end of file diff --git a/.cursor/rules/notes-llms-txt.mdc b/.cursor/rules/notes-llms-txt.mdc deleted file mode 100644 index ac1709773..000000000 --- a/.cursor/rules/notes-llms-txt.mdc +++ /dev/null @@ -1,42 +0,0 @@ ---- -description: LLM-friendly markdown format for notes directories -globs: notes/**/*.md,**/notes/**/*.md -alwaysApply: true ---- - -# Instructions for Generating LLM-Optimized Markdown Content - -When creating or editing markdown files within the specified directories, adhere to the following guidelines to ensure the content is optimized for LLM understanding and efficient token usage: - -1. **Conciseness and Clarity**: - - **Be Brief**: Present information succinctly, avoiding unnecessary elaboration. - - **Use Clear Language**: Employ straightforward language to convey ideas effectively. - -2. **Structured Formatting**: - - **Headings**: Utilize markdown headings (`#`, `##`, `###`, etc.) to organize content hierarchically. - - **Lists**: Use bullet points (`-`) or numbered lists (`1.`, `2.`, etc.) to enumerate items clearly. - - **Code Blocks**: Enclose code snippets within triple backticks (```) to distinguish them from regular text. - -3. **Semantic Elements**: - - **Emphasis**: Use asterisks (`*`) or underscores (`_`) for italicizing text to denote emphasis. - - **Strong Emphasis**: Use double asterisks (`**`) or double underscores (`__`) for bold text to highlight critical points. - - **Inline Code**: Use single backticks (`) for inline code references. - -4. **Linking and References**: - - **Hyperlinks**: Format links using `[Link Text](mdc:URL)` to provide direct access to external resources. - - **References**: When citing sources, use footnotes or inline citations to maintain readability. - -5. **Avoid Redundancy**: - - **Eliminate Repetition**: Ensure that information is not unnecessarily repeated within the document. - - **Use Summaries**: Provide brief summaries where detailed explanations are not essential. - -6. **Standard Compliance**: - - **llms.txt Conformance**: Structure the document in alignment with the `llms.txt` standard, which includes: - - An H1 heading with the project or site name. - - A blockquote summarizing the project's purpose. - - Additional markdown sections providing detailed information. - - H2-delimited sections containing lists of URLs for further details. - -By following these guidelines, the markdown files will be tailored for optimal LLM processing, ensuring that the content is both accessible and efficiently tokenized for AI applications. - -For more information on the `llms.txt` standard, refer to the official documentation: https://llmstxt.org/ From aeae2a71159cd8878b1e59e90b027eca69c1aac0 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:35:20 -0600 Subject: [PATCH 02/10] chore(ai): Remove legacy .windsurfrules why: Prevent conflicting assistant rules alongside AGENTS.md and REVIEW.md. what: - Delete legacy .windsurfrules from repository root --- .windsurfrules | 162 ------------------------------------------------- 1 file changed, 162 deletions(-) delete mode 100644 .windsurfrules diff --git a/.windsurfrules b/.windsurfrules deleted file mode 100644 index e5cd77815..000000000 --- a/.windsurfrules +++ /dev/null @@ -1,162 +0,0 @@ -# Python Project Rules - - -- uv - Python package management and virtual environments -- ruff - Fast Python linter and formatter -- py.test - Testing framework - - pytest-watcher - Continuous test runner -- ty - Static type checking -- doctest - Testing code examples in documentation - - - -- Use a consistent coding style throughout the project -- Format code with ruff before committing -- Run linting and type checking before finalizing changes -- Verify tests pass after each significant change - - - -- Use reStructuredText format for all docstrings in src/**/*.py files -- Keep the main description on the first line after the opening `"""` -- Use NumPy docstyle for parameter and return value documentation -- Format docstrings as follows: - ```python - """Short description of the function or class. - - Detailed description using reStructuredText format. - - Parameters - ---------- - param1 : type - Description of param1 - param2 : type - Description of param2 - - Returns - ------- - type - Description of return value - """ - ``` - - - -- Use narrative descriptions for test sections rather than inline comments -- Format doctests as follows: - ```python - """ - Examples - -------- - Create an instance: - - >>> obj = ExampleClass() - - Verify a property: - - >>> obj.property - 'expected value' - """ - ``` -- Add blank lines between test sections for improved readability -- Keep doctests simple and focused on demonstrating usage -- Move complex examples to dedicated test files at tests/examples//test_.py -- Utilize pytest fixtures via doctest_namespace for complex scenarios - - - -- Run tests with `uv run py.test` before committing changes -- Use pytest-watcher for continuous testing: `uv run ptw . --now --doctest-modules` -- Fix any test failures before proceeding with additional changes - - - -- Make atomic commits with conventional commit messages -- Start with an initial commit of functional changes -- Follow with separate commits for formatting, linting, and type checking fixes - - - -- Use the following commit message format: - ``` - Component/File(commit-type[Subcomponent/method]): Concise description - - why: Explanation of necessity or impact. - what: - - Specific technical changes made - - Focused on a single topic - - refs: #issue-number, breaking changes, or relevant links - ``` - -- Common commit types: - - **feat**: New features or enhancements - - **fix**: Bug fixes - - **refactor**: Code restructuring without functional change - - **docs**: Documentation updates - - **chore**: Maintenance (dependencies, tooling, config) - - **test**: Test-related updates - - **style**: Code style and formatting - -- Prefix Python package changes with: - - `py(deps):` for standard packages - - `py(deps[dev]):` for development packages - - `py(deps[extra]):` for extras/sub-packages - -- General guidelines: - - Subject line: Maximum 50 characters - - Body lines: Maximum 72 characters - - Use imperative mood (e.g., "Add", "Fix", not "Added", "Fixed") - - Limit to one topic per commit - - Separate subject from body with a blank line - - Mark breaking changes clearly: `BREAKING:` - - - -- Use fixtures from conftest.py instead of monkeypatch and MagicMock when available -- For instance, if using libtmux, use provided fixtures: server, session, window, and pane -- Document in test docstrings why standard fixtures weren't used for exceptional cases -- Use tmp_path (pathlib.Path) fixture over Python's tempfile -- Use monkeypatch fixture over unittest.mock - - - -- Prefer namespace imports over importing specific symbols -- Import modules and access attributes through the namespace: - - Use `import enum` and access `enum.Enum` instead of `from enum import Enum` - - This applies to standard library modules like pathlib, os, and similar cases -- For typing, use `import typing as t` and access via the namespace: - - Access typing elements as `t.NamedTuple`, `t.TypedDict`, etc. - - Note primitive types like unions can be done via `|` pipes - - Primitive types like list and dict can be done via `list` and `dict` directly -- Benefits of namespace imports: - - Improves code readability by making the source of symbols clear - - Reduces potential naming conflicts - - Makes import statements more maintainable - - - -- Use our own libvcs pytest fixtures for all repository-related tests in this project: - - Create temporary repositories efficiently with factory fixtures - - Benefit from automatic cleanup when tests finish - - Utilize proper environment variables and configurations - - Test against real VCS operations without mocking - -- Basic repository testing pattern: - ```python - def test_repository_operation(create_git_remote_repo): - # Create a test repository - repo_path = create_git_remote_repo() - - # Test vcspull functionality with the repository - # ... - ``` - -- For more complex scenarios, use the pre-configured repository instances: - ```python - def test_sync_operations(git_repo): - # git_repo is already a GitSync instance - # Test vcspull sync operations - # ... - ``` - From dba9da0b6879e8310251a0a55a56c3303f07a3ca Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:35:20 -0600 Subject: [PATCH 03/10] chore(ai): Remove legacy .augment-guidelines why: Retire duplicate assistant guidelines superseded by AGENTS.md, REVIEW.md, and .github/WRITING.md. what: - Delete legacy .augment-guidelines from repository root --- .augment-guidelines | 328 -------------------------------------------- 1 file changed, 328 deletions(-) delete mode 100644 .augment-guidelines diff --git a/.augment-guidelines b/.augment-guidelines deleted file mode 100644 index 47ababe7e..000000000 --- a/.augment-guidelines +++ /dev/null @@ -1,328 +0,0 @@ -# Augment Guidelines - -## Development Process - -### Project Stack - -The project uses the following tools and technologies: - -- **uv** - Python package management and virtual environments -- **ruff** - Fast Python linter and formatter -- **py.test** - Testing framework - - **pytest-watcher** - Continuous test runner -- **ty** - Static type checking -- **doctest** - Testing code examples in documentation - -### Development Workflow - -1. **Start with Formatting** - ``` - uv run ruff format . - ``` - -2. **Run Tests** - ``` - uv run py.test - ``` - - For continuous testing during development, use pytest-watcher: - ``` - # Watch all tests - uv run ptw . - - # Watch and run tests immediately, including doctests - uv run ptw . --now --doctest-modules - - # Watch specific files or directories - uv run ptw . --now --doctest-modules src/libtmux/_internal/ - ``` - -3. **Commit Initial Changes** - Make an atomic commit for your changes using conventional commits. - -4. **Run Linting and Type Checking** - ``` - uv run ruff check . --fix --show-fixes - uv run ty check - ``` - -5. **Verify Tests Again** - ``` - uv run py.test - ``` - -6. **Final Commit** - Make a final commit with any linting/typing fixes. - -### Python Code Standards - -#### Docstring Guidelines - -For `src/**/*.py` files, follow these docstring guidelines: - -1. **Use reStructuredText format** for all docstrings. - ```python - """Short description of the function or class. - - Detailed description using reStructuredText format. - - Parameters - ---------- - param1 : type - Description of param1 - param2 : type - Description of param2 - - Returns - ------- - type - Description of return value - """ - ``` - -2. **Keep the main description on the first line** after the opening `"""`. - -3. **Use NumPy docstyle** for parameter and return value documentation. - -#### Doctest Guidelines - -For doctests in `src/**/*.py` files: - -1. **Use narrative descriptions** for test sections rather than inline comments: - ```python - """Example function. - - Examples - -------- - Create an instance: - - >>> obj = ExampleClass() - - Verify a property: - - >>> obj.property - 'expected value' - """ - ``` - -2. **Move complex examples** to dedicated test files at `tests/examples//test_.py` if they require elaborate setup or multiple steps. - -3. **Utilize pytest fixtures** via `doctest_namespace` for more complex test scenarios: - ```python - """Example with fixture. - - Examples - -------- - >>> # doctest_namespace contains all pytest fixtures from conftest.py - >>> example_fixture = getfixture('example_fixture') - >>> example_fixture.method() - 'expected result' - """ - ``` - -4. **Keep doctests simple and focused** on demonstrating usage rather than comprehensive testing. - -5. **Add blank lines between test sections** for improved readability. - -6. **Test your doctests continuously** using pytest-watcher during development: - ``` - # Watch specific modules for doctest changes - uv run ptw . --now --doctest-modules src/path/to/module.py - ``` - -#### Pytest Testing Guidelines - -1. **Use existing fixtures over mocks**: - - Use fixtures from conftest.py instead of `monkeypatch` and `MagicMock` when available - - For instance, if using libtmux, use provided fixtures: `server`, `session`, `window`, and `pane` - - Document in test docstrings why standard fixtures weren't used for exceptional cases - -2. **Preferred pytest patterns**: - - Use `tmp_path` (pathlib.Path) fixture over Python's `tempfile` - - Use `monkeypatch` fixture over `unittest.mock` - -#### Import Guidelines - -1. **Prefer namespace imports**: - - Import modules and access attributes through the namespace instead of importing specific symbols - - Example: Use `import enum` and access `enum.Enum` instead of `from enum import Enum` - - This applies to standard library modules like `pathlib`, `os`, and similar cases - -2. **Standard aliases**: - - For `typing` module, use `import typing as t` - - Access typing elements via the namespace: `t.NamedTuple`, `t.TypedDict`, etc. - - Note primitive types like unions can be done via `|` pipes and primitive types like list and dict can be done via `list` and `dict` directly. - -3. **Benefits of namespace imports**: - - Improves code readability by making the source of symbols clear - - Reduces potential naming conflicts - - Makes import statements more maintainable - -## Git Commit Standards - -### Commit Message Format -``` -Component/File(commit-type[Subcomponent/method]): Concise description - -why: Explanation of necessity or impact. -what: -- Specific technical changes made -- Focused on a single topic - -refs: #issue-number, breaking changes, or relevant links -``` - -### Component Patterns -#### General Code Changes -``` -Component/File(feat[method]): Add feature -Component/File(fix[method]): Fix bug -Component/File(refactor[method]): Code restructure -``` - -#### Packages and Dependencies -| Language | Standard Packages | Dev Packages | Extras / Sub-packages | -|------------|------------------------------------|-------------------------------|-----------------------------------------------| -| General | `lang(deps):` | `lang(deps[dev]):` | | -| Python | `py(deps):` | `py(deps[dev]):` | `py(deps[extra]):` | -| JavaScript | `js(deps):` | `js(deps[dev]):` | `js(deps[subpackage]):`, `js(deps[dev{subpackage}]):` | - -##### Examples -- `py(deps[dev]): Update pytest to v8.1` -- `js(deps[ui-components]): Upgrade Button component package` -- `js(deps[dev{linting}]): Add ESLint plugin` - -#### Documentation Changes -Prefix with `docs:` -``` -docs(Component/File[Subcomponent/method]): Update API usage guide -``` - -#### Test Changes -Prefix with `tests:` -``` -tests(Component/File[Subcomponent/method]): Add edge case tests -``` - -### Commit Types Summary -- **feat**: New features or enhancements -- **fix**: Bug fixes -- **refactor**: Code restructuring without functional change -- **docs**: Documentation updates -- **chore**: Maintenance (dependencies, tooling, config) -- **test**: Test-related updates -- **style**: Code style and formatting - -### General Guidelines -- Subject line: Maximum 50 characters -- Body lines: Maximum 72 characters -- Use imperative mood (e.g., "Add", "Fix", not "Added", "Fixed") -- Limit to one topic per commit -- Separate subject from body with a blank line -- Mark breaking changes clearly: `BREAKING:` -- Use `See also:` to provide external references - -### Good Commit Example -``` -Pane(feat[capture_pane]): Add screenshot capture support - -why: Provide visual debugging capability -what: -- Implement capturePane method with image export -- Integrate with existing Pane component logic -- Document usage in Pane README - -refs: #485 -See also: https://example.com/docs/pane-capture -``` - -### Bad Commit Example -``` -fixed stuff and improved some functions -``` - -## Avoiding Debug Loops - -When debugging becomes circular and unproductive, follow these steps: - -### Detection -- You have made multiple unsuccessful attempts to fix the same issue -- You are adding increasingly complex code to address errors -- Each fix creates new errors in a cascading pattern -- You are uncertain about the root cause after 2-3 iterations - -### Action Plan - -1. **Pause and acknowledge the loop** - - Explicitly state that you are in a potential debug loop - - Review what approaches have been tried and failed - -2. **Minimize to MVP** - - Remove all debugging cruft and experimental code - - Revert to the simplest version that demonstrates the issue - - Focus on isolating the core problem without added complexity - -3. **Comprehensive Documentation** - - Provide a clear summary of the issue - - Include minimal but complete code examples that reproduce the problem - - Document exact error messages and unexpected behaviors - - Explain your current understanding of potential causes - -4. **Format for Portability** - - Present the problem in quadruple backticks for easy copying: - -```` -# Problem Summary -[Concise explanation of the issue] - -## Minimal Reproduction Code -```python -# Minimal code example that reproduces the issue -``` - -## Error/Unexpected Output -``` -[Exact error messages or unexpected output] -``` - -## Failed Approaches -[Brief summary of approaches already tried] - -## Suspected Cause -[Your current hypothesis about what might be causing the issue] -```` - -## LLM-Optimized Markdown Content Guidelines - -When creating or editing markdown files within notes directories, adhere to the following guidelines: - -1. **Conciseness and Clarity**: - - **Be Brief**: Present information succinctly, avoiding unnecessary elaboration. - - **Use Clear Language**: Employ straightforward language to convey ideas effectively. - -2. **Structured Formatting**: - - **Headings**: Utilize markdown headings (`#`, `##`, `###`, etc.) to organize content hierarchically. - - **Lists**: Use bullet points (`-`) or numbered lists (`1.`, `2.`, etc.) to enumerate items clearly. - - **Code Blocks**: Enclose code snippets within triple backticks (```) to distinguish them from regular text. - -3. **Semantic Elements**: - - **Emphasis**: Use asterisks (`*`) or underscores (`_`) for italicizing text to denote emphasis. - - **Strong Emphasis**: Use double asterisks (`**`) or double underscores (`__`) for bold text to highlight critical points. - - **Inline Code**: Use single backticks (`) for inline code references. - -4. **Linking and References**: - - **Hyperlinks**: Format links using `[Link Text](mdc:URL)` to provide direct access to external resources. - - **References**: When citing sources, use footnotes or inline citations to maintain readability. - -5. **Avoid Redundancy**: - - **Eliminate Repetition**: Ensure that information is not unnecessarily repeated within the document. - - **Use Summaries**: Provide brief summaries where detailed explanations are not essential. - -6. **Standard Compliance**: - - **llms.txt Conformance**: Structure the document in alignment with the `llms.txt` standard, which includes: - - An H1 heading with the project or site name. - - A blockquote summarizing the project's purpose. - - Additional markdown sections providing detailed information. - - H2-delimited sections containing lists of URLs for further details. - -For more information on the `llms.txt` standard, refer to the official documentation: https://llmstxt.org/ From a065048b784f837ffad0fb6b4cb4865f8749e88e Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:35:20 -0600 Subject: [PATCH 04/10] chore(ai): Remove legacy .codex/instructions.md why: Codex loads root AGENTS.md and REVIEW.md directly without needing a separate .codex/instructions.md file. what: - Delete legacy .codex/instructions.md --- .codex/instructions.md | 1 - 1 file changed, 1 deletion(-) delete mode 120000 .codex/instructions.md diff --git a/.codex/instructions.md b/.codex/instructions.md deleted file mode 120000 index 4ff3f86e7..000000000 --- a/.codex/instructions.md +++ /dev/null @@ -1 +0,0 @@ -../.windsurfrules \ No newline at end of file From 7c3b18e08c9df5d8a08f6a0a86ca42db1709dab4 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:36:07 -0600 Subject: [PATCH 05/10] docs(policy): Add REVIEW.md and link from AGENTS.md why: Define layer ownership across libvcs URL, cmd, sync, and _internal modules alongside regression baselines and falsifiable review verdicts. what: - Add root REVIEW.md covering sync, cmd, url, _internal, and pytest fixtures - Link REVIEW.md from AGENTS.md policy and change-discipline sections --- AGENTS.md | 4 ++++ REVIEW.md | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 REVIEW.md diff --git a/AGENTS.md b/AGENTS.md index a2c5a2e73..f1b160828 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,6 +29,8 @@ was asked for. - Documentation, user-facing text, `CHANGES`, release notes, commit messages, docstrings, and source comments: [.github/WRITING.md](.github/WRITING.md) +- Design, planning, and pull request review decisions: + [REVIEW.md](REVIEW.md) - Environment, the gates, tests, documentation builds, releases, and pull requests: [.github/CONTRIBUTING.md](.github/CONTRIBUTING.md) @@ -47,6 +49,8 @@ stated twice, the file listed above is the one that governs. for every change to the public API or pytest fixtures. - A passing gate is evidence only once it has been shown capable of failing. Pair a new test with a deliberate break that proves it bites. +- Before planning code changes, check the owning module and sibling entry + points against [REVIEW.md](REVIEW.md). ## Python typing diff --git a/REVIEW.md b/REVIEW.md new file mode 100644 index 000000000..2bf5a7d53 --- /dev/null +++ b/REVIEW.md @@ -0,0 +1,38 @@ +# Code and architecture review (`vcs-python/libvcs`) + +Posture: `experimental` (pre-1.0 zero-dependency Python library for Git, Mercurial, and Subversion URLs, command wrappers, and checkout synchronization; repair asymmetric or leaky contracts at the owning module and update callers, docs, and `CHANGES` in the same diff). + +Review the complete change against ``, including untracked files. Report all findings in one pass without editing files. [Writing conventions](.github/WRITING.md) · [Contributing gates](.github/CONTRIBUTING.md) · [AI policy](https://github.com/vcs-python/.github/blob/HEAD/AI_POLICY.md). + +## 1. Layer ownership + +| Layer | Modules | Owns | Must not own | +| --- | --- | --- | --- | +| Sync orchestration | `src/libvcs/sync/*` (`base.py`, `git.py`, `hg.py`, `svn.py`) | Checkout lifecycle (`obtain`, `update_repo`, remote/branch sync), dirty-tree guards, and repository state inspection | Raw `subprocess` spawning bypassing `cmd/*` or `vcspull` manifest schemas | +| Typed CLI wrappers | `src/libvcs/cmd/*` (`git.py`, `git_filter.py`, `hg.py`, `svn.py`) | Flag construction, command invocation over `_internal/run.py`, and structured `vcs_*` log fields | URL scheme detection or multi-repo workspace orchestration | +| URL grammar and registry | `src/libvcs/url/*` (`base.py`, `registry.py`, `git.py`, `hg.py`, `svn.py`) | Pure URL parsing, explicit/implicit rule matching, SCP-like syntax, and scheme normalization | Subprocess execution, filesystem probes, or network I/O | +| Internal runtime and locks | `src/libvcs/_internal/*`, `exc.py` | Subprocess runner (`run.py`, `subprocess.py`), `QueryList`, file locks (`file_lock.py`), and working-tree preservation (`preservation.py`, `svn_preservation.py`) | Serving as an undocumented cross-package API for `vcspull` when a public export is warranted | +| Test fixtures | `src/libvcs/pytest_plugin.py` | Isolated `$HOME`, VCS config fixtures, and disposable `git`/`hg`/`svn` repositories | Mutating the host user's `$HOME`, `~/.gitconfig`, or SSH agent | + +### Changing the map + +Do not `BLOCK` against `:REVIEW.md`'s prior owner row when a pull request migrates an invariant cleanly to a single owner, updates callers, tests, and `REVIEW.md` in the same diff, and states the old and new owner in the pull request description. + +### Adapters and format leaks + +- **Adapter versus duplicated rule**: `sync/*` orchestrates repository state over `cmd/*` and `url/*`, and `pytest_plugin.py` adapts temporary repositories for tests. Block when `sync/*` re-parses URLs with ad-hoc regexes instead of `libvcs.url`, spawns VCS binaries directly instead of routing through `cmd/*`, or forces downstream `vcspull` callers to import `libvcs._internal` for a capability that belongs on the public API. +- **Zero-import format leaks**: Check dependency direction even when imports stay clean. Block `url/*`, `cmd/*`, or `sync/*` modules that parse `vcspull` YAML/JSON workspace structures, snapshot `.ambr` headers, or `PYTEST_CURRENT_TEST` environment state, or attach test-only attributes to sync objects. + +### Rejected here + +- **Asymmetric behavior across `git`, `hg`, and `svn` siblings**: When changing URL rule precedence, `obtain` / `update_repo` contracts, or structured `vcs_*` log fields, check `git`, `hg`, and `svn` modules together and document backend-specific differences explicitly. +- **Boundary-blind URL regexes**: Test positive and negative boundary inputs on `libvcs.url` rules (scheme spoofing, ports, credentials, SCP colons, Unicode paths, and control characters). +- **Silent partial multi-step state or data loss**: Multi-step sync, remote-update, and `preservation.py` / `svn_preservation.py` backup-and-restore flows must preserve uncommitted work and surface partial state clearly if step `N` fails mid-flight. +- **Runtime dependencies or import-time side effects**: Keep `dependencies = []` in `pyproject.toml`, and never configure logging handlers or spawn VCS binaries at module import. +- **Unpinned VCS tool workarounds**: Track version-specific `git`, `hg`, or `svn` quirks in `.github/workarounds.toml` (`issue_only = true` with `reason_no_lock` and an upstream issue URL) verified by `scripts/check_workarounds.py`. + +## 2. Regression baseline and decision + +1. For bug fixes and behavioral changes, reproduce the failure on `` (or on `` when fixing a defect introduced earlier in the same open pull request) through the public `libvcs.url`, `libvcs.cmd`, or `libvcs.sync` API. +2. Verify the production-only revert check fails the new test inside the real owner call (for behavioral changes), then run `uv run ruff check .`, `uv run ruff format . --check`, `uv run ty check`, `uv run pytest`, and `PYTHONDONTWRITEBYTECODE=1 uv run python -B scripts/check_workarounds.py`. +3. Emit `BLOCK` or `NO FINDINGS` (plus optional non-blocking `NOTE` items). Before emitting `BLOCK` on placement, weigh any boundary-adapter or ownership-transfer counter-case and state a concrete test, command, or code observation that would prove the finding wrong. From 5dbf919e5a95047742e668f75068683c12230c04 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:36:18 -0600 Subject: [PATCH 06/10] docs(contributing): Add test-bite check and pull request template why: Give pull request authors an explicit owner, baseline, and verification checklist alongside a copy-pasteable production-only revert command for regression tests. what: - Add .github/PULL_REQUEST_TEMPLATE.md with owner, failure baseline, and verification prompts - Link REVIEW.md and add production-only test-bite recipe in .github/CONTRIBUTING.md --- .github/CONTRIBUTING.md | 25 ++++++++++++++++++++++++- .github/PULL_REQUEST_TEMPLATE.md | 26 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 921fb73df..e7fad9394 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -64,7 +64,28 @@ qualify, and the one mistake that silently removes a test, are in [WRITING.md](WRITING.md#documented-examples-that-run). Before claiming a test or a gate works, show it failing. A gate that has -never been red is an assumption. +never been red is an assumption. For bug fixes and behavioral changes, +verify new or updated `pytest` regressions fail inside the real owner +call when modified production files are restored to `` and newly +added production files are removed temporarily: + +```console +$ mapfile -t mod_py < <( + git diff --name-only -M --diff-filter=MDR ..HEAD -- '*.py' | + rg -v '(^|/)tests?/|(^|/)conftest\.py$|(^|/)test_[^/]*\.py$|_test\.py$' + ) && + mapfile -t add_py < <( + git diff --name-only -M --diff-filter=A ..HEAD -- '*.py' | + rg -v '(^|/)tests?/|(^|/)conftest\.py$|(^|/)test_[^/]*\.py$|_test\.py$' + ) && + test $(( ${#mod_py[@]} + ${#add_py[@]} )) -gt 0 && + { [ "${#mod_py[@]}" -eq 0 ] || + git restore --source= --worktree -- "${mod_py[@]}"; } && + { [ "${#add_py[@]}" -eq 0 ] || rm -f -- "${add_py[@]}"; } && + ! uv run pytest -x && + git restore --source=HEAD --worktree -- "${mod_py[@]}" "${add_py[@]}" && + uv run pytest +``` ### Imports @@ -235,6 +256,8 @@ documentation. The version is set in `src/libvcs/__about__.py` and ## Pull requests +Use [REVIEW.md](../REVIEW.md) for design and pull request review. + One subject per pull request. Unrelated cleanup found along the way belongs in its own commit, and usually in its own pull request. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..27a6b2347 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,26 @@ + + +Closes # + +### 1. Owner and boundary + +- Rule changed and module that owns it: +- Sibling entry points checked (`sync`/`async`, CLI/API, single/batch, or `N/A`): +- Why this belongs here (owner fix, boundary adapter, or single-PR ownership transfer): + +### 2. Failure before the fix (`N/A` for docs, lockfile bumps, or pure refactors) + +- Baseline (`` commit, or `` SHA if fixing a defect introduced in this PR): +- Failing input or command and observed failure before the fix: + +### 3. Verification and tool disclosure + +- Gates run (plus production-only revert check for behavioral fixes, or `N/A`): +- `.github/workarounds.toml` updates (`None` if none): +- Tool use: From ddc693f3172d40531f48bdb08bf45f8c03ca94a3 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:36:49 -0600 Subject: [PATCH 07/10] ci(governance): Add check_workarounds.py and lint guards why: Fail CI once a locked package version satisfies a declared workaround's removal condition or when a bare suppression comment lands. what: - Add scripts/check_workarounds.py and run it in the test workflow - Select PGH003 and PGH004 in pyproject.toml --- .github/workflows/tests.yml | 3 + pyproject.toml | 2 + scripts/check_workarounds.py | 377 +++++++++++++++++++++++++++++++++++ 3 files changed, 382 insertions(+) create mode 100755 scripts/check_workarounds.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 3efcc1991..fa4acdd24 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -52,6 +52,9 @@ jobs: uv run ty check --python-version "${{ matrix.python-version }}" uv run ruff check --select ANN001,ANN002,ANN003,ANN201,ANN202,ANN204,ANN205,ANN206 src/libvcs/_vendor/*.py + - name: Check declared workarounds + run: PYTHONDONTWRITEBYTECODE=1 uv run python -B scripts/check_workarounds.py + - name: Print python versions run: | python -V diff --git a/pyproject.toml b/pyproject.toml index 672326227..81b4be700 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -201,6 +201,8 @@ extend-select = [ "RUF", # Ruff-specific rules "D", # pydocstyle "FA100", # future annotations + "PGH003", # specific type-ignore codes + "PGH004", # specific noqa codes ] ignore = [ "COM812", # missing trailing comma, ruff format conflict diff --git a/scripts/check_workarounds.py b/scripts/check_workarounds.py new file mode 100755 index 000000000..f7cdd1480 --- /dev/null +++ b/scripts/check_workarounds.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python3 +"""Verify declared workaround removal conditions against lockfiles. + +Checks `.github/workarounds.toml` against `uv.lock`, `Cargo.lock`, +`package-lock.json`, and `pnpm-lock.yaml`. + +Each entry in `.github/workarounds.toml` declares: +- `id`: stable kebab-case identifier cited in the target source file +- `path`: repository-relative code path containing the workaround +- `owner`: upstream package or external tool that owns the root cause +- `issue`: pinned upstream issue, pull request, commit, or specification URL +- `remove_when` (optional only when `issue_only = true` for a non-lockfile tool): + `":>="` where `` is `pypi`, `cargo`, + or `npm`. The check fails once every locked copy of `` meets or + exceeds ``, proving the workaround is ready to delete. + +Examples +-------- +>>> sample_toml = ''' +... [[workaround]] +... id = "vcspull-daemon-url-schemes" +... path = "src/vcspull/validator.py" +... owner = "libvcs" +... issue = "https://github.com/vcs-python/libvcs/issues/546" +... remove_when = "pypi:libvcs>=0.49.0" +... ''' +>>> locks = {"pypi": {"libvcs": "0.48.0"}, "cargo": {}, "npm": {}} +>>> check_entries( +... parse_workarounds(sample_toml), +... locks, +... existing_paths={"src/vcspull/validator.py"}, +... ) +[] +>>> version_key("0.49.0-rc.1") < version_key("0.49.0") < version_key("0.49.1a1") +True +>>> version_key("0.49") == version_key("0.49.0") +True +>>> locks_bumped = {"pypi": {"libvcs": "0.49.0"}, "cargo": {}, "npm": {}} +>>> [ +... e["reason"] +... for e in check_entries( +... parse_workarounds(sample_toml), +... locks_bumped, +... existing_paths={"src/vcspull/validator.py"}, +... ) +... ] +['condition met (pypi:libvcs is 0.49.0 >= 0.49.0); remove workaround'] +""" + +from __future__ import annotations + +import json +import pathlib +import re +import sys +import tomllib + +COND_RE = re.compile(r"^(pypi|cargo|npm):([A-Za-z0-9_./@-]+)>=([0-9][0-9A-Za-z._-]*)$") +DATE_ONLY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") +ISSUE_URL_RE = re.compile(r"^https://[^/\s]+/[^/\s]+/\S+$") +PRE_SEG_RE = re.compile(r"^(\d+)([A-Za-z]+)(\d*)$") +EXACT_VER_RE = re.compile(r"^\d+(?:\.\d+)*(?:[-.][0-9A-Za-z.-]+)?$") +PNPM_PKG_RE = re.compile( + r"""(?m)^\s{2,4}['"]?/?(@?[^'"@\s:]+)@(\d[^'"(\s:]*)(?:\([^)]*\))*['"]?:""" +) +DOC_SUFFIXES = {".md", ".rst", ".txt", ".adoc"} + + +def normalize_pkg(eco: str, name: str) -> str: + """Normalize package names per ecosystem rules (PEP 503 for PyPI).""" + if eco == "pypi": + return re.sub(r"[-_.]+", "-", name).lower() + if eco == "cargo": + return name.lower() + return name + + +def _tag_stage(tag: str) -> int: + if tag.startswith("post"): + return 1 + if tag.startswith("dev"): + return -4 + if tag in {"a", "alpha"}: + return -3 + if tag in {"b", "beta"}: + return -2 + return -1 + + +def version_key( + ver: str, +) -> tuple[tuple[int, ...], int, tuple[tuple[int, int, str], ...]]: + """Order dev < alpha < beta < rc < final < post releases.""" + base = ver.split("+", 1)[0] + nums: list[int] = [] + tail: list[tuple[int, int, str]] = [] + stage = 0 + in_tail = False + for tok in re.split(r"[.-]", base): + if not tok: + continue + if not in_tail and tok.isdigit(): + nums.append(int(tok)) + continue + m = PRE_SEG_RE.match(tok) if not in_tail else None + if m: + nums.append(int(m.group(1))) + tag = m.group(2).lower() + in_tail = True + stage = _tag_stage(tag) + tail.append((0, 0, tag)) + if m.group(3): + tail.append((1, int(m.group(3)), "")) + continue + low = tok.lower() + if not in_tail: + m2 = re.match(r"^([a-z]+)(\d+)$", low) + if m2: + stage = _tag_stage(m2.group(1)) + in_tail = True + tail.append((0, 0, m2.group(1))) + tail.append((1, int(m2.group(2)), "")) + continue + stage = _tag_stage(low) + in_tail = True + tail.append((1, int(tok), "") if tok.isdigit() else (0, 0, low)) + while len(nums) > 1 and nums[-1] == 0: + nums.pop() + return (tuple(nums), stage, tuple(tail)) + + +def _record_min(bucket: dict[str, str], name: str, ver: str) -> None: + prev = bucket.get(name) + if prev is None or version_key(ver) < version_key(prev): + bucket[name] = ver + + +def parse_workarounds(toml_text: str) -> list[dict[str, object]]: + """Parse ``[[workaround]]`` tables from TOML text.""" + data = tomllib.loads(toml_text) + raw = data.get("workaround", []) + if not isinstance(raw, list): + msg = "'workaround' must be an array of tables" + raise TypeError(msg) + return [dict(item) for item in raw if isinstance(item, dict)] + + +def load_locks(repo_root: pathlib.Path) -> dict[str, dict[str, str]]: + """Read minimum locked versions from uv, Cargo, pnpm, or npm lockfiles.""" + locks: dict[str, dict[str, str]] = {"pypi": {}, "cargo": {}, "npm": {}} + uv_lock = repo_root / "uv.lock" + if uv_lock.is_file(): + data = tomllib.loads(uv_lock.read_text(encoding="utf-8")) + for pkg in data.get("package", []): + if isinstance(pkg, dict) and "name" in pkg and "version" in pkg: + _record_min( + locks["pypi"], + normalize_pkg("pypi", str(pkg["name"])), + str(pkg["version"]), + ) + cargo_lock = repo_root / "Cargo.lock" + if cargo_lock.is_file(): + data = tomllib.loads(cargo_lock.read_text(encoding="utf-8")) + for pkg in data.get("package", []): + if isinstance(pkg, dict) and "name" in pkg and "version" in pkg: + _record_min( + locks["cargo"], + normalize_pkg("cargo", str(pkg["name"])), + str(pkg["version"]), + ) + pnpm_lock = repo_root / "pnpm-lock.yaml" + npm_lock = repo_root / "package-lock.json" + if pnpm_lock.is_file(): + for m in PNPM_PKG_RE.finditer(pnpm_lock.read_text(encoding="utf-8")): + _record_min(locks["npm"], m.group(1), m.group(2)) + elif npm_lock.is_file(): + ndata = json.loads(npm_lock.read_text(encoding="utf-8")) + pkgs = ndata.get("packages", {}) + if isinstance(pkgs, dict): + for k, info in pkgs.items(): + if ( + k.startswith("node_modules/") + and isinstance(info, dict) + and "version" in info + ): + pkg_name = k.rsplit("node_modules/", 1)[-1] + _record_min(locks["npm"], pkg_name, str(info["version"])) + else: + pkg_json = repo_root / "package.json" + if pkg_json.is_file(): + pdata = json.loads(pkg_json.read_text(encoding="utf-8")) + for section in ("dependencies", "devDependencies"): + deps = pdata.get(section, {}) + if isinstance(deps, dict): + for name, spec in deps.items(): + spec_s = str(spec).strip() + if EXACT_VER_RE.match(spec_s): + _record_min(locks["npm"], str(name), spec_s) + return locks + + +def check_entries( + entries: list[dict[str, object]], + locks: dict[str, dict[str, str]], + existing_paths: set[str] | None = None, + file_texts: dict[str, str] | None = None, +) -> list[dict[str, str]]: + """Return violations for missing fields, decoy paths, or met predicates.""" + problems: list[dict[str, str]] = [] + for entry in entries: + wid = str(entry.get("id") or "") + rel_path = str(entry.get("path") or "") + owner = str(entry.get("owner") or "") + issue = str(entry.get("issue") or "") + cond = str(entry.get("remove_when") or "") + if not rel_path or not owner or not ISSUE_URL_RE.match(issue): + problems.append( + { + "id": wid, + "reason": ( + "requires path, owner, and full " + "https://// issue URL" + ), + } + ) + continue + if ( + pathlib.Path(rel_path).suffix.lower() in DOC_SUFFIXES + and entry.get("allow_doc_path") is not True + ): + problems.append( + { + "id": wid, + "reason": ( + f"path '{rel_path}' points to documentation " + "rather than source code" + ), + } + ) + continue + if existing_paths is not None and rel_path not in existing_paths: + problems.append( + { + "id": wid, + "reason": ( + f"path '{rel_path}' does not exist as a regular " + "file inside repository" + ), + } + ) + continue + if file_texts is not None and rel_path in file_texts: + src_txt = file_texts[rel_path] + if wid not in src_txt and issue not in src_txt: + problems.append( + { + "id": wid, + "reason": ( + f"path '{rel_path}' contains neither " + f"workaround id '{wid}' nor issue URL" + ), + } + ) + continue + if DATE_ONLY_RE.match(cond): + problems.append( + { + "id": wid, + "reason": ( + "calendar dates are not allowed in remove_when; " + "use a lockfile predicate or issue_only = true" + ), + } + ) + continue + if not cond: + in_locks = any( + normalize_pkg(eco, owner) in locks.get(eco, {}) + for eco in ("pypi", "cargo", "npm") + ) + if in_locks: + problems.append( + { + "id": wid, + "reason": ( + f"owner '{owner}' is present in lockfiles; " + "specify remove_when instead of issue_only" + ), + } + ) + continue + if ( + entry.get("issue_only") is True + and str(entry.get("reason_no_lock") or "").strip() + ): + continue + problems.append( + { + "id": wid, + "reason": ( + "missing remove_when (or issue_only = true with reason_no_lock)" + ), + } + ) + continue + m = COND_RE.match(cond) + if not m: + problems.append( + { + "id": wid, + "reason": ( + f"invalid remove_when '{cond}'; " + "expected ':>='" + ), + } + ) + continue + eco, pkg, target = m.group(1), m.group(2), m.group(3) + norm_pkg = normalize_pkg(eco, pkg) + locked = locks.get(eco, {}).get(norm_pkg) + if locked is None: + problems.append( + { + "id": wid, + "reason": f"package '{pkg}' not found in {eco} lockfile", + } + ) + continue + if version_key(locked) >= version_key(target): + problems.append( + { + "id": wid, + "reason": ( + f"condition met ({eco}:{pkg} is {locked} >= {target}); " + "remove workaround" + ), + } + ) + return problems + + +def main(argv: list[str] | None = None) -> int: + """Run the CLI check against the repository root and manifest path.""" + args = argv if argv is not None else sys.argv[1:] + repo = pathlib.Path(args[0]).resolve() if args else pathlib.Path.cwd().resolve() + manifest = ( + pathlib.Path(args[1]).resolve() + if len(args) > 1 + else repo / ".github" / "workarounds.toml" + ) + if not manifest.is_file(): + sys.stdout.write(f"{json.dumps({'ok': True, 'checked': 0, 'problems': []})}\n") + return 0 + entries = parse_workarounds(manifest.read_text(encoding="utf-8")) + existing: set[str] = set() + texts: dict[str, str] = {} + for entry in entries: + raw_p = str(entry.get("path") or "") + if not raw_p: + continue + cand = (repo / raw_p).resolve() + if cand.is_relative_to(repo) and cand.is_file(): + existing.add(raw_p) + texts[raw_p] = cand.read_text(encoding="utf-8", errors="replace") + problems = check_entries( + entries, + load_locks(repo), + existing_paths=existing, + file_texts=texts, + ) + payload = {"ok": not problems, "checked": len(entries), "problems": problems} + sys.stdout.write(f"{json.dumps(payload)}\n") + return 0 if not problems else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) From 2e608af79db71b0413fee1fc35d83030d2dd2f98 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 15:50:17 -0600 Subject: [PATCH 08/10] docs(review): Add verdict rules and link the posture definitions why: The decision section did not say what to do with behavior the base already has or with a gate nobody ran, or which findings block. what: - Add verdict rules: base run, existing and separate, unverified gates, behavior defects, and checks and claims - Link the organization's posture definitions --- REVIEW.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/REVIEW.md b/REVIEW.md index 2bf5a7d53..6fe0bf8ec 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -2,6 +2,8 @@ Posture: `experimental` (pre-1.0 zero-dependency Python library for Git, Mercurial, and Subversion URLs, command wrappers, and checkout synchronization; repair asymmetric or leaky contracts at the owning module and update callers, docs, and `CHANGES` in the same diff). +[Posture](https://github.com/vcs-python/.github/blob/HEAD/CONTRIBUTING.md#posture) defines `experimental`, `stable` and `private`. + Review the complete change against ``, including untracked files. Report all findings in one pass without editing files. [Writing conventions](.github/WRITING.md) · [Contributing gates](.github/CONTRIBUTING.md) · [AI policy](https://github.com/vcs-python/.github/blob/HEAD/AI_POLICY.md). ## 1. Layer ownership @@ -36,3 +38,13 @@ Do not `BLOCK` against `:REVIEW.md`'s prior owner row when a pull request 1. For bug fixes and behavioral changes, reproduce the failure on `` (or on `` when fixing a defect introduced earlier in the same open pull request) through the public `libvcs.url`, `libvcs.cmd`, or `libvcs.sync` API. 2. Verify the production-only revert check fails the new test inside the real owner call (for behavioral changes), then run `uv run ruff check .`, `uv run ruff format . --check`, `uv run ty check`, `uv run pytest`, and `PYTHONDONTWRITEBYTECODE=1 uv run python -B scripts/check_workarounds.py`. 3. Emit `BLOCK` or `NO FINDINGS` (plus optional non-blocking `NOTE` items). Before emitting `BLOCK` on placement, weigh any boundary-adapter or ownership-transfer counter-case and state a concrete test, command, or code observation that would prove the finding wrong. + +## 3. Verdict + +These rules decide which findings block. + +- **Base run**: A finding that code misbehaves shows its check run on `` and on the change, with one line of output from each. +- **Existing and separate**: Behavior `` already has does not block. Report it as a `NOTE`, unless the change adds a promise the behavior breaks; then the broken promise is the finding. +- **Unverified**: A gate nobody ran is unverified. Name the command that would run it. It holds the merge until someone runs it, and it does not make the verdict `BLOCK`. +- **Behavior defects**: A behavior defect blocks when a caller can reach it in a supported environment, or when it breaks a promise in the pull request description, a docstring, help text or the changelog. Otherwise it is a `NOTE`. +- **Checks and claims**: A weakened check, a rule written in a second place and a behavior claimed as tested with no test that bites block whether or not a caller reaches them. From 0145f984365b01160cda4e4fb273bea35845cccc Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 15:51:01 -0600 Subject: [PATCH 09/10] docs(contributing): Run the test-bite check in a throwaway worktree why: The earlier command restored files in the contributor's checkout. It could erase an uncommitted edit, and it left the source reverted when a test did not bite. It counted any nonzero exit as a bite and used mapfile, which zsh lacks. what: - Run the check in a disposable git worktree at HEAD - Name the regression test in BITE_TEST, and succeed only when the runner reports that test as failed - Default the base to the remote trunk, with BITE_BASE for a pre-fix commit --- .github/CONTRIBUTING.md | 42 ++++++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index e7fad9394..0a1dc20a7 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -70,23 +70,35 @@ call when modified production files are restored to `` and newly added production files are removed temporarily: ```console -$ mapfile -t mod_py < <( - git diff --name-only -M --diff-filter=MDR ..HEAD -- '*.py' | - rg -v '(^|/)tests?/|(^|/)conftest\.py$|(^|/)test_[^/]*\.py$|_test\.py$' - ) && - mapfile -t add_py < <( - git diff --name-only -M --diff-filter=A ..HEAD -- '*.py' | - rg -v '(^|/)tests?/|(^|/)conftest\.py$|(^|/)test_[^/]*\.py$|_test\.py$' - ) && - test $(( ${#mod_py[@]} + ${#add_py[@]} )) -gt 0 && - { [ "${#mod_py[@]}" -eq 0 ] || - git restore --source= --worktree -- "${mod_py[@]}"; } && - { [ "${#add_py[@]}" -eq 0 ] || rm -f -- "${add_py[@]}"; } && - ! uv run pytest -x && - git restore --source=HEAD --worktree -- "${mod_py[@]}" "${add_py[@]}" && - uv run pytest +$ : "${BITE_TEST:?set BITE_TEST to the regression test}" && \ + wt=$(mktemp -d) && \ + git worktree add --quiet --detach "$wt" HEAD && \ + ( cd "$wt" && \ + base=${BITE_BASE:-origin/master} && \ + git diff --name-only --no-renames "$base" HEAD | \ + grep -E '\.py$' | \ + grep -Ev '(^|/)tests?/|(^|/)conftest\.py$|(^|/)test_[^/]*\.py$|_test\.py$' \ + > bite.files && \ + git restore --source="$base" --worktree \ + --pathspec-from-file=bite.files && \ + { uv run pytest -rf "$BITE_TEST" 2>&1 | tee bite.log; \ + grep -E '^FAILED ' bite.log | \ + grep -F -- "$BITE_TEST" | \ + grep -Ev 'ImportError|ModuleNotFoundError'; } ); \ + bite=$?; \ + git worktree remove --force "$wt"; \ + test "$bite" -eq 0 ``` +This runs in a disposable `git worktree` at `HEAD`, so the checkout and any +uncommitted edit stay untouched; commit the change first. Set `BITE_TEST` to a +pytest node id such as `tests/test_x.py::test_name`. `BITE_BASE` defaults to +`origin/master`; set it to the pre-fix commit when the defect was introduced +earlier in the same pull request. The command succeeds only when the runner +reports that test as failed, and it prints the failure line. A missing runner, +a build error or an import error prints no such line, so it is not a bite. +Check that the printed failure is the assertion that describes the defect. + ### Imports - `from __future__ import annotations` at the top of every file. From 35d851aa2620de794c1d0848038d457a9c39d88c Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 15:59:36 -0600 Subject: [PATCH 10/10] ci(workarounds): Run the shared check-workarounds action why: The checker was copied into this repository, so a correction to it had to land in every copy. what: - Delete scripts/check_workarounds.py - Run libtmux/.github's check-workarounds action in CI, pinned to a commit - Point the policy files at the action --- .github/workflows/tests.yml | 2 +- REVIEW.md | 4 +- scripts/check_workarounds.py | 377 ----------------------------------- 3 files changed, 3 insertions(+), 380 deletions(-) delete mode 100755 scripts/check_workarounds.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index fa4acdd24..f3a1c31e2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -53,7 +53,7 @@ jobs: uv run ruff check --select ANN001,ANN002,ANN003,ANN201,ANN202,ANN204,ANN205,ANN206 src/libvcs/_vendor/*.py - name: Check declared workarounds - run: PYTHONDONTWRITEBYTECODE=1 uv run python -B scripts/check_workarounds.py + uses: libtmux/.github/actions/check-workarounds@22703e1b8ee1c176ca72d9ffc9520f2ca0ce3a85 # main - name: Print python versions run: | diff --git a/REVIEW.md b/REVIEW.md index 6fe0bf8ec..4f322d7ad 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -31,12 +31,12 @@ Do not `BLOCK` against `:REVIEW.md`'s prior owner row when a pull request - **Boundary-blind URL regexes**: Test positive and negative boundary inputs on `libvcs.url` rules (scheme spoofing, ports, credentials, SCP colons, Unicode paths, and control characters). - **Silent partial multi-step state or data loss**: Multi-step sync, remote-update, and `preservation.py` / `svn_preservation.py` backup-and-restore flows must preserve uncommitted work and surface partial state clearly if step `N` fails mid-flight. - **Runtime dependencies or import-time side effects**: Keep `dependencies = []` in `pyproject.toml`, and never configure logging handlers or spawn VCS binaries at module import. -- **Unpinned VCS tool workarounds**: Track version-specific `git`, `hg`, or `svn` quirks in `.github/workarounds.toml` (`issue_only = true` with `reason_no_lock` and an upstream issue URL) verified by `scripts/check_workarounds.py`. +- **Unpinned VCS tool workarounds**: Track version-specific `git`, `hg`, or `svn` quirks in `.github/workarounds.toml` (`issue_only = true` with `reason_no_lock` and an upstream issue URL) verified by the shared `check-workarounds` action in CI. ## 2. Regression baseline and decision 1. For bug fixes and behavioral changes, reproduce the failure on `` (or on `` when fixing a defect introduced earlier in the same open pull request) through the public `libvcs.url`, `libvcs.cmd`, or `libvcs.sync` API. -2. Verify the production-only revert check fails the new test inside the real owner call (for behavioral changes), then run `uv run ruff check .`, `uv run ruff format . --check`, `uv run ty check`, `uv run pytest`, and `PYTHONDONTWRITEBYTECODE=1 uv run python -B scripts/check_workarounds.py`. +2. Verify the production-only revert check fails the new test inside the real owner call (for behavioral changes), then run `uv run ruff check .`, `uv run ruff format . --check`, `uv run ty check`, `uv run pytest`, and the shared `libtmux/.github/actions/check-workarounds` action, which CI runs. 3. Emit `BLOCK` or `NO FINDINGS` (plus optional non-blocking `NOTE` items). Before emitting `BLOCK` on placement, weigh any boundary-adapter or ownership-transfer counter-case and state a concrete test, command, or code observation that would prove the finding wrong. ## 3. Verdict diff --git a/scripts/check_workarounds.py b/scripts/check_workarounds.py deleted file mode 100755 index f7cdd1480..000000000 --- a/scripts/check_workarounds.py +++ /dev/null @@ -1,377 +0,0 @@ -#!/usr/bin/env python3 -"""Verify declared workaround removal conditions against lockfiles. - -Checks `.github/workarounds.toml` against `uv.lock`, `Cargo.lock`, -`package-lock.json`, and `pnpm-lock.yaml`. - -Each entry in `.github/workarounds.toml` declares: -- `id`: stable kebab-case identifier cited in the target source file -- `path`: repository-relative code path containing the workaround -- `owner`: upstream package or external tool that owns the root cause -- `issue`: pinned upstream issue, pull request, commit, or specification URL -- `remove_when` (optional only when `issue_only = true` for a non-lockfile tool): - `":>="` where `` is `pypi`, `cargo`, - or `npm`. The check fails once every locked copy of `` meets or - exceeds ``, proving the workaround is ready to delete. - -Examples --------- ->>> sample_toml = ''' -... [[workaround]] -... id = "vcspull-daemon-url-schemes" -... path = "src/vcspull/validator.py" -... owner = "libvcs" -... issue = "https://github.com/vcs-python/libvcs/issues/546" -... remove_when = "pypi:libvcs>=0.49.0" -... ''' ->>> locks = {"pypi": {"libvcs": "0.48.0"}, "cargo": {}, "npm": {}} ->>> check_entries( -... parse_workarounds(sample_toml), -... locks, -... existing_paths={"src/vcspull/validator.py"}, -... ) -[] ->>> version_key("0.49.0-rc.1") < version_key("0.49.0") < version_key("0.49.1a1") -True ->>> version_key("0.49") == version_key("0.49.0") -True ->>> locks_bumped = {"pypi": {"libvcs": "0.49.0"}, "cargo": {}, "npm": {}} ->>> [ -... e["reason"] -... for e in check_entries( -... parse_workarounds(sample_toml), -... locks_bumped, -... existing_paths={"src/vcspull/validator.py"}, -... ) -... ] -['condition met (pypi:libvcs is 0.49.0 >= 0.49.0); remove workaround'] -""" - -from __future__ import annotations - -import json -import pathlib -import re -import sys -import tomllib - -COND_RE = re.compile(r"^(pypi|cargo|npm):([A-Za-z0-9_./@-]+)>=([0-9][0-9A-Za-z._-]*)$") -DATE_ONLY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") -ISSUE_URL_RE = re.compile(r"^https://[^/\s]+/[^/\s]+/\S+$") -PRE_SEG_RE = re.compile(r"^(\d+)([A-Za-z]+)(\d*)$") -EXACT_VER_RE = re.compile(r"^\d+(?:\.\d+)*(?:[-.][0-9A-Za-z.-]+)?$") -PNPM_PKG_RE = re.compile( - r"""(?m)^\s{2,4}['"]?/?(@?[^'"@\s:]+)@(\d[^'"(\s:]*)(?:\([^)]*\))*['"]?:""" -) -DOC_SUFFIXES = {".md", ".rst", ".txt", ".adoc"} - - -def normalize_pkg(eco: str, name: str) -> str: - """Normalize package names per ecosystem rules (PEP 503 for PyPI).""" - if eco == "pypi": - return re.sub(r"[-_.]+", "-", name).lower() - if eco == "cargo": - return name.lower() - return name - - -def _tag_stage(tag: str) -> int: - if tag.startswith("post"): - return 1 - if tag.startswith("dev"): - return -4 - if tag in {"a", "alpha"}: - return -3 - if tag in {"b", "beta"}: - return -2 - return -1 - - -def version_key( - ver: str, -) -> tuple[tuple[int, ...], int, tuple[tuple[int, int, str], ...]]: - """Order dev < alpha < beta < rc < final < post releases.""" - base = ver.split("+", 1)[0] - nums: list[int] = [] - tail: list[tuple[int, int, str]] = [] - stage = 0 - in_tail = False - for tok in re.split(r"[.-]", base): - if not tok: - continue - if not in_tail and tok.isdigit(): - nums.append(int(tok)) - continue - m = PRE_SEG_RE.match(tok) if not in_tail else None - if m: - nums.append(int(m.group(1))) - tag = m.group(2).lower() - in_tail = True - stage = _tag_stage(tag) - tail.append((0, 0, tag)) - if m.group(3): - tail.append((1, int(m.group(3)), "")) - continue - low = tok.lower() - if not in_tail: - m2 = re.match(r"^([a-z]+)(\d+)$", low) - if m2: - stage = _tag_stage(m2.group(1)) - in_tail = True - tail.append((0, 0, m2.group(1))) - tail.append((1, int(m2.group(2)), "")) - continue - stage = _tag_stage(low) - in_tail = True - tail.append((1, int(tok), "") if tok.isdigit() else (0, 0, low)) - while len(nums) > 1 and nums[-1] == 0: - nums.pop() - return (tuple(nums), stage, tuple(tail)) - - -def _record_min(bucket: dict[str, str], name: str, ver: str) -> None: - prev = bucket.get(name) - if prev is None or version_key(ver) < version_key(prev): - bucket[name] = ver - - -def parse_workarounds(toml_text: str) -> list[dict[str, object]]: - """Parse ``[[workaround]]`` tables from TOML text.""" - data = tomllib.loads(toml_text) - raw = data.get("workaround", []) - if not isinstance(raw, list): - msg = "'workaround' must be an array of tables" - raise TypeError(msg) - return [dict(item) for item in raw if isinstance(item, dict)] - - -def load_locks(repo_root: pathlib.Path) -> dict[str, dict[str, str]]: - """Read minimum locked versions from uv, Cargo, pnpm, or npm lockfiles.""" - locks: dict[str, dict[str, str]] = {"pypi": {}, "cargo": {}, "npm": {}} - uv_lock = repo_root / "uv.lock" - if uv_lock.is_file(): - data = tomllib.loads(uv_lock.read_text(encoding="utf-8")) - for pkg in data.get("package", []): - if isinstance(pkg, dict) and "name" in pkg and "version" in pkg: - _record_min( - locks["pypi"], - normalize_pkg("pypi", str(pkg["name"])), - str(pkg["version"]), - ) - cargo_lock = repo_root / "Cargo.lock" - if cargo_lock.is_file(): - data = tomllib.loads(cargo_lock.read_text(encoding="utf-8")) - for pkg in data.get("package", []): - if isinstance(pkg, dict) and "name" in pkg and "version" in pkg: - _record_min( - locks["cargo"], - normalize_pkg("cargo", str(pkg["name"])), - str(pkg["version"]), - ) - pnpm_lock = repo_root / "pnpm-lock.yaml" - npm_lock = repo_root / "package-lock.json" - if pnpm_lock.is_file(): - for m in PNPM_PKG_RE.finditer(pnpm_lock.read_text(encoding="utf-8")): - _record_min(locks["npm"], m.group(1), m.group(2)) - elif npm_lock.is_file(): - ndata = json.loads(npm_lock.read_text(encoding="utf-8")) - pkgs = ndata.get("packages", {}) - if isinstance(pkgs, dict): - for k, info in pkgs.items(): - if ( - k.startswith("node_modules/") - and isinstance(info, dict) - and "version" in info - ): - pkg_name = k.rsplit("node_modules/", 1)[-1] - _record_min(locks["npm"], pkg_name, str(info["version"])) - else: - pkg_json = repo_root / "package.json" - if pkg_json.is_file(): - pdata = json.loads(pkg_json.read_text(encoding="utf-8")) - for section in ("dependencies", "devDependencies"): - deps = pdata.get(section, {}) - if isinstance(deps, dict): - for name, spec in deps.items(): - spec_s = str(spec).strip() - if EXACT_VER_RE.match(spec_s): - _record_min(locks["npm"], str(name), spec_s) - return locks - - -def check_entries( - entries: list[dict[str, object]], - locks: dict[str, dict[str, str]], - existing_paths: set[str] | None = None, - file_texts: dict[str, str] | None = None, -) -> list[dict[str, str]]: - """Return violations for missing fields, decoy paths, or met predicates.""" - problems: list[dict[str, str]] = [] - for entry in entries: - wid = str(entry.get("id") or "") - rel_path = str(entry.get("path") or "") - owner = str(entry.get("owner") or "") - issue = str(entry.get("issue") or "") - cond = str(entry.get("remove_when") or "") - if not rel_path or not owner or not ISSUE_URL_RE.match(issue): - problems.append( - { - "id": wid, - "reason": ( - "requires path, owner, and full " - "https://// issue URL" - ), - } - ) - continue - if ( - pathlib.Path(rel_path).suffix.lower() in DOC_SUFFIXES - and entry.get("allow_doc_path") is not True - ): - problems.append( - { - "id": wid, - "reason": ( - f"path '{rel_path}' points to documentation " - "rather than source code" - ), - } - ) - continue - if existing_paths is not None and rel_path not in existing_paths: - problems.append( - { - "id": wid, - "reason": ( - f"path '{rel_path}' does not exist as a regular " - "file inside repository" - ), - } - ) - continue - if file_texts is not None and rel_path in file_texts: - src_txt = file_texts[rel_path] - if wid not in src_txt and issue not in src_txt: - problems.append( - { - "id": wid, - "reason": ( - f"path '{rel_path}' contains neither " - f"workaround id '{wid}' nor issue URL" - ), - } - ) - continue - if DATE_ONLY_RE.match(cond): - problems.append( - { - "id": wid, - "reason": ( - "calendar dates are not allowed in remove_when; " - "use a lockfile predicate or issue_only = true" - ), - } - ) - continue - if not cond: - in_locks = any( - normalize_pkg(eco, owner) in locks.get(eco, {}) - for eco in ("pypi", "cargo", "npm") - ) - if in_locks: - problems.append( - { - "id": wid, - "reason": ( - f"owner '{owner}' is present in lockfiles; " - "specify remove_when instead of issue_only" - ), - } - ) - continue - if ( - entry.get("issue_only") is True - and str(entry.get("reason_no_lock") or "").strip() - ): - continue - problems.append( - { - "id": wid, - "reason": ( - "missing remove_when (or issue_only = true with reason_no_lock)" - ), - } - ) - continue - m = COND_RE.match(cond) - if not m: - problems.append( - { - "id": wid, - "reason": ( - f"invalid remove_when '{cond}'; " - "expected ':>='" - ), - } - ) - continue - eco, pkg, target = m.group(1), m.group(2), m.group(3) - norm_pkg = normalize_pkg(eco, pkg) - locked = locks.get(eco, {}).get(norm_pkg) - if locked is None: - problems.append( - { - "id": wid, - "reason": f"package '{pkg}' not found in {eco} lockfile", - } - ) - continue - if version_key(locked) >= version_key(target): - problems.append( - { - "id": wid, - "reason": ( - f"condition met ({eco}:{pkg} is {locked} >= {target}); " - "remove workaround" - ), - } - ) - return problems - - -def main(argv: list[str] | None = None) -> int: - """Run the CLI check against the repository root and manifest path.""" - args = argv if argv is not None else sys.argv[1:] - repo = pathlib.Path(args[0]).resolve() if args else pathlib.Path.cwd().resolve() - manifest = ( - pathlib.Path(args[1]).resolve() - if len(args) > 1 - else repo / ".github" / "workarounds.toml" - ) - if not manifest.is_file(): - sys.stdout.write(f"{json.dumps({'ok': True, 'checked': 0, 'problems': []})}\n") - return 0 - entries = parse_workarounds(manifest.read_text(encoding="utf-8")) - existing: set[str] = set() - texts: dict[str, str] = {} - for entry in entries: - raw_p = str(entry.get("path") or "") - if not raw_p: - continue - cand = (repo / raw_p).resolve() - if cand.is_relative_to(repo) and cand.is_file(): - existing.add(raw_p) - texts[raw_p] = cand.read_text(encoding="utf-8", errors="replace") - problems = check_entries( - entries, - load_locks(repo), - existing_paths=existing, - file_texts=texts, - ) - payload = {"ok": not problems, "checked": len(entries), "problems": problems} - sys.stdout.write(f"{json.dumps(payload)}\n") - return 0 if not problems else 1 - - -if __name__ == "__main__": - raise SystemExit(main())