@workingpayload/agent-skills 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/APIForge/skill.md +165 -0
  2. package/AccessPlus/skill.md +136 -0
  3. package/AlgoMaster/skill.md +125 -0
  4. package/Architekt AI/skill.md +140 -0
  5. package/AuthCraft/skill.md +144 -0
  6. package/AutoScriptor/skill.md +137 -0
  7. package/BoilerCore/skill.md +136 -0
  8. package/BugHunter Pro/skill.md +133 -0
  9. package/ChangeScribe/skill.md +113 -0
  10. package/CodeSage/skill.md +163 -0
  11. package/CommitCraft/skill.md +113 -0
  12. package/CoverageMax/skill.md +161 -0
  13. package/CronGenius/skill.md +157 -0
  14. package/DataPolish/skill.md +142 -0
  15. package/DataWeaver/skill.md +151 -0
  16. package/DockMaster/skill.md +158 -0
  17. package/DocuGenie/skill.md +138 -0
  18. package/EdgeGuard/skill.md +160 -0
  19. package/EnvWizard/skill.md +156 -0
  20. package/ErrorMedic/skill.md +152 -0
  21. package/FeatureSmith/skill.md +139 -0
  22. package/FlexiLayout/skill.md +144 -0
  23. package/FlowTester/skill.md +154 -0
  24. package/FunctionForge/skill.md +136 -0
  25. package/InputShield/skill.md +144 -0
  26. package/IssueForge/skill.md +148 -0
  27. package/KubeCrafter/skill.md +149 -0
  28. package/LogicLens/skill.md +132 -0
  29. package/MockSmith/skill.md +146 -0
  30. package/ModelSensei/skill.md +138 -0
  31. package/PRMentor/skill.md +103 -0
  32. package/PerfDetective/skill.md +90 -0
  33. package/PipelinePro/skill.md +146 -0
  34. package/PolyglotShift/skill.md +94 -0
  35. package/PromptForge/skill.md +118 -0
  36. package/QueryPulse/skill.md +123 -0
  37. package/README.md +416 -329
  38. package/ReadMeCraft/skill.md +127 -0
  39. package/RefactorX/skill.md +84 -0
  40. package/RenderBoost/skill.md +148 -0
  41. package/SEOMancer/skill.md +156 -0
  42. package/ScrapeMaster/skill.md +157 -0
  43. package/SecretSniffer/skill.md +123 -0
  44. package/SecureScan/skill.md +130 -0
  45. package/ServiceSplitter/skill.md +153 -0
  46. package/SpeedSmith/skill.md +155 -0
  47. package/StackWise/skill.md +155 -0
  48. package/TaskOrchestrator/skill.md +135 -0
  49. package/TestCrafter/skill.md +158 -0
  50. package/TraceMind/skill.md +143 -0
  51. package/UISmith/skill.md +131 -0
  52. package/bin/cli.js +377 -0
  53. package/extension-extender/SKILL.md +122 -0
  54. package/fastapi-furious/SKILL.md +148 -0
  55. package/package.json +41 -32
  56. package/python-master/SKILL.md +108 -0
  57. package/react-ranger/SKILL.md +93 -0
  58. package/scripts/build_index.py +282 -0
  59. package/scripts/doctor.py +541 -0
  60. package/scripts/install.py +397 -0
  61. package/scripts/route.py +348 -0
  62. package/scripts/score.py +355 -0
  63. package/scripts/test_skill.py +473 -0
  64. package/scripts/validate.py +254 -0
  65. package/skills-routing.json +1131 -0
  66. package/skills.json +3261 -0
  67. package/cli.js +0 -181
  68. package/skills/APIForge/skill.md +0 -32
  69. package/skills/AccessPlus/skill.md +0 -32
  70. package/skills/AlgoMaster/skill.md +0 -32
  71. package/skills/Architekt AI/skill.md +0 -32
  72. package/skills/AuthCraft/skill.md +0 -32
  73. package/skills/AutoScriptor/skill.md +0 -32
  74. package/skills/BoilerCore/skill.md +0 -32
  75. package/skills/BugHunter Pro/skill.md +0 -32
  76. package/skills/ChangeScribe/skill.md +0 -32
  77. package/skills/CodeSage/skill.md +0 -32
  78. package/skills/CommitCraft/skill.md +0 -32
  79. package/skills/CoverageMax/skill.md +0 -32
  80. package/skills/CronGenius/skill.md +0 -32
  81. package/skills/DataPolish/skill.md +0 -32
  82. package/skills/DataWeaver/skill.md +0 -32
  83. package/skills/DockMaster/skill.md +0 -32
  84. package/skills/DocuGenie/skill.md +0 -32
  85. package/skills/EdgeGuard/skill.md +0 -32
  86. package/skills/EnvWizard/skill.md +0 -32
  87. package/skills/ErrorMedic/skill.md +0 -32
  88. package/skills/Extension-Extender/SKILL.md +0 -41
  89. package/skills/Extension-Extender/references/ui-guidelines.md +0 -26
  90. package/skills/Fastapi-Furious/README.md +0 -16
  91. package/skills/Fastapi-Furious/SKILL.md +0 -37
  92. package/skills/FeatureSmith/skill.md +0 -32
  93. package/skills/FlexiLayout/skill.md +0 -32
  94. package/skills/FlowTester/skill.md +0 -32
  95. package/skills/FunctionForge/skill.md +0 -32
  96. package/skills/InputShield/skill.md +0 -32
  97. package/skills/IssueForge/skill.md +0 -32
  98. package/skills/KubeCrafter/skill.md +0 -32
  99. package/skills/LogicLens/skill.md +0 -32
  100. package/skills/MockSmith/skill.md +0 -32
  101. package/skills/ModelSensei/skill.md +0 -32
  102. package/skills/PRMentor/skill.md +0 -32
  103. package/skills/PerfDetective/skill.md +0 -32
  104. package/skills/PipelinePro/skill.md +0 -32
  105. package/skills/PolyglotShift/skill.md +0 -32
  106. package/skills/PromptForge/skill.md +0 -32
  107. package/skills/Python-Master/README.md +0 -11
  108. package/skills/Python-Master/SKILL.md +0 -37
  109. package/skills/QueryPulse/skill.md +0 -32
  110. package/skills/React-Ranger/README.md +0 -17
  111. package/skills/React-Ranger/SKILL.md +0 -37
  112. package/skills/ReadMeCraft/skill.md +0 -32
  113. package/skills/RefactorX/skill.md +0 -32
  114. package/skills/RenderBoost/skill.md +0 -32
  115. package/skills/SEOMancer/skill.md +0 -32
  116. package/skills/ScrapeMaster/skill.md +0 -32
  117. package/skills/SecretSniffer/skill.md +0 -32
  118. package/skills/SecureScan/skill.md +0 -32
  119. package/skills/ServiceSplitter/skill.md +0 -32
  120. package/skills/SpeedSmith/skill.md +0 -32
  121. package/skills/StackWise/skill.md +0 -32
  122. package/skills/TaskOrchestrator/skill.md +0 -32
  123. package/skills/TestCrafter/skill.md +0 -32
  124. package/skills/TraceMind/skill.md +0 -32
  125. package/skills/UISmith/skill.md +0 -32
  126. /package/{skills/Extension-Extender → extension-extender}/assets/manifest.json +0 -0
  127. /package/{skills/Extension-Extender → extension-extender}/assets/popup.css +0 -0
  128. /package/{skills/Extension-Extender → extension-extender}/assets/popup.html +0 -0
  129. /package/{skills/Extension-Extender → extension-extender}/assets/popup.js +0 -0
