@srobroek/pi-code-quality 0.0.0-stage → 0.15.3

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 (55) hide show
  1. package/CHANGELOG.md +191 -0
  2. package/LICENSE +202 -0
  3. package/README.md +150 -2
  4. package/agents/adversarial-challenger.md +29 -0
  5. package/extensions/quality.js +4583 -0
  6. package/package.json +40 -4
  7. package/skills/prototype-logic/LICENSE +21 -0
  8. package/skills/prototype-logic/NOTICE +26 -0
  9. package/skills/prototype-logic/SKILL.md +76 -0
  10. package/skills/quality-code-design/LICENSE-mattpocock-skills +21 -0
  11. package/skills/quality-code-design/NOTICE +63 -0
  12. package/skills/quality-code-design/SKILL.md +63 -0
  13. package/skills/quality-code-design/references/contracts.md +37 -0
  14. package/skills/quality-code-design/references/debugging.md +85 -0
  15. package/skills/quality-code-design/references/deep-modules.md +67 -0
  16. package/skills/quality-code-design/references/dependencies.md +81 -0
  17. package/skills/quality-code-design/references/encapsulation.md +148 -0
  18. package/skills/quality-code-design/references/feature-flags.md +189 -0
  19. package/skills/quality-code-design/references/go.md +110 -0
  20. package/skills/quality-code-design/references/lifecycle.md +66 -0
  21. package/skills/quality-code-design/references/middleware.md +55 -0
  22. package/skills/quality-code-design/references/other-paradigms.md +44 -0
  23. package/skills/quality-code-design/references/persistence.md +52 -0
  24. package/skills/quality-code-design/references/python.md +100 -0
  25. package/skills/quality-code-design/references/release.md +59 -0
  26. package/skills/quality-code-design/references/review.md +121 -0
  27. package/skills/quality-code-design/references/rust.md +140 -0
  28. package/skills/quality-code-design/references/safe-mutation.md +33 -0
  29. package/skills/quality-code-design/references/security.md +65 -0
  30. package/skills/quality-code-design/references/simplicity.md +165 -0
  31. package/skills/quality-code-design/references/solid.md +165 -0
  32. package/skills/quality-code-design/references/supporting-principles.md +78 -0
  33. package/skills/quality-code-design/references/telemetry.md +54 -0
  34. package/skills/quality-code-design/references/test-first.md +78 -0
  35. package/skills/quality-code-design/references/typescript.md +93 -0
  36. package/skills/quality-code-design/references/verification.md +53 -0
  37. package/skills/quality-code-policy/SKILL.md +34 -0
  38. package/skills/quality-profiling/SKILL.md +48 -0
  39. package/skills/quality-profiling/references/hygiene.md +27 -0
  40. package/skills/quality-profiling/references/reading-profiles.md +21 -0
  41. package/skills/quality-profiling/references/system.md +51 -0
  42. package/skills/quality-test-audit/SKILL.md +122 -0
  43. package/skills/quality-test-audit/references/catalog.md +108 -0
  44. package/skills/quality-test-audit/references/evidence.md +123 -0
  45. package/skills/quality-test-audit/references/report.md +75 -0
  46. package/skills/quality-testing/SKILL.md +62 -0
  47. package/skills/quality-testing/references/bad-tests.md +258 -0
  48. package/skills/quality-testing/references/doubles.md +49 -0
  49. package/skills/quality-testing/references/good-tests.md +90 -0
  50. package/skills/quality-testing/references/maintenance.md +96 -0
  51. package/skills/quality-testing/references/review-tests.md +72 -0
  52. package/skills/quality-testing/references/shared-contracts.md +30 -0
  53. package/skills/quality-testing/references/signals.md +50 -0
  54. package/skills/quality-testing/references/test-budget.md +81 -0
  55. package/skills/quality-testing/references/what-to-test.md +58 -0
