@itphx/synth-storage-postgres 0.11.3 → 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 (141) hide show
  1. package/dist/errors.d.ts +1 -1
  2. package/dist/errors.js +2 -2
  3. package/dist/index.d.ts +15 -1
  4. package/dist/index.js +24 -2
  5. package/dist/locks.d.ts +4 -4
  6. package/dist/locks.js +4 -4
  7. package/dist/migrate.d.ts +1 -1
  8. package/dist/migrate.js +1 -1
  9. package/dist/migrations/001-init.d.ts +2 -2
  10. package/dist/migrations/001-init.js +2 -2
  11. package/dist/migrations/003-analytics-rollups.d.ts +1 -1
  12. package/dist/migrations/003-analytics-rollups.js +1 -1
  13. package/dist/migrations/004-pipeline-engine.d.ts +19 -0
  14. package/dist/migrations/004-pipeline-engine.js +74 -0
  15. package/dist/migrations/005-pipeline-provenance.d.ts +12 -0
  16. package/dist/migrations/005-pipeline-provenance.js +15 -0
  17. package/dist/migrations/006-plugin-audit.d.ts +13 -0
  18. package/dist/migrations/006-plugin-audit.js +34 -0
  19. package/dist/migrations/007-plugin-lock.d.ts +10 -0
  20. package/dist/migrations/007-plugin-lock.js +25 -0
  21. package/dist/migrations/008-plugin-audit-scan.d.ts +11 -0
  22. package/dist/migrations/008-plugin-audit-scan.js +15 -0
  23. package/dist/migrations/009-plugin-lock-previous.d.ts +13 -0
  24. package/dist/migrations/009-plugin-lock-previous.js +16 -0
  25. package/dist/migrations/010-plugin-lock-mode.d.ts +16 -0
  26. package/dist/migrations/010-plugin-lock-mode.js +20 -0
  27. package/dist/migrations/011-session-steer-inbox.d.ts +11 -0
  28. package/dist/migrations/011-session-steer-inbox.js +14 -0
  29. package/dist/migrations/012-external-credentials.d.ts +15 -0
  30. package/dist/migrations/012-external-credentials.js +40 -0
  31. package/dist/migrations/013-service-key-plugin-id.d.ts +17 -0
  32. package/dist/migrations/013-service-key-plugin-id.js +20 -0
  33. package/dist/migrations/014-session-mode-by-principal.d.ts +12 -0
  34. package/dist/migrations/014-session-mode-by-principal.js +15 -0
  35. package/dist/migrations/015-authority.d.ts +17 -0
  36. package/dist/migrations/015-authority.js +43 -0
  37. package/dist/migrations/016-credential-audit.d.ts +17 -0
  38. package/dist/migrations/016-credential-audit.js +32 -0
  39. package/dist/migrations/017-memory.d.ts +29 -0
  40. package/dist/migrations/017-memory.js +95 -0
  41. package/dist/migrations/018-memory-index-scope.d.ts +14 -0
  42. package/dist/migrations/018-memory-index-scope.js +18 -0
  43. package/dist/migrations/019-memory-index-enabled.d.ts +11 -0
  44. package/dist/migrations/019-memory-index-enabled.js +14 -0
  45. package/dist/migrations/020-project-memory.d.ts +11 -0
  46. package/dist/migrations/020-project-memory.js +13 -0
  47. package/dist/migrations/021-background-runs.d.ts +17 -0
  48. package/dist/migrations/021-background-runs.js +67 -0
  49. package/dist/migrations/022-background-run-process-id.d.ts +14 -0
  50. package/dist/migrations/022-background-run-process-id.js +18 -0
  51. package/dist/migrations/023-session-worktree.d.ts +12 -0
  52. package/dist/migrations/023-session-worktree.js +16 -0
  53. package/dist/migrations/024-blob-refs.d.ts +15 -0
  54. package/dist/migrations/024-blob-refs.js +26 -0
  55. package/dist/migrations/025-packs-pipelines.d.ts +28 -0
  56. package/dist/migrations/025-packs-pipelines.js +82 -0
  57. package/dist/migrations/026-instance-skills.d.ts +17 -0
  58. package/dist/migrations/026-instance-skills.js +25 -0
  59. package/dist/migrations/027-context-files.d.ts +20 -0
  60. package/dist/migrations/027-context-files.js +30 -0
  61. package/dist/migrations/index.d.ts +1 -1
  62. package/dist/migrations/index.js +49 -1
  63. package/dist/pool.d.ts +6 -6
  64. package/dist/pool.js +8 -8
  65. package/dist/ports/analytics.d.ts +1 -1
  66. package/dist/ports/analytics.js +1 -1
  67. package/dist/ports/audit.d.ts +1 -1
  68. package/dist/ports/audit.js +3 -0
  69. package/dist/ports/authority.d.ts +27 -0
  70. package/dist/ports/authority.js +148 -0
  71. package/dist/ports/background-runs.d.ts +41 -0
  72. package/dist/ports/background-runs.js +179 -0
  73. package/dist/ports/blob-refs.d.ts +36 -0
  74. package/dist/ports/blob-refs.js +55 -0
  75. package/dist/ports/content.d.ts +1 -1
  76. package/dist/ports/content.js +21 -7
  77. package/dist/ports/context-files.d.ts +145 -0
  78. package/dist/ports/context-files.js +279 -0
  79. package/dist/ports/core-sync.d.ts +1 -1
  80. package/dist/ports/core-sync.js +1 -1
  81. package/dist/ports/credential-audit.d.ts +19 -0
  82. package/dist/ports/credential-audit.js +96 -0
  83. package/dist/ports/deps.d.ts +2 -2
  84. package/dist/ports/deps.js +1 -1
  85. package/dist/ports/events-bindings.d.ts +2 -2
  86. package/dist/ports/events-bindings.js +2 -2
  87. package/dist/ports/events-core.d.ts +1 -1
  88. package/dist/ports/events-core.js +1 -1
  89. package/dist/ports/events-journal.d.ts +1 -1
  90. package/dist/ports/events-journal.js +1 -1
  91. package/dist/ports/events-scheduler.d.ts +1 -1
  92. package/dist/ports/events-scheduler.js +1 -1
  93. package/dist/ports/events-webhooks.d.ts +1 -1
  94. package/dist/ports/events-webhooks.js +1 -1
  95. package/dist/ports/events.d.ts +1 -1
  96. package/dist/ports/events.js +1 -1
  97. package/dist/ports/external-credentials.d.ts +6 -0
  98. package/dist/ports/external-credentials.js +363 -0
  99. package/dist/ports/legacy-pipelines.d.ts +50 -0
  100. package/dist/ports/legacy-pipelines.js +202 -0
  101. package/dist/ports/memory.d.ts +65 -0
  102. package/dist/ports/memory.js +471 -0
  103. package/dist/ports/packs.d.ts +32 -0
  104. package/dist/ports/packs.js +117 -0
  105. package/dist/ports/pipelines.d.ts +67 -0
  106. package/dist/ports/pipelines.js +297 -0
  107. package/dist/ports/plugin-audit.d.ts +14 -0
  108. package/dist/ports/plugin-audit.js +110 -0
  109. package/dist/ports/plugin-lock.d.ts +27 -0
  110. package/dist/ports/plugin-lock.js +145 -0
  111. package/dist/ports/principals-defaults.d.ts +1 -1
  112. package/dist/ports/principals-defaults.js +1 -1
  113. package/dist/ports/principals-documents.d.ts +1 -1
  114. package/dist/ports/principals-documents.js +1 -1
  115. package/dist/ports/principals-profiles.d.ts +1 -1
  116. package/dist/ports/principals-profiles.js +1 -1
  117. package/dist/ports/principals-projects.d.ts +1 -1
  118. package/dist/ports/principals-projects.js +6 -3
  119. package/dist/ports/principals-settings.d.ts +1 -1
  120. package/dist/ports/principals-settings.js +21 -1
  121. package/dist/ports/principals-shared.d.ts +1 -1
  122. package/dist/ports/principals-shared.js +1 -1
  123. package/dist/ports/principals.d.ts +1 -1
  124. package/dist/ports/principals.js +1 -1
  125. package/dist/ports/questions.d.ts +40 -0
  126. package/dist/ports/questions.js +135 -0
  127. package/dist/ports/sessions-mapping.d.ts +20 -3
  128. package/dist/ports/sessions-mapping.js +46 -2
  129. package/dist/ports/sessions.d.ts +13 -3
  130. package/dist/ports/sessions.js +20 -5
  131. package/dist/ports/skills.d.ts +59 -0
  132. package/dist/ports/skills.js +205 -0
  133. package/dist/ports/stub.d.ts +1 -1
  134. package/dist/ports/stub.js +2 -2
  135. package/dist/ports/worktrees.d.ts +41 -0
  136. package/dist/ports/worktrees.js +85 -0
  137. package/dist/postgres-storage.d.ts +4 -5
  138. package/dist/postgres-storage.js +5 -6
  139. package/dist/storage-context.d.ts +44 -15
  140. package/dist/storage-context.js +139 -31
  141. package/package.json +4 -4
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Порт lock-файла плагинов PostgreSQL-драйвера (PROP-068 §4.4 / ADR-090,
3
+ * ADR-097).
4
+ *
5
+ * Отдельная таблица `plugin_lock` (ключ — имя плагина). Семантика — как у
6
+ * файловой реализации core (`FilePluginLockStore`): upsert по имени
7
+ * (`installed_at` сохраняется, `updated_at` обновляется), чтечение, список с
8
+ * детерминированным порядком по имени, снятие записи.
9
+ *
10
+ * **Ступень отката (долги Д2).** Колонка `previous jsonb` (миграция `009`) —
11
+ * одна предыдущая версия для `rollback`; отсутствует (`NULL`) у записи,
12
+ * поставленной обычной установкой. `pg` отдаёт `jsonb` разобранным объектом,
13
+ * но драйвер не полагается на это: строка нормализуется (объект или JSON-
14
+ * строка), неполное значение игнорируется (fail-safe — откат просто
15
+ * недоступен, чтение записи не падает).
16
+ *
17
+ * **Режим исполнения (Ф4б-2).** Колонки `mode text` и `remote_entry text`
18
+ * (миграция `010`): режим `inline`/`remote`/`both` и путь к серверной точке
19
+ * входа (`dist/server.js`) нужны активации, чтобы выбрать транспорт и поднять
20
+ * процесс. `NULL` — поле в домене отсутствует (legacy-запись).
21
+ */
22
+ function toISO(value) {
23
+ if (value instanceof Date)
24
+ return value.toISOString();
25
+ return String(value);
26
+ }
27
+ /** Разобрать `previous` из `jsonb` (объект или JSON-строка); неполное — `undefined`. */
28
+ function normalizePrevious(value) {
29
+ let raw = value;
30
+ if (typeof raw === 'string') {
31
+ try {
32
+ raw = JSON.parse(raw);
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ }
38
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
39
+ return undefined;
40
+ const record = raw;
41
+ if (typeof record.version !== 'string' || typeof record.content_hash !== 'string') {
42
+ return undefined;
43
+ }
44
+ const previous = {
45
+ version: record.version,
46
+ content_hash: record.content_hash,
47
+ installed_at: typeof record.installed_at === 'string' ? record.installed_at : '',
48
+ };
49
+ if (typeof record.entry === 'string')
50
+ previous.entry = record.entry;
51
+ return previous;
52
+ }
53
+ function pluginLockRowToEntry(row) {
54
+ const entry = {
55
+ name: row.name,
56
+ version: row.version,
57
+ source: row.source,
58
+ trust_level: row.trust_level,
59
+ scan_verdict: row.scan_verdict,
60
+ content_hash: row.content_hash,
61
+ installed_at: toISO(row.installed_at),
62
+ updated_at: toISO(row.updated_at),
63
+ };
64
+ if (row.identifier !== null)
65
+ entry.identifier = row.identifier;
66
+ if (row.ref !== null)
67
+ entry.ref = row.ref;
68
+ if (row.entry !== null)
69
+ entry.entry = row.entry;
70
+ const previous = normalizePrevious(row.previous);
71
+ if (previous)
72
+ entry.previous = previous;
73
+ if (row.mode !== null && row.mode !== undefined) {
74
+ entry.mode = row.mode;
75
+ }
76
+ if (row.remote_entry !== null && row.remote_entry !== undefined) {
77
+ entry.remote_entry = row.remote_entry;
78
+ }
79
+ return entry;
80
+ }
81
+ /** Реализация порта `PluginLockRepository` поверх SQL. */
82
+ class PostgresPluginLockRepository {
83
+ _deps;
84
+ constructor(_deps) {
85
+ this._deps = _deps;
86
+ }
87
+ _db() {
88
+ return this._deps.connection;
89
+ }
90
+ async save(entry) {
91
+ await this._db().query(`INSERT INTO plugin_lock
92
+ (name, version, source, identifier, trust_level, scan_verdict, content_hash,
93
+ ref, entry, installed_at, updated_at, previous, mode, remote_entry)
94
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)
95
+ ON CONFLICT (name) DO UPDATE SET
96
+ version = EXCLUDED.version,
97
+ source = EXCLUDED.source,
98
+ identifier = EXCLUDED.identifier,
99
+ trust_level = EXCLUDED.trust_level,
100
+ scan_verdict = EXCLUDED.scan_verdict,
101
+ content_hash = EXCLUDED.content_hash,
102
+ ref = EXCLUDED.ref,
103
+ entry = EXCLUDED.entry,
104
+ installed_at = plugin_lock.installed_at,
105
+ updated_at = EXCLUDED.updated_at,
106
+ previous = EXCLUDED.previous,
107
+ mode = EXCLUDED.mode,
108
+ remote_entry = EXCLUDED.remote_entry`, [
109
+ entry.name,
110
+ entry.version,
111
+ entry.source,
112
+ entry.identifier ?? null,
113
+ entry.trust_level,
114
+ entry.scan_verdict,
115
+ entry.content_hash,
116
+ entry.ref ?? null,
117
+ entry.entry ?? null,
118
+ entry.installed_at,
119
+ entry.updated_at,
120
+ entry.previous ? JSON.stringify(entry.previous) : null,
121
+ entry.mode ?? null,
122
+ entry.remote_entry ?? null,
123
+ ]);
124
+ }
125
+ async get(name) {
126
+ const rows = await this._db().query('SELECT * FROM plugin_lock WHERE name = $1', [name]);
127
+ const row = rows[0];
128
+ return row ? pluginLockRowToEntry(row) : null;
129
+ }
130
+ async list() {
131
+ const rows = await this._db().query('SELECT * FROM plugin_lock ORDER BY name ASC');
132
+ return rows.map(pluginLockRowToEntry);
133
+ }
134
+ async delete(name) {
135
+ const rows = await this._db().query('WITH deleted AS (DELETE FROM plugin_lock WHERE name = $1 RETURNING 1) SELECT count(*)::int AS n FROM deleted', [name]);
136
+ const value = rows[0]?.n;
137
+ return typeof value === 'number' ? value > 0 : Number(value) > 0;
138
+ }
139
+ }
140
+ /** Собрать порт lock-файла плагинов. */
141
+ export function buildPluginLockPorts(deps) {
142
+ return {
143
+ pluginLock: new PostgresPluginLockRepository(deps),
144
+ };
145
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Порт `defaults` (умолчания оформления) PostgreSQL-драйвера
3
- * (PROP-032, волна 3b).
3
+ * (ADR-097, волна 3b).
4
4
  *
5
5
  * Эталон семантики — `DefaultsStore`/`MemoryDefaultsRepository`: `loadDefaults`
6
6
  * на пустом сторе — `{}`; `saveDefaults` — частичный патч, сливается поверх
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Порт `defaults` (умолчания оформления) PostgreSQL-драйвера
3
- * (PROP-032, волна 3b).
3
+ * (ADR-097, волна 3b).
4
4
  *
5
5
  * Эталон семантики — `DefaultsStore`/`MemoryDefaultsRepository`: `loadDefaults`
6
6
  * на пустом сторе — `{}`; `saveDefaults` — частичный патч, сливается поверх
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Порты `providers`/`models`/`agents` PostgreSQL-драйвера (PROP-032, волна 3b).
2
+ * Порты `providers`/`models`/`agents` PostgreSQL-драйвера (ADR-097, волна 3b).
3
3
  *
4
4
  * Все три — `DocumentRepository<T>` над одной таблицей `documents(kind, key,
5
5
  * value jsonb)`: `kind` = `provider`/`model`/`agent`, ключ документа — как в
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Порты `providers`/`models`/`agents` PostgreSQL-драйвера (PROP-032, волна 3b).
2
+ * Порты `providers`/`models`/`agents` PostgreSQL-драйвера (ADR-097, волна 3b).
3
3
  *
4
4
  * Все три — `DocumentRepository<T>` над одной таблицей `documents(kind, key,
5
5
  * value jsonb)`: `kind` = `provider`/`model`/`agent`, ключ документа — как в
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Порт `profiles` PostgreSQL-драйвера (PROP-032, волна 3b).
2
+ * Порт `profiles` PostgreSQL-драйвера (ADR-097, волна 3b).
3
3
  *
4
4
  * Эталон семантики — `FileProfileStore`/`MemoryProfileRepository`:
5
5
  * - `saveProfile` проставляет `updatedAt` при записи;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Порт `profiles` PostgreSQL-драйвера (PROP-032, волна 3b).
2
+ * Порт `profiles` PostgreSQL-драйвера (ADR-097, волна 3b).
3
3
  *
4
4
  * Эталон семантики — `FileProfileStore`/`MemoryProfileRepository`:
5
5
  * - `saveProfile` проставляет `updatedAt` при записи;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Порт `projects` PostgreSQL-драйвера (PROP-032, волна 3b).
2
+ * Порт `projects` PostgreSQL-драйвера (ADR-097, волна 3b).
3
3
  *
4
4
  * Эталон семантики — `ProjectStore`/`MemoryProjectRepository`:
5
5
  * - `create()` — синхронная чистая фабрика (id, `members`, 4 дефолтные колонки
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Порт `projects` PostgreSQL-драйвера (PROP-032, волна 3b).
2
+ * Порт `projects` PostgreSQL-драйвера (ADR-097, волна 3b).
3
3
  *
4
4
  * Эталон семантики — `ProjectStore`/`MemoryProjectRepository`:
5
5
  * - `create()` — синхронная чистая фабрика (id, `members`, 4 дефолтные колонки
@@ -40,6 +40,7 @@ function rowToProject(row) {
40
40
  repos: (row.repos ?? undefined),
41
41
  mcp: (row.mcp ?? undefined),
42
42
  skills: (row.skills ?? undefined),
43
+ memory: (row.memory ?? undefined),
43
44
  statusMessages: (row.status_messages ?? []),
44
45
  plan: (row.plan ?? undefined),
45
46
  log: (row.log ?? undefined),
@@ -59,10 +60,10 @@ export function createPrincipalProjectsPort(conn) {
59
60
  await conn.withTransaction(async (tx) => {
60
61
  await tx.query(`INSERT INTO projects (
61
62
  id, name, owner_id, description, current_task, invariants, icon, color,
62
- workspace, plan, log, status_messages, repos, mcp, skills, created_at, updated_at
63
+ workspace, plan, log, status_messages, repos, mcp, skills, memory, created_at, updated_at
63
64
  ) VALUES (
64
65
  $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
+ $9, $10::jsonb, $11::jsonb, $12::jsonb, $13::jsonb, $14::jsonb, $15::jsonb, $16::jsonb, $17, $18
66
67
  )
67
68
  ON CONFLICT (id) DO UPDATE SET
68
69
  name = EXCLUDED.name,
@@ -79,6 +80,7 @@ export function createPrincipalProjectsPort(conn) {
79
80
  repos = EXCLUDED.repos,
80
81
  mcp = EXCLUDED.mcp,
81
82
  skills = EXCLUDED.skills,
83
+ memory = EXCLUDED.memory,
82
84
  updated_at = EXCLUDED.updated_at`, [
83
85
  project.id,
84
86
  project.name,
@@ -95,6 +97,7 @@ export function createPrincipalProjectsPort(conn) {
95
97
  jsonbParam(project.repos ?? null),
96
98
  jsonbParam(project.mcp ?? null),
97
99
  jsonbParam(project.skills ?? null),
100
+ jsonbParam(project.memory ?? null),
98
101
  project.createdAt,
99
102
  project.updatedAt,
100
103
  ]);
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Порт `settings` (runtime-настройки инстанса) PostgreSQL-драйвера
3
- * (PROP-032, волна 3b).
3
+ * (ADR-097, волна 3b).
4
4
  *
5
5
  * Эталон семантики — `RuntimeSettingsStore`/`MemorySettingsRepository`:
6
6
  * - `load()` на пустом сторе — `{}` (не заданные секции в результат не попадают);
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Порт `settings` (runtime-настройки инстанса) PostgreSQL-драйвера
3
- * (PROP-032, волна 3b).
3
+ * (ADR-097, волна 3b).
4
4
  *
5
5
  * Эталон семантики — `RuntimeSettingsStore`/`MemorySettingsRepository`:
6
6
  * - `load()` на пустом сторе — `{}` (не заданные секции в результат не попадают);
@@ -38,6 +38,8 @@ const SECTION_KEYS = [
38
38
  'events',
39
39
  'decision',
40
40
  'proxy',
41
+ 'plugins',
42
+ 'attachments',
41
43
  ];
42
44
  const SECTION_KEY_SET = new Set(SECTION_KEYS);
43
45
  /** Собрать порт runtime-настроек поверх SQL. */
@@ -262,6 +264,15 @@ export function createPrincipalSettingsPort(conn) {
262
264
  async clearMetrics() {
263
265
  await deleteSetting(conn, 'metrics');
264
266
  },
267
+ async getPlugins() {
268
+ return (await readSetting(conn, 'plugins')) ?? {};
269
+ },
270
+ async setPlugins(config) {
271
+ await writeSetting(conn, 'plugins', config);
272
+ },
273
+ async clearPlugins() {
274
+ await deleteSetting(conn, 'plugins');
275
+ },
265
276
  async getProxySettings() {
266
277
  return readSetting(conn, 'proxy');
267
278
  },
@@ -271,5 +282,14 @@ export function createPrincipalSettingsPort(conn) {
271
282
  async clearProxySettings() {
272
283
  await deleteSetting(conn, 'proxy');
273
284
  },
285
+ async getAttachments() {
286
+ return (await readSetting(conn, 'attachments')) ?? {};
287
+ },
288
+ async setAttachments(config) {
289
+ await writeSetting(conn, 'attachments', config);
290
+ },
291
+ async clearAttachments() {
292
+ await deleteSetting(conn, 'attachments');
293
+ },
274
294
  };
275
295
  }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Общие утилиты группы портов `principals` PostgreSQL-драйвера
3
- * (PROP-032, волна 3b).
3
+ * (ADR-097, волна 3b).
4
4
  *
5
5
  * Драйвер объявляет `@itphx/synth-shared` обычной зависимостью, поэтому доменные
6
6
  * типы сущностей берутся из неё напрямую (алиасы — для читаемости портов).
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Общие утилиты группы портов `principals` PostgreSQL-драйвера
3
- * (PROP-032, волна 3b).
3
+ * (ADR-097, волна 3b).
4
4
  *
5
5
  * Драйвер объявляет `@itphx/synth-shared` обычной зависимостью, поэтому доменные
6
6
  * типы сущностей берутся из неё напрямую (алиасы — для читаемости портов).
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Группа портов **принципалов и конфигурации** PostgreSQL-драйвера
3
- * (PROP-032, волна 3b).
3
+ * (ADR-097, волна 3b).
4
4
  *
5
5
  * Владелец файла — один агент волны реализации; правит `principals.ts` и
6
6
  * `principals-*.ts`. Файл экспортирует единственную фабрику
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Группа портов **принципалов и конфигурации** PostgreSQL-драйвера
3
- * (PROP-032, волна 3b).
3
+ * (ADR-097, волна 3b).
4
4
  *
5
5
  * Владелец файла — один агент волны реализации; правит `principals.ts` и
6
6
  * `principals-*.ts`. Файл экспортирует единственную фабрику
@@ -0,0 +1,40 @@
1
+ /**
2
+ * PG-реализация порта **вопросов пользователю** (этап 1 roadmap 0.13 — блок 1.3,
3
+ * ADR-097).
4
+ *
5
+ * Таблица `questions` (миграция 021): состав вопросов и ответы — `jsonb`,
6
+ * выборки — по сессии и статусу, порядок — «свежие первыми»
7
+ * (`created_at` убыв., тайбрейкер `id`).
8
+ *
9
+ * Семантика повторяет файловые реализации core (`FileQuestionStore`) и
10
+ * in-memory (`MemoryQuestionRepository`):
11
+ * - upsert по `id`: `created_at` не перезаписывается, `updated_at` — метка
12
+ * вызывающего (драйвер не подставляет «сейчас» — иначе retention-очистка по
13
+ * метке записи теряла бы смысл);
14
+ * - `prune` — **только терминальные** статусы (`answered`/`cancelled`), метка
15
+ * которых строго старше отсечки (`updated_at < $1`).
16
+ *
17
+ * Драйвер не тянет core рантаймом (только `import type`), поэтому потолок
18
+ * выборки и правила timestamps повторены здесь локально — как в
19
+ * `ports/pipelines.ts`.
20
+ */
21
+ import type { QuestionRepository, StorageContext } from '@itphx/synth-core';
22
+ import type { QuestionRecord, QuestionStatus } from '@itphx/synth-shared';
23
+ import type { PortDeps } from './deps.js';
24
+ /** Часть `StorageContext`, которой владеет группа «вопросы/фоны». */
25
+ export type QuestionPorts = Pick<StorageContext, 'questions'>;
26
+ /** Порт вопросов пользователю поверх таблицы `questions`. */
27
+ export declare class PgQuestionRepository implements QuestionRepository {
28
+ private readonly _deps;
29
+ constructor(_deps: PortDeps);
30
+ save(record: QuestionRecord): Promise<void>;
31
+ get(id: string): Promise<QuestionRecord | null>;
32
+ list(filter?: {
33
+ sessionId?: string;
34
+ status?: QuestionStatus;
35
+ limit?: number;
36
+ }): Promise<QuestionRecord[]>;
37
+ prune(before: string): Promise<number>;
38
+ }
39
+ /** Собрать порты группы «вопросы» (этап 1 roadmap 0.13, блок 1.3). */
40
+ export declare function buildQuestionPorts(deps: PortDeps): QuestionPorts;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * PG-реализация порта **вопросов пользователю** (этап 1 roadmap 0.13 — блок 1.3,
3
+ * ADR-097).
4
+ *
5
+ * Таблица `questions` (миграция 021): состав вопросов и ответы — `jsonb`,
6
+ * выборки — по сессии и статусу, порядок — «свежие первыми»
7
+ * (`created_at` убыв., тайбрейкер `id`).
8
+ *
9
+ * Семантика повторяет файловые реализации core (`FileQuestionStore`) и
10
+ * in-memory (`MemoryQuestionRepository`):
11
+ * - upsert по `id`: `created_at` не перезаписывается, `updated_at` — метка
12
+ * вызывающего (драйвер не подставляет «сейчас» — иначе retention-очистка по
13
+ * метке записи теряла бы смысл);
14
+ * - `prune` — **только терминальные** статусы (`answered`/`cancelled`), метка
15
+ * которых строго старше отсечки (`updated_at < $1`).
16
+ *
17
+ * Драйвер не тянет core рантаймом (только `import type`), поэтому потолок
18
+ * выборки и правила timestamps повторены здесь локально — как в
19
+ * `ports/pipelines.ts`.
20
+ */
21
+ import { jsonbParam } from '../json-param.js';
22
+ import { compact, toIso, toIsoRequired } from './events-core.js';
23
+ // ── Локальные реплики core-хелперов (core рантаймом не тянем) ────────────────
24
+ /** Дефолтный потолок выборки (паритет с core `COLLECTION_LIMIT_DEFAULT`). */
25
+ const LIST_DEFAULT_LIMIT = 100;
26
+ /** Абсолютный потолок выборки (паритет с core `COLLECTION_LIMIT_MAX`). */
27
+ const LIST_MAX_LIMIT = 1000;
28
+ /** Привести `limit` к допустимому виду: дефолт 100, потолок 1000. */
29
+ function resolveLimit(limit) {
30
+ if (limit === undefined || !Number.isFinite(limit) || limit <= 0)
31
+ return LIST_DEFAULT_LIMIT;
32
+ return Math.min(Math.floor(limit), LIST_MAX_LIMIT);
33
+ }
34
+ /** Терминальные статусы вопроса (очищаемые; `pending` — не терминальный). */
35
+ const TERMINAL_STATUSES = ['answered', 'cancelled'];
36
+ /** Запись вопроса из колонок. */
37
+ function toQuestion(row) {
38
+ return compact({
39
+ id: row.id,
40
+ sessionId: row.session_id,
41
+ turnId: row.turn_id ?? undefined,
42
+ toolCallId: row.tool_call_id ?? undefined,
43
+ agentRole: row.agent_role ?? undefined,
44
+ questions: (row.questions ?? []),
45
+ status: row.status,
46
+ answers: (row.answers ?? undefined),
47
+ createdAt: toIsoRequired(row.created_at),
48
+ updatedAt: toIsoRequired(row.updated_at),
49
+ expiresAt: toIso(row.expires_at),
50
+ answeredAt: toIso(row.answered_at),
51
+ cancelledAt: toIso(row.cancelled_at),
52
+ cancelReason: row.cancel_reason ?? undefined,
53
+ answeredBy: row.answered_by ?? undefined,
54
+ });
55
+ }
56
+ /** Порт вопросов пользователю поверх таблицы `questions`. */
57
+ export class PgQuestionRepository {
58
+ _deps;
59
+ constructor(_deps) {
60
+ this._deps = _deps;
61
+ }
62
+ async save(record) {
63
+ await this._deps.connection.query(`INSERT INTO questions
64
+ (id, session_id, turn_id, tool_call_id, agent_role, questions, status, answers,
65
+ created_at, updated_at, expires_at, answered_at, cancelled_at, cancel_reason, answered_by)
66
+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8::jsonb, $9::timestamptz,
67
+ $10::timestamptz, $11::timestamptz, $12::timestamptz, $13::timestamptz, $14, $15)
68
+ ON CONFLICT (id) DO UPDATE SET
69
+ session_id = EXCLUDED.session_id,
70
+ turn_id = EXCLUDED.turn_id,
71
+ tool_call_id = EXCLUDED.tool_call_id,
72
+ agent_role = EXCLUDED.agent_role,
73
+ questions = EXCLUDED.questions,
74
+ status = EXCLUDED.status,
75
+ answers = EXCLUDED.answers,
76
+ created_at = questions.created_at,
77
+ updated_at = EXCLUDED.updated_at,
78
+ expires_at = EXCLUDED.expires_at,
79
+ answered_at = EXCLUDED.answered_at,
80
+ cancelled_at = EXCLUDED.cancelled_at,
81
+ cancel_reason = EXCLUDED.cancel_reason,
82
+ answered_by = EXCLUDED.answered_by`, [
83
+ record.id,
84
+ record.sessionId,
85
+ record.turnId ?? null,
86
+ record.toolCallId ?? null,
87
+ record.agentRole ?? null,
88
+ jsonbParam(record.questions),
89
+ record.status,
90
+ record.answers !== undefined ? jsonbParam(record.answers) : null,
91
+ record.createdAt,
92
+ record.updatedAt,
93
+ record.expiresAt ?? null,
94
+ record.answeredAt ?? null,
95
+ record.cancelledAt ?? null,
96
+ record.cancelReason ?? null,
97
+ record.answeredBy ?? null,
98
+ ]);
99
+ }
100
+ async get(id) {
101
+ const rows = await this._deps.connection.query('SELECT * FROM questions WHERE id = $1 LIMIT 1', [id]);
102
+ return rows[0] ? toQuestion(rows[0]) : null;
103
+ }
104
+ async list(filter) {
105
+ const params = [];
106
+ const where = [];
107
+ if (filter?.sessionId !== undefined) {
108
+ params.push(filter.sessionId);
109
+ where.push(`session_id = $${params.length}`);
110
+ }
111
+ if (filter?.status !== undefined) {
112
+ params.push(filter.status);
113
+ where.push(`status = $${params.length}`);
114
+ }
115
+ params.push(resolveLimit(filter?.limit));
116
+ const sql = 'SELECT * FROM questions' +
117
+ (where.length ? ` WHERE ${where.join(' AND ')}` : '') +
118
+ ' ORDER BY created_at DESC, id ASC' +
119
+ ` LIMIT $${params.length}`;
120
+ const rows = await this._deps.connection.query(sql, params);
121
+ return rows.map(toQuestion);
122
+ }
123
+ async prune(before) {
124
+ const rows = await this._deps.connection.query(`DELETE FROM questions
125
+ WHERE status = ANY($1::text[]) AND updated_at < $2::timestamptz
126
+ RETURNING id`, [[...TERMINAL_STATUSES], before]);
127
+ return rows.length;
128
+ }
129
+ }
130
+ /** Собрать порты группы «вопросы» (этап 1 roadmap 0.13, блок 1.3). */
131
+ export function buildQuestionPorts(deps) {
132
+ return {
133
+ questions: new PgQuestionRepository(deps),
134
+ };
135
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Отображение строк PostgreSQL ↔ доменных объектов порта `SessionRepository`
3
- * (PROP-032, волна 3b).
3
+ * (ADR-097, волна 3b).
4
4
  *
5
5
  * Эталон семантики — файловая реализация (`core/src/storage/file-store.ts`):
6
6
  * `serializeSession`/`serializeMessage` и `deserializeSession`/`deserializeMessage`
@@ -18,7 +18,7 @@
18
18
  * `buildContentFromParts`, `generateId`) берутся напрямую из
19
19
  * `@itphx/synth-shared` — обычной зависимости драйвера (ADR-097).
20
20
  */
21
- import { type Checkpoint, type Message, type Session, type SessionReference, type StickyNote } from '@itphx/synth-shared';
21
+ import { type Checkpoint, type Message, type Session, type SessionReference, type SessionWorktree, type StickyNote } from '@itphx/synth-shared';
22
22
  /** Строка `sessions` (jsonb — уже разобранные значения; `bigint` — строка). */
23
23
  export interface SessionRow {
24
24
  id: string;
@@ -30,9 +30,16 @@ export interface SessionRow {
30
30
  branch_point: string | null;
31
31
  plan_approved: boolean | null;
32
32
  mode: string | null;
33
+ /** ADR-106 Ф4 (шаг C): режим по принципалу (переопределения режима сессии). */
34
+ mode_by_principal: unknown;
33
35
  user_id: string | null;
34
36
  owner_id: string | null;
35
37
  project_id: string | null;
38
+ /**
39
+ * ADR-114: привязка сессии к worktree (jsonb). В записях, созданных до
40
+ * миграции `023`, поля нет — чтение даёт `undefined`.
41
+ */
42
+ worktree?: unknown;
36
43
  todos: unknown;
37
44
  prompt_states: unknown;
38
45
  obfuscation_map: unknown;
@@ -40,6 +47,8 @@ export interface SessionRow {
40
47
  settings: unknown;
41
48
  mcp_servers: unknown;
42
49
  pending_messages: unknown;
50
+ /** ADR-104: очередь инъекций (steering) — отдельно от `pending_messages`. */
51
+ steer_inbox: unknown;
43
52
  current_stream: unknown;
44
53
  summarization_pending: boolean;
45
54
  can_summarize: boolean;
@@ -221,6 +230,14 @@ export declare function deserializeCheckpoint(row: CheckpointRow): Checkpoint;
221
230
  export declare function stickyNoteRow(sessionId: string, note: StickyNote): Record<string, unknown>;
222
231
  /** Строка `sticky_notes` → доменная заметка. */
223
232
  export declare function deserializeStickyNote(row: StickyNoteRow): StickyNote;
233
+ /**
234
+ * ADR-114: привязка сессии к worktree из jsonb-колонки `sessions.worktree`.
235
+ *
236
+ * Терпима к отсутствию поля (записи до миграции `023`) и к частичным
237
+ * значениям: привязка без `worktree_id`/`directory` бессмысленна — она
238
+ * игнорируется, сессия работает как прежде.
239
+ */
240
+ export declare function deserializeSessionWorktree(data: unknown): SessionWorktree | undefined;
224
241
  /**
225
242
  * Строка `sessions` + child-данные → доменная сессия: дословный
226
243
  * `deserializeSession` файловой реализации (нормализация иконки/цвета,
@@ -230,7 +247,7 @@ export declare function deserializeStickyNote(row: StickyNoteRow): StickyNote;
230
247
  export declare function deserializeSession(row: SessionRow, children: SessionChildren): Session;
231
248
  /**
232
249
  * Строка `sessions` → доменная сессия **без истории** (`SessionRepository.listLight`,
233
- * PROP-032): `messages`/`pendingMessages`/`checkpoints` пусты, child-таблицы не
250
+ * ADR-097): `messages`/`pendingMessages`/`checkpoints` пусты, child-таблицы не
234
251
  * читаются. Метаданные (id/статус/settings/projectId/expiresAt/…) идентичны
235
252
  * `deserializeSession` — механика переиспользуется.
236
253
  */