@domain-first/project-structure 8.6.1 → 8.7.1

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 (51) hide show
  1. package/README.md +1 -1
  2. package/bin/df-skills.mjs +55 -9
  3. package/dist/287.js +44 -138
  4. package/dist/38.js +36 -0
  5. package/dist/561.js +9 -1
  6. package/dist/947.js +11 -1
  7. package/dist/agent-cli.d.ts +9 -2
  8. package/dist/agent-principles.cjs +116 -0
  9. package/dist/agent-principles.d.ts +9 -0
  10. package/dist/agent-principles.js +64 -0
  11. package/dist/agent-principles.spec.d.ts +1 -0
  12. package/dist/agent-requests.d.ts +16 -2
  13. package/dist/graph.cjs +10 -0
  14. package/dist/in-memory-db.d.ts +1 -6
  15. package/dist/index.cjs +64 -137
  16. package/dist/index.js +4 -1
  17. package/dist/init.cjs +12 -21
  18. package/dist/integration.cjs +61 -137
  19. package/dist/lint.cjs +46 -0
  20. package/dist/react.cjs +61 -137
  21. package/dist/use-cases/add-integration.d.ts +1 -1
  22. package/dist/use-cases/index.d.ts +1 -0
  23. package/dist/use-cases/scaffold-new-infrastructure-helper.d.ts +7 -0
  24. package/dist/wiring.d.ts +2 -2
  25. package/package.json +3 -2
  26. package/principles/df-principles.md +33 -0
  27. package/skills/df-ps-implement/SKILL.md +26 -1
  28. package/skills/df-ps-plan-feature/SKILL.md +22 -18
  29. package/skills/df-ps-react/SKILL.md +2 -9
  30. package/skills/df-ps-react/references/generators.md +9 -9
  31. package/skills/df-ps-scaffold/SKILL.md +20 -126
  32. package/skills/df-ps-scaffold/references/agent-mode.md +2 -2
  33. package/skills/df-ps-scaffold/references/agent-operations.md +1 -0
  34. package/skills/df-ps-scaffold/references/choosing-components.md +65 -49
  35. package/skills/df-ps-scaffold/references/generators.md +33 -11
  36. package/skills/df-ps-scaffold/references/units/aggregate.md +3 -5
  37. package/skills/df-ps-scaffold/references/units/bounded-context.md +1 -1
  38. package/skills/df-ps-scaffold/references/units/command-query.md +6 -8
  39. package/skills/df-ps-scaffold/references/units/delete.md +0 -2
  40. package/skills/df-ps-scaffold/references/units/endpoint.md +1 -4
  41. package/skills/df-ps-scaffold/references/units/entity-value-object.md +0 -4
  42. package/skills/df-ps-scaffold/references/units/errors.md +0 -4
  43. package/skills/df-ps-scaffold/references/units/helper.md +30 -0
  44. package/skills/df-ps-scaffold/references/units/implementation.md +1 -5
  45. package/skills/df-ps-scaffold/references/units/move-or-rename.md +0 -4
  46. package/skills/df-ps-scaffold/references/units/port.md +3 -6
  47. package/skills/df-ps-scaffold/references/units/services.md +4 -6
  48. package/skills/df-ps-scaffold/references/units/use-case.md +1 -2
  49. package/skills/df-ps-scaffold/references/units/wire-dependency.md +0 -2
  50. package/skills/df-ps-scaffold/references/work-plan.md +73 -0
  51. package/skills/df-ps-scaffold/scripts/drive.mjs +0 -252
@@ -1,15 +1,13 @@
1
1
  # Aggregate and repository
2
2
 
3
- When: a thing with identity, lifecycle, and rules about its own state, owned by this context and stored on its own (`../choosing-components.md`, step 4). A rule about its own state is a method on it (step 7), not a new unit. Loading/saving one aggregate is a repository method, not a query or command.
3
+ When: a thing with identity, lifecycle, and rules about its own state, owned by this context and stored on its own (`../choosing-components.md`, step 4). A rule about its own state is a method on it (step 7), not a new unit. Loading aggregates to change them or check their rules, and saving them, is a repository method. Returning data to a reader is a query, even for one aggregate.
4
4
 
5
5
  ## Generate (context only)
6
6
 
7
7
  Prompts: name → `With Repository` → primary implementation select → `Add a test implementation` → test implementation select if yes → {wire} dependencies per implementation. Each select contains saved repository types for that role, available system types and both manual-entry actions (`../generators.md`). `System: in-memory (uses the shared in-memory database)` appears only with the shared DB enabled and scaffolded. There are no ordinary presets; default to the first available saved/system choice, otherwise manual entry.
8
8
 
9
- `… pick:Domain "pick:New Aggregate" text:order yes "pick:Enter implementation type and save for future use" text:prisma yes "pick:System: in-memory"` (with the shared DB ready; otherwise enter the test type manually).
10
-
11
9
  - Custom types entered with the save action are staged in the shared config under `backend.implementations.repositories.primary` or `backend.implementations.repositories.test` and offered on later runs, including in other contexts. Both manual-entry actions from `../generators.md` are available; the run-only action generates the repository without remembering its type.
12
- - `<C>/domain/aggregates/n/`: `n.aggregate-root.ts` (`class N extends domainType()` {types}), `index.ts`, spec; with repository: `n-repository.ts` (`abstract class NRepository`), spec
10
+ - `<C>/domain/aggregates/n/`: `n.aggregate-root.ts` (`class N extends domainType()` {types}), `index.ts`, spec; with repository: `n-repository.ts` (`abstract class NRepository`), no spec
13
11
  - `<C>/infrastructure/repositories/I/I-n-repository.ts` per implementation (`class INRepository implements NRepository`)
14
12
  - {wire} `<C>/wiring/repositories/wire-n-repository.ts` (env-branched)
15
13
  - With `backend.withInMemoryDb` in the config, the `in-memory` implementation can keep its section of the DB: `private readonly data: InMemoryDbInfrastructureService['ns']`, set in the constructor from its `inMemoryDbInfrastructureService` parameter; `ns = this.section<N>('NS');` is added to `<rootFolder>/shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts` if missing (`N` needs an `id`). Without {wire} this always happens. {wire} `Dependencies for InMemoryNRepository:` lists the DB under `Suggested`, checked: kept, it gets the section and `wireInMemoryDbInfrastructureService` in its `wireClass`; unchecked, the implementation stays empty (`constructor() {}`) and no section is added.
