@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,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Порт `defaults` (умолчания оформления) PostgreSQL-драйвера
|
|
3
|
+
* (ADR-097, волна 3b).
|
|
4
|
+
*
|
|
5
|
+
* Эталон семантики — `DefaultsStore`/`MemoryDefaultsRepository`: `loadDefaults`
|
|
6
|
+
* на пустом сторе — `{}`; `saveDefaults` — частичный патч, сливается поверх
|
|
7
|
+
* текущих значений; некорректные поля отбрасываются (санитизация). Санитизация
|
|
8
|
+
* воспроизводится локально: core не экспортирует хелпер, а поведение обязано
|
|
9
|
+
* совпадать с файловой реализацией.
|
|
10
|
+
*
|
|
11
|
+
* Хранение — ключ `defaults` в таблице `settings` (`jsonb`). Read-modify-write
|
|
12
|
+
* (как в файловой реализации) выполняется в транзакции с блокировкой строки.
|
|
13
|
+
*/
|
|
14
|
+
import type { StorageContext } from '@itphx/synth-core';
|
|
15
|
+
import type { PostgresConnection } from '../pool.js';
|
|
16
|
+
type DefaultsPort = StorageContext['defaults'];
|
|
17
|
+
/** Ключ секции умолчаний оформления в таблице `settings`. */
|
|
18
|
+
export declare const DEFAULTS_SETTINGS_KEY = "defaults";
|
|
19
|
+
/** Собрать порт умолчаний оформления поверх SQL. */
|
|
20
|
+
export declare function createPrincipalDefaultsPort(conn: PostgresConnection): DefaultsPort;
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Порт `defaults` (умолчания оформления) PostgreSQL-драйвера
|
|
3
|
+
* (ADR-097, волна 3b).
|
|
4
|
+
*
|
|
5
|
+
* Эталон семантики — `DefaultsStore`/`MemoryDefaultsRepository`: `loadDefaults`
|
|
6
|
+
* на пустом сторе — `{}`; `saveDefaults` — частичный патч, сливается поверх
|
|
7
|
+
* текущих значений; некорректные поля отбрасываются (санитизация). Санитизация
|
|
8
|
+
* воспроизводится локально: core не экспортирует хелпер, а поведение обязано
|
|
9
|
+
* совпадать с файловой реализацией.
|
|
10
|
+
*
|
|
11
|
+
* Хранение — ключ `defaults` в таблице `settings` (`jsonb`). Read-modify-write
|
|
12
|
+
* (как в файловой реализации) выполняется в транзакции с блокировкой строки.
|
|
13
|
+
*/
|
|
14
|
+
import { readSetting, writeSetting } from './principals-shared.js';
|
|
15
|
+
/** Ключ секции умолчаний оформления в таблице `settings`. */
|
|
16
|
+
export const DEFAULTS_SETTINGS_KEY = 'defaults';
|
|
17
|
+
/** Минимальный/максимальный допустимый масштаб интерфейса (паритет `DefaultsStore`). */
|
|
18
|
+
const UI_SCALE_MIN = 0.5;
|
|
19
|
+
const UI_SCALE_MAX = 1.2;
|
|
20
|
+
/** Масштаб интерфейса: число в диапазоне 0.5..1.2, иначе `undefined`. */
|
|
21
|
+
function sanitizeScale(value) {
|
|
22
|
+
if (typeof value === 'number' && Number.isFinite(value) && value >= UI_SCALE_MIN && value <= UI_SCALE_MAX) {
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
/** Оставить только валидные поля умолчаний оформления (паритет `DefaultsStore`). */
|
|
28
|
+
function sanitize(raw) {
|
|
29
|
+
if (typeof raw !== 'object' || raw === null)
|
|
30
|
+
return {};
|
|
31
|
+
const src = raw;
|
|
32
|
+
const out = {};
|
|
33
|
+
if (src.locale === 'ru' || src.locale === 'en')
|
|
34
|
+
out.locale = src.locale;
|
|
35
|
+
if (src.themeMode === 'system' || src.themeMode === 'light' || src.themeMode === 'dark') {
|
|
36
|
+
out.themeMode = src.themeMode;
|
|
37
|
+
}
|
|
38
|
+
if (typeof src.theme === 'string' && src.theme.trim() !== '')
|
|
39
|
+
out.theme = src.theme;
|
|
40
|
+
const mobile = sanitizeScale(src.uiScaleMobile);
|
|
41
|
+
if (mobile !== undefined)
|
|
42
|
+
out.uiScaleMobile = mobile;
|
|
43
|
+
const desktop = sanitizeScale(src.uiScaleDesktop);
|
|
44
|
+
if (desktop !== undefined)
|
|
45
|
+
out.uiScaleDesktop = desktop;
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
/** Прочитать умолчания оформления (без блокировки — чтение). */
|
|
49
|
+
async function readDefaults(exec) {
|
|
50
|
+
return sanitize(await readSetting(exec, DEFAULTS_SETTINGS_KEY));
|
|
51
|
+
}
|
|
52
|
+
/** Собрать порт умолчаний оформления поверх SQL. */
|
|
53
|
+
export function createPrincipalDefaultsPort(conn) {
|
|
54
|
+
return {
|
|
55
|
+
async loadDefaults() {
|
|
56
|
+
return readDefaults(conn);
|
|
57
|
+
},
|
|
58
|
+
async saveDefaults(patch) {
|
|
59
|
+
return conn.withTransaction(async (tx) => {
|
|
60
|
+
// Блокируем строку секции, чтобы конкурентный патч не потерялся (как AsyncLock в файловой реализации).
|
|
61
|
+
const rows = await tx.query('SELECT value FROM settings WHERE key = $1 FOR UPDATE', [DEFAULTS_SETTINGS_KEY]);
|
|
62
|
+
const next = { ...sanitize(rows[0]?.value), ...sanitize(patch) };
|
|
63
|
+
await writeSetting(tx, DEFAULTS_SETTINGS_KEY, next);
|
|
64
|
+
return next;
|
|
65
|
+
});
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Порты `providers`/`models`/`agents` PostgreSQL-драйвера (ADR-097, волна 3b).
|
|
3
|
+
*
|
|
4
|
+
* Все три — `DocumentRepository<T>` над одной таблицей `documents(kind, key,
|
|
5
|
+
* value jsonb)`: `kind` = `provider`/`model`/`agent`, ключ документа — как в
|
|
6
|
+
* файловой/in-memory реализации (для моделей — `provider/model`). Драйвер не
|
|
7
|
+
* интерпретирует ключ: он лишь хранит документ целиком, поэтому вложенные ключи
|
|
8
|
+
* работают без специальной обработки.
|
|
9
|
+
*
|
|
10
|
+
* `load` отсутствующего — `null`, `exists` — наличие строки (значение `jsonb`
|
|
11
|
+
* `NOT NULL`, пустых/битых документов в БД не бывает), `delete` идемпотентен.
|
|
12
|
+
*/
|
|
13
|
+
import type { AgentDefinition, ModelConfig, ProviderConfig } from '@itphx/synth-shared';
|
|
14
|
+
import type { DocumentRepository } from '@itphx/synth-core';
|
|
15
|
+
import type { PostgresConnection } from '../pool.js';
|
|
16
|
+
/** Документ-провайдер. */
|
|
17
|
+
export type ProviderDocument = ProviderConfig;
|
|
18
|
+
/** Документ-модель. */
|
|
19
|
+
export type ModelDocument = ModelConfig;
|
|
20
|
+
/** Документ-агент. */
|
|
21
|
+
export type AgentDocument = AgentDefinition;
|
|
22
|
+
/** Собрать `DocumentRepository<T>` поверх таблицы `documents` для заданного `kind`. */
|
|
23
|
+
export declare function createDocumentPort<T>(conn: PostgresConnection, kind: 'provider' | 'model' | 'agent'): DocumentRepository<T>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Порты `providers`/`models`/`agents` PostgreSQL-драйвера (ADR-097, волна 3b).
|
|
3
|
+
*
|
|
4
|
+
* Все три — `DocumentRepository<T>` над одной таблицей `documents(kind, key,
|
|
5
|
+
* value jsonb)`: `kind` = `provider`/`model`/`agent`, ключ документа — как в
|
|
6
|
+
* файловой/in-memory реализации (для моделей — `provider/model`). Драйвер не
|
|
7
|
+
* интерпретирует ключ: он лишь хранит документ целиком, поэтому вложенные ключи
|
|
8
|
+
* работают без специальной обработки.
|
|
9
|
+
*
|
|
10
|
+
* `load` отсутствующего — `null`, `exists` — наличие строки (значение `jsonb`
|
|
11
|
+
* `NOT NULL`, пустых/битых документов в БД не бывает), `delete` идемпотентен.
|
|
12
|
+
*/
|
|
13
|
+
import { jsonbParam } from '../json-param.js';
|
|
14
|
+
/** Собрать `DocumentRepository<T>` поверх таблицы `documents` для заданного `kind`. */
|
|
15
|
+
export function createDocumentPort(conn, kind) {
|
|
16
|
+
return {
|
|
17
|
+
async load(key) {
|
|
18
|
+
const rows = await conn.query('SELECT value FROM documents WHERE kind = $1 AND key = $2', [kind, key]);
|
|
19
|
+
const row = rows[0];
|
|
20
|
+
return row ? row.value : null;
|
|
21
|
+
},
|
|
22
|
+
async save(key, value) {
|
|
23
|
+
await conn.query(`INSERT INTO documents (kind, key, value, updated_at) VALUES ($1, $2, $3::jsonb, now())
|
|
24
|
+
ON CONFLICT (kind, key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, [kind, key, jsonbParam(value)]);
|
|
25
|
+
},
|
|
26
|
+
async delete(key) {
|
|
27
|
+
await conn.query('DELETE FROM documents WHERE kind = $1 AND key = $2', [kind, key]);
|
|
28
|
+
},
|
|
29
|
+
async exists(key) {
|
|
30
|
+
const rows = await conn.query('SELECT 1 AS present FROM documents WHERE kind = $1 AND key = $2', [kind, key]);
|
|
31
|
+
return rows.length > 0;
|
|
32
|
+
},
|
|
33
|
+
async list() {
|
|
34
|
+
const rows = await conn.query('SELECT value FROM documents WHERE kind = $1 ORDER BY key', [kind]);
|
|
35
|
+
return rows.map((row) => row.value);
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Порт `profiles` PostgreSQL-драйвера (ADR-097, волна 3b).
|
|
3
|
+
*
|
|
4
|
+
* Эталон семантики — `FileProfileStore`/`MemoryProfileRepository`:
|
|
5
|
+
* - `saveProfile` проставляет `updatedAt` при записи;
|
|
6
|
+
* - `listProfiles` — `updated_at DESC`; `deleteProfile` — boolean;
|
|
7
|
+
* - `getOrCreateProfile` идемпотентен по `username`;
|
|
8
|
+
* - ADR-089: `identities` — child-таблица `profile_identities` (snake_case
|
|
9
|
+
* `external_id`/`display_name`/`linked_at`/`linked_by`, UNIQUE
|
|
10
|
+
* `(provider, external_id)`); `linkIdentity` идемпотентна и **не бросает**
|
|
11
|
+
* при конфликте пары с другим профилем (`null`), `unlinkIdentity` без записи
|
|
12
|
+
* возвращает `null`; обе операции атомарны.
|
|
13
|
+
*
|
|
14
|
+
* `roles`/`team_roles`/`preferences` — `jsonb`; `username`/`email` — UNIQUE.
|
|
15
|
+
*/
|
|
16
|
+
import type { StorageContext } from '@itphx/synth-core';
|
|
17
|
+
import type { PostgresConnection } from '../pool.js';
|
|
18
|
+
type ProfilesPort = StorageContext['profiles'];
|
|
19
|
+
/** Собрать порт профилей поверх SQL. */
|
|
20
|
+
export declare function createPrincipalProfilesPort(conn: PostgresConnection): ProfilesPort;
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Порт `profiles` PostgreSQL-драйвера (ADR-097, волна 3b).
|
|
3
|
+
*
|
|
4
|
+
* Эталон семантики — `FileProfileStore`/`MemoryProfileRepository`:
|
|
5
|
+
* - `saveProfile` проставляет `updatedAt` при записи;
|
|
6
|
+
* - `listProfiles` — `updated_at DESC`; `deleteProfile` — boolean;
|
|
7
|
+
* - `getOrCreateProfile` идемпотентен по `username`;
|
|
8
|
+
* - ADR-089: `identities` — child-таблица `profile_identities` (snake_case
|
|
9
|
+
* `external_id`/`display_name`/`linked_at`/`linked_by`, UNIQUE
|
|
10
|
+
* `(provider, external_id)`); `linkIdentity` идемпотентна и **не бросает**
|
|
11
|
+
* при конфликте пары с другим профилем (`null`), `unlinkIdentity` без записи
|
|
12
|
+
* возвращает `null`; обе операции атомарны.
|
|
13
|
+
*
|
|
14
|
+
* `roles`/`team_roles`/`preferences` — `jsonb`; `username`/`email` — UNIQUE.
|
|
15
|
+
*/
|
|
16
|
+
import { randomUUID } from 'node:crypto';
|
|
17
|
+
import { jsonbParam, requiredIso, toIso, } from './principals-shared.js';
|
|
18
|
+
const PROFILE_COLUMNS = `id, username, email, phone, roles, team_roles, is_active, preferences,
|
|
19
|
+
notes, interview_completed, interview_completed_at, display_name, created_at, updated_at, last_login`;
|
|
20
|
+
const IDENTITY_COLUMNS = `profile_id, provider, external_id, username, display_name, linked_at, linked_by`;
|
|
21
|
+
function rowToIdentity(row) {
|
|
22
|
+
return {
|
|
23
|
+
provider: row.provider,
|
|
24
|
+
externalId: row.external_id,
|
|
25
|
+
...(row.username !== null ? { username: row.username } : {}),
|
|
26
|
+
...(row.display_name !== null ? { displayName: row.display_name } : {}),
|
|
27
|
+
linkedAt: requiredIso(row.linked_at),
|
|
28
|
+
...(row.linked_by !== null ? { linkedBy: row.linked_by } : {}),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function rowToProfile(row, identities) {
|
|
32
|
+
// Backfill для legacy-профилей (дословно `FileProfileStore._deserialize`): до
|
|
33
|
+
// появления поля статус интервью хранился меткой `[ИНТЕРВЬЮ]` в `notes`.
|
|
34
|
+
// `??`-семантика: `NULL`-колонка (поле отсутствует) → метка; явный `false`
|
|
35
|
+
// метку игнорирует. Время завершения: `interview_completed_at`, иначе для
|
|
36
|
+
// legacy — `updated_at`.
|
|
37
|
+
const notes = row.notes ?? '';
|
|
38
|
+
const legacyInterview = notes.includes('[ИНТЕРВЬЮ]');
|
|
39
|
+
const interviewCompleted = row.interview_completed ?? legacyInterview;
|
|
40
|
+
const interviewCompletedAt = row.interview_completed_at
|
|
41
|
+
? requiredIso(row.interview_completed_at)
|
|
42
|
+
: legacyInterview
|
|
43
|
+
? requiredIso(row.updated_at)
|
|
44
|
+
: undefined;
|
|
45
|
+
return {
|
|
46
|
+
id: row.id,
|
|
47
|
+
username: row.username,
|
|
48
|
+
email: row.email ?? undefined,
|
|
49
|
+
phone: row.phone ?? undefined,
|
|
50
|
+
roles: row.roles ?? [],
|
|
51
|
+
teamRoles: row.team_roles ?? [],
|
|
52
|
+
isActive: row.is_active,
|
|
53
|
+
preferences: row.preferences ?? {},
|
|
54
|
+
notes,
|
|
55
|
+
interviewCompleted,
|
|
56
|
+
...(interviewCompletedAt !== undefined ? { interviewCompletedAt } : {}),
|
|
57
|
+
displayName: row.display_name ?? undefined,
|
|
58
|
+
identities,
|
|
59
|
+
createdAt: requiredIso(row.created_at),
|
|
60
|
+
updatedAt: requiredIso(row.updated_at),
|
|
61
|
+
lastLogin: toIso(row.last_login),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** Прочитать внешние идентичности профиля. */
|
|
65
|
+
async function loadIdentities(exec, profileId) {
|
|
66
|
+
const rows = await exec.query(`SELECT ${IDENTITY_COLUMNS} FROM profile_identities WHERE profile_id = $1 ORDER BY id`, [profileId]);
|
|
67
|
+
return rows.map(rowToIdentity);
|
|
68
|
+
}
|
|
69
|
+
/** Агрегировать идентичности всех профилей одним запросом (без N+1). */
|
|
70
|
+
async function loadAllIdentities(exec) {
|
|
71
|
+
const rows = await exec.query(`SELECT ${IDENTITY_COLUMNS} FROM profile_identities ORDER BY id`);
|
|
72
|
+
const byProfile = new Map();
|
|
73
|
+
for (const row of rows) {
|
|
74
|
+
const list = byProfile.get(row.profile_id);
|
|
75
|
+
if (list)
|
|
76
|
+
list.push(rowToIdentity(row));
|
|
77
|
+
else
|
|
78
|
+
byProfile.set(row.profile_id, [rowToIdentity(row)]);
|
|
79
|
+
}
|
|
80
|
+
return byProfile;
|
|
81
|
+
}
|
|
82
|
+
async function selectProfileRow(exec, column, value) {
|
|
83
|
+
const rows = await exec.query(`SELECT ${PROFILE_COLUMNS} FROM profiles WHERE ${column} = $1`, [
|
|
84
|
+
value,
|
|
85
|
+
]);
|
|
86
|
+
return rows[0];
|
|
87
|
+
}
|
|
88
|
+
async function loadProfileById(exec, id) {
|
|
89
|
+
const row = await selectProfileRow(exec, 'id', id);
|
|
90
|
+
if (!row)
|
|
91
|
+
return null;
|
|
92
|
+
return rowToProfile(row, await loadIdentities(exec, id));
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Записать профиль и его идентичности атомарно: строка `profiles` — upsert,
|
|
96
|
+
* `profile_identities` — заменяются целиком (как JSON round-trip файловой
|
|
97
|
+
* реализации, где `identities` — часть профиля).
|
|
98
|
+
*/
|
|
99
|
+
async function saveProfileRow(exec, profile) {
|
|
100
|
+
const updatedAt = new Date().toISOString();
|
|
101
|
+
await exec.query(`INSERT INTO profiles (${PROFILE_COLUMNS}) VALUES (
|
|
102
|
+
$1, $2, $3, $4, $5::jsonb, $6::jsonb, $7, $8::jsonb, $9, $10, $11, $12, $13, $14, $15
|
|
103
|
+
)
|
|
104
|
+
ON CONFLICT (id) DO UPDATE SET
|
|
105
|
+
username = EXCLUDED.username,
|
|
106
|
+
email = EXCLUDED.email,
|
|
107
|
+
phone = EXCLUDED.phone,
|
|
108
|
+
roles = EXCLUDED.roles,
|
|
109
|
+
team_roles = EXCLUDED.team_roles,
|
|
110
|
+
is_active = EXCLUDED.is_active,
|
|
111
|
+
preferences = EXCLUDED.preferences,
|
|
112
|
+
notes = EXCLUDED.notes,
|
|
113
|
+
interview_completed = EXCLUDED.interview_completed,
|
|
114
|
+
interview_completed_at = EXCLUDED.interview_completed_at,
|
|
115
|
+
display_name = EXCLUDED.display_name,
|
|
116
|
+
updated_at = EXCLUDED.updated_at,
|
|
117
|
+
last_login = EXCLUDED.last_login`, [
|
|
118
|
+
profile.id,
|
|
119
|
+
profile.username,
|
|
120
|
+
profile.email ?? null,
|
|
121
|
+
profile.phone ?? null,
|
|
122
|
+
jsonbParam(profile.roles ?? []),
|
|
123
|
+
jsonbParam(profile.teamRoles ?? []),
|
|
124
|
+
profile.isActive,
|
|
125
|
+
jsonbParam(profile.preferences ?? {}),
|
|
126
|
+
profile.notes ?? '',
|
|
127
|
+
profile.interviewCompleted,
|
|
128
|
+
profile.interviewCompletedAt ?? null,
|
|
129
|
+
profile.displayName ?? null,
|
|
130
|
+
profile.createdAt,
|
|
131
|
+
updatedAt,
|
|
132
|
+
profile.lastLogin ?? null,
|
|
133
|
+
]);
|
|
134
|
+
await exec.query('DELETE FROM profile_identities WHERE profile_id = $1', [profile.id]);
|
|
135
|
+
for (const identity of profile.identities ?? []) {
|
|
136
|
+
await exec.query(`INSERT INTO profile_identities (${IDENTITY_COLUMNS}) VALUES ($1, $2, $3, $4, $5, $6, $7)`, [
|
|
137
|
+
profile.id,
|
|
138
|
+
identity.provider,
|
|
139
|
+
identity.externalId,
|
|
140
|
+
identity.username ?? null,
|
|
141
|
+
identity.displayName ?? null,
|
|
142
|
+
identity.linkedAt,
|
|
143
|
+
identity.linkedBy ?? null,
|
|
144
|
+
]);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** Собрать порт профилей поверх SQL. */
|
|
148
|
+
export function createPrincipalProfilesPort(conn) {
|
|
149
|
+
return {
|
|
150
|
+
async loadProfile(id) {
|
|
151
|
+
return loadProfileById(conn, id);
|
|
152
|
+
},
|
|
153
|
+
async saveProfile(profile) {
|
|
154
|
+
await conn.withTransaction(async (tx) => {
|
|
155
|
+
await saveProfileRow(tx, profile);
|
|
156
|
+
});
|
|
157
|
+
},
|
|
158
|
+
async listProfiles() {
|
|
159
|
+
const rows = await conn.query(`SELECT ${PROFILE_COLUMNS} FROM profiles ORDER BY updated_at DESC`);
|
|
160
|
+
const identities = await loadAllIdentities(conn);
|
|
161
|
+
return rows.map((row) => rowToProfile(row, identities.get(row.id) ?? []));
|
|
162
|
+
},
|
|
163
|
+
async deleteProfile(id) {
|
|
164
|
+
const rows = await conn.query('DELETE FROM profiles WHERE id = $1 RETURNING id', [id]);
|
|
165
|
+
return rows.length > 0;
|
|
166
|
+
},
|
|
167
|
+
async getProfileByUsername(username) {
|
|
168
|
+
const row = await selectProfileRow(conn, 'username', username);
|
|
169
|
+
if (!row)
|
|
170
|
+
return null;
|
|
171
|
+
return rowToProfile(row, await loadIdentities(conn, row.id));
|
|
172
|
+
},
|
|
173
|
+
async getProfileByEmail(email) {
|
|
174
|
+
const row = await selectProfileRow(conn, 'email', email);
|
|
175
|
+
if (!row)
|
|
176
|
+
return null;
|
|
177
|
+
return rowToProfile(row, await loadIdentities(conn, row.id));
|
|
178
|
+
},
|
|
179
|
+
async getOrCreateProfile(params) {
|
|
180
|
+
const existingRow = await selectProfileRow(conn, 'username', params.username);
|
|
181
|
+
if (existingRow) {
|
|
182
|
+
const current = rowToProfile(existingRow, await loadIdentities(conn, existingRow.id));
|
|
183
|
+
const next = {
|
|
184
|
+
...current,
|
|
185
|
+
...(params.email ? { email: params.email } : {}),
|
|
186
|
+
...(params.roles ? { roles: params.roles } : {}),
|
|
187
|
+
...(params.teamRoles ? { teamRoles: params.teamRoles } : {}),
|
|
188
|
+
...(params.interviewCompleted !== undefined
|
|
189
|
+
? { interviewCompleted: params.interviewCompleted }
|
|
190
|
+
: {}),
|
|
191
|
+
};
|
|
192
|
+
await conn.withTransaction(async (tx) => {
|
|
193
|
+
await saveProfileRow(tx, next);
|
|
194
|
+
});
|
|
195
|
+
return next;
|
|
196
|
+
}
|
|
197
|
+
const now = new Date().toISOString();
|
|
198
|
+
const profile = {
|
|
199
|
+
id: randomUUID(),
|
|
200
|
+
username: params.username,
|
|
201
|
+
email: params.email,
|
|
202
|
+
roles: params.roles ?? ['USER'],
|
|
203
|
+
teamRoles: params.teamRoles ?? [],
|
|
204
|
+
isActive: true,
|
|
205
|
+
preferences: {},
|
|
206
|
+
notes: '',
|
|
207
|
+
interviewCompleted: params.interviewCompleted ?? false,
|
|
208
|
+
displayName: params.username,
|
|
209
|
+
createdAt: now,
|
|
210
|
+
updatedAt: now,
|
|
211
|
+
};
|
|
212
|
+
await conn.withTransaction(async (tx) => {
|
|
213
|
+
await saveProfileRow(tx, profile);
|
|
214
|
+
});
|
|
215
|
+
return profile;
|
|
216
|
+
},
|
|
217
|
+
async updateLastLogin(id) {
|
|
218
|
+
await conn.query('UPDATE profiles SET last_login = now(), updated_at = now() WHERE id = $1', [id]);
|
|
219
|
+
},
|
|
220
|
+
async findProfileByExternalId(provider, externalId) {
|
|
221
|
+
const rows = await conn.query('SELECT profile_id FROM profile_identities WHERE provider = $1 AND external_id = $2 LIMIT 1', [provider, externalId]);
|
|
222
|
+
const row = rows[0];
|
|
223
|
+
if (!row)
|
|
224
|
+
return null;
|
|
225
|
+
return loadProfileById(conn, row.profile_id);
|
|
226
|
+
},
|
|
227
|
+
async linkIdentity(userId, identity) {
|
|
228
|
+
const exists = await conn.query('SELECT id FROM profiles WHERE id = $1', [userId]);
|
|
229
|
+
if (!exists[0])
|
|
230
|
+
return null;
|
|
231
|
+
const outcome = await conn.withTransaction(async (tx) => {
|
|
232
|
+
const inserted = await tx.query(`INSERT INTO profile_identities (${IDENTITY_COLUMNS})
|
|
233
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
234
|
+
ON CONFLICT (provider, external_id) DO NOTHING
|
|
235
|
+
RETURNING profile_id`, [
|
|
236
|
+
userId,
|
|
237
|
+
identity.provider,
|
|
238
|
+
identity.externalId,
|
|
239
|
+
identity.username ?? null,
|
|
240
|
+
identity.displayName ?? null,
|
|
241
|
+
identity.linkedAt ?? new Date().toISOString(),
|
|
242
|
+
identity.linkedBy ?? null,
|
|
243
|
+
]);
|
|
244
|
+
if (inserted.length > 0)
|
|
245
|
+
return 'inserted';
|
|
246
|
+
// Пара уже существует: идемпотентно для своего профиля, конфликт — чужой.
|
|
247
|
+
const owners = await tx.query('SELECT profile_id FROM profile_identities WHERE provider = $1 AND external_id = $2', [identity.provider, identity.externalId]);
|
|
248
|
+
return owners[0]?.profile_id === userId ? 'existing' : 'conflict';
|
|
249
|
+
});
|
|
250
|
+
if (outcome === 'conflict')
|
|
251
|
+
return null;
|
|
252
|
+
return loadProfileById(conn, userId);
|
|
253
|
+
},
|
|
254
|
+
async unlinkIdentity(userId, provider, externalId) {
|
|
255
|
+
const rows = await conn.query(`DELETE FROM profile_identities
|
|
256
|
+
WHERE profile_id = $1 AND provider = $2 AND external_id = $3
|
|
257
|
+
RETURNING profile_id`, [userId, provider, externalId]);
|
|
258
|
+
if (rows.length === 0)
|
|
259
|
+
return null;
|
|
260
|
+
return loadProfileById(conn, userId);
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Порт `projects` PostgreSQL-драйвера (ADR-097, волна 3b).
|
|
3
|
+
*
|
|
4
|
+
* Эталон семантики — `ProjectStore`/`MemoryProjectRepository`:
|
|
5
|
+
* - `create()` — синхронная чистая фабрика (id, `members`, 4 дефолтные колонки
|
|
6
|
+
* плана, пустые `statusMessages`/`log`, `version: 1`, таймстемпы);
|
|
7
|
+
* - `list(userId)` — владелец **или** участник, сортировка `updated_at DESC`;
|
|
8
|
+
* - `delete` отсутствующего — не ошибка; `load` отсутствующего — `null`.
|
|
9
|
+
*
|
|
10
|
+
* `members` — child-таблица `project_members` (PK `(project_id,user_id)`,
|
|
11
|
+
* индекс `(user_id)`): `save` заменяет набор участий в той же транзакции, что и
|
|
12
|
+
* строку проекта. `plan`/`log`/`status_messages`/`repos`/`mcp`/`skills` — `jsonb`.
|
|
13
|
+
*/
|
|
14
|
+
import type { StorageContext } from '@itphx/synth-core';
|
|
15
|
+
import type { PostgresConnection } from '../pool.js';
|
|
16
|
+
type ProjectsPort = StorageContext['projects'];
|
|
17
|
+
/** Собрать порт проектов поверх SQL. */
|
|
18
|
+
export declare function createPrincipalProjectsPort(conn: PostgresConnection): ProjectsPort;
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Порт `projects` PostgreSQL-драйвера (ADR-097, волна 3b).
|
|
3
|
+
*
|
|
4
|
+
* Эталон семантики — `ProjectStore`/`MemoryProjectRepository`:
|
|
5
|
+
* - `create()` — синхронная чистая фабрика (id, `members`, 4 дефолтные колонки
|
|
6
|
+
* плана, пустые `statusMessages`/`log`, `version: 1`, таймстемпы);
|
|
7
|
+
* - `list(userId)` — владелец **или** участник, сортировка `updated_at DESC`;
|
|
8
|
+
* - `delete` отсутствующего — не ошибка; `load` отсутствующего — `null`.
|
|
9
|
+
*
|
|
10
|
+
* `members` — child-таблица `project_members` (PK `(project_id,user_id)`,
|
|
11
|
+
* индекс `(user_id)`): `save` заменяет набор участий в той же транзакции, что и
|
|
12
|
+
* строку проекта. `plan`/`log`/`status_messages`/`repos`/`mcp`/`skills` — `jsonb`.
|
|
13
|
+
*/
|
|
14
|
+
import { randomUUID } from 'node:crypto';
|
|
15
|
+
import { normalizeColorKey, normalizeIconKey } from '@itphx/synth-shared';
|
|
16
|
+
import { jsonbParam, requiredIso } from './principals-shared.js';
|
|
17
|
+
/** Проекции проекта + json-агрегация участий одним запросом (без N+1). */
|
|
18
|
+
const SELECT_PROJECT = `
|
|
19
|
+
SELECT p.*, COALESCE(m.members, '{}'::jsonb) AS members
|
|
20
|
+
FROM projects p
|
|
21
|
+
LEFT JOIN LATERAL (
|
|
22
|
+
SELECT jsonb_object_agg(pm.user_id, pm.role) AS members
|
|
23
|
+
FROM project_members pm
|
|
24
|
+
WHERE pm.project_id = p.id
|
|
25
|
+
) m ON true`;
|
|
26
|
+
function rowToProject(row) {
|
|
27
|
+
return {
|
|
28
|
+
id: row.id,
|
|
29
|
+
name: row.name,
|
|
30
|
+
ownerId: row.owner_id,
|
|
31
|
+
members: (row.members ?? {}),
|
|
32
|
+
description: row.description ?? '',
|
|
33
|
+
currentTask: row.current_task ?? '',
|
|
34
|
+
invariants: row.invariants ?? '',
|
|
35
|
+
// Нормализация метаданных при чтении (паритет с `ProjectStore.load`):
|
|
36
|
+
// невалидные/legacy-ключи → `undefined`.
|
|
37
|
+
icon: normalizeIconKey(row.icon),
|
|
38
|
+
color: normalizeColorKey(row.color),
|
|
39
|
+
workspace: row.workspace ?? undefined,
|
|
40
|
+
repos: (row.repos ?? undefined),
|
|
41
|
+
mcp: (row.mcp ?? undefined),
|
|
42
|
+
skills: (row.skills ?? undefined),
|
|
43
|
+
memory: (row.memory ?? undefined),
|
|
44
|
+
statusMessages: (row.status_messages ?? []),
|
|
45
|
+
plan: (row.plan ?? undefined),
|
|
46
|
+
log: (row.log ?? undefined),
|
|
47
|
+
createdAt: requiredIso(row.created_at),
|
|
48
|
+
updatedAt: requiredIso(row.updated_at),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Собрать порт проектов поверх SQL. */
|
|
52
|
+
export function createPrincipalProjectsPort(conn) {
|
|
53
|
+
return {
|
|
54
|
+
async load(id) {
|
|
55
|
+
const rows = await conn.query(`${SELECT_PROJECT} WHERE p.id = $1`, [id]);
|
|
56
|
+
const row = rows[0];
|
|
57
|
+
return row ? rowToProject(row) : null;
|
|
58
|
+
},
|
|
59
|
+
async save(project) {
|
|
60
|
+
await conn.withTransaction(async (tx) => {
|
|
61
|
+
await tx.query(`INSERT INTO projects (
|
|
62
|
+
id, name, owner_id, description, current_task, invariants, icon, color,
|
|
63
|
+
workspace, plan, log, status_messages, repos, mcp, skills, memory, created_at, updated_at
|
|
64
|
+
) VALUES (
|
|
65
|
+
$1, $2, $3, $4, $5, $6, $7, $8,
|
|
66
|
+
$9, $10::jsonb, $11::jsonb, $12::jsonb, $13::jsonb, $14::jsonb, $15::jsonb, $16::jsonb, $17, $18
|
|
67
|
+
)
|
|
68
|
+
ON CONFLICT (id) DO UPDATE SET
|
|
69
|
+
name = EXCLUDED.name,
|
|
70
|
+
owner_id = EXCLUDED.owner_id,
|
|
71
|
+
description = EXCLUDED.description,
|
|
72
|
+
current_task = EXCLUDED.current_task,
|
|
73
|
+
invariants = EXCLUDED.invariants,
|
|
74
|
+
icon = EXCLUDED.icon,
|
|
75
|
+
color = EXCLUDED.color,
|
|
76
|
+
workspace = EXCLUDED.workspace,
|
|
77
|
+
plan = EXCLUDED.plan,
|
|
78
|
+
log = EXCLUDED.log,
|
|
79
|
+
status_messages = EXCLUDED.status_messages,
|
|
80
|
+
repos = EXCLUDED.repos,
|
|
81
|
+
mcp = EXCLUDED.mcp,
|
|
82
|
+
skills = EXCLUDED.skills,
|
|
83
|
+
memory = EXCLUDED.memory,
|
|
84
|
+
updated_at = EXCLUDED.updated_at`, [
|
|
85
|
+
project.id,
|
|
86
|
+
project.name,
|
|
87
|
+
project.ownerId,
|
|
88
|
+
project.description ?? '',
|
|
89
|
+
project.currentTask ?? '',
|
|
90
|
+
project.invariants ?? '',
|
|
91
|
+
project.icon ?? null,
|
|
92
|
+
project.color ?? null,
|
|
93
|
+
project.workspace ?? null,
|
|
94
|
+
jsonbParam(project.plan ?? null),
|
|
95
|
+
jsonbParam(project.log ?? null),
|
|
96
|
+
jsonbParam(project.statusMessages ?? []),
|
|
97
|
+
jsonbParam(project.repos ?? null),
|
|
98
|
+
jsonbParam(project.mcp ?? null),
|
|
99
|
+
jsonbParam(project.skills ?? null),
|
|
100
|
+
jsonbParam(project.memory ?? null),
|
|
101
|
+
project.createdAt,
|
|
102
|
+
project.updatedAt,
|
|
103
|
+
]);
|
|
104
|
+
// Набор участий — источник истины в самом проекте: заменяем целиком.
|
|
105
|
+
await tx.query('DELETE FROM project_members WHERE project_id = $1', [project.id]);
|
|
106
|
+
for (const [userId, role] of Object.entries(project.members ?? {})) {
|
|
107
|
+
await tx.query('INSERT INTO project_members (project_id, user_id, role) VALUES ($1, $2, $3)', [project.id, userId, role]);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
},
|
|
111
|
+
async delete(id) {
|
|
112
|
+
await conn.query('DELETE FROM projects WHERE id = $1', [id]);
|
|
113
|
+
},
|
|
114
|
+
async list(userId) {
|
|
115
|
+
const rows = userId
|
|
116
|
+
? await conn.query(`${SELECT_PROJECT}
|
|
117
|
+
WHERE p.owner_id = $1
|
|
118
|
+
OR EXISTS (
|
|
119
|
+
SELECT 1 FROM project_members pm2
|
|
120
|
+
WHERE pm2.project_id = p.id AND pm2.user_id = $1
|
|
121
|
+
)
|
|
122
|
+
ORDER BY p.updated_at DESC`, [userId])
|
|
123
|
+
: await conn.query(`${SELECT_PROJECT} ORDER BY p.updated_at DESC`);
|
|
124
|
+
return rows.map(rowToProject);
|
|
125
|
+
},
|
|
126
|
+
create(name, ownerId, data) {
|
|
127
|
+
const now = new Date().toISOString();
|
|
128
|
+
return {
|
|
129
|
+
id: randomUUID(),
|
|
130
|
+
name,
|
|
131
|
+
ownerId,
|
|
132
|
+
members: { [ownerId]: 'owner' },
|
|
133
|
+
description: data?.description || '',
|
|
134
|
+
currentTask: '',
|
|
135
|
+
invariants: '',
|
|
136
|
+
icon: data?.icon,
|
|
137
|
+
color: data?.color,
|
|
138
|
+
workspace: data?.workspace,
|
|
139
|
+
repos: data?.repos,
|
|
140
|
+
// ADR-071 §2.4 / ADR-046 §4.5: сид скоупа новых проектов (снимок системных дефолтов).
|
|
141
|
+
...(data?.mcp ? { mcp: data.mcp } : {}),
|
|
142
|
+
...(data?.skills ? { skills: data.skills } : {}),
|
|
143
|
+
statusMessages: [],
|
|
144
|
+
plan: {
|
|
145
|
+
version: 1,
|
|
146
|
+
updatedAt: now,
|
|
147
|
+
columns: [
|
|
148
|
+
{ id: 'backlog', name: 'Бэклог', order: 0 },
|
|
149
|
+
{ id: 'todo', name: 'К выполнению', order: 1 },
|
|
150
|
+
{ id: 'in_progress', name: 'В работе', order: 2 },
|
|
151
|
+
{ id: 'done', name: 'Готово', order: 3 },
|
|
152
|
+
],
|
|
153
|
+
items: [],
|
|
154
|
+
},
|
|
155
|
+
log: [],
|
|
156
|
+
createdAt: now,
|
|
157
|
+
updatedAt: now,
|
|
158
|
+
};
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
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 type { StorageContext } from '@itphx/synth-core';
|
|
21
|
+
import type { PostgresConnection } from '../pool.js';
|
|
22
|
+
type SettingsPort = StorageContext['settings'];
|
|
23
|
+
/** Собрать порт runtime-настроек поверх SQL. */
|
|
24
|
+
export declare function createPrincipalSettingsPort(conn: PostgresConnection): SettingsPort;
|
|
25
|
+
export {};
|