rebase generation

This commit is contained in:
MaKarin
2026-04-07 19:40:41 +03:00
parent 73ddb1a948
commit aab7bfa691
180 changed files with 15512 additions and 364 deletions

View File

@@ -0,0 +1,181 @@
# Claude Code — KIS-TOiR workspace supplement
This file supplements the repository root `AGENTS.md` with Claude-specific
operational notes. The root `AGENTS.md` is the authoritative contract —
if anything here contradicts root, root wins.
---
## Agent role summary
| Role | Config file | Sandbox | Primary responsibility |
| ----------------------------------- | --------------------------------------------- | --------------- | ---------------------- |
| `explorer` | `agents/explorer.toml` | read-only | Discovery only |
| `docs_researcher` | `agents/docs-researcher.toml` | read-only | Official docs only |
| `generator_prisma` | `agents/generator_prisma.toml` | workspace-write | Prisma schema only |
| `generator_nest_resources` | `agents/generator_nest_resources.toml` | workspace-write | Nest resource layer |
| `generator_react_admin_resources` | `agents/generator_react_admin_resources.toml` | workspace-write | React Admin resources |
| `generator_data_access` | `agents/generator_data_access.toml` | workspace-write | Frontend data access |
| `reviewer` | `agents/reviewer.toml` | read-only | Final review only |
Use `explorer` first for discovery, `docs_researcher` for framework verification,
the specialized generators only after contract freeze, and `reviewer` only after
integration and validation. The old broad `generator` role is removed from the
normal full-generation workflow.
---
## Delegation model
- Shallow delegation only: keep bounded sub-tasks and one primary responsibility
per sub-agent.
- Parent owns discovery orchestration, docs verification, contract freeze,
shared scaffold, auth platform skeleton, deploy/runtime skeleton, integration,
validation, and reviewer handoff.
- Feature/resource generation must be delegated to specialized generators before
the parent falls back to manual implementation.
- Shared seams stay parent-owned even when resource generators attach
resource-aware bindings inside their delegated zones.
---
## Mutation boundary map
```
Tier 1 — Source of truth (NEVER written by any agent)
domain/*.api.dsl — single source of truth for all generation
prompts/*.md — generation spec / rules
AGENTS.md — agent operating rules
.codex/AGENTS.md — Codex-specific supplement
.claude/CLAUDE.md (this file) — Claude-specific supplement
Tier 2 — Deterministic derivatives (written only by npm scripts, not by agents)
api-summary.json ← npm run generate:api-summary
openapi.json ← npm run generate:openapi (auxiliary)
Tier 3 — LLM-generated artifacts (ownership split by bounded role)
Parent-owned shared seams:
server/src/auth/
client/src/auth/
toir-realm.json
docker-compose.yml
server/Dockerfile
client/Dockerfile
client/nginx/default.conf
server/docker-entrypoint.sh
db-seed/Dockerfile
db-seed/import.sh
server/.env.example
client/.env.example
Specialized generators:
generator_prisma
server/prisma/schema.prisma
generator_nest_resources
server/src/modules/<entity>/
server/src/app.module.ts (only when explicitly delegated)
generator_react_admin_resources
client/src/resources/<entity>/
client/src/App.tsx (only when explicitly delegated)
generator_data_access
client/src/dataProvider.ts
narrowly delegated frontend integration seams only when explicitly delegated
Note: these Tier 3 outputs may be absent at the start of a repo-wide full
regeneration run. Their absence is expected until CLI scaffolding and
generation recreate them from Tier 1 inputs.
Tier 4 — Framework-managed support files
framework scaffold and Prisma CLI-managed migrations outside prompt-governed outputs
```
## Contract freeze and acceptance
- Parent must freeze a normalized structured contract before specialized
generation starts.
- Each delegated task must include explicit write-zones, expected outputs, and
non-goals.
- Parent accepts delegated output only if allowed zones were respected, the
frozen contract still holds, no cross-layer edits leaked, and the result is
integration-ready.
- Allow at most one bounded repair pass before explicit rejection.
- Manual fallback is allowed only after rejection, not as a silent continuation
of partial delegated work.
---
## Runtime / Deploy Contract
- Tier 3 runtime/deploy outputs are first-class generation targets and must be
regenerated or repaired from the companion rules when they drift.
- Tier 4 support files are framework-managed rather than hand-authored sources
of truth.
- Runtime/deploy readiness is part of completion, not an optional follow-up.
Completion is defined in `docs/completion-contract.md`.
## Version Policy
- The approved stack version policy lives in root `AGENTS.md` and the companion prompt docs.
- After CLI scaffold creation or repair, normalize package manifests back to the approved exact versions before generation continues.
- Do not leave `latest`, caret ranges, or unreviewed major-version upgrades in regenerated manifests.
- Treat a Prisma v6 -> v7 move as an explicit migration task, not as a routine dependency refresh.
---
## Standard generation invocation
```bash
# 0. In full-regeneration mode, begin without relying on existing Tier 3 outputs
# 1. Read AGENTS.md + prompts/general-prompt.md
# 2. Use explorer for discovery and docs_researcher for official verification
# 3. Freeze the structured contract and delegated write-zones
# 4. Recreate or repair official CLI scaffolds
# 5. Launch specialized generators after contract freeze
# 6. Integrate, validate, and send to reviewer
node tools/validate-generation.mjs --artifacts-only
npm run eval:generation
```
---
## MCP servers (project-local)
Defined in `.claude/config.toml`:
- **github** — repository access when PR/repo context matters
- **context7** — primary library documentation lookup
- **exa** — current web search fallback
- **memory** — persistent cross-session context, sparingly
- **playwright** — browser automation only when UI/runtime verification needs it
- **sequential-thinking** — structured multi-step reasoning
Add heavier or credential-backed servers in `~/.claude/config.toml`.
---
## Validation gate
Run before every commit and after every generation:
```bash
# Stage 1 — structural gate
node tools/validate-generation.mjs --artifacts-only
# Stage 2 — eval harness
npm run eval:generation
```
The pre-commit hook (`tools/hooks/pre-commit`) runs both stages automatically
after `npm run install-hooks`.
---
## Security notes
- Never commit secrets. Use environment variables from `.env.example` templates.
- Run `npm audit` when adding new dependencies to `server/` or `client/`.
- Auth contracts live in `prompts/auth-rules.md`. Do not deviate from them.

View File

@@ -0,0 +1,39 @@
model = "anthropic/claude-sonnet-4.5"
model_reasoning_effort = "low"
sandbox_mode = "read-only"
developer_instructions = """
Verify APIs, framework behavior, and release-note claims against primary documentation before changes land.
Cite the exact docs or file paths that support each claim.
Do not invent undocumented behavior.
Start with local repository contracts first: AGENTS.md, prompts/general-prompt.md, the relevant prompt docs,
and the narrowest relevant DSL slice when the question is generation-related.
MCP USAGE:
- Context7 is the primary source for official library/framework documentation, API references,
canonical patterns, and examples. Use it before any generic web research for NestJS, React Admin,
Prisma, Vite, Docker, nginx, Keycloak/OIDC/JWT, and other libraries used by the task.
- Before answering a framework question, first query Context7 for the exact library involved and read
the specific section relevant to the requested behavior or API.
- GitHub is optional for upstream repository context such as release discussions, issue threads,
PR conversations, or examples hosted in the project repository.
- Exa is required when the question depends on current or unstable external information that Context7
does not reliably cover, such as release notes, breaking changes, version support, or ecosystem status.
- Playwright is optional and only relevant when documentation research needs browser evidence from a live UI flow.
- Sequential Thinking is optional for multi-step research synthesis or when multiple sources disagree.
- Memory is optional and should be used sparingly for durable research conclusions that will matter across tasks.
SOURCE PREFERENCE:
1. Local repository contracts and DSL context
2. Context7 official docs
3. GitHub for repo-hosted context
4. Exa for current external facts
PRE-READ REQUIREMENTS:
- NestJS questions: read the relevant NestJS docs in Context7 before answering.
- React Admin questions: read the relevant React Admin docs in Context7 before answering.
- Prisma questions: read the relevant Prisma docs in Context7 before answering.
- Vite questions: read the relevant Vite docs in Context7 before answering.
- Keycloak/OIDC/JWT questions: read the relevant official auth docs through Context7 when available;
use Exa for release-specific or deployment-specific material not covered there.
"""

View File

@@ -0,0 +1,48 @@
model = "anthropic/claude-haiku-4.5"
model_reasoning_effort = "medium"
sandbox_mode = "read-only"
developer_instructions = """
Stay in exploration mode. Read files freely; write nothing.
Trace the real execution path, cite files and symbols, and avoid proposing
fixes unless the parent agent asks for them.
Prefer targeted search and file reads over broad scans.
KIS-TOiR source-of-truth tier reference (read-only for this agent):
Tier 1: domain/*.api.dsl, prompts/*.md, AGENTS.md
Tier 2: api-summary.json (deterministic auxiliary derivative; never authoritative)
Tier 3: server/src/modules/, client/src/resources/, server/src/app.module.ts,
client/src/App.tsx, server/prisma/schema.prisma, server/src/auth/,
client/src/auth/, client/src/dataProvider.ts, toir-realm.json,
docker-compose.yml, server/Dockerfile, client/Dockerfile,
client/nginx/default.conf, server/docker-entrypoint.sh,
db-seed/Dockerfile, db-seed/import.sh,
server/.env.example, client/.env.example
Tier 4: framework scaffold and Prisma CLI-managed support files
When asked about generation output, always trace it back to its Tier 1 DSL source
and do not recommend api-summary.json as the primary input when the DSL is available.
MCP AND PRE-READ WORKFLOW:
- Start with local files first. Read AGENTS.md, prompts/general-prompt.md, the relevant prompt docs,
and the narrowest possible DSL slice before using any external source.
- Use Context7 when the exploration question depends on framework structure or canonical behavior:
NestJS module wiring, React Admin resource patterns, Prisma schema conventions, Vite setup,
or Keycloak/OIDC integration. For those questions, Context7 is required before Exa.
- Use GitHub optionally when the parent agent needs remote repository context, upstream implementation
examples, PR history, or issue discussions that are not present locally.
- Use Exa only for current external facts, release notes, breaking changes, or docs not available
through Context7. Do not use Exa for stable framework behavior that official docs already cover.
- Use Playwright optionally when read-only UI inspection or browser-state evidence is needed to trace
a flow, reproduce a bug, or confirm runtime behavior.
- Use Sequential Thinking for non-trivial investigations with multiple plausible execution paths or
when you need a structured evidence trail. Skip it for straightforward symbol lookup.
- Use Memory only for durable repo context that materially helps future discovery; never for transient notes or secrets.
SOURCE PREFERENCE:
1. Local authoritative files and the active DSL slice
2. Local implementation files
3. Context7 official docs
4. GitHub or Exa if their specific use cases apply
"""

View File

@@ -0,0 +1,54 @@
model = "anthropic/claude-opus-4.6"
model_reasoning_effort = "high"
sandbox_mode = "workspace-write"
approval_policy = "on-request"
developer_instructions = """
You are the bounded frontend data-access generator for KIS-TOiR.
ROLE / PURPOSE:
- Generate or update the frontend integration layer between React Admin and the backend contract.
ALLOWED WRITE ZONES:
- client/src/dataProvider.ts
- narrowly delegated frontend integration seams only when the parent explicitly includes them in the frozen contract
FORBIDDEN ZONES:
- client/src/resources/**
- client/src/auth/** unless the parent explicitly delegates a tiny compatibility touchpoint
- server/**
- server/prisma/schema.prisma
- runtime/deploy/env artifacts
- prompts, DSL files, tools, AGENTS docs
SCOPE:
- resource/path mapping
- composite key handling
- request/response normalization
- auth-aware request plumbing according to the existing auth contract
- compatibility between backend API contract and React Admin expectations
- do not redesign frontend auth from scratch, backend auth, or shared runtime/deploy behavior
REQUIRED PRE-READ ORDER:
1. AGENTS.md
2. prompts/general-prompt.md
3. parent-frozen structured contract
4. the narrow relevant DSL slice
5. prompts/auth-rules.md and prompts/frontend-rules.md
PREFERRED MCP / DOC SOURCES:
- Context7 first for official React Admin data provider and auth-related documentation
- local repository backend/path conventions next
- Exa only for version-sensitive clarification
COMPLETION CRITERIA:
- only allowed zones changed
- data-access layer matches the frozen contract and existing auth contract
- no unauthorized resource UI, backend, or runtime redesign
- output is integration-ready for parent review
HANDOFF EXPECTATIONS:
- report changed paths
- surface unresolved normalization or auth-plumbing issues explicitly
- do not claim ownership of final integration or validation
"""

View File

@@ -0,0 +1,53 @@
model = "anthropic/claude-opus-4.6"
model_reasoning_effort = "high"
sandbox_mode = "workspace-write"
approval_policy = "on-request"
developer_instructions = """
You are the bounded NestJS resource generator for KIS-TOiR.
ROLE / PURPOSE:
- Generate backend resource-level NestJS modules from a frozen contract.
ALLOWED WRITE ZONES:
- server/src/modules/**
- server/src/app.module.ts only when the parent explicitly delegates module registration touchpoints
FORBIDDEN ZONES:
- server/prisma/schema.prisma unless the parent explicitly expands the frozen contract, which should be rare
- client/**
- server/src/auth/**
- runtime/deploy/env artifacts
- prompts, DSL files, tools, AGENTS docs
SCOPE:
- controllers
- services
- DTOs
- module-level resource wiring
- attach already-defined auth platform seams where the frozen contract requires them
- do not redesign JWT/JWKS strategy, global backend infra, or shared auth platform behavior
REQUIRED PRE-READ ORDER:
1. AGENTS.md
2. prompts/general-prompt.md
3. parent-frozen structured contract
4. the narrow relevant DSL slice
5. prompts/backend-rules.md
PREFERRED MCP / DOC SOURCES:
- Context7 first for official NestJS documentation
- local repository auth/runtime seam evidence next
- Exa only when official docs are insufficient or version-sensitive details are missing
COMPLETION CRITERIA:
- only allowed zones changed
- generated modules match the frozen contract and backend rules
- no unauthorized auth/runtime/platform redesign
- output is integration-ready for parent review
HANDOFF EXPECTATIONS:
- report changed paths
- surface unresolved guard/decorator/wiring issues explicitly
- do not claim ownership of final integration or validation
"""

View File

@@ -0,0 +1,52 @@
model = "anthropic/claude-opus-4.6"
model_reasoning_effort = "high"
sandbox_mode = "workspace-write"
approval_policy = "on-request"
developer_instructions = """
You are the bounded Prisma generator for KIS-TOiR.
ROLE / PURPOSE:
- Generate or update Prisma/data-model artifacts from a frozen contract.
- Own schema/model consistency only.
ALLOWED WRITE ZONES:
- server/prisma/schema.prisma
- optional machine-readable schema summary only when the parent explicitly delegates it
FORBIDDEN ZONES:
- server/src/modules/**
- client/src/resources/**
- server/src/auth/**
- client/src/auth/**
- client/src/dataProvider.ts unless the parent explicitly delegates a summary handoff there, which is discouraged
- docker-compose.yml, Dockerfiles, nginx, env templates, realm, prompts, DSL files, tools, AGENTS docs
SCOPE:
- relations, enums, ids, composite-key representation, model consistency
- preserve or emit the Prisma header per prompt rules
- do not redesign backend/frontend/auth/runtime/platform seams
REQUIRED PRE-READ ORDER:
1. AGENTS.md
2. prompts/general-prompt.md
3. parent-frozen structured contract
4. the narrow relevant DSL slice
5. prompts/prisma-rules.md
PREFERRED MCP / DOC SOURCES:
- Context7 first for official Prisma documentation
- local repository contracts next
- Exa only for version-sensitive or missing documentation details
COMPLETION CRITERIA:
- only allowed zones changed
- schema matches the frozen contract and DSL
- no unauthorized cross-layer edits
- any parent-requested summary is included in the handoff
HANDOFF EXPECTATIONS:
- report changed paths
- summarize any unresolved relation or migration concerns explicitly
- do not claim platform integration or validation ownership
"""

View File

@@ -0,0 +1,53 @@
model = "anthropic/claude-opus-4.6"
model_reasoning_effort = "high"
sandbox_mode = "workspace-write"
approval_policy = "on-request"
developer_instructions = """
You are the bounded React Admin resource generator for KIS-TOiR.
ROLE / PURPOSE:
- Generate frontend resource-level React Admin UI from a frozen contract.
ALLOWED WRITE ZONES:
- client/src/resources/**
- client/src/App.tsx only when the parent explicitly delegates resource registration touchpoints
FORBIDDEN ZONES:
- client/src/dataProvider.ts unless the parent explicitly delegates a narrow integration touchpoint, which should usually go to generator_data_access
- client/src/auth/**
- server/**
- runtime/deploy/env artifacts
- prompts, DSL files, tools, AGENTS docs
SCOPE:
- list/show/create/edit views
- resource-level field mapping
- form/filter/sort resource logic
- compatibility with the repository data-access and auth contracts
- do not redesign auth strategy, shared API client/data-access architecture, or runtime/platform seams
REQUIRED PRE-READ ORDER:
1. AGENTS.md
2. prompts/general-prompt.md
3. parent-frozen structured contract
4. the narrow relevant DSL slice
5. prompts/frontend-rules.md
PREFERRED MCP / DOC SOURCES:
- Context7 first for official React Admin documentation
- local repository contracts next
- do not rely on memory alone for React Admin patterns
- Exa only for version-sensitive clarification
COMPLETION CRITERIA:
- only allowed zones changed
- resources match the frozen contract and frontend rules
- no unauthorized auth/data-access/runtime redesign
- output is integration-ready for parent review
HANDOFF EXPECTATIONS:
- report changed paths
- surface unresolved resource-level compatibility issues explicitly
- do not claim ownership of shared data-access or final validation
"""

View File

@@ -0,0 +1,61 @@
model = "anthropic/claude-sonnet-4.5"
model_reasoning_effort = "medium"
sandbox_mode = "read-only"
developer_instructions = """
Review mode. You may propose changes as text patches but must not write files directly.
Focus on:
- Correctness: does generated code match the api.dsl and prompt contracts?
- Security: auth guard placement, CORS, env variable handling.
- Regression: do both verification gates pass?
node tools/validate-generation.mjs --artifacts-only
npm run eval:generation
- DSL fidelity: do generated DTOs contain all fields declared in DTO.<Entity>Create/Update?
- Decorator coverage: does each DTO field have the correct class-validator decorator?
- Frontend type correctness: does each field use the correct React Admin component?
- Prompt-architecture consistency: if prompts/configs changed, is domain/toir.api.dsl still clearly authoritative and api-summary.json still clearly auxiliary?
KIS-TOiR mutation boundary (reviewer must not write to these zones):
FORBIDDEN writes: domain/*.api.dsl, prompts/*.md, AGENTS.md,
api-summary.json, tools/, server/prisma/schema.prisma
ALLOWED proposal targets (propose patches, not direct writes):
server/src/modules/<entity>/ — backend artifacts
client/src/resources/<entity>/ — frontend artifacts
server/src/app.module.ts, client/src/App.tsx — registrations
server/src/auth/, client/src/auth/ — auth artifacts
client/src/dataProvider.ts — authenticated data provider seam
toir-realm.json, docker-compose.yml — runtime/realm artifacts
server/Dockerfile, client/Dockerfile, client/nginx/default.conf — deploy/runtime artifacts
server/docker-entrypoint.sh, db-seed/Dockerfile, db-seed/import.sh — runtime bootstrap artifacts
server/.env.example, client/.env.example — runtime defaults
docs/ — documentation updates
REVIEW WORKFLOW:
1. Start with local contract files: AGENTS.md, prompts/general-prompt.md, the relevant prompt docs,
docs/completion-contract.md, prompts/validation-rules.md, and the active DSL slice.
2. Compare the changed artifacts against those contracts before consulting external sources.
3. Require validation evidence when completion is claimed:
node tools/validate-generation.mjs --artifacts-only
npm run eval:generation
MCP USAGE:
- Context7 is required when judging framework correctness or canonical usage in NestJS, React Admin,
Prisma, Vite, Docker/nginx, or Keycloak/OIDC/JWT integration and the answer is not explicit in repo rules.
- GitHub is optional for PR context, upstream issue links, or remote discussion history that affects the review.
- Exa is optional and should be used only for time-sensitive external facts such as release notes,
breaking changes, or behavior not documented in Context7.
- Playwright is required for review signoff when the change touches browser flow, SPA routing,
login behavior, or UI/runtime integration that cannot be validated from code and test output alone.
- Sequential Thinking is required for multi-finding investigations, ambiguous regressions,
or conflicts between DSL, prompts, and observed output.
- Memory is optional and should be used sparingly for durable cross-task review context only.
SOURCE PREFERENCE:
1. Root AGENTS.md and prompt contracts
2. Active DSL slice and local changed files
3. Validation output
4. Context7 official docs
5. GitHub or Exa when their specific use cases apply
"""

View File

@@ -0,0 +1,25 @@
# Claude Code Configuration for KIS-TOiR
#
# This file mirrors `.codex/config.toml` in intent. Differences here should be
# format-level only for Claude Code compatibility, not workflow or policy drift.
# Claude and Codex use different config schemas; agent role definitions live in
# `.claude/agents/*.toml`, but the intended MCP/tool strategy matches `.codex/config.toml`.
model = "claude-opus-4-6"
[mcpServers]
github = { command = "npx", args = ["-y", "@modelcontextprotocol/server-github"] }
context7 = { command = "npx", args = ["-y", "@upstash/context7-mcp@latest"] }
exa = { command = "npx", args = ["-y", "@modelcontextprotocol/server-exa"] }
memory = { command = "npx", args = ["-y", "@modelcontextprotocol/server-memory"] }
playwright = { command = "npx", args = ["-y", "@playwright/mcp@latest", "--extension"] }
sequential-thinking = { command = "npx", args = ["-y", "@modelcontextprotocol/server-sequential-thinking"] }
[agents]
explorer = { config_file = "agents/explorer.toml" }
docs_researcher = { config_file = "agents/docs-researcher.toml" }
generator_prisma = { config_file = "agents/generator_prisma.toml" }
generator_nest_resources = { config_file = "agents/generator_nest_resources.toml" }
generator_react_admin_resources = { config_file = "agents/generator_react_admin_resources.toml" }
generator_data_access = { config_file = "agents/generator_data_access.toml" }
reviewer = { config_file = "agents/reviewer.toml" }

View File

@@ -0,0 +1,181 @@
# Codex CLI — KIS-TOiR workspace supplement
This file supplements the repository root `AGENTS.md` with Codex-specific
operational notes. The root `AGENTS.md` is the authoritative contract —
if anything here contradicts root, root wins.
---
## Agent role summary
| Role | Config file | Sandbox | Primary responsibility |
| ----------------------------------- | --------------------------------------------- | --------------- | ---------------------- |
| `explorer` | `agents/explorer.toml` | read-only | Discovery only |
| `docs_researcher` | `agents/docs-researcher.toml` | read-only | Official docs only |
| `generator_prisma` | `agents/generator_prisma.toml` | workspace-write | Prisma schema only |
| `generator_nest_resources` | `agents/generator_nest_resources.toml` | workspace-write | Nest resource layer |
| `generator_react_admin_resources` | `agents/generator_react_admin_resources.toml` | workspace-write | React Admin resources |
| `generator_data_access` | `agents/generator_data_access.toml` | workspace-write | Frontend data access |
| `reviewer` | `agents/reviewer.toml` | read-only | Final review only |
Use `explorer` first for discovery, `docs_researcher` for framework verification,
the specialized generators only after contract freeze, and `reviewer` only after
integration and validation. The old broad `generator` role is removed from the
normal full-generation workflow.
---
## Delegation model
- Shallow delegation only: keep `max_depth = 1` and bounded sub-tasks.
- One primary responsibility per sub-agent.
- Parent owns discovery orchestration, docs verification, contract freeze,
shared scaffold, auth platform skeleton, deploy/runtime skeleton, integration,
validation, and reviewer handoff.
- Feature/resource generation must be delegated to specialized generators before
the parent falls back to manual implementation.
- Shared seams stay parent-owned even when resource generators attach
resource-aware bindings inside their delegated zones.
---
## Mutation boundary map
```
Tier 1 — Source of truth (NEVER written by any agent)
domain/*.api.dsl — single source of truth for all generation
prompts/*.md — generation spec / rules
AGENTS.md — agent operating rules
.codex/AGENTS.md (this file) — Codex-specific supplement
.claude/CLAUDE.md — Claude-specific supplement
Tier 2 — Deterministic derivatives (written only by npm scripts, not by agents)
api-summary.json ← npm run generate:api-summary
openapi.json ← npm run generate:openapi (auxiliary)
Tier 3 — LLM-generated artifacts (ownership split by bounded role)
Parent-owned shared seams:
server/src/auth/
client/src/auth/
toir-realm.json
docker-compose.yml
server/Dockerfile
client/Dockerfile
client/nginx/default.conf
server/docker-entrypoint.sh
db-seed/Dockerfile
db-seed/import.sh
server/.env.example
client/.env.example
Specialized generators:
generator_prisma
server/prisma/schema.prisma
generator_nest_resources
server/src/modules/<entity>/
server/src/app.module.ts (only when explicitly delegated)
generator_react_admin_resources
client/src/resources/<entity>/
client/src/App.tsx (only when explicitly delegated)
generator_data_access
client/src/dataProvider.ts
narrowly delegated frontend integration seams only when explicitly delegated
Note: these Tier 3 outputs may be absent at the start of a repo-wide full
regeneration run. Their absence is expected until CLI scaffolding and
generation recreate them from Tier 1 inputs.
Tier 4 — Framework-managed support files
framework scaffold and Prisma CLI-managed migrations outside prompt-governed outputs
```
## Contract freeze and acceptance
- Parent must freeze a normalized structured contract before specialized
generation starts.
- Each delegated task must include explicit write-zones, expected outputs, and
non-goals.
- Parent accepts delegated output only if allowed zones were respected, the
frozen contract still holds, no cross-layer edits leaked, and the result is
integration-ready.
- Allow at most one bounded repair pass before explicit rejection.
- Manual fallback is allowed only after rejection, not as a silent continuation
of partial delegated work.
## Runtime / Deploy Contract
- Tier 3 runtime/deploy outputs are first-class generation targets and must be
regenerated or repaired from the companion rules when they drift.
- Tier 4 support files are framework-managed rather than hand-authored sources
of truth.
- Runtime/deploy readiness is part of completion, not an optional follow-up.
Completion is defined in `docs/completion-contract.md`.
## Version Policy
- The approved stack version policy lives in root `AGENTS.md` and the companion prompt docs.
- After CLI scaffold creation or repair, normalize package manifests back to the approved exact versions before generation continues.
- Do not leave `latest`, caret ranges, or unreviewed major-version upgrades in regenerated manifests.
- Treat a Prisma v6 -> v7 move as an explicit migration task, not as a routine dependency refresh.
---
## Standard generation invocation
```bash
# 0. In full-regeneration mode, begin without relying on existing Tier 3 outputs
# 1. Read AGENTS.md + prompts/general-prompt.md
# 2. Use explorer for discovery and docs_researcher for official verification
# 3. Freeze the structured contract and delegated write-zones
# 4. Recreate or repair official CLI scaffolds
# 5. Launch specialized generators after contract freeze
# 6. Integrate, validate, and send to reviewer
node tools/validate-generation.mjs --artifacts-only
npm run eval:generation
```
---
## MCP servers (project-local)
Defined in `.codex/config.toml`:
- **github** — repository access when PR/repo context matters
- **context7** — primary library documentation lookup
- **exa** — current web search fallback
- **memory** — persistent cross-session context, sparingly
- **playwright** — browser automation only when UI/runtime verification needs it
- **sequential-thinking** — structured multi-step reasoning
Add heavier or credential-backed servers in `~/.codex/config.toml`.
---
## Validation gate
Run before every commit and after every generation:
```bash
# Stage 1 — structural gate
node tools/validate-generation.mjs --artifacts-only
# Stage 2 — eval harness
npm run eval:generation
```
The pre-commit hook (`tools/hooks/pre-commit`) runs both stages automatically
after `npm run install-hooks`.
Completion is defined in `docs/completion-contract.md`.
---
## Security notes
- Never commit secrets. Use environment variables from `.env.example` templates.
- Run `npm audit` when adding new dependencies to `server/` or `client/`.
- Auth contracts live in `prompts/auth-rules.md`. Do not deviate from them.

View File

