@domain-first/project-structure 2.17.1 → 2.18.0

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/README.md CHANGED
@@ -11,7 +11,7 @@ npm install --save-dev @domain-first/project-structure
11
11
  npx df-ps
12
12
  ```
13
13
 
14
- [Quick start](#quick-start) · [Project structure](#project-structure) · [Generators](#generators) · [Configuration](#configuration) · [Example workflow](#example-workflow)
14
+ [Quick start](#quick-start) · [Project structure](#project-structure) · [Generators](#generators) · [Configuration](#configuration) · [Agent skills](#agent-skills) · [Example workflow](#example-workflow)
15
15
 
16
16
  ## Why use it?
17
17
 
@@ -449,6 +449,24 @@ Select the packages you intend to use and install them in your application separ
449
449
 
450
450
  You can edit the configuration for future runs. Existing files are left as they are when you edit settings; enabling `wire` or `errors` later also requires adding the shared helpers that initial setup would create, plus context error namespaces where needed.
451
451
 
452
+ ## Agent skills
453
+
454
+ The package ships skills that teach coding agents to plan features, scaffold components with `df-ps`, and implement the generated code. Copy them into your project:
455
+
456
+ ```bash
457
+ npx df-skills
458
+ ```
459
+
460
+ Choose the agents and whether to install into the project or your home directory. Or pass flags:
461
+
462
+ | Flag | Installs into |
463
+ | --- | --- |
464
+ | `--claude` | `.claude/skills` (Claude Code) |
465
+ | `--codex` | `.agents/skills` (Codex) |
466
+ | `--global` | the home directory instead of the current project |
467
+
468
+ Run it again after upgrading the package: existing `df-ps-*` skill folders are replaced with the new versions.
469
+
452
470
  ## Example workflow
453
471
 
454
472
  To start an order feature, enable `@domain-first/wire` during initialization and run `npx df-ps` for each step:
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { cpSync, existsSync, readdirSync, rmSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join, relative, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { parseArgs } from 'node:util';
8
+ import { checkbox, select } from '@inquirer/prompts';
9
+
10
+ const SKILLS_SOURCE = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'skills');
11
+
12
+ const AGENTS = {
13
+ claude: { title: 'Claude Code', folder: join('.claude', 'skills') },
14
+ codex: { title: 'Codex', folder: join('.agents', 'skills') },
15
+ };
16
+
17
+ const HELP = `Usage: df-skills [options]
18
+
19
+ Copies Domain-First (df-ps) agent skills into your project.
20
+ Runs interactively when no agent is given.
21
+
22
+ Options:
23
+ --claude install for Claude Code (.claude/skills)
24
+ --codex install for Codex (.agents/skills)
25
+ --global install into the home directory instead of the current project
26
+ -h, --help show this help`;
27
+
28
+ const { values } = parseArgs({
29
+ options: {
30
+ claude: { type: 'boolean', default: false },
31
+ codex: { type: 'boolean', default: false },
32
+ global: { type: 'boolean', default: false },
33
+ help: { type: 'boolean', short: 'h', default: false },
34
+ },
35
+ });
36
+
37
+ if (values.help) {
38
+ console.log(HELP);
39
+ process.exit(0);
40
+ }
41
+
42
+ const skills = readdirSync(SKILLS_SOURCE, { withFileTypes: true })
43
+ .filter((entry) => entry.isDirectory())
44
+ .map((entry) => entry.name);
45
+
46
+ const interactive = !values.claude && !values.codex;
47
+
48
+ const agents = interactive
49
+ ? await checkbox({
50
+ message: 'Install skills for',
51
+ choices: Object.entries(AGENTS).map(([value, { title }]) => ({
52
+ value,
53
+ name: title,
54
+ checked: value === 'claude',
55
+ })),
56
+ required: true,
57
+ })
58
+ : Object.keys(AGENTS).filter((agent) => values[agent]);
59
+
60
+ const global =
61
+ interactive && !values.global
62
+ ? await select({
63
+ message: 'Install into',
64
+ choices: [
65
+ { value: false, name: `This project (${process.cwd()})` },
66
+ { value: true, name: `Home directory (${homedir()})` },
67
+ ],
68
+ })
69
+ : values.global;
70
+
71
+ const root = global ? homedir() : process.cwd();
72
+
73
+ for (const agent of agents) {
74
+ const target = join(root, AGENTS[agent].folder);
75
+ console.log(`\n${AGENTS[agent].title} → ${global ? target : relative(root, target)}`);
76
+
77
+ for (const skill of skills) {
78
+ const destination = join(target, skill);
79
+ const existed = existsSync(destination);
80
+ // Replace the whole folder so files removed upstream don't linger.
81
+ rmSync(destination, { recursive: true, force: true });
82
+ cpSync(join(SKILLS_SOURCE, skill), destination, { recursive: true });
83
+ console.log(` ${existed ? 'updated' : 'added '} ${skill}`);
84
+ }
85
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@domain-first/project-structure",
3
3
  "description": "Build and manage your Domain-First project structure with CLI",
4
- "version": "2.17.1",
4
+ "version": "2.18.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -16,12 +16,15 @@
16
16
  }
17
17
  },
18
18
  "bin": {
19
- "df-ps": "./dist/index.js"
19
+ "df-ps": "./dist/index.js",
20
+ "df-skills": "./bin/df-skills.mjs"
20
21
  },
21
22
  "main": "./dist/index.cjs",
22
23
  "types": "./dist/index.d.ts",
23
24
  "files": [
24
- "dist"
25
+ "dist",
26
+ "bin",
27
+ "skills"
25
28
  ],
26
29
  "publishConfig": {
27
30
  "access": "public"
@@ -0,0 +1,100 @@
1
+ ---
2
+ name: df-ps-implement
3
+ description: Fill in code generated by the `df-ps` CLI (@domain-first/project-structure) — aggregates, entities and value objects (@domain-first/types), repositories, handler schemas (@domain-first/handlers), errors (@domain-first/errors), wiring (@domain-first/wire), handlers-rest endpoints, React modules, tests — while keeping bounded contexts isolated. Use after scaffolding, or when the user asks to implement, connect, or wire Domain-First components in a project with domain-first.project-structure.config.json.
4
+ ---
5
+
6
+ # Implement Domain-First scaffolds
7
+
8
+ Generated files contain placeholders: empty classes, `{}` schemas, `[]` dependency lists, `never` handlers. Read the config to see which integrations are on. For API details, read the `@domain-first/*` READMEs and typings in `node_modules`; don't guess.
9
+
10
+ ## Ground rules
11
+
12
+ - New files need an approved work plan (`df-ps-scaffold`, rule 1) and come only via df-ps or its listed exceptions (rule 2). Edits to existing files don't need approval; report them.
13
+ - Keep generated names and paths: barrels, wiring, specs, and `presentation/rest/wires.ts` import them.
14
+ - Layers: domain imports nothing from other layers. Application uses domain and its own abstractions. Infrastructure implements repositories, contracts, and ports. Presentation calls application handlers. Only `wiring/` knows concrete classes.
15
+ - Constructors take abstractions (`OrderRepository`, abstract `PlaceOrderCommand`, port `PaymentGateway`), never `PrismaOrderRepository`.
16
+ - Implementation order: domain → application → schema tool runs (migrations, only if infrastructure needs data the database lacks) → infrastructure (repositories, execution commands/queries, adapters) → endpoints → other tool runs (OpenAPI, API client) → React. Widgets need the regenerated client. How to run tools and handle their output: the project's scripts skill (`project-scripts`), if there is one.
17
+ - Run the project's tsc/lint/tests after each component.
18
+
19
+ ## Bounded context isolation
20
+
21
+ A file in context A imports **nothing** from context B: no types (`import type` too), barrels, aliases, errors, or wiring. No exceptions: every context must be movable to its own service.
22
+
23
+ - A needs B's data or behavior → an **execution query** (read) or **execution command** (write) in A. Its input/output are A's own models, duplicated in A's terms; B's models never appear in A.
24
+ - Its infrastructure implementation reaches B's data **the simplest available way**: a shared database → query it directly (e.g. `prisma`); otherwise the way chosen in the plan (`df-ps-plan-feature`, step 3, rule 4), by default B's REST endpoint (`http`), like an external service. Either way it maps the result to A's models and errors and imports nothing from B. Its test implementation returns fixed data, so A's tests never run B.
25
+ - Refer to B's entities by id only.
26
+ - `shared/` may import any context's **`domain/errors`** (e.g. to map them to HTTP statuses), and nothing else from a context. Don't move a context's domain concepts into `shared/` to share them between contexts; only universal entities / value objects (`money`, `email`) live there.
27
+ - `<rootFolder>/presentation/rest/` (the generated `wires.ts`, `index.ts`) may import every context's REST wiring.
28
+ - `<rootFolder>/presentation/react/` imports **nothing** from contexts whenever it can avoid it (`ui-kit/` never does). If the project has a generated API client (orval, openapi-typescript, … from the OpenAPI document built by `generateOpenAPI`), use its hooks and types only. As a fallback, without such a client, it may import **only endpoint contract types**: `import type` from `<C>/presentation/rest/**`, e.g. `type Contract = EndpointContract<OrdersRecentGetEndpoint['handle']>`. No value imports, no `import { type X }`, nothing from other layers.
29
+ - Need a forbidden import? A's own execution query or command is missing. Plan it and generate it.
30
+
31
+ Check before reporting done; fix every finding:
32
+
33
+ ```bash
34
+ node <this-skill-dir>/scripts/check-context-isolation.mjs [rootFolder]
35
+ ```
36
+
37
+ Run it from the project root; `rootFolder` defaults to the config's. It resolves relative paths and tsconfig `paths` aliases, and checks `import`/`export … from`, side-effect imports, `import()`, and `require()`. It also reports a widget importing another widget (a widget = the nearest folder under `presentation/react/widgets/` with a `*-widget.tsx`, nested widgets included).
38
+
39
+ ## Domain
40
+
41
+ ```ts
42
+ export class Order extends domainType(
43
+ z.object({ id: z.instanceof(OrderId), lines: z.array(z.instanceof(OrderLine)), status: z.enum(['open', 'paid']) })
44
+ ) {
45
+ pay = () => {
46
+ if (this.status === 'paid') throw new AlreadyPaidOrderSalesError({ id: this.id.value })
47
+ return new Order({ id: this.id, lines: this.lines, status: 'paid' })
48
+ }
49
+ }
50
+ ```
51
+
52
+ - Use the schema library the project already uses. Methods return new instances. Invalid input throws `TypeParsingError`.
53
+ - Entities and value objects are `domainType(...)` classes generated by Domain → New Entity / New Value Object; inside an aggregate, the generator exports them from its `index.ts`.
54
+ - Entities and value objects are rich and know nothing about storage (`df-ps-scaffold/references/choosing-components.md`): write their rules and factories as methods, using the standard library where it suffices. No repository calls, persistence fields, or storage mapping in them.
55
+ - Repository contract: abstract members (`abstract findById(id: OrderId): Promise<Order | null>`, `abstract save(order: Order): Promise<void>`). Implementations map storage ⇄ aggregates. The in-memory one behaves like the real one for what tests use.
56
+ - Errors: `.define<{ orderId: string }>('not-found')` for details; throw `new XError({...})`; recognize with `XError.is(e)`, or `XError.matchesCode(data)` after serialization.
57
+
58
+ ## Application
59
+
60
+ - Use cases, commands, queries ({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. Execution: the abstract contract holds the static schemas and `abstract handle`; each infrastructure implementation defines `handle` with the contract's schemas and writes only its `handler` callback. Orchestrator: a concrete class composing injected contracts. Call with `x.handle(input)` (returns a result) or `x.handle.unsafe(input)` (throws).
61
+ - What a query or command may change: "Commonly confused" in `df-ps-scaffold/references/choosing-components.md`. Data a command returns goes in its output schema.
62
+ - Ports: abstract members in the port, one implementation per adapter (`api` real, `mock`/`fake` deterministic). Use the shared `clock` port instead of `new Date()`.
63
+ - Services: what each kind may contain and call is in `choosing-components.md` (steps 13–16, "Port or service?"). Domain services take and return domain types. Application services have no `handle`.
64
+
65
+ ## Wiring ({wire})
66
+
67
+ Dependencies (constructor parameters and their wires) are added only by `df-ps` (`df-ps-scaffold`, rule 3): the generator's `Dependencies:` step or `Wire dependency`. It keeps each `wireClass(X, [...])` in the order of the constructor, which TypeScript checks:
68
+
69
+ ```ts
70
+ export const wirePlaceOrderUseCase = wireClass(PlaceOrderUseCase, [wireOrderRepository, wirePaymentGateway])
71
+ ```
72
+
73
+ - Use the injected dependencies in the class body; don't edit the parameter list or the wire list.
74
+ - Env-branched files (repositories, execution commands/queries, ports): each `wire<Impl>Implementation` has its own dependencies, added per implementation. `NODE_ENV=test` selects the test one; vitest sets it.
75
+ - External clients and config values: an infrastructure service named after the implementation label creates or reads them (`readonly client = new PrismaClient()`); wrap its wire in `memoWire(...)` when the instance must be shared. Implementations depend on that service, never on a `wireValue(...)`.
76
+ - A needed dependency the CLI doesn't offer: see rule 3 (change the design).
77
+
78
+ ## REST endpoints ({handlers-rest})
79
+
80
+ 1. Generator: once per project, before the first endpoint, generate Shared Layer → Presentation → New Service `rest-endpoint-generator` with `readonly generate = createEndpoint({ context, errorStatuses })(adapter)`. Map domain errors to statuses in `errorStatuses`, importing them from the contexts' `domain/errors` (the only thing `shared/` may import from a context). Generate the exposed handler before the endpoint too: with wire, the endpoint generator takes both picks and fills the types and the wire (`[wireRestEndpointGeneratorPresentationService, wireGetRecentOrdersUseCase]`).
81
+ 2. If `handler: never` is left (no handler existed at generation), re-run the endpoint generator as an approved overwrite to pick it (rule 3); don't replace it by hand.
82
+ 3. Complete `get handle()`: call the picked service's generating method (`this.endpointGenerator.generate(...)` instead of `this.endpointGenerator(...)`), then `.input(...)`, `.mapInput(...)`, optional `.output(...)`, `.mapOutput(...)`.
83
+ 4. Register `restHandlers` from `<rootFolder>/presentation/rest/index.ts` in the server bootstrap (rule 2, exception 5).
84
+
85
+ ## React
86
+
87
+ - Separated UI widget: state, effects, and derived data in `hooks/use-<name>-ui-model.ts` (props → UI props); `ui/` stays presentational. Headless: the same hook, and the consumer passes `UI`.
88
+ - Widgets never import other widgets (their component, `ui/`, `hooks/` or `types.ts`). Shared markup → UI-kit, shared logic → a shared hook, combining widgets → the page.
89
+ - UI-kit components: presentational, driven only by props; no API client, no data loading, no imports from widgets, pages, or contexts. Other UI-kit components and shared hooks (`hooks/`) are fine. Business terms only in a domain UI-kit component — an element several widgets repeat whole (`references/choosing-components.md` in `df-ps-scaffold`); its props describe what it shows, not domain types.
90
+ - Shared hooks (`…/presentation/react/hooks/use-<name>.ts`): generic app-wide logic, driven only by arguments; no business terms, no API client, no imports from UI-kit, widgets, pages, or contexts.
91
+ - Stories (`storybookFramework`): fill `args` of `Default` with valid props and add one story per meaningful state (`Disabled`, `Loading`, `WithError`). Keep `meta`, the file name, and the title (`UI-kit/N` or `Widgets/N`). For widget UI, the stories cover the UI states that its UI model produces.
92
+ - Extra hooks, UI parts, styles, and stories: rule 2, exceptions 3–4.
93
+ - Moving or renaming a page or widget (files, code names, imports): only with df-ps, `Move or rename page` / `Move or rename widget` (`df-ps-scaffold`, rule 2).
94
+ - Talk to the backend over HTTP. First look for a generated API client (orval config, `openapi-typescript` output, generated `*.gen.ts` / `api/` folders) and use it, importing nothing from contexts. Only without one, take types from endpoint contracts (`import type`, see "Bounded context isolation"). Regenerating the client is tool output (rule 2, exception 2).
95
+
96
+ ## Tests
97
+
98
+ - Entities and value objects: extend their generated `<name>.entity.spec.ts` / `<name>.value-object.spec.ts` with their rules (e.g. rating is 1–5).
99
+ - Generated specs only check construction. Extend them in the same file with behavior tests: aggregate rules, repository contracts against the test implementation, handlers via `handle(...)`.
100
+ - Missing spec: create it from "Spec templates" in `df-ps-scaffold/references/generators.md` (exception 1). Don't re-run the generator: it would overwrite the implementation. Never delete generated specs.
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Reports imports that cross bounded-context boundaries outside the allowed places.
4
+ *
5
+ * Usage (from the project root):
6
+ * node check-context-isolation.mjs [rootFolder]
7
+ * rootFolder defaults to `rootFolder` in domain-first.project-structure.config.json.
8
+ *
9
+ * Bounded contexts never import each other (no exceptions).
10
+ * Allowed: shared/** may import any context's domain/errors; presentation/react/** may only
11
+ * `import type` from a context's presentation/rest/; presentation/react/ui-kit/** imports
12
+ * nothing from bounded contexts, widgets or pages.
13
+ * Widgets never import each other: a file of one widget (the nearest folder under widgets/
14
+ * that has a `*-widget.tsx`) must not import anything of another widget.
15
+ * Everything else that imports another bounded context is reported.
16
+ *
17
+ * Checked: `import … from`, `export … from`, side-effect `import '…'`, `import('…')`,
18
+ * `require('…')`; specifiers are resolved as relative paths or tsconfig `paths` aliases.
19
+ * Exit code 1 when violations are found.
20
+ */
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import { createRequire } from 'node:module';
24
+
25
+ const cwd = process.cwd();
26
+
27
+ const readRootFolder = () => {
28
+ const configPath = path.join(cwd, 'domain-first.project-structure.config.json');
29
+ if (!fs.existsSync(configPath)) return 'src';
30
+ return JSON.parse(fs.readFileSync(configPath, 'utf8')).rootFolder ?? 'src';
31
+ };
32
+
33
+ const root = path.resolve(cwd, process.argv[2] ?? readRootFolder());
34
+ const contextsDir = path.join(root, 'bounded-contexts');
35
+ const sharedDir = path.join(root, 'shared');
36
+ const reactDir = path.join(root, 'presentation', 'react');
37
+ const uiKitDir = path.join(reactDir, 'ui-kit');
38
+ const widgetsDir = path.join(reactDir, 'widgets');
39
+
40
+ // tsconfig `paths` → [{ prefix, wildcard, targets }]
41
+ const readTsconfig = (file) => {
42
+ try {
43
+ const ts = createRequire(path.join(cwd, 'package.json'))('typescript');
44
+ const { config, error } = ts.readConfigFile(file, ts.sys.readFile);
45
+ if (!error) return config;
46
+ } catch {}
47
+ const text = fs
48
+ .readFileSync(file, 'utf8')
49
+ .replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '')
50
+ .replace(/,(\s*[}\]])/g, '$1');
51
+ return JSON.parse(text);
52
+ };
53
+
54
+ const readAliases = () => {
55
+ const file = path.join(cwd, 'tsconfig.json');
56
+ if (!fs.existsSync(file)) return [];
57
+ let options;
58
+ try {
59
+ options = readTsconfig(file).compilerOptions ?? {};
60
+ } catch (e) {
61
+ console.warn(`WARNING: cannot parse tsconfig.json (${e.message}); aliases are not checked\n`);
62
+ return [];
63
+ }
64
+ const base = path.resolve(cwd, options.baseUrl ?? '.');
65
+ return Object.entries(options.paths ?? {})
66
+ .map(([key, targets]) => {
67
+ const wildcard = key.endsWith('*');
68
+ return {
69
+ prefix: wildcard ? key.slice(0, -1) : key,
70
+ wildcard,
71
+ targets: targets.map((t) => path.resolve(base, wildcard ? t.replace(/\*$/, '') : t)),
72
+ };
73
+ })
74
+ .sort((a, b) => b.prefix.length - a.prefix.length);
75
+ };
76
+
77
+ const aliases = readAliases();
78
+
79
+ // Absolute path a specifier points to, or null for a package.
80
+ const resolveSpecifier = (spec, fromFile) => {
81
+ if (spec.startsWith('.')) return path.resolve(path.dirname(fromFile), spec);
82
+ for (const { prefix, wildcard, targets } of aliases) {
83
+ if (wildcard ? spec.startsWith(prefix) : spec === prefix) {
84
+ return path.join(targets[0], wildcard ? spec.slice(prefix.length) : '');
85
+ }
86
+ }
87
+ return null;
88
+ };
89
+
90
+ const inside = (dir, file) => {
91
+ const rel = path.relative(dir, file);
92
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.split(path.sep) : null;
93
+ };
94
+
95
+ const sourceFiles = (dir) => {
96
+ if (!fs.existsSync(dir)) return [];
97
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
98
+ const full = path.join(dir, entry.name);
99
+ if (entry.isDirectory()) return entry.name === 'node_modules' ? [] : sourceFiles(full);
100
+ return /\.(c|m)?tsx?$/.test(entry.name) && !entry.name.endsWith('.d.ts') ? [full] : [];
101
+ });
102
+ };
103
+
104
+ // One alternation, scanned left to right, so a match never spans two statements.
105
+ const importPattern =
106
+ /\b(?:(import|export)\s+(type\s+)?(?:(?!\b(?:import|export)\b)[\w*{}\s,$])*?\s*from\s*|import\s*\(\s*|require\s*\(\s*|import\s*)(['"])([^'"\n]+)\3/g;
107
+
108
+ const importsOf = (file) => {
109
+ const text = fs.readFileSync(file, 'utf8');
110
+ return [...text.matchAll(importPattern)].map((m) => ({
111
+ typeOnly: m[1] === 'import' && Boolean(m[2]),
112
+ target: resolveSpecifier(m[4], file),
113
+ line: text.slice(0, m.index).split('\n').length,
114
+ statement: m[0].replace(/\s+/g, ' '),
115
+ }));
116
+ };
117
+
118
+ const contexts = fs.existsSync(contextsDir)
119
+ ? fs
120
+ .readdirSync(contextsDir, { withFileTypes: true })
121
+ .filter((e) => e.isDirectory())
122
+ .map((e) => e.name)
123
+ .sort()
124
+ : [];
125
+
126
+ // Folder of the widget a path belongs to: the nearest folder under widgets/ with a `*-widget.tsx`.
127
+ const widgetCache = new Map();
128
+ const isWidgetFolder = (dir) => {
129
+ if (!widgetCache.has(dir)) {
130
+ widgetCache.set(
131
+ dir,
132
+ fs.existsSync(dir) &&
133
+ fs.statSync(dir).isDirectory() &&
134
+ fs.readdirSync(dir).some((name) => name.endsWith('-widget.tsx')),
135
+ );
136
+ }
137
+ return widgetCache.get(dir);
138
+ };
139
+ const widgetOf = (target) => {
140
+ if (!inside(widgetsDir, target)) return null;
141
+ for (let dir = target; inside(widgetsDir, dir); dir = path.dirname(dir)) {
142
+ if (isWidgetFolder(dir)) return dir;
143
+ }
144
+ return null;
145
+ };
146
+
147
+ const violations = new Map();
148
+ const report = (title, file, imp) => {
149
+ if (!violations.has(title)) violations.set(title, []);
150
+ violations.get(title).push(`${path.relative(cwd, file)}:${imp.line}: ${imp.statement}`);
151
+ };
152
+
153
+ const scanned = [contextsDir, sharedDir, reactDir].flatMap(sourceFiles);
154
+
155
+ for (const file of scanned) {
156
+ const ownContext = inside(contextsDir, file)?.[0];
157
+ for (const imp of importsOf(file)) {
158
+ if (!imp.target) continue;
159
+ const [targetContext, layer, part] = inside(contextsDir, imp.target) ?? [];
160
+
161
+ if (ownContext) {
162
+ if (targetContext && targetContext !== ownContext) report(`[${ownContext}] imports another context:`, file, imp);
163
+ } else if (inside(sharedDir, file)) {
164
+ if (targetContext && !(layer === 'domain' && part === 'errors')) {
165
+ report('[shared] imports a bounded context outside its domain/errors:', file, imp);
166
+ }
167
+ } else if (inside(uiKitDir, file)) {
168
+ const [area] = inside(reactDir, imp.target) ?? [];
169
+ if (targetContext || area === 'widgets' || area === 'pages') {
170
+ report('[presentation/react/ui-kit] imports a bounded context, widget or page:', file, imp);
171
+ }
172
+ } else if (targetContext && !(imp.typeOnly && layer === 'presentation' && part === 'rest')) {
173
+ report('[presentation/react] imports a context other than `import type` from presentation/rest:', file, imp);
174
+ }
175
+
176
+ const ownWidget = widgetOf(file);
177
+ const targetWidget = widgetOf(imp.target);
178
+ if (ownWidget && targetWidget && targetWidget !== ownWidget) {
179
+ report('[presentation/react/widgets] a widget imports another widget:', file, imp);
180
+ }
181
+ }
182
+ }
183
+
184
+ for (const [title, lines] of violations) {
185
+ console.log(title);
186
+ for (const line of lines) console.log(` ${line}`);
187
+ console.log();
188
+ }
189
+
190
+ if (violations.size === 0) {
191
+ console.log(`OK: no cross-context or cross-widget import violations (${contexts.length} contexts)`);
192
+ }
193
+ process.exit(violations.size === 0 ? 0 : 1);
@@ -0,0 +1,77 @@
1
+ ---
2
+ name: df-ps-plan-feature
3
+ description: Turn an abstract feature request into a Domain-First plan for a project using `df-ps` (@domain-first/project-structure) — decide which bounded contexts own what and which components are needed, then get the user's approval before generating anything. Use when the project has domain-first.project-structure.config.json and the user describes a feature ("add product reviews", "let users cancel orders") without naming bounded contexts or exact components.
4
+ ---
5
+
6
+ # Plan a feature
7
+
8
+ Understand → decompose → assign → get approval → hand off. A feature creates files, so nothing is generated or written before approval (`df-ps-scaffold`, rule 1).
9
+
10
+ ## 1. Understand what exists
11
+
12
+ Read the config, then build an overview of the contexts and `shared/` from existing architecture docs and a file inventory:
13
+
14
+ ```bash
15
+ rg --files <rootFolder>/bounded-contexts <rootFolder>/shared
16
+ ```
17
+
18
+ Use the overview to identify likely owners and related contexts. Search for the feature's domain terms and synonyms; don't infer ownership from folder names alone.
19
+
20
+ Read the relevant code in the affected contexts: aggregates and their rules, use cases, commands/queries, ports, and behavior tests. Follow their dependencies into adapters, wiring, relevant `shared/` components, and the REST endpoints of any providing context. Note how contexts can reach each other: which database each one uses, and any message queue, RPC, or event setup. Expand the search when ownership or a dependency remains unclear; unrelated implementations do not need a full read.
21
+
22
+ For each affected context, note what it owns, what it does, its language, and the ports and other-context queries/commands involved in the feature. Stop expanding when you can justify ownership, identify reusable components, and verify both sides of each required cross-context interaction. Mark unresolved assumptions in the plan. If there are no contexts yet, propose an initial split in step 3.
23
+
24
+ ## 2. Decompose
25
+
26
+ Split the request into pieces of logic and choose each piece's component with `df-ps-scaffold/references/choosing-components.md`. Record the deciding step for the "Why" in the plan: `choosing-components, step N` for a component, `step 3, rule N` (below) for a placement.
27
+
28
+ ## 3. Assign to contexts
29
+
30
+ 1. A component goes where the data and rules it depends on live.
31
+ 2. Extend an existing context when the concept fits its language and lifecycle (the normal case).
32
+ 3. Create a new context only for a concept with its own lifecycle and vocabulary, or a different business owner. Never one context per feature.
33
+ 4. Contexts are fully isolated and never import each other, so each can become its own service. Every need for another context's data or behavior is an **execution query or command** in the consuming context, with its own duplicated models, implemented the simplest available way. Find it in the code:
34
+ - Both contexts use the same database → query it directly (the persistence label, e.g. `prisma`).
35
+ - Otherwise, look for the ways the project already reaches a context besides its REST endpoints: message queue, RPC, events, generated API clients. Several options (REST counts) → ask the user which one in "Decisions for you", with a recommendation. Never pick silently.
36
+ - Nothing besides REST → the providing context's REST endpoint (`http`).
37
+
38
+ Unless it's the database, plan **both sides**: check that the providing context exposes what the call needs (endpoint, queue consumer…). If not, add it (and the use case behind it) to the plan.
39
+ 5. `shared/` holds technical, ownerless pieces and universal entities / value objects (`money`, `email`): the same meaning in every context, owned by none. Never a concept with one context's meaning or rules.
40
+ 6. Names: kebab-case, in the context's language. Contexts are business areas (`sales`, `reviews`), not features.
41
+
42
+ If two placements are plausible, ask the user and give your recommendation.
43
+
44
+ ### When ownership is unclear
45
+
46
+ Find out why, then act:
47
+
48
+ - **You don't understand the domain** (unknown term, unclear who changes the data). Ask business questions, not "which context?": Who changes it, and when? What rule does it protect? What changes together with it? Who decides when the rule changes? The answers point to the owner. Check whether the code already has the concept under another name.
49
+ - **The logic spans several contexts** (e.g. "cancel only if not shipped and refunded"). It's a process: each context owns its part, and the initiating context gets the coordinating use case and reaches the others through its own execution queries and commands.
50
+ - **Nobody knows, including the user.** Pick a reversible default: the initiating or closest context, other contexts behind its own queries and commands, and mark it **(provisional)** with the reason.
51
+
52
+ Never: pick silently, put one context's domain logic in `shared/`, create a catch-all context (`common`, `core`, `misc`), or split arbitrarily.
53
+
54
+ ## 4. Present the plan
55
+
56
+ One message: the architectural part plus the work plan in the `df-ps-scaffold` rule 1 format. Then stop.
57
+
58
+ ```markdown
59
+ **Feature:** product reviews
60
+ **Contexts:** `reviews` (new): reviews and their moderation. `sales`: unchanged; `reviews` reads purchases from the shared database.
61
+
62
+ **Work plan**
63
+ (df-ps-scaffold format: new contexts first; mark (new) and (provisional))
64
+
65
+ **Why:** own lifecycle and vocabulary → own context (step 3, rule 3); review → aggregate (choosing-components, step 4). "Only buyers" needs `sales` data → execution query `customer-purchase` in `reviews` with its own models, implementation `prisma`: same database, so no `sales` endpoint is needed (choosing-components, step 9; step 3, rule 4).
66
+
67
+ **Decisions for you:**
68
+ 1. Separate `reviews` context (recommended) or part of `catalog`?
69
+ 2. Must reviews be moderated before publishing?
70
+ ```
71
+
72
+ - Ask only what changes structure or domain behavior. Decide names and details yourself.
73
+ - Open questions block approval: answers first, then the updated plan, then approval.
74
+
75
+ ## 5. Hand off
76
+
77
+ After explicit approval, continue from step 6 of the `df-ps-scaffold` workflow: generate, implement, check isolation, report.
@@ -0,0 +1,40 @@
1
+ ---
2
+ name: df-ps-project-scripts
3
+ description: Rules for running this project's own scripts (package.json) and handling the files they produce — Prisma contract (`contract.prisma`, `prisma:emit`), database migrations (`prisma:migration:plan`, `prisma:migration:apply`), and other codegen. Use when a change needs new or changed database data (models, fields), when planning or creating a migration, when regenerating contract types, or when the user asks to run any project script that writes files.
4
+ ---
5
+
6
+ # Project scripts
7
+
8
+ The project's scripts live in `package.json`. Run them through `npm run <script>`; never call the underlying CLI with other arguments instead, except the flags listed below.
9
+
10
+ ## Rules
11
+
12
+ 1. **No approval needed.** Files written by the project's own scripts (`prisma:emit`, `prisma:migration:plan`, …) aren't "new files" under `df-ps-scaffold` rule 1: run these scripts yourself when the work needs them. Still list them under "Tool runs" in a work plan so the user sees them coming, and report every run.
13
+ 2. **The database is changed only by a human.** Never run `prisma:migration:apply` or anything else that touches the database (`prisma db …`). When a migration is ready, give the user the command (`! npm run prisma:migration:apply`) and wait.
14
+ 3. **Script output is never edited.** Generated migrations, `contract.json`, `contract.d.ts`, and any other output are used as-is: no edits, no deletions, no hand-written copies. Output is wrong → change the source (`contract.prisma`) and run the script again; if that can't fix it (a wrong migration already exists), stop and tell the user.
15
+
16
+ ## Prisma
17
+
18
+ Config: `shared/infrastructure/prisma/prisma.config.ts`. Source: `shared/infrastructure/prisma/contract.prisma` (edit by hand). Output: `contract.json`, `contract.d.ts` (from `prisma:emit`) and `migrations/` (from `prisma:migration:plan`), all next to it. The client is created in `shared/infrastructure/services/prisma-infrastructure-service.ts`.
19
+
20
+ | Script | Does | Who runs it |
21
+ | ------------------------ | ------------------------------------------------------------------------- | ----------------- |
22
+ | `prisma:emit` | Emits contract types from `contract.prisma`. Offline. | You |
23
+ | `prisma:migration:plan` | Emits, then writes a migration package from the contract change. Offline. | You |
24
+ | `prisma:migration:apply` | Applies migrations to the database. | **The user only** |
25
+
26
+ ### When to migrate
27
+
28
+ Only when domain and application logic are implemented, and implementing an infrastructure module (repository, execution command/query) needs data the database doesn't have yet. Not earlier "just in case", and never as the first step of a feature: the domain decides what's stored, not the schema.
29
+
30
+ Order: domain → application → `contract.prisma` + migration → user applies it → infrastructure → endpoints → other codegen → React.
31
+
32
+ ### Making a migration
33
+
34
+ 1. Edit `contract.prisma` for **one** logical change (a new model, a new field, a renamed field).
35
+ 2. Plan it with a name by meaning, kebab-case: `npm run prisma:migration:plan -- --name add-user`. Name what changes (`add-user`, `add-order-status`, `rename-review-text-to-body`), not the feature or the ticket.
36
+ 3. Several changes → repeat 1–2 once per change, so each migration stays atomic.
37
+ 4. Data loss: if the plan refuses and lists questions, never pass `--delete` without the user's explicit decision for that subject. Pass `--rename old:new` only when the plan says it's a rename; otherwise ask.
38
+ 5. Check the output: the planned files only, nothing else changed. Report each migration and ask the user to apply them before implementing the infrastructure that depends on them.
39
+
40
+ Types only (no storage change, e.g. after pulling someone's contract change): `npm run prisma:emit`.