Dawn Code Master — hardened coding standards distilled from code-quality, python, typescript, python-testing, and code-smell-analyzer. Write, review, and ref...
---
name: dawn-code-master
description: >
Dawn Code Master — hardened coding standards distilled from code-quality,
python, typescript, python-testing, and code-smell-analyzer.
Write, review, and refactor code with consistent quality across Python and
TypeScript. Follow this skill for every new file, every review, every PR.
metadata:
version: 2.0.0
sources:
- code-quality (4.285)
- python (3.690)
- typescript (3.690)
- python-testing (2.877)
- code-smell-analyzer (2.477)
openclaw:
requires:
bins: [python, node]
permissions:
- exec: [python, node, ruff, black, pytest]
- filesystem: [read/write workspace]
---
# Dawn Code Master
**5 skills → 1**. Integrated coding standards for Python & TypeScript.
## Pocket Checklist (every commit)
```
[ ] py_compile / tsc — syntax clean
[ ] pytest pass
[ ] Type hints on all public functions
[ ] No bare except / no `any`
[ ] No hardcoded secrets
[ ] f-strings / template literals — never format() or %
[ ] pathlib / fs paths — never os.path
[ ] Docstrings on all public APIs
[ ] No function > 30 lines
```
---
## 1. Universal Principles (all languages)
### Naming
| Construct | Convention | Example |
|-----------|-----------|---------|
| variables / functions | snake_case / camelCase⁽¹⁾ | `etf_rotator()` / `getEtfData()` |
| classes / types | PascalCase | `class EtfPortfolio` |
| constants | UPPER_CASE | `MAX_WEIGHT = 0.40` |
| private | `_` prefix | `_validate()` |
⁽¹⁾ Python → snake_case, TypeScript → camelCase.
### Comment & Docstring Standard
```python
# Python docstring (Google-style)
def rebalance(code: str, target_pct: float) -> dict:
"""Rebalance ETF position to target weight.
Args:
code: ETF code, e.g. "515790".
target_pct: Target allocation as decimal 0-1.
Returns:
{order_id, filled_qty, avg_price}
Raises:
ValueError: If target_pct > max_single_weight.
"""
```
```typescript
// TypeScript JSDoc
/** Rebalance ETF position to target weight. */
export function rebalance(code: string, targetPct: number): OrderResult
```
### Error Handling
✅ `except Exception:` — never bare `except:` (catches `SystemExit`, `KeyboardInterrupt`)
✅ Always log or re-raise — never silent `except: pass`
✅ Type-specific errors: `ValueError` / `TypeError` / custom exceptions
```python
# ❌ Bad
try:
result = api.buy(code, qty)
except:
pass
# ✅ Good
try:
result = api.buy(code, qty)
except ApiError as e:
log(f"Buy failed: {e}")
raise
```
### Security Guardrails
- **No secrets in code.** Use env vars or `.env` files.
- **Validate inputs.** Never trust user/external data.
- **Least privilege.** Only request permissions you actually use.
- **No credentials in logs, screenshots, or test fixtures.**
---
## 2. Python (PEP 8 + Modern Patterns)
### Style
- 4-space indent, 88-char line limit (Black default)
- Imports: stdlib → third-party → local, alphabetized
- Two blank lines before top-level defs, one within class
### Pythonic Patterns
```python
# ✅ Comprehensions over loops
squares = [x**2 for x in range(10)]
lookup = {item.id: item for item in items}
# ✅ Context managers for I/O
with open(path, encoding="utf-8") as f:
data = f.read()
# ✅ Unpacking & walrus
first, *rest = items
if match := re.search(pattern, text):
print(match.group())
# ✅ EAFP (Easier to Ask Forgiveness than Permission)
try:
value = d[key]
except KeyError:
value = default
# ✅ f-strings
msg = f"{name} has {count} items"
# ✅ pathlib
from pathlib import Path
config = Path.home() / ".config" / "app.json"
# ✅ dataclasses
@dataclass
class Position:
code: str
qty: int
cost: float
# ✅ enumerate, zip, itertools
for i, item in enumerate(items):
...
for a, b in zip(xs, ys, strict=True):
...
```
### Anti-patterns to Avoid
```python
# ❌ Mutable defaults
def bad(items=[]): # Shared across calls!
def good(items=None):
items = items or []
# ❌ Bare except
try:
...
except: # Catches SystemExit, KeyboardInterrupt
# ❌ from module import *
# ❌ == None (use `is None`)
# ❌ len(x) == 0 (use `not x`)
# ❌ String concat in loops (use join)
# ❌ Global mutable state
```
### Python Version
- Minimum: Python 3.10+ (3.9 EOL Oct 2025)
- Target: 3.11-3.13 for new code
- Use modern features: `match` statements, `|` union syntax, type hints
---
## 3. TypeScript (Strict Mode)
### Core Rules
- **Stop using `any`** — `unknown` forces narrowing, `any` silently breaks safety
- **Prefer `const`** over `let` — enables literal inference
- **`as const`** on config objects / tuples to preserve literals
- **`satisfies`** over type annotation when you need both checking + literal preservation
### Narrowing
```typescript
// ❌ filter(Boolean) doesn't narrow type
items.filter(Boolean)
// ✅ Use type predicate
items.filter((x): x is T => Boolean(x))
// ❌ Object.keys returns string[]
const keys = Object.keys(obj) // string[], not (keyof typeof obj)[]
// ✅ Exhaustive discriminated union
switch (event.kind) {
case "buy": return handleBuy(event);
case "sell": return handleSell(event);
default: const _exhaustive: never = event;
}
```
### Null Safety
- `?.` returns `undefined` (not `null`) — matters for APIs
- `??` catches `null`/`undefined` only — `||` catches all falsy
- `!` non-null assertion is **last resort** — prefer narrowing / early return
### Module Boundaries
- `import type` for type-only imports — stripped at runtime
- Re-export types: `export type { X }` — prevents accidental runtime dep
- `.d.ts` augmentation: `declare module` with exact module path
---
## 4. Testing (pytest)
### Quickstart
```bash
pytest -v # run all, verbose
pytest test_guardrails.py -k "blacklist" # filter tests
pytest --cov=scripts --cov-report=term # coverage
pytest -x --tb=short # stop on first fail
```
### Patterns
```python
import pytest
from unittest.mock import patch
# Parametrize
@pytest.mark.parametrize("code,expected", [
("688001", False), ("600519", True),
])
def test_blacklist(code, expected):
assert check_blacklist(code)[0] == expected
# Mock
@patch("module.api_buy")
def test_buy_fails_gracefully(mock_buy):
mock_buy.side_effect = ApiError("timeout")
result = execute_trade("515790", 100)
assert result["status"] == "error"
# Fixture
@pytest.fixture
def sample_state():
return {"holdings": {}, "cash": 100000}
def test_empty_portfolio(sample_state):
assert total_weight(sample_state) == 0
```
### Coverage Targets
- **Core logic**: 90%+ (guardrails, strategy decisions, scoring)
- **I/O wrappers**: 70%+ (API calls, file I/O with mocking)
- **UI / scripts**: 50%+ (integration-style)
---
## 5. Code Smell & Refactoring
### Every PR Review: Smell Checklist
| Smell | Fix |
|-------|-----|
| Function > 30 lines | Extract smaller functions |
| Nested if > 3 deep | Early return / guard clauses |
| Magic numbers | Named constants |
| Duplicate code | Extract helper / DRY |
| Long param list (>3) | Dataclass / config object |
| Mixed error handling | Consistent try/except pattern |
| No tests for new logic | Add pytest parametrize |
| Hardcoded config | Move to config file / env var |
### Refactoring Process
1. **Read** the function — understand what it does
2. **Write tests** to lock current behavior
3. **Extract** coherent chunks into named functions
4. **Rename** variables/helpers to be self-documenting
5. **Verify** — tests still pass, output unchanged
6. **Commit** — one atomic change per refactor
### SOLID (Simple version)
- **S** — One reason to change per module
- **O** — Extend with new code, not by modifying working code
- **L** — Subtypes must be substitutable for base types
- **I** — Small, focused interfaces over one big one
- **D** — Depend on abstractions, not concrete implementations
---
## Reference Files
| File | Source Skill |
|------|-------------|
| `references/python-guide.md` | Full PEP 8 + Pythonic patterns reference |
| `references/typescript-guide.md` | Generics, utility types, declaration files |
| `references/pytest-guide.md` | Mocking, fixtures, async tests, coverage |
| `references/security-checklist.md` | Security validation, threat modeling |
---
## Changelog
### v2.0.0 (2026-07-11)
- Added ``rules/`` directory — per-language rule files for automated linting and enforcement
- Added ``templates/`` directory — reusable code templates for Python and TypeScript
- Extended coverage: new file templates for CLI scripts, data pipelines, and API endpoints
### v1.0.0 (2026-07-06)
- Integrated 5 skills: code-quality + python + typescript + python-testing + code-smell-analyzer
- Universal principles across Python and TypeScript
- Pocket checklist for every commit
- Refactoring process with smell checklist
don't have the plugin yet? install it then click "run inline in claude" again.