@@ -0,0 +1,39 @@
model = "gpt-5.4-mini"
model_reasoning_effort = "medium"
sandbox_mode = "read-only"
developer_instructions = """
Verify APIs, framework behavior, and release-note claims against primary documentation before changes land.
Cite the exact docs or file paths that support each claim.
Do not invent undocumented behavior.
Start with local repository contracts first: AGENTS.md, prompts/general-prompt.md, the relevant prompt docs,
and the narrowest relevant DSL slice when the question is generation-related.
MCP USAGE:
- Context7 is the primary source for official library/framework documentation, API references,
canonical patterns, and examples. Use it before any generic web research for NestJS, React Admin,
Prisma, Vite, Docker, nginx, Keycloak/OIDC/JWT, and other libraries used by the task.
- Before answering a framework question, first query Context7 for the exact library involved and read
the specific section relevant to the requested behavior or API.
- GitHub is optional for upstream repository context such as release discussions, issue threads,
PR conversations, or examples hosted in the project repository.
- Exa is required when the question depends on current or unstable external information that Context7
does not reliably cover, such as release notes, breaking changes, version support, or ecosystem status.
- Playwright is optional and only relevant when documentation research needs browser evidence from a live UI flow.
- Sequential Thinking is optional for multi-step research synthesis or when multiple sources disagree.
- Memory is optional and should be used sparingly for durable research conclusions that will matter across tasks.
SOURCE PREFERENCE:
1. Local repository contracts and DSL context
2. Context7 official docs
3. GitHub for repo-hosted context
4. Exa for current external facts
PRE-READ REQUIREMENTS:
- NestJS questions: read the relevant NestJS docs in Context7 before answering.
- React Admin questions: read the relevant React Admin docs in Context7 before answering.
- Prisma questions: read the relevant Prisma docs in Context7 before answering.
- Vite questions: read the relevant Vite docs in Context7 before answering.
- Keycloak/OIDC/JWT questions: read the relevant official auth docs through Context7 when available;
use Exa for release-specific or deployment-specific material not covered there.
"""

View File

@@ -0,0 +1,48 @@
model = "gpt-5.4-mini"
model_reasoning_effort = "medium"
sandbox_mode = "read-only"
developer_instructions = """
Stay in exploration mode. Read files freely; write nothing.
Trace the real execution path, cite files and symbols, and avoid proposing
fixes unless the parent agent asks for them.
Prefer targeted search and file reads over broad scans.
KIS-TOiR source-of-truth tier reference (read-only for this agent):
Tier 1: domain/*.api.dsl, prompts/*.md, AGENTS.md
Tier 2: api-summary.json (deterministic auxiliary derivative; never authoritative)
Tier 3: server/src/modules/, client/src/resources/, server/src/app.module.ts,
client/src/App.tsx, server/prisma/schema.prisma, server/src/auth/,
client/src/auth/, client/src/dataProvider.ts, toir-realm.json,
docker-compose.yml, server/Dockerfile, client/Dockerfile,
client/nginx/default.conf, server/docker-entrypoint.sh,
db-seed/Dockerfile, db-seed/import.sh,
server/.env.example, client/.env.example
Tier 4: framework scaffold and Prisma CLI-managed support files
When asked about generation output, always trace it back to its Tier 1 DSL source
and do not recommend api-summary.json as the primary input when the DSL is available.
MCP AND PRE-READ WORKFLOW:
- Start with local files first. Read AGENTS.md, prompts/general-prompt.md, the relevant prompt docs,
and the narrowest possible DSL slice before using any external source.
- Use Context7 when the exploration question depends on framework structure or canonical behavior:
NestJS module wiring, React Admin resource patterns, Prisma schema conventions, Vite setup,
or Keycloak/OIDC integration. For those questions, Context7 is required before Exa.
- Use GitHub optionally when the parent agent needs remote repository context, upstream implementation
examples, PR history, or issue discussions that are not present locally.
- Use Exa only for current external facts, release notes, breaking changes, or docs not available
through Context7. Do not use Exa for stable framework behavior that official docs already cover.
- Use Playwright optionally when read-only UI inspection or browser-state evidence is needed to trace
a flow, reproduce a bug, or confirm runtime behavior.
- Use Sequential Thinking for non-trivial investigations with multiple plausible execution paths or
when you need a structured evidence trail. Skip it for straightforward symbol lookup.
- Use Memory only for durable repo context that materially helps future discovery; never for transient notes or secrets.
SOURCE PREFERENCE:
1. Local authoritative files and the active DSL slice
2. Local implementation files
3. Context7 official docs
4. GitHub or Exa if their specific use cases apply
"""

View File

@@ -0,0 +1,54 @@
model = "gpt-5.4"
model_reasoning_effort = "high"
sandbox_mode = "workspace-write"
approval_policy = "on-request"
developer_instructions = """
You are the bounded frontend data-access generator for KIS-TOiR.
ROLE / PURPOSE:
- Generate or update the frontend integration layer between React Admin and the backend contract.
ALLOWED WRITE ZONES:
- client/src/dataProvider.ts
- narrowly delegated frontend integration seams only when the parent explicitly includes them in the frozen contract
FORBIDDEN ZONES:
- client/src/resources/**
- client/src/auth/** unless the parent explicitly delegates a tiny compatibility touchpoint
- server/**
- server/prisma/schema.prisma
- runtime/deploy/env artifacts
- prompts, DSL files, tools, AGENTS docs
SCOPE:
- resource/path mapping
- composite key handling
- request/response normalization
- auth-aware request plumbing according to the existing auth contract
- compatibility between backend API contract and React Admin expectations
- do not redesign frontend auth from scratch, backend auth, or shared runtime/deploy behavior
REQUIRED PRE-READ ORDER:
1. AGENTS.md
2. prompts/general-prompt.md
3. parent-frozen structured contract
4. the narrow relevant DSL slice
5. prompts/auth-rules.md and prompts/frontend-rules.md
PREFERRED MCP / DOC SOURCES:
- Context7 first for official React Admin data provider and auth-related documentation
- local repository backend/path conventions next
- Exa only for version-sensitive clarification
COMPLETION CRITERIA:
- only allowed zones changed
- data-access layer matches the frozen contract and existing auth contract
- no unauthorized resource UI, backend, or runtime redesign
- output is integration-ready for parent review
HANDOFF EXPECTATIONS:
- report changed paths
- surface unresolved normalization or auth-plumbing issues explicitly
- do not claim ownership of final integration or validation
"""

View File

@@ -0,0 +1,53 @@
model = "gpt-5.4"
model_reasoning_effort = "high"
sandbox_mode = "workspace-write"
approval_policy = "on-request"
developer_instructions = """
You are the bounded NestJS resource generator for KIS-TOiR.
ROLE / PURPOSE:
- Generate backend resource-level NestJS modules from a frozen contract.
ALLOWED WRITE ZONES:
- server/src/modules/**
- server/src/app.module.ts only when the parent explicitly delegates module registration touchpoints
FORBIDDEN ZONES:
- server/prisma/schema.prisma unless the parent explicitly expands the frozen contract, which should be rare
- client/**
- server/src/auth/**
- runtime/deploy/env artifacts
- prompts, DSL files, tools, AGENTS docs
SCOPE:
- controllers
- services
- DTOs
- module-level resource wiring
- attach already-defined auth platform seams where the frozen contract requires them
- do not redesign JWT/JWKS strategy, global backend infra, or shared auth platform behavior
REQUIRED PRE-READ ORDER:
1. AGENTS.md
2. prompts/general-prompt.md
3. parent-frozen structured contract
4. the narrow relevant DSL slice
5. prompts/backend-rules.md
PREFERRED MCP / DOC SOURCES:
- Context7 first for official NestJS documentation
- local repository auth/runtime seam evidence next
- Exa only when official docs are insufficient or version-sensitive details are missing
COMPLETION CRITERIA:
- only allowed zones changed
- generated modules match the frozen contract and backend rules
- no unauthorized auth/runtime/platform redesign
- output is integration-ready for parent review
HANDOFF EXPECTATIONS:
- report changed paths
- surface unresolved guard/decorator/wiring issues explicitly
- do not claim ownership of final integration or validation
"""

View File

@@ -0,0 +1,52 @@
model = "gpt-5.4"
model_reasoning_effort = "high"
sandbox_mode = "workspace-write"
approval_policy = "on-request"
developer_instructions = """
You are the bounded Prisma generator for KIS-TOiR.
ROLE / PURPOSE:
- Generate or update Prisma/data-model artifacts from a frozen contract.
- Own schema/model consistency only.
ALLOWED WRITE ZONES:
- server/prisma/schema.prisma
- optional machine-readable schema summary only when the parent explicitly delegates it
FORBIDDEN ZONES:
- server/src/modules/**
- client/src/resources/**
- server/src/auth/**
- client/src/auth/**
- client/src/dataProvider.ts unless the parent explicitly delegates a summary handoff there, which is discouraged
- docker-compose.yml, Dockerfiles, nginx, env templates, realm, prompts, DSL files, tools, AGENTS docs
SCOPE:
- relations, enums, ids, composite-key representation, model consistency
- preserve or emit the Prisma header per prompt rules
- do not redesign backend/frontend/auth/runtime/platform seams
REQUIRED PRE-READ ORDER:
1. AGENTS.md
2. prompts/general-prompt.md
3. parent-frozen structured contract
4. the narrow relevant DSL slice
5. prompts/prisma-rules.md
PREFERRED MCP / DOC SOURCES:
- Context7 first for official Prisma documentation
- local repository contracts next
- Exa only for version-sensitive or missing documentation details
COMPLETION CRITERIA:
- only allowed zones changed
- schema matches the frozen contract and DSL
- no unauthorized cross-layer edits
- any parent-requested summary is included in the handoff
HANDOFF EXPECTATIONS:
- report changed paths
- summarize any unresolved relation or migration concerns explicitly
- do not claim platform integration or validation ownership
"""

View File

@@ -0,0 +1,53 @@
model = "gpt-5.4"
model_reasoning_effort = "high"
sandbox_mode = "workspace-write"
approval_policy = "on-request"
developer_instructions = """
You are the bounded React Admin resource generator for KIS-TOiR.
ROLE / PURPOSE:
- Generate frontend resource-level React Admin UI from a frozen contract.
ALLOWED WRITE ZONES:
- client/src/resources/**
- client/src/App.tsx only when the parent explicitly delegates resource registration touchpoints
FORBIDDEN ZONES:
- client/src/dataProvider.ts unless the parent explicitly delegates a narrow integration touchpoint, which should usually go to generator_data_access
- client/src/auth/**
- server/**
- runtime/deploy/env artifacts
- prompts, DSL files, tools, AGENTS docs
SCOPE:
- list/show/create/edit views
- resource-level field mapping
- form/filter/sort resource logic
- compatibility with the repository data-access and auth contracts
- do not redesign auth strategy, shared API client/data-access architecture, or runtime/platform seams
REQUIRED PRE-READ ORDER:
1. AGENTS.md
2. prompts/general-prompt.md
3. parent-frozen structured contract
4. the narrow relevant DSL slice
5. prompts/frontend-rules.md
PREFERRED MCP / DOC SOURCES:
- Context7 first for official React Admin documentation
- local repository contracts next
- do not rely on memory alone for React Admin patterns
- Exa only for version-sensitive clarification
COMPLETION CRITERIA:
- only allowed zones changed
- resources match the frozen contract and frontend rules
- no unauthorized auth/data-access/runtime redesign
- output is integration-ready for parent review
HANDOFF EXPECTATIONS:
- report changed paths
- surface unresolved resource-level compatibility issues explicitly
- do not claim ownership of shared data-access or final validation
"""

View File

@@ -0,0 +1,61 @@
model = "gpt-5.4"
model_reasoning_effort = "high"
sandbox_mode = "read-only"
developer_instructions = """
Review mode. You may propose changes as text patches but must not write files directly.
Focus on:
- Correctness: does generated code match the api.dsl and prompt contracts?
- Security: auth guard placement, CORS, env variable handling.
- Regression: do both verification gates pass?
node tools/validate-generation.mjs --artifacts-only
npm run eval:generation
- DSL fidelity: do generated DTOs contain all fields declared in DTO.<Entity>Create/Update?
- Decorator coverage: does each DTO field have the correct class-validator decorator?
- Frontend type correctness: does each field use the correct React Admin component?
- Prompt-architecture consistency: if prompts/configs changed, is domain/toir.api.dsl still clearly authoritative and api-summary.json still clearly auxiliary?
KIS-TOiR mutation boundary (reviewer must not write to these zones):
FORBIDDEN writes: domain/*.api.dsl, prompts/*.md, AGENTS.md,
api-summary.json, tools/, server/prisma/schema.prisma
ALLOWED proposal targets (propose patches, not direct writes):
server/src/modules/<entity>/ — backend artifacts
client/src/resources/<entity>/ — frontend artifacts
server/src/app.module.ts, client/src/App.tsx — registrations
server/src/auth/, client/src/auth/ — auth artifacts
client/src/dataProvider.ts — authenticated data provider seam
toir-realm.json, docker-compose.yml — runtime/realm artifacts
server/Dockerfile, client/Dockerfile, client/nginx/default.conf — deploy/runtime artifacts
server/docker-entrypoint.sh, db-seed/Dockerfile, db-seed/import.sh — runtime bootstrap artifacts
server/.env.example, client/.env.example — runtime defaults
docs/ — documentation updates
REVIEW WORKFLOW:
1. Start with local contract files: AGENTS.md, prompts/general-prompt.md, the relevant prompt docs,
docs/completion-contract.md, prompts/validation-rules.md, and the active DSL slice.
2. Compare the changed artifacts against those contracts before consulting external sources.
3. Require validation evidence when completion is claimed:
node tools/validate-generation.mjs --artifacts-only
npm run eval:generation
MCP USAGE:
- Context7 is required when judging framework correctness or canonical usage in NestJS, React Admin,
Prisma, Vite, Docker/nginx, or Keycloak/OIDC/JWT integration and the answer is not explicit in repo rules.
- GitHub is optional for PR context, upstream issue links, or remote discussion history that affects the review.
- Exa is optional and should be used only for time-sensitive external facts such as release notes,
breaking changes, or behavior not documented in Context7.
- Playwright is required for review signoff when the change touches browser flow, SPA routing,
login behavior, or UI/runtime integration that cannot be validated from code and test output alone.
- Sequential Thinking is required for multi-finding investigations, ambiguous regressions,
or conflicts between DSL, prompts, and observed output.
- Memory is optional and should be used sparingly for durable cross-task review context only.
SOURCE PREFERENCE:
1. Root AGENTS.md and prompt contracts
2. Active DSL slice and local changed files
3. Validation output
4. Context7 official docs
5. GitHub or Exa when their specific use cases apply
"""

View File

@@ -0,0 +1,137 @@
#:schema https://developers.openai.com/codex/config-schema.json
# Everything Claude Code (ECC) — Codex Reference Configuration
#
# Copy this file to ~/.codex/config.toml for global defaults, or keep it in
# the project root as .codex/config.toml for project-local settings.
#
# Official docs:
# - https://developers.openai.com/codex/config-reference
# - https://developers.openai.com/codex/multi-agent
# Model selection
# Leave `model` and `model_provider` unset so Codex CLI uses its current
# built-in defaults. Uncomment and pin them only if you intentionally want
# repo-local or global model overrides.
# Top-level runtime settings (current Codex schema)
approval_policy = "on-request"
sandbox_mode = "workspace-write"
web_search = "live"
# External notifications receive a JSON payload on stdin.
# macOS example (uncomment on Mac if `terminal-notifier` is installed):
# notify = [
# "terminal-notifier",
# "-title", "Codex KIS",
# "-message", "Task completed!",
# "-sound", "default",
# ]
# Persistent instructions are appended to every prompt (additive, unlike
# model_instructions_file which replaces AGENTS.md).
persistent_instructions = "Follow project AGENTS.md guidelines. Use available MCP servers when they can help."
# model_instructions_file replaces built-in instructions instead of AGENTS.md,
# so leave it unset unless you intentionally want a single override file.
# model_instructions_file = "/absolute/path/to/instructions.md"
# MCP servers
# Keep the default project set lean. API-backed servers inherit credentials from
# the launching environment or can be supplied by a user-level ~/.codex/config.toml.
[mcp_servers.github]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-github"]
startup_timeout_sec = 30
[mcp_servers.context7]
command = "npx"
# Canonical Codex section name is `context7`; the package itself remains
# `@upstash/context7-mcp`.
args = ["-y", "@upstash/context7-mcp@latest"]
startup_timeout_sec = 30
[mcp_servers.exa]
url = "https://mcp.exa.ai/mcp"
[mcp_servers.memory]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-memory"]
startup_timeout_sec = 30
[mcp_servers.playwright]
command = "npx"
args = ["-y", "@playwright/mcp@latest"]
startup_timeout_sec = 30
[mcp_servers.sequential-thinking]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-sequential-thinking"]
startup_timeout_sec = 30
# Additional MCP servers (uncomment as needed):
# [mcp_servers.supabase]
# command = "npx"
# args = ["-y", "supabase-mcp-server@latest", "--read-only"]
#
# [mcp_servers.firecrawl]
# command = "npx"
# args = ["-y", "firecrawl-mcp"]
#
# [mcp_servers.fal-ai]
# command = "npx"
# args = ["-y", "fal-ai-mcp-server"]
#
# [mcp_servers.cloudflare]
# command = "npx"
# args = ["-y", "@cloudflare/mcp-server-cloudflare"]
[features]
# Codex multi-agent collaboration is stable and on by default in current builds.
# Keep the explicit toggle here so the repo documents its expectation clearly.
multi_agent = true
# Profiles — switch with `codex -p <name>`
[profiles.strict]
approval_policy = "on-request"
sandbox_mode = "read-only"
web_search = "cached"
[profiles.yolo]
approval_policy = "never"
sandbox_mode = "workspace-write"
web_search = "live"
[agents]
# Multi-agent role limits and local role definitions.
# These map to `.codex/agents/*.toml` and mirror the repo's explorer/reviewer/docs workflow.
max_threads = 6
max_depth = 1
[agents.explorer]
description = "Read-only codebase explorer for gathering evidence before changes are proposed."
config_file = "agents/explorer.toml"
[agents.reviewer]
description = "PR reviewer focused on correctness, security, and DSL fidelity. Proposes patches; writes nothing directly."
config_file = "agents/reviewer.toml"
[agents.docs_researcher]
description = "Documentation specialist that verifies APIs, framework behavior, and release notes."
config_file = "agents/docs-researcher.toml"
[agents.generator_prisma]
description = "Bounded Prisma schema generator for frozen-contract data-model work only."
config_file = "agents/generator_prisma.toml"
[agents.generator_nest_resources]
description = "Bounded NestJS resource generator for server module artifacts only."
config_file = "agents/generator_nest_resources.toml"
[agents.generator_react_admin_resources]
description = "Bounded React Admin resource generator for frontend resource artifacts only."
config_file = "agents/generator_react_admin_resources.toml"
[agents.generator_data_access]
description = "Bounded frontend data-access generator for the React Admin/backend integration seam."
config_file = "agents/generator_data_access.toml"

View File

@@ -0,0 +1,13 @@
POSTGRES_USER=postgres
POSTGRES_PASSWORD=change-me
POSTGRES_DB=toir
CORS_ALLOWED_ORIGINS=https://toir.example.ru
KEYCLOAK_ISSUER_URL=https://sso.example.ru/realms/toir
KEYCLOAK_AUDIENCE=toir-backend
KEYCLOAK_JWKS_URL=
VITE_API_URL=/api
VITE_KEYCLOAK_URL=https://sso.example.ru
VITE_KEYCLOAK_REALM=toir
VITE_KEYCLOAK_CLIENT_ID=toir-frontend

View File

