@punks/cli 3.1.9 → 3.1.11
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.
- package/dist/BASELINE_CHANGELOG.md +67 -0
- package/dist/CHANGELOG.md +48 -0
- package/dist/data/subagents/manifest.mjs +11 -6
- package/dist/index.js +32 -29
- package/dist/skills/agnostic/cli/hi-cli/references/post-command-flow.md +5 -0
- package/dist/skills/agnostic/docs/writing-great-skills/GLOSSARY.md +69 -0
- package/dist/skills/agnostic/docs/writing-great-skills/SKILL.md +63 -0
- package/dist/skills/agnostic/planning/create-plan/REFERENCE.md +1 -1
- package/dist/skills/agnostic/planning/create-plan/SKILL.md +19 -7
- package/dist/skills/agnostic/planning/create-plan/references/plan-schema.md +19 -0
- package/dist/skills/agnostic/planning/create-plan/references/planner-task-graph.md +27 -10
- package/dist/skills/agnostic/planning/implement-spec/SKILL.md +6 -2
- package/dist/skills/agnostic/planning/implement-spec/assets/IMPLEMENTATION-NOTES-TEMPLATE.md +22 -6
- package/dist/skills/agnostic/planning/implement-spec/references/lifecycle.md +12 -0
- package/dist/skills/agnostic/planning/implement-spec/references/parallel-orchestration.md +10 -2
- package/dist/skills/agnostic/planning/implement-spec/references/parallel-worker-brief.md +10 -1
- package/dist/skills/agnostic/planning/implement-spec/references/parallel.md +2 -0
- package/dist/skills/agnostic/quality/autoreview/SKILL.md +11 -2
- package/dist/skills/agnostic/quality/review/SKILL.md +16 -11
- package/dist/skills/frameworks/effect/effect-service-design/LICENSE +21 -0
- package/dist/skills/frameworks/effect/effect-service-design/SKILL.md +124 -0
- package/dist/skills/frameworks/effect/effect-service-design/references/AUDIT.md +98 -0
- package/dist/skills/frameworks/nestjs/nestjs-best-practices/.gitignore +29 -0
- package/dist/skills/languages/python/python-backend-structure/SKILL.md +91 -0
- package/dist/skills/languages/python/python-backend-structure/agents/openai.yaml +4 -0
- package/dist/skills/languages/python/python-design-patterns/SKILL.md +93 -69
- package/dist/skills/languages/python/python-project-structure/SKILL.md +4 -247
- package/dist/skills/phases/delivery-phase/SKILL.md +13 -4
- package/dist/skills/phases/delivery-phase/phases/closeout.md +3 -0
- package/dist/skills/phases/delivery-phase/phases/debug.md +8 -1
- package/dist/skills/phases/delivery-phase/phases/implement.md +11 -2
- package/dist/skills/phases/delivery-phase/phases/review.md +50 -29
- package/dist/skills/phases/delivery-phase/phases/router.md +56 -36
- package/dist/skills/phases/delivery-phase/references/artifact-state.md +8 -2
- package/dist/skills/phases/delivery-phase/references/phase-handoff.md +60 -10
- package/dist/skills/phases/finder-phase/references/root-routing.md +6 -1
- package/dist/skills/phases/review-phase/REFERENCE.md +83 -145
- package/dist/skills/phases/review-phase/SKILL.md +41 -45
- package/dist/skills/phases/review-phase/agents/openai.yaml +2 -0
- package/dist/skills/phases/review-phase/references/durable-report.md +172 -0
- package/dist/skills/phases/review-phase/references/state-graph.md +69 -0
- package/dist/skills/phases/review-phase/references/targets.md +156 -0
- package/dist/skills/phases/review-phase/scripts/review-contract.mjs +819 -0
- package/package.json +9 -63
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: effect-service-design
|
|
3
|
+
description: Design Effect services. Use when designing a new Effect service module or auditing an existing codebase for service, Layer, and composition improvements.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Effect Service Design
|
|
7
|
+
|
|
8
|
+
Treat a service as an **authority seam**: a cohesive capability whose requirements should propagate through Effect context. An **Effect service module** owns the service contract, construction, production Layer, and any honest reusable test implementation that belong to the same capability.
|
|
9
|
+
|
|
10
|
+
## 1. Establish the local rules
|
|
11
|
+
|
|
12
|
+
Read the nearest `AGENTS.md`, architecture docs, coding standards, project Effect guidance, pinned Effect version/source, and relevant vendored examples. Prefer current project-compatible patterns over remembered APIs.
|
|
13
|
+
|
|
14
|
+
**Complete when:** the governing files and pinned source examples have been read and recorded for use in later decisions.
|
|
15
|
+
|
|
16
|
+
## 2. Select the branch
|
|
17
|
+
|
|
18
|
+
- **Design branch:** for a new service or a focused redesign, bound the capability, trace one caller-visible operation to every effect, then continue below.
|
|
19
|
+
- **Audit branch:** for a codebase, package, feature slice, or diff, read and follow [`references/AUDIT.md`](references/AUDIT.md), applying the rules below to every candidate it finds.
|
|
20
|
+
|
|
21
|
+
**Complete when:** one branch is selected, its scope is bounded, and the caller-visible operations in scope are named.
|
|
22
|
+
|
|
23
|
+
## 3. Apply the service test
|
|
24
|
+
|
|
25
|
+
A real service owns at least one meaningful capability:
|
|
26
|
+
|
|
27
|
+
- authority over persistence, credentials, external I/O, runtime resources, configuration, time, randomness, or lifecycle;
|
|
28
|
+
- state or behavior with real production and test/runtime variation;
|
|
29
|
+
- enough implementation complexity that deleting the module would spread complexity into callers.
|
|
30
|
+
|
|
31
|
+
Prefer an existing Effect service such as `Clock`, `Crypto`, `Random`, `Config`, `HttpClient`, `FileSystem`, or `Path` before defining an application service.
|
|
32
|
+
|
|
33
|
+
Keep these as values or pure modules:
|
|
34
|
+
|
|
35
|
+
- parsed domain inputs and per-call request data;
|
|
36
|
+
- deterministic calculations, projections, parsers, and constructors;
|
|
37
|
+
- options that select policy for one call;
|
|
38
|
+
- framework values confined to their adapter;
|
|
39
|
+
- wrappers that only rename or forward another service.
|
|
40
|
+
|
|
41
|
+
A test-only desire to inject a value is not enough. The seam must represent real ownership or variability in production.
|
|
42
|
+
|
|
43
|
+
**Complete when:** the deletion test and the existing-service/adapter audit both support either “service” or “value,” and the rejected alternative is stated plainly.
|
|
44
|
+
|
|
45
|
+
## 4. Place the authority seam
|
|
46
|
+
|
|
47
|
+
- Domain modules stay pure.
|
|
48
|
+
- A concrete adapter owns its technology-specific `make` and `layer`.
|
|
49
|
+
- Composition roots select and provide concrete Layers. They do not become reusable policy modules.
|
|
50
|
+
- Runtime bindings are yielded in the composition root or owning adapter, then hidden behind application/domain types.
|
|
51
|
+
|
|
52
|
+
Yield stable dependencies while building the Layer and close over them in service methods. Yield request-, fiber-, or operation-scoped context inside the method that uses it. Let requirements propagate until the module that truthfully chooses an implementation provides them.
|
|
53
|
+
|
|
54
|
+
Passing an external library's constructor options remains correct after the owning adapter has yielded the relevant runtime capability. React props, request values, domain inputs, and framework constructors are not Effect dependency injection.
|
|
55
|
+
|
|
56
|
+
**Complete when:** dependencies point inward, raw technology types stop at adapters, and no inner caller chooses a concrete implementation it does not own.
|
|
57
|
+
|
|
58
|
+
## 5. Shape the Effect service module
|
|
59
|
+
|
|
60
|
+
Follow the project's established equivalent of this shape:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
export interface Interface {
|
|
64
|
+
readonly operation: (input: Input) => Effect.Effect<Output, OperationError>
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export class Service extends Context.Service<Service, Interface>()(
|
|
68
|
+
"@app/Capability",
|
|
69
|
+
) {}
|
|
70
|
+
|
|
71
|
+
export const make: Effect.Effect<
|
|
72
|
+
Service["Service"],
|
|
73
|
+
never,
|
|
74
|
+
Dependency.Service
|
|
75
|
+
> = Effect.gen(function* () {
|
|
76
|
+
const dependency = yield* Dependency.Service
|
|
77
|
+
|
|
78
|
+
const operation = Effect.fn("Capability.operation")(function* (input: Input) {
|
|
79
|
+
return yield* dependency.operation(input)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
return Service.of({ operation })
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
export const layerWithoutDependencies = Layer.effect(Service, make)
|
|
86
|
+
|
|
87
|
+
export const layer = layerWithoutDependencies.pipe(
|
|
88
|
+
Layer.provide([Dependency.layer]),
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
export const layerTest = Layer.succeed(
|
|
92
|
+
Service,
|
|
93
|
+
Service.of({
|
|
94
|
+
operation: (_input) => Effect.succeed(testOutput),
|
|
95
|
+
}),
|
|
96
|
+
)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`layerWithoutDependencies` preserves the service's requirements for composition. `layer` is the ready production assembly and provides the concrete dependency Layers. `layerTest` illustrates a complete static substitute; export it only when that behavior is reusable and honest. Use `layerMemory` instead when an in-memory implementation faithfully preserves the observable contract.
|
|
100
|
+
|
|
101
|
+
Use `Layer.succeed` for an already-built value, `Layer.sync` for lazy synchronous construction, and `Layer.effect` for effectful acquisition. Preserve an established compatible naming convention when renaming would add churn without clarity.
|
|
102
|
+
|
|
103
|
+
Keep interfaces narrow and domain-shaped. Use named `Effect.fn` methods, typed expected errors, and yielded dependencies. Add options, methods, services, and combinators only when each hides enough complexity to earn its place.
|
|
104
|
+
|
|
105
|
+
**Complete when:** the tag, interface, `make`, dependency-preserving Layer, production `layer`, errors, methods, and test strategy have one clear owner, and every exported symbol is required by a caller.
|
|
106
|
+
|
|
107
|
+
## 6. Choose test Layers honestly
|
|
108
|
+
|
|
109
|
+
- Use `Layer.succeed` for a complete static implementation.
|
|
110
|
+
- Add `layerTest` plus a test-control service when reusable state, failure injection, or observation is part of a real seam.
|
|
111
|
+
- Name a Layer `layerMemory` only when it faithfully implements the service's observable contract in memory.
|
|
112
|
+
- Prefer a real local substitute when persistence, transactions, serialization, or protocol behavior matters.
|
|
113
|
+
- Keep a tiny one-off fake in its test when promoting it would create production surface solely for that test.
|
|
114
|
+
|
|
115
|
+
Tests cross the same service interface as production callers. When a reusable control service exists, back its production tag and test-control tag with the same object. Partial objects with “unused” methods that die are focused test fixtures, not reusable in-memory adapters.
|
|
116
|
+
|
|
117
|
+
**Complete when:** each test implementation is complete for its advertised name, tests observe outcomes through the public interface, and no new seam exists only to support mocking.
|
|
118
|
+
|
|
119
|
+
## 7. Finish the selected branch
|
|
120
|
+
|
|
121
|
+
- **Design branch:** record the service-or-value decision and its evidence. When implementation is requested, create or refactor the module, update composition roots and tests, and run the repository's required checks.
|
|
122
|
+
- **Audit branch:** produce prioritized findings with file/line or symbol evidence, target module shapes, composition and test impact, and explicit “keep” decisions.
|
|
123
|
+
|
|
124
|
+
**Complete when:** the designed capability has an explicit disposition and validated implementation when requested, or every audit inventory row has a disposition; validation passes or every failure is reported.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# Codebase audit branch
|
|
2
|
+
|
|
3
|
+
Use this branch for an entire codebase, package, feature slice, or diff.
|
|
4
|
+
|
|
5
|
+
## 1. Build the inventory
|
|
6
|
+
|
|
7
|
+
Enumerate source and test files, then find:
|
|
8
|
+
|
|
9
|
+
- every `Context.Service`, tag, `Layer`, `make`, `provide`, and `provideService`;
|
|
10
|
+
- service-shaped interfaces/classes with effectful methods;
|
|
11
|
+
- parameter, property, constructor, callback, options-bag, and Layer injection;
|
|
12
|
+
- direct access to time, randomness, cryptography, IDs, configuration, HTTP, persistence, registries, renderers, filesystem, runtime bindings, and mutable globals;
|
|
13
|
+
- test fakes, in-memory implementations, module mocks, and hand-built `Layer.succeed` values.
|
|
14
|
+
|
|
15
|
+
For each service record:
|
|
16
|
+
|
|
17
|
+
| Field | Question |
|
|
18
|
+
| --- | --- |
|
|
19
|
+
| Owner | Which module owns the capability's meaning? |
|
|
20
|
+
| Contract | Where are the interface and tag? |
|
|
21
|
+
| Constructor | Does `make` yield every dependency? |
|
|
22
|
+
| Production | Which module owns the concrete `layer`? |
|
|
23
|
+
| Tests | Is there an honest reusable test/local implementation? |
|
|
24
|
+
| Consumers | Are capabilities yielded or drilled? |
|
|
25
|
+
| Requirements | Do Effect requirements propagate to the composition root? |
|
|
26
|
+
| Verdict | Keep, deepen, relocate, merge, remove, or create? |
|
|
27
|
+
|
|
28
|
+
**Complete when:** every discovered service/tag and Layer appears exactly once in the inventory.
|
|
29
|
+
|
|
30
|
+
## 2. Trace requirements
|
|
31
|
+
|
|
32
|
+
For each service and service-shaped constructor:
|
|
33
|
+
|
|
34
|
+
1. Trace one public operation to every effect.
|
|
35
|
+
2. Mark where each dependency first appears.
|
|
36
|
+
3. Mark where it is yielded, passed as a value, captured from a property, or concretely provided.
|
|
37
|
+
4. Verify the module providing a Layer truthfully owns that implementation choice.
|
|
38
|
+
5. Check pinned source for framework/runtime services before recommending a wrapper.
|
|
39
|
+
|
|
40
|
+
Pay special attention to:
|
|
41
|
+
|
|
42
|
+
- a service yielded once and then passed through several functions;
|
|
43
|
+
- a `Layer` accepted as a function argument;
|
|
44
|
+
- dependency bags and constructors in Effect-native code;
|
|
45
|
+
- plain service values passed into handler builders;
|
|
46
|
+
- local `Effect.provide` calls that erase requirements below the composition root;
|
|
47
|
+
- global Clock, crypto, random, environment, fetch, database, registry, or binding access;
|
|
48
|
+
- a service contract, `make`, production Layer, and test Layer scattered across unrelated modules.
|
|
49
|
+
|
|
50
|
+
**Complete when:** every capability in the inventory has an unbroken path from use to the composition root or a documented value boundary.
|
|
51
|
+
|
|
52
|
+
## 3. Classify each candidate
|
|
53
|
+
|
|
54
|
+
Apply the service test from `SKILL.md`, then classify dependencies:
|
|
55
|
+
|
|
56
|
+
- **built-in Effect capability** — yield it directly;
|
|
57
|
+
- **technology adapter** — implement the port in the adapter module;
|
|
58
|
+
- **request/domain value** — keep it explicit;
|
|
59
|
+
- **framework boundary** — isolate its required constructor/property API in the adapter or root;
|
|
60
|
+
- **pass-through abstraction** — remove or fold into its owner.
|
|
61
|
+
|
|
62
|
+
Use the deletion test. Confirm an existing module cannot own the behavior before proposing a new one. Prefer merging duplicated capabilities over introducing a generic registry or dependency bag.
|
|
63
|
+
|
|
64
|
+
**Complete when:** every candidate has one classification and concrete evidence; no finding rests only on stylistic preference.
|
|
65
|
+
|
|
66
|
+
## 4. Audit test implementations
|
|
67
|
+
|
|
68
|
+
For each service, inspect how tests replace or control it:
|
|
69
|
+
|
|
70
|
+
- static complete value → local or colocated `Layer.succeed`;
|
|
71
|
+
- reusable state/control → first-class test service and `layerTest`;
|
|
72
|
+
- faithful in-memory semantics → `layerMemory`;
|
|
73
|
+
- persistence/protocol semantics → real local adapter;
|
|
74
|
+
- narrow one-off behavior → fixture local to the test.
|
|
75
|
+
|
|
76
|
+
Compare the fake's advertised contract with its implementation. A partial fake can remain local, but it cannot be recommended as a general in-memory Layer.
|
|
77
|
+
|
|
78
|
+
**Complete when:** every production service has an intentional test strategy or an explicit reason no substitute is needed.
|
|
79
|
+
|
|
80
|
+
## 5. Report only actionable findings
|
|
81
|
+
|
|
82
|
+
Prioritize by correctness and requirement visibility:
|
|
83
|
+
|
|
84
|
+
- **P0** — hidden authority, direct unsafe runtime access, broken or duplicated capability, wrong Layer ownership;
|
|
85
|
+
- **P1** — repeated dependency drilling, missing dependency-preserving or production Layer, scattered service module;
|
|
86
|
+
- **P2** — naming or colocation cleanup that should ride with a nearby refactor.
|
|
87
|
+
|
|
88
|
+
For each finding include:
|
|
89
|
+
|
|
90
|
+
1. evidence with file/line or symbol references;
|
|
91
|
+
2. why the current shape hides requirements or creates caller burden;
|
|
92
|
+
3. the smallest target Effect service module shape, including `layerWithoutDependencies`, assembled `layer`, and any honest reusable test Layer;
|
|
93
|
+
4. the composition-root and test impact;
|
|
94
|
+
5. what should remain unchanged.
|
|
95
|
+
|
|
96
|
+
Include a final “keep” section covering explicit values, pure functions, framework boundaries, correctly separated ports/adapters, and request-scoped services.
|
|
97
|
+
|
|
98
|
+
**Complete when:** every inventory row has a disposition, every recommendation names its owner and target shape, and speculative abstractions have been removed from the report.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Dependencies
|
|
2
|
+
node_modules/
|
|
3
|
+
|
|
4
|
+
# Website (lives on docs branch)
|
|
5
|
+
website/
|
|
6
|
+
|
|
7
|
+
# Build outputs
|
|
8
|
+
dist/
|
|
9
|
+
*.js
|
|
10
|
+
*.d.ts
|
|
11
|
+
*.js.map
|
|
12
|
+
|
|
13
|
+
# IDE
|
|
14
|
+
.idea/
|
|
15
|
+
.vscode/
|
|
16
|
+
*.swp
|
|
17
|
+
*.swo
|
|
18
|
+
|
|
19
|
+
# OS
|
|
20
|
+
.DS_Store
|
|
21
|
+
Thumbs.db
|
|
22
|
+
|
|
23
|
+
# Logs
|
|
24
|
+
*.log
|
|
25
|
+
npm-debug.log*
|
|
26
|
+
|
|
27
|
+
# Environment
|
|
28
|
+
.env
|
|
29
|
+
.env.local
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: python-backend-structure
|
|
3
|
+
description: Organize Python backend domain and package architecture. Use when creating or refactoring Python backend packages, resolving import cycles, choosing composition roots or public package APIs, or placing actions, services, repositories, integrations, and adapters.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Python Backend Structure
|
|
7
|
+
|
|
8
|
+
Apply `$backend-domain-structure` to the backend as a whole, then tighten its boundaries for Python packages and imports.
|
|
9
|
+
|
|
10
|
+
This Python overlay intentionally overrides its platform placement for application wiring. `backend/composition.py` is the parent-owned application composition module needed to preserve no-sibling imports; `platform/` retains runtime and transport assembly and accepts injected entrypoints.
|
|
11
|
+
|
|
12
|
+
## Domain tree
|
|
13
|
+
|
|
14
|
+
Start from responsibilities, not framework types:
|
|
15
|
+
|
|
16
|
+
```text
|
|
17
|
+
backend/
|
|
18
|
+
├── composition.py # root-owned application wiring
|
|
19
|
+
├── platform/ # runtime and transport mechanics
|
|
20
|
+
├── integrations/ # external-system adapters
|
|
21
|
+
└── features/
|
|
22
|
+
└── commerce/ # domain parent
|
|
23
|
+
├── composition.py # domain-owned child wiring
|
|
24
|
+
├── contracts.py # parent-owned leaf contracts
|
|
25
|
+
├── models.py # parent-owned domain values and events
|
|
26
|
+
├── checkout/ # child capability
|
|
27
|
+
│ ├── composition.py
|
|
28
|
+
│ ├── contracts.py
|
|
29
|
+
│ ├── models.py
|
|
30
|
+
│ ├── actions.py
|
|
31
|
+
│ ├── services.py
|
|
32
|
+
│ ├── repositories.py
|
|
33
|
+
│ └── adapters.py
|
|
34
|
+
└── fulfillment/ # equivalent sibling capability
|
|
35
|
+
├── composition.py
|
|
36
|
+
├── contracts.py
|
|
37
|
+
└── models.py
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Adapt names and depth to the product. The invariant is ownership: a domain parent owns leaf contract, model, and composition modules; child capabilities own their actions, services, repositories, and adapters. A composition module belongs to its parent and is not another child package. The rule is recursive at every package depth.
|
|
41
|
+
|
|
42
|
+
- Root `composition.py` owns application wiring across `platform/`, `integrations/`, and `features/`.
|
|
43
|
+
- `platform/` owns runtime and transport mechanics that accept injected entrypoints.
|
|
44
|
+
- `integrations/` owns external-system boundaries and concrete adapters that are not feature-private.
|
|
45
|
+
- `features/` owns product behavior grouped by domain.
|
|
46
|
+
- Actions own use-case policy, authorization, state transitions, and orchestration.
|
|
47
|
+
- Services own reusable capability mechanics used by actions.
|
|
48
|
+
- Repositories own persistence only: durable reads, writes, and transaction-shaped operations.
|
|
49
|
+
- External systems enter through integrations or adapters, not repositories.
|
|
50
|
+
|
|
51
|
+
## Import topology
|
|
52
|
+
|
|
53
|
+
Keep all top-level imports acyclic. Lazy imports must not conceal cycles; repair ownership or composition instead.
|
|
54
|
+
|
|
55
|
+
- Sibling packages at the same parent never import one another, even through public package roots. The same law covers sibling implementation branches represented as modules or packages. This includes actions, services, repositories, and adapters.
|
|
56
|
+
- Parent composition may import child implementations at its owning boundary: parent-owned composition modules import immediate child implementation branches and select their wiring. An outer parent imports the child's composed entrypoint, not its internals.
|
|
57
|
+
- Children never import parent composition modules.
|
|
58
|
+
- Child modules import parent-owned leaf `contracts.py` and `models.py` directly. They never import the parent `__init__` or `composition.py`.
|
|
59
|
+
- `checkout/composition.py` is parent-owned relative to checkout's implementation branches and may import and wire them.
|
|
60
|
+
- Each implementation branch imports checkout-owned leaf `contracts.py` and `models.py` and never imports its siblings.
|
|
61
|
+
- `commerce/composition.py` imports only the checkout composed entrypoint and fulfillment equivalent, never either child's internals.
|
|
62
|
+
- A workflow spanning siblings belongs at the nearest honest common parent. When orchestration should remain elsewhere, depend on a lower contract or event owned honestly by the domain that defines it.
|
|
63
|
+
- Root composition injects composed feature entrypoints into platform and transport, so platform and transport do not import feature siblings.
|
|
64
|
+
- Integration adapters can structurally satisfy feature-owned Protocols without importing feature implementation packages. Root composition wires those adapters into feature composition.
|
|
65
|
+
- Concrete adapters depend inward on owned contracts. Contracts and domain models do not import their implementations.
|
|
66
|
+
|
|
67
|
+
Treat an import cycle as evidence that policy, a contract, or construction lives under the wrong owner. Moving an import inside a function changes timing, not the dependency.
|
|
68
|
+
|
|
69
|
+
## Public package APIs
|
|
70
|
+
|
|
71
|
+
Keep every public `__init__.py` deliberately narrow. Re-export only stable entrypoints, contracts, and domain types that callers should couple to.
|
|
72
|
+
|
|
73
|
+
Use `__all__` at public package roots when useful, not every module. Import leaf modules directly inside a package, especially for contracts and models, so package initialization does not create hidden edges.
|
|
74
|
+
|
|
75
|
+
## Services and construction
|
|
76
|
+
|
|
77
|
+
Apply the service-versus-value deletion test before introducing a service: if deleting the seam leaves only a deterministic value or thin forwarding wrapper, keep a value or function. A service earns its name as an authority or capability seam over behavior, resources, external I/O, state, or meaningful production variation.
|
|
78
|
+
|
|
79
|
+
For each service, identify:
|
|
80
|
+
|
|
81
|
+
1. The contract owner: the domain that names the capability in caller terms.
|
|
82
|
+
2. The concrete adapter: the implementation that owns technology-specific mechanics.
|
|
83
|
+
3. The production construction owner: the parent or root composition module that selects the adapter.
|
|
84
|
+
|
|
85
|
+
Make dependencies visible through constructor or setup injection. Pass the capability a caller needs; a service locator hides both ownership and import direction. Keep per-call inputs as values rather than turning them into services.
|
|
86
|
+
|
|
87
|
+
## Applying the structure
|
|
88
|
+
|
|
89
|
+
Classify existing responsibilities before moving modules. Prefer the smallest tree that expresses honest ownership, then check that imports follow the rules above and public roots expose only intended contracts.
|
|
90
|
+
|
|
91
|
+
This skill is descriptive and stateless. Do not require projects to create architecture or import-boundary tests, ledgers, reports, or other persistent artifacts. Use existing validation when it is already part of the project.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
interface:
|
|
2
|
+
display_name: "Python Backend Structure"
|
|
3
|
+
short_description: "Acyclic domain-first Python backend packages"
|
|
4
|
+
default_prompt: "Use $python-backend-structure to organize Python backend domains, package imports, public APIs, services, adapters, and composition roots."
|
|
@@ -7,6 +7,8 @@ description: Python design patterns including KISS, Separation of Concerns, Sing
|
|
|
7
7
|
|
|
8
8
|
Write maintainable Python code using fundamental design principles. These patterns help you build systems that are easy to understand, test, and modify.
|
|
9
9
|
|
|
10
|
+
For backend package topology and import direction, [python-backend-structure](../python-backend-structure/SKILL.md) is authoritative.
|
|
11
|
+
|
|
10
12
|
## When to Use This Skill
|
|
11
13
|
|
|
12
14
|
- Designing new components or services
|
|
@@ -111,27 +113,34 @@ class UserHandler:
|
|
|
111
113
|
# Response formatting
|
|
112
114
|
return Response({"id": user.id, "email": user.email}, status=201)
|
|
113
115
|
|
|
114
|
-
# GOOD:
|
|
115
|
-
class
|
|
116
|
-
|
|
116
|
+
# GOOD: Parent-owned contracts describe dependencies; child packages own implementations
|
|
117
|
+
class UserRepository(Protocol):
|
|
118
|
+
async def save(self, user: User) -> User:
|
|
119
|
+
...
|
|
120
|
+
|
|
121
|
+
class CreateUser(Protocol):
|
|
122
|
+
async def __call__(self, data: CreateUserInput) -> User:
|
|
123
|
+
...
|
|
124
|
+
|
|
125
|
+
class CreateUserAction:
|
|
126
|
+
"""Use-case policy."""
|
|
117
127
|
|
|
118
|
-
def __init__(self,
|
|
119
|
-
self.
|
|
128
|
+
def __init__(self, repository: UserRepository) -> None:
|
|
129
|
+
self._repository = repository
|
|
120
130
|
|
|
121
|
-
async def
|
|
122
|
-
# Only business rules here
|
|
131
|
+
async def __call__(self, data: CreateUserInput) -> User:
|
|
123
132
|
user = User(email=data.email, name=data.name)
|
|
124
|
-
return await self.
|
|
133
|
+
return await self._repository.save(user)
|
|
125
134
|
|
|
126
135
|
class UserHandler:
|
|
127
136
|
"""HTTP concerns only."""
|
|
128
137
|
|
|
129
|
-
def __init__(self,
|
|
130
|
-
self.
|
|
138
|
+
def __init__(self, create_user: CreateUser) -> None:
|
|
139
|
+
self._create_user = create_user
|
|
131
140
|
|
|
132
141
|
async def create_user(self, request: Request) -> Response:
|
|
133
142
|
data = CreateUserInput(**(await request.json()))
|
|
134
|
-
user = await self.
|
|
143
|
+
user = await self._create_user(data)
|
|
135
144
|
return Response(user.to_dict(), status=201)
|
|
136
145
|
```
|
|
137
146
|
|
|
@@ -139,60 +148,70 @@ Now HTTP changes don't affect business logic, and vice versa.
|
|
|
139
148
|
|
|
140
149
|
### Pattern 3: Separation of Concerns
|
|
141
150
|
|
|
142
|
-
|
|
151
|
+
Separate runtime call flow from Python import topology. A request may run through a handler, action, and repository capability, but peer packages at the same parent never import one another. They depend on parent-owned contracts and models; composition imports and wires their concrete implementations.
|
|
143
152
|
|
|
144
153
|
```
|
|
145
154
|
┌─────────────────────────────────────────────────────┐
|
|
146
|
-
│
|
|
155
|
+
│ Transport handler │
|
|
147
156
|
│ - Parse requests │
|
|
148
|
-
│ - Call
|
|
157
|
+
│ - Call an injected action contract │
|
|
149
158
|
│ - Format responses │
|
|
150
159
|
└─────────────────────────────────────────────────────┘
|
|
151
160
|
│
|
|
161
|
+
│ runtime call
|
|
152
162
|
▼
|
|
153
163
|
┌─────────────────────────────────────────────────────┐
|
|
154
|
-
│
|
|
155
|
-
│ -
|
|
156
|
-
│ -
|
|
157
|
-
│ - Pure functions where possible │
|
|
164
|
+
│ Action │
|
|
165
|
+
│ - Own use-case policy │
|
|
166
|
+
│ - Call an injected repository contract │
|
|
158
167
|
└─────────────────────────────────────────────────────┘
|
|
159
168
|
│
|
|
169
|
+
│ runtime call
|
|
160
170
|
▼
|
|
161
171
|
┌─────────────────────────────────────────────────────┐
|
|
162
|
-
│ Repository
|
|
163
|
-
│ -
|
|
164
|
-
│ -
|
|
165
|
-
│ -
|
|
172
|
+
│ Repository adapter │
|
|
173
|
+
│ - Persistence reads and writes │
|
|
174
|
+
│ - Durable storage mapping │
|
|
175
|
+
│ - Transaction-shaped operations │
|
|
166
176
|
└─────────────────────────────────────────────────────┘
|
|
167
177
|
```
|
|
168
178
|
|
|
169
|
-
|
|
179
|
+
HTTP clients, external APIs, and caches belong behind integrations or adapters, not persistence repositories.
|
|
170
180
|
|
|
171
181
|
```python
|
|
172
|
-
#
|
|
173
|
-
class UserRepository:
|
|
182
|
+
# Parent-owned contracts and models
|
|
183
|
+
class UserRepository(Protocol):
|
|
174
184
|
async def get_by_id(self, user_id: str) -> User | None:
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
185
|
+
...
|
|
186
|
+
|
|
187
|
+
class GetUser(Protocol):
|
|
188
|
+
async def __call__(self, user_id: str) -> User:
|
|
189
|
+
...
|
|
179
190
|
|
|
180
|
-
#
|
|
181
|
-
class
|
|
182
|
-
def __init__(self,
|
|
183
|
-
self.
|
|
191
|
+
# Action implementation: imports only parent contracts and models
|
|
192
|
+
class GetUserAction:
|
|
193
|
+
def __init__(self, repository: UserRepository) -> None:
|
|
194
|
+
self._repository = repository
|
|
184
195
|
|
|
185
|
-
async def
|
|
186
|
-
user = await self.
|
|
196
|
+
async def __call__(self, user_id: str) -> User:
|
|
197
|
+
user = await self._repository.get_by_id(user_id)
|
|
187
198
|
if user is None:
|
|
188
199
|
raise UserNotFoundError(user_id)
|
|
189
200
|
return user
|
|
190
201
|
|
|
191
|
-
#
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
202
|
+
# Transport implementation: imports the parent action contract, not an action package
|
|
203
|
+
class UserHandler:
|
|
204
|
+
def __init__(self, get_user: GetUser) -> None:
|
|
205
|
+
self._get_user = get_user
|
|
206
|
+
|
|
207
|
+
async def handle(self, user_id: str) -> UserResponse:
|
|
208
|
+
user = await self._get_user(user_id)
|
|
209
|
+
return UserResponse.from_user(user)
|
|
210
|
+
|
|
211
|
+
# Parent composition: the only place that imports and selects implementations
|
|
212
|
+
repository: UserRepository = StoredUserRepository(storage)
|
|
213
|
+
get_user: GetUser = GetUserAction(repository)
|
|
214
|
+
handler = UserHandler(get_user)
|
|
196
215
|
```
|
|
197
216
|
|
|
198
217
|
### Pattern 4: Composition Over Inheritance
|
|
@@ -308,58 +327,63 @@ def process_order(order: Order) -> Result:
|
|
|
308
327
|
|
|
309
328
|
### Pattern 7: Dependency Injection
|
|
310
329
|
|
|
311
|
-
Pass
|
|
330
|
+
Pass parent-owned capability contracts through constructors. Child implementations import those leaf Protocols; parent composition selects implementations and wires them.
|
|
312
331
|
|
|
313
332
|
```python
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
def info(self, msg: str, **kwargs) -> None: ...
|
|
318
|
-
def error(self, msg: str, **kwargs) -> None: ...
|
|
333
|
+
class UserRepository(Protocol):
|
|
334
|
+
async def get_by_id(self, user_id: str) -> User | None:
|
|
335
|
+
...
|
|
319
336
|
|
|
320
|
-
class
|
|
337
|
+
class UserCache(Protocol):
|
|
321
338
|
async def get(self, key: str) -> str | None: ...
|
|
322
339
|
async def set(self, key: str, value: str, ttl: int) -> None: ...
|
|
323
340
|
|
|
324
|
-
class
|
|
325
|
-
|
|
341
|
+
class AuditLog(Protocol):
|
|
342
|
+
def info(self, event: str, **fields: str) -> None:
|
|
343
|
+
...
|
|
344
|
+
|
|
345
|
+
class GetUser(Protocol):
|
|
346
|
+
async def __call__(self, user_id: str) -> User | None:
|
|
347
|
+
...
|
|
326
348
|
|
|
349
|
+
class GetUserAction:
|
|
327
350
|
def __init__(
|
|
328
351
|
self,
|
|
329
352
|
repository: UserRepository,
|
|
330
|
-
cache:
|
|
331
|
-
|
|
353
|
+
cache: UserCache,
|
|
354
|
+
audit_log: AuditLog,
|
|
332
355
|
) -> None:
|
|
333
|
-
self.
|
|
356
|
+
self._repository = repository
|
|
334
357
|
self._cache = cache
|
|
335
|
-
self.
|
|
358
|
+
self._audit_log = audit_log
|
|
336
359
|
|
|
337
|
-
async def
|
|
338
|
-
# Check cache first
|
|
360
|
+
async def __call__(self, user_id: str) -> User | None:
|
|
339
361
|
cached = await self._cache.get(f"user:{user_id}")
|
|
340
362
|
if cached:
|
|
341
|
-
self.
|
|
363
|
+
self._audit_log.info("user_cache_hit", user_id=user_id)
|
|
342
364
|
return User.from_json(cached)
|
|
343
365
|
|
|
344
|
-
|
|
345
|
-
user = await self._repo.get_by_id(user_id)
|
|
366
|
+
user = await self._repository.get_by_id(user_id)
|
|
346
367
|
if user:
|
|
347
368
|
await self._cache.set(f"user:{user_id}", user.to_json(), ttl=300)
|
|
348
369
|
|
|
349
370
|
return user
|
|
350
371
|
|
|
351
|
-
#
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
372
|
+
# Parent composition selects implementations and wires the action
|
|
373
|
+
repository: UserRepository = StoredUserRepository(storage)
|
|
374
|
+
cache: UserCache = ExternalUserCache(cache_client)
|
|
375
|
+
audit_log: AuditLog = ApplicationAuditLog(log_sink)
|
|
376
|
+
get_user: GetUser = GetUserAction(
|
|
377
|
+
repository=repository,
|
|
378
|
+
cache=cache,
|
|
379
|
+
audit_log=audit_log,
|
|
356
380
|
)
|
|
357
381
|
|
|
358
|
-
#
|
|
359
|
-
|
|
382
|
+
# A focused test supplies the same parent-owned contracts
|
|
383
|
+
get_user = GetUserAction(
|
|
360
384
|
repository=InMemoryUserRepository(),
|
|
361
|
-
cache=
|
|
362
|
-
|
|
385
|
+
cache=FakeUserCache(),
|
|
386
|
+
audit_log=RecordingAuditLog(),
|
|
363
387
|
)
|
|
364
388
|
```
|
|
365
389
|
|
|
@@ -425,9 +449,9 @@ Keep the composition shallow (2-3 levels). If wrapping is the only mechanism, co
|
|
|
425
449
|
Duplication that diverges in dangerous ways should be abstracted sooner. The rule of three is a heuristic, not a law. If the copies are already diverging incorrectly, extract immediately and add a test that exercises the shared behavior.
|
|
426
450
|
|
|
427
451
|
**A service layer is importing from the API layer, breaking the dependency direction.**
|
|
428
|
-
This is
|
|
452
|
+
This is an ownership violation. Runtime calls may flow from transport through an action to a repository capability, but sibling packages do not encode that flow by importing one another. Move contracts and models to their honest parent, inject them into children, and let parent composition wire implementations.
|
|
429
453
|
|
|
430
454
|
## Related Skills
|
|
431
455
|
|
|
432
456
|
- [python-testing-patterns](../python-testing-patterns/SKILL.md) — Test each layer in isolation using the dependency injection structure established here
|
|
433
|
-
- [python-
|
|
457
|
+
- [python-backend-structure](../python-backend-structure/SKILL.md) — Python backend domains, composition, and import boundaries
|