@itphx/synth-storage-postgres 0.0.0-stage → 0.11.3
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 +37 -0
- package/dist/index.js +34 -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/index.d.ts +23 -0
- package/dist/migrations/index.js +23 -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 +189 -0
- package/dist/ports/content.d.ts +41 -0
- package/dist/ports/content.js +1539 -0
- package/dist/ports/core-sync.d.ts +31 -0
- package/dist/ports/core-sync.js +34 -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/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 +158 -0
- package/dist/ports/principals-settings.d.ts +25 -0
- package/dist/ports/principals-settings.js +275 -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/sessions-mapping.d.ts +237 -0
- package/dist/ports/sessions-mapping.js +405 -0
- package/dist/ports/sessions.d.ts +133 -0
- package/dist/ports/sessions.js +502 -0
- package/dist/ports/stub.d.ts +14 -0
- package/dist/ports/stub.js +32 -0
- package/dist/postgres-storage.d.ts +59 -0
- package/dist/postgres-storage.js +111 -0
- package/dist/schema.d.ts +13 -0
- package/dist/schema.js +22 -0
- package/dist/storage-context.d.ts +51 -0
- package/dist/storage-context.js +130 -0
- package/package.json +40 -3
- package/README.md +0 -3
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Порт `profiles` PostgreSQL-драйвера (PROP-032, волна 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-драйвера (PROP-032, волна 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,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Порт `projects` PostgreSQL-драйвера (PROP-032, волна 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
|
+
statusMessages: (row.status_messages ?? []),
|
|
44
|
+
plan: (row.plan ?? undefined),
|
|
45
|
+
log: (row.log ?? undefined),
|
|
46
|
+
createdAt: requiredIso(row.created_at),
|
|
47
|
+
updatedAt: requiredIso(row.updated_at),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** Собрать порт проектов поверх SQL. */
|
|
51
|
+
export function createPrincipalProjectsPort(conn) {
|
|
52
|
+
return {
|
|
53
|
+
async load(id) {
|
|
54
|
+
const rows = await conn.query(`${SELECT_PROJECT} WHERE p.id = $1`, [id]);
|
|
55
|
+
const row = rows[0];
|
|
56
|
+
return row ? rowToProject(row) : null;
|
|
57
|
+
},
|
|
58
|
+
async save(project) {
|
|
59
|
+
await conn.withTransaction(async (tx) => {
|
|
60
|
+
await tx.query(`INSERT INTO projects (
|
|
61
|
+
id, name, owner_id, description, current_task, invariants, icon, color,
|
|
62
|
+
workspace, plan, log, status_messages, repos, mcp, skills, created_at, updated_at
|
|
63
|
+
) VALUES (
|
|
64
|
+
$1, $2, $3, $4, $5, $6, $7, $8,
|
|
65
|
+
$9, $10::jsonb, $11::jsonb, $12::jsonb, $13::jsonb, $14::jsonb, $15::jsonb, $16, $17
|
|
66
|
+
)
|
|
67
|
+
ON CONFLICT (id) DO UPDATE SET
|
|
68
|
+
name = EXCLUDED.name,
|
|
69
|
+
owner_id = EXCLUDED.owner_id,
|
|
70
|
+
description = EXCLUDED.description,
|
|
71
|
+
current_task = EXCLUDED.current_task,
|
|
72
|
+
invariants = EXCLUDED.invariants,
|
|
73
|
+
icon = EXCLUDED.icon,
|
|
74
|
+
color = EXCLUDED.color,
|
|
75
|
+
workspace = EXCLUDED.workspace,
|
|
76
|
+
plan = EXCLUDED.plan,
|
|
77
|
+
log = EXCLUDED.log,
|
|
78
|
+
status_messages = EXCLUDED.status_messages,
|
|
79
|
+
repos = EXCLUDED.repos,
|
|
80
|
+
mcp = EXCLUDED.mcp,
|
|
81
|
+
skills = EXCLUDED.skills,
|
|
82
|
+
updated_at = EXCLUDED.updated_at`, [
|
|
83
|
+
project.id,
|
|
84
|
+
project.name,
|
|
85
|
+
project.ownerId,
|
|
86
|
+
project.description ?? '',
|
|
87
|
+
project.currentTask ?? '',
|
|
88
|
+
project.invariants ?? '',
|
|
89
|
+
project.icon ?? null,
|
|
90
|
+
project.color ?? null,
|
|
91
|
+
project.workspace ?? null,
|
|
92
|
+
jsonbParam(project.plan ?? null),
|
|
93
|
+
jsonbParam(project.log ?? null),
|
|
94
|
+
jsonbParam(project.statusMessages ?? []),
|
|
95
|
+
jsonbParam(project.repos ?? null),
|
|
96
|
+
jsonbParam(project.mcp ?? null),
|
|
97
|
+
jsonbParam(project.skills ?? null),
|
|
98
|
+
project.createdAt,
|
|
99
|
+
project.updatedAt,
|
|
100
|
+
]);
|
|
101
|
+
// Набор участий — источник истины в самом проекте: заменяем целиком.
|
|
102
|
+
await tx.query('DELETE FROM project_members WHERE project_id = $1', [project.id]);
|
|
103
|
+
for (const [userId, role] of Object.entries(project.members ?? {})) {
|
|
104
|
+
await tx.query('INSERT INTO project_members (project_id, user_id, role) VALUES ($1, $2, $3)', [project.id, userId, role]);
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
},
|
|
108
|
+
async delete(id) {
|
|
109
|
+
await conn.query('DELETE FROM projects WHERE id = $1', [id]);
|
|
110
|
+
},
|
|
111
|
+
async list(userId) {
|
|
112
|
+
const rows = userId
|
|
113
|
+
? await conn.query(`${SELECT_PROJECT}
|
|
114
|
+
WHERE p.owner_id = $1
|
|
115
|
+
OR EXISTS (
|
|
116
|
+
SELECT 1 FROM project_members pm2
|
|
117
|
+
WHERE pm2.project_id = p.id AND pm2.user_id = $1
|
|
118
|
+
)
|
|
119
|
+
ORDER BY p.updated_at DESC`, [userId])
|
|
120
|
+
: await conn.query(`${SELECT_PROJECT} ORDER BY p.updated_at DESC`);
|
|
121
|
+
return rows.map(rowToProject);
|
|
122
|
+
},
|
|
123
|
+
create(name, ownerId, data) {
|
|
124
|
+
const now = new Date().toISOString();
|
|
125
|
+
return {
|
|
126
|
+
id: randomUUID(),
|
|
127
|
+
name,
|
|
128
|
+
ownerId,
|
|
129
|
+
members: { [ownerId]: 'owner' },
|
|
130
|
+
description: data?.description || '',
|
|
131
|
+
currentTask: '',
|
|
132
|
+
invariants: '',
|
|
133
|
+
icon: data?.icon,
|
|
134
|
+
color: data?.color,
|
|
135
|
+
workspace: data?.workspace,
|
|
136
|
+
repos: data?.repos,
|
|
137
|
+
// ADR-071 §2.4 / ADR-046 §4.5: сид скоупа новых проектов (снимок системных дефолтов).
|
|
138
|
+
...(data?.mcp ? { mcp: data.mcp } : {}),
|
|
139
|
+
...(data?.skills ? { skills: data.skills } : {}),
|
|
140
|
+
statusMessages: [],
|
|
141
|
+
plan: {
|
|
142
|
+
version: 1,
|
|
143
|
+
updatedAt: now,
|
|
144
|
+
columns: [
|
|
145
|
+
{ id: 'backlog', name: 'Бэклог', order: 0 },
|
|
146
|
+
{ id: 'todo', name: 'К выполнению', order: 1 },
|
|
147
|
+
{ id: 'in_progress', name: 'В работе', order: 2 },
|
|
148
|
+
{ id: 'done', name: 'Готово', order: 3 },
|
|
149
|
+
],
|
|
150
|
+
items: [],
|
|
151
|
+
},
|
|
152
|
+
log: [],
|
|
153
|
+
createdAt: now,
|
|
154
|
+
updatedAt: now,
|
|
155
|
+
};
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Порт `settings` (runtime-настройки инстанса) PostgreSQL-драйвера
|
|
3
|
+
* (PROP-032, волна 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 {};
|