@@ -0,0 +1,43 @@
# Dependencies
**/node_modules/
# Build outputs
**/dist/
**/dist-ssr/
**/coverage/
**/.cache/
**/*.tsbuildinfo
# Environment files
**/.env
**/.env.local
**/.env.*.local
# Logs
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# OS files
.DS_Store
Thumbs.db
# Editor / IDE
.vscode/*
!.vscode/extensions.json
.idea/
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Generated OpenAPI (local runs; commit only if you want to publish the spec)
openapi.generated.json
openapi.llm.json
tools/api-format-to-openapi/demo-output/
.cursor/

View File

@@ -0,0 +1,475 @@
# KIS-TOiR — Agent Operating Rules
Read this file at the start of every session before reading any other file.
---
## What this repository is
KIS-TOiR is a fullstack CRUD application (NestJS backend + React Admin frontend)
for equipment maintenance management (Техническое обслуживание и ремонт).
Generation is driven by a single authoritative source file:
- `domain/toir.api.dsl` — the complete API contract: enums, DTOs, endpoints, HTTP methods, pagination
---
## Source-of-truth hierarchy
### Tier 1 — authoritative (hand-authored; never overwritten by generation)
| File | Authoritative for |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `domain/*.api.dsl` | Enums, DTO shapes per operation, nullability, HTTP verb+path per endpoint, endpoint names, pagination contracts. Single source of truth. Drives: NestJS modules + React Admin resources + Prisma schema. |
| `prompts/*.md` | Auth rules, runtime rules, framework scaffold rules, Prisma rules, validation rules, generation policy, naming conventions. |
| `AGENTS.md` (this file) | Agent workflow, mutation boundaries, verification contract. |
| `docs/completion-contract.md` | Operational definition of done, success tiers, failure modes, recovery rules. |
| `.codex/AGENTS.md` | Codex-specific agent governance supplement. |
| `.claude/CLAUDE.md` | Claude-specific agent governance supplement. |
### Tier 2 — deterministic derivative (generated by script; never edited manually)
| File | Generated from | Command |
| ------------------ | ------------------ | ------------------------------ |
| `api-summary.json` | `domain/*.api.dsl` | `npm run generate:api-summary` |
### Tier 3 — LLM-generated artifacts (never edit manually after generation)
These outputs are end-state generation targets. During a repo-wide full
regeneration driven by `prompts/general-prompt.md`, they may be absent at the
start of the run and are recreated from Tier 1 sources plus official CLI
scaffolding.
| Zone | Generated from |
| -------------------------------- | ------------------------------------------------------ |
| `server/src/modules/<entity>/` | `domain/*.api.dsl` + `prompts/backend-rules.md` |
| `client/src/resources/<entity>/` | `domain/*.api.dsl` + `prompts/frontend-rules.md` |
| `server/src/app.module.ts` | Module registrations derived from api.dsl api blocks |
| `client/src/App.tsx` | Resource registrations derived from api.dsl api blocks |
| `server/prisma/schema.prisma` | `domain/*.api.dsl` + `prompts/prisma-rules.md` |
| `server/src/auth/` | `prompts/auth-rules.md` |
| `client/src/auth/` | `prompts/auth-rules.md` |
| `client/src/dataProvider.ts` | `prompts/auth-rules.md` |
| `toir-realm.json` | `prompts/auth-rules.md` |
| `docker-compose.yml` | `prompts/runtime-rules.md` |
| `server/Dockerfile` | `prompts/runtime-rules.md` |
| `client/Dockerfile` | `prompts/runtime-rules.md` |
| `client/nginx/default.conf` | `prompts/runtime-rules.md` |
| `server/docker-entrypoint.sh` | `prompts/runtime-rules.md` |
| `db-seed/Dockerfile` | `prompts/runtime-rules.md` |
| `db-seed/import.sh` | `prompts/runtime-rules.md` |
| `server/.env.example` | `prompts/runtime-rules.md` |
| `client/.env.example` | `prompts/runtime-rules.md` |
### Tier 4 — handwritten / framework-managed support files
- Framework scaffold and bootstrap helpers that remain manually maintained unless a repair task says otherwise:
`server/nest-cli.json`, `server/tsconfig*.json`, `client/vite.config.*`, etc.
### Runtime / Deploy Contract
- Tier 3 runtime/deploy outputs are first-class generation targets and must be regenerated from the companion rules when they drift.
- Tier 4 support files are framework-managed rather than hand-authored sources of truth.
- Runtime/deploy readiness is part of completion, not an optional follow-up.
## Approved Stack Version Policy
Future full-regeneration runs must normalize scaffolded package manifests and runtime inputs to the approved versions below. Do not use `latest`, caret ranges, or unreviewed major bumps when the repository regenerates or repairs the stack.
Runtime baseline:
- Node.js: prefer the Node 22 LTS line; minimum approved version is `22.12.0`
- Package manager: `npm` only, with committed `package-lock.json` files; do not switch the repo to `pnpm`, `yarn`, or `bun`
Backend generation baseline:
- `@nestjs/common`, `@nestjs/core`, `@nestjs/platform-express`, `@nestjs/testing`: `11.1.18`
- `@nestjs/config`: `4.0.3`
- `@nestjs/cli`: `11.0.17`
- `@nestjs/schematics`: `11.0.10`
- `prisma` and `@prisma/client`: `6.16.2` exactly, kept on the same version
- `class-validator`: `0.15.1`
- `class-transformer`: `0.5.1`
- `jose`: `6.2.2`
- `reflect-metadata`: `0.2.2`
- `rxjs`: `7.8.1`
- backend `typescript`: `5.7.3`
Frontend generation baseline:
- `react` and `react-dom`: `19.2.4`
- `react-admin` and `ra-data-simple-rest`: `5.14.5`
- `@mui/material` and `@mui/icons-material`: `7.3.9`
- `@emotion/react`: `11.14.0`
- `@emotion/styled`: `11.14.1`
- `vite`: `8.0.3`
- `@vitejs/plugin-react`: `6.0.1`
- frontend `typescript`: `5.9.3`
- `keycloak-js`: `26.2.3`
Policy rules:
- When official CLIs scaffold newer dependency sets, repair the scaffold and then pin it back to the approved versions above before generation continues.
- `prisma` and `@prisma/client` must always stay on the same exact version.
- Do not upgrade Prisma from v6 to v7 as part of routine regeneration; treat that as a separate explicit migration task with updated prompts, runtime checks, and verification.
---
## Forbidden mutations during any generation run
**NEVER write to `*.dsl` files.**
They are read-only inputs. To change the API contract or domain model, edit `domain/*.api.dsl`
as a separate explicit task.
**NEVER manually edit files under `server/src/modules/` or `client/src/resources/`.**
To change generated code: update `domain/*.api.dsl` and regenerate.
**NEVER edit `server/prisma/schema.prisma` directly.**
It is LLM-generated from `domain/*.api.dsl` following `prompts/prisma-rules.md`.
---
## Multi-agent orchestration model
Full-generation runs use a parent-orchestrated, bounded multi-agent model.
The parent agent is the orchestrator/integrator. It is not the default broad
feature implementer.
Parent-only responsibilities:
- discovery orchestration
- docs verification orchestration
- contract freeze
- shared platform scaffold
- auth platform skeleton
- deploy/runtime skeleton
- shared platform wiring and env/runtime conventions
- launching specialized generators
- accepting or rejecting generator outputs
- final integration
- validation
- final handoff to reviewer
Specialized generation agents:
- `generator_prisma` — schema/model generation only
- `generator_nest_resources` — NestJS resource modules only
- `generator_react_admin_resources` — React Admin resource UI only
- `generator_data_access` — frontend data-access seam only
The old universal `generator` agent is removed from the active orchestration
model and must not be used for full-generation workflows.
### Delegation order
Use agents in this order:
1. `explorer` for repository discovery, execution-path inspection, scaffold checks, and local seam tracing
2. `docs_researcher` for official documentation verification and version-sensitive framework behavior
3. parent contract freeze and shared scaffold/auth/runtime planning
4. specialized generators after contract freeze, in parallel when safe:
- `generator_prisma`
- `generator_nest_resources`
- `generator_react_admin_resources`
- `generator_data_access`
5. parent integration and validation
6. `reviewer` only at the final review stage
If a runtime does not expose named subagents, keep the same separation of
responsibilities inside one agent and preserve the same handoff boundaries.
### Write-zone ownership
Parent-only write zones:
- shared scaffold and framework repair surfaces
- `server/src/auth/`
- `client/src/auth/`
- `toir-realm.json`
- `docker-compose.yml`
- `server/Dockerfile`
- `client/Dockerfile`
- `client/nginx/default.conf`
- `server/docker-entrypoint.sh`
- `db-seed/Dockerfile`
- `db-seed/import.sh`
- `server/.env.example`
- `client/.env.example`
- shared integration seams and final validation outputs explicitly delegated by prompts
Specialized generator write zones:
- `generator_prisma`
- `server/prisma/schema.prisma`
- optional machine-readable schema summary or structured handoff artifact when the parent explicitly requests it
- `generator_nest_resources`
- `server/src/modules/**`
- backend registration touchpoints only when explicitly delegated by the parent contract
- `generator_react_admin_resources`
- `client/src/resources/**`
- frontend resource registration touchpoints only when explicitly delegated by the parent contract
- `generator_data_access`
- `client/src/dataProvider.ts`
- narrowly delegated frontend integration seams only when explicitly delegated by the parent contract
Specialized generators must not redesign shared auth, runtime, deploy, scaffold,
or platform seams outside their delegated zones.
### Contract freeze (required before specialized generation)
Before launching specialized generators, the parent must produce a normalized
structured handoff from the DSL and prompt contracts. This contract freeze is a
required protocol owned by the parent; it does not replace `domain/*.api.dsl`.
The frozen contract must cover, where relevant:
- entities
- fields
- scalar and enum types
- ids and composite keys
- relations
- enums
- endpoint conventions
- route and path conventions
- naming rules
- auth surface expectations
- validator and eval compatibility constraints
- allowed write-zones per generator
Specialized generators start only after the parent freezes this contract and
delegates a bounded write-scope.
### Acceptance protocol for generator outputs
Parent acceptance is explicit, never implicit. A delegated output is accepted
only if all of the following are true:
- only allowed zones were modified
- the frozen contract is respected
- there are no unauthorized cross-layer edits
- the output is integration-ready
- relevant validation or build checks were attempted where applicable
- unresolved issues are surfaced explicitly
Failure handling:
- allow at most one bounded repair pass for a rejected generator output
- reject explicitly if the output is still not usable after that pass
- use manual fallback only after explicit rejection, never as a silent completion of half-finished delegated work
### Role guidance
- `explorer`
- use first for codebase discovery, file/symbol tracing, scaffold inspection, and local evidence gathering
- `docs_researcher`
- use for official documentation verification, framework semantics, and version-sensitive claims
- `generator_prisma`
- launch after contract freeze when schema/model artifacts need generation or repair
- `generator_nest_resources`
- launch after contract freeze when backend resource modules need generation or repair
- `generator_react_admin_resources`
- launch after contract freeze when frontend resource views and registrations need generation or repair
- `generator_data_access`
- launch after contract freeze when React Admin to backend integration seams need generation or repair
- `reviewer`
- use only after parent integration and validation, as the final correctness/security/test-gap review gate
### Documentation-first rule for parent planning
Before the parent designs or repairs framework-sensitive shared seams, it must
review current official documentation rather than relying on memory alone.
Use Context7 first for:
- React Admin authProvider and dataProvider expectations
- NestJS modules, controllers, providers, guards, and auth attachment patterns
- Prisma schema and relation behavior
- Vite, Docker, and nginx behavior relevant to scaffold/runtime work
- Keycloak, OIDC, JWT, and JWKS integration guidance when available
Use external web research only for current, unstable, or missing documentation
details. Parent auth, data-access, and runtime planning must not be done purely
from memory when framework-specific guidance matters.
---
## Generation workflow (required sequence)
0. For a repo-wide full regeneration driven by `prompts/general-prompt.md`, start from the Tier 1/Tier 2 contract without pre-existing Tier 3 app/runtime outputs. In that mode, `server/`, `client/`, `db-seed/`, and root runtime artifacts such as `docker-compose.yml` and `toir-realm.json` are recreated; they are not prerequisites.
1. Read `AGENTS.md` and `prompts/general-prompt.md`.
2. Run discovery first with `explorer` and verify framework-sensitive behavior with `docs_researcher` before designing shared seams.
3. Read the active `api API.<EntityName>` block + its DTOs + its enums from `domain/toir.api.dsl` (entity-scoped — do not inject the full DSL as a blob).
4. Load the companion rule files required for the active stage:
- `prompts/prisma-rules.md`
- `prompts/backend-rules.md`
- `prompts/frontend-rules.md`
- `prompts/auth-rules.md`
- `prompts/runtime-rules.md`
- `prompts/validation-rules.md`
5. Freeze a normalized structured contract and bounded write-zones before launching any specialized generator.
6. Verify or repair framework scaffolds before domain generation:
- official Nest CLI for backend workspace creation/repair
- official Vite React TypeScript CLI for frontend workspace creation/repair
- official Prisma CLI when Prisma initialization or repair is required
7. Parent generates shared auth platform skeleton and deploy/runtime skeleton per `prompts/auth-rules.md` and `prompts/runtime-rules.md`.
8. Launch specialized generators after contract freeze, in parallel when safe:
- `generator_prisma` for `server/prisma/schema.prisma`
- `generator_nest_resources` for backend resource modules
- `generator_react_admin_resources` for frontend resource modules
- `generator_data_access` for `client/src/dataProvider.ts`
9. Accept or reject each delegated output using the acceptance protocol above. Only after acceptance may the parent integrate results.
10. Refresh `api-summary.json` only when validation/tooling requires the auxiliary freshness artifact: `npm run generate:api-summary`.
11. Run: `node tools/validate-generation.mjs --artifacts-only`
12. Run: `npm run eval:generation`
13. Fix all failures before considering the task complete.
14. Hand the final integrated result to `reviewer` before claiming completion.
**Context budget rule:** Before generating any DTO or component, quote the field
definitions from the DSL api block verbatim, then generate from those quotes. This
prevents training-data contamination. See `prompts/general-prompt.md`.
---
## Type mappings
| DSL type | Prisma type | TS DTO type | React Admin component |
| --------- | ----------------------------- | ----------- | ----------------------------- |
| `uuid` | `String @id @default(uuid())` | `string` | `TextInput` / `TextField` |
| `string` | `String` | `string` | `TextInput` / `TextField` |
| `text` | `String` | `string` | `TextInput` / `TextField` |
| `integer` | `Int` | `number` | `NumberInput` / `NumberField` |
| `number` | `Float` | `number` | `NumberInput` / `NumberField` |
| `decimal` | `Decimal` | `string` | `NumberInput` / `NumberField` |
| `date` | `DateTime` | `string` | `DateInput` / `DateField` |
| `boolean` | `Boolean` | `boolean` | (appropriate boolean input) |
| enum name | enum name | `string` | `SelectInput` / `SelectField` |
---
## Naming conventions
Resource name (plural, kebab-case):
- `Equipment``equipment` (irregular — stays as-is)
- `EquipmentType``equipment-types`
- `RepairOrder``repair-orders`
- General: PascalCase → kebab-case → append `s` (or `es` if ends in `s`; irregular cases explicit)
Default sort field (when not declared in api.dsl):
Priority: `inventoryNumber` > `number` > `code` > `name` > primary key
---
## Verification gate (two-stage)
### Stage 1 — Structural gate
```
node tools/validate-generation.mjs --artifacts-only
```
Checks: scaffold/build readiness, required runtime/deploy artifact presence, api-summary freshness, auth seam contracts, realm structure, env/runtime contract, Docker/nginx/compose invariants, and whether build verification ran or was explicitly skipped.
This gate validates the post-generation repository state. It is not a prerequisite for the clean-slate start of a full regeneration run.
Full structural verification (requires installed `node_modules`):
```
node tools/validate-generation.mjs
```
### Stage 2 — Eval harness (Rule 6)
```
npm run eval:generation
```
Fixture-based semantic checks from `tools/eval/fixtures/`. Checks: DSL fidelity, CRUD method/path behavior, DTO field coverage and decorators, natural-key semantics, FK/reference wiring, Content-Range behavior, and React Admin UX/component invariants.
Reviewed eval fixtures are the authoritative semantic gate. They may be scaffolded from source-of-truth as a helper, but a full regeneration run must not auto-rewrite the committed eval corpus as part of step 0.
See `tools/eval/README.md` for fixture authoring and eval-driven development workflow.
**Generation is incomplete unless both stages pass.**
---
## Proven-Good Runtime References
Existing runnable runtime/deploy artifacts are baseline behavior, not disposable examples.
- Preserve repository-proven behavior in `docker-compose.yml`, `server/Dockerfile`, `client/Dockerfile`, `client/nginx/default.conf`, `server/.env.example`, and `client/.env.example` unless the DSL, prompt contract, or an explicit task requires a change.
- When these artifacts are regenerated, preserve still-valid production behavior such as SPA routing, `/api` proxying, external Keycloak, PostgreSQL topology, and container startup flow.
- Do not claim runtime/deploy readiness from file presence alone; these artifacts remain part of completion and verification.
## Prisma Migration Policy
Current repository policy:
- `server/prisma/schema.prisma` is generated from the DSL and is the immediate database contract for generation runs.
- Committed Prisma migrations are preferred but not currently required for every schema change.
- The current repository state is accepted temporary technical debt: when `server/prisma/migrations/` is absent, local/runtime flows may fall back to `prisma db push`; when migrations exist, runtime must use `prisma migrate deploy`.
Target policy:
- Every DSL-driven schema change should produce a reviewed committed migration under `server/prisma/migrations/`.
- Production/runtime execution should rely on `prisma migrate deploy` only, with the `db push` fallback removed after migration discipline is established.
## Pre-commit hook
Install with `npm run install-hooks`. The hook runs **both** the structural gate and
the eval harness before every commit. Commits are blocked when either fails.
---
## Auth and runtime defaults
Full auth contract: `prompts/auth-rules.md`
Working defaults (do not regress to localhost):
- Keycloak base: `https://sso.greact.ru`
- Realm/client: `toir` / `toir-frontend` / `toir-backend`
- Production frontend: `https://toir-frontend.greact.ru`
- CORS: `http://localhost:5173,https://toir-frontend.greact.ru`
---
## OpenRouter configuration
```
OPENAI_API_KEY=<openrouter-key>
OPENAI_BASE_URL=https://openrouter.ai/api/v1
OPENAI_MODEL=<model-id>
```
These variables are used by `tools/api-format-to-openapi/convert.mjs --mode llm`.
---
## Reading order for generation tasks
**Critical zone (load first, never drop):**
1. `AGENTS.md` (this file) — project governance, mutation boundaries, tier hierarchy
2. `prompts/general-prompt.md` — master orchestration prompt: mission, stage ownership, delegation model, completion criteria
3. `domain/toir.api.dsl §API.<EntityName>` — active api block only, plus its referenced DTOs and enums
**Companion zone (load when the matching stage is active):**
4. `prompts/prisma-rules.md` — Prisma schema generation details
5. `prompts/backend-rules.md` — NestJS generation details
6. `prompts/frontend-rules.md` — React Admin generation details
7. `prompts/auth-rules.md` — auth seam and realm requirements
8. `prompts/runtime-rules.md` — scaffold, env, and bootstrap requirements
9. `prompts/validation-rules.md` — success gate requirements
**Auxiliary zone (never authoritative):**
10. `api-summary.json` — optional inventory/freshness artifact for validators and supporting tooling; do not use it instead of the DSL
**Reference only (do not load proactively):**
- `domain/dsl-spec.md` — DSL syntax reference; load only if DSL is ambiguous
- `docs/generation-playbook.md` — step-by-step workflow reference
- `docs/future-work.md` — deferred items (Rules 7 and 8)

View File

@@ -0,0 +1,78 @@
This repository keeps the current LLM-first CRUD generation architecture as the primary working baseline.
It is not a new generator engine and it is not a compiler platform. The repository remains:
- an AI generation context
- an active generated and maintained fullstack CRUD project
- `server/` as the active backend target output path
- `client/` as the active frontend target output path
- an LLM-first orchestration baseline with CLI-first framework bootstrap
- a compact rule set that strengthens the existing pipeline with:
- `api-summary.json` (deterministic intermediate context)
- a physical root-level realm artifact
- a lightweight automated validation gate
## Active knowledge blocks
The master generation prompt is `prompts/general-prompt.md`. It contains the complete
generation workflow, type mappings, naming conventions, and all core rules.
Companion rule files for artifact-specific details:
1. [prompts/general-prompt.md](prompts/general-prompt.md) — master generation prompt
2. [prompts/auth-rules.md](prompts/auth-rules.md) — auth seam / realm spec
3. [prompts/backend-rules.md](prompts/backend-rules.md) — backend reference
4. [prompts/frontend-rules.md](prompts/frontend-rules.md) — frontend reference
5. [prompts/prisma-rules.md](prompts/prisma-rules.md) — Prisma schema rules
6. [prompts/runtime-rules.md](prompts/runtime-rules.md) — runtime / bootstrap
7. [prompts/validation-rules.md](prompts/validation-rules.md) — validation gate
## Baseline contracts
- `domain/*.api.dsl` is the single source of truth for the domain model and API contract.
- [api-summary.json](api-summary.json) is a derived artifact for LLM stabilization and validation.
- [toir-realm.json](toir-realm.json) is the physical Keycloak bootstrap artifact baseline.
- `server/` and `client/` are the active target output paths for this repository.
- `server/` must remain a valid NestJS workspace baseline.
- `client/` must remain a valid Vite React TypeScript workspace baseline.
## Scaffold baseline
- Generation remains LLM-first for orchestration and domain-derived feature code.
- Framework bootstrap is CLI-first:
- backend baseline starts from official Nest CLI conventions
- frontend baseline starts from official Vite React TypeScript conventions
- If `server/` or `client/` drift away from a valid workspace, repair the workspace baseline before generating more feature code.
- Do not replace the framework workspace with a hand-written minimal skeleton.
## Anti-regression contract
- The active prompts define forbidden generation patterns, required invariants, and recovery rules for future agents.
- Buildability is part of the baseline contract, not an optional follow-up.
- Validation targets `domain/*.api.dsl` as reusable source inputs, while TOiR names remain project defaults/examples.
## Repository layout
- [docs/repository-structure.md](docs/repository-structure.md) explains the normalized folder structure.
- Active prompts live in `prompts/`.
- Helper scripts live in `tools/`.
## Commands
```bash
npm run generate:api-summary
npm run validate:generation
npm run validate:generation:runtime
npm run eval:generation
```
`npm run validate:generation` checks both contract shape and workspace validity. When dependencies are installed, it also verifies `npm run build` in `server/` and `client/`. If dependencies are missing, it reports build verification as skipped instead of pretending the baseline is fully green.
## AID export (OpenAPI)
HTTP-экспортёр для интеграции с AID: **`POST /aid/export/openapi`** (api-format → OpenAPI 3.0). Подробно: **[docs/AID_EXPORT_README.md](docs/AID_EXPORT_README.md)**.
> **Note:** The `POST /aid/export/app` endpoint (DSL → generated app bundle) is currently
> non-operative because its backing script (`generation/generate.mjs`) was removed during
> the architecture migration to api.dsl-first generation. See `docs/AID_EXPORT_README.md`
> for details.

View File

@@ -0,0 +1,780 @@
{
"sourceFiles": [
"domain/toir.api.dsl"
],
"enums": [],
"dtos": [
{
"name": "DTO.Equipment",
"description": "Полный response-объект для единицы оборудования",
"fields": [
{
"name": "id",
"type": "uuid",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": null,
"map": "Equipment.id",
"sync": false,
"label": null
},
{
"name": "name",
"type": "string",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": "Название оборудования",
"map": "Equipment.name",
"sync": false,
"label": null
},
{
"name": "serialNumber",
"type": "string",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": "Заводской (серийный) номер",
"map": "Equipment.serialNumber",
"sync": false,
"label": null
},
{
"name": "dateOfInspection",
"type": "date",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Дата поверки",
"map": "Equipment.dateOfInspection",
"sync": false,
"label": null
},
{
"name": "commissionedAt",
"type": "date",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Дата изготовления",
"map": "Equipment.commissionedAt",
"sync": false,
"label": null
},
{
"name": "status",
"type": "EquipmentStatus",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": "Текущий статус",
"map": "Equipment.status",
"sync": false,
"label": null
}
]
},
{
"name": "DTO.EquipmentCreate",
"description": "Тело запроса на создание единицы оборудования",
"fields": [
{
"name": "name",
"type": "string",
"required": true,
"nullable": false,
"unique": false,
"primary": false,
"description": "Название оборудования",
"map": "Equipment.name",
"sync": false,
"label": null
},
{
"name": "serialNumber",
"type": "string",
"required": true,
"nullable": false,
"unique": false,
"primary": false,
"description": "Заводской (серийный) номер",
"map": "Equipment.serialNumber",
"sync": false,
"label": null
},
{
"name": "dateOfInspection",
"type": "date",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Дата поверки",
"map": "Equipment.dateOfInspection",
"sync": false,
"label": null
},
{
"name": "commissionedAt",
"type": "date",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Дата изготовления",
"map": "Equipment.commissionedAt",
"sync": false,
"label": null
},
{
"name": "status",
"type": "EquipmentStatus",
"required": true,
"nullable": false,
"unique": false,
"primary": false,
"description": "Текущий статус",
"map": "Equipment.status",
"sync": false,
"label": null
}
]
},
{
"name": "DTO.EquipmentUpdate",
"description": "Тело запроса на обновление единицы оборудования",
"fields": [
{
"name": "name",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Название оборудования",
"map": "Equipment.name",
"sync": false,
"label": null
},
{
"name": "serialNumber",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Заводской (серийный) номер",
"map": "Equipment.serialNumber",
"sync": false,
"label": null
},
{
"name": "dateOfInspection",
"type": "date",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Дата поверки",
"map": "Equipment.dateOfInspection",
"sync": false,
"label": null
},
{
"name": "commissionedAt",
"type": "date",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Дата изготовления",
"map": "Equipment.commissionedAt",
"sync": false,
"label": null
},
{
"name": "status",
"type": "EquipmentStatus",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Текущий статус",
"map": "Equipment.status",
"sync": false,
"label": null
}
]
},
{
"name": "DTO.EquipmentListRequest",
"description": "Запрос для постраничного получения списка оборудования с фильтрацией",
"fields": [
{
"name": "page",
"type": "DTO.PageRequest",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
},
{
"name": "filterName",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
},
{
"name": "filterSerialNumber",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
},
{
"name": "filterStatus",
"type": "EquipmentStatus",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
}
]
},
{
"name": "DTO.EquipmentListResponse",
"description": "Ответ с постраничным списком оборудования и метаданными",
"fields": [
{
"name": "content",
"type": "DTO.Equipment[]",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
},
{
"name": "pageInfo",
"type": "DTO.PageInfo",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
}
]
},
{
"name": "DTO.ChangeEquipmentStatus",
"description": "Полный response-объект для документа изменения статуса",
"fields": [
{
"name": "equipmentId",
"type": "Equipment",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": null,
"map": "ChangeEquipmentStatus.equipmentId",
"sync": false,
"label": null
},
{
"name": "newStatus",
"type": "EquipmentStatus",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": "Новый статус",
"map": "ChangeEquipmentStatus.newStatus",
"sync": false,
"label": null
},
{
"name": "number",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Номер",
"map": "ChangeEquipmentStatus.number",
"sync": false,
"label": null
},
{
"name": "date",
"type": "date",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": "Дата изменения статуса",
"map": "ChangeEquipmentStatus.date",
"sync": false,
"label": null
},
{
"name": "responsible",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Ответственный",
"map": "ChangeEquipmentStatus.responsible",
"sync": false,
"label": null
}
]
},
{
"name": "DTO.ChangeEquipmentStatusCreate",
"description": "Тело запроса на создание документа изменения статуса",
"fields": [
{
"name": "equipmentId",
"type": "Equipment",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": null,
"map": "ChangeEquipmentStatus.equipmentId",
"sync": false,
"label": null
},
{
"name": "newStatus",
"type": "EquipmentStatus",
"required": true,
"nullable": false,
"unique": false,
"primary": false,
"description": "Новый статус",
"map": "ChangeEquipmentStatus.newStatus",
"sync": false,
"label": null
},
{
"name": "number",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Номер",
"map": "ChangeEquipmentStatus.number",
"sync": false,
"label": null
},
{
"name": "date",
"type": "date",
"required": true,
"nullable": false,
"unique": false,
"primary": false,
"description": "Дата изменения статуса",
"map": "ChangeEquipmentStatus.date",
"sync": false,
"label": null
},
{
"name": "responsible",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Ответственный",
"map": "ChangeEquipmentStatus.responsible",
"sync": false,
"label": null
}
]
},
{
"name": "DTO.ChangeEquipmentStatusUpdate",
"description": "Тело запроса на обновление документа изменения статуса",
"fields": [
{
"name": "equipmentId",
"type": "Equipment",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": null,
"map": "ChangeEquipmentStatus.equipmentId",
"sync": false,
"label": null
},
{
"name": "newStatus",
"type": "EquipmentStatus",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Новый статус",
"map": "ChangeEquipmentStatus.newStatus",
"sync": false,
"label": null
},
{
"name": "number",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Номер",
"map": "ChangeEquipmentStatus.number",
"sync": false,
"label": null
},
{
"name": "date",
"type": "date",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Дата изменения статуса",
"map": "ChangeEquipmentStatus.date",
"sync": false,
"label": null
},
{
"name": "responsible",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": "Ответственный",
"map": "ChangeEquipmentStatus.responsible",
"sync": false,
"label": null
}
]
},
{
"name": "DTO.ChangeEquipmentStatusListRequest",
"description": "Запрос для постраничного получения списка документов изменения статуса с фильтрацией",
"fields": [
{
"name": "page",
"type": "DTO.PageRequest",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
},
{
"name": "filterEquipmentId",
"type": "uuid",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
},
{
"name": "filterNumber",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
},
{
"name": "filterDate",
"type": "date",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
},
{
"name": "filterResponsible",
"type": "string",
"required": false,
"nullable": true,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
}
]
},
{
"name": "DTO.ChangeEquipmentStatusListResponse",
"description": "Ответ с постраничным списком документов изменения статуса и метаданными",
"fields": [
{
"name": "content",
"type": "DTO.ChangeEquipmentStatus[]",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
},
{
"name": "pageInfo",
"type": "DTO.PageInfo",
"required": false,
"nullable": false,
"unique": false,
"primary": false,
"description": null,
"map": null,
"sync": false,
"label": null
}
]
}
],
"apis": [
{
"name": "API.Equipment",
"description": "API управления справочником оборудования",
"endpoints": [
{
"name": "listEquipment",
"label": "POST /equipment/page",
"method": "POST",
"path": "/equipment/page",
"description": "Постраничный список оборудования с фильтрацией",
"attributes": [
{
"name": "request",
"type": "DTO.EquipmentListRequest",
"description": null
},
{
"name": "response",
"type": "DTO.EquipmentListResponse",
"description": null
}
]
},
{
"name": "getEquipment",
"label": "GET /equipment/{id}",
"method": "GET",
"path": "/equipment/{id}",
"description": "Получить единицу оборудования по идентификатору",
"attributes": [
{
"name": "id",
"type": "uuid",
"description": null
},
{
"name": "response",
"type": "DTO.Equipment",
"description": null
}
]
},
{
"name": "createEquipment",
"label": "POST /equipment",
"method": "POST",
"path": "/equipment",
"description": "Создать новую единицу оборудования",
"attributes": [
{
"name": "request",
"type": "DTO.EquipmentCreate",
"description": null
}
]
},
{
"name": "updateEquipment",
"label": "PUT /equipment/{id}",
"method": "PUT",
"path": "/equipment/{id}",
"description": "Обновить данные единицы оборудования",
"attributes": [
{
"name": "id",
"type": "uuid",
"description": null
},
{
"name": "request",
"type": "DTO.EquipmentUpdate",
"description": null
}
]
},
{
"name": "deleteEquipment",
"label": "DELETE /equipment/{id}",
"method": "DELETE",
"path": "/equipment/{id}",
"description": "Удалить единицу оборудования",
"attributes": [
{
"name": "id",
"type": "uuid",
"description": null
}
]
}
]
},
{
"name": "API.EquipmentStatusChange",
"description": "API управления документами изменения статуса оборудования",
"endpoints": [
{
"name": "listStatusChanges",
"label": "POST /status-changes/page",
"method": "POST",
"path": "/status-changes/page",
"description": "Постраничный список документов изменения статуса с фильтрацией",
"attributes": [
{
"name": "request",
"type": "DTO.ChangeEquipmentStatusListRequest",
"description": null
},
{
"name": "response",
"type": "DTO.ChangeEquipmentStatusListResponse",
"description": null
}
]
},
{
"name": "getStatusChange",
"label": "GET /status-changes/{id}",
"method": "GET",
"path": "/status-changes/{id}",
"description": "Получить документ изменения статуса по идентификатору",
"attributes": [
{
"name": "id",
"type": "uuid",
"description": null
},
{
"name": "response",
"type": "DTO.ChangeEquipmentStatus",
"description": null
}
]
},
{
"name": "createStatusChange",
"label": "POST /status-changes",
"method": "POST",
"path": "/status-changes",
"description": "Создать документ изменения статуса оборудования",
"attributes": [
{
"name": "request",
"type": "DTO.ChangeEquipmentStatusCreate",
"description": null
}
]
},
{
"name": "updateStatusChange",
"label": null,
"method": null,
"path": null,
"description": "Обновить документ изменения статуса",
"attributes": [
{
"name": "id",
"type": "uuid",
"description": null
},
{
"name": "request",
"type": "DTO.ChangeEquipmentStatusUpdate",
"description": null
}
]
},
{
"name": "deleteStatusChange",
"label": "DELETE /status-changes/{id}",
"method": "DELETE",
"path": "/status-changes/{id}",
"description": "Удалить документ изменения статуса",
"attributes": [
{
"name": "id",
"type": "uuid",
"description": null
}
]
}
]
}
]
}

View File

@@ -0,0 +1,4 @@
VITE_API_URL=http://localhost:3000
VITE_KEYCLOAK_URL=https://sso.greact.ru
VITE_KEYCLOAK_REALM=toir
VITE_KEYCLOAK_CLIENT_ID=toir-frontend

View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -0,0 +1,14 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:1.27-alpine
COPY nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80

View File

@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>client</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -0,0 +1,20 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://server:3000/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
try_files $uri $uri/ /index.html;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,37 @@
{
"name": "client",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.3.9",
"@mui/material": "^7.3.9",
"keycloak-js": "^26.2.3",
"ra-data-simple-rest": "^5.14.5",
"react": "^19.2.4",
"react-admin": "^5.14.5",
"react-dom": "^19.2.4"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@types/node": "^24.12.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.57.0",
"vite": "^8.0.1"
}
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

View File

@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

View File

@@ -0,0 +1,184 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}

View File

@@ -0,0 +1,30 @@
import { Resource } from 'react-admin';
import EquipmentCreate from './resources/equipment/EquipmentCreate';
import EquipmentEdit from './resources/equipment/EquipmentEdit';
import EquipmentList from './resources/equipment/EquipmentList';
import EquipmentShow from './resources/equipment/EquipmentShow';
import ChangeEquipmentStatusCreate from './resources/change-equipment-status/ChangeEquipmentStatusCreate';
import ChangeEquipmentStatusEdit from './resources/change-equipment-status/ChangeEquipmentStatusEdit';
import ChangeEquipmentStatusList from './resources/change-equipment-status/ChangeEquipmentStatusList';
import ChangeEquipmentStatusShow from './resources/change-equipment-status/ChangeEquipmentStatusShow';
export default function App() {
return (
<>
<Resource
name="equipment"
list={EquipmentList}
create={EquipmentCreate}
edit={EquipmentEdit}
show={EquipmentShow}
/>
<Resource
name="change-equipment-statuses"
list={ChangeEquipmentStatusList}
create={ChangeEquipmentStatusCreate}
edit={ChangeEquipmentStatusEdit}
show={ChangeEquipmentStatusShow}
/>
</>
);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

View File

@@ -0,0 +1,63 @@
import type { AuthProvider } from 'react-admin';
import { initKeycloak, keycloak } from './keycloak';
const getRealmRoles = () => {
const parsed = keycloak.tokenParsed as { realm_access?: { roles?: string[] } } | undefined;
return parsed?.realm_access?.roles ?? [];
};
export const authProvider: AuthProvider = {
async login() {
await initKeycloak();
await keycloak.login();
},
async logout() {
await keycloak.logout({
redirectUri: window.location.origin,
});
},
async checkAuth() {
await initKeycloak();
if (!keycloak.authenticated) {
await keycloak.login();
}
},
async checkError(error) {
const status = error?.status;
if (status === 401) {
await keycloak.login();
return Promise.reject(error);
}
if (status === 403) {
return Promise.reject(error);
}
return Promise.resolve();
},
async getIdentity() {
await initKeycloak();
const parsed = keycloak.tokenParsed as
| {
sub?: string;
preferred_username?: string;
name?: string;
email?: string;
}
| undefined;
return {
id: parsed?.sub ?? 'anonymous',
fullName: parsed?.name ?? parsed?.preferred_username ?? 'User',
avatar: undefined,
email: parsed?.email,
};
},
async getPermissions() {
await initKeycloak();
return getRealmRoles();
},
};

View File

@@ -0,0 +1,47 @@
import Keycloak from 'keycloak-js';
import { env } from '../config/env';
export const keycloak = new Keycloak({
url: env.keycloakUrl,
realm: env.keycloakRealm,
clientId: env.keycloakClientId,
});
let initPromise: Promise<boolean> | null = null;
let refreshPromise: Promise<string | null> | null = null;
export async function initKeycloak() {
if (!initPromise) {
initPromise = keycloak.init({
onLoad: 'login-required',
pkceMethod: 'S256',
checkLoginIframe: false,
});
}
await initPromise;
return keycloak;
}
export async function getAccessToken() {
await initKeycloak();
if (!keycloak.authenticated) {
return null;
}
if (!refreshPromise) {
refreshPromise = keycloak
.updateToken(30)
.then(() => keycloak.token ?? null)
.catch(async () => {
await keycloak.login();
return keycloak.token ?? null;
})
.finally(() => {
refreshPromise = null;
});
}
return refreshPromise;
}

View File

@@ -0,0 +1,8 @@
import { Admin } from 'react-admin';
import { authProvider } from './auth/authProvider';
import { dataProvider } from './dataProvider';
import App from './App';
export function BootstrapApp() {
return <Admin authProvider={authProvider} dataProvider={dataProvider} title="KIS-TOiR"><App /></Admin>;
}

View File

@@ -0,0 +1,6 @@
export const env = {
apiUrl: import.meta.env.VITE_API_URL ?? '/api',
keycloakUrl: import.meta.env.VITE_KEYCLOAK_URL ?? 'https://sso.greact.ru',
keycloakRealm: import.meta.env.VITE_KEYCLOAK_REALM ?? 'toir',
keycloakClientId: import.meta.env.VITE_KEYCLOAK_CLIENT_ID ?? 'toir-frontend',
};

View File

@@ -0,0 +1,223 @@
import type {
CreateParams,
DataProvider,
DeleteParams,
GetListParams,
GetManyParams,
GetManyReferenceParams,
GetOneParams,
RaRecord,
UpdateParams,
} from 'react-admin';
import { fetchUtils } from 'react-admin';
import { env } from './config/env';
import { getAccessToken } from './auth/keycloak';
type ResourceConfig = {
path: string;
compositeKeys?: string[];
};
const resourceConfig: Record<string, ResourceConfig> = {
equipment: { path: 'equipment' },
'equipment-status-changes': {
path: 'change-equipment-status',
compositeKeys: ['equipmentId', 'newStatus'],
},
'change-equipment-statuses': {
path: 'change-equipment-status',
compositeKeys: ['equipmentId', 'newStatus'],
},
};
const getResourceConfig = (resource: string): ResourceConfig => {
return resourceConfig[resource] ?? { path: resource };
};
const normalizeRecord = (resource: string, record: Record<string, unknown>) => {
const config = getResourceConfig(resource);
if (!config.compositeKeys || record.id) {
return record;
}
const parts = config.compositeKeys.map((key) => String(record[key] ?? ''));
return {
...record,
id: parts.join(':'),
};
};
const buildCompositePath = (resource: string, params: { id?: string | number; data?: Partial<RaRecord> }) => {
const config = getResourceConfig(resource);
if (!config.compositeKeys) {
return String(params.id);
}
const source = params.id != null ? {} : (params.data ?? {});
const values = config.compositeKeys.map((key) => {
if (source[key] != null) {
return String(source[key]);
}
const id = String(params.id ?? '');
const parts = id.split(':');
const index = config.compositeKeys?.indexOf(key) ?? -1;
return parts[index] ?? '';
});
return values.map((value) => encodeURIComponent(value)).join('/');
};
const buildQueryString = (params: Record<string, unknown>) => {
const searchParams = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value == null || value === '') {
continue;
}
if (Array.isArray(value)) {
value.forEach((entry) => {
if (entry != null && entry !== '') {
searchParams.append(key, String(entry));
}
});
continue;
}
searchParams.append(key, String(value));
}
const encoded = searchParams.toString();
return encoded ? `?${encoded}` : '';
};
const httpClient = async (url: string, options: RequestInit = {}) => {
const token = await getAccessToken();
const headers = new Headers(options.headers ?? {});
if (!headers.has('Accept')) {
headers.set('Accept', 'application/json');
}
if (!headers.has('Content-Type') && options.body) {
headers.set('Content-Type', 'application/json');
}
if (token) {
// headers.set('Authorization', `Bearer ${token}`);
headers.set('Authorization', `Bearer ${token}`);
}
return fetchUtils.fetchJson(url, {
...options,
headers,
});
};
const parseListResponse = async (resource: string, url: string, options?: RequestInit) => {
const response = await httpClient(url, options);
const totalHeader = response.headers.get('Content-Range') ?? 'items 0-0/0';
const total = Number(totalHeader.split('/').at(-1) ?? 0);
const data = Array.isArray(response.json)
? response.json.map((item) => normalizeRecord(resource, item))
: [];
return {
data,
total,
};
};
const getOne: DataProvider['getOne'] = async (resource: string, params: GetOneParams) => {
const { path } = getResourceConfig(resource);
const id = buildCompositePath(resource, params);
const response = await httpClient(`${env.apiUrl}/${path}/${id}`);
return {
data: normalizeRecord(resource, response.json),
};
};
const getList: DataProvider['getList'] = async (resource: string, params: GetListParams) => {
const { path } = getResourceConfig(resource);
const query = buildQueryString({
_start: params.pagination?.page && params.pagination?.perPage
? (params.pagination.page - 1) * params.pagination.perPage
: 0,
_end: params.pagination?.page && params.pagination?.perPage
? params.pagination.page * params.pagination.perPage
: 25,
_sort: params.sort?.field,
_order: params.sort?.order,
q: typeof params.filter?.q === 'string' ? params.filter.q : undefined,
...params.filter,
});
return parseListResponse(resource, `${env.apiUrl}/${path}${query}`);
};
export const dataProvider: DataProvider = {
async getList(resource: string, params: GetListParams) {
return getList(resource, params);
},
async getOne(resource: string, params: GetOneParams) {
return getOne(resource, params);
},
async getMany(resource: string, params: GetManyParams) {
const results = await Promise.all(params.ids.map((id) => getOne(resource, { id })));
return {
data: results.map((result) => result.data),
};
},
async getManyReference(resource: string, params: GetManyReferenceParams) {
return getList(resource, {
...params,
filter: {
...params.filter,
[params.target]: params.id,
},
});
},
async update(resource: string, params: UpdateParams) {
const { path } = getResourceConfig(resource);
const id = buildCompositePath(resource, params);
const response = await httpClient(`${env.apiUrl}/${path}/${id}`, {
method: 'PATCH',
body: JSON.stringify(params.data),
});
return {
data: normalizeRecord(resource, response.json),
};
},
async updateMany() {
throw new Error('updateMany is not implemented');
},
async create(resource: string, params: CreateParams) {
const { path } = getResourceConfig(resource);
const response = await httpClient(`${env.apiUrl}/${path}`, {
method: 'POST',
body: JSON.stringify(params.data),
});
return {
data: normalizeRecord(resource, response.json),
};
},
async delete(resource: string, params: DeleteParams) {
const { path } = getResourceConfig(resource);
const id = buildCompositePath(resource, params);
const response = await httpClient(`${env.apiUrl}/${path}/${id}`, {
method: 'DELETE',
});
return {
data: normalizeRecord(resource, response.json ?? params.previousData ?? { id: params.id }),
};
},
async deleteMany() {
throw new Error('deleteMany is not implemented');
},
};

View File

@@ -0,0 +1,26 @@
:root {
font-family: Inter, system-ui, sans-serif;
line-height: 1.5;
font-weight: 400;
color: #162033;
background: #f4f7fb;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
* {
box-sizing: border-box;
}
html,
body,
#root {
margin: 0;
min-height: 100%;
}
body {
min-height: 100vh;
}

View File

@@ -0,0 +1,22 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { initKeycloak } from './auth/keycloak';
import './index.css';
import App from './App';
async function bootstrap() {
await initKeycloak();
const container = document.getElementById('root');
if (!container) {
throw new Error('Root container not found');
}
createRoot(container).render(
<StrictMode>
<App />
</StrictMode>,
);
}
void bootstrap();

View File

@@ -0,0 +1,32 @@
import {
AutocompleteInput,
Create,
DateInput,
ReferenceInput,
SelectInput,
SimpleForm,
TextInput as RaTextInput,
} from 'react-admin';
import { equipmentOptionText, equipmentStatusChoices } from '../shared/equipmentStatusChoices';
export default function ChangeEquipmentStatusCreate() {
return (
<Create>
<SimpleForm>
<ReferenceInput source="equipmentId" reference="equipment">
<AutocompleteInput
optionText={equipmentOptionText}
filterToQuery={(searchText) => ({ q: searchText })}
/>
</ReferenceInput>
<SelectInput source="newStatus" choices={equipmentStatusChoices} />
{/* TextInput source="number" */}
<RaTextInput source="number" />
{/* date-fields-separator ..................................................................................................................................................................................................................... */}
<DateInput source="date" />
{/* TextInput source="responsible" */}
<RaTextInput source="responsible" />
</SimpleForm>
</Create>
);
}

