@itphx/synth-storage-postgres 0.11.3 → 0.13.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 (147) 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/028-message-reasoning-signature.d.ts +13 -0
  62. package/dist/migrations/028-message-reasoning-signature.js +19 -0
  63. package/dist/migrations/029-message-stream-v2.d.ts +22 -0
  64. package/dist/migrations/029-message-stream-v2.js +33 -0
  65. package/dist/migrations/030-session-retry.d.ts +12 -0
  66. package/dist/migrations/030-session-retry.js +16 -0
  67. package/dist/migrations/index.d.ts +1 -1
  68. package/dist/migrations/index.js +55 -1
  69. package/dist/pool.d.ts +6 -6
  70. package/dist/pool.js +8 -8
  71. package/dist/ports/analytics.d.ts +1 -1
  72. package/dist/ports/analytics.js +1 -1
  73. package/dist/ports/audit.d.ts +1 -1
  74. package/dist/ports/audit.js +3 -0
  75. package/dist/ports/authority.d.ts +27 -0
  76. package/dist/ports/authority.js +148 -0
  77. package/dist/ports/background-runs.d.ts +41 -0
  78. package/dist/ports/background-runs.js +179 -0
  79. package/dist/ports/blob-refs.d.ts +36 -0
  80. package/dist/ports/blob-refs.js +55 -0
  81. package/dist/ports/content.d.ts +1 -1
  82. package/dist/ports/content.js +21 -7
  83. package/dist/ports/context-files.d.ts +147 -0
  84. package/dist/ports/context-files.js +285 -0
  85. package/dist/ports/core-sync.d.ts +1 -1
  86. package/dist/ports/core-sync.js +1 -1
  87. package/dist/ports/credential-audit.d.ts +19 -0
  88. package/dist/ports/credential-audit.js +96 -0
  89. package/dist/ports/deps.d.ts +2 -2
  90. package/dist/ports/deps.js +1 -1
  91. package/dist/ports/events-bindings.d.ts +2 -2
  92. package/dist/ports/events-bindings.js +2 -2
  93. package/dist/ports/events-core.d.ts +1 -1
  94. package/dist/ports/events-core.js +1 -1
  95. package/dist/ports/events-journal.d.ts +1 -1
  96. package/dist/ports/events-journal.js +1 -1
  97. package/dist/ports/events-scheduler.d.ts +1 -1
  98. package/dist/ports/events-scheduler.js +20 -12
  99. package/dist/ports/events-webhooks.d.ts +1 -1
  100. package/dist/ports/events-webhooks.js +1 -1
  101. package/dist/ports/events.d.ts +1 -1
  102. package/dist/ports/events.js +1 -1
  103. package/dist/ports/external-credentials.d.ts +6 -0
  104. package/dist/ports/external-credentials.js +363 -0
  105. package/dist/ports/legacy-pipelines.d.ts +50 -0
  106. package/dist/ports/legacy-pipelines.js +202 -0
  107. package/dist/ports/memory.d.ts +65 -0
  108. package/dist/ports/memory.js +471 -0
  109. package/dist/ports/packs.d.ts +32 -0
  110. package/dist/ports/packs.js +117 -0
  111. package/dist/ports/pipelines.d.ts +67 -0
  112. package/dist/ports/pipelines.js +297 -0
  113. package/dist/ports/plugin-audit.d.ts +14 -0
  114. package/dist/ports/plugin-audit.js +110 -0
  115. package/dist/ports/plugin-lock.d.ts +27 -0
  116. package/dist/ports/plugin-lock.js +145 -0
  117. package/dist/ports/principals-defaults.d.ts +1 -1
  118. package/dist/ports/principals-defaults.js +21 -1
  119. package/dist/ports/principals-documents.d.ts +1 -1
  120. package/dist/ports/principals-documents.js +1 -1
  121. package/dist/ports/principals-profiles.d.ts +1 -1
  122. package/dist/ports/principals-profiles.js +1 -1
  123. package/dist/ports/principals-projects.d.ts +1 -1
  124. package/dist/ports/principals-projects.js +82 -47
  125. package/dist/ports/principals-settings.d.ts +1 -1
  126. package/dist/ports/principals-settings.js +57 -1
  127. package/dist/ports/principals-shared.d.ts +1 -1
  128. package/dist/ports/principals-shared.js +1 -1
  129. package/dist/ports/principals.d.ts +1 -1
  130. package/dist/ports/principals.js +1 -1
  131. package/dist/ports/questions.d.ts +40 -0
  132. package/dist/ports/questions.js +135 -0
  133. package/dist/ports/sessions-mapping.d.ts +80 -6
  134. package/dist/ports/sessions-mapping.js +165 -8
  135. package/dist/ports/sessions.d.ts +62 -8
  136. package/dist/ports/sessions.js +96 -20
  137. package/dist/ports/skills.d.ts +59 -0
  138. package/dist/ports/skills.js +205 -0
  139. package/dist/ports/stub.d.ts +1 -1
  140. package/dist/ports/stub.js +2 -2
  141. package/dist/ports/worktrees.d.ts +41 -0
  142. package/dist/ports/worktrees.js +85 -0
  143. package/dist/postgres-storage.d.ts +4 -5
  144. package/dist/postgres-storage.js +5 -6
  145. package/dist/storage-context.d.ts +44 -15
  146. package/dist/storage-context.js +139 -31
  147. package/package.json +4 -4
