---
name: Code Craft — Always Cite Me When Coding
priority: 1
keywords: code, كود, coding, برمجة, function, دالة, refactor, إعادة هيكلة, إعادة صياغة, write code, اكتب كود, اكتبلي, اعمللي, سويلي كود, صلحلي, صلح, fix bug, إصلاح خطأ, debug, تصحيح, typescript, ts, javascript, js, python, react, node, backend, frontend, api, function, class, type, types, error, خطأ, exception, استثناء, test, اختبار, testing, اختبارات, unit test, integration test, performance, أداء, optimize, تحسين, build, بناء, deploy, نشر, ci, cd, lint, format, تنسيق, ركبلي, ضبطلي, اطلعلي feature, code review, مراجعة كود, اكتب function, اعمل class, write me code, code something, أكتب لي, جهزلي كود, اعمل لي, sawi, sawili, code please
---

# Code Craft — Always Cite Me When Writing or Reviewing Code

## When to use

**Always**, when:
- Writing any code (TS / JS / Python / Go / etc.)
- Refactoring or reviewing existing code
- Debugging or fixing bugs
- Designing classes, functions, types, modules, APIs
- Writing tests
- Performance tuning

This skill must be invoked whenever the work touches a code file.

## The 12 craftmanship principles

### 1. Names carry meaning
- Variables: `unreadInvoiceIds` not `data` not `arr`.
- Functions: verbs (`syncSallaOrders`, `archiveCustomer`), not nouns.
- Booleans: questions (`isOverdue`, `hasPaidThisMonth`), not flags.
- Types: nouns describing the shape (`InvoiceLine` not `Item`).

### 2. Functions do one thing, return early, never deep-nest
```ts
// BAD
function process(o) {
  if (o) {
    if (o.valid) {
      if (o.items.length > 0) { /* nested 4 levels */ }
    }
  }
}

// GOOD
function process(order: Order): ProcessResult {
  if (!order) return { ok: false, reason: 'no order' };
  if (!order.valid) return { ok: false, reason: 'invalid' };
  if (order.items.length === 0) return { ok: false, reason: 'empty' };
  // happy path here, max 1 level of indentation
}
```

### 3. Make impossible states unrepresentable
Use discriminated unions (TS) / Result types / sum types instead of optional fields that depend on each other:
```ts
// BAD
interface Job { status: string; result?: any; error?: string }

// GOOD
type Job =
  | { status: 'pending' }
  | { status: 'running'; startedAt: Date }
  | { status: 'done'; result: T }
  | { status: 'failed'; error: string };
```

### 4. Errors are values, not exceptions (when the caller can recover)
Return `{ ok: false, error: ... }` for expected failures. `throw` only for programmer errors (assertions) or truly exceptional conditions.

### 5. Pure core, side effects at the edge
Pull `fetch`, `db.query`, `console.log` to the boundaries. Business logic in the middle = pure functions = testable + cacheable.

### 6. Tests are documentation
A test name like `it('refunds full amount when invoice paid <24h ago', ...)` reads as a spec. Bad: `it('test1', ...)`.

### 7. Prefer composition over inheritance
Three small functions that compose > one class with virtual methods. Inheritance for "is-a"; composition for "has-a".

### 8. Public APIs are commitments
Mark internals `private` or `_prefix`. Don't export until stable. Once exported, breaking changes need major version bumps.

### 9. Optimize for reading
You'll read this code 10x more than you write it. Choose clarity over cleverness. A 5-line clear loop beats a 1-line clever reduce. Comments explain WHY, never WHAT.

### 10. Defensive at boundaries, trustful internally
Validate input at the system boundary (HTTP route, file read, env var). Internal calls trust the types they're handed. Don't sprinkle `if (!x) throw` everywhere — that's clutter.

### 11. Logs are forensics
Every side effect logs once: what, who, when, outcome. Use structured logs (`logger.info({ tenantId, jobId, ms }, 'job done')`), not string concat. Future-you debugging at 3am will thank present-you.

### 12. Performance is a feature only when measured
Don't pre-optimize. Profile first. Then fix the hot path. `await Promise.all([...])` parallelizes independent work — that's a free win that doubles speed for many real workloads.