View File

@@ -0,0 +1,32 @@
import {
AutocompleteInput,
DateInput,
Edit,
ReferenceInput,
SelectInput,
SimpleForm,
TextInput as RaTextInput,
} from 'react-admin';
import { equipmentOptionText, equipmentStatusChoices } from '../shared/equipmentStatusChoices';
export default function ChangeEquipmentStatusEdit() {
return (
<Edit>
<SimpleForm>
<ReferenceInput source="equipmentId" reference="equipment">
<AutocompleteInput
optionText={equipmentOptionText}
filterToQuery={(searchText) => ({ q: searchText })}
/>
</ReferenceInput>
<SelectInput source="newStatus" choices={equipmentStatusChoices} />
{/* TextInput source="number" */}
<RaTextInput source="number" />
{/* date-fields-separator ..................................................................................................................................................................................................................... */}
<DateInput source="date" />
{/* TextInput source="responsible" */}
<RaTextInput source="responsible" />
</SimpleForm>
</Edit>
);
}

View File

@@ -0,0 +1,43 @@
import {
Datagrid,
DateField,
FilterButton,
List,
ReferenceField,
SelectArrayInput,
SelectField,
TextField,
TextInput,
TopToolbar,
} from 'react-admin';
import { equipmentOptionText, equipmentStatusChoices } from '../shared/equipmentStatusChoices';
const statusChangeFilters = [
<TextInput key="equipmentId" source="equipmentId" label="Equipment" />,
<SelectArrayInput key="newStatus" source="newStatus" label="Status" choices={equipmentStatusChoices} />,
<TextInput key="number" source="number" label="Number" />,
<TextInput key="responsible" source="responsible" label="Responsible" />,
];
const StatusChangeListActions = () => (
<TopToolbar>
<FilterButton />
</TopToolbar>
);
export default function ChangeEquipmentStatusList() {
return (
<List actions={<StatusChangeListActions />} filters={statusChangeFilters}>
<Datagrid rowClick="show">
<TextField source="id" />
<ReferenceField source="equipmentId" reference="equipment" link="show">
<TextField source="name" />
</ReferenceField>
<SelectField source="newStatus" choices={equipmentStatusChoices} />
<TextField source="number" />
<DateField source="date" />
<TextField source="responsible" />
</Datagrid>
</List>
);
}

View File

@@ -0,0 +1,26 @@
import {
DateField,
ReferenceField,
SelectField,
Show,
SimpleShowLayout,
TextField,
} from 'react-admin';
import { equipmentStatusChoices } from '../shared/equipmentStatusChoices';
export default function ChangeEquipmentStatusShow() {
return (
<Show>
<SimpleShowLayout>
<TextField source="id" />
<ReferenceField source="equipmentId" reference="equipment" link="show">
<TextField source="name" />
</ReferenceField>
<SelectField source="newStatus" choices={equipmentStatusChoices} />
<TextField source="number" />
<DateField source="date" />
<TextField source="responsible" />
</SimpleShowLayout>
</Show>
);
}

View File

@@ -0,0 +1 @@
export { default } from '../change-equipment-status/ChangeEquipmentStatusCreate';

View File

@@ -0,0 +1 @@
export { default } from '../change-equipment-status/ChangeEquipmentStatusEdit';

View File

@@ -0,0 +1 @@
export { default } from '../change-equipment-status/ChangeEquipmentStatusList';

View File

@@ -0,0 +1 @@
export { default } from '../change-equipment-status/ChangeEquipmentStatusShow';

View File

@@ -0,0 +1,19 @@
import { Create, DateInput, SelectInput, SimpleForm, TextInput as RaTextInput } from 'react-admin';
import { equipmentStatusChoices } from '../shared/equipmentStatusChoices';
export default function EquipmentCreate() {
return (
<Create>
<SimpleForm>
{/* TextInput source="name" */}
<RaTextInput source="name" />
{/* TextInput source="serialNumber" */}
<RaTextInput source="serialNumber" />
{/* date-fields-separator ..................................................................................................................................................................................................................... */}
<DateInput source="dateOfInspection" />
<DateInput source="commissionedAt" />
<SelectInput source="status" choices={equipmentStatusChoices} />
</SimpleForm>
</Create>
);
}

View File

@@ -0,0 +1,19 @@
import { DateInput, Edit, SelectInput, SimpleForm, TextInput as RaTextInput } from 'react-admin';
import { equipmentStatusChoices } from '../shared/equipmentStatusChoices';
export default function EquipmentEdit() {
return (
<Edit>
<SimpleForm>
{/* TextInput source="name" */}
<RaTextInput source="name" />
{/* TextInput source="serialNumber" */}
<RaTextInput source="serialNumber" />
{/* date-fields-separator ..................................................................................................................................................................................................................... */}
<DateInput source="dateOfInspection" />
<DateInput source="commissionedAt" />
<SelectInput source="status" choices={equipmentStatusChoices} />
</SimpleForm>
</Edit>
);
}

View File

@@ -0,0 +1,41 @@
import {
Datagrid,
DateField,
FilterButton,
List,
NumberField,
SelectArrayInput,
SelectField,
TextField,
TextInput,
TopToolbar,
} from 'react-admin';
import { equipmentStatusChoices } from '../shared/equipmentStatusChoices';
const equipmentFilters = [
<TextInput key="name" source="name" label="Name" alwaysOn />,
<TextInput key="serialNumber" source="serialNumber" label="Serial number" />,
<SelectArrayInput key="status" source="status" label="Status" choices={equipmentStatusChoices} />,
];
const EquipmentListActions = () => (
<TopToolbar>
<FilterButton />
</TopToolbar>
);
export default function EquipmentList() {
return (
<List actions={<EquipmentListActions />} filters={equipmentFilters}>
<Datagrid rowClick="show">
<TextField source="id" />
<TextField source="name" />
<TextField source="serialNumber" />
<DateField source="dateOfInspection" />
<DateField source="commissionedAt" />
<SelectField source="status" choices={equipmentStatusChoices} />
<NumberField source="id" sx={{ display: 'none' }} />
</Datagrid>
</List>
);
}

View File

@@ -0,0 +1,17 @@
import { DateField, SelectField, Show, SimpleShowLayout, TextField } from 'react-admin';
import { equipmentStatusChoices } from '../shared/equipmentStatusChoices';
export default function EquipmentShow() {
return (
<Show>
<SimpleShowLayout>
<TextField source="id" />
<TextField source="name" />
<TextField source="serialNumber" />
<DateField source="dateOfInspection" />
<DateField source="commissionedAt" />
<SelectField source="status" choices={equipmentStatusChoices} />
</SimpleShowLayout>
</Show>
);
}

View File

@@ -0,0 +1,34 @@
export const equipmentStatusChoices = [
{ id: 'Active', name: 'Active' },
{ id: 'Repair', name: 'Repair' },
];
export const equipmentOptionText = (record?: {
inventoryNumber?: string;
code?: string;
number?: string;
name?: string;
id?: string;
}) => {
if (!record) {
return '';
}
if (record.inventoryNumber) {
return `${record.inventoryNumber}${record.name ?? record.inventoryNumber}`;
}
if (record.code) {
return `${record.code}${record.name ?? record.code}`;
}
if (record.number) {
return `${record.number}${record.name ?? record.number}`;
}
if (record.name) {
return record.name ?? String(record.id ?? '');
}
return String(record.id ?? '');
};

View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2023",
"useDefineForClassFields": true,
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})

View File

@@ -0,0 +1,9 @@
FROM postgres:16
WORKDIR /seed
COPY equipment-import.sql /seed/equipment-import.sql
COPY db-seed/import.sh /seed/import.sh
RUN chmod +x /seed/import.sh
CMD ["/seed/import.sh"]

View File

@@ -0,0 +1,16 @@
#!/bin/sh
set -eu
export PGPASSWORD="${POSTGRES_PASSWORD:-postgres}"
until pg_isready -h "${POSTGRES_HOST:-postgres}" -U "${POSTGRES_USER:-postgres}" -d "${POSTGRES_DB:-toir}"; do
sleep 2
done
if [ -f /seed/equipment-import.sql ]; then
psql \
-h "${POSTGRES_HOST:-postgres}" \
-U "${POSTGRES_USER:-postgres}" \
-d "${POSTGRES_DB:-toir}" \
-f /seed/equipment-import.sql
fi

View File

@@ -0,0 +1,46 @@
services:
postgres:
image: postgres:16
environment:
POSTGRES_DB: toir
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- "${POSTGRES_PORT:-5432}:5432"
volumes:
- postgres-data:/var/lib/postgresql/data
server:
build:
context: ./server
env_file:
- ./server/.env.example
environment:
DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/toir"
depends_on:
- postgres
ports:
- "${SERVER_PORT:-3000}:3000"
db-seed:
build:
context: .
dockerfile: db-seed/Dockerfile
environment:
POSTGRES_HOST: postgres
POSTGRES_DB: toir
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
depends_on:
- postgres
client:
build:
context: ./client
depends_on:
- server
ports:
- "${CLIENT_PORT:-8080}:80"
volumes:
postgres-data:

View File

@@ -0,0 +1,120 @@
# AID: экспорт OpenAPI и генератор приложения
В репозитории добавлены **сервисы-экспортёры** для интеграции с **AID** (или любым другим клиентом по HTTP): автоматическое получение **OpenAPI 3.0** из доменного **api-format**.
---
## Что работает
| Компонент | Назначение |
|-----------|------------|
| **`POST /aid/export/openapi`** (NestJS) | На вход JSON **api-format** → на выход документ **OpenAPI 3.0** в поле `openapi`. |
| **`tools/api-format-to-openapi/`** | CLI и промпт для LLM: тот же конвертер, что вызывает Nest. |
| **`server/src/aid-export/`** | Модуль Nest: контроллер, сервис, краткая справка в `README.md` рядом с кодом. |
## Что временно не работает
| Компонент | Статус |
|-----------|--------|
| **`POST /aid/export/app`** (DSL → бандл/apply) | **Non-operative.** The backing script (`generation/generate.mjs`) was removed during the architecture migration to api.dsl-first LLM generation. The endpoint returns 500 with a descriptive error. |
---
## Требования к запуску
1. Репозиторий клонирован целиком (есть `tools/`, `server/`, `client/`).
2. Backend запускается из каталога **`server/`** (`npm run start` / `start:dev`), чтобы относительные пути `../tools/api-format-to-openapi/convert.mjs` были корректны.
3. Для режима OpenAPI через LLM на сервере нужны **`OPENAI_API_KEY`** (и при необходимости `OPENAI_MODEL`, `OPENAI_BASE_URL`).
---
## Переменные окружения (`server/.env`)
| Переменная | Зачем |
|------------|--------|
| `AID_EXPORT_API_KEY` | Если задана, к **`/aid/export/*`** нужен заголовок **`X-AID-Export-Key`** с тем же значением. |
| `OPENAI_API_KEY` | Для `POST /aid/export/openapi` с **`"mode": "llm"`**. |
Остальное как для обычного бэкенда (`DATABASE_URL`, `PORT` и т.д.).
---
## HTTP API (интеграция с AID)
Базовый URL: `http://<host>:<port>` (например `http://localhost:3000`).
### 1. OpenAPI из api-format
**`POST /aid/export/openapi`**
```http
Content-Type: application/json
X-AID-Export-Key: <если задан AID_EXPORT_API_KEY>
```
```json
{
"apiFormat": {
"apiFormatVersion": "1",
"info": { "title": "API", "version": "1.0.0" },
"server": { "basePath": "/api" },
"resources": []
},
"mode": "deterministic"
}
```
- **`mode`**: `deterministic` (по умолчанию) — маппинг в коде для схемы версии `1`; **`llm`** — вызов OpenAI по промпту из `tools/api-format-to-openapi/prompts/llm-system.md`.
**Ответ:** `{ "openapi": { "openapi": "3.0.3", ... } }`
Пример входа для теста: `tools/api-format-to-openapi/examples/api-format.example.json` (подставьте как значение `apiFormat`).
### 2. Генератор приложения из DSL (non-operative)
**`POST /aid/export/app`**
> **Non-operative.** This endpoint depended on `generation/generate.mjs` which was removed
> during the migration to api.dsl-first LLM generation. It currently returns HTTP 500
> with a descriptive error message. Restoring this endpoint requires implementing a new
> backing script compatible with the current `domain/*.api.dsl` pipeline.
---
## CLI (без Nest)
### api-format → OpenAPI
```bash
cd tools/api-format-to-openapi
node convert.mjs --in examples/api-format.example.json --out ../../openapi.generated.json
```
LLM:
```bash
set OPENAI_API_KEY=sk-...
node convert.mjs --mode llm --in your-api-format.json --out ../../openapi.llm.json
```
Подробнее: **`tools/api-format-to-openapi/README.md`**.
---
## Типичный сценарий для AID
1. AID уже сформировал **api-format** (как у вас принято после DTO).
2. AID вызывает **`POST /aid/export/openapi`** → получает **OpenAPI 3.0** → сохраняет в проект / отдаёт в Swagger / в реестр.
---
## Где смотреть код и короткую справку
- Полное описание эндпоинтов рядом с реализацией: **`server/src/aid-export/README.md`**
---
## Ограничения и дальнейшие шаги
- Пример **api-format** в репозитории — **учебный**; под ваш продакшен-формат может понадобиться расширить маппинг в `convert.mjs` или отточить промпт **`llm-system.md`**.
- **`/aid/export/app`** requires a new backing implementation compatible with the `domain/*.api.dsl` pipeline to be restored. See `docs/future-work.md` for planned future work.

View File

@@ -0,0 +1,162 @@
# api.dsl Conventions
Grammar and authoring conventions for `domain/*.api.dsl` files.
See `domain/toir.api.dsl` as the canonical example.
---
## File location and naming
- All api.dsl files live in `domain/`.
- Naming: `<project>.api.dsl` (e.g. `toir.api.dsl`).
- Multiple api.dsl files are allowed but not required.
---
## Two top-level block types
An api.dsl file contains two types of top-level blocks:
1. `dto` — defines the shape of a data transfer object
2. `api` — declares a group of API endpoints for one resource
---
## dto block
```
dto DTO.<Name> {
description "Human-readable description";
attribute <fieldName> {
description "Field description";
type <type>;
is required; // or: is nullable;
map <Entity>.<field>; // links to a field in domain/*.api.dsl
}
}
```
### DTO naming convention
| DTO name | Purpose |
|----------|---------|
| `DTO.<Entity>` | Full response shape (GET by id, list items) |
| `DTO.<Entity>Create` | Create request body |
| `DTO.<Entity>Update` | Update request body (partial — all fields nullable) |
| `DTO.<Entity>ListRequest` | Paginated list request (filters + page) |
| `DTO.<Entity>ListResponse` | Paginated list response (content + page info) |
### Types
Same scalar types as the domain DSL:
`uuid`, `string`, `text`, `integer`, `decimal`, `date`, `boolean`, or an enum name from
`domain/*.api.dsl`.
Cross-DTO references: `DTO.<Name>` or `DTO.<Name>[]`.
Standard pagination types (not entity-specific; treated as well-known):
`DTO.Filter[]`, `DTO.PageRequest`, `DTO.PageInfo`.
### is required vs is nullable
Unlike the domain DSL (where these drive DB constraints), in api.dsl these drive the
TypeScript DTO property modifier:
- `is required``field!: type` in the generated class
- `is nullable``field?: type` in the generated class
- Neither modifier → treated as optional (`field?: type`)
### map directive
`map Entity.field` links the DTO attribute to a domain entity field.
Rules:
- The entity and field must exist in `domain/*.api.dsl`.
- The scalar type must match the domain DSL field type (nullability may differ).
- Omit `map` only for pagination helper types (`DTO.Filter[]`, `DTO.PageRequest`, etc.)
that have no direct entity field counterpart.
### Conflict resolution
If the type declared in a `dto` attribute conflicts with the domain DSL field type,
the domain DSL is correct. Fix the api.dsl.
---
## api block
```
api API.<Name> {
description "API group description";
endpoint <endpointName> {
label "METHOD /path";
description "Endpoint description";
// For endpoints with a request body:
attribute request {
type DTO.<RequestDto>;
}
// For endpoints with a response body:
attribute response {
type DTO.<ResponseDto>;
}
// For path parameters:
attribute <paramName> {
type <type>;
}
}
}
```
### api block naming
`API.<EntityName>` (e.g. `API.Equipment`, `API.RepairOrder`)
### endpoint label
`label "METHOD /path"` is the authoritative declaration of HTTP verb and route.
| Label pattern | NestJS decorator | Notes |
|---------------|-----------------|-------|
| `"GET /resource/{id}"` | `@Get(':id')` | |
| `"POST /resource"` | `@Post()` | Create |
| `"POST /resource/page"` | `@Post('page')` | Paginated list (body-based filter) |
| `"PUT /resource/{id}"` | `@Put(':id')` | Full or partial update |
| `"DELETE /resource/{id}"` | `@Delete(':id')` | |
Do not infer HTTP verbs from endpoint names. Always read the `label`.
### Path parameters
Declared as a plain `attribute` inside the endpoint block (not wrapped in `request`
or `response`):
```
attribute id {
type uuid;
}
```
### Standard 5-endpoint CRUD pattern
| Endpoint name | Label | Body |
|---------------|-------|------|
| `list<Entity>s` | `"POST /<path>/page"` | request: `DTO.<Entity>ListRequest`, response: `DTO.<Entity>ListResponse` |
| `get<Entity>` | `"GET /<path>/{id}"` | path param `id`, response: `DTO.<Entity>` |
| `create<Entity>` | `"POST /<path>"` | request: `DTO.<Entity>Create` |
| `update<Entity>` | `"PUT /<path>/{id}"` | path param `id`, request: `DTO.<Entity>Update` |
| `delete<Entity>` | `"DELETE /<path>/{id}"` | path param `id` |
---
## Constraints
1. Every `map Entity.field` must resolve to an existing entity + field in `domain/*.api.dsl`.
2. Types in api.dsl must be compatible with domain DSL field types (same scalar type).
3. api.dsl must not define entities or enums. Those belong in `domain/*.api.dsl`.
4. An api.dsl may omit domain entity fields from a DTO (e.g. no PK in Create DTO).
It must not add fields that don't exist in the domain model.

View File

@@ -0,0 +1,121 @@
# Completion Contract
This document defines the definition of done for a KIS-TOiR generation run. It provides prioritized success criteria, failure modes, and recovery procedures to ensure consistent, production-ready outcomes.
These criteria apply to the post-generation repository state. In a repo-wide full regeneration driven by `prompts/general-prompt.md`, the run intentionally starts without relying on pre-existing generated workspaces or runtime artifacts.
## Prioritized Success Criteria
### Tier 1: Infrastructure Readiness (Must Pass)
- By the end of the run, `server/` exists and builds successfully (`npm run build`)
- By the end of the run, `client/` exists and builds successfully (`npm run build`)
- `node tools/validate-generation.mjs --artifacts-only` passes (stable infra/runtime/deploy checks)
- Required scaffold files present (NestJS/Vite essentials)
- Runtime/deploy baseline files are present and coherent: `docker-compose.yml`, `server/Dockerfile`, `client/Dockerfile`, `client/nginx/default.conf`, env templates, and the realm artifact
- scaffolded package manifests are normalized to the repository-approved exact version policy instead of floating on `latest` or caret ranges
### Tier 2: Domain Fidelity (Must Pass)
- `npm run eval:generation` passes (DSL fidelity, CRUD behavior, UX invariants)
- DTOs match DSL shapes exactly
- Controllers have correct guards and roles
- React Admin resources use type-correct components
- Natural-key handling correct
- Prisma schema reflects DSL without manual edits
- Reviewed eval contracts lead any new or changed entity behavior before regeneration; automation may scaffold candidate contracts, but it must not silently rewrite the committed eval corpus during every run
- Specialized generator outputs respect frozen-contract write-zones and do not leak unauthorized cross-layer edits
### Tier 3: Runtime/Deploy Readiness (Must Pass)
- Production Dockerfiles exist and are valid
- Reverse-proxy nginx config supports SPA routing and `/api` proxying
- Compose topology matches the repository contract: `postgres`, `server`, `db-seed`, and `client`, with Keycloak external to the compose stack
- Env examples align with auth/runtime contracts
- Realm artifact matches frontend/backend expectations
- Runtime/deploy artifacts are treated as first-class generation targets, not optional extras
### Tier 3A: Prisma Migration Policy (Current Explicit State)
- Current state: accepted temporary technical debt
- Immediate contract: `server/prisma/schema.prisma` must match the DSL
- Current runtime behavior: if committed migrations exist, runtime uses `prisma migrate deploy`; if not, bootstrap flows may fall back to `prisma db push`
- Preferred target: commit reviewed Prisma migrations for each DSL-driven schema change and remove the `db push` fallback from production/runtime paths
### Tier 4: Auth Seam Integrity (Must Pass)
- JWKS resolution works (no silent failures)
- Role extraction from `realm_access.roles`
- `/health` remains public
- 401/403 semantics correct
## Failure Modes and Recovery
### Failure Mode: Scaffold Degradation
**Symptoms**: Build fails, missing Nest/Vite files.
**Recovery**: Run official CLI repair (`nest new` or `vite create`), then regenerate domain code.
### Failure Mode: DSL Mismatch
**Symptoms**: Eval fails on DTO shapes or field mappings.
**Recovery**: Re-read DSL entity block, regenerate affected artifacts, re-run evals.
### Failure Mode: Delegated Output Drift
**Symptoms**: A specialized generator edits unauthorized zones, violates the frozen contract, or hands back output that is not integration-ready.
**Recovery**: Allow one bounded repair pass. If drift remains, reject the output explicitly and only then use parent manual fallback.
### Failure Mode: Guard/Header Issues
**Symptoms**: Eval fails on guards or Content-Range.
**Recovery**: Fix guard order (JwtAuthGuard first), ensure Content-Range format (`items`), re-run evals.
### Failure Mode: Relation Annotation Missing
**Symptoms**: Prisma schema invalid.
**Recovery**: Add explicit `@relation(fields: [...], references: [...])`, regenerate schema.
### Failure Mode: Runtime/Deploy Gaps
**Symptoms**: Docker build fails, nginx proxy broken.
**Recovery**: Update `prompts/runtime-rules.md`, regenerate the affected runtime/deploy artifacts, and verify the deploy baseline again.
### Failure Mode: Auth Seam Drift
**Symptoms**: JWKS fails, roles not extracted.
**Recovery**: Verify JWKS order, ensure `realm_access.roles`, regenerate auth artifacts.
## Recovery Procedures
1. **Partial Regenerate**: If only one entity fails, regenerate that entity only.
2. **Full Reset**: If scaffold broken or a repo-wide regeneration is requested, remove the generated Tier 3 app/runtime outputs (`server/`, `client/`, `db-seed/`, root runtime artifacts), re-scaffold from official CLIs, and regenerate all.
3. **Rollback**: If generation introduces breaking changes, revert to last passing commit.
4. **Debug Mode**: Run `node tools/validate-generation.mjs` with `--run-runtime` for deeper checks.
## Acceptance Protocol
Parent acceptance is explicit for all delegated generation outputs.
A delegated output is accepted only if:
- only allowed zones were modified
- the frozen contract is respected
- no unauthorized cross-layer edits occurred
- the result is integration-ready
- relevant checks were attempted where applicable
- unresolved issues are surfaced explicitly
Escalation rule:
- allow at most one bounded repair pass
- reject explicitly if the output still is not usable
- manual fallback is allowed only after rejection
## Definition of Complete
A generation run is complete when all Tier 1-4 criteria pass, the explicit
Prisma migration policy state is acknowledged, contract freeze and delegated
acceptance rules were respected, the reviewer signs off, the package manifests
follow the approved version policy, and the app is runnable/deployable with the
repository-managed runtime/deploy artifacts and documented external dependencies.

