@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,243 @@
1
+ /**
2
+ * Порт роллапов аналитики PostgreSQL-драйвера (ADR-102).
3
+ *
4
+ * Таблица `analytics_rollups` (миграция 003): ключ бакета — составной первичный
5
+ * ключ `(family, day, dimensions)` (`jsonb` нормализует порядок ключей объекта,
6
+ * поэтому равенство измерений устойчиво и годится для btree-равенства; отдельный
7
+ * `dimensions_key` не нужен). `measures`/`cost_by_currency` — `jsonb`-словари
8
+ * чисел (`cost_by_currency` пустая → `NULL`).
9
+ *
10
+ * `increment` — атомарный upsert `INSERT … ON CONFLICT (family, day, dimensions)
11
+ * DO UPDATE` с суммированием `measures`/`cost_by_currency` прямо в SQL (jsonb →
12
+ * `jsonb_each_text` → `SUM` → `jsonb_object_agg`); advisory-локи не нужны —
13
+ * конкурентные инкременты сериализуются конфликтом уникального ключа. `set` —
14
+ * точная перезапись полей из `EXCLUDED`.
15
+ *
16
+ * Семантика нормализации/сложения/агрегации повторяет общий core-хелпер
17
+ * (`analytics-rollup-helpers.ts`): драйвер не тянет core рантаймом (только
18
+ * `import type`), поэтому фильтр по семейству/периоду выполняется в SQL, а
19
+ * группировка `groupBy` и слияние мер — локальной точной репликой хелпера.
20
+ */
21
+ import { jsonbParam } from '../json-param.js';
22
+ // ────────────────────────────────────────────────────────────────────────────
23
+ // Локальная реплика `packages/core/src/storage/analytics-rollup-helpers.ts`
24
+ // (core не тянется рантаймом; поведение обязано совпадать с memory/file).
25
+ // ────────────────────────────────────────────────────────────────────────────
26
+ function isFiniteNumber(value) {
27
+ return typeof value === 'number' && Number.isFinite(value);
28
+ }
29
+ /** Оставить только finite-числа (NaN/Infinity — мусор). */
30
+ function normalizeNumberMap(input) {
31
+ const out = {};
32
+ if (!input)
33
+ return out;
34
+ for (const [key, value] of Object.entries(input)) {
35
+ if (isFiniteNumber(value))
36
+ out[key] = value;
37
+ }
38
+ return out;
39
+ }
40
+ /**
41
+ * Нормализовать бакет: в измерениях — только строки, в мерах — только
42
+ * finite-числа; пустая разбивка по валютам опускается (поле не задаётся).
43
+ */
44
+ function normalizeBucket(bucket) {
45
+ const dimensions = {};
46
+ for (const [key, value] of Object.entries(bucket.dimensions ?? {})) {
47
+ if (typeof value === 'string')
48
+ dimensions[key] = value;
49
+ }
50
+ const normalized = {
51
+ family: bucket.family,
52
+ day: bucket.day,
53
+ dimensions,
54
+ measures: normalizeNumberMap(bucket.measures),
55
+ };
56
+ const costByCurrency = normalizeNumberMap(bucket.costByCurrency);
57
+ if (Object.keys(costByCurrency).length > 0)
58
+ normalized.costByCurrency = costByCurrency;
59
+ return normalized;
60
+ }
61
+ /** Отсортированные пары осей — устойчивый порядок (устойчив к `&`/`=` в значениях). */
62
+ function sortedDimensionPairs(dimensions) {
63
+ return Object.entries(dimensions).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
64
+ }
65
+ /** Значение оси бакета (`day` — отдельным полем, прочие — из `dimensions`). */
66
+ function axisValue(bucket, axis) {
67
+ return axis === 'day' ? bucket.day : bucket.dimensions[axis];
68
+ }
69
+ /** Подходит ли бакет под фильтры (семейство, период включительно, оси по равенству). */
70
+ function matchesQuery(bucket, query) {
71
+ if (bucket.family !== query.family)
72
+ return false;
73
+ if (query.from !== undefined && bucket.day < query.from)
74
+ return false;
75
+ if (query.to !== undefined && bucket.day > query.to)
76
+ return false;
77
+ if (query.dimensions) {
78
+ for (const [axis, expected] of Object.entries(query.dimensions)) {
79
+ if (expected === undefined)
80
+ continue;
81
+ if (axisValue(bucket, axis) !== expected)
82
+ return false;
83
+ }
84
+ }
85
+ return true;
86
+ }
87
+ /** Детерминированный порядок строк: лексикографически по осям группировки. */
88
+ function compareRows(a, b, axes) {
89
+ for (const axis of axes) {
90
+ const av = a.dimensions[axis] ?? '';
91
+ const bv = b.dimensions[axis] ?? '';
92
+ if (av !== bv)
93
+ return av < bv ? -1 : 1;
94
+ }
95
+ return 0;
96
+ }
97
+ /** Агрегировать бакеты по `groupBy` (пусто — одна итоговая строка). */
98
+ function aggregateRollups(buckets, query) {
99
+ const groupBy = query.groupBy ?? [];
100
+ const groups = new Map();
101
+ for (const bucket of buckets) {
102
+ if (!matchesQuery(bucket, query))
103
+ continue;
104
+ const dimensions = {};
105
+ for (const axis of groupBy) {
106
+ const value = axisValue(bucket, axis);
107
+ if (value !== undefined)
108
+ dimensions[axis] = value;
109
+ }
110
+ const key = JSON.stringify(sortedDimensionPairs(dimensions));
111
+ let row = groups.get(key);
112
+ if (!row) {
113
+ row = { dimensions, measures: {} };
114
+ groups.set(key, row);
115
+ }
116
+ for (const [measure, value] of Object.entries(bucket.measures)) {
117
+ row.measures[measure] = (row.measures[measure] ?? 0) + value;
118
+ }
119
+ if (bucket.costByCurrency) {
120
+ const merged = row.costByCurrency ?? {};
121
+ for (const [currency, value] of Object.entries(bucket.costByCurrency)) {
122
+ merged[currency] = (merged[currency] ?? 0) + value;
123
+ }
124
+ if (Object.keys(merged).length > 0)
125
+ row.costByCurrency = merged;
126
+ }
127
+ }
128
+ const rows = [...groups.values()];
129
+ for (const row of rows) {
130
+ if (row.costByCurrency && Object.keys(row.costByCurrency).length === 0)
131
+ delete row.costByCurrency;
132
+ }
133
+ rows.sort((a, b) => compareRows(a, b, groupBy));
134
+ return rows;
135
+ }
136
+ // ────────────────────────────────────────────────────────────────────────────
137
+ // Чтение строк БД → бакет
138
+ // ────────────────────────────────────────────────────────────────────────────
139
+ function rowToBucket(row) {
140
+ const bucket = {
141
+ family: String(row.family),
142
+ day: String(row.day),
143
+ dimensions: (row.dimensions ?? {}),
144
+ measures: (row.measures ?? {}),
145
+ };
146
+ if (row.cost_by_currency !== null && row.cost_by_currency !== undefined) {
147
+ bucket.costByCurrency = row.cost_by_currency;
148
+ }
149
+ return bucket;
150
+ }
151
+ /** Параметры записи бакета: family/day + нормализованные jsonb-словари. */
152
+ function bucketParams(bucket) {
153
+ const normalized = normalizeBucket(bucket);
154
+ return [
155
+ normalized.family,
156
+ normalized.day,
157
+ jsonbParam(normalized.dimensions),
158
+ jsonbParam(normalized.measures),
159
+ normalized.costByCurrency ? jsonbParam(normalized.costByCurrency) : null,
160
+ ];
161
+ }
162
+ /**
163
+ * `jsonb_object_agg` сумм (`SUM`) с `COALESCE` для пустого набора строк
164
+ * (нет ни одной меры) → `'{}'::jsonb`.
165
+ */
166
+ const SQL_SUM_MEASURES = `COALESCE(jsonb_object_agg(key, total), '{}'::jsonb)`;
167
+ const SQL_EACH_SUM = `SELECT key, SUM(value::numeric) AS total
168
+ FROM (%ROWS%) AS merged
169
+ GROUP BY key`;
170
+ /** Слитый `measures` при инкременте: сумма по ключам существующих и новых мер. */
171
+ const INCREMENT_SQL = `
172
+ INSERT INTO analytics_rollups (family, day, dimensions, measures, cost_by_currency)
173
+ VALUES ($1, $2, $3::jsonb, $4::jsonb, $5::jsonb)
174
+ ON CONFLICT (family, day, dimensions) DO UPDATE SET
175
+ measures = (
176
+ SELECT ${SQL_SUM_MEASURES}
177
+ FROM (${SQL_EACH_SUM.replace('%ROWS%', `SELECT key, value FROM jsonb_each_text(analytics_rollups.measures)
178
+ UNION ALL
179
+ SELECT key, value FROM jsonb_each_text(EXCLUDED.measures)`)}) AS summed
180
+ ),
181
+ cost_by_currency = CASE
182
+ WHEN COALESCE(analytics_rollups.cost_by_currency, '{}'::jsonb) = '{}'::jsonb
183
+ AND COALESCE(EXCLUDED.cost_by_currency, '{}'::jsonb) = '{}'::jsonb
184
+ THEN NULL
185
+ ELSE (
186
+ SELECT ${SQL_SUM_MEASURES}
187
+ FROM (${SQL_EACH_SUM.replace('%ROWS%', `SELECT key, value FROM jsonb_each_text(COALESCE(analytics_rollups.cost_by_currency, '{}'::jsonb))
188
+ UNION ALL
189
+ SELECT key, value FROM jsonb_each_text(COALESCE(EXCLUDED.cost_by_currency, '{}'::jsonb))`)}) AS summed
190
+ )
191
+ END`;
192
+ /** Точная перезапись бакета по ключу (`set`). */
193
+ const SET_SQL = `
194
+ INSERT INTO analytics_rollups (family, day, dimensions, measures, cost_by_currency)
195
+ VALUES ($1, $2, $3::jsonb, $4::jsonb, $5::jsonb)
196
+ ON CONFLICT (family, day, dimensions) DO UPDATE SET
197
+ measures = EXCLUDED.measures,
198
+ cost_by_currency = EXCLUDED.cost_by_currency`;
199
+ /** Порт пред-агрегированных суточных роллапов аналитики поверх SQL. */
200
+ class PostgresAnalyticsRollupRepository {
201
+ _deps;
202
+ constructor(_deps) {
203
+ this._deps = _deps;
204
+ }
205
+ _db() {
206
+ return this._deps.connection;
207
+ }
208
+ async increment(bucket) {
209
+ await this._db().query(INCREMENT_SQL, bucketParams(bucket));
210
+ }
211
+ async set(bucket) {
212
+ await this._db().query(SET_SQL, bucketParams(bucket));
213
+ }
214
+ async query(query) {
215
+ const params = [query.family];
216
+ let where = 'family = $1';
217
+ if (query.from !== undefined) {
218
+ params.push(query.from);
219
+ where += ` AND day >= $${params.length}`;
220
+ }
221
+ if (query.to !== undefined) {
222
+ params.push(query.to);
223
+ where += ` AND day <= $${params.length}`;
224
+ }
225
+ const rows = await this._db().query(`SELECT family, day, dimensions, measures, cost_by_currency
226
+ FROM analytics_rollups WHERE ${where}`, params);
227
+ return aggregateRollups(rows.map(rowToBucket), query);
228
+ }
229
+ async prune(beforeDay) {
230
+ const rows = await this._db().query('WITH deleted AS (DELETE FROM analytics_rollups WHERE day < $1 RETURNING 1) SELECT count(*)::int AS n FROM deleted', [beforeDay]);
231
+ const value = rows[0]?.n;
232
+ return typeof value === 'number' ? value : Number(value) || 0;
233
+ }
234
+ async clear() {
235
+ const rows = await this._db().query('WITH deleted AS (DELETE FROM analytics_rollups RETURNING 1) SELECT count(*)::int AS n FROM deleted');
236
+ const value = rows[0]?.n;
237
+ return typeof value === 'number' ? value : Number(value) || 0;
238
+ }
239
+ }
240
+ /** Собрать порт роллапов аналитики. */
241
+ export function buildAnalyticsPorts(deps) {
242
+ return { analyticsRollups: new PostgresAnalyticsRollupRepository(deps) };
243
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Порты журналов безопасности PostgreSQL-драйвера (egress/ADR-071):
3
+ * `securityAudit` — аудит изменений egress/security-политик,
4
+ * `egressRequests` — журнал внешних запросов.
5
+ *
6
+ * Обе таблицы append-only (`seq bigserial` — порядок «свежие первыми»).
7
+ * `before`/`after` в security-аудите хранятся в JSONB (снимки политики могут быть
8
+ * `null`); журнал egress не содержит тел/заголовков.
9
+ */
10
+ import type { StorageContext } from '@itphx/synth-core';
11
+ import type { PortDeps } from './deps.js';
12
+ /** Часть `StorageContext`, которой владеет группа `audit`. */
13
+ export type AuditPorts = Pick<StorageContext, 'securityAudit' | 'egressRequests' | 'pluginAudit'>;
14
+ /** Собрать порты журналов безопасности. */
15
+ export declare function buildAuditPorts(deps: PortDeps): AuditPorts;
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Порты журналов безопасности PostgreSQL-драйвера (egress/ADR-071):
3
+ * `securityAudit` — аудит изменений egress/security-политик,
4
+ * `egressRequests` — журнал внешних запросов.
5
+ *
6
+ * Обе таблицы append-only (`seq bigserial` — порядок «свежие первыми»).
7
+ * `before`/`after` в security-аудите хранятся в JSONB (снимки политики могут быть
8
+ * `null`); журнал egress не содержит тел/заголовков.
9
+ */
10
+ import { jsonbLiteral } from '../json-param.js';
11
+ import { buildPluginAuditPorts } from './plugin-audit.js';
12
+ function toISO(value) {
13
+ if (value instanceof Date)
14
+ return value.toISOString();
15
+ return String(value);
16
+ }
17
+ function jsonParam(value) {
18
+ return jsonbLiteral(value ?? null);
19
+ }
20
+ function toNumber(value) {
21
+ if (value === null || value === undefined)
22
+ return undefined;
23
+ if (typeof value === 'number')
24
+ return value;
25
+ if (typeof value === 'string') {
26
+ const parsed = Number(value);
27
+ return Number.isFinite(parsed) ? parsed : undefined;
28
+ }
29
+ return undefined;
30
+ }
31
+ function securityRowToEntry(row) {
32
+ return {
33
+ id: row.id,
34
+ ts: toISO(row.ts),
35
+ actor: row.actor,
36
+ scope: row.scope,
37
+ action: row.action,
38
+ source: row.source,
39
+ before: row.before_jsonb ?? null,
40
+ after: row.after_jsonb ?? null,
41
+ version: typeof row.version === 'number' ? row.version : Number(row.version) || 1,
42
+ };
43
+ }
44
+ class PostgresSecurityAuditRepository {
45
+ _deps;
46
+ constructor(_deps) {
47
+ this._deps = _deps;
48
+ }
49
+ _db() {
50
+ return this._deps.connection;
51
+ }
52
+ async append(entry) {
53
+ await this._db().query(`INSERT INTO security_audit (id, ts, actor, scope, action, source, before_jsonb, after_jsonb, version)
54
+ VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8::jsonb,$9)`, [
55
+ entry.id,
56
+ entry.ts,
57
+ entry.actor,
58
+ entry.scope,
59
+ entry.action,
60
+ entry.source,
61
+ jsonParam(entry.before),
62
+ jsonParam(entry.after),
63
+ entry.version,
64
+ ]);
65
+ }
66
+ async list(opts = {}) {
67
+ const params = [];
68
+ let where = '';
69
+ if (opts.scope !== undefined) {
70
+ params.push(opts.scope);
71
+ where = `WHERE scope = $${params.length}`;
72
+ }
73
+ let limit = '';
74
+ if (opts.limit !== undefined && Number.isFinite(opts.limit) && opts.limit > 0) {
75
+ params.push(Math.floor(opts.limit));
76
+ limit = `LIMIT $${params.length}::int`;
77
+ }
78
+ const rows = await this._db().query(`SELECT * FROM security_audit ${where} ORDER BY seq DESC ${limit}`, params);
79
+ return rows.map(securityRowToEntry);
80
+ }
81
+ async clear() {
82
+ const rows = await this._db().query('WITH deleted AS (DELETE FROM security_audit RETURNING 1) SELECT count(*)::int AS n FROM deleted');
83
+ const value = rows[0]?.n;
84
+ return typeof value === 'number' ? value : Number(value) || 0;
85
+ }
86
+ }
87
+ function egressRowToEntry(row) {
88
+ const entry = {
89
+ id: row.id,
90
+ ts: toISO(row.ts),
91
+ scope: row.scope,
92
+ host: row.host,
93
+ url: row.url,
94
+ status: row.status,
95
+ };
96
+ if (row.method !== null)
97
+ entry.method = row.method;
98
+ if (row.via !== null)
99
+ entry.via = row.via;
100
+ if (row.http_status !== null)
101
+ entry.httpStatus = row.http_status;
102
+ const bytes = toNumber(row.bytes);
103
+ if (bytes !== undefined)
104
+ entry.bytes = bytes;
105
+ if (row.duration_ms !== null)
106
+ entry.durationMs = row.duration_ms;
107
+ if (row.reason !== null)
108
+ entry.reason = row.reason;
109
+ if (row.matched_rule !== null)
110
+ entry.matchedRule = row.matched_rule;
111
+ if (row.session_id !== null)
112
+ entry.sessionId = row.session_id;
113
+ if (row.project_id !== null)
114
+ entry.projectId = row.project_id;
115
+ if (row.actor !== null)
116
+ entry.actor = row.actor;
117
+ return entry;
118
+ }
119
+ class PostgresEgressRequestLogRepository {
120
+ _deps;
121
+ constructor(_deps) {
122
+ this._deps = _deps;
123
+ }
124
+ _db() {
125
+ return this._deps.connection;
126
+ }
127
+ async append(entry) {
128
+ await this._db().query(`INSERT INTO egress_requests
129
+ (id, ts, scope, host, url, method, status, via, http_status, bytes, duration_ms,
130
+ reason, matched_rule, session_id, project_id, actor)
131
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)`, [
132
+ entry.id,
133
+ entry.ts,
134
+ entry.scope,
135
+ entry.host,
136
+ entry.url,
137
+ entry.method ?? null,
138
+ entry.status,
139
+ entry.via ?? null,
140
+ entry.httpStatus ?? null,
141
+ entry.bytes ?? null,
142
+ entry.durationMs ?? null,
143
+ entry.reason ?? null,
144
+ entry.matchedRule ?? null,
145
+ entry.sessionId ?? null,
146
+ entry.projectId ?? null,
147
+ entry.actor ?? null,
148
+ ]);
149
+ }
150
+ async list(opts = {}) {
151
+ const params = [];
152
+ const clauses = [];
153
+ if (opts.scope !== undefined) {
154
+ params.push(opts.scope);
155
+ clauses.push(`scope = $${params.length}`);
156
+ }
157
+ if (opts.status !== undefined) {
158
+ params.push(opts.status);
159
+ clauses.push(`status = $${params.length}`);
160
+ }
161
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
162
+ let limit = '';
163
+ if (opts.limit !== undefined && Number.isFinite(opts.limit) && opts.limit > 0) {
164
+ params.push(Math.floor(opts.limit));
165
+ limit = `LIMIT $${params.length}::int`;
166
+ }
167
+ const rows = await this._db().query(`SELECT * FROM egress_requests ${where} ORDER BY seq DESC ${limit}`, params);
168
+ return rows.map(egressRowToEntry);
169
+ }
170
+ async prune(days) {
171
+ if (!Number.isFinite(days) || days <= 0)
172
+ return 0;
173
+ const cutoff = new Date(Date.now() - days * 24 * 3600_000).toISOString();
174
+ const rows = await this._db().query('WITH deleted AS (DELETE FROM egress_requests WHERE ts < $1 RETURNING 1) SELECT count(*)::int AS n FROM deleted', [cutoff]);
175
+ const value = rows[0]?.n;
176
+ return typeof value === 'number' ? value : Number(value) || 0;
177
+ }
178
+ async clear() {
179
+ const rows = await this._db().query('WITH deleted AS (DELETE FROM egress_requests RETURNING 1) SELECT count(*)::int AS n FROM deleted');
180
+ const value = rows[0]?.n;
181
+ return typeof value === 'number' ? value : Number(value) || 0;
182
+ }
183
+ }
184
+ /** Собрать порты журналов безопасности. */
185
+ export function buildAuditPorts(deps) {
186
+ return {
187
+ securityAudit: new PostgresSecurityAuditRepository(deps),
188
+ egressRequests: new PostgresEgressRequestLogRepository(deps),
189
+ // ADR-090: журнал аудита плагинов (отдельный порт, не security-аудит).
190
+ ...buildPluginAuditPorts(deps),
191
+ };
192
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Порты Authority-слоя PostgreSQL-драйвера (ADR-106 Ф0/Ф1, ADR-097).
3
+ *
4
+ * - `authority_policy` — политика полномочий **инстанса** (таблица из
5
+ * миграции 014): одна строка (`id = 'instance'`), документ — JSONB. «Политика
6
+ * не задана» (строк нет) и «политика задана и ничего не разрешает» (пустой
7
+ * документ) — **разные** состояния: первое означает «ось инстанса не
8
+ * применима», второе — «ось сужает до нуля». Чтение невалидного документа
9
+ * считается **отсутствием политики** (fail-closed на оси «user», а не
10
+ * «политика без грантов») — паритет с файловой реализацией core
11
+ * (`FileAuthorityPolicyStore`).
12
+ * - `authority_decisions` — append-only журнал решений (таблица из миграции
13
+ * 014; `seq bigserial` — порядок «свежие первыми», как у `security_audit`/
14
+ * `plugin_audit`).
15
+ *
16
+ * Политика и журнал — **отдельные** сущности: журнал фиксирует решения о
17
+ * правах, политика — потолок инстанса (ADR-106 §«Инварианты модели», п. 8).
18
+ *
19
+ * Драйвер не дублирует доменную валидацию: схема `authorityPolicySchema`
20
+ * берётся из `@itphx/synth-shared` (обычная зависимость пакета).
21
+ */
22
+ import type { StorageContext } from '@itphx/synth-core';
23
+ import type { PortDeps } from './deps.js';
24
+ /** Часть `StorageContext`, которой владеет модуль портов Authority-слоя. */
25
+ export type AuthorityPorts = Pick<StorageContext, 'authorityPolicy' | 'authorityDecisions'>;
26
+ /** Собрать порты Authority-слоя (ADR-106 Ф0/Ф1). */
27
+ export declare function buildAuthorityPorts(deps: PortDeps): AuthorityPorts;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Порты Authority-слоя PostgreSQL-драйвера (ADR-106 Ф0/Ф1, ADR-097).
3
+ *
4
+ * - `authority_policy` — политика полномочий **инстанса** (таблица из
5
+ * миграции 014): одна строка (`id = 'instance'`), документ — JSONB. «Политика
6
+ * не задана» (строк нет) и «политика задана и ничего не разрешает» (пустой
7
+ * документ) — **разные** состояния: первое означает «ось инстанса не
8
+ * применима», второе — «ось сужает до нуля». Чтение невалидного документа
9
+ * считается **отсутствием политики** (fail-closed на оси «user», а не
10
+ * «политика без грантов») — паритет с файловой реализацией core
11
+ * (`FileAuthorityPolicyStore`).
12
+ * - `authority_decisions` — append-only журнал решений (таблица из миграции
13
+ * 014; `seq bigserial` — порядок «свежие первыми», как у `security_audit`/
14
+ * `plugin_audit`).
15
+ *
16
+ * Политика и журнал — **отдельные** сущности: журнал фиксирует решения о
17
+ * правах, политика — потолок инстанса (ADR-106 §«Инварианты модели», п. 8).
18
+ *
19
+ * Драйвер не дублирует доменную валидацию: схема `authorityPolicySchema`
20
+ * берётся из `@itphx/synth-shared` (обычная зависимость пакета).
21
+ */
22
+ import { authorityPolicySchema, nowISO } from '@itphx/synth-shared';
23
+ import { jsonbLiteral } from '../json-param.js';
24
+ /** Ключ единственной строки политики инстанца. */
25
+ const AUTHORITY_POLICY_ROW_ID = 'instance';
26
+ /** ISO-строка из `timestamptz` (pg отдаёт `Date`) либо строки. */
27
+ function toISO(value) {
28
+ if (value instanceof Date)
29
+ return value.toISOString();
30
+ return String(value);
31
+ }
32
+ /** Порт политики полномочий инстанса поверх таблицы `authority_policy`. */
33
+ class PostgresAuthorityPolicyRepository {
34
+ _deps;
35
+ constructor(_deps) {
36
+ this._deps = _deps;
37
+ }
38
+ _db() {
39
+ return this._deps.connection;
40
+ }
41
+ /** Политика инстанца; `null` — документа нет или он невалиден. */
42
+ async getPolicy() {
43
+ const rows = await this._db().query('SELECT * FROM authority_policy WHERE id = $1', [AUTHORITY_POLICY_ROW_ID]);
44
+ const row = rows[0];
45
+ if (!row)
46
+ return null;
47
+ const parsed = authorityPolicySchema.safeParse(row.document);
48
+ if (!parsed.success) {
49
+ // Документ невалиден — политика считается незаданной (fail-closed на
50
+ // оси «user», а не «политика без грантов»).
51
+ console.warn(`[PostgresAuthorityPolicyRepository] документ политики Authority невалиден — считается отсутствующим: ${parsed.error.issues
52
+ .map((issue) => `${issue.path.join('.')}: ${issue.message}`)
53
+ .join('; ')}`);
54
+ return null;
55
+ }
56
+ return parsed.data;
57
+ }
58
+ /** Полная замена политики (атомарная upsert по ключу `instance`). */
59
+ async savePolicy(policy) {
60
+ const validated = authorityPolicySchema.parse(policy);
61
+ await this._db().query(`INSERT INTO authority_policy (id, document, updated_at)
62
+ VALUES ($1,$2::jsonb,$3)
63
+ ON CONFLICT (id) DO UPDATE
64
+ SET document = EXCLUDED.document, updated_at = EXCLUDED.updated_at`, [AUTHORITY_POLICY_ROW_ID, jsonbLiteral(validated), nowISO()]);
65
+ }
66
+ }
67
+ function rowToDecision(row) {
68
+ const entry = {
69
+ id: row.id,
70
+ ts: toISO(row.ts),
71
+ principal: row.principal,
72
+ action: row.action,
73
+ target: row.target,
74
+ effect: row.effect,
75
+ source: row.source,
76
+ reason: row.reason,
77
+ mode: (row.mode ?? 'shadow'),
78
+ };
79
+ // `permissionEffect` — только в shadow-режиме (в enforced — отсутствует).
80
+ if (row.permission_effect !== null && row.permission_effect !== undefined) {
81
+ entry.permissionEffect = row.permission_effect;
82
+ }
83
+ return entry;
84
+ }
85
+ /** Порт append-only журнала решений Authority-слоя поверх `authority_decisions`. */
86
+ class PostgresAuthorityDecisionJournal {
87
+ _deps;
88
+ constructor(_deps) {
89
+ this._deps = _deps;
90
+ }
91
+ _db() {
92
+ return this._deps.connection;
93
+ }
94
+ async append(entry) {
95
+ await this._db().query(`INSERT INTO authority_decisions
96
+ (id, ts, principal, action, target, effect, source, reason, mode, permission_effect)
97
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, [
98
+ entry.id,
99
+ entry.ts,
100
+ entry.principal,
101
+ entry.action,
102
+ entry.target,
103
+ entry.effect,
104
+ entry.source,
105
+ entry.reason ?? null,
106
+ entry.mode ?? 'shadow',
107
+ entry.permissionEffect ?? null,
108
+ ]);
109
+ }
110
+ /** Решения «свежие первыми»; фильтры `action`/`effect`/`source`, `limit` — последние N. */
111
+ async list(opts = {}) {
112
+ const params = [];
113
+ const clauses = [];
114
+ if (opts.action !== undefined) {
115
+ params.push(opts.action);
116
+ clauses.push(`action = $${params.length}`);
117
+ }
118
+ if (opts.effect !== undefined) {
119
+ params.push(opts.effect);
120
+ clauses.push(`effect = $${params.length}`);
121
+ }
122
+ if (opts.source !== undefined) {
123
+ params.push(opts.source);
124
+ clauses.push(`source = $${params.length}`);
125
+ }
126
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
127
+ let limit = '';
128
+ const { limit: requested } = opts;
129
+ if (requested !== undefined && Number.isFinite(requested) && requested > 0) {
130
+ params.push(Math.floor(requested));
131
+ limit = `LIMIT $${params.length}::int`;
132
+ }
133
+ const rows = await this._db().query(`SELECT * FROM authority_decisions ${where} ORDER BY seq DESC ${limit}`, params);
134
+ return rows.map(rowToDecision);
135
+ }
136
+ async clear() {
137
+ const rows = await this._db().query('WITH deleted AS (DELETE FROM authority_decisions RETURNING 1) SELECT count(*)::int AS n FROM deleted');
138
+ const value = rows[0]?.n;
139
+ return typeof value === 'number' ? value : Number(value) || 0;
140
+ }
141
+ }
142
+ /** Собрать порты Authority-слоя (ADR-106 Ф0/Ф1). */
143
+ export function buildAuthorityPorts(deps) {
144
+ return {
145
+ authorityPolicy: new PostgresAuthorityPolicyRepository(deps),
146
+ authorityDecisions: new PostgresAuthorityDecisionJournal(deps),
147
+ };
148
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * PG-реализация порта **единого реестра фоновых прогонов** (этап 1 roadmap 0.13
3
+ * — блок 1.2, ADR-097; PROP-096 — фоновые саб-агенты, PROP-097 — фоновые
4
+ * шелл-процессы).
5
+ *
6
+ * Таблица `background_runs` (миграция 021): вид, статус, владелец и параметры
7
+ * прогона; `metadata` — `jsonb`; лог процесса — относительный путь в
8
+ * BlobStore (`log_path`), сами логи остаются на диске (ФС-периметр вне портов,
9
+ * ADR-091/ADR-092). Идентификатор фонового процесса у порта исполнения
10
+ * (`process_id`, `proc_<uuid>`) — колонка миграции 022.
11
+ *
12
+ * Семантика повторяет файловые реализации core (`FileBackgroundRunStore`) и
13
+ * in-memory (`MemoryBackgroundRunRepository`):
14
+ * - upsert по `id`: `started_at` не перезаписывается, `updated_at` — метка
15
+ * вызывающего (драйвер не подставляет «сейчас» — иначе retention-очистка по
16
+ * метке записи теряла бы смысл);
17
+ * - список — «свежие первыми» (`started_at` убыв., тайбрейкер `id`), фильтры —
18
+ * по «И»;
19
+ * - `prune` — **только терминальные** статусы, метка которых строго старше
20
+ * отсечки (`updated_at < $2`); нетерминальный `running` не удаляется никогда.
21
+ *
22
+ * Драйвер не тянет core рантаймом (только `import type`), поэтому потолок
23
+ * выборки повторён здесь локально — как в `ports/pipelines.ts`.
24
+ */
25
+ import type { BackgroundRunRepository, StorageContext } from '@itphx/synth-core';
26
+ import type { BackgroundRunFilter, BackgroundRunRecord, BackgroundRunStatus } from '@itphx/synth-shared';
27
+ import type { PortDeps } from './deps.js';
28
+ /** Часть `StorageContext`, которой владеет группа «фоновые прогоны». */
29
+ export type BackgroundRunPorts = Pick<StorageContext, 'backgroundRuns'>;
30
+ /** Порт реестра фоновых прогонов поверх таблицы `background_runs`. */
31
+ export declare class PgBackgroundRunRepository implements BackgroundRunRepository {
32
+ private readonly _deps;
33
+ constructor(_deps: PortDeps);
34
+ save(record: BackgroundRunRecord): Promise<void>;
35
+ get(id: string): Promise<BackgroundRunRecord | null>;
36
+ list(filter?: BackgroundRunFilter): Promise<BackgroundRunRecord[]>;
37
+ remove(id: string): Promise<boolean>;
38
+ prune(before: string, statuses?: BackgroundRunStatus[]): Promise<number>;
39
+ }
40
+ /** Собрать порты группы «фоновые прогоны» (этап 1 roadmap 0.13, блок 1.2). */
41
+ export declare function buildBackgroundRunPorts(deps: PortDeps): BackgroundRunPorts;