@@ -45,4 +43,4 @@ export class Order extends domainType(
45
43
 
46
44
  ## Test
47
45
 
48
- Extend the generated specs in the same files: aggregate rules on the root, the repository contract against the test implementation.
46
+ Extend the generated spec of the root with the aggregate rules. The repository has no unit spec: it is infrastructure, tested through integration tests and the use cases that inject its test implementation.
@@ -4,7 +4,7 @@ When: a concept with its own lifecycle and vocabulary, or a different business o
4
4
 
5
5
  ## Generate
6
6
 
7
- `"pick:Scaffold new bounded context" text:sales` → empty folder `<rootFolder>/bounded-contexts/sales/`. No error namespace until the first error ([errors](errors.md)).
7
+ Creates an empty folder `<rootFolder>/bounded-contexts/sales/`. No error namespace until the first error ([errors](errors.md)).
8
8
 
9
9
  Name: a business area in kebab-case (`sales`, `reviews`), not a feature.
10
10
 
@@ -1,18 +1,15 @@
1
1
  # Command and query
2
2
 
3
- When (`../choosing-components.md`, step 11): one atomic read/write on this context's own storage that is not "load/save one aggregate" (read model, report, bulk update). Another context or external system is reached through a port (`port.md`).
3
+ When (`../choosing-components.md`, step 11): one atomic read/write on this context's own storage that doesn't load aggregates to change them or check their rules (read model, data for a reader, report, bulk update). Another context or external system is reached through a port (`port.md`).
4
4
 
5
5
  - One atomic operation of one kind of storage implementation: several statements in one transaction count as one. Several operations, a mix of storages, or logic between steps → several queries/commands, composed in a use case.
6
- - A query only reads: it never changes any state, not even idempotently, and never calls a command. A command returns nothing or the minimum needed to use its result later (e.g. a created ID); read changed data with a query.
6
+ - A query only reads: it never changes any state, not even idempotently, and never calls a command. A command returns nothing or only what is needed to get the result of its work (e.g. a created ID), never the changed data itself: read that with a query.
7
7
 
8
8
  ## Generate (context only)
9
9
 
10
10
  Prompts: name → primary implementation select → `Add a test implementation` → test implementation select if yes → {wire} dependencies per implementation. Menus contain saved types from `commands` or `queries` for the selected role, active system types and both manual-entry actions (`../generators.md`). Only `System: in-memory (uses the shared in-memory database)` can be automatic here, when its integration is ready. `api` and `mock` must be saved or entered manually. The first saved/system choice is the default, otherwise manual entry without a suggested name. Saving stages the new ordinary label for that category/role; run-only input leaves the catalog unchanged.
11
11
 
12
- `… pick:Application "pick:New Command" text:place-order "pick:Enter implementation type and save for future use" text:prisma yes "pick:System: in-memory"` (with the shared DB ready).
13
- `… pick:Application "pick:New Query" text:order-summary "pick:Enter implementation type for this run only" text:sql no`
14
-
15
- - `<C>/application/commands/n-command.ts`: abstract `NCommand` ({handlers} schemas + abstract `handle: Handler<…>`), spec
12
+ - `<C>/application/commands/n-command.ts`: abstract `NCommand` ({handlers} schemas + abstract `handle: Handler<…>`), no spec
16
13
  - `<C>/infrastructure/commands/I/I-n-command.ts` per implementation (`extends NCommand`, implements `handle`)
17
14
  - {wire} `<C>/wiring/commands/wire-n-command.ts` (env-branched)
18
15
  - With `backend.withInMemoryDb` in the config, the `in-memory` implementation can get the whole DB: `constructor(private readonly inMemoryDbInfrastructureService: InMemoryDbInfrastructureService)`. No section is added. Without {wire} this always happens; {wire} it is the checked `Suggested` choice of `Dependencies for InMemoryN<Suffix>:`, and unchecking it leaves the implementation empty.
@@ -24,9 +21,10 @@ Queries: the same with `query` / `queries`.
24
21
  - Queries and commands never import neighboring contexts. `cross-context` is reserved for port adapters and is unavailable here, including as a custom label.
25
22
  - {handlers} The abstract contract holds static schemas and `abstract handle`; replace the `{}` schemas with real ones. Each infrastructure implementation defines `handle` with the contract's schemas and writes its `handler` callback.
26
23
  - An implementation performs its one operation with no business logic or surrounding steps. Its wired dependencies are infrastructure services (the database client it runs on); repositories, ports, domain services and other queries/commands stay with the consuming use case.
27
- - Input/output use this context's domain models; time comes through input, never through the clock port.
24
+ - Query input and command input use this context's domain models; time comes through input, never through the clock port.
25
+ - A query never returns a domain model as its output. Its output is an independent DTO, needed only in the context of this query: it is defined by the query's `outputSchema` and isn't shared with other queries, even when the fields match. Fields of the DTO may use value objects and even entities, but the DTO itself is always a separate type.
28
26
  - An `in-memory` implementation works on the in-memory DB when configured; `mock`/`stub` implementations may return fixed data.
29
27
 
30
28
  ## Test
31
29
 
32
- Extend the generated spec: the handler against the test implementation via `handle(...)`.
30
+ No unit spec: a command or query is infrastructure, tested through integration tests and the use cases that inject its test implementation.
@@ -6,8 +6,6 @@ When: a module is no longer needed. Never delete module files by hand: the CLI r
6
6
 
7
7
  Prompts: `Module to delete:` (select, grouped by kind as in Move or rename) → `Delete?` (default No).
8
8
 
9
- `… "pick:Delete" pick:orders yes`
10
-
11
9
  JSON: `{ "operation": "delete", "context": "sales", "module": "query:orders" }`.
12
10
 
13
11
  Deleted: the files of the unit, as Move or rename moves them (an aggregate with its whole folder, entities and value objects inside included). Cleaned up: an entity's or value object's `export *` in its aggregate's `index.ts`, and an aggregate's in-memory DB section with its import.
@@ -6,9 +6,6 @@ When: an HTTP entry point (`../choosing-components.md`, step 2). It exposes a qu
6
6
 
7
7
  Prompts: controller (select: `(root) — /<C>` | existing | `New controller` → name) → method (`get` `post` `patch` `delete` `put`) → relative path (may be empty: `default`) → {wire} `Handler:` (select: queries, commands, and use cases of `<C>`, grouped; skipped if there are none).
8
8
 
9
- `… pick:Presentation "pick:New Handlers" "pick:New controller" text:orders pick:get text:recent pick:RecentOrdersQuery`
10
- `… pick:Presentation "pick:New Handlers" pick:orders pick:post default pick:PlaceOrder`
11
-
12
9
  For `sales`, `orders`, `get`, `recent`:
13
10
 
14
11
  - `<C>/presentation/rest/orders/recent/GET.ts`: `class OrdersRecentGetEndpoint(endpointGenerator, handler)`, route `['sales','orders','recent']`. `endpointGenerator: RestEndpointGeneratorPresentationService` (the Shared Kernel generator) and `handler: RecentOrdersQuery` (`never` without a pick), both `import type`. `get handle()` calls `this.endpointGenerator(...)`, which doesn't compile until a generating getter is picked (`this.endpointGenerator.withoutGuards(...)`); that's expected, not a generator bug. Projects without the generator file get `EndpointGenerator` from handlers-rest.
@@ -24,7 +21,7 @@ The same controller, path, and method replace the existing endpoint (after `Over
24
21
  1. Generator: `df-init` (or the `REST endpoint generator` integration) creates `RestEndpointGeneratorPresentationService` in `<rootFolder>/shared-kernel/presentation/services/`; every endpoint uses it. Set the module-level `const adapter` above the class (`undefined` until set) to the HTTP framework's adapter; the class reads it through closure. If the Next adapter was connected, the file already imports `nextAdapter` from `@domain-first/handlers-next` and passes it instead; just make sure that package is installed.
25
22
  2. Errors: invalid requests (`400`) are answered by `invalidRequest()` of `@domain-first/handlers-rest` in `errors`; don't map `RequestParsingError` / `InputMappingError` by hand, add your own mappings next to it: `errors: [httpError(MyError, 404), invalidRequest()]`. Map domain errors with `httpError(ErrorClass, status, { description, message, details: { schema, map } })` (one class) or `httpStatus(status, { code, match })` (many errors, one code); the first match wins, so put specific mappings first, importing them from the contexts' `domain/errors` (the only thing `shared-kernel/` may import from a context, besides domain models in the in-memory DB).
26
23
  3. A new kind of endpoint (auth, other context) is a new getter returning `createEndpoint({ context, errors: [..., invalidRequest()] })(adapter) as EndpointGenerator` (`nextAdapter` with the Next adapter), next to `withoutGuards`.
27
- 4. Complete `get handle()`: pick the generating getter that fits the endpoint (`this.endpointGenerator.withoutGuards(...)`, or one with the needed guards), then `.input(...)`, `.mapInput(...)`, optional `.output(...)`, `.mapOutput(...)`.
24
+ 4. Complete `get handle()`: pick the generating getter that fits the endpoint (`this.endpointGenerator.withoutGuards(...)`, or one with the needed guards), then `.input(...)`, `.mapInput(...)`, optional `.output(...)`, `.mapOutput(...)`. They check only the shape of the request: a condition on the input as a whole belongs to the use case (`use-case.md`, "The use case checks that its input makes sense"), so no `refine` or checks in `mapInput` for it. `get handle()` doesn't compile until a guard is chosen, on purpose: there is no default, so a protected endpoint can't be left open by accident. Choose by who may call the endpoint. `withoutGuards` is only for endpoints that are public by design, never a way to make the code compile. If the access rules aren't specified, ask. A guard the generator doesn't have yet is a new getter (step 3).
28
25
  5. Register `restHandlers` from `<rootFolder>/presentation/rest/index.ts` in the server bootstrap (`df-ps-scaffold` `SKILL.md`, rule 2, exception 5). With the Next adapter and wire, `app/api/[...path]/route.ts` (or `src/app/…`) already serves them through `nextEndpoints(restHandlers)`; it compiles once the first endpoint exists.
29
26
 
30
27
  After new endpoints, regenerate the OpenAPI document and the API client with the project's scripts (Running in the plan).
@@ -6,10 +6,6 @@ When (`../choosing-components.md`, steps 5–6): used only inside one aggregate
6
6
 
7
7
  Prompts: name → aggregate (select: existing aggregate folders | `No aggregate`; asked only if `<C>/domain/aggregates/` has aggregates, so never in Shared Kernel).
8
8
 
9
- `… pick:Domain "pick:New Entity" text:order-line pick:order`
10
- `… pick:Domain "pick:New Value Object" text:money "pick:No aggregate"`
11
- `"pick:Shared Kernel" pick:Domain "pick:New Value Object" text:money`
12
-
13
9
  - In an aggregate: `<C>/domain/aggregates/a/entities/n.entity.ts` or `<C>/domain/aggregates/a/value-objects/n.value-object.ts` (`class N extends domainType()` {types}), spec; `export * from './entities/n.entity'` (or `./value-objects/n.value-object`) appended to the aggregate's `index.ts`
14
10
  - `No aggregate`: `<C>/domain/entities/n.entity.ts` or `<C>/domain/value-objects/n.value-object.ts`, spec; no barrel
15
11
 
@@ -6,10 +6,6 @@ When: a business failure callers must recognize (`../choosing-components.md`, st
6
6
 
7
7
  First prompt (select): `New error without namespace` | `New namespace` | `New error in namespace <ns>`, then a name.
8
8
 
9
- `… pick:Domain pick:Errors "pick:New namespace" text:order`
10
- `… pick:Domain pick:Errors "pick:New error in namespace order" text:not-found`
11
- `… pick:Domain pick:Errors "pick:New error without" text:order-closed`
12
-
13
9
  - Without namespace: appends `export class N extends CtxErrors.define('n') {}` to `<C>/domain/errors/index.ts`; the first one also puts `CtxErrors = errorNamespace('ctx')` (with its import) at the top of `index.ts`
14
10
  - New namespace: `<C>/domain/errors/ns.ts` (`NsErrors = errorNamespace('ctx').subnamespace('ns')`) + `export * from './ns'` in `index.ts`
15
11
  - In namespace: appends `export class NsN extends NsErrors.define('n') {}` to `ns.ts` (namespace first), extending the namespace the file exports
@@ -0,0 +1,30 @@
1
+ # Infrastructure helper
2
+
3
+ When (`../choosing-components.md`, step 14): stateless technical code of one implementation type: a mapper between storage and domain, a query builder, an error translator. No class, no wire, no state. If it needs a dependency or several implementation types share it (cursor encoding for `prisma` and `in-memory`, retry for several adapters), it is an infrastructure service (`services.md`). Other layers have no helpers: domain logic belongs in the model, application logic in a use case or application service, presentation logic in a presentation service.
4
+
5
+ ## Generate (context and Shared Kernel)
6
+
7
+ Prompts: `Name (folders split by "/"):` → `Implementation:` (a type the project already has).
8
+
9
+ JSON: `{ "operation": "helper", "context": "sales", "name": "mappers/social-network-type", "implementationType": "prisma" }`.
10
+
11
+ - `<C>/infrastructure/helpers/I/<folders>/I-n.ts` (`export const iN = () => {}`), no spec
12
+
13
+ A name that already starts with the type (`prisma-errors`) doesn't get the prefix twice. A helper of a type that isn't saved yet can't be generated: add an implementation of that type first, saving the type.
14
+
15
+ ## Implement
16
+
17
+ Replace the stub. Rename the function and add more next to it freely. Use the helper by importing it directly: it isn't injected or listed under `Dependencies:`.
18
+
19
+ - Location: always inside the folder of its type, nothing right under `helpers/`.
20
+ - Imports: domain models, helpers of its type, and `import type` of query, command and port contracts. No repositories, domain services, services or implementations.
21
+ - Used by: implementations of its type and infrastructure services. Never by wiring, application, presentation, or another context; a helper of the Shared Kernel is available to implementations of its type in every context.
22
+ - `npx df-lint` checks all of this except that a helper is stateless.
23
+
24
+ ## Move and delete
25
+
26
+ Helpers are not modules: `Move or rename` and `Delete` don't list them, so edit them by hand.
27
+
28
+ - A module that uses a helper can't move to another context while the helper stays behind: the CLI refuses and names the imports. Move the helper by hand first, then the module.
29
+ - `Delete` of a module refuses while a helper imports it. Delete or change the helper by hand first.
30
+ - Renaming a module inside its context leaves the helper's file name as it was: rename it by hand if it no longer fits.
@@ -6,10 +6,6 @@ When: a repository, command, query or port already exists and needs one more imp
6
6
 
7
7
  Prompts: `Contract:` → `Implementation type:` → {wire} `Environments:` (at least one) → {wire} dependencies for the new implementation. The type menu merges the category's primary/test history with active system choices and both manual-entry actions (`../generators.md`); it has no ordinary `api`, `mock` or `in-memory` presets. System choices are explicitly marked and conditional: cross-context for ports with a neighbor, shared in-memory DB for repositories/commands/queries with that integration ready. Existing types are disabled. Saving a new ordinary label registers it under `test` and/or `primary` according to selected environments (primary without usable wiring). The run-only action registers nothing.
8
8
 
9
- `… pick:Infrastructure "pick:New Implementation" pick:file-storage "pick:Enter implementation type and save for future use" text:local toggle:2`
10
-
11
- `toggle:` numbers the environments top to bottom: 1 `test`, 2 `development`, 3 `production`.
12
-
13
9
  - `<C>/infrastructure/<kind>/I/I-n….ts` as the contract's generator creates it (in-memory DB included)
14
10
  - {wire} `~ <C>/wiring/<kind>/wire-n….ts`: import, `const wireIImplementation = wireClass(IN…, [])` before the module's wire, the chosen environments of `envBranchedWire` point at it
15
11
 
@@ -17,4 +13,4 @@ An implementation left without environments stays in the wire file; the CLI prin
17
13
 
18
14
  ## Implement and test
19
15
 
20
- As the implementations of the contract's unit file. The spec of the contract wires what `NODE_ENV=test` uses: only a new `test` implementation changes what it tests.
16
+ As the implementations of the contract's unit file. Contracts have no unit spec; specs of the use cases that inject the contract wire what `NODE_ENV=test` uses: only a new `test` implementation changes what they test.
@@ -6,10 +6,6 @@ When: a module's name no longer fits, or it belongs elsewhere: another bounded c
6
6
 
7
7
  Prompts: `Module:` (select, grouped by kind; entities and value objects of an aggregate show it: `order-line (order)`) → `Move to:` (`Bounded Context: <current> (stays)`, other contexts, `Shared Kernel` for the kinds it has) → `Aggregate:` (entities and value objects only, when the target context has aggregates: `No aggregate` or one of them) → `New name:` (default: the current one) → `Apply?`.
8
8
 
9
- `… "pick:Move or rename" pick:order "pick:Bounded Context: sales" text:purchase yes`
10
- `… "pick:Move or rename" pick:money "pick:Shared Kernel" default yes`
11
- `… "pick:Move or rename" pick:order-line "pick:Bounded Context: sales" "pick:No aggregate" default yes`
12
-
13
9
  Every file of the module moves (contract, implementations, wire, specs; an aggregate with its whole folder), every import of it follows, and derived names change in the module and its importers: `OrderRepository`, `PrismaOrderRepository`, `wireOrderRepository`, dependents' `orderRepository` parameters, an aggregate's in-memory DB section. An entity leaving its aggregate is no longer re-exported there; its importers import its file.
14
10
 
15
11
  Before `Apply?` the CLI lists the files to move and to update: check that they are the module's files and its importers. A move that would introduce a forbidden context import prints `Nothing was moved: these imports would cross a bounded context boundary.` with the imports: nothing changed. Fix the design instead (`../choosing-components.md`, step 9: the consuming context gets a port with a cross-context adapter), or move the dependency first.
@@ -1,15 +1,12 @@
1
1
  # Port
2
2
 
3
- When: a capability across this context's boundary: another bounded context, an external system, time or configuration (`../choosing-components.md`, steps 9–10). Own aggregate persistence → repository; atomic operations on this context's own storage → command/query. One method is enough. Wanting to mock a class or imagining multiple implementations does not by itself establish a boundary. The `clock` and `config` ports usually belong in the Shared Kernel.
3
+ When: a capability across this context's boundary: another bounded context, an external system, time or configuration (`../choosing-components.md`, steps 9–10). Own aggregate persistence → repository; atomic operations on this context's own storage → command/query. One method is enough. Wanting to mock a class or imagining multiple implementations does not by itself establish a boundary. The `clock` and `application-config` ports usually belong in the Shared Kernel.
4
4
 
5
5
  ## Generate (context and Shared Kernel)
6
6
 
7
7
  Prompts: name → primary adapter select → `With test implementation` → test adapter select if yes → {wire} dependencies per adapter. Both selects show saved port types for their role, active system types and both manual-entry actions (`../generators.md`). The only automatic system choice is `System: cross-context (calls handlers in another bounded context)`, conditional on a neighboring context and unavailable in the Shared Kernel. No `api`, `mock` or `in-memory` presets are inserted for ports. The first saved/system choice is the default; manual input is empty without saved choices. Existing labels are disabled. Saved ordinary port types are isolated from other categories. Save-entry updates `ports` history; run-only entry generates the adapter without updating the catalog.
8
8
 
9
- `… pick:Application "pick:New Port" text:payment-gateway "pick:Enter implementation type and save for future use" text:api yes "pick:Enter implementation type and save for future use" text:mock`
10
- `… pick:Application "pick:New Port" text:billing-gateway "pick:System: cross-context" yes "pick:Enter implementation type for this run only" text:mock`
11
-
12
- - `<C>/application/ports/n.ts` (abstract `N`; name it after the capability), spec
9
+ - `<C>/application/ports/n.ts` (abstract `N`; name it after the capability), no spec
13
10
  - `<C>/infrastructure/application-adapters/I/I-n.ts` per implementation (`class IN extends N`)
14
11
  - {wire} `<C>/wiring/application-ports/wire-n.ts` (env-branched)
15
12
 
@@ -19,7 +16,7 @@ Prompts: name → primary adapter select → `With test implementation` → test
19
16
  - For another context, define the port in the consuming context with its own models and errors. A `cross-context` adapter can inject queries, commands and use cases from any neighboring context; choices are labelled `(<context>)` and names get context-qualified aliases. Only this adapter imports neighboring handler types, and only its matching wiring imports their factories. Never import foreign models, errors, repositories, ports, services, infrastructure or barrels.
20
17
  - Implement the capability's methods by mapping input, invoking injected handlers, and mapping results/errors. The CLI creates the contract, adapters and dependencies; it does not generate methods or delegation. Keep business coordination in the consuming use case.
21
18
  - One implementation per adapter: `api` performs the real interaction (an SDK or HTTP client, through an [infrastructure service](services.md) for the client); `mock`/`fake` is deterministic.
22
- - Use the Shared Kernel `clock` port instead of `new Date()` / `Date.now()` in domain and application code, and a `config` port instead of `process.env` / `import.meta.env`. Its adapter reads the environment; infrastructure and wiring may read it directly.
19
+ - Use the Shared Kernel `clock` port instead of `new Date()` / `Date.now()` in domain and application code, and an `application-config` port instead of `process.env` / `import.meta.env`. Its adapter reads the environment; infrastructure and wiring may read it directly.
23
20
 
24
21
  ## Test
25
22
 
@@ -4,25 +4,23 @@ When (`../choosing-components.md`, steps 12–15, "Port or service?"):
4
4
 
5
5
  - **Domain service**: a rule at the junction of several entities / value objects not all belonging to one aggregate, no I/O. It takes the aggregates and values it needs as arguments; loading them is the caller's job. In the Shared Kernel only for junctions of universal types.
6
6
  - **Application service**: application logic reused by 2+ use cases, with external interaction or storage access delegated to injected ports, commands or queries. A composition needed by one use case stays in it.
7
- - **Infrastructure service**: a technical helper used only by infrastructure code; also the home of a value that isn't a wired module (a database or SDK client, a config value), named after the implementation label (`prisma`, `stripe`).
7
+ - **Infrastructure service**: a technical helper used only by infrastructure code that has state or dependencies or is shared by several implementation types (stateless code of one type is an [infrastructure helper](helper.md)); also the home of a value that isn't a wired module (a database or SDK client, a config value), named after the implementation label (`prisma`, `stripe`).
8
8
  - **Presentation service**: a helper used only by presentation code.
9
9
 
10
10
  ## Generate (context and Shared Kernel)
11
11
 
12
12
  Prompts: name → {wire} `Dependencies:` (`../generators.md`). `L` = `domain` | `application` | `infrastructure` | `presentation`.
13
13
 
14
- `… pick:Application "pick:New Service" text:checkout`
15
-
16
- - `<C>/L/services/n-L-service.ts` (`class NLService`, e.g. `CheckoutApplicationService`), spec
14
+ - `<C>/L/services/n-L-service.ts` (`class NLService`, e.g. `CheckoutApplicationService`), spec except for `infrastructure`
17
15
  - {wire} `<C>/wiring/L-services/wire-n-L-service.ts` (`wireClass(X, [])`)
18
16
 
19
17
  ## Implement
20
18
 
21
19
  - Domain services take and return domain types. Pure: no I/O, ports, or repositories, not even injected ones; they work with the data they are handed. They depend only on other domain services.
22
20
  - Application services have no `handle`: a use case is how an endpoint reaches their logic. They call injected ports, commands and queries, never external SDKs, HTTP clients, or another context directly.
23
- - Infrastructure services: an external client or config value is created or read by the service itself (`readonly client = new PrismaClient()`), with no constructor parameter for it. Implementations get the service through `df-scaffold`, where it shows up under `Suggested`. Wrap its wire in `memoWire(...)` when one instance must be shared (a connection pool, an in-memory store). No `wireValue(...)`.
21
+ - Infrastructure services: an external client or config value is created or read by the service itself (`readonly client = new PrismaClient()`), with no constructor parameter for it. Implementations get the service through `df-scaffold`. Only `prisma-infrastructure-service` for `prisma` and `in-memory-db-infrastructure-service` for `in-memory` come checked under `Suggested`; select any other service explicitly. Wrap its wire in `memoWire(...)` when one instance must be shared (a connection pool, an in-memory store). No `wireValue(...)`.
24
22
  - Infrastructure never sees application services. Logic infrastructure needs from one: pure logic without ports → a domain service; logic over ports → call the ports directly; technical (mapping, retries, external API formats) → an infrastructure service.
25
23
 
26
24
  ## Test
27
25
 
28
- Test a service's logic with fake dependencies in its generated spec.
26
+ Test a domain, application or presentation service's logic with fake dependencies in its generated spec. Infrastructure services have no unit spec: integration tests cover them.
@@ -6,8 +6,6 @@ When: one business action a user or system triggers that doesn't fit into a sing
6
6
 
7
7
  Prompts: name → {wire} `Dependencies:` (`../generators.md`; use cases never see use cases by default).
8
8
 
9
- `… pick:Application "pick:New Use Case" text:place-order`
10
-
11
9
  - `<C>/application/use-cases/n-use-case.ts`: {handlers} schemas + `handle = defineHandler(...)`, else an empty class; spec
12
10
  - {wire} `<C>/wiring/use-cases/wire-n-use-case.ts`
13
11
 
@@ -18,6 +16,7 @@ Generate its dependencies (repositories, ports, commands, queries, application s
18
16
  - {handlers} The member is `handle = defineHandler({ inputSchema, outputSchema, handler })`. Replace the static `{}` schemas with real ones and write the logic in the `handler` callback; dependencies come through the constructor.
19
17
  - It composes repositories, ports, commands, queries and domain services: loads aggregates, calls their methods, saves them. Reading the time: the `clock` port, then pass the time into commands and queries in their input.
20
18
  - A rule about a set of aggregates: a repository method that queries it, plus a check and a domain error here.
19
+ - **The use case checks that its input makes sense.** The HTTP layer checks the shape of each request part: types, formats, required fields (through the value objects' schemas). Whether the input as a whole makes sense for the scenario ("at least one field to change") is the use case's job. It throws a domain error (`NothingToEdit`), and the endpoint maps it in `errors` (`httpError(NothingToEdit, 400)`). Don't express such conditions with `refine` in the request schema or the use case's `inputSchema`, or with checks in `mapInput`: the client would get a generic `invalid-request`, and other callers of the use case would skip the check. If the endpoint calls a single command or query, such a check is a reason to add a use case: it isn't a proxy.
21
20
  - Call others' handlers with `x.handle(input)` (returns a result) or `x.handle.unsafe(input)` (throws).
22
21
 
23
22
  ## Test
@@ -6,8 +6,6 @@ When: an existing wired module needs a new dependency (`df-ps-scaffold` `SKILL.m
6
6
 
7
7
  Prompts: module (select: wired modules of `<C>`, grouped as in `Dependencies:`, endpoints excluded; an env-branched module is listed once per implementation, e.g. `UserRepository (prisma)`, `UserRepository (in-memory)`) → `Dependencies:`, or `Dependencies for <Implementation>:` for the chosen implementation only (`../generators.md`). Modules already in the wire are not listed. If nothing fits, it prints `No dependencies available for this module.` and changes nothing.
8
8
 
9
- `"pick:Bounded Context: users" "pick:Wire dependency" "pick:UserRepository (prisma)" toggle:1`
10
-
11
9
  Edits the wire and the implementation classes in place; this never triggers `Overwrite them?`. List it in the plan as a run for the existing module.
12
10
 
13
11
  ## Implement
@@ -0,0 +1,73 @@
1
+ # Work plan format
2
+
3
+ How to write the plan that `SKILL.md`, rule 1, requires. Show it in this format and stop:
4
+
5
+ ```markdown
6
+ **Plan: order cancellation**
7
+
8
+ **Scaffolding**
9
+
10
+ **sales**
11
+
12
+ Why here: cancelling changes the order's status; orders belong to sales.
13
+
14
+ What will be scaffolded:
15
+
16
+ | Layer | Type | Name | Details | Why |
17
+ | --- | --- | --- | --- | --- |
18
+ | **domain** | error | order-already-shipped | | shipped orders can't be cancelled |
19
+ | **application** | command | cancel-order | prisma, fake in tests | one atomic status change |
20
+ | | query | cancellable-orders | prisma | read-only list for the UI |
21
+ | **presentation** | endpoint | POST orders/:id/cancel | → cancel-order | UI calls it over HTTP |
22
+
23
+ **billing**
24
+
25
+ Why here: refunds are payments; payments belong to billing.
26
+
27
+ What will be scaffolded:
28
+
29
+ | Layer | Type | Name | Details | Why |
30
+ | --- | --- | --- | --- | --- |
31
+ | **application** | port | order-refunds | cross-context, stub in tests | paid amount lives in sales |
32
+ | | use case | refund-cancelled-order | deps: OrderRefunds, PaymentGateway | read order, then call provider |
33
+
34
+ **React**
35
+
36
+ Why here: the user cancels from the order screen.
37
+
38
+ What will be scaffolded:
39
+
40
+ | Layer | Type | Name | Details | Why |
41
+ | --- | --- | --- | --- | --- |
42
+ | **presentation** | widget | orders/cancel-order | with separated ui | dialog has its own state |
43
+ | | page | orders/details | add the widget | button goes on this screen |
44
+
45
+ **Writing by hand**
46
+ - cancel-order: input { orderId }, output { status }
47
+ - prisma implementation: update status, throw OrderAlreadyShipped
48
+ - endpoint: :id → orderId, OrderAlreadyShipped → 409
49
+ - order-refunds adapter: sales:OrderSummaryQuery result → RefundableAmount
50
+
51
+ **Running**
52
+ - after the endpoint: npm run openapi && npm run client:orval
53
+
54
+ **Question**
55
+ 1. Refund right on cancel, or after a manager confirms?
56
+
57
+ Reply "ok" to start.
58
+ ```
59
+
60
+ - Write the plan in the user's language (headings and sentences); module names, types, commands and paths stay as in the code. Omit empty sections.
61
+ - **Scaffolding** has one block per owner, in run order: new contexts first, marked `(new)` (and `(provisional)` with the reason when ownership is a reversible default), then existing contexts, `shared-kernel`, React last.
62
+ - **Why here**: one short sentence on why this owner, not another: the data or rule the context owns; for `shared-kernel`, why several contexts share it; for React, why the UI changes.
63
+ - **What will be scaffolded**: one table per owner, one row per `df-scaffold`/`df-react` run. Layers in order domain → application → infrastructure → presentation, the layer in bold only on its first row. Repositories go with their aggregate in domain; commands, queries and ports in application (their implementations are Details); endpoints and React modules in presentation.
64
+ - **Type**: the unit: aggregate, entity, value object, error, error namespace, service, port, command, query, use case, implementation, endpoint, wire dependency, move, delete; for React: page, widget, ui-kit component, hook, page move, widget move, ui-kit component move, hook move, page delete, widget delete, ui-kit component delete, hook delete.
65
+ - **Name**: the entered name; for a move `old → new`; for an implementation the contract; for wire dependency the module.
66
+ - **Details**: only what changes behavior: implementation types (`(saved)` when saved for future runs), the test implementation, dependencies (`deps: OrderRepository`), environments, widget type, the endpoint's handler, whether a Next.js route moves (`route moves: /a → /b`). No file paths, no CLI menu paths.
67
+ - **Why**: at most six words: why this kind of module (`choosing-components.md`).
68
+ - **Writing by hand**: members, schemas, mappings. Not full code.
69
+ - **Running**: every command that generates files (migrations, OpenAPI, API client, other codegen), with what it produces and when. Use the project's own scripts; find them in `package.json` and configs. Their output needs no approval of its own and is never edited; scripts that change a database are run only by the user. Details: the project's scripts skill (`project-scripts`), if there is one.
70
+ - **Overwrites**, only when a run would replace existing files (`overwriteRequired` of a `dryRun`): list those files.
71
+ - **Exception requests**, only for hand-created files: `<path>` (`SKILL.md`, rule 2, #n) with the reason. Any other file needs its own request with a reason.
72
+ - **Question**, only for open decisions that change structure or domain behavior. Open questions block approval: answers first, then the updated plan.
73
+ - The last line says what reply starts the work.
@@ -1,252 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Drives an interactive CLI of the package (`df-scaffold` by default, or
4
- * `df-react` / `df-init` with `--bin`) with a scripted list of answers and
5
- * prints the files it created or changed.
6
- *
7
- * Usage:
8
- * node drive.mjs [--bin <name>] [--cwd <dir>] [--delay <ms>] <step> [<step> ...]
9
- * node drive.mjs "pick:Bounded Context: sales" pick:Application "pick:New Port" text:billing-gateway "pick:System: cross-context" no toggle:1
10
- * (when the dependency list has the desired neighboring handler at item 1)
11
- *
12
- * Steps (one per prompt, in the order the CLI asks them):
13
- * pick:<label> select prompt: type the choice label (or a unique prefix) and press Enter
14
- * text:<value> input prompt: type the value and press Enter
15
- * default input/select prompt: accept the suggested default (press Enter)
16
- * yes | no confirm prompt
17
- * toggle:<n,..> checkbox prompt: toggle 1-based items (headers not counted),
18
- * moving with the arrow keys, then press Enter
19
- * none checkbox prompt: submit as is (pre-checked items stay checked)
20
- *
21
- * Implementation menus use the same pick:<label> steps as any select:
22
- * a saved implementation label or an available System: implementation,
23
- * or either manual-entry action followed by a separate text:<type> step:
24
- * "pick:Enter implementation type and save for future use" text:redis
25
- * "pick:Enter implementation type for this run only" text:redis
26
- */
27
- import { spawn } from 'node:child_process';
28
- import fs from 'node:fs';
29
- import path from 'node:path';
30
-
31
- const args = process.argv.slice(2);
32
- let cwd = process.cwd();
33
- let delay = 600;
34
- let bin = 'df-scaffold';
35
- const steps = [];
36
-
37
- for (let i = 0; i < args.length; i++) {
38
- if (args[i] === '--cwd') cwd = path.resolve(args[++i]);
39
- else if (args[i] === '--bin') bin = args[++i];
40
- else if (args[i] === '--delay') delay = Number(args[++i]);
41
- else steps.push(args[i]);
42
- }
43
-
44
- const findProjectRoot = (dir) => {
45
- while (dir !== path.parse(dir).root) {
46
- if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
47
- dir = path.dirname(dir);
48
- }
49
- throw new Error(`No package.json found above ${cwd}`);
50
- };
51
-
52
- const projectRoot = findProjectRoot(cwd);
53
-
54
- const toKeys = (step) => {
55
- if (step === 'yes') return ['y\r'];
56
- if (step === 'no') return ['n\r'];
57
- if (step === 'default' || step === 'none') return ['\r'];
58
- if (step.startsWith('text:')) return [`${step.slice(5)}\r`];
59
- // Select prompts jump to the first choice starting with the typed text.
60
- if (step.startsWith('pick:')) return [step.slice(5), '\r'];
61
- if (step.startsWith('toggle:')) {
62
- const items = step
63
- .slice(7)
64
- .split(',')
65
- .map((n) => n.trim());
66
- if (!items.every((n) => /^[1-9]\d*$/.test(n))) {
67
- throw new Error(`Toggle items must be positive numbers: ${step}`);
68
- }
69
- // Sent by the main loop, which moves with the arrow keys.
70
- return [];
71
- }
72
- throw new Error(`Unknown step: ${step}`);
73
- };
74
-
75
- // biome-ignore lint/suspicious/noControlCharactersInRegex: strip ANSI escapes
76
- const stripAnsi = (text) => text.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '');
77
-
78
- // Fail on malformed steps before the CLI starts writing files.
79
- try {
80
- steps.forEach(toKeys);
81
- } catch (error) {
82
- console.error(error.message);
83
- process.exit(2);
84
- }
85
-
86
- const ignored = new Set(['node_modules', '.git', 'dist', 'build', '.next']);
87
- const snapshot = () => {
88
- const result = new Map();
89
- const walk = (dir) => {
90
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
91
- if (ignored.has(entry.name)) continue;
92
- const full = path.join(dir, entry.name);
93
- if (entry.isDirectory()) walk(full);
94
- else result.set(full, fs.readFileSync(full, 'utf8'));
95
- }
96
- };
97
- walk(projectRoot);
98
- return result;
99
- };
100
-
101
- if (!['df-scaffold', 'df-react', 'df-init'].includes(bin)) {
102
- console.error(`Unknown --bin: ${bin}`);
103
- process.exit(2);
104
- }
105
-
106
- const localBin = path.join(projectRoot, 'node_modules', '.bin', bin);
107
- const [command, commandArgs] = fs.existsSync(localBin)
108
- ? [localBin, []]
109
- : [
110
- 'npm',
111
- ['exec', '--yes', '--package=@domain-first/project-structure', '--', bin]
112
- ];
113
-
114
- const before = snapshot();
115
- const child = spawn(command, commandArgs, {
116
- cwd,
117
- stdio: ['pipe', 'pipe', 'pipe']
118
- });
119
-
120
- let output = '';
121
- child.stdout.on('data', (chunk) => (output += chunk));
122
- child.stderr.on('data', (chunk) => (output += chunk));
123
-
124
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
125
-
126
- let exited = false;
127
- const exitCode = new Promise((resolve) =>
128
- child.on('exit', (code) => {
129
- exited = true;
130
- resolve(code);
131
- })
132
- );
133
-
134
- // npm exec may need extra time to download the package on first use.
135
- await sleep(fs.existsSync(localBin) ? 1200 : 8000);
136
- let aborted;
137
- const arrowDown = '\x1b[B';
138
-
139
- // The latest highlighted choice, without checkbox marks.
140
- const highlightedChoice = () =>
141
- [...stripAnsi(output).matchAll(/❯\s*([^\n]*)/g)]
142
- .at(-1)?.[1]
143
- ?.replace(/^[◯◉]\s*/, '')
144
- .trim();
145
-
146
- for (const step of steps) {
147
- if (exited) break;
148
- const keys = toKeys(step);
149
- if (step.startsWith('toggle:')) {
150
- // Number keys reach only items 1-9, so walk down from the first
151
- // item instead. Headers are skipped by the prompt itself.
152
- const targets = [
153
- ...new Set(
154
- step
155
- .slice(7)
156
- .split(',')
157
- .map((n) => Number(n.trim()))
158
- )
159
- ].sort((a, b) => a - b);
160
- let position = 1;
161
- for (const target of targets) {
162
- for (; position < target - 1; position++) {
163
- child.stdin.write(arrowDown);
164
- await sleep(Math.min(delay, 100));
165
- }
166
- if (position < target) {
167
- // The cursor stays put past the last item, so check the
168
- // last step down.
169
- await sleep(delay);
170
- const before = highlightedChoice();
171
- child.stdin.write(arrowDown);
172
- position++;
173
- await sleep(delay);
174
- if (highlightedChoice() === before) {
175
- aborted = `${step}: item ${target} does not exist; the list ends at "${before ?? '?'}".`;
176
- break;
177
- }
178
- }
179
- child.stdin.write(' ');
180
- await sleep(delay);
181
- }
182
- if (aborted) break;
183
- child.stdin.write('\r');
184
- await sleep(delay);
185
- continue;
186
- }
187
- if (step.startsWith('pick:')) {
188
- // Type the label, then make sure the highlighted choice really
189
- // matches before pressing Enter: a miss would silently keep the
190
- // previously highlighted choice.
191
- child.stdin.write(keys[0]);
192
- await sleep(delay);
193
- // No re-render happens when the match is already highlighted, so
194
- // read the latest highlighted line from the whole output.
195
- const render = stripAnsi(output);
196
- const highlighted = [...render.matchAll(/❯\s*([^\n]*)/g)]
197
- .at(-1)?.[1]
198
- ?.trim();
199
- const wanted = step.slice(5).toLowerCase();
200
- if (!highlighted?.toLowerCase().startsWith(wanted)) {
201
- aborted = `"${step.slice(5)}" does not match the highlighted choice "${highlighted ?? '?'}". A pick label must be a prefix of a choice shown in the menu.`;
202
- break;
203
- }
204
- child.stdin.write(keys[1]);
205
- await sleep(delay);
206
- continue;
207
- }
208
- for (const key of keys) {
209
- child.stdin.write(key);
210
- await sleep(delay);
211
- }
212
- }
213
- await sleep(delay);
214
- const unansweredPrompt = !exited && !aborted;
215
- if (aborted) child.kill();
216
- child.stdin.end();
217
- const code = await exitCode;
218
-
219
- const after = snapshot();
220
- const rel = (p) => path.relative(projectRoot, p);
221
- const created = [...after.keys()].filter((p) => !before.has(p)).map(rel);
222
- const changed = [...after.keys()]
223
- .filter((p) => before.has(p) && before.get(p) !== after.get(p))
224
- .map(rel);
225
- const deleted = [...before.keys()].filter((p) => !after.has(p)).map(rel);
226
-
227
- const plain = stripAnsi(output);
228
- const answered = [...plain.matchAll(/✔\s*([^\n]*)/g)].map((m) => m[1].trim());
229
-
230
- console.log(`project root: ${projectRoot}`);
231
- console.log(`exit code: ${code}`);
232
- if (aborted) {
233
- console.log(`ABORTED before submitting the answer: ${aborted}`);
234
- }
235
- if (unansweredPrompt) {
236
- console.log('WARNING: the CLI was still waiting for input after the last step.');
237
- }
238
- console.log('\nanswered prompts:');
239
- for (const line of answered) console.log(` ${line}`);
240
- console.log('\ncreated:');
241
- for (const file of created) console.log(` + ${file}`);
242
- console.log('\nchanged:');
243
- for (const file of changed) console.log(` ~ ${file}`);
244
- if (deleted.length) {
245
- console.log('\ndeleted:');
246
- for (const file of deleted) console.log(` - ${file}`);
247
- }
248
- if (code !== 0 || unansweredPrompt || aborted) {
249
- console.log('\nraw output (tail):');
250
- console.log(plain.split('\n').slice(-15).join('\n'));
251
- process.exitCode = 1;
252
- }