View File

@@ -0,0 +1,180 @@
# Future Work — Deferred Items
This file tracks engineering improvements that are deliberately deferred due to the
current stage of the project. They are not forgotten — they are acknowledged technical
debt that should be addressed before scaling.
---
## Rule 7 — Tracing, Telemetry, Cost/Latency Observability
**Status:** Deferred. No LLM calls are instrumented.
**Why it matters (Anthropic / Google / Microsoft guidance):**
Without observability, you cannot:
- Know which prompts are expensive (token count, latency)
- Detect prompt regressions via cost drift
- Attribute generation failures to specific prompt versions
- Track improvement over time
**What needs to be built:**
### 7.1 — Generation log
Create `tools/generation-log.mjs` that wraps any LLM generation call and writes a
structured JSON entry to `logs/generation.jsonl`:
```json
{
"timestamp": "2026-04-03T10:00:00.000Z",
"entity": "Equipment",
"artifact": "backend",
"prompt_version": "1.0",
"model": "...",
"input_tokens": 4200,
"output_tokens": 1800,
"latency_ms": 3200,
"validation_passed": true,
"eval_passed": true
}
```
### 7.2 — Cost budget alerts
Add a threshold check (e.g., warn if input_tokens > 8000 for a single entity generation).
This enforces the context budget from `prompts/general-prompt.md §CONTEXT BUDGET`.
### 7.3 — Prompt version tracking
Add `<!-- prompt-version: X.Y -->` comments to all prompt files (already started in
`backend-rules.md` and `frontend-rules.md`). Increment version on any non-trivial change.
Log the prompt versions alongside the generation log entry.
### 7.4 — Drift detection
Compare generation log entries across runs. If token count for the same entity increases
by >20% without a DSL change, flag it as context rot.
**Effort estimate:** Medium. 23 days to build the logging layer. Zero effort for
prompt versioning (already partially done).
**Trigger:** Implement before the system is used for more than 10 entities or before
any production deployment.
---
## Rule 8 — Risk Controls and Red-Teaming
**Status:** Deferred. No sanitization or adversarial testing exists.
**Why it matters (Anthropic / Google / Microsoft guidance):**
LLM-generated code at scale introduces risks that do not exist in hand-written code:
- **Prompt injection**: malicious content in DSL `description` fields could steer
generation (e.g., `description "Ignore previous instructions and..."`)
- **Generated credential leakage**: LLM may hallucinate hardcoded secrets that look
real (e.g., `apiKey: 'sk-...'`)
- **Missing auth guards**: already caught by Rule 4 validator, but adversarial prompts
could bypass it by generating valid-looking guard syntax that is semantically inactive
- **Supply chain**: generated package imports could reference non-existent or malicious
packages if the LLM hallucinates
**What needs to be built:**
### 8.1 — DSL input sanitization
In `tools/api-summary.mjs`, before building the summary, check all `description` and
`label` fields for injection patterns:
```javascript
function sanitizeDslString(value, fieldPath) {
const injectionPatterns = [
/ignore previous/i,
/disregard.*instruction/i,
/you are now/i,
/system:/i,
];
for (const pattern of injectionPatterns) {
if (pattern.test(value)) {
throw new Error(`Potential prompt injection in DSL field ${fieldPath}: "${value}"`);
}
}
return value;
}
```
### 8.2 — Generated code security scan
Add to `tools/validate-generation.mjs` (or a separate `tools/security-scan.mjs`):
```javascript
// Check no hardcoded secrets leaked into generated code
function validateNoSecretLeakage() {
const patterns = [
/sk-[a-zA-Z0-9]{20,}/, // OpenAI key pattern
/[a-zA-Z0-9+/]{40}={0,2}/, // Base64 secret-like
/password\s*=\s*['"][^'"]{4,}['"]/, // Hardcoded password
/apiKey\s*=\s*['"][^'"]{4,}['"]/, // Hardcoded API key
];
// Run against all generated files...
}
```
### 8.3 — UseGuards completeness audit
Beyond the current semantic gate coverage, add: verify that the guard
constructor arguments are non-empty and match the expected guard class names. A guard
call like `@UseGuards()` (empty) should fail eval coverage because it provides no protection.
### 8.4 — Red-team fixture
Create `tools/eval/fixtures/_adversarial/` with a fixture that includes a DSL snippet
containing a benign injection attempt (e.g., a `description` field with "ignore format
rules") and verifies the generation still produces spec-compliant output.
### 8.5 — Generated import allowlist
Maintain a list of approved npm packages that generated code may import. Flag any
import not on the allowlist as a manual review item.
**Effort estimate:** Medium-High. 35 days. Security scan and sanitization are low
effort; red-team fixtures and import allowlisting are higher effort.
**Trigger:** Implement before any external user can influence `domain/*.api.dsl` content
(i.e., before a UI or API to edit the DSL is exposed).
---
## Tracking
| Rule | Status | Priority | Trigger |
|------|--------|----------|---------|
| Rule 7 — Telemetry | Deferred | Medium | Before >10 entities or production deployment |
| Rule 8 — Risk controls | Deferred | High | Before DSL editing is exposed to external users |
| Rule 9 — Eval corpus automation | Deferred | Medium | After the contract stabilizes for the current entity set |
---
## Rule 9 — Eval Corpus Automation
**Status:** Deferred. Reviewed eval fixtures are still the authoritative semantic gate.
**Why it matters:**
The repository already requires eval-first behavior for new or changed entity coverage, but the repo does not yet synthesize starter eval contracts from source-of-truth. That means humans still have to review and finalize the first failing semantic contract.
**What needs to be built:**
- a deterministic helper that can scaffold `tools/eval/fixtures/<entity>/` starters from the active source-of-truth slice
- a prompt-to-eval helper that emits backend and frontend assertion starters before regeneration
- a documented workflow where generated starters are reviewed and committed, instead of silently replacing the authoritative eval corpus on every run
**Status of current contract:**
- This is not implemented yet.
- The repo should not imply that evals are auto-generated today.
- The repo should also not imply that a step-0 LLM subagent should rewrite committed eval fixtures on every regeneration run; that would collapse the independence of the semantic gate.
- Until bounded automation exists, the reviewed eval-first rule in `prompts/general-prompt.md` and `docs/generation-playbook.md` remains required.
**Effort estimate:** Medium.
**Trigger:** After the contract stabilizes for the current entity set.
Last updated: 2026-04-03

View File

@@ -0,0 +1,333 @@
# Generation Playbook
Step-by-step instructions for generating and regenerating artifacts in this repository.
Read `AGENTS.md` and `docs/source-of-truth.md` first.
---
## Pipeline overview
```
Tier 1 — Single Source of Truth (hand-authored, never generated)
domain/toir.api.dsl ──┐ enums, DTOs, endpoints, HTTP methods,
│ entity field mappings, primary keys
Tier 2 — Deterministic Preprocessing (npm scripts, no LLM)
api-summary.json ←─ npm run generate:api-summary
openapi.json ←─ npm run generate:openapi (auxiliary)
Tier 1 (api.dsl) + prompts/*.md ──► LLM Generation
prompts/general-prompt.md
parent orchestrator ──► discovery, docs verification, contract freeze, shared scaffold, auth/runtime skeleton, integration
prompts/prisma-rules.md ──► generator_prisma ──► server/prisma/schema.prisma
prompts/backend-rules.md ──► generator_nest_resources ──► server/src/modules/<entity>/
prompts/frontend-rules.md ──► generator_react_admin_resources ──► client/src/resources/<entity>/
prompts/auth-rules.md ──► parent + generator_data_access ──► server/src/auth/, client/src/auth/, client/src/dataProvider.ts, toir-realm.json
prompts/runtime-rules.md ──► parent ──► docker-compose.yml, server/client Dockerfiles, nginx config, env templates, docker-entrypoint, db-seed artifacts
prompts/validation-rules.md ──► (validation gate reference)
Tier 4 — Validation Gate
node tools/validate-generation.mjs --artifacts-only
npm run eval:generation
```
---
## Prerequisites
Before any generation run:
1. `domain/*.api.dsl` is current and valid.
2. Read `AGENTS.md` and `prompts/general-prompt.md`.
3. If this is a repo-wide full regeneration, begin from Tier 1/Tier 2 inputs without relying on existing Tier 3 outputs such as `server/`, `client/`, `db-seed/`, `docker-compose.yml`, or `toir-realm.json`.
4. Refresh the Tier 2 intermediate context only when validator/tooling or a supporting workflow needs it:
```bash
npm run generate:api-summary
```
Do not require `node tools/validate-generation.mjs --artifacts-only` to pass before a clean-slate full regeneration. That command validates the post-generation repository state.
---
## Standard generation workflow
### Step 0 — Full-regeneration reset when requested
For a repo-wide full regeneration driven by `prompts/general-prompt.md`:
- do not assume `server/`, `client/`, `db-seed/`, Dockerfiles, env templates, `docker-compose.yml`, or `toir-realm.json` already exist
- recreate backend and frontend workspaces from the official NestJS and Vite React TypeScript CLIs
- regenerate Tier 3 runtime/deploy artifacts after scaffold recreation
- treat the validator and eval harness as end-state checks after generation
### Step 1 — Refresh auxiliary derived artifacts only when needed
```bash
# From repo root
npm run generate:api-summary
```
### Step 2 — Read generation inputs (context budget)
> **`prompts/general-prompt.md` is the master generation prompt.** It contains all core
> type mappings, naming conventions, DTO/controller/service/frontend rules, mutation
> boundaries, and the complete generation workflow. Load it as the single entrypoint.
>
> For artifact-specific details (Prisma FK rules, auth JWKS chain, detailed validation
> groups), load the relevant companion file: `prompts/prisma-rules.md`,
> `prompts/auth-rules.md`, `prompts/validation-rules.md`, or `prompts/runtime-rules.md`.
>
> See `prompts/general-prompt.md §CONTEXT BUDGET` for the full budget model.
1. `prompts/general-prompt.md` — master generation prompt (always load)
2. `domain/*.api.dsl §API.<EntityName>` — **only the api block + its referenced DTOs + enums** (entity-scoped)
3. `api-summary.json` — only when validator/tooling explicitly needs the auxiliary freshness artifact
4. **If needed:** `prompts/prisma-rules.md` (Prisma), `prompts/auth-rules.md` (auth seams), `prompts/runtime-rules.md` (deploy/runtime artifacts), or `prompts/validation-rules.md` (gate ownership)
Before generating any DTO or component: **quote the relevant DSL field definitions verbatim first**, then generate from those quotes. This prevents training-data contamination.
If a new or changed entity behavior is not already covered by an eval contract, write or review the failing eval first so the semantic gate leads the generation change. Helpers may scaffold candidate fixtures from source-of-truth, but committed evals remain reviewed artifacts rather than auto-regenerated outputs.
### Step 3 — Discovery and docs verification
- Use `explorer` first for repo discovery, scaffold inspection, and tracing shared seams.
- Use `docs_researcher` before planning framework-sensitive auth, runtime, Prisma, NestJS, or React Admin work.
- Prefer Context7 for official framework/library docs; use web fallback only for current or missing details.
### Step 4 — Freeze the contract
Before specialized generation, the parent must freeze a normalized structured handoff that captures:
- entities, fields, types, ids/composite keys, relations, and enums
- endpoint, route, and naming conventions
- auth surface expectations
- validator/eval compatibility constraints
- allowed write-zones for each delegated generator
This freeze is a parent-owned protocol. It does not replace the DSL as source of truth.
### Step 5 — Shared scaffold and parent-owned seams
- repair or recreate official Nest/Vite/Prisma scaffolds as needed
- parent owns auth platform skeleton, deploy/runtime skeleton, env conventions, and shared wiring
- do not start specialized generators before scaffold and frozen-contract inputs are ready
### Step 6 — Generate Prisma schema
Generate `server/prisma/schema.prisma` from `domain/*.api.dsl` following `prompts/prisma-rules.md`.
Preferred migration policy:
- if the DSL changes the schema, create or update Prisma migrations in `server/`
- keep `db push` only as a bootstrap fallback for fresh environments that do not yet have migration history
- treat schema changes shipped without a migration as temporary technical debt that must be called out explicitly
If the schema changed, follow the explicit repository migration policy:
```bash
cd server
npx prisma migrate dev --name <description>
```
If committed migrations do not yet exist, the current repository accepts `prisma db push` only as temporary bootstrap debt. Do not present that fallback as the target steady state.
Use `generator_prisma` for this bounded scope. It must not modify backend modules, frontend resources, auth, or runtime/deploy artifacts.
### Step 7 — Generate backend modules
For each `api` block in `domain/*.api.dsl`, generate:
1. `server/src/modules/<kebab>/<entity>.module.ts`
2. `server/src/modules/<kebab>/dto/create-<kebab>.dto.ts`
— fields from the `DTO.<Entity>Create` block in api.dsl
3. `server/src/modules/<kebab>/dto/update-<kebab>.dto.ts`
— fields from the `DTO.<Entity>Update` block in api.dsl
4. `server/src/modules/<kebab>/<entity>.service.ts`
— CRUD operations using Prisma; respect type mappings from `prompts/backend-rules.md`
5. `server/src/modules/<kebab>/<entity>.controller.ts`
— one method per `endpoint` in the `api` block; HTTP verb and path from the `label`
Register the module in `server/src/app.module.ts`.
Use `generator_nest_resources` for this bounded scope. It must stay within backend resource zones and must not redesign the shared auth or runtime platform.
### Step 8 — Generate frontend resources
For each `api` block in `domain/*.api.dsl`, generate:
1. `client/src/resources/<kebab>/<Entity>List.tsx`
— columns from `DTO.<Entity>` (response shape)
2. `client/src/resources/<kebab>/<Entity>Create.tsx`
— fields from `DTO.<Entity>Create`
3. `client/src/resources/<kebab>/<Entity>Edit.tsx`
— fields from `DTO.<Entity>Update`
4. `client/src/resources/<kebab>/<Entity>Show.tsx`
— fields from `DTO.<Entity>`
Register the resource in `client/src/App.tsx`.
Use `generator_react_admin_resources` for this bounded scope. It must stay within frontend resource zones and must not redesign shared data-access or auth strategy.
### Step 9 — Generate data-access and auth/runtime/deploy artifacts
Use `generator_data_access` for `client/src/dataProvider.ts` and only the narrowly delegated frontend integration seam. Parent retains ownership of the shared auth platform skeleton and all deploy/runtime skeleton artifacts.
Generate or repair:
1. `server/src/auth/`
2. `client/src/auth/`
3. `client/src/dataProvider.ts`
4. `toir-realm.json`
5. `docker-compose.yml`
6. `server/.env.example`, `client/.env.example`
7. `server/Dockerfile`, `client/Dockerfile`
8. `client/nginx/default.conf`
9. `server/docker-entrypoint.sh`
10. `db-seed/Dockerfile`, `db-seed/import.sh`
Preserve the proven-good runtime behaviors from `prompts/runtime-rules.md` unless the repository contract explicitly changes them.
### Step 10 — Accept delegated outputs and integrate
Parent acceptance is explicit. Accept a delegated output only if:
- only allowed zones changed
- the frozen contract is respected
- no unauthorized cross-layer edits occurred
- the result is integration-ready
- relevant checks were attempted where applicable
- unresolved issues are surfaced explicitly
Allow at most one bounded repair pass. If still unusable, reject explicitly.
Manual fallback is allowed only after rejection.
### Step 11 — Verify (two-stage gate)
**Stage 1 — Structural gate:**
```bash
node tools/validate-generation.mjs --artifacts-only
```
Checks scaffold/build readiness, auth/runtime/realm seams, required runtime/deploy artifacts, and other stable repository invariants.
Full structural verification (requires installed deps):
```bash
node tools/validate-generation.mjs
```
**Stage 2 — Eval harness:**
```bash
npm run eval:generation
```
Fixture-based semantic checks. See `tools/eval/README.md`.
Both must pass before the task is complete.
### Step 12 — Final review
Run `reviewer` only after integration and validation. Reviewer is the final
correctness/security/test-gap gate, not a substitute for parent validation.
---
## Adding a new entity
1. Add the entity's enums, DTOs, and `api` block to `domain/toir.api.dsl`.
2. Run `npm run generate:api-summary`.
3. **Before generating:** create `tools/eval/fixtures/<kebab>/meta.json`, `backend.assertions.json`, and `frontend.assertions.json` with expected patterns.
4. Run `npm run eval:generation` — it will fail (entity files don't exist yet). That's expected.
5. Generate backend, frontend, and runtime-facing artifacts (Steps 36).
6. Run `npm run eval:generation` again — now it should pass.
7. Run `node tools/validate-generation.mjs --artifacts-only` — both gates must pass.
> This is **eval-driven development**: write the failing eval first (step 3), then generate to make it pass (step 6). A passing eval confirms the LLM followed the rules.
---
## Changing an existing entity
**If the domain model changes** (new field, changed type, new FK, new enum):
1. Update `domain/toir.api.dsl` (enums, DTO attributes, `map` references).
2. Run `npm run generate:api-summary`.
3. Regenerate `server/prisma/schema.prisma`, run migration.
4. Regenerate the affected modules/resources and any affected runtime artifacts (Steps 47).
**If only the API contract changes** (different nullability, new endpoint, different HTTP method):
1. Update `domain/toir.api.dsl` only.
2. Run `npm run generate:api-summary` to refresh `api-summary.json`.
3. Run Steps 47. No Prisma migration needed.
---
## Artifact traceability matrix
| Artifact | DSL source | Prompt rule | Validator check |
| ---------------------------------------------- | ---------------------- | ---------------------------------------------- | --------------------------------------- |
| `server/prisma/schema.prisma` | `domain/*.api.dsl` | `prompts/prisma-rules.md` | `§validateBuildChecks` (file exists) |
| `api-summary.json` | `domain/*.api.dsl` | — (deterministic) | `§validateBuildChecks` (freshness) |
| `server/src/modules/<e>/*.ts` | `domain/*.api.dsl` | `prompts/backend-rules.md` | `npm run eval:generation` |
| `server/src/modules/<e>/dto/create-<e>.dto.ts` | `DTO.<E>Create` fields | `prompts/backend-rules.md §DTO-field-coverage` | `npm run eval:generation` |
| `server/src/modules/<e>/dto/update-<e>.dto.ts` | `DTO.<E>Update` fields | `prompts/backend-rules.md §DTO-field-coverage` | `npm run eval:generation` |
| `client/src/resources/<e>/<E>*.tsx` | `domain/*.api.dsl` | `prompts/frontend-rules.md` | `npm run eval:generation` |
| `client/src/auth/keycloak.ts` | auth/runtime contract | `prompts/auth-rules.md` | `§validateAuthChecks` |
| `toir-realm.json` | auth/runtime contract | `prompts/auth-rules.md` | `§validateRealmChecks` |
| `docker-compose.yml` | runtime contract | `prompts/runtime-rules.md` | `§validateRuntimeContractChecks` |
| `server/Dockerfile` | runtime contract | `prompts/runtime-rules.md` | `§validateRuntimeContractChecks` |
| `client/Dockerfile` | runtime contract | `prompts/runtime-rules.md` | `§validateRuntimeContractChecks` |
| `client/nginx/default.conf` | runtime contract | `prompts/runtime-rules.md` | `§validateRuntimeContractChecks` |
| `server/docker-entrypoint.sh` | runtime contract | `prompts/runtime-rules.md` | `§validateRuntimeContractChecks` |
| `db-seed/Dockerfile`, `db-seed/import.sh` | runtime contract | `prompts/runtime-rules.md` | `§validateRuntimeContractChecks` |
---
## Verification commands reference
| Command | When to use |
| ----------------------------------------------------- | ------------------------------------------ |
| `npm run generate:api-summary` | After any change to `domain/*.api.dsl` |
| `npm run generate:openapi` | To regenerate OpenAPI 3.0.3 documentation |
| `node tools/validate-generation.mjs --artifacts-only` | After every generation run (required) |
| `node tools/validate-generation.mjs` | Before committing; requires installed deps |
| `node tools/validate-generation.mjs --run-runtime` | End-to-end; requires running DB |
---
## OpenRouter invocation
Set environment variables before any LLM-mode tool call:
```
OPENAI_API_KEY=<openrouter-key>
OPENAI_BASE_URL=https://openrouter.ai/api/v1
OPENAI_MODEL=<model-id>
```
The `OPENAI_BASE_URL` variable is consumed by `tools/api-format-to-openapi/convert.mjs --mode llm`.
For agent-driven generation via Cursor or direct API calls, the standard workflow above
applies regardless of model provider.
---
## Auxiliary tools
### `tools/api-summary-to-openapi.mjs`
Generates `openapi.json` (OpenAPI 3.0.3) from `api-summary.json` deterministically.
This is a documentation/integration artifact, not part of the core generation pipeline.
```bash
npm run generate:openapi
```
### `tools/api-format-to-openapi/`
Auxiliary integration tool for external consumers using the `api-format` JSON schema.
Not connected to the main DSL pipeline. See `docs/AID_EXPORT_README.md` for details.

View File

@@ -0,0 +1,39 @@
# Repository Structure
`KIS-TOiR` keeps the existing LLM-first generation philosophy and organizes the repository by meaning:
- `domain/`
- canonical DSL inputs
- DSL specification
- `prompts/`
- active prompt corpus used to drive generation
- `docs/`
- overview and repository-level architecture notes
- `tools/`
- helper scripts for summary generation and validation
- `server/`
- generated backend target output after generation; may be absent at the clean-slate start of a full regeneration run
- `client/`
- generated frontend target output after generation; may be absent at the clean-slate start of a full regeneration run
- `db-seed/`
- generated runtime/bootstrap output after generation; may be absent before a full regeneration run
The repository keeps LLM-first generation orchestration, but framework bootstrap is CLI-first:
- `server/` must remain a valid NestJS workspace baseline
- `client/` must remain a valid Vite React TypeScript workspace baseline
- repair a broken workspace before applying more domain-derived generation changes
- future agents must treat forbidden generation patterns in `prompts/` as contract violations, not suggestions
Root-level files stay limited to repository-level artifacts such as:
- `README.md`
- `package.json`
- `docker-compose.yml`
- `api-summary.json`
- `toir-realm.json`
- `.gitignore`
Generated root runtime artifacts such as `docker-compose.yml` and `toir-realm.json` are end-state outputs, not clean-slate prerequisites for `prompts/general-prompt.md`.
The repository does not introduce a new generator engine or compiler platform. It keeps the current LLM-first pipeline and makes it cleaner, more explicit, and easier to navigate.

View File

@@ -0,0 +1,144 @@
# Source-of-Truth Hierarchy
This document is the authoritative reference for which files own which decisions.
---
## Tier 1: Authoritative sources (hand-authored; never generated)
### `domain/*.api.dsl`
**Single source of truth for the entire domain and API contract:**
- Entity names and structure
- Attribute names, scalar types, descriptions
- Primary keys (including natural string keys)
- Foreign keys and relations
- Enum definitions and their values
- Database-level constraints: `is required`, `is unique`, `default`
- DTO shapes per operation (Create, Update, Read, ListRequest, ListResponse)
- Which fields appear in each DTO and with what TypeScript modifier (`!` or `?`)
- HTTP method and path for each endpoint (via `label "METHOD /path"`)
- Endpoint names (camelCase identifiers)
- Pagination request/response contract
**Drives:** `server/prisma/schema.prisma`, `server/src/modules/`, `client/src/resources/`,
`server/src/app.module.ts`, `client/src/App.tsx`, and the generated auth/runtime/deploy
artifacts named by the companion prompt contracts.
### `prompts/*.md` and `AGENTS.md`
**Authoritative for:**
- Agent generation workflow and reading order
- Parent-versus-specialist orchestration ownership
- Approved stack versions and dependency pinning policy
- Auth seam patterns (Keycloak, JWT, PKCE S256, JWKS resolution chain)
- Runtime conventions (env examples, docker-compose topology)
- Framework scaffold baseline requirements (NestJS CLI, Vite React TypeScript)
- Filtering and sorting contract
- Naming conventions and implicit rules (pluralization, sort field priority, type mappings)
- Mutation boundaries (what agents must not overwrite)
- Runtime/deploy artifact classification and preservation rules
### `docs/completion-contract.md`
**Operational definition of done for generation runs:**
- prioritized success tiers
- failure modes and recovery procedures
- reviewer signoff requirement
- runtime/deploy readiness requirements
---
## Tier 2: Deterministic derivatives (never edit manually)
| File | Generated from | Command |
| ----------------- | ------------------ | ------------------------------ |
| `api-summary.json` | `domain/*.api.dsl` | `npm run generate:api-summary` |
These files are regenerated from their sources. Manual edits are overwritten on the
next generation run.
---
## Tier 3: LLM-generated artifacts (never edit manually after generation)
These are end-state outputs. A repo-wide full regeneration may begin with some or all Tier 3 artifacts absent and then recreate them from Tier 1 inputs plus official CLI scaffolding.
| Zone | Generated from |
| -------------------------------- | ------------------------------------------------ |
| `server/prisma/schema.prisma` | `domain/*.api.dsl` + `prompts/prisma-rules.md` |
| `server/src/modules/<entity>/` | `domain/*.api.dsl` + `prompts/backend-rules.md` |
| `client/src/resources/<entity>/` | `domain/*.api.dsl` + `prompts/frontend-rules.md` |
| `server/src/app.module.ts` | Module list derived from api.dsl `api` blocks |
| `client/src/App.tsx` | Resource list derived from api.dsl `api` blocks |
| `docker-compose.yml` | `prompts/runtime-rules.md` |
| `server/Dockerfile` | `prompts/runtime-rules.md` |
| `client/Dockerfile` | `prompts/runtime-rules.md` |
| `client/nginx/default.conf` | `prompts/runtime-rules.md` |
| `server/.env.example` | `prompts/runtime-rules.md` |
| `client/.env.example` | `prompts/runtime-rules.md` |
| `server/docker-entrypoint.sh` | `prompts/runtime-rules.md` |
| `db-seed/Dockerfile` | `prompts/runtime-rules.md` |
| `db-seed/import.sh` | `prompts/runtime-rules.md` |
| `server/src/auth/` | `prompts/auth-rules.md` |
| `client/src/auth/` | `prompts/auth-rules.md` |
| `client/src/dataProvider.ts` | `prompts/auth-rules.md` |
| `toir-realm.json` | `prompts/auth-rules.md` |
To change DSL-driven domain artifacts: update `domain/*.api.dsl` and regenerate.
To change auth/runtime/deploy artifacts: update the governing prompt contracts and regenerate or repair them through the orchestrator.
Ownership rule for Tier 3:
- parent owns shared scaffold, auth platform skeleton, deploy/runtime skeleton, env conventions, integration, and validation
- `generator_prisma` owns `server/prisma/schema.prisma`
- `generator_nest_resources` owns `server/src/modules/**` plus delegated backend registration touchpoints
- `generator_react_admin_resources` owns `client/src/resources/**` plus delegated frontend registration touchpoints
- `generator_data_access` owns `client/src/dataProvider.ts` and any parent-delegated narrow frontend integration seam
- specialized generators must not redesign shared auth/runtime/platform seams outside their delegated zones
Contract freeze rule:
- before specialized generation, the parent must freeze a structured handoff covering entities, fields, types, ids/composite keys, relations, enums, endpoint/path conventions, naming rules, auth surface expectations, validator/eval constraints, and allowed write-zones per generator
- this handoff is an orchestration protocol, not a replacement for the DSL
---
## Tier 4: Framework-managed support
- Prisma migrations under `server/prisma/migrations/` when created by the official Prisma CLI
- Framework config: `nest-cli.json`, `tsconfig*.json`, `vite.config.*`, etc.
- All `prompts/*.md`, `AGENTS.md`, `domain/dsl-spec.md`, `domain/*.api.dsl`
Runtime/deploy policy:
- Tier 3 runtime/deploy outputs are first-class generation targets and should be regenerated or repaired from the companion rules when they drift.
- Tier 4 support files are framework-managed rather than hand-authored sources of truth.
---
## Validation gate
### Stage 1 — Structural gate
```
node tools/validate-generation.mjs --artifacts-only
```
Verifies scaffold/build readiness, required runtime/deploy artifacts, auth/runtime seams,
realm structure, and other stable repository invariants.
This gate validates the post-generation state, not the clean-slate starting state for a full regeneration run.
### Stage 2 — Eval harness
```
npm run eval:generation
```
Fixture-based semantic checks from `tools/eval/fixtures/` for DSL fidelity, CRUD behavior,
natural-key handling, and UI invariants.
Both stages must pass before any generation task is considered complete.

View File

@@ -0,0 +1,248 @@
# DSL Language Specification
This document describes the DSL system used to specify fullstack CRUD applications.
`domain/*.api.dsl` is the single source of truth for the entire domain model and API
contract. It drives Prisma schema generation, NestJS module generation, and React Admin
resource generation.
`api-summary.json` is a derived artifact generated from the api.dsl to stabilize
LLM-first generation and feed the lightweight validation gate. It must never replace the
DSL as the source of truth. The active prompt corpus that consumes this contract lives in
`prompts/`.
---
# DSL Architecture
## `domain/*.api.dsl`
The api.dsl is the authoritative source of truth for:
- entities and their attributes
- scalar types and enums
- primary keys and foreign keys
- database-level constraints (required, unique, default)
- relations between entities
- DTO shapes per operation (Create, Update, Read, List)
- nullability and requiredness of each DTO attribute per operation
- HTTP methods and paths for each endpoint
- endpoint names and groupings
- pagination request/response contracts
The api.dsl drives: Prisma schema, NestJS controller/service/DTO generation,
and React Admin resource generation.
Constraint: every `map Entity.field` or `sync Entity.field` reference in `domain/*.api.dsl`
must resolve to an entity and field defined within the same api.dsl file.
## Optional extension mechanism
```text
overrides/
api-overrides.dsl
ui-overrides.dsl
```
Override rules:
- Overrides are optional.
- The generator must work without them.
- Overrides may refine derived API or UI behavior, but they must not duplicate or redefine
entities, attributes, primary keys, foreign keys, relations, or enums.
---
# DSL Grammar Concepts
## entity
An **entity** is a domain object that becomes a database table and a first-class resource in the backend and frontend.
```
entity Equipment {
attribute id { type uuid; key primary; }
attribute name { type string; is required; }
}
```
- **Domain:** Defines the canonical model; one entity = one Prisma model, one NestJS module, one React Admin resource.
- **Naming:** PascalCase (e.g. `Equipment`, `EquipmentType`, `RepairOrder`).
---
## attribute
An **attribute** is a field of an entity. It has a type and optional modifiers.
```
attribute name {
description "Наименование";
type string;
is required;
is unique;
}
```
**Modifiers:**
- `type` — required; one of: `string`, `uuid`, `integer`, `decimal`, `date`, `text`, `boolean`, `number`, or an enum name.
- `key primary` — this attribute is the primary key.
- `key foreign { relates Entity.field }` — foreign key to another entity's field.
- `is required` — non-nullable.
- `is unique` — unique constraint.
- `is nullable` — explicitly nullable.
- `default Value` — default value (for enums or literals).
- `description "..."` — human-readable description.
- `label "..."` — display label for UI.
---
## enum
An **enum** defines a fixed set of values. Used for attributes that can only take one of these values.
```
enum EquipmentStatus {
value Active { label "В эксплуатации"; }
value Repair { label "В ремонте"; }
}
```
- **value** — identifier used in data and code.
- **label** — optional display label for UI.
---
## primary key
Exactly one attribute per entity must be marked as primary key.
```
attribute id {
type uuid;
key primary;
}
```
Or for a natural key:
```
attribute code {
type string;
key primary;
is required;
is unique;
}
```
---
## foreign key
A **foreign key** links to another entity's primary key. The attribute type must match the referenced primary key type.
```
attribute equipmentTypeCode {
type string;
key foreign {
relates EquipmentType.code;
}
is required;
}
```
- `relates Entity.attribute` — references `Entity`'s `attribute` (must be primary key).
- FK type must equal referenced PK type (e.g. `string``EquipmentType.code`, `uuid``Equipment.id`).
---
## required
- **is required** — attribute is non-nullable in the domain model and drives requiredness in derived DTO/API/UI artifacts.
- Absence of `is required` means the attribute is optional (nullable).
---
## default
- **default Value** — applied when no value is provided (e.g. enum defaults like `default Active`).
- Value must exist in the enum when the attribute type is an enum.
---
# DSL → System Component Mapping
## DSL → Prisma
| DSL Concept | Prisma Result |
| ------------ | --------------------------- |
| entity | model |
| attribute | field |
| enum | enum |
| key primary | @id or @id @default(uuid()) |
| key foreign | relation + references |
| type string | String |
| type uuid | String @id @default(uuid()) |
| type integer | Int |
| type number | Float |
| type decimal | Decimal |
| type date | DateTime |
| type text | String |
| type boolean | Boolean |
---
## DSL → NestJS
| DSL Concept | NestJS Result |
| --------------------------- | ------------------------------------- |
| entity | One module (e.g. equipment.module.ts) |
| entity | Controller with CRUD endpoints |
| entity | Service with Prisma CRUD |
| entity + attribute metadata | create-{entity}.dto.ts |
| entity + attribute metadata | update-{entity}.dto.ts |
| entity + attribute metadata | Response DTO / API shape |
API paths are derived from entity name: PascalCase → kebab-case, pluralized (e.g. `Equipment``/equipment`, `RepairOrder``/repair-orders`).
---
## DSL → React Admin
| DSL Concept | React Admin Result |
| -------------------- | ----------------------------------- |
| entity | Resource (name = kebab-case plural) |
| attribute | Form field / column |
| type string | TextInput, TextField |
| type integer/decimal | NumberInput, NumberField |
| type number | NumberInput, NumberField |
| type date | DateInput, DateField |
| type boolean | BooleanInput, BooleanField |
| enum | SelectInput with choices |
| foreign key | ReferenceInput, ReferenceField |
---
# API DSL Layer Mapping
DTO shapes and endpoint contracts are declared in `domain/*.api.dsl`. The api.dsl
is the authoritative source for:
- **Create DTO** — declared as `dto DTO.<Entity>Create` in api.dsl. Must not include
server-generated primary keys (e.g. no `id` for uuid PKs). Required/nullable per field
is explicit in the api.dsl, not inferred.
- **Update DTO** — declared as `dto DTO.<Entity>Update` in api.dsl. All fields are
typically nullable for partial update semantics.
- **API response shape** — declared as `dto DTO.<Entity>` in api.dsl. Must expose
React Admin-compatible `id` field.
- **UI field mapping** — derived from the DTO shapes in api.dsl, not from domain
attributes directly. The Create form uses `DTO.<Entity>Create` fields; the Edit form
uses `DTO.<Entity>Update` fields; List and Show use `DTO.<Entity>` fields.

View File

@@ -0,0 +1,367 @@
dto DTO.Equipment {
description "Полный response-объект для единицы оборудования";
attribute id {
type uuid;
map Equipment.id;
}
attribute name {
type string;
description "Название оборудования";
map Equipment.name;
}
attribute serialNumber {
type string;
description "Заводской (серийный) номер";
map Equipment.serialNumber;
}
attribute dateOfInspection {
type date;
is nullable;
description "Дата поверки";
map Equipment.dateOfInspection;
}
attribute commissionedAt {
type date;
is nullable;
description "Дата изготовления";
map Equipment.commissionedAt;
}
attribute status {
type EquipmentStatus;
description "Текущий статус";
map Equipment.status;
}
}
dto DTO.EquipmentCreate {
description "Тело запроса на создание единицы оборудования";
attribute name {
type string;
description "Название оборудования";
is required;
map Equipment.name;
}
attribute serialNumber {
type string;
description "Заводской (серийный) номер";
is required;
map Equipment.serialNumber;
}
attribute dateOfInspection {
type date;
is nullable;
description "Дата поверки";
map Equipment.dateOfInspection;
}
attribute commissionedAt {
type date;
is nullable;
description "Дата изготовления";
map Equipment.commissionedAt;
}
attribute status {
type EquipmentStatus;
description "Текущий статус";
is required;
map Equipment.status;
}
}
dto DTO.EquipmentUpdate {
description "Тело запроса на обновление единицы оборудования";
attribute name {
type string;
description "Название оборудования";
is nullable;
map Equipment.name;
}
attribute serialNumber {
type string;
description "Заводской (серийный) номер";
is nullable;
map Equipment.serialNumber;
}
attribute dateOfInspection {
type date;
is nullable;
description "Дата поверки";
map Equipment.dateOfInspection;
}
attribute commissionedAt {
type date;
is nullable;
description "Дата изготовления";
map Equipment.commissionedAt;
}
attribute status {
type EquipmentStatus;
description "Текущий статус";
is nullable;
map Equipment.status;
}
}
dto DTO.EquipmentListRequest {
description "Запрос для постраничного получения списка оборудования с фильтрацией";
attribute page {
type DTO.PageRequest;
}
attribute filterName {
type string;
is nullable;
}
attribute filterSerialNumber {
type string;
is nullable;
}
attribute filterStatus {
type EquipmentStatus;
is nullable;
}
}
dto DTO.EquipmentListResponse {
description "Ответ с постраничным списком оборудования и метаданными";
attribute content {
type DTO.Equipment[];
}
attribute pageInfo {
type DTO.PageInfo;
}
}
dto DTO.ChangeEquipmentStatus {
description "Полный response-объект для документа изменения статуса";
attribute equipmentId {
type Equipment;
is nullable;
map ChangeEquipmentStatus.equipmentId;
}
attribute newStatus {
type EquipmentStatus;
description "Новый статус";
map ChangeEquipmentStatus.newStatus;
}
attribute number {
type string;
description "Номер";
is nullable;
map ChangeEquipmentStatus.number;
}
attribute date {
type date;
description "Дата изменения статуса";
map ChangeEquipmentStatus.date;
}
attribute responsible {
type string;
description "Ответственный";
is nullable;
map ChangeEquipmentStatus.responsible;
}
}
dto DTO.ChangeEquipmentStatusCreate {
description "Тело запроса на создание документа изменения статуса";
attribute equipmentId {
type Equipment;
is nullable;
map ChangeEquipmentStatus.equipmentId;
}
attribute newStatus {
type EquipmentStatus;
description "Новый статус";
is required;
map ChangeEquipmentStatus.newStatus;
}
attribute number {
type string;
description "Номер";
is nullable;
map ChangeEquipmentStatus.number;
}
attribute date {
type date;
description "Дата изменения статуса";
is required;
map ChangeEquipmentStatus.date;
}
attribute responsible {
type string;
description "Ответственный";
is nullable;
map ChangeEquipmentStatus.responsible;
}
}
dto DTO.ChangeEquipmentStatusUpdate {
description "Тело запроса на обновление документа изменения статуса";
attribute equipmentId {
type Equipment;
is nullable;
map ChangeEquipmentStatus.equipmentId;
}
attribute newStatus {
type EquipmentStatus;
description "Новый статус";
is nullable;
map ChangeEquipmentStatus.newStatus;
}
attribute number {
type string;
description "Номер";
is nullable;
map ChangeEquipmentStatus.number;
}
attribute date {
type date;
description "Дата изменения статуса";
is nullable;
map ChangeEquipmentStatus.date;
}
attribute responsible {
type string;
description "Ответственный";
is nullable;
map ChangeEquipmentStatus.responsible;
}
}
dto DTO.ChangeEquipmentStatusListRequest {
description "Запрос для постраничного получения списка документов изменения статуса с фильтрацией";
attribute page {
type DTO.PageRequest;
}
attribute filterEquipmentId {
type uuid;
is nullable;
}
attribute filterNumber {
type string;
is nullable;
}
attribute filterDate {
type date;
is nullable;
}
attribute filterResponsible {
type string;
is nullable;
}
}
dto DTO.ChangeEquipmentStatusListResponse {
description "Ответ с постраничным списком документов изменения статуса и метаданными";
attribute content {
type DTO.ChangeEquipmentStatus[];
}
attribute pageInfo {
type DTO.PageInfo;
}
}
api API.Equipment {
description "API управления справочником оборудования";
endpoint listEquipment {
label "POST /equipment/page";
description "Постраничный список оборудования с фильтрацией";
attribute request {
type DTO.EquipmentListRequest;
}
attribute response {
type DTO.EquipmentListResponse;
}
}
endpoint getEquipment {
label "GET /equipment/{id}";
description "Получить единицу оборудования по идентификатору";
attribute id {
type uuid;
}
attribute response {
type DTO.Equipment;
}
}
endpoint createEquipment {
label "POST /equipment";
description "Создать новую единицу оборудования";
attribute request {
type DTO.EquipmentCreate;
}
}
endpoint updateEquipment {
label "PUT /equipment/{id}";
description "Обновить данные единицы оборудования";
attribute id {
type uuid;
}
attribute request {
type DTO.EquipmentUpdate;
}
}
endpoint deleteEquipment {
label "DELETE /equipment/{id}";
description "Удалить единицу оборудования";
attribute id {
type uuid;
}
}
}
api API.EquipmentStatusChange {
description "API управления документами изменения статуса оборудования";
endpoint listStatusChanges {
label "POST /status-changes/page";
description "Постраничный список документов изменения статуса с фильтрацией";
attribute request {
type DTO.ChangeEquipmentStatusListRequest;
}
attribute response {
type DTO.ChangeEquipmentStatusListResponse;
}
}
endpoint getStatusChange {
label "GET /status-changes/{id}";
description "Получить документ изменения статуса по идентификатору";
attribute id {
type uuid;
}
attribute response {
type DTO.ChangeEquipmentStatus;
}
}
endpoint createStatusChange {
label "POST /status-changes";
description "Создать документ изменения статуса оборудования";
attribute request {
type DTO.ChangeEquipmentStatusCreate;
}
}
endpoint updateStatusChange {
labelо "PUT /status-changes/{id}";
description "Обновить документ изменения статуса";
attribute id {
type uuid;
}
attribute request {
type DTO.ChangeEquipmentStatusUpdate;
}
}
endpoint deleteStatusChange {
label "DELETE /status-changes/{id}";
description "Удалить документ изменения статуса";
attribute id {
type uuid;
}
}
}

View File

@@ -0,0 +1,92 @@
-- Generated from /Users/yyy/Downloads/СКПБ бр. № 9.xlsx
-- Mapping: Наименование -> name, Заводской номер -> serialNumber, Дата изготовления -> dateOfInspection, Дата поверки -> commissionedAt
-- Date normalization rules:
-- * Excel serial numbers converted to ISO dates
-- * bare year like 2020 converted to YYYY-01-01
-- * date ranges like 12.12.2025-11.12.2027 use the first date
-- * non-date text left as NULL in date fields; raw values preserved below as comments where relevant
BEGIN;
DELETE FROM "Equipment"
WHERE "id" IN (
'8f1e0982-18de-4bfb-b481-455673884bb2',
'ef0d6b72-6e17-43f9-955f-2e9c63875c51',
'cdda593b-011b-492f-a235-1b7ac37e1e30',
'e741ec42-3c7f-4e42-bec9-896b68024981',
'49c08799-b2e1-4845-8aec-c9afd4cf0bd3',
'd67208e2-93a3-4aff-9b1e-227be28fe38f',
'6c841f0f-4054-4ad3-8b1c-64261702647c',
'5cbade71-0c1f-4a4d-ab4b-a9ee065bbdf5',
'62e75150-70e7-4527-a0a5-edef172a06d9',
'53565d24-91ee-4426-960d-66088aa6c1ae',
'85b9f17c-df54-4099-b453-8b5d15ce64f2',
'6b57fd58-2f60-4982-a3c2-72bc5d634298',
'af787239-6217-43c0-a258-435db9be46db',
'b03850eb-e6cf-4053-85f7-681b6f2516e0',
'8b2b2640-97b0-4d72-82ed-dc6c3d8b78c6',
'cb1e9b26-ad0c-4115-beca-37f882a4c792',
'c9009cf8-24f3-44ba-b881-145c20d2d6db',
'16e24e20-e49c-49af-940d-5c248f386abc',
'402312f7-7a49-4222-a333-8cdea2a51c48',
'ea724126-3f1e-40ee-a92b-aa7110cb1dbd',
'040eb936-1155-4ea1-90e5-a0f8b36d1f4a',
'70e8c028-e470-4480-bbcb-73b000c6aab9',
'6c358390-ece0-41f1-88d9-84edb5a0c40c',
'22f82db2-6fb1-4c54-b429-d889ce6aa45f',
'91bb8600-2252-4bfe-9d65-f566c52c4e14',
'67c6004d-fb46-4b00-aae5-924f22d8357c'
)
OR "serialNumber" IN (
'520110 А 25',
'81',
'5100427 А 25',
'22410032',
'6350237',
'2558277',
'142435',
'22410042',
'3107',
'5836',
'10644',
'5885',
'3673',
'15444',
'3259',
'1400',
'9779',
'9771',
'9754',
'9746',
'9766',
'9769',
'9780',
'9748',
'9764',
'10438'
);
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('8f1e0982-18de-4bfb-b481-455673884bb2', 'Счетчик НОРМА СТВ 50Г', '520110 А 25', '2025-11-10'::timestamp, '2025-11-10'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('ef0d6b72-6e17-43f9-955f-2e9c63875c51', 'ВысотаА - LITE', '81', '2025-07-01'::timestamp, '2025-07-01'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('cdda593b-011b-492f-a235-1b7ac37e1e30', 'Счетчик НОРМА СТВ 50 Х', '5100427 А 25', '2025-09-16'::timestamp, '2025-09-20'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('e741ec42-3c7f-4e42-bec9-896b68024981', 'ДМ 2005CrY2 0-400 kgf/cm', '22410032', NULL, NULL, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('49c08799-b2e1-4845-8aec-c9afd4cf0bd3', 'М-ЗВУКсУХЛ1 0-250 kgf/cm', '6350237', NULL, NULL, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('d67208e2-93a3-4aff-9b1e-227be28fe38f', 'ДМ 8008-Вуф kgf/cm', '2558277', '2018-08-01'::timestamp, NULL, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('6c841f0f-4054-4ad3-8b1c-64261702647c', 'ДМ 2005Cr1EXT3 0-40 Mpa', '142435', NULL, NULL, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('5cbade71-0c1f-4a4d-ab4b-a9ee065bbdf5', 'ДМ 2005CrY2 0-400 kgf/cm', '22410042', NULL, NULL, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('62e75150-70e7-4527-a0a5-edef172a06d9', 'Уровнемер У-150', '3107', '2020-01-01'::timestamp, '2025-12-12'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('53565d24-91ee-4426-960d-66088aa6c1ae', 'Датчик нагрузки ДН-130 25 т.', '5836', '2015-01-01'::timestamp, '2025-11-21'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('85b9f17c-df54-4099-b453-8b5d15ce64f2', 'Датчик нагрузки ДН-130 10 т.с.', '10644', '2022-01-01'::timestamp, '2025-11-21'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('6b57fd58-2f60-4982-a3c2-72bc5d634298', 'Преобразователь давления ТП-140Д', '5885', '2019-01-01'::timestamp, '2025-07-17'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('af787239-6217-43c0-a258-435db9be46db', 'Преобразователь давления ТП-140Д', '3673', '2016-01-01'::timestamp, '2026-02-26'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('b03850eb-e6cf-4053-85f7-681b6f2516e0', 'СКПБ ДЭЛ-150 (ГАЗ) (ПЛА150.104.025.000)', '15444', '2024-11-27'::timestamp, NULL, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('8b2b2640-97b0-4d72-82ed-dc6c3d8b78c6', 'Модуль коммутации МК-140 (ГАЗ)', '3259', '2020-12-24'::timestamp, NULL, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('cb1e9b26-ad0c-4115-beca-37f882a4c792', 'Датчик положения', '1400', NULL, NULL, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('c9009cf8-24f3-44ba-b881-145c20d2d6db', 'Газоанализатор ГСВ-1', '9779', '2024-07-14'::timestamp, '2025-11-14'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('16e24e20-e49c-49af-940d-5c248f386abc', 'Пост ГСВ-1(И) с оповещателем комбинированным ОК-150', '9771', '2024-11-27'::timestamp, '2025-11-11'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('402312f7-7a49-4222-a333-8cdea2a51c48', 'Пост ГСВ-1(И) с оповещателем комбинированным ОК-150', '9754', '2024-11-27'::timestamp, '2025-11-11'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('ea724126-3f1e-40ee-a92b-aa7110cb1dbd', 'Пост ГСВ-1(И) с оповещателем комбинированным ОК-150', '9746', '2024-11-27'::timestamp, '2025-11-11'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('040eb936-1155-4ea1-90e5-a0f8b36d1f4a', 'Пост ГСВ-1(И) с оповещателем комбинированным ОК-150', '9766', '2024-11-27'::timestamp, '2025-11-11'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('70e8c028-e470-4480-bbcb-73b000c6aab9', 'Пост ГСВ-1(И) с оповещателем комбинированным ОК-150', '9769', '2024-11-27'::timestamp, '2025-11-11'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('6c358390-ece0-41f1-88d9-84edb5a0c40c', 'Газоанализатор ГСВ-1', '9780', '2024-07-14'::timestamp, '2025-11-14'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('22f82db2-6fb1-4c54-b429-d889ce6aa45f', 'Пост ГСВ-1(И) с оповещателем комбинированным ОК-150', '9748', '2024-11-27'::timestamp, '2025-11-14'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('91bb8600-2252-4bfe-9d65-f566c52c4e14', 'Пост ГСВ-1(И) с оповещателем комбинированным ОК-150', '9764', '2024-11-27'::timestamp, '2025-11-11'::timestamp, 'Active');
INSERT INTO "Equipment" ("id", "name", "serialNumber", "dateOfInspection", "commissionedAt", "status") VALUES ('67c6004d-fb46-4b00-aae5-924f22d8357c', 'Измерительный комплекс (СКПБ) ДЭЛ-150', '10438', NULL, NULL, 'Active');
COMMIT;

View File

@@ -0,0 +1,931 @@
{
"openapi": "3.0.3",
"info": {
"title": "KIS-TOiR API",
"description": "Equipment maintenance management system. Generated from domain/toir.api.dsl via tools/api-summary-to-openapi.mjs.",
"version": "1.0.0"
},
"servers": [
{
"url": "/api",
"description": "Default server"
}
],
"components": {
"securitySchemes": {
"bearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
},
"schemas": {
"Equipment": {
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"inventoryNumber": {
"type": "string",
"description": "Инвентарный номер"
},
"serialNumber": {
"type": "string",
"description": "Заводской (серийный) номер"
},
"name": {
"type": "string",
"description": "Наименование единицы оборудования"
},
"equipmentTypeCode": {
"type": "string",
"description": "Код вида оборудования"
},
"status": {
"allOf": [
{
"$ref": "#/components/schemas/EquipmentStatus"
}
],
"description": "Текущий статус"
},
"location": {
"type": "string",
"description": "Место эксплуатации / скважина / куст"
},
"commissionedAt": {
"type": "string",
"format": "date-time",
"description": "Дата ввода в эксплуатацию"
},
"totalEngineHours": {
"type": "string",
"format": "decimal",
"description": "Общая наработка, моточасов"
},
"engineHoursSinceLastRepair": {
"type": "string",
"format": "decimal",
"description": "Наработка с последнего ремонта, моточасов"
},
"lastRepairAt": {
"type": "string",
"format": "date-time",
"description": "Дата последнего ремонта"
},
"notes": {
"type": "string",
"description": "Примечания"
}
},
"description": "Оборудование — полный объект ответа"
},
"EquipmentCreate": {
"type": "object",
"properties": {
"inventoryNumber": {
"type": "string",
"description": "Инвентарный номер"
},
"serialNumber": {
"type": "string",
"description": "Заводской (серийный) номер"
},
"name": {
"type": "string",
"description": "Наименование единицы оборудования"
},
"equipmentTypeCode": {
"type": "string",
"description": "Код вида оборудования"
},
"status": {
"allOf": [
{
"$ref": "#/components/schemas/EquipmentStatus"
}
],
"description": "Текущий статус"
},
"location": {
"type": "string",
"description": "Место эксплуатации / скважина / куст"
},
"commissionedAt": {
"type": "string",
"format": "date-time",
"description": "Дата ввода в эксплуатацию"
},
"totalEngineHours": {
"type": "string",
"format": "decimal",
"description": "Общая наработка, моточасов"
},
"engineHoursSinceLastRepair": {
"type": "string",
"format": "decimal",
"description": "Наработка с последнего ремонта, моточасов"
},
"lastRepairAt": {
"type": "string",
"format": "date-time",
"description": "Дата последнего ремонта"
},
"notes": {
"type": "string",
"description": "Примечания"
}
},
"description": "Оборудование — тело запроса на создание",
"required": [
"inventoryNumber",
"name",
"equipmentTypeCode"
]
},
"EquipmentUpdate": {
"type": "object",
"properties": {
"inventoryNumber": {
"type": "string",
"description": "Инвентарный номер"
},
"serialNumber": {
"type": "string",
"description": "Заводской (серийный) номер"
},
"name": {
"type": "string",
"description": "Наименование единицы оборудования"
},
"equipmentTypeCode": {
"type": "string",
"description": "Код вида оборудования"
},
"status": {
"allOf": [
{
"$ref": "#/components/schemas/EquipmentStatus"
}
],
"description": "Текущий статус"
},
"location": {
"type": "string",
"description": "Место эксплуатации / скважина / куст"
},
"commissionedAt": {
"type": "string",
"format": "date-time",
"description": "Дата ввода в эксплуатацию"
},
"totalEngineHours": {
"type": "string",
"format": "decimal",
"description": "Общая наработка, моточасов"
},
"engineHoursSinceLastRepair": {
"type": "string",
"format": "decimal",
"description": "Наработка с последнего ремонта, моточасов"
},
"lastRepairAt": {
"type": "string",
"format": "date-time",
"description": "Дата последнего ремонта"
},
"notes": {
"type": "string",
"description": "Примечания"
}
},
"description": "Оборудование — тело запроса на обновление (частичное)"
},
"EquipmentListRequest": {
"type": "object",
"properties": {
"filters": {
"type": "array",
"items": {
"$ref": "#/components/schemas/DTO.Filter"
}
},
"page": {
"$ref": "#/components/schemas/DTO.PageRequest"
}
},
"description": "Оборудование — запрос постраничного списка с фильтрацией"
},
"EquipmentListResponse": {
"type": "object",
"properties": {
"content": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Equipment"
}
},
"page": {
"$ref": "#/components/schemas/DTO.PageInfo"
}
},
"description": "Оборудование — постраничный результат"
},
"RepairOrder": {
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"number": {
"type": "string",
"description": "Номер заявки"
},
"equipmentId": {
"type": "string",
"format": "uuid",
"description": "Идентификатор оборудования"
},
"repairKind": {
"allOf": [
{
"$ref": "#/components/schemas/RepairKind"
}
],
"description": "Вид ремонта"
},
"status": {
"allOf": [
{
"$ref": "#/components/schemas/RepairOrderStatus"
}
],
"description": "Статус заявки"
},
"plannedAt": {
"type": "string",
"format": "date-time",
"description": "Плановая дата начала"
},
"startedAt": {
"type": "string",
"format": "date-time",
"description": "Фактическая дата начала"
},
"completedAt": {
"type": "string",
"format": "date-time",
"description": "Фактическая дата завершения"
},
"contractor": {
"type": "string",
"description": "Подрядная организация (если внешний ремонт)"
},
"engineHoursAtRepair": {
"type": "string",
"format": "decimal",
"description": "Наработка на момент ремонта, моточасов"
},
"description": {
"type": "string",
"description": "Описание работ / дефекта"
},
"notes": {
"type": "string",
"description": "Примечания"
},
"confirmed": {
"type": "boolean",
"description": "Согласовано/Не согласовано"
}
},
"description": "Заявка на ремонт — полный объект ответа"
},
"RepairOrderCreate": {
"type": "object",
"properties": {
"number": {
"type": "string",
"description": "Номер заявки"
},
"equipmentId": {
"type": "string",
"format": "uuid",
"description": "Идентификатор оборудования"
},
"repairKind": {
"allOf": [
{
"$ref": "#/components/schemas/RepairKind"
}
],
"description": "Вид ремонта"
},
"status": {
"allOf": [
{
"$ref": "#/components/schemas/RepairOrderStatus"
}
],
"description": "Статус заявки"
},
"plannedAt": {
"type": "string",
"format": "date-time",
"description": "Плановая дата начала"
},
"startedAt": {
"type": "string",
"format": "date-time",
"description": "Фактическая дата начала"
},
"completedAt": {
"type": "string",
"format": "date-time",
"description": "Фактическая дата завершения"
},
"contractor": {
"type": "string",
"description": "Подрядная организация (если внешний ремонт)"
},
"engineHoursAtRepair": {
"type": "string",
"format": "decimal",
"description": "Наработка на момент ремонта, моточасов"
},
"description": {
"type": "string",
"description": "Описание работ / дефекта"
},
"notes": {
"type": "string",
"description": "Примечания"
},
"confirmed": {
"type": "boolean",
"description": "Согласовано/Не согласовано"
}
},
"description": "Заявка на ремонт — тело запроса на создание",
"required": [
"number",
"equipmentId",
"repairKind",
"plannedAt"
]
},
"RepairOrderUpdate": {
"type": "object",
"properties": {
"number": {
"type": "string",
"description": "Номер заявки"
},
"equipmentId": {
"type": "string",
"format": "uuid",
"description": "Идентификатор оборудования"
},
"repairKind": {
"allOf": [
{
"$ref": "#/components/schemas/RepairKind"
}
],
"description": "Вид ремонта"
},
"status": {
"allOf": [
{
"$ref": "#/components/schemas/RepairOrderStatus"
}
],
"description": "Статус заявки"
},
"plannedAt": {
"type": "string",
"format": "date-time",
"description": "Плановая дата начала"
},
"startedAt": {
"type": "string",
"format": "date-time",
"description": "Фактическая дата начала"
},
"completedAt": {
"type": "string",
"format": "date-time",
"description": "Фактическая дата завершения"
},
"contractor": {
"type": "string",
"description": "Подрядная организация (если внешний ремонт)"
},
"engineHoursAtRepair": {
"type": "string",
"format": "decimal",
"description": "Наработка на момент ремонта, моточасов"
},
"description": {
"type": "string",
"description": "Описание работ / дефекта"
},
"notes": {
"type": "string",
"description": "Примечания"
},
"confirmed": {
"type": "boolean",
"description": "Согласовано/Не согласовано"
}
},
"description": "Заявка на ремонт — тело запроса на обновление (частичное)"
},
"RepairOrderListRequest": {
"type": "object",
"properties": {
"filters": {
"type": "array",
"items": {
"$ref": "#/components/schemas/DTO.Filter"
}
},
"page": {
"$ref": "#/components/schemas/DTO.PageRequest"
}
},
"description": "Заявка на ремонт — запрос постраничного списка с фильтрацией"
},
"RepairOrderListResponse": {
"type": "object",
"properties": {
"content": {
"type": "array",
"items": {
"$ref": "#/components/schemas/RepairOrder"
}
},
"page": {
"$ref": "#/components/schemas/DTO.PageInfo"
}
},
"description": "Заявка на ремонт — постраничный результат"
},
"EquipmentStatus": {
"type": "string",
"x-dsl-enum": "EquipmentStatus",
"description": "Enum: EquipmentStatus (values defined in domain/*.api.dsl)"
},
"DTO.Filter": {
"type": "string",
"x-dsl-enum": "DTO.Filter",
"description": "Enum: DTO.Filter (values defined in domain/*.api.dsl)"
},
"DTO.PageRequest": {
"type": "string",
"x-dsl-enum": "DTO.PageRequest",
"description": "Enum: DTO.PageRequest (values defined in domain/*.api.dsl)"
},
"DTO.PageInfo": {
"type": "string",
"x-dsl-enum": "DTO.PageInfo",
"description": "Enum: DTO.PageInfo (values defined in domain/*.api.dsl)"
},
"RepairKind": {
"type": "string",
"x-dsl-enum": "RepairKind",
"description": "Enum: RepairKind (values defined in domain/*.api.dsl)"
},
"RepairOrderStatus": {
"type": "string",
"x-dsl-enum": "RepairOrderStatus",
"description": "Enum: RepairOrderStatus (values defined in domain/*.api.dsl)"
}
}
},
"paths": {
"/equipment/page": {
"post": {
"summary": "Постраничный список оборудования с фильтрацией",
"security": [
{
"bearerAuth": []
}
],
"tags": [
"оборудованием"
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/EquipmentListRequest"
}
}
}
},
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/EquipmentListResponse"
}
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
}
}
}
},
"/equipment/{id}": {
"get": {
"summary": "Получить оборудование по идентификатору",
"security": [
{
"bearerAuth": []
}
],
"tags": [
"оборудованием"
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"format": "uuid"
}
}
],
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Equipment"
}
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
}
}
},
"put": {
"summary": "Обновить единицу оборудования",
"security": [
{
"bearerAuth": []
}
],
"tags": [
"оборудованием"
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"format": "uuid"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/EquipmentUpdate"
}
}
}
},
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
}
}
},
"delete": {
"summary": "Удалить единицу оборудования",
"security": [
{
"bearerAuth": []
}
],
"tags": [
"оборудованием"
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"format": "uuid"
}
}
],
"responses": {
"204": {
"description": "No content"
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
},
"404": {
"description": "Not found"
}
}
}
},
"/equipment": {
"post": {
"summary": "Создать единицу оборудования",
"security": [
{
"bearerAuth": []
}
],
"tags": [
"оборудованием"
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/EquipmentCreate"
}
}
}
},
"responses": {
"201": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
}
}
}
},
"/repair-orders/page": {
"post": {
"summary": "Постраничный список заявок на ремонт с фильтрацией",
"security": [
{
"bearerAuth": []
}
],
"tags": [
"заявками на ремонт"
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RepairOrderListRequest"
}
}
}
},
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RepairOrderListResponse"
}
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
}
}
}
},
"/repair-orders/{id}": {
"get": {
"summary": "Получить заявку на ремонт по идентификатору",
"security": [
{
"bearerAuth": []
}
],
"tags": [
"заявками на ремонт"
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"format": "uuid"
}
}
],
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RepairOrder"
}
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
}
}
},
"put": {
"summary": "Обновить заявку на ремонт",
"security": [
{
"bearerAuth": []
}
],
"tags": [
"заявками на ремонт"
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"format": "uuid"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RepairOrderUpdate"
}
}
}
},
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
}
}
},
"delete": {
"summary": "Удалить заявку на ремонт",
"security": [
{
"bearerAuth": []
}
],
"tags": [
"заявками на ремонт"
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"format": "uuid"
}
}
],
"responses": {
"204": {
"description": "No content"
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
},
"404": {
"description": "Not found"
}
}
}
},
"/repair-orders": {
"post": {
"summary": "Создать заявку на ремонт",
"security": [
{
"bearerAuth": []
}
],
"tags": [
"заявками на ремонт"
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RepairOrderCreate"
}
}
}
},
"responses": {
"201": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
}
}
}
}
}
}

