@punks/cli 3.1.10 → 3.1.12

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 (76) hide show
  1. package/dist/BASELINE_CHANGELOG.md +61 -0
  2. package/dist/CHANGELOG.md +57 -0
  3. package/dist/data/subagents/manifest.mjs +11 -6
  4. package/dist/index.js +28 -28
  5. package/dist/skills/agnostic/cli/hi-cli/references/post-command-flow.md +5 -0
  6. package/dist/skills/agnostic/docs/writing-beats/LICENSE +21 -0
  7. package/dist/skills/agnostic/docs/writing-beats/UPSTREAM.md +11 -0
  8. package/dist/skills/agnostic/docs/writing-fragments/LICENSE +21 -0
  9. package/dist/skills/agnostic/docs/writing-fragments/UPSTREAM.md +11 -0
  10. package/dist/skills/agnostic/docs/writing-shape/LICENSE +21 -0
  11. package/dist/skills/agnostic/docs/writing-shape/UPSTREAM.md +11 -0
  12. package/dist/skills/agnostic/frontend/frontend-domain-structure/SKILL.md +24 -42
  13. package/dist/skills/agnostic/frontend/frontend-domain-structure/agents/openai.yaml +1 -1
  14. package/dist/skills/agnostic/frontend/frontend-domain-structure/references/react/structure.md +51 -78
  15. package/dist/skills/agnostic/frontend/frontend-domain-structure/references/structure.md +89 -212
  16. package/dist/skills/agnostic/generic/handoff/LICENSE +21 -0
  17. package/dist/skills/agnostic/generic/handoff/UPSTREAM.md +11 -0
  18. package/dist/skills/agnostic/planning/create-plan/REFERENCE.md +1 -1
  19. package/dist/skills/agnostic/planning/create-plan/SKILL.md +19 -7
  20. package/dist/skills/agnostic/planning/create-plan/references/plan-schema.md +19 -0
  21. package/dist/skills/agnostic/planning/create-plan/references/planner-task-graph.md +27 -10
  22. package/dist/skills/agnostic/planning/implement-spec/SKILL.md +6 -2
  23. package/dist/skills/agnostic/planning/implement-spec/assets/IMPLEMENTATION-NOTES-TEMPLATE.md +22 -6
  24. package/dist/skills/agnostic/planning/implement-spec/references/lifecycle.md +12 -0
  25. package/dist/skills/agnostic/planning/implement-spec/references/parallel-orchestration.md +10 -2
  26. package/dist/skills/agnostic/planning/implement-spec/references/parallel-worker-brief.md +10 -1
  27. package/dist/skills/agnostic/planning/implement-spec/references/parallel.md +2 -0
  28. package/dist/skills/agnostic/quality/autoreview/SKILL.md +11 -2
  29. package/dist/skills/agnostic/quality/codebase-design/LICENSE +21 -0
  30. package/dist/skills/agnostic/quality/codebase-design/UPSTREAM.md +11 -0
  31. package/dist/skills/agnostic/quality/review/LICENSE +21 -0
  32. package/dist/skills/agnostic/quality/review/SKILL.md +16 -11
  33. package/dist/skills/agnostic/quality/review/UPSTREAM.md +11 -0
  34. package/dist/skills/agnostic/quality/tdd/LICENSE +21 -0
  35. package/dist/skills/agnostic/quality/tdd/UPSTREAM.md +11 -0
  36. package/dist/skills/agnostic/research/improve-codebase-architecture/LICENSE +21 -0
  37. package/dist/skills/agnostic/research/improve-codebase-architecture/UPSTREAM.md +11 -0
  38. package/dist/skills/frameworks/effect/effect/SKILL.md +5 -12
  39. package/dist/skills/frameworks/effect/effect/references/CONFIG.md +10 -19
  40. package/dist/skills/frameworks/effect/effect/references/SERVICES_LAYERS.md +3 -63
  41. package/dist/skills/frameworks/effect/effect/references/TESTING.md +2 -72
  42. package/dist/skills/frameworks/effect/effect-backend-structure/SKILL.md +12 -29
  43. package/dist/skills/frameworks/effect/effect-backend-structure/agents/openai.yaml +1 -1
  44. package/dist/skills/frameworks/effect/effect-backend-structure/references/layout.md +9 -9
  45. package/dist/skills/frameworks/sqlalchemy/sqlalchemy-schema-design/SKILL.md +199 -0
  46. package/dist/skills/frameworks/sqlalchemy/sqlalchemy-schema-design/UPSTREAM.md +31 -0
  47. package/dist/skills/frameworks/sqlalchemy/sqlalchemy-schema-design/agents/openai.yaml +4 -0
  48. package/dist/skills/languages/python/python-backend-structure/SKILL.md +91 -0
  49. package/dist/skills/languages/python/python-backend-structure/agents/openai.yaml +4 -0
  50. package/dist/skills/languages/python/python-design-patterns/SKILL.md +93 -69
  51. package/dist/skills/languages/python/python-project-structure/SKILL.md +4 -247
  52. package/dist/skills/phases/delivery-phase/SKILL.md +13 -4
  53. package/dist/skills/phases/delivery-phase/phases/closeout.md +3 -0
  54. package/dist/skills/phases/delivery-phase/phases/debug.md +8 -1
  55. package/dist/skills/phases/delivery-phase/phases/implement.md +11 -2
  56. package/dist/skills/phases/delivery-phase/phases/review.md +50 -29
  57. package/dist/skills/phases/delivery-phase/phases/router.md +56 -36
  58. package/dist/skills/phases/delivery-phase/references/artifact-state.md +8 -2
  59. package/dist/skills/phases/delivery-phase/references/phase-handoff.md +60 -10
  60. package/dist/skills/phases/finder-phase/references/root-routing.md +6 -1
  61. package/dist/skills/phases/prototype-phase/agents/openai.yaml +2 -0
  62. package/dist/skills/phases/review-phase/AUTHORING-HANDOFF.md +622 -0
  63. package/dist/skills/phases/review-phase/SKILL.md +11 -42
  64. package/dist/skills/phases/review-phase/agents/openai.yaml +2 -0
  65. package/dist/skills/phases/review-phase/phases/prepare-review.md +105 -0
  66. package/dist/skills/phases/review-phase/phases/retain-report.md +113 -0
  67. package/dist/skills/phases/review-phase/phases/return-route.md +95 -0
  68. package/dist/skills/phases/review-phase/phases/router.md +78 -0
  69. package/dist/skills/phases/review-phase/phases/run-review.md +128 -0
  70. package/dist/skills/phases/review-phase/references/durable-report.md +153 -0
  71. package/dist/skills/phases/review-phase/references/runtime-handoff.md +138 -0
  72. package/dist/skills/phases/review-phase/references/state-graph.md +69 -0
  73. package/dist/skills/phases/review-phase/references/targets.md +156 -0
  74. package/dist/skills/phases/review-phase/scripts/review-contract.mjs +819 -0
  75. package/package.json +56 -2
  76. package/dist/skills/phases/review-phase/REFERENCE.md +0 -147
