@itphx/synth-backend 0.11.3 → 0.12.4

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.
@@ -3,10 +3,14 @@
3
3
  // определяет приоритеты маршрутов (статические сегменты раньше параметрических,
4
4
  // SSE-хаб `/api/v2/events` после роутов событий, но до admin-роутов).
5
5
  // Вынесено из `app.ts` (ADR-095, шаг 4b) — «вынос по швам», без изменения поведения.
6
- import { isAbsolute, normalize, resolve } from 'node:path';
6
+ import { isAbsolute, join, normalize, resolve } from 'node:path';
7
+ import { randomUUID } from 'node:crypto';
7
8
  import { DEFAULT_LLM_GATEWAY_RATE_LIMIT, ProjectRole, SYNTH_VERSION, resolveSecretKey, resolveStorageBackend, resolvePostgresConfig, resolvePostgresPassword } from '@itphx/synth-shared';
8
- import { DEFAULT_AGENT_ID, RateLimiter, getPublicOpenApiDocument, createFsRoutes, createGitRoutes, createSshKeyRoutes, createAgentSshKeyRoutes, createEventRoutes, createSchedulerRoutes, createServiceKeyRoutes, createWebhookRoutes, mergeLlmGatewayConfig, mergeSecurityConfig, createSkillRoutes, createCommandRoutes, createSkillBundleRoutes, createSessionSkillScopeRoutes, createProjectSkillScopeRoutes, createSkillSettingsRoutes, createIdentityRoutes, createMaintenanceRoutes, createAnalyticsRoutes, AnalyticsService, createProjectPortableRoutes, createStorageContextAsync, ProjectInstructionsResolver, createInstructionsInfoResolver, createSettingsRoutes, createDictionaryRoutes, createAuditRoutes as createSecurityAuditRoutes, currentEgressLog, createContextRoutes as createCoreContextRoutes, createMetricsSettingsRoutes, resolveProjectWorkspace, } from '@itphx/synth-core';
9
+ import { DEFAULT_AGENT_ID, RateLimiter, getPublicOpenApiDocument, createFsRoutes, createGitRoutes, createSshKeyRoutes, createAgentSshKeyRoutes, createEventRoutes, createSchedulerRoutes, createServiceKeyRoutes, createWebhookRoutes, mergeLlmGatewayConfig, mergeSecurityConfig, mergePluginsConfig, createSkillRoutes, createCommandRoutes, createSkillBundleRoutes, createSessionSkillScopeRoutes, createProjectSkillScopeRoutes, createSkillSettingsRoutes, createIdentityRoutes, createMaintenanceRoutes, createAnalyticsRoutes, AnalyticsService, createProjectPortableRoutes, createStorageContextAsync, ProjectInstructionsResolver, createInstructionsInfoResolver, createSettingsRoutes, createDictionaryRoutes, createAuditRoutes as createSecurityAuditRoutes, currentEgressLog, createContextRoutes as createCoreContextRoutes, createMetricsSettingsRoutes,
10
+ // ADR-115: админ-раздел «Вложения» — runtime-настройки мультимодального ввода.
11
+ createAttachmentsSettingsRoutes, createModalityModelLookup, createStagingAttachmentRoutes, AttachmentService, createPacksRoutes, createPipelinesRoutes, createPipelineProjectRoutes, createProcessRoutes, createPluginsRoutes, createPluginSettingsRoutes, createMemoryRoutes, MEMORY_PLUGIN_NAME, MemoryProviderUnavailableError, executeToolDef, createOAuthRoutes, bindCredentialToConnector, syncMcpManagerFromRegistry, resolveProjectWorkspace, resolvePluginServerPolicy, } from '@itphx/synth-core';
9
12
  import { createProjectRoutes, createProjectAccess } from '../routes/projects.js';
13
+ import { createBackendProcessAccess } from '../routes/processes.js';
10
14
  import { createSessionRoutes } from '../routes/sessions.js';
11
15
  import { createMessageRoutes } from '../routes/messages.js';
12
16
  import { createQueueRoutes } from '../routes/queue.js';
@@ -23,7 +27,7 @@ import { createGatewayPatternsRoutes } from '../routes/gateway-patterns.js';
23
27
  import { createLlmRoutes } from '../routes/llm.js';
24
28
  import { createRateLimiter } from '../middleware/rate-limiter.js';
25
29
  import { scopeGuard, serviceProjectProjection } from '../auth/service-scope.js';
26
- import { requireAdminOrScope } from '../auth/guards.js';
30
+ import { requireAdminOrScope, requireAdminRoleOrScope } from '../auth/guards.js';
27
31
  import { t, getTranslations } from '../lib/i18n.js';
28
32
  import { registerEventsSse } from './sse-events.js';
29
33
  /**
@@ -32,7 +36,7 @@ import { registerEventsSse } from './sse-events.js';
32
36
  */
