@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,117 @@
1
+ /**
2
+ * PG-реализация порта **реестра установок пакетов расширений**
3
+ * (ADR-086 §5 / PROP-068, ADR-116, ADR-097).
4
+ *
5
+ * Хранение — таблица `pack_installations` (миграция `025_packs_pipelines`):
6
+ * ключ записи — **имя пакета** (уникально в инстансе), `manifest`/`files`/
7
+ * `provides` — `jsonb`.
8
+ *
9
+ * Семантика повторяет файловую реализацию core (`FilePackStore`) и in-memory
10
+ * (`MemoryPackRepository`):
11
+ * - `save` — upsert по `name`: `installed_at` не перезаписывается, `updated_at`
12
+ * монотонно не убывает (в SQL — `GREATEST` + сдвиг 1 мс, паритет с
13
+ * `record-timestamps.ts` core);
14
+ * - `get` — `null` для неизвестного имени;
15
+ * - `list` — детерминированный порядок (`ORDER BY name ASC`);
16
+ * - `delete` — `true`, если запись была удалена (снятие установки), иначе `false`.
17
+ */
18
+ import { jsonbParam } from '../json-param.js';
19
+ import { compact, toIsoRequired } from './events-core.js';
20
+ /**
21
+ * Выражение `updated_at` при upsert: максимум из «сейчас», входящего и
22
+ * сохранённого значения; если максимум совпал с сохранённым — сдвиг на 1 мс
23
+ * (паритет с `resolveUpdatedAt` в `record-timestamps.ts` core: метка не
24
+ * откатывается и всегда наблюдаема). Локальная реплика — как в
25
+ * `ports/pipelines.ts`: драйвер не тянет core рантаймом.
26
+ */
27
+ function updatedAtExpr(table) {
28
+ return `CASE
29
+ WHEN GREATEST(EXCLUDED.updated_at, ${table}.updated_at, now()) <= ${table}.updated_at
30
+ THEN ${table}.updated_at + interval '1 millisecond'
31
+ ELSE GREATEST(EXCLUDED.updated_at, ${table}.updated_at, now())
32
+ END`;
33
+ }
34
+ /** Пустой набор вкладов (страховка для чтения битой/пустой записи `provides`). */
35
+ function emptyProvides() {
36
+ return { agents: [], skills: [], mcp: [], pipelines: [] };
37
+ }
38
+ /** Запись реестра из колонок: `null` → отсутствие необязательного поля. */
39
+ function toPack(row) {
40
+ return compact({
41
+ name: row.name,
42
+ version: row.version,
43
+ kind: row.kind,
44
+ packType: row.pack_type ?? undefined,
45
+ description: row.description ?? undefined,
46
+ status: row.status,
47
+ requiresApproval: row.requires_approval,
48
+ trustLevel: (row.trust_level ?? undefined),
49
+ provides: (row.provides ?? emptyProvides()),
50
+ manifest: row.manifest ?? undefined,
51
+ files: (row.files ?? undefined),
52
+ installedAt: toIsoRequired(row.installed_at),
53
+ updatedAt: toIsoRequired(row.updated_at),
54
+ installedBy: row.installed_by ?? undefined,
55
+ });
56
+ }
57
+ /** Реестр установок пакетов поверх таблицы `pack_installations`. */
58
+ export class PgPackRepository {
59
+ _deps;
60
+ constructor(_deps) {
61
+ this._deps = _deps;
62
+ }
63
+ async save(pack) {
64
+ await this._deps.connection.query(`INSERT INTO pack_installations
65
+ (name, version, kind, pack_type, description, status, requires_approval,
66
+ trust_level, manifest, files, provides, installed_by, installed_at, updated_at)
67
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10::jsonb, $11::jsonb, $12,
68
+ $13::timestamptz, GREATEST($14::timestamptz, now()))
69
+ ON CONFLICT (name) DO UPDATE SET
70
+ version = EXCLUDED.version,
71
+ kind = EXCLUDED.kind,
72
+ pack_type = EXCLUDED.pack_type,
73
+ description = EXCLUDED.description,
74
+ status = EXCLUDED.status,
75
+ requires_approval = EXCLUDED.requires_approval,
76
+ trust_level = EXCLUDED.trust_level,
77
+ manifest = EXCLUDED.manifest,
78
+ files = EXCLUDED.files,
79
+ provides = EXCLUDED.provides,
80
+ installed_by = EXCLUDED.installed_by,
81
+ installed_at = pack_installations.installed_at,
82
+ updated_at = ${updatedAtExpr('pack_installations')}`, [
83
+ pack.name,
84
+ pack.version,
85
+ pack.kind,
86
+ pack.packType ?? null,
87
+ pack.description ?? null,
88
+ pack.status,
89
+ pack.requiresApproval,
90
+ pack.trustLevel ?? null,
91
+ pack.manifest !== undefined ? jsonbParam(pack.manifest) : null,
92
+ pack.files !== undefined ? jsonbParam(pack.files) : null,
93
+ jsonbParam(pack.provides ?? emptyProvides()),
94
+ pack.installedBy ?? null,
95
+ pack.installedAt,
96
+ pack.updatedAt,
97
+ ]);
98
+ }
99
+ async get(name) {
100
+ const rows = await this._deps.connection.query('SELECT * FROM pack_installations WHERE name = $1 LIMIT 1', [name]);
101
+ return rows[0] ? toPack(rows[0]) : null;
102
+ }
103
+ async list() {
104
+ const rows = await this._deps.connection.query('SELECT * FROM pack_installations ORDER BY name ASC');
105
+ return rows.map(toPack);
106
+ }
107
+ async delete(name) {
108
+ const rows = await this._deps.connection.query('DELETE FROM pack_installations WHERE name = $1 RETURNING name', [name]);
109
+ return rows.length > 0;
110
+ }
111
+ }
112
+ /** Собрать порт реестра установок пакетов (ADR-086 §5). */
113
+ export function buildPackPorts(deps) {
114
+ return {
115
+ packs: new PgPackRepository(deps),
116
+ };
117
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * PG-реализация портов **движка пайплайнов** (ADR-101): спецификации
3
+ * (черновик + опубликованные версии), прогоны и журнал выполнения.
4
+ *
5
+ * Таблицы (миграция 004): `pipeline_specs`, `pipeline_versions`, `pipeline_runs`,
6
+ * `pipeline_run_events`.
7
+ *
8
+ * Семантика повторяет файловые реализации core (`FileProjectPipelineStore`,
9
+ * `FilePipelineRunStore`):
10
+ * - upsert по `id`: `created_at` не перезаписывается, `updated_at` монотонно
11
+ * не убывает (в SQL — `GREATEST` + сдвиг 1 мс, паритет с
12
+ * `record-timestamps.ts` core);
13
+ * - список пайплайнов — по `id` asc, фильтры `scope`/`projectId` — по «И»;
14
+ * - список прогонов — «свежие первыми» (`created_at` убыв., тайбрейкер `id`),
15
+ * фильтры — по «И», `limit` — дефолт 100 / потолок 1000;
16
+ * - журнал событий — **append-only** (`seq bigserial`), чтение хронологическое
17
+ * (по `ts`, затем порядок добавления), `limit` — последние N;
18
+ * - удаление пайплайна удаляет его версии, но **не** прогоны (прогон
19
+ * самодостаточен — несёт снимок спецификации).
20
+ *
21
+ * Драйвер не тянет core рантаймом (только `import type`), поэтому потолок
22
+ * выборки и правило timestamps повторены здесь локально — как в
23
+ * `ports/analytics.ts` (локальная точная реплика core-хелпера).
24
+ */
25
+ import type { PipelineRecord, PipelineRunEventRecord, PipelineRunRecord, PipelineRunRepository, PipelineScope, PipelineVersionRecord, ProjectPipelineRepository, StorageContext } from '@itphx/synth-core';
26
+ import type { PortDeps } from './deps.js';
27
+ /** Часть `StorageContext`, которой владеет группа `pipelines`. */
28
+ export type PipelinePorts = Pick<StorageContext, 'projectPipelines' | 'pipelineRuns'>;
29
+ /**
30
+ * ADR-101: спецификации пайплайнов поверх `pipeline_specs`/`pipeline_versions`.
31
+ */
32
+ export declare class PgProjectPipelineRepository implements ProjectPipelineRepository {
33
+ private readonly _deps;
34
+ constructor(_deps: PortDeps);
35
+ savePipeline(rec: PipelineRecord): Promise<void>;
36
+ getPipeline(id: string): Promise<PipelineRecord | null>;
37
+ listPipelines(filter?: {
38
+ scope?: PipelineScope;
39
+ projectId?: string;
40
+ }): Promise<PipelineRecord[]>;
41
+ deletePipeline(id: string): Promise<boolean>;
42
+ saveVersion(rec: PipelineVersionRecord): Promise<void>;
43
+ getVersion(pipelineId: string, version: number): Promise<PipelineVersionRecord | null>;
44
+ listVersions(pipelineId: string): Promise<PipelineVersionRecord[]>;
45
+ }
46
+ /**
47
+ * ADR-101: прогоны пайплайнов и журнал выполнения поверх `pipeline_runs`/
48
+ * `pipeline_run_events`.
49
+ */
50
+ export declare class PgPipelineRunRepository implements PipelineRunRepository {
51
+ private readonly _deps;
52
+ constructor(_deps: PortDeps);
53
+ saveRun(rec: PipelineRunRecord): Promise<void>;
54
+ getRun(id: string): Promise<PipelineRunRecord | null>;
55
+ listRuns(filter?: {
56
+ pipelineId?: string;
57
+ projectId?: string;
58
+ status?: PipelineRunRecord['status'];
59
+ limit?: number;
60
+ }): Promise<PipelineRunRecord[]>;
61
+ appendEvent(ev: PipelineRunEventRecord): Promise<void>;
62
+ listEvents(runId: string, opts?: {
63
+ limit?: number;
64
+ }): Promise<PipelineRunEventRecord[]>;
65
+ }
66
+ /** Собрать порты группы `pipelines` (ADR-101). */
67
+ export declare function buildPipelinePorts(deps: PortDeps): PipelinePorts;
@@ -0,0 +1,297 @@
1
+ /**
2
+ * PG-реализация портов **движка пайплайнов** (ADR-101): спецификации
3
+ * (черновик + опубликованные версии), прогоны и журнал выполнения.
4
+ *
5
+ * Таблицы (миграция 004): `pipeline_specs`, `pipeline_versions`, `pipeline_runs`,
6
+ * `pipeline_run_events`.
7
+ *
8
+ * Семантика повторяет файловые реализации core (`FileProjectPipelineStore`,
9
+ * `FilePipelineRunStore`):
10
+ * - upsert по `id`: `created_at` не перезаписывается, `updated_at` монотонно
11
+ * не убывает (в SQL — `GREATEST` + сдвиг 1 мс, паритет с
12
+ * `record-timestamps.ts` core);
13
+ * - список пайплайнов — по `id` asc, фильтры `scope`/`projectId` — по «И»;
14
+ * - список прогонов — «свежие первыми» (`created_at` убыв., тайбрейкер `id`),
15
+ * фильтры — по «И», `limit` — дефолт 100 / потолок 1000;
16
+ * - журнал событий — **append-only** (`seq bigserial`), чтение хронологическое
17
+ * (по `ts`, затем порядок добавления), `limit` — последние N;
18
+ * - удаление пайплайна удаляет его версии, но **не** прогоны (прогон
19
+ * самодостаточен — несёт снимок спецификации).
20
+ *
21
+ * Драйвер не тянет core рантаймом (только `import type`), поэтому потолок
22
+ * выборки и правило timestamps повторены здесь локально — как в
23
+ * `ports/analytics.ts` (локальная точная реплика core-хелпера).
24
+ */
25
+ import { normalizeIconKey } from '@itphx/synth-shared';
26
+ import { jsonbParam } from '../json-param.js';
27
+ import { compact, toIso, toIsoRequired } from './events-core.js';
28
+ // ── Локальные реплики core-хелперов (core рантаймом не тянем) ────────────────
29
+ /** Дефолтный потолок выборки прогонов (паритет с core `COLLECTION_LIMIT_DEFAULT`). */
30
+ const RUN_LIST_DEFAULT_LIMIT = 100;
31
+ /** Абсолютный потолок выборки прогонов (паритет с core `COLLECTION_LIMIT_MAX`). */
32
+ const RUN_LIST_MAX_LIMIT = 1000;
33
+ /** Привести `limit` к допустимому виду: дефолт 100, потолок 1000. */
34
+ function resolveRunLimit(limit) {
35
+ if (limit === undefined || !Number.isFinite(limit) || limit <= 0) {
36
+ return RUN_LIST_DEFAULT_LIMIT;
37
+ }
38
+ return Math.min(Math.floor(limit), RUN_LIST_MAX_LIMIT);
39
+ }
40
+ /**
41
+ * Выражение `updated_at` при upsert: максимум из «сейчас», входящего и
42
+ * сохранённого значения; если максимум совпал с сохранённым — сдвиг на 1 мс
43
+ * (паритет с `resolveUpdatedAt` в `record-timestamps.ts` core: метка не
44
+ * откатывается и всегда наблюдаема).
45
+ */
46
+ function updatedAtExpr(table) {
47
+ return `CASE
48
+ WHEN GREATEST(EXCLUDED.updated_at, ${table}.updated_at, now()) <= ${table}.updated_at
49
+ THEN ${table}.updated_at + interval '1 millisecond'
50
+ ELSE GREATEST(EXCLUDED.updated_at, ${table}.updated_at, now())
51
+ END`;
52
+ }
53
+ /** Запись пайплайна из колонок; ключ иконки нормализуется при чтении. */
54
+ function toPipeline(row) {
55
+ return compact({
56
+ id: row.id,
57
+ scope: row.scope,
58
+ projectId: row.project_id ?? undefined,
59
+ name: row.name,
60
+ description: row.description ?? undefined,
61
+ icon: normalizeIconKey(row.icon),
62
+ draft: (row.draft ?? undefined),
63
+ draftVersion: row.draft_version,
64
+ publishedVersion: row.published_version ?? undefined,
65
+ // Провенанс установки (ADR-101 §2.11): jsonb `{pack, version}`.
66
+ installedBy: (row.installed_by ?? undefined),
67
+ createdAt: toIsoRequired(row.created_at),
68
+ updatedAt: toIsoRequired(row.updated_at),
69
+ });
70
+ }
71
+ /** Запись опубликованной версии из колонок. */
72
+ function toPipelineVersion(row) {
73
+ return compact({
74
+ pipelineId: row.pipeline_id,
75
+ version: row.version,
76
+ spec: row.spec,
77
+ publishedAt: toIsoRequired(row.published_at),
78
+ publishedBy: row.published_by ?? undefined,
79
+ });
80
+ }
81
+ /**
82
+ * ADR-101: спецификации пайплайнов поверх `pipeline_specs`/`pipeline_versions`.
83
+ */
84
+ export class PgProjectPipelineRepository {
85
+ _deps;
86
+ constructor(_deps) {
87
+ this._deps = _deps;
88
+ }
89
+ async savePipeline(rec) {
90
+ await this._deps.connection.query(`INSERT INTO pipeline_specs
91
+ (id, scope, project_id, name, description, icon, draft, draft_version,
92
+ published_version, installed_by, created_at, updated_at)
93
+ VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8, $9, $10::jsonb, $11::timestamptz,
94
+ GREATEST($12::timestamptz, now()))
95
+ ON CONFLICT (id) DO UPDATE SET
96
+ scope = EXCLUDED.scope,
97
+ project_id = EXCLUDED.project_id,
98
+ name = EXCLUDED.name,
99
+ description = EXCLUDED.description,
100
+ icon = EXCLUDED.icon,
101
+ draft = EXCLUDED.draft,
102
+ draft_version = EXCLUDED.draft_version,
103
+ published_version = EXCLUDED.published_version,
104
+ installed_by = EXCLUDED.installed_by,
105
+ created_at = pipeline_specs.created_at,
106
+ updated_at = ${updatedAtExpr('pipeline_specs')}`, [
107
+ rec.id,
108
+ rec.scope,
109
+ rec.projectId ?? null,
110
+ rec.name,
111
+ rec.description ?? null,
112
+ rec.icon ?? null,
113
+ rec.draft !== undefined ? jsonbParam(rec.draft) : null,
114
+ rec.draftVersion,
115
+ rec.publishedVersion ?? null,
116
+ rec.installedBy !== undefined ? jsonbParam(rec.installedBy) : null,
117
+ rec.createdAt,
118
+ rec.updatedAt,
119
+ ]);
120
+ }
121
+ async getPipeline(id) {
122
+ const rows = await this._deps.connection.query('SELECT * FROM pipeline_specs WHERE id = $1 LIMIT 1', [id]);
123
+ return rows[0] ? toPipeline(rows[0]) : null;
124
+ }
125
+ async listPipelines(filter) {
126
+ const params = [];
127
+ const where = [];
128
+ if (filter?.scope !== undefined) {
129
+ params.push(filter.scope);
130
+ where.push(`scope = $${params.length}`);
131
+ }
132
+ if (filter?.projectId !== undefined) {
133
+ params.push(filter.projectId);
134
+ where.push(`project_id = $${params.length}`);
135
+ }
136
+ const sql = 'SELECT * FROM pipeline_specs' +
137
+ (where.length ? ` WHERE ${where.join(' AND ')}` : '') +
138
+ ' ORDER BY id ASC';
139
+ const rows = await this._deps.connection.query(sql, params);
140
+ return rows.map(toPipeline);
141
+ }
142
+ async deletePipeline(id) {
143
+ return this._deps.connection.withTransaction(async (tx) => {
144
+ const rows = await tx.query('DELETE FROM pipeline_specs WHERE id = $1 RETURNING id', [id]);
145
+ if (rows.length === 0)
146
+ return false;
147
+ // Версии пайплайна удаляются каскадом; прогоны **не** трогаются — прогон
148
+ // самодостаточен (несёт снимок спецификации).
149
+ await tx.query('DELETE FROM pipeline_versions WHERE pipeline_id = $1', [id]);
150
+ return true;
151
+ });
152
+ }
153
+ async saveVersion(rec) {
154
+ await this._deps.connection.query(`INSERT INTO pipeline_versions (pipeline_id, version, spec, published_at, published_by)
155
+ VALUES ($1, $2, $3::jsonb, $4::timestamptz, $5)
156
+ ON CONFLICT (pipeline_id, version) DO UPDATE SET
157
+ spec = EXCLUDED.spec,
158
+ published_at = EXCLUDED.published_at,
159
+ published_by = EXCLUDED.published_by`, [
160
+ rec.pipelineId,
161
+ rec.version,
162
+ jsonbParam(rec.spec),
163
+ rec.publishedAt,
164
+ rec.publishedBy ?? null,
165
+ ]);
166
+ }
167
+ async getVersion(pipelineId, version) {
168
+ const rows = await this._deps.connection.query('SELECT * FROM pipeline_versions WHERE pipeline_id = $1 AND version = $2 LIMIT 1', [pipelineId, version]);
169
+ return rows[0] ? toPipelineVersion(rows[0]) : null;
170
+ }
171
+ async listVersions(pipelineId) {
172
+ const rows = await this._deps.connection.query('SELECT * FROM pipeline_versions WHERE pipeline_id = $1 ORDER BY version ASC', [pipelineId]);
173
+ return rows.map(toPipelineVersion);
174
+ }
175
+ }
176
+ /** Запись прогона из колонок. */
177
+ function toRun(row) {
178
+ return compact({
179
+ id: row.id,
180
+ pipelineId: row.pipeline_id,
181
+ version: row.version,
182
+ spec: row.spec,
183
+ projectId: row.project_id ?? undefined,
184
+ status: row.status,
185
+ currentNode: row.current_node ?? undefined,
186
+ trigger: (row.trigger_data ?? undefined),
187
+ startedAt: toIso(row.started_at),
188
+ finishedAt: toIso(row.finished_at),
189
+ error: row.error ?? undefined,
190
+ createdAt: toIsoRequired(row.created_at),
191
+ updatedAt: toIsoRequired(row.updated_at),
192
+ });
193
+ }
194
+ /** Событие прогона из колонок. */
195
+ function toRunEvent(row) {
196
+ return compact({
197
+ runId: row.run_id,
198
+ ts: toIsoRequired(row.ts),
199
+ type: row.type,
200
+ payload: (row.payload ?? undefined),
201
+ });
202
+ }
203
+ /**
204
+ * ADR-101: прогоны пайплайнов и журнал выполнения поверх `pipeline_runs`/
205
+ * `pipeline_run_events`.
206
+ */
207
+ export class PgPipelineRunRepository {
208
+ _deps;
209
+ constructor(_deps) {
210
+ this._deps = _deps;
211
+ }
212
+ async saveRun(rec) {
213
+ await this._deps.connection.query(`INSERT INTO pipeline_runs
214
+ (id, pipeline_id, version, spec, project_id, status, current_node, trigger_data,
215
+ started_at, finished_at, error, created_at, updated_at)
216
+ VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8::jsonb, $9::timestamptz,
217
+ $10::timestamptz, $11, $12::timestamptz, GREATEST($13::timestamptz, now()))
218
+ ON CONFLICT (id) DO UPDATE SET
219
+ pipeline_id = EXCLUDED.pipeline_id,
220
+ version = EXCLUDED.version,
221
+ spec = EXCLUDED.spec,
222
+ project_id = EXCLUDED.project_id,
223
+ status = EXCLUDED.status,
224
+ current_node = EXCLUDED.current_node,
225
+ trigger_data = EXCLUDED.trigger_data,
226
+ started_at = EXCLUDED.started_at,
227
+ finished_at = EXCLUDED.finished_at,
228
+ error = EXCLUDED.error,
229
+ created_at = pipeline_runs.created_at,
230
+ updated_at = ${updatedAtExpr('pipeline_runs')}`, [
231
+ rec.id,
232
+ rec.pipelineId,
233
+ rec.version,
234
+ jsonbParam(rec.spec),
235
+ rec.projectId ?? null,
236
+ rec.status,
237
+ rec.currentNode ?? null,
238
+ rec.trigger !== undefined ? jsonbParam(rec.trigger) : null,
239
+ rec.startedAt ?? null,
240
+ rec.finishedAt ?? null,
241
+ rec.error ?? null,
242
+ rec.createdAt,
243
+ rec.updatedAt,
244
+ ]);
245
+ }
246
+ async getRun(id) {
247
+ const rows = await this._deps.connection.query('SELECT * FROM pipeline_runs WHERE id = $1 LIMIT 1', [id]);
248
+ return rows[0] ? toRun(rows[0]) : null;
249
+ }
250
+ async listRuns(filter) {
251
+ const params = [];
252
+ const where = [];
253
+ if (filter?.pipelineId !== undefined) {
254
+ params.push(filter.pipelineId);
255
+ where.push(`pipeline_id = $${params.length}`);
256
+ }
257
+ if (filter?.projectId !== undefined) {
258
+ params.push(filter.projectId);
259
+ where.push(`project_id = $${params.length}`);
260
+ }
261
+ if (filter?.status !== undefined) {
262
+ params.push(filter.status);
263
+ where.push(`status = $${params.length}`);
264
+ }
265
+ params.push(resolveRunLimit(filter?.limit));
266
+ const sql = 'SELECT * FROM pipeline_runs' +
267
+ (where.length ? ` WHERE ${where.join(' AND ')}` : '') +
268
+ ' ORDER BY created_at DESC, id ASC' +
269
+ ` LIMIT $${params.length}`;
270
+ const rows = await this._deps.connection.query(sql, params);
271
+ return rows.map(toRun);
272
+ }
273
+ async appendEvent(ev) {
274
+ await this._deps.connection.query(`INSERT INTO pipeline_run_events (run_id, ts, type, payload)
275
+ VALUES ($1, $2::timestamptz, $3, $4::jsonb)`, [ev.runId, ev.ts, ev.type, ev.payload !== undefined ? jsonbParam(ev.payload) : null]);
276
+ }
277
+ async listEvents(runId, opts) {
278
+ const limit = opts?.limit;
279
+ if (limit !== undefined && Number.isFinite(limit) && limit > 0) {
280
+ // Последние N по хронологии — в хронологическом порядке.
281
+ const rows = await this._deps.connection.query(`SELECT * FROM (
282
+ SELECT * FROM pipeline_run_events WHERE run_id = $1
283
+ ORDER BY ts DESC, seq DESC LIMIT $2
284
+ ) t ORDER BY ts ASC, seq ASC`, [runId, Math.floor(limit)]);
285
+ return rows.map(toRunEvent);
286
+ }
287
+ const rows = await this._deps.connection.query('SELECT * FROM pipeline_run_events WHERE run_id = $1 ORDER BY ts ASC, seq ASC', [runId]);
288
+ return rows.map(toRunEvent);
289
+ }
290
+ }
291
+ /** Собрать порты группы `pipelines` (ADR-101). */
292
+ export function buildPipelinePorts(deps) {
293
+ return {
294
+ projectPipelines: new PgProjectPipelineRepository(deps),
295
+ pipelineRuns: new PgPipelineRunRepository(deps),
296
+ };
297
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Порт журнала аудита плагинов PostgreSQL-драйвера (ADR-090, ADR-097).
3
+ *
4
+ * Отдельная append-only таблица `plugin_audit` (`seq bigserial` — порядок
5
+ * «свежие первыми»). Семантика — как у файловой реализации core
6
+ * (`FilePluginAuditStore`): append, выборка «свежие первыми» с фильтрами
7
+ * `plugin`/`action`/`outcome`/`limit`, очистка с числом удалённых.
8
+ */
9
+ import type { StorageContext } from '@itphx/synth-core';
10
+ import type { PortDeps } from './deps.js';
11
+ /** Часть `StorageContext`, которой владеет модуль журнала плагинов. */
12
+ export type PluginAuditPorts = Pick<StorageContext, 'pluginAudit'>;
13
+ /** Собрать порт журнала аудита плагинов. */
14
+ export declare function buildPluginAuditPorts(deps: PortDeps): PluginAuditPorts;
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Порт журнала аудита плагинов PostgreSQL-драйвера (ADR-090, ADR-097).
3
+ *
4
+ * Отдельная append-only таблица `plugin_audit` (`seq bigserial` — порядок
5
+ * «свежие первыми»). Семантика — как у файловой реализации core
6
+ * (`FilePluginAuditStore`): append, выборка «свежие первыми» с фильтрами
7
+ * `plugin`/`action`/`outcome`/`limit`, очистка с числом удалённых.
8
+ */
9
+ function toISO(value) {
10
+ if (value instanceof Date)
11
+ return value.toISOString();
12
+ return String(value);
13
+ }
14
+ function pluginRowToEntry(row) {
15
+ const entry = {
16
+ id: row.id,
17
+ ts: toISO(row.ts),
18
+ actor: row.actor,
19
+ scope: 'plugin',
20
+ action: row.action,
21
+ plugin: row.plugin,
22
+ version: row.version,
23
+ outcome: row.outcome,
24
+ };
25
+ if (row.trust_level !== null)
26
+ entry.trustLevel = row.trust_level;
27
+ if (row.scan_verdict !== null)
28
+ entry.scanVerdict = row.scan_verdict;
29
+ if (row.scan_performed !== null)
30
+ entry.scanPerformed = row.scan_performed;
31
+ if (row.scan_findings !== null)
32
+ entry.scanFindings = row.scan_findings;
33
+ if (row.content_hash !== null)
34
+ entry.contentHash = row.content_hash;
35
+ if (row.mode !== null)
36
+ entry.mode = row.mode;
37
+ if (row.reason !== null)
38
+ entry.reason = row.reason;
39
+ if (row.source !== null)
40
+ entry.source = row.source;
41
+ return entry;
42
+ }
43
+ /** Реализация порта `PluginAuditRepository` поверх SQL. */
44
+ class PostgresPluginAuditRepository {
45
+ _deps;
46
+ constructor(_deps) {
47
+ this._deps = _deps;
48
+ }
49
+ _db() {
50
+ return this._deps.connection;
51
+ }
52
+ async append(entry) {
53
+ await this._db().query(`INSERT INTO plugin_audit
54
+ (id, ts, actor, scope, action, plugin, version, trust_level, scan_verdict,
55
+ scan_performed, scan_findings, content_hash, mode, outcome, reason, source)
56
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)`, [
57
+ entry.id,
58
+ entry.ts,
59
+ entry.actor,
60
+ entry.scope,
61
+ entry.action,
62
+ entry.plugin,
63
+ entry.version,
64
+ entry.trustLevel ?? null,
65
+ entry.scanVerdict ?? null,
66
+ entry.scanPerformed ?? null,
67
+ entry.scanFindings ?? null,
68
+ entry.contentHash ?? null,
69
+ entry.mode ?? null,
70
+ entry.outcome,
71
+ entry.reason ?? null,
72
+ entry.source ?? null,
73
+ ]);
74
+ }
75
+ async list(opts = {}) {
76
+ const params = [];
77
+ const clauses = [];
78
+ if (opts.plugin !== undefined) {
79
+ params.push(opts.plugin);
80
+ clauses.push(`plugin = $${params.length}`);
81
+ }
82
+ if (opts.action !== undefined) {
83
+ params.push(opts.action);
84
+ clauses.push(`action = $${params.length}`);
85
+ }
86
+ if (opts.outcome !== undefined) {
87
+ params.push(opts.outcome);
88
+ clauses.push(`outcome = $${params.length}`);
89
+ }
90
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
91
+ let limit = '';
92
+ if (opts.limit !== undefined && Number.isFinite(opts.limit) && opts.limit > 0) {
93
+ params.push(Math.floor(opts.limit));
94
+ limit = `LIMIT $${params.length}::int`;
95
+ }
96
+ const rows = await this._db().query(`SELECT * FROM plugin_audit ${where} ORDER BY seq DESC ${limit}`, params);
97
+ return rows.map(pluginRowToEntry);
98
+ }
99
+ async clear() {
100
+ const rows = await this._db().query('WITH deleted AS (DELETE FROM plugin_audit RETURNING 1) SELECT count(*)::int AS n FROM deleted');
101
+ const value = rows[0]?.n;
102
+ return typeof value === 'number' ? value : Number(value) || 0;
103
+ }
104
+ }
105
+ /** Собрать порт журнала аудита плагинов. */
106
+ export function buildPluginAuditPorts(deps) {
107
+ return {
108
+ pluginAudit: new PostgresPluginAuditRepository(deps),
109
+ };
110
+ }
@@ -0,0 +1,27 @@
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
+ import type { StorageContext } from '@itphx/synth-core';
23
+ import type { PortDeps } from './deps.js';
24
+ /** Часть `StorageContext`, которой владеет модуль lock-файла плагинов. */
25
+ export type PluginLockPorts = Pick<StorageContext, 'pluginLock'>;
26
+ /** Собрать порт lock-файла плагинов. */
27
+ export declare function buildPluginLockPorts(deps: PortDeps): PluginLockPorts;