Code patterns for AI-assisted development. Full rules: [AGENTS.md](AGENTS.md) · Planning contract: [docs/adr/0000-purpose-to-software-compiler.md](docs/adr/0000-purpose-to-software-compiler.md)
---
## Quick Index
Agent-facing docs are for model consumption first: terse, structured, low-ceremony. Compress wording, not semantics — never remove purpose, value, consumer, consequence, invariants, or action thresholds to save tokens.
| Section | Description |
|---------|-------------|
| [1. Purpose Doctrine](#1-purpose-doctrine) | The #1 rule: every symbol must answer why it exists |
| `throw new Error(...)` bare in business logic | Callers can't distinguish failure classes | Throw with a descriptive prefix: `throw new Error("session-recorder.initSessionRecorder: db unavailable")` | **STY001** |
| Silent `catch` swallowing | Hides breakage | `logWarning(module, msg)` then decide: re-throw or return explicit failure | **STY002** |
| Magic status strings inline | Spreads typo-prone comparisons | Named constant or exported string literal at definition site | **STY003** |
| Generic names: `utils`, `helpers`, `common`, `misc` | Unsearchable, no domain signal | Name by capability: `memory-source-store.js`, `embed-circuit.js` | **STY004** |
| `// TODO: fix later` without ticket / owner | Permanent invisible debt | Fix now, or add a dated `// TODO(owner): <why>` with `node scripts/tech-debt-scan.mjs` visibility | **STY005** |
| Embedding logic in hook wiring | Blurs responsibilities; untestable | Extract to a purpose-named module; wire only the call in `register-hooks.js` | **STY007** |
| Docstring = "Helper." or no docstring | Purpose is invisible to RAG and reviewers | Full JSDoc with Purpose + Consumer (§ 1) | **STY008** |
| Bare `process.env.FOO` scattered in logic | Config not auditable or testable | Named constant + `loadXxxConfigFromEnv()` function with null-guard | **STY009** |
| Test name = `"test X"` / `"works"` | Not a contract claim | `what_when_expected` form: `claimUnit_whenLeaseExpired_returnsTrue` | **STY010** |
| Mechanical test (counts mocks, not behavior) | Breaks on refactors that don't change behavior | Test what the *consumer receives*; label implementation guards `// guard:` | **STY011** |
| Committing to `dist/` or `~/.sf/agent/` | Generated output, not source | `dist/` is gitignored build output; run `npm run copy-resources` to rebuild | **STY012** |
---
## 4. Thresholds
Two-tier: **Warn** = flag in review; **Error** = blocks merge.
| Metric | Warn | Error |
|--------|------|-------|
| Function lines | 50 | 75 |
| File lines | 800 | 1500 |
| Function arguments | 5 | 8 |
| Nesting depth | 4 | 6 |
| Dead code | 0 tolerance | — |
| `TODO`/`FIXME` count | per `tech-debt-scan.mjs` thresholds | — |
Infrastructure files (`sf-db.js`, generated schemas) may exceed file-line limits when extraction would harm clarity. Add a comment explaining why.
`src/resources/extensions/sf/sf-db/` is the only module family that prepares and executes write SQL. The public surface remains `sf-db.js`; all other modules call exported wrappers. This makes the write surface auditable, testable, and migration-safe while allowing the DB implementation to stay split by domain.
const stmt = db.prepare("INSERT INTO sessions ...");
```
### Config from env
Always read env vars through a named `loadXxxConfigFromEnv()` function that returns `null` when required keys are absent (opt-in) or throws with a clear message (required).
```js
export function loadGatewayConfigFromEnv() {
const keyEntry = firstEnvEntry(KEY_ALIASES);
if (!keyEntry) return null; // opt-in: absent = no-op
1.**Behaviour contracts** — what the consumer receives. Primary. Spec.
2.**Degradation contracts** — what happens when dependencies fail (DB down, gateway unreachable).
3.**Implementation guards** — labelled `// guard:` — protect specific failure modes. Refactors may update these.
---
## 7. Documentation
### When to comment
- **Always**: exported symbols with non-trivial behavior (full JSDoc per § 1)
- **Rarely**: inline comments only when the *why* is genuinely non-obvious from reading the code
- **Never**: comments that restate what the code does; comments as TODO parking
### Keeping docs current
When you change behavior, update the JSDoc Purpose and Consumer in the same commit. A stale Purpose is worse than no Purpose — it actively misleads the next reader.
### Module headers
```js
// module-name.js — one-line description
//
// Purpose: why this module exists as a separable unit.
//
// Consumer: who imports this at runtime (or "internal" if only tests).
```
---
## See Also
- [AGENTS.md](AGENTS.md) — planning conventions, spec-first TDD, test naming