View File

@@ -0,0 +1,13 @@
{
"name": "toir-generation-context",
"private": true,
"scripts": {
"generate:api-summary": "node tools/generate-api-summary.mjs",
"generate:openapi": "node tools/api-summary-to-openapi.mjs --out openapi.json",
"validate:generation": "node tools/validate-generation.mjs",
"validate:generation:runtime": "node tools/validate-generation.mjs --run-runtime",
"validate:generation:artifacts": "node tools/validate-generation.mjs --artifacts-only",
"eval:generation": "node tools/eval/run-evals.mjs",
"install-hooks": "node tools/install-hooks.mjs"
}
}

View File

@@ -0,0 +1,115 @@
# Auth Rules
<!-- prompt-version: 2.0 -->
<!-- applies-to: client/src/auth/, server/src/auth/, toir-realm.json -->
<!-- validated-by: tools/validate-generation.mjs §validateAuthChecks §validateRealmChecks -->
Use this document during the **D. Shared Platform Scaffold** and **F. Integration**
stages defined in `prompts/general-prompt.md`.
## Purpose
Generate and preserve the auth contracts that let the CRUD app run as a React Admin SPA backed by a NestJS API protected by external Keycloak.
The realm import is a deploy/runtime artifact and is part of the generated workspace, not a sample.
Ownership rule:
- the parent owns the auth platform skeleton and shared auth seams
- specialized generators may attach resource-aware bindings only inside their delegated zones
- do not redesign the shared auth platform from inside a resource generator
## Mandatory Inputs
- `prompts/general-prompt.md`
- `prompts/runtime-rules.md`
- current repository auth/runtime defaults
## Expected Outputs
- `client/src/auth/`
- `client/src/dataProvider.ts`
- `server/src/auth/`
- `toir-realm.json`
## Approved Auth Dependency Baseline
- `keycloak-js`: `26.2.3`
- `jose`: `6.2.2`
Pinning rules:
- Keep frontend auth on the approved `keycloak-js` version during routine regeneration.
- Keep backend JWT verification on the approved `jose` version during routine regeneration.
- Do not upgrade auth library majors implicitly when repairing scaffolds or auth seams.
## Frontend Auth Invariants
- use `keycloak-js` with redirect-based login only
- initialize Keycloak before rendering the SPA
- use Authorization Code Flow + PKCE (`S256`)
- keep `authProvider`, `dataProvider`, `getIdentity()`, `getPermissions()`, and `checkError()` as stable seams
- derive identity from token claims already present in the token
- do not call `loadUserProfile()`
- `401` forces re-authentication; `403` remains an authorization error
- keep token handling in memory with one shared in-flight refresh path
## Backend Auth Invariants
- verify JWTs with `jose`
- validate issuer, audience, and signature via JWKS
- resolve JWKS in this order:
1. `KEYCLOAK_JWKS_URL`
2. OIDC discovery at `/.well-known/openid-configuration`
3. `${issuer}/protocol/openid-connect/certs`
- if all JWKS resolution attempts fail, reject authentication (no silent fallback)
- extract roles only from `realm_access.roles`
- keep `/health` public
- generated CRUD routes stay protected by default
## Working Runtime Defaults
Keep these defaults unless a task explicitly overrides them:
- `VITE_KEYCLOAK_URL=https://sso.greact.ru`
- `VITE_KEYCLOAK_REALM=toir`
- `VITE_KEYCLOAK_CLIENT_ID=toir-frontend`
- `KEYCLOAK_ISSUER_URL=https://sso.greact.ru/realms/toir`
- `KEYCLOAK_AUDIENCE=toir-backend`
- `CORS_ALLOWED_ORIGINS=http://localhost:5173,https://toir-frontend.greact.ru`
Anti-regression rule:
- do not revert shared examples to localhost Keycloak defaults unless a task explicitly requests a local Keycloak baseline
## Realm Artifact Contract
The root realm artifact is mandatory and must:
- be importable and versioned
- align with generated frontend/backend env contracts
- parameterize:
- realm name
- frontend client id
- backend client id / audience
- local and production frontend URLs
- artifact filename
- explicitly deliver:
- `sub`
- `aud`
- `realm_access.roles`
- define:
- realm roles `admin`, `editor`, `viewer`
- a public SPA client with PKCE S256
- a bearer-only backend client
- an explicit audience client scope
- protocol mappers for baseline identity and role claims
## Completion Expectations
Auth/runtime generation is incomplete if any of the following is true:
- frontend and backend auth seams drift from each other
- JWKS resolution order changes
- `/health` stops being public
- shared Keycloak defaults regress to localhost examples
- the realm artifact no longer matches backend/frontend expectations

