{"id":"aae6ea26-a30f-4c53-a156-4a708cddf4c4","entityType":"agent","slug":"clawhub-athola-nm-sanctum-test-updates","name":"test-updates","canonicalUrl":"https://www.xpersona.co/agent/clawhub-athola-nm-sanctum-test-updates","canonicalPath":"/agent/clawhub-athola-nm-sanctum-test-updates","generatedAt":"2026-10-10T11:54:00.878Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-10T09:03:52.916Z","emptyReason":null},"description":"Updates, generates, and validates tests using git-workspace context and TDD/BDD methodology Skill: test-updates Owner: athola Summary: Updates, generates, and validates tests using git-workspace context and TDD/BDD methodology Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:21:11.130Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:41:12.204Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:57:59.998Z | user Release v1.9.16 v1.9.14 | 2026-06-30T18:05:47.824Z | user Release v1.9.14 v1.9.13 | 2026-0","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.5K downloads reported by the source. Last updated 10/10/2026.","installCommand":"clawhub skill install s17emme0e2m3cpf7k2jvp3a84984b8z9:nm-sanctum-test-updates","sourceUrl":"https://clawhub.ai/athola/nm-sanctum-test-updates","homepage":"https://clawhub.ai/athola/skills/nm-sanctum-test-updates","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/athola/nm-sanctum-test-updates","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/athola/skills/nm-sanctum-test-updates","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":64,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Updates, generates, and validates tests using git-workspace context and TDD/BDD methodology Skill: test-updates Owner: athola Summary: Updates, generates, and v"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-10T09:03:52.916Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T09:03:52.916Z","emptyReason":null},"stars":null,"forks":null,"downloads":1539,"packageName":null,"latestVersion":"1.9.19","tractionLabel":"1.5K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T09:03:52.916Z","emptyReason":null},"lastUpdatedAt":"2026-10-10T09:03:52.916Z","lastCrawledAt":"2026-10-10T09:03:52.916Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-11T09:03:52.916Z","lastVerifiedAt":null,"highlights":[{"version":"1.9.19","createdAt":"2026-08-26T13:21:11.130Z","changelog":"Release v1.9.19","fileCount":10,"zipByteSize":23219},{"version":"1.9.17","createdAt":"2026-07-30T05:41:12.204Z","changelog":"Release v1.9.17","fileCount":10,"zipByteSize":23335},{"version":"1.9.16","createdAt":"2026-07-14T19:57:59.998Z","changelog":"Release v1.9.16","fileCount":10,"zipByteSize":23221},{"version":"1.9.14","createdAt":"2026-06-30T18:05:47.824Z","changelog":"Release v1.9.14","fileCount":10,"zipByteSize":23121},{"version":"1.9.13","createdAt":"2026-06-27T16:23:38.291Z","changelog":"Release v1.9.13","fileCount":10,"zipByteSize":23343},{"version":"1.9.12","createdAt":"2026-06-19T03:19:10.032Z","changelog":"Release v1.9.12","fileCount":10,"zipByteSize":23434},{"version":"1.0.3","createdAt":"2026-06-18T15:21:15.565Z","changelog":"Release v1.9.12","fileCount":10,"zipByteSize":23294},{"version":"1.0.2","createdAt":"2026-05-09T02:20:07.513Z","changelog":"Release v1.9.5","fileCount":23,"zipByteSize":27178}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17emme0e2m3cpf7k2jvp3a84984b8z9:nm-sanctum-test-updates","setupComplexity":"low","setupSteps":["Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-sanctum-test-updates/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-sanctum-test-updates/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-sanctum-test-updates/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-sanctum-test-updates/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-sanctum-test-updates/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-sanctum-test-updates/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-10T11:54:00.876Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-sanctum-test-updates/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-sanctum-test-updates/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-sanctum-test-updates/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-sanctum-test-updates/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-10T09:03:52.916Z","emptyReason":null},"readme":"Skill: test-updates\n\nOwner: athola\n\nSummary: Updates, generates, and validates tests using git-workspace context and TDD/BDD methodology\n\nTags: latest:1.9.19\n\nVersion history:\n\nv1.9.19 | 2026-08-26T13:21:11.130Z | user\n\nRelease v1.9.19\n\nv1.9.17 | 2026-07-30T05:41:12.204Z | user\n\nRelease v1.9.17\n\nv1.9.16 | 2026-07-14T19:57:59.998Z | user\n\nRelease v1.9.16\n\nv1.9.14 | 2026-06-30T18:05:47.824Z | user\n\nRelease v1.9.14\n\nv1.9.13 | 2026-06-27T16:23:38.291Z | user\n\nRelease v1.9.13\n\nv1.9.12 | 2026-06-19T03:19:10.032Z | user\n\nRelease v1.9.12\n\nv1.0.3 | 2026-06-18T15:21:15.565Z | user\n\nRelease v1.9.12\n\nv1.0.2 | 2026-05-09T02:20:07.513Z | user\n\nRelease v1.9.5\n\nv1.0.1 | 2026-05-06T14:21:32.423Z | user\n\nRelease v1.9.4\n\nv1.0.0 | 2026-04-20T12:01:37.128Z | auto\n\n- Initial public release of the skill for test update and generation management.\n- Provides TDD/BDD-driven workflows to update, generate, and validate tests using git-workspace-review.\n- Supports targeted or full test updates, quality validation, and detailed QA metrics.\n- Includes quick start guides, troubleshooting, performance tips, and examples for effective integration into projects.\n- Designed to work with pytest and integrate smoothly with CI/CD pipelines and code review processes.\n\nArchive index:\n\nArchive v1.9.19: 10 files, 23219 bytes\n\nFiles: modules/bdd-patterns.md (5571b), modules/content-test-discovery.md (3355b), modules/quality-validation.md (8344b), modules/tdd-workflow.md (3663b), modules/test-discovery.md (2810b), modules/test-enhancement.md (6145b), modules/test-generation.md (13129b), skill-card.md (2073b), SKILL.md (12295b), _meta.json (143b)\n\nFile v1.9.19:SKILL.md\n\n---\nname: test-updates\ndescription: |\n  Updates, generates, and validates tests using git-workspace context and TDD/BDD methodology\nversion: 1.9.8\ntriggers:\n  - tdd\n  - bdd\n  - testing\n  - quality-assurance\n  - test-generation\n  - pytest\n  - code changes require new or updated test coverage\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/sanctum\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.test-driven-development\", \"night-market.git-workspace-review\", \"night-market.file-analysis\"]}}}\nsource: claude-night-market\nsource_plugin: sanctum\n---\n\n> **Night Market Skill** — ported from [claude-night-market/sanctum](https://github.com/athola/claude-night-market/tree/master/plugins/sanctum). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Overview](#overview)\n- [Core Philosophy](#core-philosophy)\n- [What It Is](#what-it-is)\n- [Quick Start](#quick-start)\n- [Quick Checklist for First Time Use](#quick-checklist-for-first-time-use)\n- [detailed Test Update](#detailed-test-update)\n- [Targeted Test Updates](#targeted-test-updates)\n- [TDD for New Features](#tdd-for-new-features)\n- [Using the Scripts Directly](#using-the-scripts-directly)\n- [When to Use It](#when-to-use-it)\n- [Workflow Integration](#workflow-integration)\n- [Phase 1: Discovery](#phase-1:-discovery)\n- [Phase 2: Strategy](#phase-2:-strategy)\n- [Phase 3: Implementation](#phase-3:-implementation)\n- [Phase 4: Validation](#phase-4:-validation)\n- [Quality Assurance](#quality-assurance)\n- [Examples](#examples)\n- [BDD-Style Test Generation](#bdd-style-test-generation)\n- [Test Enhancement](#test-enhancement)\n- [Integration with Existing Skills](#integration-with-existing-skills)\n- [Success Metrics](#success-metrics)\n- [Troubleshooting FAQ](#troubleshooting-faq)\n- [Common Issues](#common-issues)\n- [Performance Tips](#performance-tips)\n- [Getting Help](#getting-help)\n\n\n# Test Updates and Maintenance\n\n## Overview\n\ndetailed test management system that applies TDD/BDD principles to maintain, generate, and enhance tests across codebases. This skill practices what it preaches - it uses TDD principles for its own development and serves as a living example of best practices.\n\n### Core Philosophy\n\n- **RED-GREEN-REFACTOR**: Strict adherence to TDD cycle\n- **Behavior-First**: BDD patterns that describe what code should do\n- **Invariant-Encoding**: Tests guard design decisions, not just behavior\n- **Meta Dogfooding**: The skill's own tests demonstrate the principles it teaches\n- **Quality Gates**: detailed validation before considering tests complete\n\n## What It Is\n\nA modular test management system that:\n- Discovers what needs testing or updating\n- Generates tests following TDD principles\n- Enhances existing tests with BDD patterns\n- Validate test quality through multiple lenses\n\n## Quick Start\n\n### Quick Checklist for First Time Use\n- [ ] validate pytest is installed (`pip install pytest`)\n- [ ] Have your source code in `src/` or similar directory\n- [ ] Create a `tests/` directory if it doesn't exist\n- [ ] Run `Skill(sanctum:git-workspace-review)` first to understand changes\n- [ ] Start with `Skill(test-updates) --target <specific-module>` for focused updates\n\n### detailed Test Update\n```bash\n# Run full test update workflow\nSkill(test-updates)\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### Targeted Test Updates\n```bash\n# Update tests for specific paths\nSkill(test-updates) --target src/sanctum/agents\nSkill(test-updates) --target tests/test_commit_messages.py\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### TDD for New Features\n```bash\n# Apply TDD to new code\nSkill(test-updates) --tdd-only --target new_feature.py\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### Using the Scripts Directly\n\n**Human-Readable Output:**\n```bash\n# Analyze test coverage gaps\npython plugins/sanctum/scripts/test_analyzer.py --scan src/\n\n# Generate test scaffolding\npython plugins/sanctum/scripts/test_generator.py \\\n    --source src/my_module.py --style pytest_bdd\n\n# Check test quality\npython plugins/sanctum/scripts/quality_checker.py \\\n    --validate tests/test_my_module.py\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n**Programmatic Output (for Claude Code):**\n```bash\n# Get JSON output for programmatic parsing - test_analyzer\npython plugins/sanctum/scripts/test_analyzer.py \\\n    --scan src/ --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"source_files\": [\"src/module.py\", ...],\n#     \"test_files\": [\"tests/test_module.py\", ...],\n#     \"uncovered_files\": [\"module_without_tests\", ...],\n#     \"coverage_gaps\": [{\"file\": \"...\", \"reason\": \"...\"}]\n#   }\n# }\n\n# Get JSON output - test_generator\npython plugins/sanctum/scripts/test_generator.py \\\n    --source src/my_module.py --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"test_file\": \"path/to/test_my_module.py\",\n#     \"source_file\": \"src/my_module.py\",\n#     \"style\": \"pytest_bdd\",\n#     \"fixtures_included\": true,\n#     \"edge_cases_included\": true,\n#     \"error_cases_included\": true\n#   }\n# }\n\n# Get JSON output - quality_checker\npython plugins/sanctum/scripts/quality_checker.py \\\n    --validate tests/test_my_module.py --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"static_analysis\": {...},\n#     \"dynamic_validation\": {...},\n#     \"metrics\": {...},\n#     \"quality_score\": 85,\n#     \"quality_level\": \"QualityLevel.GOOD\",\n#     \"recommendations\": [...]\n#   }\n# }\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n## When To Use It\n\n**Use this skill when you need to:**\n- Update tests after code changes\n- Generate tests for new features\n- Improve existing test quality\n- validate detailed test coverage\n\n**Perfect for:**\n- Pre-commit test validation\n- CI/CD pipeline integration\n- Refactoring with test safety\n- Onboarding new developers\n\n## When NOT To Use\n\n- Auditing\n  test suites - use pensive:test-review\n- Writing production code\n  - focus on implementation first\n- Auditing\n  test suites - use pensive:test-review\n- Writing production code\n  - focus on implementation first\n\n## Workflow Integration\n\n### Phase 1: Discovery\n1. Scan codebase for test gaps\n2. Analyze recent changes\n3. Identify broken or outdated tests\n\nSee `modules/test-discovery.md` for detection patterns.\n\n### Phase 2: Strategy\n1. Choose appropriate BDD style (see `modules/bdd-patterns.md`)\n2. Plan test structure\n3. Define quality criteria\n4. Identify design invariants to encode as tests\n\n### Phase 2.5: Invariant-Encoding Tests\n\nBefore writing behavioral tests, identify the design\ninvariants that the code relies on and write tests\nthat would break if those invariants were violated.\n\n**What to encode:**\n\n- Module boundary constraints (A never imports from B)\n- Data flow direction (events flow publisher-to-subscriber,\n  never the reverse)\n- API contract shapes (public interfaces don't change\n  without versioning)\n- Data structure choices (if a map was chosen over a list,\n  test the properties that justify that choice)\n- Error handling strategies (fail-fast boundaries, recovery\n  zones)\n\n**Example:**\n\n```python\ndef test_plugins_never_import_from_other_plugins():\n    \"\"\"Encode the invariant: plugins are independent modules.\n\n    If this test breaks, someone is coupling plugins\n    directly. Present the 3 options to a human:\n    1. Preserve: revert the import, keep plugins independent\n    2. Layer: add a shared interface in leyline instead\n    3. Revise: merge the plugins (requires ADR)\n    \"\"\"\n    for plugin_dir in plugin_dirs:\n        imports = extract_imports(plugin_dir)\n        for imp in imports:\n            assert not imp.startswith(\"plugins.\"), (\n                f\"{plugin_dir} imports {imp} — \"\n                f\"violates plugin independence invariant\"\n            )\n```\n\n**Why this matters:** Tests that encode invariants are\nload-bearing. When an agent later encounters a feature\nthat clashes with the invariant, the test failure forces\na conscious decision rather than a silent drift. Without\nthese tests, bad invariant decisions compound until the\ncodebase is unsalvageable.\n\n**When updating existing tests:**\n\nIf an invariant-encoding test needs to change, do NOT\nsilently update the assertion. Flag it for human review\nwith the three options: preserve the invariant, layer\non top, or revise the invariant. This is a judgment\ncall that requires human wisdom — models default to\nthe \"average\" of training data and get these wrong far\ntoo often.\n\n### Phase 3: Implementation\n1. Write failing tests (RED) - see `modules/tdd-workflow.md`\n2. Implement minimal passing code (GREEN)\n3. Refactor for clarity (REFACTOR)\n\nSee `modules/test-generation.md` for generation templates.\n\n### Phase 4: Validation\n1. Static analysis and linting\n2. Dynamic test execution\n3. Coverage and quality metrics\n\nSee `modules/quality-validation.md` for validation criteria.\n\n## Quality Assurance\n\nThe skill applies multiple quality checks:\n- **Static**: Linting, type checking, pattern validation\n- **Dynamic**: Test execution in sandboxed environments\n- **Metrics**: Coverage, mutation score, complexity analysis\n- **Invariant**: Verify design-decision tests are not weakened\n- **Review**: Structured checklists for peer validation\n\n## Examples\n\n### BDD-Style Test Generation\n\nSee `modules/bdd-patterns.md` for additional patterns.\n```python\nclass TestGitWorkflow:\n    \"\"\"BDD-style tests for Git workflow operations.\"\"\"\n\n    def test_commit_workflow_with_staged_changes(self):\n        \"\"\"\n        GIVEN a Git repository with staged changes\n        WHEN the user runs the commit workflow\n        THEN it should create a commit with proper message format\n        AND all tests should pass\n        \"\"\"\n        # Test implementation following TDD principles\n        pass\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### Test Enhancement\n- Add edge cases and error scenarios\n- Include performance benchmarks\n- Add mutation testing for robustness\n\nSee `modules/test-enhancement.md` for enhancement strategies.\n\n## Integration with Existing Skills\n\n1. **git-workspace-review**: Get context of changes\n2. **file-analysis**: Understand code structure\n3. **test-driven-development**: Apply strict TDD discipline\n4. **skills-eval**: Validate quality and compliance\n\n## Success Metrics\n\n- Test coverage > 85%\n- All tests follow BDD patterns\n- Zero broken tests in CI\n- Mutation score > 80%\n\n## Troubleshooting FAQ\n\n### Common Issues\n\n**Q: Tests are failing after generation**\nA: This is expected! The skill follows TDD principles - generated tests are designed to fail first. Follow the RED-GREEN-REFACTOR cycle:\n1. Run the test and confirm it fails for the right reason\n2. Implement minimal code to make it pass\n3. Refactor for clarity\n\n**Q: Quality score is low despite having tests**\nA: Check for these common issues:\n- Missing BDD patterns (Given/When/Then)\n- Vague assertions like `assert result is not None`\n- Tests without documentation\n- Long, complex tests (>50 lines)\n\n**Q: Generated tests don't match my code structure**\nA: The scripts analyze AST patterns and may need guidance:\n- Use `--style` flag to match your preferred BDD style\n- Check that source files have proper function/class definitions\n- Review the generated scaffolding and customize as needed\n\n**Q: Mutation testing takes too long**\nA: Mutation testing is resource-intensive:\n- Use `--quick-mutation` flag for subset testing\n- Focus on critical modules first\n- Run overnight for detailed analysis\n\n**Q: Can't find tests for my file**\nA: The analyzer uses naming conventions:\n- Source: `my_module.py` → Test: `test_my_module.py`\n- Check that test files follow pytest naming patterns\n- validate test directory structure is standard\n\n### Performance Tips\n\n- **Large codebases**: Use `--target` to focus on specific directories\n- **CI integration**: Run validation in parallel with other checks\n- **Memory usage**: Process files in batches for very large projects\n\n### Getting Help\n\n1. Check script outputs for detailed error messages\n2. Use `--verbose` flag for more information\n3. Review the validation report for specific recommendations\n4. Start with small modules to understand patterns before scaling\n\nFile v1.9.19:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-sanctum-test-updates\",\n  \"version\": \"1.9.19\",\n  \"publishedAt\": 1787750471130\n}\n\nFile v1.9.19:modules/bdd-patterns.md\n\n# BDD Patterns Module\n\n## Overview\n\nProvides multiple Behavior-Driven Development styles and patterns for creating expressive, behavior-focused tests.\n\n## Available Styles\n\n| Style | Best For |\n|-------|----------|\n| Gherkin | Complex workflows, acceptance criteria, cross-team |\n| BDD-pytest | Unit/API tests, developer focus |\n| Docstring BDD | Simple tests, quick docs |\n\n## Choosing the Right Style\n\n### Decision Guide\n\n| Style | Best For | Complexity | Collaboration |\n|-------|----------|------------|----------------|\n| Gherkin | Complex workflows, documentation | High | Excellent |\n| BDD-pytest | Unit/API tests, developer focus | Medium | Good |\n| Docstring BDD | Simple tests, quick docs | Low | Limited |\n\n### Mixing Styles\n- Use Gherkin for critical user journeys\n- Use BDD-pytest for unit and API tests\n- Use Docstring BDD for simple utilities\n- Maintain consistency within modules\n\n## Best Practices\n\n### Naming Conventions\n- **Tests**: `test_[behavior]_[when]_[expected]`\n- **Given/When/Then**: Clear separation of concerns\n- **Scenarios**: Describe business value, not technical details\n\n### Test Organization\nGroup related BDD scenarios in test classes with clear setup and teardown.\n\n---\n\n### Gherkin Style\n\nFeature files with Given/When/Then scenarios for complex user\nworkflows and cross-team collaboration.\n\n#### Feature File Structure\n\n```gherkin\nFeature: Git Workflow Management\n  As a developer\n  I want to automate git workflows\n  So that I can maintain clean commit history\n\n  Scenario: Commit with staged changes\n    Given a git repository with staged changes\n    When I run the commit workflow\n    Then a commit should be created with proper message\n    And all tests should pass\n\n  Scenario Outline: Multiple file types\n    Given a git repository with staged <file_type> files\n    When I run the commit workflow\n    Then the commit should reference <file_type>\n    And the commit type should be <commit_type>\n\n    Examples:\n      | file_type | commit_type |\n      | source    | feat       |\n      | test      | test       |\n      | docs      | docs       |\n```\n\n#### Step Definitions\n\n```python\n@given('a git repository with staged changes')\ndef step_given_git_repo_with_changes(context):\n    context.repo = create_test_repo()\n    context.repo.stage_changes(['file1.py', 'file2.py'])\n\n@when('I run the commit workflow')\ndef step_when_run_commit_workflow(context):\n    context.result = run_commit_workflow(context.repo)\n\n@then('a commit should be created with proper message')\ndef step_then_commit_created(context):\n    assert context.repo.has_commit()\n    assert context.repo.last_commit_message().startswith('feat:')\n```\n\n#### When to Use\n\n- Complex user workflows\n- Acceptance criteria documentation\n- Cross-team collaboration\n- Living documentation requirements\n\n---\n\n### Pytest Style\n\nBDD-style pytest tests with descriptive names and docstrings\nfor unit and API testing.\n\n#### Structure Example\n\n```python\nclass TestGitWorkflow:\n    \"\"\"BDD-style tests for Git workflow operations.\"\"\"\n\n    @pytest.mark.bdd\n    def test_commit_workflow_with_staged_changes(self):\n        \"\"\"\n        GIVEN a Git repository with staged changes\n        WHEN the user runs the commit workflow\n        THEN it should create a commit with proper message format\n        AND all tests should pass\n        \"\"\"\n        # Given\n        repo = create_git_repo()\n        repo.stage_changes(['feature.py'])\n\n        # When\n        result = run_commit_workflow(repo)\n\n        # Then\n        assert result.success is True\n        assert repo.has_commit()\n        assert repo.last_commit_message().startswith('feat:')\n\n    @pytest.mark.bdd\n    def test_commit_workflow_rejects_empty_changes(self):\n        \"\"\"\n        GIVEN a Git repository with no staged changes\n        WHEN the user runs the commit workflow\n        THEN it should reject with appropriate error message\n        \"\"\"\n        # Given\n        repo = create_git_repo()  # No changes staged\n\n        # When\n        result = run_commit_workflow(repo)\n\n        # Then\n        assert result.success is False\n        assert \"no staged changes\" in result.error.lower()\n```\n\n#### Best Practices\n\n- **Descriptive names**: Describe behavior, not implementation\n- **Clear sections**: Use Given/When/Then in docstrings\n- **Single responsibility**: One behavior per test\n- **Meaningful assertions**: Test specific outcomes\n\n#### When to Use\n\n- Unit tests with behavior focus\n- API testing\n- Service layer testing\n- Developer-facing documentation\n\n---\n\n### Docstring Style\n\nSimple BDD pattern using docstrings for quick behavior\ndocumentation and simple unit tests.\n\n#### Structure Example\n\n```python\ndef test_git_status_parsing():\n    \"\"\"Test parsing git status output.\n\n    GIVEN git status output with modified and untracked files\n    WHEN parsing the status\n    THEN it should return structured file information\n    AND correctly identify file states\n    \"\"\"\n    status_output = \"\"\"\n    M modified_file.py\n    A  added_file.py\n    ?? untracked_file.py\n    \"\"\"\n\n    result = parse_git_status(status_output)\n\n    assert 'modified_file.py' in result.modified\n    assert 'added_file.py' in result.added\n    assert 'untracked_file.py' in result.untracked\n```\n\n#### Best Practices\n\n- **Clear docstrings**: Include Given/When/Then\n- **Simple structure**: Ideal for utilities and helpers\n- **Quick documentation**: Minimal overhead for behavior specs\n- **Focused tests**: One clear behavior per test\n\n#### When to Use\n\n- Simple unit tests\n- Internal module testing\n- Quick behavior documentation\n- Utility function testing\n\nFile v1.9.19:modules/content-test-discovery.md\n\n# Content Test Discovery\n\nDetects when modified markdown files are \"execution markdown\" requiring content assertions, and identifies test gaps.\n\n## Execution Markdown Detection\n\nFiles matching ALL of these criteria are execution markdown:\n\n1. File extension is `.md`\n2. Path contains `skills/`, `agents/`, `modules/`, or `commands/`\n3. File is NOT named `README.md`, `CHANGELOG.md`, or located under `docs/` directories\n\n```python\ndef is_execution_markdown(file_path: str) -> bool:\n    \"\"\"Markdown that Claude interprets as behavioral instructions.\"\"\"\n    path = Path(file_path)\n    exec_dirs = {\"skills\", \"agents\", \"modules\", \"commands\"}\n    skip_names = {\"README.md\", \"CHANGELOG.md\"}\n    return (\n        path.suffix == \".md\"\n        and any(d in path.parts for d in exec_dirs)\n        and path.name not in skip_names\n        and \"docs\" not in path.parts\n    )\n```\n\n## Priority Reclassification\n\nOverride the default test-discovery priority scoring for execution markdown:\n\n| Change Type | Priority | Rationale |\n|---|---|---|\n| `SKILL.md` modified | **High** | Directly drives Claude's behavior |\n| Module `.md` modified | **Medium** | Loaded on-demand, affects specific workflows |\n| Agent `.md` modified | **Medium** | Defines agent behavior and constraints |\n| Command `.md` modified | **Low-Medium** | Affects slash command documentation |\n| README, CHANGELOG | Low | Not interpreted by Claude as instructions |\n\n## Test Gap Detection\n\nWhen execution markdown is modified, check for a corresponding content test class.\n\n### Naming Convention\n\n| Source File | Expected Test Location |\n|---|---|\n| `plugins/<plugin>/skills/<name>/SKILL.md` | `plugins/<plugin>/tests/unit/skills/test_<name_underscored>.py` |\n| `plugins/<plugin>/skills/<name>/modules/<mod>.md` | `plugins/<plugin>/tests/unit/skills/test_<name_underscored>.py` |\n| `plugins/<plugin>/agents/<name>.md` | `plugins/<plugin>/tests/unit/test_<name_underscored>.py` |\n\n### Detection Heuristic\n\nLook for existing content test classes by checking:\n\n1. Test file exists at the expected path\n2. File contains a class ending in `Content` (e.g., `TestClearContextSkillContent`)\n3. File contains fixtures that read `.md` files (e.g., `skill_content`, `module_content`)\n\nIf no content test class exists, flag as a content test gap.\n\n## When to Generate vs. Skip\n\nNot every markdown change needs new content tests.\n\n### Generate Content Tests When\n\n- A new skill or module is created (no existing tests)\n- Code examples (JSON, YAML, Python) are added or modified (L2 needed)\n- Version references are added or changed (L3 cross-reference needed)\n- Decision frameworks or behavioral guidance is modified (L3 contract needed)\n- Forbidden behavior patterns are specified (L3 anti-pattern detection needed)\n\n### Skip Content Tests When\n\n- Typo or grammar fix only (no behavioral change)\n- Whitespace or formatting changes\n- Changes to prose that don't affect decision logic\n- Changes already covered by `scribe:slop-detector` (style, not behavior)\n\n## Integration\n\nThis module is loaded during Phase 1 (Discovery) of the test-updates workflow. It extends git-based change detection to recognize execution markdown as high-priority test targets.\n\nReference: `leyline:testing-quality-standards/modules/content-assertion-levels.md` for the L1/L2/L3 taxonomy that determines which level of tests to generate.\n\nFile v1.9.19:modules/quality-validation.md\n\n# Quality Validation Module\n\n## Overview\n\ndetailed test quality assurance through static analysis, dynamic validation, metrics tracking, and structured peer review.\n\n## Validation Categories\n\n### 1. Static Analysis\nValidate test code without execution (details below).\n\n### 2. Dynamic Validation\nExecute tests to verify they actually work (details below).\n\n### 3. Metrics Validation\nTrack quantitative quality measures (details below).\n\n### 4. Peer Review Checklist\nStructured validation for human review.\n\n#### Quality Gates Checklist\n```python\nQUALITY_GATES = {\n    \"structure\": [\n        \"Test follows BDD pattern with Given/When/Then\",\n        \"Test has descriptive name explaining behavior\",\n        \"Test is independent and isolated\",\n        \"Test uses appropriate fixtures or setup\",\n    ],\n    \"assertions\": [\n        \"Assertions are specific and meaningful\",\n        \"Error messages are descriptive\",\n        \"Both positive and negative cases tested\",\n        \"Edge cases are covered\",\n    ],\n    \"maintenance\": [\n        \"Test is readable and understandable\",\n        \"Test data is clearly defined\",\n        \"External dependencies are mocked\",\n        \"Test documentation is adequate\",\n    ],\n    \"performance\": [\n        \"Test runs quickly (< 1 second)\",\n        \"No unnecessary I/O operations\",\n        \"Memory usage is reasonable\",\n        \"Tests are parallelizable\",\n    ],\n}\n```\n\n## Validation Workflow\n\n```python\ndef run_validation_pipeline(test_path, source_path=None):\n    \"\"\"Run complete validation pipeline.\"\"\"\n\n    report = ValidationReport()\n\n    # Phase 1: Static Analysis\n    static_issues = validate_static_quality(test_path)\n    report.add_section(\"Static Analysis\", static_issues)\n\n    # Phase 2: Dynamic Validation\n    execution_results = validate_test_execution(test_path)\n    report.add_section(\"Dynamic Validation\", execution_results)\n\n    # Phase 3: Mutation Testing (if source provided)\n    if source_path:\n        mutation_score = run_mutation_tests(test_path, source_path)\n        report.add_section(\"Mutation Testing\", {\"score\": mutation_score})\n\n    # Phase 4: Metrics Validation\n    coverage_violations = validate_coverage_metrics(execution_results[\"coverage\"])\n    report.add_section(\"Coverage Metrics\", coverage_violations)\n\n    # Phase 5: Complexity Analysis\n    complexity = calculate_test_complexity(test_path)\n    report.add_section(\"Complexity Metrics\", complexity)\n\n    return report\n```\n\n## Quality Standards\n\n### Minimum Requirements\n- **Coverage**: 85% line, 80% branch, 90% function\n- **Mutation Score**: 80% or higher\n- **Test Speed**: < 1 second per test\n- **Independence**: No test dependencies\n- **BDD Compliance**: All tests follow BDD patterns\n\n### Excellence Criteria\n- **Coverage**: 95% line, 90% branch, 100% function\n- **Mutation Score**: 90% or higher\n- **Test Speed**: < 0.5 seconds per test\n- **Documentation**: detailed behavior description\n- **Maintainability**: Clear, readable, well-structured\n\n### Failure Modes\nTests failing validation should:\n1. Generate detailed issue reports\n2. Suggest specific improvements\n3. Provide examples of fixes\n4. Block merging until resolved\n\n---\n\n### Static Analysis\n\nValidate test code without execution using pattern matching\nand AST analysis.\n\n#### Code Quality Checks\n\n```python\ndef validate_static_quality(test_file):\n    \"\"\"Perform static quality validation.\"\"\"\n\n    issues = []\n\n    # Check test naming\n    if not test_has_descriptive_name(test_file):\n        issues.append(\"Test name should describe behavior\")\n\n    # Check BDD structure\n    if not has_bdd_structure(test_file):\n        issues.append(\"Test should follow BDD pattern\")\n\n    # Check assertion quality\n    if has_vague_assertions(test_file):\n        issues.append(\"Use specific, meaningful assertions\")\n\n    # Check test independence\n    if tests_have_dependencies(test_file):\n        issues.append(\"Tests should be independent\")\n\n    return issues\n```\n\n#### Pattern Validation\n\n```python\nBDD_PATTERNS = {\n    \"given_pattern\": r\"GIVEN\\s+.+\",\n    \"when_pattern\": r\"WHEN\\s+.+\",\n    \"then_pattern\": r\"THEN\\s+.+\",\n    \"and_pattern\": r\"AND\\s+.+\",\n}\n\ndef validate_bdd_patterns(test_content):\n    \"\"\"Validate BDD pattern usage.\"\"\"\n    missing_patterns = []\n\n    for pattern_name, pattern_regex in BDD_PATTERNS.items():\n        if not re.search(pattern_regex, test_content, re.IGNORECASE):\n            missing_patterns.append(pattern_name)\n\n    return missing_patterns\n```\n\n#### Validation Categories\n\n- **Naming**: Descriptive, behavior-focused test names\n- **Structure**: Proper BDD patterns and organization\n- **Assertions**: Specific, meaningful checks\n- **Independence**: No test dependencies\n- **Documentation**: Clear docstrings and comments\n\n---\n\n### Dynamic Validation\n\nExecutes tests to verify they actually work and measure their\nquality.\n\n#### Test Execution Validation\n\n```python\ndef validate_test_execution(test_path):\n    \"\"\"Validate test executes correctly.\"\"\"\n\n    results = {\n        \"passes\": False,\n        \"failures\": [],\n        \"errors\": [],\n        \"warnings\": [],\n        \"coverage\": 0,\n    }\n\n    # Run tests in isolated environment\n    test_result = pytest.main([\n        test_path,\n        \"-v\",\n        \"--tb=short\",\n        \"--cov=src\",\n        \"--cov-report=json\",\n    ])\n\n    # Analyze results\n    if test_result == 0:\n        results[\"passes\"] = True\n    else:\n        # Parse failures and errors\n        results[\"failures\"] = parse_test_failures()\n        results[\"errors\"] = parse_test_errors()\n\n    # Load coverage data\n    results[\"coverage\"] = load_coverage_data()\n\n    return results\n```\n\n#### Mutation Testing\n\n```python\ndef run_mutation_tests(test_path, source_path):\n    \"\"\"Run mutation testing to verify test quality.\"\"\"\n\n    mutations = generate_mutations(source_path)\n    killed_mutants = 0\n    total_mutants = len(mutations)\n\n    for mutation in mutations:\n        # Apply mutation\n        apply_mutation(source_path, mutation)\n\n        # Run tests\n        if pytest.main([test_path, \"-q\"]) != 0:\n            killed_mutants += 1  # Test caught the mutation\n\n        # Restore original code\n        restore_original(source_path)\n\n    mutation_score = killed_mutants / total_mutants\n    return mutation_score\n```\n\n#### Performance Testing\n\n- **Execution time**: Tests should run quickly (< 1 second)\n- **Memory usage**: No memory leaks or excessive consumption\n- **Parallel execution**: Tests should run independently\n- **Resource cleanup**: Proper teardown after each test\n\n---\n\n### Quality Metrics\n\nTracks quantitative quality measures for test suites.\n\n#### Coverage Metrics\n\n```python\ndef validate_coverage_metrics(coverage_data):\n    \"\"\"Validate test coverage meets standards.\"\"\"\n\n    metrics = {\n        \"line_coverage\": coverage_data[\"lines_covered\"] / coverage_data[\"lines_valid\"],\n        \"branch_coverage\": coverage_data[\"branches_covered\"] / coverage_data[\"branches_valid\"],\n        \"function_coverage\": coverage_data[\"functions_covered\"] / coverage_data[\"functions_valid\"],\n    }\n\n    standards = {\n        \"line_coverage\": 0.85,  # 85% minimum\n        \"branch_coverage\": 0.80,  # 80% minimum\n        \"function_coverage\": 0.90,  # 90% minimum\n    }\n\n    violations = []\n    for metric, value in metrics.items():\n        if value < standards[metric]:\n            violations.append(f\"{metric}: {value:.1%} < {standards[metric]:.1%}\")\n\n    return violations\n```\n\n#### Test Complexity Metrics\n\n```python\ndef calculate_test_complexity(test_file):\n    \"\"\"Calculate cyclomatic complexity of tests.\"\"\"\n\n    complexity_metrics = {\n        \"average_assertions_per_test\": 0,\n        \"test_length_violations\": 0,\n        \"setup_complexity\": 0,\n        \"mock_count\": 0,\n    }\n\n    # Analyze each test\n    for test in extract_tests(test_file):\n        assertions = count_assertions(test)\n        if assertions > 5:\n            complexity_metrics[\"test_length_violations\"] += 1\n\n        complexity_metrics[\"average_assertions_per_test\"] += assertions\n        complexity_metrics[\"mock_count\"] += count_mocks(test)\n\n    complexity_metrics[\"average_assertions_per_test\"] /= len(extract_tests(test_file))\n\n    return complexity_metrics\n```\n\n#### Quality Score Calculation\n\nCombine multiple metrics into an overall score:\n- Static analysis (20%)\n- Dynamic validation (30%)\n- Coverage metrics (20%)\n- Mutation testing (20%)\n- Complexity (10%)\n\nFile v1.9.19:modules/tdd-workflow.md\n\n# TDD Workflow Module\n\n## Table of Contents\n- [Overview](#overview)\n- [The TDD Cycle](#the-tdd-cycle)\n  - [RED Phase: Write Failing Test](#red-phase-write-failing-test)\n  - [GREEN Phase: Minimal Implementation](#green-phase-minimal-implementation)\n  - [REFACTOR Phase: Clean Up](#refactor-phase-clean-up)\n- [TDD Discipline Rules](#tdd-discipline-rules)\n- [Error Handling in TDD](#error-handling-in-tdd)\n- [Advanced TDD Patterns](#advanced-tdd-patterns)\n\n## Overview\n\nImplements strict Test-Driven Development workflow with RED-GREEN-REFACTOR cycle. This module validates all test creation follows proper TDD discipline.\n\n## The TDD Cycle\n\n### RED Phase: Write Failing Test\n\n**Principles:**\n- Write ONE test at a time\n- Test must FAIL for the right reason\n- No production code exists yet\n- Test describes desired behavior\n\n**Implementation Pattern:**\n```python\ndef test_new_feature_behavior():\n    \"\"\"\n    GIVEN a specific context\n    WHEN an action is performed\n    THEN expected outcome occurs\n    \"\"\"\n    # Arrange - Set up test context\n    context = create_test_context()\n\n    # Act - Execute the behavior\n    result = perform_action(context)\n\n    # Assert - Verify the outcome\n    assert result == expected_value\n\n# Run and verify it fails: pytest -xvs test_file.py::test_new_feature_behavior\n```\n\n### Verification Steps\n1. **Run the test**: Must fail\n2. **Check failure reason**: Should be \"feature not implemented\"\n3. **Confirm test quality**: Clear, focused, one behavior\n\n### GREEN Phase: Minimal Implementation\n\n**Principles:**\n- Write simplest code to pass\n- No extra features\n- Don't fix other tests\n- Keep it ugly if it works\n\n**Implementation Pattern:**\n```python\n# Minimal implementation - just enough to pass\ndef perform_action(context):\n    if context.should_succeed:\n        return expected_value\n    raise NotImplementedError(\"Feature not yet implemented\")\n```\n\n### Verification Steps\n1. **Run the test**: Must pass\n2. **Check other tests**: All still passing\n3. **No warnings/errors**: Clean execution\n\n### REFACTOR Phase: Clean Up\n\n**Principles:**\n- Tests must stay green\n- Remove duplication\n- Improve names and structure\n- Add necessary abstractions\n\n**Refactoring Checklist:**\n- [ ] Extract magic numbers to constants\n- [ ] Improve variable names\n- [ ] Remove code duplication\n- [ ] Add helpful comments\n- [ ] validate single responsibility\n\n## TDD Discipline Rules\n\n### Iron Rules\n1. **NO production code without a failing test first**\n2. **Watch it fail** - Don't skip this step\n3. **Write minimal code** - No extra features\n4. **Refactor only when green** - Clean up with safety net\n\n### Common Violations to Avoid\n- Writing code before tests\n- \"I'll test it after\" mentality\n- Keeping implementation as \"reference\"\n- Skipping the failure verification\n- Adding extra features in GREEN phase\n\n## Error Handling in TDD\n\n### Test Errors vs Failures\n- **Error**: Syntax, imports, setup issues - Fix immediately\n- **Failure**: Assertion fails - Good! This is expected\n\n### Debugging Process\n1. Test fails unexpectedly → Check test logic\n2. Implementation doesn't work → Simplify further\n3. Other tests break → Check for side effects\n\n## Advanced TDD Patterns\n\n### Outside-In TDD\n- Start with acceptance/feature tests\n- Work inward to unit tests\n- Maintain failing test chain\n\n### Mocking Strategies\n- Mock external dependencies\n- Use dependency injection\n- Test behavior, not implementation\n\n### Parameterized Tests\n```python\n@pytest.mark.parametrize(\"input,expected\", [\n    (\"valid_input\", \"expected_output\"),\n    (\"edge_case\", \"edge_output\"),\n])\ndef test_multiple_scenarios(input, expected):\n    assert process(input) == expected\n```\n\nFile v1.9.19:modules/test-discovery.md\n\n# Test Discovery Module\n\n## Overview\n\nIdentifies what needs testing or updating by analyzing code structure, git changes, and existing test coverage.\n\n## Discovery Strategies\n\n### 1. detailed Codebase Scan\n- Analyze all Python files for test coverage\n- Identify functions, classes, and modules without tests\n- Check for public API without corresponding tests\n\n### 2. Git-Based Change Detection\n- Parse `git diff` to find modified files\n- Identify new functions or changed signatures\n- Detect breaking changes requiring test updates\n\n### 3. Targeted Analysis\n- Accept specific paths or patterns\n- Deep dive into particular modules\n- Custom filters based on user criteria\n\n## Analysis Patterns\n\n### Code Structure Analysis\n```python\n# Example patterns for identifying test needs\ndef discover_test_targets(codebase_path):\n    \"\"\"Discover what needs testing.\"\"\"\n\n    # Find Python modules\n    modules = find_python_modules(codebase_path)\n\n    # Analyze each module for test coverage\n    for module in modules:\n        public_functions = extract_public_functions(module)\n        test_coverage = analyze_existing_tests(module)\n\n        if test_coverage < 1.0:  # 100% coverage target\n            report_missing_tests(module, public_functions, test_coverage)\n```\n\n### Change Impact Analysis\n```python\ndef analyze_git_changes():\n    \"\"\"Analyze git changes for test impact.\"\"\"\n\n    # Get changed files\n    changed_files = git_diff --name-only HEAD~1\n\n    # Categorize changes\n    for file in changed_files:\n        if file.endswith('.py'):\n            if is_test_file(file):\n                mark_for_review(file)  # May need updates\n            else:\n                mark_for_test_update(file)  # Code changed\n```\n\n## Discovery Outputs\n\n### Test Gap Report\n- Missing test files\n- Uncovered functions/methods\n- Modules with low coverage\n- Edge cases not tested\n\n### Change Impact Report\n- Files modified since last test run\n- Functions with changed signatures\n- Breaking changes detected\n- Integration points affected\n\n### Priority Scoring\n\n- **High**: Public API changes, execution markdown changes (SKILL.md files, agent definitions)\n- **Medium**: Internal refactoring, module markdown changes (files under `modules/` directories)\n- **Low**: README, CHANGELOG, non-execution documentation, test-only changes\n\n#### Execution Markdown Detection\n\nFiles under `skills/`, `agents/`, `modules/`, or `commands/` with `.md` extension are execution markdown -- Claude interprets them as behavioral instructions. These are NOT low-priority documentation changes.\n\nWhen execution markdown is modified, check for corresponding content tests using the L1/L2/L3 taxonomy. See `modules/content-test-discovery.md` for detection heuristics and gap analysis, and `modules/generation/content-test-templates.md` for BDD test scaffolding.\n\nFile v1.9.19:modules/test-enhancement.md\n\n# Test Enhancement Module\n\n## Overview\n\nImproves existing tests by applying BDD patterns, adding edge cases, and increasing test quality. Transforms basic tests into detailed behavior specifications.\n\n## Enhancement Strategies\n\n### 1. BDD Pattern Application\nTransforms traditional tests into BDD-style tests (details below).\n\n### 2. Edge Case Expansion\nAdds detailed edge case testing (details below).\n\n### 3. Test Organization\nImproves test structure and maintainability (details below).\n\n## Quality Enhancement Rules\n\n### The Rule of Three\nFor every assertion, add:\n1. **Positive case**: Expected behavior\n2. **Negative case**: Error handling\n3. **Edge case**: Boundary condition\n\n### AAA Pattern (Arrange-Act-Assert)\n```python\ndef test_workflow():\n    # Arrange - Setup everything needed\n    context = create_test_context()\n    expected = prepare_expected_result()\n\n    # Act - Perform the action\n    result = perform_action(context)\n\n    # Assert - Verify outcomes\n    assert result == expected\n```\n\n### Test Data Factory Pattern\nCreate reusable test data factories for consistent test setup.\n\n## Enhancement Checklist\n\nFor each existing test:\n- [ ] Add BDD-style docstring with Given/When/Then\n- [ ] Include edge cases and error scenarios\n- [ ] Use descriptive test names\n- [ ] Add appropriate fixtures\n- [ ] Verify test independence\n- [ ] Add performance assertions if relevant\n- [ ] Include behavior documentation\n- [ ] Mock external dependencies appropriately\n\n---\n\n### BDD Transformation\n\nTransforms traditional tests into BDD-style tests with clear\nbehavior specifications.\n\n#### Before: Traditional Test\n\n```python\ndef test_commit():\n    repo = GitRepo()\n    repo.add('file.txt')\n    result = repo.commit('message')\n    assert result is True\n```\n\n#### After: BDD-Style Test\n\n```python\n@pytest.mark.bdd\ndef test_commit_workflow_with_staged_file():\n    \"\"\"\n    GIVEN a Git repository with a staged file\n    WHEN the user commits with a message\n    THEN the commit should be created successfully\n    AND the commit message should match\n    \"\"\"\n    # Given\n    repo = GitRepo()\n    repo.add('file.txt')\n\n    # When\n    result = repo.commit('Add new feature')\n\n    # Then\n    assert result is True\n    assert repo.get_last_commit_message() == 'Add new feature'\n```\n\n#### Transformation Steps\n\n1. **Add descriptive test name**: Describe behavior, not implementation\n2. **Add BDD docstring**: Include Given/When/Then clauses\n3. **Structure test with AAA**: Arrange-Act-Assert\n4. **Add specific assertions**: Test behavior, not just truthiness\n\n---\n\n### Edge Cases\n\nSystematically adds detailed edge case testing to existing tests.\n\n#### The Rule of Three\n\nFor every assertion, add:\n1. **Positive case**: Expected behavior\n2. **Negative case**: Error handling\n3. **Edge case**: Boundary condition\n\n#### Example Expansion\n\n**Original:**\n```python\ndef test_parse_number():\n    assert parse_number(\"123\") == 123\n```\n\n**Enhanced:**\n```python\n@pytest.mark.parametrize(\"input_str,expected,description\", [\n    (\"123\", 123, \"valid positive integer\"),\n    (\"-456\", -456, \"valid negative integer\"),\n    (\"0\", 0, \"zero value\"),\n    (\"3.14\", 3.14, \"valid float\"),\n    (\"1e5\", 100000, \"scientific notation\"),\n])\ndef test_parse_number_valid_inputs(input_str, expected, description):\n    \"\"\"\n    GIVEN various valid number strings\n    WHEN parsing the string\n    THEN it should return the correct number\n    \"\"\"\n    assert parse_number(input_str) == expected\n\n@pytest.mark.parametrize(\"invalid_input\", [\n    \"abc\",\n    \"\",\n    \"12.34.56\",\n    \"1,234\",\n    None,\n])\ndef test_parse_number_invalid_inputs(invalid_input):\n    \"\"\"\n    GIVEN invalid number inputs\n    WHEN parsing the string\n    THEN it should raise a ValueError\n    \"\"\"\n    with pytest.raises(ValueError):\n        parse_number(invalid_input)\n```\n\n#### Common Edge Cases\n\n- **Strings**: Empty, whitespace, special characters, unicode\n- **Numbers**: Zero, negative, maximum/minimum values, infinity\n- **Collections**: Empty, single item, maximum capacity\n- **Dates**: Leap years, timezone changes, daylight saving\n- **Files**: Missing, permissions, full disk, network errors\n\n---\n\n### Organization Patterns\n\nRestructures tests for better maintainability and clarity.\n\n#### Test Organization Example\n\n```python\nclass TestGitRepository:\n    \"\"\"BDD-style test suite for GitRepository operations.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_repo(self, tmp_path):\n        \"\"\"Setup a test repository for each test.\"\"\"\n        self.repo_path = tmp_path / \"test_repo\"\n        self.repo = GitRepository(self.repo_path)\n        self.repo.init()\n\n    @pytest.mark.bdd\n    def test_init_creates_git_directory(self):\n        \"\"\"\n        GIVEN a directory path\n        WHEN initializing a git repository\n        THEN it should create a .git directory\n        \"\"\"\n        assert (self.repo_path / \".git\").exists()\n\n    @pytest.mark.bdd\n    def test_init_with_existing_repo_raises_error(self):\n        \"\"\"\n        GIVEN an existing git repository\n        WHEN initializing again\n        THEN it should raise RepositoryError\n        \"\"\"\n        with pytest.raises(RepositoryError):\n            GitRepository(self.repo_path).init()\n```\n\n#### AAA Pattern (Arrange-Act-Assert)\n\n```python\ndef test_workflow():\n    # Arrange - Setup everything needed\n    context = create_test_context()\n    expected = prepare_expected_result()\n\n    # Act - Perform the action\n    result = perform_action(context)\n\n    # Assert - Verify outcomes\n    assert result == expected\n```\n\n#### Test Data Factory Pattern\n\n```python\nclass TestDataFactory:\n    \"\"\"Factory for creating test data.\"\"\"\n\n    @staticmethod\n    def create_git_repo(branch=\"main\", with_commits=False):\n        repo = GitRepository()\n        repo.init(branch)\n\n        if with_commits:\n            repo.add(\"README.md\")\n            repo.commit(\"Initial commit\")\n\n        return repo\n\n    @staticmethod\n    def create_user(role=\"user\", **overrides):\n        default_user = {\n            \"name\": \"Test User\",\n            \"email\": \"test@example.com\",\n            \"role\": role,\n        }\n        default_user.update(overrides)\n        return User(**default_user)\n```\n\nFile v1.9.19:modules/test-generation.md\n\n# Test Generation Module\n\n## Overview\n\nAutomated test scaffolding and generation following TDD/BDD principles. Creates test templates that developers complete using proper TDD workflow.\n\n## Capabilities\n\n- **Generation strategies**: Code analysis, git change detection, API-based\n- **Test templates**: Function, class, and API scaffolding\n- **Smart features**: Parameter discovery, error scenarios, context-aware patterns\n- **Content tests**: BDD templates for skill content assertions\n\n## Workflow\n\n1. **Analyze**: Parse code structure and dependencies\n2. **Discover**: Identify test scenarios and edge cases\n3. **Generate**: Create test scaffolding with BDD patterns\n4. **Review**: Validate generated tests\n5. **Complete**: Developer finishes with TDD cycle\n\n## Best Practices\n\n### Do Generate\n- Test scaffolding with TODO comments\n- BDD-style structure templates\n- Parameterized test skeletons\n- Mock/stub setup patterns\n\n### Don't Generate\n- Actual test implementations\n- Complex assertions\n- Business logic\n- Mock behavior (too specific)\n\n---\n\n### Generation Strategies\n\nDifferent approaches for discovering what needs testing and\ngenerating appropriate test scaffolding.\n\n#### From Code Analysis\n\nAnalyzes existing code to generate appropriate test scaffolding.\n\n```python\ndef generate_tests_from_code(code_path):\n    \"\"\"Generate test scaffolding from code analysis.\"\"\"\n\n    # Parse the code\n    ast_tree = ast.parse(open(code_path).read())\n\n    # Extract testable elements\n    functions = extract_functions(ast_tree)\n    classes = extract_classes(ast_tree)\n\n    # Generate test templates\n    for func in functions:\n        generate_function_test_template(func)\n\n    for cls in classes:\n        generate_class_test_template(cls)\n```\n\n#### From Git Changes\n\nGenerates tests for new or modified code.\n\n```python\ndef generate_tests_for_changes(git_diff):\n    \"\"\"Generate tests based on git changes.\"\"\"\n\n    changes = parse_git_diff(git_diff)\n\n    for change in changes:\n        if change.type == 'new_function':\n            generate_new_function_test(change)\n        elif change.type == 'modified_signature':\n            generate_updated_test(change)\n        elif change.type == 'new_class':\n            generate_class_test_suite(change)\n```\n\n#### From API Definitions\n\nGenerates integration tests from API contracts or OpenAPI specs.\n\n```python\ndef generate_api_tests(openapi_spec):\n    \"\"\"Generate BDD-style API tests from OpenAPI spec.\"\"\"\n\n    for endpoint in openapi_spec.paths:\n        for method in endpoint.methods:\n            generate_endpoint_test(endpoint, method)\n```\n\n#### Strategy Selection\n\nChoose based on your needs:\n- **Code Analysis**: For existing code without tests\n- **Git Changes**: For recent modifications\n- **API Definitions**: For contract-first development\n\n---\n\n### Test Templates\n\nStandard templates for different types of tests following BDD\npatterns.\n\n#### Function Test Template\n\n```python\ndef test_{function_name}_{scenario}():\n    \"\"\"\n    GIVEN {given_context}\n    WHEN {when_action}\n    THEN {then_expected}\n    \"\"\"\n    # TODO: Arrange - Set up test context\n    # TODO: Act - Execute the function\n    # TODO: Assert - Verify the outcome\n    pass\n```\n\n#### Class Test Template\n\n```python\nclass Test{ClassName}:\n    \"\"\"BDD-style tests for {ClassName} behavior.\"\"\"\n\n    def setup_method(self):\n        \"\"\"Setup test instance.\"\"\"\n        self.instance = {ClassName}()\n\n    @pytest.mark.bdd\n    def test_{method_name}_{scenario}(self):\n        \"\"\"\n        GIVEN {given_context}\n        WHEN {when_action}\n        THEN {then_expected}\n        \"\"\"\n        # TODO: Implement test following BDD pattern\n        pass\n\n    def teardown_method(self):\n        \"\"\"Cleanup after each test.\"\"\"\n        pass\n```\n\n#### API Test Template\n\n```python\n@pytest.mark.bdd\ndef test_{endpoint}_{method}_{scenario}(client):\n    \"\"\"\n    GIVEN {given_context}\n    WHEN making {method} request to {endpoint}\n    THEN response should be {expected_status}\n    AND response should contain {expected_content}\n    \"\"\"\n    # TODO: Setup request data\n    # TODO: Make API call\n    # TODO: Verify response\n    pass\n```\n\n#### Using Templates\n\nTemplates provide scaffolding that developers complete using TDD:\n1. Write the failing test (RED)\n2. Implement minimal code to pass (GREEN)\n3. Refactor for clarity (REFACTOR)\n\n---\n\n### Smart Features\n\nAdvanced features that make test generation more intelligent\nand context-aware.\n\n#### Parameter Discovery\n\n```python\ndef discover_test_parameters(func):\n    \"\"\"Discover parameters for test generation.\"\"\"\n\n    params = inspect.signature(func).parameters\n\n    test_cases = []\n\n    # Happy path\n    test_cases.append(generate_happy_path_test(params))\n\n    # Edge cases\n    for param in params:\n        if param.annotation == str:\n            test_cases.append(generate_string_edge_cases(param.name))\n        elif param.annotation == int:\n            test_cases.append(generate_numeric_edge_cases(param.name))\n\n    return test_cases\n```\n\n#### Error Scenario Generation\n\n```python\ndef generate_error_scenarios(func):\n    \"\"\"Generate error handling test scenarios.\"\"\"\n\n    scenarios = []\n\n    # Type errors\n    scenarios.extend(generate_type_error_tests(func))\n\n    # Value errors\n    scenarios.extend(generate_value_error_tests(func))\n\n    # Dependency errors\n    scenarios.extend(generate_dependency_error_tests(func))\n\n    return scenarios\n```\n\n#### Context-Aware Patterns\n\nRecognizes common patterns to generate specialized tests:\n- Repository pattern\n- Service pattern\n- Command pattern\n- Factory pattern\n\n#### Quality-Aware Generation\n\nIncludes:\n- Smart assertion generation\n- Parameterized test skeletons\n- Mock/stub setup patterns\n\n---\n\n### Content Test Templates\n\nBDD test templates for each content assertion level. Use these\nas scaffolding when generating content tests for execution\nmarkdown files.\n\nReference: `leyline:testing-quality-standards/modules/content-assertion-levels.md`\n\n#### Level 1: Keyword Presence\n\nMinimum viable content test. Validates structural completeness.\n\n```python\nfrom pathlib import Path\nimport pytest\n\n\nclass TestExampleSkillContent:  # Rename to match your skill\n    \"\"\"Feature: example skill has required structural elements.\n\n    As a skill interpreted by Claude Code\n    I want all required sections to be present\n    So that Claude has complete instructions to follow.\n\n    Level 1: Structural presence checks.\n    \"\"\"\n\n    @pytest.fixture\n    def skill_path(self) -> Path:\n        # Adjust \"example-skill\" to your actual skill directory name\n        return Path(__file__).parents[3] / \"skills\" / \"example-skill\" / \"SKILL.md\"\n\n    @pytest.fixture\n    def skill_content(self, skill_path: Path) -> str:\n        return skill_path.read_text()\n\n    @pytest.mark.bdd\n    @pytest.mark.unit\n    def test_skill_has_required_sections(self, skill_content: str) -> None:\n        \"\"\"Given the skill content\n        When Claude loads it for execution\n        Then all required sections must be present.\"\"\"\n        required = [\n            \"## When To Use\",\n            \"## When NOT To Use\",\n            # Add skill-specific required sections\n        ]\n        for section in required:\n            assert section in skill_content, f\"Missing '{section}'\"\n\n    @pytest.mark.bdd\n    @pytest.mark.unit\n    @pytest.mark.parametrize(\"module_name\", [\n        # List modules referenced in SKILL.md\n    ])\n    def test_referenced_modules_exist(\n        self, skill_path: Path, module_name: str\n    ) -> None:\n        \"\"\"Given modules referenced in the skill\n        Then each must exist on disk with content.\"\"\"\n        module_path = skill_path.parent / \"modules\" / module_name\n        assert module_path.exists(), f\"Referenced module {module_name} not found\"\n        content = module_path.read_text()\n        min_lines = 10\n        assert len(content.splitlines()) >= min_lines, (\n            f\"Module {module_name} has fewer than {min_lines} lines\"\n        )\n```\n\n#### Level 2: Code Example Validity\n\nValidates embedded code examples parse correctly and have\nrequired schema.\n\n```python\nimport json\nimport re\n\n# --- Level 2: Code example validity ---\n# Add these methods inside your Test*Content class\n\n@pytest.fixture\ndef json_code_blocks(self, skill_content: str):\n    \"\"\"Extract all JSON code blocks from the skill.\"\"\"\n    return re.findall(r\"```json\\n(.*?)```\", skill_content, re.DOTALL)\n\n@pytest.mark.bdd\n@pytest.mark.unit\ndef test_all_json_examples_parse(self, json_code_blocks) -> None:\n    \"\"\"Given JSON code blocks in the skill\n    When Claude copies them as configuration templates\n    Then every block must be valid JSON.\"\"\"\n    assert len(json_code_blocks) > 0, \"Skill should contain JSON examples\"\n    for i, block in enumerate(json_code_blocks):\n        try:\n            json.loads(block)\n        except json.JSONDecodeError as exc:\n            pytest.fail(f\"JSON block #{i + 1} is invalid: {exc}\")\n\n@pytest.mark.bdd\n@pytest.mark.unit\ndef test_version_references_exist(self, skill_content: str) -> None:\n    \"\"\"Given version references in the skill\n    Then each must follow semantic versioning format.\"\"\"\n    versions = re.findall(r\"\\d+\\.\\d+\\.\\d+\", skill_content)\n    # Verify at least one version reference exists\n    # (adjust based on whether skill uses version gates)\n    assert len(versions) >= 1, \"Expected at least one version reference\"\n```\n\n#### Level 3: Behavioral Contracts\n\nValidates semantic correctness, cross-references, and\nanti-patterns.\n\n```python\n# --- Level 3: Behavioral contracts ---\n# Add these methods inside your Test*Content class\n# Requires: re (imported in Level 2), Path (imported in Level 1)\n\n@pytest.mark.bdd\n@pytest.mark.unit\ndef test_no_forbidden_language(self, skill_content: str) -> None:\n    \"\"\"Given the skill instructs Claude's behavior\n    When Claude reads the instructions\n    Then it must NOT find manipulative imperatives.\n\n    Imperative language causes Claude to ignore user intent\n    and force actions without consent.\n    \"\"\"\n    forbidden = [\n        \"YOU MUST EXECUTE THIS NOW\",\n        \"MANDATORY AUTO-CONTINUATION\",\n        # Add context-specific forbidden phrases\n    ]\n    for phrase in forbidden:\n        assert phrase not in skill_content, (\n            f\"Contains manipulative language: '{phrase}'. \"\n            \"Instructions should be informational, not imperative.\"\n        )\n\n@pytest.mark.bdd\n@pytest.mark.unit\ndef test_offers_multiple_strategies(self, skill_content: str) -> None:\n    \"\"\"Given the skill guides Claude's decisions\n    Then it must offer multiple approaches, not force one path.\n\n    Single-path guidance removes user agency.\n    \"\"\"\n    strategies = [\n        # List expected alternative strategies\n    ]\n    found = [s for s in strategies if s.lower() in skill_content.lower()]\n    min_strategies = 3\n    assert len(found) >= min_strategies, (\n        f\"Too few strategies: {found}, need at least {min_strategies}\"\n    )\n\n@pytest.mark.bdd\n@pytest.mark.unit\ndef test_version_refs_cross_reference_docs(\n    self, skill_content: str\n) -> None:\n    \"\"\"Given version references in the skill\n    Then each must exist in compatibility documentation.\n\n    Prevents Claude from citing nonexistent versions.\n    \"\"\"\n    versions = set(re.findall(r\"2\\.1\\.(\\d+)\", skill_content))\n    compat_dir = (\n        Path(__file__).parents[4]  # Adjust depth for your test location\n        / \"abstract\"\n        / \"docs\"\n        / \"compatibility\"\n    )\n    compat_content = \"\"\n    for compat_file in compat_dir.glob(\"compatibility-features*.md\"):\n        compat_content += compat_file.read_text()\n\n    for minor in versions:\n        version_str = f\"2.1.{minor}\"\n        assert version_str in compat_content, (\n            f\"References {version_str} but it's missing from \"\n            \"compatibility-features*.md\"\n        )\n```\n\n#### Choosing the Right Level\n\n| Observed in Git Diff | Start With |\n|---|---|\n| New skill or module created | L1 (sections and modules exist) |\n| JSON/YAML code blocks added or modified | L2 (parse and schema) |\n| Version references added or changed | L3 (cross-reference) |\n| Behavioral guidance added (decision trees, strategies) | L3 (contracts) |\n| Forbidden behavior patterns specified | L3 (anti-pattern detection) |\n| Simple section reordering or prose editing | L1 if no tests exist, skip otherwise |\n\n#### Common Fixtures\n\nThese fixtures appear across all three exemplar test classes:\n\n```python\n@pytest.fixture\ndef skill_path(self) -> Path:\n    \"\"\"Resolve path to the skill file under test.\"\"\"\n    depth = 3  # Adjust based on test file location relative to plugin root\n    return Path(__file__).parents[depth] / \"skills\" / \"skill-name\" / \"SKILL.md\"\n\n@pytest.fixture\ndef skill_content(self, skill_path: Path) -> str:\n    \"\"\"Read the full skill content for assertion.\"\"\"\n    return skill_path.read_text()\n\n@pytest.fixture\ndef module_path(self) -> Path:\n    \"\"\"Resolve path to a specific module file.\"\"\"\n    depth = 3  # Adjust based on test file location relative to plugin root\n    return Path(__file__).parents[depth] / \"skills\" / \"skill-name\" / \"modules\" / \"module.md\"\n```\n\nAdjust `parents[N]` based on your test file's depth relative\nto the plugin root.\n\nFile v1.9.19:skill-card.md\n\n## Description:\n\nUpdates, generates, and validates tests using git-workspace context and TDD/BDD methodology.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[athola](https://clawhub.ai/user/athola)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and engineers use this skill to discover test gaps, generate TDD/BDD-oriented test scaffolding, enhance existing tests, and validate test quality after code changes.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Test execution and generated test changes may modify project files.\n\nMitigation: Run the skill in a virtual environment and on a branch or disposable worktree, then review diffs before committing.\n\nRisk: Mutation-testing guidance may alter source files in place.\n\nMitigation: Avoid mutation testing in the main working tree; use backups or a disposable worktree and restore changes after the run.\n\nRisk: Generated tests may fail first or encode the wrong behavior if accepted without review.\n\nMitigation: Review generated scaffolding and confirm failing tests express the intended behavior before implementing code to pass them.\n\n## Reference(s):\n\n- [ClawHub skill page](https://clawhub.ai/athola/skills/nm-sanctum-test-updates)\n- [Clawdis homepage](https://github.com/athola/claude-night-market/tree/master/plugins/sanctum)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown guidance with code examples, shell commands, test scaffolding, and validation checklists]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May propose or modify test-related files and may recommend running project test commands.]\n\n## Skill Version(s):\n\n1.9.19 (source: server release evidence)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nArchive v1.9.17: 10 files, 23335 bytes\n\nFiles: modules/bdd-patterns.md (5571b), modules/content-test-discovery.md (3355b), modules/quality-validation.md (8344b), modules/tdd-workflow.md (3663b), modules/test-discovery.md (2810b), modules/test-enhancement.md (6145b), modules/test-generation.md (13129b), skill-card.md (2385b), SKILL.md (12295b), _meta.json (143b)\n\nFile v1.9.17:SKILL.md\n\n---\nname: test-updates\ndescription: |\n  Updates, generates, and validates tests using git-workspace context and TDD/BDD methodology\nversion: 1.9.8\ntriggers:\n  - tdd\n  - bdd\n  - testing\n  - quality-assurance\n  - test-generation\n  - pytest\n  - code changes require new or updated test coverage\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/sanctum\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.test-driven-development\", \"night-market.git-workspace-review\", \"night-market.file-analysis\"]}}}\nsource: claude-night-market\nsource_plugin: sanctum\n---\n\n> **Night Market Skill** — ported from [claude-night-market/sanctum](https://github.com/athola/claude-night-market/tree/master/plugins/sanctum). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Overview](#overview)\n- [Core Philosophy](#core-philosophy)\n- [What It Is](#what-it-is)\n- [Quick Start](#quick-start)\n- [Quick Checklist for First Time Use](#quick-checklist-for-first-time-use)\n- [detailed Test Update](#detailed-test-update)\n- [Targeted Test Updates](#targeted-test-updates)\n- [TDD for New Features](#tdd-for-new-features)\n- [Using the Scripts Directly](#using-the-scripts-directly)\n- [When to Use It](#when-to-use-it)\n- [Workflow Integration](#workflow-integration)\n- [Phase 1: Discovery](#phase-1:-discovery)\n- [Phase 2: Strategy](#phase-2:-strategy)\n- [Phase 3: Implementation](#phase-3:-implementation)\n- [Phase 4: Validation](#phase-4:-validation)\n- [Quality Assurance](#quality-assurance)\n- [Examples](#examples)\n- [BDD-Style Test Generation](#bdd-style-test-generation)\n- [Test Enhancement](#test-enhancement)\n- [Integration with Existing Skills](#integration-with-existing-skills)\n- [Success Metrics](#success-metrics)\n- [Troubleshooting FAQ](#troubleshooting-faq)\n- [Common Issues](#common-issues)\n- [Performance Tips](#performance-tips)\n- [Getting Help](#getting-help)\n\n\n# Test Updates and Maintenance\n\n## Overview\n\ndetailed test management system that applies TDD/BDD principles to maintain, generate, and enhance tests across codebases. This skill practices what it preaches - it uses TDD principles for its own development and serves as a living example of best practices.\n\n### Core Philosophy\n\n- **RED-GREEN-REFACTOR**: Strict adherence to TDD cycle\n- **Behavior-First**: BDD patterns that describe what code should do\n- **Invariant-Encoding**: Tests guard design decisions, not just behavior\n- **Meta Dogfooding**: The skill's own tests demonstrate the principles it teaches\n- **Quality Gates**: detailed validation before considering tests complete\n\n## What It Is\n\nA modular test management system that:\n- Discovers what needs testing or updating\n- Generates tests following TDD principles\n- Enhances existing tests with BDD patterns\n- Validate test quality through multiple lenses\n\n## Quick Start\n\n### Quick Checklist for First Time Use\n- [ ] validate pytest is installed (`pip install pytest`)\n- [ ] Have your source code in `src/` or similar directory\n- [ ] Create a `tests/` directory if it doesn't exist\n- [ ] Run `Skill(sanctum:git-workspace-review)` first to understand changes\n- [ ] Start with `Skill(test-updates) --target <specific-module>` for focused updates\n\n### detailed Test Update\n```bash\n# Run full test update workflow\nSkill(test-updates)\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### Targeted Test Updates\n```bash\n# Update tests for specific paths\nSkill(test-updates) --target src/sanctum/agents\nSkill(test-updates) --target tests/test_commit_messages.py\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### TDD for New Features\n```bash\n# Apply TDD to new code\nSkill(test-updates) --tdd-only --target new_feature.py\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### Using the Scripts Directly\n\n**Human-Readable Output:**\n```bash\n# Analyze test coverage gaps\npython plugins/sanctum/scripts/test_analyzer.py --scan src/\n\n# Generate test scaffolding\npython plugins/sanctum/scripts/test_generator.py \\\n    --source src/my_module.py --style pytest_bdd\n\n# Check test quality\npython plugins/sanctum/scripts/quality_checker.py \\\n    --validate tests/test_my_module.py\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n**Programmatic Output (for Claude Code):**\n```bash\n# Get JSON output for programmatic parsing - test_analyzer\npython plugins/sanctum/scripts/test_analyzer.py \\\n    --scan src/ --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"source_files\": [\"src/module.py\", ...],\n#     \"test_files\": [\"tests/test_module.py\", ...],\n#     \"uncovered_files\": [\"module_without_tests\", ...],\n#     \"coverage_gaps\": [{\"file\": \"...\", \"reason\": \"...\"}]\n#   }\n# }\n\n# Get JSON output - test_generator\npython plugins/sanctum/scripts/test_generator.py \\\n    --source src/my_module.py --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"test_file\": \"path/to/test_my_module.py\",\n#     \"source_file\": \"src/my_module.py\",\n#     \"style\": \"pytest_bdd\",\n#     \"fixtures_included\": true,\n#     \"edge_cases_included\": true,\n#     \"error_cases_included\": true\n#   }\n# }\n\n# Get JSON output - quality_checker\npython plugins/sanctum/scripts/quality_checker.py \\\n    --validate tests/test_my_module.py --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"static_analysis\": {...},\n#     \"dynamic_validation\": {...},\n#     \"metrics\": {...},\n#     \"quality_score\": 85,\n#     \"quality_level\": \"QualityLevel.GOOD\",\n#     \"recommendations\": [...]\n#   }\n# }\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n## When To Use It\n\n**Use this skill when you need to:**\n- Update tests after code changes\n- Generate tests for new features\n- Improve existing test quality\n- validate detailed test coverage\n\n**Perfect for:**\n- Pre-commit test validation\n- CI/CD pipeline integration\n- Refactoring with test safety\n- Onboarding new developers\n\n## When NOT To Use\n\n- Auditing\n  test suites - use pensive:test-review\n- Writing production code\n  - focus on implementation first\n- Auditing\n  test suites - use pensive:test-review\n- Writing production code\n  - focus on implementation first\n\n## Workflow Integration\n\n### Phase 1: Discovery\n1. Scan codebase for test gaps\n2. Analyze recent changes\n3. Identify broken or outdated tests\n\nSee `modules/test-discovery.md` for detection patterns.\n\n### Phase 2: Strategy\n1. Choose appropriate BDD style (see `modules/bdd-patterns.md`)\n2. Plan test structure\n3. Define quality criteria\n4. Identify design invariants to encode as tests\n\n### Phase 2.5: Invariant-Encoding Tests\n\nBefore writing behavioral tests, identify the design\ninvariants that the code relies on and write tests\nthat would break if those invariants were violated.\n\n**What to encode:**\n\n- Module boundary constraints (A never imports from B)\n- Data flow direction (events flow publisher-to-subscriber,\n  never the reverse)\n- API contract shapes (public interfaces don't change\n  without versioning)\n- Data structure choices (if a map was chosen over a list,\n  test the properties that justify that choice)\n- Error handling strategies (fail-fast boundaries, recovery\n  zones)\n\n**Example:**\n\n```python\ndef test_plugins_never_import_from_other_plugins():\n    \"\"\"Encode the invariant: plugins are independent modules.\n\n    If this test breaks, someone is coupling plugins\n    directly. Present the 3 options to a human:\n    1. Preserve: revert the import, keep plugins independent\n    2. Layer: add a shared interface in leyline instead\n    3. Revise: merge the plugins (requires ADR)\n    \"\"\"\n    for plugin_dir in plugin_dirs:\n        imports = extract_imports(plugin_dir)\n        for imp in imports:\n            assert not imp.startswith(\"plugins.\"), (\n                f\"{plugin_dir} imports {imp} — \"\n                f\"violates plugin independence invariant\"\n            )\n```\n\n**Why this matters:** Tests that encode invariants are\nload-bearing. When an agent later encounters a feature\nthat clashes with the invariant, the test failure forces\na conscious decision rather than a silent drift. Without\nthese tests, bad invariant decisions compound until the\ncodebase is unsalvageable.\n\n**When updating existing tests:**\n\nIf an invariant-encoding test needs to change, do NOT\nsilently update the assertion. Flag it for human review\nwith the three options: preserve the invariant, layer\non top, or revise the invariant. This is a judgment\ncall that requires human wisdom — models default to\nthe \"average\" of training data and get these wrong far\ntoo often.\n\n### Phase 3: Implementation\n1. Write failing tests (RED) - see `modules/tdd-workflow.md`\n2. Implement minimal passing code (GREEN)\n3. Refactor for clarity (REFACTOR)\n\nSee `modules/test-generation.md` for generation templates.\n\n### Phase 4: Validation\n1. Static analysis and linting\n2. Dynamic test execution\n3. Coverage and quality metrics\n\nSee `modules/quality-validation.md` for validation criteria.\n\n## Quality Assurance\n\nThe skill applies multiple quality checks:\n- **Static**: Linting, type checking, pattern validation\n- **Dynamic**: Test execution in sandboxed environments\n- **Metrics**: Coverage, mutation score, complexity analysis\n- **Invariant**: Verify design-decision tests are not weakened\n- **Review**: Structured checklists for peer validation\n\n## Examples\n\n### BDD-Style Test Generation\n\nSee `modules/bdd-patterns.md` for additional patterns.\n```python\nclass TestGitWorkflow:\n    \"\"\"BDD-style tests for Git workflow operations.\"\"\"\n\n    def test_commit_workflow_with_staged_changes(self):\n        \"\"\"\n        GIVEN a Git repository with staged changes\n        WHEN the user runs the commit workflow\n        THEN it should create a commit with proper message format\n        AND all tests should pass\n        \"\"\"\n        # Test implementation following TDD principles\n        pass\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### Test Enhancement\n- Add edge cases and error scenarios\n- Include performance benchmarks\n- Add mutation testing for robustness\n\nSee `modules/test-enhancement.md` for enhancement strategies.\n\n## Integration with Existing Skills\n\n1. **git-workspace-review**: Get context of changes\n2. **file-analysis**: Understand code structure\n3. **test-driven-development**: Apply strict TDD discipline\n4. **skills-eval**: Validate quality and compliance\n\n## Success Metrics\n\n- Test coverage > 85%\n- All tests follow BDD patterns\n- Zero broken tests in CI\n- Mutation score > 80%\n\n## Troubleshooting FAQ\n\n### Common Issues\n\n**Q: Tests are failing after generation**\nA: This is expected! The skill follows TDD principles - generated tests are designed to fail first. Follow the RED-GREEN-REFACTOR cycle:\n1. Run the test and confirm it fails for the right reason\n2. Implement minimal code to make it pass\n3. Refactor for clarity\n\n**Q: Quality score is low despite having tests**\nA: Check for these common issues:\n- Missing BDD patterns (Given/When/Then)\n- Vague assertions like `assert result is not None`\n- Tests without documentation\n- Long, complex tests (>50 lines)\n\n**Q: Generated tests don't match my code structure**\nA: The scripts analyze AST patterns and may need guidance:\n- Use `--style` flag to match your preferred BDD style\n- Check that source files have proper function/class definitions\n- Review the generated scaffolding and customize as needed\n\n**Q: Mutation testing takes too long**\nA: Mutation testing is resource-intensive:\n- Use `--quick-mutation` flag for subset testing\n- Focus on critical modules first\n- Run overnight for detailed analysis\n\n**Q: Can't find tests for my file**\nA: The analyzer uses naming conventions:\n- Source: `my_module.py` → Test: `test_my_module.py`\n- Check that test files follow pytest naming patterns\n- validate test directory structure is standard\n\n### Performance Tips\n\n- **Large codebases**: Use `--target` to focus on specific directories\n- **CI integration**: Run validation in parallel with other checks\n- **Memory usage**: Process files in batches for very large projects\n\n### Getting Help\n\n1. Check script outputs for detailed error messages\n2. Use `--verbose` flag for more information\n3. Review the validation report for specific recommendations\n4. Start with small modules to understand patterns before scaling\n\nFile v1.9.17:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-sanctum-test-updates\",\n  \"version\": \"1.9.17\",\n  \"publishedAt\": 1785390072204\n}\n\nFile v1.9.17:modules/bdd-patterns.md\n\n# BDD Patterns Module\n\n## Overview\n\nProvides multiple Behavior-Driven Development styles and patterns for creating expressive, behavior-focused tests.\n\n## Available Styles\n\n| Style | Best For |\n|-------|----------|\n| Gherkin | Complex workflows, acceptance criteria, cross-team |\n| BDD-pytest | Unit/API tests, developer focus |\n| Docstring BDD | Simple tests, quick docs |\n\n## Choosing the Right Style\n\n### Decision Guide\n\n| Style | Best For | Complexity | Collaboration |\n|-------|----------|------------|----------------|\n| Gherkin | Complex workflows, documentation | High | Excellent |\n| BDD-pytest | Unit/API tests, developer focus | Medium | Good |\n| Docstring BDD | Simple tests, quick docs | Low | Limited |\n\n### Mixing Styles\n- Use Gherkin for critical user journeys\n- Use BDD-pytest for unit and API tests\n- Use Docstring BDD for simple utilities\n- Maintain consistency within modules\n\n## Best Practices\n\n### Naming Conventions\n- **Tests**: `test_[behavior]_[when]_[expected]`\n- **Given/When/Then**: Clear separation of concerns\n- **Scenarios**: Describe business value, not technical details\n\n### Test Organization\nGroup related BDD scenarios in test classes with clear setup and teardown.\n\n---\n\n### Gherkin Style\n\nFeature files with Given/When/Then scenarios for complex user\nworkflows and cross-team collaboration.\n\n#### Feature File Structure\n\n```gherkin\nFeature: Git Workflow Management\n  As a developer\n  I want to automate git workflows\n  So that I can maintain clean commit history\n\n  Scenario: Commit with staged changes\n    Given a git repository with staged changes\n    When I run the commit workflow\n    Then a commit should be created with proper message\n    And all tests should pass\n\n  Scenario Outline: Multiple file types\n    Given a git repository with staged <file_type> files\n    When I run the commit workflow\n    Then the commit should reference <file_type>\n    And the commit type should be <commit_type>\n\n    Examples:\n      | file_type | commit_type |\n      | source    | feat       |\n      | test      | test       |\n      | docs      | docs       |\n```\n\n#### Step Definitions\n\n```python\n@given('a git repository with staged changes')\ndef step_given_git_repo_with_changes(context):\n    context.repo = create_test_repo()\n    context.repo.stage_changes(['file1.py', 'file2.py'])\n\n@when('I run the commit workflow')\ndef step_when_run_commit_workflow(context):\n    context.result = run_commit_workflow(context.repo)\n\n@then('a commit should be created with proper message')\ndef step_then_commit_created(context):\n    assert context.repo.has_commit()\n    assert context.repo.last_commit_message().startswith('feat:')\n```\n\n#### When to Use\n\n- Complex user workflows\n- Acceptance criteria documentation\n- Cross-team collaboration\n- Living documentation requirements\n\n---\n\n### Pytest Style\n\nBDD-style pytest tests with descriptive names and docstrings\nfor unit and API testing.\n\n#### Structure Example\n\n```python\nclass TestGitWorkflow:\n    \"\"\"BDD-style tests for Git workflow operations.\"\"\"\n\n    @pytest.mark.bdd\n    def test_commit_workflow_with_staged_changes(self):\n        \"\"\"\n        GIVEN a Git repository with staged changes\n        WHEN the user runs the commit workflow\n        THEN it should create a commit with proper message format\n        AND all tests should pass\n        \"\"\"\n        # Given\n        repo = create_git_repo()\n        repo.stage_changes(['feature.py'])\n\n        # When\n        result = run_commit_workflow(repo)\n\n        # Then\n        assert result.success is True\n        assert repo.has_commit()\n        assert repo.last_commit_message().startswith('feat:')\n\n    @pytest.mark.bdd\n    def test_commit_workflow_rejects_empty_changes(self):\n        \"\"\"\n        GIVEN a Git repository with no staged changes\n        WHEN the user runs the commit workflow\n        THEN it should reject with appropriate error message\n        \"\"\"\n        # Given\n        repo = create_git_repo()  # No changes staged\n\n        # When\n        result = run_commit_workflow(repo)\n\n        # Then\n        assert result.success is False\n        assert \"no staged changes\" in result.error.lower()\n```\n\n#### Best Practices\n\n- **Descriptive names**: Describe behavior, not implementation\n- **Clear sections**: Use Given/When/Then in docstrings\n- **Single responsibility**: One behavior per test\n- **Meaningful assertions**: Test specific outcomes\n\n#### When to Use\n\n- Unit tests with behavior focus\n- API testing\n- Service layer testing\n- Developer-facing documentation\n\n---\n\n### Docstring Style\n\nSimple BDD pattern using docstrings for quick behavior\ndocumentation and simple unit tests.\n\n#### Structure Example\n\n```python\ndef test_git_status_parsing():\n    \"\"\"Test parsing git status output.\n\n    GIVEN git status output with modified and untracked files\n    WHEN parsing the status\n    THEN it should return structured file information\n    AND correctly identify file states\n    \"\"\"\n    status_output = \"\"\"\n    M modified_file.py\n    A  added_file.py\n    ?? untracked_file.py\n    \"\"\"\n\n    result = parse_git_status(status_output)\n\n    assert 'modified_file.py' in result.modified\n    assert 'added_file.py' in result.added\n    assert 'untracked_file.py' in result.untracked\n```\n\n#### Best Practices\n\n- **Clear docstrings**: Include Given/When/Then\n- **Simple structure**: Ideal for utilities and helpers\n- **Quick documentation**: Minimal overhead for behavior specs\n- **Focused tests**: One clear behavior per test\n\n#### When to Use\n\n- Simple unit tests\n- Internal module testing\n- Quick behavior documentation\n- Utility function testing\n\nFile v1.9.17:modules/content-test-discovery.md\n\n# Content Test Discovery\n\nDetects when modified markdown files are \"execution markdown\" requiring content assertions, and identifies test gaps.\n\n## Execution Markdown Detection\n\nFiles matching ALL of these criteria are execution markdown:\n\n1. File extension is `.md`\n2. Path contains `skills/`, `agents/`, `modules/`, or `commands/`\n3. File is NOT named `README.md`, `CHANGELOG.md`, or located under `docs/` directories\n\n```python\ndef is_execution_markdown(file_path: str) -> bool:\n    \"\"\"Markdown that Claude interprets as behavioral instructions.\"\"\"\n    path = Path(file_path)\n    exec_dirs = {\"skills\", \"agents\", \"modules\", \"commands\"}\n    skip_names = {\"README.md\", \"CHANGELOG.md\"}\n    return (\n        path.suffix == \".md\"\n        and any(d in path.parts for d in exec_dirs)\n        and path.name not in skip_names\n        and \"docs\" not in path.parts\n    )\n```\n\n## Priority Reclassification\n\nOverride the default test-discovery priority scoring for execution markdown:\n\n| Change Type | Priority | Rationale |\n|---|---|---|\n| `SKILL.md` modified | **High** | Directly drives Claude's behavior |\n| Module `.md` modified | **Medium** | Loaded on-demand, affects specific workflows |\n| Agent `.md` modified | **Medium** | Defines agent behavior and constraints |\n| Command `.md` modified | **Low-Medium** | Affects slash command documentation |\n| README, CHANGELOG | Low | Not interpreted by Claude as instructions |\n\n## Test Gap Detection\n\nWhen execution markdown is modified, check for a corresponding content test class.\n\n### Naming Convention\n\n| Source File | Expected Test Location |\n|---|---|\n| `plugins/<plugin>/skills/<name>/SKILL.md` | `plugins/<plugin>/tests/unit/skills/test_<name_underscored>.py` |\n| `plugins/<plugin>/skills/<name>/modules/<mod>.md` | `plugins/<plugin>/tests/unit/skills/test_<name_underscored>.py` |\n| `plugins/<plugin>/agents/<name>.md` | `plugins/<plugin>/tests/unit/test_<name_underscored>.py` |\n\n### Detection Heuristic\n\nLook for existing content test classes by checking:\n\n1. Test file exists at the expected path\n2. File contains a class ending in `Content` (e.g., `TestClearContextSkillContent`)\n3. File contains fixtures that read `.md` files (e.g., `skill_content`, `module_content`)\n\nIf no content test class exists, flag as a content test gap.\n\n## When to Generate vs. Skip\n\nNot every markdown change needs new content tests.\n\n### Generate Content Tests When\n\n- A new skill or module is created (no existing tests)\n- Code examples (JSON, YAML, Python) are added or modified (L2 needed)\n- Version references are added or changed (L3 cross-reference needed)\n- Decision frameworks or behavioral guidance is modified (L3 contract needed)\n- Forbidden behavior patterns are specified (L3 anti-pattern detection needed)\n\n### Skip Content Tests When\n\n- Typo or grammar fix only (no behavioral change)\n- Whitespace or formatting changes\n- Changes to prose that don't affect decision logic\n- Changes already covered by `scribe:slop-detector` (style, not behavior)\n\n## Integration\n\nThis module is loaded during Phase 1 (Discovery) of the test-updates workflow. It extends git-based change detection to recognize execution markdown as high-priority test targets.\n\nReference: `leyline:testing-quality-standards/modules/content-assertion-levels.md` for the L1/L2/L3 taxonomy that determines which level of tests to generate.\n\nFile v1.9.17:modules/quality-validation.md\n\n# Quality Validation Module\n\n## Overview\n\ndetailed test quality assurance through static analysis, dynamic validation, metrics tracking, and structured peer review.\n\n## Validation Categories\n\n### 1. Static Analysis\nValidate test code without execution (details below).\n\n### 2. Dynamic Validation\nExecute tests to verify they actually work (details below).\n\n### 3. Metrics Validation\nTrack quantitative quality measures (details below).\n\n### 4. Peer Review Checklist\nStructured validation for human review.\n\n#### Quality Gates Checklist\n```python\nQUALITY_GATES = {\n    \"structure\": [\n        \"Test follows BDD pattern with Given/When/Then\",\n        \"Test has descriptive name explaining behavior\",\n        \"Test is independent and isolated\",\n        \"Test uses appropriate fixtures or setup\",\n    ],\n    \"assertions\": [\n        \"Assertions are specific and meaningful\",\n        \"Error messages are descriptive\",\n        \"Both positive and negative cases tested\",\n        \"Edge cases are covered\",\n    ],\n    \"maintenance\": [\n        \"Test is readable and understandable\",\n        \"Test data is clearly defined\",\n        \"External dependencies are mocked\",\n        \"Test documentation is adequate\",\n    ],\n    \"performance\": [\n        \"Test runs quickly (< 1 second)\",\n        \"No unnecessary I/O operations\",\n        \"Memory usage is reasonable\",\n        \"Tests are parallelizable\",\n    ],\n}\n```\n\n## Validation Workflow\n\n```python\ndef run_validation_pipeline(test_path, source_path=None):\n    \"\"\"Run complete validation pipeline.\"\"\"\n\n    report = ValidationReport()\n\n    # Phase 1: Static Analysis\n    static_issues = validate_static_quality(test_path)\n    report.add_section(\"Static Analysis\", static_issues)\n\n    # Phase 2: Dynamic Validation\n    execution_results = validate_test_execution(test_path)\n    report.add_section(\"Dynamic Validation\", execution_results)\n\n    # Phase 3: Mutation Testing (if source provided)\n    if source_path:\n        mutation_score = run_mutation_tests(test_path, source_path)\n        report.add_section(\"Mutation Testing\", {\"score\": mutation_score})\n\n    # Phase 4: Metrics Validation\n    coverage_violations = validate_coverage_metrics(execution_results[\"coverage\"])\n    report.add_section(\"Coverage Metrics\", coverage_violations)\n\n    # Phase 5: Complexity Analysis\n    complexity = calculate_test_complexity(test_path)\n    report.add_section(\"Complexity Metrics\", complexity)\n\n    return report\n```\n\n## Quality Standards\n\n### Minimum Requirements\n- **Coverage**: 85% line, 80% branch, 90% function\n- **Mutation Score**: 80% or higher\n- **Test Speed**: < 1 second per test\n- **Independence**: No test dependencies\n- **BDD Compliance**: All tests follow BDD patterns\n\n### Excellence Criteria\n- **Coverage**: 95% line, 90% branch, 100% function\n- **Mutation Score**: 90% or higher\n- **Test Speed**: < 0.5 seconds per test\n- **Documentation**: detailed behavior description\n- **Maintainability**: Clear, readable, well-structured\n\n### Failure Modes\nTests failing validation should:\n1. Generate detailed issue reports\n2. Suggest specific improvements\n3. Provide examples of fixes\n4. Block merging until resolved\n\n---\n\n### Static Analysis\n\nValidate test code without execution using pattern matching\nand AST analysis.\n\n#### Code Quality Checks\n\n```python\ndef validate_static_quality(test_file):\n    \"\"\"Perform static quality validation.\"\"\"\n\n    issues = []\n\n    # Check test naming\n    if not test_has_descriptive_name(test_file):\n        issues.append(\"Test name should describe behavior\")\n\n    # Check BDD structure\n    if not has_bdd_structure(test_file):\n        issues.append(\"Test should follow BDD pattern\")\n\n    # Check assertion quality\n    if has_vague_assertions(test_file):\n        issues.append(\"Use specific, meaningful assertions\")\n\n    # Check test independence\n    if tests_have_dependencies(test_file):\n        issues.append(\"Tests should be independent\")\n\n    return issues\n```\n\n#### Pattern Validation\n\n```python\nBDD_PATTERNS = {\n    \"given_pattern\": r\"GIVEN\\s+.+\",\n    \"when_pattern\": r\"WHEN\\s+.+\",\n    \"then_pattern\": r\"THEN\\s+.+\",\n    \"and_pattern\": r\"AND\\s+.+\",\n}\n\ndef validate_bdd_patterns(test_content):\n    \"\"\"Validate BDD pattern usage.\"\"\"\n    missing_patterns = []\n\n    for pattern_name, pattern_regex in BDD_PATTERNS.items():\n        if not re.search(pattern_regex, test_content, re.IGNORECASE):\n            missing_patterns.append(pattern_name)\n\n    return missing_patterns\n```\n\n#### Validation Categories\n\n- **Naming**: Descriptive, behavior-focused test names\n- **Structure**: Proper BDD patterns and organization\n- **Assertions**: Specific, meaningful checks\n- **Independence**: No test dependencies\n- **Documentation**: Clear docstrings and comments\n\n---\n\n### Dynamic Validation\n\nExecutes tests to verify they actually work and measure their\nquality.\n\n#### Test Execution Validation\n\n```python\ndef validate_test_execution(test_path):\n    \"\"\"Validate test executes correctly.\"\"\"\n\n    results = {\n        \"passes\": False,\n        \"failures\": [],\n        \"errors\": [],\n        \"warnings\": [],\n        \"coverage\": 0,\n    }\n\n    # Run tests in isolated environment\n    test_result = pytest.main([\n        test_path,\n        \"-v\",\n        \"--tb=short\",\n        \"--cov=src\",\n        \"--cov-report=json\",\n    ])\n\n    # Analyze results\n    if test_result == 0:\n        results[\"passes\"] = True\n    else:\n        # Parse failures and errors\n        results[\"failures\"] = parse_test_failures()\n        results[\"errors\"] = parse_test_errors()\n\n    # Load coverage data\n    results[\"coverage\"] = load_coverage_data()\n\n    return results\n```\n\n#### Mutation Testing\n\n```python\ndef run_mutation_tests(test_path, source_path):\n    \"\"\"Run mutation testing to verify test quality.\"\"\"\n\n    mutations = generate_mutations(source_path)\n    killed_mutants = 0\n    total_mutants = len(mutations)\n\n    for mutation in mutations:\n        # Apply mutation\n        apply_mutation(source_path, mutation)\n\n        # Run tests\n        if pytest.main([test_path, \"-q\"]) != 0:\n            killed_mutants += 1  # Test caught the mutation\n\n        # Restore original code\n        restore_original(source_path)\n\n    mutation_score = killed_mutants / total_mutants\n    return mutation_score\n```\n\n#### Performance Testing\n\n- **Execution time**: Tests should run quickly (< 1 second)\n- **Memory usage**: No memory leaks or excessive consumption\n- **Parallel execution**: Tests should run independently\n- **Resource cleanup**: Proper teardown after each test\n\n---\n\n### Quality Metrics\n\nTracks quantitative quality measures for test suites.\n\n#### Coverage Metrics\n\n```python\ndef validate_coverage_metrics(coverage_data):\n    \"\"\"Validate test coverage meets standards.\"\"\"\n\n    metrics = {\n        \"line_coverage\": coverage_data[\"lines_covered\"] / coverage_data[\"lines_valid\"],\n        \"branch_coverage\": coverage_data[\"branches_covered\"] / coverage_data[\"branches_valid\"],\n        \"function_coverage\": coverage_data[\"functions_covered\"] / coverage_data[\"functions_valid\"],\n    }\n\n    standards = {\n        \"line_coverage\": 0.85,  # 85% minimum\n        \"branch_coverage\": 0.80,  # 80% minimum\n        \"function_coverage\": 0.90,  # 90% minimum\n    }\n\n    violations = []\n    for metric, value in metrics.items():\n        if value < standards[metric]:\n            violations.append(f\"{metric}: {value:.1%} < {standards[metric]:.1%}\")\n\n    return violations\n```\n\n#### Test Complexity Metrics\n\n```python\ndef calculate_test_complexity(test_file):\n    \"\"\"Calculate cyclomatic complexity of tests.\"\"\"\n\n    complexity_metrics = {\n        \"average_assertions_per_test\": 0,\n        \"test_length_violations\": 0,\n        \"setup_complexity\": 0,\n        \"mock_count\": 0,\n    }\n\n    # Analyze each test\n    for test in extract_tests(test_file):\n        assertions = count_assertions(test)\n        if assertions > 5:\n            complexity_metrics[\"test_length_violations\"] += 1\n\n        complexity_metrics[\"average_assertions_per_test\"] += assertions\n        complexity_metrics[\"mock_count\"] += count_mocks(test)\n\n    complexity_metrics[\"average_assertions_per_test\"] /= len(extract_tests(test_file))\n\n    return complexity_metrics\n```\n\n#### Quality Score Calculation\n\nCombine multiple metrics into an overall score:\n- Static analysis (20%)\n- Dynamic validation (30%)\n- Coverage metrics (20%)\n- Mutation testing (20%)\n- Complexity (10%)\n\nFile v1.9.17:modules/tdd-workflow.md\n\n# TDD Workflow Module\n\n## Table of Contents\n- [Overview](#overview)\n- [The TDD Cycle](#the-tdd-cycle)\n  - [RED Phase: Write Failing Test](#red-phase-write-failing-test)\n  - [GREEN Phase: Minimal Implementation](#green-phase-minimal-implementation)\n  - [REFACTOR Phase: Clean Up](#refactor-phase-clean-up)\n- [TDD Discipline Rules](#tdd-discipline-rules)\n- [Error Handling in TDD](#error-handling-in-tdd)\n- [Advanced TDD Patterns](#advanced-tdd-patterns)\n\n## Overview\n\nImplements strict Test-Driven Development workflow with RED-GREEN-REFACTOR cycle. This module validates all test creation follows proper TDD discipline.\n\n## The TDD Cycle\n\n### RED Phase: Write Failing Test\n\n**Principles:**\n- Write ONE test at a time\n- Test must FAIL for the right reason\n- No production code exists yet\n- Test describes desired behavior\n\n**Implementation Pattern:**\n```python\ndef test_new_feature_behavior():\n    \"\"\"\n    GIVEN a specific context\n    WHEN an action is performed\n    THEN expected outcome occurs\n    \"\"\"\n    # Arrange - Set up test context\n    context = create_test_context()\n\n    # Act - Execute the behavior\n    result = perform_action(context)\n\n    # Assert - Verify the outcome\n    assert result == expected_value\n\n# Run and verify it fails: pytest -xvs test_file.py::test_new_feature_behavior\n```\n\n### Verification Steps\n1. **Run the test**: Must fail\n2. **Check failure reason**: Should be \"feature not implemented\"\n3. **Confirm test quality**: Clear, focused, one behavior\n\n### GREEN Phase: Minimal Implementation\n\n**Principles:**\n- Write simplest code to pass\n- No extra features\n- Don't fix other tests\n- Keep it ugly if it works\n\n**Implementation Pattern:**\n```python\n# Minimal implementation - just enough to pass\ndef perform_action(context):\n    if context.should_succeed:\n        return expected_value\n    raise NotImplementedError(\"Feature not yet implemented\")\n```\n\n### Verification Steps\n1. **Run the test**: Must pass\n2. **Check other tests**: All still passing\n3. **No warnings/errors**: Clean execution\n\n### REFACTOR Phase: Clean Up\n\n**Principles:**\n- Tests must stay green\n- Remove duplication\n- Improve names and structure\n- Add necessary abstractions\n\n**Refactoring Checklist:**\n- [ ] Extract magic numbers to constants\n- [ ] Improve variable names\n- [ ] Remove code duplication\n- [ ] Add helpful comments\n- [ ] validate single responsibility\n\n## TDD Discipline Rules\n\n### Iron Rules\n1. **NO production code without a failing test first**\n2. **Watch it fail** - Don't skip this step\n3. **Write minimal code** - No extra features\n4. **Refactor only when green** - Clean up with safety net\n\n### Common Violations to Avoid\n- Writing code before tests\n- \"I'll test it after\" mentality\n- Keeping implementation as \"reference\"\n- Skipping the failure verification\n- Adding extra features in GREEN phase\n\n## Error Handling in TDD\n\n### Test Errors vs Failures\n- **Error**: Syntax, imports, setup issues - Fix immediately\n- **Failure**: Assertion fails - Good! This is expected\n\n### Debugging Process\n1. Test fails unexpectedly → Check test logic\n2. Implementation doesn't work → Simplify further\n3. Other tests break → Check for side effects\n\n## Advanced TDD Patterns\n\n### Outside-In TDD\n- Start with acceptance/feature tests\n- Work inward to unit tests\n- Maintain failing test chain\n\n### Mocking Strategies\n- Mock external dependencies\n- Use dependency injection\n- Test behavior, not implementation\n\n### Parameterized Tests\n```python\n@pytest.mark.parametrize(\"input,expected\", [\n    (\"valid_input\", \"expected_output\"),\n    (\"edge_case\", \"edge_output\"),\n])\ndef test_multiple_scenarios(input, expected):\n    assert process(input) == expected\n```\n\nFile v1.9.17:modules/test-discovery.md\n\n# Test Discovery Module\n\n## Overview\n\nIdentifies what needs testing or updating by analyzing code structure, git changes, and existing test coverage.\n\n## Discovery Strategies\n\n### 1. detailed Codebase Scan\n- Analyze all Python files for test coverage\n- Identify functions, classes, and modules without tests\n- Check for public API without corresponding tests\n\n### 2. Git-Based Change Detection\n- Parse `git diff` to find modified files\n- Identify new functions or changed signatures\n- Detect breaking changes requiring test updates\n\n### 3. Targeted Analysis\n- Accept specific paths or patterns\n- Deep dive into particular modules\n- Custom filters based on user criteria\n\n## Analysis Patterns\n\n### Code Structure Analysis\n```python\n# Example patterns for identifying test needs\ndef discover_test_targets(codebase_path):\n    \"\"\"Discover what needs testing.\"\"\"\n\n    # Find Python modules\n    modules = find_python_modules(codebase_path)\n\n    # Analyze each module for test coverage\n    for module in modules:\n        public_functions = extract_public_functions(module)\n        test_coverage = analyze_existing_tests(module)\n\n        if test_coverage < 1.0:  # 100% coverage target\n            report_missing_tests(module, public_functions, test_coverage)\n```\n\n### Change Impact Analysis\n```python\ndef analyze_git_changes():\n    \"\"\"Analyze git changes for test impact.\"\"\"\n\n    # Get changed files\n    changed_files = git_diff --name-only HEAD~1\n\n    # Categorize changes\n    for file in changed_files:\n        if file.endswith('.py'):\n            if is_test_file(file):\n                mark_for_review(file)  # May need updates\n            else:\n                mark_for_test_update(file)  # Code changed\n```\n\n## Discovery Outputs\n\n### Test Gap Report\n- Missing test files\n- Uncovered functions/methods\n- Modules with low coverage\n- Edge cases not tested\n\n### Change Impact Report\n- Files modified since last test run\n- Functions with changed signatures\n- Breaking changes detected\n- Integration points affected\n\n### Priority Scoring\n\n- **High**: Public API changes, execution markdown changes (SKILL.md files, agent definitions)\n- **Medium**: Internal refactoring, module markdown changes (files under `modules/` directories)\n- **Low**: README, CHANGELOG, non-execution documentation, test-only changes\n\n#### Execution Markdown Detection\n\nFiles under `skills/`, `agents/`, `modules/`, or `commands/` with `.md` extension are execution markdown -- Claude interprets them as behavioral instructions. These are NOT low-priority documentation changes.\n\nWhen execution markdown is modified, check for corresponding content tests using the L1/L2/L3 taxonomy. See `modules/content-test-discovery.md` for detection heuristics and gap analysis, and `modules/generation/content-test-templates.md` for BDD test scaffolding.\n\nFile v1.9.17:modules/test-enhancement.md\n\n# Test Enhancement Module\n\n## Overview\n\nImproves existing tests by applying BDD patterns, adding edge cases, and increasing test quality. Transforms basic tests into detailed behavior specifications.\n\n## Enhancement Strategies\n\n### 1. BDD Pattern Application\nTransforms traditional tests into BDD-style tests (details below).\n\n### 2. Edge Case Expansion\nAdds detailed edge case testing (details below).\n\n### 3. Test Organization\nImproves test structure and maintainability (details below).\n\n## Quality Enhancement Rules\n\n### The Rule of Three\nFor every assertion, add:\n1. **Positive case**: Expected behavior\n2. **Negative case**: Error handling\n3. **Edge case**: Boundary condition\n\n### AAA Pattern (Arrange-Act-Assert)\n```python\ndef test_workflow():\n    # Arrange - Setup everything needed\n    context = create_test_context()\n    expected = prepare_expected_result()\n\n    # Act - Perform the action\n    result = perform_action(context)\n\n    # Assert - Verify outcomes\n    assert result == expected\n```\n\n### Test Data Factory Pattern\nCreate reusable test data factories for consistent test setup.\n\n## Enhancement Checklist\n\nFor each existing test:\n- [ ] Add BDD-style docstring with Given/When/Then\n- [ ] Include edge cases and error scenarios\n- [ ] Use descriptive test names\n- [ ] Add appropriate fixtures\n- [ ] Verify test independence\n- [ ] Add performance assertions if relevant\n- [ ] Include behavior documentation\n- [ ] Mock external dependencies appropriately\n\n---\n\n### BDD Transformation\n\nTransforms traditional tests into BDD-style tests with clear\nbehavior specifications.\n\n#### Before: Traditional Test\n\n```python\ndef test_commit():\n    repo = GitRepo()\n    repo.add('file.txt')\n    result = repo.commit('message')\n    assert result is True\n```\n\n#### After: BDD-Style Test\n\n```python\n@pytest.mark.bdd\ndef test_commit_workflow_with_staged_file():\n    \"\"\"\n    GIVEN a Git repository with a staged file\n    WHEN the user commits with a message\n    THEN the commit should be created successfully\n    AND the commit message should match\n    \"\"\"\n    # Given\n    repo = GitRepo()\n    repo.add('file.txt')\n\n    # When\n    result = repo.commit('Add new feature')\n\n    # Then\n    assert result is True\n    assert repo.get_last_commit_message() == 'Add new feature'\n```\n\n#### Transformation Steps\n\n1. **Add descriptive test name**: Describe behavior, not implementation\n2. **Add BDD docstring**: Include Given/When/Then clauses\n3. **Structure test with AAA**: Arrange-Act-Assert\n4. **Add specific assertions**: Test behavior, not just truthiness\n\n---\n\n### Edge Cases\n\nSystematically adds detailed edge case testing to existing tests.\n\n#### The Rule of Three\n\nFor every assertion, add:\n1. **Positive case**: Expected behavior\n2. **Negative case**: Error handling\n3. **Edge case**: Boundary condition\n\n#### Example Expansion\n\n**Original:**\n```python\ndef test_parse_number():\n    assert parse_number(\"123\") == 123\n```\n\n**Enhanced:**\n```python\n@pytest.mark.parametrize(\"input_str,expected,description\", [\n    (\"123\", 123, \"valid positive integer\"),\n    (\"-456\", -456, \"valid negative integer\"),\n    (\"0\", 0, \"zero value\"),\n    (\"3.14\", 3.14, \"valid float\"),\n    (\"1e5\", 100000, \"scientific notation\"),\n])\ndef test_parse_number_valid_inputs(input_str, expected, description):\n    \"\"\"\n    GIVEN various valid number strings\n    WHEN parsing the string\n    THEN it should return the correct number\n    \"\"\"\n    assert parse_number(input_str) == expected\n\n@pytest.mark.parametrize(\"invalid_input\", [\n    \"abc\",\n    \"\",\n    \"12.34.56\",\n    \"1,234\",\n    None,\n])\ndef test_parse_number_invalid_inputs(invalid_input):\n    \"\"\"\n    GIVEN invalid number inputs\n    WHEN parsing the string\n    THEN it should raise a ValueError\n    \"\"\"\n    with pytest.raises(ValueError):\n        parse_number(invalid_input)\n```\n\n#### Common Edge Cases\n\n- **Strings**: Empty, whitespace, special characters, unicode\n- **Numbers**: Zero, negative, maximum/minimum values, infinity\n- **Collections**: Empty, single item, maximum capacity\n- **Dates**: Leap years, timezone changes, daylight saving\n- **Files**: Missing, permissions, full disk, network errors\n\n---\n\n### Organization Patterns\n\nRestructures tests for better maintainability and clarity.\n\n#### Test Organization Example\n\n```python\nclass TestGitRepository:\n    \"\"\"BDD-style test suite for GitRepository operations.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_repo(self, tmp_path):\n        \"\"\"Setup a test repository for each test.\"\"\"\n        self.repo_path = tmp_path / \"test_repo\"\n        self.repo = GitRepository(self.repo_path)\n        self.repo.init()\n\n    @pytest.mark.bdd\n    def test_init_creates_git_directory(self):\n        \"\"\"\n        GIVEN a directory path\n        WHEN initializing a git repository\n        THEN it should create a .git directory\n        \"\"\"\n        assert (self.repo_path / \".git\").exists()\n\n    @pytest.mark.bdd\n    def test_init_with_existing_repo_raises_error(self):\n        \"\"\"\n        GIVEN an existing git repository\n        WHEN initializing again\n        THEN it should raise RepositoryError\n        \"\"\"\n        with pytest.raises(RepositoryError):\n            GitRepository(self.repo_path).init()\n```\n\n#### AAA Pattern (Arrange-Act-Assert)\n\n```python\ndef test_workflow():\n    # Arrange - Setup everything needed\n    context = create_test_context()\n    expected = prepare_expected_result()\n\n    # Act - Perform the action\n    result = perform_action(context)\n\n    # Assert - Verify outcomes\n    assert result == expected\n```\n\n#### Test Data Factory Pattern\n\n```python\nclass TestDataFactory:\n    \"\"\"Factory for creating test data.\"\"\"\n\n    @staticmethod\n    def create_git_repo(branch=\"main\", with_commits=False):\n        repo = GitRepository()\n        repo.init(branch)\n\n        if with_commits:\n            repo.add(\"README.md\")\n            repo.commit(\"Initial commit\")\n\n        return repo\n\n    @staticmethod\n    def create_user(role=\"user\", **overrides):\n        default_user = {\n            \"name\": \"Test User\",\n            \"email\": \"test@example.com\",\n            \"role\": role,\n        }\n        default_user.update(overrides)\n        return User(**default_user)\n```\n\nFile v1.9.17:modules/test-generation.md\n\n# Test Generation Module\n\n## Overview\n\nAutomated test scaffolding and generation following TDD/BDD principles. Creates test templates that developers complete using proper TDD workflow.\n\n## Capabilities\n\n- **Generation strategies**: Code analysis, git change detection, API-based\n- **Test templates**: Function, class, and API scaffolding\n- **Smart features**: Parameter discovery, error scenarios, context-aware patterns\n- **Content tests**: BDD templates for skill content assertions\n\n## Workflow\n\n1. **Analyze**: Parse code structure and dependencies\n2. **Discover**: Identify test scenarios and edge cases\n3. **Generate**: Create test scaffolding with BDD patterns\n4. **Review**: Validate generated tests\n5. **Complete**: Developer finishes with TDD cycle\n\n## Best Practices\n\n### Do Generate\n- Test scaffolding with TODO comments\n- BDD-style structure templates\n- Parameterized test skeletons\n- Mock/stub setup patterns\n\n### Don't Generate\n- Actual test implementations\n- Complex assertions\n- Business logic\n- Mock behavior (too specific)\n\n---\n\n### Generation Strategies\n\nDifferent approaches for discovering what needs testing and\ngenerating appropriate test scaffolding.\n\n#### From Code Analysis\n\nAnalyzes existing code to generate appropriate test scaffolding.\n\n```python\ndef generate_tests_from_code(code_path):\n    \"\"\"Generate test scaffolding from code analysis.\"\"\"\n\n    # Parse the code\n    ast_tree = ast.parse(open(code_path).read())\n\n    # Extract testable elements\n    functions = extract_functions(ast_tree)\n    classes = extract_classes(ast_tree)\n\n    # Generate test templates\n    for func in functions:\n        generate_function_test_template(func)\n\n    for cls in classes:\n        generate_class_test_template(cls)\n```\n\n#### From Git Changes\n\nGenerates tests for new or modified code.\n\n```python\ndef generate_tests_for_changes(git_diff):\n    \"\"\"Generate tests based on git changes.\"\"\"\n\n    changes = parse_git_diff(git_diff)\n\n    for change in changes:\n        if change.type == 'new_function':\n            generate_new_function_test(change)\n        elif change.type == 'modified_signature':\n            generate_updated_test(change)\n        elif change.type == 'new_class':\n            generate_class_test_suite(change)\n```\n\n#### From API Definitions\n\nGenerates integration tests from API contracts or OpenAPI specs.\n\n```python\ndef generate_api_tests(openapi_spec):\n    \"\"\"Generate BDD-style API tests from OpenAPI spec.\"\"\"\n\n    for endpoint in openapi_spec.paths:\n        for method in endpoint.methods:\n            generate_endpoint_test(endpoint, method)\n```\n\n#### Strategy Selection\n\nChoose based on your needs:\n- **Code Analysis**: For existing code without tests\n- **Git Changes**: For recent modifications\n- **API Definitions**: For contract-first development\n\n---\n\n### Test Templates\n\nStandard templates for different types of tests following BDD\npatterns.\n\n#### Function Test Template\n\n```python\ndef test_{function_name}_{scenario}():\n    \"\"\"\n    GIVEN {given_context}\n    WHEN {when_action}\n    THEN {then_expected}\n    \"\"\"\n    # TODO: Arrange - Set up test context\n    # TODO: Act - Execute the function\n    # TODO: Assert - Verify the outcome\n    pass\n```\n\n#### Class Test Template\n\n```python\nclass Test{ClassName}:\n    \"\"\"BDD-style tests for {ClassName} behavior.\"\"\"\n\n    def setup_method(self):\n        \"\"\"Setup test instance.\"\"\"\n        self.instance = {ClassName}()\n\n    @pytest.mark.bdd\n    def test_{method_name}_{scenario}(self):\n        \"\"\"\n        GIVEN {given_context}\n        WHEN {when_action}\n        THEN {then_expected}\n        \"\"\"\n        # TODO: Implement test following BDD pattern\n        pass\n\n    def teardown_method(self):\n        \"\"\"Cleanup after each test.\"\"\"\n        pass\n```\n\n#### API Test Template\n\n```python\n@pytest.mark.bdd\ndef test_{endpoint}_{method}_{scenario}(client):\n    \"\"\"\n    GIVEN {given_context}\n    WHEN making {method} request to {endpoint}\n    THEN response should be {expected_status}\n    AND response should contain {expected_content}\n    \"\"\"\n    # TODO: Setup request data\n    # TODO: Make API call\n    # TODO: Verify response\n    pass\n```\n\n#### Using Templates\n\nTemplates provide scaffolding that developers complete using TDD:\n1. Write the failing test (RED)\n2. Implement minimal code to pass (GREEN)\n3. Refactor for clarity (REFACTOR)\n\n---\n\n### Smart Features\n\nAdvanced features that make test generation more intelligent\nand context-aware.\n\n#### Parameter Discovery\n\n```python\ndef discover_test_parameters(func):\n    \"\"\"Discover parameters for test generation.\"\"\"\n\n    params = inspect.signature(func).parameters\n\n    test_cases = []\n\n    # Happy path\n    test_cases.append(generate_happy_path_test(params))\n\n    # Edge cases\n    for param in params:\n        if param.annotation == str:\n            test_cases.append(generate_string_edge_cases(param.name))\n        elif param.annotation == int:\n            test_cases.append(generate_numeric_edge_cases(param.name))\n\n    return test_cases\n```\n\n#### Error Scenario Generation\n\n```python\ndef generate_error_scenarios(func):\n    \"\"\"Generate error handling test scenarios.\"\"\"\n\n    scenarios = []\n\n    # Type errors\n    scenarios.extend(generate_type_error_tests(func))\n\n    # Value errors\n    scenarios.extend(generate_value_error_tests(func))\n\n    # Dependency errors\n    scenarios.extend(generate_dependency_error_tests(func))\n\n    return scenarios\n```\n\n#### Context-Aware Patterns\n\nRecognizes common patterns to generate specialized tests:\n- Repository pattern\n- Service pattern\n- Command pattern\n- Factory pattern\n\n#### Quality-Aware Generation\n\nIncludes:\n- Smart assertion generation\n- Parameterized test skeletons\n- Mock/stub setup patterns\n\n---\n\n### Content Test Templates\n\nBDD test templates for each content assertion level. Use these\nas scaffolding when generating content tests for execution\nmarkdown files.\n\nReference: `leyline:testing-quality-standards/modules/content-assertion-levels.md`\n\n#### Level 1: Keyword Presence\n\nMinimum viable content test. Validates structural completeness.\n\n```python\nfrom pathlib import Path\nimport pytest\n\n\nclass TestExampleSkillContent:  # Rename to match your skill\n    \"\"\"Feature: example skill has required structural elements.\n\n    As a skill interpreted by Claude Code\n    I want all required sections to be present\n    So that Claude has complete instructions to follow.\n\n    Level 1: Structural presence checks.\n    \"\"\"\n\n    @pytest.fixture\n    def skill_path(self) -> Path:\n        # Adjust \"example-skill\" to your actual skill directory name\n        return Path(__file__).parents[3] / \"skills\" / \"example-skill\" / \"SKILL.md\"\n\n    @pytest.fixture\n    def skill_content(self, skill_path: Path) -> str:\n        return skill_path.read_text()\n\n    @pytest.mark.bdd\n    @pytest.mark.unit\n    def test_skill_has_required_sections(self, skill_content: str) -> None:\n        \"\"\"Given the skill content\n        When Claude loads it for execution\n        Then all required sections must be present.\"\"\"\n        required = [\n            \"## When To Use\",\n            \"## When NOT To Use\",\n            # Add skill-specific required sections\n        ]\n        for section in required:\n            assert section in skill_content, f\"Missing '{section}'\"\n\n    @pytest.mark.bdd\n    @pytest.mark.unit\n    @pytest.mark.parametrize(\"module_name\", [\n        # List modules referenced in SKILL.md\n    ])\n    def test_referenced_modules_exist(\n        self, skill_path: Path, module_name: str\n    ) -> None:\n        \"\"\"Given modules referenced in the skill\n        Then each must exist on disk with content.\"\"\"\n        module_path = skill_path.parent / \"modules\" / module_name\n        assert module_path.exists(), f\"Referenced module {module_name} not found\"\n        content = module_path.read_text()\n        min_lines = 10\n        assert len(content.splitlines()) >= min_lines, (\n            f\"Module {module_name} has fewer than {min_lines} lines\"\n        )\n```\n\n#### Level 2: Code Example Validity\n\nValidates embedded code examples parse correctly and have\nrequired schema.\n\n```python\nimport json\nimport re\n\n# --- Level 2: Code example validity ---\n# Add these methods inside your Test*Content class\n\n@pytest.fixture\ndef json_code_blocks(self, skill_content: str):\n    \"\"\"Extract all JSON code blocks from the skill.\"\"\"\n    return re.findall(r\"```json\\n(.*?)```\", skill_content, re.DOTALL)\n\n@pytest.mark.bdd\n@pytest.mark.unit\ndef test_all_json_examples_parse(self, json_code_blocks) -> None:\n    \"\"\"Given JSON code blocks in the skill\n    When Claude copies them as configuration templates\n    Then every block must be valid JSON.\"\"\"\n    assert len(json_code_blocks) > 0, \"Skill should contain JSON examples\"\n    for i, block in enumerate(json_code_blocks):\n        try:\n            json.loads(block)\n        except json.JSONDecodeError as exc:\n            pytest.fail(f\"JSON block #{i + 1} is invalid: {exc}\")\n\n@pytest.mark.bdd\n@pytest.mark.unit\ndef test_version_references_exist(self, skill_content: str) -> None:\n    \"\"\"Given version references in the skill\n    Then each must follow semantic versioning format.\"\"\"\n    versions = re.findall(r\"\\d+\\.\\d+\\.\\d+\", skill_content)\n    # Verify at least one version reference exists\n    # (adjust based on whether skill uses version gates)\n    assert len(versions) >= 1, \"Expected at least one version reference\"\n```\n\n#### Level 3: Behavioral Contracts\n\nValidates semantic correctness, cross-references, and\nanti-patterns.\n\n```python\n# --- Level 3: Behavioral contracts ---\n# Add these methods inside your Test*Content class\n# Requires: re (imported in Level 2), Path (imported in Level 1)\n\n@pytest.mark.bdd\n@pytest.mark.unit\ndef test_no_forbidden_language(self, skill_content: str) -> None:\n    \"\"\"Given the skill instructs Claude's behavior\n    When Claude reads the instructions\n    Then it must NOT find manipulative imperatives.\n\n    Imperative language causes Claude to ignore user intent\n    and force actions without consent.\n    \"\"\"\n    forbidden = [\n        \"YOU MUST EXECUTE THIS NOW\",\n        \"MANDATORY AUTO-CONTINUATION\",\n        # Add context-specific forbidden phrases\n    ]\n    for phrase in forbidden:\n        assert phrase not in skill_content, (\n            f\"Contains manipulative language: '{phrase}'. \"\n            \"Instructions should be informational, not imperative.\"\n        )\n\n@pytest.mark.bdd\n@pytest.mark.unit\ndef test_offers_multiple_strategies(self, skill_content: str) -> None:\n    \"\"\"Given the skill guides Claude's decisions\n    Then it must offer multiple approaches, not force one path.\n\n    Single-path guidance removes user agency.\n    \"\"\"\n    strategies = [\n        # List expected alternative strategies\n    ]\n    found = [s for s in strategies if s.lower() in skill_content.lower()]\n    min_strategies = 3\n    assert len(found) >= min_strategies, (\n        f\"Too few strategies: {found}, need at least {min_strategies}\"\n    )\n\n@pytest.mark.bdd\n@pytest.mark.unit\ndef test_version_refs_cross_reference_docs(\n    self, skill_content: str\n) -> None:\n    \"\"\"Given version references in the skill\n    Then each must exist in compatibility documentation.\n\n    Prevents Claude from citing nonexistent versions.\n    \"\"\"\n    versions = set(re.findall(r\"2\\.1\\.(\\d+)\", skill_content))\n    compat_dir = (\n        Path(__file__).parents[4]  # Adjust depth for your test location\n        / \"abstract\"\n        / \"docs\"\n        / \"compatibility\"\n    )\n    compat_content = \"\"\n    for compat_file in compat_dir.glob(\"compatibility-features*.md\"):\n        compat_content += compat_file.read_text()\n\n    for minor in versions:\n        version_str = f\"2.1.{minor}\"\n        assert version_str in compat_content, (\n            f\"References {version_str} but it's missing from \"\n            \"compatibility-features*.md\"\n        )\n```\n\n#### Choosing the Right Level\n\n| Observed in Git Diff | Start With |\n|---|---|\n| New skill or module created | L1 (sections and modules exist) |\n| JSON/YAML code blocks added or modified | L2 (parse and schema) |\n| Version references added or changed | L3 (cross-reference) |\n| Behavioral guidance added (decision trees, strategies) | L3 (contracts) |\n| Forbidden behavior patterns specified | L3 (anti-pattern detection) |\n| Simple section reordering or prose editing | L1 if no tests exist, skip otherwise |\n\n#### Common Fixtures\n\nThese fixtures appear across all three exemplar test classes:\n\n```python\n@pytest.fixture\ndef skill_path(self) -> Path:\n    \"\"\"Resolve path to the skill file under test.\"\"\"\n    depth = 3  # Adjust based on test file location relative to plugin root\n    return Path(__file__).parents[depth] / \"skills\" / \"skill-name\" / \"SKILL.md\"\n\n@pytest.fixture\ndef skill_content(self, skill_path: Path) -> str:\n    \"\"\"Read the full skill content for assertion.\"\"\"\n    return skill_path.read_text()\n\n@pytest.fixture\ndef module_path(self) -> Path:\n    \"\"\"Resolve path to a specific module file.\"\"\"\n    depth = 3  # Adjust based on test file location relative to plugin root\n    return Path(__file__).parents[depth] / \"skills\" / \"skill-name\" / \"modules\" / \"module.md\"\n```\n\nAdjust `parents[N]` based on your test file's depth relative\nto the plugin root.\n\nFile v1.9.17:skill-card.md\n\n## Description: <br>\nUpdates, generates, and validates tests using git-workspace context and TDD/BDD methodology. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[athola](https://clawhub.ai/user/athola) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and engineering teams use this skill to discover test gaps, generate or update pytest-oriented tests, and validate test quality after code changes. It is intended for test maintenance, TDD/BDD workflows, refactoring support, and CI-oriented quality checks. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The skill may lead an agent to scan repository contents, create or edit tests, and run pytest or mutation-testing workflows with workspace side effects. <br>\nMitigation: Use targeted paths where possible, review proposed file changes before accepting them, and run validation in trusted repositories or disposable worktrees/containers when side effects matter. <br>\nRisk: Generated tests or test-maintenance guidance can be incorrect, brittle, or misaligned with intended design invariants. <br>\nMitigation: Review generated tests, preserve human review for invariant changes, and verify results with the repository's normal test and quality gates. <br>\n\n\n## Reference(s): <br>\n- [ClawHub skill page](https://clawhub.ai/athola/skills/nm-sanctum-test-updates) <br>\n- [Project homepage from ClawHub metadata](https://github.com/athola/claude-night-market/tree/master/plugins/sanctum) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [guidance, markdown, code, shell commands, configuration] <br>\n**Output Format:** [Markdown guidance with inline shell commands and example test code; referenced workflows may also describe JSON report output.] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [Can propose targeted test updates, generated test scaffolding, validation steps, and quality-review findings for repository paths.] <br>\n\n## Skill Version(s): <br>\n1.9.17 (source: server release metadata) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nArchive v1.9.16: 10 files, 23221 bytes\n\nFiles: modules/bdd-patterns.md (5571b), modules/content-test-discovery.md (3355b), modules/quality-validation.md (8344b), modules/tdd-workflow.md (3663b), modules/test-discovery.md (2810b), modules/test-enhancement.md (6145b), modules/test-generation.md (13129b), skill-card.md (2184b), SKILL.md (12295b), _meta.json (143b)\n\nFile v1.9.16:SKILL.md\n\n---\nname: test-updates\ndescription: |\n  Updates, generates, and validates tests using git-workspace context and TDD/BDD methodology\nversion: 1.9.8\ntriggers:\n  - tdd\n  - bdd\n  - testing\n  - quality-assurance\n  - test-generation\n  - pytest\n  - code changes require new or updated test coverage\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/sanctum\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.test-driven-development\", \"night-market.git-workspace-review\", \"night-market.file-analysis\"]}}}\nsource: claude-night-market\nsource_plugin: sanctum\n---\n\n> **Night Market Skill** — ported from [claude-night-market/sanctum](https://github.com/athola/claude-night-market/tree/master/plugins/sanctum). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Overview](#overview)\n- [Core Philosophy](#core-philosophy)\n- [What It Is](#what-it-is)\n- [Quick Start](#quick-start)\n- [Quick Checklist for First Time Use](#quick-checklist-for-first-time-use)\n- [detailed Test Update](#detailed-test-update)\n- [Targeted Test Updates](#targeted-test-updates)\n- [TDD for New Features](#tdd-for-new-features)\n- [Using the Scripts Directly](#using-the-scripts-directly)\n- [When to Use It](#when-to-use-it)\n- [Workflow Integration](#workflow-integration)\n- [Phase 1: Discovery](#phase-1:-discovery)\n- [Phase 2: Strategy](#phase-2:-strategy)\n- [Phase 3: Implementation](#phase-3:-implementation)\n- [Phase 4: Validation](#phase-4:-validation)\n- [Quality Assurance](#quality-assurance)\n- [Examples](#examples)\n- [BDD-Style Test Generation](#bdd-style-test-generation)\n- [Test Enhancement](#test-enhancement)\n- [Integration with Existing Skills](#integration-with-existing-skills)\n- [Success Metrics](#success-metrics)\n- [Troubleshooting FAQ](#troubleshooting-faq)\n- [Common Issues](#common-issues)\n- [Performance Tips](#performance-tips)\n- [Getting Help](#getting-help)\n\n\n# Test Updates and Maintenance\n\n## Overview\n\ndetailed test management system that applies TDD/BDD principles to maintain, generate, and enhance tests across codebases. This skill practices what it preaches - it uses TDD principles for its own development and serves as a living example of best practices.\n\n### Core Philosophy\n\n- **RED-GREEN-REFACTOR**: Strict adherence to TDD cycle\n- **Behavior-First**: BDD patterns that describe what code should do\n- **Invariant-Encoding**: Tests guard design decisions, not just behavior\n- **Meta Dogfooding**: The skill's own tests demonstrate the principles it teaches\n- **Quality Gates**: detailed validation before considering tests complete\n\n## What It Is\n\nA modular test management system that:\n- Discovers what needs testing or updating\n- Generates tests following TDD principles\n- Enhances existing tests with BDD patterns\n- Validate test quality through multiple lenses\n\n## Quick Start\n\n### Quick Checklist for First Time Use\n- [ ] validate pytest is installed (`pip install pytest`)\n- [ ] Have your source code in `src/` or similar directory\n- [ ] Create a `tests/` directory if it doesn't exist\n- [ ] Run `Skill(sanctum:git-workspace-review)` first to understand changes\n- [ ] Start with `Skill(test-updates) --target <specific-module>` for focused updates\n\n### detailed Test Update\n```bash\n# Run full test update workflow\nSkill(test-updates)\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### Targeted Test Updates\n```bash\n# Update tests for specific paths\nSkill(test-updates) --target src/sanctum/agents\nSkill(test-updates) --target tests/test_commit_messages.py\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### TDD for New Features\n```bash\n# Apply TDD to new code\nSkill(test-updates) --tdd-only --target new_feature.py\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### Using the Scripts Directly\n\n**Human-Readable Output:**\n```bash\n# Analyze test coverage gaps\npython plugins/sanctum/scripts/test_analyzer.py --scan src/\n\n# Generate test scaffolding\npython plugins/sanctum/scripts/test_generator.py \\\n    --source src/my_module.py --style pytest_bdd\n\n# Check test quality\npython plugins/sanctum/scripts/quality_checker.py \\\n    --validate tests/test_my_module.py\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n**Programmatic Output (for Claude Code):**\n```bash\n# Get JSON output for programmatic parsing - test_analyzer\npython plugins/sanctum/scripts/test_analyzer.py \\\n    --scan src/ --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"source_files\": [\"src/module.py\", ...],\n#     \"test_files\": [\"tests/test_module.py\", ...],\n#     \"uncovered_files\": [\"module_without_tests\", ...],\n#     \"coverage_gaps\": [{\"file\": \"...\", \"reason\": \"...\"}]\n#   }\n# }\n\n# Get JSON output - test_generator\npython plugins/sanctum/scripts/test_generator.py \\\n    --source src/my_module.py --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"test_file\": \"path/to/test_my_module.py\",\n#     \"source_file\": \"src/my_module.py\",\n#     \"style\": \"pytest_bdd\",\n#     \"fixtures_included\": true,\n#     \"edge_cases_included\": true,\n#     \"error_cases_included\": true\n#   }\n# }\n\n# Get JSON output - quality_checker\npython plugins/sanctum/scripts/quality_checker.py \\\n    --validate tests/test_my_module.py --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"static_analysis\": {...},\n#     \"dynamic_validation\": {...},\n#     \"metrics\": {...},\n#     \"quality_score\": 85,\n#     \"quality_level\": \"QualityLevel.GOOD\",\n#     \"recommendations\": [...]\n#   }\n# }\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n## When To Use It\n\n**Use this skill when you need to:**\n- Update tests after code changes\n- Generate tests for new features\n- Improve existing test quality\n- validate detailed test coverage\n\n**Perfect for:**\n- Pre-commit test validation\n- CI/CD pipeline integration\n- Refactoring with test safety\n- Onboarding new developers\n\n## When NOT To Use\n\n- Auditing\n  test suites - use pensive:test-review\n- Writing production code\n  - focus on implementation first\n- Auditing\n  test suites - use pensive:test-review\n- Writing production code\n  - focus on implementation first\n\n## Workflow Integration\n\n### Phase 1: Discovery\n1. Scan codebase for test gaps\n2. Analyze recent changes\n3. Identify broken or outdated tests\n\nSee `modules/test-discovery.md` for detection patterns.\n\n### Phase 2: Strategy\n1. Choose appropriate BDD style (see `modules/bdd-patterns.md`)\n2. Plan test structure\n3. Define quality criteria\n4. Identify design invariants to encode as tests\n\n### Phase 2.5: Invariant-Encoding Tests\n\nBefore writing behavioral tests, identify the design\ninvariants that the code relies on and write tests\nthat would break if those invariants were violated.\n\n**What to encode:**\n\n- Module boundary constraints (A never imports from B)\n- Data flow direction (events flow publisher-to-subscriber,\n  never the reverse)\n- API contract shapes (public interfaces don't change\n  without versioning)\n- Data structure choices (if a map was chosen over a list,\n  test the properties that justify that choice)\n- Error handling strategies (fail-fast boundaries, recovery\n  zones)\n\n**Example:**\n\n```python\ndef test_plugins_never_import_from_other_plugins():\n    \"\"\"Encode the invariant: plugins are independent modules.\n\n    If this test breaks, someone is coupling plugins\n    directly. Present the 3 options to a human:\n    1. Preserve: revert the import, keep plugins independent\n    2. Layer: add a shared interface in leyline instead\n    3. Revise: merge the plugins (requires ADR)\n    \"\"\"\n    for plugin_dir in plugin_dirs:\n        imports = extract_imports(plugin_dir)\n        for imp in imports:\n            assert not imp.startswith(\"plugins.\"), (\n                f\"{plugin_dir} imports {imp} — \"\n                f\"violates plugin independence invariant\"\n            )\n```\n\n**Why this matters:** Tests that encode invariants are\nload-bearing. When an agent later encounters a feature\nthat clashes with the invariant, the test failure forces\na conscious decision rather than a silent drift. Without\nthese tests, bad invariant decisions compound until the\ncodebase is unsalvageable.\n\n**When updating existing tests:**\n\nIf an invariant-encoding test needs to change, do NOT\nsilently update the assertion. Flag it for human review\nwith the three options: preserve the invariant, layer\non top, or revise the invariant. This is a judgment\ncall that requires human wisdom — models default to\nthe \"average\" of training data and get these wrong far\ntoo often.\n\n### Phase 3: Implementation\n1. Write failing tests (RED) - see `modules/tdd-workflow.md`\n2. Implement minimal passing code (GREEN)\n3. Refactor for clarity (REFACTOR)\n\nSee `modules/test-generation.md` for generation templates.\n\n### Phase 4: Validation\n1. Static analysis and linting\n2. Dynamic test execution\n3. Coverage and quality metrics\n\nSee `modules/quality-validation.md` for validation criteria.\n\n## Quality Assurance\n\nThe skill applies multiple quality checks:\n- **Static**: Linting, type checking, pattern validation\n- **Dynamic**: Test execution in sandboxed environments\n- **Metrics**: Coverage, mutation score, complexity analysis\n- **Invariant**: Verify design-decision tests are not weakened\n- **Review**: Structured checklists for peer validation\n\n## Examples\n\n### BDD-Style Test Generation\n\nSee `modules/bdd-patterns.md` for additional patterns.\n```python\nclass TestGitWorkflow:\n    \"\"\"BDD-style tests for Git workflow operations.\"\"\"\n\n    def test_commit_workflow_with_staged_changes(self):\n        \"\"\"\n        GIVEN a Git repository with staged changes\n        WHEN the user runs the commit workflow\n        THEN it should create a commit with proper message format\n        AND all tests should pass\n        \"\"\"\n        # Test implementation following TDD principles\n        pass\n```\n**Verification:** Run `pytest -v` to verify tests pass.\n\n### Test Enhancement\n- Add edge cases and error scenarios\n- Include performance benchmarks\n- Add mutation testing for robustness\n\nSee `modules/test-enhancement.md` for enhancement strategies.\n\n## Integration with Existing Skills\n\n1. **git-workspace-review**: Get context of changes\n2. **file-analysis**: Understand code structure\n3. **test-driven-development**: Apply strict TDD discipline\n4. **skills-eval**: Validate quality and compliance\n\n## Success Metrics\n\n- Test coverage > 85%\n- All tests follow BDD patterns\n- Zero broken tests in CI\n- Mutation score > 80%\n\n## Troubleshooting FAQ\n\n### Common Issues\n\n**Q: Tests are failing after generation**\nA: This is expected! The skill follows TDD principles - generated tests are designed to fail first. Follow the RED-GREEN-REFACTOR cycle:\n1. Run the test and confirm it fails for the right reason\n2. Implement minimal code to make it pass\n3. Refactor for clarity\n\n**Q: Quality score is low despite having tests**\nA: Check for these common issues:\n- Missing BDD patterns (Given/When/Then)\n- Vague assertions like `assert result is not None`\n- Tests without documentation\n- Long, complex tests (>50 lines)\n\n**Q: Generated tests don't match my code structure**\nA: The scripts analyze AST patterns and may need guidance:\n- Use `--style` flag to match your preferred BDD style\n- Check that source files have proper function/class definitions\n- Review the generated scaffolding and customize as needed\n\n**Q: Mutation testing takes too long**\nA: Mutation testing is resource-intensive:\n- Use `--quick-mutation` flag for subset testing\n- Focus on critical modules first\n- Run overnight for detailed analysis\n\n**Q: Can't find tests for my file**\nA: The analyzer uses naming conventions:\n- Source: `my_module.py` → Test: `test_my_module.py`\n- Check that test files follow pytest naming patterns\n- validate test directory structure is standard\n\n### Performance Tips\n\n- **Large codebases**: Use `--target` to focus on specific directories\n- **CI integration**: Run validation in parallel with other checks\n- **Memory usage**: Process files in batches for very large projects\n\n### Getting Help\n\n1. Check script outputs for detailed error messages\n2. Use `--verbose` flag for more information\n3. Review the validation report for specific recommendations\n4. Start with small modules to understand patterns before scaling\n\nFile v1.9.16:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-sanctum-test-updates\",\n  \"version\": \"1.9.16\",\n  \"publishedAt\": 1784059079998\n}\n\nFile v1.9.16:modules/bdd-patterns.md\n\n# BDD Patterns Module\n\n## Overview\n\nProvides multiple Behavior-Driven Development styles and patterns for creating expressive, behavior-focused tests.\n\n## Available Styles\n\n| Style | Best For |\n|-------|----------|\n| Gherkin | Complex workflows, acceptance criteria, cross-team |\n| BDD-pytest | Unit/API tests, developer focus |\n| Docstring BDD | Simple tests, quick docs |\n\n## Choosing the Right Style\n\n### Decision Guide\n\n| Style | Best For | Complexity | Collaboration |\n|-------|----------|------------|----------------|\n| Gherkin | Complex workflows, documentation | High | Excellent |\n| BDD-pytest | Unit/API tests, developer focus | Medium | Good |\n| Docstring BDD | Simple tests, quick docs | Low | Limited |\n\n### Mixing Styles\n- Use Gherkin for critical user journeys\n- Use BDD-pytest for unit and API tests\n- Use Docstring BDD for simple utilities\n- Maintain consistency within modules\n\n## Best Practices\n\n### Naming Conventions\n- **Tests**: `test_[behavior]_[when]_[expected]`\n- **Given/When/Then**: Clear separation of concerns\n- **Scenarios**: Describe business value, not technical details\n\n### Test Organization\nGroup related BDD scenarios in test classes with clear setup and teardown.\n\n---\n\n### Gherkin Style\n\nFeature files with Given/When/Then scenarios for complex user\nworkflows and cross-team collaboration.\n\n#### Feature File Structure\n\n```gherkin\nFeature: Git Workflow Management\n  As a developer\n  I want to automate git workflows\n  So that I can maintain clean commit history\n\n  Scenario: Commit with staged changes\n    Given a git repository with staged changes\n    When I run the commit workflow\n    Then a commit should be created with proper message\n    And all tests should pass\n\n  Scenario Outline: Multiple file types\n    Given a git repository with staged <file_type> files\n    When I run the commit workflow\n    Then the commit should reference <file_type>\n    And the commit type should be <commit_type>\n\n    Examples:\n      | file_type | commit_type |\n      | source    | feat       |\n      | test      | test       |\n      | docs      | docs       |\n```\n\n#### Step Definitions\n\n```python\n@given('a git repository with staged changes')\ndef step_given_git_repo_with_changes(context):\n    context.repo = create_test_repo()\n    context.repo.stage_changes(['file1.py', 'file2.py'])\n\n@when('I run the commit workflow')\ndef step_when_run_commit_workflow(context):\n    context.result = run_commit_workflow(context.repo)\n\n@then('a commit should be created with proper message')\ndef step_then_commit_created(context):\n    assert context.repo.has_commit()\n    assert context.repo.last_commit_message().startswith('feat:')\n```\n\n#### When to Use\n\n- Complex user workflows\n- Acceptance criteria documentation\n- Cross-team collaboration\n- Living documentation requirements\n\n---\n\n### Pytest Style\n\nBDD-style pytest tests with descriptive names and docstrings\nfor unit and API testing.\n\n#### Structure Example\n\n```python\nclass TestGitWorkflow:\n    \"\"\"BDD-style tests for Git workflow operations.\"\"\"\n\n    @pytest.mark.bdd\n    def test_commit_workflow_with_staged_changes(self):\n        \"\"\"\n        GIVEN a Git repository with staged changes\n        WHEN the user runs the commit workflow\n        THEN it should create a commit with proper message format\n        AND all tests should pass\n        \"\"\"\n        # Given\n        repo = create_git_repo()\n        repo.stage_changes(['feature.py'])\n\n        # When\n        result = run_commit_workflow(repo)\n\n        # Then\n        assert result.success is True\n        assert repo.has_commit()\n        assert repo.last_commit_message().startswith('feat:')\n\n    @pytest.mark.bdd\n    def test_commit_workflow_rejects_empty_changes(self):\n        \"\"\"\n        GIVEN a Git repository with no staged changes\n        WHEN the user runs the commit workflow\n        THEN it should reject with appropriate error message\n        \"\"\"\n        # Given\n        repo = create_git_repo()  # No changes staged\n\n        # When\n        result = run_commit_workflow(repo)\n\n        # Then\n        assert result.success is False\n        assert \"no staged changes\" in result.error.lower()\n```\n\n#### Best Practices\n\n- **Descriptive names**: Describe behavior, not implementation\n- **Clear sections**: Use Given/When/Then in docstrings\n- **Single responsibility**: One behavior per test\n- **Meaningful assertions**: Test specific outcomes\n\n#### When to Use\n\n- Unit tests with behavior focus\n- API testing\n- Service layer testing\n- Developer-facing documentation\n\n---\n\n### Docstring Style\n\nSimple BDD pattern using docstrings for quick behavior\ndocumentation and simple unit tests.\n\n#### Structure Example\n\n```python\ndef test_git_status_parsing():\n    \"\"\"Test parsing git status output.\n\n    GIVEN git status output with modified and untracked files\n    WHEN parsing the status\n    THEN it should return structured file information\n    AND correctly identify file states\n    \"\"\"\n    status_output = \"\"\"\n    M modified_file.py\n    A  added_file.py\n    ?? untracked_file.py\n    \"\"\"\n\n    result = parse_git_status(status_output)\n\n    assert 'modified_file.py' in result.modified\n    assert 'added_file.py' in result.added\n    assert 'untracked_file.py' in result.untracked\n```\n\n#### Best Practices\n\n- **Clear docstrings**: Include Given/When/Then\n- **Simple structure**: Ideal for utilities and helpers\n- **Quick documentation**: Minimal overhead for behavior specs\n- **Focused tests**: One clear behavior per test\n\n#### When to Use\n\n- Simple unit tests\n- Internal module testing\n- Quick behavior documentation\n- Utility function testing\n\nFile v1.9.16:modules/content-test-discovery.md\n\n# Content Test Discovery\n\nDetects when modified markdown files are \"execution markdown\" requiring content assertions, and identifies test gaps.\n\n## Execution Markdown Detection\n\nFiles matching ALL of these criteria are execution markdown:\n\n1. File extension is `.md`\n2. Path contains `skills/`, `agents/`, `modules/`, or `commands/`\n3. File is NOT named `README.md`, `CHANGELOG.md`, or located under `docs/` directories\n\n```python\ndef is_execution_markdown(file_path: str) -> bool:\n    \"\"\"Markdown that Claude interprets as behavioral instructions.\"\"\"\n    path = Path(file_path)\n    exec_dirs = {\"skills\", \"agents\", \"modules\", \"commands\"}\n    skip_names = {\"README.md\", \"CHANGELOG.md\"}\n    return (\n        path.suffix == \".md\"\n        and any(d in path.parts for d in exec_dirs)\n        and path.name not in skip_names\n        and \"docs\" not in path.parts\n    )\n```\n\n## Priority Reclassification\n\nOverride the default test-discovery priority scoring for execution markdown:\n\n| Change Type | Priority | Rationale |\n|---|---|---|\n| `SKILL.md` modified | **High** | Directly drives Claude's behavior |\n| Module `.md` modified | **Medium** | Loaded on-demand, affects specific workflows |\n| Agent `.md` modified | **Medium** | Defines agent behavior and constraints |\n| Command `.md` modified | **Low-Medium** | Affects slash command documentation |\n| README, CHANGELOG | Low | Not interpreted by Claude as instructions |\n\n## Test Gap Detection\n\nWhen execution markdown is modified, check for a corresponding content test class.\n\n### Naming Convention\n\n| Source File | Expected Test Location |\n|---|---|\n| `plugins/<plugin>/skills/<name>/SKILL.md` | `plugins/<plugin>/tests/unit/skills/test_<name_underscored>.py` |\n| `plugins/<plugin>/skills/<name>/modules/<mod>.md` | `plugins/<plugin>/tests/unit/skills/test_<name_underscored>.py` |\n| `plugins/<plugin>/agents/<name>.md` | `plugins/<plugin>/tests/unit/test_<name_underscored>.py` |\n\n### Detection Heuristic\n\nLook for existing content test classes by checking:\n\n1. Test file exists at the expected path\n2. File contains a class ending in `Content` (e.g., `TestClearContextSkillContent`)\n3. File contains fixtures that read `.md` files (e.g., `skill_content`, `module_content`)\n\nIf no content test class exists, flag as a content test gap.\n\n## When to Generate vs. Skip\n\nNot every markdown change needs new content tests.\n\n### Generate Content Tests When\n\n- A new skill or module is created (no existing tests)\n- Code examples (JSON, YAML, Python) are added or modified (L2 needed)\n- Version references are added or changed (L3 cross-reference needed)\n- Decision frameworks or behavioral guidance is modified (L3 contract needed)\n- Forbidden behavior patterns are specified (L3 anti-pattern detection needed)\n\n### Skip Content Tests When\n\n- Typo or grammar fix only (no behavioral change)\n- Whitespace or formatting changes\n- Changes to prose that don't affect decision logic\n- Changes already covered by `scribe:slop-detector` (style, not behavior)\n\n## Integration\n\nThis module is loaded during Phase 1 (Discovery) of the test-updates workflow. It extends git-based change detection to recognize execution markdown as high-priority test targets.\n\nReference: `leyline:testing-quality-standards/modules/content-assertion-levels.md` for the L1/L2/L3 taxonomy that determines which level of tests to generate.\n\nFile v1.9.16:modules/quality-validation.md\n\n# Quality Validation Module\n\n## Overview\n\ndetailed test quality assurance through static analysis, dynamic validation, metrics tracking, and structured peer review.\n\n## Validation Categories\n\n### 1. Static Analysis\nValidate test code without execution (details below).\n\n### 2. Dynamic Validation\nExecute tests to verify they actually work (details below).\n\n### 3. Metrics Validation\nTrack quantitative quality measures (details below).\n\n### 4. Peer Review Checklist\nStructured validation for human review.\n\n#### Quality Gates Checklist\n```python\nQUALITY_GATES = {\n    \"structure\": [\n        \"Test follows BDD pattern with Given/When/Then\",\n        \"Test has descriptive name explaining behavior\",\n        \"Test is independent and isolated\",\n        \"Test uses appropriate fixtures or setup\",\n    ],\n    \"assertions\": [\n        \"Assertions are specific and meaningful\",\n        \"Error messages are descriptive\",\n        \"Both positive and negative cases tested\",\n        \"Edge cases are covered\",\n    ],\n    \"maintenance\": [\n        \"Test is readable and understandable\",\n        \"Test data is clearly defined\",\n        \"External dependencies are mocked\",\n        \"Test documentation is adequate\",\n    ],\n    \"performance\": [\n        \"Test runs quickly (< 1 second)\",\n        \"No unnecessary I/O operations\",\n        \"Memory usage is reasonable\",\n        \"Tests are parallelizable\",\n    ],\n}\n```\n\n## Validation Workflow\n\n```python\ndef run_validation_pipeline(test_path, source_path=None):\n    \"\"\"Run complete validation pipeline.\"\"\"\n\n    report = ValidationReport()\n\n    # Phase 1: Static Analysis\n    static_issues = validate_static_quality(test_path)\n    report.add_section(\"Static Analysis\", static_issues)\n\n    # Phase 2: Dynamic Validation\n    execution_results = validate_test_execution(test_path)\n    report.add_section(\"Dynamic Validation\", execution_results)\n\n    # Phase 3: Mutation Testing (if source provided)\n    if source_path:\n        mutation_score = run_mutation_tests(test_path, source_path)\n        report.add_section(\"Mutation Testing\", {\"score\": mutation_score})\n\n    # Phase 4: Metrics Validation\n    coverage_violations = validate_coverage_metrics(execution_results[\"coverage\"])\n    report.add_section(\"Coverage Metrics\", coverage_violations)\n\n    # Phase 5: Complexity Analysis\n    complexity = calculate_test_complexity(test_path)\n    report.add_section(\"Complexity Metrics\", complexity)\n\n    return report\n```\n\n## Quality Standards\n\n### Minimum Requirements\n- **Coverage**: 85% line, 80% branch, 90% function\n- **Mutation Score**: 80% or higher\n- **Test Speed**: < 1 second per test\n- **Independence**: No test dependencies\n- **BDD Compliance**: All tests follow BDD patterns\n\n### Excellence Criteria\n- **Coverage**: 95% line, 90% branch, 100% function\n- **Mutation Score**: 90% or higher\n- **Test Speed**: < 0.5 seconds per test\n- **Documentation**: detailed behavior description\n- **Maintainability**: Clear, readable, well-structured\n\n### Failure Modes\nTests failing validation should:\n1. Generate detailed issue reports\n2. Suggest specific improvements\n3. Provide examples of fixes\n4. Block merging until resolved\n\n---\n\n### Static Analysis\n\nValidate test code without execution using pattern matching\nand AST analysis.\n\n#### Code Quality Checks\n\n```python\ndef validate_static_quality(test_file):\n\n\nArchive v1.9.14: 10 files, 23121 bytes\n\nFiles: modules/bdd-patterns.md (5571b), modules/content-test-discovery.md (3355b), modules/quality-validation.md (8344b), modules/tdd-workflow.md (3663b), modules/test-discovery.md (2810b), modules/test-enhancement.md (6145b), modules/test-generation.md (13129b), skill-card.md (1930b), SKILL.md (12295b), _meta.json (143b)\n\nArchive v1.9.13: 10 files, 23343 bytes\n\nFiles: modules/bdd-patterns.md (5571b), modules/content-test-discovery.md (3355b), modules/quality-validation.md (8344b), modules/tdd-workflow.md (3663b), modules/test-discovery.md (2810b), modules/test-enhancement.md (6145b), modules/test-generation.md (13129b), skill-card.md (2406b), SKILL.md (12295b), _meta.json (143b)\n\nArchive v1.9.12: 10 files, 23434 bytes\n\nFiles: modules/bdd-patterns.md (5571b), modules/content-test-discovery.md (3355b), modules/quality-validation.md (8344b), modules/tdd-workflow.md (3663b), modules/test-discovery.md (2810b), modules/test-enhancement.md (6145b), modules/test-generation.md (13129b), skill-card.md (2817b), SKILL.md (12295b), _meta.json (143b)\n\nArchive v1.0.3: 10 files, 23294 bytes\n\nFiles: modules/bdd-patterns.md (5571b), modules/content-test-discovery.md (3355b), modules/quality-validation.md (8344b), modules/tdd-workflow.md (3663b), modules/test-discovery.md (2810b), modules/test-enhancement.md (6145b), modules/test-generation.md (13129b), skill-card.md (2350b), SKILL.md (12295b), _meta.json (142b)\n\nArchive v1.0.2: 23 files, 27178 bytes\n\nFiles: modules/bdd-patterns.md (1468b), modules/bdd/docstring-style.md (1082b), modules/bdd/gherkin-style.md (1603b), modules/bdd/pytest-style.md (1714b), modules/content-test-discovery.md (3355b), modules/enhancement/bdd-transformation.md (1192b), modules/enhancement/edge-cases.md (1591b), modules/enhancement/organization-patterns.md (2027b), modules/generation/content-test-templates.md (7458b), modules/generation/smart-features.md (1374b), modules/generation/strategies.md (1749b), modules/generation/templates.md (1533b), modules/quality-validation.md (3393b), modules/tdd-workflow.md (3663b), modules/test-discovery.md (2810b), modules/test-enhancement.md (1735b), modules/test-generation.md (1211b), modules/validation/dynamic-validation.md (1775b), modules/validation/quality-metrics.md (1866b), modules/validation/static-analysis.md (1578b), skill-card.md (2475b), SKILL.md (10055b), _meta.json (142b)\n\nArchive v1.0.1: 22 files, 25874 bytes\n\nFiles: modules/bdd-patterns.md (1468b), modules/bdd/docstring-style.md (1082b), modules/bdd/gherkin-style.md (1603b), modules/bdd/pytest-style.md (1714b), modules/content-test-discovery.md (3355b), modules/enhancement/bdd-transformation.md (1192b), modules/enhancement/edge-cases.md (1591b), modules/enhancement/organization-patterns.md (2027b), modules/generation/content-test-templates.md (7458b), modules/generation/smart-features.md (1374b), modules/generation/strategies.md (1749b), modules/generation/templates.md (1533b), modules/quality-validation.md (3393b), modules/tdd-workflow.md (3663b), modules/test-discovery.md (2810b), modules/test-enhancement.md (1735b), modules/test-generation.md (1211b), modules/validation/dynamic-validation.md (1775b), modules/validation/quality-metrics.md (1866b), modules/validation/static-analysis.md (1578b), SKILL.md (10055b), _meta.json (142b)\n\nArchive v1.0.0: 22 files, 25874 bytes\n\nFiles: modules/bdd-patterns.md (1468b), modules/bdd/docstring-style.md (1082b), modules/bdd/gherkin-style.md (1603b), modules/bdd/pytest-style.md (1714b), modules/content-test-discovery.md (3355b), modules/enhancement/bdd-transformation.md (1192b), modules/enhancement/edge-cases.md (1591b), modules/enhancement/organization-patterns.md (2027b), modules/generation/content-test-templates.md (7458b), modules/generation/smart-features.md (1374b), modules/generation/strategies.md (1749b), modules/generation/templates.md (1533b), modules/quality-validation.md (3393b), modules/tdd-workflow.md (3663b), modules/test-discovery.md (2810b), modules/test-enhancement.md (1735b), modules/test-generation.md (1211b), modules/validation/dynamic-validation.md (1775b), modules/validation/quality-metrics.md (1866b), modules/validation/static-analysis.md (1578b), SKILL.md (10055b), _meta.json (142b)","readmeExcerpt":"Skill: test-updates Owner: athola Summary: Updates, generates, and validates tests using git-workspace context and TDD/BDD methodology Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:21:11.130Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:41:12.204Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:57:59.998Z | user Release v1.9.16 v1.9.14 | 2026-06-30T18:05:47.824Z | user Release v1.9.14 v1.9.13 | 2026-0","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"# Run full test update workflow\nSkill(test-updates)"},{"language":"bash","snippet":"# Update tests for specific paths\nSkill(test-updates) --target src/sanctum/agents\nSkill(test-updates) --target tests/test_commit_messages.py"},{"language":"bash","snippet":"# Apply TDD to new code\nSkill(test-updates) --tdd-only --target new_feature.py"},{"language":"bash","snippet":"# Analyze test coverage gaps\npython plugins/sanctum/scripts/test_analyzer.py --scan src/\n\n# Generate test scaffolding\npython plugins/sanctum/scripts/test_generator.py \\\n    --source src/my_module.py --style pytest_bdd\n\n# Check test quality\npython plugins/sanctum/scripts/quality_checker.py \\\n    --validate tests/test_my_module.py"},{"language":"bash","snippet":"# Get JSON output for programmatic parsing - test_analyzer\npython plugins/sanctum/scripts/test_analyzer.py \\\n    --scan src/ --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"source_files\": [\"src/module.py\", ...],\n#     \"test_files\": [\"tests/test_module.py\", ...],\n#     \"uncovered_files\": [\"module_without_tests\", ...],\n#     \"coverage_gaps\": [{\"file\": \"...\", \"reason\": \"...\"}]\n#   }\n# }\n\n# Get JSON output - test_generator\npython plugins/sanctum/scripts/test_generator.py \\\n    --source src/my_module.py --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"test_file\": \"path/to/test_my_module.py\",\n#     \"source_file\": \"src/my_module.py\",\n#     \"style\": \"pytest_bdd\",\n#     \"fixtures_included\": true,\n#     \"edge_cases_included\": true,\n#     \"error_cases_included\": true\n#   }\n# }\n\n# Get JSON output - quality_checker\npython plugins/sanctum/scripts/quality_checker.py \\\n    --validate tests/test_my_module.py --output-json\n\n# Returns:\n# {\n#   \"success\": true,\n#   \"data\": {\n#     \"static_analysis\": {...},\n#     \"dynamic_validation\": {...},\n#     \"metrics\": {...},\n#     \"quality_score\": 85,\n#     \"quality_level\": \"QualityLevel.GOOD\",\n#     \"recommendations\": [...]\n#   }\n# }"},{"language":"python","snippet":"def test_plugins_never_import_from_other_plugins():\n    \"\"\"Encode the invariant: plugins are independent modules.\n\n    If this test breaks, someone is coupling plugins\n    directly. Present the 3 options to a human:\n    1. Preserve: revert the import, keep plugins independent\n    2. Layer: add a shared interface in leyline instead\n    3. Revise: merge the plugins (requires ADR)\n    \"\"\"\n    for plugin_dir in plugin_dirs:\n        imports = extract_imports(plugin_dir)\n        for imp in imports:\n            assert not imp.startswith(\"plugins.\"), (\n                f\"{plugin_dir} imports {imp} — \"\n                f\"violates plugin independence invariant\"\n            )"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: test-updates\ndescription: |\n  Updates, generates, and validates tests using git-workspace context and TDD/BDD methodology\nversion: 1.9.8\ntriggers:\n  - tdd\n  - bdd\n  - testing\n  - quality-assurance\n  - test-generation\n  - pytest\n  - code changes require new or updated test coverage\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/sanctum\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.test-driven-development\", \"night-market.git-workspace-review\", \"night-market.file-analysis\"]}}}\nsource: claude-night-market\nsource_plugin: sanctum\n---\n\n> **Night Market Skill** — ported from [claude-night-market/sanctum](https://github.com/athola/claude-night-market/tree/master/plugins/sanctum). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Overview](#overview)\n- [Core Philosophy](#core-philosophy)\n- [What It Is](#what-it-is)\n- [Quick Start](#quick-start)\n- [Quick Checklist for First Time Use](#quick-checklist-for-first-time-use)\n- [detailed Test Update](#detailed-test-update)\n- [Targeted Test Updates](#targeted-test-updates)\n- [TDD for New Features](#tdd-for-new-features)\n- [Using the Scripts Directly](#using-the-scripts-directly)\n- [When to Use It](#when-to-use-it)\n- [Workflow Integration](#workflow-integration)\n- [Phase 1: Discovery](#phase-1:-discovery)\n- [Phase 2: Strategy](#phase-2:-strategy)\n- [Phase 3: Implementation](#phase-3:-implementation)\n- [Phase 4: Validation](#phase-4:-validation)\n- [Quality Assurance](#quality-assurance)\n- [Examples](#examples)\n- [BDD-Style Test Generation](#bdd-style-test-generation)\n- [Test Enhancement](#test-enhancement)\n- [Integration with Existing Skills](#integration-with-existing-skills)\n- [Success Metrics](#success-metrics)\n- [Troubleshooting FAQ](#troubleshooting-faq)\n- [Common Issues](#common-issues)\n- [Performance Tips](#performance-tips)\n- [Getting Help](#getting-help)\n\n\n# Test Updates and Maintenance\n\n## Overview\n\ndetailed test management system that applies TDD/BDD principles to maintain, generate, and enhance tests across codebases. This skill practices what it preaches - it uses TDD principles for its own development and serves as a living example of best practices.\n\n### Core Philosophy\n\n- **RED-GREEN-REFACTOR**: Strict adherence to TDD cycle\n- **Behavior-First**: BDD patterns that describe what code should do\n- **Invariant-Encoding**: Tests guard design decisions, not just behavior\n- **Meta Dogfooding**: The skill's own tests demonstrate the principles it teaches\n- **Quality Gates**: detailed validation before considering tests complete\n\n## What It Is\n\nA modular test management system that:\n- Discovers what needs testing or updating\n- Generates tests following TDD principles\n- Enhances existing tests with BDD patterns\n- Validate test quality through multiple lenses\n\n## Quick Start\n\n### Quick Checklist for First Time Use\n- [ ] validate pytest is installed (`pip install"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-sanctum-test-updates\",\n  \"version\": \"1.9.19\",\n  \"publishedAt\": 1787750471130\n}"},{"path":"modules/bdd-patterns.md","content":"# BDD Patterns Module\n\n## Overview\n\nProvides multiple Behavior-Driven Development styles and patterns for creating expressive, behavior-focused tests.\n\n## Available Styles\n\n| Style | Best For |\n|-------|----------|\n| Gherkin | Complex workflows, acceptance criteria, cross-team |\n| BDD-pytest | Unit/API tests, developer focus |\n| Docstring BDD | Simple tests, quick docs |\n\n## Choosing the Right Style\n\n### Decision Guide\n\n| Style | Best For | Complexity | Collaboration |\n|-------|----------|------------|----------------|\n| Gherkin | Complex workflows, documentation | High | Excellent |\n| BDD-pytest | Unit/API tests, developer focus | Medium | Good |\n| Docstring BDD | Simple tests, quick docs | Low | Limited |\n\n### Mixing Styles\n- Use Gherkin for critical user journeys\n- Use BDD-pytest for unit and API tests\n- Use Docstring BDD for simple utilities\n- Maintain consistency within modules\n\n## Best Practices\n\n### Naming Conventions\n- **Tests**: `test_[behavior]_[when]_[expected]`\n- **Given/When/Then**: Clear separation of concerns\n- **Scenarios**: Describe business value, not technical details\n\n### Test Organization\nGroup related BDD scenarios in test classes with clear setup and teardown.\n\n---\n\n### Gherkin Style\n\nFeature files with Given/When/Then scenarios for complex user\nworkflows and cross-team collaboration.\n\n#### Feature File Structure\n\n```gherkin\nFeature: Git Workflow Management\n  As a developer\n  I want to automate git workflows\n  So that I can maintain clean commit history\n\n  Scenario: Commit with staged changes\n    Given a git repository with staged changes\n    When I run the commit workflow\n    Then a commit should be created with proper message\n    And all tests should pass\n\n  Scenario Outline: Multiple file types\n    Given a git repository with staged <file_type> files\n    When I run the commit workflow\n    Then the commit should reference <file_type>\n    And the commit type should be <commit_type>\n\n    Examples:\n      | file_type | commit_type |\n      | source    | feat       |\n      | test      | test       |\n      | docs      | docs       |\n```\n\n#### Step Definitions\n\n```python\n@given('a git repository with staged changes')\ndef step_given_git_repo_with_changes(context):\n    context.repo = create_test_repo()\n    context.repo.stage_changes(['file1.py', 'file2.py'])\n\n@when('I run the commit workflow')\ndef step_when_run_commit_workflow(context):\n    context.result = run_commit_workflow(context.repo)\n\n@then('a commit should be created with proper message')\ndef step_then_commit_created(context):\n    assert context.repo.has_commit()\n    assert context.repo.last_commit_message().startswith('feat:')\n```\n\n#### When to Use\n\n- Complex user workflows\n- Acceptance criteria documentation\n- Cross-team collaboration\n- Living documentation requirements\n\n---\n\n### Pytest Style\n\nBDD-style pytest tests with descriptive names and docstrings\nfor unit and API testing.\n\n#### Structure Example\n\n```python\nclass TestGitWorkflow:\n    \"\"\"BDD-style tests for Git workf"},{"path":"modules/content-test-discovery.md","content":"# Content Test Discovery\n\nDetects when modified markdown files are \"execution markdown\" requiring content assertions, and identifies test gaps.\n\n## Execution Markdown Detection\n\nFiles matching ALL of these criteria are execution markdown:\n\n1. File extension is `.md`\n2. Path contains `skills/`, `agents/`, `modules/`, or `commands/`\n3. File is NOT named `README.md`, `CHANGELOG.md`, or located under `docs/` directories\n\n```python\ndef is_execution_markdown(file_path: str) -> bool:\n    \"\"\"Markdown that Claude interprets as behavioral instructions.\"\"\"\n    path = Path(file_path)\n    exec_dirs = {\"skills\", \"agents\", \"modules\", \"commands\"}\n    skip_names = {\"README.md\", \"CHANGELOG.md\"}\n    return (\n        path.suffix == \".md\"\n        and any(d in path.parts for d in exec_dirs)\n        and path.name not in skip_names\n        and \"docs\" not in path.parts\n    )\n```\n\n## Priority Reclassification\n\nOverride the default test-discovery priority scoring for execution markdown:\n\n| Change Type | Priority | Rationale |\n|---|---|---|\n| `SKILL.md` modified | **High** | Directly drives Claude's behavior |\n| Module `.md` modified | **Medium** | Loaded on-demand, affects specific workflows |\n| Agent `.md` modified | **Medium** | Defines agent behavior and constraints |\n| Command `.md` modified | **Low-Medium** | Affects slash command documentation |\n| README, CHANGELOG | Low | Not interpreted by Claude as instructions |\n\n## Test Gap Detection\n\nWhen execution markdown is modified, check for a corresponding content test class.\n\n### Naming Convention\n\n| Source File | Expected Test Location |\n|---|---|\n| `plugins/<plugin>/skills/<name>/SKILL.md` | `plugins/<plugin>/tests/unit/skills/test_<name_underscored>.py` |\n| `plugins/<plugin>/skills/<name>/modules/<mod>.md` | `plugins/<plugin>/tests/unit/skills/test_<name_underscored>.py` |\n| `plugins/<plugin>/agents/<name>.md` | `plugins/<plugin>/tests/unit/test_<name_underscored>.py` |\n\n### Detection Heuristic\n\nLook for existing content test classes by checking:\n\n1. Test file exists at the expected path\n2. File contains a class ending in `Content` (e.g., `TestClearContextSkillContent`)\n3. File contains fixtures that read `.md` files (e.g., `skill_content`, `module_content`)\n\nIf no content test class exists, flag as a content test gap.\n\n## When to Generate vs. Skip\n\nNot every markdown change needs new content tests.\n\n### Generate Content Tests When\n\n- A new skill or module is created (no existing tests)\n- Code examples (JSON, YAML, Python) are added or modified (L2 needed)\n- Version references are added or changed (L3 cross-reference needed)\n- Decision frameworks or behavioral guidance is modified (L3 contract needed)\n- Forbidden behavior patterns are specified (L3 anti-pattern detection needed)\n\n### Skip Content Tests When\n\n- Typo or grammar fix only (no behavioral change)\n- Whitespace or formatting changes\n- Changes to prose that don't affect decision logic\n- Changes already covered by `scribe:slop-detector` (style, not behavior)\n\n#"},{"path":"modules/quality-validation.md","content":"# Quality Validation Module\n\n## Overview\n\ndetailed test quality assurance through static analysis, dynamic validation, metrics tracking, and structured peer review.\n\n## Validation Categories\n\n### 1. Static Analysis\nValidate test code without execution (details below).\n\n### 2. Dynamic Validation\nExecute tests to verify they actually work (details below).\n\n### 3. Metrics Validation\nTrack quantitative quality measures (details below).\n\n### 4. Peer Review Checklist\nStructured validation for human review.\n\n#### Quality Gates Checklist\n```python\nQUALITY_GATES = {\n    \"structure\": [\n        \"Test follows BDD pattern with Given/When/Then\",\n        \"Test has descriptive name explaining behavior\",\n        \"Test is independent and isolated\",\n        \"Test uses appropriate fixtures or setup\",\n    ],\n    \"assertions\": [\n        \"Assertions are specific and meaningful\",\n        \"Error messages are descriptive\",\n        \"Both positive and negative cases tested\",\n        \"Edge cases are covered\",\n    ],\n    \"maintenance\": [\n        \"Test is readable and understandable\",\n        \"Test data is clearly defined\",\n        \"External dependencies are mocked\",\n        \"Test documentation is adequate\",\n    ],\n    \"performance\": [\n        \"Test runs quickly (< 1 second)\",\n        \"No unnecessary I/O operations\",\n        \"Memory usage is reasonable\",\n        \"Tests are parallelizable\",\n    ],\n}\n```\n\n## Validation Workflow\n\n```python\ndef run_validation_pipeline(test_path, source_path=None):\n    \"\"\"Run complete validation pipeline.\"\"\"\n\n    report = ValidationReport()\n\n    # Phase 1: Static Analysis\n    static_issues = validate_static_quality(test_path)\n    report.add_section(\"Static Analysis\", static_issues)\n\n    # Phase 2: Dynamic Validation\n    execution_results = validate_test_execution(test_path)\n    report.add_section(\"Dynamic Validation\", execution_results)\n\n    # Phase 3: Mutation Testing (if source provided)\n    if source_path:\n        mutation_score = run_mutation_tests(test_path, source_path)\n        report.add_section(\"Mutation Testing\", {\"score\": mutation_score})\n\n    # Phase 4: Metrics Validation\n    coverage_violations = validate_coverage_metrics(execution_results[\"coverage\"])\n    report.add_section(\"Coverage Metrics\", coverage_violations)\n\n    # Phase 5: Complexity Analysis\n    complexity = calculate_test_complexity(test_path)\n    report.add_section(\"Complexity Metrics\", complexity)\n\n    return report\n```\n\n## Quality Standards\n\n### Minimum Requirements\n- **Coverage**: 85% line, 80% branch, 90% function\n- **Mutation Score**: 80% or higher\n- **Test Speed**: < 1 second per test\n- **Independence**: No test dependencies\n- **BDD Compliance**: All tests follow BDD patterns\n\n### Excellence Criteria\n- **Coverage**: 95% line, 90% branch, 100% function\n- **Mutation Score**: 90% or higher\n- **Test Speed**: < 0.5 seconds per test\n- **Documentation**: detailed behavior description\n- **Maintainability**: Clear, readable, well-structured\n\n### Failure Modes\nTests failing valid"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Updates, generates, and validates tests using git-workspace context and TDD/BDD methodology Skill: test-updates Owner: athola Summary: Updates, generates, and validates tests using git-workspace context and TDD/BDD methodology Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:21:11.130Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:41:12.204Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:57:59.998Z | user Release v1.9.16 v1.9.14 | 2026-06-30T18:05:47.824Z | user Release v1.9.14 v1.9.13 | 2026-0","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1255,"uniquenessScore":49,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-10T09:03:52.916Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-10T09:03:52.916Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-10T11:54:00.878Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}