@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.
Files changed (150) hide show
  1. package/LICENSE +18 -0
  2. package/LICENSE.ru.md +31 -0
  3. package/dist/errors.d.ts +71 -0
  4. package/dist/errors.js +126 -0
  5. package/dist/index.d.ts +51 -0
  6. package/dist/index.js +56 -0
  7. package/dist/json-param.d.ts +14 -0
  8. package/dist/json-param.js +22 -0
  9. package/dist/locks.d.ts +104 -0
  10. package/dist/locks.js +201 -0
  11. package/dist/migrate.d.ts +58 -0
  12. package/dist/migrate.js +125 -0
  13. package/dist/migrations/001-init.d.ts +15 -0
  14. package/dist/migrations/001-init.js +457 -0
  15. package/dist/migrations/002-egress-audit.d.ts +12 -0
  16. package/dist/migrations/002-egress-audit.js +52 -0
  17. package/dist/migrations/003-analytics-rollups.d.ts +12 -0
  18. package/dist/migrations/003-analytics-rollups.js +21 -0
  19. package/dist/migrations/004-pipeline-engine.d.ts +19 -0
  20. package/dist/migrations/004-pipeline-engine.js +74 -0
  21. package/dist/migrations/005-pipeline-provenance.d.ts +12 -0
  22. package/dist/migrations/005-pipeline-provenance.js +15 -0
  23. package/dist/migrations/006-plugin-audit.d.ts +13 -0
  24. package/dist/migrations/006-plugin-audit.js +34 -0
  25. package/dist/migrations/007-plugin-lock.d.ts +10 -0
  26. package/dist/migrations/007-plugin-lock.js +25 -0
  27. package/dist/migrations/008-plugin-audit-scan.d.ts +11 -0
  28. package/dist/migrations/008-plugin-audit-scan.js +15 -0
  29. package/dist/migrations/009-plugin-lock-previous.d.ts +13 -0
  30. package/dist/migrations/009-plugin-lock-previous.js +16 -0
  31. package/dist/migrations/010-plugin-lock-mode.d.ts +16 -0
  32. package/dist/migrations/010-plugin-lock-mode.js +20 -0
  33. package/dist/migrations/011-session-steer-inbox.d.ts +11 -0
  34. package/dist/migrations/011-session-steer-inbox.js +14 -0
  35. package/dist/migrations/012-external-credentials.d.ts +15 -0
  36. package/dist/migrations/012-external-credentials.js +40 -0
  37. package/dist/migrations/013-service-key-plugin-id.d.ts +17 -0
  38. package/dist/migrations/013-service-key-plugin-id.js +20 -0
  39. package/dist/migrations/014-session-mode-by-principal.d.ts +12 -0
  40. package/dist/migrations/014-session-mode-by-principal.js +15 -0
  41. package/dist/migrations/015-authority.d.ts +17 -0
  42. package/dist/migrations/015-authority.js +43 -0
  43. package/dist/migrations/016-credential-audit.d.ts +17 -0
  44. package/dist/migrations/016-credential-audit.js +32 -0
  45. package/dist/migrations/017-memory.d.ts +29 -0
  46. package/dist/migrations/017-memory.js +95 -0
  47. package/dist/migrations/018-memory-index-scope.d.ts +14 -0
  48. package/dist/migrations/018-memory-index-scope.js +18 -0
  49. package/dist/migrations/019-memory-index-enabled.d.ts +11 -0
  50. package/dist/migrations/019-memory-index-enabled.js +14 -0
  51. package/dist/migrations/020-project-memory.d.ts +11 -0
  52. package/dist/migrations/020-project-memory.js +13 -0
  53. package/dist/migrations/021-background-runs.d.ts +17 -0
  54. package/dist/migrations/021-background-runs.js +67 -0
  55. package/dist/migrations/022-background-run-process-id.d.ts +14 -0
  56. package/dist/migrations/022-background-run-process-id.js +18 -0
  57. package/dist/migrations/023-session-worktree.d.ts +12 -0
  58. package/dist/migrations/023-session-worktree.js +16 -0
  59. package/dist/migrations/024-blob-refs.d.ts +15 -0
  60. package/dist/migrations/024-blob-refs.js +26 -0
  61. package/dist/migrations/025-packs-pipelines.d.ts +28 -0
  62. package/dist/migrations/025-packs-pipelines.js +82 -0
  63. package/dist/migrations/026-instance-skills.d.ts +17 -0
  64. package/dist/migrations/026-instance-skills.js +25 -0
  65. package/dist/migrations/027-context-files.d.ts +20 -0
  66. package/dist/migrations/027-context-files.js +30 -0
  67. package/dist/migrations/index.d.ts +23 -0
  68. package/dist/migrations/index.js +71 -0
  69. package/dist/pool.d.ts +178 -0
  70. package/dist/pool.js +382 -0
  71. package/dist/ports/analytics.d.ts +26 -0
  72. package/dist/ports/analytics.js +243 -0
  73. package/dist/ports/audit.d.ts +15 -0
  74. package/dist/ports/audit.js +192 -0
  75. package/dist/ports/authority.d.ts +27 -0
  76. package/dist/ports/authority.js +148 -0
  77. package/dist/ports/background-runs.d.ts +41 -0
  78. package/dist/ports/background-runs.js +179 -0
  79. package/dist/ports/blob-refs.d.ts +36 -0
  80. package/dist/ports/blob-refs.js +55 -0
  81. package/dist/ports/content.d.ts +41 -0
  82. package/dist/ports/content.js +1553 -0
  83. package/dist/ports/context-files.d.ts +145 -0
  84. package/dist/ports/context-files.js +279 -0
  85. package/dist/ports/core-sync.d.ts +31 -0
  86. package/dist/ports/core-sync.js +34 -0
  87. package/dist/ports/credential-audit.d.ts +19 -0
  88. package/dist/ports/credential-audit.js +96 -0
  89. package/dist/ports/deps.d.ts +63 -0
  90. package/dist/ports/deps.js +19 -0
  91. package/dist/ports/events-bindings.d.ts +77 -0
  92. package/dist/ports/events-bindings.js +356 -0
  93. package/dist/ports/events-core.d.ts +35 -0
  94. package/dist/ports/events-core.js +71 -0
  95. package/dist/ports/events-journal.d.ts +68 -0
  96. package/dist/ports/events-journal.js +211 -0
  97. package/dist/ports/events-scheduler.d.ts +49 -0
  98. package/dist/ports/events-scheduler.js +231 -0
  99. package/dist/ports/events-webhooks.d.ts +64 -0
  100. package/dist/ports/events-webhooks.js +268 -0
  101. package/dist/ports/events.d.ts +20 -0
  102. package/dist/ports/events.js +27 -0
  103. package/dist/ports/external-credentials.d.ts +6 -0
  104. package/dist/ports/external-credentials.js +363 -0
  105. package/dist/ports/legacy-pipelines.d.ts +50 -0
  106. package/dist/ports/legacy-pipelines.js +202 -0
  107. package/dist/ports/memory.d.ts +65 -0
  108. package/dist/ports/memory.js +471 -0
  109. package/dist/ports/packs.d.ts +32 -0
  110. package/dist/ports/packs.js +117 -0
  111. package/dist/ports/pipelines.d.ts +67 -0
  112. package/dist/ports/pipelines.js +297 -0
  113. package/dist/ports/plugin-audit.d.ts +14 -0
  114. package/dist/ports/plugin-audit.js +110 -0
  115. package/dist/ports/plugin-lock.d.ts +27 -0
  116. package/dist/ports/plugin-lock.js +145 -0
  117. package/dist/ports/principals-defaults.d.ts +21 -0
  118. package/dist/ports/principals-defaults.js +68 -0
  119. package/dist/ports/principals-documents.d.ts +23 -0
  120. package/dist/ports/principals-documents.js +38 -0
  121. package/dist/ports/principals-profiles.d.ts +21 -0
  122. package/dist/ports/principals-profiles.js +263 -0
  123. package/dist/ports/principals-projects.d.ts +19 -0
  124. package/dist/ports/principals-projects.js +161 -0
  125. package/dist/ports/principals-settings.d.ts +25 -0
  126. package/dist/ports/principals-settings.js +295 -0
  127. package/dist/ports/principals-shared.d.ts +33 -0
  128. package/dist/ports/principals-shared.js +44 -0
  129. package/dist/ports/principals.d.ts +27 -0
  130. package/dist/ports/principals.js +39 -0
  131. package/dist/ports/questions.d.ts +40 -0
  132. package/dist/ports/questions.js +135 -0
  133. package/dist/ports/sessions-mapping.d.ts +254 -0
  134. package/dist/ports/sessions-mapping.js +449 -0
  135. package/dist/ports/sessions.d.ts +143 -0
  136. package/dist/ports/sessions.js +517 -0
  137. package/dist/ports/skills.d.ts +59 -0
  138. package/dist/ports/skills.js +205 -0
  139. package/dist/ports/stub.d.ts +14 -0
  140. package/dist/ports/stub.js +32 -0
  141. package/dist/ports/worktrees.d.ts +41 -0
  142. package/dist/ports/worktrees.js +85 -0
  143. package/dist/postgres-storage.d.ts +58 -0
  144. package/dist/postgres-storage.js +110 -0
  145. package/dist/schema.d.ts +13 -0
  146. package/dist/schema.js +22 -0
  147. package/dist/storage-context.d.ts +80 -0
  148. package/dist/storage-context.js +238 -0
  149. package/package.json +40 -3
  150. package/README.md +0 -3
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Порт `settings` (runtime-настройки инстанса) PostgreSQL-драйвера
3
+ * (ADR-097, волна 3b).
4
+ *
5
+ * Эталон семантики — `RuntimeSettingsStore`/`MemorySettingsRepository`:
6
+ * - `load()` на пустом сторе — `{}` (не заданные секции в результат не попадают);
7
+ * - геттеры отдают `undefined`/`{}`/`false` для не заданных значений;
8
+ * - `clear*` убирает секцию (ключ удаляется, а не пишется `null`).
9
+ *
10
+ * Хранение разложено по таблицам `001_init`:
11
+ * - `settings(key PK, value jsonb)` — секции `RuntimeSettings` (по ключу на секцию);
12
+ * - `token_ratios(model PK, ratio)` — chars-per-token по модели;
13
+ * - `migration_markers(name PK)` — маркеры разовых миграций.
14
+ *
15
+ * Запись секции — upsert одного ключа. Read-modify-write файловой реализации для
16
+ * `migrations`/`tokenRatios` здесь отсутствует by design: они нормализованы в
17
+ * отдельные таблицы (строку за раз), поэтому гонки между обновлениями разных
18
+ * моделей/маркеров нет.
19
+ */
20
+ import { deleteSetting, readSetting, writeSetting } from './principals-shared.js';
21
+ /** Ключи секций, которые порт хранит в таблице `settings` (порядок стабилен). */
22
+ const SECTION_KEYS = [
23
+ 'workspace',
24
+ 'mcpServers',
25
+ 'llmGateway',
26
+ 'security',
27
+ 'toolsPolicy',
28
+ 'mcpPolicy',
29
+ 'toolsDisabled',
30
+ 'skillsDisabled',
31
+ 'skillsDisabledForNewProjects',
32
+ 'skillsPolicy',
33
+ 'mcpNetworkPolicy',
34
+ 'egress',
35
+ 'defaultAgent',
36
+ 'defaultModel',
37
+ 'workspacePolicy',
38
+ 'events',
39
+ 'decision',
40
+ 'proxy',
41
+ 'plugins',
42
+ 'attachments',
43
+ ];
44
+ const SECTION_KEY_SET = new Set(SECTION_KEYS);
45
+ /** Собрать порт runtime-настроек поверх SQL. */
46
+ export function createPrincipalSettingsPort(conn) {
47
+ return {
48
+ async load() {
49
+ const settings = {};
50
+ const rows = await conn.query('SELECT key, value FROM settings WHERE key = ANY($1::text[])', [[...SECTION_KEYS]]);
51
+ for (const row of rows) {
52
+ if (!SECTION_KEY_SET.has(row.key))
53
+ continue;
54
+ settings[row.key] = row.value;
55
+ }
56
+ const ratios = await conn.query('SELECT model, ratio FROM token_ratios');
57
+ if (ratios.length > 0) {
58
+ const tokenRatios = {};
59
+ for (const row of ratios)
60
+ tokenRatios[row.model] = row.ratio;
61
+ settings.tokenRatios = tokenRatios;
62
+ }
63
+ const markers = await conn.query('SELECT name FROM migration_markers');
64
+ if (markers.length > 0) {
65
+ const migrations = {};
66
+ for (const row of markers)
67
+ migrations[row.name] = true;
68
+ settings.migrations = migrations;
69
+ }
70
+ return settings;
71
+ },
72
+ async getWorkspace() {
73
+ return readSetting(conn, 'workspace');
74
+ },
75
+ async setWorkspace(workspace) {
76
+ await writeSetting(conn, 'workspace', workspace);
77
+ },
78
+ async clearWorkspace() {
79
+ await deleteSetting(conn, 'workspace');
80
+ },
81
+ async getMcpSettings() {
82
+ return (await readSetting(conn, 'mcpServers')) ?? {};
83
+ },
84
+ async setMcpSettings(servers) {
85
+ await writeSetting(conn, 'mcpServers', servers);
86
+ },
87
+ async clearMcpSettings() {
88
+ await deleteSetting(conn, 'mcpServers');
89
+ },
90
+ async getLlmGatewaySettings() {
91
+ return (await readSetting(conn, 'llmGateway')) ?? {};
92
+ },
93
+ async setLlmGatewaySettings(config) {
94
+ await writeSetting(conn, 'llmGateway', config);
95
+ },
96
+ async clearLlmGatewaySettings() {
97
+ await deleteSetting(conn, 'llmGateway');
98
+ },
99
+ async getSecuritySettings() {
100
+ return (await readSetting(conn, 'security')) ?? {};
101
+ },
102
+ async setSecuritySettings(config) {
103
+ await writeSetting(conn, 'security', config);
104
+ },
105
+ async clearSecuritySettings() {
106
+ await deleteSetting(conn, 'security');
107
+ },
108
+ async getToolsPolicy() {
109
+ return readSetting(conn, 'toolsPolicy');
110
+ },
111
+ async setToolsPolicy(policy) {
112
+ await writeSetting(conn, 'toolsPolicy', policy);
113
+ },
114
+ async clearToolsPolicy() {
115
+ await deleteSetting(conn, 'toolsPolicy');
116
+ },
117
+ async getMcpPolicy() {
118
+ return readSetting(conn, 'mcpPolicy');
119
+ },
120
+ async setMcpPolicy(policy) {
121
+ await writeSetting(conn, 'mcpPolicy', policy);
122
+ },
123
+ async clearMcpPolicy() {
124
+ await deleteSetting(conn, 'mcpPolicy');
125
+ },
126
+ async getToolsDisabled() {
127
+ return readSetting(conn, 'toolsDisabled');
128
+ },
129
+ async setToolsDisabled(config) {
130
+ await writeSetting(conn, 'toolsDisabled', config);
131
+ },
132
+ async clearToolsDisabled() {
133
+ await deleteSetting(conn, 'toolsDisabled');
134
+ },
135
+ async getSkillsDisabled() {
136
+ return readSetting(conn, 'skillsDisabled');
137
+ },
138
+ async setSkillsDisabled(config) {
139
+ await writeSetting(conn, 'skillsDisabled', config);
140
+ },
141
+ async clearSkillsDisabled() {
142
+ await deleteSetting(conn, 'skillsDisabled');
143
+ },
144
+ async getSkillsDisabledForNewProjects() {
145
+ return readSetting(conn, 'skillsDisabledForNewProjects');
146
+ },
147
+ async setSkillsDisabledForNewProjects(config) {
148
+ await writeSetting(conn, 'skillsDisabledForNewProjects', config);
149
+ },
150
+ async clearSkillsDisabledForNewProjects() {
151
+ await deleteSetting(conn, 'skillsDisabledForNewProjects');
152
+ },
153
+ async getMigrationMarker(name) {
154
+ const rows = await conn.query('SELECT name FROM migration_markers WHERE name = $1', [name]);
155
+ return rows.length > 0;
156
+ },
157
+ async setMigrationMarker(name) {
158
+ await conn.query(`INSERT INTO migration_markers (name) VALUES ($1)
159
+ ON CONFLICT (name) DO UPDATE SET applied_at = now()`, [name]);
160
+ },
161
+ async getSkillsPolicy() {
162
+ return readSetting(conn, 'skillsPolicy');
163
+ },
164
+ async setSkillsPolicy(policy) {
165
+ await writeSetting(conn, 'skillsPolicy', policy);
166
+ },
167
+ async clearSkillsPolicy() {
168
+ await deleteSetting(conn, 'skillsPolicy');
169
+ },
170
+ async getTokenRatio(model) {
171
+ const rows = await conn.query('SELECT ratio FROM token_ratios WHERE model = $1', [model]);
172
+ return rows[0]?.ratio;
173
+ },
174
+ async getTokenRatios() {
175
+ const rows = await conn.query('SELECT model, ratio FROM token_ratios');
176
+ const ratios = {};
177
+ for (const row of rows)
178
+ ratios[row.model] = row.ratio;
179
+ return ratios;
180
+ },
181
+ async setTokenRatio(model, ratio) {
182
+ await conn.query(`INSERT INTO token_ratios (model, ratio, updated_at) VALUES ($1, $2, now())
183
+ ON CONFLICT (model) DO UPDATE SET ratio = EXCLUDED.ratio, updated_at = now()`, [model, ratio]);
184
+ },
185
+ async getMcpNetworkPolicy() {
186
+ return readSetting(conn, 'mcpNetworkPolicy');
187
+ },
188
+ async setMcpNetworkPolicy(policy) {
189
+ await writeSetting(conn, 'mcpNetworkPolicy', policy);
190
+ },
191
+ async getEgressPolicy(scope) {
192
+ const all = await readSetting(conn, 'egress');
193
+ return all?.[scope];
194
+ },
195
+ async setEgressPolicy(scope, policy) {
196
+ const all = (await readSetting(conn, 'egress')) ?? {};
197
+ await writeSetting(conn, 'egress', { ...all, [scope]: policy });
198
+ },
199
+ async clearEgressPolicy(scope) {
200
+ const all = await readSetting(conn, 'egress');
201
+ if (!all)
202
+ return;
203
+ const next = { ...all };
204
+ delete next[scope];
205
+ if (Object.keys(next).length > 0)
206
+ await writeSetting(conn, 'egress', next);
207
+ else
208
+ await deleteSetting(conn, 'egress');
209
+ },
210
+ async clearMcpNetworkPolicy() {
211
+ await deleteSetting(conn, 'mcpNetworkPolicy');
212
+ },
213
+ async getDefaultAgent() {
214
+ return readSetting(conn, 'defaultAgent');
215
+ },
216
+ async setDefaultAgent(id) {
217
+ await writeSetting(conn, 'defaultAgent', id);
218
+ },
219
+ async clearDefaultAgent() {
220
+ await deleteSetting(conn, 'defaultAgent');
221
+ },
222
+ async getDefaultModel() {
223
+ return readSetting(conn, 'defaultModel');
224
+ },
225
+ async setDefaultModel(pair) {
226
+ await writeSetting(conn, 'defaultModel', pair);
227
+ },
228
+ async clearDefaultModel() {
229
+ await deleteSetting(conn, 'defaultModel');
230
+ },
231
+ async getWorkspacePolicy() {
232
+ return readSetting(conn, 'workspacePolicy');
233
+ },
234
+ async setWorkspacePolicy(policy) {
235
+ await writeSetting(conn, 'workspacePolicy', policy);
236
+ },
237
+ async clearWorkspacePolicy() {
238
+ await deleteSetting(conn, 'workspacePolicy');
239
+ },
240
+ async getEvents() {
241
+ return (await readSetting(conn, 'events')) ?? {};
242
+ },
243
+ async setEvents(config) {
244
+ await writeSetting(conn, 'events', config);
245
+ },
246
+ async clearEvents() {
247
+ await deleteSetting(conn, 'events');
248
+ },
249
+ async getDecision() {
250
+ return (await readSetting(conn, 'decision')) ?? {};
251
+ },
252
+ async setDecision(config) {
253
+ await writeSetting(conn, 'decision', config);
254
+ },
255
+ async clearDecision() {
256
+ await deleteSetting(conn, 'decision');
257
+ },
258
+ async getMetrics() {
259
+ return (await readSetting(conn, 'metrics')) ?? {};
260
+ },
261
+ async setMetrics(config) {
262
+ await writeSetting(conn, 'metrics', config);
263
+ },
264
+ async clearMetrics() {
265
+ await deleteSetting(conn, 'metrics');
266
+ },
267
+ async getPlugins() {
268
+ return (await readSetting(conn, 'plugins')) ?? {};
269
+ },
270
+ async setPlugins(config) {
271
+ await writeSetting(conn, 'plugins', config);
272
+ },
273
+ async clearPlugins() {
274
+ await deleteSetting(conn, 'plugins');
275
+ },
276
+ async getProxySettings() {
277
+ return readSetting(conn, 'proxy');
278
+ },
279
+ async setProxySettings(config) {
280
+ await writeSetting(conn, 'proxy', config);
281
+ },
282
+ async clearProxySettings() {
283
+ await deleteSetting(conn, 'proxy');
284
+ },
285
+ async getAttachments() {
286
+ return (await readSetting(conn, 'attachments')) ?? {};
287
+ },
288
+ async setAttachments(config) {
289
+ await writeSetting(conn, 'attachments', config);
290
+ },
291
+ async clearAttachments() {
292
+ await deleteSetting(conn, 'attachments');
293
+ },
294
+ };
295
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Общие утилиты группы портов `principals` PostgreSQL-драйвера
3
+ * (ADR-097, волна 3b).
4
+ *
5
+ * Драйвер объявляет `@itphx/synth-shared` обычной зависимостью, поэтому доменные
6
+ * типы сущностей берутся из неё напрямую (алиасы — для читаемости портов).
7
+ * Значения `jsonb`/`timestamptz` преобразуются здесь, чтобы все порты группы
8
+ * работали единообразно:
9
+ * - `jsonb` пишется явной JSON-строкой (`pg` иначе превратил бы JS-массив в
10
+ * Postgres-массив) с приведением `$n::jsonb`;
11
+ * - `timestamptz` читается как `Date` (`pg` парсит его в `Date`) и отдаётся
12
+ * домену ISO-строкой — как в файловой реализации (JSON round-trip).
13
+ */
14
+ import type { ExternalIdentity, ProfileData, Project } from '@itphx/synth-shared';
15
+ import type { PostgresExecutor } from '../pool.js';
16
+ /** Доменный проект. */
17
+ export type ProjectEntity = Project;
18
+ /** Доменный профиль. */
19
+ export type ProfileEntity = ProfileData;
20
+ /** Внешняя идентичность профиля (ADR-089). */
21
+ export type ExternalIdentityEntity = ExternalIdentity;
22
+ /** `timestamptz` (`Date` из `pg`) → ISO-строка; `NULL`/`undefined` → `undefined`. */
23
+ export declare function toIso(value: unknown): string | undefined;
24
+ /** `timestamptz NOT NULL` → ISO-строка (отсутствие — пустая строка, не бросаем). */
25
+ export declare function requiredIso(value: unknown): string;
26
+ /** Значение `jsonb`-параметра: JSON-строка либо `null` (NUL — вычищены). */
27
+ export declare function jsonbParam(value: unknown): string | null;
28
+ /** Прочитать `jsonb`-значение ключа таблицы `settings`. */
29
+ export declare function readSetting<T>(exec: PostgresExecutor, key: string): Promise<T | undefined>;
30
+ /** Записать (upsert) `jsonb`-значение ключа таблицы `settings`. */
31
+ export declare function writeSetting(exec: PostgresExecutor, key: string, value: unknown): Promise<void>;
32
+ /** Удалить ключ таблицы `settings` (отсутствие — не ошибка). */
33
+ export declare function deleteSetting(exec: PostgresExecutor, key: string): Promise<void>;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Общие утилиты группы портов `principals` PostgreSQL-драйвера
3
+ * (ADR-097, волна 3b).
4
+ *
5
+ * Драйвер объявляет `@itphx/synth-shared` обычной зависимостью, поэтому доменные
6
+ * типы сущностей берутся из неё напрямую (алиасы — для читаемости портов).
7
+ * Значения `jsonb`/`timestamptz` преобразуются здесь, чтобы все порты группы
8
+ * работали единообразно:
9
+ * - `jsonb` пишется явной JSON-строкой (`pg` иначе превратил бы JS-массив в
10
+ * Postgres-массив) с приведением `$n::jsonb`;
11
+ * - `timestamptz` читается как `Date` (`pg` парсит его в `Date`) и отдаётся
12
+ * домену ISO-строкой — как в файловой реализации (JSON round-trip).
13
+ */
14
+ import { jsonbParam as serializeJsonbParam } from '../json-param.js';
15
+ /** `timestamptz` (`Date` из `pg`) → ISO-строка; `NULL`/`undefined` → `undefined`. */
16
+ export function toIso(value) {
17
+ if (value === null || value === undefined)
18
+ return undefined;
19
+ if (value instanceof Date)
20
+ return value.toISOString();
21
+ return String(value);
22
+ }
23
+ /** `timestamptz NOT NULL` → ISO-строка (отсутствие — пустая строка, не бросаем). */
24
+ export function requiredIso(value) {
25
+ return toIso(value) ?? '';
26
+ }
27
+ /** Значение `jsonb`-параметра: JSON-строка либо `null` (NUL — вычищены). */
28
+ export function jsonbParam(value) {
29
+ return serializeJsonbParam(value);
30
+ }
31
+ /** Прочитать `jsonb`-значение ключа таблицы `settings`. */
32
+ export async function readSetting(exec, key) {
33
+ const rows = await exec.query('SELECT value FROM settings WHERE key = $1', [key]);
34
+ return rows[0]?.value;
35
+ }
36
+ /** Записать (upsert) `jsonb`-значение ключа таблицы `settings`. */
37
+ export async function writeSetting(exec, key, value) {
38
+ await exec.query(`INSERT INTO settings (key, value, updated_at) VALUES ($1, $2::jsonb, now())
39
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, [key, jsonbParam(value)]);
40
+ }
41
+ /** Удалить ключ таблицы `settings` (отсутствие — не ошибка). */
42
+ export async function deleteSetting(exec, key) {
43
+ await exec.query('DELETE FROM settings WHERE key = $1', [key]);
44
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Группа портов **принципалов и конфигурации** PostgreSQL-драйвера
3
+ * (ADR-097, волна 3b).
4
+ *
5
+ * Владелец файла — один агент волны реализации; правит `principals.ts` и
6
+ * `principals-*.ts`. Файл экспортирует единственную фабрику
7
+ * `buildPrincipalPorts(deps)`, возвращающую свою часть `StorageContext`:
8
+ * `projects`, `profiles`, `settings`, `defaults`, `providers`, `models`,
9
+ * `agents`.
10
+ *
11
+ * Реализация разложена по файлам (по одному ответственному порту/семейству):
12
+ * - `principals-projects.ts` → `projects` (projects + project_members);
13
+ * - `principals-profiles.ts` → `profiles` (profiles + profile_identities);
14
+ * - `principals-settings.ts` → `settings` (settings + token_ratios +
15
+ * migration_markers);
16
+ * - `principals-defaults.ts` → `defaults` (ключ в `settings`);
17
+ * - `principals-documents.ts` → `providers`/`models`/`agents` (documents).
18
+ *
19
+ * `deps.dataDir` этим портам не нужен: всё состояние — в БД (секции/документы),
20
+ * файловых путей у группы нет. Контракты — `packages/core/src/storage/contract/*`.
21
+ */
22
+ import type { StorageContext } from '@itphx/synth-core';
23
+ import type { PortDeps } from './deps.js';
24
+ /** Часть `StorageContext`, которой владеет группа `principals`. */
25
+ export type PrincipalPorts = Pick<StorageContext, 'projects' | 'profiles' | 'settings' | 'defaults' | 'providers' | 'models' | 'agents'>;
26
+ /** Собрать порты группы `principals`. */
27
+ export declare function buildPrincipalPorts(deps: PortDeps): PrincipalPorts;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Группа портов **принципалов и конфигурации** PostgreSQL-драйвера
3
+ * (ADR-097, волна 3b).
4
+ *
5
+ * Владелец файла — один агент волны реализации; правит `principals.ts` и
6
+ * `principals-*.ts`. Файл экспортирует единственную фабрику
7
+ * `buildPrincipalPorts(deps)`, возвращающую свою часть `StorageContext`:
8
+ * `projects`, `profiles`, `settings`, `defaults`, `providers`, `models`,
9
+ * `agents`.
10
+ *
11
+ * Реализация разложена по файлам (по одному ответственному порту/семейству):
12
+ * - `principals-projects.ts` → `projects` (projects + project_members);
13
+ * - `principals-profiles.ts` → `profiles` (profiles + profile_identities);
14
+ * - `principals-settings.ts` → `settings` (settings + token_ratios +
15
+ * migration_markers);
16
+ * - `principals-defaults.ts` → `defaults` (ключ в `settings`);
17
+ * - `principals-documents.ts` → `providers`/`models`/`agents` (documents).
18
+ *
19
+ * `deps.dataDir` этим портам не нужен: всё состояние — в БД (секции/документы),
20
+ * файловых путей у группы нет. Контракты — `packages/core/src/storage/contract/*`.
21
+ */
22
+ import { createDocumentPort, } from './principals-documents.js';
23
+ import { createPrincipalDefaultsPort } from './principals-defaults.js';
24
+ import { createPrincipalProfilesPort } from './principals-profiles.js';
25
+ import { createPrincipalProjectsPort } from './principals-projects.js';
26
+ import { createPrincipalSettingsPort } from './principals-settings.js';
27
+ /** Собрать порты группы `principals`. */
28
+ export function buildPrincipalPorts(deps) {
29
+ const { connection } = deps;
30
+ return {
31
+ projects: createPrincipalProjectsPort(connection),
32
+ profiles: createPrincipalProfilesPort(connection),
33
+ settings: createPrincipalSettingsPort(connection),
34
+ defaults: createPrincipalDefaultsPort(connection),
35
+ providers: createDocumentPort(connection, 'provider'),
36
+ models: createDocumentPort(connection, 'model'),
37
+ agents: createDocumentPort(connection, 'agent'),
38
+ };
39
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * PG-реализация порта **вопросов пользователю** (этап 1 roadmap 0.13 — блок 1.3,
3
+ * ADR-097).
4
+ *
5
+ * Таблица `questions` (миграция 021): состав вопросов и ответы — `jsonb`,
6
+ * выборки — по сессии и статусу, порядок — «свежие первыми»
7
+ * (`created_at` убыв., тайбрейкер `id`).
8
+ *
9
+ * Семантика повторяет файловые реализации core (`FileQuestionStore`) и
10
+ * in-memory (`MemoryQuestionRepository`):
11
+ * - upsert по `id`: `created_at` не перезаписывается, `updated_at` — метка
12
+ * вызывающего (драйвер не подставляет «сейчас» — иначе retention-очистка по
13
+ * метке записи теряла бы смысл);
14
+ * - `prune` — **только терминальные** статусы (`answered`/`cancelled`), метка
15
+ * которых строго старше отсечки (`updated_at < $1`).
16
+ *
17
+ * Драйвер не тянет core рантаймом (только `import type`), поэтому потолок
18
+ * выборки и правила timestamps повторены здесь локально — как в
19
+ * `ports/pipelines.ts`.
20
+ */
21
+ import type { QuestionRepository, StorageContext } from '@itphx/synth-core';
22
+ import type { QuestionRecord, QuestionStatus } from '@itphx/synth-shared';
23
+ import type { PortDeps } from './deps.js';
24
+ /** Часть `StorageContext`, которой владеет группа «вопросы/фоны». */
25
+ export type QuestionPorts = Pick<StorageContext, 'questions'>;
26
+ /** Порт вопросов пользователю поверх таблицы `questions`. */
27
+ export declare class PgQuestionRepository implements QuestionRepository {
28
+ private readonly _deps;
29
+ constructor(_deps: PortDeps);
30
+ save(record: QuestionRecord): Promise<void>;
31
+ get(id: string): Promise<QuestionRecord | null>;
32
+ list(filter?: {
33
+ sessionId?: string;
34
+ status?: QuestionStatus;
35
+ limit?: number;
36
+ }): Promise<QuestionRecord[]>;
37
+ prune(before: string): Promise<number>;
38
+ }
39
+ /** Собрать порты группы «вопросы» (этап 1 roadmap 0.13, блок 1.3). */
40
+ export declare function buildQuestionPorts(deps: PortDeps): QuestionPorts;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * PG-реализация порта **вопросов пользователю** (этап 1 roadmap 0.13 — блок 1.3,
3
+ * ADR-097).
4
+ *
5
+ * Таблица `questions` (миграция 021): состав вопросов и ответы — `jsonb`,
6
+ * выборки — по сессии и статусу, порядок — «свежие первыми»
7
+ * (`created_at` убыв., тайбрейкер `id`).
8
+ *
9
+ * Семантика повторяет файловые реализации core (`FileQuestionStore`) и
10
+ * in-memory (`MemoryQuestionRepository`):
11
+ * - upsert по `id`: `created_at` не перезаписывается, `updated_at` — метка
12
+ * вызывающего (драйвер не подставляет «сейчас» — иначе retention-очистка по
13
+ * метке записи теряла бы смысл);
14
+ * - `prune` — **только терминальные** статусы (`answered`/`cancelled`), метка
15
+ * которых строго старше отсечки (`updated_at < $1`).
16
+ *
17
+ * Драйвер не тянет core рантаймом (только `import type`), поэтому потолок
18
+ * выборки и правила timestamps повторены здесь локально — как в
19
+ * `ports/pipelines.ts`.
20
+ */
21
+ import { jsonbParam } from '../json-param.js';
22
+ import { compact, toIso, toIsoRequired } from './events-core.js';
23
+ // ── Локальные реплики core-хелперов (core рантаймом не тянем) ────────────────
24
+ /** Дефолтный потолок выборки (паритет с core `COLLECTION_LIMIT_DEFAULT`). */
25
+ const LIST_DEFAULT_LIMIT = 100;
26
+ /** Абсолютный потолок выборки (паритет с core `COLLECTION_LIMIT_MAX`). */
27
+ const LIST_MAX_LIMIT = 1000;
28
+ /** Привести `limit` к допустимому виду: дефолт 100, потолок 1000. */
29
+ function resolveLimit(limit) {
30
+ if (limit === undefined || !Number.isFinite(limit) || limit <= 0)
31
+ return LIST_DEFAULT_LIMIT;
32
+ return Math.min(Math.floor(limit), LIST_MAX_LIMIT);
33
+ }
34
+ /** Терминальные статусы вопроса (очищаемые; `pending` — не терминальный). */
35
+ const TERMINAL_STATUSES = ['answered', 'cancelled'];
36
+ /** Запись вопроса из колонок. */
37
+ function toQuestion(row) {
38
+ return compact({
39
+ id: row.id,
40
+ sessionId: row.session_id,
41
+ turnId: row.turn_id ?? undefined,
42
+ toolCallId: row.tool_call_id ?? undefined,
43
+ agentRole: row.agent_role ?? undefined,
44
+ questions: (row.questions ?? []),
45
+ status: row.status,
46
+ answers: (row.answers ?? undefined),
47
+ createdAt: toIsoRequired(row.created_at),
48
+ updatedAt: toIsoRequired(row.updated_at),
49
+ expiresAt: toIso(row.expires_at),
50
+ answeredAt: toIso(row.answered_at),
51
+ cancelledAt: toIso(row.cancelled_at),
52
+ cancelReason: row.cancel_reason ?? undefined,
53
+ answeredBy: row.answered_by ?? undefined,
54
+ });
55
+ }
56
+ /** Порт вопросов пользователю поверх таблицы `questions`. */
57
+ export class PgQuestionRepository {
58
+ _deps;
59
+ constructor(_deps) {
60
+ this._deps = _deps;
61
+ }
62
+ async save(record) {
63
+ await this._deps.connection.query(`INSERT INTO questions
64
+ (id, session_id, turn_id, tool_call_id, agent_role, questions, status, answers,
65
+ created_at, updated_at, expires_at, answered_at, cancelled_at, cancel_reason, answered_by)
66
+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8::jsonb, $9::timestamptz,
67
+ $10::timestamptz, $11::timestamptz, $12::timestamptz, $13::timestamptz, $14, $15)
68
+ ON CONFLICT (id) DO UPDATE SET
69
+ session_id = EXCLUDED.session_id,
70
+ turn_id = EXCLUDED.turn_id,
71
+ tool_call_id = EXCLUDED.tool_call_id,
72
+ agent_role = EXCLUDED.agent_role,
73
+ questions = EXCLUDED.questions,
74
+ status = EXCLUDED.status,
75
+ answers = EXCLUDED.answers,
76
+ created_at = questions.created_at,
77
+ updated_at = EXCLUDED.updated_at,
78
+ expires_at = EXCLUDED.expires_at,
79
+ answered_at = EXCLUDED.answered_at,
80
+ cancelled_at = EXCLUDED.cancelled_at,
81
+ cancel_reason = EXCLUDED.cancel_reason,
82
+ answered_by = EXCLUDED.answered_by`, [
83
+ record.id,
84
+ record.sessionId,
85
+ record.turnId ?? null,
86
+ record.toolCallId ?? null,
87
+ record.agentRole ?? null,
88
+ jsonbParam(record.questions),
89
+ record.status,
90
+ record.answers !== undefined ? jsonbParam(record.answers) : null,
91
+ record.createdAt,
92
+ record.updatedAt,
93
+ record.expiresAt ?? null,
94
+ record.answeredAt ?? null,
95
+ record.cancelledAt ?? null,
96
+ record.cancelReason ?? null,
97
+ record.answeredBy ?? null,
98
+ ]);
99
+ }
100
+ async get(id) {
101
+ const rows = await this._deps.connection.query('SELECT * FROM questions WHERE id = $1 LIMIT 1', [id]);
102
+ return rows[0] ? toQuestion(rows[0]) : null;
103
+ }
104
+ async list(filter) {
105
+ const params = [];
106
+ const where = [];
107
+ if (filter?.sessionId !== undefined) {
108
+ params.push(filter.sessionId);
109
+ where.push(`session_id = $${params.length}`);
110
+ }
111
+ if (filter?.status !== undefined) {
112
+ params.push(filter.status);
113
+ where.push(`status = $${params.length}`);
114
+ }
115
+ params.push(resolveLimit(filter?.limit));
116
+ const sql = 'SELECT * FROM questions' +
117
+ (where.length ? ` WHERE ${where.join(' AND ')}` : '') +
118
+ ' ORDER BY created_at DESC, id ASC' +
119
+ ` LIMIT $${params.length}`;
120
+ const rows = await this._deps.connection.query(sql, params);
121
+ return rows.map(toQuestion);
122
+ }
123
+ async prune(before) {
124
+ const rows = await this._deps.connection.query(`DELETE FROM questions
125
+ WHERE status = ANY($1::text[]) AND updated_at < $2::timestamptz
126
+ RETURNING id`, [[...TERMINAL_STATUSES], before]);
127
+ return rows.length;
128
+ }
129
+ }
130
+ /** Собрать порты группы «вопросы» (этап 1 roadmap 0.13, блок 1.3). */
131
+ export function buildQuestionPorts(deps) {
132
+ return {
133
+ questions: new PgQuestionRepository(deps),
134
+ };
135
+ }