33
37
  export function mountBackendRoutes(app, auth, ctx) {
34
38
  const { config, deps } = ctx;
35
- const { dataDir, projectStore, sessionManager, eventBus, queueManager, processMessage, orchestrator, profilesStore, getDefaultAgentId, requestSessionService, contextOptimizer, protectedPathsStore, providerStore, providerCache, modelStore, modelCache, agentStore, agentRegistry, contextConfig, sshKeyStore, commandService, bundleStore, dictionaries, serviceApiKeyStore, eventIngress, eventBindingStore, eventJournal, routeRuleStore, eventApiKeyStore, schedulerService, scheduleStore, jobStore, webhookStore, webhookDeliveryStore, webhookService, webhooksConfig, eventHub, mcpManager, mcpRegistryStore, skillService, settingsStore, egressResolver, securityAudit, egressRequests, defaultWorkingDir, patternStore, toolRegistry, gatewayAuditLogger, gatewayPayloadLogPath, gatewayConfig, providerLoader, modelLoader, modelWindowLoader, resolveAgentTemplate, identityClaimStore, live, maintenanceAudit, analyticsRollups, analytics, metrics, } = deps;
39
+ const { dataDir, projectStore, sessionManager, eventBus, queueManager, processMessage, orchestrator, profilesStore, getDefaultAgentId, requestSessionService, contextOptimizer, protectedPathsStore, providerStore, providerCache, modelStore, modelCache, agentStore, agentRegistry, contextConfig, sshKeyStore, commandService, bundleStore, dictionaries, serviceApiKeyStore, eventIngress, eventBindingStore, eventJournal, routeRuleStore, eventApiKeyStore, schedulerService, scheduleStore, jobStore, webhookStore, webhookDeliveryStore, webhookService, webhooksConfig, eventHub, mcpManager, mcpRegistryStore, skillService, settingsStore, egressResolver, securityAudit, egressRequests, defaultWorkingDir, patternStore, toolRegistry, gatewayAuditLogger, gatewayPayloadLogPath, gatewayConfig, providerLoader, modelLoader, modelWindowLoader, resolveAgentTemplate, identityClaimStore, live, maintenanceAudit, analyticsRollups, analytics, metrics, pipelines, packs, } = deps;
36
40
  /**
37
41
  * Fallback-пара «модель по умолчанию» из config (`llm.defaultProvider` +
38
42
  * `llm.defaultModel`) — только если заданы оба.
@@ -54,7 +58,7 @@ export function mountBackendRoutes(app, auth, ctx) {
54
58
  // публичную выдачу без auth согласуем отдельно.
55
59
  app.get('/api/v2/openapi.json', auth.requireAuth, (c) => c.json(getPublicOpenApiDocument()));
56
60
  // Projects routes
57
- app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore));
61
+ app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore, deps.worktreeService));
58
62
  // ADR-091 (этап 2): портативный экспорт/импорт проекта (скачать/загрузить архив).
59
63
  // Managed RBAC: скачивание — право чтения проекта (owner/участник/LEAD/ADMIN),
60
64
  // импорт в существующий проект (`mergeInto`) — право редактирования; создание
@@ -63,7 +67,7 @@ export function mountBackendRoutes(app, auth, ctx) {
63
67
  // (ADR-089, инвариант 18).
64
68
  app.route('/api/v2/projects', createProjectPortableRoutes({ requireAuth: auth.requireAuth }, {
65
69
  dataDir,
66
- // PROP-032: экспорт/импорт проекта работают через контекст хранения
70
+ // ADR-096: экспорт/импорт проекта работают через контекст хранения
67
71
  // инстанса (иначе — свой файловый контекст, а на `backend=postgres`
68
72
  // проект не найден бы).
69
73
  storage: deps.storageContext,
@@ -109,9 +113,29 @@ export function mountBackendRoutes(app, auth, ctx) {
109
113
  },
110
114
  }));
111
115
  // Sessions routes
112
- app.route('/api/v2/sessions', createSessionRoutes(auth, sessionManager, eventBus, queueManager, processMessage, orchestrator, eventHub, contextOptimizer, projectStore, profilesStore, getDefaultAgentId, requestSessionService, analytics));
116
+ app.route('/api/v2/sessions', createSessionRoutes(auth, sessionManager, eventBus, queueManager, processMessage, orchestrator, eventHub, contextOptimizer, projectStore, profilesStore, getDefaultAgentId, requestSessionService, analytics,
117
+ // ADR-107: агрегаты памяти сессии для вкладки «Память».
118
+ {
119
+ facts: deps.storageContext.memoryFacts,
120
+ indexes: deps.storageContext.memoryIndexes,
121
+ isPluginActive: () => deps.pluginRuntime.host.isActive(MEMORY_PLUGIN_NAME),
122
+ },
123
+ // Этап 1 roadmap 0.13 (блок 3): сервис «вопрос пользователю» (`ask_user`).
124
+ deps.questionService,
125
+ // ADR-114: сервис worktree'ов — привязка сессии к worktree
126
+ // (`PATCH /api/v2/sessions/:id { worktreeId }`).
127
+ deps.worktreeService,
128
+ // ADR-115: вложения сообщений — blob-порт, учёт ссылок; лимиты читаются
129
+ // резолвером на каждый запрос (runtime-настройки из админки без рестарта).
130
+ {
131
+ blobs: deps.storageContext.blobs,
132
+ blobRefs: deps.storageContext.blobRefs,
133
+ config: () => deps.attachmentsSettings.getConfig(),
134
+ }));
113
135
  // Messages routes
114
- app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus, projectStore));
136
+ app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus, projectStore,
137
+ // ADR-115: удаление сообщения снимает ссылки на объекты вложений.
138
+ deps.storageContext.blobRefs));
115
139
  // Queue routes
116
140
  app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage, projectStore));
117
141
  // FS routes (ADR-075): core-фабрика, managed поверх workspace проекта.
@@ -153,7 +177,9 @@ export function mountBackendRoutes(app, auth, ctx) {
153
177
  setDefaultModel: (pair) => settingsStore.setDefaultModel(pair),
154
178
  }));
155
179
  // Agents routes
156
- app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId));
180
+ // ADR-046/ADR-089: ролевой промпт агента (`role_prompt` в теле POST)
181
+ // пишется портом файлов контекста — `{dataDir}/context/roles/<contextFile>`.
182
+ app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId, contextConfig));
157
183
  // Context routes (глобальные identity-файлы; админ-мутации)
158
184
  app.route('/api/v2/context', createContextFileRoutes(auth, contextConfig));
159
185
  // User admin routes
@@ -166,6 +192,7 @@ export function mountBackendRoutes(app, auth, ctx) {
166
192
  // читал бы git-данные чужого проекта по его id.
167
193
  app.route('/api/v2/git', createGitRoutes(auth, projectStore, config.workspacesRoot, {
168
194
  sshKeyStore,
195
+ execution: deps.executionPort,
169
196
  authorizeProject: async (c, projectId) => {
170
197
  const user = await auth.getCurrentUser(c);
171
198
  if (!user)
@@ -253,6 +280,279 @@ export function mountBackendRoutes(app, auth, ctx) {
253
280
  serviceProjectProjection,
254
281
  resolveSessionProject: async (id) => (await sessionManager.getSession(id))?.projectId,
255
282
  }));
283
+ // ADR-051/ADR-100: API пайплайнов — определения (ставит установщик пакета),
284
+ // экземпляры и ручной запуск. Чтение — ADMIN (реестр автоматов инстанса),
285
+ // ручной запуск — ADMIN или service-key со scope `automation:install`.
286
+ app.route('/api/v2/pipelines', createPipelinesRoutes({ requireAuth: auth.requireAuth }, { pipelines }, {
287
+ readGuard: auth.requirePermission('ADMIN'),
288
+ writeGuard: requireAdminRoleOrScope('automation:install'),
289
+ scopeGuard,
290
+ }));
291
+ // ADR-101 (Э6): пайплайны проекта (черновик/публикация), прогоны и журнал,
292
+ // HITL-действия и шаблоны инстанса (инстанцирование в проект).
293
+ // Права — по правилам проекта (ADR-089 §5.5/§5.8): читать — владелец/
294
+ // участник/LEAD/ADMIN, изменять — OWNER/EDITOR/LEAD/ADMIN (VIEWER читает,
295
+ // но не мутирует — инвариант 21). Шаблоны инстанса — ADMIN.
296
+ app.route('/api/v2', createPipelineProjectRoutes({ requireAuth: auth.requireAuth }, {
297
+ pipelines: deps.storageContext.projectPipelines,
298
+ runs: deps.storageContext.pipelineRuns,
299
+ engine: deps.pipelineEngine,
300
+ projects: projectStore,
301
+ templates: pipelines,
302
+ // ADR-101: общий реестр активных прогонов (soft-lock + отмена) —
303
+ // тот же экземпляр, что у встроенных тулов агента.
304
+ runControl: deps.pipelineRunControl,
305
+ // ADR-116: раздача артефактов прогона (blob-порт) — тот же store, что у
306
+ // выхода `file` движка пайплайнов (без него route всегда 404).
307
+ artifacts: deps.pipelineArtifacts,
308
+ // ADR-115 × ADR-101: вложения прогона — проверка ссылок в теле запуска
309
+ // (тот же сервис вложений, что у приёма событий) и учёт в `blob_refs`.
310
+ attachments: deps.pipelineAttachments,
311
+ blobRefs: deps.storageContext.blobRefs,
312
+ }, {
313
+ writeGuard: auth.requireAuth,
314
+ adminGuard: auth.requirePermission('ADMIN'),
315
+ canReadProject: async (c, project, userId) => projectAccess.canReadProject(c, project, userId),
316
+ canEditProject: async (c, project, userId) => projectAccess.canEditProjectContent(c, project, userId),
317
+ getCurrentUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
318
+ scopeGuard,
319
+ serviceProjectProjection,
320
+ messages: {
321
+ pipelineNotFound: (c) => t('errors.notFound.pipeline', undefined, c),
322
+ runNotFound: (c) => t('errors.notFound.pipelineRun', undefined, c),
323
+ projectNotFound: (c) => t('errors.notFound.project', undefined, c),
324
+ templateNotFound: (c) => t('errors.notFound.pipelineTemplate', undefined, c),
325
+ forbidden: (c) => t('auth.forbidden', undefined, c),
326
+ invalidBody: (c) => t('errors.validation.invalidPipelineBody', undefined, c),
327
+ invalidSpec: (c) => t('errors.validation.invalidPipelineSpec', undefined, c),
328
+ notPublished: (c) => t('errors.conflict.pipelineNotPublished', undefined, c),
329
+ invalidState: (c) => t('errors.conflict.pipelineInvalidState', undefined, c),
330
+ nothingToPublish: (c) => t('errors.conflict.pipelineNothingToPublish', undefined, c),
331
+ runFinished: (c) => t('errors.conflict.pipelineRunFinished', undefined, c),
332
+ templateNotInstantiable: (c) => t('errors.conflict.pipelineTemplateUnsupported', undefined, c),
333
+ projectIdRequired: (c) => t('errors.validation.projectIdRequired', undefined, c),
334
+ },
335
+ }));
336
+ // PROP-096/097: HTTP-контур единого реестра фоновых прогонов (список,
337
+ // деталь, лог, остановка, удаление). Право на прогон — право на его
338
+ // сессию-владельца: владелец|ADMIN, участник проекта (read — любая роль,
339
+ // write — OWNER/EDITOR/LEAD/ADMIN; `VIEWER` читает, но не мутирует —
340
+ // инвариант 21). Проверка — граничный guard core-фабрики (инвариант 16),
341
+ // в обработчиках проверок нет. Сервисы фоновой работы в деградированном
342
+ // режиме хранилища не создаются — тогда контура нет.
343
+ if (deps.backgroundService && deps.processService) {
344
+ app.route('/api/v2/processes', createProcessRoutes({ requireAuth: auth.requireAuth }, {
345
+ backgroundRuns: deps.storageContext.backgroundRuns,
346
+ background: deps.backgroundService,
347
+ processes: deps.processService,
348
+ sessionManager,
349
+ }, {
350
+ isAllowed: createBackendProcessAccess({ auth, projectStore }),
351
+ resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
352
+ messages: {
353
+ runNotFound: (c) => t('errors.notFound.backgroundRun', undefined, c),
354
+ sessionNotFound: (c) => t('errors.notFound.backgroundRunSession', undefined, c),
355
+ forbidden: (c) => t('auth.forbidden', undefined, c),
356
+ invalidQuery: (c) => t('errors.validation.invalidBackgroundRunQuery', undefined, c),
357
+ invalidKind: (c) => t('errors.validation.backgroundRunLogKind', undefined, c),
358
+ logNotFound: (c) => t('errors.notFound.processLog', undefined, c),
359
+ alreadyFinished: (c) => t('errors.conflict.backgroundRunFinished', undefined, c),
360
+ notStoppable: (c) => t('errors.conflict.backgroundRunNotStoppable', undefined, c),
361
+ runActive: (c) => t('errors.conflict.backgroundRunActive', undefined, c),
362
+ },
363
+ }));
364
+ }
365
+ // ADR-086 §5: установка пакетов расширений (скиллы/MCP/агенты/пайплайны) и
366
+ // реестр установок. Managed RBAC: установка — ADMIN или service-key со
367
+ // scope `automation:install`; одобрение и снятие — **только ADMIN** (снимают
368
+ // чужие артефакты инстанса).
369
+ app.route('/api/v2/packs', createPacksRoutes({ requireAuth: auth.requireAuth }, {
370
+ packs,
371
+ pipelines,
372
+ skills: skillService,
373
+ mcpRegistry: mcpRegistryStore,
374
+ agents: agentStore,
375
+ roleFiles: contextConfig,
376
+ routes: routeRuleStore,
377
+ // ADR-106 Ф5: контент полномочий пакета активируется в политике
378
+ // инстанса при одобрении и снимается при снятии установки.
379
+ authorityPolicy: deps.storageContext.authorityPolicy,
380
+ registerAgent: (agent) => agentRegistry.register(agent),
381
+ unregisterAgent: (id) => agentRegistry.unregister(id),
382
+ resolveUserId: (c) => {
383
+ const user = c.get('user');
384
+ return user?.id;
385
+ },
386
+ }, {
387
+ readGuard: auth.requirePermission('ADMIN'),
388
+ writeGuard: requireAdminRoleOrScope('automation:install'),
389
+ approveGuard: auth.requirePermission('ADMIN'),
390
+ uninstallGuard: auth.requirePermission('ADMIN'),
391
+ scopeGuard,
392
+ }));
393
+ // ADR-090 (Ф5б-2): управление плагинами инстанса. Managed RBAC:
394
+ // чтение — ADMIN (реестр инстанса), установка/активация/деактивация —
395
+ // ADMIN или service-key со scope `addons:install` (установка аддонов —
396
+ // зонтичный scope реестра расширений), подтверждение карантина и снятие —
397
+ // **только ADMIN** (снятие гасит код в процессе ядра). Установка из
398
+ // локального каталога/архива запрещена (`localInstall: false` → 403
399
+ // `LOCAL_INSTALL_DISABLED`): путь с ФС хоста в managed не принимается.
400
+ // Сетевые источники (`npm`/`url`) разрешены — это не локальный путь, а
401
+ // доставка бандла с проверкой целостности (SRI/sha256).
402
+ app.route('/api/v2/plugins', createPluginsRoutes({ requireAuth: auth.requireAuth }, {
403
+ runtime: deps.pluginRuntime,
404
+ config: mergePluginsConfig(config.synth.plugins, {}),
405
+ settings: settingsStore,
406
+ localInstall: false,
407
+ // Ф7 (ADR-090): реестр service-key — для выдачи server-scoped токена
408
+ // плагину (`POST /api/v2/plugins/token`).
409
+ serviceKeys: serviceApiKeyStore,
410
+ // Ф7: серверная политика (allow-list) из работающего рантайма.
411
+ serverPolicy: () => resolvePluginServerPolicy(deps.pluginRuntime.config),
412
+ resolveUserId: (c) => {
413
+ const user = c.get('user');
414
+ return user?.id;
415
+ },
416
+ }, {
417
+ readGuard: auth.requirePermission('ADMIN'),
418
+ writeGuard: requireAdminRoleOrScope('addons:install'),
419
+ approveGuard: auth.requirePermission('ADMIN'),
420
+ uninstallGuard: auth.requirePermission('ADMIN'),
421
+ // Ф7 (Уровень 2): выдача server-scoped токена — только ADMIN (токен даёт
422
+ // плагину машинный доступ к серверу).
423
+ tokenGuard: auth.requirePermission('ADMIN'),
424
+ }));
425
+ // ADR-090 (Ф5б-2): runtime-настройки слоя плагинов. Managed RBAC —
426
+ // ADMIN (чтение и запись): политика доверия/скана/исполнения — инстанс-уровневая.
427
+ // `restartRequired` — всегда true (рантайм собирается при старте, инвариант 24).
428
+ app.route('/api/v2/settings', createPluginSettingsRoutes({ requireAuth: auth.requireAuth }, {
429
+ config: mergePluginsConfig(config.synth.plugins, {}),
430
+ settings: settingsStore,
431
+ running: deps.pluginRuntime.config,
432
+ // Долги Д3: бюджеты (`promptBlockMaxChars`, `llmFilterTimeoutMs`) —
433
+ // живые; остальные ключи — после рестарта (инвариант 24).
434
+ onPluginsChange: (effective) => {
435
+ deps.orchestrator.setPromptBlockMaxChars(effective.promptBlockMaxChars);
436
+ deps.orchestrator.setLlmFilterTimeoutMs(effective.llmFilterTimeoutMs);
437
+ },
438
+ }, {
439
+ readGuard: auth.requirePermission('ADMIN'),
440
+ writeGuard: auth.requirePermission('ADMIN'),
441
+ }));
442
+ // ADR-115: админ-раздел «Вложения» — runtime-настройки мультимодального
443
+ // ввода. Managed RBAC — **ADMIN** (чтение и запись): мастер-выключатель,
444
+ // семейства MIME и лимиты — политика инстанса. Применяется сразу
445
+ // (`restartRequired: false`): сервис вложений, промпт и GC читают резолвер
446
+ // на каждый вызов.
447
+ app.route('/api/v2/settings', createAttachmentsSettingsRoutes({ requireAuth: auth.requireAuth }, {
448
+ settingsStore,
449
+ config: config.synth.attachments,
450
+ live: deps.attachmentsSettings,
451
+ securityAudit,
452
+ env: process.env,
453
+ // ADR-115: проверка `modalityModels` по каталогу (провайдер + модель +
454
+ // модальности модели) — до записи runtime-патча.
455
+ lookupModel: createModalityModelLookup({ providers: providerStore, models: modelStore }),
456
+ }, {
457
+ readGuard: auth.requirePermission('ADMIN'),
458
+ writeGuard: auth.requirePermission('ADMIN'),
459
+ }));
460
+ // ADR-115: staging-загрузка без сессии — `POST /api/v2/attachments`
461
+ // (шлюзы принимают файл из внешнего канала, пайплайны — из шага). Managed:
462
+ // `requireAuth` + scope-гейт service-key `events:ingest` (у шлюзов он уже
463
+ // есть; для интерактивных кред — no-op). Объект не привязан к сессии: без
464
+ // ссылки `blob_refs` живёт `attachments.gcDays` до GC.
465
+ app.route('/api/v2/attachments', createStagingAttachmentRoutes({ requireAuth: auth.requireAuth, getCurrentUser: auth.getCurrentUser }, {
466
+ service: new AttachmentService({
467
+ blobs: deps.storageContext.blobs,
468
+ config: () => deps.attachmentsSettings.getConfig(),
469
+ }),
470
+ config: () => deps.attachmentsSettings.getConfig(),
471
+ }, { guard: scopeGuard('events:ingest') }));
472
+ // ADR-107 / PROP-047 §2.1: портал памяти в ядре — чтение фактов и индексов
473
+ // через доменные порты памяти. Managed RBAC: **только ADMIN** — портал
474
+ // админский (данные памяти видны целиком, без проектной проекции).
475
+ // Namespace плагина памяти подставляет сервер — клиент его не задаёт.
476
+ app.route('/api/v2/memory', createMemoryRoutes({ requireAuth: auth.requireAuth }, {
477
+ memory: {
478
+ facts: deps.storageContext.memoryFacts,
479
+ indexes: deps.storageContext.memoryIndexes,
480
+ },
481
+ guard: auth.requirePermission('ADMIN'),
482
+ // Проектная авторизация (инвариант 16, ADR-089 §5.8): проверка прав на
483
+ // границе — до обращения к порту/тулу. `read` — право чтения проекта
484
+ // (владелец/участник/`LEAD`/`ADMIN`), `write` — право изменения
485
+ // содержимого (владелец/`EDITOR`/`LEAD`/`ADMIN`; `VIEWER` только
486
+ // читает, инвариант 21). Нет проекта/прав → отказ (fail-closed).
487
+ authorizeProject: async (c, projectId, mode) => {
488
+ const user = await auth.getCurrentUser(c);
489
+ if (!user)
490
+ return false;
491
+ const project = await projectStore.load(projectId);
492
+ if (!project)
493
+ return false;
494
+ return mode === 'read'
495
+ ? projectAccess.canReadProject(c, project, user.id)
496
+ : projectAccess.canEditProjectContent(c, project, user.id);
497
+ },
498
+ // Активен ли плагин памяти в процессе — реестр активаций хоста (ADR-090).
499
+ isPluginActive: () => deps.pluginRuntime.host.isActive(MEMORY_PLUGIN_NAME),
500
+ // М2: мутации индексов — через админ-тул плагина памяти (реестр тулов).
501
+ // Контекст вызова (sessionId/messageId) создаёт вызывающая сторона:
502
+ // сессии у портала нет — это служебный вызов инстанса.
503
+ invokeTool: async ({ tool, params, projectId, workingDir }) => {
504
+ const def = toolRegistry.get(tool);
505
+ if (!def)
506
+ throw new MemoryProviderUnavailableError(tool);
507
+ return executeToolDef(def, params, {
508
+ sessionId: `system:memory-portal:${randomUUID()}`,
509
+ messageId: `system:memory-portal:${randomUUID()}`,
510
+ workingDir,
511
+ ...(projectId ? { projectId } : {}),
512
+ }, tool);
513
+ },
514
+ // Проект и его workspace (ADR-075): относительный workspace резолвится
515
+ // от `workspacesRoot`, абсолютный — как есть.
516
+ resolveProject: async (projectId) => {
517
+ const project = await deps.storageContext.projects.load(projectId);
518
+ if (!project)
519
+ return null;
520
+ if (!project.workspace)
521
+ return { id: project.id };
522
+ const root = config.workspacesRoot ?? join(dataDir, 'workspaces');
523
+ const workspace = isAbsolute(project.workspace)
524
+ ? normalize(project.workspace)
525
+ : resolve(root, project.workspace);
526
+ return { id: project.id, workspace };
527
+ },
528
+ // Каталог данных — рабочий каталог для источника `facts` (нет workspace).
529
+ dataDir,
530
+ messages: {
531
+ invalidStatus: (c) => t('errors.validation.invalidMemoryStatus', undefined, c),
532
+ invalidState: (c) => t('errors.validation.invalidMemoryState', undefined, c),
533
+ invalidLimit: (c) => t('errors.validation.invalidMemoryLimit', undefined, c),
534
+ invalidOffset: (c) => t('errors.validation.invalidMemoryOffset', undefined, c),
535
+ factNotFound: (c) => t('errors.notFound.memoryFact', undefined, c),
536
+ unavailable: (c) => t('errors.unavailable.memory', undefined, c),
537
+ invalidBody: (c) => t('errors.validation.invalidMemoryBody', undefined, c),
538
+ invalidSource: (c) => t('errors.validation.invalidMemorySource', undefined, c),
539
+ projectRequired: (c) => t('errors.validation.memoryProjectRequired', undefined, c),
540
+ projectNotFound: (c) => t('errors.notFound.memoryProject', undefined, c),
541
+ workspaceRequired: (c) => t('errors.validation.memoryWorkspaceRequired', undefined, c),
542
+ providerUnavailable: (c) => t('errors.unavailable.memoryProvider', undefined, c),
543
+ indexNotFound: (c) => t('errors.notFound.memoryIndex', undefined, c),
544
+ indexFailed: (c) => t('errors.failed.memoryIndex', undefined, c),
545
+ indexCreated: (c) => t('memory.indexCreated', undefined, c),
546
+ invalidThreshold: (c) => t('errors.validation.invalidMemoryThreshold', undefined, c),
547
+ consolidationFailed: (c) => t('errors.failed.memoryConsolidation', undefined, c),
548
+ consolidated: (c) => t('memory.consolidated', undefined, c),
549
+ invalidGraphDepth: (c) => t('errors.validation.invalidMemoryGraphDepth', undefined, c),
550
+ invalidGraphLimit: (c) => t('errors.validation.invalidMemoryGraphLimit', undefined, c),
551
+ invalidGraphEntity: (c) => t('errors.validation.invalidMemoryGraphEntity', undefined, c),
552
+ graphFailed: (c) => t('errors.failed.memoryGraph', undefined, c),
553
+ forbidden: (c) => t('auth.forbidden', undefined, c),
554
+ },
555
+ }));
256
556
  // ADR-052 (этап I): CRUD service-key инстанса (`synth_svc_…`). Managed RBAC:
257
557
  // только ADMIN (ключи дают машинный доступ — управление админское), i18n.
258
558
  app.route('/api/v2/service-keys', createServiceKeyRoutes({ requireAuth: auth.requireAuth }, { store: serviceApiKeyStore }, {
@@ -293,7 +593,7 @@ export function mountBackendRoutes(app, auth, ctx) {
293
593
  // ADR-091/ADR-092: обслуживание инстанса (backup/restore/doctor/migrate).
294
594
  // Managed RBAC: только ADMIN — операции меняют/отдают данные всего инстанса
295
595
  // (архивы могут содержать секреты), i18n.
296
- // PROP-032: при backend=postgres doctor/migrations ходят в БД через read-only
596
+ // ADR-097: при backend=postgres doctor/migrations ходят в БД через read-only
297
597
  // пробу (контекст в режиме `skip` — миграции не применяются).
298
598
  const maintenanceBackend = resolveStorageBackend(config.synth, process.env);
299
599
  const withPostgresContext = maintenanceBackend === 'postgres'
@@ -353,6 +653,67 @@ export function mountBackendRoutes(app, auth, ctx) {
353
653
  registry: mcpRegistryStore,
354
654
  // Политика резолвится на каждый запрос (live; исключения/режим — из стора).
355
655
  getNetworkPolicy: () => egressResolver.resolveMcp(),
656
+ // ADR-105 (Ф3): порт слоя внешних доступов — право привязать доступ
657
+ // к коннектору проверяется на границе (инвариант 16).
658
+ credentials: deps.storageContext.externalCredentials,
659
+ // ADR-105 (Ф3): проектный доступ привязывает участник проекта с правом
660
+ // изменения содержимого (OWNER/EDITOR + LEAD/ADMIN; VIEWER — нет).
661
+ canEditProject: async (c, projectId) => {
662
+ const user = c.get('user');
663
+ if (!user?.id)
664
+ return false;
665
+ const project = await projectStore.load(projectId);
666
+ return project ? projectAccess.canEditProjectContent(c, project, user.id) : false;
667
+ },
668
+ }));
669
+ // ADR-105 (Ф4): HTTP-контур слоя внешних доступов. Managed RBAC:
670
+ // чтение — свои доступы (владелец/участник проекта), `ADMIN`/`LEAD` — все;
671
+ // мутации — владелец доступа (инстансные — `ADMIN`/`LEAD`); право
672
+ // распоряжения доступом проверяется на границе (инвариант 16).
673
+ app.route('/api/v2/oauth', createOAuthRoutes({ requireAuth: auth.requireAuth }, {
674
+ credentials: deps.storageContext.externalCredentials,
675
+ service: deps.oauthCredentialService,
676
+ providers: deps.oauthProviders,
677
+ // ADR-105 (Ф4): журнал операций со слоем доступов (привязка к коннектору).
678
+ audit: deps.storageContext.credentialAudit,
679
+ ownerKind: 'user',
680
+ resolveActor: (c) => {
681
+ const user = c.get('user');
682
+ return { userId: user?.id ?? '', roles: user?.roles ?? [] };
683
+ },
684
+ canReadProject: async (c, projectId) => {
685
+ const user = await auth.getCurrentUser(c);
686
+ if (!user)
687
+ return false;
688
+ const project = await projectStore.load(projectId);
689
+ return project ? projectAccess.canReadProject(c, project, user.id) : false;
690
+ },
691
+ canEditProject: async (c, projectId) => {
692
+ const user = await auth.getCurrentUser(c);
693
+ if (!user)
694
+ return false;
695
+ const project = await projectStore.load(projectId);
696
+ return project ? projectAccess.canEditProjectContent(c, project, user.id) : false;
697
+ },
698
+ bindConnector: async ({ connectorId, credentialId, actor, c }) => {
699
+ await bindCredentialToConnector({
700
+ registry: deps.mcpRegistryStore,
701
+ connectorId,
702
+ credentialId,
703
+ // Запись реестра меняет автор записи или `ADMIN` (как в `mcp-registry`).
704
+ canModify: (entry) => {
705
+ const user = c.get('user');
706
+ if (auth.isAdmin(c))
707
+ return true;
708
+ if (entry.author?.userId && user?.id && entry.author.userId === user.id)
709
+ return true;
710
+ return actor.roles.includes('ADMIN') || actor.roles.includes('LEAD');
711
+ },
712
+ });
713
+ // Реестр — источник истины для конфигурации серверов (ADR-071 §2.5):
714
+ // без синхронизации менеджер остался бы со старым конфигом (без `auth`).
715
+ await syncMcpManagerFromRegistry(mcpManager, deps.mcpRegistryStore);
716
+ },
356
717
  }));
357
718
  // Скиллы (ADR-046 §9.1/§9.2): core-фабрика + RBAC ADMIN на запись.
358
719
  app.route('/api/v2/skills', createSkillRoutes(auth, {
@@ -639,7 +1000,7 @@ export function mountBackendRoutes(app, auth, ctx) {
639
1000
  }, {
640
1001
  readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
641
1002
  }));
642
- // PROP-102 (волна 1): отчёты аналитики — только чтение, данных без локализации.
1003
+ // ADR-102 (волна 1): отчёты аналитики — только чтение, данных без локализации.
643
1004
  // Managed RBAC (§7): ADMIN/LEAD — сквозной обзор; AUDITOR — чтение всех отчётов;
644
1005
  // обычный USER — принудительный фильтр оси `user` по себе (+ 403 на `decision`/`summary`).
645
1006
  app.route('/api/v2/analytics', createAnalyticsRoutes({ requireAuth: auth.requireAuth }, { service: new AnalyticsService({ repo: analyticsRollups }) }, {
@@ -671,6 +1032,8 @@ export function mountBackendRoutes(app, auth, ctx) {
671
1032
  trustedProjectDirs: config.synth.skills.trustedProjectDirs,
672
1033
  // ADR-069 R3: авто-trust workspace внутри workspacesRoot (managed-каталоги).
673
1034
  workspacesRoot: config.workspacesRoot,
1035
+ // ADR-077: `git rev-parse` — через порт исполнения (тот же, что у тулов).
1036
+ execution: deps.executionPort,
674
1037
  }), config.synth.instructions);
675
1038
  app.route('/api/v2/context', createCoreContextRoutes(auth, {
676
1039
  resolveInstructions: instructionsInfoResolver,
package/dist/app.d.ts CHANGED
@@ -2,7 +2,7 @@ import { createServer } from 'node:http';
2
2
  import { WebSocketServer } from 'ws';
3
3
  import { Hono } from 'hono';
4
4
  import { MetricsRegistry } from '@itphx/synth-core';
5
- import type { EventBus, SessionManager, QueueProcessorManager, ChatOrchestrator, ProjectRepository, SettingsRepository, EventRouter, RequestSessionService, EventBindingRepository, EventJournalRepository, EventIngress, ScheduleRepository, SchedulerService, WebhookRepository, WebhookService } from '@itphx/synth-core';
5
+ import type { EventBus, SessionManager, QueueProcessorManager, ChatOrchestrator, ProjectRepository, SettingsRepository, EventRouter, RequestSessionService, EventBindingRepository, EventJournalRepository, EventIngress, ScheduleRepository, SchedulerService, WebhookRepository, WebhookService, PluginRuntime, McpManager } from '@itphx/synth-core';
6
6
  import type { BackendConfig } from './lib/app-config.js';
7
7
  import type { AuthKit } from './auth/middleware.js';
8
8
  import type { EventHub } from './events/hub.js';
@@ -43,6 +43,16 @@ export interface BackendAppHandle {
43
43
  eventJournal: EventJournalRepository;
44
44
  /** ADR-089: ingress-точка приёма внешних событий. */
45
45
  ingress: EventIngress;
46
+ /**
47
+ * ADR-090 (Ф5б-1): рантайм плагинов — старт-активация установленного
48
+ * (`main.ts`) и точки для HTTP API/CLI (Ф5б-2/3).
49
+ */
50
+ pluginRuntime: PluginRuntime;
51
+ /**
52
+ * ADR-071 §2.5: менеджер MCP. Конфиг серверов приходит из единого реестра
53
+ * (в т.ч. после привязки внешнего доступа к коннектору, ADR-105 Ф4).
54
+ */
55
+ mcpManager: McpManager;
46
56
  scheduleStore: ScheduleRepository;
47
57
  scheduler: SchedulerService;
48
58
  /** ADR-051 (срез): остановка планировщика (на graceful shutdown). */
@@ -51,8 +61,24 @@ export interface BackendAppHandle {
51
61
  stopEphemeralSweeper: () => void;
52
62
  /** ADR-089: остановка периодической retention-очистки журнала событий. */
53
63
  stopEventJournalPruner: () => void;
54
- /** PROP-102: остановка retention-очистки суточных роллапов аналитики. */
64
+ /** ADR-102: остановка retention-очистки суточных роллапов аналитики. */
55
65
  stopAnalyticsRollupPruner: () => void;
66
+ /**
67
+ * Этап 1 roadmap 0.13 (блок 3): остановка retention-очистки вопросов и
68
+ * освобождение ожиданий ответа.
69
+ */
70
+ stopQuestionPruner: () => void;
71
+ /**
72
+ * Этап 1 roadmap 0.13 (блок 4): остановка retention-очистки реестра фоновых
73
+ * прогонов (PROP-096).
74
+ */
75
+ stopBackgroundRunPruner: () => void;
76
+ /**
77
+ * PROP-097 (блок 5b): остановка retention-очистки логов фоновых процессов.
78
+ */
79
+ stopProcessLogPruner: () => void;
80
+ /** ADR-115: остановка GC осиротевших вложений сообщений. */
81
+ stopAttachmentPruner: () => void;
56
82
  /** ADR-052 (этап II): реестр подписок webhooks (для тестов/диагностики). */
57
83
  webhookStore: WebhookRepository;
58
84
  /** ADR-052 (этап II): движок исходящих webhooks. */