@punks/cli 3.1.11 → 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.
- package/dist/BASELINE_CHANGELOG.md +28 -0
- package/dist/CHANGELOG.md +27 -0
- package/dist/index.js +6 -6
- package/dist/skills/agnostic/docs/writing-beats/LICENSE +21 -0
- package/dist/skills/agnostic/docs/writing-beats/UPSTREAM.md +11 -0
- package/dist/skills/agnostic/docs/writing-fragments/LICENSE +21 -0
- package/dist/skills/agnostic/docs/writing-fragments/UPSTREAM.md +11 -0
- package/dist/skills/agnostic/docs/writing-shape/LICENSE +21 -0
- package/dist/skills/agnostic/docs/writing-shape/UPSTREAM.md +11 -0
- package/dist/skills/agnostic/frontend/frontend-domain-structure/SKILL.md +24 -42
- package/dist/skills/agnostic/frontend/frontend-domain-structure/agents/openai.yaml +1 -1
- package/dist/skills/agnostic/frontend/frontend-domain-structure/references/react/structure.md +51 -78
- package/dist/skills/agnostic/frontend/frontend-domain-structure/references/structure.md +89 -212
- package/dist/skills/agnostic/generic/handoff/LICENSE +21 -0
- package/dist/skills/agnostic/generic/handoff/UPSTREAM.md +11 -0
- package/dist/skills/agnostic/quality/codebase-design/LICENSE +21 -0
- package/dist/skills/agnostic/quality/codebase-design/UPSTREAM.md +11 -0
- package/dist/skills/agnostic/quality/review/LICENSE +21 -0
- package/dist/skills/agnostic/quality/review/UPSTREAM.md +11 -0
- package/dist/skills/agnostic/quality/tdd/LICENSE +21 -0
- package/dist/skills/agnostic/quality/tdd/UPSTREAM.md +11 -0
- package/dist/skills/agnostic/research/improve-codebase-architecture/LICENSE +21 -0
- package/dist/skills/agnostic/research/improve-codebase-architecture/UPSTREAM.md +11 -0
- package/dist/skills/frameworks/effect/effect/SKILL.md +5 -12
- package/dist/skills/frameworks/effect/effect/references/CONFIG.md +10 -19
- package/dist/skills/frameworks/effect/effect/references/SERVICES_LAYERS.md +3 -63
- package/dist/skills/frameworks/effect/effect/references/TESTING.md +2 -72
- package/dist/skills/frameworks/effect/effect-backend-structure/SKILL.md +12 -29
- package/dist/skills/frameworks/effect/effect-backend-structure/agents/openai.yaml +1 -1
- package/dist/skills/frameworks/effect/effect-backend-structure/references/layout.md +9 -9
- package/dist/skills/frameworks/sqlalchemy/sqlalchemy-schema-design/SKILL.md +199 -0
- package/dist/skills/frameworks/sqlalchemy/sqlalchemy-schema-design/UPSTREAM.md +31 -0
- package/dist/skills/frameworks/sqlalchemy/sqlalchemy-schema-design/agents/openai.yaml +4 -0
- package/dist/skills/phases/prototype-phase/agents/openai.yaml +2 -0
- package/dist/skills/phases/review-phase/AUTHORING-HANDOFF.md +622 -0
- package/dist/skills/phases/review-phase/SKILL.md +9 -36
- package/dist/skills/phases/review-phase/phases/prepare-review.md +105 -0
- package/dist/skills/phases/review-phase/phases/retain-report.md +113 -0
- package/dist/skills/phases/review-phase/phases/return-route.md +95 -0
- package/dist/skills/phases/review-phase/phases/router.md +78 -0
- package/dist/skills/phases/review-phase/phases/run-review.md +128 -0
- package/dist/skills/phases/review-phase/references/durable-report.md +11 -30
- package/dist/skills/phases/review-phase/references/runtime-handoff.md +138 -0
- package/package.json +63 -9
- package/dist/skills/phases/review-phase/REFERENCE.md +0 -85
|
@@ -1,42 +1,10 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Module Surfaces, Scoped Work, And Operation Helpers
|
|
2
2
|
|
|
3
|
-
Use this
|
|
3
|
+
Use this for the local module namespace convention, scoped long-lived work, whole-function `Effect.fn` transforms, and operation error helpers. Use `$effect-service-design` for service qualification, service module construction, Layer composition, requirement propagation, test Layers, and audits.
|
|
4
4
|
|
|
5
5
|
## Module Surface
|
|
6
6
|
|
|
7
|
-
One opinionated application-module style uses file-local role names and one canonical ES module namespace projection. Follow the existing codebase's module style when it has one; this convention is not required by Effect.
|
|
8
|
-
|
|
9
|
-
```ts
|
|
10
|
-
export interface Interface {
|
|
11
|
-
readonly get: (id: UserId) => Effect.Effect<User, NotFound | PersistenceError>
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export class Service extends Context.Service<Service, Interface>()(
|
|
15
|
-
"@app/UserRepo",
|
|
16
|
-
) {}
|
|
17
|
-
|
|
18
|
-
export const layer = Layer.effect(
|
|
19
|
-
Service,
|
|
20
|
-
Effect.gen(function* () {
|
|
21
|
-
const sql = yield* SqlClient.SqlClient
|
|
22
|
-
|
|
23
|
-
const get = Effect.fn("UserRepo.get")(function* (id: UserId) {
|
|
24
|
-
// ...
|
|
25
|
-
})
|
|
26
|
-
|
|
27
|
-
return Service.of({ get })
|
|
28
|
-
}),
|
|
29
|
-
)
|
|
30
|
-
|
|
31
|
-
export class NotFound extends Schema.TaggedErrorClass<NotFound>()(
|
|
32
|
-
"UserRepo.NotFound",
|
|
33
|
-
{ id: UserId },
|
|
34
|
-
) {}
|
|
35
|
-
|
|
36
|
-
export * as UserRepo from "./user-repo.js"
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
Consumers use the module namespace.
|
|
7
|
+
One opinionated application-module style uses file-local role names and one canonical ES module namespace projection. Follow the existing codebase's module style when it has one; this convention is not required by Effect. Consumers use the module namespace.
|
|
40
8
|
|
|
41
9
|
```ts
|
|
42
10
|
import { UserRepo } from "./user-repo.js"
|
|
@@ -66,25 +34,6 @@ Guidance:
|
|
|
66
34
|
- The resulting `UserRepo.UserRepo === UserRepo` self-reference is unusual. Use this pattern only where the runtime and toolchain support it; otherwise use named exports or a separate barrel.
|
|
67
35
|
- Export only intentional surface; keep local schemas, row codecs, helpers, and implementation details unexported.
|
|
68
36
|
- Do not introduce TypeScript `namespace` declarations for organization.
|
|
69
|
-
- Use a named service class such as `class UserRepo extends Context.Service...` when an external library or existing codebase does not use module namespace style.
|
|
70
|
-
|
|
71
|
-
## Layer Constructors
|
|
72
|
-
|
|
73
|
-
Choose the layer constructor that matches the thing produced.
|
|
74
|
-
|
|
75
|
-
```ts
|
|
76
|
-
Layer.succeed(Service, impl) // already-built service
|
|
77
|
-
Layer.sync(Service, () => impl) // lazy synchronous service
|
|
78
|
-
Layer.effect(Service, makeEffect) // effectful service acquisition
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
Guidance:
|
|
82
|
-
|
|
83
|
-
- Default real implementations to `Layer.effect(Service, Effect.gen(...))`.
|
|
84
|
-
- Use `Layer.effectContext(...)` when one acquisition intentionally supplies multiple services, especially first-class test stubs or one client backing several service tags.
|
|
85
|
-
- Use `Layer.unwrap(...)` when config or runtime discovery chooses/builds the layer.
|
|
86
|
-
- Use `Layer.fresh(...)` or `Effect.provide(layer, { local: true })` only when a test or operation needs isolated acquisition.
|
|
87
|
-
- Use `Context.Reference` rarely, only for ambient/defaultable runtime references where a safe default is real.
|
|
88
37
|
|
|
89
38
|
## Long-Lived Work
|
|
90
39
|
|
|
@@ -109,15 +58,6 @@ Guidance:
|
|
|
109
58
|
- Do not run forever work inline during layer acquisition.
|
|
110
59
|
- Do not expose public `start` methods unless the domain explicitly needs manual lifecycle control.
|
|
111
60
|
|
|
112
|
-
## Runtime Wiring
|
|
113
|
-
|
|
114
|
-
- Use `Layer.provide(...)` to hide an implementation dependency.
|
|
115
|
-
- Use `Layer.provideMerge(...)` only when the dependency should remain exposed for downstream consumers.
|
|
116
|
-
- Use `Layer.mergeAll(...)` for independent exposed layers.
|
|
117
|
-
- Prefer flat, topologically sorted runtime layer values with named subgraphs.
|
|
118
|
-
- Avoid using `provideMerge` as a blind make-it-compile tool.
|
|
119
|
-
- Avoid hiding important authority or lifecycle dependencies behind broad invisible provisioning.
|
|
120
|
-
|
|
121
61
|
## Effect.fn
|
|
122
62
|
|
|
123
63
|
Use extra `Effect.fn(...)` arguments for wrappers that apply to the whole function call. Each transform receives `(effect, ...originalArgs)`.
|
|
@@ -1,27 +1,17 @@
|
|
|
1
1
|
# Testing
|
|
2
2
|
|
|
3
|
-
Use this when writing Effect tests
|
|
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
|
|
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
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
79
|
-
- Integration tests use
|
|
80
|
-
-
|
|
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
|
|
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
|
-
|
|
37
|
+
Composition file placement:
|
|
38
38
|
|
|
39
|
-
- `platform/effect/app.ts` or local equivalent
|
|
40
|
-
- `platform/effect/request.ts` or local equivalent
|
|
41
|
-
- `features/<domain>/layer.ts`
|
|
42
|
-
- `features/<domain>/tests/support
|
|
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
|
-
|
|
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
|
-
|
|
62
|
+
feature-local reusable test support
|
|
63
63
|
- `tests/unit`
|
|
64
|
-
action and guard behavior
|
|
64
|
+
action and guard behavior
|
|
65
65
|
- `tests/integration`
|
|
66
|
-
live router/app behavior
|
|
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>
|