@simetrajs/designer 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/README.md +79 -2
- package/dist/command-BCAw6Fsb.js +794 -0
- package/dist/default-dir-DerxTbci.js +158 -0
- package/dist/errors-Brw6UjAD.js +35 -0
- package/dist/init-jr0Xsrpp.js +832 -0
- package/dist/main.js +29 -0
- package/dist/mcp-ChltmHBb.js +277 -0
- package/dist/mcp-args-D63akJ97.js +56 -0
- package/dist/package-Dg3MXPve.js +4 -0
- package/dist/report-DV4deFdu.js +2059 -0
- package/dist/schema-engine-DPPnife2.js +2809 -0
- package/dist/types-iWavtmdS.js +31 -0
- package/package.json +67 -3
- package/skills/simetra-adoption/SKILL.md +185 -0
- package/skills/simetra-metadata/SKILL.md +494 -0
- package/skills/simetra-metadata/references/agents-over-mcp.md +119 -0
- package/skills/simetra-metadata/references/object-modules.md +60 -0
- package/skills/simetra-metadata/references/people-and-rights.md +757 -0
- package/skills/simetra-metadata/references/project-setup.md +28 -0
- package/skills/simetra-metadata/references/sql-trust-boundary.md +194 -0
|
@@ -0,0 +1,2059 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { r as defineTool, t as PLANS_DIR } from "./types-iWavtmdS.js";
|
|
3
|
+
import { a as dataWriteHint, c as noDatabaseHint, d as installedPackageDir, f as posixRelative, l as readOnlyHint, o as databaseWriteHint, p as UsageError, s as noDataHint, u as rightsWriteHint } from "./default-dir-DerxTbci.js";
|
|
4
|
+
import { n as ShadowServerError, r as ShadowServerMismatchError, t as ShadowCreateRefusedError } from "./errors-Brw6UjAD.js";
|
|
5
|
+
import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
6
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
7
|
+
import { ATTRIBUTE_CASES, DATABASE_PROVIDERS, KIND_REGISTRY, PLATFORM_LOGIN_ROLES, PLATFORM_ROLES, PLATFORM_SCHEMA, PROVIDER_API_ROLES, PROVIDER_SCHEMAS, SQL_DEBT_FILE, UUID_TEXT, batchSchema, logicalTypeOf, metadataKindSchema, objectNameSchema, quoteIdent, readQuerySchema } from "simetra/model";
|
|
8
|
+
import { ApplyConnectionLost, ApplyDbError, FINGERPRINT_VERSION, LOCK_MODE_SQL, PLATFORM_VERSION, applyStateOf, buildPlan, checkOwnerMembership, checkPermissions, checkPlatformRoles, compareWithDesired, desiredForApply, engineScope, ensurePlatformRoles, executePlan, parsePlan, parseRehearsal, planFileName, platformRoleSet, rehearsalFileName, rehearsalReport, reverseGenerate, runRightsMaintenance, serializePlan, serializeRehearsal, verifyPlanHash } from "simetra/schema";
|
|
9
|
+
import pg from "pg";
|
|
10
|
+
import { CommandFailure, createCommandRuntime, fromPgPool, readRoleOf } from "simetra/server";
|
|
11
|
+
import { ZodError, z } from "zod";
|
|
12
|
+
import { addElement, addElementInput, buildRuntimeCatalog, canonicalSnapshot, compile, createObject, createObjectInput, deleteElement, deleteInput, diagnostic, explainObject, fixFiles, loadSqlParser, localize, promoteInput, promoteObject, promotionFileName, promotionRecordSchema, readProjectFile, renameElement, renameInput, serializeCanonical } from "simetra/compiler";
|
|
13
|
+
import { existsSync } from "node:fs";
|
|
14
|
+
// src/io/data-guard-refusal.ts
|
|
15
|
+
/**
|
|
16
|
+
* Тексти не називають ні рядка підключення, ні ролі входу: відмова йде
|
|
17
|
+
* агентові й у журнали клієнта. Пізніша версія — П4-F (спека П4 §6.14);
|
|
18
|
+
* назву віхи споживачеві не показуємо.
|
|
19
|
+
*/
|
|
20
|
+
const MESSAGES = {
|
|
21
|
+
"not-local": "Data tools work only with a development database on this machine: the connection string must point to localhost, a 127.x.x.x address, ::1 or a unix socket. Agent access to other databases comes in a later version. Nothing changed.",
|
|
22
|
+
"not-development": "The database is not marked as a development database: the database-level setting simetra.environment = 'development' is missing. A superuser sets it on the local development database only. Agent access to other databases comes in a later version. Nothing changed.",
|
|
23
|
+
"login-refused": "The connection string must use the runtime login role: a role that is not a superuser, does not bypass row-level security, is neither the migrator nor the provider service role, and may switch to the platform command role. Nothing changed."
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Відмова запобіжника бази розробника. Окремий легкий модуль: його
|
|
27
|
+
* імпортує `invoke.ts`, і він не мусить тягнути `pg` чи ярус сервера.
|
|
28
|
+
* Запобіжники ловлять випадковий запуск, а не межа безпеки: межа —
|
|
29
|
+
* облікові дані ролі входу рантайму (спека П4 §6.14).
|
|
30
|
+
*/
|
|
31
|
+
var DataGuardRefusal = class extends UsageError {
|
|
32
|
+
detail;
|
|
33
|
+
name = "DataGuardRefusal";
|
|
34
|
+
constructor(detail) {
|
|
35
|
+
super(MESSAGES[detail]);
|
|
36
|
+
this.detail = detail;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
// src/io/database.ts
|
|
40
|
+
/**
|
|
41
|
+
* Відмова виклику бази з текстом, який уже безпечно показати: без рядка
|
|
42
|
+
* підключення, користувача й пароля. Помилка використання — викликач може
|
|
43
|
+
* виправити її сам (змінна середовища, сервер тіні).
|
|
44
|
+
*/
|
|
45
|
+
var DatabaseRefusal = class extends UsageError {
|
|
46
|
+
name = "DatabaseRefusal";
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* `host:port/db` — єдине про підключення, що можна показати. Рядок, який не
|
|
50
|
+
* розбирається як URL, не цитуємо: він міг би бути самим паролем.
|
|
51
|
+
*/
|
|
52
|
+
function describeConnection(url) {
|
|
53
|
+
try {
|
|
54
|
+
const u = new URL(url);
|
|
55
|
+
const db = decodeURIComponent(u.pathname.replace(/^\//, ""));
|
|
56
|
+
return `${u.hostname}:${u.port === "" ? "5432" : u.port}/${db}`;
|
|
57
|
+
} catch {
|
|
58
|
+
return "the configured database";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Ресурс запуску з імен змінних, зафіксованих при запуску. Без змінної цілі
|
|
63
|
+
* ресурсу немає — `invoke` відмовить з її ім'ям. Значення читається тут, а
|
|
64
|
+
* пули відкриває лише виклик інструмента бази.
|
|
65
|
+
*/
|
|
66
|
+
function databaseResource(env, names) {
|
|
67
|
+
const url = env[names.url];
|
|
68
|
+
if (url === void 0 || url === "") return void 0;
|
|
69
|
+
const describe = describeConnection(url);
|
|
70
|
+
return {
|
|
71
|
+
describe,
|
|
72
|
+
async connect() {
|
|
73
|
+
if (names.shadow === void 0) return {
|
|
74
|
+
target: { url },
|
|
75
|
+
describe
|
|
76
|
+
};
|
|
77
|
+
const shadowUrl = env[names.shadow];
|
|
78
|
+
if (shadowUrl === void 0 || shadowUrl === "") throw new DatabaseRefusal(`The environment variable ${names.shadow} named by --shadow-url-env is not set. Nothing changed.`);
|
|
79
|
+
return {
|
|
80
|
+
target: { url },
|
|
81
|
+
shadowBase: { url: shadowUrl },
|
|
82
|
+
describe
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** Мережеві коди Node: база недосяжна, і повторити варто після виправлення адреси. */
|
|
88
|
+
const UNREACHABLE = /* @__PURE__ */ new Set([
|
|
89
|
+
"ECONNREFUSED",
|
|
90
|
+
"ECONNRESET",
|
|
91
|
+
"ENOTFOUND",
|
|
92
|
+
"EAI_AGAIN",
|
|
93
|
+
"ETIMEDOUT",
|
|
94
|
+
"EHOSTUNREACH",
|
|
95
|
+
"ENETUNREACH"
|
|
96
|
+
]);
|
|
97
|
+
/**
|
|
98
|
+
* Код Node (`EPIPE`, `ERR_INVALID_URL`) перевіряється раніше за SQLSTATE: обидва
|
|
99
|
+
* бувають п'ятисимвольними, а класу SQLSTATE на `E` у Postgres немає.
|
|
100
|
+
*/
|
|
101
|
+
const NODE_CODE = /^E[A-Z_]+$/;
|
|
102
|
+
const SQLSTATE$1 = /^[0-9A-Z]{5}$/;
|
|
103
|
+
/**
|
|
104
|
+
* Збій драйвера без коду, що означає втрачене чи не встановлене з'єднання.
|
|
105
|
+
* Текст лише розпізнається, ніколи не цитується.
|
|
106
|
+
*/
|
|
107
|
+
const LOST_CONNECTION = /^Connection terminated|^timeout expired/;
|
|
108
|
+
/**
|
|
109
|
+
* Код помилки: драйвер і Node кладуть його в `code`, а порт виконання T2 —
|
|
110
|
+
* SQLSTATE в `sqlstate` (клас T2 не знає драйвера й не імітує його поле).
|
|
111
|
+
*/
|
|
112
|
+
function codeOf(error) {
|
|
113
|
+
if (error instanceof ApplyDbError) return error.sqlstate;
|
|
114
|
+
const code = error.code;
|
|
115
|
+
return typeof code === "string" ? code : void 0;
|
|
116
|
+
}
|
|
117
|
+
const refusal = (message, note = "") => ({
|
|
118
|
+
kind: "refusal",
|
|
119
|
+
message: `${message}${note} Nothing changed.`
|
|
120
|
+
});
|
|
121
|
+
/**
|
|
122
|
+
* Тінь потребує сесійної семантики (`CREATE DATABASE`, підключення до нової
|
|
123
|
+
* бази за іменем, сесійні `SET` завантажувача), а детектора режиму пулера
|
|
124
|
+
* немає (спека designer §3.2): збій тіні з нерозпізнаною причиною лише
|
|
125
|
+
* називає вимогу. Відмова без `CREATEDB` чи через іншу мажорну версію її не
|
|
126
|
+
* отримує — причина там уже відома.
|
|
127
|
+
*/
|
|
128
|
+
const SHADOW_CONNECTION = " The shadow needs a direct or session-mode connection; a transaction-mode pooler is not guaranteed to support it.";
|
|
129
|
+
/**
|
|
130
|
+
* Єдина межа, на якій помилка підключення чи запиту стає текстом для
|
|
131
|
+
* виводу. Текст складається лише зі стабільних фраз, адреси `host:port/db` і
|
|
132
|
+
* коду помилки: повідомлення драйвера й двигуна не цитуються, бо несуть ім'я
|
|
133
|
+
* користувача («password authentication failed for user …»), а інші —
|
|
134
|
+
* будь-що з рядка підключення. Наші власні відмови вже безпечні й ідуть як є.
|
|
135
|
+
*/
|
|
136
|
+
function classifyDatabaseError(error, names) {
|
|
137
|
+
return classify(error, names, "");
|
|
138
|
+
}
|
|
139
|
+
/** `note` — речення перед «Nothing changed.» у кожній відмові. */
|
|
140
|
+
function classify(error, names, note) {
|
|
141
|
+
const describe = names.target;
|
|
142
|
+
const refused = (message) => refusal(message, note);
|
|
143
|
+
if (error instanceof DatabaseRefusal) return {
|
|
144
|
+
kind: "refusal",
|
|
145
|
+
message: error.message
|
|
146
|
+
};
|
|
147
|
+
if (error instanceof ShadowServerMismatchError) return {
|
|
148
|
+
kind: "refusal",
|
|
149
|
+
message: error.message
|
|
150
|
+
};
|
|
151
|
+
if (error instanceof ShadowCreateRefusedError) {
|
|
152
|
+
const where = error.onShadowBase ? names.shadow ?? describe : describe;
|
|
153
|
+
return refusal(`A shadow database cannot be created on ${where}: the connecting role lacks CREATEDB.${error.onShadowBase ? "" : " Point --shadow-url-env at a server where it has it."}`);
|
|
154
|
+
}
|
|
155
|
+
if (error instanceof ShadowServerError) {
|
|
156
|
+
const where = error.onShadowBase ? names.shadow ?? describe : describe;
|
|
157
|
+
const c = classify(error.cause, { target: where }, SHADOW_CONNECTION);
|
|
158
|
+
if (c.kind === "refusal") return c;
|
|
159
|
+
const { error: name, sqlstate } = c.params;
|
|
160
|
+
return refusal(`A shadow database could not be created or reached on ${where} (${name}${sqlstate === void 0 ? "" : `, SQLSTATE ${sqlstate}`}).`, SHADOW_CONNECTION);
|
|
161
|
+
}
|
|
162
|
+
if (error instanceof AggregateError && error.errors.length > 0) return classify(error.errors[0], names, note);
|
|
163
|
+
if (!(error instanceof Error)) return {
|
|
164
|
+
kind: "failure",
|
|
165
|
+
params: {
|
|
166
|
+
database: describe,
|
|
167
|
+
error: "unknown"
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
if (error instanceof ApplyConnectionLost) return refused(`The connection to the database at ${describe} was lost or timed out.`);
|
|
171
|
+
const code = codeOf(error);
|
|
172
|
+
if (code !== void 0 && NODE_CODE.test(code)) {
|
|
173
|
+
if (UNREACHABLE.has(code)) return refused(`The database at ${describe} is unreachable (${code}). Check the host and port in the connection string.`);
|
|
174
|
+
if (code === "ERR_INVALID_URL") return refused("The connection string is not a valid URL.");
|
|
175
|
+
return {
|
|
176
|
+
kind: "failure",
|
|
177
|
+
params: {
|
|
178
|
+
database: describe,
|
|
179
|
+
error: `${error.name} ${code}`
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
if (code !== void 0 && SQLSTATE$1.test(code)) {
|
|
184
|
+
if (code.startsWith("28")) return refused(`Authentication to the database at ${describe} failed. Check the user and password in the connection string.`);
|
|
185
|
+
if (code.startsWith("08")) return refused(`The connection to the database at ${describe} failed (SQLSTATE ${code}).`);
|
|
186
|
+
if (code === "3D000") return refused(`The database at ${describe} does not exist.`);
|
|
187
|
+
if (code === "42501") return refused(`The connecting role lacks a privilege this tool needs on ${describe} (SQLSTATE 42501).`);
|
|
188
|
+
return {
|
|
189
|
+
kind: "failure",
|
|
190
|
+
params: {
|
|
191
|
+
database: describe,
|
|
192
|
+
error: error.name,
|
|
193
|
+
sqlstate: code
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
if (code === void 0 && LOST_CONNECTION.test(error.message)) return refused(`The connection to the database at ${describe} was lost or timed out.`);
|
|
198
|
+
return {
|
|
199
|
+
kind: "failure",
|
|
200
|
+
params: {
|
|
201
|
+
database: describe,
|
|
202
|
+
error: error.name
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Помилка програми, а не бази: вбудовані класи JS без коду драйвера чи Node
|
|
208
|
+
* (у Node `TypeError` буває з кодом `ERR_*`, як `ERR_INVALID_URL`). Драйвер
|
|
209
|
+
* кидає `Error` чи `DatabaseError`, тож його текст сюди не потрапляє, а
|
|
210
|
+
* баг не маскується під збій бази.
|
|
211
|
+
*/
|
|
212
|
+
function isProgramBug(error) {
|
|
213
|
+
return (error instanceof TypeError || error instanceof RangeError || error instanceof ReferenceError || error instanceof SyntaxError) && codeOf(error) === void 0;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Підключення одного виклику — єдина межа помилок бази. Відмова
|
|
217
|
+
* (`DatabaseRefusal`) летить до `invoke` і стає кодом 2; збій роботи з базою
|
|
218
|
+
* стає діагностикою `database.failed` (код 1, MCP `isError`). Сирий виняток
|
|
219
|
+
* бази далі не йде: SDK MCP показав би агенту його текст. Баг програми
|
|
220
|
+
* (`isProgramBug`) летить далі як є — шлях внутрішньої помилки `invoke`.
|
|
221
|
+
* Пули відкриває й закриває двигун усередині `fn`.
|
|
222
|
+
*/
|
|
223
|
+
async function withDatabase(resource, tool, fn) {
|
|
224
|
+
let names = { target: resource.describe };
|
|
225
|
+
try {
|
|
226
|
+
const db = await resource.connect();
|
|
227
|
+
if (db.shadowBase !== void 0) names = {
|
|
228
|
+
...names,
|
|
229
|
+
shadow: describeConnection(db.shadowBase.url)
|
|
230
|
+
};
|
|
231
|
+
return {
|
|
232
|
+
ok: true,
|
|
233
|
+
value: await fn(db)
|
|
234
|
+
};
|
|
235
|
+
} catch (error) {
|
|
236
|
+
if (isProgramBug(error)) throw error;
|
|
237
|
+
const c = classifyDatabaseError(error, names);
|
|
238
|
+
if (c.kind === "refusal") throw new DatabaseRefusal(c.message);
|
|
239
|
+
return {
|
|
240
|
+
ok: false,
|
|
241
|
+
diagnostic: diagnostic("database.failed", "", "", {
|
|
242
|
+
tool,
|
|
243
|
+
...c.params
|
|
244
|
+
})
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
// src/io/data.ts
|
|
249
|
+
/**
|
|
250
|
+
* Ознака бази розробника — налаштування рівня бази, яке ставить оператор
|
|
251
|
+
* (`ALTER DATABASE … SET` від суперкористувача). Сесійне `options=-c …` чи
|
|
252
|
+
* налаштування ролі її не дають: їх може задати сам рядок підключення.
|
|
253
|
+
*/
|
|
254
|
+
const DEVELOPMENT_ENVIRONMENT = {
|
|
255
|
+
setting: "simetra.environment",
|
|
256
|
+
value: "development"
|
|
257
|
+
};
|
|
258
|
+
const IPV4_LOOPBACK = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
|
|
259
|
+
/**
|
|
260
|
+
* Хост, який візьме `pg`, — машина розробника: `localhost`, петля IPv4
|
|
261
|
+
* `127.0.0.0/8`, `::1` чи шлях unix-сокета. DNS не розв'язується: ім'я, що
|
|
262
|
+
* лише вказує на петлю, — уже не «ця машина» за формою рядка.
|
|
263
|
+
*/
|
|
264
|
+
function isLocalHost(host) {
|
|
265
|
+
if (host === void 0 || host === "") return false;
|
|
266
|
+
if (host.startsWith("/")) return true;
|
|
267
|
+
const h = host.toLowerCase();
|
|
268
|
+
if (h === "localhost" || h === "::1") return true;
|
|
269
|
+
const m = IPV4_LOOPBACK.exec(h);
|
|
270
|
+
return m !== null && m.slice(1).every((octet) => Number(octet) <= 255);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Факти ролі входу й ознаки бази одним оператором. Роль перевіряється
|
|
274
|
+
* фактами, не іменем: ім'я `simetra_runtime` не доводить, що роль не
|
|
275
|
+
* суперкористувач і не мігратор. Відсутня в кластері роль команд дає
|
|
276
|
+
* `false`, а не `42704`, — підзапит з `COALESCE`.
|
|
277
|
+
*/
|
|
278
|
+
const DATA_GUARD_FACTS_SQL = `SELECT r.rolsuper, r.rolbypassrls,
|
|
279
|
+
COALESCE((SELECT pg_catalog.pg_has_role(session_user, c.oid, 'SET')
|
|
280
|
+
FROM pg_catalog.pg_roles c WHERE c.rolname = $1), false) AS command,
|
|
281
|
+
COALESCE(pg_catalog.pg_has_role(session_user, n.nspowner, 'MEMBER'), false) AS migrator,
|
|
282
|
+
COALESCE((SELECT pg_catalog.pg_has_role(session_user, s.oid, 'MEMBER')
|
|
283
|
+
FROM pg_catalog.pg_roles s WHERE s.rolname = $2), false) AS service,
|
|
284
|
+
EXISTS (SELECT FROM pg_catalog.pg_db_role_setting d
|
|
285
|
+
JOIN pg_catalog.pg_database b ON b.oid = d.setdatabase
|
|
286
|
+
WHERE b.datname = pg_catalog.current_database() AND d.setrole = 0
|
|
287
|
+
AND $3 = ANY (d.setconfig)) AS development
|
|
288
|
+
FROM pg_catalog.pg_roles r
|
|
289
|
+
LEFT JOIN pg_catalog.pg_namespace n ON n.nspname = $4
|
|
290
|
+
WHERE r.rolname = session_user`;
|
|
291
|
+
/** Параметри {@link DATA_GUARD_FACTS_SQL} для профілю провайдера. */
|
|
292
|
+
function dataGuardFactsParams(provider) {
|
|
293
|
+
return [
|
|
294
|
+
PLATFORM_ROLES.command,
|
|
295
|
+
PROVIDER_API_ROLES[provider].service,
|
|
296
|
+
`${DEVELOPMENT_ENVIRONMENT.setting}=${DEVELOPMENT_ENVIRONMENT.value}`,
|
|
297
|
+
PLATFORM_SCHEMA
|
|
298
|
+
];
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Claims сесії інструмента: права — користувача `--as`, агент лише
|
|
302
|
+
* названий в `act` (RFC 8693) і прав не дає.
|
|
303
|
+
*/
|
|
304
|
+
function dataSession(provider, o) {
|
|
305
|
+
const role = readRoleOf(provider);
|
|
306
|
+
return {
|
|
307
|
+
sub: o.as,
|
|
308
|
+
...role === void 0 ? {} : { role },
|
|
309
|
+
...o.agent === void 0 ? {} : { act: { sub: o.agent } }
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Запит фактів сирим клієнтом пулу (булеві — `boolean`, а не текст порту
|
|
314
|
+
* рантайму) у транзакції лише читання. Клієнт звільняється до повернення:
|
|
315
|
+
* за `max: 1` незвільнений клієнт заблокував би рантайм.
|
|
316
|
+
*/
|
|
317
|
+
async function checkGuards(pool, provider) {
|
|
318
|
+
const client = await pool.connect();
|
|
319
|
+
client.on("error", () => {});
|
|
320
|
+
let facts;
|
|
321
|
+
let broken = false;
|
|
322
|
+
try {
|
|
323
|
+
await client.query("BEGIN READ ONLY");
|
|
324
|
+
const { rows } = await client.query(DATA_GUARD_FACTS_SQL, dataGuardFactsParams(provider));
|
|
325
|
+
await client.query("COMMIT");
|
|
326
|
+
facts = rows[0];
|
|
327
|
+
} catch (error) {
|
|
328
|
+
broken = true;
|
|
329
|
+
throw error;
|
|
330
|
+
} finally {
|
|
331
|
+
client.release(broken);
|
|
332
|
+
}
|
|
333
|
+
if (facts === void 0 || facts.rolsuper || facts.rolbypassrls || facts.migrator || facts.service || !facts.command) throw new DataGuardRefusal("login-refused");
|
|
334
|
+
if (!facts.development) throw new DataGuardRefusal("not-development");
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Ресурс даних з імені змінної, зафіксованого при запуску. Порожня змінна —
|
|
338
|
+
* ресурсу немає, `invoke` відмовить `no-data`. Пул — на виклик (`open`), і
|
|
339
|
+
* кожен виклик заново проходить запобіжники.
|
|
340
|
+
*/
|
|
341
|
+
function dataResource(env, o) {
|
|
342
|
+
const url = env[o.urlEnv];
|
|
343
|
+
if (url === void 0 || url === "") return void 0;
|
|
344
|
+
return {
|
|
345
|
+
describe: describeConnection(url),
|
|
346
|
+
as: o.as,
|
|
347
|
+
...o.agent === void 0 ? {} : { agent: o.agent },
|
|
348
|
+
async open(provider) {
|
|
349
|
+
let host;
|
|
350
|
+
try {
|
|
351
|
+
host = new pg.Client({ connectionString: url }).host;
|
|
352
|
+
} catch {
|
|
353
|
+
throw new DatabaseRefusal(`The connection string in ${o.urlEnv} is not a valid URL. Nothing changed.`);
|
|
354
|
+
}
|
|
355
|
+
if (!isLocalHost(host)) throw new DataGuardRefusal("not-local");
|
|
356
|
+
const pool = new pg.Pool({
|
|
357
|
+
connectionString: url,
|
|
358
|
+
max: 1
|
|
359
|
+
});
|
|
360
|
+
pool.on("error", () => {});
|
|
361
|
+
try {
|
|
362
|
+
await checkGuards(pool, provider);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
await pool.end().catch(() => {});
|
|
365
|
+
throw error;
|
|
366
|
+
}
|
|
367
|
+
return {
|
|
368
|
+
database: fromPgPool(pool),
|
|
369
|
+
session: dataSession(provider, o),
|
|
370
|
+
close: () => pool.end()
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Збій роботи з базою даних виклику: лише параметри `database.failed`
|
|
377
|
+
* (адреса й код), без `cause` і тексту драйвера, — `run` інструмента
|
|
378
|
+
* повертає їх діагностикою.
|
|
379
|
+
*/
|
|
380
|
+
var DataFailure = class extends Error {
|
|
381
|
+
params;
|
|
382
|
+
name = "DataFailure";
|
|
383
|
+
constructor(params) {
|
|
384
|
+
super("database.failed");
|
|
385
|
+
this.params = params;
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
/** Межа помилок `withData`: правило `withDatabase`, плюс власні відмови й вади. */
|
|
389
|
+
function boundary(error, describe) {
|
|
390
|
+
if (error instanceof DataGuardRefusal || error instanceof ZodError || isProgramBug(error)) return error;
|
|
391
|
+
const c = classifyDatabaseError(error, { target: describe });
|
|
392
|
+
if (c.kind === "refusal") return new DatabaseRefusal(c.message);
|
|
393
|
+
const { sqlstate, ...rest } = c.params;
|
|
394
|
+
return new DataFailure(sqlstate === void 0 ? rest : {
|
|
395
|
+
...rest,
|
|
396
|
+
sqlstate
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Сесія даних одного виклику — єдина межа помилок бази для інструментів
|
|
401
|
+
* даних. `CommandFailure` до неї не доходить: `fn` повертає її як дані.
|
|
402
|
+
* Пул закривається тут, у `finally`, на будь-якому результаті.
|
|
403
|
+
*/
|
|
404
|
+
async function withData(resource, provider, fn) {
|
|
405
|
+
let session;
|
|
406
|
+
try {
|
|
407
|
+
session = await resource.open(provider);
|
|
408
|
+
} catch (error) {
|
|
409
|
+
throw boundary(error, resource.describe);
|
|
410
|
+
}
|
|
411
|
+
let result;
|
|
412
|
+
try {
|
|
413
|
+
result = await fn(session);
|
|
414
|
+
} catch (error) {
|
|
415
|
+
await closeQuietly(session);
|
|
416
|
+
throw boundary(error, resource.describe);
|
|
417
|
+
}
|
|
418
|
+
await closeQuietly(session);
|
|
419
|
+
return result;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Закриття пулу — поза межею результату: після успішного `fn` команда вже
|
|
423
|
+
* закомічена, тож збій закриття не має підміняти ні результат, ні помилку
|
|
424
|
+
* `fn`. У журнал — лише факт, без тексту драйвера (він несе ім'я входу).
|
|
425
|
+
*/
|
|
426
|
+
async function closeQuietly(session) {
|
|
427
|
+
try {
|
|
428
|
+
await session.close();
|
|
429
|
+
} catch {
|
|
430
|
+
process.stderr.write("simetra: closing the data session failed\n");
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
434
|
+
/**
|
|
435
|
+
* Прапорець бере ім'я змінної, а не значення: підказки й `instructions`
|
|
436
|
+
* повторюють argv запуску, тож рядок підключення, переданий замість імені,
|
|
437
|
+
* потрапив би агентові. Значення в тексті не цитується.
|
|
438
|
+
*/
|
|
439
|
+
function checkEnvName(flag, value) {
|
|
440
|
+
if (!ENV_NAME.test(value)) throw new UsageError(`${flag} takes the name of an environment variable (letters, digits and underscores, not starting with a digit), not its value.`);
|
|
441
|
+
}
|
|
442
|
+
const isGuid = (value) => z.guid().safeParse(value).success;
|
|
443
|
+
/**
|
|
444
|
+
* Спільна перевірка прапорців даних MCP і CLI. Типової змінної немає:
|
|
445
|
+
* доступ від імені користувача — явне рішення людини, тож прапорці йдуть
|
|
446
|
+
* разом або не йдуть зовсім. Значення в текст помилки не потрапляють.
|
|
447
|
+
*/
|
|
448
|
+
function parseDataLaunch(flags) {
|
|
449
|
+
const { dataUrlEnv, as, agent } = flags;
|
|
450
|
+
if (dataUrlEnv === void 0 && as === void 0 && agent === void 0) return void 0;
|
|
451
|
+
if (as === void 0) throw new UsageError(agent === void 0 ? "--data-url-env needs --as with the UUID of the user the data tools act as." : "--agent needs --as: the agent acts on behalf of the user named by --as.");
|
|
452
|
+
if (dataUrlEnv === void 0) throw new UsageError("--as needs --data-url-env with the name of the environment variable that holds the connection string of the development database.");
|
|
453
|
+
checkEnvName("--data-url-env", dataUrlEnv);
|
|
454
|
+
if (!isGuid(as)) throw new UsageError("--as takes a user UUID.");
|
|
455
|
+
if (agent !== void 0 && !isGuid(agent)) throw new UsageError("--agent takes an agent UUID.");
|
|
456
|
+
return {
|
|
457
|
+
urlEnv: dataUrlEnv,
|
|
458
|
+
as,
|
|
459
|
+
...agent === void 0 ? {} : { agent }
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
// src/io/metadata-dir.ts
|
|
463
|
+
/**
|
|
464
|
+
* Файли, які читає компілятор; усе інше в теці його не стосується. Перелік
|
|
465
|
+
* боргу — один файл у корені теки: без нього ратчет бачив би порожній перелік
|
|
466
|
+
* і звітував кожну одиницю боргу.
|
|
467
|
+
*/
|
|
468
|
+
const METADATA_SUFFIXES = [
|
|
469
|
+
".meta.json",
|
|
470
|
+
".sql",
|
|
471
|
+
".module.ts"
|
|
472
|
+
];
|
|
473
|
+
const isMetadataFile = (key) => key === SQL_DEBT_FILE || METADATA_SUFFIXES.some((suffix) => key.endsWith(suffix));
|
|
474
|
+
/**
|
|
475
|
+
* Єдине місце читання диска для дверей CLI: компілятор (T1) працює над мапою
|
|
476
|
+
* «шлях → текст» і не знає про файлову систему.
|
|
477
|
+
*/
|
|
478
|
+
async function readMetadataDir(dir) {
|
|
479
|
+
let isDirectory;
|
|
480
|
+
try {
|
|
481
|
+
isDirectory = (await stat(dir)).isDirectory();
|
|
482
|
+
} catch (error) {
|
|
483
|
+
const code = error.code;
|
|
484
|
+
if (code === "ENOENT" || code === "ENOTDIR") throw new UsageError(`metadata directory not found: ${dir}`);
|
|
485
|
+
throw error;
|
|
486
|
+
}
|
|
487
|
+
if (!isDirectory) throw new UsageError(`Not a directory: ${dir}`);
|
|
488
|
+
const entries = await readdir(dir, {
|
|
489
|
+
recursive: true,
|
|
490
|
+
withFileTypes: true
|
|
491
|
+
});
|
|
492
|
+
const files = /* @__PURE__ */ new Map();
|
|
493
|
+
for (const entry of entries) {
|
|
494
|
+
if (!entry.isFile()) continue;
|
|
495
|
+
const full = join(entry.parentPath, entry.name);
|
|
496
|
+
const key = relative(dir, full).split(sep).join("/");
|
|
497
|
+
if (!isMetadataFile(key)) continue;
|
|
498
|
+
files.set(key, await readFile(full, "utf8"));
|
|
499
|
+
}
|
|
500
|
+
return files;
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Єдине місце запису; `content: null` видаляє файл і прибирає порожні теки.
|
|
504
|
+
* Видалення йдуть першими: на регістронезалежній ФС перейменування лише
|
|
505
|
+
* регістру — це видалення старого шляху й запис нового, що вказують на той
|
|
506
|
+
* самий файл, і зворотний порядок стер би щойно записане.
|
|
507
|
+
*/
|
|
508
|
+
async function writeChanges(dir, changes) {
|
|
509
|
+
const root = resolve(dir);
|
|
510
|
+
const targets = /* @__PURE__ */ new Map();
|
|
511
|
+
for (const change of changes) {
|
|
512
|
+
const target = resolve(root, change.path);
|
|
513
|
+
if (!target.startsWith(root + sep)) throw new UsageError(`Path escapes the target directory: ${change.path}`);
|
|
514
|
+
targets.set(change, target);
|
|
515
|
+
}
|
|
516
|
+
const ordered = [...changes.filter((c) => c.content === null), ...changes.filter((c) => c.content !== null)];
|
|
517
|
+
for (const change of ordered) {
|
|
518
|
+
const target = targets.get(change);
|
|
519
|
+
if (change.content === null) {
|
|
520
|
+
await rm(target, { force: true });
|
|
521
|
+
await pruneEmptyDirs(dirname(target), root);
|
|
522
|
+
} else {
|
|
523
|
+
await mkdir(dirname(target), { recursive: true });
|
|
524
|
+
await writeFile(target, change.content, "utf8");
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
async function pruneEmptyDirs(from, root) {
|
|
529
|
+
let current = from;
|
|
530
|
+
while (current !== root && current.startsWith(root + sep)) {
|
|
531
|
+
let entries;
|
|
532
|
+
try {
|
|
533
|
+
entries = await readdir(current);
|
|
534
|
+
} catch {
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
if (entries.length > 0) return;
|
|
538
|
+
await rm(current, { recursive: true });
|
|
539
|
+
current = dirname(current);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
// src/io/schema-path.ts
|
|
543
|
+
/**
|
|
544
|
+
* Резолвер `$schema` для теки метаданих: відносний POSIX-шлях від теки файлу
|
|
545
|
+
* до `node_modules/simetra/schemas/…` проєкту. Саме встановлений пакет, а не
|
|
546
|
+
* той, з якого запущено інструмент: `$schema` вказує на схеми тієї версії,
|
|
547
|
+
* з якою проєкт збирається (спека П2 §8.5). Пакет шукається ліниво — лише
|
|
548
|
+
* коли компілятор справді записує `$schema`, тож читальні виклики працюють і
|
|
549
|
+
* в теці без встановленого пакета.
|
|
550
|
+
*/
|
|
551
|
+
function schemaPathResolver(metadataDir) {
|
|
552
|
+
const root = resolve(metadataDir);
|
|
553
|
+
let schemas;
|
|
554
|
+
return (file, schemaFile) => {
|
|
555
|
+
schemas ??= join(installedPackageDir(root, "simetra"), "schemas");
|
|
556
|
+
return posixRelative(dirname(join(root, file)), join(schemas, schemaFile));
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
// src/tools/database-tools.ts
|
|
560
|
+
const PROJECT_FILE$1 = "project.meta.json";
|
|
561
|
+
/**
|
|
562
|
+
* Двигун вантажиться лише викликом інструмента бази: `simetra compile` і
|
|
563
|
+
* MCP-сервер без бази не тягнуть pg-delta.
|
|
564
|
+
*/
|
|
565
|
+
async function loadEngine() {
|
|
566
|
+
const { createPgDeltaEngine } = await import("./schema-engine-DPPnife2.js");
|
|
567
|
+
return createPgDeltaEngine();
|
|
568
|
+
}
|
|
569
|
+
/** Резолвер `invoke` гарантує ресурс для інструмента з віссю бази. */
|
|
570
|
+
function required$1(database) {
|
|
571
|
+
if (database === void 0) throw new Error("invoke passes the database to a database tool");
|
|
572
|
+
return database;
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Діагностика двигуна у формі компілятора: без файлу (стосується бази, не
|
|
576
|
+
* теки), з параметрами, з яких звіт будує текст потрібною мовою. Ідентичність
|
|
577
|
+
* об'єкта й код двигуна — у параметрах, щоб JSON-вивід їх ніс.
|
|
578
|
+
*/
|
|
579
|
+
function fromEngine(d) {
|
|
580
|
+
return {
|
|
581
|
+
code: d.code,
|
|
582
|
+
severity: d.severity,
|
|
583
|
+
file: "",
|
|
584
|
+
pointer: "",
|
|
585
|
+
message: d.message,
|
|
586
|
+
params: {
|
|
587
|
+
...d.object === void 0 ? {} : { object: d.object },
|
|
588
|
+
...d.engineCode === void 0 ? {} : { engineCode: d.engineCode },
|
|
589
|
+
...d.params
|
|
590
|
+
}
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
const hasErrors = (diagnostics) => diagnostics.some((d) => d.severity === "error");
|
|
594
|
+
/** Тека, якої ще немає, — порожня тека: `introspect` створює проєкт. */
|
|
595
|
+
async function readFolder(dir) {
|
|
596
|
+
return await stat(dir).then(() => true, () => false) ? readMetadataDir(dir) : /* @__PURE__ */ new Map();
|
|
597
|
+
}
|
|
598
|
+
const schemaName = z.string().min(1).max(63);
|
|
599
|
+
const introspectTool = defineTool({
|
|
600
|
+
name: "introspect",
|
|
601
|
+
description: "Read the live database into metadata: tables become CustomTable, enum types PgEnum, everything else verbatim .sql files; ids of known objects are kept. The connection comes from the server's environment. Scope: the schemas of the existing metadata plus `schemas`; a directory without project.meta.json needs `schemas`. Writes nothing when anything is unrepresentable or does not compile.",
|
|
602
|
+
input: z.strictObject({
|
|
603
|
+
schemas: z.array(schemaName).min(1).optional().meta({ description: "Schemas to read; required when the directory has no project.meta.json. The first is the default schema of a new project." }),
|
|
604
|
+
project: z.strictObject({
|
|
605
|
+
name: z.string().min(1).optional(),
|
|
606
|
+
attributeCase: z.enum(ATTRIBUTE_CASES).optional(),
|
|
607
|
+
database: z.strictObject({ provider: z.enum(DATABASE_PROVIDERS).optional() }).optional()
|
|
608
|
+
}).optional().meta({ description: "Name, attribute case and database provider (default supabase) of a new project; an existing project.meta.json is never rewritten, and a value that differs from it is an error." })
|
|
609
|
+
}),
|
|
610
|
+
files: "write",
|
|
611
|
+
database: "read",
|
|
612
|
+
data: "none",
|
|
613
|
+
destructive: false,
|
|
614
|
+
async run({ dir, database }, input) {
|
|
615
|
+
const existing = await readFolder(dir);
|
|
616
|
+
const provider = new Set(PROVIDER_SCHEMAS.supabase);
|
|
617
|
+
const foreign = (input.schemas ?? []).filter((s) => provider.has(s));
|
|
618
|
+
if (foreign.length > 0) throw new UsageError(`Provider schemas are not introspected: ${foreign.join(", ")}. Nothing changed.`);
|
|
619
|
+
if ((input.schemas ?? []).includes(PLATFORM_SCHEMA)) throw new UsageError(`Schema ${PLATFORM_SCHEMA} belongs to the platform and is not introspected. Nothing changed.`);
|
|
620
|
+
let project;
|
|
621
|
+
let scope;
|
|
622
|
+
if (existing.has(PROJECT_FILE$1)) {
|
|
623
|
+
const compiled = await compile(existing);
|
|
624
|
+
if (compiled.model === void 0) return {
|
|
625
|
+
ok: false,
|
|
626
|
+
changes: [],
|
|
627
|
+
diagnostics: compiled.diagnostics
|
|
628
|
+
};
|
|
629
|
+
const own = compiled.model.project;
|
|
630
|
+
project = {
|
|
631
|
+
name: input.project?.name ?? own.name,
|
|
632
|
+
defaultSchema: own.defaultSchema,
|
|
633
|
+
attributeCase: input.project?.attributeCase ?? own.naming.attributeCase,
|
|
634
|
+
databaseProvider: own.database.provider
|
|
635
|
+
};
|
|
636
|
+
const modelScope = (await engineScope(compiled.model)).scope;
|
|
637
|
+
scope = {
|
|
638
|
+
...modelScope,
|
|
639
|
+
schemas: [.../* @__PURE__ */ new Set([...modelScope.schemas, ...input.schemas ?? []])].filter((schema) => schema !== PLATFORM_SCHEMA).sort()
|
|
640
|
+
};
|
|
641
|
+
} else {
|
|
642
|
+
if (input.schemas === void 0) throw new UsageError(`${dir} has no ${PROJECT_FILE$1}, so there is no scope to read: pass schemas, e.g. {"schemas": ["public"]}. Nothing changed.`);
|
|
643
|
+
project = {
|
|
644
|
+
name: input.project?.name ?? "App",
|
|
645
|
+
defaultSchema: input.schemas[0],
|
|
646
|
+
attributeCase: input.project?.attributeCase ?? "camelCase",
|
|
647
|
+
databaseProvider: input.project?.database?.provider ?? "supabase"
|
|
648
|
+
};
|
|
649
|
+
scope = {
|
|
650
|
+
schemas: [...new Set(input.schemas)].sort(),
|
|
651
|
+
provider: project.databaseProvider
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
const engine = await loadEngine();
|
|
655
|
+
const read = await withDatabase(required$1(database), "introspect", (db) => engine.extract(db.target, scope));
|
|
656
|
+
if (!read.ok) return {
|
|
657
|
+
ok: false,
|
|
658
|
+
changes: [],
|
|
659
|
+
diagnostics: [read.diagnostic]
|
|
660
|
+
};
|
|
661
|
+
const extracted = read.value;
|
|
662
|
+
const extractDiagnostics = extracted.diagnostics.map(fromEngine);
|
|
663
|
+
const reversed = await reverseGenerate(extracted.model, {
|
|
664
|
+
project,
|
|
665
|
+
existing,
|
|
666
|
+
newId: () => crypto.randomUUID(),
|
|
667
|
+
schemaPath: schemaPathResolver(dir),
|
|
668
|
+
parse: await loadSqlParser()
|
|
669
|
+
});
|
|
670
|
+
const diagnostics = [...extractDiagnostics, ...reversed.diagnostics];
|
|
671
|
+
const ok = !hasErrors(diagnostics);
|
|
672
|
+
return {
|
|
673
|
+
ok,
|
|
674
|
+
changes: ok ? reversed.changes : [],
|
|
675
|
+
diagnostics,
|
|
676
|
+
data: { schemas: [...scope.schemas] }
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
});
|
|
680
|
+
/** Імена фільтра (`schema.table` чи `table`) у таблиці обох моделей. */
|
|
681
|
+
function resolveTables(filter, known) {
|
|
682
|
+
const tables = [];
|
|
683
|
+
const unknown = [];
|
|
684
|
+
for (const entry of filter) {
|
|
685
|
+
const dot = entry.indexOf(".");
|
|
686
|
+
const hits = known.filter((t) => dot < 0 ? t.name === entry : t.schema === entry.slice(0, dot) && t.name === entry.slice(dot + 1));
|
|
687
|
+
if (hits.length === 0) unknown.push(entry);
|
|
688
|
+
tables.push(...hits);
|
|
689
|
+
}
|
|
690
|
+
return {
|
|
691
|
+
tables,
|
|
692
|
+
unknown
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Чи стосується ідентичність двигуна однієї з таблиць: сама таблиця, її
|
|
697
|
+
* колонки, обмеження, тригери, політики, типові значення, пов'язані з нею
|
|
698
|
+
* індекси, енами й послідовності (`related`) і обгортки (`comment:(…)`,
|
|
699
|
+
* `acl:(…)`) над будь-чим із цього. Індекс, енам і послідовність у Postgres
|
|
700
|
+
* адресуються схемою, а не таблицею, тож зв'язок з таблицею дають моделі.
|
|
701
|
+
*/
|
|
702
|
+
function touchesTables(tables, related) {
|
|
703
|
+
const own = new Set(tables.map((t) => `table:${t.schema}.${t.name}`));
|
|
704
|
+
const prefixes = tables.map((t) => `${t.schema}.${t.name}.`);
|
|
705
|
+
const sub = /^(column|constraint|trigger|rule|policy|default):(.*)$/;
|
|
706
|
+
const touches = (id) => {
|
|
707
|
+
if (own.has(id) || related.has(id)) return true;
|
|
708
|
+
const m = sub.exec(id);
|
|
709
|
+
if (m !== null) return prefixes.some((p) => m[2].startsWith(p));
|
|
710
|
+
const wrapped = /^(?:comment|acl|securityLabel):\((.*)\)/.exec(id);
|
|
711
|
+
return wrapped !== null && touches(wrapped[1]);
|
|
712
|
+
};
|
|
713
|
+
return touches;
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* Ціль дії — те, що вона створює чи знищує. Лише в дій без них (GRANT,
|
|
717
|
+
* `ENABLE RLS`, `REPLICA IDENTITY`) ціль видно в `consumes`; інакше
|
|
718
|
+
* `consumes` — залежності, і FK чужої таблиці потрапив би у фільтр таблиці,
|
|
719
|
+
* на яку посилається.
|
|
720
|
+
*/
|
|
721
|
+
function targetsOf(a) {
|
|
722
|
+
const own = [...a.produces, ...a.destroys];
|
|
723
|
+
return own.length > 0 ? own : a.consumes;
|
|
724
|
+
}
|
|
725
|
+
/** Частини `a.b.c` з лапками Postgres; `undefined` — не ім'я. */
|
|
726
|
+
function nameParts(text) {
|
|
727
|
+
const parts = [];
|
|
728
|
+
const part = /\s*(?:"((?:[^"]|"")+)"|([A-Za-z_][\w$]*))\s*(\.|$)/y;
|
|
729
|
+
while (part.lastIndex < text.length) {
|
|
730
|
+
const m = part.exec(text);
|
|
731
|
+
if (m === null) return void 0;
|
|
732
|
+
parts.push(m[1] === void 0 ? m[2].toLowerCase() : m[1].replace(/""/g, "\""));
|
|
733
|
+
if (m[3] === "") break;
|
|
734
|
+
}
|
|
735
|
+
return parts.length > 0 ? parts : void 0;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Енами й послідовності названих таблиць. Вони адресуються схемою, а не
|
|
739
|
+
* таблицею, тож зв'язок дають колонки (тип, identity, `nextval` у типовому
|
|
740
|
+
* значенні) і `OWNED BY` одиниць — з обох моделей: енам нової колонки є
|
|
741
|
+
* лише в бажаній, видаленої — лише в цільовій.
|
|
742
|
+
*/
|
|
743
|
+
function dependentIds(keys, models) {
|
|
744
|
+
const enums = new Set(models.flatMap((m) => m.enumTypes.map((e) => `${e.schema}.${e.name}`)));
|
|
745
|
+
const ids = /* @__PURE__ */ new Set();
|
|
746
|
+
const sequence = (schema, parts) => {
|
|
747
|
+
if (parts === void 0 || parts.length > 2) return;
|
|
748
|
+
const key = (parts.length === 2 ? parts : [schema, parts[0]]).join(".");
|
|
749
|
+
ids.add(`sequence:${key}`).add(`sequenceOwnedBy:${key}`);
|
|
750
|
+
};
|
|
751
|
+
for (const table of models.flatMap((m) => m.tables)) {
|
|
752
|
+
if (!keys.has(`${table.schema}.${table.name}`)) continue;
|
|
753
|
+
for (const column of table.columns) {
|
|
754
|
+
const type = logicalTypeOf(column.type.replace(/(\[\])+$/, ""), enums);
|
|
755
|
+
if (type.form === "enum") ids.add(`type:${type.schema}.${type.name}`);
|
|
756
|
+
if (column.identity !== void 0) sequence(table.schema, [column.identity.sequence]);
|
|
757
|
+
const next = /nextval\('((?:[^']|'')+)'::regclass\)/.exec(column.default ?? "");
|
|
758
|
+
if (next !== null) sequence(table.schema, nameParts(next[1].replace(/''/g, "'")));
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
for (const unit of models.flatMap((m) => m.units)) {
|
|
762
|
+
if (unit.class !== "sequenceOwnedBy") continue;
|
|
763
|
+
const owner = /OWNED\s+BY\s+(.+?)\s*;?\s*$/i.exec(unit.sql);
|
|
764
|
+
const parts = owner === null ? void 0 : nameParts(owner[1]);
|
|
765
|
+
const table = parts === void 0 ? void 0 : parts.length === 3 ? `${parts[0]}.${parts[1]}` : parts.length === 2 ? `${unit.schema}.${parts[0]}` : void 0;
|
|
766
|
+
if (table !== void 0 && keys.has(table)) sequence(unit.schema, nameParts(unit.identity.slice(unit.identity.indexOf(":") + 1)));
|
|
767
|
+
}
|
|
768
|
+
return ids;
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Чи належить ідентичність двигуна якійсь таблиці моделей, її індексу чи
|
|
772
|
+
* енаму: лише тоді фільтр може судити, що вона поза названими таблицями.
|
|
773
|
+
* Функція, в'юха, роль чи грант-одиниця таблиці не мають — їх не відкидаємо.
|
|
774
|
+
*/
|
|
775
|
+
function attributable(models) {
|
|
776
|
+
const indexes = new Set(models.flatMap((m) => m.tables.flatMap((t) => t.indexes.map((i) => `index:${t.schema}.${i.name}`))));
|
|
777
|
+
const enums = new Set(models.flatMap((m) => m.enumTypes.map((e) => `type:${e.schema}.${e.name}`)));
|
|
778
|
+
const tableKinds = /^(?:table|column|constraint|trigger|rule|policy|default):/;
|
|
779
|
+
const check = (id) => {
|
|
780
|
+
const wrapped = /^(?:comment|acl|securityLabel):\((.*)\)/.exec(id);
|
|
781
|
+
if (wrapped !== null) return check(wrapped[1]);
|
|
782
|
+
return tableKinds.test(id) || indexes.has(id) || enums.has(id);
|
|
783
|
+
};
|
|
784
|
+
return check;
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Звуження звірки до названих таблиць (§10.3 спеки П2: звірка документа з
|
|
788
|
+
* його ТЧ і регістрами, а не всієї бази) разом з їхніми енамами й
|
|
789
|
+
* послідовностями. Діагностика двигуна (без файлу) відкидається лише тоді,
|
|
790
|
+
* коли її об'єкт належить іншій таблиці; без атрибуції вона лишається, бо
|
|
791
|
+
* помилка, яку не віднести до таблиці, може стосуватися й названих.
|
|
792
|
+
*/
|
|
793
|
+
function narrow(data, tables, models) {
|
|
794
|
+
const keys = new Set(tables.map((t) => `${t.schema}.${t.name}`));
|
|
795
|
+
const indexes = new Set(models.flatMap((m) => m.tables.filter((t) => keys.has(`${t.schema}.${t.name}`)).flatMap((t) => t.indexes.map((i) => `index:${t.schema}.${i.name}`))));
|
|
796
|
+
const dependent = dependentIds(keys, models);
|
|
797
|
+
const owned = attributable(models);
|
|
798
|
+
const touches = touchesTables(tables, /* @__PURE__ */ new Set([...indexes, ...dependent]));
|
|
799
|
+
const tablePaths = [...keys].map((k) => `tables.${k}`);
|
|
800
|
+
const enumPaths = new Set([...dependent].filter((id) => id.startsWith("type:")).map((id) => `enumTypes.${id.slice(5)}`));
|
|
801
|
+
return {
|
|
802
|
+
plan: data.plan.filter((a) => targetsOf(a).some(touches)),
|
|
803
|
+
differences: data.differences.filter((d) => tablePaths.some((p) => d.path === p || d.path.startsWith(`${p}.`)) || enumPaths.has(d.path) || d.path.startsWith("units.") && touches(d.path.slice(6))),
|
|
804
|
+
diagnostics: data.diagnostics.filter((d) => {
|
|
805
|
+
const object = d.params?.object;
|
|
806
|
+
return d.file !== "" || typeof object !== "string" || !owned(object) || touches(object);
|
|
807
|
+
})
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
const diffTool = defineTool({
|
|
811
|
+
name: "diff",
|
|
812
|
+
description: "Compare the live database with the metadata through a throwaway shadow database: the plan from the database to the metadata, catalog differences and diagnostics. The connection comes from the server's environment; the target is only read. `tables` narrows the plan, differences and table-attributed diagnostics to the named tables. While the platform's apply state is absent from the database (`applyState`), creating it is not a difference.",
|
|
813
|
+
input: z.strictObject({ tables: z.array(z.string().min(1)).min(1).optional().meta({ description: "Tables to compare: `schema.table` or `table`." }) }),
|
|
814
|
+
files: "read",
|
|
815
|
+
database: "read",
|
|
816
|
+
data: "none",
|
|
817
|
+
destructive: false,
|
|
818
|
+
async run({ dir, database }, input) {
|
|
819
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
820
|
+
const model = compiled.model;
|
|
821
|
+
if (model === void 0) return {
|
|
822
|
+
ok: false,
|
|
823
|
+
changes: [],
|
|
824
|
+
diagnostics: compiled.diagnostics
|
|
825
|
+
};
|
|
826
|
+
const desired = await desiredForApply(model);
|
|
827
|
+
const engine = await loadEngine();
|
|
828
|
+
const { createApplyDatabase } = await import("./schema-engine-DPPnife2.js");
|
|
829
|
+
const compared = await withDatabase(required$1(database), "diff", async (db) => {
|
|
830
|
+
const reader = createApplyDatabase({ readOnly: true });
|
|
831
|
+
const membership = await checkOwnerMembership(reader, db.target, desired.scope, "engine.owner-not-member");
|
|
832
|
+
if (membership.refusal !== void 0) return { refusal: [membership.refusal] };
|
|
833
|
+
const roles = await checkPlatformRoles(reader, db.target, db.shadowBase, desired.sql, await loadSqlParser());
|
|
834
|
+
if (roles.refusal !== void 0) return { refusal: roles.refusal };
|
|
835
|
+
return { comparison: await compareWithDesired(engine, {
|
|
836
|
+
target: db.target,
|
|
837
|
+
...db.shadowBase ? { shadowBase: db.shadowBase } : {}
|
|
838
|
+
}, desired.sql, desired.scope, desired.diagnostics) };
|
|
839
|
+
});
|
|
840
|
+
if (!compared.ok) return {
|
|
841
|
+
ok: false,
|
|
842
|
+
changes: [],
|
|
843
|
+
diagnostics: [...compiled.diagnostics, compared.diagnostic]
|
|
844
|
+
};
|
|
845
|
+
if (compared.value.refusal !== void 0) return {
|
|
846
|
+
ok: false,
|
|
847
|
+
changes: [],
|
|
848
|
+
diagnostics: [...compiled.diagnostics, ...compared.value.refusal.map(fromEngine)]
|
|
849
|
+
};
|
|
850
|
+
const comparison = compared.value.comparison;
|
|
851
|
+
const diagnostics = [...compiled.diagnostics, ...comparison.diagnostics.map(fromEngine)];
|
|
852
|
+
if (comparison.status === "shadow-failed") return {
|
|
853
|
+
ok: false,
|
|
854
|
+
changes: [],
|
|
855
|
+
diagnostics
|
|
856
|
+
};
|
|
857
|
+
const state = applyStateOf(comparison.target, comparison.plan, model);
|
|
858
|
+
const ownedAction = (a) => {
|
|
859
|
+
const targets = targetsOf(a).filter((id) => !id.startsWith("role:"));
|
|
860
|
+
return targets.length > 0 && targets.every(state.owns);
|
|
861
|
+
};
|
|
862
|
+
let data = state.state === "absent" ? {
|
|
863
|
+
plan: comparison.plan.actions.filter((a) => !ownedAction(a)),
|
|
864
|
+
differences: comparison.differences.filter((d) => !state.ownsPath(d.path)),
|
|
865
|
+
diagnostics
|
|
866
|
+
} : {
|
|
867
|
+
plan: comparison.plan.actions,
|
|
868
|
+
differences: comparison.differences,
|
|
869
|
+
diagnostics
|
|
870
|
+
};
|
|
871
|
+
if (input.tables !== void 0) {
|
|
872
|
+
const models = [comparison.target.model, comparison.desired.model];
|
|
873
|
+
const { tables, unknown } = resolveTables(input.tables, models.flatMap((m) => m.tables));
|
|
874
|
+
if (unknown.length > 0) throw new UsageError(`Unknown tables in the filter: ${unknown.join(", ")}. They are neither in the database nor in the metadata. Nothing compared.`);
|
|
875
|
+
data = narrow(data, tables, models);
|
|
876
|
+
}
|
|
877
|
+
const ok = !hasErrors(data.diagnostics);
|
|
878
|
+
return {
|
|
879
|
+
ok,
|
|
880
|
+
changes: [],
|
|
881
|
+
diagnostics: data.diagnostics,
|
|
882
|
+
data: {
|
|
883
|
+
...data,
|
|
884
|
+
applyState: state.state,
|
|
885
|
+
empty: ok && data.plan.length === 0 && data.differences.length === 0
|
|
886
|
+
}
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
});
|
|
890
|
+
// src/tools/apply-tools.ts
|
|
891
|
+
/**
|
|
892
|
+
* Пул лише на виклик: інструменти без застосування не тягнуть `pg`, як і
|
|
893
|
+
* двигун у `loadEngine`.
|
|
894
|
+
*/
|
|
895
|
+
async function applyDatabase(o) {
|
|
896
|
+
const { createApplyDatabase } = await import("./schema-engine-DPPnife2.js");
|
|
897
|
+
return createApplyDatabase(o);
|
|
898
|
+
}
|
|
899
|
+
const refusedWith = (diagnostics) => ({
|
|
900
|
+
ok: false,
|
|
901
|
+
changes: [],
|
|
902
|
+
diagnostics
|
|
903
|
+
});
|
|
904
|
+
function planPromotion(section, model) {
|
|
905
|
+
const { record } = section;
|
|
906
|
+
const object = model.objects.find((o) => o.id === record.objectId);
|
|
907
|
+
return {
|
|
908
|
+
objectId: record.objectId,
|
|
909
|
+
kind: record.kind,
|
|
910
|
+
name: object?.name ?? record.objectId,
|
|
911
|
+
recordHash: section.recordHash,
|
|
912
|
+
tables: record.tables.map(({ schema, from, to }) => ({
|
|
913
|
+
schema,
|
|
914
|
+
from,
|
|
915
|
+
to
|
|
916
|
+
})),
|
|
917
|
+
columns: section.columns,
|
|
918
|
+
canonicalNames: section.canonicalNames,
|
|
919
|
+
permissionItems: section.permissionItems,
|
|
920
|
+
data: section.data
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
function planData(file, artifact, model, expectedBlindFunctions, rightsOrphans) {
|
|
924
|
+
const conversions = new Map((artifact.promotion?.conversions ?? []).map((c) => [c.step, c.class]));
|
|
925
|
+
return {
|
|
926
|
+
file,
|
|
927
|
+
planHash: artifact.planHash,
|
|
928
|
+
fromHash: artifact.fromHash,
|
|
929
|
+
toHash: artifact.toHash,
|
|
930
|
+
drift: artifact.drift,
|
|
931
|
+
promotion: artifact.promotion === null ? null : planPromotion(artifact.promotion, model),
|
|
932
|
+
steps: artifact.steps.map(({ id, origin, class: cls, lockClass, sql }) => {
|
|
933
|
+
const conversion = conversions.get(id);
|
|
934
|
+
return {
|
|
935
|
+
id,
|
|
936
|
+
origin,
|
|
937
|
+
class: cls,
|
|
938
|
+
lockClass,
|
|
939
|
+
sql,
|
|
940
|
+
...conversion === void 0 ? {} : { conversion }
|
|
941
|
+
};
|
|
942
|
+
}),
|
|
943
|
+
locks: artifact.locks,
|
|
944
|
+
implicitLocks: artifact.implicitLocks,
|
|
945
|
+
requiredPermissions: artifact.requiredPermissions,
|
|
946
|
+
environment: {
|
|
947
|
+
role: artifact.role,
|
|
948
|
+
defaultPrivileges: artifact.environment.defaultPrivileges
|
|
949
|
+
},
|
|
950
|
+
plpgsqlCheck: artifact.plpgsqlCheck,
|
|
951
|
+
expectedBlindFunctions,
|
|
952
|
+
rightsOrphans
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
/** Суфікс файлу запису промоції в `plans/` (`promotionFileName`). */
|
|
956
|
+
const RECORD_SUFFIX = promotionFileName("");
|
|
957
|
+
/**
|
|
958
|
+
* Записи промоції з `plans/` кореня (спека промоції §7.1), строго: файл, що
|
|
959
|
+
* не розбирається схемою чи названий не за своїм `objectId`, — відмова плану
|
|
960
|
+
* `plan.promotion-record-invalid`, а не пропуск. Пропущений запис перетворив
|
|
961
|
+
* би промоцію на «запису немає», а вгаданий — на чужий намір. Порядок — за
|
|
962
|
+
* іменем файлу: план детермінований незалежно від файлової системи.
|
|
963
|
+
*/
|
|
964
|
+
async function readPromotionRecords(root) {
|
|
965
|
+
let names;
|
|
966
|
+
try {
|
|
967
|
+
names = await readdir(join(root, PLANS_DIR));
|
|
968
|
+
} catch (error) {
|
|
969
|
+
if (error.code === "ENOENT") return {
|
|
970
|
+
ok: true,
|
|
971
|
+
records: []
|
|
972
|
+
};
|
|
973
|
+
throw error;
|
|
974
|
+
}
|
|
975
|
+
const records = [];
|
|
976
|
+
for (const name of names.filter((n) => n.endsWith(RECORD_SUFFIX)).sort()) {
|
|
977
|
+
const file = `${PLANS_DIR}/${name}`;
|
|
978
|
+
const invalid = (detail) => ({
|
|
979
|
+
ok: false,
|
|
980
|
+
diagnostic: diagnostic("plan.promotion-record-invalid", "", "", {
|
|
981
|
+
file,
|
|
982
|
+
detail
|
|
983
|
+
})
|
|
984
|
+
});
|
|
985
|
+
let text;
|
|
986
|
+
try {
|
|
987
|
+
text = await readFile(join(root, file), "utf8");
|
|
988
|
+
} catch (error) {
|
|
989
|
+
const code = error.code;
|
|
990
|
+
if (code === void 0) throw error;
|
|
991
|
+
return invalid(`the file could not be read (${code})`);
|
|
992
|
+
}
|
|
993
|
+
let json;
|
|
994
|
+
try {
|
|
995
|
+
json = JSON.parse(text);
|
|
996
|
+
} catch (error) {
|
|
997
|
+
if (error instanceof SyntaxError) return invalid(error.message);
|
|
998
|
+
throw error;
|
|
999
|
+
}
|
|
1000
|
+
const parsed = promotionRecordSchema.safeParse(json);
|
|
1001
|
+
if (!parsed.success) return invalid(parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; "));
|
|
1002
|
+
const record = parsed.data;
|
|
1003
|
+
if (promotionFileName(record.objectId) !== name) return invalid(`the record is for object ${record.objectId}, so its file is ${PLANS_DIR}/${promotionFileName(record.objectId)}`);
|
|
1004
|
+
records.push({
|
|
1005
|
+
record,
|
|
1006
|
+
file
|
|
1007
|
+
});
|
|
1008
|
+
}
|
|
1009
|
+
return {
|
|
1010
|
+
ok: true,
|
|
1011
|
+
records
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
const planTool = defineTool({
|
|
1015
|
+
name: "plan",
|
|
1016
|
+
description: "Plan applying the metadata to the live database: drift gate, steps with classes and lock levels, proof on a copy of the current state. Writes plans/<from>-<to>.plan.json next to the metadata directory and nothing else; the database is only read.",
|
|
1017
|
+
input: z.strictObject({}),
|
|
1018
|
+
files: "artifact",
|
|
1019
|
+
database: "read",
|
|
1020
|
+
data: "none",
|
|
1021
|
+
destructive: false,
|
|
1022
|
+
async run({ dir, root, database }) {
|
|
1023
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
1024
|
+
const model = compiled.model;
|
|
1025
|
+
if (model === void 0) return refusedWith(compiled.diagnostics);
|
|
1026
|
+
const promotions = await readPromotionRecords(root);
|
|
1027
|
+
if (!promotions.ok) return refusedWith([...compiled.diagnostics, promotions.diagnostic]);
|
|
1028
|
+
const engine = await loadEngine();
|
|
1029
|
+
const dbs = {
|
|
1030
|
+
reader: await applyDatabase({ readOnly: true }),
|
|
1031
|
+
scratch: await applyDatabase({ readOnly: false })
|
|
1032
|
+
};
|
|
1033
|
+
const built = await withDatabase(required$1(database), "plan", (db) => buildPlan(engine, dbs, model, {
|
|
1034
|
+
target: db.target,
|
|
1035
|
+
...db.shadowBase ? { shadowBase: db.shadowBase } : {}
|
|
1036
|
+
}, promotions.records));
|
|
1037
|
+
if (!built.ok) return refusedWith([...compiled.diagnostics, built.diagnostic]);
|
|
1038
|
+
const outcome = built.value;
|
|
1039
|
+
const diagnostics = [...compiled.diagnostics, ...outcome.diagnostics.map(fromEngine)];
|
|
1040
|
+
switch (outcome.status) {
|
|
1041
|
+
case "refused": return refusedWith(diagnostics);
|
|
1042
|
+
case "unchanged": return {
|
|
1043
|
+
ok: !hasErrors(diagnostics),
|
|
1044
|
+
changes: [],
|
|
1045
|
+
diagnostics,
|
|
1046
|
+
artifacts: [],
|
|
1047
|
+
data: {
|
|
1048
|
+
unchanged: true,
|
|
1049
|
+
rightsOrphans: outcome.rightsOrphans
|
|
1050
|
+
}
|
|
1051
|
+
};
|
|
1052
|
+
case "planned": {
|
|
1053
|
+
const { artifact } = outcome;
|
|
1054
|
+
const file = `${PLANS_DIR}/${planFileName(artifact.fromHash, artifact.toHash)}`;
|
|
1055
|
+
return {
|
|
1056
|
+
ok: !hasErrors(diagnostics),
|
|
1057
|
+
changes: [],
|
|
1058
|
+
diagnostics,
|
|
1059
|
+
artifacts: [{
|
|
1060
|
+
path: file,
|
|
1061
|
+
content: serializePlan(artifact)
|
|
1062
|
+
}],
|
|
1063
|
+
data: planData(file, artifact, model, outcome.expectedBlindFunctions, outcome.rightsOrphans)
|
|
1064
|
+
};
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
});
|
|
1069
|
+
const engineLabel = (e) => `${e.name} ${e.version}`;
|
|
1070
|
+
/** Перші 12 hex-символів, як у імені файлу плану. */
|
|
1071
|
+
const short$1 = (hash) => hash.slice(0, 12);
|
|
1072
|
+
/** Читає файл плану з `plans/` кореня; поза ним — помилка використання. */
|
|
1073
|
+
async function readPlanFile(root, plan) {
|
|
1074
|
+
const path = resolve(root, plan);
|
|
1075
|
+
if (!path.startsWith(resolve(root, "plans") + sep)) throw new UsageError(`The plan file must be under ${PLANS_DIR}/, given relative to the project root (the directory that contains the metadata directory), not to the current directory: ${plan}. Nothing changed.`);
|
|
1076
|
+
try {
|
|
1077
|
+
return await readFile(path, "utf8");
|
|
1078
|
+
} catch (error) {
|
|
1079
|
+
const code = error.code;
|
|
1080
|
+
if (code === "ENOENT" || code === "EISDIR") throw new UsageError(`Plan file not found: ${plan}. Nothing changed.`);
|
|
1081
|
+
throw error;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
/**
|
|
1085
|
+
* Текст звіту репетиції з `plans/`; файлу немає — `undefined`, і раннер
|
|
1086
|
+
* відмовить `apply.rehearsal-required`. Тека на місці звіту — те саме, що
|
|
1087
|
+
* його немає, як у `readPlanFile`: звіту там нема, а сирий EISDIR людині
|
|
1088
|
+
* нічого не скаже.
|
|
1089
|
+
*/
|
|
1090
|
+
async function readReport(root, file) {
|
|
1091
|
+
try {
|
|
1092
|
+
return await readFile(join(root, file), "utf8");
|
|
1093
|
+
} catch (error) {
|
|
1094
|
+
const code = error.code;
|
|
1095
|
+
if (code === "ENOENT" || code === "EISDIR") return void 0;
|
|
1096
|
+
throw error;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* Версії, з якими план побудовано й доведено, мусять бути поточними: інакше
|
|
1101
|
+
* кроки чи відбитки значать інше (платформна спека §6.10). Формат файлу звіряє
|
|
1102
|
+
* вже `parsePlan`.
|
|
1103
|
+
*/
|
|
1104
|
+
function versionMismatches(artifact, engine) {
|
|
1105
|
+
return [
|
|
1106
|
+
[
|
|
1107
|
+
"fingerprintVersion",
|
|
1108
|
+
artifact.fingerprintVersion,
|
|
1109
|
+
FINGERPRINT_VERSION
|
|
1110
|
+
],
|
|
1111
|
+
[
|
|
1112
|
+
"platformVersion",
|
|
1113
|
+
artifact.platformVersion,
|
|
1114
|
+
PLATFORM_VERSION
|
|
1115
|
+
],
|
|
1116
|
+
[
|
|
1117
|
+
"engine",
|
|
1118
|
+
engineLabel(artifact.engine),
|
|
1119
|
+
engineLabel(engine)
|
|
1120
|
+
]
|
|
1121
|
+
].filter(([, plan, current]) => plan !== current).map(([field, plan, current]) => diagnostic("apply.plan-versions", "", "", {
|
|
1122
|
+
field,
|
|
1123
|
+
plan,
|
|
1124
|
+
current
|
|
1125
|
+
}));
|
|
1126
|
+
}
|
|
1127
|
+
const timeoutMs = z.number().int().positive();
|
|
1128
|
+
const applyTool = defineTool({
|
|
1129
|
+
name: "apply",
|
|
1130
|
+
description: "Apply a reviewed plan file to the live database in one transaction, or rehearse it (rolled back; still takes the plan's locks). A rehearsal also builds the desired shadow and proves the resulting state with the engine on the same connection, holding the plan's locks a little longer; a successful rehearsal writes its report to plans/<from>-<to>.rehearsal.json next to the plan. Needs the plan's hash; destructive and relaxing steps need `allow` by id, drift needs `drift`, and a promotion needs its access:, delete:, update:, remove: and repair: items and a valid report from a rehearsal on a copy of the target with data.",
|
|
1131
|
+
input: z.strictObject({
|
|
1132
|
+
plan: z.string().min(1).meta({ description: "Plan file from `plan`, relative to the project root: plans/….plan.json." }),
|
|
1133
|
+
planHash: z.string().regex(/^[0-9a-f]{64}$/).meta({ description: "planHash of the reviewed plan." }),
|
|
1134
|
+
allow: z.array(z.string().regex(/^(?:s[1-9][0-9]*|drift|(?:access|delete|remove|repair):.+)$/)).optional().meta({ description: "Plan items to permit: step ids (s1, s2, …), drift, access:<table>, delete:<table>.<constraint>, remove:<table>, repair:<table>." }),
|
|
1135
|
+
rehearse: z.boolean().optional(),
|
|
1136
|
+
lockTimeoutMs: timeoutMs.optional(),
|
|
1137
|
+
statementTimeoutMs: timeoutMs.optional()
|
|
1138
|
+
}),
|
|
1139
|
+
files: "artifact",
|
|
1140
|
+
database: "write",
|
|
1141
|
+
data: "none",
|
|
1142
|
+
destructive: true,
|
|
1143
|
+
async run({ dir, root, database }, input) {
|
|
1144
|
+
const parsed = parsePlan(await readPlanFile(root, input.plan));
|
|
1145
|
+
if (!parsed.ok && parsed.reason === "format") return refusedWith([fromEngine(parsed.diagnostic)]);
|
|
1146
|
+
if (!parsed.ok) throw new UsageError(`${input.plan} is not a plan file: ${parsed.message}. Nothing changed.`);
|
|
1147
|
+
const { artifact } = parsed;
|
|
1148
|
+
if (!await verifyPlanHash(artifact) || artifact.planHash !== input.planHash) return refusedWith([diagnostic("apply.plan-hash", "", "", {
|
|
1149
|
+
file: input.plan,
|
|
1150
|
+
planHash: input.planHash
|
|
1151
|
+
})]);
|
|
1152
|
+
const engine = await loadEngine();
|
|
1153
|
+
const versions = versionMismatches(artifact, engine.identity);
|
|
1154
|
+
if (versions.length > 0) return refusedWith(versions);
|
|
1155
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
1156
|
+
const model = compiled.model;
|
|
1157
|
+
if (model === void 0) return refusedWith(compiled.diagnostics);
|
|
1158
|
+
if (model.hash !== artifact.toHash) return refusedWith([diagnostic("apply.plan-stale", "", "", {
|
|
1159
|
+
plan: short$1(artifact.toHash),
|
|
1160
|
+
current: short$1(model.hash)
|
|
1161
|
+
})]);
|
|
1162
|
+
const allow = input.allow ?? [];
|
|
1163
|
+
const permissions = checkPermissions({
|
|
1164
|
+
steps: artifact.steps,
|
|
1165
|
+
drift: artifact.drift,
|
|
1166
|
+
promotion: artifact.promotion
|
|
1167
|
+
}, allow);
|
|
1168
|
+
if (permissions.length > 0) return refusedWith(permissions.map(fromEngine));
|
|
1169
|
+
let report;
|
|
1170
|
+
if (input.rehearse !== true && artifact.promotion !== null) {
|
|
1171
|
+
const file = `${PLANS_DIR}/${rehearsalFileName(artifact.fromHash, artifact.toHash)}`;
|
|
1172
|
+
const text = await readReport(root, file);
|
|
1173
|
+
if (text !== void 0) {
|
|
1174
|
+
const parsed = parseRehearsal(text);
|
|
1175
|
+
if (!parsed.ok && parsed.reason === "format") return refusedWith([diagnostic("apply.rehearsal-stale", "", "", { reason: "format" })]);
|
|
1176
|
+
if (!parsed.ok) throw new UsageError(`${file} is not a rehearsal report: ${parsed.message}. Nothing changed.`);
|
|
1177
|
+
report = parsed.report;
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
const timeouts = {
|
|
1181
|
+
...input.lockTimeoutMs === void 0 ? {} : { lockTimeoutMs: input.lockTimeoutMs },
|
|
1182
|
+
...input.statementTimeoutMs === void 0 ? {} : { statementTimeoutMs: input.statementTimeoutMs }
|
|
1183
|
+
};
|
|
1184
|
+
const writer = await applyDatabase({ readOnly: false });
|
|
1185
|
+
const base = {
|
|
1186
|
+
planHash: artifact.planHash,
|
|
1187
|
+
allow,
|
|
1188
|
+
snapshot: canonicalSnapshot(model),
|
|
1189
|
+
timeouts
|
|
1190
|
+
};
|
|
1191
|
+
const executed = await withDatabase(required$1(database), "apply", async (db) => {
|
|
1192
|
+
if (input.rehearse !== true) return { outcome: await executePlan(writer, db.target, artifact, {
|
|
1193
|
+
...base,
|
|
1194
|
+
mode: "apply",
|
|
1195
|
+
...report === void 0 ? {} : { report }
|
|
1196
|
+
}) };
|
|
1197
|
+
const desired = await desiredForApply(model);
|
|
1198
|
+
const roles = await checkPlatformRoles(await applyDatabase({ readOnly: true }), db.target, db.shadowBase, desired.sql, await loadSqlParser());
|
|
1199
|
+
if (roles.refusal !== void 0) return { rolesRefused: roles.refusal };
|
|
1200
|
+
const shadow = await engine.withDesiredShadow({
|
|
1201
|
+
target: db.target,
|
|
1202
|
+
...db.shadowBase ? { shadowBase: db.shadowBase } : {}
|
|
1203
|
+
}, desired.sql, artifact.scope, (shadowDb) => engine.extract(shadowDb, artifact.scope));
|
|
1204
|
+
if (shadow.status === "shadow-failed") return { shadowFailed: shadow.diagnostics };
|
|
1205
|
+
return { outcome: await executePlan(writer, db.target, artifact, {
|
|
1206
|
+
...base,
|
|
1207
|
+
mode: "rehearse",
|
|
1208
|
+
rehearsal: {
|
|
1209
|
+
engine,
|
|
1210
|
+
desired: shadow.value.catalog
|
|
1211
|
+
}
|
|
1212
|
+
}) };
|
|
1213
|
+
});
|
|
1214
|
+
if (!executed.ok) return refusedWith([executed.diagnostic]);
|
|
1215
|
+
if ("shadowFailed" in executed.value) return refusedWith(executed.value.shadowFailed.map(fromEngine));
|
|
1216
|
+
if ("rolesRefused" in executed.value) return refusedWith(executed.value.rolesRefused.map(fromEngine));
|
|
1217
|
+
const outcome = executed.value.outcome;
|
|
1218
|
+
const diagnostics = outcome.diagnostics.map(fromEngine);
|
|
1219
|
+
const ok = !hasErrors(diagnostics);
|
|
1220
|
+
switch (outcome.status) {
|
|
1221
|
+
case "committed": return {
|
|
1222
|
+
ok,
|
|
1223
|
+
changes: [],
|
|
1224
|
+
diagnostics,
|
|
1225
|
+
data: {
|
|
1226
|
+
status: outcome.status,
|
|
1227
|
+
attempts: outcome.attempts,
|
|
1228
|
+
report: null
|
|
1229
|
+
}
|
|
1230
|
+
};
|
|
1231
|
+
case "rolledBack": {
|
|
1232
|
+
const report = `${PLANS_DIR}/${rehearsalFileName(artifact.fromHash, artifact.toHash)}`;
|
|
1233
|
+
return {
|
|
1234
|
+
ok,
|
|
1235
|
+
changes: [],
|
|
1236
|
+
diagnostics,
|
|
1237
|
+
data: {
|
|
1238
|
+
status: outcome.status,
|
|
1239
|
+
attempts: outcome.attempts,
|
|
1240
|
+
report: ok ? report : null
|
|
1241
|
+
},
|
|
1242
|
+
artifacts: ok ? [{
|
|
1243
|
+
path: report,
|
|
1244
|
+
content: serializeRehearsal(rehearsalReport(artifact.planHash, outcome.evidence))
|
|
1245
|
+
}] : []
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
case "refused":
|
|
1249
|
+
case "failed": return refusedWith(diagnostics);
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
});
|
|
1253
|
+
// src/tools/data-policy.ts
|
|
1254
|
+
/**
|
|
1255
|
+
* Чиста політика пакета `data-command` до першого з'єднання: база не
|
|
1256
|
+
* бачить запиту, якому відмовлено. Перевіряється кожна фаза пакета, бо
|
|
1257
|
+
* пакет — одна транзакція: дозволена перша фаза не робить дозволеною решту.
|
|
1258
|
+
* Невідомий об'єкт пропускається — його відхилить схема каталогу T3
|
|
1259
|
+
* (`command.invalid`), і політика не дублює її текст.
|
|
1260
|
+
*/
|
|
1261
|
+
function dataCommandRefusal(model, catalog, batch, o) {
|
|
1262
|
+
const hasModule = (x) => model.moduleFiles.some((m) => m.ownerObjectId === x.id);
|
|
1263
|
+
const moduleRefusal = (object) => ({
|
|
1264
|
+
kind: "command",
|
|
1265
|
+
error: {
|
|
1266
|
+
code: "command.invalid",
|
|
1267
|
+
reason: "object-module",
|
|
1268
|
+
object
|
|
1269
|
+
}
|
|
1270
|
+
});
|
|
1271
|
+
for (const op of batch) {
|
|
1272
|
+
const object = model.objects.find((x) => x.kind === op.object.kind && x.name === op.object.name);
|
|
1273
|
+
if (object === void 0) continue;
|
|
1274
|
+
if (hasModule(object)) return moduleRefusal(op.object);
|
|
1275
|
+
const membershipId = op.action === "create" ? catalog.objects.find((x) => x.id === object.id)?.operations.create?.root?.membership : void 0;
|
|
1276
|
+
const membership = membershipId === void 0 ? void 0 : model.objects.find((x) => x.id === membershipId);
|
|
1277
|
+
if (membership !== void 0 && hasModule(membership)) return moduleRefusal({
|
|
1278
|
+
kind: membership.kind,
|
|
1279
|
+
name: membership.name
|
|
1280
|
+
});
|
|
1281
|
+
if (o.allowRightsWrite) continue;
|
|
1282
|
+
if (KIND_REGISTRY[object.kind].rightsSystem?.(object.data) !== void 0) return {
|
|
1283
|
+
kind: "rights",
|
|
1284
|
+
object: op.object
|
|
1285
|
+
};
|
|
1286
|
+
if (membershipId !== void 0) return {
|
|
1287
|
+
kind: "rights",
|
|
1288
|
+
object: op.object
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
// src/tools/data-tools.ts
|
|
1293
|
+
/**
|
|
1294
|
+
* JSON не має `bigint`, а формат передачі клієнтам — справа П4-B: інструмент
|
|
1295
|
+
* не клієнт П4-B, тож віддає десятковий рядок, який вхід `BigInt` T0 уже
|
|
1296
|
+
* приймає назад.
|
|
1297
|
+
*/
|
|
1298
|
+
function toJson(value) {
|
|
1299
|
+
if (typeof value === "bigint") return String(value);
|
|
1300
|
+
if (Array.isArray(value)) return value.map(toJson);
|
|
1301
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toJson(v)]));
|
|
1302
|
+
return value;
|
|
1303
|
+
}
|
|
1304
|
+
/**
|
|
1305
|
+
* Зведення результату даних для тексту MCP і CLI: кількість рядків чи змін
|
|
1306
|
+
* або код помилки T3 з причиною — повні дані йдуть у структурований вивід.
|
|
1307
|
+
*/
|
|
1308
|
+
function summarizeData(name, data) {
|
|
1309
|
+
if ("error" in data) return `${name}: ${data.error.code}${data.error.reason === void 0 ? "" : `: ${data.error.reason}`}`;
|
|
1310
|
+
const count = (n, what) => `${n} ${what}${n === 1 ? "" : "s"}`;
|
|
1311
|
+
return "rows" in data ? `${name}: ${count(data.rows.length, "row")}` : `${name}: ${count(data.result.changes.length, "change")}`;
|
|
1312
|
+
}
|
|
1313
|
+
const SQLSTATE = /^[0-9A-Z]{5}$/;
|
|
1314
|
+
/**
|
|
1315
|
+
* Журнал рантайму: T3 кладе сюди сирий виняток бази, а stderr MCP-сервера
|
|
1316
|
+
* йде в журнали клієнта. Тож лише вид запису, SQLSTATE і таблиця — ні
|
|
1317
|
+
* тексту, ні `detail`, де Postgres цитує значення й ім'я входу. Stdout —
|
|
1318
|
+
* канал протоколу MCP, туди не пишемо нічого.
|
|
1319
|
+
*/
|
|
1320
|
+
function logRuntimeEntry(entry) {
|
|
1321
|
+
const error = entry.error;
|
|
1322
|
+
const code = typeof error?.code === "string" && SQLSTATE.test(error.code) ? ` SQLSTATE ${error.code}` : "";
|
|
1323
|
+
const table = typeof error?.table === "string" ? ` table ${JSON.stringify(error.table)}` : "";
|
|
1324
|
+
process.stderr.write(`simetra: runtime ${entry.kind} error${code}${table}\n`);
|
|
1325
|
+
}
|
|
1326
|
+
function required(data) {
|
|
1327
|
+
if (data === void 0) throw new Error("invoke passes the data resource to a data tool");
|
|
1328
|
+
return data;
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* Компіляція на кожен виклик (Р-A5-5): зміна теки між викликами дає нову
|
|
1332
|
+
* модель, і рантайм звіряє її хеш із застосованим — кешу, який треба
|
|
1333
|
+
* інвалідувати, немає.
|
|
1334
|
+
*/
|
|
1335
|
+
async function compileDir(dir) {
|
|
1336
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
1337
|
+
if (compiled.model === void 0) return { failed: {
|
|
1338
|
+
ok: false,
|
|
1339
|
+
changes: [],
|
|
1340
|
+
diagnostics: compiled.diagnostics
|
|
1341
|
+
} };
|
|
1342
|
+
return { model: compiled.model };
|
|
1343
|
+
}
|
|
1344
|
+
/**
|
|
1345
|
+
* Рантайм на виклик: пул ролі входу, звірка хешу, дія й закриття пулу
|
|
1346
|
+
* (`withData`). `CommandFailure` — відповідь T3, тож дані результату, а не
|
|
1347
|
+
* збій; збій бази — `database.failed` лише з адресою й кодом.
|
|
1348
|
+
*/
|
|
1349
|
+
async function onRuntime(tool, ctx, model, act) {
|
|
1350
|
+
try {
|
|
1351
|
+
const ran = await withData(required(ctx.data), model.project.database.provider, async (s) => {
|
|
1352
|
+
try {
|
|
1353
|
+
return {
|
|
1354
|
+
ok: true,
|
|
1355
|
+
data: await act(await createCommandRuntime({
|
|
1356
|
+
database: s.database,
|
|
1357
|
+
catalog: buildRuntimeCatalog(model),
|
|
1358
|
+
log: logRuntimeEntry
|
|
1359
|
+
}), s.session)
|
|
1360
|
+
};
|
|
1361
|
+
} catch (error) {
|
|
1362
|
+
if (error instanceof CommandFailure) return {
|
|
1363
|
+
ok: false,
|
|
1364
|
+
data: { error: error.error }
|
|
1365
|
+
};
|
|
1366
|
+
throw error;
|
|
1367
|
+
}
|
|
1368
|
+
});
|
|
1369
|
+
return {
|
|
1370
|
+
ok: ran.ok,
|
|
1371
|
+
changes: [],
|
|
1372
|
+
diagnostics: [],
|
|
1373
|
+
data: ran.data
|
|
1374
|
+
};
|
|
1375
|
+
} catch (error) {
|
|
1376
|
+
if (error instanceof DataFailure) return {
|
|
1377
|
+
ok: false,
|
|
1378
|
+
changes: [],
|
|
1379
|
+
diagnostics: [diagnostic("database.failed", "", "", {
|
|
1380
|
+
tool,
|
|
1381
|
+
...error.params
|
|
1382
|
+
})]
|
|
1383
|
+
};
|
|
1384
|
+
throw error;
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
const dataReadTool = defineTool({
|
|
1388
|
+
name: "data-read",
|
|
1389
|
+
description: "Read application data of the development database as the user given by --as, with that user's rights: one row by id, or a page of rows by equality filter (where, after, limit up to 200). BigInt values come as decimal strings. A runtime error comes as data.error with a code.",
|
|
1390
|
+
input: z.strictObject({ query: readQuerySchema }),
|
|
1391
|
+
files: "read",
|
|
1392
|
+
database: "none",
|
|
1393
|
+
data: "read",
|
|
1394
|
+
destructive: false,
|
|
1395
|
+
async run(ctx, input) {
|
|
1396
|
+
const compiled = await compileDir(ctx.dir);
|
|
1397
|
+
if ("failed" in compiled) return compiled.failed;
|
|
1398
|
+
return onRuntime("data-read", ctx, compiled.model, async (rt, session) => ({ rows: toJson(await rt.read(session, input.query)) }));
|
|
1399
|
+
}
|
|
1400
|
+
});
|
|
1401
|
+
const dataCommandTool = defineTool({
|
|
1402
|
+
name: "data-command",
|
|
1403
|
+
description: "Change application data of the development database as the user given by --as, with that user's rights: a batch of create, update, markDeletion and delete operations in one transaction (update, markDeletion and delete need expectedVersion). Rights catalogs and create of a scope root whose creator gets a role need --allow-rights-write; objects with a module are refused, and for such a root also when its membership catalog has one. BigInt values may be passed as decimal strings. A runtime error comes as data.error with a code.",
|
|
1404
|
+
input: z.strictObject({ operations: batchSchema }),
|
|
1405
|
+
files: "read",
|
|
1406
|
+
database: "none",
|
|
1407
|
+
data: "write",
|
|
1408
|
+
destructive: false,
|
|
1409
|
+
async run(ctx, input) {
|
|
1410
|
+
const compiled = await compileDir(ctx.dir);
|
|
1411
|
+
if ("failed" in compiled) return compiled.failed;
|
|
1412
|
+
const { model } = compiled;
|
|
1413
|
+
const refusal = dataCommandRefusal(model, buildRuntimeCatalog(model), input.operations, { allowRightsWrite: ctx.allowRightsWrite === true });
|
|
1414
|
+
if (refusal?.kind === "command") return {
|
|
1415
|
+
ok: false,
|
|
1416
|
+
changes: [],
|
|
1417
|
+
diagnostics: [],
|
|
1418
|
+
data: { error: refusal.error }
|
|
1419
|
+
};
|
|
1420
|
+
if (refusal?.kind === "rights") return {
|
|
1421
|
+
ok: false,
|
|
1422
|
+
changes: [],
|
|
1423
|
+
diagnostics: [],
|
|
1424
|
+
refusalReason: "rights-write-disabled"
|
|
1425
|
+
};
|
|
1426
|
+
return onRuntime("data-command", ctx, model, async (rt, session) => {
|
|
1427
|
+
return { result: toJson(await rt.run(session, input.operations)) };
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
});
|
|
1431
|
+
// src/tools/mutations.ts
|
|
1432
|
+
const completion = (dir) => ({
|
|
1433
|
+
schemaPath: schemaPathResolver(dir),
|
|
1434
|
+
newId: () => crypto.randomUUID()
|
|
1435
|
+
});
|
|
1436
|
+
/**
|
|
1437
|
+
* Тека читається заново на кожен виклик (стан — диск, не пам'ять процесу), а
|
|
1438
|
+
* в T1 іде лише валідований вхід операції. Запис і dry-run вирішує `invoke`.
|
|
1439
|
+
*/
|
|
1440
|
+
async function apply(dir, operation) {
|
|
1441
|
+
const result = await operation(await readMetadataDir(dir));
|
|
1442
|
+
return {
|
|
1443
|
+
ok: result.ok,
|
|
1444
|
+
changes: result.changes,
|
|
1445
|
+
diagnostics: result.diagnostics
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* Те саме для `promote`: запис промоції їде в `data` і артефактом у
|
|
1450
|
+
* `plans/<objectId>.promotion.json` — план бази читає його звідти (спека
|
|
1451
|
+
* промоції §7.1), бо мапінг у `metadata/` не лишається.
|
|
1452
|
+
*/
|
|
1453
|
+
async function applyPromotion(dir, operation) {
|
|
1454
|
+
const result = await operation(await readMetadataDir(dir));
|
|
1455
|
+
const { record } = result;
|
|
1456
|
+
return {
|
|
1457
|
+
ok: result.ok,
|
|
1458
|
+
changes: result.changes,
|
|
1459
|
+
diagnostics: result.diagnostics,
|
|
1460
|
+
...record === void 0 ? {} : {
|
|
1461
|
+
data: record,
|
|
1462
|
+
artifacts: [{
|
|
1463
|
+
path: `${PLANS_DIR}/${promotionFileName(record.objectId)}`,
|
|
1464
|
+
content: serializeCanonical(record)
|
|
1465
|
+
}]
|
|
1466
|
+
}
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
const createTool = defineTool({
|
|
1470
|
+
name: "create",
|
|
1471
|
+
description: "Create a metadata object; ids and physical names are assigned. Writes only when the result compiles without errors.",
|
|
1472
|
+
input: createObjectInput,
|
|
1473
|
+
files: "write",
|
|
1474
|
+
database: "none",
|
|
1475
|
+
data: "none",
|
|
1476
|
+
destructive: false,
|
|
1477
|
+
run: ({ dir }, input) => apply(dir, (files) => createObject(files, input, completion(dir)))
|
|
1478
|
+
});
|
|
1479
|
+
const addTool = defineTool({
|
|
1480
|
+
name: "add",
|
|
1481
|
+
description: "Add a named element (attribute, tabular section, value, scope kind, ...) to a collection of an object or of the project root. Writes only when the result compiles without errors.",
|
|
1482
|
+
input: addElementInput,
|
|
1483
|
+
files: "write",
|
|
1484
|
+
database: "none",
|
|
1485
|
+
data: "none",
|
|
1486
|
+
destructive: false,
|
|
1487
|
+
run: ({ dir }, input) => apply(dir, (files) => addElement(files, input, completion(dir)))
|
|
1488
|
+
});
|
|
1489
|
+
const renameTool = defineTool({
|
|
1490
|
+
name: "rename",
|
|
1491
|
+
description: "Rename an object or a nested element; references are rewritten, ids and physical names never change. Writes only when the result compiles without errors.",
|
|
1492
|
+
input: renameInput,
|
|
1493
|
+
files: "write",
|
|
1494
|
+
database: "none",
|
|
1495
|
+
data: "none",
|
|
1496
|
+
destructive: false,
|
|
1497
|
+
run: ({ dir }, input) => apply(dir, (files) => renameElement(files, input))
|
|
1498
|
+
});
|
|
1499
|
+
const deleteTool = defineTool({
|
|
1500
|
+
name: "delete",
|
|
1501
|
+
description: "Delete an object or a nested element. Refused while anything references it.",
|
|
1502
|
+
input: deleteInput,
|
|
1503
|
+
files: "write",
|
|
1504
|
+
database: "none",
|
|
1505
|
+
data: "none",
|
|
1506
|
+
destructive: true,
|
|
1507
|
+
run: ({ dir }, input) => apply(dir, (files) => deleteElement(files, input))
|
|
1508
|
+
});
|
|
1509
|
+
const promoteTool = defineTool({
|
|
1510
|
+
name: "promote",
|
|
1511
|
+
description: "Promote an adopted CustomTable (with its tabular-section tables) into a Catalog, a Document without movements or an independent InformationRegister from a complete one-off mapping; ids carry over, names become canonical, dependent function bodies are rewritten. Writes only when the result compiles; returns the promotion record for the database plan.",
|
|
1512
|
+
input: promoteInput,
|
|
1513
|
+
files: "write",
|
|
1514
|
+
database: "none",
|
|
1515
|
+
data: "none",
|
|
1516
|
+
destructive: false,
|
|
1517
|
+
run: ({ dir }, input) => applyPromotion(dir, (files) => promoteObject(files, input, completion(dir)))
|
|
1518
|
+
});
|
|
1519
|
+
// src/tools/read.ts
|
|
1520
|
+
const compileTool = defineTool({
|
|
1521
|
+
name: "compile",
|
|
1522
|
+
description: "Compile the metadata directory and return diagnostics. Reads the disk on every call; writes nothing.",
|
|
1523
|
+
input: z.strictObject({}),
|
|
1524
|
+
files: "read",
|
|
1525
|
+
database: "none",
|
|
1526
|
+
data: "none",
|
|
1527
|
+
destructive: false,
|
|
1528
|
+
async run({ dir, baseline }) {
|
|
1529
|
+
const result = await compile(await readMetadataDir(dir), baseline === void 0 ? void 0 : { baseline });
|
|
1530
|
+
return {
|
|
1531
|
+
ok: result.ok,
|
|
1532
|
+
changes: [],
|
|
1533
|
+
diagnostics: result.diagnostics,
|
|
1534
|
+
data: { model: result.model }
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
});
|
|
1538
|
+
const explainTool = defineTool({
|
|
1539
|
+
name: "explain",
|
|
1540
|
+
description: "Explain one object: its tables, columns, keys and movement queries. Needs a metadata directory that compiles without errors.",
|
|
1541
|
+
input: z.strictObject({
|
|
1542
|
+
kind: metadataKindSchema,
|
|
1543
|
+
name: objectNameSchema
|
|
1544
|
+
}),
|
|
1545
|
+
files: "read",
|
|
1546
|
+
database: "none",
|
|
1547
|
+
data: "none",
|
|
1548
|
+
destructive: false,
|
|
1549
|
+
async run({ dir }, { kind, name }) {
|
|
1550
|
+
const result = await compile(await readMetadataDir(dir));
|
|
1551
|
+
if (result.model === void 0) return {
|
|
1552
|
+
ok: false,
|
|
1553
|
+
changes: [],
|
|
1554
|
+
diagnostics: result.diagnostics
|
|
1555
|
+
};
|
|
1556
|
+
const explanation = explainObject(result.model, {
|
|
1557
|
+
kind,
|
|
1558
|
+
name
|
|
1559
|
+
});
|
|
1560
|
+
if (explanation === void 0) return {
|
|
1561
|
+
ok: false,
|
|
1562
|
+
changes: [],
|
|
1563
|
+
diagnostics: result.diagnostics,
|
|
1564
|
+
refusal: `Object not found: ${kind} ${name}`
|
|
1565
|
+
};
|
|
1566
|
+
return {
|
|
1567
|
+
ok: true,
|
|
1568
|
+
changes: [],
|
|
1569
|
+
diagnostics: result.diagnostics,
|
|
1570
|
+
data: explanation
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
});
|
|
1574
|
+
const fixTool = defineTool({
|
|
1575
|
+
name: "fix",
|
|
1576
|
+
description: "Assign missing ids and physical names, set $schema and canonical form. Writes only when the result compiles without errors.",
|
|
1577
|
+
input: z.strictObject({}),
|
|
1578
|
+
files: "write",
|
|
1579
|
+
database: "none",
|
|
1580
|
+
data: "none",
|
|
1581
|
+
destructive: false,
|
|
1582
|
+
async run({ dir }) {
|
|
1583
|
+
const result = await fixFiles(await readMetadataDir(dir), {
|
|
1584
|
+
schemaPath: schemaPathResolver(dir),
|
|
1585
|
+
newId: () => crypto.randomUUID()
|
|
1586
|
+
});
|
|
1587
|
+
return {
|
|
1588
|
+
ok: result.ok,
|
|
1589
|
+
changes: result.changes,
|
|
1590
|
+
diagnostics: result.diagnostics
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
});
|
|
1594
|
+
// src/tools/rights-maintenance-tool.ts
|
|
1595
|
+
const id = z.string().regex(UUID_TEXT, "expected a UUID");
|
|
1596
|
+
const role = z.string().min(1);
|
|
1597
|
+
/**
|
|
1598
|
+
* Вхід — JSON, одна дія на запуск (Р-A4-8): `strictObject` не пропускає поля
|
|
1599
|
+
* іншої дії, тож помилка написання не перетвориться на тиху іншу дію.
|
|
1600
|
+
*/
|
|
1601
|
+
const input = z.discriminatedUnion("action", [
|
|
1602
|
+
z.strictObject({
|
|
1603
|
+
action: z.literal("firstGlobalAssignment"),
|
|
1604
|
+
user: id,
|
|
1605
|
+
role
|
|
1606
|
+
}),
|
|
1607
|
+
z.strictObject({
|
|
1608
|
+
action: z.literal("restoreGlobalFullAccess"),
|
|
1609
|
+
user: id,
|
|
1610
|
+
role: role.optional()
|
|
1611
|
+
}),
|
|
1612
|
+
z.strictObject({
|
|
1613
|
+
action: z.literal("tenantFullAccess"),
|
|
1614
|
+
scopeKind: z.string().min(1),
|
|
1615
|
+
scope: id,
|
|
1616
|
+
user: id,
|
|
1617
|
+
role,
|
|
1618
|
+
member: z.record(z.string(), z.unknown()).optional()
|
|
1619
|
+
})
|
|
1620
|
+
]);
|
|
1621
|
+
/**
|
|
1622
|
+
* Аварійний вхід у права поза командами (спека П4 §6.12): режим
|
|
1623
|
+
* обслуговування бази діє лише для входу мігратора, тож інструмент — лише
|
|
1624
|
+
* командний рядок і лише з `--yes`; агент через MCP його не бачить (Р-A4-7).
|
|
1625
|
+
*/
|
|
1626
|
+
const rightsMaintenanceTool = defineTool({
|
|
1627
|
+
name: "rights-maintenance",
|
|
1628
|
+
description: "Command line only, needs --yes. Writes one rights assignment in the database maintenance mode, connected as the migrator that applied the plan (SIMETRA_DATABASE_URL). Input is JSON with one action: firstGlobalAssignment {user, role} makes the first global assignment; restoreGlobalFullAccess {user, role?} restores a global fullAccess holder when none is effective; tenantFullAccess {scopeKind, scope, user, role, member?} restores the fullAccess owner of one scope, adding the user's member row from member when the user is not a member yet. Refuses without writing when another apply or maintenance run holds the lock, the applied model is not the compiled one, the user or the scope is unknown, the role does not fit the action, or the level already has what the action makes; a write the user would not hold effectively is rolled back.",
|
|
1629
|
+
input,
|
|
1630
|
+
files: "read",
|
|
1631
|
+
database: "write",
|
|
1632
|
+
data: "none",
|
|
1633
|
+
destructive: true,
|
|
1634
|
+
cliOnly: true,
|
|
1635
|
+
async run({ dir, database }, request) {
|
|
1636
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
1637
|
+
const model = compiled.model;
|
|
1638
|
+
if (model === void 0) return {
|
|
1639
|
+
ok: false,
|
|
1640
|
+
changes: [],
|
|
1641
|
+
diagnostics: compiled.diagnostics
|
|
1642
|
+
};
|
|
1643
|
+
const { createApplyDatabase } = await import("./schema-engine-DPPnife2.js");
|
|
1644
|
+
const ran = await withDatabase(required$1(database), "rights-maintenance", (db) => runRightsMaintenance(createApplyDatabase({ readOnly: false }), db.target, model, request));
|
|
1645
|
+
if (!ran.ok) return {
|
|
1646
|
+
ok: false,
|
|
1647
|
+
changes: [],
|
|
1648
|
+
diagnostics: [ran.diagnostic]
|
|
1649
|
+
};
|
|
1650
|
+
if (!ran.value.ok) return {
|
|
1651
|
+
ok: false,
|
|
1652
|
+
changes: [],
|
|
1653
|
+
diagnostics: [fromEngine(ran.value.diagnostic)]
|
|
1654
|
+
};
|
|
1655
|
+
return {
|
|
1656
|
+
ok: true,
|
|
1657
|
+
changes: [],
|
|
1658
|
+
diagnostics: [],
|
|
1659
|
+
data: ran.value.done
|
|
1660
|
+
};
|
|
1661
|
+
}
|
|
1662
|
+
});
|
|
1663
|
+
// src/tools/roles-tool.ts
|
|
1664
|
+
const PROJECT_FILE = "project.meta.json";
|
|
1665
|
+
/**
|
|
1666
|
+
* Набір ролей теки проєкту (спека П4 §6.2): провайдер — з файлу проєкту, тим самим
|
|
1667
|
+
* читачем, що й `compile`. Без файлу роль входу пропускається явно — пропуск
|
|
1668
|
+
* видно у виводі, бо роль без членства в ролі запиту `roles` потім не
|
|
1669
|
+
* виправив би (наявну лише звіряє).
|
|
1670
|
+
*/
|
|
1671
|
+
async function projectRoleSet(dir) {
|
|
1672
|
+
const text = existsSync(dir) ? (await readMetadataDir(dir)).get(PROJECT_FILE) : void 0;
|
|
1673
|
+
if (text === void 0) return {
|
|
1674
|
+
ok: true,
|
|
1675
|
+
roles: platformRoleSet(void 0),
|
|
1676
|
+
skipped: [{
|
|
1677
|
+
name: PLATFORM_LOGIN_ROLES.runtime,
|
|
1678
|
+
reason: "no-project-file"
|
|
1679
|
+
}]
|
|
1680
|
+
};
|
|
1681
|
+
const read = readProjectFile(text);
|
|
1682
|
+
if (read.project === void 0) return {
|
|
1683
|
+
ok: false,
|
|
1684
|
+
diagnostics: read.diagnostics
|
|
1685
|
+
};
|
|
1686
|
+
return {
|
|
1687
|
+
ok: true,
|
|
1688
|
+
roles: platformRoleSet(read.project.database.provider),
|
|
1689
|
+
skipped: []
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
// src/tools/catalog.ts
|
|
1693
|
+
/** Єдиний каталог інструментів: CLI, MCP і студія — лише його адаптери. */
|
|
1694
|
+
const TOOLS = [
|
|
1695
|
+
compileTool,
|
|
1696
|
+
explainTool,
|
|
1697
|
+
fixTool,
|
|
1698
|
+
createTool,
|
|
1699
|
+
addTool,
|
|
1700
|
+
renameTool,
|
|
1701
|
+
deleteTool,
|
|
1702
|
+
promoteTool,
|
|
1703
|
+
introspectTool,
|
|
1704
|
+
diffTool,
|
|
1705
|
+
planTool,
|
|
1706
|
+
applyTool,
|
|
1707
|
+
defineTool({
|
|
1708
|
+
name: "roles",
|
|
1709
|
+
description: "Create the platform roles: NOLOGIN roles that generated SQL grants to on the target and the shadow server, and the runtime login role on the target only. Reads the project file for `database.provider`; without a project file the login role is skipped, and the output says so. An existing role is only checked. Needs CREATEROLE, and ADMIN OPTION on every parent role of the login role; refuses before creating anything when a server lacks CREATEROLE or a role has an unsafe shape.",
|
|
1710
|
+
input: z.strictObject({}),
|
|
1711
|
+
files: "read",
|
|
1712
|
+
database: "write",
|
|
1713
|
+
data: "none",
|
|
1714
|
+
destructive: false,
|
|
1715
|
+
async run({ dir, database }) {
|
|
1716
|
+
const set = await projectRoleSet(dir);
|
|
1717
|
+
if (!set.ok) return {
|
|
1718
|
+
ok: false,
|
|
1719
|
+
changes: [],
|
|
1720
|
+
diagnostics: set.diagnostics
|
|
1721
|
+
};
|
|
1722
|
+
const { createApplyDatabase } = await import("./schema-engine-DPPnife2.js");
|
|
1723
|
+
const ran = await withDatabase(required$1(database), "roles", (db) => ensurePlatformRoles(createApplyDatabase({ readOnly: false }), [{
|
|
1724
|
+
server: "target",
|
|
1725
|
+
db: db.target
|
|
1726
|
+
}, ...db.shadowBase === void 0 ? [] : [{
|
|
1727
|
+
server: "shadow",
|
|
1728
|
+
db: db.shadowBase
|
|
1729
|
+
}]], set.roles));
|
|
1730
|
+
if (!ran.ok) return {
|
|
1731
|
+
ok: false,
|
|
1732
|
+
changes: [],
|
|
1733
|
+
diagnostics: [ran.diagnostic]
|
|
1734
|
+
};
|
|
1735
|
+
const data = {
|
|
1736
|
+
roles: ran.value.created,
|
|
1737
|
+
skipped: set.skipped
|
|
1738
|
+
};
|
|
1739
|
+
return {
|
|
1740
|
+
ok: ran.value.refusal === void 0,
|
|
1741
|
+
changes: [],
|
|
1742
|
+
diagnostics: (ran.value.refusal ?? []).map(fromEngine),
|
|
1743
|
+
data
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
}),
|
|
1747
|
+
rightsMaintenanceTool,
|
|
1748
|
+
dataReadTool,
|
|
1749
|
+
dataCommandTool
|
|
1750
|
+
];
|
|
1751
|
+
function toolByName(name) {
|
|
1752
|
+
return TOOLS.find((t) => t.name === name);
|
|
1753
|
+
}
|
|
1754
|
+
// src/tools/queue.ts
|
|
1755
|
+
const tails = /* @__PURE__ */ new Map();
|
|
1756
|
+
/**
|
|
1757
|
+
* Черга викликів однієї теки метаданих. Адаптери (MCP-сервер, CLI) можуть
|
|
1758
|
+
* слати виклики паралельно, тож без черги дві мутації читали б той самий стан
|
|
1759
|
+
* і друга мовчки затирала б першу, а записана комбінація двох результатів не
|
|
1760
|
+
* проходила б компіляцію. Читальні інструменти стоять у тій самій черзі:
|
|
1761
|
+
* `writeChanges` пише файли по одному, і компіляція посеред запису побачила б
|
|
1762
|
+
* напівзаписане дерево. Ціна — послідовні компіляції; вони короткі, а
|
|
1763
|
+
* коректність відповіді важливіша за паралелізм. Ключ — розв'язаний шлях, щоб
|
|
1764
|
+
* `./metadata` і абсолютний шлях ділили одну чергу.
|
|
1765
|
+
*/
|
|
1766
|
+
function queueFor(dir) {
|
|
1767
|
+
const key = resolve(dir);
|
|
1768
|
+
return (task) => {
|
|
1769
|
+
const run = (tails.get(key) ?? Promise.resolve()).then(task);
|
|
1770
|
+
const tail = run.catch(() => void 0);
|
|
1771
|
+
tails.set(key, tail);
|
|
1772
|
+
tail.then(() => {
|
|
1773
|
+
if (tails.get(key) === tail) tails.delete(key);
|
|
1774
|
+
});
|
|
1775
|
+
return run;
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1778
|
+
// src/tools/invoke.ts
|
|
1779
|
+
/**
|
|
1780
|
+
* Вичерпні switch по всіх осях: нове значення осі не компілюється, доки не
|
|
1781
|
+
* вирішено його дозвіл. `--read-only` вимикає будь-який запис; запис у базу
|
|
1782
|
+
* й запис даних ще й потребують рішення людини при запуску
|
|
1783
|
+
* (`allowDatabaseWrite`, `allowDataWrite`), а власне тертя (підтвердження з
|
|
1784
|
+
* показаним планом) — ознака `destructive`.
|
|
1785
|
+
*/
|
|
1786
|
+
function permits(tool, o) {
|
|
1787
|
+
const files = tool.files;
|
|
1788
|
+
const database = tool.database;
|
|
1789
|
+
const data = tool.data;
|
|
1790
|
+
let filesOk;
|
|
1791
|
+
switch (files) {
|
|
1792
|
+
case "read":
|
|
1793
|
+
filesOk = true;
|
|
1794
|
+
break;
|
|
1795
|
+
case "artifact":
|
|
1796
|
+
case "write": filesOk = !o.readOnly;
|
|
1797
|
+
}
|
|
1798
|
+
let databaseOk;
|
|
1799
|
+
switch (database) {
|
|
1800
|
+
case "none":
|
|
1801
|
+
case "read":
|
|
1802
|
+
databaseOk = true;
|
|
1803
|
+
break;
|
|
1804
|
+
case "write": databaseOk = !o.readOnly && o.allowDatabaseWrite;
|
|
1805
|
+
}
|
|
1806
|
+
let dataOk;
|
|
1807
|
+
switch (data) {
|
|
1808
|
+
case "none":
|
|
1809
|
+
case "read":
|
|
1810
|
+
dataOk = true;
|
|
1811
|
+
break;
|
|
1812
|
+
case "write": dataOk = !o.readOnly && o.allowDataWrite === true;
|
|
1813
|
+
}
|
|
1814
|
+
return filesOk && databaseOk && dataOk;
|
|
1815
|
+
}
|
|
1816
|
+
/**
|
|
1817
|
+
* Артефакт пишеться лише в `plans/` кореня проєкту (спека designer §3.2);
|
|
1818
|
+
* будь-який інший шлях — помилка інструмента, і перевіряється вона до
|
|
1819
|
+
* першого запису.
|
|
1820
|
+
*/
|
|
1821
|
+
function checkArtifacts(root, artifacts) {
|
|
1822
|
+
const plans = resolve(root, PLANS_DIR) + sep;
|
|
1823
|
+
for (const a of artifacts) {
|
|
1824
|
+
if (a.content === null) throw new UsageError(`An artifact must never delete a file: ${a.path}`);
|
|
1825
|
+
if (!resolve(root, a.path).startsWith(plans)) throw new UsageError(`An artifact must be written under ${PLANS_DIR}/ next to the metadata directory: ${a.path}`);
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
function refused(reason, message, detail) {
|
|
1829
|
+
return {
|
|
1830
|
+
ok: false,
|
|
1831
|
+
written: false,
|
|
1832
|
+
changes: [],
|
|
1833
|
+
diagnostics: [],
|
|
1834
|
+
refusal: {
|
|
1835
|
+
reason,
|
|
1836
|
+
message,
|
|
1837
|
+
...detail === void 0 ? {} : { detail }
|
|
1838
|
+
}
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
/**
|
|
1842
|
+
* Єдине місце рішень про розбір входу, дозволи, підтвердження й запис:
|
|
1843
|
+
* адаптери (CLI, MCP) лише переказують результат. Порядок має значення —
|
|
1844
|
+
* відмова на кожному кроці гарантує, що далі диск не чіпають.
|
|
1845
|
+
*/
|
|
1846
|
+
async function invoke(tool, input, o) {
|
|
1847
|
+
if (tool.cliOnly && o.channel !== "cli") return refused("cli-only", `${tool.name} is available only from the command line. Nothing changed.`);
|
|
1848
|
+
const parsed = tool.input.safeParse(input);
|
|
1849
|
+
if (!parsed.success) return refused("invalid-input", parsed.error.issues.map((i) => i.path.length === 0 ? i.message : `${i.path.join(".")}: ${i.message}`).join("; "));
|
|
1850
|
+
if (o.dryRun && tool.files !== "write") return refused("dry-run-unsupported", tool.name === "apply" ? "apply has no dry run: it writes the database, not files. To run the plan and roll it back, rehearse it. Nothing changed." : `${tool.name} has no dry run: only tools that change the metadata directory preview their changes. Nothing changed.`);
|
|
1851
|
+
if (!permits(tool, o)) {
|
|
1852
|
+
if (permits(tool, {
|
|
1853
|
+
...o,
|
|
1854
|
+
allowDatabaseWrite: true
|
|
1855
|
+
})) return refused("database-write-disabled", databaseWriteHint(o.launchArgs, { tools: tool.name }));
|
|
1856
|
+
if (permits(tool, {
|
|
1857
|
+
...o,
|
|
1858
|
+
allowDataWrite: true
|
|
1859
|
+
})) return refused("data-write-disabled", dataWriteHint(o.launchArgs, { tools: tool.name }));
|
|
1860
|
+
return refused("read-only", readOnlyHint(o.launchArgs));
|
|
1861
|
+
}
|
|
1862
|
+
if (tool.database !== "none" && o.database === void 0) return refused("no-database", noDatabaseHint(o.databaseEnv ?? "SIMETRA_DATABASE_URL", o.channel));
|
|
1863
|
+
if (tool.data !== "none" && o.data === void 0) return refused("no-data", noDataHint(o.dataEnv, o.channel));
|
|
1864
|
+
if (tool.destructive && !o.dryRun && !o.confirmed) return refused("unconfirmed", `${tool.name} is destructive and needs confirmation. Nothing changed.`);
|
|
1865
|
+
const root = dirname(resolve(o.dir));
|
|
1866
|
+
return queueFor(o.dir)(async () => {
|
|
1867
|
+
try {
|
|
1868
|
+
const outcome = await tool.run({
|
|
1869
|
+
dir: o.dir,
|
|
1870
|
+
root,
|
|
1871
|
+
...tool.database === "none" ? {} : { database: o.database },
|
|
1872
|
+
...tool.data === "none" ? {} : { data: o.data },
|
|
1873
|
+
...tool.data === "write" ? { allowRightsWrite: o.allowRightsWrite === true } : {},
|
|
1874
|
+
...o.baseline === void 0 ? {} : { baseline: o.baseline }
|
|
1875
|
+
}, parsed.data);
|
|
1876
|
+
if (outcome.refusalReason === "rights-write-disabled") return refused("rights-write-disabled", rightsWriteHint(o.launchArgs, o.channel));
|
|
1877
|
+
const artifacts = outcome.artifacts ?? [];
|
|
1878
|
+
checkArtifacts(root, artifacts);
|
|
1879
|
+
let write = false;
|
|
1880
|
+
let writeArtifacts = false;
|
|
1881
|
+
switch (tool.files) {
|
|
1882
|
+
case "read": break;
|
|
1883
|
+
case "artifact":
|
|
1884
|
+
if (outcome.changes.length > 0) throw new Error(`${tool.name} is an artifact tool and must not change the metadata directory`);
|
|
1885
|
+
writeArtifacts = outcome.ok && artifacts.length > 0;
|
|
1886
|
+
break;
|
|
1887
|
+
case "write":
|
|
1888
|
+
write = outcome.ok && !o.dryRun && outcome.changes.length > 0;
|
|
1889
|
+
writeArtifacts = outcome.ok && !o.dryRun && artifacts.length > 0;
|
|
1890
|
+
}
|
|
1891
|
+
if (writeArtifacts) await writeChanges(root, artifacts);
|
|
1892
|
+
if (write) await writeChanges(o.dir, outcome.changes);
|
|
1893
|
+
return {
|
|
1894
|
+
ok: outcome.ok,
|
|
1895
|
+
written: write || writeArtifacts,
|
|
1896
|
+
changes: outcome.changes.map((c) => ({
|
|
1897
|
+
path: c.path,
|
|
1898
|
+
deleted: c.content === null
|
|
1899
|
+
})),
|
|
1900
|
+
diagnostics: outcome.diagnostics,
|
|
1901
|
+
...outcome.data === void 0 ? {} : { data: outcome.data },
|
|
1902
|
+
...outcome.artifacts === void 0 ? {} : { artifacts: outcome.artifacts.map((a) => a.path) },
|
|
1903
|
+
...outcome.refusal === void 0 ? {} : { refusal: {
|
|
1904
|
+
reason: "refused",
|
|
1905
|
+
message: outcome.refusal
|
|
1906
|
+
} }
|
|
1907
|
+
};
|
|
1908
|
+
} catch (error) {
|
|
1909
|
+
if (error instanceof DataGuardRefusal) return refused("data-guard", error.message, error.detail);
|
|
1910
|
+
if (error instanceof UsageError) return refused("refused", error.message);
|
|
1911
|
+
throw error;
|
|
1912
|
+
}
|
|
1913
|
+
});
|
|
1914
|
+
}
|
|
1915
|
+
// src/io/report.ts
|
|
1916
|
+
/** Діагностика з текстом потрібною мовою; саме її віддають обидва формати. */
|
|
1917
|
+
function localized(d, locale) {
|
|
1918
|
+
const { message, hint } = localize(d, locale);
|
|
1919
|
+
const rest = { ...d };
|
|
1920
|
+
delete rest.hint;
|
|
1921
|
+
return {
|
|
1922
|
+
...rest,
|
|
1923
|
+
message,
|
|
1924
|
+
...hint === void 0 ? {} : { hint }
|
|
1925
|
+
};
|
|
1926
|
+
}
|
|
1927
|
+
function formatDiagnostics(diagnostics, { dir, locale, format }) {
|
|
1928
|
+
const items = diagnostics.map((d) => localized(d, locale));
|
|
1929
|
+
if (format === "json") return JSON.stringify(items.map((d) => ({
|
|
1930
|
+
...d,
|
|
1931
|
+
dir
|
|
1932
|
+
})), null, 2);
|
|
1933
|
+
const lines = [];
|
|
1934
|
+
for (const d of items) {
|
|
1935
|
+
lines.push(`${placeOf(d, dir)} ${d.severity} ${d.code} ${d.message}`);
|
|
1936
|
+
if (d.hint !== void 0) lines.push(` hint: ${d.hint}`);
|
|
1937
|
+
}
|
|
1938
|
+
const errors = items.filter((d) => d.severity === "error").length;
|
|
1939
|
+
lines.push(`${errors} error(s), ${items.length - errors} warning(s)`);
|
|
1940
|
+
return lines.join("\n");
|
|
1941
|
+
}
|
|
1942
|
+
/**
|
|
1943
|
+
* Місце діагностики в тексті. Позиція друкується лише тоді, коли вона є:
|
|
1944
|
+
* діагностика без файлу (вхід операції загалом) чи файлу, якого немає в
|
|
1945
|
+
* теці, отримала б фальшиве `:1:1`, а читач шукав би там неіснуючу причину.
|
|
1946
|
+
*/
|
|
1947
|
+
function placeOf(d, dir) {
|
|
1948
|
+
if (d.file === "") return `${dir}:`;
|
|
1949
|
+
if (d.range === void 0) return `${dir}/${d.file}:`;
|
|
1950
|
+
const { line, character } = d.range.start;
|
|
1951
|
+
return `${dir}/${d.file}:${line + 1}:${character + 1}`;
|
|
1952
|
+
}
|
|
1953
|
+
/** Зведення звірки: дії плану, відмінності каталогу, діагностика. */
|
|
1954
|
+
function renderDiff(d, report) {
|
|
1955
|
+
const lines = [];
|
|
1956
|
+
if (d.plan.length > 0) {
|
|
1957
|
+
lines.push(`plan (${d.plan.length} action(s), database -> metadata):`);
|
|
1958
|
+
for (const a of d.plan) {
|
|
1959
|
+
const tags = [a.dataLoss ? "data loss" : void 0, a.rewriteRisk ? "rewrite" : void 0].filter((x) => x !== void 0);
|
|
1960
|
+
lines.push(` ${a.sql.trim()}${tags.length > 0 ? ` -- ${tags.join(", ")}` : ""}`);
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
if (d.differences.length > 0) {
|
|
1964
|
+
lines.push(`differences (${d.differences.length}):`);
|
|
1965
|
+
for (const x of d.differences) lines.push(` ${x.kind} ${x.path}: ${x.detail}`);
|
|
1966
|
+
}
|
|
1967
|
+
if (d.applyState === "absent") lines.push("apply state: absent from the database; the first apply creates it");
|
|
1968
|
+
if (d.empty) lines.push("diff: the database matches the metadata");
|
|
1969
|
+
lines.push(report);
|
|
1970
|
+
return lines.join("\n");
|
|
1971
|
+
}
|
|
1972
|
+
const short = (hash) => hash === null ? "initial" : hash.slice(0, 12);
|
|
1973
|
+
/** Режим `plpgsql_check` плану словами виводу. */
|
|
1974
|
+
const PLPGSQL_CHECK_LABEL = {
|
|
1975
|
+
installed: "installed",
|
|
1976
|
+
transient: "transient (installed for the check, rolled back)",
|
|
1977
|
+
unavailable: "unavailable"
|
|
1978
|
+
};
|
|
1979
|
+
const qualified = (schema, name) => `${quoteIdent(schema)}.${quoteIdent(name)}`;
|
|
1980
|
+
/**
|
|
1981
|
+
* Блок «Promotion»: що стає чим і що людина
|
|
1982
|
+
* дозволяє. Таблиця, що лишає своє ім'я, рядка перейменування не дає:
|
|
1983
|
+
* `a -> a` читався б як зміна, якої немає.
|
|
1984
|
+
*/
|
|
1985
|
+
function promotionLines(p, needs) {
|
|
1986
|
+
const lines = [`promotion: ${p.kind} ${p.name} (${p.objectId})`, ` record hash: ${p.recordHash}`];
|
|
1987
|
+
for (const t of p.tables.filter((x) => x.from !== x.to)) lines.push(` table ${qualified(t.schema, t.from)} -> ${qualified(t.schema, t.to)}`);
|
|
1988
|
+
for (const c of p.columns) lines.push(` column ${qualified(c.table.schema, c.table.name)}: ${quoteIdent(c.from)} -> ${quoteIdent(c.to)}`);
|
|
1989
|
+
for (const c of p.canonicalNames) lines.push(` ${c.kind} ${qualified(c.table.schema, c.table.name)}: ${quoteIdent(c.from)} -> ${quoteIdent(c.to)}`);
|
|
1990
|
+
for (const t of p.data) {
|
|
1991
|
+
lines.push(` data steps ${qualified(t.after.schema, t.after.table)}:`);
|
|
1992
|
+
for (const c of t.columns) lines.push(` ${c.step} ${quoteIdent(c.column)} ← ${c.expression} (${c.kind})`);
|
|
1993
|
+
if (t.triggers.length > 0) lines.push(` triggers disabled during the write: ${t.triggers.map((x) => quoteIdent(x.name)).join(", ")}`);
|
|
1994
|
+
}
|
|
1995
|
+
for (const item of p.permissionItems) {
|
|
1996
|
+
lines.push(` ${item.token}${needs.has(item.token) ? ` (needs allow: ${item.token})` : ""}`);
|
|
1997
|
+
for (const s of item.summary) lines.push(` ${s}`);
|
|
1998
|
+
}
|
|
1999
|
+
return lines;
|
|
2000
|
+
}
|
|
2001
|
+
/**
|
|
2002
|
+
* Зведення плану для людини й агента: звідки й куди, `planHash` і файл,
|
|
2003
|
+
* дрейф — першим блоком, до кроків (платформна спека §6.2): кроки читаються
|
|
2004
|
+
* вже знаючи, що ціль дрейфнула. Далі — промоція, бо кроки наміру й класи
|
|
2005
|
+
* конверсій читаються, знаючи, що стає чим. Повний
|
|
2006
|
+
* SQL — у файлі плану; тут перший рядок.
|
|
2007
|
+
*/
|
|
2008
|
+
function renderPlan(d, report, o) {
|
|
2009
|
+
if (d === void 0 || "unchanged" in d) return [o.ok ? "plan: nothing to apply; the database is at the metadata" : "plan: no plan written: the plan was refused or has errors", report].join("\n");
|
|
2010
|
+
const needs = new Set(d.requiredPermissions);
|
|
2011
|
+
const lines = [
|
|
2012
|
+
`plan ${short(d.fromHash)} -> ${short(d.toHash)}`,
|
|
2013
|
+
`${o.written ? "written" : "not written"} ${d.file}`,
|
|
2014
|
+
`planHash: ${d.planHash}`
|
|
2015
|
+
];
|
|
2016
|
+
if (d.drift !== null) {
|
|
2017
|
+
lines.push(`drift (${d.drift.reason}): needs allow: drift`);
|
|
2018
|
+
if (d.drift.sections.length > 0) lines.push(` fingerprint sections: ${d.drift.sections.join(", ")}`);
|
|
2019
|
+
for (const path of d.drift.paths) lines.push(` ${path}`);
|
|
2020
|
+
}
|
|
2021
|
+
if (d.promotion !== null) lines.push(...promotionLines(d.promotion, needs));
|
|
2022
|
+
const stepLine = (s) => {
|
|
2023
|
+
const tags = [
|
|
2024
|
+
`lock ${s.lockClass}`,
|
|
2025
|
+
...s.conversion === void 0 ? [] : [`conversion ${s.conversion}`],
|
|
2026
|
+
...needs.has(s.id) ? [`needs allow: ${s.id}`] : []
|
|
2027
|
+
];
|
|
2028
|
+
const first = s.sql.trim().split("\n")[0] ?? "";
|
|
2029
|
+
return ` ${s.id} ${s.origin} ${s.class} (${tags.join("; ")}) ${first}`;
|
|
2030
|
+
};
|
|
2031
|
+
const environment = d.steps.filter((s) => s.origin === "environment");
|
|
2032
|
+
const steps = d.steps.filter((s) => s.origin !== "environment");
|
|
2033
|
+
if (steps.length === 0) lines.push("steps: none");
|
|
2034
|
+
else {
|
|
2035
|
+
lines.push(`steps (${steps.length}):`);
|
|
2036
|
+
lines.push(...steps.map(stepLine));
|
|
2037
|
+
}
|
|
2038
|
+
if (environment.length > 0) {
|
|
2039
|
+
lines.push(`environment rights: the global default privileges of role ${quoteIdent(d.environment.role)}:`);
|
|
2040
|
+
lines.push(...environment.map(stepLine));
|
|
2041
|
+
}
|
|
2042
|
+
if (d.locks.length > 0) lines.push(`locks up front: ${d.locks.map((l) => `${qualified(l.schema, l.name)} ${LOCK_MODE_SQL[l.mode]}`).join(", ")}`);
|
|
2043
|
+
for (const l of d.implicitLocks) lines.push(`implicit lock: ${qualified(l.schema, l.name)} ${LOCK_MODE_SQL[l.mode]} taken by step ${l.step}, not up front: the apply role may not lock it explicitly`);
|
|
2044
|
+
lines.push(`plpgsql_check: ${PLPGSQL_CHECK_LABEL[d.plpgsqlCheck]}`);
|
|
2045
|
+
if (d.expectedBlindFunctions > 0) lines.push(`expected provider blind functions (preset): ${d.expectedBlindFunctions}`);
|
|
2046
|
+
lines.push(report);
|
|
2047
|
+
return lines.join("\n");
|
|
2048
|
+
}
|
|
2049
|
+
/**
|
|
2050
|
+
* Підсумок застосування; репетиція нагадує, що блокування були справжні.
|
|
2051
|
+
* Без даних заголовок судить за діагностикою: після обриву з невідомим
|
|
2052
|
+
* результатом «нічого не записано» було б неправдою, а повтор за нею міг би
|
|
2053
|
+
* застосувати план удруге.
|
|
2054
|
+
*/
|
|
2055
|
+
function renderApply(d, diagnostics, report) {
|
|
2056
|
+
const unknown = diagnostics.find((x) => x.code === "apply.connection-lost" && x.params?.outcome === "unknown");
|
|
2057
|
+
return [d === void 0 ? unknown === void 0 ? "apply: nothing was written" : `apply: outcome unknown — check simetra.ledger for apply id ${String(unknown.params?.applyId)}` : d.status === "committed" ? `apply: committed in ${d.attempts} attempt(s)` : `rehearse: rolled back after ${d.attempts} attempt(s); the database was not changed; ${d.report === null ? "no rehearsal report was written" : `rehearsal report written to ${d.report}`}. The rehearsal took the plan's locks, as apply does.`, report].join("\n");
|
|
2058
|
+
}
|
|
2059
|
+
export { invoke as a, summarizeData as c, writeChanges as d, checkEnvName as f, databaseResource as h, renderPlan as i, toJson as l, parseDataLaunch as m, renderApply as n, TOOLS as o, dataResource as p, renderDiff as r, toolByName as s, formatDiagnostics as t, isMetadataFile as u };
|