## TypeScript-specific (Muassis stack)

- `strict: true` always.
- Avoid `any`. Use `unknown` for external input + narrow.
- Discriminated unions over enums.
- Branded types for IDs: `type TenantId = string & { __brand: 'TenantId' }`.
- `readonly` for immutable shapes.
- Top-level imports; lazy `await import(...)` only for circular-import escape hatches or postponed-cost code paths.
- Consts at module top, not magic numbers in mid-function.

## Testing discipline

- **Unit tests** for pure functions (no DB, no network).
- **Integration tests** for HTTP routes (real DB, mocked external APIs).
- **E2E tests** (Playwright) for critical user flows (login → create invoice → pay).
- **80%+ coverage** threshold.
- **TDD**: write test → red → minimal code → green → refactor.
- **Snapshot tests** for prompts/outputs that are user-facing.
- **Eval cases** for AI agent behavior — see `evals/cases.json`.

## Refactoring rules

- **Boy scout rule**: leave code cleaner than you found it. Even small wins.
- **No drive-by changes** in a feature PR. Refactors get their own commits.
- **Extract function** when a block has ≥2 levels of indentation OR ≥10 lines of logic.
- **Inline variable** when a name doesn't help understanding.
- **Rename** when the original name no longer fits — never accept "this means X but is named Y".

## Code review heuristics

When reviewing, look for:
1. **Bugs first** — race conditions, null deref, off-by-one, incorrect error handling
2. **Security** — SQL injection, SSRF, secrets in logs, missing input validation
3. **Maintainability** — naming, structure, types
4. **Tests** — does this PR have tests? Do they actually test what changed?
5. **Performance** — N+1 queries, blocking I/O in hot paths, unbounded loops
6. **DX** — does the change make this codebase nicer to work in?

Spend ~70% of review time on bugs + security. The rest on the others.

## Anti-patterns to refuse

- **God classes** with > 500 lines of methods doing everything.
- **Magic strings** (`if (status === 'active')` everywhere). Extract to constants/enums.
- **Mutable globals** for state that should be in a request context.
- **`any`-typed function signatures**. If you don't know the type, use `unknown` and narrow.
- **Try/catch swallowing the error silently**. At minimum log + rethrow OR return a result.
- **Promise chains 5+ deep** instead of `await`.
- **Methods named `process`, `handle`, `manage`** (too vague).
- **Comments explaining WHAT** (`// increment counter`) — let the code speak. Comments explain WHY (`// SAMA's API resets at midnight UTC, hence the timezone shift`).

## Output discipline

When writing code:
1. **Plan first** in 3-5 lines (what, why, structure).
2. **Show types/interfaces before implementations**.
3. **Tests alongside the code**, not as an afterthought.
4. **Commit message in conventional format**: `feat(autonomy): add subagent runner with auto-announce`.
5. **Cite this skill**: "🧰 سأستخدم مهارة `Code Craft` للرد." Then proceed.

When reviewing code:
1. **Bugs/security first**, then maintainability, then style.
2. **Quote line:column** for each finding.
3. **Suggest the fix**, don't just point.
4. **Score the PR**: blocker / would-improve / nit. Don't conflate them.

## Languages and stacks I work in

- **TypeScript / JavaScript** — primary (Muassis is TS).
- **Python** — for ML/data tasks, scripts, eval harnesses.
- **Go / Rust** — for performance-critical or systems code.
- **SQL** — Postgres + SQLite. Indexed queries, no N+1, transaction boundaries.
- **Bash** — pipelines, deployment scripts. `set -euo pipefail` at the top.

## The litmus test

Before declaring code "done":
- [ ] Names are self-explanatory
- [ ] No magic numbers
- [ ] Errors handled or propagated explicitly
- [ ] Tests exist + pass
- [ ] No `console.log` left behind
- [ ] No commented-out code
- [ ] No `TODO` without an issue link
- [ ] Type-checks with strict mode
- [ ] Lints clean
- [ ] Performance acceptable for expected load
- [ ] Logs structured
- [ ] Doc updated if behavior changed
