@itphx/synth-storage-postgres 0.0.0-stage → 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.
- package/LICENSE +18 -0
- package/LICENSE.ru.md +31 -0
- package/dist/errors.d.ts +71 -0
- package/dist/errors.js +126 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.js +56 -0
- package/dist/json-param.d.ts +14 -0
- package/dist/json-param.js +22 -0
- package/dist/locks.d.ts +104 -0
- package/dist/locks.js +201 -0
- package/dist/migrate.d.ts +58 -0
- package/dist/migrate.js +125 -0
- package/dist/migrations/001-init.d.ts +15 -0
- package/dist/migrations/001-init.js +457 -0
- package/dist/migrations/002-egress-audit.d.ts +12 -0
- package/dist/migrations/002-egress-audit.js +52 -0
- package/dist/migrations/003-analytics-rollups.d.ts +12 -0
- package/dist/migrations/003-analytics-rollups.js +21 -0
- package/dist/migrations/004-pipeline-engine.d.ts +19 -0
- package/dist/migrations/004-pipeline-engine.js +74 -0
- package/dist/migrations/005-pipeline-provenance.d.ts +12 -0
- package/dist/migrations/005-pipeline-provenance.js +15 -0
- package/dist/migrations/006-plugin-audit.d.ts +13 -0
- package/dist/migrations/006-plugin-audit.js +34 -0
- package/dist/migrations/007-plugin-lock.d.ts +10 -0
- package/dist/migrations/007-plugin-lock.js +25 -0
- package/dist/migrations/008-plugin-audit-scan.d.ts +11 -0
- package/dist/migrations/008-plugin-audit-scan.js +15 -0
- package/dist/migrations/009-plugin-lock-previous.d.ts +13 -0
- package/dist/migrations/009-plugin-lock-previous.js +16 -0
- package/dist/migrations/010-plugin-lock-mode.d.ts +16 -0
- package/dist/migrations/010-plugin-lock-mode.js +20 -0
- package/dist/migrations/011-session-steer-inbox.d.ts +11 -0
- package/dist/migrations/011-session-steer-inbox.js +14 -0
- package/dist/migrations/012-external-credentials.d.ts +15 -0
- package/dist/migrations/012-external-credentials.js +40 -0
- package/dist/migrations/013-service-key-plugin-id.d.ts +17 -0
- package/dist/migrations/013-service-key-plugin-id.js +20 -0
- package/dist/migrations/014-session-mode-by-principal.d.ts +12 -0
- package/dist/migrations/014-session-mode-by-principal.js +15 -0
- package/dist/migrations/015-authority.d.ts +17 -0
- package/dist/migrations/015-authority.js +43 -0
- package/dist/migrations/016-credential-audit.d.ts +17 -0
- package/dist/migrations/016-credential-audit.js +32 -0
- package/dist/migrations/017-memory.d.ts +29 -0
- package/dist/migrations/017-memory.js +95 -0
- package/dist/migrations/018-memory-index-scope.d.ts +14 -0
- package/dist/migrations/018-memory-index-scope.js +18 -0
- package/dist/migrations/019-memory-index-enabled.d.ts +11 -0
- package/dist/migrations/019-memory-index-enabled.js +14 -0
- package/dist/migrations/020-project-memory.d.ts +11 -0
- package/dist/migrations/020-project-memory.js +13 -0
- package/dist/migrations/021-background-runs.d.ts +17 -0
- package/dist/migrations/021-background-runs.js +67 -0
- package/dist/migrations/022-background-run-process-id.d.ts +14 -0
- package/dist/migrations/022-background-run-process-id.js +18 -0
- package/dist/migrations/023-session-worktree.d.ts +12 -0
- package/dist/migrations/023-session-worktree.js +16 -0
- package/dist/migrations/024-blob-refs.d.ts +15 -0
- package/dist/migrations/024-blob-refs.js +26 -0
- package/dist/migrations/025-packs-pipelines.d.ts +28 -0
- package/dist/migrations/025-packs-pipelines.js +82 -0
- package/dist/migrations/026-instance-skills.d.ts +17 -0
- package/dist/migrations/026-instance-skills.js +25 -0
- package/dist/migrations/027-context-files.d.ts +20 -0
- package/dist/migrations/027-context-files.js +30 -0
- package/dist/migrations/index.d.ts +23 -0
- package/dist/migrations/index.js +71 -0
- package/dist/pool.d.ts +178 -0
- package/dist/pool.js +382 -0
- package/dist/ports/analytics.d.ts +26 -0
- package/dist/ports/analytics.js +243 -0
- package/dist/ports/audit.d.ts +15 -0
- package/dist/ports/audit.js +192 -0
- package/dist/ports/authority.d.ts +27 -0
- package/dist/ports/authority.js +148 -0
- package/dist/ports/background-runs.d.ts +41 -0
- package/dist/ports/background-runs.js +179 -0
- package/dist/ports/blob-refs.d.ts +36 -0
- package/dist/ports/blob-refs.js +55 -0
- package/dist/ports/content.d.ts +41 -0
- package/dist/ports/content.js +1553 -0
- package/dist/ports/context-files.d.ts +145 -0
- package/dist/ports/context-files.js +279 -0
- package/dist/ports/core-sync.d.ts +31 -0
- package/dist/ports/core-sync.js +34 -0
- package/dist/ports/credential-audit.d.ts +19 -0
- package/dist/ports/credential-audit.js +96 -0
- package/dist/ports/deps.d.ts +63 -0
- package/dist/ports/deps.js +19 -0
- package/dist/ports/events-bindings.d.ts +77 -0
- package/dist/ports/events-bindings.js +356 -0
- package/dist/ports/events-core.d.ts +35 -0
- package/dist/ports/events-core.js +71 -0
- package/dist/ports/events-journal.d.ts +68 -0
- package/dist/ports/events-journal.js +211 -0
- package/dist/ports/events-scheduler.d.ts +49 -0
- package/dist/ports/events-scheduler.js +231 -0
- package/dist/ports/events-webhooks.d.ts +64 -0
- package/dist/ports/events-webhooks.js +268 -0
- package/dist/ports/events.d.ts +20 -0
- package/dist/ports/events.js +27 -0
- package/dist/ports/external-credentials.d.ts +6 -0
- package/dist/ports/external-credentials.js +363 -0
- package/dist/ports/legacy-pipelines.d.ts +50 -0
- package/dist/ports/legacy-pipelines.js +202 -0
- package/dist/ports/memory.d.ts +65 -0
- package/dist/ports/memory.js +471 -0
- package/dist/ports/packs.d.ts +32 -0
- package/dist/ports/packs.js +117 -0
- package/dist/ports/pipelines.d.ts +67 -0
- package/dist/ports/pipelines.js +297 -0
- package/dist/ports/plugin-audit.d.ts +14 -0
- package/dist/ports/plugin-audit.js +110 -0
- package/dist/ports/plugin-lock.d.ts +27 -0
- package/dist/ports/plugin-lock.js +145 -0
- package/dist/ports/principals-defaults.d.ts +21 -0
- package/dist/ports/principals-defaults.js +68 -0
- package/dist/ports/principals-documents.d.ts +23 -0
- package/dist/ports/principals-documents.js +38 -0
- package/dist/ports/principals-profiles.d.ts +21 -0
- package/dist/ports/principals-profiles.js +263 -0
- package/dist/ports/principals-projects.d.ts +19 -0
- package/dist/ports/principals-projects.js +161 -0
- package/dist/ports/principals-settings.d.ts +25 -0
- package/dist/ports/principals-settings.js +295 -0
- package/dist/ports/principals-shared.d.ts +33 -0
- package/dist/ports/principals-shared.js +44 -0
- package/dist/ports/principals.d.ts +27 -0
- package/dist/ports/principals.js +39 -0
- package/dist/ports/questions.d.ts +40 -0
- package/dist/ports/questions.js +135 -0
- package/dist/ports/sessions-mapping.d.ts +254 -0
- package/dist/ports/sessions-mapping.js +449 -0
- package/dist/ports/sessions.d.ts +143 -0
- package/dist/ports/sessions.js +517 -0
- package/dist/ports/skills.d.ts +59 -0
- package/dist/ports/skills.js +205 -0
- package/dist/ports/stub.d.ts +14 -0
- package/dist/ports/stub.js +32 -0
- package/dist/ports/worktrees.d.ts +41 -0
- package/dist/ports/worktrees.js +85 -0
- package/dist/postgres-storage.d.ts +58 -0
- package/dist/postgres-storage.js +110 -0
- package/dist/schema.d.ts +13 -0
- package/dist/schema.js +22 -0
- package/dist/storage-context.d.ts +80 -0
- package/dist/storage-context.js +238 -0
- package/package.json +40 -3
- package/README.md +0 -3
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Сборка `StorageContext` PostgreSQL-драйвера (ADR-097, волна 3b-каркас).
|
|
3
|
+
*
|
|
4
|
+
* Контекст собирается из независимых файлов-групп портов
|
|
5
|
+
* (`src/ports/{sessions,principals,events,content,audit,analytics}.ts`) — по одной
|
|
6
|
+
* фабрике на группу, чтобы волна реализации правила группы параллельно и без
|
|
7
|
+
* конфликтов:
|
|
8
|
+
* - `buildSessionPorts(deps)` → `sessions`;
|
|
9
|
+
* - `buildPrincipalPorts(deps)` → `projects`/`profiles`/`settings`/`defaults`/
|
|
10
|
+
* `providers`/`models`/`agents`;
|
|
11
|
+
* - `buildEventPorts(deps)` → `eventBindings`/`eventRoutes`/`eventApiKeys`/
|
|
12
|
+
* `eventJournal`/`identityClaims`/`dedup`/`schedules`/`jobs`/`webhooks`/
|
|
13
|
+
* `webhookDeliveries`;
|
|
14
|
+
* - `buildContentPorts(deps)` → `serviceKeys`/`sshKeys`/`mcpRegistry`/
|
|
15
|
+
* `skillBundles`/`dictionaries`/`secretPatterns`/`protectedPaths`/
|
|
16
|
+
* `maintenanceAudit`;
|
|
17
|
+
* - `buildAuditPorts(deps)` → `securityAudit`/`egressRequests`;
|
|
18
|
+
* - `buildAnalyticsPorts(deps)` → `analyticsRollups` (ADR-102);
|
|
19
|
+
* - `buildAuthorityPorts(deps)` → `authorityPolicy`/`authorityDecisions` (ADR-106 Ф0/Ф1);
|
|
20
|
+
* - `buildExternalCredentialPorts(deps)` → `externalCredentials` (ADR-105 Ф1);
|
|
21
|
+
* - `buildCredentialAuditPorts(deps)` → `credentialAudit` (ADR-105 Ф4);
|
|
22
|
+
* - `buildPipelinePorts(deps)` → `projectPipelines`/`pipelineRuns` (ADR-101);
|
|
23
|
+
* - `buildMemoryPorts(deps)` → `memoryFacts`/`memoryIndexes` (PROP-047 §2.1);
|
|
24
|
+
* - `buildQuestionPorts(deps)` → `questions` (этап 1 roadmap 0.13, блок 1.3);
|
|
25
|
+
* - `buildBackgroundRunPorts(deps)` → `backgroundRuns` (этап 1 roadmap 0.13,
|
|
26
|
+
* блок 1.2 — фоновые саб-агенты и шелл-процессы);
|
|
27
|
+
* - `buildWorktreePorts(deps)` → `worktrees` (ADR-114 — инвентарь
|
|
28
|
+
* git-worktree'ов; generic-таблица `documents`, `kind='worktree'`).
|
|
29
|
+
* - `buildBlobRefPorts(deps)` → `blobRefs` (ADR-115/ADR-116 — учёт ссылок
|
|
30
|
+
* на объекты blob-хранилища; таблица `blob_refs`).
|
|
31
|
+
* - `buildPackPorts(deps)` → `packs` (ADR-086 §5 — реестр установок
|
|
32
|
+
* пакетов расширений; таблица `pack_installations`).
|
|
33
|
+
* - `buildLegacyPipelinePorts(deps)` → `pipelines` (ADR-051/ADR-100 — реестр
|
|
34
|
+
* определений и экземпляров инстанса; таблицы `pipeline_definitions`/
|
|
35
|
+
* `pipeline_instances`). Не путать с `buildPipelinePorts` (ADR-101).
|
|
36
|
+
* - `buildSkillPorts(deps, blobs)` → `skills` (ADR-046 §4 / ADR-116 —
|
|
37
|
+
* метаданные в таблице `instance_skills`, содержимое — в blob-сторе
|
|
38
|
+
* `skills/<name>/…`).
|
|
39
|
+
* - `buildContextFilePorts(deps, opts)` → `contextFiles` (ADR-069/ADR-070 /
|
|
40
|
+
* ADR-116 — пользовательская часть в таблице `context_files`, системные
|
|
41
|
+
* промпты образа остаются ФС).
|
|
42
|
+
*
|
|
43
|
+
* Все доменные порты реализованы поверх SQL; **`blobs`** остаётся файловым по
|
|
44
|
+
* конструкции (байты вложений/логов/содержимого скиллов — на томе, в БД только
|
|
45
|
+
* `blob_refs`; ADR-091/ADR-092: ФС-периметр вне портов). `packs`, legacy
|
|
46
|
+
* `pipelines`, `skills` и `contextFiles` — **SQL** (ADR-116): таблицы
|
|
47
|
+
* `pack_installations`/`pipeline_definitions`/`pipeline_instances` (миграция 025),
|
|
48
|
+
* `instance_skills` (миграция 026; содержимое скиллов — в blob-сторе) и
|
|
49
|
+
* `context_files` (миграция 027; системные промпты образа остаются ФС).
|
|
50
|
+
*
|
|
51
|
+
* Рантайм-импорт core сужен до трёх точечных вещей (ADR-116): `FileBlobStore` +
|
|
52
|
+
* `prepareBlobRoot`/`blobRootPath` (blob-порт — файловый по конструкции, корень
|
|
53
|
+
* `{dataDir}/blobs`) и `ContextConfig` (системные промпты образа — его резолвер;
|
|
54
|
+
* пользовательская часть контекста в SQL). Файловый контекст
|
|
55
|
+
* (`createFileStorage`) драйвер **не собирает**. Для портов БД core по-прежнему
|
|
56
|
+
* не тянется: порты подключаются динамическим `import()` из core по
|
|
57
|
+
* `storage.backend`.
|
|
58
|
+
*/
|
|
59
|
+
import type { StorageContext } from '@itphx/synth-core';
|
|
60
|
+
import type { PostgresConnection } from './pool.js';
|
|
61
|
+
import type { CoreSyncDeps } from './ports/deps.js';
|
|
62
|
+
/** Опции сборки контекста PostgreSQL. */
|
|
63
|
+
export interface BuildPostgresContextOptions {
|
|
64
|
+
dataDir: string;
|
|
65
|
+
secretKey?: string;
|
|
66
|
+
env?: NodeJS.ProcessEnv;
|
|
67
|
+
/** Каталог системных словарей (пробрасывается группе `content`). */
|
|
68
|
+
systemDictionariesDir?: string;
|
|
69
|
+
/** Корень пользовательских промптов/ролей (композиция `contextFiles`: системные промпты — ФС образа). */
|
|
70
|
+
contextUserDataDir?: string;
|
|
71
|
+
/**
|
|
72
|
+
* ADR-097: живое соединение драйвера — удерживается в контексте, порты БД
|
|
73
|
+
* ходят через него; `close()` контекста закрывает пул.
|
|
74
|
+
*/
|
|
75
|
+
connection: PostgresConnection;
|
|
76
|
+
/** ADR-097: синхронные данные/хелперы core (см. `CoreSyncDeps`). */
|
|
77
|
+
coreSync: CoreSyncDeps;
|
|
78
|
+
}
|
|
79
|
+
/** Собрать `StorageContext`: доменные порты (SQL) + blob-стор (ФС) + `close`. */
|
|
80
|
+
export declare function buildPostgresStorageContext(opts: BuildPostgresContextOptions): StorageContext;
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Сборка `StorageContext` PostgreSQL-драйвера (ADR-097, волна 3b-каркас).
|
|
3
|
+
*
|
|
4
|
+
* Контекст собирается из независимых файлов-групп портов
|
|
5
|
+
* (`src/ports/{sessions,principals,events,content,audit,analytics}.ts`) — по одной
|
|
6
|
+
* фабрике на группу, чтобы волна реализации правила группы параллельно и без
|
|
7
|
+
* конфликтов:
|
|
8
|
+
* - `buildSessionPorts(deps)` → `sessions`;
|
|
9
|
+
* - `buildPrincipalPorts(deps)` → `projects`/`profiles`/`settings`/`defaults`/
|
|
10
|
+
* `providers`/`models`/`agents`;
|
|
11
|
+
* - `buildEventPorts(deps)` → `eventBindings`/`eventRoutes`/`eventApiKeys`/
|
|
12
|
+
* `eventJournal`/`identityClaims`/`dedup`/`schedules`/`jobs`/`webhooks`/
|
|
13
|
+
* `webhookDeliveries`;
|
|
14
|
+
* - `buildContentPorts(deps)` → `serviceKeys`/`sshKeys`/`mcpRegistry`/
|
|
15
|
+
* `skillBundles`/`dictionaries`/`secretPatterns`/`protectedPaths`/
|
|
16
|
+
* `maintenanceAudit`;
|
|
17
|
+
* - `buildAuditPorts(deps)` → `securityAudit`/`egressRequests`;
|
|
18
|
+
* - `buildAnalyticsPorts(deps)` → `analyticsRollups` (ADR-102);
|
|
19
|
+
* - `buildAuthorityPorts(deps)` → `authorityPolicy`/`authorityDecisions` (ADR-106 Ф0/Ф1);
|
|
20
|
+
* - `buildExternalCredentialPorts(deps)` → `externalCredentials` (ADR-105 Ф1);
|
|
21
|
+
* - `buildCredentialAuditPorts(deps)` → `credentialAudit` (ADR-105 Ф4);
|
|
22
|
+
* - `buildPipelinePorts(deps)` → `projectPipelines`/`pipelineRuns` (ADR-101);
|
|
23
|
+
* - `buildMemoryPorts(deps)` → `memoryFacts`/`memoryIndexes` (PROP-047 §2.1);
|
|
24
|
+
* - `buildQuestionPorts(deps)` → `questions` (этап 1 roadmap 0.13, блок 1.3);
|
|
25
|
+
* - `buildBackgroundRunPorts(deps)` → `backgroundRuns` (этап 1 roadmap 0.13,
|
|
26
|
+
* блок 1.2 — фоновые саб-агенты и шелл-процессы);
|
|
27
|
+
* - `buildWorktreePorts(deps)` → `worktrees` (ADR-114 — инвентарь
|
|
28
|
+
* git-worktree'ов; generic-таблица `documents`, `kind='worktree'`).
|
|
29
|
+
* - `buildBlobRefPorts(deps)` → `blobRefs` (ADR-115/ADR-116 — учёт ссылок
|
|
30
|
+
* на объекты blob-хранилища; таблица `blob_refs`).
|
|
31
|
+
* - `buildPackPorts(deps)` → `packs` (ADR-086 §5 — реестр установок
|
|
32
|
+
* пакетов расширений; таблица `pack_installations`).
|
|
33
|
+
* - `buildLegacyPipelinePorts(deps)` → `pipelines` (ADR-051/ADR-100 — реестр
|
|
34
|
+
* определений и экземпляров инстанса; таблицы `pipeline_definitions`/
|
|
35
|
+
* `pipeline_instances`). Не путать с `buildPipelinePorts` (ADR-101).
|
|
36
|
+
* - `buildSkillPorts(deps, blobs)` → `skills` (ADR-046 §4 / ADR-116 —
|
|
37
|
+
* метаданные в таблице `instance_skills`, содержимое — в blob-сторе
|
|
38
|
+
* `skills/<name>/…`).
|
|
39
|
+
* - `buildContextFilePorts(deps, opts)` → `contextFiles` (ADR-069/ADR-070 /
|
|
40
|
+
* ADR-116 — пользовательская часть в таблице `context_files`, системные
|
|
41
|
+
* промпты образа остаются ФС).
|
|
42
|
+
*
|
|
43
|
+
* Все доменные порты реализованы поверх SQL; **`blobs`** остаётся файловым по
|
|
44
|
+
* конструкции (байты вложений/логов/содержимого скиллов — на томе, в БД только
|
|
45
|
+
* `blob_refs`; ADR-091/ADR-092: ФС-периметр вне портов). `packs`, legacy
|
|
46
|
+
* `pipelines`, `skills` и `contextFiles` — **SQL** (ADR-116): таблицы
|
|
47
|
+
* `pack_installations`/`pipeline_definitions`/`pipeline_instances` (миграция 025),
|
|
48
|
+
* `instance_skills` (миграция 026; содержимое скиллов — в blob-сторе) и
|
|
49
|
+
* `context_files` (миграция 027; системные промпты образа остаются ФС).
|
|
50
|
+
*
|
|
51
|
+
* Рантайм-импорт core сужен до трёх точечных вещей (ADR-116): `FileBlobStore` +
|
|
52
|
+
* `prepareBlobRoot`/`blobRootPath` (blob-порт — файловый по конструкции, корень
|
|
53
|
+
* `{dataDir}/blobs`) и `ContextConfig` (системные промпты образа — его резолвер;
|
|
54
|
+
* пользовательская часть контекста в SQL). Файловый контекст
|
|
55
|
+
* (`createFileStorage`) драйвер **не собирает**. Для портов БД core по-прежнему
|
|
56
|
+
* не тянется: порты подключаются динамическим `import()` из core по
|
|
57
|
+
* `storage.backend`.
|
|
58
|
+
*/
|
|
59
|
+
import { join } from 'node:path';
|
|
60
|
+
// ADR-116: точечный рантайм-импорт core — blob-порт (файловый по конструкции) и
|
|
61
|
+
// `ContextConfig` как источник каталога системных промптов образа.
|
|
62
|
+
import { blobRootPath, ContextConfig, FileBlobStore, prepareBlobRoot } from '@itphx/synth-core';
|
|
63
|
+
import { latestSchemaVersion, MIGRATIONS } from './migrations/index.js';
|
|
64
|
+
import { planMigrations, readSchemaVersion, runMigrations } from './migrate.js';
|
|
65
|
+
import { buildContentPorts } from './ports/content.js';
|
|
66
|
+
import { buildAuditPorts } from './ports/audit.js';
|
|
67
|
+
import { buildAnalyticsPorts } from './ports/analytics.js';
|
|
68
|
+
import { buildAuthorityPorts } from './ports/authority.js';
|
|
69
|
+
import { buildExternalCredentialPorts } from './ports/external-credentials.js';
|
|
70
|
+
import { buildCredentialAuditPorts } from './ports/credential-audit.js';
|
|
71
|
+
import { buildMemoryPorts } from './ports/memory.js';
|
|
72
|
+
import { buildEventPorts } from './ports/events.js';
|
|
73
|
+
import { buildPipelinePorts } from './ports/pipelines.js';
|
|
74
|
+
// ADR-116: реестр установок пакетов (ADR-086 §5) и legacy-пайплайны
|
|
75
|
+
// (ADR-051/ADR-100) переведены в SQL (миграция `025_packs_pipelines`).
|
|
76
|
+
import { buildPackPorts } from './ports/packs.js';
|
|
77
|
+
import { buildLegacyPipelinePorts } from './ports/legacy-pipelines.js';
|
|
78
|
+
// ADR-116: instance-скиллы — метаданные в SQL (`instance_skills`, миграция 026),
|
|
79
|
+
// содержимое — в blob-сторе (`skills/<name>/…`).
|
|
80
|
+
import { buildSkillPorts } from './ports/skills.js';
|
|
81
|
+
// ADR-116: файлы контекста — пользовательская часть в SQL (`context_files`,
|
|
82
|
+
// миграция 027), системные промпты образа остаются ФС.
|
|
83
|
+
import { buildContextFilePorts } from './ports/context-files.js';
|
|
84
|
+
import { buildQuestionPorts } from './ports/questions.js';
|
|
85
|
+
import { buildBackgroundRunPorts } from './ports/background-runs.js';
|
|
86
|
+
import { buildWorktreePorts } from './ports/worktrees.js';
|
|
87
|
+
// ADR-115/ADR-116: учёт ссылок на объекты blob-хранилища (таблица `blob_refs`).
|
|
88
|
+
import { buildBlobRefPorts } from './ports/blob-refs.js';
|
|
89
|
+
import { buildPluginLockPorts } from './ports/plugin-lock.js';
|
|
90
|
+
import { buildPrincipalPorts } from './ports/principals.js';
|
|
91
|
+
import { buildSessionPorts } from './ports/sessions.js';
|
|
92
|
+
import { createPostgresLocks } from './locks.js';
|
|
93
|
+
/** Собрать `StorageContext`: доменные порты (SQL) + blob-стор (ФС) + `close`. */
|
|
94
|
+
export function buildPostgresStorageContext(opts) {
|
|
95
|
+
// ADR-116: blob-стор остаётся файловым по конструкции, поэтому создаётся
|
|
96
|
+
// точечно (а не сборкой всего файлового контекста) с тем же корнем, что у
|
|
97
|
+
// файлового backend'а — `{dataDir}/blobs`. `prepareBlobRoot` идемпотентно
|
|
98
|
+
// создаёт каталог и переносит логи старой раскладки.
|
|
99
|
+
prepareBlobRoot(opts.dataDir);
|
|
100
|
+
const blobs = new FileBlobStore({ root: blobRootPath(opts.dataDir) });
|
|
101
|
+
const background = [];
|
|
102
|
+
// ADR-116: пользовательская часть файлов контекста — SQL, системные промпты —
|
|
103
|
+
// ФС. Каталог пользовательских файлов тот же, что у файловой реализации
|
|
104
|
+
// (используется лишь как путь по умолчанию для композиции).
|
|
105
|
+
const contextUserDataDir = opts.contextUserDataDir ?? join(opts.dataDir, 'context');
|
|
106
|
+
// Каталог системных промптов образа резолвит сам `ContextConfig`
|
|
107
|
+
// (`{root}/prompts`, fallback `{root}/dist/prompts`) — берём его у класса,
|
|
108
|
+
// чтобы поведение не разошлось с файловой реализацией; файловый контекст ради
|
|
109
|
+
// этого не нужен.
|
|
110
|
+
const systemPromptsDir = new ContextConfig({ userDataDir: contextUserDataDir }).systemPromptsDir;
|
|
111
|
+
const deps = {
|
|
112
|
+
connection: opts.connection,
|
|
113
|
+
dataDir: opts.dataDir,
|
|
114
|
+
secretKey: opts.secretKey,
|
|
115
|
+
env: opts.env,
|
|
116
|
+
systemDictionariesDir: opts.systemDictionariesDir,
|
|
117
|
+
contextUserDataDir: opts.contextUserDataDir,
|
|
118
|
+
coreSync: opts.coreSync,
|
|
119
|
+
// Фоновые задачи сборки (best-effort прогрев кэшей `content`) — дожидаемся
|
|
120
|
+
// их в `close()` до закрытия пула, иначе warm-запросы падают с «пул недоступен».
|
|
121
|
+
trackBackground: (task) => background.push(task),
|
|
122
|
+
};
|
|
123
|
+
return {
|
|
124
|
+
kind: 'postgres',
|
|
125
|
+
// ADR-097: соединение живёт в контексте; `close()` закрывает пул (graceful
|
|
126
|
+
// shutdown домена). Перед закрытием дожидаемся фоновых задач сборки
|
|
127
|
+
// (best-effort прогрев синхронных кэшей `content`): warm-запросы не должны
|
|
128
|
+
// попадать в уже закрытый пул — иначе диагностика/`backup`/`migrate` видят
|
|
129
|
+
// ложные предупреждения «прогрев порта не удался: пул недоступен».
|
|
130
|
+
close: async () => {
|
|
131
|
+
await Promise.allSettled(background);
|
|
132
|
+
await opts.connection.end();
|
|
133
|
+
},
|
|
134
|
+
// ADR-097/ADR-091: диагностика backend'а — реальный probe БД + версия схемы
|
|
135
|
+
// (read-only, без применения миграций) для `synth doctor`/admin-API.
|
|
136
|
+
health: async () => {
|
|
137
|
+
const started = Date.now();
|
|
138
|
+
try {
|
|
139
|
+
await opts.connection.query('SELECT 1');
|
|
140
|
+
const schemaVersion = await readSchemaVersion(opts.connection, opts.connection.schema);
|
|
141
|
+
return {
|
|
142
|
+
ok: true,
|
|
143
|
+
latencyMs: Date.now() - started,
|
|
144
|
+
schemaVersion,
|
|
145
|
+
expectedSchemaVersion: latestSchemaVersion(MIGRATIONS),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
return {
|
|
150
|
+
ok: false,
|
|
151
|
+
latencyMs: Date.now() - started,
|
|
152
|
+
error: err instanceof Error ? err.message : String(err),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
// ADR-097/ADR-092: миграции схемы БД — план (`dryRun`) или применение
|
|
157
|
+
// (лок/транзакции берёт `runMigrations`).
|
|
158
|
+
schemaMigrations: async (migrationOpts) => {
|
|
159
|
+
if (migrationOpts?.dryRun) {
|
|
160
|
+
const plan = await planMigrations(opts.connection, { schema: opts.connection.schema });
|
|
161
|
+
return { ...plan, applied: [] };
|
|
162
|
+
}
|
|
163
|
+
const result = await runMigrations(opts.connection, { schema: opts.connection.schema });
|
|
164
|
+
return {
|
|
165
|
+
current: result.version,
|
|
166
|
+
expected: result.version,
|
|
167
|
+
pending: [],
|
|
168
|
+
applied: result.applied,
|
|
169
|
+
};
|
|
170
|
+
},
|
|
171
|
+
// ADR-097: удаление схемы БД — только по явному `uninstall --purge-db`.
|
|
172
|
+
purgeSchema: () => opts.connection.dropSchema(),
|
|
173
|
+
// ADR-097: примитивы координации БД (advisory-локи) — composition root
|
|
174
|
+
// подставляет их вместо файловых `FileMutex`/`FileLeader`.
|
|
175
|
+
locks: createPostgresLocks(opts.connection),
|
|
176
|
+
...buildSessionPorts(deps),
|
|
177
|
+
...buildPrincipalPorts(deps),
|
|
178
|
+
...buildEventPorts(deps),
|
|
179
|
+
...buildContentPorts(deps),
|
|
180
|
+
...buildAuditPorts(deps),
|
|
181
|
+
// ADR-106 (Ф0/Ф1): порты Authority-слоя — политика полномочий инстанса
|
|
182
|
+
// (`authority_policy`, миграция 014) и append-only журнал решений
|
|
183
|
+
// (`authority_decisions`).
|
|
184
|
+
...buildAuthorityPorts(deps),
|
|
185
|
+
// ADR-105 (Ф1): внешние доступы к коннекторам (таблица `external_credentials`,
|
|
186
|
+
// миграция 011). Токены шифруются core-хелперами (ленивый `import()`), в БД
|
|
187
|
+
// лежит готовый `enc:v1:…`; наружу отдаются только метаданные с маской.
|
|
188
|
+
...buildExternalCredentialPorts(deps),
|
|
189
|
+
// ADR-105 (Ф4): журнал операций со слоем доступов (таблица
|
|
190
|
+
// `credential_audit`, миграция 016). Секретов и id сессий/пользователей
|
|
191
|
+
// в записях нет.
|
|
192
|
+
...buildCredentialAuditPorts(deps),
|
|
193
|
+
// ADR-102: порт роллапов аналитики — пред-агрегированные суточные бакеты
|
|
194
|
+
// (`analytics_rollups`, миграция 003) с атомарным `ON CONFLICT … DO UPDATE`.
|
|
195
|
+
...buildAnalyticsPorts(deps),
|
|
196
|
+
// ADR-101: спецификации пайплайнов, прогоны и журнал выполнения
|
|
197
|
+
// (`pipeline_specs`/`pipeline_versions`/`pipeline_runs`/`pipeline_run_events`,
|
|
198
|
+
// миграция 004).
|
|
199
|
+
...buildPipelinePorts(deps),
|
|
200
|
+
// PROP-047 §2.1 (предпосылка A): порты памяти — факты, индексы и чанки
|
|
201
|
+
// (`memory_facts`/`memory_indexes`/`memory_chunks`, миграция 017). Векторы
|
|
202
|
+
// хранятся в `jsonb` (без `pgvector` — расширение в БД не установлено).
|
|
203
|
+
...buildMemoryPorts(deps),
|
|
204
|
+
// PROP-068 §4.4 / ADR-090: lock-файл плагинов (таблица `plugin_lock`,
|
|
205
|
+
// миграция 007) — источник истины для update/uninstall.
|
|
206
|
+
...buildPluginLockPorts(deps),
|
|
207
|
+
// Этап 1 roadmap 0.13: вопросы пользователю (таблица `questions`) и единый
|
|
208
|
+
// реестр фоновых прогонов (таблица `background_runs`) — миграция 021.
|
|
209
|
+
...buildQuestionPorts(deps),
|
|
210
|
+
...buildBackgroundRunPorts(deps),
|
|
211
|
+
// ADR-114: инвентарь git-worktree'ов — generic-таблица `documents`
|
|
212
|
+
// (`kind='worktree'`), без новой миграции.
|
|
213
|
+
...buildWorktreePorts(deps),
|
|
214
|
+
// ADR-115/ADR-116: учёт ссылок на объекты blob-хранилища — таблица
|
|
215
|
+
// `blob_refs` (миграция 024). Байты объектов остаются на томе (`blobs`).
|
|
216
|
+
...buildBlobRefPorts(deps),
|
|
217
|
+
// ADR-116: blob-стор остаётся файловым по конструкции (байты вложений,
|
|
218
|
+
// логов, содержимого скиллов — на томе; в БД только `blob_refs`).
|
|
219
|
+
blobs,
|
|
220
|
+
// ADR-116: пользовательские файлы контекста/промптов — SQL
|
|
221
|
+
// (`context_files`, миграция 027); системные промпты образа — ФС по пути
|
|
222
|
+
// `ContextConfig.systemPromptsDir` (композиция читает их напрямую, а
|
|
223
|
+
// пользовательские override — из кэша таблицы).
|
|
224
|
+
...buildContextFilePorts(deps, {
|
|
225
|
+
systemPromptsDir,
|
|
226
|
+
createConfig: (overrides) => new ContextConfig({ userDataDir: contextUserDataDir, systemPromptsDir, overrides }),
|
|
227
|
+
}),
|
|
228
|
+
// ADR-116: instance-скиллы — метаданные в SQL (`instance_skills`,
|
|
229
|
+
// миграция 026), содержимое — в том же blob-сторе (`skills/<name>/…`).
|
|
230
|
+
...buildSkillPorts(deps, blobs),
|
|
231
|
+
// ADR-116: реестр установок пакетов (ADR-086 §5) и legacy-пайплайны
|
|
232
|
+
// (ADR-051/ADR-100) — SQL-реализации (таблицы `pack_installations` /
|
|
233
|
+
// `pipeline_definitions` / `pipeline_instances`, миграция 025). До ADR-116
|
|
234
|
+
// они были переходно файловыми; контрактный suite проверяет SQL.
|
|
235
|
+
...buildPackPorts(deps),
|
|
236
|
+
...buildLegacyPipelinePorts(deps),
|
|
237
|
+
};
|
|
238
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@itphx/synth-storage-postgres",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.12.4",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@itphx/synth-shared": "0.12.4"
|
|
19
|
+
},
|
|
20
|
+
"peerDependencies": {
|
|
21
|
+
"@itphx/synth-core": "0.12.4"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@itphx/synth-core": "0.12.4",
|
|
25
|
+
"@types/node": "^22.0.0",
|
|
26
|
+
"@types/pg": "^8.15.0",
|
|
27
|
+
"typescript": "^5.8.0"
|
|
28
|
+
},
|
|
29
|
+
"optionalDependencies": {
|
|
30
|
+
"pg": "^8.13.0"
|
|
31
|
+
},
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=22.0.0"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
37
|
+
"typecheck": "tsc --noEmit",
|
|
38
|
+
"lint": "eslint src/",
|
|
39
|
+
"test": "vitest run",
|
|
40
|
+
"test:watch": "vitest",
|
|
41
|
+
"clean": "rm -rf dist"
|
|
42
|
+
}
|
|
6
43
|
}
|
package/README.md
DELETED