File size: 7,308 Bytes
59ce7b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# Code Style Guide

> **Last Updated**: 2025-12-06

This guide covers code style conventions and tooling for DeepBoner.

## Quick Reference

```bash
# Auto-format code
make format

# Check linting
make lint

# Type check
make typecheck

# Run all checks
make check
```

## Tooling

### Ruff (Linting & Formatting)

Configuration in `pyproject.toml`:

```toml
[tool.ruff]
line-length = 100
target-version = "py311"
src = ["src", "tests"]

[tool.ruff.lint]
select = [
    "E",    # pycodestyle errors
    "F",    # pyflakes
    "B",    # flake8-bugbear
    "I",    # isort
    "N",    # pep8-naming
    "UP",   # pyupgrade
    "PL",   # pylint
    "RUF",  # ruff-specific
]
```

### MyPy (Type Checking)

Configuration in `pyproject.toml`:

```toml
[tool.mypy]
python_version = "3.11"
strict = true
ignore_missing_imports = true
disallow_untyped_defs = true
warn_return_any = true
```

### Pre-commit Hooks

Hooks run automatically on commit:

```yaml
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    hooks:
      - id: ruff
      - id: ruff-format
  - repo: https://github.com/pre-commit/mirrors-mypy
    hooks:
      - id: mypy
```

## Python Style

### Type Hints

All functions must have type annotations:

```python
# Good
def search(query: str, limit: int = 10) -> list[Evidence]:
    """Search for evidence."""
    pass

# Bad
def search(query, limit=10):
    pass
```

Use modern type hint syntax (Python 3.11+):

```python
# Good
def process(items: list[str] | None) -> dict[str, int]:
    pass

# Avoid (old syntax)
from typing import List, Dict, Optional
def process(items: Optional[List[str]]) -> Dict[str, int]:
    pass
```

### Docstrings

Use Google-style docstrings for public APIs:

```python
def search_pubmed(query: str, max_results: int = 10) -> SearchResult:
    """Search PubMed for biomedical literature.

    Args:
        query: The search query string.
        max_results: Maximum number of results to return.

    Returns:
        SearchResult containing evidence and metadata.

    Raises:
        SearchError: If the API call fails.
        RateLimitError: If rate limit is exceeded.
    """
    pass
```

### Class Documentation

```python
class SearchHandler:
    """Orchestrates parallel searches across multiple sources.

    This handler implements a scatter-gather pattern to query
    multiple biomedical databases simultaneously.

    Attributes:
        sources: List of enabled search sources.
        timeout: Timeout for each search in seconds.

    Example:
        handler = SearchHandler()
        result = handler.search_all("testosterone therapy")
    """

    def __init__(self, sources: list[str] | None = None) -> None:
        """Initialize the search handler.

        Args:
            sources: Optional list of sources to enable.
                    Defaults to all sources.
        """
        pass
```

### Imports

Imports are sorted by isort (via ruff):

```python
# Standard library
import asyncio
from datetime import datetime
from typing import Any

# Third-party
import httpx
from pydantic import BaseModel

# Local
from src.utils.config import settings
from src.utils.exceptions import SearchError
```

### Line Length

Maximum 100 characters. Break long lines:

```python
# Good - break at logical points
result = very_long_function_name(
    first_argument=value1,
    second_argument=value2,
    third_argument=value3,
)

# Good - string continuation
message = (
    "This is a very long message that needs to be "
    "split across multiple lines for readability."
)
```

### Naming Conventions

| Type | Convention | Example |
|------|------------|---------|
| Classes | PascalCase | `SearchHandler` |
| Functions | snake_case | `search_pubmed` |
| Variables | snake_case | `max_results` |
| Constants | UPPER_SNAKE | `MAX_ITERATIONS` |
| Private | leading underscore | `_internal_method` |
| Type vars | PascalCase | `T`, `ConfigT` |

### Exceptions

Custom exceptions in `src/utils/exceptions.py`:

```python
from src.utils.exceptions import SearchError

# Raising
raise SearchError(f"API returned {status_code}")

# With cause
try:
    response = client.get(url)
except httpx.HTTPError as e:
    raise SearchError(f"Request failed: {e}") from e
```

## Pydantic Models

### Model Definition

```python
from pydantic import BaseModel, Field

class Evidence(BaseModel):
    """A piece of evidence from search."""

    content: str = Field(min_length=1, description="The evidence text")
    relevance: float = Field(ge=0.0, le=1.0, default=0.0)
    metadata: dict[str, Any] = Field(default_factory=dict)

    model_config = {"frozen": True}  # Make immutable
```

### Settings

```python
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    """Application settings from environment."""

    model_config = SettingsConfigDict(
        env_file=".env",
        case_sensitive=False,
    )

    max_iterations: int = Field(default=10, ge=1, le=50)
```

## Async Code

### Async Functions

```python
async def search_async(query: str) -> SearchResult:
    """Async search implementation."""
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        return parse_response(response)
```

### Concurrent Execution

```python
async def search_all(query: str) -> list[SearchResult]:
    """Search all sources concurrently."""
    tasks = [
        search_pubmed(query),
        search_clinicaltrials(query),
        search_europepmc(query),
    ]
    return await asyncio.gather(*tasks, return_exceptions=True)
```

## Comments

### When to Comment

```python
# Good: Explain WHY, not WHAT
# PubMed rate limits without API key - add delay to avoid 429
await asyncio.sleep(0.34)

# Bad: Obvious comment
# Increment counter
counter += 1
```

### TODO Comments

```python
# TODO(username): Description of what needs to be done
# TODO: Short-term fix, proper solution needs X
```

## Ignored Rules

Some rules are disabled for good reasons:

```toml
ignore = [
    "PLR0913",  # Too many arguments (agents need many params)
    "PLR0912",  # Too many branches (complex orchestrator logic)
    "PLR2004",  # Magic values (statistical constants)
    "PLW0603",  # Global statement (singleton pattern)
    "PLC0415",  # Lazy imports for optional dependencies
]
```

## File Organization

### Module Structure

```python
"""Module docstring explaining purpose."""

# Imports (sorted)
import ...

# Constants
MAX_RESULTS = 100

# Type definitions
ResultType = dict[str, Any]

# Classes
class MyClass:
    pass

# Functions
def my_function():
    pass

# Module-level code (minimize)
if __name__ == "__main__":
    main()
```

### Package Structure

```
src/tools/
β”œβ”€β”€ __init__.py    # Public exports
β”œβ”€β”€ base.py        # Base classes
β”œβ”€β”€ pubmed.py      # PubMed implementation
β”œβ”€β”€ clinicaltrials.py
└── search_handler.py
```

## Code Review Checklist

Before submitting a PR:

- [ ] All functions have type hints
- [ ] Public APIs have docstrings
- [ ] `make check` passes
- [ ] No hardcoded credentials
- [ ] Error cases are handled
- [ ] Tests cover new code

---

## Related Documentation

- [Testing Guide](testing.md)
- [Contributing Guide](../../CONTRIBUTING.md)
- [Architecture Overview](../architecture/overview.md)