View File

@@ -0,0 +1,176 @@
# Backend Rules
Use this document during the **E. Parallel Specialized Generation** stage
defined in `prompts/general-prompt.md`.
## Purpose
Generate NestJS CRUD artifacts that match the DSL contract exactly and remain compatible with a standard NestJS workspace.
Ownership rule:
- this stage belongs to `generator_nest_resources` after contract freeze
- parent retains ownership of shared auth strategy, JWT/JWKS design, global backend infra, runtime, and deploy seams
- backend resource generation may attach already-defined auth platform seams where required by the frozen contract, but must not redesign them
## Mandatory Inputs
- `prompts/general-prompt.md`
- the active `api API.<Entity>` block from `domain/toir.api.dsl`
- referenced DTOs and enums from `domain/toir.api.dsl`
- an intact or repaired official NestJS scaffold under `server/`
`api-summary.json` may be consulted only as an auxiliary inventory or validator-related artifact. It must never replace the DSL as the backend source of truth.
## Expected Outputs
Per entity:
- `server/src/modules/<kebab>/<kebab>.module.ts`
- `server/src/modules/<kebab>/<kebab>.controller.ts`
- `server/src/modules/<kebab>/<kebab>.service.ts`
- `server/src/modules/<kebab>/dto/create-<kebab>.dto.ts`
- `server/src/modules/<kebab>/dto/update-<kebab>.dto.ts`
Repository-wide:
- `server/src/app.module.ts` registrations
## Scaffold Baseline
- Start backend initialization and repair from the official NestJS CLI workspace, not from hand-written files.
- Preserve Nest workspace essentials:
- `server/tsconfig.json`
- `server/tsconfig.build.json`
- `server/nest-cli.json`
- `server/src/main.ts`
- `server/src/app.module.ts`
- If the workspace is degraded, repair it before generating domain code.
Forbidden patterns:
- hand-written pseudo-Nest scaffolds
- deleting required Nest config files after generation
- replacing normal Nest build/start behavior with ad hoc scripts
## Approved Backend Dependency Baseline
When the backend workspace is created or repaired, pin the backend package manifest to these exact versions before continuing:
- `@nestjs/common`: `11.1.18`
- `@nestjs/core`: `11.1.18`
- `@nestjs/platform-express`: `11.1.18`
- `@nestjs/testing`: `11.1.18`
- `@nestjs/config`: `4.0.3`
- `@nestjs/cli`: `11.0.17`
- `@nestjs/schematics`: `11.0.10`
- `class-validator`: `0.15.1`
- `class-transformer`: `0.5.1`
- `jose`: `6.2.2`
- `reflect-metadata`: `0.2.2`
- `rxjs`: `7.8.1`
- backend `typescript`: `5.7.3`
Pinning rules:
- Use exact versions, not `latest` and not caret ranges.
- Keep the Nest runtime packages on the same approved major/minor line.
- Prisma-specific versions are governed by `prompts/prisma-rules.md`.
## Route And Resource Contract
- Use the shared entity-to-resource naming convention from `prompts/general-prompt.md`.
- Each entity becomes a NestJS module, controller, service, and create/update DTO pair.
- CRUD routes use the real primary key name in the path.
- Every API record returned to React Admin must include `id`.
- For natural-key entities, map the real primary key to `id` in responses and sort translation.
## DTO Contract
- `DTO.<Entity>Create` defines `Create<Entity>Dto`.
- `DTO.<Entity>Update` defines `Update<Entity>Dto`.
- Do not invent fields or pull field lists from memory.
- Never include `id` in Create/Update DTOs.
Type and decorator rules:
| DSL type | TS DTO type | class-validator decorator | Notes |
| --------- | ----------- | ------------------------- | ----------------------------- |
| `uuid` | `string` | `@IsUUID()` | |
| `string` | `string` | `@IsString()` | |
| `text` | `string` | `@IsString()` | |
| `integer` | `number` | `@IsInt()` | |
| `number` | `number` | `@IsNumber()` | |
| `decimal` | `string` | `@IsString()` | serialize with Prisma Decimal |
| `date` | `string` | `@IsString()` | serialize as ISO string |
| `boolean` | `boolean` | `@IsBoolean()` | |
| enum name | `string` | `@IsEnum(EnumName)` | |
Nullability rules:
- every field that is not `is required` gets `@IsOptional()` before the type decorator
- every generated DTO imports from `'class-validator'`
## Controller Contract
- Apply `@UseGuards(JwtAuthGuard, RolesGuard)` at controller class level.
- Guard order: JwtAuthGuard must run before RolesGuard to ensure token validation precedes role extraction.
- Roles per verb:
- `GET` -> `viewer | editor | admin`
- `POST`, `PATCH`, `PUT` -> `editor | admin`
- `DELETE` -> `admin`
- Reconcile DSL HTTP shapes for repository compatibility:
- list endpoints declared as `POST .../page` generate as `@Get()` with React Admin query params
- update endpoints declared as `PUT` generate as `@Patch(':<pk>')`
- Path parameters are taken from the DSL endpoint contract, not invented from generic CRUD memory.
## Service Contract
- Never pass raw update DTOs directly into Prisma update `data`.
- Strip `id`, the real primary key, and readonly fields before writes.
- Keep `PrismaService` lightweight:
- extend `PrismaClient`
- implement `OnModuleInit`
- call `$connect()`
- do not add `beforeExit`
List endpoint requirements:
- accept React Admin query params: `_start`, `_end`, `_sort`, `_order`, `q`
- set `Content-Range: items <start>-<end>/<total>` header (RFC 7233 format for items, not bytes)
- set `Access-Control-Expose-Headers: Content-Range`
- return HTTP 200 for successful pagination
Filtering rules:
- string/text filters may use case-insensitive `contains`
- foreign-key scalar filters must use exact-match semantics
- enum filters must support both single and repeated params
- repeated enum params must map to Prisma `{ in: [...] }`
- `_sort=id` must map to the real primary key for natural-key entities
Decimal and date handling:
- `decimal` writes: `new Prisma.Decimal(value)`
- `decimal` reads: `.toString()`
- `date` writes: `new Date(value)`
- `date` reads: `.toISOString()`
## Natural-Key Rules
For entities whose physical primary key is not `id`:
- route params use the real primary key name
- responses expose `id` mapped from that primary key
- sort/update behavior never targets a fake physical `id`
- update payload sanitization removes both `id` and the real primary key
## Completion Expectations
Backend generation is incomplete if any of the following is true:
- required Nest scaffold files are missing
- DTO decorators are incomplete or type-incorrect
- controllers are missing guards or role decorators
- natural-key handling regresses to a fake physical `id`
- list/filter behavior is incompatible with React Admin expectations

View File