@@ -1,27 +1,17 @@
1
1
  # Testing
2
2
 
3
- Use this when writing Effect tests, tests involving time, retry, schedules, concurrency, workers, services, fakes, or config.
3
+ Use this when writing Effect tests involving time, retry, schedules, concurrency, workers, or config. Use `$effect-service-design` for service test substitutes and reusable test Layers.
4
4
 
5
5
  ## Defaults
6
6
 
7
7
  - Use `it.effect` by default.
8
8
  - Use `it.live` only when real time or live runtime services are the behavior under test.
9
- - Use test layers and `ConfigProvider` rather than global mutation.
9
+ - Use `ConfigProvider` rather than global mutation for configuration tests.
10
10
  - Use `TestClock.setTime` / `TestClock.adjust` for sleeps, schedules, retries, leases, and timeouts.
11
11
  - Fork sleeping effects before advancing `TestClock`.
12
12
  - Avoid arbitrary `Effect.sleep(...)` in tests; it usually makes tests slow and flaky.
13
13
  - Assert typed failures, rollback, interruption, finalization, retry bounds, idempotency, concurrency laws, and malformed persistence where relevant.
14
14
 
15
- ```ts
16
- it.effect("finds a user", () =>
17
- Effect.gen(function* () {
18
- const users = yield* UserRepo.Service
19
- const result = yield* users.find(UserId.make("u1"))
20
- expect(Option.isSome(result)).toBe(true)
21
- }).pipe(Effect.provide(UserRepo.testLayer)),
22
- )
23
- ```
24
-
25
15
  ## Synchronization Instead Of Sleeps