@@ -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` — частичный патч, сливается поверх
@@ -17,6 +17,9 @@ export const DEFAULTS_SETTINGS_KEY = 'defaults';
17
17
  /** Минимальный/максимальный допустимый масштаб интерфейса (паритет `DefaultsStore`). */
18
18
  const UI_SCALE_MIN = 0.5;
19
19
  const UI_SCALE_MAX = 1.2;
20
+ /** Диапазон масштаба области чата (паритет `DefaultsStore`/UI `CHAT_SCALE_*`). */
21
+ const CHAT_SCALE_MIN = 0.75;
22
+ const CHAT_SCALE_MAX = 1.5;
20
23
  /** Масштаб интерфейса: число в диапазоне 0.5..1.2, иначе `undefined`. */
21
24
  function sanitizeScale(value) {
22
25
  if (typeof value === 'number' && Number.isFinite(value) && value >= UI_SCALE_MIN && value <= UI_SCALE_MAX) {
@@ -24,6 +27,13 @@ function sanitizeScale(value) {
24
27
  }
25
28
  return undefined;
26
29
  }
30
+ /** Масштаб области чата: число в диапазоне 0.75..1.5, иначе `undefined`. */
31
+ function sanitizeChatScale(value) {
32
+ if (typeof value === 'number' && Number.isFinite(value) && value >= CHAT_SCALE_MIN && value <= CHAT_SCALE_MAX) {
33
+ return value;
34
+ }
35
+ return undefined;
36
+ }
27
37
  /** Оставить только валидные поля умолчаний оформления (паритет `DefaultsStore`). */
28
38
  function sanitize(raw) {
29
39
  if (typeof raw !== 'object' || raw === null)
@@ -43,6 +53,16 @@ function sanitize(raw) {
43
53
  const desktop = sanitizeScale(src.uiScaleDesktop);
44
54
  if (desktop !== undefined)
45
55
  out.uiScaleDesktop = desktop;
56
+ if (src.chatViewMode === 'detailed' || src.chatViewMode === 'feed')
57
+ out.chatViewMode = src.chatViewMode;
58
+ if (src.chatDensity === 'normal' || src.chatDensity === 'compact')
59
+ out.chatDensity = src.chatDensity;
60
+ const chatMobile = sanitizeChatScale(src.chatScaleMobile);
61
+ if (chatMobile !== undefined)
62
+ out.chatScaleMobile = chatMobile;
63
+ const chatDesktop = sanitizeChatScale(src.chatScaleDesktop);
64
+ if (chatDesktop !== undefined)
65
+ out.chatScaleDesktop = chatDesktop;
46
66
  return out;
47
67
  }
48
68
  /** Прочитать умолчания оформления (без блокировки — чтение). */
@@ -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),
@@ -47,6 +48,61 @@ function rowToProject(row) {
47
48
  updatedAt: requiredIso(row.updated_at),
48
49
  };
49
50
  }
51
+ /**
52
+ * Запись проекта в БД (строка + набор участий) **тем же соединением/транзакцией**,
53
+ * что и вызывающий: `save` и `mutate` не дублируют SQL и не открывают вложенную
54
+ * транзакцию.
55
+ */
56
+ async function writeProject(tx, project) {
57
+ await tx.query(`INSERT INTO projects (
58
+ id, name, owner_id, description, current_task, invariants, icon, color,
59
+ workspace, plan, log, status_messages, repos, mcp, skills, memory, created_at, updated_at
60
+ ) VALUES (
61
+ $1, $2, $3, $4, $5, $6, $7, $8,
62
+ $9, $10::jsonb, $11::jsonb, $12::jsonb, $13::jsonb, $14::jsonb, $15::jsonb, $16::jsonb, $17, $18
63
+ )
64
+ ON CONFLICT (id) DO UPDATE SET
65
+ name = EXCLUDED.name,
66
+ owner_id = EXCLUDED.owner_id,
67
+ description = EXCLUDED.description,
68
+ current_task = EXCLUDED.current_task,
69
+ invariants = EXCLUDED.invariants,
70
+ icon = EXCLUDED.icon,
71
+ color = EXCLUDED.color,
72
+ workspace = EXCLUDED.workspace,
73
+ plan = EXCLUDED.plan,
74
+ log = EXCLUDED.log,
75
+ status_messages = EXCLUDED.status_messages,
76
+ repos = EXCLUDED.repos,
77
+ mcp = EXCLUDED.mcp,
78
+ skills = EXCLUDED.skills,
79
+ memory = EXCLUDED.memory,
80
+ updated_at = EXCLUDED.updated_at`, [
81
+ project.id,
82
+ project.name,
83
+ project.ownerId,
84
+ project.description ?? '',
85
+ project.currentTask ?? '',
86
+ project.invariants ?? '',
87
+ project.icon ?? null,
88
+ project.color ?? null,
89
+ project.workspace ?? null,
90
+ jsonbParam(project.plan ?? null),
91
+ jsonbParam(project.log ?? null),
92
+ jsonbParam(project.statusMessages ?? []),
93
+ jsonbParam(project.repos ?? null),
94
+ jsonbParam(project.mcp ?? null),
95
+ jsonbParam(project.skills ?? null),
96
+ jsonbParam(project.memory ?? null),
97
+ project.createdAt,
98
+ project.updatedAt,
99
+ ]);
100
+ // Набор участий — источник истины в самом проекте: заменяем целиком.
101
+ await tx.query('DELETE FROM project_members WHERE project_id = $1', [project.id]);
102
+ for (const [userId, role] of Object.entries(project.members ?? {})) {
103
+ await tx.query('INSERT INTO project_members (project_id, user_id, role) VALUES ($1, $2, $3)', [project.id, userId, role]);
104
+ }
105
+ }
50
106
  /** Собрать порт проектов поверх SQL. */
51
107
  export function createPrincipalProjectsPort(conn) {
52
108
  return {
@@ -57,52 +113,31 @@ export function createPrincipalProjectsPort(conn) {
57
113
  },
58
114
  async save(project) {
59
115
  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
- }
116
+ await writeProject(tx, project);
117
+ });
118
+ },
119
+ /**
120
+ * Атомарный read-modify-write (порт `ProjectRepository.mutate`): блокировка
121
+ * строки `projects` и запись в **одной** транзакции, поэтому параллельные
122
+ * мутации одного проекта сериализуются и не теряют правки друг друга.
123
+ *
124
+ * `FOR UPDATE OF p` — обязательный: `SELECT_PROJECT` содержит
125
+ * `LEFT JOIN LATERAL`, а `FOR UPDATE` без `OF` PostgreSQL отвергает
126
+ * («cannot be applied to the nullable side of an outer join»). `OF p`
127
+ * блокирует только строку проекта (строка агрегата `members` — подзапрос,
128
+ * её lock не нужен: чтение участий идёт в той же транзакции-снимке, а запись
129
+ * заменяет набор под той же блокировкой).
130
+ */
131
+ async mutate(id, mutator) {
132
+ return conn.withTransaction(async (tx) => {
133
+ const rows = await tx.query(`${SELECT_PROJECT} WHERE p.id = $1 FOR UPDATE OF p`, [id]);
134
+ const row = rows[0];
135
+ if (!row)
136
+ return null;
137
+ const project = rowToProject(row);
138
+ mutator(project);
139
+ await writeProject(tx, project);
140
+ return project;
106
141
  });
107
142
  },
108
143
  async delete(id) {
@@ -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,50 @@ 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
+ },
294
+ async getContextWindowPolicy() {
295
+ return readSetting(conn, 'contextWindowPolicy');
296
+ },
297
+ async setContextWindowPolicy(policy) {
298
+ await writeSetting(conn, 'contextWindowPolicy', policy);
299
+ },
300
+ async clearContextWindowPolicy() {
301
+ await deleteSetting(conn, 'contextWindowPolicy');
302
+ },
303
+ async getSubagentMaxInputTokens() {
304
+ return readSetting(conn, 'subagentMaxInputTokens');
305
+ },
306
+ async setSubagentMaxInputTokens(value) {
307
+ await writeSetting(conn, 'subagentMaxInputTokens', value);
308
+ },
309
+ async clearSubagentMaxInputTokens() {
310
+ await deleteSetting(conn, 'subagentMaxInputTokens');
311
+ },
312
+ async getContextDefaults() {
313
+ return readSetting(conn, 'contextDefaults');
314
+ },
315
+ async setContextDefaults(defaults) {
316
+ await writeSetting(conn, 'contextDefaults', defaults);
317
+ },
318
+ async clearContextDefaults() {
319
+ await deleteSetting(conn, 'contextDefaults');
320
+ },
321
+ async getStickyNotesLimits() {
322
+ return readSetting(conn, 'stickyNotesLimits');
323
+ },
324
+ async setStickyNotesLimits(limits) {
325
+ await writeSetting(conn, 'stickyNotesLimits', limits);
326
+ },
327
+ async clearStickyNotesLimits() {
328
+ await deleteSetting(conn, 'stickyNotesLimits');
329
+ },
274
330
  };
275
331
  }
@@ -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
+ }