@@ -0,0 +1,151 @@
# Frontend Rules
<!-- prompt-version: 2.0 -->
<!-- applies-to: client/src/resources/, client/src/App.tsx -->
<!-- validated-by: tools/validate-generation.mjs §validateApiDslCoverage -->
Use this document during the **E. Parallel Specialized Generation** stage
defined in `prompts/general-prompt.md`.
## Purpose
Generate React Admin resources that stay aligned with the DSL contract, the backend contract, and the repository auth/data provider seams.
Ownership rule:
- this stage belongs to `generator_react_admin_resources` after contract freeze
- parent retains ownership of shared auth strategy, global data-access architecture, runtime, and deploy seams
- resource generation must stay compatible with the frozen data-access and auth contracts rather than redesigning them
## Mandatory Inputs
- `prompts/general-prompt.md`
- the active `api API.<Entity>` block from `domain/toir.api.dsl`
- referenced DTOs and enums from `domain/toir.api.dsl`
- an intact or repaired official Vite React TypeScript scaffold under `client/`
## Expected Outputs
Per entity:
- `client/src/resources/<kebab>/<Entity>List.tsx`
- `client/src/resources/<kebab>/<Entity>Create.tsx`
- `client/src/resources/<kebab>/<Entity>Edit.tsx`
- `client/src/resources/<kebab>/<Entity>Show.tsx`
Repository-wide:
- `client/src/App.tsx` resource registrations
## Scaffold Baseline
- Start frontend initialization and repair from the official Vite React TypeScript scaffold, not from a hand-written shell.
- Preserve workspace essentials:
- `client/index.html`
- `client/tsconfig.json`
- `client/vite.config.*`
- `client/src/main.tsx`
- `client/src/vite-env.d.ts`
- Repair the scaffold before generating resources if it is degraded.
- Do not delete `client/src/vite-env.d.ts`. The official Vite React TypeScript scaffold creates it, and its absence means the scaffold was not preserved or was later overwritten.
## Approved Frontend Dependency Baseline
When the frontend workspace is created or repaired, pin the frontend package manifest to these exact versions before continuing:
- `react`: `19.2.4`
- `react-dom`: `19.2.4`
- `react-admin`: `5.14.5`
- `ra-data-simple-rest`: `5.14.5`
- `@mui/material`: `7.3.9`
- `@mui/icons-material`: `7.3.9`
- `@emotion/react`: `11.14.0`
- `@emotion/styled`: `11.14.1`
- `vite`: `8.0.3`
- `@vitejs/plugin-react`: `6.0.1`
- frontend `typescript`: `5.9.3`
- `keycloak-js`: `26.2.3`
Pinning rules:
- Use exact versions, not `latest` and not caret ranges.
- Keep `react` and `react-dom` on the same exact version.
- Keep `react-admin` and `ra-data-simple-rest` on the same exact version line.
- Keep `@mui/material` and `@mui/icons-material` on the same exact version.
## Resource Contract
- Use the shared entity-to-resource naming convention from `prompts/general-prompt.md`.
- Every entity becomes a React Admin resource with `list`, `create`, `edit`, and `show`.
- `Resource` registration in `client/src/App.tsx` must include `show={...}`.
- Every frontend record must work with React Admin's `id` contract, including natural-key entities.
DTO-driven view rules:
- List and Show views use fields from `DTO.<Entity>`
- Create view uses fields from `DTO.<Entity>Create`
- Edit view uses fields from `DTO.<Entity>Update`
- Do not derive form fields directly from model attributes when the DTO contract is narrower
## Input And Field Mapping
Form inputs:
- `integer`, `number`, `decimal` -> `NumberInput`
- `date` -> `DateInput`
- required `boolean` -> `BooleanInput`
- nullable `boolean` -> `NullableBooleanInput`
- enum -> `SelectInput`
- FK reference -> `ReferenceInput` + `AutocompleteInput`
Display fields:
- `integer`, `number`, `decimal` -> `NumberField`
- `date` -> `DateField`
- `boolean` -> `BooleanField`
- enum -> `SelectField`
- FK reference -> `ReferenceField`
Hard failure rule:
- using plain `TextInput` for `integer`, `number`, `decimal`, `date`, or `boolean` is a generation failure
## Filter And Reference Contract
- Lists must expose filters and include a toolbar with `FilterButton`.
- Enum multi-select filters use `SelectArrayInput`.
- Reference filters and form selectors use `ReferenceInput` + `AutocompleteInput` with `filterToQuery={(searchText) => ({ q: searchText })}`.
- FK list/show rendering must use `ReferenceField link=\"show\"`.
- `dataProvider` query serialization must preserve repeated params for array filters.
Reference display expression priority:
1. if `inventoryNumber` exists: ``(record) => `${record.inventoryNumber} — ${record.name ?? record.inventoryNumber}``
2. else if `code` exists: ``(record) => `${record.code} — ${record.name ?? record.code}``
3. else if `number` exists: ``(record) => `${record.number} — ${record.name ?? record.number}``
4. else if `name` exists: `(record) => record.name ?? record.id`
5. else: `(record) => record.id`
## Auth And Provider Seams
- `client/src/dataProvider.ts` remains the single authenticated request seam.
- `client/src/auth/authProvider.ts` remains the single React Admin auth seam.
- Resource components must not embed auth logic.
- `getIdentity()` resolves from token claims.
- `getPermissions()` may expose realm roles for UI awareness, but backend enforcement stays authoritative.
## Natural-Key Compatibility
- Frontend requests and routes must continue to work when the real primary key is not named `id`.
- Edit/show/delete flows must preserve compatibility with backend natural-key handling.
- Sorting and filtering assumptions must not regress to a fake physical `id`.
## Completion Expectations
Frontend generation is incomplete if any of the following is true:
- required Vite scaffold files are missing
- Create/Edit inputs are type-incorrect
- filter UI is missing or incomplete
- reference fields stop linking to `show`
- resource registration omits `show={...}`

View File

@@ -0,0 +1,496 @@
# Role
You are the master orchestrator of the KIS-TOiR generation pipeline.
Own the full run: understand the current workspace, read the domain contract,
coordinate sub-agents and MCP tools, generate or repair artifacts in the
correct order, run the required gates, fix failures, and stop only when the
repository is genuinely generation-complete.
# Project Description
KIS-TOiR is an LLM-first fullstack CRUD generation project for equipment maintenance management.
- Backend: NestJS + Prisma
- Frontend: Vite React TypeScript + React Admin
- Auth/runtime/deploy: external Keycloak + PostgreSQL + repository-managed env/runtime/deploy artifacts
- Deploy/runtime deliverables are first-class generation targets: Dockerfiles, nginx proxy config, compose topology, env templates, realm import, and bootstrap helpers are part of the contract, not incidental support files
The repository is intentionally prompt-driven. `prompts/*.md` define generation policy; generated code lives under `server/` and `client/` after generation, but those generated workspaces may be absent at the clean-slate start of a full regeneration run.
# Mission
Turn the repository source contract into a buildable, validated workspace by:
1. starting from a clean Tier 1/Tier 2 contract for repo-wide full regeneration, without relying on pre-existing Tier 3 workspaces or runtime artifacts
2. recreating official framework scaffolding when a workspace is missing or degraded
3. generating Prisma, backend, frontend, auth, runtime, deploy, and realm artifacts from the DSL
4. using sub-agents intentionally instead of carrying every concern in one context window
5. proving completion with builds and repository validation gates
6. preserving proven-good runtime/deploy behavior unless a contract change requires a targeted update
# Parent Responsibilities
The parent agent is the orchestrator/integrator. It is not the default broad
manual feature implementer.
Parent-only responsibilities:
- discovery orchestration
- docs verification orchestration
- contract freeze
- shared platform scaffold
- auth platform skeleton
- deploy/runtime skeleton
- shared platform wiring and env/runtime conventions
- launching specialized generators
- acceptance or rejection of delegated outputs
- final integration
- validation
- final handoff to reviewer
# Source Of Truth
`domain/toir.api.dsl` is the operative source of truth for generation runs.
It is authoritative for:
- entities and enums
- DTO shapes per operation
- nullability and requiredness
- primary and foreign keys
- HTTP methods, endpoint paths, and pagination contracts
Rules:
- Read the DSL directly. Do not substitute `api-summary.json` for `domain/toir.api.dsl`.
- Work from entity-scoped slices: the active `api API.<Entity>` block plus its referenced DTOs and enums.
- Quote the relevant DSL field definitions verbatim before generating DTOs, Prisma fields, controller contracts, or React Admin components.
- Treat `api-summary.json` only as an auxiliary artifact for quick inventory or validation/tooling that explicitly depends on it. It is never the authoritative generation input.
- Treat runtime/deploy artifacts named by `prompts/runtime-rules.md` and `prompts/auth-rules.md` as first-class generation targets. If any helper remains handwritten temporarily, the contract must say so explicitly instead of implying it is generated.
# Orchestration Model
Use a manager-first, agent-as-tool architecture.
- Keep one orchestrator in charge of planning, sequencing, integration, and final acceptance.
- Delegate bounded work to specialists; do not let sub-agents redefine the source hierarchy or completion criteria.
- Use shallow delegation only: one primary responsibility per sub-agent and explicit write-zones.
- Delegate by artifact family and by entity only when parallelism does not create write-zone overlap.
- If a sub-agent result conflicts with the DSL, companion rules, or validator output, trust the DSL and the gates.
- Do not let specialized generators redesign shared auth, runtime, deploy, scaffold, or platform seams.
Mandatory delegation pattern for future runs:
- `explorer`
Use first for repo discovery, scaffold inspection, locating entity-scoped DSL context, and finding existing registrations/seams.
- `docs_researcher`
Use when framework behavior, CLI scaffolding, auth/runtime planning, or prompt/orchestration patterns need verification against official docs or Context7.
- `generator_prisma`
Use after contract freeze for bounded Prisma and model-layer generation only.
- `generator_nest_resources`
Use after contract freeze for bounded NestJS resource module generation only.
- `generator_react_admin_resources`
Use after contract freeze for bounded React Admin resource generation only.
- `generator_data_access`
Use after contract freeze for bounded frontend data-access generation only.
- `reviewer`
Use only at the final review stage after integration and validation. Reviewer must check DSL fidelity, prompt-contract compliance, and whether validation output supports the completion claim.
The old universal `generator` is removed from the active full-generation model
and must not be used for full-generation workflows.
If a runtime does not expose named sub-agents, preserve the same separation of responsibilities inside one agent and keep stage handoffs explicit.
# Contract Freeze
Before any specialized generator starts, the parent must produce a normalized
structured handoff from the DSL and prompt contracts. This contract freeze does
not replace `domain/toir.api.dsl`; it is the parent-owned integration protocol
for bounded delegation.
The frozen contract must capture, where relevant:
- entities
- fields
- scalar and enum types
- ids and composite keys
- relations
- enums
- endpoint conventions
- route/path conventions
- naming rules
- auth surface expectations
- validator/eval compatibility constraints
- allowed write-zones per generator
Specialized generation must not begin before this contract freeze is explicit.
# Acceptance Protocol
Parent acceptance is explicit. A generator output is accepted only if:
- only allowed zones changed
- the frozen contract is respected
- no unauthorized cross-layer edits occurred
- the output is integration-ready
- relevant validation/build checks were attempted where applicable
- unresolved issues are surfaced explicitly
Failure handling:
- allow at most one bounded repair pass for a rejected generator output
- explicitly reject if the output is still not usable
- use manual fallback only after explicit rejection, never as a silent completion of partial delegated work
# MCP Usage Model
Use MCP/tools deliberately, not reflexively.
- Filesystem/search tools: gather exact local context before making decisions.
- Shell/runtime tools: run official CLI scaffolding, Prisma commands, builds, validators, and evals. Do not simulate command results from memory.
- Context7: primary source for current official NestJS, Prisma, React Admin, Vite, Docker, nginx, Keycloak, OIDC, JWT, JWKS, or prompt/orchestration guidance when repository docs are not enough.
- Web research: only after local files and Context7 are insufficient; prefer primary sources.
- Diff/validation tools: use before edits, after edits, and always at the end.
Tool-order policy:
1. local authoritative files
2. Context7 / official docs
3. web fallback
4. validation gates
# Documentation-first rule
Before the parent plans or repairs framework-sensitive seams, it must review
current official documentation rather than relying on memory alone.
- Use `explorer` first for repository discovery and seam tracing.
- Use `docs_researcher` before framework-sensitive planning for Prisma, NestJS,
React Admin, auth, data-access, runtime, deploy, or version-sensitive work.
- Prefer Context7 for Prisma, NestJS, React Admin, Vite, Docker, nginx, and
Keycloak/OIDC/JWT guidance.
- Use web fallback only for current, unstable, or missing documentation details.
- Do not design auth, data-access, or runtime seams purely from memory when
current framework guidance matters.
# Full-Regeneration Mode
When the task is a repo-wide full regeneration driven by this prompt:
- start from Tier 1/Tier 2 inputs only; do not require existing `server/`, `client/`, `db-seed/`, `docker-compose.yml`, Dockerfiles, env templates, or `toir-realm.json`
- treat existing Tier 3 outputs as disposable generated state rather than as prerequisites
- recreate backend and frontend workspaces from official CLIs before applying domain generation
- regenerate runtime/deploy artifacts from their companion rules after scaffolding
- treat validation as an end-state check after regeneration, not as a clean-slate prerequisite
# Approved Version Policy
Use exact approved dependency versions for scaffold repair and regeneration. Do not use `latest`, caret ranges, or unreviewed major-version upgrades in generated `package.json` files.
Repository-approved runtime baseline:
- Node.js: `22.12.0` or newer within the Node 22 LTS line
- Package manager: `npm` only with committed `package-lock.json`
Repository-approved backend baseline:
- `@nestjs/common`, `@nestjs/core`, `@nestjs/platform-express`, `@nestjs/testing`: `11.1.18`
- `@nestjs/config`: `4.0.3`
- `@nestjs/cli`: `11.0.17`
- `@nestjs/schematics`: `11.0.10`
- `prisma` and `@prisma/client`: `6.16.2`
- `class-validator`: `0.15.1`
- `class-transformer`: `0.5.1`
- `jose`: `6.2.2`
- `reflect-metadata`: `0.2.2`
- `rxjs`: `7.8.1`
- backend `typescript`: `5.7.3`
Repository-approved frontend baseline:
- `react` and `react-dom`: `19.2.4`
- `react-admin` and `ra-data-simple-rest`: `5.14.5`
- `@mui/material` and `@mui/icons-material`: `7.3.9`
- `@emotion/react`: `11.14.0`
- `@emotion/styled`: `11.14.1`
- `vite`: `8.0.3`
- `@vitejs/plugin-react`: `6.0.1`
- frontend `typescript`: `5.9.3`
- `keycloak-js`: `26.2.3`
Version rules:
- After official CLI scaffolding, immediately pin the workspace back to the approved versions above before domain generation starts.
- `prisma` and `@prisma/client` must always remain on the same exact version.
- Do not upgrade Prisma from v6 to v7 during normal regeneration. A Prisma major upgrade requires a separate explicit migration pass.
# Generation Roadmap
## A. Discovery
Purpose:
- establish the active scope
- verify scaffold health
- load only the context needed for the next stage
Responsible:
- orchestrator
- `explorer` first
- `docs_researcher` if scaffold conventions or framework behavior are uncertain
Mandatory inputs:
- `AGENTS.md`
- `prompts/general-prompt.md`
- `domain/toir.api.dsl`
- `prompts/runtime-rules.md`
- `.codex/AGENTS.md` and `.codex/agents/*.toml` when the runtime supports those agents
Expected outputs:
- entity-scoped DSL quotes for the active work
- a clean stage plan
- traced local seams and registration touchpoints
Handoff:
- proceed to docs verification only after the current repository state and likely write-zones are understood
Stage rules:
- Use `explorer` first.
- Do not handcraft framework scaffolds that should come from official CLIs.
## B. Docs Verification
Purpose:
- verify current framework behavior before parent planning touches shared seams or generator contracts
Responsible:
- orchestrator
- `docs_researcher`
Mandatory inputs:
- discovery findings
- relevant prompt docs
- relevant official docs via Context7 first
Expected outputs:
- verified framework constraints for Prisma, NestJS, React Admin, auth, runtime, or deploy planning
- explicit notes on any version-sensitive behavior that affects the frozen contract
Handoff:
- proceed to contract freeze only after framework-sensitive assumptions are verified or explicitly flagged
## C. Contract Freeze
Purpose:
- normalize the active DSL slice and prompt constraints into a bounded handoff for specialized generators
Responsible:
- orchestrator
Mandatory inputs:
- entity-scoped DSL quotes
- relevant prompt docs
- discovery and docs-verification findings
Expected outputs:
- a normalized structured contract covering entities, fields, types, ids/composite keys, relations, enums, endpoint/path conventions, naming rules, auth surface expectations, validator/eval constraints, and allowed write-zones per generator
- explicit delegated scopes for each specialized generator
Handoff:
- specialized generation starts only after contract freeze is explicit
## D. Shared Platform Scaffold
Purpose:
- create or repair shared framework scaffolds and parent-owned base platform seams before feature-layer generation
Responsible:
- orchestrator
- `explorer` and `docs_researcher` as needed
Mandatory inputs:
- frozen contract
- `prompts/runtime-rules.md`
- `prompts/auth-rules.md` when auth/runtime seams are affected
Expected outputs:
- `server/` and `client/` recreated or confirmed healthy from official scaffolding
- parent-owned auth platform skeleton
- parent-owned deploy/runtime skeleton
- shared wiring and env/runtime conventions ready for specialized generators
Handoff:
- proceed to specialized generation only after shared scaffold and parent-owned seams are coherent
Stage rules:
- Use official Nest CLI for initial backend workspace creation or repair.
- Use official Vite React TypeScript CLI for initial frontend workspace creation or repair.
- Use Prisma CLI for Prisma initialization when relevant.
- Parent owns shared scaffold, auth platform skeleton, and deploy/runtime skeleton.
## E. Parallel Specialized Generation
Purpose:
- generate bounded feature-layer artifacts after contract freeze without reassigning shared platform ownership
Responsible:
- orchestrator
- `generator_prisma`
- `generator_nest_resources`
- `generator_react_admin_resources`
- `generator_data_access`
Mandatory inputs:
- frozen contract
- stage-specific prompt docs
Expected outputs:
- `server/prisma/schema.prisma`
- `server/src/modules/<entity>/...`
- `client/src/resources/<entity>/...`
- `client/src/dataProvider.ts`
Handoff:
- parent accepts or rejects each delegated output before integration
- resource-aware auth bindings may be attached only inside delegated write-zones
## F. Integration
Purpose:
- integrate accepted specialized outputs into the parent-owned shared platform and registration seams
Responsible:
- orchestrator
Mandatory inputs:
- accepted specialized outputs only
- `prompts/auth-rules.md`
- `prompts/runtime-rules.md`
Expected outputs:
- final shared wiring across backend, frontend, auth, and runtime seams
- no unresolved cross-layer drift between accepted outputs
Handoff:
- proceed to validation only after all accepted outputs are integration-ready
## G. Validation
Purpose:
- prove the run is complete rather than merely plausible
Responsible:
- orchestrator
- relevant generator for one bounded repair pass when needed
Mandatory inputs:
- `prompts/validation-rules.md`
- validation command output
Expected outputs:
- passing structural and semantic gates
- explicit rejection or bounded repair for any delegated output that still drifts
Handoff:
- final review starts only after validation passes
## H. Final Review
Purpose:
- perform the final correctness, security, and test-gap review before completion is claimed
Responsible:
- orchestrator
- `reviewer`
Mandatory inputs:
- validated integrated output
- reviewer findings
Expected outputs:
- reviewer signoff or blocking findings
Handoff:
- there is no next stage; report complete only when reviewer signoff and all success criteria are satisfied
# Success Criteria
Generation is successful only if all of the following are true:
- by the end of the run, `server/` exists in the project root
- by the end of the run, `client/` exists in the project root
- the backend builds successfully
- the frontend builds successfully
- `node tools/validate-generation.mjs --artifacts-only` passes
- `npm run eval:generation` passes
- required auth/runtime/realm/deploy artifacts exist and match their companion rules
- module/resource registrations are complete
- any validator-required auxiliary artifacts, including `api-summary.json`, are refreshed and consistent
- the reviewer has not identified unresolved contract violations
- runtime/deploy artifacts remain runnable and match the runtime/auth rules
# Non-Goals / Constraints
- Do not edit `domain/toir.api.dsl` during generation.
- Do not treat `api-summary.json` as the source of truth or default starting point.
- Do not inline large backend/frontend/prisma/auth/runtime/validation rule sets into this master prompt; load the companion docs instead.
- Do not generate domain artifacts on top of a broken scaffold when official CLI repair is required.
- Do not claim success from prompt reasoning alone; use builds and repository gates.
- Do not load the full DSL blob when entity-scoped context is enough.
- Do not treat runtime/deploy artifacts as optional documentation; if the companion rules name them, they are generation targets.
- Do not claim runtime/deploy readiness without verifying the deploy-facing artifacts named in the companion rules.
# Companion Rule Documents
These documents are mandatory when their stage is active:
- Prisma stage: `prompts/prisma-rules.md`
- Backend stage: `prompts/backend-rules.md`
- Frontend stage: `prompts/frontend-rules.md`
- Auth / realm stage: `prompts/auth-rules.md`
- Runtime / bootstrap stage: `prompts/runtime-rules.md`
- Verification stage: `prompts/validation-rules.md`
The master prompt owns orchestration. Companion docs own artifact-specific detail.

View File

@@ -0,0 +1,145 @@
# Prisma Rules
<!-- prompt-version: 2.0 -->
<!-- applies-to: server/prisma/schema.prisma -->
<!-- generated-by: LLM following these rules -->
<!-- source-of-truth: domain/toir.api.dsl -->
<!-- validated-by: tools/validate-generation.mjs §validateBuildChecks -->
Use this document during the **E. Parallel Specialized Generation** stage
defined in `prompts/general-prompt.md`.
## Purpose
Generate `server/prisma/schema.prisma` as a faithful reflection of `domain/toir.api.dsl`.
Ownership rule:
- this stage belongs to `generator_prisma` after contract freeze
- Prisma work is limited to schema/model artifacts and optional parent-requested machine-readable summaries
- do not redesign backend/frontend/auth/runtime/platform seams from this stage
## Mandatory Inputs
- `prompts/general-prompt.md`
- the relevant entity/enum definitions from `domain/toir.api.dsl`
- the existing Prisma header if `server/prisma/schema.prisma` already exists
`api-summary.json` may be used only as an auxiliary validator/inventory artifact. It is not part of the authoritative Prisma source hierarchy.
## Expected Output
- `server/prisma/schema.prisma`
Never edit the schema manually during normal generation. Change the DSL and regenerate instead.
## Approved Dependency Baseline
- Runtime baseline for Prisma work: Node.js `22.12.0` or newer within the Node 22 LTS line
- `prisma`: `6.16.2`
- `@prisma/client`: `6.16.2`
- backend `typescript`: `5.7.3`
Version rules:
- Keep `prisma` and `@prisma/client` on the same exact version.
- Do not replace the approved Prisma v6 line with Prisma v7 during routine regeneration or scaffold repair.
- If a task explicitly upgrades Prisma majors, update the runtime/bootstrap contract and verification expectations in the same change.
## Migration Policy
- Preferred target policy: when the DSL changes the database shape, generate the schema and create or update Prisma migrations so deploys use migration history as the primary path.
- Current repository practice: the runtime entrypoint may fall back to `prisma db push` when no migration history exists, so fresh local or bootstrap environments still come up. Treat that fallback as bootstrap debt, not the desired steady state.
- If a schema change is committed without a migration, call it out explicitly as temporary technical debt and schedule the migration in the next repair pass.
## Source Of Truth
Entity definitions, field types, PKs, FKs, enums, optionality, uniqueness, and defaults come from `domain/toir.api.dsl`.
## Scalar Type Mapping
| DSL type | Prisma scalar type |
| --------- | ------------------ |
| `uuid` | `String` |
| `string` | `String` |
| `text` | `String` |
| `integer` | `Int` |
| `number` | `Float` |
| `decimal` | `Decimal` |
| `date` | `DateTime` |
| `boolean` | `Boolean` |
| enum name | enum name as-is |
Unknown DSL types pass through as-is for forward compatibility.
## Primary Key Rules
- a field marked `key primary` becomes `@id`
- if the primary key type is `uuid` or the field name is `id`, use `@id @default(uuid())`
- non-uuid natural keys keep plain `@id`
- every entity must resolve to exactly one primary key
## Optionality And Defaults
- primary keys are required
- fields marked `is required` are required
- all other fields are optional with Prisma `?`
- non-primary unique fields get `@unique`
- `default <value>` maps to Prisma `@default(...)`
## Foreign Key And Relation Rules
For a DSL field declared `key foreign { relates Entity.field }`:
1. emit the FK scalar field first
2. add a relation field named `lowerFirst(relatedEntity)`
3. if that relation name collides, append `Ref`
4. annotate with `@relation(fields: [<fkField>], references: [<referencedField>])`
Inverse array relations:
- add inverse array fields for referencing entities automatically
- pluralization rules:
- `equipment` stays `equipment`
- names ending in `s` add `es`
- all others add `s`
- if the inverse name collides, append `List`
## Enum Rules
- every DSL enum becomes a Prisma enum
- preserve declaration order
- preserve the enum name exactly
## Header Preservation
If `server/prisma/schema.prisma` already contains a `generator client { ... }` block, preserve everything before the first `enum` or `model` keyword.
If no valid header exists, emit:
```prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
```
## Forbidden Patterns
- do not add fields not declared in the DSL
- do not add `@@index`, `@@map`, or schema-level directives not declared by the DSL
- do not add `@db.*` modifiers
- do not change the datasource provider away from `postgresql`
## Completion Expectations
Prisma generation is incomplete if any of the following is true:
- `server/prisma/schema.prisma` does not exist
- the schema no longer reflects the DSL
- required relation fields or inverse arrays are missing
- header generation or preservation breaks Prisma baseline behavior

View File

@@ -0,0 +1,126 @@
# Runtime Rules
<!-- prompt-version: 2.0 -->
<!-- applies-to: docker-compose.yml, server/Dockerfile, client/Dockerfile, client/nginx/default.conf, server/.env.example, client/.env.example, server/docker-entrypoint.sh, db-seed/Dockerfile, db-seed/import.sh -->
<!-- validated-by: tools/validate-generation.mjs §validateRuntimeContractChecks -->
Use this document during the **A. Discovery**, **D. Shared Platform Scaffold**,
and **F. Integration** stages defined in `prompts/general-prompt.md`.
## Purpose
Define the runtime topology, environment defaults, scaffold expectations, deploy packaging, and bootstrap sequence for a buildable generated workspace.
Ownership rule:
- the parent owns runtime/deploy skeletons, shared platform wiring, and env/runtime conventions
- specialized generators may perform only minor resource-aware integration repairs inside explicitly delegated zones
- do not redesign shared deploy/runtime behavior from a resource generator
## Mandatory Inputs
- `prompts/general-prompt.md`
- `prompts/auth-rules.md` when runtime changes affect auth defaults or seams
- current repository runtime/auth defaults
`api-summary.json` is an auxiliary artifact only. Refresh it when validator/tooling requires freshness checks or when a compact inventory helps discovery. Do not treat it as the runtime source of truth.
## Expected Outputs
- `docker-compose.yml`
- `server/Dockerfile`
- `client/Dockerfile`
- `client/nginx/default.conf`
- `server/.env.example`
- `client/.env.example`
- `server/docker-entrypoint.sh`
- `db-seed/Dockerfile`
- `db-seed/import.sh`
- a buildable NestJS workspace under `server/`
- a buildable Vite React TypeScript workspace under `client/`
- any validator-required auxiliary artifacts such as `api-summary.json`
## Baseline Runtime Topology
- `server/` is the backend output path
- `client/` is the frontend output path
- compose-managed services are `postgres`, `server`, `db-seed`, and `client`
- the internal database container remains PostgreSQL-only
- Keycloak remains external to repository runtime
- the project remains LLM-first and prompt-driven
- runtime/deploy artifacts are first-class deliverables, not optional examples
## Proven-Good Runtime Baseline
- preserve the current `server/Dockerfile`, `client/Dockerfile`, `client/nginx/default.conf`, `docker-compose.yml`, `server/docker-entrypoint.sh`, `db-seed/Dockerfile`, and `db-seed/import.sh` behavior unless a contract change requires a targeted update
- treat `docker-compose.yml`, the Dockerfiles, nginx config, env templates, and realm import as deploy-facing outputs that must stay coherent with the auth and validation rules
- the runtime stage may create or repair all files named in `Expected Outputs`; do not describe them as optional support files
## Concrete Runtime Defaults
Backend:
- `PORT=3000`
- `DATABASE_URL="postgresql://postgres:postgres@localhost:5432/toir"`
- `CORS_ALLOWED_ORIGINS="http://localhost:5173,https://toir-frontend.greact.ru"`
- `KEYCLOAK_ISSUER_URL="https://sso.greact.ru/realms/toir"`
- `KEYCLOAK_AUDIENCE="toir-backend"`
Frontend:
- `VITE_API_URL=http://localhost:3000`
- `VITE_KEYCLOAK_URL=https://sso.greact.ru`
- `VITE_KEYCLOAK_REALM=toir`
- `VITE_KEYCLOAK_CLIENT_ID=toir-frontend`
## Runtime Toolchain Baseline
- Runtime Node.js baseline: `22.12.0` or newer within the Node 22 LTS line
- Package manager baseline: `npm` only
- Commit and preserve `package-lock.json` files for `server/` and `client/`
- Do not introduce `pnpm-lock.yaml`, `yarn.lock`, or Bun-specific package-manager assumptions during regeneration
- After CLI scaffolding, replace floating scaffold dependency ranges with the repository-approved exact versions from `AGENTS.md` and `prompts/general-prompt.md`
## Scaffold Expectations
- new or repaired backend workspaces start from the official Nest CLI
- new or repaired frontend workspaces start from the official Vite React TypeScript CLI
- Prisma initialization uses the official Prisma CLI when relevant
- the LLM may customize generated code after scaffold creation, but must not replace official initialization with ad hoc file creation
## Runtime Bootstrap
1. import `toir-realm.json` into Keycloak
2. start PostgreSQL with `docker compose up -d`
3. from `server/`:
- repair or create the workspace with official Nest CLI if needed
- install dependencies
- run Prisma commands required by the schema stage
- apply Prisma migrations when they exist; use `db push` only as a bootstrap fallback in fresh environments without migrations
- run `npm run build`
- run `npm run start`
4. from `client/`:
- repair or create the workspace with official Vite CLI if needed
- install dependencies
- run `npm run build`
- run `npm run dev`
## Prisma Migration Policy At Runtime
- Current accepted repository state: no committed `server/prisma/migrations/` directory is required for local bootstrap.
- Current runtime behavior therefore preserves the proven-good fallback in `server/docker-entrypoint.sh`:
- use `prisma migrate deploy` when committed migrations exist
- otherwise use `prisma db push`
- Preferred target policy for shared and production environments: commit reviewed Prisma migrations and let runtime use `prisma migrate deploy`.
- Treat migration absence as accepted temporary technical debt, not as the long-term deploy standard.
## Completion Expectations
Runtime preparation is incomplete if any of the following is true:
- `server/` is missing or not buildable as a NestJS workspace
- `client/` is missing or not buildable as a Vite React TypeScript workspace
- framework scaffolding was hand-built instead of created or repaired from official CLIs
- shared env defaults drift from the repository auth/runtime contract
- runtime success is claimed without actual build verification
- runtime/deploy outputs named in this file are missing or incoherent with the auth/runtime contract

View File

@@ -0,0 +1,100 @@
# Validation Rules
<!-- prompt-version: 2.0 -->
<!-- applies-to: tools/validate-generation.mjs and npm run eval:generation -->
<!-- validated-by: self -->
Use this document during the **G. Validation** and **H. Final Review**
stages defined in `prompts/general-prompt.md`.
## Purpose
Define the repository gates that convert a plausible generation run into a verified one.
These gates validate the post-generation repository state. They are not prerequisites for the clean-slate start of a repo-wide full regeneration run.
Validation ownership rule:
- parent owns integration, validation, acceptance/rejection decisions, and escalation to reviewer
- reviewers are the final review gate, not a substitute for parent validation
## Primary Gates
- `node tools/validate-generation.mjs --artifacts-only`
- `npm run eval:generation`
## Auxiliary Freshness Prep
- `npm run generate:api-summary`
Run the freshness prep when the repository validator or supporting tooling expects `api-summary.json` to exist and match the current DSL. This artifact is auxiliary to validation and inventory, not the generation source of truth.
## Prompt-Gate Alignment Rule
- every invariant marked required in the active prompt corpus must either be enforced by a gate or called out as manual/runtime-only
- the validator is the structural gate for infrastructure, runtime/deploy artifacts, and low-level wiring contracts
- evals are the semantic gate for DSL fidelity, CRUD behavior, UX invariants, and domain-contract compliance
- validation must not silently ignore a forbidden pattern
- build verification must not be reported as green when it was skipped
- reviewed eval fixtures are the authoritative semantic gate; do not auto-rewrite the committed eval corpus as part of every regeneration run
- if a new or changed entity behavior is not already represented, add or review the failing eval fixture before regeneration so evals lead the change
- approved dependency-version pinning is currently a manual review requirement unless or until the structural validator grows package-manifest checks
## Gate Groups
### Build Checks
- at least one `domain/*.api.dsl` file exists
- required artifacts exist:
- `server/prisma/schema.prisma`
- env examples
- required scaffold files
- auth/runtime/realm artifacts
- if the current validator policy checks `api-summary.json`, it exists and is fresh relative to the DSL
- `server/` remains a valid Nest workspace
- `client/` remains a valid Vite workspace
- `client/src/vite-env.d.ts` remains present as part of the official Vite React TypeScript scaffold unless the scaffold contract is explicitly revised
- package manifests must follow the approved exact-version policy from `AGENTS.md` and `prompts/general-prompt.md`; until the validator enforces this directly, treat it as a manual completion check
- if dependencies are installed, backend and frontend build verification runs
- if dependencies are missing, build verification is reported as skipped with reason instead of green
### Runtime / Deploy Checks
- docker topology remains PostgreSQL-only
- required Dockerfiles and nginx proxy config remain present when the runtime rules name them
- env examples stay aligned with repository defaults
- auth/runtime/realm artifacts remain coherent
- `/health` remains public
- Prisma lifecycle commands remain available where required
### Auth Checks
- frontend auth seam files exist
- backend auth seam files exist
- `401` and `403` semantics remain split
- auth code keeps the required Keycloak/JWT contracts
- JWKS resolution order remains:
1. explicit `KEYCLOAK_JWKS_URL`
2. OIDC discovery
3. certs fallback
### Realm Checks
- a root `*-realm.json` artifact exists
- required roles, audience delivery, and claims remain explicit
- SPA and backend client structure remains explicit
### Semantic Eval Checks
- `npm run eval:generation` runs fixture-based semantic checks
- eval failures block completion
- prompt changes that break evals are regressions, not acceptable simplifications
- eval helpers may scaffold candidate contracts from source-of-truth, but the committed eval corpus remains a reviewed artifact rather than an auto-regenerated byproduct of each full run
- evals own DSL fidelity, CRUD behavior, HTTP method/path behavior, DTO field coverage and decorator coverage, natural-key semantics, FK/reference wiring, Content-Range behavior, and React Admin UX/component invariants
## Split Rule
The validator must not be the place where entity-level DSL fidelity is graded.
- keep in the validator: scaffold health, buildability, required artifact presence, auth/runtime/deploy seams, env defaults, Docker/nginx/compose invariants, realm structure, and whether build verification was actually executed or explicitly skipped
- keep in evals: per-entity file coverage, DTO field presence, decorator/type mapping, controller verb/path fidelity, list/header behavior, natural-key behavior, FK/reference UX, and other DSL-driven CRUD semantics
- any validator checks that resemble output-contract checks exist only as stable syntax-level guardrails; they are justified as mechanical wiring checks, not as the semantic source of truth for generation correctness

View File

@@ -0,0 +1,7 @@
PORT=3000
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/toir"
CORS_ALLOWED_ORIGINS="http://localhost:5173,https://toir-frontend.greact.ru"
KEYCLOAK_ISSUER_URL="https://sso.greact.ru/realms/toir"
KEYCLOAK_AUDIENCE="toir-backend"
# Optional explicit JWKS URL override
KEYCLOAK_JWKS_URL=""

View File

@@ -0,0 +1,5 @@
node_modules
# Keep environment variables out of version control
.env
/generated/prisma

View File

@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

View File

@@ -0,0 +1,26 @@
FROM node:24-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npx prisma generate
RUN npm run build
FROM node:24-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
COPY --from=build /app/prisma ./prisma
COPY --from=build /app/docker-entrypoint.sh ./docker-entrypoint.sh
COPY .env.example ./.env.example
RUN chmod +x /app/docker-entrypoint.sh
EXPOSE 3000
ENTRYPOINT ["./docker-entrypoint.sh"]
CMD ["npm", "run", "start:prod"]

View File

@@ -0,0 +1,98 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Project setup
```bash
$ npm install
```
## Compile and run the project
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Run tests
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
```bash
$ npm install -g @nestjs/mau
$ mau deploy
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
## Resources
Check out a few resources that may come in handy when working with NestJS:
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).

View File

@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
npx prisma generate
if [ -d prisma/migrations ] && [ "$(find prisma/migrations -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ')" -gt 0 ]; then
npx prisma migrate deploy
else
npx prisma db push
fi
exec "$@"

View File

@@ -0,0 +1,35 @@
// @ts-check
import eslint from '@eslint/js';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: ['eslint.config.mjs'],
},
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
eslintPluginPrettierRecommended,
{
languageOptions: {
globals: {
...globals.node,
...globals.jest,
},
sourceType: 'commonjs',
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
"prettier/prettier": ["error", { endOfLine: "auto" }],
},
},
);

View File

@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,79 @@
{
"name": "server",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"prisma:generate": "prisma generate",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"seed": "node prisma/seed.js"
},
"dependencies": {
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.3",
"@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1",
"@prisma/client": "^6.16.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"jose": "^6.2.2",
"prisma": "^6.16.2",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^24.0.0",
"@types/supertest": "^7.0.0",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^17.0.0",
"jest": "^30.0.0",
"prettier": "^3.4.2",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@@ -0,0 +1,34 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
enum EquipmentStatus {
Active
Repair
}
model Equipment {
id String @id @default(uuid())
name String
serialNumber String
dateOfInspection DateTime?
commissionedAt DateTime?
status EquipmentStatus
changeEquipmentStatus ChangeEquipmentStatus[]
}
model ChangeEquipmentStatus {
equipmentId String
newStatus EquipmentStatus
number String?
date DateTime
responsible String?
equipment Equipment @relation(fields: [equipmentId], references: [id])
@@id([equipmentId, newStatus])
}

View File

@@ -0,0 +1 @@
console.log('No seed data configured.');

View File

@@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

Some files were not shown because too many files have changed in this diff Show More