@@ -0,0 +1,163 @@
1
+ ---
2
+ name: codesage
3
+ description: Performs structured code reviews with severity-tiered findings covering security, correctness, performance, and maintainability. Uses language-specific linters and static analysis tools. Use when a user submits code for review, asks for feedback on a PR, or needs an audit of a module or function.
4
+ ---
5
+
6
+ # CodeSage
7
+
8
+ ## Domain Scope
9
+
10
+ Code review across languages (Python, TypeScript/JavaScript, Java, Go, Rust, C/C++), covering: correctness bugs, security vulnerabilities, performance anti-patterns, API design, test coverage gaps, and maintainability issues. Output is structured by severity tier.
11
+
12
+ ---
13
+
14
+ ## Severity Tiers
15
+
16
+ Every finding must be tagged with a severity:
17
+
18
+ | Tier | Label | Meaning | Action required |
19
+ |------|-------|---------|-----------------|
20
+ | 1 | **CRITICAL** | Security vulnerability, data loss risk, or crash-causing bug | Block merge; must fix |
21
+ | 2 | **HIGH** | Logic error, incorrect behavior under edge cases, significant performance issue | Block merge; must fix |
22
+ | 3 | **MEDIUM** | Code smell, missing error handling, test gap, suboptimal approach | Fix before merge preferred |
23
+ | 4 | **LOW** | Style, naming, minor readability, non-idiomatic code | Fix or acknowledge |
24
+ | 5 | **NOTE** | Suggestion, alternative approach, educational context | No action required |
25
+
26
+ ---
27
+
28
+ ## Workflow
29
+
30
+ ### 1. Identify Language and Context
31
+ - Detect language from file extension and syntax.
32
+ - Note: framework (React, Spring, FastAPI), runtime (Node, JVM, Python 3.11+), and test framework.
33
+ - Check if this is new code, a modification, or a refactor.
34
+
35
+ ### 2. Static Analysis Pass (Automated Tools)
36
+ Run mentally (or recommend the user run):
37
+
38
+ **Python**: `ruff check` (style + basic errors), `mypy --strict` (type errors), `bandit -r .` (security), `pylint` (additional checks).
39
+
40
+ **TypeScript/JavaScript**: `eslint --max-warnings 0` with `@typescript-eslint/recommended`, `eslint-plugin-security`, `eslint-plugin-unicorn`. `tsc --noEmit` for type checking.
41
+
42
+ **Java**: SpotBugs + FindSecurityBugs plugin, Checkstyle, SonarQube rules. PMD for code quality.
43
+
44
+ **Go**: `go vet ./...`, `staticcheck ./...`, `gosec ./...`, `golangci-lint run`.
45
+
46
+ **Rust**: `cargo clippy -- -D warnings`, `cargo audit`, `cargo geiger` (unsafe usage audit).
47
+
48
+ **C/C++**: `clang-tidy`, `cppcheck`, AddressSanitizer/UBSan in tests.
49
+
50
+ ### 3. Security Review Checklist
51
+ Check for OWASP Top 10 patterns, including:
52
+
53
+ **OWASP A02 — Cryptographic Failures**: Flag any custom or hand-rolled cryptography implementation as CRITICAL — no exceptions. Recommend library-only crypto (`cryptography` in Python, `libsodium`, `WebCrypto API`). Common red flags: custom XOR/ROT ciphers, MD5/SHA-1 for security, ECB mode, hardcoded IVs/keys, non-constant-time secret comparisons.
54
+
55
+ **Feature Flag Removal Review**: When a feature flag is being removed (flag permanently on), verify all guarded code paths are cleaned up:
56
+ - [ ] Flag check condition and its `else` branch both removed (not just the `if`).
57
+ - [ ] Dead code path (the disabled branch) deleted, not just unreachable.
58
+ - [ ] Flag definition removed from config/constants and feature flag service.
59
+ - [ ] Tests for the old disabled path removed; tests for the enabled path remain without the flag setup.
60
+
61
+ **LLM-Generated Code Review**: Apply elevated scrutiny to code known or suspected to be AI-generated:
62
+ - Verify all referenced APIs, methods, and library functions actually exist — LLMs hallucinate plausible-sounding but non-existent APIs.
63
+ - Increase semantic testing requirement: generated code often passes syntactic checks but has subtle logic errors in edge cases. Add property-based tests or fuzz the inputs.
64
+ - Check for over-confident error handling (`except Exception: pass` patterns are common in generated code).
65
+ - Do not assume generated code follows your codebase's security conventions — recheck the full security checklist.
66
+
67
+ Check for additional OWASP Top 10 patterns:
68
+
69
+ - [ ] **Injection**: SQL queries built with string concatenation instead of parameterized queries / ORM. Command injection via `shell=True` (Python), `exec()`/`eval()` with user input.
70
+ - [ ] **Broken auth**: Hardcoded credentials, tokens in source code, weak random (use `secrets` module, not `random`).
71
+ - [ ] **Sensitive data exposure**: PII/secrets logged, HTTP instead of HTTPS, sensitive fields not excluded from serialization.
72
+ - [ ] **Insecure deserialization**: `pickle.loads()` / `yaml.load()` (use `yaml.safe_load()`) on untrusted input.
73
+ - [ ] **XSS**: `innerHTML`, `dangerouslySetInnerHTML` with unsanitized user content.
74
+ - [ ] **Path traversal**: file paths constructed from user input without validation (`os.path.join` does not protect against absolute paths in user input).
75
+ - [ ] **SSRF**: HTTP requests to URLs from user input without allowlist validation.
76
+ - [ ] **Dependency vulnerabilities**: check `npm audit`, `pip-audit`, `cargo audit`, `trivy`.
77
+
78
+ ### 4. Correctness Review
79
+
80
+ - **Off-by-one errors**: loop bounds, slice indices, pagination.
81
+ - **Null/undefined handling**: unchecked nullable access. In TypeScript: `strictNullChecks` enabled?
82
+ - **Error handling**: errors silently swallowed (`except: pass`, `.catch(() => {})`, unchecked `err` in Go). Every error must be handled, logged, or explicitly propagated.
83
+ - **Concurrency**: shared mutable state accessed without synchronization. Thread-safe collections used where needed.
84
+ - **Resource leaks**: file handles, DB connections, HTTP response bodies not closed in `finally`/`defer`/`using`.
85
+ - **Integer overflow**: especially in size calculations, array indexing, financial math (use `Decimal`, not `float`, for money).
86
+ - **Floating-point equality**: `if (x === 0.1 + 0.2)` is wrong; use epsilon comparison or integer arithmetic.
87
+
88
+ ### 5. Performance Review
89
+
90
+ - **N+1 queries**: loop that issues a DB query per iteration. Fix with eager loading (`JOIN`, `prefetch_related`, DataLoader).
91
+ - **Missing database indexes**: `WHERE`, `ORDER BY`, `JOIN` columns without indexes. Check `EXPLAIN ANALYZE`.
92
+ - **Unbounded queries**: no `LIMIT` on user-triggered queries. Risk: full table scan under load.
93
+ - **Unnecessary serialization**: converting to/from JSON inside a hot loop.
94
+ - **Algorithm complexity**: O(n²) where O(n log n) or O(n) is achievable (see AlgoMaster skill).
95
+ - **Memory allocation in loops**: creating large objects, closures, or buffers inside tight loops.
96
+ - **Blocking I/O in async context**: `time.sleep()` in an async function (Python), `fs.readFileSync()` in Node.js event handler.
97
+
98
+ ### 6. Maintainability Review
99
+
100
+ - **Function length**: functions > 40 lines are candidates for extraction. Single Responsibility Principle.
101
+ - **Cyclomatic complexity**: branches > 10 in a single function — extract sub-functions.
102
+ - **Magic numbers/strings**: unexplained literal values — extract to named constants.
103
+ - **Test coverage**: are happy path, error path, and edge cases covered? Missing tests for the code under review.
104
+ - **Documentation**: exported functions/classes must have docstrings. Complex algorithms need inline explanation.
105
+ - **Dead code**: unreachable branches, unused variables/imports (linters catch these).
106
+
107
+ ### 7. Language-Specific Idioms
108
+
109
+ **Python**: use comprehensions over explicit loops for simple transforms; `pathlib` over `os.path`; `dataclasses` or `pydantic` over raw dicts for structured data; `contextlib.contextmanager` for resource management.
110
+
111
+ **TypeScript**: prefer `const` over `let`; use `unknown` over `any`; use discriminated unions over optional fields; prefer `Array.prototype.map/filter/reduce` over imperative loops.
112
+
113
+ **Go**: handle errors explicitly, do not use `_` for error return unless the error is truly impossible; prefer `errors.Is`/`errors.As` over string comparison; use `context.Context` for cancellation propagation.
114
+
115
+ **Rust**: prefer `Option`/`Result` over panics in library code; use `?` operator for error propagation; avoid `clone()` in hot paths; use iterators over manual indexing.
116
+
117
+ ---
118
+
119
+ ## Output Format
120
+
121
+ Structure the review output as:
122
+
123
+ ```
124
+ ## Code Review: <filename or PR title>
125
+
126
+ ### Summary
127
+ <2-3 sentences: overall quality, main concerns, recommendation (approve / approve with changes / request changes)>
128
+
129
+ ### Findings
130
+
131
+ #### [CRITICAL] SQL injection via string concatenation — line 47
132
+ **File**: `src/repositories/user_repo.py:47`
133
+ **Issue**: `query = f"SELECT * FROM users WHERE id = {user_id}"` — user-controlled input concatenated directly into SQL.
134
+ **Impact**: Attacker can exfiltrate entire database, bypass auth, or drop tables.
135
+ **Fix**:
136
+ ```python
137
+ cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
138
+ ```
139
+
140
+ #### [HIGH] Error silently swallowed — line 83
141
+ ...
142
+
143
+ #### [MEDIUM] Missing index on query filter — line 12 of migration
144
+ ...
145
+
146
+ ### Test Coverage Gaps
147
+ - No test for `user_id` being negative
148
+ - No test for empty result set from `list_users()`
149
+
150
+ ### Positive Notes
151
+ - Good use of `contextlib.suppress` in cleanup handler
152
+ - Consistent error message format across all endpoints
153
+ ```
154
+
155
+ ---
156
+
157
+ ## Edge Cases
158
+
159
+ 1. **Reviewing auto-generated code** (e.g., from Prisma, gRPC protobuf, OpenAPI codegen): Do not flag generated files for style or structure issues — they are not human-maintained. Focus review on: (a) the generator configuration and schema (the real source), (b) any hand-written code that extends or wraps the generated code, (c) whether generated code is committed or regenerated in CI (prefer CI regeneration to avoid drift).
160
+
161
+ 2. **Security findings with false positive risk**: A finding like "user input passed to a function" is not automatically a security bug — it depends on whether the function performs sanitization internally. Before escalating to CRITICAL, trace the data flow from source to sink and confirm there is no sanitization in the call chain. Use data flow analysis tools (Semgrep with taint mode, CodeQL) to reduce false positives. Always include a concrete exploit scenario to justify CRITICAL/HIGH security findings.
162
+
163
+ 3. **Reviewing performance-sensitive code without profiling data**: Avoid premature optimization flags. Only flag a performance issue if: (a) the algorithmic complexity is provably worse (O(n²) where O(n) exists), (b) the pattern is a known anti-pattern (N+1 queries, blocking I/O), or (c) there is profiling data showing this is a hot path. For speculative performance concerns, use NOTE tier: "This loop allocates a new object per iteration — worth profiling if this becomes a hot path."
@@ -0,0 +1,113 @@
1
+ ---
2
+ name: commitcraft
3
+ description: Crafts Conventional Commits v1.0.0 compliant messages by analyzing git diffs. Use when a user asks for help with commit messages, git commits, or wants to commit staged changes.
4
+ ---
5
+
6
+ # CommitCraft
7
+
8
+ ## Overview
9
+
10
+ Produce Conventional Commits v1.0.0 messages from staged diffs or change descriptions. Every message must be machine-parseable for changelogs and semver automation.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Gather the Diff
15
+
16
+ Run `git diff --staged` (or `git diff HEAD~1` for the last commit). If nothing is staged, tell the user and stop.
17
+
18
+ Read the diff to identify:
19
+ - Which files changed and in what way (added, deleted, modified, renamed)
20
+ - Whether any public API surface changed (exported functions, REST routes, DB schema)
21
+ - Whether any config, env var, or migration is included
22
+
23
+ ### 2. Choose Type and Scope
24
+
25
+ **Type** — pick exactly one:
26
+ | Type | When to use |
27
+ |------|-------------|
28
+ | `feat` | New user-facing capability |
29
+ | `fix` | Bug correction |
30
+ | `refactor` | Code restructure with no behaviour change |
31
+ | `perf` | Performance improvement |
32
+ | `test` | Adding or fixing tests only |
33
+ | `docs` | Documentation only |
34
+ | `build` | Build system / dependency changes (webpack, npm, gradle) |
35
+ | `ci` | CI/CD pipeline changes |
36
+ | `chore` | Housekeeping (linting, formatting) |
37
+ | `revert` | Reverting a prior commit |
38
+
39
+ **Scope** — optional, in parentheses. Use the module, package, or route name: `feat(auth)`, `fix(api/users)`.
40
+
41
+ Before choosing types or scopes, check for `commitlint.config.js` or `.commitlintrc` — these override defaults and define allowed types/scopes. Use only values listed there; introducing an unlisted scope will break automated changelog tooling.
42
+
43
+ **Monorepo multi-scope**: When a change spans tightly coupled packages (e.g., a shared type changed in `core` that requires updates in `api` and `ui`), use the most impacted scope and list affected packages in the body: `feat(core): add PaymentIntent type` then `Affects: api, ui` in the body. Avoid comma-separated scopes like `feat(api,ui)` — most parsers reject them.
44
+
45
+ ### 3. Write the Subject Line
46
+
47
+ Rules (all mandatory):
48
+ - Format: `<type>(<scope>): <imperative description>`
49
+ - Max **72 characters** total
50
+ - Imperative mood: "add", "fix", "remove" — never "added", "fixes", "adding"
51
+ - No period at the end
52
+ - Lowercase everything except proper nouns and acronyms
53
+
54
+ Examples:
55
+ ```
56
+ feat(payments): add Stripe webhook signature verification
57
+ fix(auth): handle expired JWT refresh tokens correctly
58
+ refactor(db): replace raw queries with Drizzle ORM
59
+ perf(images): lazy-load thumbnails below the fold
60
+ ```
61
+
62
+ ### 4. Write the Body (when needed)
63
+
64
+ Include a body when the diff is non-trivial. Separate from subject with a blank line. Wrap at 72 characters. Explain *why*, not *what* — the diff already shows what.
65
+
66
+ ### 5. Add Footers
67
+
68
+ **Breaking change** (triggers major semver bump):
69
+ ```
70
+ BREAKING CHANGE: <description of what breaks and migration path>
71
+ ```
72
+
73
+ **Issue references:**
74
+ ```
75
+ Closes #42
76
+ Refs #17, #23
77
+ ```
78
+
79
+ **Co-authors:**
80
+ ```
81
+ Co-authored-by: Name <email>
82
+ ```
83
+
84
+ ### 6. Validate Before Presenting
85
+
86
+ Check:
87
+ - [ ] Subject ≤ 72 chars
88
+ - [ ] Imperative verb in subject
89
+ - [ ] `BREAKING CHANGE:` footer present if any public API removed or changed incompatibly
90
+ - [ ] Body explains motivation, not mechanics
91
+ - [ ] No trailing whitespace, no period on subject
92
+
93
+ ## Output Format
94
+
95
+ Present the final message in a fenced code block so the user can copy it directly:
96
+
97
+ ```
98
+ feat(scope): short imperative description
99
+
100
+ Longer explanation of why this change was needed. Mention
101
+ any trade-offs or alternatives considered.
102
+
103
+ BREAKING CHANGE: describe what breaks and how to migrate.
104
+ Closes #42
105
+ ```
106
+
107
+ ## Edge Cases
108
+
109
+ **Multiple unrelated changes in one diff**: Flag this. Suggest splitting with `git add -p`. Offer a message for the dominant change only, with a note listing the other concerns.
110
+
111
+ **Revert commit**: Use `revert: revert "original subject"` as subject, and include `This reverts commit <SHA>` in the body. For merge or squash commits, use `git revert -m 1 <SHA>` to revert to the mainline parent; without `-m 1`, git cannot determine which parent to revert to and will error.
112
+
113
+ **Dependency-only bump**: Use `build(deps): bump <package> from X to Y` — never `chore` for security-relevant dependency upgrades; use `fix(deps)` if it patches a CVE.
@@ -0,0 +1,161 @@
1
+ ---
2
+ name: coveragemax
3
+ description: Identifies untested code paths and generates targeted unit tests to reach 80%+ coverage using pytest-cov, Jest, Istanbul/nyc, or JaCoCo. Use when a user asks to improve test coverage, add missing tests, or analyze coverage reports.
4
+ ---
5
+
6
+ # CoverageMax
7
+
8
+ ## Overview
9
+
10
+ Analyze existing coverage reports, identify uncovered branches and lines, then generate well-structured tests using the AAA (Arrange-Act-Assert) pattern. Target: 80% line coverage and 75% branch coverage as a minimum bar.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Detect the Stack and Run Coverage
15
+
16
+ **Python (pytest-cov):**
17
+ ```bash
18
+ pytest --cov=src --cov-report=term-missing --cov-report=html:coverage_html
19
+ ```
20
+ Read the `term-missing` output — the rightmost column lists uncovered line ranges.
21
+
22
+ **JavaScript/TypeScript (Jest):**
23
+ ```bash
24
+ jest --coverage --coverageReporters=text --coverageReporters=lcov
25
+ ```
26
+ Check `coverage/lcov-report/index.html` or the terminal table.
27
+
28
+ **JavaScript (Istanbul/nyc standalone):**
29
+ ```bash
30
+ nyc --reporter=text --reporter=lcov npm test
31
+ ```
32
+
33
+ **Java (JaCoCo via Maven):**
34
+ ```bash
35
+ mvn test jacoco:report
36
+ ```
37
+ Open `target/site/jacoco/index.html`. Focus on "Missed Branches" column.
38
+
39
+ **Go:**
40
+ ```bash
41
+ go test ./... -coverprofile=coverage.out && go tool cover -html=coverage.out
42
+ ```
43
+
44
+ **Rust (cargo-tarpaulin):**
45
+ ```bash
46
+ cargo tarpaulin --out Html --output-dir coverage/
47
+ ```
48
+
49
+ **Exclusion config**: Exclude generated code, migrations, and vendor files rather than artificially inflating scores.
50
+ - Python: `pytest --cov-omit="src/migrations/*,src/generated/*"` or list paths under `[tool:coverage] omit =` in `.coveragerc`
51
+ - Jest: `coveragePathIgnorePatterns: ["/migrations/", "/generated/"]` in `jest.config.js`
52
+ - Go: tag generated files with `//go:build ignore` or pass `-coverpkg` to scope coverage explicitly
53
+
54
+ ### 2. Triage Coverage Gaps
55
+
56
+ Priority order for what to test first:
57
+ 1. **Uncovered branches** in business logic (conditionals, early returns, switch cases)
58
+ 2. **Error/exception paths** (catch blocks, null guards, validation failures)
59
+ 3. **Uncovered lines** in pure functions
60
+ 4. Skip: generated code, migrations, `__init__.py` re-exports, trivial getters/setters
61
+
62
+ Flag files with 0% coverage — these likely indicate missing test files entirely.
63
+
64
+ ### 3. Write Tests Using AAA Pattern
65
+
66
+ Every test must have three clearly separated sections:
67
+
68
+ ```python
69
+ def test_calculate_discount_applies_vip_rate():
70
+ # Arrange
71
+ user = User(tier="vip", cart_total=100.0)
72
+ pricing = PricingService(vip_rate=0.20)
73
+
74
+ # Act
75
+ result = pricing.calculate_discount(user)
76
+
77
+ # Assert
78
+ assert result == 20.0
79
+ ```
80
+
81
+ ```typescript
82
+ it('returns 401 when token is expired', async () => {
83
+ // Arrange
84
+ const expiredToken = generateToken({ exp: Date.now() - 1000 });
85
+
86
+ // Act
87
+ const response = await request(app).get('/api/profile')
88
+ .set('Authorization', `Bearer ${expiredToken}`);
89
+
90
+ // Assert
91
+ expect(response.status).toBe(401);
92
+ expect(response.body.error).toBe('TOKEN_EXPIRED');
93
+ });
94
+ ```
95
+
96
+ ### 4. Cover Branch Conditions Systematically
97
+
98
+ For each `if/else`, ternary, `||`, `&&`, or `switch`, write one test per branch:
99
+ - Truthy path
100
+ - Falsy path
101
+ - Boundary value (off-by-one, empty string, zero, null)
102
+
103
+ Use parameterized tests to reduce boilerplate:
104
+
105
+ ```python
106
+ @pytest.mark.parametrize("value,expected", [
107
+ (0, False),
108
+ (1, True),
109
+ (-1, False),
110
+ (None, False),
111
+ ])
112
+ def test_is_positive(value, expected):
113
+ assert is_positive(value) == expected
114
+ ```
115
+
116
+ ```typescript
117
+ test.each([
118
+ [0, false],
119
+ [1, true],
120
+ [-1, false],
121
+ ])('isPositive(%i) returns %s', (value, expected) => {
122
+ expect(isPositive(value)).toBe(expected);
123
+ });
124
+ ```
125
+
126
+ ### 5. Mock External Dependencies
127
+
128
+ Never let tests hit real databases, HTTP endpoints, or file systems.
129
+
130
+ **Python:** `unittest.mock.patch`, `pytest-mock`'s `mocker.patch`
131
+ **Jest:** `jest.mock()`, `jest.spyOn()`
132
+ **Java:** Mockito `@Mock` + `@InjectMocks`
133
+
134
+ ### 6. Verify Coverage Improved
135
+
136
+ Re-run the coverage command from Step 1. Confirm:
137
+ - Line coverage >= 80%
138
+ - Branch coverage >= 75%
139
+ - No previously-covered lines regressed
140
+
141
+ ## Output Format
142
+
143
+ After writing tests, provide a summary table:
144
+
145
+ ```
146
+ File Before After Δ
147
+ src/pricing.py 42% 87% +45%
148
+ src/auth/tokens.py 61% 91% +30%
149
+ ```
150
+
151
+ List any remaining uncovered branches that are intentionally excluded (dead code, platform-specific guards) with a brief justification.
152
+
153
+ ## Edge Cases
154
+
155
+ **Legacy code with no tests at all**: Start with integration/smoke tests to establish a safety net before adding unit tests. Use `pytest --cov` with `--cov-fail-under=0` initially just to generate the baseline report.
156
+
157
+ **Over-mocking warning**: High coverage achieved by mocking away all real logic is misleading — tests pass because they only verify mock behavior, not the unit under test. If every meaningful call in the function is replaced by a mock return value, the coverage number is meaningless. Mock only external boundaries (HTTP, DB, filesystem); leave business logic unmocked.
158
+
159
+ **Coverage inflation via trivial tests**: Never write tests that just call a function without asserting anything meaningful. A test that passes with `assert True` harms more than it helps — reviewers should reject it.
160
+
161
+ **Async code**: Use `pytest-asyncio` with `@pytest.mark.asyncio`, or Jest's `async/await` test bodies. Ensure all async branches (resolved, rejected, timeout) are covered.
@@ -0,0 +1,157 @@
1
+ ---
2
+ name: crongenius
3
+ description: Designs correct cron expressions, schedules background jobs with overlap prevention and retry logic, and selects the right scheduler (Celery Beat, systemd timers, EventBridge, GitHub Actions schedule). Use when a user asks about cron jobs, scheduled tasks, or background job automation.
4
+ ---
5
+
6
+ # CronGenius
7
+
8
+ ## Overview
9
+
10
+ Produce correct, timezone-aware cron schedules with overlap prevention, retry strategies, and dead-letter handling. Choose the right scheduling backend for the deployment context.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Parse the Schedule Requirement
15
+
16
+ Ask or infer:
17
+ - **Frequency**: every N minutes/hours, daily at time X, weekly on day Y
18
+ - **Timezone**: always confirm — `0 9 * * *` means different things in UTC vs America/New_York
19
+ - **DST sensitivity**: does the job need to fire at local clock time (use TZ-aware scheduler) or at a fixed UTC offset?
20
+ - **Overlap risk**: can two instances run simultaneously? Most jobs cannot.
21
+
22
+ ### 2. Write the Cron Expression
23
+
24
+ Standard 5-field syntax: `minute hour day-of-month month day-of-week`
25
+
26
+ ```
27
+ ┌─ minute (0-59)
28
+ │ ┌─ hour (0-23)
29
+ │ │ ┌─ DOM (1-31)
30
+ │ │ │ ┌─ month (1-12 or JAN-DEC)
31
+ │ │ │ │ ┌─ DOW (0-7, 0 and 7 = Sunday, or SUN-SAT)
32
+ │ │ │ │ │
33
+ * * * * *
34
+ ```
35
+
36
+ Common patterns:
37
+ ```
38
+ 0 2 * * * # daily at 02:00
39
+ */15 * * * * # every 15 minutes
40
+ 0 9 * * 1 # every Monday at 09:00
41
+ 0 0 1 * * # first of each month at midnight
42
+ 0 6 * * 1-5 # weekdays at 06:00
43
+ */5 9-17 * * 1-5 # every 5 min during business hours Mon-Fri
44
+ ```
45
+
46
+ Validate expressions at [crontab.guru](https://crontab.guru) mentally — write out "fires at X, then X+interval" to confirm.
47
+
48
+ ### 3. Prevent Overlapping Executions
49
+
50
+ **Linux cron + flock:**
51
+ ```bash
52
+ /usr/bin/flock -n /var/lock/myjob.lock /usr/local/bin/myjob.sh
53
+ ```
54
+ `-n` means "fail immediately if lock is held" — add `-w 0` for the same effect. Log when skipped.
55
+
56
+ **Celery Beat:**
57
+ ```python
58
+ CELERY_BEAT_SCHEDULE = {
59
+ 'daily-report': {
60
+ 'task': 'tasks.generate_report',
61
+ 'schedule': crontab(hour=2, minute=0),
62
+ 'options': {'expires': 3600}, # drop if not consumed in 1h
63
+ },
64
+ }
65
+ ```
66
+ Use `celery-redbeat` (Redis-backed) for distributed deployments to avoid duplicate firing across multiple Beat instances.
67
+
68
+ **systemd timer (preferred over cron on modern Linux):**
69
+ ```ini
70
+ # /etc/systemd/system/myjob.timer
71
+ [Timer]
72
+ OnCalendar=*-*-* 02:00:00
73
+ Persistent=true
74
+ Unit=myjob.service
75
+
76
+ # /etc/systemd/system/myjob.service
77
+ [Service]
78
+ Type=oneshot
79
+ ExecStart=/usr/local/bin/myjob.sh
80
+ ```
81
+ `systemctl enable --now myjob.timer`. systemd prevents overlap natively for `Type=oneshot`.
82
+
83
+ **AWS EventBridge (serverless):**
84
+ ```
85
+ rate(1 hour)
86
+ # or cron-style:
87
+ cron(0 2 * * ? *) # Note: EventBridge uses 6 fields, year is 7th optional
88
+ ```
89
+ Pair with SQS + Lambda for retry semantics.
90
+
91
+ ### 4. Add Retry and Dead-Letter Logic
92
+
93
+ Never let silent failures go undetected.
94
+
95
+ **Celery:**
96
+ ```python
97
+ @app.task(bind=True, max_retries=3, default_retry_delay=300)
98
+ def my_task(self):
99
+ try:
100
+ do_work()
101
+ except TransientError as exc:
102
+ raise self.retry(exc=exc, countdown=2 ** self.request.retries * 60)
103
+ ```
104
+ Configure a dead-letter queue (DLQ):
105
+ ```python
106
+ task_reject_on_worker_lost = True
107
+ task_acks_late = True
108
+ ```
109
+
110
+ **GitHub Actions schedule (CI-hosted jobs):**
111
+ ```yaml
112
+ on:
113
+ schedule:
114
+ - cron: '0 2 * * *'
115
+ ```
116
+ Add `timeout-minutes: 30` and `continue-on-error: false` to fail visibly.
117
+
118
+ **GitHub Actions inactivity warning**: GitHub automatically disables scheduled workflows on public repos after 60 days of no repository activity (no pushes, PRs, etc.). Add a periodic commit or use the GitHub API to re-enable the workflow. Monitor via the Actions UI or set a calendar reminder for long-running scheduled workflows.
119
+
120
+ **Celery Beat rolling deploy**: During a rolling deploy, multiple Beat instances may run briefly in parallel, causing duplicate task fires. Prevent this by using `celery-redbeat` (Redis-backed distributed lock) so only one Beat instance holds the scheduler lock at a time. Do not run more than one Beat process per environment without a distributed lock backend.
121
+
122
+ ### 5. Handle Timezones Correctly
123
+
124
+ - Always store and compute in UTC internally.
125
+ - Use TZ-aware schedulers for local-time jobs:
126
+ - Celery Beat: `timezone = 'America/New_York'` in config
127
+ - systemd: `OnCalendar=America/New_York *-*-* 09:00:00`
128
+ - EventBridge: no native TZ — compute UTC offset and adjust for DST manually, or use a Lambda to re-schedule
129
+
130
+ ### 6. Document the Schedule
131
+
132
+ For every scheduled job, record:
133
+ ```
134
+ Job: generate-monthly-invoices
135
+ Schedule: 0 1 1 * * (first of month, 01:00 UTC)
136
+ Timezone: UTC
137
+ Max runtime: 30 minutes
138
+ Overlap prevention: flock /var/lock/invoices.lock
139
+ On failure: PagerDuty alert + DLQ
140
+ Owner: billing-team
141
+ ```
142
+
143
+ ## Output Format
144
+
145
+ Provide:
146
+ 1. The cron expression with an English plain-language description
147
+ 2. The platform-specific scheduler config block
148
+ 3. The overlap prevention mechanism
149
+ 4. The retry/failure handling approach
150
+
151
+ ## Edge Cases
152
+
153
+ **DST clock changes**: A job at `0 2 * * *` America/New_York will fire at 01:00 or 03:00 UTC depending on DST. If exact local time matters, use a TZ-aware scheduler. If the job must always fire at a fixed UTC time, document the apparent local time shift.
154
+
155
+ **Month-end edge cases**: `0 0 31 * *` silently skips months with fewer than 31 days. Use `0 0 28-31 * *` + an idempotency check in the job, or use a scheduler that supports `last day of month` (EventBridge supports `L`).
156
+
157
+ **Catching up missed runs**: systemd `Persistent=true` replays missed runs after downtime. Celery Beat does not replay by default. Add idempotency keys to jobs that must not double-execute on catch-up.