26
16
 
27
17
  - Use `Deferred` for one-shot readiness/completion signals.
@@ -53,66 +43,6 @@ it.effect("publishes exactly once", () =>
53
43
  )
54
44
  ```
55
45
 
56
- ## First-Class App Test Stubs
57
-
58
- Use `TestInterface extends Interface`, `TestService`, and `testLayer` for reusable/stateful fakes.
59
-
60
- ```ts
61
- export interface Interface {
62
- readonly send: (message: Message) => Effect.Effect<void, SendError>
63
- }
64
-
65
- export class Service extends Context.Service<Service, Interface>()(
66
- "@app/Notifier",
67
- ) {}
68
-
69
- export interface TestInterface extends Interface {
70
- readonly sentMessages: () => Effect.Effect<ReadonlyArray<Message>>
71
- readonly failNextSend: (error: SendError) => Effect.Effect<void>
72
- }
73
-
74
- export class TestService extends Context.Service<TestService, TestInterface>()(
75
- "@app/Notifier/Test",
76
- ) {}
77
-
78
- export const testLayer = Layer.effectContext(
79
- Effect.gen(function* () {
80
- const sent = yield* Ref.make<ReadonlyArray<Message>>([])
81
- const nextFailure = yield* Ref.make<Option.Option<SendError>>(Option.none())
82
-
83
- const service = TestService.of({
84
- send: Effect.fn("Notifier.Test.send")(function* (message) {
85
- const failure = yield* Ref.getAndSet(nextFailure, Option.none())
86
- if (Option.isSome(failure)) return yield* Effect.fail(failure.value)
87
- yield* Ref.update(sent, (messages) => [...messages, message])
88
- }),
89
- sentMessages: Effect.fn("Notifier.Test.sentMessages")(function* () {
90
- return yield* Ref.get(sent)
91
- }),
92
- failNextSend: Effect.fn("Notifier.Test.failNextSend")(function* (error) {
93
- yield* Ref.set(nextFailure, Option.some(error))
94
- }),
95
- })
96
-
97
- return Context.empty().pipe(
98
- Context.add(Service, service),
99
- Context.add(TestService, service),
100
- )
101
- }),
102
- )
103
- ```
104
-
105
- Guidance:
106
-
107
- - The same object should back both the real `Service` tag and `TestService` tag.
108
- - Production code depends only on the real service tag.
109
- - Tests use `TestService` for control and inspection.
110
- - Use function-valued service members, including zero-argument operations, so `Effect.fn` fits naturally.
111
- - Use `Layer.succeed` for complete dead-simple static test implementations.
112
- - Use `Layer.mock` only for tiny local partial mocks where omitted members should fail loudly if used.
113
-
114
46
  ## Config In Tests
115
47
 
116
48
  Use `ConfigProvider.layer(ConfigProvider.fromUnknown(...))` when the test should exercise Config decoding.
117
-
118
- Use `Layer.succeed(AppConfiguration.Service, config)` when the app wraps decoded config in its own service and the test does not need to exercise env decoding.
@@ -2,17 +2,16 @@
2
2
  name: effect-backend-structure
3
3
  description: |
4
4
  Apply Effect-specific backend structure on top of backend-domain-structure.
5
- Use when creating or changing Effect services, layers, actions, repositories,
6
- transport adapters, DB integrations, test layers, or backend boilerplate in any
7
- Effect backend root. Enforces visible Effect requirements, layer-provided
8
- implementations, effect-solutions plus opensrc source lookup, and @effect/vitest
9
- testing conventions.
5
+ Use when creating or changing Effect actions, repositories, transport adapters,
6
+ DB integrations, test placement, or backend boilerplate in any Effect backend
7
+ root. Enforces actions-own-orchestration, integration dependency direction,
8
+ effect-solutions plus opensrc source lookup, and @effect/vitest conventions.
10
9
  compatibility: Requires Effect v4. Examples are reviewed against the version documented in this repository.
11
10
  ---
12
11
 
13
12
  # Effect Backend Structure
14
13
 
15
- Use this skill with `$backend-domain-structure` and `$effect` for Effect backend code. `$effect` owns Effect v4 API guidance.
14
+ Use this skill with `$backend-domain-structure` and `$effect` for Effect backend code. `$effect` owns Effect v4 API guidance. Use `$effect-service-design` for service qualification, service modules, Layers, requirements, test substitutes, and service audits.
16
15
 
17
16
  The agnostic skill owns the layer model:
18
17
 
@@ -21,24 +20,23 @@ The agnostic skill owns the layer model:
21
20
  - `features/*`
22
21
  - shared libraries and packages
23
22
 
24
- This skill adds Effect-specific services, layers, dependency visibility, source lookup, and testing rules.
23
+ This skill adds Effect-specific backend topology, action ownership, source lookup, and test placement rules.
25
24
 
26
25
  ## Workflow
27
26
 
28
27
  1. Identify the backend root from the current repo; do not assume a monorepo path.
29
28
  2. Read the nearest relevant `AGENTS.md` files.
30
- 3. Read `$backend-domain-structure`, `$effect`, and `references/layout.md`.
29
+ 3. Read `$backend-domain-structure`, `$effect`, `$effect-service-design` when services or Layers are in scope, and `references/layout.md`.
31
30
  4. Run the relevant `effect-solutions` guides before coding.
32
31
  5. Check local `opensrc` Effect sources when docs are vague or an API surface is unfamiliar.
33
32
  6. Place code using the agnostic backend layers plus the Effect rules below.
34
33
  7. Keep transport thin and run business logic through Effects.
35
- 8. Add or update colocated `@effect/vitest` tests with test layers for unit coverage and live layers for integration coverage.
34
+ 8. Add or update colocated `@effect/vitest` tests for unit and integration coverage.
36
35
 
37
36
  ## Required Source Lookup
38
37
 
39
38
  Always consult `effect-solutions` first. Use the smallest relevant set:
40
39
 
41
- - `effect-solutions show services-and-layers`
42
40
  - `effect-solutions show config`
43
41
  - `effect-solutions show data-modeling`
44
42
  - `effect-solutions show error-handling`
@@ -51,20 +49,9 @@ Use `opensrc` next when the guide is not enough:
51
49
 
52
50
  For non-Effect libraries, run `opensrc path <package>` or `opensrc path owner/repo`.
53
51
 
54
- ## Services and Layers
55
-
56
- - Define business services, repositories, and reusable capability interfaces with `Context.Service`.
57
- - Build implementations with layers and return values through `Service.of(...)`.
58
- - Let actions consume services/repositories through Effect accessors or `yield* Service`.
59
- - Keep action requirements visible until a feature, app, runner, or test layer provides them.
60
- - Compose feature dependencies in `features/<domain>/layer.ts` or the local equivalent.
61
- - Compose cross-feature and infrastructure dependencies in `platform/`.
62
- - Use `Layer.mergeAll` for same-level composition and shallow `Layer.provide` / `Layer.provideMerge` for wiring levels together.
63
- - Avoid `Effect.provide` inside actions, services, repositories, and transport adapters except at the final runner/test boundary.
64
-
65
52
  ## Effect Coding Rules
66
53
 
67
- - Use `Effect.fn("Domain.action")` for actions and service methods.
54
+ - Use `Effect.fn("Domain.action")` for actions.
68
55
  - Use `Schema.TaggedError` for domain failures.
69
56
  - Use branded IDs and Effect Schema for domain models.
70
57
  - Use `Config.*` instead of reading `process.env` inside Effect code.
@@ -75,19 +62,15 @@ For non-Effect libraries, run `opensrc path <package>` or `opensrc path owner/re
75
62
 
76
63
  - Keep tests inside the owning feature or module.
77
64
  - Use `@effect/vitest`.
78
- - Unit tests provide fake leaf services/repos via test layers.
79
- - Integration tests use live layers and public action or transport boundaries.
80
- - Expose assertions through test-state tags in `tests/support`.
81
- - Do not add test-only methods to production services.
82
- - Do not use module mocks for Effect services; provide a replacement `Layer`.
65
+ - Unit tests cover action and guard behavior.
66
+ - Integration tests use public action or transport boundaries.
67
+ - Apply `$effect-service-design` when tests replace or control a service.
83
68
 
84
69
  ## Output Checklist
85
70
 
86
71
  - `$backend-domain-structure` was applied
87
72
  - relevant `effect-solutions` guides were checked
88
73
  - `opensrc` sources were checked when needed
89
- - dependencies stay visible as Effect requirements or service dependencies
90
- - implementations are supplied by layers, not hidden imports or module mocks
91
74
  - code landed in the correct backend layer
92
75
  - actions own orchestration
93
76
  - services are only reusable mechanics
@@ -1,4 +1,4 @@
1
1
  interface:
2
2
  display_name: "Effect Backend Structure"
3
3
  short_description: "Effect backend architecture"
4
- default_prompt: "Use $backend-domain-structure alongside $effect-backend-structure to shape or bootstrap Effect backend code in any backend root; first apply agnostic backend layers, then apply Effect-specific services, layers, and testing rules."
4
+ default_prompt: "Use $backend-domain-structure alongside $effect-backend-structure to shape Effect backend topology and action boundaries; add $effect-service-design when services or Layers are in scope."
@@ -34,14 +34,14 @@ Dependency direction:
34
34
  - features may depend on other features only when the domain relationship is explicit and stable
35
35
  - integrations do not import features
36
36
 
37
- Layer ownership:
37
+ Composition file placement:
38
38
 
39
- - `platform/effect/app.ts` or local equivalent composes the app-wide live layer and provides infrastructure once
40
- - `platform/effect/request.ts` or local equivalent builds request-scoped services and runtime context only
41
- - `features/<domain>/layer.ts` composes that domain's action/repository/service requirements
42
- - `features/<domain>/tests/support/layer.ts` provides fake leaf layers and test-state tags for unit tests
39
+ - `platform/effect/app.ts` or local equivalent is the app-wide composition root
40
+ - `platform/effect/request.ts` or local equivalent owns request-scoped runtime context
41
+ - `features/<domain>/layer.ts` is the domain composition root
42
+ - `features/<domain>/tests/support/` owns feature-local reusable test support
43
43
 
44
- Keep dependency requirements visible until one of these layer files provides them. Do not import live implementations directly inside actions, services, repositories, or transport adapters.
44
+ Do not import live implementations directly inside actions, services, repositories, or transport adapters.
45
45
 
46
46
  Test layout:
47
47
 
@@ -59,10 +59,10 @@ Test layout:
59
59
  Testing split:
60
60
 
61
61
  - `tests/support`
62
- fake leaf layers plus state tags for assertions
62
+ feature-local reusable test support
63
63
  - `tests/unit`
64
- action and guard behavior on fake layers
64
+ action and guard behavior
65
65
  - `tests/integration`
66
- live router/app behavior on real layers
66
+ live router/app behavior
67
67
 
68
68
  Do not recreate a package-root `tests/` folder unless the current repo already requires that convention.
@@ -0,0 +1,199 @@
1
+ ---
2
+ name: sqlalchemy-schema-design
3
+ description: Design SQLAlchemy 2.x models and Alembic migrations. Use for persisted type selection, enums versus extensible strings, JSON columns, constraints, relationships, indexes, or online schema evolution.
4
+ ---
5
+
6
+ # SQLAlchemy schema design
7
+
8
+ Make database invariants explicit in both SQLAlchemy metadata and the database.
9
+ Choose each persisted type from who owns its vocabulary and how it may evolve,
10
+ then shape migrations around the target dialect, table size, traffic, and lock
11
+ budget.
12
+
13
+ ## Persisted types
14
+
15
+ | Field behavior | Persisted shape |
16
+ | --- | --- |
17
+ | Closed, code-owned state or protocol vocabulary | Python enum mapped with `sqlalchemy.Enum` |
18
+ | Extension-, provider-, tenant-, or user-defined identifier | String with a documented format and boundary validation |
19
+ | Free-form human text | `Text`, with length validation at the application boundary when needed |
20
+ | Stable JSON object with known fields | Named application model plus `JSON`/`JSONB`; use a `TypeDecorator` when values should validate on bind and reconstruct on load |
21
+ | Intentionally arbitrary JSON | Named recursive JSON value/object aliases rather than `dict[str, Any]` |
22
+ | Values that need joins, foreign keys, independent updates, or relational filtering | Normalized rows and relationships |
23
+ | Exact quantities such as money | `Numeric` mapped to `Decimal`, with explicit precision and scale |
24
+ | Instants in time | Time-zone-aware timestamp with an explicit UTC convention |
25
+
26
+ Observed values are evidence, not ownership. A column with two current values is
27
+ an enum only when the application owns the complete vocabulary. Keep open
28
+ identifiers as strings even when their current set is small.
29
+
30
+ ### Enums
31
+
32
+ Map code-owned choices to the enum type at entity, constructor, query, and
33
+ service boundaries. When persisted values should be the Python members'
34
+ `.value`, declare that choice explicitly:
35
+
36
+ ```python
37
+ import enum
38
+
39
+ import sqlalchemy as sa
40
+ from sqlalchemy.orm import Mapped, mapped_column
41
+
42
+
43
+ class JobState(str, enum.Enum):
44
+ QUEUED = "queued"
45
+ RUNNING = "running"
46
+ SUCCEEDED = "succeeded"
47
+
48
+
49
+ job_state_type = sa.Enum(
50
+ JobState,
51
+ name="job_state",
52
+ values_callable=lambda members: [member.value for member in members],
53
+ native_enum=False,
54
+ create_constraint=True,
55
+ )
56
+
57
+
58
+ class Job(Base):
59
+ __tablename__ = "job"
60
+
61
+ state: Mapped[JobState] = mapped_column(job_state_type, nullable=False)
62
+ ```
63
+
64
+ Choose the storage strategy deliberately:
65
+
66
+ - `native_enum=False` gives portable string storage with a named check
67
+ constraint. It keeps type evolution in ordinary table DDL.
68
+ - PostgreSQL native enums give a shared database type and strong database
69
+ semantics, but adding, renaming, reordering, or removing values has a
70
+ dialect-specific migration lifecycle.
71
+ - Persist member values or member names by contract. Preserve those stored
72
+ strings across Python symbol renames; migrate data before changing them.
73
+ - When adopting an enum on an existing string column, match its physical type
74
+ and length explicitly so metadata does not introduce an incidental rewrite.
75
+
76
+ Validate open vocabularies against their current source of truth instead of
77
+ centralizing them in a code enum.
78
+
79
+ ### JSON
80
+
81
+ Use JSON for document-shaped data, not as an escape from schema design.
82
+
83
+ - Give known shapes a named model at the application boundary. A
84
+ `TypeDecorator` may validate and serialize on bind, then validate and
85
+ reconstruct on result.
86
+ - Give genuinely generic JSON a recursive `JsonValue` contract. Use narrower
87
+ semantic aliases for guarantees such as redacted or UI-safe content.
88
+ - Use `JSONB` only where the dialect and query operators justify it; otherwise
89
+ use SQLAlchemy's portable `JSON` type.
90
+ - Track in-place ORM mutation with `MutableDict`/`MutableList`, or replace the
91
+ whole value so the unit of work sees the change.
92
+ - Index the operators actually used. PostgreSQL containment, key lookup, and
93
+ path expressions can require different GIN or expression indexes.
94
+
95
+ ## Columns and constraints
96
+
97
+ - Declare nullability from domain meaning. `Optional` Python types and database
98
+ `NULL` behavior must agree.
99
+ - Put invariants that must survive every writer in primary keys, foreign keys,
100
+ unique constraints, check constraints, and exclusion constraints.
101
+ - Name constraints and indexes deterministically, preferably through a metadata
102
+ naming convention, so Alembic can address them across dialects.
103
+ - Distinguish Python defaults from `server_default`. Use a server default when
104
+ inserts outside the ORM must receive the same value.
105
+ - Model delete behavior once. Align `ForeignKey(..., ondelete=...)`, ORM
106
+ cascade, relationship optionality, and `passive_deletes`; database cascades
107
+ can avoid loading large child collections.
108
+ - Use association tables for many-to-many relationships. Give them a composite
109
+ key or unique constraint that prevents duplicate edges.
110
+ - Treat string length, collation, case sensitivity, numeric precision, and time
111
+ zone behavior as database contracts rather than incidental Python details.
112
+
113
+ ## Indexes follow queries
114
+
115
+ Derive indexes from concrete predicates, joins, ordering, and cardinality.
116
+
117
+ - Put equality columns before range or ordering columns when that matches the
118
+ target database's planner behavior.
119
+ - Remember the left-prefix behavior of composite B-tree indexes. A composite
120
+ index may cover a leading-column lookup, but the reverse ordering may not.
121
+ - Add indexes for foreign-key lookup and deletion paths when the database does
122
+ not create them automatically. PostgreSQL does not automatically index the
123
+ referencing columns.
124
+ - Use partial, expression, covering, GIN, or GiST indexes only when the query
125
+ shape and dialect support them.
126
+ - Remove a single-column index only when an existing composite index truly
127
+ covers its predicates and ordering. Distinct operator classes, sort order,
128
+ predicates, and included columns make superficially similar indexes
129
+ different.
130
+ - Let write cost, storage, selectivity, and measured plans bound index width and
131
+ count. A fixed maximum column count is not a design rule.
132
+
133
+ Confirm important paths with representative data and the target database's
134
+ `EXPLAIN` facilities. SQLite test behavior is not evidence of a PostgreSQL or
135
+ MySQL query plan.
136
+
137
+ ## Alembic migrations
138
+
139
+ Treat autogenerate output as a draft. Reconcile it with intended renames,
140
+ constraint names, server defaults, custom types, data transitions, and
141
+ dialect-specific operations.
142
+
143
+ Every migration must preserve a valid application/database contract at its
144
+ deployment boundary:
145
+
146
+ - Add a required column through expand and contract: add it nullable or with a
147
+ safe server default, deploy compatible writes, backfill in bounded batches,
148
+ enforce `NOT NULL`, then remove transitional behavior.
149
+ - Rename a table or column explicitly. Autogenerate commonly represents a
150
+ rename as drop plus add.
151
+ - Change a type in place only when the target database, data volume, conversion,
152
+ and lock budget make it safe. Otherwise add the new column, dual-write,
153
+ backfill, move reads, stop old writes, and remove the old column later.
154
+ - Separate schema and data changes when batching, retries, observability, or
155
+ deploy ordering require an application-controlled backfill.
156
+ - Clean or migrate unknown stored values before deploying readers that
157
+ deserialize every row into a closed Python enum.
158
+ - State the conversion with `postgresql_using` or explicit SQL when PostgreSQL
159
+ cannot infer it safely.
160
+ - Make downgrade behavior honest. Preserve data when practical; mark an
161
+ irreversible destructive transition explicitly instead of pretending it can
162
+ restore discarded values.
163
+
164
+ ### PostgreSQL online DDL
165
+
166
+ Use online patterns for large or write-active PostgreSQL tables. Small, empty,
167
+ or maintenance-window tables may favor simpler transactional DDL.
168
+
169
+ - Create or drop production indexes with `postgresql_concurrently=True` inside
170
+ `op.get_context().autocommit_block()`. Concurrent operations cannot run in a
171
+ transaction block, take longer, have platform restrictions, and can leave an
172
+ invalid index after failure; detect and clean up that state before retrying.
173
+ - Build a unique index concurrently, then attach a unique constraint with
174
+ `USING INDEX` when adding uniqueness without a blocking index build.
175
+ - Add foreign-key and check constraints as `NOT VALID` when validating existing
176
+ rows would exceed the lock budget, then run `VALIDATE CONSTRAINT` separately.
177
+ New writes are still checked after the unvalidated constraint is installed.
178
+ - Account for the unconditional commit before an Alembic autocommit block. Use
179
+ short, per-migration transactions when the migration environment contains
180
+ such operations.
181
+ - Set intentional lock and statement timeouts for operational safety, and make
182
+ retries aware of partially created database objects.
183
+
184
+ ## Evidence
185
+
186
+ Prove the schema against the database engines it supports:
187
+
188
+ - upgrade a fresh database to head;
189
+ - upgrade a representative pre-change database to head;
190
+ - run metadata-versus-database drift detection;
191
+ - exercise constraints, defaults, enum round trips, JSON round trips, cascades,
192
+ and relationship loading;
193
+ - inspect generated SQL for dialect-specific DDL;
194
+ - measure plans for material queries with representative data;
195
+ - test both the expand and contract application versions at their shared schema
196
+ boundary when deployment is staged.
197
+
198
+ Account for every changed column, constraint, relationship, index, and migration
199
+ operation before the schema is complete.
@@ -0,0 +1,31 @@
1
+ # Upstream provenance
2
+
3
+ Adapted from
4
+ [`wispbit-ai/skills`](https://github.com/wispbit-ai/skills/tree/8b2c7d0ceca0204634dd308970629c4cd4a5a05f/skills/sqlalchemy-alembic-expert-best-practices-code-review)
5
+ at commit:
6
+
7
+ ```text
8
+ 8b2c7d0ceca0204634dd308970629c4cd4a5a05f
9
+ ```
10
+
11
+ The upstream skill declares the MIT license in its frontmatter but does not
12
+ provide a repository or adjacent license file at that revision.
13
+
14
+ Devpunks rewrites the source as a stateless schema-design reference, scopes
15
+ online DDL guidance to PostgreSQL conditions, removes arbitrary index-width and
16
+ unconditional concurrency rules, and adds persisted vocabulary, enum storage,
17
+ typed JSON, relational constraints, ORM relationship, and evidence guidance.
18
+
19
+ The persisted-type classification also incorporates the project-agnostic parts
20
+ of Collective Intelligence's `db-schema-review` skill. Collective
21
+ Intelligence-specific ownership, workflow, output, and validation instructions
22
+ are excluded.
23
+
24
+ Implementation details were checked against the official SQLAlchemy, Alembic,
25
+ and PostgreSQL documentation:
26
+
27
+ - <https://docs.sqlalchemy.org/en/20/core/type_basics.html#sqlalchemy.types.Enum>
28
+ - <https://docs.sqlalchemy.org/en/20/orm/cascades.html#using-foreign-key-on-delete-cascade-with-orm-relationships>
29
+ - <https://alembic.sqlalchemy.org/en/latest/api/runtime.html#alembic.runtime.migration.MigrationContext.autocommit_block>
30
+ - <https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY>
31
+ - <https://www.postgresql.org/docs/current/sql-altertable.html>
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "SQLAlchemy Schema Design"
3
+ short_description: "Design robust SQLAlchemy schemas and migrations"
4
+ default_prompt: "Use $sqlalchemy-schema-design to design a safe SQLAlchemy schema and Alembic migration."
@@ -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."