@skathio/somi 1.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 (84) hide show
  1. package/.claude/settings.json +108 -0
  2. package/.claude/settings.local.json +9 -0
  3. package/.claude/somi-state/last-context-signature +1 -0
  4. package/.claude-plugin/marketplace.json +21 -0
  5. package/.claude-plugin/plugin.json +24 -0
  6. package/.copilot-extension/extension.json +51 -0
  7. package/.copilot-extension/marketplace.json +19 -0
  8. package/LICENSE +21 -0
  9. package/README.md +209 -0
  10. package/VERSION +1 -0
  11. package/agents/architecture-reviewer.md +86 -0
  12. package/agents/coder.md +222 -0
  13. package/agents/discovery-analyst.md +305 -0
  14. package/agents/planner.md +256 -0
  15. package/agents/refactorer.md +72 -0
  16. package/agents/reviewer.md +233 -0
  17. package/agents/security-reviewer.md +85 -0
  18. package/agents/test-strategist.md +74 -0
  19. package/commands/architecture-review.md +92 -0
  20. package/commands/code-loop.md +142 -0
  21. package/commands/code-parallel.md +155 -0
  22. package/commands/code.md +138 -0
  23. package/commands/discover.md +175 -0
  24. package/commands/plan-loop.md +124 -0
  25. package/commands/plan.md +174 -0
  26. package/commands/refactor.md +44 -0
  27. package/commands/review-panel.md +123 -0
  28. package/commands/review.md +149 -0
  29. package/commands/security-review.md +73 -0
  30. package/commands/ship-loop.md +135 -0
  31. package/commands/ship.md +108 -0
  32. package/commands/test-strategy.md +82 -0
  33. package/examples/README.md +19 -0
  34. package/examples/code-review-example.md +88 -0
  35. package/examples/discovery-example.md +200 -0
  36. package/examples/feature-plan-example.md +377 -0
  37. package/examples/full-pipeline-example.md +188 -0
  38. package/examples/sample-consumer/.claude/settings.json +29 -0
  39. package/examples/sample-consumer/CLAUDE.md +41 -0
  40. package/examples/sample-consumer/README.md +77 -0
  41. package/hooks/hooks.json +64 -0
  42. package/hooks/lib/common.sh +120 -0
  43. package/hooks/post-tool/audit-log.sh +40 -0
  44. package/hooks/post-tool/lint-changed-files.sh +80 -0
  45. package/hooks/pre-tool/block-dangerous-bash.sh +83 -0
  46. package/hooks/pre-tool/block-secret-writes.sh +83 -0
  47. package/hooks/pre-tool/gate-dep-install.sh +72 -0
  48. package/hooks/pre-tool/guard-protected-paths.sh +74 -0
  49. package/hooks/user-prompt-submit/inject-workflow-context.sh +143 -0
  50. package/package.json +51 -0
  51. package/rules/00-priorities.md +48 -0
  52. package/rules/10-solid.md +87 -0
  53. package/rules/20-clean-code.md +62 -0
  54. package/rules/30-security-owasp.md +83 -0
  55. package/rules/40-engineering-practices.md +65 -0
  56. package/rules/50-collaboration.md +108 -0
  57. package/rules/99-overrides.md +52 -0
  58. package/rules/CLAUDE.md +164 -0
  59. package/skills/api-design/SKILL.md +147 -0
  60. package/skills/clean-code/SKILL.md +142 -0
  61. package/skills/market-research/SKILL.md +125 -0
  62. package/skills/observability/SKILL.md +133 -0
  63. package/skills/owasp-defense/SKILL.md +141 -0
  64. package/skills/requirements-engineering/SKILL.md +137 -0
  65. package/skills/solid-principles/SKILL.md +143 -0
  66. package/skills/test-strategy/SKILL.md +133 -0
  67. package/skills/threat-modeling/SKILL.md +117 -0
  68. package/templates/ADR.md.tmpl +73 -0
  69. package/templates/BRD.md.tmpl +68 -0
  70. package/templates/CONTEXT.md.tmpl +74 -0
  71. package/templates/DECISIONS.md.tmpl +104 -0
  72. package/templates/DIARY.md.tmpl +65 -0
  73. package/templates/DOD.md.tmpl +66 -0
  74. package/templates/FRD.md.tmpl +64 -0
  75. package/templates/PHASE.md.tmpl +80 -0
  76. package/templates/PROGRESS.md.tmpl +76 -0
  77. package/templates/RD-README.md.tmpl +70 -0
  78. package/templates/RESEARCH.md.tmpl +96 -0
  79. package/templates/REVIEW.md.tmpl +81 -0
  80. package/templates/SDD.md.tmpl +82 -0
  81. package/templates/SOMI-README.md.tmpl +66 -0
  82. package/templates/SPEC.md.tmpl +123 -0
  83. package/templates/SRS.md.tmpl +85 -0
  84. package/templates/TDD.md.tmpl +77 -0
