diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 10904d6..dca3922 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -1,97 +1,81 @@ # 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. +This file supplements the repository root `AGENTS.md` with Claude Code-specific operational notes. + +**Architecture:** Subagents are defined programmatically in `agents/definitions.ts` using Claude Agent SDK. +Agent instructions are loaded from `.claude/agents/*.toml` config files at invocation time. --- -## Agent role summary +## Subagent Registry -| 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 | +All subagents operate under the orchestrator pattern defined in `prompts/claude-orchestration-rules.md`. -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. +| Agent | Description | Sandbox | Model | Config | +|-------|-------------|---------|-------|--------| +| `explorer` | Codebase discovery & exploration | read-only | haiku | `.claude/agents/explorer.toml` | +| `docs_researcher` | Framework docs verification | read-only | haiku | `.claude/agents/docs-researcher.toml` | +| `generator_prisma` | Prisma schema generation | workspace-write | opus | `.claude/agents/generator_prisma.toml` | +| `generator_nest_resources` | NestJS backend generation | workspace-write | opus | `.claude/agents/generator_nest_resources.toml` | +| `generator_react_admin_resources` | React Admin generation | workspace-write | opus | `.claude/agents/generator_react_admin_resources.toml` | +| `generator_data_access` | Frontend data-access integration | workspace-write | opus | `.claude/agents/generator_data_access.toml` | +| `reviewer` | Final review & validation | read-only | sonnet | `.claude/agents/reviewer.toml` | --- -## Delegation model +## Orchestration Entry Points -- 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. +### CLI (TypeScript/Node) ---- - -## Mutation boundary map +```bash +# Use the orchestrator directly +npx ts-node tools/orchestrator.ts "Your generation task" +# Add to package.json for convenience +npm run orchestrate "Your task" ``` -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) +### From Claude Code (programmatic) -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// - server/src/app.module.ts (only when explicitly delegated) - - generator_react_admin_resources - client/src/resources// - 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 +```typescript +import orchestrate from './tools/orchestrator'; +await orchestrate("Generate Prisma schema from domain/toir.api.dsl"); ``` +### How Subagents Are Invoked + +1. **Orchestrator (main agent)** reads task and frozen contract +2. **Agent SDK reads subagent descriptions** from `agents/definitions.ts` +3. **Claude matches intent to description** → "generate schema" → `generator_prisma` +4. **`Agent` tool invokes matching subagent** with: + - Agent-specific instructions (from `.claude/agents/*.toml`) + - Frozen contract & relevant DSL context + - Sandbox restrictions (read-only vs. workspace-write) + - Available MCP servers + +5. **Subagent executes bounded task** and returns result +6. **Orchestrator examines output** for write-zone compliance + contract adherence +7. **Orchestrator explicitly accepts or rejects** the output + +--- + +## Delegation Model + +**Full details in `prompts/claude-orchestration-rules.md`** — read this file when delegating. + +- **Shallow delegation only:** one primary responsibility per subagent +- **Orchestrator owns:** discovery, docs verification, contract freeze, shared scaffold, auth skeleton, deploy skeleton, integration, validation, final handoff +- **Generators own:** bounded feature-layer artifacts only (Prisma, NestJS modules, React Admin resources, data-access) +- **Shared seams stay parent-owned:** orchestrator manages app.module.ts, App.tsx, auth/, runtime/, deploy/ integration even when generators produce resource-aware bindings + +## Write-Zone Enforcement + +**Authoritative source:** `AGENTS.md` §Source-of-truth hierarchy (lines 17–76) + +For detailed write-zone enforcement and acceptance protocols specific to Claude Code orchestration, see: +- `prompts/claude-orchestration-rules.md` §Write-Zone Enforcement +- `prompts/claude-orchestration-rules.md` §Acceptance Protocol + ## Contract freeze and acceptance - Parent must freeze a normalized structured contract before specialized @@ -109,51 +93,56 @@ Tier 4 — Framework-managed support files ## 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`. +For runtime and deploy contract definition, see: +- `AGENTS.md` §Runtime / Deploy Contract (lines 71–75) +- `docs/completion-contract.md` — operational definition of done ## 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. +For approved stack version policy and dependency pinning, see: +- `AGENTS.md` §Approved Stack Version Policy (lines 77–96) --- -## Standard generation invocation +## 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 +# Full-generation mode: start from Tier 1 inputs only +# 1. Read AGENTS.md + prompts/general-prompt.md + prompts/claude-orchestration-rules.md +# 2. Use explorer for discovery, docs_researcher for framework verification +# 3. Freeze structured contract and write-zones # 4. Recreate or repair official CLI scaffolds -# 5. Launch specialized generators after contract freeze -# 6. Integrate, validate, and send to reviewer +# 5. Launch specialized generators after contract freeze via orchestrator +# 6. Integrate accepted outputs, run validation gates, send to reviewer + +# Run orchestrator +npx ts-node tools/orchestrator.ts "Full-generation task: [details]" + +# Verify completion node tools/validate-generation.mjs --artifacts-only npm run eval:generation ``` --- -## MCP servers (project-local) +## MCP Servers (Project-Local) -Defined in `.claude/config.toml`: +Defined in `.claude/config.toml`. All subagents have access: -- **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 +- **github** — repository context & PR history +- **context7** — official NestJS, Prisma, React Admin, Vite, Docker, Keycloak/OIDC docs +- **exa** — web search for current behavior, release notes, breaking changes +- **memory** — persistent cross-session notes (use sparingly) +- **playwright** — browser automation for UI/runtime verification +- **sequential-thinking** — structured multi-step reasoning for complex investigations -Add heavier or credential-backed servers in `~/.claude/config.toml`. +**Tool-order policy (all agents):** +1. Local authoritative files (domain/*.api.dsl, prompts/*.md, AGENTS.md) +2. Context7 official docs +3. Web search (exa) +4. Validation gates + +Add credential-backed servers in `~/.claude/config.toml` if needed. --- diff --git a/.claude/GETTING_STARTED.md b/.claude/GETTING_STARTED.md new file mode 100644 index 0000000..c069031 --- /dev/null +++ b/.claude/GETTING_STARTED.md @@ -0,0 +1,116 @@ +# Getting Started: Claude Code Full-Generation Workflow + +You're launching a full-generation task in Claude Code. **Read in this order:** + +## Step 1: Root Governance (CRITICAL) +Read **AGENTS.md** (all 477 lines, ~10 minutes) +- Why: Defines the source-of-truth hierarchy, mutation boundaries, tier structure, version policy, and success criteria +- Key sections: + - Lines 1-77: Source-of-truth hierarchy (Tier 1-4, what's hand-authored vs. generated) + - Lines 78-117: Approved stack versions (Node.js, NestJS, Prisma, React, etc.) + - Lines 298-328: Generation workflow (13 mandatory steps) + - Lines 493-507: Success criteria (what done actually looks like) + +## Step 2: Master Task Definition (CRITICAL) +Read **prompts/general-prompt.md** (all 535 lines, ~10 minutes) +- Why: Defines your mission as orchestrator, the 8-stage roadmap, parent vs. generator responsibilities, and contract freeze protocol +- Key sections: + - Lines 1-56: Your role and mission + - Lines 212-492: Stage-by-stage roadmap (Discovery → Final Review) + - Lines 493-507: Success criteria (must pass all) + +## Step 3: Claude Code Entry Points (FOR YOU) +Read **.claude/CLAUDE.md** (all 242 lines, ~5 minutes) +- Why: Claude Code-specific entry points and MCP tools +- Key sections: + - Lines 26-59: How to invoke orchestrator (CLI, programmatic, via Agent SDK) + - Lines 199-217: Available MCP servers (Context7, exa, memory, etc.) + - **Skip lines 10-88**: These duplicate AGENTS.md; use as reference only + +## Step 4: Subagent Delegation Protocol (FOR YOU) +Read **prompts/claude-orchestration-rules.md** (all 389 lines, ~8 minutes) +- Why: Defines how to delegate to subagents, contract freeze, acceptance protocol, and failure handling +- Key sections: + - Lines 70-173: Mandatory delegation workflow (5 phases) + - Lines 196-213: Write-zone enforcement (what each agent is allowed to touch) + - Lines 216-237: Failure handling (how to handle rejected outputs) + - Lines 279-356: Example full delegation cycle (read this if unsure) +- **Skip lines 1-68**: These duplicate general-prompt.md; use as reference only + +## Before Delegating to a Generator + +Load the stage-specific rule file that matches your current work: + +**Stage D (Shared Platform Scaffold):** +- prompts/auth-rules.md (auth/realm generation) +- prompts/runtime-rules.md (docker, env, deploy) + +**Stage E (Parallel Specialized Generation):** +- prompts/prisma-rules.md (before delegating to generator_prisma) +- prompts/backend-rules.md (before delegating to generator_nest_resources) +- prompts/frontend-rules.md (before delegating to generator_react_admin_resources) + +**Stage G (Validation):** +- prompts/validation-rules.md (interpreting validation gate output) + +## Reference Documents (Consult as Needed) + +- **docs/completion-contract.md**: Definition of done, failure modes, recovery procedures +- **domain/dsl-spec.md**: DSL syntax reference (only if DSL is ambiguous) +- **docs/generation-playbook.md**: Step-by-step workflow (optional deep-dive) + +## Key Decisions to Make Before Starting + +1. **Am I doing a full-generation run or a repair run?** + - Full-generation: Start from clean Tier 1/2 (DSL only); recreate server/ and client/ from scratch + - Repair: Start with existing Tier 3; fix specific issues + +2. **Which subagents do I need?** + - Always: explorer (discovery), docs_researcher (verification) + - Usually: generator_prisma, generator_nest_resources, generator_react_admin_resources + - Maybe: generator_data_access (only if dataProvider needs repair) + - Always last: reviewer (final quality check) + +3. **What's my acceptance threshold for delegated outputs?** + - Review against: write-zones, contract adherence, integration readiness + - Allow one bounded repair if rejected + - Reject explicitly if repair fails + - Don't silently continue with partial work + +## Quick Checklist + +- [ ] Read AGENTS.md +- [ ] Read prompts/general-prompt.md +- [ ] Read .claude/CLAUDE.md +- [ ] Read prompts/claude-orchestration-rules.md +- [ ] Understand the 8-stage roadmap (general-prompt.md) +- [ ] Know when to load stage-specific prompts +- [ ] Know your write-zones (prompts/claude-orchestration-rules.md lines 196-213) +- [ ] Know your acceptance protocol (prompts/claude-orchestration-rules.md lines 138-155) +- [ ] Ready to delegate? Start with explorer, then docs_researcher, then contract freeze + +## Common Questions + +**Q: Do I read .codex/AGENTS.md?** +A: Only if using Codex runtime (a different Claude product). For Claude Code, read `.claude/CLAUDE.md` instead. Root `AGENTS.md` applies to all runtimes. + +**Q: Do I read agents/definitions.ts?** +A: No, it's loaded automatically by the orchestrator. It's for implementation, not user reading. + +**Q: Do I read the .toml files?** +A: No, they're loaded automatically by agents. They're not for manual reading. + +**Q: What if I disagree with the version policy?** +A: Don't. It's Tier 1 source of truth (AGENTS.md lines 78-117). If you need to upgrade, make that a separate explicit task, not part of routine generation. + +**Q: What if a subagent output violates write-zones?** +A: Reject it explicitly. Quote the specific violation and the allowed write-zone from prompts/claude-orchestration-rules.md. Allow one bounded repair. If it still violates, manual fallback. + +**Q: What if validation gates fail?** +A: See prompts/claude-orchestration-rules.md Phase 5 (Validation & Final Review). Run the gates, surface failures explicitly, allow one bounded repair, or flag for manual review. + +--- + +**Ready? Start with AGENTS.md.** + +*Last Updated: 2026-04-07* diff --git a/.claude/ORCHESTRATION_SETUP.md b/.claude/ORCHESTRATION_SETUP.md new file mode 100644 index 0000000..de408c0 --- /dev/null +++ b/.claude/ORCHESTRATION_SETUP.md @@ -0,0 +1,227 @@ +# Claude Code Orchestration Setup — KIS-TOiR + +**Status:** ✅ Configuration complete + +This document confirms the orchestration system is ready for Claude Code use. + +--- + +## 📋 What Was Changed + +### 1. New Files Created + +#### SDK-Style Agent Definitions +- **`agents/definitions.ts`** — Programmatic subagent registry using Claude Agent SDK + - Loads agent instructions from `.claude/agents/*.toml` + - Defines 7 specialized subagents: explorer, docs_researcher, 5 generators, reviewer + - Sets sandbox limits and model overrides per agent + - Makes agents auto-discoverable via description matching + +#### Orchestrator Engine +- **`tools/orchestrator.ts`** — CLI orchestrator tool + - Entry point for multi-agent coordination + - Configures `Agent` tool for subagent invocation + - Shares MCP servers (github, context7, exa, memory, playwright, sequential-thinking) + - Command: `npx ts-node tools/orchestrator.ts "Your task"` + +#### Claude Code Orchestration Rules +- **`prompts/claude-orchestration-rules.md`** — Subagent governance (MANDATORY) + - Write-zone enforcement per agent + - Contract freeze workflow + - Delegation phases (discovery → contract → generation → acceptance → integration → validation) + - Failure handling and repair protocols + - MCP tool ordering + - Example: full delegation cycle + +#### Claude-Specific Supplement +- **`.claude/CLAUDE.md` (UPDATED)** — Governance supplement + - Describes subagent invocation model + - Lists write-zones and allowed files + - Documents MCP server access + - Explains orchestration entry points + +### 2. Configuration Updates + +#### `package.json` (UPDATED) +- Added `"type": "module"` for ES modules +- Added dev dependency: `@anthropic-ai/claude-agent-sdk` +- Added npm script: `npm run orchestrate` for CLI convenience + +#### `.claude/settings.local.json` (UPDATED) +- Added permissions for `tools/orchestrator.ts` +- Added `npm install` permission for dependency setup +- Added `node --loader ts-node/esm` loader permission + +#### `prompts/general-prompt.md` (UPDATED) +- Updated "Role" section with explicit delegation principle +- Expanded "Orchestration Model" with subagent invocation details +- Added reference to `prompts/claude-orchestration-rules.md` (mandatory) +- Clarified mandatory delegation pattern for each agent +- Added "Subagent Invocation" section explaining Agent tool requirement + +#### `AGENTS.md` (UPDATED) +- Added Tier 1 entries for: + - `.claude/CLAUDE.md` — Claude Code governance supplement + - `prompts/claude-orchestration-rules.md` — Orchestration rules (mandatory) + +--- + +## 🚀 How to Use + +### Installation (One-time) + +```bash +cd /Users/yyy/Desktop/toir-light +npm install +# This installs @anthropic-ai/claude-agent-sdk +``` + +### Orchestration Invocation + +**Option 1: Via npm script** +```bash +npm run orchestrate "Your generation task here" +``` + +**Option 2: Direct TypeScript** +```bash +npx ts-node tools/orchestrator.ts "Your generation task here" +``` + +**Option 3: From within Claude Code session (programmatic)** +```typescript +import orchestrate from './tools/orchestrator'; +await orchestrate("Generate Prisma schema from domain/toir.api.dsl"); +``` + +### Example: Full Generation Task + +```bash +npm run orchestrate "Execute full KIS-TOiR generation: +1. Use explorer to understand current workspace state +2. Freeze contract for ChangeEquipmentStatus resource +3. Delegate to generator_prisma, generator_nest_resources, generator_react_admin_resources, generator_data_access +4. Accept all outputs, integrate into shared platform +5. Run validation gates +6. Send to reviewer for final signoff" +``` + +--- + +## 📖 Required Reading Order + +When starting any orchestration session in Claude Code: + +1. **This file** — Understand what changed and how to invoke +2. **AGENTS.md** — Understand agent workflow and mutation boundaries +3. **prompts/general-prompt.md** — Understand orchestration model and roles +4. **prompts/claude-orchestration-rules.md** — MANDATORY before delegating; defines write-zones, contract freeze, acceptance protocol +5. **.claude/CLAUDE.md** — Understand Claude-specific entry points and MCP access + +When delegating to specific agents, read their `.claude/agents/*.toml` files for detailed instructions. + +--- + +## 🎯 Key Architectural Changes + +### Before (Codex-style, not working in Claude Code) + +```toml +# .claude/config.toml +[agents] +explorer = { config_file = "agents/explorer.toml" } +# ... (config file references) +``` + +❌ Claude Code couldn't invoke these agents — incompatible naming/invocation model + +### After (Claude Agent SDK style, fully compatible) + +```typescript +// agents/definitions.ts +export const agents = { + explorer: { + description: "Codebase discovery and exploration...", + prompt: loadAgentInstructions("explorer"), + tools: ["Read", "Glob", "Grep"], + model: "haiku" + }, + // ... (7 agents total) +} +``` + +```typescript +// tools/orchestrator.ts +for await (const message of query({ + prompt: mainPrompt, + options: { + allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep", "Agent"], + agents // ← Agent tool enables subagent invocation + } +})) { ... } +``` + +✅ Claude Code can now: +- Read agent definitions +- Match task intent to agent descriptions +- Invoke subagents via `Agent` tool +- Enforce write-zones and sandbox limits +- Accept/reject delegated outputs + +--- + +## ✅ Verification Checklist + +Before running your first orchestration task: + +- [ ] Read `.claude/CLAUDE.md` +- [ ] Read `prompts/claude-orchestration-rules.md` +- [ ] Run `npm install` (installs `@anthropic-ai/claude-agent-sdk`) +- [ ] Verify `agents/definitions.ts` exists +- [ ] Verify `tools/orchestrator.ts` exists +- [ ] Try `npm run orchestrate "Test: list the KIS-TOiR agents"` + +--- + +## 🔧 Troubleshooting + +### "Agent tool not available" +→ Add `"Agent"` to `allowedTools` in orchestrator.ts (already done, but verify) + +### "Subagent descriptions don't match my task" +→ Be explicit in your orchestration prompt; use agent names or clear descriptions +→ Example: "Use the generator_prisma agent to generate server/prisma/schema.prisma" + +### "Subagent writes to forbidden zone" +→ This is grounds for rejection. Examine .claude/agents/*.toml for agent instructions and write-zone rules. +→ Reread `prompts/claude-orchestration-rules.md` write-zone table + +### "npm install fails" +→ Ensure Node.js 22 LTS is installed: `node --version` +→ Ensure npm is available: `npm --version` + +--- + +## 🔐 Security Notes + +- ✅ All agent instructions loaded from version-controlled `.claude/agents/*.toml` files +- ✅ Write-zones strictly enforced per agent (sandbox restrictions) +- ✅ MCP servers configured in `.claude/config.toml` (read-only agents can't write) +- ✅ No hardcoded secrets; use `.env.example` patterns only +- ✅ Reviewer agent is read-only; cannot write or modify artifacts + +--- + +## 📚 Related Files + +- **AGENTS.md** — Master agent operating rules (authoritative) +- **prompts/general-prompt.md** — Master orchestrator prompt +- **prompts/claude-orchestration-rules.md** — Subagent governance (mandatory for delegation) +- **.claude/CLAUDE.md** — Claude Code-specific governance supplement +- **.claude/agents/*.toml** — Individual agent configurations (6 generator + reviewer) +- **.claude/config.toml** — MCP server definitions (github, context7, exa, memory, playwright, sequential-thinking) + +--- + +**Generated:** 2026-04-06 +**System:** Claude Agent SDK Orchestration v0.2.0 diff --git a/.claude/REFERENCE_TABLES.md b/.claude/REFERENCE_TABLES.md new file mode 100644 index 0000000..264a7a1 --- /dev/null +++ b/.claude/REFERENCE_TABLES.md @@ -0,0 +1,227 @@ +# KIS-TOiR Reference Tables +## For Quick Lookup During Generation + +This file consolidates the key reference tables from AGENTS.md and companion prompts. Use this as a quick lookup; for authoritative details, refer to the source documents. + +--- + +## Subagent Registry + +| Agent | Purpose | Sandbox | Model | Entry Point | When to Use | +|-------|---------|---------|-------|-------------|------------| +| `explorer` | Codebase discovery | read-only | haiku | `.claude/agents/explorer.toml` | First, to understand current state | +| `docs_researcher` | Framework docs verification | read-only | haiku | `.claude/agents/docs-researcher.toml` | Before designing shared seams | +| `generator_prisma` | Prisma schema generation | workspace-write | opus | `.claude/agents/generator_prisma.toml` | After contract freeze, for schema only | +| `generator_nest_resources` | NestJS backend generation | workspace-write | opus | `.claude/agents/generator_nest_resources.toml` | After contract freeze, for modules only | +| `generator_react_admin_resources` | React Admin generation | workspace-write | opus | `.claude/agents/generator_react_admin_resources.toml` | After contract freeze, for resources only | +| `generator_data_access` | Frontend data-access integration | workspace-write | opus | `.claude/agents/generator_data_access.toml` | After contract freeze, for dataProvider only | +| `reviewer` | Final review & validation | read-only | sonnet | `.claude/agents/reviewer.toml` | Last, after integration and validation | + +**Key Rule**: Use agents in this order: explorer → docs_researcher → contract freeze → specialized generators → integration → validation → reviewer. + +**Critical**: Do not manually name agents. Instead, describe your task clearly; Claude will match intent to agent description and invoke automatically via the Agent tool. + +--- + +## Write-Zone Enforcement + +**Allowed Write Zones (per Agent):** + +| Agent | Allowed | Forbidden | +|-------|---------|-----------| +| `generator_prisma` | `server/prisma/schema.prisma` | Everything else | +| `generator_nest_resources` | `server/src/modules//` (optionally `server/src/app.module.ts` when explicitly delegated) | `server/src/auth/`, `client/**`, `prisma`, `docker-compose.yml`, `Dockerfile`, `.env`, `prompts/`, `domain/*.api.dsl`, `tools/` | +| `generator_react_admin_resources` | `client/src/resources//` | `client/src/auth/`, `client/src/dataProvider.ts`, `server/**`, `docker-compose.yml`, all deploy/auth/prompts/domain/tools | +| `generator_data_access` | Narrowly delegated parts of `client/src/dataProvider.ts` only | Broad dataProvider rewrites, `client/src/resources/**`, `server/**`, `client/src/auth/`, auth, deploy, prompts | +| `reviewer` | **READ-ONLY** (may propose patches, not write) | No write permission on any file | + +**Parent-Owned Zones (Never Delegated):** +- `server/src/auth/`, `client/src/auth/` +- `docker-compose.yml`, `server/Dockerfile`, `client/Dockerfile`, `client/nginx/default.conf` +- `server/.env.example`, `client/.env.example`, `toir-realm.json` +- `prompts/`, `AGENTS.md`, `domain/`, `tools/` + +**Enforcement Rule**: If a generator touches outside its allowed zones, reject it explicitly. Quote the specific violation. Allow one bounded repair. If it still violates, use manual fallback. + +--- + +## Approved Stack Versions + +**Runtime Baseline (All Stages):** +- Node.js: `22.12.0` or newer within the Node 22 LTS line +- Package manager: `npm` only, with committed `package-lock.json` + +**Backend Baseline (Stages D & E):** +- `@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` (must be 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` +- TypeScript: `5.7.3` + +**Frontend Baseline (Stages D & E):** +- `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` +- TypeScript: `5.9.3` +- `keycloak-js`: `26.2.3` + +**Version Rules:** +- After official CLI scaffolding, immediately normalize `package.json` to these exact versions 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 routine generation (separate explicit migration task) +- Do not use `latest`, caret ranges, or unreviewed major bumps + +--- + +## Generation Roadmap (8 Stages) + +| Stage | Responsible | Task | Input | Output | +|-------|------------|------|-------|--------| +| A. Discovery | Orchestrator + `explorer` + `docs_researcher` | Understand current state, scaffold health, local seams | AGENTS.md, general-prompt.md, domain/toir.api.dsl | Entity-scoped DSL quotes, clean stage plan, traced seams | +| B. Docs Verification | Orchestrator + `docs_researcher` | Verify framework behavior before planning | Discovery findings, relevant prompts, Context7 docs | Verified framework constraints, version-sensitive notes | +| C. Contract Freeze | Orchestrator only | Normalize DSL + prompts into bounded handoff | Entity-scoped DSL, prompt docs, discovery findings | Structured contract (entities, fields, types, endpoints, naming, write-zones) | +| D. Shared Platform Scaffold | Orchestrator + `explorer`/`docs_researcher` | Create/repair shared framework scaffolds, auth skeleton, deploy skeleton | Frozen contract, auth-rules.md, runtime-rules.md | server/ and client/ from official CLIs, auth platform, deploy skeleton, env/runtime conventions | +| E. Parallel Specialized Generation | Orchestrator delegates to generators | Generate bounded feature-layer artifacts | Frozen contract, stage-specific prompts | Prisma schema, NestJS modules, React Admin resources, dataProvider | +| F. Integration | Orchestrator only | Wire accepted outputs into shared platform | Accepted generator outputs, auth-rules.md, runtime-rules.md | Final shared wiring, no unresolved cross-layer drift | +| G. Validation | Orchestrator + relevant generator (one repair pass) | Prove run is complete, not merely plausible | validation-rules.md, validation gate output | Passing structural gate (`validate-generation.mjs`) + semantic gate (`npm run eval:generation`) | +| H. Final Review | Orchestrator + `reviewer` | Final correctness, security, test-gap review | Validated integrated output, reviewer findings | Reviewer signoff or blocking findings | + +**Critical Rules:** +- Stages are sequential (A → B → C → D → E → F → G → H); do not skip stages +- Generators start only after contract freeze (Stage C) +- Validation gates (Stage G) are proof of completion, not optional +- No stage is complete until its expected outputs are produced +- Two gates must pass: `node tools/validate-generation.mjs --artifacts-only` AND `npm run eval:generation` + +--- + +## Mandatory Delegation Phases (Claude Code) + +| Phase | When | Who | Key Actions | +|-------|------|-----|-------------| +| Phase 1: Discovery & Docs Verification | At session start | Orchestrator + `explorer` + `docs_researcher` | Scan repo state, verify scaffold health, confirm framework behavior | +| Phase 2: Contract Freeze | After discovery, before any generator | Orchestrator only | Extract DSL, read prompts, produce normalized contract with explicit write-zones | +| Phase 3: Parallel Specialized Generation | After contract freeze | Orchestrator delegates to generators | Invoke generators in parallel (safe zones), receive outputs | +| Phase 4: Acceptance & Integration | After each generator | Orchestrator | Check write-zones + contract adherence, explicit accept or reject, allow one repair, integrate accepted outputs | +| Phase 5: Validation & Final Review | After integration | Orchestrator + validators + `reviewer` | Run both gates, diagnose failures, allow one bounded repair, hand off to reviewer for signoff | + +**Acceptance Checklist:** +- ✅ Only allowed write-zones changed +- ✅ No cross-layer edits outside delegated zone +- ✅ Output matches frozen contract +- ✅ Output is integration-ready +- ✅ No unresolved issues + +--- + +## MCP Tool Access + +| Server | Use For | When | Agents | +|--------|---------|------|--------| +| **github** | PR context, repo history, issue links | When parent needs remote context | All agents | +| **context7** | Official docs (NestJS, Prisma, React Admin, Vite, Docker, nginx, Keycloak/OIDC/JWT) | Before framework-sensitive planning | All agents | +| **exa** | Web search for current behavior, release notes, breaking changes | Only after Context7 is insufficient | All agents | +| **memory** | Persistent cross-session notes | For durable repo context only (use sparingly) | All agents | +| **playwright** | Browser automation for UI/runtime verification | When read-only code inspection insufficient | All agents | +| **sequential-thinking** | Structured multi-step reasoning | For ambiguous conflicts or multi-finding investigations | All agents | + +**Tool-Order Policy (Golden Rule):** +1. Local authoritative files (domain/*.api.dsl, prompts/*.md, AGENTS.md) +2. Context7 official docs +3. Web fallback (exa) +4. Validation gates + +--- + +## Success Criteria (All Must Pass) + +### Tier 1: Infrastructure Readiness +- ✅ `server/` exists and builds successfully (`npm run build`) +- ✅ `client/` exists and builds successfully (`npm run build`) +- ✅ `node tools/validate-generation.mjs --artifacts-only` passes +- ✅ Required scaffold files present (NestJS/Vite essentials) +- ✅ Runtime/deploy baseline files present: docker-compose.yml, Dockerfiles, nginx, env templates, realm +- ✅ Package manifests normalized to approved exact versions + +### Tier 2: Domain Fidelity +- ✅ `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 +- ✅ Eval contracts not silently rewritten + +### Tier 3: Runtime/Deploy Readiness +- ✅ Dockerfiles exist and are valid +- ✅ nginx config supports SPA routing and `/api` proxying +- ✅ Compose topology: postgres, server, db-seed, client (Keycloak external) +- ✅ Env examples align with auth/runtime contracts +- ✅ Realm artifact matches frontend/backend expectations + +### Tier 4: Auth Seam Integrity +- ✅ JWKS resolution works +- ✅ Role extraction from `realm_access.roles` +- ✅ `/health` remains public +- ✅ 401/403 semantics correct + +--- + +## Type Mappings (DSL → Prisma → TS → React Admin) + +| 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 Names (Plural, Kebab-Case):** +- `Equipment` → `equipment` (irregular — stays as-is) +- `EquipmentType` → `equipment-types` +- `RepairOrder` → `repair-orders` +- General rule: PascalCase → kebab-case → append `s` (or `es` if ends in `s`) + +**Default Sort Field (When Not Declared in DSL):** +- Priority: `inventoryNumber` > `number` > `code` > `name` > primary key + +--- + +## Quick Troubleshooting + +| Symptom | Likely Cause | Fix | +|---------|-------------|-----| +| Build fails, missing files | Scaffold degraded | Run official CLI repair, then regenerate domain | +| Eval fails on DTO shapes | DSL mismatch | Re-read DSL, regenerate affected artifacts | +| Generator edits unauthorized zones | Contract violation | Reject, allow one repair, manual fallback if still fails | +| Eval fails on guards/Content-Range | Guard order or header issue | Fix guard order (JwtAuthGuard first), ensure `Content-Range: items`, re-run evals | +| Prisma schema invalid | Missing relation annotation | Add explicit `@relation(fields: [...], references: [...])` | +| Validation gate fails | Artifact drift or missing file | Run gate, diagnose, allow one bounded repair, or flag for manual review | +| Version pins floating | Manifest not normalized | Pin to approved exact versions from this table after scaffold creation | + +--- + +**Source of Authority**: AGENTS.md (root), prompts/general-prompt.md, prompts/claude-orchestration-rules.md +**Last Updated**: 2026-04-07 +**For Detailed Guidance**: See corresponding documents listed above + +--- diff --git a/.claude/config.toml b/.claude/config.toml index 6d683d6..c61edfc 100644 --- a/.claude/config.toml +++ b/.claude/config.toml @@ -15,6 +15,14 @@ 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"] } +# KIS-TOiR read-only validation MCP servers. These are lightweight Node +# scripts under tools/mcp/ that expose structural checks without executing +# Prisma/npm/NestJS CLIs. See tools/mcp/lib/mcp-server.mjs for the protocol +# implementation and tools/mcp/*.mjs for tool definitions. +prisma-validator = { command = "node", args = ["tools/mcp/prisma-validator.mjs"] } +npm-validator = { command = "node", args = ["tools/mcp/npm-validator.mjs"] } +nest-validator = { command = "node", args = ["tools/mcp/nest-validator.mjs"] } + [agents] explorer = { config_file = "agents/explorer.toml" } docs_researcher = { config_file = "agents/docs-researcher.toml" } diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..0167413 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,15 @@ +{ + "permissions": { + "allow": [ + "Bash(npm --version)", + "Bash(export PATH=\"/usr/local/bin:$PATH\")", + "Bash(npm install:*)", + "Bash(npm run:*)", + "Bash(node tools/validate-generation.mjs:*)", + "Bash(node tools/orchestrator.ts:*)", + "Bash(node --loader ts-node/esm tools/orchestrator.ts:*)", + "Bash(docker compose:*)", + "Bash(npx --yes -p typescript@latest tsc --noEmit --strict --target es2022 --module nodenext --moduleResolution nodenext --esModuleInterop --skipLibCheck tools/orchestrator.ts tools/performance-monitor.ts)" + ] + } +} diff --git a/.claude/worktrees/goofy-haslett/.claude/CLAUDE.md b/.claude/worktrees/goofy-haslett/.claude/CLAUDE.md new file mode 100644 index 0000000..10904d6 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.claude/CLAUDE.md @@ -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// + server/src/app.module.ts (only when explicitly delegated) + + generator_react_admin_resources + client/src/resources// + 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. diff --git a/.claude/worktrees/goofy-haslett/.claude/agents/docs-researcher.toml b/.claude/worktrees/goofy-haslett/.claude/agents/docs-researcher.toml new file mode 100644 index 0000000..f894e65 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.claude/agents/docs-researcher.toml @@ -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. +""" diff --git a/.claude/worktrees/goofy-haslett/.claude/agents/explorer.toml b/.claude/worktrees/goofy-haslett/.claude/agents/explorer.toml new file mode 100644 index 0000000..5fbcac4 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.claude/agents/explorer.toml @@ -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 +""" diff --git a/.claude/worktrees/goofy-haslett/.claude/agents/generator_data_access.toml b/.claude/worktrees/goofy-haslett/.claude/agents/generator_data_access.toml new file mode 100644 index 0000000..08d0849 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.claude/agents/generator_data_access.toml @@ -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 +""" diff --git a/.claude/worktrees/goofy-haslett/.claude/agents/generator_nest_resources.toml b/.claude/worktrees/goofy-haslett/.claude/agents/generator_nest_resources.toml new file mode 100644 index 0000000..96026d3 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.claude/agents/generator_nest_resources.toml @@ -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 +""" diff --git a/.claude/worktrees/goofy-haslett/.claude/agents/generator_prisma.toml b/.claude/worktrees/goofy-haslett/.claude/agents/generator_prisma.toml new file mode 100644 index 0000000..dbeb22f --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.claude/agents/generator_prisma.toml @@ -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 +""" diff --git a/.claude/worktrees/goofy-haslett/.claude/agents/generator_react_admin_resources.toml b/.claude/worktrees/goofy-haslett/.claude/agents/generator_react_admin_resources.toml new file mode 100644 index 0000000..297d281 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.claude/agents/generator_react_admin_resources.toml @@ -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 +""" diff --git a/.claude/worktrees/goofy-haslett/.claude/agents/reviewer.toml b/.claude/worktrees/goofy-haslett/.claude/agents/reviewer.toml new file mode 100644 index 0000000..6d77773 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.claude/agents/reviewer.toml @@ -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.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// — backend artifacts + client/src/resources// — 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 +""" diff --git a/.claude/worktrees/goofy-haslett/.claude/config.toml b/.claude/worktrees/goofy-haslett/.claude/config.toml new file mode 100644 index 0000000..6d683d6 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.claude/config.toml @@ -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" } diff --git a/.claude/worktrees/goofy-haslett/.codex/AGENTS.md b/.claude/worktrees/goofy-haslett/.codex/AGENTS.md new file mode 100644 index 0000000..ebd582a --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.codex/AGENTS.md @@ -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// + server/src/app.module.ts (only when explicitly delegated) + + generator_react_admin_resources + client/src/resources// + 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. diff --git a/.claude/worktrees/goofy-haslett/.codex/agents/docs-researcher.toml b/.claude/worktrees/goofy-haslett/.codex/agents/docs-researcher.toml new file mode 100644 index 0000000..830f5cd --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.codex/agents/docs-researcher.toml @@ -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. +""" diff --git a/.claude/worktrees/goofy-haslett/.codex/agents/explorer.toml b/.claude/worktrees/goofy-haslett/.codex/agents/explorer.toml new file mode 100644 index 0000000..e88b59e --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.codex/agents/explorer.toml @@ -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 +""" diff --git a/.claude/worktrees/goofy-haslett/.codex/agents/generator_data_access.toml b/.claude/worktrees/goofy-haslett/.codex/agents/generator_data_access.toml new file mode 100644 index 0000000..74c33a1 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.codex/agents/generator_data_access.toml @@ -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 +""" diff --git a/.claude/worktrees/goofy-haslett/.codex/agents/generator_nest_resources.toml b/.claude/worktrees/goofy-haslett/.codex/agents/generator_nest_resources.toml new file mode 100644 index 0000000..64587a3 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.codex/agents/generator_nest_resources.toml @@ -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 +""" diff --git a/.claude/worktrees/goofy-haslett/.codex/agents/generator_prisma.toml b/.claude/worktrees/goofy-haslett/.codex/agents/generator_prisma.toml new file mode 100644 index 0000000..af4aa53 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.codex/agents/generator_prisma.toml @@ -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 +""" diff --git a/.claude/worktrees/goofy-haslett/.codex/agents/generator_react_admin_resources.toml b/.claude/worktrees/goofy-haslett/.codex/agents/generator_react_admin_resources.toml new file mode 100644 index 0000000..368865b --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.codex/agents/generator_react_admin_resources.toml @@ -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 +""" diff --git a/.claude/worktrees/goofy-haslett/.codex/agents/reviewer.toml b/.claude/worktrees/goofy-haslett/.codex/agents/reviewer.toml new file mode 100644 index 0000000..50f275e --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.codex/agents/reviewer.toml @@ -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.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// — backend artifacts + client/src/resources// — 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 +""" diff --git a/.claude/worktrees/goofy-haslett/.codex/config.toml b/.claude/worktrees/goofy-haslett/.codex/config.toml new file mode 100644 index 0000000..e3d45ef --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.codex/config.toml @@ -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 ` +[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" diff --git a/.claude/worktrees/goofy-haslett/.env.portainer.example b/.claude/worktrees/goofy-haslett/.env.portainer.example new file mode 100644 index 0000000..bbde392 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.env.portainer.example @@ -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 diff --git a/.claude/worktrees/goofy-haslett/.gitignore b/.claude/worktrees/goofy-haslett/.gitignore new file mode 100644 index 0000000..58f091b --- /dev/null +++ b/.claude/worktrees/goofy-haslett/.gitignore @@ -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/ \ No newline at end of file diff --git a/.claude/worktrees/goofy-haslett/AGENTS.md b/.claude/worktrees/goofy-haslett/AGENTS.md new file mode 100644 index 0000000..6403d24 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/AGENTS.md @@ -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//` | `domain/*.api.dsl` + `prompts/backend-rules.md` | +| `client/src/resources//` | `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.` 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= +OPENAI_BASE_URL=https://openrouter.ai/api/v1 +OPENAI_MODEL= +``` + +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.` — 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) diff --git a/.claude/worktrees/goofy-haslett/README.md b/.claude/worktrees/goofy-haslett/README.md new file mode 100644 index 0000000..19a24b4 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/README.md @@ -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. diff --git a/.claude/worktrees/goofy-haslett/api-summary.json b/.claude/worktrees/goofy-haslett/api-summary.json new file mode 100644 index 0000000..b808e4f --- /dev/null +++ b/.claude/worktrees/goofy-haslett/api-summary.json @@ -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 + } + ] + } + ] + } + ] +} diff --git a/client/.env.example b/.claude/worktrees/goofy-haslett/client/.env.example similarity index 100% rename from client/.env.example rename to .claude/worktrees/goofy-haslett/client/.env.example diff --git a/client/.gitignore b/.claude/worktrees/goofy-haslett/client/.gitignore similarity index 100% rename from client/.gitignore rename to .claude/worktrees/goofy-haslett/client/.gitignore diff --git a/client/Dockerfile b/.claude/worktrees/goofy-haslett/client/Dockerfile similarity index 100% rename from client/Dockerfile rename to .claude/worktrees/goofy-haslett/client/Dockerfile diff --git a/client/README.md b/.claude/worktrees/goofy-haslett/client/README.md similarity index 100% rename from client/README.md rename to .claude/worktrees/goofy-haslett/client/README.md diff --git a/client/eslint.config.js b/.claude/worktrees/goofy-haslett/client/eslint.config.js similarity index 100% rename from client/eslint.config.js rename to .claude/worktrees/goofy-haslett/client/eslint.config.js diff --git a/client/index.html b/.claude/worktrees/goofy-haslett/client/index.html similarity index 100% rename from client/index.html rename to .claude/worktrees/goofy-haslett/client/index.html diff --git a/client/nginx/default.conf b/.claude/worktrees/goofy-haslett/client/nginx/default.conf similarity index 100% rename from client/nginx/default.conf rename to .claude/worktrees/goofy-haslett/client/nginx/default.conf diff --git a/client/package-lock.json b/.claude/worktrees/goofy-haslett/client/package-lock.json similarity index 100% rename from client/package-lock.json rename to .claude/worktrees/goofy-haslett/client/package-lock.json diff --git a/client/package.json b/.claude/worktrees/goofy-haslett/client/package.json similarity index 100% rename from client/package.json rename to .claude/worktrees/goofy-haslett/client/package.json diff --git a/client/public/favicon.svg b/.claude/worktrees/goofy-haslett/client/public/favicon.svg similarity index 100% rename from client/public/favicon.svg rename to .claude/worktrees/goofy-haslett/client/public/favicon.svg diff --git a/client/public/icons.svg b/.claude/worktrees/goofy-haslett/client/public/icons.svg similarity index 100% rename from client/public/icons.svg rename to .claude/worktrees/goofy-haslett/client/public/icons.svg diff --git a/client/src/App.css b/.claude/worktrees/goofy-haslett/client/src/App.css similarity index 100% rename from client/src/App.css rename to .claude/worktrees/goofy-haslett/client/src/App.css diff --git a/client/src/App.tsx b/.claude/worktrees/goofy-haslett/client/src/App.tsx similarity index 100% rename from client/src/App.tsx rename to .claude/worktrees/goofy-haslett/client/src/App.tsx diff --git a/client/src/assets/hero.png b/.claude/worktrees/goofy-haslett/client/src/assets/hero.png similarity index 100% rename from client/src/assets/hero.png rename to .claude/worktrees/goofy-haslett/client/src/assets/hero.png diff --git a/client/src/assets/react.svg b/.claude/worktrees/goofy-haslett/client/src/assets/react.svg similarity index 100% rename from client/src/assets/react.svg rename to .claude/worktrees/goofy-haslett/client/src/assets/react.svg diff --git a/client/src/assets/vite.svg b/.claude/worktrees/goofy-haslett/client/src/assets/vite.svg similarity index 100% rename from client/src/assets/vite.svg rename to .claude/worktrees/goofy-haslett/client/src/assets/vite.svg diff --git a/client/src/auth/authProvider.ts b/.claude/worktrees/goofy-haslett/client/src/auth/authProvider.ts similarity index 100% rename from client/src/auth/authProvider.ts rename to .claude/worktrees/goofy-haslett/client/src/auth/authProvider.ts diff --git a/client/src/auth/keycloak.ts b/.claude/worktrees/goofy-haslett/client/src/auth/keycloak.ts similarity index 100% rename from client/src/auth/keycloak.ts rename to .claude/worktrees/goofy-haslett/client/src/auth/keycloak.ts diff --git a/client/src/bootstrap.tsx b/.claude/worktrees/goofy-haslett/client/src/bootstrap.tsx similarity index 100% rename from client/src/bootstrap.tsx rename to .claude/worktrees/goofy-haslett/client/src/bootstrap.tsx diff --git a/client/src/config/env.ts b/.claude/worktrees/goofy-haslett/client/src/config/env.ts similarity index 100% rename from client/src/config/env.ts rename to .claude/worktrees/goofy-haslett/client/src/config/env.ts diff --git a/client/src/dataProvider.ts b/.claude/worktrees/goofy-haslett/client/src/dataProvider.ts similarity index 100% rename from client/src/dataProvider.ts rename to .claude/worktrees/goofy-haslett/client/src/dataProvider.ts diff --git a/client/src/index.css b/.claude/worktrees/goofy-haslett/client/src/index.css similarity index 100% rename from client/src/index.css rename to .claude/worktrees/goofy-haslett/client/src/index.css diff --git a/client/src/main.tsx b/.claude/worktrees/goofy-haslett/client/src/main.tsx similarity index 100% rename from client/src/main.tsx rename to .claude/worktrees/goofy-haslett/client/src/main.tsx diff --git a/client/src/resources/change-equipment-status/ChangeEquipmentStatusCreate.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/change-equipment-status/ChangeEquipmentStatusCreate.tsx similarity index 100% rename from client/src/resources/change-equipment-status/ChangeEquipmentStatusCreate.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/change-equipment-status/ChangeEquipmentStatusCreate.tsx diff --git a/client/src/resources/change-equipment-status/ChangeEquipmentStatusEdit.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/change-equipment-status/ChangeEquipmentStatusEdit.tsx similarity index 100% rename from client/src/resources/change-equipment-status/ChangeEquipmentStatusEdit.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/change-equipment-status/ChangeEquipmentStatusEdit.tsx diff --git a/client/src/resources/change-equipment-status/ChangeEquipmentStatusList.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/change-equipment-status/ChangeEquipmentStatusList.tsx similarity index 100% rename from client/src/resources/change-equipment-status/ChangeEquipmentStatusList.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/change-equipment-status/ChangeEquipmentStatusList.tsx diff --git a/client/src/resources/change-equipment-status/ChangeEquipmentStatusShow.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/change-equipment-status/ChangeEquipmentStatusShow.tsx similarity index 100% rename from client/src/resources/change-equipment-status/ChangeEquipmentStatusShow.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/change-equipment-status/ChangeEquipmentStatusShow.tsx diff --git a/client/src/resources/equipment-status-change/EquipmentStatusChangeCreate.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/equipment-status-change/EquipmentStatusChangeCreate.tsx similarity index 100% rename from client/src/resources/equipment-status-change/EquipmentStatusChangeCreate.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/equipment-status-change/EquipmentStatusChangeCreate.tsx diff --git a/client/src/resources/equipment-status-change/EquipmentStatusChangeEdit.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/equipment-status-change/EquipmentStatusChangeEdit.tsx similarity index 100% rename from client/src/resources/equipment-status-change/EquipmentStatusChangeEdit.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/equipment-status-change/EquipmentStatusChangeEdit.tsx diff --git a/client/src/resources/equipment-status-change/EquipmentStatusChangeList.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/equipment-status-change/EquipmentStatusChangeList.tsx similarity index 100% rename from client/src/resources/equipment-status-change/EquipmentStatusChangeList.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/equipment-status-change/EquipmentStatusChangeList.tsx diff --git a/client/src/resources/equipment-status-change/EquipmentStatusChangeShow.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/equipment-status-change/EquipmentStatusChangeShow.tsx similarity index 100% rename from client/src/resources/equipment-status-change/EquipmentStatusChangeShow.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/equipment-status-change/EquipmentStatusChangeShow.tsx diff --git a/client/src/resources/equipment/EquipmentCreate.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/equipment/EquipmentCreate.tsx similarity index 100% rename from client/src/resources/equipment/EquipmentCreate.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/equipment/EquipmentCreate.tsx diff --git a/client/src/resources/equipment/EquipmentEdit.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/equipment/EquipmentEdit.tsx similarity index 100% rename from client/src/resources/equipment/EquipmentEdit.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/equipment/EquipmentEdit.tsx diff --git a/client/src/resources/equipment/EquipmentList.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/equipment/EquipmentList.tsx similarity index 100% rename from client/src/resources/equipment/EquipmentList.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/equipment/EquipmentList.tsx diff --git a/client/src/resources/equipment/EquipmentShow.tsx b/.claude/worktrees/goofy-haslett/client/src/resources/equipment/EquipmentShow.tsx similarity index 100% rename from client/src/resources/equipment/EquipmentShow.tsx rename to .claude/worktrees/goofy-haslett/client/src/resources/equipment/EquipmentShow.tsx diff --git a/client/src/resources/shared/equipmentStatusChoices.ts b/.claude/worktrees/goofy-haslett/client/src/resources/shared/equipmentStatusChoices.ts similarity index 100% rename from client/src/resources/shared/equipmentStatusChoices.ts rename to .claude/worktrees/goofy-haslett/client/src/resources/shared/equipmentStatusChoices.ts diff --git a/client/src/vite-env.d.ts b/.claude/worktrees/goofy-haslett/client/src/vite-env.d.ts similarity index 100% rename from client/src/vite-env.d.ts rename to .claude/worktrees/goofy-haslett/client/src/vite-env.d.ts diff --git a/client/tsconfig.app.json b/.claude/worktrees/goofy-haslett/client/tsconfig.app.json similarity index 100% rename from client/tsconfig.app.json rename to .claude/worktrees/goofy-haslett/client/tsconfig.app.json diff --git a/client/tsconfig.json b/.claude/worktrees/goofy-haslett/client/tsconfig.json similarity index 100% rename from client/tsconfig.json rename to .claude/worktrees/goofy-haslett/client/tsconfig.json diff --git a/client/tsconfig.node.json b/.claude/worktrees/goofy-haslett/client/tsconfig.node.json similarity index 100% rename from client/tsconfig.node.json rename to .claude/worktrees/goofy-haslett/client/tsconfig.node.json diff --git a/client/vite.config.ts b/.claude/worktrees/goofy-haslett/client/vite.config.ts similarity index 100% rename from client/vite.config.ts rename to .claude/worktrees/goofy-haslett/client/vite.config.ts diff --git a/db-seed/Dockerfile b/.claude/worktrees/goofy-haslett/db-seed/Dockerfile similarity index 100% rename from db-seed/Dockerfile rename to .claude/worktrees/goofy-haslett/db-seed/Dockerfile diff --git a/db-seed/import.sh b/.claude/worktrees/goofy-haslett/db-seed/import.sh similarity index 100% rename from db-seed/import.sh rename to .claude/worktrees/goofy-haslett/db-seed/import.sh diff --git a/docker-compose.yml b/.claude/worktrees/goofy-haslett/docker-compose.yml similarity index 100% rename from docker-compose.yml rename to .claude/worktrees/goofy-haslett/docker-compose.yml diff --git a/.claude/worktrees/goofy-haslett/docs/AID_EXPORT_README.md b/.claude/worktrees/goofy-haslett/docs/AID_EXPORT_README.md new file mode 100644 index 0000000..288f625 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/docs/AID_EXPORT_README.md @@ -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://:` (например `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. diff --git a/.claude/worktrees/goofy-haslett/docs/api-dsl-conventions.md b/.claude/worktrees/goofy-haslett/docs/api-dsl-conventions.md new file mode 100644 index 0000000..4b29e3e --- /dev/null +++ b/.claude/worktrees/goofy-haslett/docs/api-dsl-conventions.md @@ -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: `.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. { + description "Human-readable description"; + + attribute { + description "Field description"; + type ; + is required; // or: is nullable; + map .; // links to a field in domain/*.api.dsl + } +} +``` + +### DTO naming convention + +| DTO name | Purpose | +|----------|---------| +| `DTO.` | Full response shape (GET by id, list items) | +| `DTO.Create` | Create request body | +| `DTO.Update` | Update request body (partial — all fields nullable) | +| `DTO.ListRequest` | Paginated list request (filters + page) | +| `DTO.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.` or `DTO.[]`. + +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. { + description "API group description"; + + endpoint { + label "METHOD /path"; + description "Endpoint description"; + + // For endpoints with a request body: + attribute request { + type DTO.; + } + + // For endpoints with a response body: + attribute response { + type DTO.; + } + + // For path parameters: + attribute { + type ; + } + } +} +``` + +### api block naming + +`API.` (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 | +|---------------|-------|------| +| `lists` | `"POST //page"` | request: `DTO.ListRequest`, response: `DTO.ListResponse` | +| `get` | `"GET //{id}"` | path param `id`, response: `DTO.` | +| `create` | `"POST /"` | request: `DTO.Create` | +| `update` | `"PUT //{id}"` | path param `id`, request: `DTO.Update` | +| `delete` | `"DELETE //{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. diff --git a/.claude/worktrees/goofy-haslett/docs/completion-contract.md b/.claude/worktrees/goofy-haslett/docs/completion-contract.md new file mode 100644 index 0000000..a9f42a0 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/docs/completion-contract.md @@ -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. diff --git a/.claude/worktrees/goofy-haslett/docs/future-work.md b/.claude/worktrees/goofy-haslett/docs/future-work.md new file mode 100644 index 0000000..5821e21 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/docs/future-work.md @@ -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 `` 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. 2–3 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. 3–5 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//` 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 diff --git a/.claude/worktrees/goofy-haslett/docs/generation-playbook.md b/.claude/worktrees/goofy-haslett/docs/generation-playbook.md new file mode 100644 index 0000000..018326f --- /dev/null +++ b/.claude/worktrees/goofy-haslett/docs/generation-playbook.md @@ -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// + prompts/frontend-rules.md ──► generator_react_admin_resources ──► client/src/resources// + 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.` — **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 +``` + +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//.module.ts` +2. `server/src/modules//dto/create-.dto.ts` + — fields from the `DTO.Create` block in api.dsl +3. `server/src/modules//dto/update-.dto.ts` + — fields from the `DTO.Update` block in api.dsl +4. `server/src/modules//.service.ts` + — CRUD operations using Prisma; respect type mappings from `prompts/backend-rules.md` +5. `server/src/modules//.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//List.tsx` + — columns from `DTO.` (response shape) +2. `client/src/resources//Create.tsx` + — fields from `DTO.Create` +3. `client/src/resources//Edit.tsx` + — fields from `DTO.Update` +4. `client/src/resources//Show.tsx` + — fields from `DTO.` + +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//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 3–6). +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 4–7). + +**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 4–7. 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//*.ts` | `domain/*.api.dsl` | `prompts/backend-rules.md` | `npm run eval:generation` | +| `server/src/modules//dto/create-.dto.ts` | `DTO.Create` fields | `prompts/backend-rules.md §DTO-field-coverage` | `npm run eval:generation` | +| `server/src/modules//dto/update-.dto.ts` | `DTO.Update` fields | `prompts/backend-rules.md §DTO-field-coverage` | `npm run eval:generation` | +| `client/src/resources//*.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= +OPENAI_BASE_URL=https://openrouter.ai/api/v1 +OPENAI_MODEL= +``` + +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. diff --git a/.claude/worktrees/goofy-haslett/docs/repository-structure.md b/.claude/worktrees/goofy-haslett/docs/repository-structure.md new file mode 100644 index 0000000..d6e0962 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/docs/repository-structure.md @@ -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. diff --git a/docs/source-of-truth.md b/.claude/worktrees/goofy-haslett/docs/source-of-truth.md similarity index 100% rename from docs/source-of-truth.md rename to .claude/worktrees/goofy-haslett/docs/source-of-truth.md diff --git a/.claude/worktrees/goofy-haslett/domain/dsl-spec.md b/.claude/worktrees/goofy-haslett/domain/dsl-spec.md new file mode 100644 index 0000000..f5fdb2d --- /dev/null +++ b/.claude/worktrees/goofy-haslett/domain/dsl-spec.md @@ -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.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.Update` in api.dsl. All fields are +typically nullable for partial update semantics. +- **API response shape** — declared as `dto DTO.` 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.Create` fields; the Edit form +uses `DTO.Update` fields; List and Show use `DTO.` fields. + diff --git a/.claude/worktrees/goofy-haslett/domain/toir.api.dsl b/.claude/worktrees/goofy-haslett/domain/toir.api.dsl new file mode 100644 index 0000000..6272a2a --- /dev/null +++ b/.claude/worktrees/goofy-haslett/domain/toir.api.dsl @@ -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; + } + } +} \ No newline at end of file diff --git a/.claude/worktrees/goofy-haslett/equipment-import.sql b/.claude/worktrees/goofy-haslett/equipment-import.sql new file mode 100644 index 0000000..328dd96 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/equipment-import.sql @@ -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; diff --git a/.claude/worktrees/goofy-haslett/openapi.json b/.claude/worktrees/goofy-haslett/openapi.json new file mode 100644 index 0000000..e731f10 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/openapi.json @@ -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" + } + } + } + } + } +} diff --git a/.claude/worktrees/goofy-haslett/package.json b/.claude/worktrees/goofy-haslett/package.json new file mode 100644 index 0000000..524587b --- /dev/null +++ b/.claude/worktrees/goofy-haslett/package.json @@ -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" + } +} diff --git a/.claude/worktrees/goofy-haslett/prompts/auth-rules.md b/.claude/worktrees/goofy-haslett/prompts/auth-rules.md new file mode 100644 index 0000000..59d91bb --- /dev/null +++ b/.claude/worktrees/goofy-haslett/prompts/auth-rules.md @@ -0,0 +1,115 @@ +# Auth Rules + + + + + +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 diff --git a/.claude/worktrees/goofy-haslett/prompts/backend-rules.md b/.claude/worktrees/goofy-haslett/prompts/backend-rules.md new file mode 100644 index 0000000..787c9dd --- /dev/null +++ b/.claude/worktrees/goofy-haslett/prompts/backend-rules.md @@ -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.` 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//.module.ts` +- `server/src/modules//.controller.ts` +- `server/src/modules//.service.ts` +- `server/src/modules//dto/create-.dto.ts` +- `server/src/modules//dto/update-.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.Create` defines `CreateDto`. +- `DTO.Update` defines `UpdateDto`. +- 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(':')` +- 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 -/` 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 diff --git a/.claude/worktrees/goofy-haslett/prompts/frontend-rules.md b/.claude/worktrees/goofy-haslett/prompts/frontend-rules.md new file mode 100644 index 0000000..72f4d67 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/prompts/frontend-rules.md @@ -0,0 +1,151 @@ +# Frontend Rules + + + + + +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.` 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//List.tsx` +- `client/src/resources//Create.tsx` +- `client/src/resources//Edit.tsx` +- `client/src/resources//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.` +- Create view uses fields from `DTO.Create` +- Edit view uses fields from `DTO.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={...}` diff --git a/.claude/worktrees/goofy-haslett/prompts/general-prompt.md b/.claude/worktrees/goofy-haslett/prompts/general-prompt.md new file mode 100644 index 0000000..e8fae39 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/prompts/general-prompt.md @@ -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.` 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//...` +- `client/src/resources//...` +- `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. diff --git a/.claude/worktrees/goofy-haslett/prompts/prisma-rules.md b/.claude/worktrees/goofy-haslett/prompts/prisma-rules.md new file mode 100644 index 0000000..d5f120a --- /dev/null +++ b/.claude/worktrees/goofy-haslett/prompts/prisma-rules.md @@ -0,0 +1,145 @@ +# Prisma Rules + + + + + + + +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 ` 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: [], references: [])` + +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 diff --git a/.claude/worktrees/goofy-haslett/prompts/runtime-rules.md b/.claude/worktrees/goofy-haslett/prompts/runtime-rules.md new file mode 100644 index 0000000..114ea13 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/prompts/runtime-rules.md @@ -0,0 +1,126 @@ +# Runtime Rules + + + + + +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 diff --git a/.claude/worktrees/goofy-haslett/prompts/validation-rules.md b/.claude/worktrees/goofy-haslett/prompts/validation-rules.md new file mode 100644 index 0000000..b09098b --- /dev/null +++ b/.claude/worktrees/goofy-haslett/prompts/validation-rules.md @@ -0,0 +1,100 @@ +# Validation Rules + + + + + +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 diff --git a/server/.env.example b/.claude/worktrees/goofy-haslett/server/.env.example similarity index 100% rename from server/.env.example rename to .claude/worktrees/goofy-haslett/server/.env.example diff --git a/server/.gitignore b/.claude/worktrees/goofy-haslett/server/.gitignore similarity index 100% rename from server/.gitignore rename to .claude/worktrees/goofy-haslett/server/.gitignore diff --git a/server/.prettierrc b/.claude/worktrees/goofy-haslett/server/.prettierrc similarity index 100% rename from server/.prettierrc rename to .claude/worktrees/goofy-haslett/server/.prettierrc diff --git a/server/Dockerfile b/.claude/worktrees/goofy-haslett/server/Dockerfile similarity index 100% rename from server/Dockerfile rename to .claude/worktrees/goofy-haslett/server/Dockerfile diff --git a/server/README.md b/.claude/worktrees/goofy-haslett/server/README.md similarity index 100% rename from server/README.md rename to .claude/worktrees/goofy-haslett/server/README.md diff --git a/server/docker-entrypoint.sh b/.claude/worktrees/goofy-haslett/server/docker-entrypoint.sh similarity index 100% rename from server/docker-entrypoint.sh rename to .claude/worktrees/goofy-haslett/server/docker-entrypoint.sh diff --git a/server/eslint.config.mjs b/.claude/worktrees/goofy-haslett/server/eslint.config.mjs similarity index 100% rename from server/eslint.config.mjs rename to .claude/worktrees/goofy-haslett/server/eslint.config.mjs diff --git a/server/nest-cli.json b/.claude/worktrees/goofy-haslett/server/nest-cli.json similarity index 100% rename from server/nest-cli.json rename to .claude/worktrees/goofy-haslett/server/nest-cli.json diff --git a/server/package-lock.json b/.claude/worktrees/goofy-haslett/server/package-lock.json similarity index 100% rename from server/package-lock.json rename to .claude/worktrees/goofy-haslett/server/package-lock.json diff --git a/server/package.json b/.claude/worktrees/goofy-haslett/server/package.json similarity index 100% rename from server/package.json rename to .claude/worktrees/goofy-haslett/server/package.json diff --git a/server/prisma/schema.prisma b/.claude/worktrees/goofy-haslett/server/prisma/schema.prisma similarity index 100% rename from server/prisma/schema.prisma rename to .claude/worktrees/goofy-haslett/server/prisma/schema.prisma diff --git a/server/prisma/seed.js b/.claude/worktrees/goofy-haslett/server/prisma/seed.js similarity index 100% rename from server/prisma/seed.js rename to .claude/worktrees/goofy-haslett/server/prisma/seed.js diff --git a/server/src/app.controller.spec.ts b/.claude/worktrees/goofy-haslett/server/src/app.controller.spec.ts similarity index 100% rename from server/src/app.controller.spec.ts rename to .claude/worktrees/goofy-haslett/server/src/app.controller.spec.ts diff --git a/server/src/app.controller.ts b/.claude/worktrees/goofy-haslett/server/src/app.controller.ts similarity index 100% rename from server/src/app.controller.ts rename to .claude/worktrees/goofy-haslett/server/src/app.controller.ts diff --git a/server/src/app.module.ts b/.claude/worktrees/goofy-haslett/server/src/app.module.ts similarity index 100% rename from server/src/app.module.ts rename to .claude/worktrees/goofy-haslett/server/src/app.module.ts diff --git a/server/src/app.service.ts b/.claude/worktrees/goofy-haslett/server/src/app.service.ts similarity index 100% rename from server/src/app.service.ts rename to .claude/worktrees/goofy-haslett/server/src/app.service.ts diff --git a/server/src/auth/auth.module.ts b/.claude/worktrees/goofy-haslett/server/src/auth/auth.module.ts similarity index 100% rename from server/src/auth/auth.module.ts rename to .claude/worktrees/goofy-haslett/server/src/auth/auth.module.ts diff --git a/server/src/auth/auth.service.ts b/.claude/worktrees/goofy-haslett/server/src/auth/auth.service.ts similarity index 100% rename from server/src/auth/auth.service.ts rename to .claude/worktrees/goofy-haslett/server/src/auth/auth.service.ts diff --git a/server/src/auth/decorators/public.decorator.ts b/.claude/worktrees/goofy-haslett/server/src/auth/decorators/public.decorator.ts similarity index 100% rename from server/src/auth/decorators/public.decorator.ts rename to .claude/worktrees/goofy-haslett/server/src/auth/decorators/public.decorator.ts diff --git a/server/src/auth/decorators/roles.decorator.ts b/.claude/worktrees/goofy-haslett/server/src/auth/decorators/roles.decorator.ts similarity index 100% rename from server/src/auth/decorators/roles.decorator.ts rename to .claude/worktrees/goofy-haslett/server/src/auth/decorators/roles.decorator.ts diff --git a/server/src/auth/guards/jwt-auth.guard.ts b/.claude/worktrees/goofy-haslett/server/src/auth/guards/jwt-auth.guard.ts similarity index 100% rename from server/src/auth/guards/jwt-auth.guard.ts rename to .claude/worktrees/goofy-haslett/server/src/auth/guards/jwt-auth.guard.ts diff --git a/server/src/auth/guards/roles.guard.ts b/.claude/worktrees/goofy-haslett/server/src/auth/guards/roles.guard.ts similarity index 100% rename from server/src/auth/guards/roles.guard.ts rename to .claude/worktrees/goofy-haslett/server/src/auth/guards/roles.guard.ts diff --git a/server/src/common/pagination.ts b/.claude/worktrees/goofy-haslett/server/src/common/pagination.ts similarity index 100% rename from server/src/common/pagination.ts rename to .claude/worktrees/goofy-haslett/server/src/common/pagination.ts diff --git a/server/src/health/health.controller.ts b/.claude/worktrees/goofy-haslett/server/src/health/health.controller.ts similarity index 100% rename from server/src/health/health.controller.ts rename to .claude/worktrees/goofy-haslett/server/src/health/health.controller.ts diff --git a/server/src/health/health.module.ts b/.claude/worktrees/goofy-haslett/server/src/health/health.module.ts similarity index 100% rename from server/src/health/health.module.ts rename to .claude/worktrees/goofy-haslett/server/src/health/health.module.ts diff --git a/server/src/main.ts b/.claude/worktrees/goofy-haslett/server/src/main.ts similarity index 100% rename from server/src/main.ts rename to .claude/worktrees/goofy-haslett/server/src/main.ts diff --git a/server/src/modules/change-equipment-status/change-equipment-status.controller.ts b/.claude/worktrees/goofy-haslett/server/src/modules/change-equipment-status/change-equipment-status.controller.ts similarity index 100% rename from server/src/modules/change-equipment-status/change-equipment-status.controller.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/change-equipment-status/change-equipment-status.controller.ts diff --git a/server/src/modules/change-equipment-status/change-equipment-status.module.ts b/.claude/worktrees/goofy-haslett/server/src/modules/change-equipment-status/change-equipment-status.module.ts similarity index 100% rename from server/src/modules/change-equipment-status/change-equipment-status.module.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/change-equipment-status/change-equipment-status.module.ts diff --git a/server/src/modules/change-equipment-status/change-equipment-status.service.ts b/.claude/worktrees/goofy-haslett/server/src/modules/change-equipment-status/change-equipment-status.service.ts similarity index 100% rename from server/src/modules/change-equipment-status/change-equipment-status.service.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/change-equipment-status/change-equipment-status.service.ts diff --git a/server/src/modules/change-equipment-status/dto/create-change-equipment-status.dto.ts b/.claude/worktrees/goofy-haslett/server/src/modules/change-equipment-status/dto/create-change-equipment-status.dto.ts similarity index 100% rename from server/src/modules/change-equipment-status/dto/create-change-equipment-status.dto.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/change-equipment-status/dto/create-change-equipment-status.dto.ts diff --git a/server/src/modules/change-equipment-status/dto/update-change-equipment-status.dto.ts b/.claude/worktrees/goofy-haslett/server/src/modules/change-equipment-status/dto/update-change-equipment-status.dto.ts similarity index 100% rename from server/src/modules/change-equipment-status/dto/update-change-equipment-status.dto.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/change-equipment-status/dto/update-change-equipment-status.dto.ts diff --git a/server/src/modules/equipment-status-change/dto/create-equipment-status-change.dto.ts b/.claude/worktrees/goofy-haslett/server/src/modules/equipment-status-change/dto/create-equipment-status-change.dto.ts similarity index 100% rename from server/src/modules/equipment-status-change/dto/create-equipment-status-change.dto.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/equipment-status-change/dto/create-equipment-status-change.dto.ts diff --git a/server/src/modules/equipment-status-change/dto/update-equipment-status-change.dto.ts b/.claude/worktrees/goofy-haslett/server/src/modules/equipment-status-change/dto/update-equipment-status-change.dto.ts similarity index 100% rename from server/src/modules/equipment-status-change/dto/update-equipment-status-change.dto.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/equipment-status-change/dto/update-equipment-status-change.dto.ts diff --git a/server/src/modules/equipment-status-change/equipment-status-change.controller.ts b/.claude/worktrees/goofy-haslett/server/src/modules/equipment-status-change/equipment-status-change.controller.ts similarity index 100% rename from server/src/modules/equipment-status-change/equipment-status-change.controller.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/equipment-status-change/equipment-status-change.controller.ts diff --git a/server/src/modules/equipment-status-change/equipment-status-change.module.ts b/.claude/worktrees/goofy-haslett/server/src/modules/equipment-status-change/equipment-status-change.module.ts similarity index 100% rename from server/src/modules/equipment-status-change/equipment-status-change.module.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/equipment-status-change/equipment-status-change.module.ts diff --git a/server/src/modules/equipment-status-change/equipment-status-change.service.ts b/.claude/worktrees/goofy-haslett/server/src/modules/equipment-status-change/equipment-status-change.service.ts similarity index 100% rename from server/src/modules/equipment-status-change/equipment-status-change.service.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/equipment-status-change/equipment-status-change.service.ts diff --git a/server/src/modules/equipment/dto/create-equipment.dto.ts b/.claude/worktrees/goofy-haslett/server/src/modules/equipment/dto/create-equipment.dto.ts similarity index 100% rename from server/src/modules/equipment/dto/create-equipment.dto.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/equipment/dto/create-equipment.dto.ts diff --git a/server/src/modules/equipment/dto/update-equipment.dto.ts b/.claude/worktrees/goofy-haslett/server/src/modules/equipment/dto/update-equipment.dto.ts similarity index 100% rename from server/src/modules/equipment/dto/update-equipment.dto.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/equipment/dto/update-equipment.dto.ts diff --git a/server/src/modules/equipment/equipment.controller.ts b/.claude/worktrees/goofy-haslett/server/src/modules/equipment/equipment.controller.ts similarity index 100% rename from server/src/modules/equipment/equipment.controller.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/equipment/equipment.controller.ts diff --git a/server/src/modules/equipment/equipment.module.ts b/.claude/worktrees/goofy-haslett/server/src/modules/equipment/equipment.module.ts similarity index 100% rename from server/src/modules/equipment/equipment.module.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/equipment/equipment.module.ts diff --git a/server/src/modules/equipment/equipment.service.ts b/.claude/worktrees/goofy-haslett/server/src/modules/equipment/equipment.service.ts similarity index 100% rename from server/src/modules/equipment/equipment.service.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/equipment/equipment.service.ts diff --git a/server/src/modules/shared/equipment-status.enum.ts b/.claude/worktrees/goofy-haslett/server/src/modules/shared/equipment-status.enum.ts similarity index 100% rename from server/src/modules/shared/equipment-status.enum.ts rename to .claude/worktrees/goofy-haslett/server/src/modules/shared/equipment-status.enum.ts diff --git a/server/src/prisma/prisma.module.ts b/.claude/worktrees/goofy-haslett/server/src/prisma/prisma.module.ts similarity index 100% rename from server/src/prisma/prisma.module.ts rename to .claude/worktrees/goofy-haslett/server/src/prisma/prisma.module.ts diff --git a/server/src/prisma/prisma.service.ts b/.claude/worktrees/goofy-haslett/server/src/prisma/prisma.service.ts similarity index 100% rename from server/src/prisma/prisma.service.ts rename to .claude/worktrees/goofy-haslett/server/src/prisma/prisma.service.ts diff --git a/server/test/app.e2e-spec.ts b/.claude/worktrees/goofy-haslett/server/test/app.e2e-spec.ts similarity index 100% rename from server/test/app.e2e-spec.ts rename to .claude/worktrees/goofy-haslett/server/test/app.e2e-spec.ts diff --git a/server/test/jest-e2e.json b/.claude/worktrees/goofy-haslett/server/test/jest-e2e.json similarity index 100% rename from server/test/jest-e2e.json rename to .claude/worktrees/goofy-haslett/server/test/jest-e2e.json diff --git a/server/tsconfig.build.json b/.claude/worktrees/goofy-haslett/server/tsconfig.build.json similarity index 100% rename from server/tsconfig.build.json rename to .claude/worktrees/goofy-haslett/server/tsconfig.build.json diff --git a/server/tsconfig.json b/.claude/worktrees/goofy-haslett/server/tsconfig.json similarity index 100% rename from server/tsconfig.json rename to .claude/worktrees/goofy-haslett/server/tsconfig.json diff --git a/.claude/worktrees/goofy-haslett/toir-realm.json b/.claude/worktrees/goofy-haslett/toir-realm.json new file mode 100644 index 0000000..bae772d --- /dev/null +++ b/.claude/worktrees/goofy-haslett/toir-realm.json @@ -0,0 +1,172 @@ +{ + "realm": "toir", + "enabled": true, + "displayName": "TOIR", + "sslRequired": "external", + "registrationAllowed": false, + "registrationEmailAsUsername": false, + "loginWithEmailAllowed": true, + "duplicateEmailsAllowed": false, + "resetPasswordAllowed": true, + "rememberMe": true, + "verifyEmail": false, + "roles": { + "realm": [ + { + "name": "admin", + "description": "Full administrative access" + }, + { + "name": "editor", + "description": "Can create and modify data" + }, + { + "name": "viewer", + "description": "Read-only access" + } + ] + }, + "clientScopes": [ + { + "name": "api-audience", + "description": "Adds backend audience to SPA access token", + "protocol": "openid-connect", + "attributes": { + "display.on.consent.screen": "false", + "include.in.token.scope": "false" + }, + "protocolMappers": [ + { + "name": "aud-toir-backend", + "protocol": "openid-connect", + "protocolMapper": "oidc-audience-mapper", + "consentRequired": false, + "config": { + "included.client.audience": "toir-backend", + "id.token.claim": "false", + "access.token.claim": "true", + "introspection.token.claim": "true" + } + } + ] + } + ], + "clients": [ + { + "clientId": "toir-frontend", + "name": "toir-frontend", + "description": "Frontend SPA client", + "enabled": true, + "protocol": "openid-connect", + "publicClient": true, + "bearerOnly": false, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "fullScopeAllowed": true, + "rootUrl": "https://toir-frontend.greact.ru", + "baseUrl": "https://toir-frontend.greact.ru", + "redirectUris": [ + "https://toir-frontend.greact.ru/*", + "http://localhost:5173/*" + ], + "webOrigins": [ + "https://toir-frontend.greact.ru", + "http://localhost:5173" + ], + "attributes": { + "pkce.code.challenge.method": "S256" + }, + "defaultClientScopes": [ + "api-audience" + ], + "optionalClientScopes": [ + "offline_access" + ], + "protocolMappers": [ + { + "name": "sub", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-property-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "id", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "sub", + "jsonType.label": "String" + } + }, + { + "name": "preferred_username", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-property-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "username", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "preferred_username", + "jsonType.label": "String" + } + }, + { + "name": "email", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-property-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "email", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "email", + "jsonType.label": "String" + } + }, + { + "name": "name", + "protocol": "openid-connect", + "protocolMapper": "oidc-full-name-mapper", + "consentRequired": false, + "config": { + "id.token.claim": "true", + "access.token.claim": "true", + "userinfo.token.claim": "true" + } + }, + { + "name": "realm roles", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-realm-role-mapper", + "consentRequired": false, + "config": { + "multivalued": "true", + "userinfo.token.claim": "true", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "realm_access.roles", + "jsonType.label": "String" + } + } + ] + }, + { + "clientId": "toir-backend", + "name": "toir-backend", + "description": "Backend API resource server", + "enabled": true, + "protocol": "openid-connect", + "publicClient": false, + "bearerOnly": true, + "standardFlowEnabled": false, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "fullScopeAllowed": false + } + ] +} diff --git a/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/README.md b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/README.md new file mode 100644 index 0000000..5ce3a31 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/README.md @@ -0,0 +1,78 @@ +# api-format → OpenAPI 3.0 + +Абстрактная заготовка под задачу: **из доменного описания API получить OpenAPI 3.0**, затем встроить в общий пайплайн (кнопка / CI / генератор). + +## Что внутри + +| Файл | Назначение | +|------|------------| +| `examples/api-format.example.json` | Пример **не-OpenAPI** формата: ресурсы, поля, операции, query для списка | +| `prompts/llm-system.md` | Системный промпт для LLM: «верни только JSON OpenAPI 3.0.3» | +| `convert.mjs` | CLI: режим `deterministic` (маппинг в коде) и `llm` (OpenAI API) | + +## Пошаговая демонстрация в терминале + +Чтобы **постепенно** увидеть: входной api-format → что делает конвертер → структура OpenAPI: + +```bash +cd tools/api-format-to-openapi +npm run demo +``` + +С паузой после каждого шага (нажимай Enter): + +```bash +npm run demo:pause +``` + +Результат кладётся в `demo-output/openapi.json`. + +## Детерминированный режим (без LLM) + +Подходит для **фиксированной** схемы `apiFormatVersion: "1"` как в примере. + +```bash +cd tools/api-format-to-openapi +node convert.mjs --in examples/api-format.example.json --out ../../openapi.generated.json +``` + +Или через npm: + +```bash +cd tools/api-format-to-openapi +npm run convert +``` + +## Режим LLM + +Когда реальный формат отличается или богаче — прогон через модель с промптом из `prompts/llm-system.md`. + +```bash +set OPENAI_API_KEY=sk-... +cd tools/api-format-to-openapi +node convert.mjs --mode llm --in path/to/your-api-format.json --out ../../openapi.llm.json +``` + +Переменные: + +- `OPENAI_API_KEY` — обязательно +- `OPENAI_MODEL` — по умолчанию `gpt-4o-mini` +- `OPENAI_BASE_URL` — по умолчанию `https://api.openai.com/v1` (совместимо с прокси) + +## HTTP-экспортёр для AID (NestJS) + +В `server` добавлен модуль **`AidExportModule`**: `POST /aid/export/openapi` принимает `{ "apiFormat": {...}, "mode"?: "deterministic"|"llm" }` и возвращает `{ "openapi": {...} }`. Подробности: `server/src/aid-export/README.md`. + +## Интеграция позже + +1. Заменить/расширить `examples/api-format.example.json` под ваш настоящий контракт из «алабужского» гита. +2. Либо расширить `toOpenApiDeterministic` в `convert.mjs`, либо перейти на `--mode llm` с отточенным промптом. +3. Согласовать с AID точный URL, заголовки и (при необходимости) обёртку ответа; при необходимости добавить отдельный маршрут «сырой» OpenAPI без `{ openapi: ... }`. + +## Валидация OpenAPI (опционально) + +После генерации можно проверить спеку любым валидатором, например: + +```bash +npx -y @apidevtools/swagger-cli validate ../../openapi.generated.json +``` diff --git a/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/convert.mjs b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/convert.mjs new file mode 100644 index 0000000..855ade0 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/convert.mjs @@ -0,0 +1,341 @@ +#!/usr/bin/env node +/** + * api-format → OpenAPI 3.0 + * + * Режимы: + * --mode deterministic — маппинг только для схемы examples/api-format.example.json (и совместимых) + * --mode llm — отправка входного JSON в OpenAI Chat Completions (нужен OPENAI_API_KEY) + * + * Примеры: + * node convert.mjs --in examples/api-format.example.json --out ../../openapi.generated.json + * node convert.mjs --mode llm --in my-api.json --out openapi.json + */ + +import { readFileSync, writeFileSync, mkdirSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +function parseArgs(argv) { + const out = { mode: "deterministic", input: null, output: null }; + for (let i = 2; i < argv.length; i++) { + const a = argv[i]; + if (a === "--mode") out.mode = argv[++i]; + else if (a === "--in") out.input = argv[++i]; + else if (a === "--out") out.output = argv[++i]; + else if (a === "-h" || a === "--help") out.help = true; + } + return out; +} + +function usage() { + console.log(` +Usage: node convert.mjs --in --out [--mode deterministic|llm] + +Environment (llm mode): + OPENAI_API_KEY required + OPENAI_MODEL optional, default gpt-4o-mini + OPENAI_BASE_URL optional, default https://api.openai.com/v1 +`); +} + +/** @param {string} t */ +function fieldToSchema(t) { + const map = { + string: { type: "string" }, + uuid: { type: "string", format: "uuid" }, + int: { type: "integer" }, + integer: { type: "integer" }, + number: { type: "number" }, + float: { type: "number" }, + boolean: { type: "boolean" }, + date: { type: "string", format: "date" }, + datetime: { type: "string", format: "date-time" }, + }; + return map[t] || { type: "string", description: `unknown type: ${t}` }; +} + +/** + * Детерминированная конвертация для apiFormatVersion "1" с полями как в example. + * @param {any} api + */ +function toOpenApiDeterministic(api) { + if (!api || api.apiFormatVersion !== "1") { + throw new Error( + 'deterministic mode: ожидается apiFormatVersion "1". Для другого формата используйте --mode llm или расширьте маппинг в convert.mjs.', + ); + } + + const base = (api.server?.basePath || "/api").replace(/\/$/, ""); + const info = api.info || { title: "API", version: "1.0.0" }; + const paths = {}; + const schemas = {}; + + for (const res of api.resources || []) { + const name = res.name; + const seg = res.pathSegment || name.toLowerCase(); + const idParam = res.idParam || "id"; + const idType = res.idType || "uuid"; + + const props = {}; + const required = []; + for (const f of res.fields || []) { + let sch; + if (f.type === "enum" && Array.isArray(f.enumValues)) { + sch = { type: "string", enum: f.enumValues }; + } else { + sch = { ...fieldToSchema(f.type) }; + } + if (f.readOnly) sch.readOnly = true; + props[f.name] = sch; + if (f.required) required.push(f.name); + } + + schemas[name] = { + type: "object", + properties: props, + ...(required.length ? { required } : {}), + }; + + const listPath = `${base}/${seg}`; + const itemPath = `${base}/${seg}/{${idParam}}`; + const idSchema = fieldToSchema(idType); + + const listQuery = []; + const lq = res.listQuery; + if (lq?.pagination) { + for (const p of lq.pagination) { + if (p === "_start" || p === "_end") + listQuery.push({ name: p, in: "query", schema: { type: "integer" }, description: "pagination" }); + } + } + if (lq?.sort) { + for (const p of lq.sort) { + if (p === "_sort") + listQuery.push({ name: "_sort", in: "query", schema: { type: "string" }, description: "sort field" }); + if (p === "_order") + listQuery.push({ + name: "_order", + in: "query", + schema: { type: "string", enum: ["asc", "desc"] }, + description: "sort order", + }); + } + } + if (lq?.filters) { + for (const p of lq.filters) { + if (p === "q") + listQuery.push({ name: "q", in: "query", schema: { type: "string" }, description: "full-text search" }); + else { + const field = (res.fields || []).find((x) => x.name === p); + const isEnum = field?.type === "enum"; + listQuery.push({ + name: p, + in: "query", + schema: isEnum + ? { type: "array", items: { type: "string", enum: field.enumValues || [] } } + : { type: "string" }, + style: isEnum ? "form" : undefined, + explode: isEnum ? true : undefined, + description: isEnum ? "repeat param for multiple values" : undefined, + }); + } + } + } + + const ops = new Set(res.operations || []); + + if (ops.has("list")) { + paths[listPath] = paths[listPath] || {}; + paths[listPath].get = { + tags: [name], + summary: `List ${name}`, + parameters: listQuery, + responses: { + "200": { + description: "OK", + content: { + "application/json": { + schema: { + type: "object", + properties: { + data: { type: "array", items: { $ref: `#/components/schemas/${name}` } }, + total: { type: "integer" }, + }, + }, + }, + }, + }, + }, + }; + } + + if (ops.has("create")) { + paths[listPath] = paths[listPath] || {}; + paths[listPath].post = { + tags: [name], + summary: `Create ${name}`, + requestBody: { + required: true, + content: { "application/json": { schema: { $ref: `#/components/schemas/${name}` } } }, + }, + responses: { + "201": { + description: "Created", + content: { "application/json": { schema: { $ref: `#/components/schemas/${name}` } } }, + }, + "400": { description: "Bad request" }, + }, + }; + } + + if (ops.has("get")) { + paths[itemPath] = paths[itemPath] || {}; + paths[itemPath].get = { + tags: [name], + summary: `Get ${name} by ${idParam}`, + parameters: [{ name: idParam, in: "path", required: true, schema: idSchema }], + responses: { + "200": { + description: "OK", + content: { "application/json": { schema: { $ref: `#/components/schemas/${name}` } } }, + }, + "404": { description: "Not found" }, + }, + }; + } + + if (ops.has("update")) { + paths[itemPath] = paths[itemPath] || {}; + paths[itemPath].patch = { + tags: [name], + summary: `Update ${name}`, + parameters: [{ name: idParam, in: "path", required: true, schema: idSchema }], + requestBody: { + content: { "application/json": { schema: { $ref: `#/components/schemas/${name}` } } }, + }, + responses: { + "200": { + description: "OK", + content: { "application/json": { schema: { $ref: `#/components/schemas/${name}` } } }, + }, + "404": { description: "Not found" }, + }, + }; + } + + if (ops.has("delete")) { + paths[itemPath] = paths[itemPath] || {}; + paths[itemPath].delete = { + tags: [name], + summary: `Delete ${name}`, + parameters: [{ name: idParam, in: "path", required: true, schema: idSchema }], + responses: { + "204": { description: "No content" }, + "404": { description: "Not found" }, + }, + }; + } + } + + const doc = { + openapi: "3.0.3", + info: { + title: info.title, + version: info.version, + ...(info.description ? { description: info.description } : {}), + }, + servers: [{ url: base || "/" }], + paths, + components: { + schemas, + ...(api.security?.type === "bearer" || api.security?.scheme === "JWT" + ? { + securitySchemes: { + bearerAuth: { type: "http", scheme: "bearer", bearerFormat: "JWT" }, + }, + } + : {}), + }, + }; + + if (doc.components.securitySchemes) { + doc.security = [{ bearerAuth: [] }]; + for (const method of Object.values(paths)) { + for (const op of Object.values(method)) { + if (op && typeof op === "object" && op.responses) op.security = [{ bearerAuth: [] }]; + } + } + } + + return doc; +} + +async function toOpenApiLlm(apiJson) { + const key = process.env.OPENAI_API_KEY; + if (!key) throw new Error("OPENAI_API_KEY не задан"); + + const model = process.env.OPENAI_MODEL || "gpt-4o-mini"; + const baseUrl = (process.env.OPENAI_BASE_URL || "https://api.openai.com/v1").replace(/\/$/, ""); + const systemPath = resolve(__dirname, "prompts", "llm-system.md"); + const system = readFileSync(systemPath, "utf8"); + const user = JSON.stringify(apiJson, null, 2); + + const res = await fetch(`${baseUrl}/chat/completions`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${key}`, + }, + body: JSON.stringify({ + model, + temperature: 0.1, + messages: [ + { role: "system", content: system }, + { role: "user", content: `Преобразуй следующий api-format в OpenAPI 3.0.3 JSON:\n\n${user}` }, + ], + }), + }); + + if (!res.ok) { + const text = await res.text(); + throw new Error(`OpenAI HTTP ${res.status}: ${text}`); + } + + const data = await res.json(); + const content = data.choices?.[0]?.message?.content; + if (!content) throw new Error("Пустой ответ от модели"); + + const trimmed = content.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, ""); + return JSON.parse(trimmed); +} + +async function main() { + const args = parseArgs(process.argv); + if (args.help || !args.input || !args.output) { + usage(); + process.exit(args.help ? 0 : 1); + } + + const inputPath = resolve(process.cwd(), args.input); + const outputPath = resolve(process.cwd(), args.output); + const raw = readFileSync(inputPath, "utf8"); + const api = JSON.parse(raw); + + let openapi; + if (args.mode === "llm") { + openapi = await toOpenApiLlm(api); + } else { + openapi = toOpenApiDeterministic(api); + } + + mkdirSync(dirname(outputPath), { recursive: true }); + writeFileSync(outputPath, JSON.stringify(openapi, null, 2), "utf8"); + console.log(`Written: ${outputPath}`); +} + +main().catch((e) => { + console.error(e.message || e); + process.exit(1); +}); diff --git a/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/demo-steps.mjs b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/demo-steps.mjs new file mode 100644 index 0000000..38865fe --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/demo-steps.mjs @@ -0,0 +1,117 @@ +#!/usr/bin/env node +/** + * Пошаговая демонстрация: api-format → OpenAPI 3.0 (детерминированный режим). + * + * node demo-steps.mjs — все шаги подряд в консоли + * node demo-steps.mjs --pause — пауза после каждого шага (Enter) + * + * Результат также пишется в demo-output/openapi.json рядом со скриптом. + */ + +import { execFileSync } from "node:child_process"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { createInterface } from "node:readline/promises"; +import { stdin as input, stdout as output } from "node:process"; +import { fileURLToPath } from "node:url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const EXAMPLE = join(__dirname, "examples", "api-format.example.json"); +const OUT_DIR = join(__dirname, "demo-output"); +const OUT_OPENAPI = join(OUT_DIR, "openapi.json"); +const usePause = process.argv.includes("--pause"); + +function banner(title) { + const line = "═".repeat(Math.min(60, title.length + 8)); + console.log(`\n${line}\n ${title}\n${line}\n`); +} + +async function pause(msg = "Нажми Enter, чтобы перейти к следующему шагу…") { + if (!usePause) return; + const rl = createInterface({ input, output }); + await rl.question(msg); + rl.close(); +} + +async function main() { + console.clear?.(); + + banner("Шаг 0. Задача"); + console.log( + "У нас есть описание API в СВОЁМ формате (api-format), не OpenAPI.\n" + + "Нужно получить стандартную спецификацию OpenAPI 3.0 — для Swagger, клиентов, AID.\n" + + "Сейчас покажем путь на учебном примере (детерминированный маппинг в convert.mjs).", + ); + await pause(); + + banner("Шаг 1. Входной файл (фрагмент api-format)"); + console.log(`Файл: ${EXAMPLE}\n`); + const rawIn = readFileSync(EXAMPLE, "utf8"); + const apiFormat = JSON.parse(rawIn); + console.log(JSON.stringify(apiFormat, null, 2)); + console.log( + "\n↑ Это НЕ OpenAPI. Здесь: версия формата, info, basePath, ресурс Equipment с полями и операциями CRUD.", + ); + await pause(); + + banner("Шаг 2. Что делает конвертер (логика)"); + console.log(` + • apiFormatVersion "1" → включается ветка toOpenApiDeterministic в convert.mjs + • Ресурс Equipment → components.schemas.Equipment + пути /api/equipment и /api/equipment/{id} + • Поля (string, uuid, enum…) → JSON Schema в components.schemas + • listQuery → query-параметры (_start, _end, _sort, _order, q, status…) + • security bearer → components.securitySchemes + security на операциях +`); + await pause(); + + banner("Шаг 3. Запуск convert.mjs"); + mkdirSync(OUT_DIR, { recursive: true }); + const convertScript = join(__dirname, "convert.mjs"); + console.log(`Команда:\n node convert.mjs --in examples/api-format.example.json --out demo-output/openapi.json\n`); + execFileSync(process.execPath, [convertScript, "--in", EXAMPLE, "--out", OUT_OPENAPI], { + stdio: "inherit", + }); + console.log(`\nГотово. Файл: ${OUT_OPENAPI}`); + await pause(); + + banner("Шаг 4. Результат — структура OpenAPI"); + const spec = JSON.parse(readFileSync(OUT_OPENAPI, "utf8")); + console.log(`openapi: ${spec.openapi}`); + console.log(`title: ${spec.info?.title}`); + console.log(`version: ${spec.info?.version}`); + console.log("\nПути (paths):"); + for (const p of Object.keys(spec.paths || {}).sort()) { + const methods = Object.keys(spec.paths[p]).join(", "); + console.log(` ${p} [${methods}]`); + } + console.log("\nСхемы (components.schemas):", Object.keys(spec.components?.schemas || {}).join(", ")); + await pause(); + + banner("Шаг 5. Фрагмент: GET список (одна операция)"); + const listPath = Object.keys(spec.paths || {}).find((k) => k.endsWith("/equipment") && !k.includes("{")); + if (listPath && spec.paths[listPath]?.get) { + console.log(JSON.stringify({ [listPath]: { get: spec.paths[listPath].get } }, null, 2)); + } else { + console.log("(путь списка не найден — открой demo-output/openapi.json)"); + } + await pause(); + + banner("Шаг 6. Как проверить дальше"); + console.log(` + 1) Открой целиком: ${OUT_OPENAPI} + 2) Валидация (из корня репозитория): + npx -y @apidevtools/swagger-cli validate tools/api-format-to-openapi/demo-output/openapi.json + 3) Через Nest (сервер на 3001): + POST http://127.0.0.1:3001/aid/export/openapi + тело: { "apiFormat": <содержимое api-format.example.json>, "mode": "deterministic" } + 4) Режим LLM (другой входной JSON): + node convert.mjs --mode llm --in your.json --out openapi.llm.json + (нужен OPENAI_API_KEY) +`); + console.log("Демо завершено.\n"); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); diff --git a/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/examples/api-format.example.json b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/examples/api-format.example.json new file mode 100644 index 0000000..056882c --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/examples/api-format.example.json @@ -0,0 +1,36 @@ +{ + "apiFormatVersion": "1", + "info": { + "title": "TOiR Demo API", + "version": "1.0.0", + "description": "Абстрактный пример доменного описания API (не OpenAPI)." + }, + "server": { + "basePath": "/api" + }, + "security": { + "type": "bearer", + "scheme": "JWT" + }, + "resources": [ + { + "name": "Equipment", + "pathSegment": "equipment", + "idParam": "id", + "idType": "uuid", + "fields": [ + { "name": "id", "type": "uuid", "readOnly": true }, + { "name": "inventoryNumber", "type": "string", "required": true }, + { "name": "name", "type": "string", "required": true }, + { "name": "status", "type": "enum", "enumValues": ["Active", "Repair", "Decommissioned"] }, + { "name": "location", "type": "string" } + ], + "operations": ["list", "get", "create", "update", "delete"], + "listQuery": { + "pagination": ["_start", "_end"], + "sort": ["_sort", "_order"], + "filters": ["q", "status"] + } + } + ] +} diff --git a/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/package.json b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/package.json new file mode 100644 index 0000000..e457ff0 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/package.json @@ -0,0 +1,12 @@ +{ + "name": "api-format-to-openapi", + "private": true, + "type": "module", + "description": "Конвертация доменного api-format в OpenAPI 3.0 (детерминированно или через LLM)", + "scripts": { + "convert": "node convert.mjs --in examples/api-format.example.json --out ../../openapi.generated.json", + "convert:llm": "node convert.mjs --mode llm --in examples/api-format.example.json --out ../../openapi.llm.json", + "demo": "node demo-steps.mjs", + "demo:pause": "node demo-steps.mjs --pause" + } +} diff --git a/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/prompts/llm-system.md b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/prompts/llm-system.md new file mode 100644 index 0000000..4b17758 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/api-format-to-openapi/prompts/llm-system.md @@ -0,0 +1,30 @@ +# Роль + +Ты конвертер доменного описания API в спецификацию **OpenAPI 3.0.3** (JSON). + +# Вход + +Пользователь пришлёт один JSON-файл в произвольном «доменном» формате (api-format). В нём могут быть сущности, поля, типы, пути, операции, фильтры, авторизация. + +# Выход + +- Верни **только** валидный JSON объекта OpenAPI 3.0.3. +- Без markdown, без комментариев, без текста до или после JSON. +- Используй `openapi: "3.0.3"`. +- Опиши `info`, `servers`, при необходимости `tags`. +- Для каждой сущности/ресурса создай `components.schemas` и `paths` с типичными REST-операциями, если они указаны. +- Типы полей маппь так: + - `string` → `type: string` + - `uuid` → `type: string`, `format: uuid` + - `int` / `integer` → `type: integer` + - `number` / `float` → `type: number` + - `boolean` → `type: boolean` + - `date` / `datetime` → `type: string`, `format: date` или `date-time` + - `enum` + список значений → `type: string`, `enum: [...]` +- Для списков с пагинацией добавь query-параметры из входа (`_start`, `_end`, `_sort`, `_order`, фильтры). +- Для `401/403/404/500` добавь минимальные `responses` с `description`. +- Если во входе указана Bearer/JWT — добавь `components.securitySchemes` и `security` на путях или глобально. + +# Если чего-то не хватает + +Делай разумные допущения и кратко отражай их в `info.description` одним предложением. diff --git a/.claude/worktrees/goofy-haslett/tools/api-summary-to-openapi.mjs b/.claude/worktrees/goofy-haslett/tools/api-summary-to-openapi.mjs new file mode 100644 index 0000000..278e2f8 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/api-summary-to-openapi.mjs @@ -0,0 +1,301 @@ +// Deterministic OpenAPI 3.0.3 generator from api-summary.json / toir.api.dsl. +// +// This script is part of the Tier 1 deterministic preprocessing layer. +// It converts the canonical api-summary (produced by tools/api-summary.mjs) +// into a valid OpenAPI 3.0.3 document. +// +// Usage: +// node tools/api-summary-to-openapi.mjs --out openapi.json +// npm run generate:openapi +// +// No LLM involvement. The output is reproducible from DSL + this script alone. + +import { writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { buildApiSummary } from './api-summary.mjs'; + +const rootDir = process.cwd(); + +// --------------------------------------------------------------------------- +// DSL scalar → OpenAPI type +// --------------------------------------------------------------------------- + +function dslTypeToOpenApi(dslType) { + switch (dslType) { + case 'uuid': + return { type: 'string', format: 'uuid' }; + case 'string': + return { type: 'string' }; + case 'text': + return { type: 'string' }; + case 'integer': + return { type: 'integer', format: 'int32' }; + case 'number': + return { type: 'number' }; + case 'decimal': + return { type: 'string', format: 'decimal' }; + case 'date': + return { type: 'string', format: 'date-time' }; + case 'boolean': + return { type: 'boolean' }; + default: + // enum names and DTO references handled by caller + return null; + } +} + +// --------------------------------------------------------------------------- +// Resolve a DSL field type to an OpenAPI schema reference or inline schema. +// dtoNames — Set of known DTO names in the api summary. +// enumNames — Set of known enum names (derived from type mappings table). +// --------------------------------------------------------------------------- + +function resolveFieldType(dslType, dtoNames, enumNames) { + if (!dslType) return { type: 'object' }; + + // Array type: "DTO.Foo[]" + if (dslType.endsWith('[]')) { + const inner = dslType.slice(0, -2); + return { type: 'array', items: resolveFieldType(inner, dtoNames, enumNames) }; + } + + // Scalar + const scalar = dslTypeToOpenApi(dslType); + if (scalar) return scalar; + + // DTO reference + if (dtoNames.has(dslType)) { + return { $ref: `#/components/schemas/${dslType.replace(/^DTO\./, '')}` }; + } + + // Enum reference + if (enumNames.has(dslType)) { + return { $ref: `#/components/schemas/${dslType}` }; + } + + // Unknown — emit as string with x-dsl-type annotation + return { type: 'string', 'x-dsl-type': dslType }; +} + +// --------------------------------------------------------------------------- +// Build OpenAPI schema object from a DTO definition +// --------------------------------------------------------------------------- + +function buildDtoSchema(dto, dtoNames, enumNames) { + const properties = {}; + const required = []; + + for (const field of dto.fields) { + const schema = resolveFieldType(field.type, dtoNames, enumNames); + if (field.description && schema.$ref) { + // OpenAPI 3.0.3: $ref cannot have sibling keys — wrap with allOf + properties[field.name] = { allOf: [schema], description: field.description }; + } else { + if (field.description) schema.description = field.description; + properties[field.name] = schema; + } + if (field.required) required.push(field.name); + } + + const schema = { + type: 'object', + properties, + }; + + if (dto.description) schema.description = dto.description; + if (required.length > 0) schema.required = required; + + return schema; +} + +// --------------------------------------------------------------------------- +// Convert DSL HTTP method to OpenAPI method key +// --------------------------------------------------------------------------- + +function methodKey(method) { + return (method ?? 'get').toLowerCase(); +} + +// --------------------------------------------------------------------------- +// Build OpenAPI path item for an endpoint +// --------------------------------------------------------------------------- + +function buildPathOperation(endpoint, apiDescription, dtoNames, enumNames) { + const operation = {}; + + if (endpoint.description) operation.summary = endpoint.description; + + // Security — all endpoints require bearer auth + operation.security = [{ bearerAuth: [] }]; + + // Tags — derive from API name or path + const tag = apiDescription ? apiDescription.replace(/^API управления\s+/i, '').replace(/ами$/, '') : undefined; + if (tag) operation.tags = [tag]; + + // Parameters — detect path params by matching attribute names against {param} in the path + const pathTemplate = endpoint.path ?? ''; + const pathParamNames = new Set( + [...pathTemplate.matchAll(/\{(\w+)\}/g)].map((m) => m[1]), + ); + const pathParams = endpoint.attributes.filter((a) => pathParamNames.has(a.name)); + if (pathParams.length > 0) { + operation.parameters = pathParams.map((p) => ({ + name: p.name, + in: 'path', + required: true, + schema: resolveFieldType(p.type, dtoNames, enumNames), + ...(p.description ? { description: p.description } : {}), + })); + } + + // Request body + const requestAttr = endpoint.attributes.find((a) => a.name === 'request'); + if (requestAttr) { + operation.requestBody = { + required: true, + content: { + 'application/json': { + schema: resolveFieldType(requestAttr.type, dtoNames, enumNames), + }, + }, + }; + } + + // Response + const responseAttr = endpoint.attributes.find((a) => a.name === 'response'); + const responseSchema = responseAttr + ? resolveFieldType(responseAttr.type, dtoNames, enumNames) + : { type: 'object' }; + + const successCode = endpoint.method === 'POST' && !endpoint.path?.endsWith('/page') ? '201' : '200'; + + operation.responses = { + [successCode]: { + description: 'Success', + content: { + 'application/json': { + schema: responseSchema, + }, + }, + }, + '401': { description: 'Unauthorized' }, + '403': { description: 'Forbidden' }, + }; + + if (endpoint.method === 'DELETE') { + operation.responses = { + '204': { description: 'No content' }, + '401': { description: 'Unauthorized' }, + '403': { description: 'Forbidden' }, + '404': { description: 'Not found' }, + }; + delete operation.responses['201']; + } + + return operation; +} + +// --------------------------------------------------------------------------- +// Main builder +// --------------------------------------------------------------------------- + +function buildOpenApi(summary) { + const dtoNames = new Set(summary.dtos.map((d) => d.name)); + + // Build enum map from api-summary enums block (fully declared enums with values) + const enumMap = new Map((summary.enums ?? []).map((e) => [e.name, e])); + + // Also collect enum names referenced in DTO fields that are not in the declared enums + // (covers cases where enums are declared in domain.dsl but referenced in api.dsl) + const enumNames = new Set(enumMap.keys()); + for (const dto of summary.dtos) { + for (const field of dto.fields) { + const t = field.type?.replace('[]', ''); + if (t && !dtoNames.has(t) && !dslTypeToOpenApi(t)) { + enumNames.add(t); + } + } + } + + // Schemas — one per DTO + const schemas = {}; + for (const dto of summary.dtos) { + const schemaName = dto.name.replace(/^DTO\./, ''); + schemas[schemaName] = buildDtoSchema(dto, dtoNames, enumNames); + } + + // Enum schemas — use actual values when available, otherwise annotate as opaque string enum + for (const enumName of enumNames) { + const enumDef = enumMap.get(enumName); + if (enumDef && enumDef.values.length > 0) { + schemas[enumName] = { + type: 'string', + enum: enumDef.values.map((v) => v.name), + 'x-enum-labels': Object.fromEntries( + enumDef.values.filter((v) => v.label).map((v) => [v.name, v.label]), + ), + ...(enumDef.description ? { description: enumDef.description } : {}), + }; + } else { + schemas[enumName] = { + type: 'string', + 'x-dsl-enum': enumName, + description: `Enum: ${enumName} (values defined in domain/*.api.dsl)`, + }; + } + } + + // Paths + const paths = {}; + for (const api of summary.apis) { + for (const endpoint of api.endpoints) { + if (!endpoint.path) continue; + const pathKey = endpoint.path; + if (!paths[pathKey]) paths[pathKey] = {}; + const opKey = methodKey(endpoint.method); + paths[pathKey][opKey] = buildPathOperation(endpoint, api.description, dtoNames, enumNames); + } + } + + return { + 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, + }, + paths, + }; +} + +// --------------------------------------------------------------------------- +// CLI +// --------------------------------------------------------------------------- + +const args = process.argv.slice(2); +const outIndex = args.indexOf('--out'); +const outPath = outIndex !== -1 ? args[outIndex + 1] : 'openapi.json'; + +const summary = buildApiSummary(rootDir); +const openApiDoc = buildOpenApi(summary); +const outputPath = path.resolve(rootDir, outPath); + +writeFileSync(outputPath, `${JSON.stringify(openApiDoc, null, 2)}\n`, 'utf8'); +console.log(`Generated ${path.relative(rootDir, outputPath)}`); diff --git a/.claude/worktrees/goofy-haslett/tools/api-summary.mjs b/.claude/worktrees/goofy-haslett/tools/api-summary.mjs new file mode 100644 index 0000000..b5e2279 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/api-summary.mjs @@ -0,0 +1,389 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function stripInlineComment(line) { + let inString = false; + let result = ''; + + for (let index = 0; index < line.length; index += 1) { + const current = line[index]; + const next = line[index + 1]; + + if (current === '"' && line[index - 1] !== '\\') { + inString = !inString; + result += current; + continue; + } + + if (!inString && current === '/' && next === '/') { + break; + } + + result += current; + } + + return result.trim(); +} + +// --------------------------------------------------------------------------- +// File discovery +// --------------------------------------------------------------------------- + +export function getApiDslFiles(rootDir) { + const domainDir = path.join(rootDir, 'domain'); + try { + return readdirSync(domainDir, { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith('.api.dsl')) + .map((entry) => path.join(domainDir, entry.name)) + .sort((left, right) => left.localeCompare(right)); + } catch { + return []; + } +} + +// --------------------------------------------------------------------------- +// Parser +// +// Parses all *.api.dsl files using a stack-based approach. +// This is the single canonical parser for the API DSL. +// +// Supported top-level blocks: +// enum { description?; value { label?; } } +// dto DTO. { description?; attribute { ... } } +// api API. { description?; endpoint { ... } } +// +// DTO attribute modifiers (any order inside the attribute block): +// type ; +// description "..."; +// map Entity.field; +// sync Entity.field; (alias for map — used for computed/aggregate fields) +// is required; +// is nullable; +// is unique; +// key primary; +// label "..."; +// +// Endpoint modifiers: +// label "METHOD /path"; +// description "..."; +// attribute { type ; description?; } +// +// Returns: +// { +// files: string[], +// enums: EnumBlock[], +// dtos: DtoBlock[], +// apis: ApiBlock[], +// } +// +// EnumBlock = { name, description, values: EnumValue[] } +// EnumValue = { name, label } +// DtoBlock = { name, description, fields: DtoField[] } +// DtoField = { name, type, required, nullable, unique, primary, description, map, label } +// ApiBlock = { name, description, endpoints: Endpoint[] } +// Endpoint = { name, label, method, path, description, attributes: EndpointAttr[] } +// EndpointAttr = { name, type, description } +// --------------------------------------------------------------------------- + +export function parseApiDsl(rootDir) { + const files = getApiDslFiles(rootDir); + const enums = []; + const dtos = []; + const apis = []; + const stack = []; + + for (const filePath of files) { + const content = readFileSync(filePath, 'utf8'); + const lines = content.split(/\r?\n/); + + for (const rawLine of lines) { + const line = stripInlineComment(rawLine); + if (!line) continue; + + const top = stack.at(-1); + + // ── Top-level: enum block ────────────────────────────────────────── + const enumMatch = line.match(/^enum\s+([A-Za-z][A-Za-z0-9_]*)\s*\{$/); + if (!top && enumMatch) { + const enumBlock = { name: enumMatch[1], description: null, values: [] }; + enums.push(enumBlock); + stack.push({ type: 'enum', ref: enumBlock }); + continue; + } + + // ── Top-level: dto block ─────────────────────────────────────────── + const dtoMatch = line.match(/^dto\s+(DTO\.\w+)\s*\{$/); + if (!top && dtoMatch) { + const dto = { name: dtoMatch[1], description: null, fields: [] }; + dtos.push(dto); + stack.push({ type: 'dto', ref: dto }); + continue; + } + + // ── Top-level: api block ─────────────────────────────────────────── + const apiMatch = line.match(/^api\s+(API\.\w+)\s*\{$/); + if (!top && apiMatch) { + const api = { name: apiMatch[1], description: null, endpoints: [] }; + apis.push(api); + stack.push({ type: 'api', ref: api }); + continue; + } + + // ── Inside enum ─────────────────────────────────────────────────── + if (top?.type === 'enum') { + const descMatch = line.match(/^description\s+"(.*)"\s*;$/); + if (descMatch) { + top.ref.description = descMatch[1]; + continue; + } + + const valueMatch = line.match(/^value\s+([^\s{]+)\s*\{$/); + if (valueMatch) { + const enumValue = { name: valueMatch[1], label: null }; + top.ref.values.push(enumValue); + stack.push({ type: 'enumValue', ref: enumValue }); + continue; + } + } + + // ── Inside enum value ───────────────────────────────────────────── + if (top?.type === 'enumValue') { + const labelMatch = line.match(/^label\s+"(.*)"\s*;$/); + if (labelMatch) { + top.ref.label = labelMatch[1]; + continue; + } + } + + // ── Inside dto ──────────────────────────────────────────────────── + if (top?.type === 'dto') { + const descMatch = line.match(/^description\s+"(.*)"\s*;$/); + if (descMatch) { + top.ref.description = descMatch[1]; + continue; + } + + const attrMatch = line.match(/^attribute\s+(\w+)\s*\{$/); + if (attrMatch) { + const field = { + name: attrMatch[1], + type: null, + required: false, + nullable: false, + unique: false, + primary: false, + description: null, + map: null, + label: null, + }; + top.ref.fields.push(field); + stack.push({ type: 'dtoField', ref: field }); + continue; + } + } + + // ── Inside dto attribute field ──────────────────────────────────── + if (top?.type === 'dtoField') { + const typeMatch = line.match(/^type\s+(.+?)\s*;$/); + if (typeMatch) { + top.ref.type = typeMatch[1]; + continue; + } + + if (/^is\s+required\s*;$/.test(line)) { + top.ref.required = true; + continue; + } + + if (/^is\s+nullable\s*;$/.test(line)) { + top.ref.nullable = true; + continue; + } + + if (/^is\s+unique\s*;$/.test(line)) { + top.ref.unique = true; + continue; + } + + if (/^key\s+primary\s*;$/.test(line)) { + top.ref.primary = true; + continue; + } + + const descMatch = line.match(/^description\s+"(.*)"\s*;$/); + if (descMatch) { + top.ref.description = descMatch[1]; + continue; + } + + // map Entity.field; — canonical field mapping + const mapMatch = line.match(/^map\s+(\w+)\.(\w+)\s*;$/); + if (mapMatch) { + top.ref.map = `${mapMatch[1]}.${mapMatch[2]}`; + continue; + } + + // sync Entity.field; — aggregate / computed field mapping (treated as map) + const syncMatch = line.match(/^sync\s+(\w+)\.(\w+)\s*;$/); + if (syncMatch) { + top.ref.map = `${syncMatch[1]}.${syncMatch[2]}`; + top.ref.sync = true; + continue; + } + + const labelMatch = line.match(/^label\s+"(.*)"\s*;$/); + if (labelMatch) { + top.ref.label = labelMatch[1]; + continue; + } + } + + // ── Inside api ──────────────────────────────────────────────────── + if (top?.type === 'api') { + const descMatch = line.match(/^description\s+"(.*)"\s*;$/); + if (descMatch) { + top.ref.description = descMatch[1]; + continue; + } + + const epMatch = line.match(/^endpoint\s+(\w+)\s*\{$/); + if (epMatch) { + const ep = { + name: epMatch[1], + label: null, + method: null, + path: null, + description: null, + attributes: [], + }; + top.ref.endpoints.push(ep); + stack.push({ type: 'endpoint', ref: ep }); + continue; + } + } + + // ── Inside endpoint ─────────────────────────────────────────────── + if (top?.type === 'endpoint') { + const labelMatch = line.match(/^label\s+"([^"]+)"\s*;$/); + if (labelMatch) { + top.ref.label = labelMatch[1]; + const parts = labelMatch[1].split(' ', 2); + top.ref.method = parts[0]?.toUpperCase() ?? null; + top.ref.path = parts[1] ?? null; + continue; + } + + const descMatch = line.match(/^description\s+"(.*)"\s*;$/); + if (descMatch) { + top.ref.description = descMatch[1]; + continue; + } + + const attrMatch = line.match(/^attribute\s+(\w+)\s*\{$/); + if (attrMatch) { + const attr = { name: attrMatch[1], type: null, description: null }; + top.ref.attributes.push(attr); + stack.push({ type: 'endpointAttr', ref: attr }); + continue; + } + } + + // ── Inside endpoint attribute ───────────────────────────────────── + if (top?.type === 'endpointAttr') { + const typeMatch = line.match(/^type\s+(.+?)\s*;$/); + if (typeMatch) { + top.ref.type = typeMatch[1]; + continue; + } + + const descMatch = line.match(/^description\s+"(.*)"\s*;$/); + if (descMatch) { + top.ref.description = descMatch[1]; + continue; + } + } + + // ── Closing brace — pop the stack ───────────────────────────────── + if (/^}\s*;?$/.test(line)) { + stack.pop(); + } + } + } + + return { files, enums, dtos, apis }; +} + +// --------------------------------------------------------------------------- +// Summary builder +// +// Produces the serialisable api-summary.json object. +// --------------------------------------------------------------------------- + +export function buildApiSummary(rootDir) { + const { files, enums, dtos, apis } = parseApiDsl(rootDir); + + // Detect duplicate DTO names + const dtoNames = new Set(); + for (const dto of dtos) { + if (dtoNames.has(dto.name)) { + throw new Error(`Duplicate DTO definition: ${dto.name}`); + } + dtoNames.add(dto.name); + } + + // Detect duplicate API names + const apiNames = new Set(); + for (const api of apis) { + if (apiNames.has(api.name)) { + throw new Error(`Duplicate API definition: ${api.name}`); + } + apiNames.add(api.name); + } + + return { + sourceFiles: files.map((filePath) => + path.relative(rootDir, filePath).replaceAll('\\', '/'), + ), + enums: enums.map((e) => ({ + name: e.name, + description: e.description, + values: e.values.map((v) => ({ name: v.name, label: v.label })), + })), + dtos: dtos.map((dto) => ({ + name: dto.name, + description: dto.description, + fields: dto.fields.map((field) => ({ + name: field.name, + type: field.type, + required: field.required, + nullable: field.nullable, + unique: field.unique, + primary: field.primary, + description: field.description, + map: field.map, + sync: field.sync ?? false, + label: field.label, + })), + })), + apis: apis.map((api) => ({ + name: api.name, + description: api.description, + endpoints: api.endpoints.map((ep) => ({ + name: ep.name, + label: ep.label, + method: ep.method, + path: ep.path, + description: ep.description, + attributes: ep.attributes.map((attr) => ({ + name: attr.name, + type: attr.type, + description: attr.description, + })), + })), + })), + }; +} diff --git a/.claude/worktrees/goofy-haslett/tools/eval/README.md b/.claude/worktrees/goofy-haslett/tools/eval/README.md new file mode 100644 index 0000000..7d62337 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/eval/README.md @@ -0,0 +1,113 @@ +# Eval Harness — Rule 6 + +Fixture-based regression tests for generated artifacts. + +## Why this exists + +> "Evals are the test suite for your prompts. You would never ship code without tests; +> don't ship prompts without evals." — Anthropic Engineering + +The validation gate (`tools/validate-generation.mjs`) checks **existence** and **structural compliance**. +The eval harness checks **semantic correctness**: are the right patterns present in the generated code? +Do the generated files actually follow the rules in `prompts/`? + +Together they enforce: +- Gate: "file exists, field names present, auth seams wired" +- Evals: "DTO has class-validator decorators, FK uses ReferenceInput, date uses DateInput, guard is present" + +The committed fixture corpus is a reviewed semantic contract. It may be scaffolded from source-of-truth as a helper, but it should not be auto-regenerated wholesale during every full regeneration run, or it stops acting as an independent regression signal. + +## Usage + +```bash +# Run all evals +npm run eval:generation + +# Run evals for one entity +node tools/eval/run-evals.mjs --entity equipment + +# Verbose output (show each file being checked) +node tools/eval/run-evals.mjs --verbose +``` + +## Fixture format + +Each fixture lives in `tools/eval/fixtures//`: + +``` +fixtures/ + equipment/ + meta.json ← what this fixture tests + backend.assertions.json ← patterns the NestJS files must satisfy + frontend.assertions.json ← patterns the React Admin files must satisfy + repair-order/ + meta.json + backend.assertions.json + frontend.assertions.json +``` + +### `meta.json` + +```json +{ + "entity": "Equipment", + "kebab": "equipment", + "resource": "equipment", + "description": "...", + "tests": ["dto-decorator-coverage", "auth-guards", ...] +} +``` + +### `*.assertions.json` + +Each file entry supports: + +| Key | Type | Meaning | +|-----|------|---------| +| `path` | string | Relative path from repo root | +| `must_contain` | string[] | Each string must appear as a literal substring | +| `must_not_contain` | string[] | Each string must NOT appear | +| `must_match_regex` | string[] | Each pattern must match (multiline dot-all) | +| `must_not_match_regex` | string[] | Each pattern must NOT match | +| `comment` | string | Human-readable explanation of what is being tested | + +## Eval-driven development workflow + +This is the critical principle from Anthropic and Google: + +1. **Write the failing eval first.** When you change a prompt or add a rule, add an + assertion that captures the new expectation *before* re-generating. +2. **Run evals**: `npm run eval:generation` → see failures. +3. **Re-generate** the affected entity (following the generation workflow in `AGENTS.md`). +4. **Run evals again**: all pass → the change is verified. +5. **Commit both** the updated fixture and the regenerated artifacts together. + +A passing eval after a prompt change confirms the LLM followed the new rule. +A failing eval before a prompt change tells you exactly which prior contract was broken. + +Automation note: + +- It is reasonable to generate starter fixtures or coverage manifests from source-of-truth. +- It is not reasonable to let the same regeneration step auto-refresh the authoritative committed eval corpus, because that couples the semantic gate too tightly to the generator and can hide regressions. + +## Adding a new entity fixture + +When adding a new entity to `domain/toir.api.dsl` and generating its backend + frontend: + +1. Create `tools/eval/fixtures//meta.json` +2. Create `tools/eval/fixtures//backend.assertions.json` with at minimum: + - controller: `@Controller(...)`, `@UseGuards(`, `JwtAuthGuard`, HTTP methods + - create_dto: `from 'class-validator'`, required fields with `!:`, `@IsString(`, `@IsOptional(` + - update_dto: `from 'class-validator'`, fields with `?:`, `@IsOptional(` +3. Create `tools/eval/fixtures//frontend.assertions.json` with at minimum: + - create: `ReferenceInput` for FK fields, `NumberInput` for numeric, `DateInput` for date, `SelectInput` for enum + - show: `ReferenceField` for FK fields, `DateField` for date +4. Run `npm run eval:generation` to verify the fixture catches real issues. + +## Integration with git hooks + +The pre-commit hook (installed by `npm run install-hooks`) runs both: +1. `node tools/validate-generation.mjs --artifacts-only` — existence gate +2. `npm run eval:generation` — semantic eval gate + +Both must pass before a commit is accepted. diff --git a/.claude/worktrees/goofy-haslett/tools/eval/fixtures/change-equipment-status/backend.assertions.json b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/change-equipment-status/backend.assertions.json new file mode 100644 index 0000000..72144fd --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/change-equipment-status/backend.assertions.json @@ -0,0 +1,72 @@ +{ + "entity": "ChangeEquipmentStatus", + "files": { + "controller": { + "path": "server/src/modules/change-equipment-status/change-equipment-status.controller.ts", + "must_contain": [ + "@Controller('change-equipment-status')", + "@UseGuards(", + "JwtAuthGuard", + "RolesGuard", + "@Get()", + "@Post()", + "@Get(':equipmentId/:newStatus')", + "@Patch(':equipmentId/:newStatus')", + "@Delete(':equipmentId/:newStatus')" + ], + "must_not_contain": [ + "@Put(':equipmentId/:newStatus')" + ], + "must_match_regex": [ + "@Delete\\(':equipmentId/:newStatus'\\)[\\s\\S]{0,120}@Roles\\('admin'\\)|@Roles\\('admin'\\)[\\s\\S]{0,120}@Delete\\(':equipmentId/:newStatus'\\)" + ] + }, + "service": { + "path": "server/src/modules/change-equipment-status/change-equipment-status.service.ts", + "must_contain": [ + "setListHeaders", + "_start", + "_end", + "_sort", + "_order", + "equipmentId", + "newStatus" + ], + "must_match_regex": [ + "equipmentId.*(equals|=)", + "newStatus.*in\\b|\\bin\\b.*newStatus" + ] + }, + "create_dto": { + "path": "server/src/modules/change-equipment-status/dto/create-change-equipment-status.dto.ts", + "must_contain": [ + "from 'class-validator'", + "equipmentId!:", + "newStatus!:", + "date!:", + "number?:", + "responsible?:", + "@IsUUID(", + "@IsEnum(", + "@IsString(", + "@IsOptional(" + ], + "must_not_contain": [ + "id?:", + "id!:" + ] + }, + "update_dto": { + "path": "server/src/modules/change-equipment-status/dto/update-change-equipment-status.dto.ts", + "must_contain": [ + "from 'class-validator'", + "@IsOptional(", + "equipmentId?:", + "newStatus?:", + "date?:", + "number?:", + "responsible?:" + ] + } + } +} diff --git a/.claude/worktrees/goofy-haslett/tools/eval/fixtures/change-equipment-status/frontend.assertions.json b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/change-equipment-status/frontend.assertions.json new file mode 100644 index 0000000..4e2c2b5 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/change-equipment-status/frontend.assertions.json @@ -0,0 +1,68 @@ +{ + "entity": "ChangeEquipmentStatus", + "resource": "change-equipment-statuses", + "files": { + "list": { + "path": "client/src/resources/change-equipment-status/ChangeEquipmentStatusList.tsx", + "must_contain": [ + "List", + "FilterButton", + "ReferenceField", + "SelectField", + "TextField" + ], + "must_match_regex": [ + "ReferenceField[\\s\\S]{0,200}reference=\"equipment\"|reference=\"equipment\"[\\s\\S]{0,200}ReferenceField", + "source=\"newStatus\"" + ] + }, + "create": { + "path": "client/src/resources/change-equipment-status/ChangeEquipmentStatusCreate.tsx", + "must_contain": [ + "Create", + "SimpleForm", + "ReferenceInput", + "AutocompleteInput", + "SelectInput", + "DateInput" + ], + "must_match_regex": [ + "ReferenceInput[\\s\\S]{0,200}reference=\"equipment\"|reference=\"equipment\"[\\s\\S]{0,200}ReferenceInput", + "AutocompleteInput[\\s\\S]{0,200}filterToQuery|filterToQuery[\\s\\S]{0,200}AutocompleteInput", + "SelectInput[\\s\\S]{0,200}source=\"newStatus\"|source=\"newStatus\"[\\s\\S]{0,200}SelectInput", + "DateInput[\\s\\S]{0,200}source=\"date\"|source=\"date\"[\\s\\S]{0,200}DateInput" + ] + }, + "edit": { + "path": "client/src/resources/change-equipment-status/ChangeEquipmentStatusEdit.tsx", + "must_contain": [ + "Edit", + "SimpleForm", + "ReferenceInput", + "AutocompleteInput", + "SelectInput", + "DateInput" + ], + "must_match_regex": [ + "ReferenceInput[\\s\\S]{0,200}reference=\"equipment\"|reference=\"equipment\"[\\s\\S]{0,200}ReferenceInput", + "AutocompleteInput[\\s\\S]{0,200}filterToQuery|filterToQuery[\\s\\S]{0,200}AutocompleteInput", + "SelectInput[\\s\\S]{0,200}source=\"newStatus\"|source=\"newStatus\"[\\s\\S]{0,200}SelectInput", + "DateInput[\\s\\S]{0,200}source=\"date\"|source=\"date\"[\\s\\S]{0,200}DateInput" + ] + }, + "show": { + "path": "client/src/resources/change-equipment-status/ChangeEquipmentStatusShow.tsx", + "must_contain": [ + "Show", + "SimpleShowLayout", + "ReferenceField", + "SelectField", + "DateField" + ], + "must_match_regex": [ + "ReferenceField[\\s\\S]{0,200}reference=\"equipment\"|reference=\"equipment\"[\\s\\S]{0,200}ReferenceField", + "source=\"newStatus\"" + ] + } + } +} diff --git a/.claude/worktrees/goofy-haslett/tools/eval/fixtures/change-equipment-status/meta.json b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/change-equipment-status/meta.json new file mode 100644 index 0000000..a2128f0 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/change-equipment-status/meta.json @@ -0,0 +1,15 @@ +{ + "entity": "ChangeEquipmentStatus", + "kebab": "change-equipment-status", + "resource": "change-equipment-statuses", + "description": "Current composite-key status history entity: equipment reference, enum status, date, and optional text metadata", + "tests": [ + "dto-decorator-coverage", + "auth-guards-per-http-method", + "composite-key-route", + "fk-reference-input", + "fk-reference-field", + "content-range-header-pattern", + "enum-filter-in-operator" + ] +} diff --git a/.claude/worktrees/goofy-haslett/tools/eval/fixtures/equipment/backend.assertions.json b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/equipment/backend.assertions.json new file mode 100644 index 0000000..99fc2ab --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/equipment/backend.assertions.json @@ -0,0 +1,82 @@ +{ + "entity": "Equipment", + "files": { + "controller": { + "path": "server/src/modules/equipment/equipment.controller.ts", + "must_contain": [ + "@Controller('equipment')", + "@UseGuards(", + "JwtAuthGuard", + "RolesGuard", + "@Get()", + "@Post()", + "@Get(':id')", + "@Patch(':id')", + "@Delete(':id')" + ], + "must_not_contain": [ + "@Put(':id')", + "@Post(':id')" + ], + "must_match_regex": [ + "@Delete\\(':id'\\)[\\s\\S]{0,80}@Roles\\('admin'\\)|@Roles\\('admin'\\)[\\s\\S]{0,80}@Delete\\(':id'\\)" + ], + "comment": "Equipment controller must expose the CRUD verbs expected by the DSL-compatible React Admin contract." + }, + "service": { + "path": "server/src/modules/equipment/equipment.service.ts", + "must_contain": [ + "setListHeaders(response", + "_start", + "_end", + "_sort", + "_order", + "q" + ], + "must_match_regex": [ + "contains\\(|mode.*insensitive|insensitive.*mode", + "status.*in\\b|\\bin\\b.*status" + ], + "comment": "Service must translate React Admin list params into Prisma filters and delegate header wiring through the shared helper." + }, + "create_dto": { + "path": "server/src/modules/equipment/dto/create-equipment.dto.ts", + "must_contain": [ + "from 'class-validator'", + "name!:", + "serialNumber!:", + "dateOfInspection?:", + "commissionedAt?:", + "status?:", + "@IsString(", + "@IsOptional(", + "@IsEnum(" + ], + "must_not_contain": [ + "id?:", + "id!:" + ], + "comment": "Required fields use '!' suffix; optional fields use '?' with @IsOptional(); enum fields use @IsEnum(); class-validator must be imported." + }, + "update_dto": { + "path": "server/src/modules/equipment/dto/update-equipment.dto.ts", + "must_contain": [ + "from 'class-validator'", + "name?:", + "serialNumber?:", + "dateOfInspection?:", + "commissionedAt?:", + "status?:", + "@IsOptional(", + "@IsString(", + "@IsEnum(" + ], + "must_not_contain": [ + "name!:", + "serialNumber!:", + "status!:" + ], + "comment": "Update DTO: all fields are optional ('?' suffix with @IsOptional())." + } + } +} diff --git a/.claude/worktrees/goofy-haslett/tools/eval/fixtures/equipment/frontend.assertions.json b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/equipment/frontend.assertions.json new file mode 100644 index 0000000..2ecec4c --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/equipment/frontend.assertions.json @@ -0,0 +1,67 @@ +{ + "entity": "Equipment", + "resource": "equipment", + "files": { + "list": { + "path": "client/src/resources/equipment/EquipmentList.tsx", + "must_contain": [ + "List", + "FilterButton", + "TextField", + "SelectField", + "name", + "serialNumber" + ], + "must_match_regex": [ + "SelectArrayInput", + "source=\"status\"" + ], + "comment": "Equipment list must expose the current fields, filter UI, and enum filters." + }, + "create": { + "path": "client/src/resources/equipment/EquipmentCreate.tsx", + "must_contain": [ + "Create", + "SimpleForm", + "SelectInput", + "TextInput" + ], + "must_match_regex": [ + "TextInput[\\s\\S]{0,300}source=\"name\"|source=\"name\"[\\s\\S]{0,300}TextInput", + "TextInput[\\s\\S]{0,300}source=\"serialNumber\"|source=\"serialNumber\"[\\s\\S]{0,300}TextInput", + "DateInput[\\s\\S]{0,300}source=\"dateOfInspection\"|source=\"dateOfInspection\"[\\s\\S]{0,300}DateInput", + "DateInput[\\s\\S]{0,300}source=\"commissionedAt\"|source=\"commissionedAt\"[\\s\\S]{0,300}DateInput", + "SelectInput[\\s\\S]{0,300}source=\"status\"|source=\"status\"[\\s\\S]{0,300}SelectInput" + ], + "comment": "Equipment create form must keep type-correct inputs for text, enum, and date fields." + }, + "edit": { + "path": "client/src/resources/equipment/EquipmentEdit.tsx", + "must_contain": [ + "Edit", + "SimpleForm", + "SelectInput", + "TextInput" + ], + "must_match_regex": [ + "TextInput[\\s\\S]{0,300}source=\"name\"|source=\"name\"[\\s\\S]{0,300}TextInput", + "TextInput[\\s\\S]{0,300}source=\"serialNumber\"|source=\"serialNumber\"[\\s\\S]{0,300}TextInput", + "DateInput[\\s\\S]{0,300}source=\"dateOfInspection\"|source=\"dateOfInspection\"[\\s\\S]{0,300}DateInput", + "DateInput[\\s\\S]{0,300}source=\"commissionedAt\"|source=\"commissionedAt\"[\\s\\S]{0,300}DateInput" + ], + "comment": "Equipment edit form must keep the same type-correctness guarantees as create." + }, + "show": { + "path": "client/src/resources/equipment/EquipmentShow.tsx", + "must_contain": [ + "Show", + "SimpleShowLayout", + "TextField", + "SelectField", + "name", + "serialNumber" + ], + "comment": "Show must display the current equipment identity and status fields." + } + } +} diff --git a/.claude/worktrees/goofy-haslett/tools/eval/fixtures/equipment/meta.json b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/equipment/meta.json new file mode 100644 index 0000000..11659ec --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/eval/fixtures/equipment/meta.json @@ -0,0 +1,15 @@ +{ + "entity": "Equipment", + "kebab": "equipment", + "resource": "equipment", + "description": "Current equipment entity: UUID primary key, text fields, nullable date fields, and an enum status field", + "tests": [ + "dto-decorator-coverage", + "auth-guards-per-http-method", + "content-range-header-pattern", + "enum-filter-in-operator", + "q-filter-contains-pattern", + "react-admin-component-types", + "class-validator-import" + ] +} diff --git a/.claude/worktrees/goofy-haslett/tools/eval/run-evals.mjs b/.claude/worktrees/goofy-haslett/tools/eval/run-evals.mjs new file mode 100644 index 0000000..6aadd7c --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/eval/run-evals.mjs @@ -0,0 +1,184 @@ +#!/usr/bin/env node +/** + * tools/eval/run-evals.mjs + * + * Rule 6 — Eval harness: fixture-based regression tests for generated artifacts. + * + * Philosophy: + * - Evals are the test suite for prompts. Never ship a prompt change without + * running evals first. + * - Use deterministic pattern/regex checks ("reference-free" grading) rather + * than golden snapshot comparison. Patterns are maintainable; snapshots are + * brittle. + * - Eval-driven development: write a failing eval FIRST, then update the prompt + * or re-generate to make it pass. + * + * Usage: + * node tools/eval/run-evals.mjs # run all fixtures + * node tools/eval/run-evals.mjs --entity equipment + * node tools/eval/run-evals.mjs --verbose + */ + +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const rootDir = path.resolve(__dirname, '../..'); +const fixturesDir = path.join(__dirname, 'fixtures'); + +const args = new Set(process.argv.slice(2)); +const verbose = args.has('--verbose') || args.has('-v'); +const entityFilter = (() => { + const idx = process.argv.indexOf('--entity'); + return idx !== -1 ? process.argv[idx + 1] : null; +})(); + +// --------------------------------------------------------------------------- +// Assertion engine +// --------------------------------------------------------------------------- + +let totalChecks = 0; +let totalFailures = 0; +const failures = []; + +function readArtifact(relativePath) { + const filePath = path.join(rootDir, relativePath); + if (!existsSync(filePath)) return null; + return readFileSync(filePath, 'utf8'); +} + +function runFileAssertions(filePath, fileSpec, entityLabel) { + const content = readArtifact(filePath); + + if (content === null) { + totalChecks++; + totalFailures++; + failures.push({ entity: entityLabel, file: filePath, check: 'file-exists', result: 'FAIL', detail: `File not found: ${filePath}` }); + return; + } + + if (verbose) { + console.log(` [${entityLabel}] Checking ${filePath}`); + } + + for (const expected of fileSpec.must_contain ?? []) { + totalChecks++; + if (!content.includes(expected)) { + totalFailures++; + failures.push({ entity: entityLabel, file: filePath, check: 'must_contain', result: 'FAIL', detail: `Missing: ${expected}` }); + } + } + + for (const forbidden of fileSpec.must_not_contain ?? []) { + totalChecks++; + if (content.includes(forbidden)) { + totalFailures++; + failures.push({ entity: entityLabel, file: filePath, check: 'must_not_contain', result: 'FAIL', detail: `Forbidden pattern found: ${forbidden}` }); + } + } + + for (const patternStr of fileSpec.must_match_regex ?? []) { + totalChecks++; + try { + const re = new RegExp(patternStr); + if (!re.test(content)) { + totalFailures++; + failures.push({ entity: entityLabel, file: filePath, check: 'must_match_regex', result: 'FAIL', detail: `Regex not matched: ${patternStr}` }); + } + } catch (e) { + totalFailures++; + failures.push({ entity: entityLabel, file: filePath, check: 'must_match_regex', result: 'ERROR', detail: `Bad regex: ${patternStr} — ${e.message}` }); + } + } + + for (const patternStr of fileSpec.must_not_match_regex ?? []) { + totalChecks++; + try { + const re = new RegExp(patternStr); + if (re.test(content)) { + totalFailures++; + failures.push({ entity: entityLabel, file: filePath, check: 'must_not_match_regex', result: 'FAIL', detail: `Forbidden regex matched: ${patternStr}` }); + } + } catch (e) { + totalFailures++; + failures.push({ entity: entityLabel, file: filePath, check: 'must_not_match_regex', result: 'ERROR', detail: `Bad regex: ${patternStr} — ${e.message}` }); + } + } +} + +function runFixture(fixtureDir) { + const metaPath = path.join(fixtureDir, 'meta.json'); + if (!existsSync(metaPath)) return; + + const meta = JSON.parse(readFileSync(metaPath, 'utf8')); + const { entity, kebab } = meta; + + if (entityFilter && kebab !== entityFilter && entity.toLowerCase() !== entityFilter.toLowerCase()) { + return; + } + + if (verbose) { + console.log(`\n[EVAL] ${entity} — ${meta.description ?? ''}`); + } + + const backendPath = path.join(fixtureDir, 'backend.assertions.json'); + if (existsSync(backendPath)) { + const spec = JSON.parse(readFileSync(backendPath, 'utf8')); + for (const [key, fileSpec] of Object.entries(spec.files ?? {})) { + runFileAssertions(fileSpec.path, fileSpec, `${entity}/${key}`); + } + } + + const frontendPath = path.join(fixtureDir, 'frontend.assertions.json'); + if (existsSync(frontendPath)) { + const spec = JSON.parse(readFileSync(frontendPath, 'utf8')); + for (const [key, fileSpec] of Object.entries(spec.files ?? {})) { + runFileAssertions(fileSpec.path, fileSpec, `${entity}/${key}`); + } + } +} + +// --------------------------------------------------------------------------- +// Main +// --------------------------------------------------------------------------- + +const fixtureDirs = readdirSync(fixturesDir, { withFileTypes: true }) + .filter((d) => d.isDirectory()) + .map((d) => path.join(fixturesDir, d.name)); + +for (const dir of fixtureDirs) { + runFixture(dir); +} + +// --------------------------------------------------------------------------- +// Report +// --------------------------------------------------------------------------- + +console.log(''); +console.log('══════════════════════════════════════════════'); +console.log(' KIS-TOiR Eval Report'); +console.log('══════════════════════════════════════════════'); +console.log(` Fixtures: ${fixtureDirs.length}`); +console.log(` Checks: ${totalChecks}`); +console.log(` Passed: ${totalChecks - totalFailures}`); +console.log(` Failed: ${totalFailures}`); +console.log('══════════════════════════════════════════════'); + +if (failures.length > 0) { + console.log(''); + console.log('Failures:'); + for (const f of failures) { + console.log(` [${f.result}] ${f.entity} — ${f.file}`); + console.log(` ${f.check}: ${f.detail}`); + } + console.log(''); + console.log('To fix: update the prompt or re-generate the failing entity, then re-run evals.'); + console.log('To update a fixture (intentional change): edit tools/eval/fixtures//*.assertions.json'); + console.log(''); + process.exit(1); +} + +console.log(''); +console.log('All evals passed.'); +console.log(''); diff --git a/.claude/worktrees/goofy-haslett/tools/generate-api-summary.mjs b/.claude/worktrees/goofy-haslett/tools/generate-api-summary.mjs new file mode 100644 index 0000000..5cbfc7f --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/generate-api-summary.mjs @@ -0,0 +1,13 @@ +import { mkdirSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { buildApiSummary } from './api-summary.mjs'; + +const rootDir = process.cwd(); +const outputPath = path.join(rootDir, 'api-summary.json'); + +mkdirSync(path.dirname(outputPath), { recursive: true }); + +const summary = buildApiSummary(rootDir); +writeFileSync(outputPath, `${JSON.stringify(summary, null, 2)}\n`, 'utf8'); + +console.log(`Generated ${path.relative(rootDir, outputPath)}`); diff --git a/.claude/worktrees/goofy-haslett/tools/hooks/pre-commit b/.claude/worktrees/goofy-haslett/tools/hooks/pre-commit new file mode 100644 index 0000000..a0a36a6 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/hooks/pre-commit @@ -0,0 +1,5 @@ +#!/bin/sh +# Pre-commit hook: runs the generation validation gate and eval harness. +# Install with: npm run install-hooks + +node tools/validate-generation.mjs --artifacts-only && node tools/eval/run-evals.mjs diff --git a/.claude/worktrees/goofy-haslett/tools/install-hooks.mjs b/.claude/worktrees/goofy-haslett/tools/install-hooks.mjs new file mode 100644 index 0000000..227319d --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/install-hooks.mjs @@ -0,0 +1,19 @@ +import { copyFileSync, chmodSync, mkdirSync, existsSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const root = path.resolve(__dirname, '..'); +const hooksDir = path.join(root, '.git', 'hooks'); +const src = path.join(root, 'tools', 'hooks', 'pre-commit'); +const dest = path.join(hooksDir, 'pre-commit'); + +if (!existsSync(path.join(root, '.git'))) { + console.error('Not a git repository. Run from the repo root.'); + process.exit(1); +} + +mkdirSync(hooksDir, { recursive: true }); +copyFileSync(src, dest); +try { chmodSync(dest, 0o755); } catch { /* Windows */ } +console.log('Installed pre-commit hook → .git/hooks/pre-commit'); diff --git a/.claude/worktrees/goofy-haslett/tools/validate-generation.mjs b/.claude/worktrees/goofy-haslett/tools/validate-generation.mjs new file mode 100644 index 0000000..5072ba3 --- /dev/null +++ b/.claude/worktrees/goofy-haslett/tools/validate-generation.mjs @@ -0,0 +1,502 @@ +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { getApiDslFiles, buildApiSummary } from './api-summary.mjs'; + +const rootDir = process.cwd(); +const args = new Set(process.argv.slice(2)); +const artifactsOnly = args.has('--artifacts-only'); +const runRuntime = args.has('--run-runtime'); + +const failures = []; +const warnings = []; + +function assertCondition(condition, message) { + if (!condition) { + failures.push(message); + } +} + +function warn(message) { + warnings.push(message); +} + +function readIfExists(relativePath) { + const filePath = path.join(rootDir, relativePath); + if (!existsSync(filePath)) { + return null; + } + + return readFileSync(filePath, 'utf8'); +} + +function requireFile(relativePath) { + assertCondition(existsSync(path.join(rootDir, relativePath)), `Missing file: ${relativePath}`); +} + +function requireFiles(relativePaths) { + relativePaths.forEach(requireFile); +} + +function requireContent(relativePath, pattern, message) { + const contents = readIfExists(relativePath); + assertCondition(Boolean(contents), `Missing file: ${relativePath}`); + if (!contents) { + return; + } + + assertCondition(pattern.test(contents), `${message} (${relativePath})`); +} + +function parseJson(relativePath) { + const raw = readIfExists(relativePath); + if (!raw) { + failures.push(`Missing file: ${relativePath}`); + return null; + } + + try { + return JSON.parse(raw); + } catch (error) { + failures.push(`Invalid JSON in ${relativePath}: ${error.message}`); + return null; + } +} + +function getRealmArtifactPath() { + const rootFiles = readdirSync(rootDir, { withFileTypes: true }) + .filter((entry) => entry.isFile()) + .map((entry) => entry.name); + + const realmArtifacts = rootFiles.filter((entry) => /-realm\.json$/i.test(entry)); + assertCondition(realmArtifacts.length === 1, 'Expected exactly one root-level *-realm.json artifact'); + + return realmArtifacts[0] ?? null; +} + +function getWorkspaceInfo() { + return { + server: { + dir: path.join(rootDir, 'server'), + packagePath: 'server/package.json', + scaffoldFiles: [ + 'server/package.json', + 'server/tsconfig.json', + 'server/tsconfig.build.json', + 'server/nest-cli.json', + 'server/src/main.ts', + 'server/src/app.module.ts', + ], + }, + client: { + dir: path.join(rootDir, 'client'), + packagePath: 'client/package.json', + scaffoldFiles: [ + 'client/package.json', + 'client/index.html', + 'client/tsconfig.json', + 'client/tsconfig.node.json', + 'client/vite.config.ts', + 'client/src/main.tsx', + 'client/src/vite-env.d.ts', + ], + }, + }; +} + +function validateBuildChecks() { + requireFiles([ + 'README.md', + 'package.json', + 'domain/dsl-spec.md', + 'api-summary.json', + 'server/prisma/schema.prisma', + 'docker-compose.yml', + 'server/Dockerfile', + 'client/Dockerfile', + 'client/nginx/default.conf', + 'server/.env.example', + 'client/.env.example', + 'prompts/general-prompt.md', + 'prompts/auth-rules.md', + 'prompts/backend-rules.md', + 'prompts/frontend-rules.md', + 'prompts/runtime-rules.md', + 'prompts/validation-rules.md', + ]); + + // rule: AGENTS.md §Tier-1 — api.dsl must exist + const apiDslFiles = getApiDslFiles(rootDir); + assertCondition(apiDslFiles.length > 0, 'Expected at least one domain/*.api.dsl file'); + + // rule: AGENTS.md §Tier-2 — api-summary.json must match parsed api.dsl + const actualApiSummaryRaw = readIfExists('api-summary.json'); + if (actualApiSummaryRaw) { + try { + const expectedApiSummary = JSON.stringify(buildApiSummary(rootDir), null, 2); + assertCondition( + actualApiSummaryRaw.trim() === expectedApiSummary, + 'api-summary.json is out of date. Run `npm run generate:api-summary`.', + ); + } catch (error) { + failures.push(`api-summary.json freshness check failed: ${error.message}`); + } + } + + const { server, client } = getWorkspaceInfo(); + requireFiles(server.scaffoldFiles); + requireFiles(client.scaffoldFiles); + + const serverPackage = parseJson(server.packagePath); + if (serverPackage) { + assertCondition(serverPackage.scripts?.build === 'nest build', 'server/package.json must keep `build = nest build`'); + assertCondition(serverPackage.scripts?.start === 'nest start', 'server/package.json must keep `start = nest start`'); + assertCondition(serverPackage.scripts?.['start:dev'] === 'nest start --watch', 'server/package.json must keep `start:dev = nest start --watch`'); + assertCondition(Boolean(serverPackage.scripts?.['start:prod']), 'server/package.json must define a start:prod script'); + assertCondition(Boolean(serverPackage.dependencies?.['@nestjs/core']), 'server/package.json must keep Nest runtime dependencies'); + } + + const clientPackage = parseJson(client.packagePath); + if (clientPackage) { + assertCondition(clientPackage.scripts?.dev === 'vite', 'client/package.json must keep `dev = vite`'); + assertCondition(clientPackage.scripts?.build === 'vite build', 'client/package.json must keep `build = vite build`'); + assertCondition(clientPackage.scripts?.preview === 'vite preview', 'client/package.json must keep `preview = vite preview`'); + assertCondition(Boolean(clientPackage.devDependencies?.vite), 'client/package.json must keep Vite as a dev dependency'); + assertCondition(Boolean(clientPackage.devDependencies?.['@vitejs/plugin-react']), 'client/package.json must keep @vitejs/plugin-react as a dev dependency'); + } +} + +function validateAuthChecks() { + requireFiles([ + 'client/src/auth/keycloak.ts', + 'client/src/auth/authProvider.ts', + 'client/src/dataProvider.ts', + 'client/src/config/env.ts', + 'client/src/main.tsx', + 'client/src/App.tsx', + 'server/src/auth/auth.module.ts', + 'server/src/auth/auth.service.ts', + 'server/src/auth/guards/jwt-auth.guard.ts', + 'server/src/auth/guards/roles.guard.ts', + 'server/src/auth/decorators/public.decorator.ts', + 'server/src/auth/decorators/roles.decorator.ts', + ]); + + requireContent( + 'client/src/auth/keycloak.ts', + /onLoad:\s*'login-required'/, + 'Frontend auth must initialize Keycloak with login-required', + ); + requireContent( + 'client/src/auth/keycloak.ts', + /pkceMethod:\s*'S256'/, + 'Frontend auth must use PKCE S256', + ); + requireContent( + 'client/src/auth/keycloak.ts', + /updateToken\(/, + 'Frontend auth must refresh access tokens through the Keycloak adapter', + ); + + const keycloakSource = readIfExists('client/src/auth/keycloak.ts') ?? ''; + assertCondition( + !/loadUserProfile\(/.test(keycloakSource), + 'Frontend auth must not call keycloak.loadUserProfile()', + ); + + requireContent( + 'client/src/dataProvider.ts', + /Authorization', `Bearer \$\{token\}`/, + 'dataProvider must attach bearer tokens in the shared request seam', + ); + + const authProvider = readIfExists('client/src/auth/authProvider.ts') ?? ''; + assertCondition( + /status === 401/.test(authProvider) && /status === 403/.test(authProvider), + 'authProvider must distinguish 401 and 403 semantics', + ); + + const authService = readIfExists('server/src/auth/auth.service.ts') ?? ''; + assertCondition( + /jwtVerify/.test(authService) && /KEYCLOAK_ISSUER_URL/.test(authService) && /KEYCLOAK_AUDIENCE/.test(authService), + 'Backend auth must verify JWTs with issuer and audience', + ); + assertCondition(/realm_access/.test(authService), 'Backend auth must extract roles from realm_access.roles'); + assertCondition(/KEYCLOAK_JWKS_URL/.test(authService), 'Backend auth must support explicit KEYCLOAK_JWKS_URL'); + assertCondition(/\.well-known\/openid-configuration/.test(authService), 'Backend auth must try OIDC discovery before fallback certs'); + assertCondition(/protocol\/openid-connect\/certs/.test(authService), 'Backend auth must keep Keycloak certs fallback resolution'); +} + +function validateRealmChecks() { + const realmArtifactName = getRealmArtifactPath(); + if (!realmArtifactName) { + return; + } + + const artifact = parseJson(realmArtifactName); + if (!artifact) { + return; + } + + const realmRoles = artifact.roles?.realm?.map((role) => role.name) ?? []; + const frontendClient = artifact.clients?.find((client) => client.clientId?.endsWith('-frontend')); + const backendClient = artifact.clients?.find((client) => client.clientId?.endsWith('-backend')); + const audienceScope = artifact.clientScopes?.find((scope) => scope.name === 'api-audience'); + + ['admin', 'editor', 'viewer'].forEach((role) => { + assertCondition(realmRoles.includes(role), `Realm artifact must define realm role ${role}`); + }); + + assertCondition(Boolean(frontendClient), 'Realm artifact must define the frontend SPA client'); + assertCondition(Boolean(backendClient), 'Realm artifact must define the backend resource client'); + assertCondition(Boolean(audienceScope), 'Realm artifact must define the api-audience client scope'); + + if (frontendClient) { + assertCondition(frontendClient.publicClient === true, 'Frontend realm client must be public'); + assertCondition( + frontendClient.standardFlowEnabled === true && + frontendClient.implicitFlowEnabled === false && + frontendClient.directAccessGrantsEnabled === false, + 'Frontend realm client must use standard flow only', + ); + assertCondition( + frontendClient.attributes?.['pkce.code.challenge.method'] === 'S256', + 'Frontend realm client must enforce PKCE S256', + ); + + const mapperNames = new Set((frontendClient.protocolMappers ?? []).map((mapper) => mapper.name)); + ['sub', 'preferred_username', 'email', 'name', 'realm roles'].forEach((mapperName) => { + assertCondition(mapperNames.has(mapperName), `Frontend realm client must include protocol mapper ${mapperName}`); + }); + } + + if (backendClient && audienceScope) { + const audienceMapper = (audienceScope.protocolMappers ?? []).find( + (mapper) => mapper.protocolMapper === 'oidc-audience-mapper', + ); + assertCondition(Boolean(audienceMapper), 'api-audience scope must include an audience mapper'); + assertCondition( + audienceMapper?.config?.['included.client.audience'] === backendClient.clientId, + 'api-audience scope must deliver the backend audience/client id', + ); + assertCondition(backendClient.bearerOnly === true, 'Backend realm client must be bearer-only'); + } +} + +function validateRuntimeContractChecks() { + requireFiles([ + 'docker-compose.yml', + 'server/Dockerfile', + 'client/Dockerfile', + 'client/nginx/default.conf', + ]); + const compose = readIfExists('docker-compose.yml') ?? ''; + assertCondition(/image:\s*postgres:16/.test(compose), 'docker-compose must provision postgres:16'); + assertCondition(/^\s{2}server\s*:/m.test(compose), 'docker-compose must define a server service'); + assertCondition(/^\s{2}client\s*:/m.test(compose), 'docker-compose must define a client service'); + assertCondition( + /^\s{4}ports:\n\s{6}-\s*"\$\{CLIENT_PORT:-8080\}:80"/m.test(compose), + 'docker-compose client service must publish the SPA on ${CLIENT_PORT:-8080}:80 by default', + ); + const hasKeycloakService = + /^\s{2}keycloak\s*:/m.test(compose) || /image:\s*.*keycloak/i.test(compose); + assertCondition(!hasKeycloakService, 'docker-compose must remain PostgreSQL-only (no Keycloak container)'); + + const codexConfig = readIfExists('.codex/config.toml') ?? ''; + if (codexConfig) { + const agentConfigPaths = [...codexConfig.matchAll(/config_file\s*=\s*"([^"]+)"/g)].map((match) => match[1]); + for (const configPath of agentConfigPaths) { + assertCondition(!path.isAbsolute(configPath), `.codex/config.toml must not hardcode absolute config_file paths: ${configPath}`); + const relativeToCodex = path.join('.codex', configPath); + assertCondition( + existsSync(path.join(rootDir, relativeToCodex)), + `.codex/config.toml references a missing agent config: ${relativeToCodex}`, + ); + } + } + + const serverDockerfile = readIfExists('server/Dockerfile') ?? ''; + assertCondition(/FROM node:/i.test(serverDockerfile), 'server/Dockerfile must build from a Node base image'); + assertCondition(/npm run build/.test(serverDockerfile), 'server/Dockerfile must build the Nest workspace'); + assertCondition(/docker-entrypoint\.sh/.test(serverDockerfile), 'server/Dockerfile must use the repository entrypoint'); + + const clientDockerfile = readIfExists('client/Dockerfile') ?? ''; + assertCondition(/FROM nginx:/i.test(clientDockerfile), 'client/Dockerfile must use nginx for runtime serving'); + assertCondition(/COPY nginx\/default\.conf/.test(clientDockerfile), 'client/Dockerfile must install the nginx proxy config'); + assertCondition(/COPY --from=build \/app\/dist/.test(clientDockerfile), 'client/Dockerfile must copy the built SPA bundle'); + + const nginxConfig = readIfExists('client/nginx/default.conf') ?? ''; + assertCondition(/location \/api\//.test(nginxConfig), 'client/nginx/default.conf must proxy /api requests'); + assertCondition(/try_files \$uri \$uri\/ \/index\.html;/.test(nginxConfig), 'client/nginx/default.conf must preserve SPA routing'); + assertCondition(/proxy_pass/.test(nginxConfig), 'client/nginx/default.conf must proxy backend traffic'); + + const serverEnvExample = readIfExists('server/.env.example') ?? ''; + assertCondition( + /KEYCLOAK_ISSUER_URL="https:\/\/sso\.greact\.ru\/realms\/toir"/.test(serverEnvExample), + 'server/.env.example must keep the working Keycloak issuer example', + ); + assertCondition( + /KEYCLOAK_AUDIENCE="?toir-backend"?/.test(serverEnvExample), + 'server/.env.example must keep the working backend audience example', + ); + assertCondition( + /CORS_ALLOWED_ORIGINS="http:\/\/localhost:5173,https:\/\/toir-frontend\.greact\.ru"/.test(serverEnvExample), + 'server/.env.example must keep the working CORS example with the production frontend domain', + ); + assertCondition( + !/KEYCLOAK_ISSUER_URL=http:\/\/localhost:8080\/realms\/toir/.test(serverEnvExample), + 'server/.env.example must not regress to localhost Keycloak as the baseline issuer example', + ); + + const clientEnvExample = readIfExists('client/.env.example') ?? ''; + assertCondition( + /VITE_KEYCLOAK_URL=https:\/\/sso\.greact\.ru/.test(clientEnvExample), + 'client/.env.example must keep the working domain-based Keycloak URL example', + ); + assertCondition( + /VITE_KEYCLOAK_REALM=toir/.test(clientEnvExample) && /VITE_KEYCLOAK_CLIENT_ID=toir-frontend/.test(clientEnvExample), + 'client/.env.example must keep the working realm and frontend client examples', + ); + assertCondition( + !/VITE_KEYCLOAK_URL=http:\/\/localhost:8080/.test(clientEnvExample), + 'client/.env.example must not regress to localhost Keycloak as the baseline example', + ); + + const healthController = readIfExists('server/src/health/health.controller.ts') ?? ''; + assertCondition(Boolean(healthController), 'Missing file: server/src/health/health.controller.ts'); + if (healthController) { + assertCondition( + /@Public\(\)/.test(healthController) && /@Controller\('health'\)/.test(healthController), + '/health must stay public', + ); + } +} + +function runCommand(command, commandArgs, workdir, failureLabel) { + const runtimeEnv = { ...process.env }; + const envExamplePath = path.join(workdir, '.env.example'); + if (existsSync(envExamplePath)) { + const envExample = readFileSync(envExamplePath, 'utf8'); + for (const line of envExample.split(/\r?\n/)) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) { + continue; + } + + const separator = trimmed.indexOf('='); + if (separator <= 0) { + continue; + } + + const key = trimmed.slice(0, separator).trim(); + const value = trimmed.slice(separator + 1).trim().replace(/^"|"$/g, ''); + if (!(key in runtimeEnv)) { + runtimeEnv[key] = value; + } + } + } + + const commandLine = [command, ...commandArgs].join(' '); + const result = spawnSync(commandLine, { + cwd: workdir, + encoding: 'utf8', + stdio: 'pipe', + shell: true, + env: runtimeEnv, + }); + + if (result.error) { + failures.push(`${failureLabel}: ${commandLine}\n${result.error.message}`); + return false; + } + + if (result.status !== 0) { + const stderr = result.stderr?.trim(); + const stdout = result.stdout?.trim(); + failures.push( + `${failureLabel}: ${commandLine}${stderr ? `\n${stderr}` : stdout ? `\n${stdout}` : ''}`, + ); + return false; + } + + return true; +} + +function maybeValidateWorkspaceBuild(relativeDir) { + const workspaceDir = path.join(rootDir, relativeDir); + if (!existsSync(path.join(workspaceDir, 'package.json'))) { + failures.push(`Missing file: ${relativeDir}/package.json`); + return; + } + + if (!existsSync(path.join(workspaceDir, 'node_modules'))) { + warn(`Skipped build verification for ${relativeDir}: install dependencies in ${relativeDir}/ to validate workspace buildability.`); + return; + } + + runCommand('npm', ['run', 'build'], workspaceDir, `Build verification failed in ${relativeDir}`); +} + +function validateBuildExecutionChecks() { + maybeValidateWorkspaceBuild('server'); + maybeValidateWorkspaceBuild('client'); +} + +function validateRuntimeExecutionChecks() { + const serverDir = path.join(rootDir, 'server'); + if (!existsSync(path.join(serverDir, 'node_modules'))) { + failures.push( + 'Runtime validation requires installed backend dependencies. Run `npm install` in server/ before `npm run validate:generation:runtime`.', + ); + return; + } + + runCommand('npx', ['prisma', 'generate'], serverDir, 'Prisma generate failed'); + const migrationsDir = path.join(serverDir, 'prisma', 'migrations'); + const hasMigrations = + existsSync(migrationsDir) && + readdirSync(migrationsDir, { withFileTypes: true }).some((entry) => entry.isDirectory()); + + if (hasMigrations) { + runCommand('npx', ['prisma', 'migrate', 'deploy'], serverDir, 'Prisma migrate deploy failed'); + } else { + warn('No committed Prisma migrations found; runtime validation is using `prisma db push` as a temporary bootstrap fallback.'); + runCommand('npx', ['prisma', 'db', 'push'], serverDir, 'Prisma db push failed'); + } + runCommand('npx', ['prisma', 'db', 'seed'], serverDir, 'Prisma seed failed'); +} + +// --------------------------------------------------------------------------- +// Structural validator scope only: +// keep stable scaffold/runtime/auth/realm/build invariants here. +// Entity-level DSL fidelity and CRUD/UI semantics are owned by `npm run eval:generation`. +// --------------------------------------------------------------------------- + +validateBuildChecks(); +validateAuthChecks(); +validateRealmChecks(); +validateRuntimeContractChecks(); + +if (!artifactsOnly) { + validateBuildExecutionChecks(); +} + +if (!artifactsOnly && runRuntime) { + validateRuntimeExecutionChecks(); +} else if (!artifactsOnly) { + warn('Runtime command execution skipped. Use --run-runtime after installing dependencies and starting the local database.'); +} + +for (const warning of warnings) { + console.warn(`WARN: ${warning}`); +} + +if (failures.length > 0) { + console.error('Generation validation failed:'); + for (const failure of failures) { + console.error(`- ${failure}`); + } + process.exit(1); +} + +console.log('Generation validation passed.'); diff --git a/AGENTS.md b/AGENTS.md index 6403d24..544f8e1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,8 +25,9 @@ Generation is driven by a single authoritative source file: | `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. | +| `.codex/AGENTS.md` | Codex-specific agent governance supplement (Codex runtime only). | +| `.claude/CLAUDE.md` | Claude Code-specific agent governance supplement. **MANDATORY for Claude Code sessions.** Defines subagent registry, orchestration entry points, write-zone enforcement, MCP tool access. | +| `prompts/claude-orchestration-rules.md` | Claude Code orchestration and subagent delegation rules. **MANDATORY when orchestrating subagents.** Defines shallow delegation pattern, contract freeze, acceptance protocol, failure handling, write-zone boundaries. | ### Tier 2 — deterministic derivative (generated by script; never edited manually) diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..544f8e1 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,476 @@ +# 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 (Codex runtime only). | +| `.claude/CLAUDE.md` | Claude Code-specific agent governance supplement. **MANDATORY for Claude Code sessions.** Defines subagent registry, orchestration entry points, write-zone enforcement, MCP tool access. | +| `prompts/claude-orchestration-rules.md` | Claude Code orchestration and subagent delegation rules. **MANDATORY when orchestrating subagents.** Defines shallow delegation pattern, contract freeze, acceptance protocol, failure handling, write-zone boundaries. | + +### 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//` | `domain/*.api.dsl` + `prompts/backend-rules.md` | +| `client/src/resources//` | `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.` 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= +OPENAI_BASE_URL=https://openrouter.ai/api/v1 +OPENAI_MODEL= +``` + +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.` — 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) diff --git a/IMPLEMENTATION_EXAMPLES.md b/IMPLEMENTATION_EXAMPLES.md new file mode 100644 index 0000000..85d791b --- /dev/null +++ b/IMPLEMENTATION_EXAMPLES.md @@ -0,0 +1,637 @@ +# 💻 Практические примеры реализации оптимизаций + +## ⚠️ Status: Partial Implementation + +The following optimizations have been **moved to actual code implementation** via the Claude Code prompt and removed from this file: +- ✅ Graceful Error Handling → `CLAUDE_CODE_PROMPT.md` Phase 1 +- ✅ Performance Monitoring → `CLAUDE_CODE_PROMPT.md` Phase 4 + +This document now focuses on **remaining optimization examples** that are still in design/planning phase and waiting for implementation. + +--- + +## 1. Incremental Generation с Caching + +### 1.1 Система кэширования (cache-manager.ts) + +```typescript +// tools/cache-manager.ts +import * as crypto from 'crypto'; +import * as fs from 'fs'; +import * as path from 'path'; + +interface CacheEntry { + hash: string; + timestamp: number; + value: any; +} + +export class GenerationCache { + private cacheDir = './.generation-cache'; + + constructor() { + if (!fs.existsSync(this.cacheDir)) { + fs.mkdirSync(this.cacheDir, { recursive: true }); + } + } + + /** + * Вычислить хеш входных данных + */ + computeHash(input: any): string { + const content = JSON.stringify(input, Object.keys(input).sort()); + return crypto.createHash('sha256').update(content).digest('hex'); + } + + /** + * Получить значение из кэша + */ + get(key: string, input: any): T | null { + const hash = this.computeHash(input); + const cachePath = path.join(this.cacheDir, `${key}.json`); + + if (!fs.existsSync(cachePath)) { + return null; + } + + try { + const cached: CacheEntry = JSON.parse(fs.readFileSync(cachePath, 'utf-8')); + if (cached.hash === hash) { + console.log(`✅ Cache hit for ${key}`); + return cached.value; + } + } catch (e) { + // Cache file corrupted, regenerate + } + + return null; + } + + /** + * Сохранить значение в кэш + */ + set(key: string, input: any, value: any): void { + const hash = this.computeHash(input); + const cachePath = path.join(this.cacheDir, `${key}.json`); + + const entry: CacheEntry = { + hash, + timestamp: Date.now(), + value, + }; + + fs.writeFileSync(cachePath, JSON.stringify(entry, null, 2)); + } + + /** + * Очистить старые кэши (>7 дней) + */ + cleanup(maxAgeDays = 7): void { + const maxAge = maxAgeDays * 24 * 60 * 60 * 1000; + const now = Date.now(); + + fs.readdirSync(this.cacheDir).forEach(file => { + const cachePath = path.join(this.cacheDir, file); + const cached: CacheEntry = JSON.parse(fs.readFileSync(cachePath, 'utf-8')); + + if (now - cached.timestamp > maxAge) { + fs.unlinkSync(cachePath); + console.log(`🗑️ Deleted old cache: ${file}`); + } + }); + } +} + +export const cache = new GenerationCache(); +``` + +### 1.2 Использование в orchestrator.ts + +```typescript +// tools/orchestrator.ts (updated) +import { cache } from './cache-manager'; + +async function orchestrate(task: string): Promise { + const dslContent = readDSL('domain/toir.api.dsl'); + + // Проверить кэш + const cachedContract = cache.get('frozen-contract', dslContent); + let contract = cachedContract || freezeContract(dslContent); + + if (!cachedContract) { + cache.set('frozen-contract', dslContent, contract); + } + + // Для Prisma: проверить кэш перед генерацией + const cachedPrismaSchema = cache.get('prisma-schema', contract); + let prismaOutput; + + if (cachedPrismaSchema) { + prismaOutput = cachedPrismaSchema; + } else { + prismaOutput = await agent('generator_prisma', { + contract, + task: 'Generate Prisma schema' + }); + cache.set('prisma-schema', contract, prismaOutput); + } + + // ... аналогично для других генераторов +} +``` + +--- + +## 2. Параллельная генерация + +### 2.1 Параллельный orchestrator + +```typescript +// tools/orchestrator-parallel.ts +async function orchestrateParallel(task: string): Promise { + const contract = freezeContract(readDSL('domain/toir.api.dsl')); + + // Независимые генерации - запустить в параллель + const [prismaOutput, nestOutput, reactOutput] = await Promise.all([ + // Prisma не зависит ни от чего + agent('generator_prisma', { + contract, + task: 'Generate Prisma schema' + }), + + // NestJS зависит от Prisma (но не блокирующая зависимость) + agent('generator_nest_resources', { + contract, + // Может получить Prisma результаты позже + task: 'Generate NestJS resources' + }), + + // React независим от NestJS на этапе генерации ресурсов + agent('generator_react_admin_resources', { + contract, + task: 'Generate React Admin resources' + }) + ]); + + // ПОТОМ: когда все завершены, интегрировать и валидировать + const dataAccessOutput = await agent('generator_data_access', { + contract, + nestModules: nestOutput, + task: 'Integrate data access' + }); + + // Финальная валидация + const reviewed = await agent('reviewer', { + outputs: { + prisma: prismaOutput, + nest: nestOutput, + react: reactOutput, + dataAccess: dataAccessOutput + }, + task: 'Validate all outputs' + }); + + return reviewed; +} +``` + +--- + +## 3. Plugin System + +### 3.1 Plugin Interface + +```typescript +// types/generator-plugin.ts +export interface GeneratorHooks { + /** + * Вызывается перед началом всей генерации + */ + beforeGeneration?: (contract: FrozenContract) => Promise; + + /** + * После фриза контракта, но перед первой генерацией + */ + afterContractFreeze?: (contract: FrozenContract) => Promise; + + /** + * После генерации Prisma schema + */ + afterPrismaGeneration?: (schema: string) => Promise; + + /** + * После генерации NestJS модулей + */ + afterNestResourcesGeneration?: (modules: GeneratedModule[]) => Promise; + + /** + * После генерации React ресурсов + */ + afterReactResourcesGeneration?: (resources: GeneratedResource[]) => Promise; + + /** + * Финальная интеграция перед валидацией + */ + beforeReview?: (outputs: AllOutputs) => Promise; + + /** + * На ошибку в любом агенте + */ + onGenerationError?: (error: Error, stage: string) => Promise; +} + +export interface GeneratorPlugin { + name: string; + version: string; + description: string; + hooks: GeneratorHooks; +} +``` + +### 3.2 Plugin Manager + +```typescript +// tools/plugin-manager.ts +export class PluginManager { + private plugins: GeneratorPlugin[] = []; + + loadPlugins(pluginDir: string): void { + const files = fs.readdirSync(pluginDir); + + files.forEach(file => { + if (file.endsWith('.plugin.ts') || file.endsWith('.plugin.js')) { + const pluginPath = path.join(pluginDir, file); + const plugin = require(pluginPath).default as GeneratorPlugin; + + this.plugins.push(plugin); + console.log(`📦 Loaded plugin: ${plugin.name} v${plugin.version}`); + } + }); + } + + async executeHook( + hookName: keyof GeneratorHooks, + input: any, + context: { stage?: string; error?: Error } + ): Promise { + let result = input; + + for (const plugin of this.plugins) { + const hook = plugin.hooks[hookName]; + if (hook) { + try { + result = await hook(result); + console.log(`✅ ${plugin.name}.${hookName}`); + } catch (e) { + console.error(`❌ ${plugin.name}.${hookName} failed:`, e); + if (plugin.hooks.onGenerationError) { + await plugin.hooks.onGenerationError(e as Error, context.stage || 'unknown'); + } + } + } + } + + return result; + } +} + +export const pluginManager = new PluginManager(); +``` + +### 3.3 Пример plugin'а + +```typescript +// plugins/oauth2-plugin.plugin.ts +import { GeneratorPlugin } from '../types/generator-plugin'; + +export default { + name: 'oauth2-auth', + version: '1.0.0', + description: 'Add OAuth2 support to generated schema and auth', + + hooks: { + afterPrismaGeneration: async (schema: string) => { + // Добавить OAuth2 таблицы + const oauthTables = ` + model OAuth2Provider { + id String @id @default(cuid()) + name String @unique + clientId String + clientSecret String + createdAt DateTime @default(now()) + } + + model OAuth2Token { + id String @id @default(cuid()) + userId String + providerId String + accessToken String + refreshToken String? + expiresAt DateTime + user User @relation(fields: [userId], references: [id]) + } + `; + + return schema + '\n' + oauthTables; + }, + + afterNestResourcesGeneration: async (modules) => { + // Добавить OAuth2 контроллер + const oauth2Module = { + name: 'oauth2', + files: { + 'oauth2.controller.ts': ` + import { Controller, Get, Query } from '@nestjs/common'; + + @Controller('auth/oauth2') + export class OAuth2Controller { + @Get('callback') + async handleCallback(@Query('code') code: string) { + // OAuth2 callback logic + } + } + ` + } + }; + + return [...modules, oauth2Module]; + } + } +} as GeneratorPlugin; +``` + +--- + +## 4. OpenAPI as Intermediate Representation + +### 4.1 DSL → OpenAPI Generator + +```typescript +// tools/dsl-to-openapi.ts +import { FrozenContract } from './types'; +import { OpenAPI, Info, Paths } from 'openapi3-ts/oas30'; + +export function dslToOpenAPI(contract: FrozenContract): OpenAPI { + const openapi: OpenAPI = { + openapi: '3.1.0', + info: { + title: contract.appName || 'Generated API', + version: contract.version || '1.0.0', + description: contract.description || '' + } as Info, + paths: {} as Paths, + components: { + schemas: {} + } + }; + + // Для каждого entity - генерировать endpoints + contract.entities.forEach(entity => { + const basePath = `/${entity.plural || entity.name}`; + + // GET /entities + openapi.paths![`${basePath}`] = { + get: { + operationId: `list${entity.name}`, + tags: [entity.name], + responses: { + '200': { + description: `List of ${entity.plural}`, + content: { + 'application/json': { + schema: { + type: 'array', + items: { $ref: `#/components/schemas/${entity.name}` } + } + } + } + } + } + }, + post: { + operationId: `create${entity.name}`, + tags: [entity.name], + requestBody: { + content: { + 'application/json': { + schema: { $ref: `#/components/schemas/${entity.name}CreateDTO` } + } + } + }, + responses: { + '201': { + description: `Created ${entity.name}`, + content: { + 'application/json': { + schema: { $ref: `#/components/schemas/${entity.name}` } + } + } + } + } + } + }; + + // GET /entities/{id} + openapi.paths![`${basePath}/{id}`] = { + get: { + operationId: `get${entity.name}`, + parameters: [ + { name: 'id', in: 'path', required: true, schema: { type: 'string' } } + ], + tags: [entity.name], + responses: { + '200': { + description: `${entity.name} details`, + content: { + 'application/json': { + schema: { $ref: `#/components/schemas/${entity.name}` } + } + } + } + } + }, + put: { + operationId: `update${entity.name}`, + parameters: [ + { name: 'id', in: 'path', required: true, schema: { type: 'string' } } + ], + tags: [entity.name], + requestBody: { + content: { + 'application/json': { + schema: { $ref: `#/components/schemas/${entity.name}UpdateDTO` } + } + } + }, + responses: { + '200': { + description: `Updated ${entity.name}`, + content: { + 'application/json': { + schema: { $ref: `#/components/schemas/${entity.name}` } + } + } + } + } + }, + delete: { + operationId: `delete${entity.name}`, + parameters: [ + { name: 'id', in: 'path', required: true, schema: { type: 'string' } } + ], + tags: [entity.name], + responses: { + '204': { + description: 'Deleted successfully' + } + } + } + }; + + // Добавить schema для entity + openapi.components!.schemas![entity.name] = { + type: 'object', + properties: Object.fromEntries( + entity.fields.map(field => [ + field.name, + { type: mapFieldTypeToOpenAPI(field.type) } + ]) + ), + required: entity.fields.filter(f => f.required).map(f => f.name) + }; + }); + + return openapi; +} + +function mapFieldTypeToOpenAPI(fieldType: string): string { + const mapping: Record = { + 'string': 'string', + 'int': 'integer', + 'float': 'number', + 'boolean': 'boolean', + 'date': 'string', // format: date + 'datetime': 'string', // format: date-time + }; + return mapping[fieldType] || 'string'; +} +``` + +### 4.2 Usage в package.json + +```json +{ + "scripts": { + "generate:api-summary": "ts-node tools/api-summary-generator.ts", + "generate:openapi": "ts-node tools/dsl-to-openapi.ts", + "generate:docs": "npm run generate:openapi && swagger-cli bundle openapi.json --outfile docs/api.html", + "generate:client-sdk": "openapi-generator-cli generate -i openapi.json -g typescript-fetch -o client/src/generated" + } +} +``` + +--- + +## 5. Type Safety с Zod + +### 5.1 DSL Validation Schema + +```typescript +// tools/validation/dsl-schema.ts +import { z } from 'zod'; + +export const FieldSchema = z.object({ + name: z.string().min(1), + type: z.enum(['string', 'int', 'float', 'boolean', 'date', 'datetime']), + required: z.boolean().default(true), + unique: z.boolean().default(false), + indexed: z.boolean().default(false), +}); + +export const EntitySchema = z.object({ + name: z.string().min(1), + plural: z.string().optional(), + description: z.string().optional(), + fields: z.array(FieldSchema).min(1), + timestamps: z.boolean().default(true), +}); + +export const RelationshipSchema = z.object({ + from: z.string(), + to: z.string(), + type: z.enum(['one-to-one', 'one-to-many', 'many-to-many']), + cascade: z.boolean().default(false), +}); + +export const DSLSchema = z.object({ + appName: z.string().min(1), + version: z.string().default('1.0.0'), + entities: z.array(EntitySchema), + relationships: z.array(RelationshipSchema).optional(), + auth: z.object({ + enabled: z.boolean().default(true), + providers: z.array(z.string()).optional(), + }).optional(), +}); + +export type DSL = z.infer; +export type Entity = z.infer; +export type Field = z.infer; +``` + +### 5.2 Validation в orchestrator + +```typescript +// tools/orchestrator.ts (with validation) +import { DSLSchema, DSL } from './validation/dsl-schema'; + +async function orchestrate(task: string): Promise { + const rawDSL = readDSL('domain/toir.api.dsl'); + + // Валидировать перед началом + let validatedDSL: DSL; + try { + validatedDSL = DSLSchema.parse(rawDSL); + console.log('✅ DSL validation passed'); + } catch (error) { + console.error('❌ DSL validation failed:'); + console.error(error.issues); + process.exit(1); + } + + // Продолжить с validated data + const contract = freezeContract(validatedDSL); + // ... +} +``` + +--- + +> **Removed:** Sections 6 (Nx Caching Configuration) and 8 (placeholder) have +> been removed. Nx caching is tracked as a future recommendation, not a worked +> example. Graceful Error Handling and Performance Monitoring are now fully +> implemented — see `tools/orchestrator.ts` (`generate()`, `GenerationOutput`, +> `runTask()`) and `tools/performance-monitor.ts` (`PerformanceMonitor` class) +> for the production code paths instead of illustrative snippets. + +--- + +## Заключение + +Эти примеры показывают как: +1. **Кэшировать** результаты генерации +2. **Параллелизировать** независимые операции +3. **Расширять** систему через плагины +4. **Генерировать** OpenAPI для документации и SDK +5. **Валидировать** входные данные + +Реализованные оптимизации (уже в репозитории): +- **Graceful error handling + parallel generation** → + `tools/orchestrator.ts` (`generate()`, `Promise.allSettled`, per-stage + try/catch, discriminated-union `GenerationStatus`). +- **Performance monitoring** → `tools/performance-monitor.ts` + (`PerformanceMonitor.mark/measure/summary/export`), отчёт в + `generation-metrics.json`. +- **MCP-валидаторы** → `tools/mcp/{prisma,npm,nest}-validator.mjs` + + `tools/mcp/lib/mcp-server.mjs` (минимальный JSON-RPC stdio сервер без + внешних зависимостей). diff --git a/agents/definitions.ts b/agents/definitions.ts new file mode 100644 index 0000000..92037be --- /dev/null +++ b/agents/definitions.ts @@ -0,0 +1,169 @@ +/** + * Claude Agent SDK — KIS-TOiR Agent Definitions + * + * This file defines all specialized subagents for the KIS-TOiR generation pipeline. + * Agents are invoked programmatically by the orchestrator via Claude Agent SDK. + * + * Each agent has: + * - description: Clear criteria for when Claude should delegate to this agent + * - prompt: Agent-specific instructions loaded from .claude/agents/*.toml + * - tools: Sandbox-limited toolset per role + * - model: Optional model override + */ + +import { AgentDefinition } from "@anthropic-ai/claude-agent-sdk"; +import fs from "fs"; +import path from "path"; +import { fileURLToPath } from "url"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +/** + * Load developer instructions from .claude/agents/*.toml config files. + * Extracts the developer_instructions markdown block. + */ +function loadAgentInstructions(agentName: string): string { + const tomlPath = path.join( + __dirname, + "..", + ".claude", + "agents", + `${agentName}.toml` + ); + + if (!fs.existsSync(tomlPath)) { + throw new Error( + `Agent config not found: ${tomlPath}. Ensure .claude/agents/${agentName}.toml exists.` + ); + } + + const content = fs.readFileSync(tomlPath, "utf-8"); + const match = content.match(/developer_instructions = """([\s\S]*?)"""/); + + if (!match) { + throw new Error( + `No developer_instructions found in ${agentName}.toml. Check TOML format.` + ); + } + + return match[1].trim(); +} + +/** + * KIS-TOiR Specialized Agent Registry + * + * All agents share access to MCP servers defined in .claude/config.toml: + * - github: repository and PR context + * - context7: official framework documentation + * - exa: web search fallback + * - memory: persistent cross-session context + * - playwright: browser automation for UI/runtime verification + * - sequential-thinking: structured multi-step reasoning + */ +export const agents: Record = { + /** + * explorer + * + * Discovery and codebase exploration. Use for: + * - Understanding project structure and finding files + * - Tracing execution paths and existing integrations + * - Locating entity-scoped DSL context + * - Inspecting scaffold health and registration seams + */ + explorer: { + description: + "Codebase discovery and exploration specialist. Use for understanding project structure, finding files, tracing execution paths, locating existing registrations and integration seams.", + prompt: loadAgentInstructions("explorer"), + tools: ["Read", "Glob", "Grep"], + model: "haiku", + }, + + /** + * docs_researcher + * + * Official documentation research and framework verification. Use for: + * - Verifying current framework behavior (NestJS, Prisma, React Admin, etc.) + * - Checking CLI scaffolding conventions + * - Auth/runtime/deployment planning questions + * - Version-sensitive behavior clarification + */ + docs_researcher: { + description: + "Framework documentation specialist. Use for verifying current behavior of NestJS, Prisma, React Admin, Vite, Docker, nginx, or Keycloak/OIDC against official docs.", + prompt: loadAgentInstructions("docs-researcher"), + tools: ["Read"], + model: "haiku", + }, + + /** + * generator_prisma + * + * Prisma schema generation and management. Delegated only after contract freeze. + * Write zone: server/prisma/schema.prisma only. + */ + generator_prisma: { + description: + "Prisma schema generator. Use ONLY after contract freeze to generate or repair server/prisma/schema.prisma from frozen contract and domain DSL.", + prompt: loadAgentInstructions("generator_prisma"), + tools: ["Read", "Write", "Edit", "Bash", "Glob"], + model: "opus", + }, + + /** + * generator_nest_resources + * + * NestJS resource module generation. Delegated only after contract freeze. + * Write zones: server/src/modules// and optionally server/src/app.module.ts + */ + generator_nest_resources: { + description: + "NestJS backend resource generator. Use ONLY after contract freeze to generate server/src/modules// controllers, services, and DTOs from frozen contract.", + prompt: loadAgentInstructions("generator_nest_resources"), + tools: ["Read", "Write", "Edit", "Bash", "Glob"], + model: "opus", + }, + + /** + * generator_react_admin_resources + * + * React Admin resource generation. Delegated only after contract freeze. + * Write zone: client/src/resources// only. + */ + generator_react_admin_resources: { + description: + "React Admin frontend resource generator. Use ONLY after contract freeze to generate client/src/resources// List, Create, Edit, and Show components from frozen contract.", + prompt: loadAgentInstructions("generator_react_admin_resources"), + tools: ["Read", "Write", "Edit", "Bash", "Glob"], + model: "opus", + }, + + /** + * generator_data_access + * + * Frontend data access layer generation. Delegated only after contract freeze. + * Write zones: narrowly delegated portions of client/src/dataProvider.ts only. + */ + generator_data_access: { + description: + "Frontend data access specialist. Use ONLY after contract freeze to generate or repair client/src/dataProvider.ts API integration from frozen contract.", + prompt: loadAgentInstructions("generator_data_access"), + tools: ["Read", "Write", "Edit", "Bash", "Glob"], + model: "opus", + }, + + /** + * reviewer + * + * Final review and validation. Use only after integration and validation gates. + * Read-only mode. Can propose changes but must not write directly. + */ + reviewer: { + description: + "Final code and contract reviewer. Use ONLY after integration and validation to perform quality, security, DSL fidelity, and compliance review.", + prompt: loadAgentInstructions("reviewer"), + tools: ["Read", "Grep", "Glob"], + model: "sonnet", + }, +}; + +export default agents; diff --git a/api-summary.json b/api-summary.json index b808e4f..4f600ed 100644 --- a/api-summary.json +++ b/api-summary.json @@ -2,11 +2,34 @@ "sourceFiles": [ "domain/toir.api.dsl" ], - "enums": [], + "enums": [ + { + "name": "EquipmentStatus", + "description": null, + "values": [ + { + "name": "Active", + "label": "В эксплуатации" + }, + { + "name": "Repair", + "label": "В ремонте" + }, + { + "name": "Reserve", + "label": "В резерве" + }, + { + "name": "WriteOff", + "label": "Списано" + } + ] + } + ], "dtos": [ { "name": "DTO.Equipment", - "description": "Полный response-объект для единицы оборудования", + "description": "Полный объект оборудования", "fields": [ { "name": "id", @@ -15,7 +38,7 @@ "nullable": false, "unique": false, "primary": false, - "description": null, + "description": "Идентификатор оборудования", "map": "Equipment.id", "sync": false, "label": null @@ -84,7 +107,7 @@ }, { "name": "DTO.EquipmentCreate", - "description": "Тело запроса на создание единицы оборудования", + "description": "Тело запроса на создание оборудования", "fields": [ { "name": "name", @@ -137,8 +160,8 @@ { "name": "status", "type": "EquipmentStatus", - "required": true, - "nullable": false, + "required": false, + "nullable": true, "unique": false, "primary": false, "description": "Текущий статус", @@ -150,7 +173,7 @@ }, { "name": "DTO.EquipmentUpdate", - "description": "Тело запроса на обновление единицы оборудования", + "description": "Тело запроса на обновление оборудования (частичное)", "fields": [ { "name": "name", @@ -216,8 +239,20 @@ }, { "name": "DTO.EquipmentListRequest", - "description": "Запрос для постраничного получения списка оборудования с фильтрацией", + "description": "Запрос постраничного списка оборудования с фильтрацией", "fields": [ + { + "name": "filter", + "type": "DTO.Filter", + "required": false, + "nullable": true, + "unique": false, + "primary": false, + "description": "Фильтр", + "map": null, + "sync": false, + "label": null + }, { "name": "page", "type": "DTO.PageRequest", @@ -225,43 +260,7 @@ "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, + "description": "Параметры пагинации", "map": null, "sync": false, "label": null @@ -270,7 +269,7 @@ }, { "name": "DTO.EquipmentListResponse", - "description": "Ответ с постраничным списком оборудования и метаданными", + "description": "Ответ со списком оборудования", "fields": [ { "name": "content", @@ -279,7 +278,7 @@ "nullable": false, "unique": false, "primary": false, - "description": null, + "description": "Список оборудования", "map": null, "sync": false, "label": null @@ -291,7 +290,7 @@ "nullable": false, "unique": false, "primary": false, - "description": null, + "description": "Метаданные пагинации", "map": null, "sync": false, "label": null @@ -300,16 +299,16 @@ }, { "name": "DTO.ChangeEquipmentStatus", - "description": "Полный response-объект для документа изменения статуса", + "description": "Полный объект документа изменения статуса оборудования", "fields": [ { "name": "equipmentId", - "type": "Equipment", + "type": "uuid", "required": false, - "nullable": true, + "nullable": false, "unique": false, "primary": false, - "description": null, + "description": "Оборудование", "map": "ChangeEquipmentStatus.equipmentId", "sync": false, "label": null @@ -370,12 +369,12 @@ "fields": [ { "name": "equipmentId", - "type": "Equipment", - "required": false, - "nullable": true, + "type": "uuid", + "required": true, + "nullable": false, "unique": false, "primary": false, - "description": null, + "description": "Оборудование", "map": "ChangeEquipmentStatus.equipmentId", "sync": false, "label": null @@ -432,16 +431,16 @@ }, { "name": "DTO.ChangeEquipmentStatusUpdate", - "description": "Тело запроса на обновление документа изменения статуса", + "description": "Тело запроса на обновление документа изменения статуса (частичное)", "fields": [ { "name": "equipmentId", - "type": "Equipment", + "type": "uuid", "required": false, "nullable": true, "unique": false, "primary": false, - "description": null, + "description": "Оборудование", "map": "ChangeEquipmentStatus.equipmentId", "sync": false, "label": null @@ -498,8 +497,20 @@ }, { "name": "DTO.ChangeEquipmentStatusListRequest", - "description": "Запрос для постраничного получения списка документов изменения статуса с фильтрацией", + "description": "Запрос постраничного списка документов изменения статуса с фильтрацией", "fields": [ + { + "name": "filter", + "type": "DTO.Filter", + "required": false, + "nullable": true, + "unique": false, + "primary": false, + "description": "Фильтр", + "map": null, + "sync": false, + "label": null + }, { "name": "page", "type": "DTO.PageRequest", @@ -507,55 +518,7 @@ "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, + "description": "Параметры пагинации", "map": null, "sync": false, "label": null @@ -564,7 +527,7 @@ }, { "name": "DTO.ChangeEquipmentStatusListResponse", - "description": "Ответ с постраничным списком документов изменения статуса и метаданными", + "description": "Ответ со списком документов изменения статуса", "fields": [ { "name": "content", @@ -573,7 +536,7 @@ "nullable": false, "unique": false, "primary": false, - "description": null, + "description": "Список документов изменения статуса", "map": null, "sync": false, "label": null @@ -585,7 +548,7 @@ "nullable": false, "unique": false, "primary": false, - "description": null, + "description": "Метаданные пагинации", "map": null, "sync": false, "label": null @@ -596,7 +559,7 @@ "apis": [ { "name": "API.Equipment", - "description": "API управления справочником оборудования", + "description": "API управления оборудованием", "endpoints": [ { "name": "listEquipment", @@ -622,12 +585,12 @@ "label": "GET /equipment/{id}", "method": "GET", "path": "/equipment/{id}", - "description": "Получить единицу оборудования по идентификатору", + "description": "Получить оборудование по идентификатору", "attributes": [ { "name": "id", "type": "uuid", - "description": null + "description": "Идентификатор оборудования" }, { "name": "response", @@ -641,7 +604,7 @@ "label": "POST /equipment", "method": "POST", "path": "/equipment", - "description": "Создать новую единицу оборудования", + "description": "Создать оборудование", "attributes": [ { "name": "request", @@ -655,12 +618,12 @@ "label": "PUT /equipment/{id}", "method": "PUT", "path": "/equipment/{id}", - "description": "Обновить данные единицы оборудования", + "description": "Обновить оборудование", "attributes": [ { "name": "id", "type": "uuid", - "description": null + "description": "Идентификатор оборудования" }, { "name": "request", @@ -674,26 +637,26 @@ "label": "DELETE /equipment/{id}", "method": "DELETE", "path": "/equipment/{id}", - "description": "Удалить единицу оборудования", + "description": "Удалить оборудование", "attributes": [ { "name": "id", "type": "uuid", - "description": null + "description": "Идентификатор оборудования" } ] } ] }, { - "name": "API.EquipmentStatusChange", + "name": "API.ChangeEquipmentStatus", "description": "API управления документами изменения статуса оборудования", "endpoints": [ { - "name": "listStatusChanges", - "label": "POST /status-changes/page", + "name": "listChangeEquipmentStatus", + "label": "POST /change-equipment-status/page", "method": "POST", - "path": "/status-changes/page", + "path": "/change-equipment-status/page", "description": "Постраничный список документов изменения статуса с фильтрацией", "attributes": [ { @@ -709,16 +672,21 @@ ] }, { - "name": "getStatusChange", - "label": "GET /status-changes/{id}", + "name": "getChangeEquipmentStatus", + "label": "GET /change-equipment-status/{equipmentId}/{newStatus}", "method": "GET", - "path": "/status-changes/{id}", - "description": "Получить документ изменения статуса по идентификатору", + "path": "/change-equipment-status/{equipmentId}/{newStatus}", + "description": "Получить документ изменения статуса по ключу", "attributes": [ { - "name": "id", + "name": "equipmentId", "type": "uuid", - "description": null + "description": "Оборудование" + }, + { + "name": "newStatus", + "type": "EquipmentStatus", + "description": "Новый статус" }, { "name": "response", @@ -728,11 +696,11 @@ ] }, { - "name": "createStatusChange", - "label": "POST /status-changes", + "name": "createChangeEquipmentStatus", + "label": "POST /change-equipment-status", "method": "POST", - "path": "/status-changes", - "description": "Создать документ изменения статуса оборудования", + "path": "/change-equipment-status", + "description": "Создать документ изменения статуса", "attributes": [ { "name": "request", @@ -742,16 +710,21 @@ ] }, { - "name": "updateStatusChange", - "label": null, - "method": null, - "path": null, + "name": "updateChangeEquipmentStatus", + "label": "PUT /change-equipment-status/{equipmentId}/{newStatus}", + "method": "PUT", + "path": "/change-equipment-status/{equipmentId}/{newStatus}", "description": "Обновить документ изменения статуса", "attributes": [ { - "name": "id", + "name": "equipmentId", "type": "uuid", - "description": null + "description": "Оборудование" + }, + { + "name": "newStatus", + "type": "EquipmentStatus", + "description": "Новый статус" }, { "name": "request", @@ -761,16 +734,21 @@ ] }, { - "name": "deleteStatusChange", - "label": "DELETE /status-changes/{id}", + "name": "deleteChangeEquipmentStatus", + "label": "DELETE /change-equipment-status/{equipmentId}/{newStatus}", "method": "DELETE", - "path": "/status-changes/{id}", + "path": "/change-equipment-status/{equipmentId}/{newStatus}", "description": "Удалить документ изменения статуса", "attributes": [ { - "name": "id", + "name": "equipmentId", "type": "uuid", - "description": null + "description": "Оборудование" + }, + { + "name": "newStatus", + "type": "EquipmentStatus", + "description": "Новый статус" } ] } diff --git a/docs/generation-playbook.md b/docs/generation-playbook.md index 018326f..250634f 100644 --- a/docs/generation-playbook.md +++ b/docs/generation-playbook.md @@ -1,7 +1,7 @@ # Generation Playbook Step-by-step instructions for generating and regenerating artifacts in this repository. -Read `AGENTS.md` and `docs/source-of-truth.md` first. +Read `AGENTS.md` first. For source-of-truth hierarchy details, see AGENTS.md §Source-of-truth hierarchy. --- diff --git a/domain/toir.api.dsl b/domain/toir.api.dsl index 6272a2a..c067045 100644 --- a/domain/toir.api.dsl +++ b/domain/toir.api.dsl @@ -1,31 +1,57 @@ +enum EquipmentStatus { + value Active { + label "В эксплуатации"; + } + value Repair { + label "В ремонте"; + } + value Reserve { + label "В резерве"; + } + value WriteOff { + label "Списано"; + } +} + +// ===================== +// DTO +// ===================== + dto DTO.Equipment { - description "Полный response-объект для единицы оборудования"; + description "Полный объект оборудования"; + attribute id { type uuid; + description "Идентификатор оборудования"; 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 "Текущий статус"; @@ -34,234 +60,261 @@ dto DTO.Equipment { } dto DTO.EquipmentCreate { - description "Тело запроса на создание единицы оборудования"; + description "Тело запроса на создание оборудования"; + attribute name { type string; - description "Название оборудования"; is required; + description "Название оборудования"; map Equipment.name; } + attribute serialNumber { type string; - description "Заводской (серийный) номер"; is required; + 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; + is nullable; description "Текущий статус"; - is required; map Equipment.status; } } dto DTO.EquipmentUpdate { - description "Тело запроса на обновление единицы оборудования"; + description "Тело запроса на обновление оборудования (частичное)"; + attribute name { type string; - description "Название оборудования"; is nullable; + description "Название оборудования"; map Equipment.name; } + attribute serialNumber { type string; - description "Заводской (серийный) номер"; is nullable; + 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 "Текущий статус"; is nullable; + description "Текущий статус"; map Equipment.status; } } dto DTO.EquipmentListRequest { - description "Запрос для постраничного получения списка оборудования с фильтрацией"; + description "Запрос постраничного списка оборудования с фильтрацией"; + + attribute filter { + type DTO.Filter; + is nullable; + description "Фильтр"; + } + attribute page { type DTO.PageRequest; - } - attribute filterName { - type string; - is nullable; - } - attribute filterSerialNumber { - type string; - is nullable; - } - attribute filterStatus { - type EquipmentStatus; - is nullable; + description "Параметры пагинации"; } } dto DTO.EquipmentListResponse { - description "Ответ с постраничным списком оборудования и метаданными"; + description "Ответ со списком оборудования"; + attribute content { type DTO.Equipment[]; + description "Список оборудования"; } + attribute pageInfo { type DTO.PageInfo; + description "Метаданные пагинации"; } } dto DTO.ChangeEquipmentStatus { - description "Полный response-объект для документа изменения статуса"; + description "Полный объект документа изменения статуса оборудования"; + attribute equipmentId { - type Equipment; - is nullable; + type uuid; + description "Оборудование"; map ChangeEquipmentStatus.equipmentId; } + attribute newStatus { type EquipmentStatus; description "Новый статус"; map ChangeEquipmentStatus.newStatus; } + attribute number { type string; - description "Номер"; is nullable; + description "Номер"; map ChangeEquipmentStatus.number; } + attribute date { type date; description "Дата изменения статуса"; map ChangeEquipmentStatus.date; } + attribute responsible { type string; - description "Ответственный"; is nullable; + description "Ответственный"; map ChangeEquipmentStatus.responsible; } } dto DTO.ChangeEquipmentStatusCreate { description "Тело запроса на создание документа изменения статуса"; + attribute equipmentId { - type Equipment; - is nullable; + type uuid; + is required; + description "Оборудование"; map ChangeEquipmentStatus.equipmentId; } + attribute newStatus { type EquipmentStatus; - description "Новый статус"; is required; + description "Новый статус"; map ChangeEquipmentStatus.newStatus; } + attribute number { type string; - description "Номер"; is nullable; + description "Номер"; map ChangeEquipmentStatus.number; } + attribute date { type date; - description "Дата изменения статуса"; is required; + description "Дата изменения статуса"; map ChangeEquipmentStatus.date; } + attribute responsible { type string; - description "Ответственный"; is nullable; + description "Ответственный"; map ChangeEquipmentStatus.responsible; } } dto DTO.ChangeEquipmentStatusUpdate { - description "Тело запроса на обновление документа изменения статуса"; + description "Тело запроса на обновление документа изменения статуса (частичное)"; + attribute equipmentId { - type Equipment; + type uuid; is nullable; + description "Оборудование"; map ChangeEquipmentStatus.equipmentId; } + attribute newStatus { type EquipmentStatus; - description "Новый статус"; is nullable; + description "Новый статус"; map ChangeEquipmentStatus.newStatus; } + attribute number { type string; - description "Номер"; is nullable; + description "Номер"; map ChangeEquipmentStatus.number; } + attribute date { type date; - description "Дата изменения статуса"; is nullable; + description "Дата изменения статуса"; map ChangeEquipmentStatus.date; } + attribute responsible { type string; - description "Ответственный"; is nullable; + description "Ответственный"; map ChangeEquipmentStatus.responsible; } } dto DTO.ChangeEquipmentStatusListRequest { - description "Запрос для постраничного получения списка документов изменения статуса с фильтрацией"; + description "Запрос постраничного списка документов изменения статуса с фильтрацией"; + + attribute filter { + type DTO.Filter; + is nullable; + 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; + description "Параметры пагинации"; } } dto DTO.ChangeEquipmentStatusListResponse { - description "Ответ с постраничным списком документов изменения статуса и метаданными"; + description "Ответ со списком документов изменения статуса"; + attribute content { type DTO.ChangeEquipmentStatus[]; + description "Список документов изменения статуса"; } + attribute pageInfo { type DTO.PageInfo; + description "Метаданные пагинации"; } } +// ===================== +// API +// ===================== + api API.Equipment { - description "API управления справочником оборудования"; + description "API управления оборудованием"; endpoint listEquipment { label "POST /equipment/page"; @@ -276,9 +329,10 @@ api API.Equipment { endpoint getEquipment { label "GET /equipment/{id}"; - description "Получить единицу оборудования по идентификатору"; + description "Получить оборудование по идентификатору"; attribute id { type uuid; + description "Идентификатор оборудования"; } attribute response { type DTO.Equipment; @@ -287,7 +341,7 @@ api API.Equipment { endpoint createEquipment { label "POST /equipment"; - description "Создать новую единицу оборудования"; + description "Создать оборудование"; attribute request { type DTO.EquipmentCreate; } @@ -295,9 +349,10 @@ api API.Equipment { endpoint updateEquipment { label "PUT /equipment/{id}"; - description "Обновить данные единицы оборудования"; + description "Обновить оборудование"; attribute id { type uuid; + description "Идентификатор оборудования"; } attribute request { type DTO.EquipmentUpdate; @@ -306,18 +361,19 @@ api API.Equipment { endpoint deleteEquipment { label "DELETE /equipment/{id}"; - description "Удалить единицу оборудования"; + description "Удалить оборудование"; attribute id { type uuid; + description "Идентификатор оборудования"; } } } -api API.EquipmentStatusChange { +api API.ChangeEquipmentStatus { description "API управления документами изменения статуса оборудования"; - endpoint listStatusChanges { - label "POST /status-changes/page"; + endpoint listChangeEquipmentStatus { + label "POST /change-equipment-status/page"; description "Постраничный список документов изменения статуса с фильтрацией"; attribute request { type DTO.ChangeEquipmentStatusListRequest; @@ -327,41 +383,56 @@ api API.EquipmentStatusChange { } } - endpoint getStatusChange { - label "GET /status-changes/{id}"; - description "Получить документ изменения статуса по идентификатору"; - attribute id { + endpoint getChangeEquipmentStatus { + label "GET /change-equipment-status/{equipmentId}/{newStatus}"; + description "Получить документ изменения статуса по ключу"; + attribute equipmentId { type uuid; + description "Оборудование"; + } + attribute newStatus { + type EquipmentStatus; + description "Новый статус"; } attribute response { type DTO.ChangeEquipmentStatus; } } - endpoint createStatusChange { - label "POST /status-changes"; - description "Создать документ изменения статуса оборудования"; + endpoint createChangeEquipmentStatus { + label "POST /change-equipment-status"; + description "Создать документ изменения статуса"; attribute request { type DTO.ChangeEquipmentStatusCreate; } } - endpoint updateStatusChange { - labelо "PUT /status-changes/{id}"; + endpoint updateChangeEquipmentStatus { + label "PUT /change-equipment-status/{equipmentId}/{newStatus}"; description "Обновить документ изменения статуса"; - attribute id { + attribute equipmentId { type uuid; + description "Оборудование"; + } + attribute newStatus { + type EquipmentStatus; + description "Новый статус"; } attribute request { type DTO.ChangeEquipmentStatusUpdate; } } - endpoint deleteStatusChange { - label "DELETE /status-changes/{id}"; + endpoint deleteChangeEquipmentStatus { + label "DELETE /change-equipment-status/{equipmentId}/{newStatus}"; description "Удалить документ изменения статуса"; - attribute id { + attribute equipmentId { type uuid; + description "Оборудование"; + } + attribute newStatus { + type EquipmentStatus; + description "Новый статус"; } } } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..8d2fb73 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2215 @@ +{ + "name": "toir-generation-context", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "toir-generation-context", + "devDependencies": { + "@anthropic-ai/claude-agent-sdk": "^0.2.0", + "tsx": "^4.19.3", + "typescript": "^5.9.3" + } + }, + "node_modules/@anthropic-ai/claude-agent-sdk": { + "version": "0.2.92", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.2.92.tgz", + "integrity": "sha512-loYyxVUC5gBwHjGi9Fv0b84mduJTp9Z3Pum+y/7IVQDb4NynKfVQl6l4VeDKZaW+1QTQtd25tY4hwUznD7Krqw==", + "dev": true, + "license": "SEE LICENSE IN README.md", + "dependencies": { + "@anthropic-ai/sdk": "^0.80.0", + "@modelcontextprotocol/sdk": "^1.27.1" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "^0.34.2", + "@img/sharp-darwin-x64": "^0.34.2", + "@img/sharp-linux-arm": "^0.34.2", + "@img/sharp-linux-arm64": "^0.34.2", + "@img/sharp-linux-x64": "^0.34.2", + "@img/sharp-linuxmusl-arm64": "^0.34.2", + "@img/sharp-linuxmusl-x64": "^0.34.2", + "@img/sharp-win32-arm64": "^0.34.2", + "@img/sharp-win32-x64": "^0.34.2" + }, + "peerDependencies": { + "zod": "^4.0.0" + } + }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.80.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.80.0.tgz", + "integrity": "sha512-WeXLn7zNVk3yjeshn+xZHvld6AoFUOR3Sep6pSoHho5YbSi6HwcirqgPA5ccFuW8QTVJAAU7N8uQQC6Wa9TG+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-schema-to-ts": "^3.1.1" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz", + "integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz", + "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz", + "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz", + "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz", + "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz", + "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz", + "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz", + "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz", + "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz", + "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz", + "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz", + "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz", + "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz", + "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz", + "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz", + "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz", + "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz", + "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz", + "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz", + "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz", + "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz", + "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz", + "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz", + "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz", + "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz", + "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz", + "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@hono/node-server": { + "version": "1.19.13", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.13.tgz", + "integrity": "sha512-TsQLe4i2gvoTtrHje625ngThGBySOgSK3Xo2XRYOdqGN1teR8+I7vchQC46uLJi8OF62YTYA3AhSpumtkhsaKQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", + "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", + "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", + "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", + "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", + "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", + "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", + "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", + "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", + "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", + "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", + "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", + "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", + "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", + "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", + "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", + "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.29.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", + "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/body-parser": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", + "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", + "dev": true, + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.1", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "dev": true, + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz", + "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.7", + "@esbuild/android-arm": "0.27.7", + "@esbuild/android-arm64": "0.27.7", + "@esbuild/android-x64": "0.27.7", + "@esbuild/darwin-arm64": "0.27.7", + "@esbuild/darwin-x64": "0.27.7", + "@esbuild/freebsd-arm64": "0.27.7", + "@esbuild/freebsd-x64": "0.27.7", + "@esbuild/linux-arm": "0.27.7", + "@esbuild/linux-arm64": "0.27.7", + "@esbuild/linux-ia32": "0.27.7", + "@esbuild/linux-loong64": "0.27.7", + "@esbuild/linux-mips64el": "0.27.7", + "@esbuild/linux-ppc64": "0.27.7", + "@esbuild/linux-riscv64": "0.27.7", + "@esbuild/linux-s390x": "0.27.7", + "@esbuild/linux-x64": "0.27.7", + "@esbuild/netbsd-arm64": "0.27.7", + "@esbuild/netbsd-x64": "0.27.7", + "@esbuild/openbsd-arm64": "0.27.7", + "@esbuild/openbsd-x64": "0.27.7", + "@esbuild/openharmony-arm64": "0.27.7", + "@esbuild/sunos-x64": "0.27.7", + "@esbuild/win32-arm64": "0.27.7", + "@esbuild/win32-ia32": "0.27.7", + "@esbuild/win32-x64": "0.27.7" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "dev": true, + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "dev": true, + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz", + "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.3.2.tgz", + "integrity": "sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ip-address": "10.1.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-tsconfig": { + "version": "4.13.7", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.7.tgz", + "integrity": "sha512-7tN6rFgBlMgpBML5j8typ92BKFi2sFQvIdpAqLA2beia5avZDrMs0FLZiM5etShWq5irVyGcGMEA1jcDaK7A/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.12.12", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.12.tgz", + "integrity": "sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/ip-address": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz", + "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.2.tgz", + "integrity": "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz", + "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true, + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tsx": { + "version": "4.21.0", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz", + "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.27.0", + "get-tsconfig": "^4.7.5" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "dev": true, + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/zod": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", + "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "dev": true, + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + } + } +} diff --git a/package.json b/package.json index 524587b..4558442 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,7 @@ { "name": "toir-generation-context", "private": true, + "type": "module", "scripts": { "generate:api-summary": "node tools/generate-api-summary.mjs", "generate:openapi": "node tools/api-summary-to-openapi.mjs --out openapi.json", @@ -8,6 +9,12 @@ "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" + "install-hooks": "node tools/install-hooks.mjs", + "orchestrate": "node --import tsx/esm tools/orchestrator.ts" + }, + "devDependencies": { + "@anthropic-ai/claude-agent-sdk": "^0.2.0", + "tsx": "^4.19.3", + "typescript": "^5.9.3" } } diff --git a/prompts/claude-orchestration-rules.md b/prompts/claude-orchestration-rules.md new file mode 100644 index 0000000..2dfc498 --- /dev/null +++ b/prompts/claude-orchestration-rules.md @@ -0,0 +1,390 @@ +# Claude Code Orchestration & Subagent Management Rules + +**For Claude Code agents coordinating KIS-TOiR generation. This file is mandatory when delegating to subagents.** + +This document complements `AGENTS.md` with Claude-specific patterns and MCP/subagent governance. + +--- + +## Subagent Model + +KIS-TOiR uses **Claude Agent SDK subagents** — specialized agents defined programmatically in `agents/definitions.ts` and coordinated via `tools/orchestrator.ts`. + +### Subagent Registry + +All subagents: +- Load instructions from `.claude/agents/*.toml` configuration files +- Share access to project-local MCP servers (github, context7, exa, memory, playwright, sequential-thinking) +- Operate under strict write-zone enforcement +- Report results back to the orchestrator for acceptance/rejection + +| Agent | Purpose | Sandbox | Model | +|-------|---------|---------|-------| +| `explorer` | Codebase discovery & exploration | read-only | haiku | +| `docs_researcher` | Framework docs verification | read-only | haiku | +| `generator_prisma` | Prisma schema generation | workspace-write | opus | +| `generator_nest_resources` | NestJS backend generation | workspace-write | opus | +| `generator_react_admin_resources` | React Admin generation | workspace-write | opus | +| `generator_data_access` | Frontend data-access integration | workspace-write | opus | +| `reviewer` | Final artifact review | read-only | sonnet | + +### How Agents Are Invoked + +Subagents are **not manually called by name**. Instead: + +1. **Claude reads agent descriptions** from `agents/definitions.ts` +2. **Claude matches task intent to agent description** — e.g., "generate the Prisma schema" → matches `generator_prisma` +3. **Claude invokes via the `Agent` tool** — which must be in `allowedTools` +4. **Subagent receives full prompt context** — including frozen contract, DSL, and sandbox restrictions + +**Example trigger pattern:** +``` +"The frozen contract specifies these entities: [DSL slice]. +Use the generator_prisma agent to generate server/prisma/schema.prisma." +``` + +Claude will automatically recognize `generator_prisma` and invoke it with its bounded instructions. + +--- + +## Orchestrator Responsibilities + +The **orchestrator** (main Claude agent running in Claude Code) owns: + +1. **Discovery** — Use `explorer` to understand current workspace state +2. **Docs Verification** — Use `docs_researcher` to verify framework behavior +3. **Contract Freeze** — Produce explicit normalized contract before generator delegation +4. **Specialized Delegation** — Delegate bounded work to each generator after contract freeze +5. **Acceptance/Rejection** — Explicit accept/reject of delegated outputs based on: + - Write-zone compliance (did it only touch allowed files?) + - Contract adherence (does output match frozen contract?) + - Integration readiness (is it ready for parent integration?) +6. **Integration** — Wire accepted outputs into shared platform seams +7. **Validation** — Run both gates before claiming completion: + - `node tools/validate-generation.mjs --artifacts-only` + - `npm run eval:generation` +8. **Final Review** — Hand off to `reviewer` agent only after validation passes + +--- + +## Mandatory Delegation Workflow + +### Phase 1: Discovery & Docs Verification + +**Who:** Orchestrator + `explorer` + `docs_researcher` + +**When:** At session start, before any generation planning + +**Triggers:** +``` +"Use the explorer agent to scan the repository structure and identify: +- Current workspace state (do server/ and client/ exist?) +- Existing registrations in app.module.ts and App.tsx +- Current schema.prisma and data layer shape +- Existing auth/runtime/deploy artifacts" +``` + +**Expected output:** +- Clear picture of what exists and what is missing +- Identified registration seams +- Current scaffold health + +### Phase 2: Contract Freeze + +**Who:** Orchestrator only + +**When:** After discovery, before any specialized generator starts + +**Process:** +1. Extract entity-scoped DSL slices from `domain/toir.api.dsl` +2. Read relevant prompt docs (prisma-rules.md, backend-rules.md, etc.) +3. Produce normalized contract covering: + - Entities and fields + - Types and nullability + - IDs and composite keys + - Relations + - Enums + - Endpoint conventions + - Write-zones per generator + +**Critical:** Do not skip this step. Generators depend on an explicit frozen contract. + +### Phase 3: Parallel Specialized Generation + +**Who:** Orchestrator delegates to specialized generators + +**Conditions:** +- Contract must be frozen and explicit +- Each generator must receive clear write-zone boundaries +- Parent must be ready to accept/reject each output + +**Delegation examples:** + +``` +"The frozen contract specifies entities: [list]. +Use the generator_prisma agent to generate server/prisma/schema.prisma. +Write-zone: server/prisma/schema.prisma ONLY. +Frozen contract: [explicit contract structure]" +``` + +``` +"The frozen contract specifies the ChangeEquipmentStatus resource: [details]. +Use the generator_nest_resources agent to generate the NestJS backend module. +Write-zone: server/src/modules/change-equipment-status/ ONLY. +Frozen contract: [details]" +``` + +### Phase 4: Acceptance & Integration + +**Who:** Orchestrator + +**Process:** +1. Examine delegated output against write-zones (did it only touch allowed files?) +2. Check contract adherence (does it match frozen contract?) +3. Explicit accept or reject +4. If rejected: allow ONE bounded repair pass from the generator +5. If still rejected: use manual fallback (not silent continuation) +6. Integrate accepted outputs into shared platform seams + +**Acceptance checklist:** +- ✅ Only allowed write-zones changed +- ✅ No cross-layer edits outside delegated zone +- ✅ Output matches frozen contract +- ✅ Output is integration-ready +- ✅ No unresolved issues + +### Phase 5: Validation & Final Review + +**Who:** Orchestrator + `reviewer` + +**Gates (both must pass):** +```bash +node tools/validate-generation.mjs --artifacts-only +npm run eval:generation +``` + +**Process:** +1. Run both validation gates +2. If either fails: surface the failure explicitly +3. Allow ONE bounded repair from relevant generator +4. Use `reviewer` agent to check final artifact quality +5. Only claim completion when reviewer signoff + both gates pass + +--- + +## MCP Tool Access + +All agents share access to these MCP servers: + +| Server | Use for | When | +|--------|---------|------| +| **github** | PR context, repo history, issue links | When parent needs remote context | +| **context7** | Official NestJS, Prisma, React Admin, Vite, Docker, Keycloak/OIDC/JWT docs | Before framework-sensitive planning | +| **exa** | Web search for current behavior, release notes, breaking changes | Only after Context7 is insufficient | +| **memory** | Persistent cross-session notes (use sparingly) | For durable repo context only | +| **playwright** | Browser automation for UI/runtime verification | When read-only code inspection is insufficient | +| **sequential-thinking** | Structured multi-step reasoning for complex issues | For ambiguous conflicts or multi-finding investigations | + +**Tool-order policy:** +1. Local authoritative files (domain/*.api.dsl, prompts/*.md, AGENTS.md) +2. Context7 official docs +3. Web fallback (exa) +4. Validation gates + +--- + +## Write-Zone Enforcement + +**Authoritative source: `AGENTS.md` §Write-zone ownership.** The table below is an operational quick-reference; if it ever conflicts with `AGENTS.md`, `AGENTS.md` wins. + +**Critical rule:** Generators are sandboxed to specific write-zones. Violating these boundaries is grounds for rejection. + +| Agent | Allowed Write Zones | Forbidden | +|-------|-------|----------| +| `generator_prisma` | `server/prisma/schema.prisma` | Everything else | +| `generator_nest_resources` | `server/src/modules//`, optionally `server/src/app.module.ts` | `server/src/auth/`, client/**, prisma, deploy, prompts | +| `generator_react_admin_resources` | `client/src/resources//` | `client/src/auth/`, `client/src/dataProvider.ts`, server/**, deploy, prompts | +| `generator_data_access` | Narrowly delegated parts of `client/src/dataProvider.ts` | Broad dataProvider rewrites, client resources, server/**, auth, deploy | +| `reviewer` | READ-ONLY; may propose patches but not write | All files (read-only mode only) | + +**Parent-owned zones (never delegated):** +- `server/src/auth/`, `client/src/auth/` +- `docker-compose.yml`, `server/Dockerfile`, `client/Dockerfile`, `client/nginx/default.conf` +- `server/.env.example`, `client/.env.example`, `toir-realm.json` +- `prompts/*.md`, `AGENTS.md`, `domain/*.api.dsl`, `tools/` + +--- + +## Failure Handling + +### If a Subagent Output Is Rejected + +1. **Be explicit:** Quote the specific contract violation or write-zone breach +2. **Allow one bounded repair:** "Generator X, repair this specific issue: [issue]. Retry with this constraint: [constraint]." +3. **If repair fails:** Explicitly reject and fall back to manual implementation +4. **Never silently continue:** Do not pretend partial delegated work is complete + +### If Validation Gates Fail + +1. **Surface the failure:** Show the exact validation error +2. **Diagnosis:** Is it a generation defect or a missing artifact? +3. **One bounded repair:** Delegate ONE targeted fix to the relevant generator +4. **If still failing:** Do not claim completion; flag for manual review + +### If Conflict Between Delegated Output and DSL + +1. **Trust the DSL first** — it is Tier 1 source of truth +2. **Surface the conflict explicitly** to the generator +3. **Reject if unfixable** — do not rationalize away DSL violations + +--- + +## Shallow Delegation Pattern + +**One responsibility per agent.** Do not: +- Ask a generator to redesign shared platform seams +- Ask explorer to also generate code +- Mix responsibilities (e.g., "generate Prisma AND wire it into app.module") + +**Instead:** +- `generator_prisma` owns schema.prisma only +- Orchestrator owns app.module.ts wiring and imports +- `generator_nest_resources` owns module internals +- Orchestrator owns module registration in app.module.ts + +This keeps agent context small and failure modes isolated. + +--- + +## Orchestrator Anti-Patterns + +❌ **Don't:** +1. Write code yourself when a generator exists for that task +2. Skip contract freeze before delegating to generators +3. Silently accept partial/broken delegated work +4. Let generators redesign shared auth, runtime, or deploy seams +5. Skip validation gates as proof of completion +6. Use broad generators when specialized agents exist +7. Delegate without explicit write-zone boundaries + +✅ **Do:** +1. Use agents intentionally for their specific responsibilities +2. Freeze contract explicitly before any generator starts +3. Examine and explicitly accept/reject each delegated output +4. Run validation gates before final handoff +5. Report completion only when gates pass + reviewer signoff +6. Keep delegation shallow (one primary responsibility) +7. Document acceptance/rejection reasons + +--- + +## Example: Full Delegation Cycle + +``` +ORCHESTRATOR: Read domain/toir.api.dsl. I'll generate ChangeEquipmentStatus. + +↓ [Discovery] +ORCHESTRATOR → explorer agent +"Explore server/src/modules/ and client/src/resources/ to see what exists." +← explorer returns: No change-equipment-status module exists yet + +↓ [Docs Verification] +ORCHESTRATOR → docs_researcher agent +"Verify NestJS composite key patterns and React Admin resource conventions." +← docs_researcher confirms current best practices + +↓ [Contract Freeze - orchestrator only] +ORCHESTRATOR (to itself): +"Frozen contract: +- Entity: ChangeEquipmentStatus +- Fields: equipmentId (ref), newStatus (enum), date (datetime) +- Composite key: (equipmentId, newStatus) +- Endpoints: [list] +- Write-zones: server/src/modules/change-equipment-status/ only" + +↓ [Delegation: Prisma] +ORCHESTRATOR → generator_prisma agent +"Generate schema.prisma with ChangeEquipmentStatus model. +Frozen contract: [details]. Write-zone: server/prisma/schema.prisma ONLY." +← generator_prisma returns schema changes + +ORCHESTRATOR reviews output: +"✅ Only schema.prisma changed. No app.module.ts touched. Matches contract. ACCEPT." + +↓ [Delegation: NestJS Backend] +ORCHESTRATOR → generator_nest_resources agent +"Generate NestJS module for ChangeEquipmentStatus. +Frozen contract: [details]. Write-zone: server/src/modules/change-equipment-status/ ONLY. +Do NOT touch app.module.ts registration." +← generator_nest_resources returns controller, service, DTOs + +ORCHESTRATOR reviews output: +"✅ Only module/ directory touched. No app.module edits. Matches contract. ACCEPT." + +↓ [Parent Integration] +ORCHESTRATOR (to itself): +"Now I wire the accepted module into app.module.ts imports and controller registration." + +↓ [Delegation: React Admin Frontend] +ORCHESTRATOR → generator_react_admin_resources agent +"Generate React Admin resources for ChangeEquipmentStatus. +Frozen contract: [details]. Write-zone: client/src/resources/change-equipment-status/ ONLY." +← generator_react_admin_resources returns List, Create, Edit, Show components + +ORCHESTRATOR reviews output: +"✅ Only resources/ directory touched. Matches contract. ACCEPT." + +↓ [Parent Integration] +ORCHESTRATOR (to itself): +"Now I wire the accepted resources into client/src/App.tsx." + +↓ [Validation] +ORCHESTRATOR (to itself): +```bash +node tools/validate-generation.mjs --artifacts-only +npm run eval:generation +``` +Result: ✅ Both pass + +↓ [Final Review] +ORCHESTRATOR → reviewer agent +"Review the ChangeEquipmentStatus implementation for quality, security, DSL fidelity." +← reviewer returns findings and signoff + +ORCHESTRATOR (to itself): +"Reviewer signoff ✅, validation gates ✅, all success criteria met. +Claiming ChangeEquipmentStatus generation COMPLETE." +``` + +--- + +## Session Handoff Protocol + +When handing off work between Claude Code sessions: + +1. **Memory capsule:** Use the `memory` MCP server sparingly to capture: + - Current frozen contract status + - Which generators have been accepted/rejected and why + - Current validation gate status + - Identified next steps + +2. **Explicit state:** Do not assume previous session context. Restart discovery if uncertain. + +3. **Validation continuity:** Do not skip gates just because "the previous session said it was done." + +--- + +## Companion Documents + +These documents are referenced by specialized agents: + +- **Agents**: `.claude/CLAUDE.md` (Claude-specific agent governance) +- **General orchestration**: `prompts/general-prompt.md` +- **Prisma rules**: `prompts/prisma-rules.md` (for `generator_prisma`) +- **Backend rules**: `prompts/backend-rules.md` (for `generator_nest_resources`) +- **Frontend rules**: `prompts/frontend-rules.md` (for `generator_react_admin_resources`) +- **Auth rules**: `prompts/auth-rules.md` (for orchestrator + auth seams) +- **Runtime rules**: `prompts/runtime-rules.md` (for orchestrator + deploy seams) +- **Validation rules**: `prompts/validation-rules.md` (for validation gates) + +When delegating to any agent, ensure they can read relevant companion docs. diff --git a/prompts/general-prompt.md b/prompts/general-prompt.md index e8fae39..d924b5a 100644 --- a/prompts/general-prompt.md +++ b/prompts/general-prompt.md @@ -2,10 +2,16 @@ 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. +Own the full run: +1. Understand the current workspace and domain contract +2. Delegate bounded work to specialized subagents (explorer, docs_researcher, generators, reviewer) +3. Coordinate via Claude Agent SDK orchestrator pattern +4. Accept/reject delegated outputs based on write-zone compliance and contract adherence +5. Integrate accepted outputs and run required validation gates +6. Stop only when repository is genuinely generation-complete + +**Critical:** Do not write code yourself when specialized agents exist for the task. +Use shallow delegation with explicit write-zones and contract freeze before any generator starts. # Project Description @@ -71,36 +77,66 @@ Rules: # Orchestration Model +**See `prompts/claude-orchestration-rules.md` for full Claude Code orchestration details.** + 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. +- Keep one orchestrator in charge of planning, sequencing, integration, and final acceptance +- Delegate bounded work to specialists; do not let subagents redefine source hierarchy or completion criteria +- Use shallow delegation only: one primary responsibility per subagent and explicit write-zones +- Delegate by artifact family and by entity only when parallelism does not create write-zone overlap +- If a subagent result conflicts with 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: +## Mandatory Delegation Pattern -- `explorer` +Subagents are invoked via Claude Agent SDK based on description matching. Use explicit language: + +- **`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` +Example: "Use the explorer agent to scan the repository and identify what exists." + +- **`docs_researcher`** +Use when framework behavior, CLI scaffolding, auth/runtime planning need verification against official docs or Context7. +Example: "Use the docs_researcher agent to verify NestJS module wiring patterns." + +- **`generator_prisma`** Use after contract freeze for bounded Prisma and model-layer generation only. -- `generator_nest_resources` +Example: "Use the generator_prisma agent to generate server/prisma/schema.prisma." +Write-zone: `server/prisma/schema.prisma` ONLY. + +- **`generator_nest_resources`** Use after contract freeze for bounded NestJS resource module generation only. -- `generator_react_admin_resources` +Example: "Use the generator_nest_resources agent to generate the ChangeEquipmentStatus backend module." +Write-zone: `server/src/modules//` only (optionally `server/src/app.module.ts` if explicitly delegated). + +- **`generator_react_admin_resources`** Use after contract freeze for bounded React Admin resource generation only. -- `generator_data_access` +Example: "Use the generator_react_admin_resources agent to generate the ChangeEquipmentStatus frontend resources." +Write-zone: `client/src/resources//` 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. +Example: "Use the generator_data_access agent to integrate the dataProvider with ChangeEquipmentStatus." +Write-zone: Narrowly delegated parts of `client/src/dataProvider.ts` only. -The old universal `generator` is removed from the active full-generation model -and must not be used for full-generation workflows. +- **`reviewer`** +Use only at the final review stage after integration and validation. Reviewer checks DSL fidelity, prompt-contract compliance, and whether validation output supports completion claim. +Example: "Use the reviewer agent to perform final quality and security review." +Mode: READ-ONLY (may propose patches, not write). -If a runtime does not expose named sub-agents, preserve the same separation of responsibilities inside one agent and keep stage handoffs explicit. +## Subagent Invocation + +Subagents are not manually named. Instead: +1. Orchestrator reads agent descriptions from `agents/definitions.ts` +2. Claude matches task intent to description (e.g., "generate schema" → `generator_prisma`) +3. `Agent` tool (from allowedTools) invokes matching subagent +4. Subagent executes bounded task with sandbox restrictions +5. Orchestrator examines output and explicitly accepts/rejects + +**Critical:** `Agent` must be in `allowedTools` for subagent delegation to work. + +The old universal `generator` is removed from the active full-generation model. # Contract Freeze @@ -162,8 +198,7 @@ Tool-order policy: # Documentation-first rule -Before the parent plans or repairs framework-sensitive seams, it must review -current official documentation rather than relying on memory alone. + 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, @@ -484,13 +519,16 @@ Generation is successful only if all of the following are true: # Companion Rule Documents -These documents are mandatory when their stage is active: +**Orchestration & Subagent Management (Claude Code):** +- `prompts/claude-orchestration-rules.md` — MANDATORY when delegating to subagents; defines write-zones, acceptance protocol, failure handling -- 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` +**Artifact-Specific Rules (loaded by agents at delegation time):** +- Prisma stage: `prompts/prisma-rules.md` (for `generator_prisma`) +- Backend stage: `prompts/backend-rules.md` (for `generator_nest_resources`) +- Frontend stage: `prompts/frontend-rules.md` (for `generator_react_admin_resources`) +- Auth / realm stage: `prompts/auth-rules.md` (for orchestrator + auth seams) +- Runtime / bootstrap stage: `prompts/runtime-rules.md` (for orchestrator + deploy seams) +- Verification stage: `prompts/validation-rules.md` (for validation gates) -The master prompt owns orchestration. Companion docs own artifact-specific detail. +The master prompt owns orchestration and subagent coordination. +Companion docs own artifact-specific detail and agent-specific constraints. diff --git a/tools/lib/project-root.mjs b/tools/lib/project-root.mjs new file mode 100644 index 0000000..ce88130 --- /dev/null +++ b/tools/lib/project-root.mjs @@ -0,0 +1,15 @@ +/** + * Resolve the KIS-TOiR project root directory. + * + * Works from any module file in the tools/ directory by walking up + * relative to __dirname. + */ + +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +export function getProjectRoot() { + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + // From tools/lib, go up two levels: ../.. = project root + return path.resolve(path.join(__dirname, "..", "..")); +} diff --git a/tools/mcp/lib/mcp-server.mjs b/tools/mcp/lib/mcp-server.mjs new file mode 100644 index 0000000..ae95109 --- /dev/null +++ b/tools/mcp/lib/mcp-server.mjs @@ -0,0 +1,185 @@ +/** + * Minimal Model Context Protocol (MCP) server over stdio. + * + * Implements just enough of the MCP JSON-RPC 2.0 surface to expose + * a static list of read-only validation tools to a Claude Code client: + * - initialize + * - tools/list + * - tools/call + * + * We intentionally avoid the @modelcontextprotocol/sdk dependency here — + * the KIS-TOiR optimization policy forbids adding new npm packages for + * these lightweight validators, so we speak raw JSON-RPC on stdin/stdout + * with Node built-ins only. + * + * Tool contract: + * { + * name: string, + * description: string, + * inputSchema?: JSONSchema, + * execute: (args: object) => Promise<{ success: boolean, result?, error? }> + * } + * + * execute() must be read-only, must resolve quickly (<500ms target), and + * must NEVER throw — wrap failures in { success: false, error }. + */ + +import readline from "node:readline"; + +const PROTOCOL_VERSION = "2024-11-05"; + +// JSON-RPC 2.0 constants +const JSONRPC_VERSION = "2.0"; +const FIELD_JSONRPC = "jsonrpc"; +const FIELD_ID = "id"; +const FIELD_METHOD = "method"; +const FIELD_PARAMS = "params"; +const FIELD_RESULT = "result"; +const FIELD_ERROR = "error"; +const FIELD_CODE = "code"; +const FIELD_MESSAGE = "message"; +const FIELD_DATA = "data"; +const CONTENT_TYPE_TEXT = "text"; +const FIELD_CONTENT = "content"; +const FIELD_TYPE = "type"; +const FIELD_IS_ERROR = "isError"; + +function write(obj) { + // MCP framing over stdio is line-delimited JSON (one JSON object per line). + process.stdout.write(JSON.stringify(obj) + "\n"); +} + +function ok(id, result) { + write({ [FIELD_JSONRPC]: JSONRPC_VERSION, [FIELD_ID]: id, [FIELD_RESULT]: result }); +} + +function fail(id, code, message, data) { + write({ + [FIELD_JSONRPC]: JSONRPC_VERSION, + [FIELD_ID]: id, + [FIELD_ERROR]: { [FIELD_CODE]: code, [FIELD_MESSAGE]: message, [FIELD_DATA]: data }, + }); +} + +/** + * Start an MCP server. Blocks on stdin until the parent process closes it. + */ +export function runMCPServer({ name, version = "0.1.0", tools }) { + const byName = new Map(tools.map((t) => [t.name, t])); + + const rl = readline.createInterface({ + input: process.stdin, + crlfDelay: Infinity, + }); + + // Log to stderr so we don't corrupt the stdout JSON-RPC channel. + const log = (level, msg) => + process.stderr.write(`[${level}] ${name}: ${msg}\n`); + + log("INFO", `starting (tools=${tools.length})`); + + rl.on("line", async (line) => { + const trimmed = line.trim(); + if (!trimmed) return; + + let req; + try { + req = JSON.parse(trimmed); + } catch (e) { + log("WARN", `invalid JSON on stdin: ${e.message}`); + return; + } + + const { id, method, params } = req; + + // Notifications have no id and expect no response. + const isNotification = id === undefined || id === null; + + try { + if (method === "initialize") { + ok(id, { + protocolVersion: PROTOCOL_VERSION, + capabilities: { tools: { listChanged: false } }, + serverInfo: { name, version }, + }); + return; + } + + if (method === "tools/list") { + ok(id, { + tools: tools.map((t) => ({ + name: t.name, + description: t.description, + inputSchema: t.inputSchema ?? { + [FIELD_TYPE]: "object", + properties: {}, + additionalProperties: true, + }, + })), + }); + return; + } + + if (method === "tools/call") { + const toolName = params?.name; + const tool = byName.get(toolName); + if (!tool) { + fail(id, -32601, `Unknown tool: ${toolName}`); + return; + } + + let result; + try { + // Enforce per-tool timeout: tools MUST resolve within 2000ms. + // Prevents hung tools from blocking the orchestrator. + const toolTimeout = new Promise((_, reject) => + setTimeout( + () => reject(new Error("Tool execution timeout (>2000ms)")), + 2000 + ) + ); + result = await Promise.race([ + tool.execute(params?.arguments ?? {}), + toolTimeout, + ]); + } catch (e) { + // Capture all errors (timeout, execution, etc.) uniformly. + result = { success: false, error: e?.message ?? String(e) }; + } + + ok(id, { + [FIELD_CONTENT]: [ + { + [FIELD_TYPE]: CONTENT_TYPE_TEXT, + text: + typeof result === "string" + ? result + : JSON.stringify(result, null, 2), + }, + ], + [FIELD_IS_ERROR]: result?.success === false, + }); + return; + } + + if (method?.startsWith("notifications/")) { + // Client lifecycle notifications (initialized, cancelled, ...). + return; + } + + if (!isNotification) { + fail(id, -32601, `Method not found: ${method}`); + } + } catch (e) { + log("ERROR", `handler crashed: ${e?.stack ?? e}`); + if (!isNotification) { + fail(id, -32603, "Internal server error", { message: e?.message }); + } + } + }); + + rl.on("close", () => { + log("INFO", "stdin closed, exiting"); + process.exit(0); + }); +} diff --git a/tools/mcp/nest-validator.mjs b/tools/mcp/nest-validator.mjs new file mode 100644 index 0000000..7212ecc --- /dev/null +++ b/tools/mcp/nest-validator.mjs @@ -0,0 +1,158 @@ +#!/usr/bin/env node +/** + * MCP server: NestJS module/controller validator (read-only). + * + * Tools: + * - validate_module_source : assert a TypeScript source string is a + * well-formed Nest module + * - check_app_registration : verify that server/src/app.module.ts + * imports and registers a given module class + * + * Purely lexical — we do not use the TypeScript compiler API (that would + * add a dependency). Regex-level checks are sufficient for the structural + * invariants the orchestrator cares about. + */ + +import fs from "node:fs"; +import path from "node:path"; +import { runMCPServer } from "./lib/mcp-server.mjs"; +import { getProjectRoot } from "../lib/project-root.mjs"; + +const projectRoot = getProjectRoot(); + +// Regex constants for NestJS module validation +const DECORATOR_KEYS_RE = /(?:^|[,{\s])(imports|controllers|providers|exports)\s*:/g; +const IMPORTS_BLOCK_RE = /imports\s*:\s*\[([\s\S]*?)\]/; + +const tools = [ + { + name: "validate_module_source", + description: + "Validate that a TypeScript source string declares a well-formed NestJS module: imports @Module from @nestjs/common, applies the @Module decorator with an object argument, and exports a class. Returns the class name and the decorator keys it declares.", + inputSchema: { + type: "object", + properties: { + source: { type: "string", description: "Contents of a *.module.ts file" }, + }, + required: ["source"], + }, + execute: async ({ source }) => { + if (typeof source !== "string" || source.length === 0) { + return { success: false, error: "source must be a non-empty string" }; + } + + const issues = []; + + if (!/from ['"]@nestjs\/common['"]/.test(source)) { + issues.push("does not import from @nestjs/common"); + } + if (!/\bModule\b/.test(source)) { + issues.push("does not reference the Module symbol"); + } + + const decoratorMatch = source.match(/@Module\s*\(\s*\{([\s\S]*?)\}\s*\)/); + if (!decoratorMatch) { + issues.push("no @Module({...}) decorator found"); + } + + const classMatch = source.match(/export\s+class\s+(\w+)/); + if (!classMatch) { + issues.push("no `export class ` declaration"); + } + + // Extract the top-level keys inside the decorator object so callers + // can sanity-check providers/controllers/imports presence. + const declaredKeys = []; + if (decoratorMatch) { + const body = decoratorMatch[1]; + let m; + while ((m = DECORATOR_KEYS_RE.exec(body)) !== null) { + declaredKeys.push(m[1]); + } + } + + return { + success: issues.length === 0, + result: { + className: classMatch?.[1] ?? null, + declaredKeys, + issues, + }, + }; + }, + }, + { + name: "check_app_registration", + description: + "Check whether server/src/app.module.ts imports and registers a given Nest module class. Useful after generator_nest_resources produces a module, to verify the orchestrator has wired it into the parent-owned app.module.ts.", + inputSchema: { + type: "object", + properties: { + moduleClass: { + type: "string", + description: "e.g. `ChangeEquipmentStatusModule`", + }, + appModulePath: { + type: "string", + description: + "Optional override for the app.module.ts path (relative to project root). Defaults to server/src/app.module.ts.", + }, + }, + required: ["moduleClass"], + }, + execute: async ({ moduleClass, appModulePath }) => { + if (typeof moduleClass !== "string" || !/^[A-Z]\w*Module$/.test(moduleClass)) { + return { + success: false, + error: "moduleClass must be a PascalCase class name ending in Module", + }; + } + + const relPath = appModulePath ?? "server/src/app.module.ts"; + const absPath = path.isAbsolute(relPath) + ? relPath + : path.join(projectRoot, relPath); + + let source: string; + try { + source = fs.readFileSync(absPath, "utf8"); + } catch (err) { + return { + success: false, + error: `failed to read ${relPath}: ${err instanceof Error ? err.message : String(err)}`, + }; + } + + const importRe = new RegExp( + `import\\s*\\{[^}]*\\b${moduleClass}\\b[^}]*\\}\\s*from\\s*['"]([^'"]+)['"]` + ); + const importMatch = source.match(importRe); + + const decoratorMatch = source.match(/@Module\s*\(\s*\{([\s\S]*?)\}\s*\)/); + let registered = false; + if (decoratorMatch) { + const importsBlock = decoratorMatch[1].match(IMPORTS_BLOCK_RE); + if (importsBlock) { + const importedModules = importsBlock[1] + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + registered = importedModules.includes(moduleClass); + } + } + + return { + success: Boolean(importMatch) && registered, + result: { + moduleClass, + appModulePath: relPath, + imported: Boolean(importMatch), + importedFrom: importMatch?.[1] ?? null, + registered, + }, + }; + }, + }, +]; + +runMCPServer({ name: "kis-toir-nest-validator", version: "0.1.0", tools }); diff --git a/tools/mcp/npm-validator.mjs b/tools/mcp/npm-validator.mjs new file mode 100644 index 0000000..be6831c --- /dev/null +++ b/tools/mcp/npm-validator.mjs @@ -0,0 +1,141 @@ +#!/usr/bin/env node +/** + * MCP server: npm package & semver validator (read-only). + * + * Tools: + * - validate_semver : check that a version string is valid semver + * and optionally reject ranges/latest + * - check_lockfile_package : look up a package in the root package-lock.json + * and return its locked version without touching + * the registry + * + * No network access, no CLI invocations. Pure parsing over local files. + */ + +import fs from "node:fs"; +import path from "node:path"; +import { runMCPServer } from "./lib/mcp-server.mjs"; +import { getProjectRoot } from "../lib/project-root.mjs"; + +const projectRoot = getProjectRoot(); + +// SemVer 2.0.0 regex from https://semver.org/ (BSD-licensed). +const SEMVER_RE = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; + +function loadLockfile() { + const lockPath = path.join(projectRoot, "package-lock.json"); + if (!fs.existsSync(lockPath)) return null; + try { + return JSON.parse(fs.readFileSync(lockPath, "utf8")); + } catch { + return null; + } +} + +const tools = [ + { + name: "validate_semver", + description: + "Validate a version string as strict SemVer 2.0.0. When `rejectRanges` is true, reject caret/tilde/latest and require an exact pinned version (the KIS-TOiR version policy). Returns parsed components on success.", + inputSchema: { + type: "object", + properties: { + version: { type: "string", description: "Version string to validate" }, + rejectRanges: { + type: "boolean", + description: + "If true, treat ^, ~, >, <, *, latest as invalid. Default true.", + }, + }, + required: ["version"], + }, + execute: async ({ version, rejectRanges = true }) => { + if (typeof version !== "string" || !version.trim()) { + return { success: false, error: "version must be a non-empty string" }; + } + + const trimmed = version.trim(); + + if (rejectRanges) { + if (/^[\^~><=*]/.test(trimmed) || trimmed === "latest") { + return { + success: false, + error: `version '${trimmed}' is a range or tag; policy requires an exact pinned version`, + }; + } + } + + // Strip a leading range operator if ranges are allowed. + const candidate = rejectRanges ? trimmed : trimmed.replace(/^[\^~><=]+/, ""); + + const m = candidate.match(SEMVER_RE); + if (!m) { + return { + success: false, + error: `'${trimmed}' is not a valid SemVer 2.0.0 version`, + }; + } + + return { + success: true, + result: { + raw: trimmed, + major: Number(m[1]), + minor: Number(m[2]), + patch: Number(m[3]), + prerelease: m[4] ?? null, + build: m[5] ?? null, + }, + }; + }, + }, + { + name: "check_lockfile_package", + description: + "Look up a package inside the root package-lock.json and return its locked version. Read-only; does not contact the npm registry. Returns { found: boolean, version?: string, paths: string[] }.", + inputSchema: { + type: "object", + properties: { + name: { type: "string", description: "Package name, e.g. @nestjs/core" }, + }, + required: ["name"], + }, + execute: async ({ name }) => { + if (typeof name !== "string" || !name.trim()) { + return { success: false, error: "name must be a non-empty string" }; + } + + const lock = loadLockfile(); + if (!lock) { + return { + success: false, + error: "package-lock.json not found or unreadable at project root", + }; + } + + const matches = []; + const packages = lock.packages ?? {}; + for (const [key, value] of Object.entries(packages)) { + // npm v7+ lockfile: keys look like "node_modules/" or + // "node_modules//". Strip the prefix and compare. + if (!key) continue; + const stripped = key.replace(/^.*node_modules\//, ""); + if (stripped === name) { + matches.push({ path: key, version: value.version }); + } + } + + return { + success: true, + result: { + name, + found: matches.length > 0, + occurrences: matches, + }, + }; + }, + }, +]; + +runMCPServer({ name: "kis-toir-npm-validator", version: "0.1.0", tools }); diff --git a/tools/mcp/prisma-validator.mjs b/tools/mcp/prisma-validator.mjs new file mode 100644 index 0000000..00fa315 --- /dev/null +++ b/tools/mcp/prisma-validator.mjs @@ -0,0 +1,178 @@ +#!/usr/bin/env node +/** + * MCP server: Prisma schema validator (read-only). + * + * Tools: + * - validate_schema : structural checks against a Prisma schema string + * - extract_models : return model/enum names and field counts + * + * These are deliberately NOT a shell-out to `prisma validate` — per the + * KIS-TOiR optimization constraints, MCP servers must be pure, synchronous, + * read-only validators with no external deps or CLI subprocess calls. + */ + +import { runMCPServer } from "./lib/mcp-server.mjs"; + +// Prisma schema constants +const BUILTIN_TYPES = new Set([ + "String", + "Int", + "Float", + "Boolean", + "DateTime", + "Json", + "Bytes", + "Decimal", + "BigInt", +]); + +// Regex constants (compiled once, reused across invocations) +const BLOCK_RE = /^\s*(model|enum|datasource|generator)\s+(\w+)\s*\{/gm; +const INLINE_ID_RE = /@id\b/; +const COMPOSITE_ID_RE = /@@id\s*\(/; +const FIELD_RE = /^(\w+)\s+([\w?\[\]]+)/; +const RELATION_RE = /@relation\b/; + +/** + * Extremely lightweight Prisma schema parser. Not a full grammar — it + * recognizes top-level blocks (`model`, `enum`, `datasource`, `generator`) + * and counts fields inside model/enum blocks by line. Sufficient for the + * structural sanity checks the orchestrator asks for. + */ +function parseBlocks(schema) { + const blocks = []; + let m; + while ((m = BLOCK_RE.exec(schema)) !== null) { + const kind = m[1]; + const name = m[2]; + const openIdx = schema.indexOf("{", m.index); + // Walk forward to find the matching close brace. Prisma schemas do not + // nest braces inside blocks, so a simple depth counter is enough. + let depth = 1; + let i = openIdx + 1; + for (; i < schema.length && depth > 0; i++) { + if (schema[i] === "{") depth++; + else if (schema[i] === "}") depth--; + } + const body = schema.slice(openIdx + 1, i - 1); + const fieldLines = body + .split(/\r?\n/) + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("//") && !l.startsWith("@@")); + blocks.push({ kind, name, body, fields: fieldLines }); + } + return blocks; +} + +const tools = [ + { + name: "validate_schema", + description: + "Validate a Prisma schema string for structural soundness: required generator and datasource blocks, at least one model, each model has an @id or @@id, referenced enums exist. Read-only; never writes files.", + inputSchema: { + type: "object", + properties: { + schema: { + type: "string", + description: "Full contents of schema.prisma", + }, + }, + required: ["schema"], + }, + execute: async ({ schema }) => { + if (typeof schema !== "string" || schema.length === 0) { + return { success: false, error: "schema must be a non-empty string" }; + } + + const issues = []; + const blocks = parseBlocks(schema); + + const generators = blocks.filter((b) => b.kind === "generator"); + const datasources = blocks.filter((b) => b.kind === "datasource"); + const models = blocks.filter((b) => b.kind === "model"); + const enums = blocks.filter((b) => b.kind === "enum"); + + if (generators.length === 0) + issues.push("missing generator block (expected `generator client`)"); + if (datasources.length === 0) + issues.push("missing datasource block (expected `datasource db`)"); + if (models.length === 0) issues.push("schema declares no models"); + + const enumNames = new Set(enums.map((e) => e.name)); + + for (const model of models) { + const hasInlineId = INLINE_ID_RE.test(model.body); + const hasCompositeId = COMPOSITE_ID_RE.test(model.body); + if (!hasInlineId && !hasCompositeId) { + issues.push(`model ${model.name} has no @id or @@id directive`); + } + + // Detect referenced types that look like enums but are not declared. + for (const fieldLine of model.fields) { + // field definition: `name Type[?] ...` + const fieldMatch = fieldLine.match(FIELD_RE); + if (!fieldMatch) continue; + const rawType = fieldMatch[2].replace(/[\?\[\]]/g, ""); + if (BUILTIN_TYPES.has(rawType)) continue; + // If a type looks like an enum reference (capitalized, no model match), + // warn when it is not found in declared models or enums. + const isKnownModel = models.some((m) => m.name === rawType); + const isKnownEnum = enumNames.has(rawType); + if (!isKnownModel && !isKnownEnum) { + // Might be a relation target defined later — only flag if it + // looks enum-shaped (all caps first letter, no `@relation` on the line). + if (!RELATION_RE.test(fieldLine)) { + issues.push( + `model ${model.name} field \`${fieldMatch[1]}\` references unknown type \`${rawType}\`` + ); + } + } + } + } + + return { + success: issues.length === 0, + result: { + blockCounts: { + generator: generators.length, + datasource: datasources.length, + model: models.length, + enum: enums.length, + }, + issues, + }, + }; + }, + }, + { + name: "extract_models", + description: + "Extract model and enum names from a Prisma schema string, along with per-model field counts. Useful before diffing against a frozen contract.", + inputSchema: { + type: "object", + properties: { + schema: { type: "string" }, + }, + required: ["schema"], + }, + execute: async ({ schema }) => { + if (typeof schema !== "string") { + return { success: false, error: "schema must be a string" }; + } + const blocks = parseBlocks(schema); + return { + success: true, + result: { + models: blocks + .filter((b) => b.kind === "model") + .map((b) => ({ name: b.name, fieldCount: b.fields.length })), + enums: blocks + .filter((b) => b.kind === "enum") + .map((b) => ({ name: b.name, valueCount: b.fields.length })), + }, + }; + }, + }, +]; + +runMCPServer({ name: "kis-toir-prisma-validator", version: "0.1.0", tools }); diff --git a/tools/orchestrator.ts b/tools/orchestrator.ts new file mode 100644 index 0000000..f87023d --- /dev/null +++ b/tools/orchestrator.ts @@ -0,0 +1,527 @@ +#!/usr/bin/env node + +/** + * KIS-TOiR Orchestrator — Multi-Agent Coordination Engine + * + * This tool uses the Claude Agent SDK to coordinate specialized subagents + * for KIS-TOiR generation workflows. The orchestrator: + * + * 1. Runs discovery + contract freeze via a single orchestrator prompt + * 2. Dispatches bounded generator tasks in parallel streams + * (Prisma / NestJS / React Admin) with graceful error isolation + * 3. Collects per-stream outputs with write-zone + contract accountability + * 4. Emits performance metrics for baseline-vs-optimized comparison + * + * The public entry point `orchestrate(prompt, options)` is preserved for + * backward compatibility. A new `generate(contract, options)` entry point + * exposes the structured graceful-error + parallel pipeline for callers + * that want programmatic control over per-agent failure modes. + * + * USAGE: + * npm run orchestrate "Generate Prisma schema from domain/toir.api.dsl" + */ + +import { query } from "@anthropic-ai/claude-agent-sdk"; +import agents from "../agents/definitions.js"; +import { PerformanceMonitor } from "./performance-monitor.js"; +import { getProjectRoot } from "./lib/project-root.mjs"; +import fs from "fs"; +import path from "path"; +import { fileURLToPath } from "url"; + +const projectRoot = getProjectRoot(); + +// --------------------------------------------------------------------------- +// Types — graceful error handling contract +// --------------------------------------------------------------------------- + +export type GenerationStatus = "success" | "partial" | "failed"; + +export interface GenerationError { + stage: string; + agent: string; + message: string; + timestamp: string; + /** + * Whether a partial artifact was still returned despite this error. + * Reviewers use this flag to decide whether to attempt bounded repair. + */ + partialOutputAvailable: boolean; +} + +export interface AgentRunResult { + agent: string; + stage: string; + /** Whether this stage is allowed to fail without stopping generation. */ + critical: boolean; + ok: boolean; + durationMs: number; + output?: string; + error?: string; +} + +export interface GenerationOutput { + status: GenerationStatus; + runs: AgentRunResult[]; + errors: GenerationError[]; + metrics: ReturnType; + /** Wall-clock ms, end-to-end. */ + totalMs: number; + /** Sum of per-stage durations — a conservative sequential baseline. */ + sequentialBaselineMs: number; + /** Max per-stage duration — the best case for pure parallelism. */ + parallelLowerBoundMs: number; + improvementPct: number; +} + +/** + * Description of one generator task. The orchestrator treats each task as a + * self-contained query() invocation and records its success/failure in + * isolation. Critical tasks block the pipeline on failure; optional ones + * degrade to partial outputs. + */ +export interface GeneratorTask { + stage: string; + agent: keyof typeof agents; + critical: boolean; + /** Human-readable task description that will be embedded in the prompt. */ + task: string; + /** The write-zones this agent is permitted to touch. */ + writeZones: string[]; +} + +// --------------------------------------------------------------------------- +// Logging helpers — 3 level logger with ISO timestamps, no external deps +// --------------------------------------------------------------------------- + +type LogLevel = "INFO" | "WARN" | "ERROR"; + +function log(level: LogLevel, message: string): void { + const ts = new Date().toISOString(); + const line = `[${ts}] [${level}] ${message}`; + if (level === "ERROR") { + // eslint-disable-next-line no-console + console.error(line); + } else if (level === "WARN") { + // eslint-disable-next-line no-console + console.warn(line); + } else { + // eslint-disable-next-line no-console + console.log(line); + } +} + +// --------------------------------------------------------------------------- +// Low-level: run a single query() stream and return its final text result +// --------------------------------------------------------------------------- + +interface RunQueryOptions { + prompt: string; + verbose?: boolean; +} + +/** + * Execute one `query()` call end-to-end and return the final text result. + * + * We iterate the async message stream and capture the `result` message. All + * errors — SDK errors, tool errors, transport errors — propagate as thrown + * exceptions so the caller's try/catch can classify them as stage failures. + */ +async function runQueryStream({ + prompt, + verbose = false, +}: RunQueryOptions): Promise { + let finalResult = ""; + + for await (const message of query({ + prompt, + options: { + // Agent tool must be in allowedTools for subagent delegation. + allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep", "Agent"], + agents, + }, + })) { + // The SDK streams a discriminated-union message type; we duck-type the + // few shapes we care about via `unknown` to avoid coupling to SDK + // internals while still keeping strict-mode safety. + const raw = message as unknown as Record; + + if (verbose && typeof raw.thinking === "string") { + log("INFO", `💭 ${raw.thinking.substring(0, 160)}...`); + } + + if (verbose && raw.toolUse && typeof raw.toolUse === "object") { + const toolUse = raw.toolUse as { name?: string }; + log("INFO", `🔧 Tool: ${toolUse.name ?? "unknown"}`); + } + + if ("result" in raw) { + finalResult = String(raw.result ?? ""); + } + } + + return finalResult; +} + +// --------------------------------------------------------------------------- +// Per-task runner — wraps runQueryStream with timing + graceful error capture +// --------------------------------------------------------------------------- + +function buildAgentPrompt(task: GeneratorTask): string { + // Each task receives a bounded prompt naming the target subagent, the + // frozen-contract task text, and the explicit write-zones. The main agent + // is expected to delegate to the matching subagent via the Agent tool. + return `You are the KIS-TOiR orchestrator running a single bounded generator task. + +Target subagent: ${task.agent} +Stage: ${task.stage} +Write-zones (STRICT — violations must be rejected): +${task.writeZones.map((z) => ` - ${z}`).join("\n")} + +Task (from frozen contract): +${task.task} + +Delegation rules: +- Use the ${task.agent} agent via the Agent tool for all code generation. +- Do not touch files outside the declared write-zones. +- Report back a short summary of what was changed and any blockers. +- If you cannot complete the task, return a clear error message — do NOT + fabricate partial success.`; +} + +async function runTask( + task: GeneratorTask, + monitor: PerformanceMonitor, + verbose: boolean +): Promise { + const started = Date.now(); + log("INFO", `▶️ stage=${task.stage} agent=${task.agent} critical=${task.critical}`); + + try { + const output = await runQueryStream({ + prompt: buildAgentPrompt(task), + verbose, + }); + const durationMs = Date.now() - started; + monitor.record(task.stage, durationMs); + log("INFO", `✅ stage=${task.stage} completed in ${durationMs}ms`); + return { + agent: task.agent, + stage: task.stage, + critical: task.critical, + ok: true, + durationMs, + output, + }; + } catch (err) { + const durationMs = Date.now() - started; + monitor.record(`${task.stage} (failed)`, durationMs); + const message = err instanceof Error ? err.message : String(err); + log("ERROR", `❌ stage=${task.stage} failed after ${durationMs}ms: ${message}`); + return { + agent: task.agent, + stage: task.stage, + critical: task.critical, + ok: false, + durationMs, + error: message, + }; + } +} + +// --------------------------------------------------------------------------- +// High-level: structured parallel generation with graceful error handling +// --------------------------------------------------------------------------- + +export interface GenerateOptions { + verbose?: boolean; + /** + * When true, run tasks sequentially instead of in parallel. Primarily used + * to capture the baseline timing for speedup comparisons. + */ + sequential?: boolean; + /** + * Destination for the metrics JSON report. Defaults to + * `/generation-metrics.json`. + */ + metricsPath?: string; +} + +/** + * Structured parallel generation pipeline. + * + * Critical tasks (Prisma, NestJS) block the pipeline on failure; optional + * tasks (React Admin, data-access) degrade to partial outputs. Regardless of + * outcome, metrics are written to disk and a full GenerationOutput is + * returned so callers can run bounded repair or surface the failure. + */ +export async function generate( + tasks: GeneratorTask[], + options: GenerateOptions = {} +): Promise { + const { verbose = false, sequential = false } = options; + const monitor = new PerformanceMonitor(); + const wallStart = Date.now(); + + log("INFO", `starting generation: tasks=${tasks.length} mode=${sequential ? "sequential" : "parallel"}`); + + let runs: AgentRunResult[]; + + if (sequential) { + // Baseline path — useful for "measure first" speedup comparisons. + runs = []; + for (const task of tasks) { + // Short-circuit on critical failure to match real-world sequential behaviour. + const result = await runTask(task, monitor, verbose); + runs.push(result); + if (!result.ok && result.critical) { + log("WARN", `aborting sequential run after critical failure: ${result.stage}`); + break; + } + } + } else { + // Parallel path — Promise.allSettled is mandatory here: Promise.all would + // reject on the first failure and lose partial outputs from siblings. + // Since each runTask already catches its own errors, all outcomes arrive + // as fulfilled promises, but allSettled keeps us safe against bugs. + const settled = await Promise.allSettled( + tasks.map((task) => runTask(task, monitor, verbose)) + ); + runs = settled.map((s, i) => { + if (s.status === "fulfilled") return s.value; + const task = tasks[i]; + const message = s.reason instanceof Error ? s.reason.message : String(s.reason); + log("ERROR", `unexpected rejection for stage=${task.stage}: ${message}`); + return { + agent: task.agent, + stage: task.stage, + critical: task.critical, + ok: false, + durationMs: 0, + error: message, + }; + }); + } + + const totalMs = Date.now() - wallStart; + + // ---- Classify outcome ------------------------------------------------ + const criticalFailures = runs.filter((r) => !r.ok && r.critical); + const optionalFailures = runs.filter((r) => !r.ok && !r.critical); + const anyFailure = criticalFailures.length + optionalFailures.length > 0; + + let status: GenerationStatus; + if (criticalFailures.length > 0) { + status = "failed"; + } else if (optionalFailures.length > 0) { + status = "partial"; + } else { + status = "success"; + } + + const errors: GenerationError[] = runs + .filter((r) => !r.ok) + .map((r) => ({ + stage: r.stage, + agent: r.agent, + message: r.error ?? "unknown error", + timestamp: new Date().toISOString(), + partialOutputAvailable: !r.critical, + })); + + // ---- Speedup accounting --------------------------------------------- + // Sequential baseline = sum of per-stage durations (what this would have + // cost if we ran each stage one after another). + // Parallel lower bound = the longest single stage (best case for pure + // parallel execution). `totalMs` is the actual wall-clock observed. + const sequentialBaselineMs = runs.reduce((acc, r) => acc + r.durationMs, 0); + const parallelLowerBoundMs = runs.reduce( + (acc, r) => Math.max(acc, r.durationMs), + 0 + ); + const improvementPct = + sequentialBaselineMs > 0 + ? ((sequentialBaselineMs - totalMs) / sequentialBaselineMs) * 100 + : 0; + + monitor.summary(sequential ? "Sequential baseline" : "Parallel generation"); + + // ---- Persist metrics report ----------------------------------------- + const metricsPath = + options.metricsPath ?? path.join(projectRoot, "generation-metrics.json"); + const metricsSnapshot = monitor.getMetrics(); + try { + const report = { + generatedAt: new Date().toISOString(), + mode: sequential ? "sequential" : "parallel", + status, + totalMs, + sequentialBaselineMs, + parallelLowerBoundMs, + improvementPct: Number(improvementPct.toFixed(2)), + runs: runs.map(({ output: _output, ...rest }) => rest), + errors, + metrics: metricsSnapshot, + }; + fs.writeFileSync(metricsPath, JSON.stringify(report, null, 2)); + log("INFO", `metrics written to ${metricsPath}`); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + log("WARN", `could not write metrics report: ${message}`); + } + + if (status === "success") { + log("INFO", `🎉 generation completed successfully in ${totalMs}ms`); + } else if (status === "partial") { + log( + "WARN", + `generation completed with ${optionalFailures.length} optional failure(s) in ${totalMs}ms — partial outputs returned` + ); + } else { + log( + "ERROR", + `generation FAILED with ${criticalFailures.length} critical failure(s) in ${totalMs}ms` + ); + } + + if (anyFailure && verbose) { + for (const err of errors) { + log("WARN", ` ${err.stage} (${err.agent}): ${err.message}`); + } + } + + return { + status, + runs, + errors, + metrics: metricsSnapshot, + totalMs, + sequentialBaselineMs, + parallelLowerBoundMs, + improvementPct, + }; +} + +// --------------------------------------------------------------------------- +// Backward-compatible monolithic entry point +// --------------------------------------------------------------------------- + +export interface OrchestrateOptions { + verbose?: boolean; +} + +/** + * Single-prompt orchestration. This is the original entry point — it runs + * one `query()` stream and lets the main Claude agent decide when to delegate + * to subagents via the Agent tool. Preserved for backward compatibility with + * existing scripts that call `orchestrate(prompt)`. + * + * Prefer `generate(tasks, options)` when you need programmatic per-agent + * failure isolation, parallel execution, or structured metrics. + */ +export async function orchestrate( + mainPrompt: string, + options?: OrchestrateOptions +): Promise { + const verbose = options?.verbose ?? false; + const monitor = new PerformanceMonitor(); + + if (verbose) { + log("INFO", `project root: ${projectRoot}`); + log("INFO", `agents available: ${Object.keys(agents).length}`); + } + + log("INFO", "🎯 orchestration task:"); + // eslint-disable-next-line no-console + console.log(mainPrompt); + log("INFO", "📡 starting agent coordination"); + + monitor.mark("orchestrate-start"); + + try { + const result = await runQueryStream({ + prompt: `You are the KIS-TOiR master orchestrator for Claude Code. + +Your role: +1. Read AGENTS.md, prompts/general-prompt.md, and relevant companion docs +2. Understand the current workspace state via the explorer agent if needed +3. Verify framework assumptions via docs_researcher if needed +4. Freeze a structured contract before specialized generation +5. Delegate bounded work to specialized agents (generator_prisma, generator_nest_resources, generator_react_admin_resources, generator_data_access, reviewer) +6. Accept or reject delegated outputs based on write-zone compliance and contract adherence +7. Integrate accepted outputs and run validation gates +8. Report completion only when both builds pass and evaluation gates succeed + +Available agents (use by description match): +- explorer: for discovery and codebase exploration +- docs_researcher: for framework verification +- generator_prisma: for Prisma schema generation (after contract freeze) +- generator_nest_resources: for NestJS backend generation (after contract freeze) +- generator_react_admin_resources: for React Admin frontend generation (after contract freeze) +- generator_data_access: for frontend data-access integration (after contract freeze) +- reviewer: for final review (after validation) + +Mandatory delegation rules: +- Do NOT generate anything yourself; use agents for specialized tasks +- Contract freeze must be explicit before generator delegation +- Accept/reject delegated outputs explicitly +- Write-zones are strictly enforced per agent (see .claude/CLAUDE.md) +- Validation gates are non-optional proof points + +Your task: +${mainPrompt}`, + verbose, + }); + + monitor.measure("orchestrate-total", "orchestrate-start"); + monitor.summary("Orchestration"); + + // eslint-disable-next-line no-console + console.log("\n=== ORCHESTRATION COMPLETE ===\n"); + // eslint-disable-next-line no-console + console.log(result); + return result; + } catch (err) { + monitor.measure("orchestrate-total (failed)", "orchestrate-start"); + const message = err instanceof Error ? err.message : String(err); + log("ERROR", `orchestration failed: ${message}`); + throw err; + } +} + +// --------------------------------------------------------------------------- +// CLI entry point +// --------------------------------------------------------------------------- + +async function main(): Promise { + const args = process.argv.slice(2); + + if (args.length === 0) { + // eslint-disable-next-line no-console + console.error("Usage: orchestrator.ts "); + // eslint-disable-next-line no-console + console.error('Example: orchestrator.ts "Generate Prisma schema"'); + process.exit(1); + } + + const task = args.filter((a: string) => !a.startsWith("--")).join(" "); + const verbose = args.includes("--verbose"); + + try { + await orchestrate(task, { verbose }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + log("ERROR", `orchestration failed: ${message}`); + process.exit(1); + } +} + +// Execute if this is the main module +if ( + (import.meta as unknown as { main?: boolean }).main || + process.argv[1] === fileURLToPath(import.meta.url) +) { + void main(); +} + +export default orchestrate; diff --git a/tools/performance-monitor.ts b/tools/performance-monitor.ts new file mode 100644 index 0000000..4e0e94b --- /dev/null +++ b/tools/performance-monitor.ts @@ -0,0 +1,169 @@ +/** + * KIS-TOiR Performance Monitor + * + * Lightweight instrumentation for the orchestrator. Tracks wall-clock time + * between named marks, accumulates metrics, prints human-readable summaries, + * and exports to JSON/CSV for trend analysis. + * + * Usage: + * import { monitor } from './performance-monitor'; + * monitor.mark('start'); + * // ... work ... + * monitor.measure('prisma'); + * monitor.summary('Full Generation'); + * fs.writeFileSync('generation-metrics.json', monitor.export('json')); + */ + +import * as fs from "fs"; +import * as path from "path"; + +export interface MetricEntry { + label: string; + duration: number; // milliseconds + timestamp: Date; +} + +export type ExportFormat = "json" | "csv"; + +export class PerformanceMonitor { + private marks: Map = new Map(); + private metrics: MetricEntry[] = []; + private readonly startTime: number; + + constructor() { + this.startTime = Date.now(); + this.marks.set("start", this.startTime); + } + + /** + * Record a named mark at the current time. A mark is an instant, not a + * duration. Use mark() to set a baseline, then measure() to record elapsed + * time from that baseline. + */ + mark(label: string): void { + this.marks.set(label, Date.now()); + } + + /** + * Record the elapsed time from the last `start` (or prior matching mark) + * until now. Returns the duration in milliseconds and stores it in the + * metrics collection. Pass `sinceMark` to measure from a specific mark + * rather than the most recent one. + */ + measure(label: string, sinceMark = "start"): number { + const origin = this.marks.get(sinceMark) ?? this.startTime; + const duration = Date.now() - origin; + this.metrics.push({ + label, + duration, + timestamp: new Date(), + }); + // eslint-disable-next-line no-console + console.log(`⏱️ ${label}: ${duration.toFixed(2)}ms`); + return duration; + } + + /** + * Manually add a metric entry. Useful for tasks where you already have the + * duration (e.g., measured inside Promise.all bookkeeping). + */ + record(label: string, duration: number): void { + this.metrics.push({ + label, + duration, + timestamp: new Date(), + }); + // eslint-disable-next-line no-console + console.log(`⏱️ ${label}: ${duration.toFixed(2)}ms`); + } + + /** + * Print a summary block. If `label` is provided, compares the max metric + * (assumed parallel total) against the sum of metrics (sequential baseline) + * and reports the speedup. + */ + summary(label = "Summary"): void { + const total = Date.now() - this.startTime; + const seqBaseline = this.metrics.reduce((acc, m) => acc + m.duration, 0); + const parallelActual = this.metrics.reduce( + (acc, m) => Math.max(acc, m.duration), + 0 + ); + const improvement = + seqBaseline > 0 + ? ((seqBaseline - parallelActual) / seqBaseline) * 100 + : 0; + + // eslint-disable-next-line no-console + console.log(`\n📊 ${label}`); + // eslint-disable-next-line no-console + console.log(` Total wall-clock: ${total.toFixed(2)}ms`); + // eslint-disable-next-line no-console + console.log(` Sum of phases: ${seqBaseline.toFixed(2)}ms (sequential baseline)`); + if (this.metrics.length > 1) { + // eslint-disable-next-line no-console + console.log( + ` Longest phase: ${parallelActual.toFixed(2)}ms (parallel lower bound)` + ); + // eslint-disable-next-line no-console + console.log(` Speedup achieved: ${improvement.toFixed(1)}%`); + } + } + + /** + * Serialize metrics for disk storage / trend analysis. + */ + export(format: ExportFormat = "json"): string { + if (format === "csv") { + const header = "label,duration_ms,timestamp"; + const rows = this.metrics.map( + (m) => `${m.label},${m.duration},${m.timestamp.toISOString()}` + ); + return [header, ...rows].join("\n"); + } + return JSON.stringify( + { + startedAt: new Date(this.startTime).toISOString(), + totalMs: Date.now() - this.startTime, + metrics: this.metrics, + }, + null, + 2 + ); + } + + /** + * Write metrics to a file alongside other generation outputs. Defaults to + * project-root `generation-metrics.json`. + */ + writeReport(filePath = "generation-metrics.json"): void { + const resolved = path.isAbsolute(filePath) + ? filePath + : path.join(process.cwd(), filePath); + fs.writeFileSync(resolved, this.export("json")); + } + + /** + * Return a shallow copy of the recorded metrics. Useful for tests and for + * attaching to GenerationOutput results. + */ + getMetrics(): MetricEntry[] { + return [...this.metrics]; + } + + /** + * Reset all marks and metrics. The monitor remains usable afterward. + */ + reset(): void { + this.marks.clear(); + this.metrics.length = 0; + this.marks.set("start", Date.now()); + } +} + +/** + * Shared singleton instance for convenience. Multiple independent runs can + * call `monitor.reset()` between them. + */ +export const monitor = new PerformanceMonitor(); +export default monitor; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..7cf78a6 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ES2020", + "moduleResolution": "node", + "lib": ["ES2020"], + "declaration": true, + "outDir": "./dist", + "rootDir": "./", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "isolatedModules": true, + "allowSyntheticDefaultImports": true, + "experimentalDecorators": true, + "emitDecoratorMetadata": true + }, + "include": [ + "tools/**/*.ts", + "agents/**/*.ts", + ".claude/**/*.ts" + ], + "exclude": [ + "node_modules", + "dist", + "server", + "client", + "db-seed" + ] +}