@@ -0,0 +1,165 @@
1
+ # YAGNI, KISS, and DRY
2
+
3
+ ## Contents
4
+
5
+ - YAGNI: current need and reversible structure
6
+ - YAGNI: remove obsolete machinery
7
+ - KISS: total complexity and clarity
8
+ - KISS: proportional scripts, CI, and tools
9
+ - KISS: refactoring and growth
10
+ - DRY: knowledge versus resemblance
11
+ - DRY: ownership across boundaries
12
+ - DRY and KISS in tests
13
+
14
+ ## YAGNI: current need and reversible structure
15
+
16
+ **Do:** implement current requirements and real design boundaries. Keep implementation choices contained so later extraction has a small, identifiable surface.
17
+ **Do not:** add hypothetical providers, options, caches, factories, or compatibility layers. Do not use YAGNI to justify hidden globals, leaking vendor data, or tangled responsibilities.
18
+
19
+ Bad: one CSV export gets an `ExportPluginRegistry`, dynamic discovery, and YAML-configured providers before any extension requirement exists.
20
+ Good: one `exportCsv(rows, writer)` operation uses the CSV library and an explicit output dependency.
21
+
22
+ Bad in the opposite direction: database calls, connection creation, and raw row fields are copied into every business function because "there is only one database."
23
+ Good: contain persistence in a module; expose operations in the consumer's vocabulary. Whether that module also needs an interface, callback, or trait follows the seam rule in [deep-modules.md](deep-modules.md).
24
+
25
+ Why: the good design supports today's need without making future extraction require a whole-program rewrite. "Easy to change later" is a test of coupling and ownership, not permission to implement tomorrow's feature.
26
+
27
+ **Exception:** a committed requirement or an external contract can justify extension behavior before the second implementation ships. Name that requirement; "we might need it" is insufficient.
28
+
29
+ ## YAGNI: remove obsolete machinery
30
+
31
+ **Do:** remove replaced paths and unused configuration in the affected scope after migrating known callers.
32
+ **Do not:** keep dead interfaces or fallback code as insurance, or delete externally used behavior without checking its contract.
33
+
34
+ Bad: after a parser replacement, retain `oldParser`, a never-enabled feature flag, and two test suites indefinitely.
35
+ Good: migrate callers, verify compatibility that is actually required, then remove the obsolete parser and flag.
36
+
37
+ Why: unused machinery increases the number of states a maintainer must understand.
38
+
39
+ **Exception:** a documented rollout or external migration requires temporary compatibility. Record the consumer, removal condition, and residual risk; do not invent a migration requirement.
40
+
41
+ ## KISS: total complexity and clarity
42
+
43
+ **Do:** minimize the work needed to understand, change, test, and operate the solution. Use explicit control flow and established libraries where they reduce that work.
44
+ **Do not:** optimize solely for line count, dependency count, cleverness, or number of files.
45
+
46
+ Bad:
47
+
48
+ ```python
49
+ result = [(x, f(x)) for x in xs if valid(x) and not (seen.add(x) if x not in seen else True)]
50
+ ```
51
+
52
+ Good:
53
+
54
+ ```python
55
+ result = []
56
+ for item in xs:
57
+ if not valid(item) or item in seen:
58
+ continue
59
+ seen.add(item)
60
+ result.append((item, f(item)))
61
+ ```
62
+
63
+ Why: the state change and filtering order are visible. Extra lines can reduce complexity.
64
+
65
+ Second bad: hand-written CSV escaping, date parsing, or migration tracking solely to avoid a dependency. Good: use an established library when its setup and lifecycle costs are smaller than maintaining the required behavior. Do not add a framework to replace one standard-library call.
66
+
67
+ **Exception:** a measured hot path can justify a less direct implementation. Keep the external contract simple, document the measurement, and preserve focused correctness checks.
68
+
69
+ ## KISS: proportional scripts, CI, and tools
70
+
71
+ **Do:** use direct steps, clear inputs, checked failures, and a few functions when they clarify the task.
72
+ **Do not:** turn Bash, CI glue, a one-off migration, or a small utility into a full application architecture.
73
+
74
+ Bad: a two-command CI step gets a plugin system, generic workflow engine, and dependency-injection container.
75
+ Good: two named CI steps or a short script; extract a helper when several jobs share a rule that must remain consistent.
76
+
77
+ Bad:
78
+
79
+ ```bash
80
+ for file in $(ls "$input"/*.json); do process $file; done
81
+ ```
82
+
83
+ Good (Bash):
84
+
85
+ ```bash
86
+ set -euo pipefail
87
+ shopt -s nullglob
88
+ for file in "$input"/*.json; do
89
+ process "$file"
90
+ done
91
+ ```
92
+
93
+ Why: quoting and explicit empty-input behavior solve the actual problem without an architecture. Decide whether no input is a valid no-op; if it is an error, check the array length and fail explicitly. `set -e` is not a complete error-handling strategy for conditional commands and pipelines.
94
+
95
+ **Exception:** a script that grows into a maintained tool with complex state or multiple independent workflows warrants modules or a more suitable language. Reassess when requirements change, not after an arbitrary line threshold.
96
+
97
+ ## KISS: refactoring and growth
98
+
99
+ **Do:** fix the violations the change introduces and simplify the code the change already has to touch. Revisit design whenever behavior is added or changed.
100
+ **Do not:** preserve a tangled design inside the touched code just because the patch can be smaller, or rewrite unrelated code for stylistic consistency.
101
+
102
+ Bad: add a fourth mode flag to a helper that now performs both file import and remote synchronization.
103
+ Good: separate the two operations around their independently changing behavior, sharing only the common parsing rule.
104
+
105
+ Bad: rename every class and adopt a new architecture while fixing one null check.
106
+ Good: fix the null check and simplify the surrounding redundant branch; report unrelated design debt separately.
107
+
108
+ Why: refactoring stays inside the requested change; pre-existing debt elsewhere is reported, not fixed.
109
+
110
+ **Major refactor:** a cross-module ownership change, public-contract or data migration, new dependency, or rewrite of a maintained component is outside the requested change unless the user approves it. Report the affected surfaces, benefit, and risk; a worker reports it to its lead instead of doing it. An approved large refactor ships as its own change.
111
+
112
+ ## DRY: knowledge versus resemblance
113
+
114
+ **Do:** give each business fact or invariant one authoritative representation.
115
+ **Do not:** merge code that only happens to look alike or wait for an arbitrary third occurrence when a shared rule already exists.
116
+
117
+ Bad: shipping eligibility independently encodes the same paid-status rule in API, batch, and UI code, with each copy deciding policy.
118
+ Good: put the authoritative eligibility rule in the owning domain layer; presentation can display its result. Independently deployed clients may need a contract or generated representation rather than importing server code.
119
+
120
+ Bad:
121
+
122
+ ```ts
123
+ function validateCode(value: string, mode: "coupon" | "employee") {
124
+ // Identical length today, unrelated policies and owners.
125
+ return value.length === 8;
126
+ }
127
+ ```
128
+
129
+ Good:
130
+
131
+ ```ts
132
+ function validCouponCode(value: string) { return value.length === 8; }
133
+ function validEmployeeCode(value: string) { return value.length === 8; }
134
+ ```
135
+
136
+ Why: an employee policy change must not accidentally alter coupon validation. A shared string primitive is fine; a shared business rule requires shared meaning.
137
+
138
+ **Exception:** temporary duplication during migration is acceptable with a named authoritative rule, synchronization risk, and removal condition. Do not claim two definitions are independent when they must always change together.
139
+
140
+ ## DRY: ownership across boundaries
141
+
142
+ **Do:** centralize shared contracts with their owner; generate derived schemas or clients when that removes manual drift.
143
+ **Do not:** create a cross-service "common" package that ties independent deployment and policy together merely to remove similar records.
144
+
145
+ Bad: billing and fulfillment import a giant shared `Customer` model and break on each other's internal field changes.
146
+ Good: each owns its internal representation; the shared event/API contract carries only agreed exchange data.
147
+
148
+ Why: duplication of representation can preserve separation of responsibilities; duplication of a required shared contract creates drift.
149
+
150
+ **Exception:** a single application with one ownership and release boundary can share a coherent domain type directly. Do not create adapters between every module by default.
151
+
152
+ ## DRY and KISS in tests
153
+
154
+ **Do:** share expensive setup and stable fixture construction while keeping inputs and expected behavior visible. Verify boundary semantics and invariants affected by the change.
155
+ **Do not:** calculate expected results with the same helper being tested, hide the assertion inside a generic test framework, or write tests that only mirror trivial implementation.
156
+
157
+ Bad: `expect(total(order)).toBe(order.lines.reduce(theSameReducer, 0))`.
158
+ Good: a named example with independently specified expected output, plus boundary cases when they exercise a concrete risk.
159
+
160
+ Bad: a five-layer fixture factory for three readable test records.
161
+ Good: explicit records, or one small builder for irrelevant defaults with meaningful fields visible in the test.
162
+
163
+ Why: some duplication makes test intent and independent evidence clearer.
164
+
165
+ **Exception:** a large matrix can use table-driven tests when each case remains named and inspectable. Share setup, not a second copy of the production algorithm.
@@ -0,0 +1,165 @@
1
+ # SOLID
2
+
3
+ ## Contents
4
+
5
+ - Single responsibility (SRP)
6
+ - Open/closed (OCP)
7
+ - Liskov substitution (LSP)
8
+ - Interface segregation (ISP)
9
+ - Dependency inversion (DIP)
10
+
11
+ Use these principles to protect responsibilities and contracts in any paradigm. A responsibility is a coherent reason to change, not one method or one line. Examples below are TypeScript excerpts; functions, modules, protocols, and traits can carry the same contracts.
12
+
13
+ ## Single responsibility (SRP)
14
+
15
+ **Do:** keep a coherent policy together and separate independently changing infrastructure, presentation, and business rules.
16
+ **Do not:** mix unrelated ownership or fragment every step into a service.
17
+
18
+ Bad: changing an invoice calculation requires navigating SMTP and SQL details.
19
+
20
+ ```ts
21
+ async function issueInvoice(order: Order) {
22
+ const total = order.lines.reduce((n, line) => n + line.price * line.quantity, 0);
23
+ await db.execute("INSERT INTO invoices ...", [order.id, total]);
24
+ await smtp.send({ to: order.email, html: `<p>Total: ${total}</p>` });
25
+ }
26
+ ```
27
+
28
+ Good: calculation owns pricing; orchestration composes persistence and notification boundaries.
29
+
30
+ ```ts
31
+ function invoiceTotal(lines: Line[]): number {
32
+ return lines.reduce((n, line) => n + line.price * line.quantity, 0);
33
+ }
34
+ async function issueInvoice(order: Order, save: SaveInvoice, notify: NotifyInvoice) {
35
+ const invoice = { orderId: order.id, total: invoiceTotal(order.lines) };
36
+ await save(invoice);
37
+ await notify(order.email, invoice);
38
+ }
39
+ ```
40
+
41
+ Why: policy can change without rewriting delivery details. Real money handling uses the application's money representation; these excerpts focus on responsibility boundaries. Retry/atomicity requirements still need an explicit contract.
42
+
43
+ Overengineered bad: `LinePriceGetter`, `QuantityGetter`, `LineMultiplier`, and `TotalAccumulator` classes for this reduction. Good: retain the cohesive function.
44
+
45
+ **Exception:** a short disposable export can orchestrate parsing and output in one script. Split when either becomes independently reused, stateful, or policy-heavy; not because the function calls two collaborators.
46
+
47
+ ## Open/closed (OCP)
48
+
49
+ **Do:** isolate an established axis of variation behind a stable contract.
50
+ **Do not:** create extension systems for hypothetical variants or interpret OCP as forbidding edits to existing code.
51
+
52
+ Bad: each supported payment provider adds another branch to pricing, checkout, and refunds.
53
+
54
+ ```ts
55
+ if (provider === "a") { /* A request mapping inside checkout */ }
56
+ else if (provider === "b") { /* B request mapping inside checkout */ }
57
+ // The same branching and provider formats also appear in refundOrder().
58
+ ```
59
+
60
+ Good: callers use the application contract; provider adapters own translation.
61
+
62
+ ```ts
63
+ interface Payments {
64
+ charge(request: ChargeRequest): Promise<ChargeResult>;
65
+ refund(request: RefundRequest): Promise<RefundResult>;
66
+ }
67
+ async function checkout(order: Order, payments: Payments) {
68
+ return payments.charge(toChargeRequest(order));
69
+ }
70
+ ```
71
+
72
+ Why: a new provider does not spread provider-specific conditionals through domain policy. One provider can justify this boundary when it already isolates an external dependency.
73
+
74
+ Counterexample: a closed set of three export formats is well served by an exhaustive switch in one module. Bad: runtime registration, discovery, and a plugin SDK with no extension requirement. Good: edit the switch when the closed set changes.
75
+
76
+ **Exception:** modify a stable abstraction when new requirements invalidate its contract. Migrate its callers; do not bolt on flags to preserve a misleading interface.
77
+
78
+ ## Liskov substitution (LSP)
79
+
80
+ **Do:** preserve preconditions, postconditions, errors, side effects, ordering, and ownership/lifetime expectations promised by the contract.
81
+ **Do not:** satisfy a method signature while weakening its meaning.
82
+
83
+ Bad: the advertised repository supports saving, but one subtype cannot honor it.
84
+
85
+ ```ts
86
+ interface Repository { load(id: string): Promise<Item>; save(item: Item): Promise<void> }
87
+ class ReadOnlyRepository implements Repository {
88
+ load(id: string) { return readItem(id); }
89
+ async save(_item: Item): Promise<void> { throw new Error("unsupported"); }
90
+ }
91
+ ```
92
+
93
+ Good: expose only supported capabilities.
94
+
95
+ ```ts
96
+ interface ItemReader { load(id: string): Promise<Item> }
97
+ interface ItemWriter { save(item: Item): Promise<void> }
98
+ class ReadOnlyRepository implements ItemReader {
99
+ load(id: string) { return readItem(id); }
100
+ }
101
+ ```
102
+
103
+ Second bad: replacing a writer whose resolved promise means "durably committed" with an adapter that resolves after queueing. Good: await durable completion or expose a separately named queued-write contract. Test the semantic promise, not only method presence.
104
+
105
+ Why: callers can substitute implementations without hidden branches for special cases.
106
+
107
+ **Exception:** an interface may explicitly permit unsupported operations, partial results, or different durability levels. Verify callers handle the documented result. Prefer narrower capabilities when unsupported cases otherwise dominate.
108
+
109
+ ## Interface segregation (ISP)
110
+
111
+ **Do:** give each consumer the capability it needs; group operations with a shared contract.
112
+ **Do not:** force consumers or test doubles to implement unrelated methods, or split cohesive protocols into arbitrary one-method interfaces.
113
+
114
+ Bad:
115
+
116
+ ```ts
117
+ interface UserPlatform {
118
+ findUser(id: string): Promise<User>;
119
+ deleteUser(id: string): Promise<void>;
120
+ sendCampaign(id: string): Promise<void>;
121
+ exportBilling(): Promise<Report>;
122
+ }
123
+ function displayProfile(platform: UserPlatform, id: string) { /* only finds a user */ }
124
+ ```
125
+
126
+ Good:
127
+
128
+ ```ts
129
+ interface UserLookup { findUser(id: string): Promise<User> }
130
+ function displayProfile(users: UserLookup, id: string) { /* consumes lookup only */ }
131
+ ```
132
+
133
+ Why: changes to campaigns no longer affect profile consumers or their doubles. The concrete platform can implement several focused capabilities without wrapper classes for each.
134
+
135
+ **Exception:** keep `begin/commit/rollback` together when callers rely on one transactional lifecycle. Segregation must preserve protocols and invariants.
136
+
137
+ ## Dependency inversion (DIP)
138
+
139
+ **Do:** express a domain operation's needs with domain-owned contracts and wire infrastructure at the composition boundary.
140
+ **Do not:** embed environment lookup, global clients, or vendor types in policy; do not equate inversion with a dependency-injection container.
141
+
142
+ Bad:
143
+
144
+ ```ts
145
+ async function canShip(id: string) {
146
+ const db = new VendorClient(process.env.DATABASE_URL!);
147
+ return (await db.order.findUnique({ where: { id } })).payment_status === "paid";
148
+ }
149
+ ```
150
+
151
+ Good:
152
+
153
+ ```ts
154
+ type LoadOrder = (id: string) => Promise<Order>;
155
+ async function canShip(id: string, loadOrder: LoadOrder) {
156
+ return (await loadOrder(id)).paymentStatus === "paid";
157
+ }
158
+ // The entry point supplies an adapter that maps ORM rows to Order.
159
+ ```
160
+
161
+ Why: the business rule depends on its own need; the adapter owns credentials, persistence shape, and translation. This boundary has value with one database.
162
+
163
+ Overengineered bad: interfaces for deterministic arithmetic and an IoC container resolving each one. Good: call a pure helper directly; inject capabilities where variation or side effects matter.
164
+
165
+ **Exception:** framework-owned CRUD with no separate domain policy can use the framework's ORM directly in its data/application layer. Do not add a repository that merely renames every ORM method. Reassess when persistence details leak into independently changing policy.
@@ -0,0 +1,78 @@
1
+ # Supporting principles
2
+
3
+ ## Contents
4
+
5
+ - Behavioral contracts
6
+ - Least knowledge and locality of change
7
+ - Predictability and explicit effects
8
+ - Command-query separation
9
+ - Existing coverage and limits
10
+
11
+ These are supporting checks, not a new ranking above SOLID and idiomatic encapsulation. The inclusion choices and examples are this policy's recommendations; the linked sources explain the underlying ideas. Read only the relevant section.
12
+
13
+ ## Behavioral contracts
14
+
15
+ **Do:** specify required inputs, promised results, invariants, and relevant failure/side-effect semantics at real boundaries. Validate untrusted input before domain operations.
16
+ **Do not:** rely on a matching signature when implementations differ in meaning, or add repeated checks everywhere after a boundary already establishes an invariant.
17
+
18
+ Bad: `reserve(quantity)` silently clamps negative inputs and sometimes returns success without reserving stock.
19
+ Good: reject invalid quantity at entry; define success as a completed reservation and preserve the documented failure state.
20
+
21
+ Why: callers and implementations need compatible obligations. This strengthens the existing LSP and invariant checks.
22
+
23
+ **Exception:** use ordinary types, focused tests, and concise API comments when sufficient; no contract framework or formal specification is required for a small helper.
24
+
25
+ Source: [Eiffel's Design by Contract introduction](https://www.eiffel.com/values/design-by-contract/introduction/).
26
+
27
+ ## Least knowledge and locality of change
28
+
29
+ **Do:** depend on collaborators' public meaning rather than their internal layout; keep related policy with its owner.
30
+ **Do not:** traverse a chain of implementation objects or add forwarding methods solely to satisfy a dot-count rule.
31
+
32
+ Bad: shipping reads `order.customer.record.addressTable.zoneCode` and owns the interpretation.
33
+ Good: obtain the shipping destination through the domain's public contract; representation changes remain local.
34
+
35
+ Why: a caller's knowledge of internal structure creates additional reasons it must change.
36
+
37
+ **Exception:** ordinary traversal of a transparent data record or a fluent builder is not automatically a violation. Look for representation coupling, not punctuation.
38
+
39
+ Source: [Law of Demeter, general formulation](https://www2.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/general-formulation.html).
40
+
41
+ ## Predictability and explicit effects
42
+
43
+ **Do:** use domain names, idiomatic constructs, visible I/O boundaries, explicit error outcomes, and controllable clock/randomness when behavior depends on them.
44
+ **Do not:** conceal network writes in property access or turn failed reads into success-shaped empty data.
45
+
46
+ Bad: `loadOrders()` returns an empty list after a timeout, so callers conclude there are no orders.
47
+ Good: distinguish a successful empty result from failure. A documented fallback identifies stale/partial data and its risk.
48
+
49
+ Bad: `DataManager.process(mode=4)` performs an undocumented payment capture.
50
+ Good: `capturePayment(request)` states the domain action and exposes its result/failure contract.
51
+
52
+ **Exception:** a fallback can be part of a reliability contract. Bound it and make its degraded result observable; do not crash an entire service under a blanket "fail fast" slogan.
53
+
54
+ Source: [Dan North's CUPID properties](https://dannorth.net/blog/cupid-for-joyful-coding/). Adopt predictability, idioms, and domain language as review lenses; composition and cohesive purpose are already covered here. This policy retains the user's SOLID priority rather than adopting CUPID as its replacement.
55
+
56
+ ## Command-query separation
57
+
58
+ **Do:** make inspection operations free of surprising state changes and name commands for their effects.
59
+ **Do not:** silently mutate business state from a getter or split an atomic operation into an unsafe read-then-write sequence for formal compliance.
60
+
61
+ Bad: `getBalance()` also settles pending payments.
62
+ Good: `balance()` inspects; `settlePayments()` explicitly changes state.
63
+
64
+ **Exception:** `pop()`, `next()`, atomic compare-and-swap, and create operations returning an identifier legitimately combine an effect with a result. Preserve atomicity and clear naming.
65
+
66
+ Why: callers can understand effects without inspecting each implementation. This is method/API guidance, not a requirement for CQRS infrastructure, separate databases, or event sourcing.
67
+
68
+ Sources: [Command Query Separation](https://martinfowler.com/bliki/CommandQuerySeparation.html) and [CQRS tradeoffs](https://martinfowler.com/bliki/CQRS.html), Martin Fowler.
69
+
70
+ ## Existing coverage and limits
71
+
72
+ **AHA / avoiding hasty abstractions:** already implemented by the DRY distinction between shared knowledge and coincidental similarity, and by the present-value test for abstractions. Bad: merge unrelated validators after two matching examples. Good: share only the common rule that must evolve together. Do not add a mandatory rule-of-three threshold; a real boundary can justify one implementation. See [Kent C. Dodds on AHA](https://kentcdodds.com/blog/aha-programming).
73
+
74
+ **Tell, don't ask:** already represented by invariant-owning operations. Bad: callers read and mutate account internals to perform a withdrawal. Good: the owner validates the withdrawal. Exception: DTOs, functional values, and legitimate queries need no artificial behavioral wrapper. [Fowler's discussion](https://martinfowler.com/bliki/TellDontAsk.html) also cautions against mechanically removing queries.
75
+
76
+ **Separation of concerns, high cohesion/low coupling, composition over inheritance:** covered by SRP, DIP, and encapsulation. Review those properties once rather than issuing several findings for the same root cause.
77
+
78
+ **Architectural and workflow patterns:** DDD, hexagonal architecture, CQRS, event sourcing, microservices, and mandatory TDD are not universal requirements of this policy. Evaluate a pattern against current requirements and existing conventions. Bad: install an architectural stack to satisfy a principle. Good: adopt the smallest structure that solves the concrete boundary or behavior problem.
@@ -0,0 +1,54 @@
1
+ # Telemetry: OpenTelemetry by default
2
+
3
+ Read when a change adds or touches a service, worker, consumer, CLI that calls the network, or Lambda function, or adds logs, traces or metrics. Checked 2026-11-12. These rules are language-neutral: SDK packages, bootstrap commands and signal stability for each language are in the `lang-<language>-libraries` skill's `observability.md`; Lambda specifics are in the `aws-guidance` skill.
4
+
5
+ New code emits OpenTelemetry. An existing project keeps its telemetry stack unless the task is a migration.
6
+
7
+ ## Setup
8
+
9
+ - **Bootstrap at the entry point**, before instrumented libraries load. Libraries depend on the OTel API only and never configure an SDK.
10
+ - **Identify the service:** set `service.name`, `service.version` and `deployment.environment.name`. `OTEL_SERVICE_NAME` overrides `service.name`. Review what resource detectors collect.
11
+ - **Configure through `OTEL_*` variables** where the SDK supports them. Declarative file configuration (`OTEL_CONFIG_FILE`) is experimental outside Java; do not require it.
12
+ - **Export OTLP** with `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` (port 4318) unless the deployment favours gRPC (4317), to an OpenTelemetry Collector. The Collector owns retries, filtering, redaction, tail sampling and backend routing. Export straight to a vendor only in development or in a deployment with one service and one backend.
13
+ - **Propagate** W3C `tracecontext` and `baggage` (the default `OTEL_PROPAGATORS`) at every HTTP, RPC and messaging boundary. Allowlist baggage keys.
14
+ - **Sample deliberately.** The default sampler is `parentbased_always_on`. Set `parentbased_traceidratio` with `OTEL_TRACES_SAMPLER_ARG` when volume needs it; make error- or latency-based decisions with Collector tail sampling.
15
+ - **Batch and flush.** Use batch processors in production and end every span. On exit, call a bounded flush and shutdown: CLIs and short jobs lose telemetry without it. On Lambda, flush at the end of each invocation through the Lambda-aware layer and do not shut providers down per invocation.
16
+ - **Auto-instrument boundaries, hand-instrument meaning.** Use zero-code or library instrumentation for frameworks and clients, and manual spans for business operations. Enrich an existing span before you add a duplicate.
17
+ - **Pin semantic conventions.** HTTP and database client spans are stable; messaging and GenAI conventions are in development (semantic conventions 1.45.0). Use `OTEL_SEMCONV_STABILITY_OPT_IN` values only as the installed instrumentation documents them.
18
+ - **One tracing owner.** Do not run a second tracing SDK over the same clients (for example the X-Ray SDK next to OTel, or a vendor agent that installs its own provider).
19
+
20
+ ## Spans, metrics and logs
21
+
22
+ - Name spans for the operation or route template (`GET /orders/{id}`), never with ids or user data.
23
+ - Keep metric attributes bounded: no user ids, raw URLs, request ids or free text. A span attribute may carry an id when it has diagnostic value and no privacy cost.
24
+ - When an operation fails, record the exception once, at the boundary that decides the outcome, and set the span status to error.
25
+ - Use counters for accumulated events, histograms for durations and sizes, and up-down counters for quantities that rise and fall. Keep exemplars (`OTEL_METRICS_EXEMPLAR_FILTER=trace_based`) so metric outliers link to traces.
26
+ - Logs are structured JSON with `trace_id` and `span_id` while a span is active. Bridge the existing logger into OTel instead of changing logging APIs. Ship logs one way: OTLP when there is a deliberate OTel log pipeline, otherwise stdout to the platform's collector, never both.
27
+ - Keep credentials and personal data out of attributes, events, logs and baggage. Hashing a predictable identifier does not anonymize it.
28
+ - For LLM and MCP calls, record the model, duration, token usage and failures. Keep prompts and completions out unless the user approved capturing them; several instrumentations capture content by default.
29
+
30
+ ## Test telemetry
31
+
32
+ **Do:** use the SDK's in-memory exporter with an isolated provider, a simple processor and always-on sampling. Assert span names, kinds, parentage, attributes, status, propagation and the absence of secrets.
33
+ **Do not:** assert timestamps or random ids, or share a global provider between tests.
34
+
35
+ ## Anti-patterns
36
+
37
+ - A span per loop iteration without diagnostic value.
38
+ - Unbounded metric attributes or dynamic span names.
39
+ - Vendor-specific instrumentation as the only integration path instead of OTLP.
40
+ - Exiting without a flush.
41
+
42
+ ## Sources
43
+
44
+ - SDK status per language: https://opentelemetry.io/docs/languages/
45
+ - SDK environment variables: https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
46
+ - OTLP exporter configuration: https://opentelemetry.io/docs/specs/otel/protocol/exporter/
47
+ - Collector: https://opentelemetry.io/docs/collector/
48
+ - Sampling: https://opentelemetry.io/docs/concepts/sampling/
49
+ - Trace API naming rules: https://opentelemetry.io/docs/specs/otel/trace/api/
50
+ - Exceptions: https://opentelemetry.io/docs/specs/otel/trace/exceptions/
51
+ - Metrics API: https://opentelemetry.io/docs/specs/otel/metrics/api/
52
+ - Semantic conventions 1.45.0: https://github.com/open-telemetry/semantic-conventions/releases/tag/v1.45.0
53
+ - Sensitive data: https://opentelemetry.io/docs/security/handling-sensitive-data/
54
+ - GenAI conventions: https://opentelemetry.io/docs/specs/semconv/gen-ai/
@@ -0,0 +1,78 @@
1
+ # Test-first loop
2
+
3
+ Read when the user asks for test-first work, red-green-refactor, or TDD. What makes a
4
+ test worth keeping (public behavior, independent expected values, fidelity, mocks only at
5
+ boundaries) is in [verification.md](verification.md) and the `quality-testing` skill; this
6
+ guide covers the loop.
7
+
8
+ ## Vertical slices
9
+
10
+ **Do:** work in tracer bullets: one test, one minimal implementation, repeat. Each test
11
+ answers to what the previous cycle taught you.
12
+ **Do not:** write all the tests first and then all the implementation. Bulk tests verify
13
+ imagined behavior: they test the shape of things, commit to a test structure before the
14
+ implementation is understood, and stay green through real changes.
15
+
16
+ ## Tools for the loop
17
+
18
+ Take the tools from the language's table in the `toolchain-languages` skill's
19
+ [concerns.md](https://github.com/srobroek/harness-plugins/blob/main/plugins/toolchain/common/skills/toolchain-languages/references/concerns.md) registry:
20
+ the `watch` row for the red-green loop and affected-test selection, and the `assertions` row for
21
+ the matcher and diff helpers. Keep the project's existing tool unless the task is a migration.
22
+
23
+ ## Pick the seams
24
+
25
+ Before the first test, name the seams the tests will use: the public interfaces that the
26
+ behavior passes through. For each, state in one line what a test there catches and what
27
+ it misses, such as "the `checkout` function: catches pricing and discount rules; misses
28
+ the HTTP mapping and the SQL". Prefer existing seams and few of them. When the interface
29
+ itself is unsettled or the scope is large, agree the seams with the user or the lead
30
+ first; otherwise proceed and report them.
31
+
32
+ ## Red, green, refactor
33
+
34
+ 1. **Red:** write the failing test first and watch it fail for the expected reason. A test
35
+ that passes before the change proves nothing about it. Each cycle tests one behavior,
36
+ with one logical assertion, through the public interface: check a write through the
37
+ code's own read operation, not by querying the store behind it.
38
+ 2. **Green:** write only enough code to pass it. No anticipated future tests, no
39
+ speculative features.
40
+ 3. **Refactor:** with the tests green, simplify the code this cycle touched, within the
41
+ change's scope. Re-run the tests after each step.
42
+
43
+ When the behavior already exists and the test passes at once, force the red: break the
44
+ code or the fixture on purpose, watch the test fail, then restore it. Diff the file
45
+ against a pristine copy (`git diff`, or a copy taken before the edit) to prove that the
46
+ break landed and that the restore removed it.
47
+
48
+ ## Make boundaries mockable
49
+
50
+ At a system boundary, inject the client and give each external operation its own
51
+ function, rather than one generic fetcher the mock must branch inside.
52
+
53
+ Bad:
54
+
55
+ ```ts
56
+ const api = { fetch: (endpoint: string, options?: RequestInit) => fetch(endpoint, options) };
57
+ // Each test's mock switches on endpoint and method to fake the right response.
58
+ ```
59
+
60
+ Good:
61
+
62
+ ```ts
63
+ const api = {
64
+ getUser: (id: string) => fetch(`/users/${id}`),
65
+ getOrders: (userId: string) => fetch(`/users/${userId}/orders`),
66
+ createOrder: (data: NewOrder) => fetch("/orders", { method: "POST", body: JSON.stringify(data) }),
67
+ };
68
+ function processPayment(order: Order, paymentClient: PaymentClient) {
69
+ return paymentClient.charge(order.total);
70
+ }
71
+ ```
72
+
73
+ Why: each mock returns one shape with no conditional logic, a test shows which endpoints
74
+ it exercises, and each endpoint keeps its own types. Whether the boundary deserves a port
75
+ at all follows the seam rule in [deep-modules.md](deep-modules.md).
76
+
77
+ **Exception:** a one-off script calling one endpoint needs no client object; call it
78
+ directly and test the script's observable result.
@@ -0,0 +1,93 @@
1
+ # TypeScript and JavaScript: conditional language guidance
2
+
3
+ Load only when the task designs, investigates, changes, or reviews TypeScript or JavaScript code. Format, lint, type-check and test commands live in the language plugin's skills when installed.
4
+
5
+ ## Functions and modules before classes
6
+
7
+ **Do:** use modules, functions, structural types, and discriminated unions for stateless behavior and closed variants; use classes for owned state and lifecycle.
8
+ **Do not:** implement a class hierarchy merely to get polymorphism, or mistake static types for runtime input validation.
9
+
10
+ Bad:
11
+
12
+ ```ts
13
+ class UppercaseService { run(value: string) { return value.toUpperCase(); } }
14
+ class UppercaseFactory { create() { return new UppercaseService(); } }
15
+ ```
16
+
17
+ Good:
18
+
19
+ ```ts
20
+ const uppercase = (value: string): string => value.toUpperCase();
21
+ ```
22
+
23
+ When locale policy, caching, or I/O is added, reassess responsibilities and dependencies. A callback or explicit options value can still be simpler than an object.
24
+
25
+ **Exception:** a framework's lifecycle requires an injectable class. Use its normal convention; do not build factories around a class the framework already constructs.
26
+
27
+ ## Closed variants: discriminated unions, checked exhaustively
28
+
29
+ **Do:** model states as a union with a literal `kind` (or `type`) field, one payload per state, and end every `switch` over it with an exhaustiveness check.
30
+ **Do not:** use `status: string` plus optional fields that are only meaningful in some states.
31
+
32
+ ```ts
33
+ type Job =
34
+ | { kind: "pending" }
35
+ | { kind: "running"; startedAt: Date }
36
+ | { kind: "finished"; result: JobResult };
37
+
38
+ function label(job: Job): string {
39
+ switch (job.kind) {
40
+ case "pending": return "queued";
41
+ case "running": return `since ${job.startedAt.toISOString()}`;
42
+ case "finished": return job.result.summary;
43
+ default: return assertNever(job);
44
+ }
45
+ }
46
+ const assertNever = (value: never): never => { throw new Error(`unhandled: ${JSON.stringify(value)}`); };
47
+ ```
48
+
49
+ Why: a new variant becomes a compile error at every switch that forgot it.
50
+
51
+ ## Validated values: branded types
52
+
53
+ **Do:** give IDs and validated values a brand so a raw `string` cannot be passed where an `OrderId` or `Email` is required. Create them only through a parser. With zod, `.brand()` does both.
54
+ **Do not:** cast with `as OrderId` outside the one constructor, or brand values that carry no invariant.
55
+
56
+ ```ts
57
+ const Email = z.string().email().brand<"Email">();
58
+ type Email = z.infer<typeof Email>;
59
+ function invite(to: Email) { /* … */ }
60
+ invite(Email.parse(input.email)); // invite(input.email) is a type error
61
+ ```
62
+
63
+ Parse at trust boundaries (HTTP, IPC, config, storage) and pass the branded type inward; do not re-parse already-typed internal values.
64
+
65
+ ## Errors keep their cause
66
+
67
+ **Do:** throw `Error` subclasses (or return a typed result union) with a stable `name` or `code` callers can branch on, and chain the underlying failure with `{ cause }`.
68
+ **Do not:** throw strings, rethrow with a new message that drops the original, or catch everything and return `undefined`.
69
+
70
+ ```ts
71
+ class ConfigError extends Error { override name = "ConfigError"; }
72
+ try { return JSON.parse(await readFile(path, "utf8")); }
73
+ catch (error) { throw new ConfigError(`cannot load ${path}`, { cause: error }); }
74
+ ```
75
+
76
+ Why: `cause` keeps the original stack for diagnosis while the outer error carries the domain meaning.
77
+
78
+ **Exception:** at a process or request edge, catching all errors to log and map them to an exit code or response is the correct boundary handling.
79
+
80
+ ## Stubs behind a contract interface
81
+
82
+ **Do:** implement the contract's interface in the stub, import the shared (generated) types, and mark it.
83
+
84
+ ```ts
85
+ import type { Quote, Quotes } from "@acme/contract"; // shared types, never redefined here
86
+
87
+ // STUB(task-id): always unsupported; real pricing service not built yet
88
+ export const stubQuotes: Quotes = {
89
+ async quote(): Promise<Quote> { throw new Error("pricing is not yet supported"); },
90
+ };
91
+ ```
92
+
93
+ Consumers accept `Quotes`; a swap changes the wiring. See [contracts.md](contracts.md).