@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,148 @@
1
+ # OOP principles and their equivalents
2
+
3
+ ## Contents
4
+
5
+ - Encapsulation and information hiding
6
+ - Valid state and invariants
7
+ - Abstraction
8
+ - Inheritance and substitutability
9
+ - Polymorphism
10
+ - Composition and coupling
11
+
12
+ Use objects when they bind meaningful state and behavior. Use modules, packages, pure functions, and types when those express the design more directly. OOPS is not a requirement to turn every function into a class.
13
+
14
+ ## Encapsulation and information hiding
15
+
16
+ **Do:** expose operations and stable meaning; keep representation and mutation ownership private.
17
+ **Do not:** treat getters/setters as encapsulation when they expose unrestricted mutation.
18
+
19
+ Bad:
20
+
21
+ ```ts
22
+ class Cart { items: Line[] = []; }
23
+ cart.items.push({ sku: "a", quantity: -5 });
24
+ ```
25
+
26
+ Good:
27
+
28
+ ```ts
29
+ class Cart {
30
+ #items: Line[] = [];
31
+ add(sku: string, quantity: number) {
32
+ if (!Number.isInteger(quantity) || quantity <= 0) throw new Error("invalid quantity");
33
+ this.#items.push({ sku, quantity });
34
+ }
35
+ snapshot(): ReadonlyArray<Readonly<Line>> {
36
+ return this.#items.map(item => ({ ...item }));
37
+ }
38
+ }
39
+ ```
40
+
41
+ Why: the owner controls mutation; callers cannot change these flat stored records through a returned alias. Nested mutable values need deliberate copying or immutable representation too.
42
+
43
+ **Exception:** plain data-transfer records need no behavioral class when they have no owned invariants. Validate untrusted input at the boundary; use read-only or copied values where ownership requires it.
44
+
45
+ ## Valid state and invariants
46
+
47
+ **Do:** establish invariants in construction and preserve them during transitions. Make invalid states unrepresentable when the language permits it.
48
+ **Do not:** rely on every caller remembering a multi-step setup protocol.
49
+
50
+ Bad:
51
+
52
+ ```ts
53
+ type Job = { running: boolean; finished: boolean; result?: Result };
54
+ const job = { running: true, finished: true }; // contradictory
55
+ ```
56
+
57
+ Good:
58
+
59
+ ```ts
60
+ type Job =
61
+ | { state: "pending" }
62
+ | { state: "running"; startedAt: Date }
63
+ | { state: "finished"; result: Result };
64
+ ```
65
+
66
+ Why: each state carries what its consumers may rely on. Constructors/factories validate runtime values; type declarations alone do not validate incoming JSON.
67
+
68
+ **Exception:** a serializer or database layer can use a loose intermediate record. Convert and validate before handing it to domain code; do not spread the intermediate representation across the application.
69
+
70
+ ## Abstraction
71
+
72
+ **Do:** name operations in the consumer's vocabulary and hide decisions likely to change independently.
73
+ **Do not:** create empty wrappers or expose internals through a supposedly stable contract.
74
+
75
+ Bad:
76
+
77
+ ```ts
78
+ interface Orders { query(sql: string): Promise<VendorRow[]> }
79
+ // Every consumer still knows tables, columns, and vendor row conventions.
80
+ ```
81
+
82
+ Good:
83
+
84
+ ```ts
85
+ interface Orders { findReadyToShip(): Promise<ReadyOrder[]> }
86
+ ```
87
+
88
+ Why: the contract expresses the application's need. A module-exported function can do the same job; an interface is not mandatory.
89
+
90
+ **Exception:** SQL is the correct public abstraction for a SQL execution tool. Judge the actual consumer, not a universal ban on low-level APIs.
91
+
92
+ ## Inheritance and substitutability
93
+
94
+ **Do:** inherit only when the subtype honors the base contract and the lifecycle is designed for extension.
95
+ **Do not:** inherit just to reuse implementation or build combinatorial hierarchies.
96
+
97
+ Bad: `ReadOnlyFile extends WritableFile` overrides `write()` to fail; callers must inspect concrete types. Good: separate readable and writable capabilities, or wrap a readable handle.
98
+
99
+ Bad: `CachedEncryptedRemoteStore extends EncryptedRemoteStore extends RemoteStore` couples ordering and transport. Good: explicit decorators around a common store contract when all three behaviors are required.
100
+
101
+ Why: composition permits changing one concern without inheriting unrelated public behavior. Decorators still must preserve error, ordering, and durability semantics.
102
+
103
+ **Exception:** framework extension points or a shallow, stable subtype hierarchy can be simpler than a parallel adapter system. Honor documented base-class hooks and LSP; do not replace valid inheritance for compliance alone.
104
+
105
+ ## Polymorphism
106
+
107
+ **Do:** choose dispatch that matches whether variants are open or closed.
108
+ **Do not:** scatter concrete-type checks or assume runtime interface dispatch is always superior.
109
+
110
+ Bad: handlers throughout the application use `instanceof EmailNotice` and `instanceof SmsNotice` and duplicate delivery logic.
111
+
112
+ Good for an open extension boundary:
113
+
114
+ ```ts
115
+ type SendNotice = (notice: Notice) => Promise<void>;
116
+ async function notify(notice: Notice, send: SendNotice) { await send(notice); }
117
+ ```
118
+
119
+ Good for a closed domain:
120
+
121
+ ```ts
122
+ type Shape = { kind: "circle"; radius: number } | { kind: "square"; side: number };
123
+ function area(shape: Shape): number {
124
+ switch (shape.kind) {
125
+ case "circle": return Math.PI * shape.radius ** 2;
126
+ case "square": return shape.side ** 2;
127
+ }
128
+ }
129
+ ```
130
+
131
+ Why: callbacks, interfaces, traits, and exhaustive matching are alternative ways of expressing variation.
132
+
133
+ **Exception:** a localized type check at a parsing or adaptation boundary is legitimate. Repeated checks in domain consumers signal a missing contract.
134
+
135
+ ## Composition and coupling
136
+
137
+ **Do:** pass collaborators explicitly and give each mutable resource an owner. Keep access through a collaborator's public contract.
138
+ **Do not:** use global service locators, pass the entire application context to every function, or navigate other modules' internals.
139
+
140
+ Bad: `app.services.database.connection.driver.orders...` inside shipping policy.
141
+ Good: pass `loadOrder` or `orders` to the shipping operation, with configuration and connection lifetime owned by the entry point.
142
+
143
+ Bad: a two-line string normalizer needs `NormalizerFactory`, `NormalizerService`, and `NormalizerRegistry`.
144
+ Good: `normalizeName(text)` remains a pure function. Revisit when it gains locale policy, mutable state, or external dependencies; do not automatically add classes.
145
+
146
+ Why: explicit dependencies make later extraction practical without speculative extension machinery.
147
+
148
+ **Exception:** established framework context can be appropriate inside framework adapters. Narrow what crosses into independent policy code.
@@ -0,0 +1,189 @@
1
+ # Feature flags: code and storage
2
+
3
+ Read when adding, evaluating, storing, rolling out or removing a feature flag.
4
+ The process lives in `trunk-dev-feature-flags`; AWS service specifics live in
5
+ `aws-guidance`; SDK packages live in `lang-<language>-libraries`, `runtime.md`
6
+ and `aws.md`. These rules are language-neutral. Facts checked 2026-11-12.
7
+
8
+ ## Name the kind and lifetime
9
+
10
+ | Kind | Purpose | Lifetime |
11
+ | --- | --- | --- |
12
+ | Release | Hide incomplete work, then roll it out | Remove after rollout or abandonment |
13
+ | Experiment | Compare stable cohorts and measured outcomes | Remove after the decision |
14
+ | Operational kill switch | Stop a risky path without deploying | Temporary, or reviewed with a runbook |
15
+ | Permission | Restrict access to an already-authorized capability | Review while the restriction exists |
16
+
17
+ **Do:** keep entitlements, tenant permissions and authorization in domain data
18
+ and policy. A rollout flag may restrict an authorized capability, never grant one.
19
+ **Do not:** use a disposable flag as proof of paid access or security permission.
20
+ Permission here means an extra rollout restriction, not the source of authority.
21
+
22
+ Static configuration, secrets and build-time constants are not rollout flags.
23
+ Connection settings belong in config; secrets belong in secret storage. A build
24
+ constant requires a rebuild and cannot serve as a runtime kill switch.
25
+
26
+ ## One flag module
27
+
28
+ **Do:** define typed keys, value types, defaults and metadata (owner, kind, expiry
29
+ or review date) in one module. Feature code calls that module, never environment,
30
+ config, SSM or AppConfig directly. Keep boolean and variant types explicit.
31
+ **Do not:** scatter string keys, backend reads or fallback values across callers.
32
+
33
+ Applications, services and CLIs use the OpenFeature client through that module,
34
+ with one provider over the backend chosen below. If no maintained provider exists
35
+ for the backend in that language, stop and ask before writing one; never silently
36
+ substitute a backend wrapper. Review third-party providers as dependencies.
37
+ A provider swap keeps the API; targeting, bucketing and analytics need separate
38
+ migration checks. Verify context mappings and behavior before migration.
39
+
40
+ **Exception:** OpenCode plugins keep plugin options: the host config is their backend.
41
+ Libraries take decisions from their caller and never evaluate flags.
42
+
43
+ ## Decide at the edge, inject the decision
44
+
45
+ The toggle router decides why a variant applies; the toggle point selects behavior.
46
+ **Do:** evaluate once per request or job at the boundary, after authentication.
47
+ Pass an immutable decision object or selected strategy into business code.
48
+ For a large replacement, branch by abstraction: select the implementation once.
49
+ **Do not:** evaluate in hot loops or nest flags. If an interaction is needed, name
50
+ the combined decision and test it explicitly.
51
+
52
+ Bad: each item in a batch fetches `new-pricing` and picks a different implementation.
53
+ Good: the job boundary selects one pricing strategy and passes it to the processor.
54
+
55
+ ## Defaults and outages
56
+
57
+ **Do:** default a release flag to existing behavior, normally off. Choose the outage
58
+ default per flag; `false` is unsafe when the flag disables a protection. Record
59
+ whether failures serve last-known-good data or the fallback, and the maximum
60
+ acceptable staleness. Define what happens after that limit, not just a cache TTL.
61
+ **Do not:** assume every SDK or provider returns a supplied default on error.
62
+ The Rust SDK returns an error that the flag module maps to the chosen default.
63
+
64
+ Bad: backend failure sets `enforce-validation` to `false` and bypasses validation.
65
+ Good: the outage default preserves validation, with a visible fallback reason.
66
+
67
+ ## Context and stable cohorts
68
+
69
+ **Do:** use an authenticated, stable targeting key. Bucket by tenant when everyone
70
+ in a tenant must see the same variant. Allowlist context fields and verify how the
71
+ provider maps them. Treat client-supplied tenant ids as untrusted until validated.
72
+ **Do not:** assign variants with per-request randomness or use secrets in context.
73
+ An experiment needs stable exposure attribution as well as an evaluation result.
74
+
75
+ ## Initialization and caching
76
+
77
+ **Do:** initialize the client once, bound the startup wait, refresh in the background
78
+ and dispose background work on shutdown. Monitor readiness and cache age.
79
+ Test cold startup without a cache separately from refresh failure with a cache.
80
+ **Do not:** promise instant fleet changes. Check provider retrieval and cache behavior.
81
+
82
+ AppConfig Agent, including its Lambda extension, polls every 45 seconds by default
83
+ and serves the cached value when a refresh times out (checked 2026-11-12).
84
+ Choose a poll interval and staleness budget that meet the kill switch's response time.
85
+
86
+ ## Choose the backend by need
87
+
88
+ | Need | Store | Who owns the definition |
89
+ | --- | --- | --- |
90
+ | Local development, CLIs, services outside AWS, or flags changed with a deploy | Repository `flags.yaml` in flagd format | Code/config owner, reviewed in Git |
91
+ | Simple runtime on/off toggles on AWS without staged rollout | SSM Parameter Store | IaC resources; audited operator values |
92
+ | Kill switches, gradual or percentage rollout | AppConfig feature flag profile through the Agent | Reviewed deployments with validators, strategies and alarm rollback |
93
+
94
+ Entitlements and tenant permissions stay in the domain database, for example
95
+ DynamoDB; they are not flags. Keep an existing repository flag service. Adding a
96
+ hosted flag service needs approval. Experiments need exposure and outcome metrics;
97
+ choosing an experiment platform needs approval. An SDK is not statistics.
98
+
99
+ **Do:** let IaC (`CDK` or `Terraform`) own applications, environments, profiles,
100
+ validators, deployment strategies and IAM. Say who changes live values, retain an
101
+ audit trail and separate production from development. Reconcile emergency changes
102
+ explicitly before the next apply.
103
+ **Do not:** let IaC silently overwrite an emergency change or put secrets in payloads.
104
+
105
+ CloudWatch Evidently was discontinued in October 2025; use AppConfig. AWS's API
106
+ notice says October 16 and its announcement says October 17 (checked 2026-11-12).
107
+ See `aws-guidance` for prices, quotas and the distinction between native AppConfig
108
+ flags and Python Powertools Feature Flags' freeform rules. Do not stack rule engines.
109
+
110
+ ## flags.yaml
111
+
112
+ Use the flagd flag-definition format: top-level `flags`, each with `state`
113
+ (`ENABLED` or `DISABLED`), same-typed `variants`, an explicit `defaultVariant`,
114
+ and optional JsonLogic `targeting` that returns a variant name.
115
+
116
+ ```yaml
117
+ $schema: https://flagd.dev/schema/v0/flags.json
118
+ flags:
119
+ new-ui:
120
+ state: ENABLED
121
+ variants: {"on": true, "off": false}
122
+ defaultVariant: "off"
123
+ ```
124
+
125
+ Node and Rust file providers accept JSON only. Generate `flags.json` from
126
+ `flags.yaml` during the build and check for drift; do not maintain two definitions.
127
+ Offline flagd file providers poll every 5 seconds by default.
128
+
129
+ ## Providers
130
+
131
+ Provider facts checked 2026-11-12. "Ask first" means no maintained provider was
132
+ found: stop and ask the user before writing one, not a silent wrapper fallback.
133
+
134
+ | Language | flags.yaml | SSM | AppConfig |
135
+ | --- | --- | --- | --- |
136
+ | Python | `openfeature-provider-flagd` `0.6`, `ResolverType.FILE`, `offline_flag_source_path`; YAML requires `.yaml` | `openfeature-provider-aws-ssm` `0.1` (contrib); set TTL cache, default LRU has no timed refresh | Ask first; provider would read Agent HTTP |
137
+ | TypeScript (Node) | `@openfeature/flagd-provider` `0.18`, in-process, `offlineFlagSourcePath`; generated JSON | `@openfeature/aws-ssm-provider` `0.1`; cache off by default, only boolean/string results cached | Ask first |
138
+ | Go | Contrib `providers/flagd` `0.8`, `WithOfflineFilePath`; `.yaml`, `.yml`, `.json` | Contrib `providers/aws-ssm` `1.0`; `GetParameter` every evaluation, no cache, shared 40 TPS default; evaluate once per request; object flags return default | Third-party `github.com/Arthur1/openfeature-provider-go-aws-appconfig` `0.4`; Agent only, boolean flags; dependency review required |
139
+ | Rust | `open-feature-flagd` `0.3`, file resolver; generated JSON | Ask first | Ask first |
140
+ | Browser | No local file; evaluate on server and send decisions, or ask first | Same | Same; never expose AWS credentials or Agent |
141
+
142
+ An approved custom provider uses `FLAG_NOT_FOUND`, `TYPE_MISMATCH`, `PARSE_ERROR`
143
+ and `GENERAL`, never a silent false. The Agent endpoint is
144
+ `http://localhost:2772/applications/<app>/environments/<env>/configurations/<profile>`;
145
+ use `?flag=<key>` for one flag and `Context: key=value` headers for multi-variant evaluation.
146
+
147
+ ## Test decisions and failures
148
+
149
+ **Do:** test default and new states, plus named interactions, not every combination.
150
+ Test the outage default, missing key, wrong type and stale-cache boundary. Use the
151
+ SDK's in-memory provider or inject the decision; do not require a backend in unit tests.
152
+ Python uses `InMemoryProvider` from `openfeature.provider.in_memory_provider`, JS
153
+ uses the SDK's `InMemoryProvider`, and Go uses `memprovider.NewInMemoryProvider`.
154
+ Rust `0.3` has no shipped in-memory provider; use `MockFeatureProvider` with `test-util`.
155
+ **Do not:** test only the enabled branch or assume a missing key is always harmless.
156
+ Use the `quality-testing` skill for test level, doubles and integration coverage.
157
+
158
+ ## Observe the rollout
159
+
160
+ **Do:** log evaluations or emit the OpenTelemetry `feature_flag.evaluation` event.
161
+ Use `feature_flag.key`, `feature_flag.result.value`, `feature_flag.result.variant`,
162
+ `feature_flag.result.reason`, `feature_flag.provider.name`, `feature_flag.version`
163
+ and `error.type` where available. The conventions are release candidate as of
164
+ 2026-11-12; avoid deprecated `feature_flag.variant` and `feature_flag.evaluation.reason`.
165
+ Compare error, latency and business metrics by variant, and tie rollout to alarms.
166
+ **Do not:** use user ids as metric dimensions or log sensitive targeting context.
167
+ See [telemetry.md](telemetry.md) for setup, cardinality and privacy rules.
168
+
169
+ ## Remove the flag and dead path together
170
+
171
+ **Do:** record owner, kind and expiry or review date for every flag. When rolled out
172
+ or abandoned, delete the dead branch, its tests and the definition in one change.
173
+ Long-lived kill switches get a review date and runbook. Uber `PolyglotPiranha` can
174
+ automate dead-branch removal; review its output and run the relevant tests.
175
+ **Do not:** leave permanent release flags or two implementations without an owner.
176
+
177
+ ## Sources
178
+
179
+ - Toggle kinds and architecture: https://martinfowler.com/articles/feature-toggles.html
180
+ - OpenFeature evaluation: https://openfeature.dev/specification/sections/flag-evaluation/
181
+ - flagd definitions and file providers: https://flagd.dev/reference/flag-definitions/ and https://flagd.dev/providers/
182
+ - Rust SDK and error handling: https://openfeature.dev/docs/reference/sdks/server/rust/
183
+ - Provider portability limits: https://docs.growthbook.io/lib/openfeature
184
+ - AppConfig Agent: https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-agent-how-to-use.html
185
+ - Lambda caching: https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-integration-lambda-extensions-config.html
186
+ - AWS pricing: https://aws.amazon.com/systems-manager/pricing/
187
+ - Evaluation events: https://opentelemetry.io/docs/specs/semconv/feature-flags/feature-flags-events
188
+ - Deprecated attributes: https://opentelemetry.io/docs/specs/semconv/registry/attributes/feature-flag
189
+ - Removal tooling: https://github.com/uber/piranha/blob/master/README.md
@@ -0,0 +1,110 @@
1
+ # Go: conditional language guidance
2
+
3
+ Load only when the task designs, investigates, changes, or reviews Go code. Do not impose Java-style hierarchies on Go.
4
+
5
+ Language reference: [Effective Go](https://go.dev/doc/effective_go) for core idioms; use the project's Go version documentation for newer language features.
6
+
7
+ ## Consumer-owned interfaces and concrete implementations
8
+
9
+ **Do:** use small interfaces at actual consumer boundaries; return concrete types when callers benefit from their concrete API.
10
+ **Do not:** define an interface beside every struct automatically or build a DI framework to pass two dependencies.
11
+
12
+ Bad:
13
+
14
+ ```go
15
+ type UserServiceInterface interface {
16
+ Find(context.Context, string) (User, error)
17
+ Delete(context.Context, string) error
18
+ ExportBilling(context.Context) ([]byte, error)
19
+ }
20
+ // A profile renderer now requires unrelated capabilities.
21
+ ```
22
+
23
+ Good, in the consuming package:
24
+
25
+ ```go
26
+ type UserFinder interface {
27
+ Find(context.Context, string) (User, error)
28
+ }
29
+ type Profile struct { users UserFinder }
30
+ func NewProfile(users UserFinder) *Profile { return &Profile{users: users} }
31
+ ```
32
+
33
+ Why: implicit satisfaction lets an adapter meet the consumer's contract without coupling the provider to it. Whether the boundary needs an interface at all follows the seam rule in [deep-modules.md](deep-modules.md); interface count is not a quality metric.
34
+
35
+ **Exception:** a pure function or local concrete helper needs no interface. A shared protocol can own an interface when it has coherent cross-consumer semantics; do not duplicate identical contracts as a ritual.
36
+
37
+ ## Structs, methods, privacy, and composition
38
+
39
+ **Do:** keep invariant-bearing fields unexported and use methods for valid transitions. Use explicit fields for composition unless embedding's promoted API is intentional.
40
+ **Do not:** embed for accidental inheritance or return mutable internals without an ownership decision.
41
+
42
+ Bad:
43
+
44
+ ```go
45
+ type Queue struct { Items []Job }
46
+ // Callers can replace the backing slice and bypass scheduling invariants.
47
+ ```
48
+
49
+ Good:
50
+
51
+ ```go
52
+ type Queue struct { items []Job }
53
+ func (q *Queue) Snapshot() []Job { return append([]Job(nil), q.items...) }
54
+ // Enqueue validates the job and owns the mutation.
55
+ ```
56
+
57
+ Why: the slice backing array is no longer shared by the snapshot. If Job contains pointers or maps, copy or make those values immutable too. Define whether concurrent access is supported; private fields alone do not make it safe.
58
+
59
+ **Exception:** exported structs suit plain data and configuration without hidden lifecycle invariants. Preserve useful zero values when possible; use constructors when valid initialization requires validation or resources.
60
+
61
+ ## Packages, errors, and contract preservation
62
+
63
+ **Do:** organize packages by coherent responsibility, keep dependencies acyclic, accept cancellation where I/O needs it, and preserve meaningful errors.
64
+ **Do not:** create a catch-all `utils` package, hide request context in global state, or replace errors with success-shaped zero values.
65
+
66
+ Bad:
67
+
68
+ ```go
69
+ user, _ := store.Find(ctx, id)
70
+ return user // missing and unavailable become indistinguishable
71
+ ```
72
+
73
+ Good:
74
+
75
+ ```go
76
+ user, err := store.Find(ctx, id)
77
+ if err != nil { return User{}, fmt.Errorf("find user: %w", err) }
78
+ return user, nil
79
+ ```
80
+
81
+ Why: wrapped errors preserve inspection with `errors.Is`/`errors.As`. The boundary still needs to define not-found semantics and whether concrete provider errors cross it.
82
+
83
+ **Exception:** translate infrastructure errors into domain errors at a boundary when callers should not depend on the provider. Preserve diagnostic context without making implementation details part of the domain contract.
84
+
85
+ ## Keep small Go tools small
86
+
87
+ Bad: `CommandFactory`, `RunnerProvider`, and a generic repository for a CLI that reads one file and writes one report.
88
+ Good: parse flags in `main`, call one transformation function, and handle I/O errors at the edge. Add a package when a coherent responsibility actually needs separation.
89
+
90
+ **Do:** revisit this structure as behavior grows.
91
+ **Do not:** equate one consumer with "no useful boundary," or multiple files with maintainability.
92
+
93
+ **Exception:** an established CLI framework can reduce present flag/subcommand complexity. Use its ordinary conventions without inventing a second framework around it.
94
+
95
+ ## Stubs behind a contract interface
96
+
97
+ **Do:** satisfy the contract's interface in the stub, import the shared types from the contract package, and mark it.
98
+
99
+ ```go
100
+ // STUB(task-id): always unsupported; real pricing service not built yet
101
+ type stubQuotes struct{}
102
+
103
+ var _ contract.Quotes = stubQuotes{} // compile-time conformance; contract.Quote is the shared type
104
+
105
+ func (stubQuotes) Quote(ctx context.Context, sku string) (contract.Quote, error) {
106
+ return contract.Quote{}, contract.ErrUnsupported
107
+ }
108
+ ```
109
+
110
+ See [contracts.md](contracts.md).
@@ -0,0 +1,66 @@
1
+ # Planning and feedback
2
+
3
+ Read for uncertain scope, work sequencing, consequential decisions, domain terminology, or recurring delivery problems. Keep the main design priorities; these practices add no mandatory project methodology.
4
+
5
+ ## Scale by consequences
6
+
7
+ **Do:** identify the observable result, affected contracts, uncertainty, blast radius, and recovery difficulty before choosing workflow depth. Preserve project-required records and checks.
8
+ **Do not:** infer safety from file count, line count, or the label "script"; require a full specification for a known local edit.
9
+
10
+ Bad: a one-line tenant authorization change receives only a syntax check.
11
+ Good: inspect the access boundary and verify allowed and denied cases, including cross-tenant access.
12
+
13
+ Bad: a mechanical rename requires a new architecture document.
14
+ Good: confirm callers with available tooling, run the relevant checks, and keep a brief acceptance note.
15
+
16
+ **Exception:** regulated or project-mandated records still apply. State the actual requirement rather than inventing a gate.
17
+
18
+ ## Small coherent batches
19
+
20
+ **Do:** split work into independently understandable, verifiable changes; keep dependent edits together unless an intermediate state remains compatible. Integrate frequently within the project's branch/review policy.
21
+ **Do not:** combine unrelated cleanup with a fix, or split a shared contract from its callers into broken intermediate commits.
22
+
23
+ Bad: an authentication fix also replaces the ORM and reformats the repository.
24
+ Good: keep the fix and its directly enabling simplification together; sequence the wider migration separately with acceptance for each increment.
25
+
26
+ Bad: require direct pushes to main or a deployment quota to claim continuous integration.
27
+ Good: use short-lived branches and fast feedback while retaining required reviews and checks.
28
+
29
+ **Exception:** a cohesive atomic change can be large. Explain why splitting would reduce correctness or reviewability. A major refactor still needs the user's approval ([simplicity.md](simplicity.md)).
30
+
31
+ ## Durable decisions
32
+
33
+ **Do:** record a decision only when all three hold: it is hard to reverse, it would surprise a future reader without context, and it came from a real trade-off between genuine alternatives. Typical cases: architectural shape, integration patterns between contexts, technology choices with lock-in, boundary and ownership decisions, deliberate deviations from the obvious path, constraints invisible in the code, and non-obvious rejected alternatives. Record context, decision, and why in a paragraph; add status, considered options, or consequences only when they carry information.
34
+ **Do not:** document every helper function, or treat an old exception as permanent permission.
35
+
36
+ Bad: "Temporary direct SQL" remains the only rationale after a disposable importer becomes a service.
37
+ Good: revisit transaction ownership, schema coupling, and verification when the importer gains long-lived consumers; update or supersede its decision record.
38
+
39
+ Where: reuse the project's existing decision-record convention. With none, use `docs/decisions.md` or `docs/decisions/NNNN-slug.md`, never a new `docs/adr/`. Numbered records have one numbering owner: in a multi-agent run the lead assigns the number and workers propose the record. Retain superseded rationale.
40
+
41
+ **Exception:** a local comment or task note suffices when the tradeoff is small and understandable. A decision record is a format for significant decisions, not a prerequisite for coding.
42
+
43
+ ## Domain terms
44
+
45
+ - Challenge a term that conflicts with the project's existing glossary or code names, and propose one canonical term for a vague or overloaded one ("account": Customer or User?).
46
+ - Stress-test stated domain relationships with concrete edge-case scenarios, and check stated behavior against the code; surface a contradiction instead of picking a side.
47
+ - Record resolved terms in the project's existing glossary. Create a new glossary file such as `CONTEXT.md` only when the task authorizes it.
48
+
49
+ ## Feedback and outcome measures
50
+
51
+ **Do:** after an escaped defect or repeated friction, identify the mechanism and the smallest useful prevention: a regression case, clearer contract, focused automated check, or corrected guidance. Measure outcomes in the application's context.
52
+ **Do not:** add a broad rule after every isolated typo, or rank people and agents by lines of code, PR count, abstraction count, or number of findings.
53
+
54
+ Bad: reward a reviewer for generating more comments, or an implementer for creating more files.
55
+ Good: track accepted behavior, escaped defects, rework, review effort, and time/cost together. Preserve a baseline and check whether the intervention improved the actual problem.
56
+
57
+ For ongoing delivery, DORA's five metrics are change lead time, deployment frequency, failed deployment recovery time, change fail rate, and deployment rework rate. Use trends for one application/service; do not impose cross-project quotas. Start with existing evidence instead of building a metrics platform for a small tool.
58
+
59
+ **Exception:** a one-off tool needs a verified result and usable handoff, not a permanent observability or reporting program.
60
+
61
+ ## Sources and limits
62
+
63
+ - [DORA small batches](https://dora.dev/capabilities/working-in-small-batches/) supports short feedback loops; it does not prescribe a universal PR size.
64
+ - [DORA delivery metrics](https://dora.dev/guides/dora-metrics/) cautions against quotas and comparisons across different contexts.
65
+ - [Michael Nygard on architecture decision records](https://cognitect.com/blog/2011/11/15/documenting-architecture-decisions) describes small records for significant decisions.
66
+ - [DORA 2025 research](https://dora.dev/research/2025/dora-report) describes AI as amplifying the surrounding system. Observational associations do not prove that one steering rule causes better outcomes.
@@ -0,0 +1,55 @@
1
+ # Middleware: cross-cutting concerns at the boundary
2
+
3
+ Read when a change touches authentication, coarse authorization, validation, request ids, logging, tracing, metrics, error mapping, timeouts, retries, rate limits, idempotency, CORS, compression, security headers or caching, or when it adds a service, handler, consumer or client. These rules are language-neutral. The mechanism, ordering details and pitfalls for each framework are in the `lang-<language>-libraries` skill's `services.md` (and `aws.md` for Lambda); telemetry rules are in [telemetry.md](telemetry.md); API errors, idempotency keys and rate-limit headers are in the `toolchain-api` skill.
4
+
5
+ ## Handlers hold business logic; middleware holds the rest
6
+
7
+ **Do:** keep each handler, consumer or command to its business decision: parse and validate input, call a testable domain function, map the result. Compose the concerns above once, at the boundary where they apply, with the framework's middleware, interceptors, hooks, layers or decorators.
8
+ **Do not:** repeat auth checks, exception-to-response mapping, timing, logging or retry loops inside each handler, or hand-roll a chain the framework already provides.
9
+
10
+ Bad: every route handler verifies the token, starts a timer, logs the request and wraps its body in a try block that builds an error response.
11
+ Good: one auth middleware or dependency, one telemetry layer, one error mapper; the handler is a few lines of domain logic.
12
+
13
+ **Exception:** a one-off script or a single function with one concern needs no middleware stack. Resource-level authorization (may this user edit this order?) stays explicit in the route dependency, guard or domain service; middleware authenticates and enforces coarse policy.
14
+
15
+ ## One middleware model per surface
16
+
17
+ **Do:** use one framework, and so one middleware model, per surface of a service. An HTTP API is one surface, including its Lambda deployment; an RPC API is another (in TypeScript: Hono for the HTTP API, Connect for RPC, each with its own middleware or interceptors). Keep event consumers (queues, streams, schedules) on plain handlers plus the platform's utilities. Share cross-cutting logic between surfaces as plain functions, such as one token verifier and one logger setup, that each surface's chain calls.
18
+ **Do not:** wrap one middleware engine in another (an HTTP framework inside a Lambda middleware engine, or an RPC framework inside an HTTP framework without a documented adapter), or run two body parsers, two error mappers or two loggers over the same request.
19
+
20
+ ## Order the stack
21
+
22
+ Typical inbound order, outermost first; the framework's lifecycle rules override it:
23
+
24
+ 1. Request id and trace-context extraction.
25
+ 2. Access logging and metrics, so they record the final status.
26
+ 3. Error mapping, so it catches everything inside it.
27
+ 4. CORS preflight and security headers.
28
+ 5. Cheap anonymous abuse limits, then authentication.
29
+ 6. Identity-based rate limits and quotas.
30
+ 7. Body-size and decompression limits, then input validation.
31
+ 8. Timeouts and idempotency.
32
+ 9. The handler.
33
+
34
+ Error responses still carry CORS and security headers. Compression must not buffer streams or server-sent events.
35
+
36
+ ## Map errors once
37
+
38
+ **Do:** translate domain errors to the transport in one place: problem details for HTTP, status codes with details for gRPC, nack or dead-letter decisions for consumers. Keep stack traces and secrets out of responses.
39
+ **Do not:** build error bodies in handlers or leak exception text to callers.
40
+
41
+ ## Clients and consumers have middleware too
42
+
43
+ **Do:** put retries, auth, timeouts and tracing for outbound calls in the HTTP client's transport, interceptor or hook layer, and order them deliberately (auth inside retries, tracing around each attempt). Wrap queue and stream processors so acknowledgement, retry, idempotency and trace-context extraction live in one place.
44
+ **Do not:** replay a non-idempotent request without an idempotency key, or acknowledge a message before its side effects are durable.
45
+
46
+ ## Test middleware alone, then assembled
47
+
48
+ **Do:** test each middleware against a stub downstream handler, then test the assembled stack for ordering, early exits, exceptions, cancellation and streaming. Pass request metadata through typed, namespaced request context.
49
+ **Do not:** hide business dependencies in request context, or keep mutable state across requests.
50
+
51
+ ## Sources
52
+
53
+ - RFC 9457 problem details: https://www.rfc-editor.org/rfc/rfc9457
54
+ - gRPC interceptors: https://grpc.io/docs/guides/interceptors/
55
+ - OWASP API Security Top 10 2023: https://owasp.org/API-Security/editions/2023/en/0x11-t10/
@@ -0,0 +1,44 @@
1
+ # Other language paradigms
2
+
3
+ Load only the section matching the code under discussion. TypeScript and JavaScript are in [typescript.md](typescript.md), Python in [python.md](python.md). These examples illustrate portable design principles, not required frameworks.
4
+
5
+ ## Java and C#
6
+
7
+ **Do:** use cohesive classes, records/value objects, narrow interfaces at real boundaries, and ordinary constructor injection.
8
+ **Do not:** add an interface, factory, abstract factory, and service wrapper to each concrete class by convention alone.
9
+
10
+ Bad: a formatter with no state or variation is wrapped in five layers and resolved through a service locator.
11
+ Good: a direct static/pure method, or the project's ordinary formatter object if framework conventions make that simpler.
12
+
13
+ Bad: a mutable `Money` object permits changing its currency without converting its amount.
14
+ Good: an immutable value object validates currency/amount together and exposes deliberate operations.
15
+
16
+ **Exception:** framework interfaces, proxies, and lifecycle hooks can be necessary. Name the framework requirement and retain the smallest structure that fulfills it; do not remove it based only on one implementation.
17
+
18
+ ## Functional languages and functional application code
19
+
20
+ **Do:** use pure transformations, algebraic data types, opaque modules, and explicit effects to express invariants and boundaries.
21
+ **Do not:** simulate OOP with records of setters or force all effects through a custom abstraction framework.
22
+
23
+ Bad: a pricing function fetches the exchange rate, reads the clock, and mutates a shared cache while appearing to calculate a value.
24
+ Good: the application boundary fetches inputs; `price(order, rate, now)` calculates the result. Keep an existing effect system when it already expresses these needs clearly.
25
+
26
+ Bad: `status: string` plus unrelated nullable payload fields.
27
+ Good: a sum type with one valid payload per state and exhaustive pattern matching.
28
+
29
+ Why: explicit inputs and effects permit local reasoning; composition and substitution do not require inheritance.
30
+
31
+ **Exception:** tightly coupled effectful operations can stay together when their transaction or resource lifetime is the responsibility being protected. Purity is a means, not a demand for needless layers.
32
+
33
+ ## C and procedural modules
34
+
35
+ **Do:** use cohesive translation units, opaque structs where invariants matter, explicit context parameters, and documented ownership/error results.
36
+ **Do not:** expose every mutable struct field to every caller or add function-pointer vtables to all small helpers.
37
+
38
+ Bad: callers reach into queue internals to edit head/tail pointers independently.
39
+ Good: the header exposes an opaque `Queue` and operations such as `queue_push`/`queue_pop`; implementation owns the representation and consistency checks.
40
+
41
+ Bad: a trivial checksum helper gets a polymorphic plugin ABI without a plugin requirement.
42
+ Good: a direct function with a length-aware input and a clear result contract.
43
+
44
+ **Exception:** plain structs suit transparent value records and performance-critical data layouts. State who owns memory and which code is allowed to mutate it; do not hide representation when that is the API's legitimate purpose.