@@ -0,0 +1,141 @@
1
+ ---
2
+ name: owasp-defense
3
+ description: Use when the work touches authentication, authorization, cryptography, secret handling, input validation, deserialization, file uploads, template rendering, outbound HTTP triggered by user input, or any sensitive sink. Provides concrete defenses for the OWASP Top 10 mapped to actionable code-level checks.
4
+ ---
5
+
6
+ # OWASP defense — practical checks
7
+
8
+ The defenses are in [`rules/30-security-owasp.md`](../../rules/30-security-owasp.md) — that's
9
+ the always-on floor (one-liner per OWASP category). This skill adds **operational depth**: the
10
+ trust-boundary→sink walk, common bug patterns to spot on sight, per-category code-level checks
11
+ that go beyond the rule's one-liner. When a section restates the rule verbatim, replace with a
12
+ pointer.
13
+
14
+ Pull this skill in when you are *writing* or *reviewing* code in security-sensitive territory.
15
+
16
+ ## Trust boundary → sink walk
17
+
18
+ Every security finding starts with the same question: **untrusted data crosses what boundary, and where
19
+ does it end up?** When you load this skill, do this walk:
20
+
21
+ 1. **Identify each ingress**: HTTP body, query, headers, cookies; queue message; file from disk/S3;
22
+ third-party webhook; gRPC field.
23
+ 2. **For each ingress, identify the sinks** the value can reach:
24
+ - SQL query → A03 injection
25
+ - Shell command → A03 command injection
26
+ - HTML template → XSS
27
+ - File path (`open`, `read`, `unlink`) → path traversal
28
+ - URL for outbound HTTP → SSRF
29
+ - Deserializer (YAML, pickle, etc.) → A08
30
+ - Hash/compare with user-supplied token → timing / A02
31
+ - Log line → log injection
32
+ 3. **At each sink**: is the input parameterized / encoded / validated for that sink's grammar?
33
+ 4. **Before the sink**: is authorization checked? Is the caller allowed to do this on this resource?
34
+
35
+ ## Per-category quick checks
36
+
37
+ ### Injection (A03)
38
+
39
+ - **SQL**: parameterized queries, prepared statements, ORM with bind variables. Never string-concat user
40
+ input. Whitelist column/table names if dynamic.
41
+ - **Shell**: `execFile`/`spawn` with an args array. Never `sh -c <user-input>`. If you must, refuse
42
+ user input.
43
+ - **NoSQL**: type-check; reject operator-typed inputs (`{$gt: ...}`) when a string is expected.
44
+ - **LDAP**: escape per RFC 4515.
45
+ - **Templating**: use the template engine's auto-escape; never `safe`/`raw` user data.
46
+ - **Headers**: reject `\r\n` in any header value built from input.
47
+
48
+ ### AuthZ (A01)
49
+
50
+ - **Default deny.** Every endpoint declares who's allowed.
51
+ - **Check at the resource, not just the route.** "Can user U access resource R?" not just "is U logged in?"
52
+ - **No tenant cross-leak.** Tenant ID in the URL/path must match the caller's session — don't trust it
53
+ blindly.
54
+ - **IDOR**: any reference to a resource by ID must be authorized for *this caller*.
55
+
56
+ ### Crypto (A02)
57
+
58
+ - **Random**: `crypto.randomBytes` / `secrets.token_bytes` — not `Math.random`, not `random.random`.
59
+ - **Hash for passwords**: argon2id (preferred), bcrypt, scrypt. Never SHA*.
60
+ - **Hash for integrity**: SHA-256+, BLAKE2/3, or HMAC for keyed.
61
+ - **Compare**: `crypto.timingSafeEqual` / `hmac.compare_digest` for any secret-bearing comparison.
62
+ - **Don't roll your own.** No custom KDF, no custom protocol.
63
+
64
+ ### Secrets
65
+
66
+ - **Never in source, logs, errors, metric labels, traces, URLs.**
67
+ - **Scoped & rotated.** Least privilege per service. Rotation tooling exists before you store the secret.
68
+ - **Local dev** uses `.env.example` placeholders; real values via secret manager / `direnv` /
69
+ vault — not committed.
70
+
71
+ ### Deserialization (A08)
72
+
73
+ - **Allowlist formats**: JSON with schema validation; protobuf with known fields; MsgPack with explicit
74
+ decoder.
75
+ - **Block dangerous formats**: pickle, Java native serialization, unsanitized YAML (`yaml.safe_load` only).
76
+ - **Validate the schema** before the type system trusts the value.
77
+
78
+ ### SSRF (A10)
79
+
80
+ - **Egress allowlist** for any outbound HTTP triggered by user input.
81
+ - **Block link-local, loopback, metadata IPs** (`169.254.169.254`, RFC1918, `127.0.0.0/8`, `::1`,
82
+ `fe80::/10`).
83
+ - **Resolve once, connect to the resolved IP** to defeat DNS rebinding.
84
+ - **Cap redirects** and re-validate each hop.
85
+
86
+ ### XSS
87
+
88
+ - **Output-encode at the sink**, not at the boundary. HTML escape for DOM, JS escape for `<script>`
89
+ contexts, URL escape for href/src.
90
+ - **Avoid `dangerouslySetInnerHTML` / `v-html` / `{{{ }}}`** with user data.
91
+ - **CSP** as defense-in-depth (script-src 'self' + nonces; no unsafe-inline; no wildcard).
92
+
93
+ ### File handling
94
+
95
+ - **Path traversal**: resolve to absolute, then check the result is under the allowed root. Reject `..`,
96
+ null bytes, and absolute paths in user input.
97
+ - **Uploads**: server-side content-type sniffing, size limit, virus scan if user-shared, store outside
98
+ the web root, serve via signed URL or proxy with `Content-Disposition: attachment`.
99
+ - **Image processing**: ImageMagick et al. have a vulnerability history. Constrain formats; use a
100
+ sandboxed processor.
101
+
102
+ ### Auth & sessions (A07)
103
+
104
+ - **Library, not bespoke.** Use the framework's session/JWT story.
105
+ - **Rotate on privilege change** (login, role change). Invalidate on logout.
106
+ - **Idle + absolute timeouts** for high-privilege scopes.
107
+ - **Rate-limit credential endpoints**; protect against enumeration (uniform error messages, uniform
108
+ timings).
109
+ - **MFA on admin paths.**
110
+
111
+ ### Logging (A09)
112
+
113
+ - **Log security-relevant events**: authn outcomes (success/fail), authz denials, admin actions,
114
+ config changes.
115
+ - **Don't log**: passwords, tokens, full PII for credential endpoints, raw cookies, raw request bodies of
116
+ sensitive endpoints.
117
+ - **Structured + correlation ID + central sink.**
118
+
119
+ ## Common bug patterns to recognize on sight
120
+
121
+ - `if user.is_admin == True: ...` written but never *called* on a path.
122
+ - `os.path.join(BASE, user_input)` without realpath check.
123
+ - `requests.get(user_url)` without SSRF guards.
124
+ - `eval(...)`, `Function(...)`, `subprocess.Popen(..., shell=True)`.
125
+ - `==` for token comparison.
126
+ - `setTimeout(<inline string>)`.
127
+ - A regex used for HTML, SQL, or URL parsing.
128
+ - `random.choice` / `Math.random` generating a token.
129
+ - `JSON.parse` of `req.body` with no schema; then field access without type checks.
130
+ - A redirect URL taken from a query parameter without an allowlist.
131
+
132
+ ## When to invoke `security-reviewer`
133
+
134
+ Loading this skill means *you are aware*. It does not replace the [`security-reviewer`](../../agents/security-reviewer.md)
135
+ agent. Invoke that agent when:
136
+
137
+ - The change introduces a new ingress or sink.
138
+ - The change touches auth, crypto, or secrets handling.
139
+ - You found a pattern from the list above and want a second pair of eyes.
140
+
141
+ This skill is the *checklist in your head*; the agent is the *audit*.
@@ -0,0 +1,137 @@
1
+ ---
2
+ name: requirements-engineering
3
+ description: Use when writing or critiquing requirements and pre-development design documents — BRD, SRS, FRD, SDD, TDD — or when turning a fuzzy idea into testable, traceable requirements. Covers functional vs non-functional, INVEST, MoSCoW, acceptance criteria, traceability, ambiguity elimination, and what belongs in which document.
4
+ ---
5
+
6
+ # Requirements engineering
7
+
8
+ The collaboration and priority rules in [`rules/50-collaboration.md`](../../rules/50-collaboration.md)
9
+ and [`rules/00-priorities.md`](../../rules/00-priorities.md) are the always-on floor. This skill adds
10
+ **operational depth** for the discovery phase: how to write a requirement that can't be misread, how
11
+ to split documents, and how to keep everything traceable. The owning agent is
12
+ [`discovery-analyst`](../../agents/discovery-analyst.md); load this skill when you are *authoring or
13
+ reviewing* requirements/design docs under `.somi/rd/<slug>/`.
14
+
15
+ Pair it with [`market-research`](../market-research/SKILL.md) (where requirements come from),
16
+ [`solid-principles`](../solid-principles/SKILL.md) and [`api-design`](../api-design/SKILL.md) (for the
17
+ SDD), and [`threat-modeling`](../threat-modeling/SKILL.md) (for security NFRs).
18
+
19
+ ## The one test for every requirement
20
+
21
+ > **"How would I write a test that proves this is met?"**
22
+
23
+ If you can't answer in one sentence, the requirement is not done. "The system should be fast",
24
+ "easy to use", "handle lots of users" are not requirements — they're wishes. Rewrite as observable,
25
+ bounded statements: "p95 read latency < 200 ms at 500 rps", "a new user completes first import in
26
+ < 3 steps", "sustains 10k concurrent sessions on the reference instance".
27
+
28
+ ## Which document holds what
29
+
30
+ These overlap if you're sloppy. Keep the seams clean:
31
+
32
+ | Document | Answers | Holds | Does **not** hold |
33
+ |----------|---------|-------|-------------------|
34
+ | **BRD** (business) | *Why build this, for whom, what is success?* | Problem, stakeholders, business goals, scope boundaries, success metrics, constraints | Feature specs, technical choices |
35
+ | **SRS** (software requirements) | *What must the software do and how well?* | The canonical functional (`FR-*`) and non-functional (`NFR-*`) requirements, prioritized & traceable | Business justification (lives in BRD), UI flows (FRD), tech choices (TDD) |
36
+ | **FRD** (functional detail) | *How does each function behave, step by step?* | Primary/alternate/exception flows, field-level rules, edge cases, state transitions | New requirements (those belong in SRS), design |
37
+ | **SDD** (software design, high-level) | *What is the shape of the solution?* | Major components & responsibilities, data the system owns, integration/trust boundaries, expensive-to-reverse choices | Detailed module/interface design, file layout (that's the planner) |
38
+ | **TDD** (technical design, high-level) | *What technology and what limits?* | Technology family, NFR engineering targets, security/compliance posture, rationale tied to SRS | Concrete library picks, per-iteration plans (planner) |
39
+
40
+ When in doubt: requirements (the *what*) go in SRS; behavior detail goes in FRD; the *why* goes in
41
+ BRD; the *shape* goes in SDD/TDD. If a line fits two documents, it belongs in the more upstream one
42
+ and is *referenced* (not copied) downstream.
43
+
44
+ ## Functional vs non-functional
45
+
46
+ - **Functional (`FR-*`)** — what the system *does*: "FR-7 — the importer rejects rows missing a
47
+ required column and reports the row number." A behavior you could demo.
48
+ - **Non-functional (`NFR-*`)** — *how well* it does it: performance, availability, security,
49
+ accessibility, compliance, operability. NFRs are where products lose trust — give them numbers and
50
+ conditions, not adjectives.
51
+
52
+ A useful prompt for NFRs: *"-ility?"* — scalability, reliability, security, usability,
53
+ maintainability, observability, portability. Each gets a measurable target or an explicit "not a
54
+ concern for v1 because …".
55
+
56
+ ## INVEST — the shape of a good requirement
57
+
58
+ - **I**ndependent — minimal coupling to other requirements.
59
+ - **N**egotiable — states the need, not a pre-baked implementation.
60
+ - **V**aluable — traces to a BRD goal; if it serves no goal, cut it.
61
+ - **E**stimable — clear enough that the planner could size it.
62
+ - **S**mall — one requirement, one behavior. Split compound "and"/"or" requirements.
63
+ - **T**estable — the one test above.
64
+
65
+ ## MoSCoW — prioritize, always
66
+
67
+ Every requirement is tagged **Must / Should / Could / Won't (this release)**. "Won't" is a
68
+ first-class output of discovery — it's how you record scope boundaries (and it pairs with BRD
69
+ non-goals). A spec where everything is a Must is a spec that hasn't made a decision.
70
+
71
+ ## Traceability — the spine of the document set
72
+
73
+ Every requirement traces **backward** (to a business goal and, where relevant, a research finding)
74
+ and **forward** (to a design element, and later to a plan phase). Maintain this in the R&D
75
+ `README.md` traceability map. Why it pays off:
76
+
77
+ - A requirement with no upstream goal is **scope creep** — surface it or cut it.
78
+ - A business goal with no downstream requirement is an **unmet goal** — a gap.
79
+ - A design element with no requirement is **gold-plating** — design for a need that doesn't exist.
80
+
81
+ Give every requirement a **stable ID** (`FR-1`, `NFR-1`, `BR-1`). IDs are forever — supersede, never
82
+ renumber, so downstream references don't rot.
83
+
84
+ ## Ambiguity elimination
85
+
86
+ Hunt these words and pin them down:
87
+
88
+ - **"etc.", "and so on"** — enumerate or scope. The reader can't test "etc."
89
+ - **"should" vs "must"** — use RFC-2119 discipline: MUST (mandatory), SHOULD (recommended, with a
90
+ stated exception path), MAY (optional). Don't mix casually.
91
+ - **"fast / quick / soon / large / many"** — replace with a number and unit.
92
+ - **"support X"** — define what "support" means (read? write? configure? at what scale?).
93
+ - **Passive voice hiding the actor** — "the file is validated" → *who* validates, *when*, on *what
94
+ failure*?
95
+ - **Unstated failure behavior** — every functional requirement needs its sad path: what happens when
96
+ the input is bad, the dependency is down, the limit is hit.
97
+
98
+ ## Acceptance criteria
99
+
100
+ Attach concrete, checkable acceptance criteria to requirements that need them. Given/When/Then is a
101
+ good default:
102
+
103
+ > **FR-12** — Bulk import reports accepted/rejected counts and fails loudly on any rejection.
104
+ > - **Given** a file with 3 valid and 2 invalid rows, **when** imported, **then** the response
105
+ > states "3 accepted, 2 rejected", lists the 2 row numbers, and exits non-zero.
106
+
107
+ ## Anti-patterns to call out
108
+
109
+ - **Solution-as-requirement** — "use PostgreSQL" stated as a requirement. That's a *decision* (TDD,
110
+ verified), not a requirement. The requirement is the need it serves ("durable, queryable storage
111
+ of orders with ACID guarantees").
112
+ - **The everything-Must spec** — no prioritization; nothing can be cut; planning can't sequence it.
113
+ - **Untestable adjectives** — "intuitive", "robust", "seamless". Restate as observable behavior.
114
+ - **Copy-paste across documents** — the same text in BRD and SRS drifts. Put it once, reference it.
115
+ - **Requirements with no failure path** — only the happy path specified.
116
+ - **Renumbered IDs** — breaks every downstream reference. Supersede instead.
117
+ - **Design smuggled into the SRS** — function signatures and module names in a requirements doc.
118
+ Direction goes in the SDD; detail goes to the planner.
119
+
120
+ ## When *not* to over-apply
121
+
122
+ - For a **small, well-understood internal tool**, a single SRS may absorb the FRD — don't force five
123
+ documents. Omit with a reason in `README.md`.
124
+ - For work that already has a settled spec, skip discovery and hand to the
125
+ [`planner`](../../agents/planner.md).
126
+ - Don't gold-plate NFRs for a prototype — state the targets that matter and explicitly defer the
127
+ rest.
128
+
129
+ ## When to escalate / hand off
130
+
131
+ - **To the user (verification protocol)** — any requirement- or direction-shaping decision: target
132
+ persona, scope boundary, build-vs-integrate, an expensive-to-reverse architectural call.
133
+ - **To the [`planner`](../../agents/planner.md)** — once the SRS/SDD are ready; the planner turns
134
+ direction into detailed, phased design. Don't do its job in the SDD.
135
+ - **To [`threat-modeling`](../threat-modeling/SKILL.md) / [`owasp-defense`](../owasp-defense/SKILL.md)**
136
+ — when the product introduces a real attack surface; the security NFRs and trust boundaries belong
137
+ in the SRS/SDD, grounded by those skills.
@@ -0,0 +1,143 @@
1
+ ---
2
+ name: solid-principles
3
+ description: Use when designing a new module, naming a class, deciding what a function should know, splitting/merging modules, or evaluating whether an abstraction is paying for itself. Operationalizes SOLID as design questions, not five recited bullets.
4
+ ---
5
+
6
+ # SOLID — design questions
7
+
8
+ The principles are in [`rules/10-solid.md`](../../rules/10-solid.md) — that's the always-on floor.
9
+ This skill adds **operational depth**: before/after example pairs, decision rules, anti-patterns.
10
+ Don't restate the rule's prose here; link to it when the principle itself is the answer.
11
+
12
+ When you load this skill you are evaluating a design, not reciting principles. Each letter is a question
13
+ to ask of the code you're about to write or review.
14
+
15
+ ## S — "What's the one reason this changes?"
16
+
17
+ If you can't say it in one sentence without "and", you have an SRP problem. SRP isn't about counting
18
+ methods; it's about counting **actors** that drive change.
19
+
20
+ **Before (SRP smell)**
21
+ ```python
22
+ class Order:
23
+ def total(self) -> Money: ...
24
+ def save(self) -> None: ... # persistence
25
+ def send_receipt(self) -> None: ... # email
26
+ ```
27
+
28
+ Three reasons to change: pricing rules, schema, comms.
29
+
30
+ **After**
31
+ ```python
32
+ class Order: # pricing rules
33
+ def total(self) -> Money: ...
34
+
35
+ class OrderRepository: # persistence
36
+ def save(self, o: Order) -> None: ...
37
+
38
+ class ReceiptSender: # comms
39
+ def send(self, o: Order) -> None: ...
40
+ ```
41
+
42
+ ## O — "Can I add the next variant without editing existing code?"
43
+
44
+ OCP isn't "make everything pluggable." It's "when the next variant arrives, design lets you *add* instead
45
+ of *modify*." Only invest when variation is real.
46
+
47
+ **The three-cases rule**: do not abstract until you have three concrete variants. Two is a coincidence;
48
+ three is a pattern. A premature strategy interface costs more than a third `if`.
49
+
50
+ ## L — "Does this subtype obey the parent's contract, or weaken it?"
51
+
52
+ The Square/Rectangle case is the canonical example. If your subclass throws `NotSupportedException`,
53
+ the type relationship is wrong — prefer composition.
54
+
55
+ **Red flag:** when a subclass override requires callers to *check the runtime type* to know what to do,
56
+ the inheritance is misused.
57
+
58
+ ## I — "Is this interface shaped for callers, or for the implementer's convenience?"
59
+
60
+ Big "service" interfaces (`IUserService` with 20 methods) usually serve the implementer. Callers
61
+ typically need 2–3 of those methods. Split:
62
+
63
+ **Before**
64
+ ```ts
65
+ interface UserService {
66
+ getUser(id: string): User
67
+ updateProfile(id: string, p: Profile): void
68
+ resetPassword(id: string): void
69
+ exportGDPRData(id: string): Blob
70
+ // ... 15 more
71
+ }
72
+ ```
73
+
74
+ **After**
75
+ ```ts
76
+ interface UserReader { getUser(id: string): User }
77
+ interface ProfileWriter { updateProfile(id: string, p: Profile): void }
78
+ interface PasswordResetter { resetPassword(id: string): void }
79
+ interface GDPRExporter { exportGDPRData(id: string): Blob }
80
+ ```
81
+
82
+ Each consumer depends on the role it actually uses. The concrete `UserService` implements all four.
83
+
84
+ ## D — "Does business policy know about mechanism?"
85
+
86
+ Domain rules should not import database drivers, HTTP clients, file systems, or cloud SDKs. The domain
87
+ declares the interface in its own language; infrastructure implements it.
88
+
89
+ **Smell**
90
+ ```python
91
+ # domain/order.py
92
+ import psycopg2
93
+ def reserve_inventory(order):
94
+ conn = psycopg2.connect(...)
95
+ ...
96
+ ```
97
+
98
+ **Better**
99
+ ```python
100
+ # domain/inventory.py
101
+ class InventoryPort(Protocol):
102
+ def reserve(self, sku: str, qty: int) -> None: ...
103
+
104
+ # domain/order.py
105
+ def reserve_inventory(order, inventory: InventoryPort):
106
+ for line in order.lines:
107
+ inventory.reserve(line.sku, line.qty)
108
+
109
+ # infrastructure/postgres_inventory.py
110
+ class PostgresInventory(InventoryPort):
111
+ def __init__(self, conn): self.conn = conn
112
+ def reserve(self, sku, qty): ...
113
+ ```
114
+
115
+ Now domain tests don't need a database. Now the inventory implementation can change without touching the
116
+ order policy.
117
+
118
+ But: **don't invert dependencies you never swap.** A `LoggerInterface` with one logger implementation is
119
+ just extra indirection.
120
+
121
+ ## Meta-rules
122
+
123
+ See [`rules/10-solid.md`](../../rules/10-solid.md) §Meta-rules for the canonical statements
124
+ (YAGNI > SOLID for hypothetical variation; three-is-the-magic-number; refactor-under-green).
125
+ Operational additions specific to this skill:
126
+
127
+ - **Composition over inheritance** in ~80% of cases; reserve inheritance for true is-a relationships
128
+ whose contract genuinely holds across subtypes (re-read the L section before reaching for `extends`).
129
+
130
+ ## When SOLID is *not* the right lens
131
+
132
+ - **One-off scripts.** A bash script doesn't need DI.
133
+ - **Performance-critical inner loops.** Sometimes the right move is a flat struct + tight loop, not
134
+ five tiny objects.
135
+ - **Trivial code paths.** A three-line function doesn't need a class hierarchy.
136
+
137
+ SOLID is a response to real change pressure. If there's no pressure, the principles are inert.
138
+
139
+ ## When to escalate
140
+
141
+ If you spot a SOLID violation that's deeper than this skill can fix — for example, the dependency
142
+ direction is wrong throughout a layer — escalate to [`architecture-reviewer`](../../agents/architecture-reviewer.md)
143
+ rather than patching locally.
@@ -0,0 +1,133 @@
1
+ ---
2
+ name: test-strategy
3
+ description: Use when deciding what to test, at what level, and how. Distinguishes risk-driven coverage from coverage-worship. Covers unit vs integration vs e2e choices, mocking policy, determinism, and what to intentionally not cover.
4
+ ---
5
+
6
+ # Test strategy
7
+
8
+ The principles are in [`rules/40-engineering-practices.md`](../../rules/40-engineering-practices.md)
9
+ (Testing section) — that's the always-on floor. This skill adds **operational depth**: decision
10
+ tables, level-selection trees, mock policy with reasons, determinism patterns. Don't restate the
11
+ rule's bullets here; if you find a line that's word-for-word the rule, replace it with a pointer.
12
+
13
+ The supporting agent is [`test-strategist`](../../agents/test-strategist.md). Load this skill when you
14
+ are *writing* tests for a change you're already coding. Invoke the agent when the test shape itself is
15
+ a problem.
16
+
17
+ ## The first question: what's the risk?
18
+
19
+ Tests exist to catch failures that matter. Before adding any test, ask:
20
+
21
+ - **What can go wrong with this code?**
22
+ - **What's the consequence?** (User sees wrong number? Money moves wrongly? Data is lost? Latency
23
+ spikes?)
24
+ - **How would I notice if it broke in production?**
25
+
26
+ Risk drives coverage. Trivial getters with high consequence (e.g., `isAdmin`) deserve tests. Complex
27
+ algorithms with low consequence (e.g., a debug formatter) may not.
28
+
29
+ ## Pick the right level
30
+
31
+ | Concern | Level |
32
+ |--------------------------------------------------|---------------|
33
+ | Pure functions, branching, data shaping | Unit |
34
+ | Crossing a process boundary (DB, queue, HTTP) | Integration |
35
+ | User-visible journey across several components | End-to-end |
36
+
37
+ **Most projects need**: a healthy unit base + a handful of integration tests at seams + a small number of
38
+ e2e tests for golden paths. Inverted pyramids (lots of e2e, few unit) are slow, flaky, and expensive.
39
+
40
+ ### When unit is enough
41
+ - Logic that is or can be made pure (no I/O).
42
+ - Behavior that's testable through the seam without crossing it (e.g., test a parser by giving it bytes,
43
+ not by reading a real file).
44
+
45
+ ### When integration is needed
46
+ - The value of the code is in **how it interacts with the seam** (e.g., a repository query against a real
47
+ schema, a message producer's interaction with the queue).
48
+ - Mocking would hide the actual risk (you're mocking the part that matters).
49
+
50
+ ### When e2e is needed
51
+ - The user-visible journey involves multiple components that have been individually tested but never
52
+ exercised together.
53
+ - The risk is integration drift over time, not unit correctness.
54
+
55
+ ## Mocking policy
56
+
57
+ The cardinal rule lives in [`rules/40-engineering-practices.md`](../../rules/40-engineering-practices.md):
58
+ **don't mock what you don't own.** Operational expansion:
59
+
60
+ - **Don't mock** third-party SDKs, databases, HTTP clients you didn't write. Mocking these tests your
61
+ understanding of their API, which is exactly the part you don't control.
62
+ - **Do mock** seams you own — interfaces you've defined for collaborators.
63
+ - **Prefer fakes you author** that implement the same contract as the real thing (in-memory repo, fake
64
+ message bus). Cheaper than full integration; more honest than mocks.
65
+ - **Integration tests** for the real-thing interaction, when the risk is at that seam.
66
+
67
+ ### Test signal anti-patterns
68
+
69
+ - **No assertion**: function called, test passes, asserts nothing useful.
70
+ - **Assertions on the mock's return value**: you're testing your mock.
71
+ - **Snapshot worship**: snapshot tests as the safety net for logic. Snapshots are great for output
72
+ formats with stable shapes (HTML, JSON), bad for behavior.
73
+ - **Mock-the-world**: every collaborator stubbed, including pure ones. The test exercises stubs, not
74
+ code.
75
+
76
+ ## Determinism
77
+
78
+ Tests that "pass sometimes" are bugs in the test (or worse, in the code).
79
+
80
+ - **Time**: inject a clock; use a frozen clock in tests; never call `time.now()` directly in code under test.
81
+ - **Randomness**: inject a seed; use a deterministic source in tests.
82
+ - **Ordering**: don't depend on dictionary/map iteration order; sort if you assert on ordering.
83
+ - **Shared state**: each test starts from a known state. Tear down or use isolated databases / temp dirs.
84
+ - **Concurrency**: explicit synchronization; no "sleep then assert" races.
85
+
86
+ Flaky tests get **fixed**, not retried. A `--retry 3` flag is a tombstone for code quality.
87
+
88
+ ## Test names
89
+
90
+ Tests document intent. Names should describe behavior in plain language:
91
+
92
+ - `test_user_with_expired_token_gets_401`
93
+ - `test_concurrent_writes_to_same_key_are_serialized`
94
+ - `test_rate_limiter_allows_burst_up_to_capacity_then_denies`
95
+
96
+ Not:
97
+
98
+ - `test_1`, `test_user`, `test_handler`, `test_works`.
99
+
100
+ ## Diagnostic quality
101
+
102
+ When a test fails, the diagnostic should tell you what broke. Strategies:
103
+
104
+ - **One assertion per concept** (not one per test). A test can assert several things, but each should be
105
+ a clear named expectation.
106
+ - **Helpful diff messages** — use libraries that print diffs for structured data, not just `assertEquals(a, b)`.
107
+ - **Name the variables in the test** for what they represent, not `a` / `b` / `result`.
108
+ - **Failure messages**: a custom message on critical asserts saves time.
109
+
110
+ ## What to *not* cover
111
+
112
+ Stating non-coverage is part of the strategy. Examples:
113
+
114
+ - "We don't unit-test the `SELECT` SQL in `OrderRepository.findRecent` — integration test in
115
+ `OrderRepositoryIT` exercises the real query."
116
+ - "We don't cover the 4xx branch of `httpClient.get` — we trust the library's tests for that."
117
+ - "Snapshot tests cover the HTML output; we don't unit-test the template rendering."
118
+
119
+ If you skip coverage **and don't say why**, you're hiding risk.
120
+
121
+ ## Coverage-worship rejection
122
+
123
+ 100% line coverage doesn't mean safe. 60% coverage of the risky paths is safer than 100% coverage of
124
+ getters. Aim for **coverage where it matters**, not coverage as a number.
125
+
126
+ ## When to invoke `test-strategist`
127
+
128
+ - The codebase has poor seams and you can't write the tests you want without refactoring first.
129
+ - Tests are flaky and you suspect the design, not the test code.
130
+ - You're not sure whether to unit-test or integration-test something.
131
+ - You're about to mock something you don't own.
132
+
133
+ The agent thinks about test shape; this skill helps you write tests under a chosen shape.
@@ -0,0 +1,117 @@
1
+ ---
2
+ name: threat-modeling
3
+ description: Use when introducing a new attack surface — a new external integration, webhook, file upload, OAuth flow, or service exposed to a less-trusted zone. Walks STRIDE / data-flow / trust-boundary frames to surface threats before code lands.
4
+ ---
5
+
6
+ # Threat modeling — light-touch
7
+
8
+ Full enterprise threat modeling is heavy. This skill is for the engineer-scale case: *we're introducing a
9
+ new surface and we want to think about how it gets abused, before we ship*. 30–90 minutes of structured
10
+ thinking, not weeks.
11
+
12
+ Pair with [`owasp-defense`](../owasp-defense/SKILL.md) (which is about mitigations) and
13
+ [`security-reviewer`](../../agents/security-reviewer.md) (which does the deep audit).
14
+
15
+ ## When to threat-model
16
+
17
+ - Adding a new public endpoint or webhook.
18
+ - Adding an integration with a third party (we call them, they call us, or both).
19
+ - Adding a file upload, file processing, or attachment feature.
20
+ - Adding an authentication mechanism (OAuth provider, SSO, API keys).
21
+ - Crossing a new trust boundary (introducing a new service, opening a new port).
22
+ - Storing or transmitting a new class of sensitive data (PII, payment, health, secrets).
23
+
24
+ ## The light-touch process
25
+
26
+ ### 1. Draw the data flow
27
+
28
+ A whiteboard sketch is fine. Identify:
29
+
30
+ - **External actors**: users, third-party services, attackers (named ones if relevant).
31
+ - **Processes**: the components doing work.
32
+ - **Data stores**: databases, caches, queues, file storage.
33
+ - **Trust boundaries**: where untrusted data becomes trusted (or moves between zones).
34
+
35
+ ### 2. For each trust boundary, ask STRIDE
36
+
37
+ | Letter | Threat | Question |
38
+ |--------|------------------------------|------------------------------------------------------|
39
+ | **S** | Spoofing | Can someone pretend to be a legitimate actor? |
40
+ | **T** | Tampering | Can data be modified in flight or at rest? |
41
+ | **R** | Repudiation | Can an actor deny an action without us proving it? |
42
+ | **I** | Information disclosure | Can an attacker read what they shouldn't? |
43
+ | **D** | Denial of service | Can the surface be overwhelmed or held open? |
44
+ | **E** | Elevation of privilege | Can a low-privilege actor act as high-privilege? |
45
+
46
+ Not every category applies to every boundary. Skip what's clearly N/A; document what's not.
47
+
48
+ ### 3. For each threat, decide
49
+
50
+ - **Mitigate**: what's the control? (Auth, validation, rate limit, signing, encryption, allowlist…)
51
+ - **Accept**: why is it not worth mitigating? (Cost, threat model assumption, defense in depth elsewhere.)
52
+ - **Transfer**: who else handles this? (Third-party WAF, framework, library, ops layer.)
53
+ - **Avoid**: change the design to eliminate the surface.
54
+
55
+ ### 4. Write it down
56
+
57
+ Even a one-page note that lives next to the code. Future you / on-call / the next reviewer will thank you.
58
+
59
+ ## Per-surface checklists
60
+
61
+ ### New webhook endpoint (we receive)
62
+
63
+ - **Authn**: signature verification (HMAC of body), or mTLS, or shared secret. Constant-time comparison.
64
+ - **Replay**: timestamp in signed payload, reject outside ±5 min; idempotency key for dedupe.
65
+ - **Source allowlist** if practical (e.g., known IP ranges from the sender's docs).
66
+ - **Body limits**: max size, max nesting depth.
67
+ - **Schema validation** before parsing into typed objects.
68
+ - **Rate limit** per sender principal.
69
+ - **Observability**: log every webhook with a correlation ID; metric for accept/reject/duplicate.
70
+
71
+ ### New file upload
72
+
73
+ - **Size cap** at the proxy *and* the handler.
74
+ - **Content-type sniff server-side** — don't trust the client's `Content-Type` or extension.
75
+ - **Antivirus / sandboxed processing** if user-shared.
76
+ - **Storage location** outside the web root; serve via signed URL or proxy with
77
+ `Content-Disposition: attachment`.
78
+ - **Filename safety**: don't use user-supplied filename for storage path; canonicalize.
79
+ - **Path traversal** on any path construction.
80
+
81
+ ### New OAuth / SSO integration
82
+
83
+ - **PKCE** for public clients.
84
+ - **State** parameter, validated server-side.
85
+ - **Redirect URI allowlist**, exact-match.
86
+ - **Validate `iss`, `aud`, `exp`, `nbf`, signature** on every token; never trust the JWT body without signature check.
87
+ - **Token storage**: HttpOnly + Secure + SameSite for browser; secret manager for backend.
88
+ - **Refresh rotation**: rotate refresh tokens; revoke on suspicious refresh.
89
+
90
+ ### New third-party integration (we call them)
91
+
92
+ - **Egress allowlist**: if user input controls the URL, see SSRF in `owasp-defense`.
93
+ - **Timeouts**: every outbound call has a timeout and a circuit-breaker policy.
94
+ - **Auth at rest**: their credentials in secret manager; rotated; scoped.
95
+ - **Failure mode**: what happens when they're down? Degraded UX, queued retry, hard fail?
96
+ - **Data leaving the boundary**: what PII / business data are we sending? Is the contract OK?
97
+
98
+ ### New service in a less-trusted zone
99
+
100
+ - **Authn between services**: mTLS, SPIFFE, signed JWTs from a known issuer.
101
+ - **AuthZ checks** at the service edge — don't assume the caller already authorized.
102
+ - **Network policy**: only allow the specific routes/IPs needed.
103
+ - **Secret access**: scoped to this service; no shared credentials with other services.
104
+
105
+ ## Threat-modeling failure modes
106
+
107
+ - **Whiteboard theatre.** Sketching, but never writing down mitigations. The artifact matters.
108
+ - **Catastrophizing.** Listing every CVE that could conceivably apply. Focus on *this surface*.
109
+ - **Underestimating the platform.** "Anyone can read this!" — is it behind auth? Inside the VPC?
110
+ - **Not revisiting.** Threat model when the design is set, and again when the design changes.
111
+
112
+ ## When to escalate
113
+
114
+ - **High-impact surface** (auth, payments, PII at scale): escalate to `security-reviewer` for the audit
115
+ pass, in addition to this skill.
116
+ - **New architecture**: pair with `architecture-reviewer` to ensure the threat model and the
117
+ architecture stay in sync.