archicore 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +2224 -375
  2. package/package.json +12 -4
package/README.md CHANGED
@@ -1,530 +1,2379 @@
1
- # AIArhitector
2
-
3
- **AI Software Architect System** - система ИИ-архитектор, которая понимает весь код, держит контекст и снижает риск багов практически до нуля.
4
-
5
- ## Ключевые возможности
6
-
7
- ### 1. **Понимание всего кода**
8
- - 🌲 **AST Parsing** - парсинг кода через Tree-sitter
9
- - 🕸️ **Dependency Graph** - полный граф зависимостей между компонентами
10
- - 🔍 **Symbol Extraction** - извлечение всех символов (функции, классы, интерфейсы)
11
- - 📊 **Call Graph** - граф вызовов функций
12
-
13
- ### 2. **Семантическая память**
14
- - 🧠 **Vector Database** - хранение семантического понимания кода (Qdrant)
15
- - 🔎 **Semantic Search** - поиск по смыслу, а не по тексту
16
- - 💾 **Long-term Memory** - долговременная память о назначении компонентов
17
-
18
- ### 3. **Архитектурные знания**
19
- - 🏛️ **Bounded Contexts** - описание границ контекстов
20
- - 📐 **Domain Entities** - доменные сущности и их связи
21
- - 📋 **Architectural Rules** - правила архитектуры
22
- - ⚖️ **Invariants** - инварианты системы
23
-
24
- ### 4. **Анализ влияния изменений**
25
- - 🎯 **Impact Analysis** - определение затронутых компонентов
26
- - ⚠️ **Risk Assessment** - оценка рисков
27
- - 💡 **Recommendations** - автоматические рекомендации
28
- - 📈 **Impact Graph** - визуальный граф влияния
29
-
30
- ### 5. **LLM Orchestration**
31
- - 🤖 **AI Architect** - ИИ-архитектор для принятия решений
32
- - 💬 **Contextual Answers** - ответы с учётом всего контекста
33
- - 🔄 **Code Review** - автоматический ревью кода
34
- - 📝 **Documentation** - генерация документации
35
-
36
- ## Архитектура системы
37
-
38
- ```
39
- ┌─────────────────────────────────────────────────────┐
40
- │ Git Repository │
41
- └─────────────────────────────────────────────────────┘
42
-
43
- ┌─────────────────────────────────────────────────────┐
44
- │ Code Index (AST + Graph) │
45
- │ - Tree-sitter Parser │
46
- - Symbol Extraction │
47
- │ - Dependency Graph Builder │
48
- └─────────────────────────────────────────────────────┘
49
-
50
- ┌─────────────────────────────────────────────────────┐
51
- │ Semantic Memory (Vector DB) │
52
- │ - Embeddings Generation │
53
- │ - Qdrant Vector Store │
54
- │ - Semantic Search │
55
- └─────────────────────────────────────────────────────┘
56
-
57
- ┌─────────────────────────────────────────────────────┐
58
- │ Architecture Knowledge Layer │
59
- - Bounded Contexts │
60
- │ - Domain Entities │
61
- │ - Architectural Rules │
62
- │ - Invariants Validation │
63
- └─────────────────────────────────────────────────────┘
64
-
65
- ┌─────────────────────────────────────────────────────┐
66
- │ Change Impact Engine │
67
- - Affected Components Detection │
68
- - Risk Assessment │
69
- - Recommendations Generation │
70
- - Impact Graph Building │
71
- └─────────────────────────────────────────────────────┘
72
-
73
- ┌─────────────────────────────────────────────────────┐
74
- │ LLM Orchestrator │
75
- - Claude / GPT Integration │
76
- - Context Management │
77
- - Architectural Decision Making │
78
- - Code Generation & Review │
79
- └─────────────────────────────────────────────────────┘
80
-
81
- ┌─────────────────────────────────────────────────────┐
82
- │ Interfaces (CLI, API, IDE) │
83
- └─────────────────────────────────────────────────────┘
84
- ```
85
-
86
- ## Установка
87
-
88
- ### 1. Клонировать репозиторий
89
-
90
- ```bash
91
- git clone https://github.com/yourusername/AIarhitector.git
92
- cd AIarhitector
93
- ```
94
-
95
- ### 2. Установить зависимости
1
+ # ArchiCore - AI Software Architect
2
+
3
+ <div align="center">
4
+
5
+ ![ArchiCore Logo](https://via.placeholder.com/200x200/0ea5e9/ffffff?text=ArchiCore)
6
+
7
+ **Intelligent AI-Powered Software Architecture Analysis Platform**
8
+
9
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.3-blue.svg)](https://www.typescriptlang.org/)
10
+ [![Node.js](https://img.shields.io/badge/Node.js-18+-green.svg)](https://nodejs.org/)
11
+ [![License](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
12
+ [![Docker](https://img.shields.io/badge/Docker-Ready-2496ED.svg)](https://www.docker.com/)
13
+ [![PostgreSQL](https://img.shields.io/badge/PostgreSQL-15-336791.svg)](https://www.postgresql.org/)
14
+
15
+ [🌐 Website](https://archicore.io) | [📖 Documentation](https://docs.archicore.io) | [🚀 API](https://api.archicore.io)
16
+
17
+ </div>
18
+
19
+ ---
20
+
21
+ ## 📋 Table of Contents
22
+
23
+ - [Overview](#overview)
24
+ - [Key Features](#key-features)
25
+ - [Architecture](#architecture)
26
+ - [Technology Stack](#technology-stack)
27
+ - [Quick Start](#quick-start)
28
+ - [Installation](#installation)
29
+ - [Usage](#usage)
30
+ - [Web Dashboard](#web-dashboard)
31
+ - [CLI Tool](#cli-tool)
32
+ - [REST API](#rest-api)
33
+ - [Authentication & Security](#authentication--security)
34
+ - [Configuration](#configuration)
35
+ - [Deployment](#deployment)
36
+ - [API Reference](#api-reference)
37
+ - [Development](#development)
38
+ - [Roadmap](#roadmap)
39
+ - [Contributing](#contributing)
40
+ - [License](#license)
41
+
42
+ ---
43
+
44
+ ## 🎯 Overview
45
+
46
+ **ArchiCore** - это интеллектуальная платформа для анализа и управления архитектурой программного обеспечения, построенная на основе AI. Система понимает код на глубоком семантическом уровне, отслеживает все зависимости и помогает принимать обоснованные архитектурные решения.
47
+
48
+ ### Зачем нужен ArchiCore?
49
+
50
+ **Проблема**: В больших проектах разработчики часто вносят изменения, не понимая полного влияния на систему. Это приводит к багам, техническому долгу и архитектурной деградации.
51
+
52
+ **Решение**: ArchiCore анализирует весь код, строит граф зависимостей, использует семантическую память и AI для предсказания влияния изменений, выявления рисков и генерации рекомендаций.
53
+
54
+ ### Для кого?
55
+
56
+ - 👨‍💻 **Software Architects** - контроль архитектуры, выявление нарушений
57
+ - 👩‍💼 **Tech Leads** - review кода, анализ влияния изменений
58
+ - 🏢 **Development Teams** - снижение багов, улучшение code quality
59
+ - 📊 **CTO/Engineering Managers** - метрики, технический долг, risk assessment
60
+
61
+ ---
62
+
63
+ ## ✨ Key Features
64
+
65
+ ### 🧠 Intelligent Code Understanding
66
+
67
+ - **AST Parsing** - Глубокий синтаксический анализ через Tree-sitter (40+ языков)
68
+ - **Dependency Graph** - Полный граф зависимостей между компонентами, функциями, классами
69
+ - **Symbol Extraction** - Извлечение всех символов: функции, классы, интерфейсы, переменные
70
+ - **Call Graph Analysis** - Граф вызовов для отслеживания потоков данных
71
+ - **Semantic Memory** - Vector database (Qdrant) для семантического понимания кода
72
+
73
+ ### 🎯 Change Impact Analysis
74
+
75
+ - **Real-time Impact Detection** - Определение затронутых компонентов при изменениях
76
+ - **Risk Assessment** - Автоматическая оценка рисков (Critical, High, Medium, Low)
77
+ - **Dependency Tracking** - Отслеживание прямых и транзитивных зависимостей
78
+ - **Impact Visualization** - Графическое представление влияния изменений
79
+ - **Smart Recommendations** - AI-генерируемые рекомендации по снижению рисков
80
+
81
+ ### 🔍 Semantic Code Search
82
+
83
+ - **Natural Language Queries** - Поиск по смыслу: "функции обработки платежей"
84
+ - **Vector Similarity** - Поиск семантически похожих фрагментов кода
85
+ - **Context-Aware Results** - Результаты с учетом контекста и зависимостей
86
+ - **Multi-language Support** - Поиск во всех поддерживаемых языках одновременно
87
+
88
+ ### 🤖 AI Architect Assistant
89
+
90
+ - **Architectural Questions** - "Как организована аутентификация в системе?"
91
+ - **Code Review** - Автоматический анализ качества и соответствия best practices
92
+ - **Documentation Generation** - Генерация архитектурной документации
93
+ - **Refactoring Suggestions** - Предложения по улучшению архитектуры
94
+ - **Dead Code Detection** - Выявление неиспользуемого кода
95
+ - **Code Duplication Analysis** - Поиск дублирования для рефакторинга
96
+
97
+ ### 🔐 Enterprise-Grade Security
98
+
99
+ - **Multi-Provider OAuth** - Google, GitHub authentication
100
+ - **Email Verification** - 6-значные коды, SMTP integration (Zoho)
101
+ - **Disposable Email Protection** - Блокировка 180+ временных email доменов
102
+ - **JWT Authentication** - Secure token-based auth
103
+ - **Device Flow** - Безопасная CLI авторизация через web browser
104
+ - **API Keys Management** - Создание, ротация, отзыв API ключей
105
+ - **Audit Logs** - Полное логирование всех действий пользователей
106
+ - **Rate Limiting** - Защита от abuse и DDoS
107
+ - **CORS & Helmet** - Защита web endpoints
108
+ - **bcrypt Password Hashing** - Industry-standard password security
109
+ - **AES-256 Encryption** - Шифрование чувствительных данных
110
+
111
+ ### 📊 Project Management
112
+
113
+ - **Multi-Project Support** - Управление несколькими проектами
114
+ - **Team Collaboration** - Совместная работа команд (до 20 разработчиков)
115
+ - **GitHub Integration** - Автоматический анализ PR, webhooks
116
+ - **Version Control** - Отслеживание изменений архитектуры
117
+ - **Progress Tracking** - Метрики качества и технического долга
118
+
119
+ ### 🌐 Multiple Interfaces
120
+
121
+ - **Web Dashboard** - Интуитивный UI для визуализации и управления
122
+ - **CLI Tool** - Мощный command-line interface для automation
123
+ - **REST API** - Полное API для интеграции с CI/CD и другими системами
124
+ - **Webhooks** - GitHub webhooks для автоматического анализа
125
+
126
+ ### 📈 Analytics & Metrics
127
+
128
+ - **Code Metrics** - Cyclomatic complexity, lines of code, maintainability index
129
+ - **Architecture Metrics** - Coupling, cohesion, modularity scores
130
+ - **Technical Debt Tracking** - Идентификация и quantification технического долга
131
+ - **Trend Analysis** - Отслеживание изменений метрик во времени
132
+ - **Custom Dashboards** - Настраиваемые дашборды для команд
133
+
134
+ ### 🚀 Developer Experience
135
+
136
+ - **40+ Language Support** - TypeScript, JavaScript, Python, Go, Rust, Java, Kotlin, C#, PHP, Ruby и др.
137
+ - **IDE Integration** - VS Code, JetBrains (в разработке)
138
+ - **CI/CD Ready** - Интеграция с GitLab CI, GitHub Actions, Jenkins
139
+ - **Docker Support** - Полная containerization для легкого deployment
140
+ - **Auto-Scaling** - Поддержка горизонтального масштабирования
141
+ - **Real-time Updates** - Live reload при изменениях кода
142
+
143
+ ---
144
+
145
+ ## 🏗️ Architecture
146
+
147
+ ArchiCore построен по принципам чистой архитектуры с четким разделением слоев:
148
+
149
+ ```
150
+ ┌─────────────────────────────────────────────────────────────────┐
151
+ │ Web Dashboard │
152
+ │ (React/Vue-like SPA - public/*.html) │
153
+ │ - Project Management - Analytics - Settings - Admin Panel │
154
+ └─────────────────────────────────────────────────────────────────┘
155
+ ↓ HTTPS/API
156
+ ┌─────────────────────────────────────────────────────────────────┐
157
+ │ API Gateway (Express 5) │
158
+ │ OAuth, JWT Auth, Rate Limiting, CORS, Helmet, Audit Logging │
159
+ └─────────────────────────────────────────────────────────────────┘
160
+
161
+ ┌─────────────────────┼─────────────────────┐
162
+ ↓ ↓ ↓
163
+ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
164
+ │ Authentication │ │ Project Core │ │ Analysis Engine │
165
+ │ - OAuth 2.0 │ │ - Code Indexing │ │ - Impact Analysis│
166
+ │ - Email Verify │ │ - AST Parsing │ │ - Risk Assessment│
167
+ │ - Device Flow │ │ - Dependency Gr.│ │ - Recommendations│
168
+ │ - API Keys │ │ - Metrics │ │ - Dead Code Det. │
169
+ └──────────────────┘ └──────────────────┘ └──────────────────┘
170
+ ↓ ↓ ↓
171
+ ┌─────────────────────────────────────────────────────────────────┐
172
+ │ Semantic Memory Layer │
173
+ │ - Vector Embeddings (Jina AI) - Semantic Search (Qdrant) │
174
+ │ - Code Similarity - Natural Language Queries │
175
+ └─────────────────────────────────────────────────────────────────┘
176
+ ↓ ↓ ↓
177
+ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
178
+ │ PostgreSQL │ │ Redis │ │ Qdrant │
179
+ │ - Users, Auth │ │ - Cache Layer │ │ - Vector Store │
180
+ │ - Projects │ │ - Sessions │ │ - Embeddings │
181
+ │ - Audit Logs │ │ - Rate Limits │ │ - Similarity │
182
+ └──────────────────┘ └──────────────────┘ └──────────────────┘
183
+ ↓ ↓ ↓
184
+ ┌─────────────────────────────────────────────────────────────────┐
185
+ │ AI Orchestration Layer │
186
+ │ - Claude (Anthropic) - GPT (OpenAI) - DeepSeek (Budget) │
187
+ │ - Context Management - Prompt Optimization - Response Caching │
188
+ └─────────────────────────────────────────────────────────────────┘
189
+ ```
190
+
191
+ ### Data Flow
192
+
193
+ 1. **User Authentication** → OAuth/Email verification → JWT token
194
+ 2. **Project Creation** → GitHub sync / Local upload → File indexing
195
+ 3. **Code Indexing** → AST Parsing (Tree-sitter) → Symbol extraction → Dependency graph
196
+ 4. **Semantic Embedding** → Code chunks → Jina AI → Vector storage (Qdrant)
197
+ 5. **Change Analysis** → Modified files → Impact engine → Affected components → Risk assessment
198
+ 6. **AI Query** → User question → Context retrieval → LLM (Claude/GPT) → Structured response
199
+
200
+ ---
201
+
202
+ ## 🛠️ Technology Stack
203
+
204
+ ### Backend
205
+ - **Runtime**: Node.js 18+ (LTS)
206
+ - **Language**: TypeScript 5.3
207
+ - **Framework**: Express 5.0
208
+ - **Authentication**: Passport.js (OAuth 2.0), JWT
209
+ - **Validation**: Zod, Express Validator
210
+
211
+ ### Databases
212
+ - **Primary Database**: PostgreSQL 15 (users, projects, audit logs)
213
+ - **Cache Layer**: Redis 7 (sessions, rate limiting, temporary data)
214
+ - **Vector Database**: Qdrant (semantic embeddings, similarity search)
215
+
216
+ ### AI & ML
217
+ - **LLM Providers**:
218
+ - Anthropic Claude (Opus 4.5, Sonnet 4.5) - Recommended
219
+ - OpenAI GPT (GPT-4 Turbo, GPT-4)
220
+ - DeepSeek (deepseek-chat, deepseek-coder) - Budget option
221
+ - **Embeddings**: Jina AI (jina-embeddings-v2-base-code)
222
+ - **Code Parsing**: Tree-sitter (40+ languages)
223
+
224
+ ### Frontend
225
+ - **Architecture**: Vanilla JavaScript (SPA-like)
226
+ - **Styling**: Tailwind-like custom CSS
227
+ - **Build**: Vite (development), Custom minification & obfuscation
228
+ - **State Management**: localStorage + fetch API
229
+
230
+ ### Infrastructure
231
+ - **Containerization**: Docker, Docker Compose
232
+ - **Reverse Proxy**: Nginx (SSL termination, load balancing)
233
+ - **SSL**: Let's Encrypt (auto-renewal)
234
+ - **CI/CD**: GitLab CI/CD
235
+ - **Monitoring**: Custom logging + Audit service
236
+
237
+ ### Email & Notifications
238
+ - **SMTP**: Zoho Mail (verification codes, welcome emails)
239
+ - **Templates**: HTML email templates with branding
240
+ - **Rate Limiting**: 30s cooldown between resends
241
+
242
+ ### Security
243
+ - **Password Hashing**: bcrypt (10 rounds)
244
+ - **Encryption**: AES-256-GCM (sensitive data)
245
+ - **CORS**: Configurable whitelist
246
+ - **Headers**: Helmet.js (CSP, HSTS, XSS protection)
247
+ - **Rate Limiting**: Express rate limit (100 req/15min)
248
+ - **Disposable Email**: 180+ domain blacklist
249
+
250
+ ### Development Tools
251
+ - **Package Manager**: npm
252
+ - **Linting**: ESLint
253
+ - **Formatting**: Prettier
254
+ - **Testing**: Jest (planned)
255
+ - **Git Hooks**: Husky (planned)
256
+
257
+ ### Supported Languages (Tree-sitter)
258
+ TypeScript, JavaScript, Python, Go, Rust, Java, Kotlin, Scala, C#, F#, Swift, Dart, PHP, Ruby, Haskell, Elixir, Clojure, Vue, Svelte, Terraform, GraphQL, YAML, JSON, CSS, HTML, SQL, Bash, Dockerfile и другие (40+)
259
+
260
+ ---
261
+
262
+ ## 🚀 Quick Start
263
+
264
+ ### Prerequisites
265
+
266
+ - **Node.js** 18+ ([Download](https://nodejs.org/))
267
+ - **Docker** (optional but recommended) ([Download](https://www.docker.com/))
268
+ - **PostgreSQL** 15+ (или через Docker)
269
+ - **Redis** 7+ (или через Docker)
270
+
271
+ ### 1. Clone Repository
96
272
 
97
273
  ```bash
98
- npm install
274
+ git clone https://github.com/yourusername/archicore.git
275
+ cd archicore
99
276
  ```
100
277
 
101
- ### 3. Настроить окружение
278
+ ### 2. Install Dependencies
102
279
 
103
- Создайте файл `.env`:
280
+ ```bash
281
+ npm install
282
+ ```
283
+
284
+ ### 3. Configure Environment
104
285
 
105
286
  ```bash
106
287
  cp .env.example .env
107
288
  ```
108
289
 
109
- Заполните необходимые ключи:
290
+ Заполните `.env` своими ключами:
110
291
 
111
292
  ```env
112
- # LLM API Keys
113
- ANTHROPIC_API_KEY=your_key_here
114
- OPENAI_API_KEY=your_key_here
293
+ # Server
294
+ PORT=3000
295
+ NODE_ENV=production
296
+ BASE_URL=http://localhost:3000
115
297
 
116
- # Vector Database
298
+ # Database
299
+ DATABASE_URL=postgresql://postgres:password@localhost:5432/archicore
300
+
301
+ # Redis
302
+ REDIS_URL=redis://localhost:6379
303
+
304
+ # Qdrant Vector DB
117
305
  QDRANT_URL=http://localhost:6333
118
- QDRANT_API_KEY=
119
306
 
120
- # Database
121
- DATABASE_URL=postgresql://localhost:5432/aiarhitector
307
+ # AI Providers (выберите один или несколько)
308
+ ANTHROPIC_API_KEY=sk-ant-xxx # Рекомендуется для production
309
+ OPENAI_API_KEY=sk-xxx # Альтернатива
310
+ DEEPSEEK_API_KEY=sk-xxx # Бюджетный вариант
311
+ JINA_API_KEY=jina_xxx # Для embeddings
312
+
313
+ # OAuth (опционально)
314
+ GOOGLE_CLIENT_ID=xxx.apps.googleusercontent.com
315
+ GOOGLE_CLIENT_SECRET=GOCSPX-xxx
316
+ GITHUB_CLIENT_ID=xxx
317
+ GITHUB_CLIENT_SECRET=xxx
318
+
319
+ # Email (для verification)
320
+ ZOHO_SMTP_USER=noreply@archicore.io
321
+ ZOHO_SMTP_PASS=xxx
322
+ EMAIL_FROM_ADDRESS=noreply@archicore.io
323
+ EMAIL_FROM_NAME=ArchiCore
324
+
325
+ # Security
326
+ JWT_SECRET=your-super-secret-jwt-key-change-this
327
+ ENCRYPTION_KEY=your-32-char-encryption-key-here
328
+ SESSION_SECRET=your-session-secret-change-this
329
+
330
+ # Admin
331
+ ADMIN_EMAIL=admin@archicore.io
122
332
  ```
123
333
 
124
- ### 4. Запустить Qdrant (векторная БД)
125
-
126
- **Вариант A: Через скрипт (рекомендуется)**
334
+ ### 4. Start with Docker (Recommended)
127
335
 
128
336
  ```bash
129
- # Windows
130
- start-qdrant.bat
337
+ # Запустить все сервисы (PostgreSQL, Redis, Qdrant, ArchiCore)
338
+ docker compose up -d
131
339
 
132
- # Linux/Mac
133
- chmod +x start-qdrant.sh
134
- ./start-qdrant.sh
340
+ # Проверить логи
341
+ docker compose logs -f archicore
135
342
  ```
136
343
 
137
- Скрипт автоматически:
138
- - Использует Docker если установлен
139
- - Или скачает и запустит Qdrant binary
344
+ ArchiCore будет доступен на:
345
+ - **Dashboard**: http://localhost:3000
346
+ - **API**: http://localhost:3000/api
140
347
 
141
- **Вариант B: Через Docker Compose**
348
+ ### 5. Start Manually (Alternative)
142
349
 
143
350
  ```bash
144
- docker-compose up -d
351
+ # Запустить PostgreSQL
352
+ docker run -d --name postgres -p 5432:5432 \
353
+ -e POSTGRES_PASSWORD=password \
354
+ -e POSTGRES_DB=archicore \
355
+ postgres:15
356
+
357
+ # Запустить Redis
358
+ docker run -d --name redis -p 6379:6379 redis:7
359
+
360
+ # Запустить Qdrant
361
+ docker run -d --name qdrant -p 6333:6333 qdrant/qdrant
362
+
363
+ # Собрать проект
364
+ npm run build
365
+
366
+ # Запустить ArchiCore
367
+ npm start
145
368
  ```
146
369
 
147
- **Вариант C: Вручную через Docker**
370
+ ### 6. Create First User
371
+
372
+ Откройте браузер: http://localhost:3000
373
+
374
+ 1. Нажмите **Sign Up**
375
+ 2. Введите email и password
376
+ 3. Подтвердите email (код придет на почту)
377
+ 4. Готово! Вы в системе
378
+
379
+ ---
380
+
381
+ ## 📦 Installation
382
+
383
+ ### Docker Deployment (Production)
384
+
385
+ Рекомендуется для production. Все сервисы в контейнерах.
148
386
 
149
387
  ```bash
150
- docker run -d --name qdrant -p 6333:6333 -p 6334:6334 qdrant/qdrant
388
+ # 1. Клонировать репозиторий
389
+ git clone https://github.com/yourusername/archicore.git
390
+ cd archicore
391
+
392
+ # 2. Настроить .env
393
+ cp .env.example .env
394
+ nano .env # Заполнить все ключи
395
+
396
+ # 3. Собрать и запустить
397
+ docker compose build
398
+ docker compose up -d
399
+
400
+ # 4. Проверить статус
401
+ docker compose ps
402
+
403
+ # 5. Просмотр логов
404
+ docker compose logs -f archicore
405
+
406
+ # 6. Остановить
407
+ docker compose down
151
408
  ```
152
409
 
153
- После запуска Qdrant доступен на:
154
- - **API:** http://localhost:6333
155
- - **Dashboard:** http://localhost:6333/dashboard
410
+ **Docker Compose включает:**
411
+ - ArchiCore (Node.js app)
412
+ - PostgreSQL 15
413
+ - Redis 7
414
+ - Qdrant vector DB
415
+ - Nginx reverse proxy (если настроен)
416
+
417
+ ### Manual Installation (Development)
156
418
 
157
- ### 5. Собрать проект
419
+ Для локальной разработки без Docker.
420
+
421
+ #### Step 1: Install Node.js
158
422
 
159
423
  ```bash
160
- npm run build
424
+ # Ubuntu/Debian
425
+ curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
426
+ sudo apt-get install -y nodejs
427
+
428
+ # macOS (Homebrew)
429
+ brew install node@18
430
+
431
+ # Windows
432
+ # Download from https://nodejs.org/
161
433
  ```
162
434
 
163
- ## Использование
435
+ #### Step 2: Install Databases
164
436
 
165
- ### CLI Команды
437
+ **PostgreSQL:**
438
+ ```bash
439
+ # Ubuntu/Debian
440
+ sudo apt install postgresql postgresql-contrib
166
441
 
167
- #### 1. Индексирование проекта
442
+ # macOS
443
+ brew install postgresql@15
444
+ brew services start postgresql@15
168
445
 
446
+ # Windows
447
+ # Download from https://www.postgresql.org/download/windows/
448
+ ```
449
+
450
+ **Redis:**
169
451
  ```bash
170
- npm run index
171
- # или
172
- npx tsx src/cli.ts index --dir /path/to/project
452
+ # Ubuntu/Debian
453
+ sudo apt install redis-server
454
+ sudo systemctl start redis
455
+
456
+ # macOS
457
+ brew install redis
458
+ brew services start redis
459
+
460
+ # Windows
461
+ # Download from https://github.com/microsoftarchive/redis/releases
173
462
  ```
174
463
 
175
- Результат:
464
+ **Qdrant:**
465
+ ```bash
466
+ # Через Docker (рекомендуется)
467
+ docker run -d --name qdrant -p 6333:6333 -p 6334:6334 qdrant/qdrant
468
+
469
+ # Или скачать binary
470
+ ./start-qdrant.sh # Linux/Mac
471
+ start-qdrant.bat # Windows
176
472
  ```
177
- ✓ Проект проиндексирован!
178
473
 
179
- 📊 Статистика:
474
+ #### Step 3: Setup Database
180
475
 
181
- Всего файлов: 156
182
- Всего символов: 1243
183
- Узлов в графе: 1399
184
- Связей: 2847
476
+ ```bash
477
+ # Создать базу данных
478
+ createdb archicore
479
+
480
+ # Или через psql
481
+ psql -U postgres
482
+ CREATE DATABASE archicore;
483
+ \q
484
+ ```
185
485
 
186
- 🔤 Символы по типам:
486
+ #### Step 4: Install ArchiCore
187
487
 
188
- function: 687
189
- class: 234
190
- interface: 145
191
- variable: 177
488
+ ```bash
489
+ # Клонировать и установить зависимости
490
+ git clone https://github.com/yourusername/archicore.git
491
+ cd archicore
492
+ npm install
192
493
 
193
- 🧠 Семантическая память:
494
+ # Настроить .env
495
+ cp .env.example .env
496
+ nano .env
194
497
 
195
- Векторов: 1243
196
- Точек: 1243
498
+ # Собрать проект
499
+ npm run build
500
+
501
+ # Запустить
502
+ npm start
197
503
  ```
198
504
 
199
- #### 2. Анализ влияния изменений
505
+ #### Step 5: Verify Installation
506
+
507
+ ```bash
508
+ # Проверить доступность API
509
+ curl http://localhost:3000/health
510
+
511
+ # Должен вернуть:
512
+ # {"status":"ok","version":"0.3.1"}
513
+ ```
514
+
515
+ ### NPM Package (CLI Only)
516
+
517
+ Установить ArchiCore CLI глобально:
200
518
 
201
519
  ```bash
202
- npx tsx src/cli.ts analyze \
203
- --description "Объединить уроки и базу знаний в единую сущность" \
204
- --files "src/lessons,src/knowledge-base" \
205
- --type "refactor"
520
+ npm install -g archicore
521
+
522
+ # Авторизоваться
523
+ archicore login
524
+
525
+ # Начать использование
526
+ archicore projects list
527
+ ```
528
+
529
+ ---
530
+
531
+ ## 💻 Usage
532
+
533
+ ArchiCore предоставляет три способа взаимодействия: Web Dashboard, CLI Tool и REST API.
534
+
535
+ ### 🌐 Web Dashboard
536
+
537
+ #### 1. Landing Page (`/`)
538
+
539
+ Главная страница с описанием продукта, ценами и возможностями.
540
+
541
+ **Features:**
542
+ - Hero section с CTA
543
+ - Features overview
544
+ - Pricing plans (Free, Team, Pro, Enterprise)
545
+ - Footer с navigation
546
+
547
+ #### 2. Authentication (`/auth`)
548
+
549
+ Страница входа/регистрации.
550
+
551
+ **Login:**
552
+ ```
553
+ 1. Email + Password
554
+ 2. OAuth (Google / GitHub)
206
555
  ```
207
556
 
208
- Результат:
557
+ **Sign Up:**
209
558
  ```
210
- 📋 ОТЧЁТ ОБ АНАЛИЗЕ ВЛИЯНИЯ
559
+ 1. Enter email + password
560
+ 2. Verify email (6-digit code sent via SMTP)
561
+ 3. Automatic login after verification
562
+ ```
563
+
564
+ **Features:**
565
+ - Email verification required
566
+ - Disposable email blocked (180+ domains)
567
+ - Device flow for CLI auth
568
+ - Password recovery (planned)
569
+
570
+ #### 3. Dashboard (`/dashboard`)
571
+
572
+ Главный рабочий интерфейс после авторизации.
573
+
574
+ **Sections:**
575
+
576
+ **Projects:**
577
+ - Create new project (name, description, GitHub URL)
578
+ - List all projects with stats
579
+ - Select active project
580
+ - Delete projects
581
+
582
+ **Project Actions:**
583
+ ```
584
+ ├── Index Project - Анализ кода и построение графа
585
+ ├── Full Analysis - Полный отчет (metrics, security, duplication, dead code)
586
+ ├── Security Analysis - Проверка уязвимостей
587
+ ├── Dead Code Detection - Поиск неиспользуемого кода
588
+ ├── Code Duplication - Поиск дублирования
589
+ ├── Metrics Report - Code metrics (complexity, LOC, maintainability)
590
+ ├── Refactoring Suggestions - AI рекомендации
591
+ └── Export Data - JSON/HTML/Markdown/CSV
592
+ ```
593
+
594
+ **Code Search:**
595
+ - Semantic search: "функции для обработки платежей"
596
+ - Results with file paths, line numbers, relevance scores
597
+
598
+ **AI Architect:**
599
+ - Ask questions: "Как организована аутентификация?"
600
+ - Context-aware answers based on your codebase
601
+ - Architecture recommendations
602
+
603
+ **Account Section:**
604
+ - Profile information
605
+ - Subscription tier (Free/Team/Pro/Enterprise)
606
+ - Usage statistics (API calls, projects, storage)
607
+ - Logout
608
+
609
+ #### 4. Pricing Page (`/pricing`)
610
+
611
+ Тарифные планы с подробным описанием.
612
+
613
+ **Plans:**
211
614
 
212
- ЗАТРОНУТЫЕ КОМПОНЕНТЫ:
615
+ | Feature | Free | Team | Pro | Enterprise |
616
+ |---------|------|------|-----|------------|
617
+ | **Price** | $0 | $249/mo | $599/mo | Custom |
618
+ | **Repositories** | 1 | 3 | 10 | Unlimited |
619
+ | **Developers** | 1 | 5 | 20 | Unlimited |
620
+ | **Analysis** | Snapshot | Regular | PR-level | Continuous |
621
+ | **API Access** | ❌ | ❌ | ✅ | ✅ |
622
+ | **GitHub/GitLab Integration** | ❌ | ❌ | ✅ | ✅ |
623
+ | **Data Retention** | 7 days | 14 days | 30 days | Custom |
624
+ | **Support** | Community | Email | Priority | Dedicated manager |
213
625
 
214
- Всего: 47
215
- 🔴 Критические: 12
216
- 🟠 Высокие: 18
217
- 🟡 Средние: 11
218
- 🟢 Низкие: 6
626
+ #### 5. Admin Panel (`/admin`)
219
627
 
220
- 🔴 КРИТИЧЕСКИЕ КОМПОНЕНТЫ:
628
+ Панель администратора (только для admin role).
221
629
 
222
- - CourseService (src/services/course.ts)
223
- Directly modified
224
- - KnowledgeRepository (src/repositories/knowledge.ts)
225
- Direct dependency
226
- - ProgressTracker (src/tracking/progress.ts)
227
- Direct dependency
630
+ **Features:**
631
+ - **Users Management**: List, search, edit, delete users
632
+ - **Tier Management**: Change user subscription tiers
633
+ - **Statistics**: Total users, projects, API calls, storage
634
+ - **Audit Logs**: View all user actions with filters
635
+ - **System Settings**:
636
+ - Maintenance mode toggle
637
+ - Email configuration test
638
+ - Cache management (clear Redis/memory)
639
+ - System backup & restore
640
+ - Factory reset
641
+ - **Export**: Export all system data (JSON/CSV)
228
642
 
229
- РИСКИ:
643
+ #### 6. Legal Pages
230
644
 
231
- [HIGH] Change affects 12 critical components
232
- 💡 Consider breaking into smaller changes
645
+ - **Privacy Policy** (`/privacy.html`)
646
+ - **Terms of Service** (`/terms.html`)
647
+ - **Security** (`/security.html`)
233
648
 
234
- [CRITICAL] Modification may break API contracts
235
- 💡 Review and update all API consumers
649
+ ---
236
650
 
237
- РЕКОМЕНДАЦИИ:
651
+ ### 🖥️ CLI Tool
238
652
 
239
- [CRITICAL] Review all affected components
240
- 47 components will be affected by this change
653
+ ArchiCore CLI - мощный инструмент для автоматизации и CI/CD интеграции.
241
654
 
242
- [CRITICAL] Test critical components
243
- Focus on: CourseService, KnowledgeRepository, ProgressTracker
655
+ #### Installation
244
656
 
245
- [CRITICAL] Address high-severity risks
246
- Change affects 12 critical components; Modification may break API contracts
657
+ ```bash
658
+ # Установить глобально
659
+ npm install -g archicore
660
+
661
+ # Или использовать локально
662
+ npx archicore [command]
247
663
  ```
248
664
 
249
- #### 3. Семантический поиск
665
+ #### Authentication
250
666
 
251
667
  ```bash
252
- npx tsx src/cli.ts search \
253
- --query "функции для обработки платежей" \
254
- --limit 5
668
+ # Device Flow (открывает браузер для авторизации)
669
+ archicore login
670
+
671
+ # Введите код из терминала на странице авторизации
672
+ # После успеха токен сохраняется в ~/.archicore/config.json
255
673
  ```
256
674
 
257
- Результат:
675
+ #### Project Management
676
+
677
+ ```bash
678
+ # Список проектов
679
+ archicore projects list
680
+
681
+ # Создать проект
682
+ archicore projects create --name "My App" --github "https://github.com/user/repo"
683
+
684
+ # Выбрать активный проект
685
+ archicore projects select
686
+
687
+ # Удалить проект
688
+ archicore projects delete --id abc123
689
+ ```
690
+
691
+ #### Code Analysis
692
+
693
+ ```bash
694
+ # Индексировать проект (AST + граф зависимостей)
695
+ archicore index --dir /path/to/project
696
+
697
+ # Полный анализ
698
+ archicore full-analysis
699
+
700
+ # Анализ безопасности
701
+ archicore security
702
+
703
+ # Поиск мертвого кода
704
+ archicore dead-code
705
+
706
+ # Метрики кода
707
+ archicore metrics
708
+
709
+ # Дублирование кода
710
+ archicore duplication
711
+
712
+ # Рефакторинг рекомендации
713
+ archicore refactoring
258
714
  ```
259
- 🔍 РЕЗУЛЬТАТЫ ПОИСКА:
260
715
 
261
- 1. src/payments/processor.ts:45
262
- Релевантность: 94.23%
263
- export class PaymentProcessor { processPayment(...)
716
+ #### Semantic Search
717
+
718
+ ```bash
719
+ # Поиск по смыслу
720
+ archicore search --query "функции валидации email" --limit 10
721
+
722
+ # Результат:
723
+ # 🔍 RESULTS:
724
+ #
725
+ # 1. src/utils/validators.ts:45 (relevance: 94.2%)
726
+ # export function validateEmail(email: string): boolean {
727
+ #
728
+ # 2. src/auth/email-validator.ts:12 (relevance: 89.7%)
729
+ # class EmailValidator {
730
+ ```
264
731
 
265
- 2. src/payments/stripe.ts:12
266
- Релевантность: 87.15%
267
- async function handleStripePayment(...)
732
+ #### AI Architect
268
733
 
269
- 3. src/billing/charge.ts:78
270
- Релевантность: 82.34%
271
- function calculateCharge(amount, currency)
734
+ ```bash
735
+ # Задать вопрос
736
+ archicore ask --question "Как организована работа с платежами?"
737
+
738
+ # Анализ изменений
739
+ archicore analyze \
740
+ --description "Добавить новый метод оплаты" \
741
+ --files "src/payments/processor.ts" \
742
+ --type "feature"
743
+
744
+ # Результат:
745
+ # ⚠️ AFFECTED COMPONENTS: 23
746
+ # 🔴 CRITICAL: 5
747
+ # 🟠 HIGH: 11
748
+ # 🟡 MEDIUM: 7
749
+ #
750
+ # RISKS:
751
+ # [HIGH] Breaking change in PaymentProcessor interface
752
+ # [MEDIUM] New dependencies added to payment flow
753
+ #
754
+ # RECOMMENDATIONS:
755
+ # ✅ Add backward compatibility wrapper
756
+ # ✅ Update API documentation
757
+ # ✅ Write integration tests for new method
272
758
  ```
273
759
 
274
- #### 4. Вопрос архитектору
760
+ #### Export
275
761
 
276
762
  ```bash
277
- npx tsx src/cli.ts ask \
278
- --question "Как организована работа с платежами в системе?"
763
+ # Экспорт результатов анализа
764
+ archicore export --format json --output analysis.json
765
+ archicore export --format html --output report.html
766
+ archicore export --format markdown --output ANALYSIS.md
767
+ archicore export --format csv --output metrics.csv
279
768
  ```
280
769
 
281
- Результат:
770
+ #### Interactive Mode
771
+
772
+ ```bash
773
+ # Интерактивный режим с autocomplete
774
+ archicore chat
775
+
776
+ # Внутри появится меню команд:
777
+ # > /help - Показать доступные команды
778
+ # > /search - Семантический поиск
779
+ # > /ask - Вопрос AI архитектору
780
+ # > /analyze - Анализ изменений
781
+ # > /metrics - Метрики проекта
782
+ # > /exit - Выход
282
783
  ```
283
- 💬 ОТВЕТ AI АРХИТЕКТОРА:
284
784
 
285
- В системе используется слоистая архитектура для работы с платежами:
785
+ ---
286
786
 
287
- 1. **Слой домена** (src/domain/payments)
288
- - PaymentEntity - доменная сущность платежа
289
- - PaymentStatus - статусы платежа
290
- - Бизнес-правила валидации
787
+ ### 🔌 REST API
291
788
 
292
- 2. **Слой приложения** (src/application/payments)
293
- - PaymentService - основной сервис обработки платежей
294
- - UseCase классы для различных сценариев
789
+ Полное REST API для интеграции с CI/CD, webhooks, custom tools.
295
790
 
296
- 3. **Инфраструктурный слой** (src/infrastructure/payments)
297
- - StripeAdapter - интеграция со Stripe
298
- - PaymentRepository - персистентность
299
- - EventPublisher - публикация событий
791
+ #### Base URL
300
792
 
301
- Платежи обрабатываются асинхронно через очередь, что обеспечивает
302
- надёжность и возможность повторных попыток при ошибках.
793
+ ```
794
+ Production: https://api.archicore.io
795
+ Development: http://localhost:3000/api
303
796
  ```
304
797
 
305
- #### 5. Генерация документации
798
+ #### Authentication
306
799
 
800
+ **JWT Token:**
307
801
  ```bash
308
- npx tsx src/cli.ts docs --output ARCHITECTURE.md
802
+ # Login
803
+ curl -X POST https://api.archicore.io/auth/login \
804
+ -H "Content-Type: application/json" \
805
+ -d '{"email":"user@example.com","password":"secret"}'
806
+
807
+ # Response:
808
+ # {"success":true,"token":"eyJhbGc...","user":{...}}
809
+
810
+ # Use token in requests
811
+ curl -H "Authorization: Bearer eyJhbGc..." \
812
+ https://api.archicore.io/projects
309
813
  ```
310
814
 
311
- Создаст подробную документацию по архитектуре проекта.
815
+ **API Key:**
816
+ ```bash
817
+ # Create API key (через dashboard /developer)
818
+ curl -X POST https://api.archicore.io/developer/keys \
819
+ -H "Authorization: Bearer YOUR_JWT" \
820
+ -d '{"name":"CI/CD Key","expiresInDays":365}'
821
+
822
+ # Use API key
823
+ curl -H "X-API-Key: ak_xxx" \
824
+ https://api.archicore.io/projects
825
+ ```
312
826
 
313
- ## Поддерживаемые LLM провайдеры
827
+ #### Endpoints Overview
314
828
 
315
- AIArhitector поддерживает несколько LLM провайдеров:
829
+ **Authentication:**
830
+ ```
831
+ POST /api/auth/register - Регистрация
832
+ POST /api/auth/login - Вход
833
+ POST /api/auth/logout - Выход
834
+ GET /api/auth/me - Текущий пользователь
835
+ GET /api/auth/usage - Статистика использования
836
+ POST /api/auth/send-verification-code - Отправить код верификации
837
+ POST /api/auth/verify-email - Подтвердить email
838
+ ```
316
839
 
317
- ### 1. **Claude (Anthropic)** ⭐ Рекомендуется
318
- - Лучшее качество для архитектурных решений
319
- - Модели: `claude-opus-4-20250514`, `claude-sonnet-4-20250514`
320
- - Контекст: до 200K токенов
321
- - Цена: $$$ (высокая)
840
+ **OAuth:**
841
+ ```
842
+ GET /api/auth/oauth/google - Начать Google OAuth
843
+ GET /api/auth/oauth/google/callback - Google callback
844
+ GET /api/auth/oauth/github - Начать GitHub OAuth
845
+ GET /api/auth/oauth/github/callback - GitHub callback
846
+ ```
322
847
 
323
- ### 2. **GPT (OpenAI)**
324
- - Отличное качество
325
- - Модели: `gpt-4-turbo-preview`, `gpt-4`, `gpt-3.5-turbo`
326
- - Контекст: до 128K токенов
327
- - Цена: $$ (средняя-высокая)
848
+ **Device Flow (CLI):**
849
+ ```
850
+ POST /api/auth/device/code - Получить device code
851
+ POST /api/auth/device/token - Обменять код на токен
852
+ GET /api/auth/device/verify/:code - Проверить код
853
+ POST /api/auth/device/authorize - Авторизовать устройство
854
+ ```
328
855
 
329
- ### 3. **DeepSeek** 💰 Бюджетный вариант ⚡ С автооптимизацией
330
- - Приемлемое качество для простых задач
331
- - Модели: `deepseek-chat`, `deepseek-coder`
332
- - Контекст: 16-32K токенов
333
- - Цена: $ (очень низкая, ~99% дешевле GPT-4)
334
- - **🚀 Автоматическая оптимизация промптов для лучшего качества!**
856
+ **Projects:**
857
+ ```
858
+ GET /api/projects - Список проектов
859
+ POST /api/projects - Создать проект
860
+ GET /api/projects/:id - Получить проект
861
+ PUT /api/projects/:id - Обновить проект
862
+ DELETE /api/projects/:id - Удалить проект
863
+ POST /api/projects/:id/index - Индексировать код
864
+ GET /api/projects/:id/architecture - Архитектурная информация
865
+ GET /api/projects/:id/graph - Граф зависимостей
866
+ GET /api/projects/:id/metrics - Метрики кода
867
+ ```
335
868
 
336
- ⚠️ **Важно**: Для критических архитектурных решений рекомендуется Claude или GPT-4. DeepSeek подходит для разработки/тестирования.
869
+ **Analysis:**
870
+ ```
871
+ POST /api/analyze/impact - Анализ влияния изменений
872
+ POST /api/analyze/security - Анализ безопасности
873
+ POST /api/analyze/full - Полный анализ
874
+ POST /api/analyze/dead-code - Мертвый код
875
+ POST /api/analyze/duplication - Дублирование
876
+ POST /api/analyze/refactoring - Рекомендации по рефакторингу
877
+ ```
337
878
 
338
- 📖 **Документация**:
339
- - [DEEPSEEK.md](./DEEPSEEK.md) - Подробное сравнение плюсов/минусов
340
- - [DEEPSEEK_OPTIMIZATION.md](./DEEPSEEK_OPTIMIZATION.md) - Как работает автооптимизация
879
+ **AI:**
880
+ ```
881
+ POST /api/ai/search - Семантический поиск
882
+ POST /api/ai/ask - Вопрос AI архитектору
883
+ POST /api/ai/simulate - Симуляция изменений
884
+ ```
341
885
 
342
- #### Что делает автооптимизация:
886
+ **GitHub:**
887
+ ```
888
+ GET /api/github/auth - GitHub OAuth
889
+ GET /api/github/callback - GitHub callback
890
+ GET /api/github/repositories - Список репозиториев
891
+ POST /api/github/webhooks - Создать webhook
892
+ ```
343
893
 
344
- 1. **Упрощает промпты** - убирает сложные формулировки
345
- 2. **Сокращает контекст** - только топ-3 самых важных фрагмента
346
- 3. **Переводит на английский** - DeepSeek лучше понимает английский
347
- 4. **Структурирует вывод** - требует четкий формат ответа
348
- 5. **Обрезает до оптимума** - 8000 символов вместо 32K
349
- 6. **Retry с упрощением** - до 2 попыток с прогрессивным упрощением
894
+ **Admin:**
895
+ ```
896
+ GET /api/admin/users - Список пользователей
897
+ PUT /api/admin/users/:id/tier - Изменить tier
898
+ GET /api/admin/stats - Статистика системы
899
+ GET /api/admin/audit-logs - Аудит логи
900
+ GET /api/admin/settings - Настройки системы
901
+ POST /api/admin/settings - Обновить настройки
902
+ POST /api/admin/test-email - Тест email
903
+ POST /api/admin/maintenance - Включить maintenance mode
904
+ GET /api/admin/export/all - Экспорт всех данных
905
+ ```
350
906
 
351
- **Результат**: DeepSeek работает в **1.5-2x точнее** с автооптимизацией!
907
+ **Developer:**
908
+ ```
909
+ GET /api/developer/keys - Список API ключей
910
+ POST /api/developer/keys - Создать API ключ
911
+ DELETE /api/developer/keys/:id - Удалить API ключ
912
+ POST /api/developer/keys/:id/revoke - Отозвать API ключ
913
+ ```
352
914
 
353
- ### Пример использования DeepSeek
915
+ #### Example: Analyze Impact
916
+
917
+ ```bash
918
+ curl -X POST https://api.archicore.io/analyze/impact \
919
+ -H "Authorization: Bearer YOUR_TOKEN" \
920
+ -H "Content-Type: application/json" \
921
+ -d '{
922
+ "projectId": "proj_abc123",
923
+ "change": {
924
+ "type": "modify",
925
+ "description": "Рефакторинг AuthService",
926
+ "files": ["src/services/auth-service.ts"],
927
+ "symbols": ["AuthService", "login", "register"]
928
+ }
929
+ }'
930
+ ```
354
931
 
355
- ```typescript
356
- const ai = new AIArhitector({
357
- rootDir: '/path/to/project',
358
- llm: {
359
- provider: 'deepseek', // вместо 'anthropic' или 'openai'
360
- model: 'deepseek-chat',
361
- temperature: 0.1,
362
- maxTokens: 4096
363
- },
364
- vectorStore: {
365
- url: 'http://localhost:6333',
366
- collectionName: 'my-project'
932
+ **Response:**
933
+ ```json
934
+ {
935
+ "success": true,
936
+ "impact": {
937
+ "affectedNodes": [
938
+ {
939
+ "id": "AuthController",
940
+ "file": "src/controllers/auth.ts",
941
+ "severity": "critical",
942
+ "reason": "Direct dependency on modified AuthService"
943
+ },
944
+ {
945
+ "id": "UserService",
946
+ "file": "src/services/user-service.ts",
947
+ "severity": "high",
948
+ "reason": "Calls AuthService.login()"
949
+ }
950
+ ],
951
+ "risks": [
952
+ {
953
+ "severity": "high",
954
+ "message": "Breaking change in public API",
955
+ "recommendation": "Add deprecation warnings before removing methods"
956
+ }
957
+ ],
958
+ "recommendations": [
959
+ "Review 15 affected components",
960
+ "Add integration tests for auth flow",
961
+ "Update API documentation"
962
+ ],
963
+ "summary": {
964
+ "total": 15,
965
+ "critical": 3,
966
+ "high": 7,
967
+ "medium": 4,
968
+ "low": 1
969
+ }
367
970
  }
368
- });
971
+ }
369
972
  ```
370
973
 
371
- ## Платформы
974
+ ---
372
975
 
373
- ### 🐧 Linux
976
+ ## 🔐 Authentication & Security
374
977
 
375
- Для Linux созданы shell-скрипты:
978
+ ArchiCore реализует многоуровневую систему безопасности корпоративного уровня.
376
979
 
377
- - **`setup.sh`** - Автоматическая установка и настройка
378
- - **`analyze-project.sh`** - Полный анализ проекта
379
- - **`ask-question.sh`** - Интерактивные вопросы AI
380
- - **`search-code.sh`** - Семантический поиск
381
- - **`test-full.sh`** - Проверка всей системы
382
- - **`start-qdrant-docker.sh`** - Запуск Qdrant в Docker
980
+ ### Authentication Methods
383
981
 
384
- **Быстрый старт Linux:**
385
- ```bash
386
- # 1. Запустить установку
387
- chmod +x setup.sh
388
- ./setup.sh
982
+ #### 1. Email + Password
389
983
 
390
- # 2. Настроить .env с API ключами
391
- nano .env
984
+ **Registration Flow:**
985
+ ```
986
+ 1. User submits email + password
987
+ 2. System checks disposable email (180+ blocked domains)
988
+ 3. Sends 6-digit verification code via SMTP (Zoho)
989
+ 4. User enters code (10-minute expiry)
990
+ 5. Password hashed with bcrypt (10 rounds)
991
+ 6. User created, JWT token issued
992
+ 7. Welcome email sent
993
+ ```
392
994
 
393
- # 3. Запустить анализ
394
- ./analyze-project.sh
395
- ```
396
-
397
- 📖 **Документация:**
398
- - [SETUP_LINUX.md](./SETUP_LINUX.md) - Полное руководство по установке
399
- - [QUICKSTART_LINUX.md](./QUICKSTART_LINUX.md) - Быстрый старт за 5 минут
400
-
401
- **Преимущества Linux:**
402
- - ✅ Лучше для production серверов
403
- - ✅ Легкая автоматизация (cron jobs)
404
- - ✅ Нет проблем с кодировкой
405
- - ✅ Отличная поддержка Docker
406
- - ✅ SSH доступ для удаленной работы
407
-
408
- ## Программное использование
409
-
410
- ```typescript
411
- import { AIArhitector, Change } from 'aiarhitector';
412
-
413
- // Создание экземпляра
414
- const ai = new AIArhitector({
415
- rootDir: '/path/to/project',
416
- llm: {
417
- provider: 'anthropic',
418
- model: 'claude-sonnet-4-20250514',
419
- temperature: 0.1,
420
- maxTokens: 4096
421
- },
422
- vectorStore: {
423
- url: 'http://localhost:6333',
424
- collectionName: 'my-project'
425
- }
426
- });
995
+ **Login Flow:**
996
+ ```
997
+ 1. User submits email + password
998
+ 2. Password verified with bcrypt
999
+ 3. JWT token issued (24h expiry)
1000
+ 4. Refresh token stored in DB (30d expiry)
1001
+ 5. Audit log created
1002
+ ```
427
1003
 
428
- // Инициализация
429
- await ai.initialize();
1004
+ #### 2. OAuth 2.0 (Google, GitHub)
430
1005
 
431
- // Анализ изменений
432
- const change: Change = {
433
- type: 'modify',
434
- description: 'Обновление API аутентификации',
435
- files: ['src/auth/api.ts'],
436
- symbols: ['AuthController', 'loginUser']
437
- };
1006
+ **Flow:**
1007
+ ```
1008
+ 1. User clicks "Continue with Google/GitHub"
1009
+ 2. Redirected to provider authorization page
1010
+ 3. User grants permissions
1011
+ 4. Provider redirects to /callback with code
1012
+ 5. ArchiCore exchanges code for access token
1013
+ 6. Fetches user profile (email, name, avatar)
1014
+ 7. Creates user if first login OR logs in existing
1015
+ 8. JWT token issued
1016
+ 9. Redirected to dashboard with token in URL
1017
+ 10. Frontend saves token to localStorage
1018
+ ```
438
1019
 
439
- const impact = await ai.analyzeChange(change);
1020
+ **Implemented Providers:**
1021
+ - ✅ Google OAuth 2.0 (scope: profile, email)
1022
+ - ✅ GitHub OAuth 2.0 (scope: user:email)
440
1023
 
441
- console.log('Затронутые компоненты:', impact.affectedNodes.length);
442
- console.log('Риски:', impact.risks);
443
- console.log('Рекомендации:', impact.recommendations);
1024
+ #### 3. Device Flow (CLI)
444
1025
 
445
- // Семантический поиск
446
- const results = await ai.searchCode('функции валидации email', 5);
1026
+ **Flow for CLI authentication:**
1027
+ ```
1028
+ 1. CLI requests device code: POST /api/auth/device/code
1029
+ 2. Server returns: {device_code, user_code, verification_url}
1030
+ 3. CLI displays: "Go to https://archicore.io/auth/device and enter: ABCD-1234"
1031
+ 4. User opens browser, enters code
1032
+ 5. User authorizes device
1033
+ 6. CLI polls: POST /api/auth/device/token with device_code
1034
+ 7. On success, receives JWT token
1035
+ 8. Token saved to ~/.archicore/config.json
1036
+ ```
447
1037
 
448
- // Вопрос архитектору
449
- const answer = await ai.askQuestion(
450
- 'Какие компоненты отвечают за аутентификацию?'
451
- );
1038
+ #### 4. API Keys
452
1039
 
453
- // Ревью кода
454
- const review = await ai.reviewCode(
455
- codeContent,
456
- ['src/auth/api.ts'],
457
- );
1040
+ **For programmatic access:**
1041
+ ```
1042
+ 1. User creates API key via dashboard (/developer)
1043
+ 2. Key format: ak_xxxxxxxxxxxxxxxxxx (40 chars)
1044
+ 3. Key stored hashed in database
1045
+ 4. Use in requests: X-API-Key: ak_xxx
1046
+ 5. Keys can be revoked or deleted
1047
+ 6. Supports expiration (optional)
1048
+ ```
458
1049
 
459
- // Генерация документации
460
- const docs = await ai.generateDocumentation();
1050
+ ### Security Features
1051
+
1052
+ #### Password Security
1053
+ - **Hashing**: bcrypt with 10 salt rounds
1054
+ - **Validation**: Min 8 chars, complexity requirements (planned)
1055
+ - **Reset**: Email-based password reset (planned)
1056
+
1057
+ #### JWT Tokens
1058
+ - **Algorithm**: HS256
1059
+ - **Expiry**: 24 hours (configurable)
1060
+ - **Payload**: userId, email, role, tier
1061
+ - **Secret**: From environment variable JWT_SECRET
1062
+ - **Refresh**: Refresh tokens with 30d expiry (planned)
1063
+
1064
+ #### Disposable Email Protection
1065
+ - **Database**: 180+ temporary email domains
1066
+ - **Blocked services**: 10minutemail, guerrillamail, mailinator, yopmail, temp-mail, etc.
1067
+ - **Check points**: Registration, email verification, OAuth
1068
+ - **Error message**: "Temporary/disposable email addresses are not allowed"
1069
+
1070
+ #### Email Verification
1071
+ - **Code**: 6 random digits
1072
+ - **Expiry**: 10 minutes
1073
+ - **Storage**: In-memory Map (auto-cleanup on expiry)
1074
+ - **Rate limit**: 30 seconds between resends
1075
+ - **Transport**: SMTP via Zoho (TLS, port 587)
1076
+ - **Templates**: Branded HTML emails
1077
+
1078
+ #### Rate Limiting
1079
+ - **Global**: 100 requests per 15 minutes per IP
1080
+ - **Auth endpoints**: 5 login attempts per 15 minutes
1081
+ - **Email sending**: 3 codes per hour per email
1082
+ - **Headers**: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
1083
+
1084
+ #### Encryption
1085
+ - **Algorithm**: AES-256-GCM
1086
+ - **Key**: From environment ENCRYPTION_KEY (32 chars)
1087
+ - **Use cases**: Sensitive user data, API keys in DB, OAuth tokens
1088
+
1089
+ #### Audit Logging
1090
+ **All actions logged:**
1091
+ - Authentication (login, logout, register, OAuth)
1092
+ - Project operations (create, update, delete)
1093
+ - Analysis requests
1094
+ - Admin actions (user management, settings changes)
1095
+ - API key operations
1096
+
1097
+ **Log fields:**
1098
+ - userId, username, action, timestamp, ip, userAgent
1099
+ - success/failure, errorMessage
1100
+ - details (JSON with context-specific data)
1101
+
1102
+ #### CORS & Headers
1103
+ - **CORS**: Configurable whitelist (production), allow-all (development)
1104
+ - **Helmet.js**: CSP, HSTS, X-Frame-Options, XSS Protection
1105
+ - **Gzip**: Response compression
1106
+
1107
+ #### HTTPS
1108
+ - **Production**: Let's Encrypt SSL certificates
1109
+ - **Auto-renewal**: Certbot cron job
1110
+ - **Redirect**: HTTP → HTTPS (nginx)
1111
+ - **HSTS**: Strict-Transport-Security header
1112
+
1113
+ ---
1114
+
1115
+ ## ⚙️ Configuration
1116
+
1117
+ ### Environment Variables
1118
+
1119
+ Полный список переменных окружения:
1120
+
1121
+ ```env
1122
+ # ═══════════════════════════════════════════════════════════
1123
+ # SERVER CONFIGURATION
1124
+ # ═══════════════════════════════════════════════════════════
1125
+ PORT=3000
1126
+ NODE_ENV=production
1127
+ BASE_URL=https://archicore.io
1128
+
1129
+ # ═══════════════════════════════════════════════════════════
1130
+ # DATABASE
1131
+ # ═══════════════════════════════════════════════════════════
1132
+ DATABASE_URL=postgresql://user:password@localhost:5432/archicore
1133
+ DATABASE_POOL_MIN=2
1134
+ DATABASE_POOL_MAX=20
1135
+
1136
+ # ═══════════════════════════════════════════════════════════
1137
+ # REDIS CACHE
1138
+ # ═══════════════════════════════════════════════════════════
1139
+ REDIS_URL=redis://localhost:6379
1140
+ REDIS_PASSWORD=
1141
+ REDIS_DB=0
1142
+
1143
+ # ═══════════════════════════════════════════════════════════
1144
+ # QDRANT VECTOR DATABASE
1145
+ # ═══════════════════════════════════════════════════════════
1146
+ QDRANT_URL=http://localhost:6333
1147
+ QDRANT_API_KEY=
1148
+ QDRANT_COLLECTION_NAME=archicore
1149
+
1150
+ # ═══════════════════════════════════════════════════════════
1151
+ # AI PROVIDERS
1152
+ # ═══════════════════════════════════════════════════════════
1153
+
1154
+ # Anthropic Claude (Рекомендуется)
1155
+ ANTHROPIC_API_KEY=sk-ant-api03-xxx
1156
+ ANTHROPIC_MODEL=claude-sonnet-4-20250514
1157
+ # Доступные модели:
1158
+ # - claude-opus-4-20250514 (самый умный, дорогой)
1159
+ # - claude-sonnet-4-20250514 (баланс качество/цена) ⭐
1160
+ # - claude-haiku-4-20250514 (быстрый, дешевый)
1161
+
1162
+ # OpenAI GPT
1163
+ OPENAI_API_KEY=sk-xxx
1164
+ OPENAI_MODEL=gpt-4-turbo-preview
1165
+ # Доступные модели:
1166
+ # - gpt-4-turbo-preview (новый GPT-4 Turbo)
1167
+ # - gpt-4 (стандартный GPT-4)
1168
+ # - gpt-3.5-turbo (быстрый, дешевый)
1169
+
1170
+ # DeepSeek (Бюджетный вариант)
1171
+ DEEPSEEK_API_KEY=sk-xxx
1172
+ DEEPSEEK_MODEL=deepseek-chat
1173
+ # Доступные модели:
1174
+ # - deepseek-chat (общего назначения)
1175
+ # - deepseek-coder (для кода) ⭐
1176
+
1177
+ # Jina AI (Embeddings)
1178
+ JINA_API_KEY=jina_xxx
1179
+ JINA_MODEL=jina-embeddings-v2-base-code
1180
+
1181
+ # ═══════════════════════════════════════════════════════════
1182
+ # OAUTH PROVIDERS
1183
+ # ═══════════════════════════════════════════════════════════
1184
+
1185
+ # Google OAuth 2.0
1186
+ GOOGLE_CLIENT_ID=xxx.apps.googleusercontent.com
1187
+ GOOGLE_CLIENT_SECRET=GOCSPX-xxx
1188
+ GOOGLE_CALLBACK_URL=https://archicore.io/api/auth/oauth/google/callback
1189
+
1190
+ # GitHub OAuth
1191
+ GITHUB_CLIENT_ID=xxx
1192
+ GITHUB_CLIENT_SECRET=xxx
1193
+ GITHUB_CALLBACK_URL=https://archicore.io/api/auth/oauth/github/callback
1194
+
1195
+ # ═══════════════════════════════════════════════════════════
1196
+ # EMAIL (SMTP)
1197
+ # ═══════════════════════════════════════════════════════════
1198
+ SMTP_HOST=smtp.zoho.com
1199
+ SMTP_PORT=587
1200
+ SMTP_SECURE=false
1201
+ ZOHO_SMTP_USER=noreply@archicore.io
1202
+ ZOHO_SMTP_PASS=xxx
1203
+ EMAIL_FROM_ADDRESS=noreply@archicore.io
1204
+ EMAIL_FROM_NAME=ArchiCore
1205
+
1206
+ # ═══════════════════════════════════════════════════════════
1207
+ # SECURITY
1208
+ # ═══════════════════════════════════════════════════════════
1209
+ JWT_SECRET=your-super-secret-jwt-key-min-32-chars
1210
+ JWT_EXPIRY=24h
1211
+ ENCRYPTION_KEY=your-32-character-encryption-key
1212
+ SESSION_SECRET=your-session-secret-min-32-chars
1213
+
1214
+ # CORS
1215
+ CORS_ORIGIN=https://archicore.io,https://app.archicore.io
1216
+ CORS_CREDENTIALS=true
1217
+
1218
+ # Rate Limiting
1219
+ RATE_LIMIT_WINDOW_MS=900000
1220
+ RATE_LIMIT_MAX_REQUESTS=100
1221
+
1222
+ # ═══════════════════════════════════════════════════════════
1223
+ # ADMIN
1224
+ # ═══════════════════════════════════════════════════════════
1225
+ ADMIN_EMAIL=admin@archicore.io
1226
+ ADMIN_PASSWORD=change-this-in-production
1227
+
1228
+ # ═══════════════════════════════════════════════════════════
1229
+ # FEATURES (Optional)
1230
+ # ═══════════════════════════════════════════════════════════
1231
+ ENABLE_GITHUB_INTEGRATION=true
1232
+ ENABLE_WEBHOOKS=true
1233
+ ENABLE_METRICS=true
1234
+ ENABLE_ANALYTICS=true
1235
+
1236
+ # ═══════════════════════════════════════════════════════════
1237
+ # LOGGING
1238
+ # ═══════════════════════════════════════════════════════════
1239
+ LOG_LEVEL=info
1240
+ # Levels: error, warn, info, debug, trace
1241
+ LOG_FORMAT=json
1242
+ # Formats: json, pretty
461
1243
  ```
462
1244
 
463
- ## Конфигурация архитектуры
1245
+ ### Architecture Configuration
464
1246
 
465
- Создайте файл `.aiarhitector/architecture.json`:
1247
+ Файл `.archicore/architecture.json` для определения правил архитектуры:
466
1248
 
467
1249
  ```json
468
1250
  {
469
1251
  "boundedContexts": [
1252
+ {
1253
+ "id": "auth",
1254
+ "name": "Authentication Context",
1255
+ "description": "User authentication and authorization",
1256
+ "modules": ["src/server/routes/auth.ts", "src/server/services/auth-service.ts"],
1257
+ "dependencies": [],
1258
+ "prohibitedDependencies": ["src/ui", "src/business-logic"]
1259
+ },
470
1260
  {
471
1261
  "id": "core",
472
- "name": "Core Domain",
473
- "description": "Основная бизнес-логика",
1262
+ "name": "Core Business Logic",
1263
+ "description": "Main business domain",
474
1264
  "modules": ["src/core"],
475
- "dependencies": [],
476
- "prohibitedDependencies": ["src/ui", "src/external"]
1265
+ "dependencies": ["auth"],
1266
+ "prohibitedDependencies": ["src/infrastructure"]
477
1267
  }
478
1268
  ],
479
1269
  "entities": [
480
1270
  {
481
1271
  "id": "user",
482
1272
  "name": "User",
483
- "context": "core",
484
- "properties": [...],
485
- "relationships": [...],
486
- "invariants": [...]
1273
+ "context": "auth",
1274
+ "properties": ["id", "email", "username", "role"],
1275
+ "relationships": [
1276
+ {"entity": "project", "type": "one-to-many"}
1277
+ ],
1278
+ "invariants": [
1279
+ "email must be unique",
1280
+ "email must be verified before login"
1281
+ ]
487
1282
  }
488
1283
  ],
489
- "rules": [],
490
- "invariants": []
1284
+ "rules": [
1285
+ {
1286
+ "id": "no-circular-deps",
1287
+ "description": "No circular dependencies allowed",
1288
+ "severity": "error",
1289
+ "check": "circular-dependencies"
1290
+ },
1291
+ {
1292
+ "id": "layer-separation",
1293
+ "description": "UI layer cannot depend on database layer",
1294
+ "severity": "error",
1295
+ "check": "layer-violation",
1296
+ "config": {
1297
+ "layers": ["ui", "business", "data"],
1298
+ "allowedDependencies": {
1299
+ "ui": ["business"],
1300
+ "business": ["data"],
1301
+ "data": []
1302
+ }
1303
+ }
1304
+ }
1305
+ ],
1306
+ "invariants": [
1307
+ "All API endpoints must have rate limiting",
1308
+ "All user actions must be logged in audit",
1309
+ "Passwords must be hashed with bcrypt"
1310
+ ]
491
1311
  }
492
1312
  ```
493
1313
 
494
- Пример см. в `.aiarhitector/architecture.example.json`
1314
+ ### Docker Compose Configuration
1315
+
1316
+ Пример production `docker-compose.yml`:
1317
+
1318
+ ```yaml
1319
+ version: '3.9'
1320
+
1321
+ services:
1322
+ # ArchiCore Application
1323
+ archicore:
1324
+ build: .
1325
+ container_name: archicore
1326
+ restart: unless-stopped
1327
+ ports:
1328
+ - "3000:3000"
1329
+ environment:
1330
+ - NODE_ENV=production
1331
+ - DATABASE_URL=postgresql://postgres:${DB_PASSWORD}@postgres:5432/archicore
1332
+ - REDIS_URL=redis://redis:6379
1333
+ - QDRANT_URL=http://qdrant:6333
1334
+ env_file:
1335
+ - .env
1336
+ depends_on:
1337
+ - postgres
1338
+ - redis
1339
+ - qdrant
1340
+ volumes:
1341
+ - ./data:/app/data
1342
+ networks:
1343
+ - archicore-network
1344
+ healthcheck:
1345
+ test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
1346
+ interval: 30s
1347
+ timeout: 10s
1348
+ retries: 3
1349
+
1350
+ # PostgreSQL Database
1351
+ postgres:
1352
+ image: postgres:15-alpine
1353
+ container_name: archicore-postgres
1354
+ restart: unless-stopped
1355
+ environment:
1356
+ - POSTGRES_USER=postgres
1357
+ - POSTGRES_PASSWORD=${DB_PASSWORD}
1358
+ - POSTGRES_DB=archicore
1359
+ volumes:
1360
+ - postgres-data:/var/lib/postgresql/data
1361
+ networks:
1362
+ - archicore-network
1363
+ healthcheck:
1364
+ test: ["CMD-SHELL", "pg_isready -U postgres"]
1365
+ interval: 10s
1366
+ timeout: 5s
1367
+ retries: 5
1368
+
1369
+ # Redis Cache
1370
+ redis:
1371
+ image: redis:7-alpine
1372
+ container_name: archicore-redis
1373
+ restart: unless-stopped
1374
+ command: redis-server --appendonly yes
1375
+ volumes:
1376
+ - redis-data:/data
1377
+ networks:
1378
+ - archicore-network
1379
+ healthcheck:
1380
+ test: ["CMD", "redis-cli", "ping"]
1381
+ interval: 10s
1382
+ timeout: 3s
1383
+ retries: 3
1384
+
1385
+ # Qdrant Vector Database
1386
+ qdrant:
1387
+ image: qdrant/qdrant:latest
1388
+ container_name: archicore-qdrant
1389
+ restart: unless-stopped
1390
+ volumes:
1391
+ - qdrant-data:/qdrant/storage
1392
+ networks:
1393
+ - archicore-network
1394
+ healthcheck:
1395
+ test: ["CMD-SHELL", "timeout 1 bash -c '</dev/tcp/localhost/6333'"]
1396
+ interval: 10s
1397
+ timeout: 5s
1398
+ retries: 3
1399
+
1400
+ # Nginx Reverse Proxy (Optional)
1401
+ nginx:
1402
+ image: nginx:alpine
1403
+ container_name: archicore-nginx
1404
+ restart: unless-stopped
1405
+ ports:
1406
+ - "80:80"
1407
+ - "443:443"
1408
+ volumes:
1409
+ - ./nginx.conf:/etc/nginx/nginx.conf:ro
1410
+ - ./ssl:/etc/nginx/ssl:ro
1411
+ depends_on:
1412
+ - archicore
1413
+ networks:
1414
+ - archicore-network
1415
+
1416
+ volumes:
1417
+ postgres-data:
1418
+ redis-data:
1419
+ qdrant-data:
1420
+
1421
+ networks:
1422
+ archicore-network:
1423
+ driver: bridge
1424
+ ```
1425
+
1426
+ ---
1427
+
1428
+ ## 🚢 Deployment
1429
+
1430
+ ### Production Deployment (Linux Server)
1431
+
1432
+ Полная инструкция для deployment на production сервер.
1433
+
1434
+ #### Prerequisites
1435
+
1436
+ - Ubuntu 20.04+ / Debian 11+ / CentOS 8+
1437
+ - Root или sudo доступ
1438
+ - Домен с настроенным DNS (A record → server IP)
1439
+
1440
+ #### Step 1: Prepare Server
1441
+
1442
+ ```bash
1443
+ # Обновить систему
1444
+ sudo apt update && sudo apt upgrade -y
1445
+
1446
+ # Установить Docker
1447
+ curl -fsSL https://get.docker.com -o get-docker.sh
1448
+ sudo sh get-docker.sh
1449
+ sudo usermod -aG docker $USER
1450
+
1451
+ # Установить Docker Compose
1452
+ sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
1453
+ sudo chmod +x /usr/local/bin/docker-compose
1454
+
1455
+ # Установить Nginx
1456
+ sudo apt install nginx -y
1457
+
1458
+ # Установить Certbot (Let's Encrypt)
1459
+ sudo apt install certbot python3-certbot-nginx -y
1460
+ ```
1461
+
1462
+ #### Step 2: Clone & Configure
1463
+
1464
+ ```bash
1465
+ # Клонировать репозиторий
1466
+ cd /opt
1467
+ sudo git clone https://github.com/yourusername/archicore.git
1468
+ cd archicore
1469
+
1470
+ # Создать .env
1471
+ sudo cp .env.example .env
1472
+ sudo nano .env # Заполнить production значения
1473
+
1474
+ # Установить правильные permissions
1475
+ sudo chown -R $USER:$USER /opt/archicore
1476
+ ```
1477
+
1478
+ #### Step 3: SSL Certificate
1479
+
1480
+ ```bash
1481
+ # Получить SSL сертификат
1482
+ sudo certbot --nginx -d archicore.io -d www.archicore.io -d api.archicore.io -d docs.archicore.io
1483
+
1484
+ # Auto-renewal настроен автоматически через systemd timer
1485
+ # Проверить:
1486
+ sudo systemctl status certbot.timer
1487
+ ```
1488
+
1489
+ #### Step 4: Nginx Configuration
1490
+
1491
+ ```bash
1492
+ # Создать конфиг
1493
+ sudo nano /etc/nginx/sites-available/archicore
1494
+
1495
+ # Вставить:
1496
+ ```
1497
+
1498
+ ```nginx
1499
+ # Main app (archicore.io)
1500
+ server {
1501
+ listen 443 ssl http2;
1502
+ server_name archicore.io www.archicore.io;
1503
+
1504
+ ssl_certificate /etc/letsencrypt/live/archicore.io/fullchain.pem;
1505
+ ssl_certificate_key /etc/letsencrypt/live/archicore.io/privkey.pem;
1506
+
1507
+ location / {
1508
+ proxy_pass http://localhost:3000;
1509
+ proxy_http_version 1.1;
1510
+ proxy_set_header Upgrade $http_upgrade;
1511
+ proxy_set_header Connection 'upgrade';
1512
+ proxy_set_header Host $host;
1513
+ proxy_set_header X-Real-IP $remote_addr;
1514
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
1515
+ proxy_set_header X-Forwarded-Proto $scheme;
1516
+ proxy_cache_bypass $http_upgrade;
1517
+ }
1518
+ }
1519
+
1520
+ # API subdomain (api.archicore.io)
1521
+ server {
1522
+ listen 443 ssl http2;
1523
+ server_name api.archicore.io;
1524
+
1525
+ ssl_certificate /etc/letsencrypt/live/archicore.io/fullchain.pem;
1526
+ ssl_certificate_key /etc/letsencrypt/live/archicore.io/privkey.pem;
1527
+
1528
+ location / {
1529
+ proxy_pass http://localhost:3000/api;
1530
+ proxy_http_version 1.1;
1531
+ proxy_set_header Host $host;
1532
+ proxy_set_header X-Real-IP $remote_addr;
1533
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
1534
+ proxy_set_header X-Forwarded-Proto $scheme;
1535
+ }
1536
+ }
1537
+
1538
+ # Redirect HTTP to HTTPS
1539
+ server {
1540
+ listen 80;
1541
+ server_name archicore.io www.archicore.io api.archicore.io;
1542
+ return 301 https://$host$request_uri;
1543
+ }
1544
+ ```
1545
+
1546
+ ```bash
1547
+ # Включить сайт
1548
+ sudo ln -s /etc/nginx/sites-available/archicore /etc/nginx/sites-enabled/
1549
+ sudo nginx -t
1550
+ sudo systemctl reload nginx
1551
+ ```
1552
+
1553
+ #### Step 5: Start Services
1554
+
1555
+ ```bash
1556
+ cd /opt/archicore
1557
+
1558
+ # Собрать образы
1559
+ sudo docker compose build
1560
+
1561
+ # Запустить все сервисы
1562
+ sudo docker compose up -d
1563
+
1564
+ # Проверить статус
1565
+ sudo docker compose ps
1566
+ sudo docker compose logs -f archicore
1567
+ ```
1568
+
1569
+ #### Step 6: Setup Systemd Service (Optional)
1570
+
1571
+ Для автоматического запуска при перезагрузке:
1572
+
1573
+ ```bash
1574
+ sudo nano /etc/systemd/system/archicore.service
1575
+ ```
1576
+
1577
+ ```ini
1578
+ [Unit]
1579
+ Description=ArchiCore Application
1580
+ Requires=docker.service
1581
+ After=docker.service
1582
+
1583
+ [Service]
1584
+ Type=oneshot
1585
+ RemainAfterExit=yes
1586
+ WorkingDirectory=/opt/archicore
1587
+ ExecStart=/usr/local/bin/docker-compose up -d
1588
+ ExecStop=/usr/local/bin/docker-compose down
1589
+ TimeoutStartSec=0
1590
+
1591
+ [Install]
1592
+ WantedBy=multi-user.target
1593
+ ```
1594
+
1595
+ ```bash
1596
+ sudo systemctl enable archicore
1597
+ sudo systemctl start archicore
1598
+ ```
1599
+
1600
+ #### Step 7: Monitoring & Logs
1601
+
1602
+ ```bash
1603
+ # Просмотр логов
1604
+ sudo docker compose logs -f archicore
1605
+ sudo docker compose logs -f postgres
1606
+ sudo docker compose logs -f redis
1607
+
1608
+ # Статус контейнеров
1609
+ sudo docker compose ps
1610
+
1611
+ # Использование ресурсов
1612
+ sudo docker stats
1613
+
1614
+ # Nginx access log
1615
+ sudo tail -f /var/log/nginx/access.log
1616
+
1617
+ # Nginx error log
1618
+ sudo tail -f /var/log/nginx/error.log
1619
+ ```
1620
+
1621
+ #### Step 8: Backup Strategy
1622
+
1623
+ ```bash
1624
+ # Создать backup скрипт
1625
+ sudo nano /opt/archicore/backup.sh
1626
+ ```
1627
+
1628
+ ```bash
1629
+ #!/bin/bash
1630
+ BACKUP_DIR=/opt/backups/archicore
1631
+ DATE=$(date +%Y%m%d_%H%M%S)
1632
+
1633
+ # Создать директорию
1634
+ mkdir -p $BACKUP_DIR
1635
+
1636
+ # Backup PostgreSQL
1637
+ docker exec archicore-postgres pg_dump -U postgres archicore | gzip > $BACKUP_DIR/postgres_$DATE.sql.gz
1638
+
1639
+ # Backup Redis
1640
+ docker exec archicore-redis redis-cli BGSAVE
1641
+ docker cp archicore-redis:/data/dump.rdb $BACKUP_DIR/redis_$DATE.rdb
1642
+
1643
+ # Backup Qdrant
1644
+ docker cp archicore-qdrant:/qdrant/storage $BACKUP_DIR/qdrant_$DATE
1645
+
1646
+ # Удалить старые бэкапы (>30 дней)
1647
+ find $BACKUP_DIR -name "*.gz" -mtime +30 -delete
1648
+
1649
+ echo "Backup completed: $DATE"
1650
+ ```
1651
+
1652
+ ```bash
1653
+ # Сделать исполняемым
1654
+ sudo chmod +x /opt/archicore/backup.sh
1655
+
1656
+ # Добавить в cron (ежедневно в 2 AM)
1657
+ sudo crontab -e
1658
+ 0 2 * * * /opt/archicore/backup.sh >> /var/log/archicore-backup.log 2>&1
1659
+ ```
1660
+
1661
+ #### Step 9: Update Procedure
1662
+
1663
+ ```bash
1664
+ # Обновление ArchiCore до новой версии
1665
+ cd /opt/archicore
1666
+ sudo git pull origin main
1667
+ sudo docker compose build
1668
+ sudo docker compose up -d
1669
+
1670
+ # Откатиться к предыдущей версии при проблемах
1671
+ sudo git log --oneline # Найти хеш коммита
1672
+ sudo git checkout <commit-hash>
1673
+ sudo docker compose build
1674
+ sudo docker compose up -d
1675
+ ```
1676
+
1677
+ ### CI/CD Pipeline (GitLab CI)
1678
+
1679
+ Пример `.gitlab-ci.yml`:
1680
+
1681
+ ```yaml
1682
+ stages:
1683
+ - test
1684
+ - build
1685
+ - deploy
1686
+
1687
+ variables:
1688
+ DOCKER_DRIVER: overlay2
1689
+ DOCKER_TLS_CERTDIR: "/certs"
1690
+
1691
+ # Run tests
1692
+ test:
1693
+ stage: test
1694
+ image: node:18
1695
+ cache:
1696
+ paths:
1697
+ - node_modules/
1698
+ script:
1699
+ - npm ci
1700
+ - npm run lint
1701
+ - npm run test # Когда тесты будут написаны
1702
+ only:
1703
+ - merge_requests
1704
+ - main
1705
+
1706
+ # Build Docker image
1707
+ build:
1708
+ stage: build
1709
+ image: docker:latest
1710
+ services:
1711
+ - docker:dind
1712
+ script:
1713
+ - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
1714
+ - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA .
1715
+ - docker build -t $CI_REGISTRY_IMAGE:latest .
1716
+ - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
1717
+ - docker push $CI_REGISTRY_IMAGE:latest
1718
+ only:
1719
+ - main
1720
+
1721
+ # Deploy to production
1722
+ deploy_production:
1723
+ stage: deploy
1724
+ image: alpine:latest
1725
+ before_script:
1726
+ - apk add --no-cache openssh-client
1727
+ - eval $(ssh-agent -s)
1728
+ - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
1729
+ - mkdir -p ~/.ssh
1730
+ - chmod 700 ~/.ssh
1731
+ - ssh-keyscan $PRODUCTION_SERVER >> ~/.ssh/known_hosts
1732
+ script:
1733
+ - ssh $PRODUCTION_USER@$PRODUCTION_SERVER "cd /opt/archicore && git pull && docker compose pull && docker compose up -d"
1734
+ only:
1735
+ - main
1736
+ when: manual
1737
+ ```
1738
+
1739
+ ---
1740
+
1741
+ ## 📚 API Reference
1742
+
1743
+ ### Authentication API
1744
+
1745
+ #### POST /api/auth/register
1746
+
1747
+ Регистрация нового пользователя.
1748
+
1749
+ **Request:**
1750
+ ```json
1751
+ {
1752
+ "email": "user@example.com",
1753
+ "password": "SecurePass123!",
1754
+ "username": "johndoe"
1755
+ }
1756
+ ```
1757
+
1758
+ **Response (200):**
1759
+ ```json
1760
+ {
1761
+ "success": true,
1762
+ "message": "Verification code sent to your email"
1763
+ }
1764
+ ```
1765
+
1766
+ **Errors:**
1767
+ - `400` - Invalid email/password, disposable email blocked
1768
+ - `409` - Email already exists
1769
+
1770
+ ---
1771
+
1772
+ #### POST /api/auth/verify-email
1773
+
1774
+ Подтверждение email с verification code.
1775
+
1776
+ **Request:**
1777
+ ```json
1778
+ {
1779
+ "email": "user@example.com",
1780
+ "code": "123456"
1781
+ }
1782
+ ```
1783
+
1784
+ **Response (200):**
1785
+ ```json
1786
+ {
1787
+ "success": true,
1788
+ "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
1789
+ "user": {
1790
+ "id": "usr_abc123",
1791
+ "email": "user@example.com",
1792
+ "username": "johndoe",
1793
+ "role": "user",
1794
+ "tier": "free",
1795
+ "createdAt": "2026-01-17T10:00:00Z"
1796
+ }
1797
+ }
1798
+ ```
1799
+
1800
+ **Errors:**
1801
+ - `400` - Invalid or expired code
1802
+ - `404` - Email not found
1803
+
1804
+ ---
1805
+
1806
+ #### POST /api/auth/login
1807
+
1808
+ Вход с email и паролем.
1809
+
1810
+ **Request:**
1811
+ ```json
1812
+ {
1813
+ "email": "user@example.com",
1814
+ "password": "SecurePass123!"
1815
+ }
1816
+ ```
1817
+
1818
+ **Response (200):**
1819
+ ```json
1820
+ {
1821
+ "success": true,
1822
+ "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
1823
+ "user": {
1824
+ "id": "usr_abc123",
1825
+ "email": "user@example.com",
1826
+ "username": "johndoe",
1827
+ "role": "user",
1828
+ "tier": "pro",
1829
+ "createdAt": "2026-01-17T10:00:00Z"
1830
+ }
1831
+ }
1832
+ ```
1833
+
1834
+ **Errors:**
1835
+ - `401` - Invalid credentials
1836
+ - `403` - Email not verified
1837
+
1838
+ ---
1839
+
1840
+ ### Projects API
1841
+
1842
+ #### GET /api/projects
1843
+
1844
+ Получить список проектов пользователя.
1845
+
1846
+ **Headers:**
1847
+ ```
1848
+ Authorization: Bearer <token>
1849
+ ```
1850
+
1851
+ **Response (200):**
1852
+ ```json
1853
+ {
1854
+ "success": true,
1855
+ "projects": [
1856
+ {
1857
+ "id": "proj_abc123",
1858
+ "name": "E-commerce Platform",
1859
+ "description": "Online store backend",
1860
+ "githubUrl": "https://github.com/user/ecommerce",
1861
+ "language": "TypeScript",
1862
+ "filesCount": 243,
1863
+ "linesOfCode": 15420,
1864
+ "indexed": true,
1865
+ "lastIndexed": "2026-01-17T12:00:00Z",
1866
+ "createdAt": "2026-01-15T10:00:00Z"
1867
+ }
1868
+ ]
1869
+ }
1870
+ ```
1871
+
1872
+ ---
1873
+
1874
+ #### POST /api/projects
1875
+
1876
+ Создать новый проект.
1877
+
1878
+ **Request:**
1879
+ ```json
1880
+ {
1881
+ "name": "E-commerce Platform",
1882
+ "description": "Online store backend",
1883
+ "githubUrl": "https://github.com/user/ecommerce"
1884
+ }
1885
+ ```
1886
+
1887
+ **Response (201):**
1888
+ ```json
1889
+ {
1890
+ "success": true,
1891
+ "project": {
1892
+ "id": "proj_abc123",
1893
+ "name": "E-commerce Platform",
1894
+ "description": "Online store backend",
1895
+ "githubUrl": "https://github.com/user/ecommerce",
1896
+ "indexed": false,
1897
+ "createdAt": "2026-01-17T12:00:00Z"
1898
+ }
1899
+ }
1900
+ ```
1901
+
1902
+ ---
1903
+
1904
+ #### POST /api/projects/:id/index
1905
+
1906
+ Индексировать код проекта.
1907
+
1908
+ **Response (200):**
1909
+ ```json
1910
+ {
1911
+ "success": true,
1912
+ "stats": {
1913
+ "filesProcessed": 243,
1914
+ "symbolsExtracted": 1854,
1915
+ "graphNodes": 2107,
1916
+ "graphEdges": 4523,
1917
+ "vectorsCreated": 1854,
1918
+ "languages": {
1919
+ "TypeScript": 180,
1920
+ "JavaScript": 45,
1921
+ "JSON": 18
1922
+ },
1923
+ "symbols": {
1924
+ "function": 892,
1925
+ "class": 156,
1926
+ "interface": 234,
1927
+ "variable": 572
1928
+ }
1929
+ }
1930
+ }
1931
+ ```
1932
+
1933
+ ---
1934
+
1935
+ ### Analysis API
1936
+
1937
+ #### POST /api/analyze/impact
1938
+
1939
+ Анализ влияния изменений.
1940
+
1941
+ **Request:**
1942
+ ```json
1943
+ {
1944
+ "projectId": "proj_abc123",
1945
+ "change": {
1946
+ "type": "modify",
1947
+ "description": "Refactor payment service",
1948
+ "files": ["src/services/payment-service.ts"],
1949
+ "symbols": ["PaymentService", "processPayment"]
1950
+ }
1951
+ }
1952
+ ```
1953
+
1954
+ **Response (200):**
1955
+ ```json
1956
+ {
1957
+ "success": true,
1958
+ "impact": {
1959
+ "affectedComponents": [
1960
+ {
1961
+ "id": "PaymentController",
1962
+ "file": "src/controllers/payment.ts",
1963
+ "line": 45,
1964
+ "severity": "critical",
1965
+ "reason": "Direct dependency on PaymentService"
1966
+ },
1967
+ {
1968
+ "id": "OrderService",
1969
+ "file": "src/services/order-service.ts",
1970
+ "line": 120,
1971
+ "severity": "high",
1972
+ "reason": "Calls PaymentService.processPayment()"
1973
+ }
1974
+ ],
1975
+ "risks": [
1976
+ {
1977
+ "severity": "critical",
1978
+ "message": "Breaking change in public API",
1979
+ "recommendation": "Add deprecation warnings"
1980
+ },
1981
+ {
1982
+ "severity": "high",
1983
+ "message": "12 components depend on modified code",
1984
+ "recommendation": "Review all affected components"
1985
+ }
1986
+ ],
1987
+ "recommendations": [
1988
+ "Add integration tests for payment flow",
1989
+ "Update API documentation",
1990
+ "Notify team about breaking changes"
1991
+ ],
1992
+ "summary": {
1993
+ "total": 23,
1994
+ "critical": 3,
1995
+ "high": 12,
1996
+ "medium": 6,
1997
+ "low": 2
1998
+ }
1999
+ }
2000
+ }
2001
+ ```
2002
+
2003
+ ---
2004
+
2005
+ #### POST /api/analyze/security
2006
+
2007
+ Анализ безопасности кода.
2008
+
2009
+ **Response (200):**
2010
+ ```json
2011
+ {
2012
+ "success": true,
2013
+ "findings": [
2014
+ {
2015
+ "severity": "critical",
2016
+ "type": "SQL Injection",
2017
+ "file": "src/database/users.ts",
2018
+ "line": 45,
2019
+ "message": "Unsanitized user input in SQL query",
2020
+ "recommendation": "Use parameterized queries"
2021
+ },
2022
+ {
2023
+ "severity": "high",
2024
+ "type": "XSS Vulnerability",
2025
+ "file": "src/views/profile.ts",
2026
+ "line": 23,
2027
+ "message": "Unescaped user content in HTML",
2028
+ "recommendation": "Use proper HTML escaping"
2029
+ }
2030
+ ],
2031
+ "summary": {
2032
+ "critical": 1,
2033
+ "high": 3,
2034
+ "medium": 7,
2035
+ "low": 12,
2036
+ "info": 5
2037
+ }
2038
+ }
2039
+ ```
2040
+
2041
+ ---
2042
+
2043
+ ### AI API
2044
+
2045
+ #### POST /api/ai/search
2046
+
2047
+ Семантический поиск кода.
2048
+
2049
+ **Request:**
2050
+ ```json
2051
+ {
2052
+ "projectId": "proj_abc123",
2053
+ "query": "функции валидации email",
2054
+ "limit": 5
2055
+ }
2056
+ ```
2057
+
2058
+ **Response (200):**
2059
+ ```json
2060
+ {
2061
+ "success": true,
2062
+ "results": [
2063
+ {
2064
+ "file": "src/utils/validators.ts",
2065
+ "line": 45,
2066
+ "code": "export function validateEmail(email: string): boolean {",
2067
+ "relevance": 0.942,
2068
+ "context": "Email validation utility"
2069
+ },
2070
+ {
2071
+ "file": "src/auth/email-validator.ts",
2072
+ "line": 12,
2073
+ "code": "class EmailValidator implements IValidator {",
2074
+ "relevance": 0.897,
2075
+ "context": "Authentication email validation"
2076
+ }
2077
+ ]
2078
+ }
2079
+ ```
2080
+
2081
+ ---
2082
+
2083
+ #### POST /api/ai/ask
2084
+
2085
+ Задать вопрос AI архитектору.
2086
+
2087
+ **Request:**
2088
+ ```json
2089
+ {
2090
+ "projectId": "proj_abc123",
2091
+ "question": "Как организована аутентификация в системе?"
2092
+ }
2093
+ ```
2094
+
2095
+ **Response (200):**
2096
+ ```json
2097
+ {
2098
+ "success": true,
2099
+ "answer": "В системе используется многоуровневая аутентификация:\n\n1. **JWT Tokens** - основной механизм (src/auth/jwt.ts)\n2. **OAuth 2.0** - Google и GitHub (src/auth/oauth/)\n3. **Email Verification** - подтверждение через SMTP (src/auth/email-verify.ts)\n\nПоток аутентификации:\n- User → Email+Password OR OAuth\n- Verification code → Email\n- Code validation → JWT token\n- Token → Stored in localStorage\n- Requests → Authorization: Bearer <token>\n\nБезопасность:\n- Passwords: bcrypt (10 rounds)\n- Tokens: HS256, 24h expiry\n- Rate limiting: 5 attempts/15min",
2100
+ "sources": [
2101
+ {"file": "src/auth/jwt.ts", "relevance": 0.95},
2102
+ {"file": "src/auth/oauth/google.ts", "relevance": 0.88},
2103
+ {"file": "src/auth/email-verify.ts", "relevance": 0.91}
2104
+ ]
2105
+ }
2106
+ ```
2107
+
2108
+ ---
2109
+
2110
+ ## 🛠️ Development
2111
+
2112
+ ### Setup Development Environment
2113
+
2114
+ ```bash
2115
+ # Clone repository
2116
+ git clone https://github.com/yourusername/archicore.git
2117
+ cd archicore
2118
+
2119
+ # Install dependencies
2120
+ npm install
2121
+
2122
+ # Start databases (Docker)
2123
+ docker compose -f docker-compose.dev.yml up -d
2124
+
2125
+ # Copy env file
2126
+ cp .env.example .env
2127
+
2128
+ # Fill in development keys
2129
+ nano .env
2130
+
2131
+ # Start in development mode (with hot reload)
2132
+ npm run dev
2133
+ ```
2134
+
2135
+ ### Project Structure
2136
+
2137
+ ```
2138
+ archicore/
2139
+ ├── public/ # Frontend (SPA-like vanilla JS)
2140
+ │ ├── index.html # Dashboard
2141
+ │ ├── auth.html # Authentication page
2142
+ │ ├── pricing.html # Pricing page
2143
+ │ ├── admin.html # Admin panel
2144
+ │ ├── privacy.html # Privacy policy
2145
+ │ ├── terms.html # Terms of service
2146
+ │ └── assets/ # Static assets
2147
+ ├── src/
2148
+ │ ├── server/ # Backend (Express)
2149
+ │ │ ├── routes/ # API routes
2150
+ │ │ │ ├── auth.ts # Authentication endpoints
2151
+ │ │ │ ├── oauth.ts # OAuth flows
2152
+ │ │ │ ├── projects.ts # Project management
2153
+ │ │ │ ├── analyze.ts # Analysis endpoints
2154
+ │ │ │ ├── ai.ts # AI endpoints
2155
+ │ │ │ ├── admin.ts # Admin endpoints
2156
+ │ │ │ └── developer.ts # API keys management
2157
+ │ │ ├── services/ # Business logic
2158
+ │ │ │ ├── auth-service.ts
2159
+ │ │ │ ├── audit-service.ts
2160
+ │ │ │ ├── database.ts
2161
+ │ │ │ ├── email-service.ts
2162
+ │ │ │ └── encryption.ts
2163
+ │ │ ├── config/ # Configuration
2164
+ │ │ │ └── passport.ts # OAuth strategies
2165
+ │ │ └── middleware/ # Express middleware
2166
+ │ ├── code-index/ # Code indexing engine
2167
+ │ │ ├── index.ts # Main indexer
2168
+ │ │ ├── ast-parser.ts # Tree-sitter parser
2169
+ │ │ ├── symbol-extractor.ts
2170
+ │ │ └── dependency-graph.ts
2171
+ │ ├── semantic-memory/ # Vector DB layer
2172
+ │ │ ├── index.ts
2173
+ │ │ ├── embedding-service.ts # Jina AI
2174
+ │ │ └── vector-store.ts # Qdrant
2175
+ │ ├── impact-engine/ # Change impact analysis
2176
+ │ │ └── index.ts
2177
+ │ ├── orchestrator/ # AI orchestration
2178
+ │ │ └── index.ts # Claude/GPT/DeepSeek
2179
+ │ ├── analyzers/ # Code analyzers
2180
+ │ │ ├── security.ts
2181
+ │ │ ├── dead-code.ts
2182
+ │ │ ├── duplication.ts
2183
+ │ │ └── metrics.ts
2184
+ │ ├── cli/ # CLI tool
2185
+ │ │ └── commands/
2186
+ │ ├── types/ # TypeScript types
2187
+ │ └── utils/ # Utilities
2188
+ ├── .archicore/ # Architecture config
2189
+ │ └── architecture.json
2190
+ ├── docker-compose.yml # Production compose
2191
+ ├── docker-compose.dev.yml # Development compose
2192
+ ├── Dockerfile
2193
+ ├── package.json
2194
+ ├── tsconfig.json
2195
+ └── README.md
2196
+ ```
2197
+
2198
+ ### Available Scripts
2199
+
2200
+ ```bash
2201
+ # Development
2202
+ npm run dev # Start with hot reload (tsx watch)
2203
+ npm run dev:debug # Start with debugger
2204
+
2205
+ # Build
2206
+ npm run build # Compile TypeScript
2207
+ npm run build:frontend # Minify & obfuscate frontend
2208
+ npm run build:all # Build backend + frontend
2209
+
2210
+ # Production
2211
+ npm start # Start production server
2212
+
2213
+ # CLI
2214
+ npm run cli # Run CLI commands
2215
+
2216
+ # Database
2217
+ npm run db:migrate # Run migrations (planned)
2218
+ npm run db:seed # Seed database (planned)
2219
+
2220
+ # Testing
2221
+ npm test # Run tests (planned)
2222
+ npm run test:watch # Watch mode (planned)
2223
+ npm run test:coverage # Coverage report (planned)
2224
+
2225
+ # Linting
2226
+ npm run lint # ESLint
2227
+ npm run lint:fix # Auto-fix issues
2228
+ npm run format # Prettier (planned)
2229
+
2230
+ # Docker
2231
+ npm run docker:build # Build Docker image
2232
+ npm run docker:up # Start containers
2233
+ npm run docker:down # Stop containers
2234
+ npm run docker:logs # View logs
2235
+ ```
495
2236
 
496
- ## Этапы внедрения
2237
+ ### Code Style
2238
+
2239
+ - **Language**: TypeScript (strict mode)
2240
+ - **Formatting**: Prettier (2 spaces, single quotes)
2241
+ - **Linting**: ESLint (Airbnb config)
2242
+ - **Naming**:
2243
+ - Files: `kebab-case.ts`
2244
+ - Classes: `PascalCase`
2245
+ - Functions: `camelCase`
2246
+ - Constants: `UPPER_SNAKE_CASE`
2247
+ - Interfaces: `PascalCase` (no `I` prefix)
2248
+
2249
+ ### Contributing Guidelines
2250
+
2251
+ 1. **Fork** the repository
2252
+ 2. **Create** feature branch (`git checkout -b feature/amazing-feature`)
2253
+ 3. **Commit** changes (`git commit -m 'Add amazing feature'`)
2254
+ 4. **Push** to branch (`git push origin feature/amazing-feature`)
2255
+ 5. **Open** Pull Request
2256
+
2257
+ **PR Requirements:**
2258
+ - Clear description of changes
2259
+ - Tests for new features (when test framework is ready)
2260
+ - No linting errors
2261
+ - Updated documentation if needed
2262
+
2263
+ ---
2264
+
2265
+ ## 🗺️ Roadmap
2266
+
2267
+ ### Q1 2026 (Current)
2268
+
2269
+ - [x] ✅ Core code indexing (AST + dependency graph)
2270
+ - [x] ✅ Semantic memory (Qdrant + embeddings)
2271
+ - [x] ✅ Impact analysis engine
2272
+ - [x] ✅ Web dashboard
2273
+ - [x] ✅ Authentication (Email, OAuth, Device Flow)
2274
+ - [x] ✅ Email verification system
2275
+ - [x] ✅ Disposable email protection
2276
+ - [x] ✅ PostgreSQL integration
2277
+ - [x] ✅ Redis caching
2278
+ - [x] ✅ Audit logging
2279
+ - [x] ✅ Admin panel
2280
+ - [x] ✅ Domain & SSL setup
2281
+ - [ ] ⏳ Payment integration (Revolut)
2282
+ - [ ] ⏳ Unit & integration tests
2283
+
2284
+ ### Q2 2026
2285
+
2286
+ - [ ] GitHub PR analysis (automatic comments)
2287
+ - [ ] GitLab integration
2288
+ - [ ] VS Code extension
2289
+ - [ ] Slack/Discord notifications
2290
+ - [ ] Custom architecture rules engine
2291
+ - [ ] Team collaboration features
2292
+ - [ ] Advanced metrics dashboard
2293
+ - [ ] Code quality trends
2294
+
2295
+ ### Q3 2026
2296
+
2297
+ - [ ] JetBrains IDE plugin (IntelliJ, WebStorm)
2298
+ - [ ] Automated refactoring suggestions with code generation
2299
+ - [ ] Technical debt tracking & prioritization
2300
+ - [ ] AI-powered architecture recommendations
2301
+ - [ ] On-premise deployment option
2302
+ - [ ] SAML/SSO authentication
2303
+
2304
+ ### Q4 2026
2305
+
2306
+ - [ ] Real-time collaboration (shared analysis sessions)
2307
+ - [ ] Custom LLM fine-tuning for domain-specific code
2308
+ - [ ] Advanced visualization (3D dependency graphs)
2309
+ - [ ] Mobile app (iOS/Android)
2310
+ - [ ] Kubernetes operator
2311
+ - [ ] Multi-region deployment
2312
+
2313
+ ### Future Vision
2314
+
2315
+ - **AI Pair Programmer**: Real-time coding assistant with full codebase context
2316
+ - **Autonomous Refactoring**: AI automatically refactors technical debt
2317
+ - **Predictive Analytics**: Predict bugs before they happen
2318
+ - **Architecture Governance**: Enforce architectural rules at commit time
2319
+ - **Cross-Project Intelligence**: Learn from multiple projects to improve recommendations
2320
+
2321
+ ---
2322
+
2323
+ ## 📄 License
2324
+
2325
+ MIT License
2326
+
2327
+ Copyright (c) 2026 ArchiCore
2328
+
2329
+ Permission is hereby granted, free of charge, to any person obtaining a copy
2330
+ of this software and associated documentation files (the "Software"), to deal
2331
+ in the Software without restriction, including without limitation the rights
2332
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2333
+ copies of the Software, and to permit persons to whom the Software is
2334
+ furnished to do so, subject to the following conditions:
2335
+
2336
+ The above copyright notice and this permission notice shall be included in all
2337
+ copies or substantial portions of the Software.
2338
+
2339
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2340
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2341
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2342
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2343
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2344
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2345
+ SOFTWARE.
497
2346
 
498
- ### Этап 1 (2-3 недели)
499
- - ✅ Индексация кода (AST + граф)
500
- - ✅ Семантическая память (векторная БД)
501
- - ✅ Анализ влияния изменений (read-only)
2347
+ ---
502
2348
 
503
- ### Этап 2 (1-2 недели)
504
- - ⏳ PR-анализ
505
- - ⏳ Автоматические подсказки
506
- - ⏳ Интеграция с IDE
2349
+ ## 🤝 Support
507
2350
 
508
- ### Этап 3 (2-3 недели)
509
- - Микро-рефакторинг
510
- - Автоматическая документация
511
- - Continuous learning
2351
+ - **Documentation**: https://docs.archicore.io
2352
+ - **Email**: support@archicore.io
2353
+ - **GitHub Issues**: https://github.com/yourusername/archicore/issues
2354
+ - **Twitter**: [@archicore_ai](https://twitter.com/archicore_ai)
2355
+ - **Discord**: https://discord.gg/archicore (coming soon)
512
2356
 
513
- ## Технологический стек
2357
+ ---
514
2358
 
515
- - **Языки**: TypeScript
516
- - **AST**: Tree-sitter (TypeScript, JavaScript, Python)
517
- - **Vector DB**: Qdrant
518
- - **LLM**: Anthropic Claude, OpenAI GPT
519
- - **Database**: PostgreSQL (опционально)
520
- - **CLI**: Commander.js
521
- - **Logging**: Custom logger with Chalk
2359
+ ## 🙏 Acknowledgments
522
2360
 
523
- ## Производительность
2361
+ - **Tree-sitter** - Parsing framework
2362
+ - **Qdrant** - Vector database
2363
+ - **Anthropic** - Claude AI
2364
+ - **Jina AI** - Code embeddings
2365
+ - **PostgreSQL** - Reliable database
2366
+ - **Redis** - Fast caching
2367
+ - **Express.js** - Web framework
2368
+ - **Docker** - Containerization
2369
+ - **All contributors** who helped make ArchiCore better!
2370
+
2371
+ ---
2372
+
2373
+ <div align="center">
524
2374
 
525
- - Индексация 1000 файлов: ~30 секунд
526
- - Анализ влияния: ~2-5 секунд
527
- - Семантический поиск: ~100ms
528
- - LLM запрос: ~2-10 секунд (зависит от модели)
2375
+ **[⬆ Back to Top](#archicore---ai-software-architect)**
529
2376
 
2377
+ Made with ❤️ by the ArchiCore Team
530
2378
 
2379
+ </div>