@simetrajs/designer 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1550 @@
1
+ #!/usr/bin/env node
2
+ import { r as defineTool, t as PLANS_DIR } from "./types-CSc8XWLd.js";
3
+ import { n as ShadowServerError, r as ShadowServerMismatchError, t as ShadowCreateRefusedError } from "./errors-D5pJLrjP.js";
4
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
5
+ import { dirname, join, posix, relative, resolve, sep } from "node:path";
6
+ import { ATTRIBUTE_CASES, DATABASE_PROVIDERS, PLATFORM_SCHEMA, SQL_DEBT_FILE, logicalTypeOf, metadataKindSchema, objectNameSchema, quoteIdent } from "simetra/model";
7
+ import { ApplyConnectionLost, ApplyDbError, FINGERPRINT_VERSION, LOCK_MODE_SQL, PLATFORM_VERSION, SUPABASE_SCHEMAS, applyStateOf, buildPlan, checkOwnerMembership, checkPermissions, compareWithDesired, desiredForApply, engineScope, executePlan, parsePlan, parseRehearsal, planFileName, rehearsalFileName, rehearsalReport, reverseGenerate, serializePlan, serializeRehearsal, verifyPlanHash } from "simetra/schema";
8
+ import { addElement, addElementInput, canonicalSnapshot, compile, createObject, createObjectInput, deleteElement, deleteInput, diagnostic, explainObject, fixFiles, loadSqlParser, localize, promoteInput, promoteObject, promotionFileName, promotionRecordSchema, renameElement, renameInput, serializeCanonical } from "simetra/compiler";
9
+ import { z } from "zod";
10
+ import { existsSync } from "node:fs";
11
+ //#region src/io/usage-error.ts
12
+ /**
13
+ * Помилка використання (немає теки, шлях поза текою): викликач може виправити
14
+ * її сам. Лише її `invoke` перетворює на відмову; будь-який інший виняток —
15
+ * баг, і він не повинен маскуватися під відмову.
16
+ */
17
+ var UsageError = class extends Error {
18
+ name = "UsageError";
19
+ };
20
+ //#endregion
21
+ //#region src/io/database.ts
22
+ /**
23
+ * Відмова виклику бази з текстом, який уже безпечно показати: без рядка
24
+ * підключення, користувача й пароля. Помилка використання — викликач може
25
+ * виправити її сам (змінна середовища, сервер тіні).
26
+ */
27
+ var DatabaseRefusal = class extends UsageError {
28
+ name = "DatabaseRefusal";
29
+ };
30
+ /**
31
+ * `host:port/db` — єдине про підключення, що можна показати. Рядок, який не
32
+ * розбирається як URL, не цитуємо: він міг би бути самим паролем.
33
+ */
34
+ function describeConnection(url) {
35
+ try {
36
+ const u = new URL(url);
37
+ const db = decodeURIComponent(u.pathname.replace(/^\//, ""));
38
+ return `${u.hostname}:${u.port === "" ? "5432" : u.port}/${db}`;
39
+ } catch {
40
+ return "the configured database";
41
+ }
42
+ }
43
+ /**
44
+ * Ресурс запуску з імен змінних, зафіксованих при запуску. Без змінної цілі
45
+ * ресурсу немає — `invoke` відмовить з її ім'ям. Значення читається тут, а
46
+ * пули відкриває лише виклик інструмента бази.
47
+ */
48
+ function databaseResource(env, names) {
49
+ const url = env[names.url];
50
+ if (url === void 0 || url === "") return void 0;
51
+ const describe = describeConnection(url);
52
+ return {
53
+ describe,
54
+ async connect() {
55
+ if (names.shadow === void 0) return {
56
+ target: { url },
57
+ describe
58
+ };
59
+ const shadowUrl = env[names.shadow];
60
+ if (shadowUrl === void 0 || shadowUrl === "") throw new DatabaseRefusal(`The environment variable ${names.shadow} named by --shadow-url-env is not set. Nothing changed.`);
61
+ return {
62
+ target: { url },
63
+ shadowBase: { url: shadowUrl },
64
+ describe
65
+ };
66
+ }
67
+ };
68
+ }
69
+ /** Мережеві коди Node: база недосяжна, і повторити варто після виправлення адреси. */
70
+ const UNREACHABLE = /* @__PURE__ */ new Set([
71
+ "ECONNREFUSED",
72
+ "ECONNRESET",
73
+ "ENOTFOUND",
74
+ "EAI_AGAIN",
75
+ "ETIMEDOUT",
76
+ "EHOSTUNREACH",
77
+ "ENETUNREACH"
78
+ ]);
79
+ /**
80
+ * Код Node (`EPIPE`, `ERR_INVALID_URL`) перевіряється раніше за SQLSTATE: обидва
81
+ * бувають п'ятисимвольними, а класу SQLSTATE на `E` у Postgres немає.
82
+ */
83
+ const NODE_CODE = /^E[A-Z_]+$/;
84
+ const SQLSTATE = /^[0-9A-Z]{5}$/;
85
+ /**
86
+ * Збій драйвера без коду, що означає втрачене чи не встановлене з'єднання.
87
+ * Текст лише розпізнається, ніколи не цитується.
88
+ */
89
+ const LOST_CONNECTION = /^Connection terminated|^timeout expired/;
90
+ /**
91
+ * Код помилки: драйвер і Node кладуть його в `code`, а порт виконання T2 —
92
+ * SQLSTATE в `sqlstate` (клас T2 не знає драйвера й не імітує його поле).
93
+ */
94
+ function codeOf(error) {
95
+ if (error instanceof ApplyDbError) return error.sqlstate;
96
+ const code = error.code;
97
+ return typeof code === "string" ? code : void 0;
98
+ }
99
+ const refusal = (message, note = "") => ({
100
+ kind: "refusal",
101
+ message: `${message}${note} Nothing changed.`
102
+ });
103
+ /**
104
+ * Тінь потребує сесійної семантики (`CREATE DATABASE`, підключення до нової
105
+ * бази за іменем, сесійні `SET` завантажувача), а детектора режиму пулера
106
+ * немає (спека designer §3.2): збій тіні з нерозпізнаною причиною лише
107
+ * називає вимогу. Відмова без `CREATEDB` чи через іншу мажорну версію її не
108
+ * отримує — причина там уже відома.
109
+ */
110
+ const SHADOW_CONNECTION = " The shadow needs a direct or session-mode connection; a transaction-mode pooler is not guaranteed to support it.";
111
+ /**
112
+ * Єдина межа, на якій помилка підключення чи запиту стає текстом для
113
+ * виводу. Текст складається лише зі стабільних фраз, адреси `host:port/db` і
114
+ * коду помилки: повідомлення драйвера й двигуна не цитуються, бо несуть ім'я
115
+ * користувача («password authentication failed for user …»), а інші —
116
+ * будь-що з рядка підключення. Наші власні відмови вже безпечні й ідуть як є.
117
+ */
118
+ function classifyDatabaseError(error, names) {
119
+ return classify(error, names, "");
120
+ }
121
+ /** `note` — речення перед «Nothing changed.» у кожній відмові. */
122
+ function classify(error, names, note) {
123
+ const describe = names.target;
124
+ const refused = (message) => refusal(message, note);
125
+ if (error instanceof DatabaseRefusal) return {
126
+ kind: "refusal",
127
+ message: error.message
128
+ };
129
+ if (error instanceof ShadowServerMismatchError) return {
130
+ kind: "refusal",
131
+ message: error.message
132
+ };
133
+ if (error instanceof ShadowCreateRefusedError) {
134
+ const where = error.onShadowBase ? names.shadow ?? describe : describe;
135
+ 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."}`);
136
+ }
137
+ if (error instanceof ShadowServerError) {
138
+ const where = error.onShadowBase ? names.shadow ?? describe : describe;
139
+ const c = classify(error.cause, { target: where }, SHADOW_CONNECTION);
140
+ if (c.kind === "refusal") return c;
141
+ const { error: name, sqlstate } = c.params;
142
+ return refusal(`A shadow database could not be created or reached on ${where} (${name}${sqlstate === void 0 ? "" : `, SQLSTATE ${sqlstate}`}).`, SHADOW_CONNECTION);
143
+ }
144
+ if (error instanceof AggregateError && error.errors.length > 0) return classify(error.errors[0], names, note);
145
+ if (!(error instanceof Error)) return {
146
+ kind: "failure",
147
+ params: {
148
+ database: describe,
149
+ error: "unknown"
150
+ }
151
+ };
152
+ if (error instanceof ApplyConnectionLost) return refused(`The connection to the database at ${describe} was lost or timed out.`);
153
+ const code = codeOf(error);
154
+ if (code !== void 0 && NODE_CODE.test(code)) {
155
+ if (UNREACHABLE.has(code)) return refused(`The database at ${describe} is unreachable (${code}). Check the host and port in the connection string.`);
156
+ if (code === "ERR_INVALID_URL") return refused("The connection string is not a valid URL.");
157
+ return {
158
+ kind: "failure",
159
+ params: {
160
+ database: describe,
161
+ error: `${error.name} ${code}`
162
+ }
163
+ };
164
+ }
165
+ if (code !== void 0 && SQLSTATE.test(code)) {
166
+ if (code.startsWith("28")) return refused(`Authentication to the database at ${describe} failed. Check the user and password in the connection string.`);
167
+ if (code.startsWith("08")) return refused(`The connection to the database at ${describe} failed (SQLSTATE ${code}).`);
168
+ if (code === "3D000") return refused(`The database at ${describe} does not exist.`);
169
+ if (code === "42501") return refused(`The connecting role lacks a privilege this tool needs on ${describe} (SQLSTATE 42501).`);
170
+ return {
171
+ kind: "failure",
172
+ params: {
173
+ database: describe,
174
+ error: error.name,
175
+ sqlstate: code
176
+ }
177
+ };
178
+ }
179
+ if (code === void 0 && LOST_CONNECTION.test(error.message)) return refused(`The connection to the database at ${describe} was lost or timed out.`);
180
+ return {
181
+ kind: "failure",
182
+ params: {
183
+ database: describe,
184
+ error: error.name
185
+ }
186
+ };
187
+ }
188
+ /**
189
+ * Помилка програми, а не бази: вбудовані класи JS без коду драйвера чи Node
190
+ * (у Node `TypeError` буває з кодом `ERR_*`, як `ERR_INVALID_URL`). Драйвер
191
+ * кидає `Error` чи `DatabaseError`, тож його текст сюди не потрапляє, а
192
+ * баг не маскується під збій бази.
193
+ */
194
+ function isProgramBug(error) {
195
+ return (error instanceof TypeError || error instanceof RangeError || error instanceof ReferenceError || error instanceof SyntaxError) && codeOf(error) === void 0;
196
+ }
197
+ /**
198
+ * Підключення одного виклику — єдина межа помилок бази. Відмова
199
+ * (`DatabaseRefusal`) летить до `invoke` і стає кодом 2; збій роботи з базою
200
+ * стає діагностикою `database.failed` (код 1, MCP `isError`). Сирий виняток
201
+ * бази далі не йде: SDK MCP показав би агенту його текст. Баг програми
202
+ * (`isProgramBug`) летить далі як є — шлях внутрішньої помилки `invoke`.
203
+ * Пули відкриває й закриває двигун усередині `fn`.
204
+ */
205
+ async function withDatabase(resource, tool, fn) {
206
+ let names = { target: resource.describe };
207
+ try {
208
+ const db = await resource.connect();
209
+ if (db.shadowBase !== void 0) names = {
210
+ ...names,
211
+ shadow: describeConnection(db.shadowBase.url)
212
+ };
213
+ return {
214
+ ok: true,
215
+ value: await fn(db)
216
+ };
217
+ } catch (error) {
218
+ if (isProgramBug(error)) throw error;
219
+ const c = classifyDatabaseError(error, names);
220
+ if (c.kind === "refusal") throw new DatabaseRefusal(c.message);
221
+ return {
222
+ ok: false,
223
+ diagnostic: diagnostic("database.failed", "", "", {
224
+ tool,
225
+ ...c.params
226
+ })
227
+ };
228
+ }
229
+ }
230
+ //#endregion
231
+ //#region src/io/metadata-dir.ts
232
+ /**
233
+ * Файли, які читає компілятор; усе інше в теці його не стосується. Перелік
234
+ * боргу — один файл у корені теки: без нього ратчет бачив би порожній перелік
235
+ * і звітував кожну одиницю боргу.
236
+ */
237
+ const METADATA_SUFFIXES = [
238
+ ".meta.json",
239
+ ".sql",
240
+ ".module.ts"
241
+ ];
242
+ const isMetadataFile = (key) => key === SQL_DEBT_FILE || METADATA_SUFFIXES.some((suffix) => key.endsWith(suffix));
243
+ /**
244
+ * Єдине місце читання диска для дверей CLI: компілятор (T1) працює над мапою
245
+ * «шлях → текст» і не знає про файлову систему.
246
+ */
247
+ async function readMetadataDir(dir) {
248
+ let isDirectory;
249
+ try {
250
+ isDirectory = (await stat(dir)).isDirectory();
251
+ } catch (error) {
252
+ const code = error.code;
253
+ if (code === "ENOENT" || code === "ENOTDIR") throw new UsageError(`metadata directory not found: ${dir}`);
254
+ throw error;
255
+ }
256
+ if (!isDirectory) throw new UsageError(`Not a directory: ${dir}`);
257
+ const entries = await readdir(dir, {
258
+ recursive: true,
259
+ withFileTypes: true
260
+ });
261
+ const files = /* @__PURE__ */ new Map();
262
+ for (const entry of entries) {
263
+ if (!entry.isFile()) continue;
264
+ const full = join(entry.parentPath, entry.name);
265
+ const key = relative(dir, full).split(sep).join("/");
266
+ if (!isMetadataFile(key)) continue;
267
+ files.set(key, await readFile(full, "utf8"));
268
+ }
269
+ return files;
270
+ }
271
+ /**
272
+ * Єдине місце запису; `content: null` видаляє файл і прибирає порожні теки.
273
+ * Видалення йдуть першими: на регістронезалежній ФС перейменування лише
274
+ * регістру — це видалення старого шляху й запис нового, що вказують на той
275
+ * самий файл, і зворотний порядок стер би щойно записане.
276
+ */
277
+ async function writeChanges(dir, changes) {
278
+ const root = resolve(dir);
279
+ const targets = /* @__PURE__ */ new Map();
280
+ for (const change of changes) {
281
+ const target = resolve(root, change.path);
282
+ if (!target.startsWith(root + sep)) throw new UsageError(`Path escapes the target directory: ${change.path}`);
283
+ targets.set(change, target);
284
+ }
285
+ const ordered = [...changes.filter((c) => c.content === null), ...changes.filter((c) => c.content !== null)];
286
+ for (const change of ordered) {
287
+ const target = targets.get(change);
288
+ if (change.content === null) {
289
+ await rm(target, { force: true });
290
+ await pruneEmptyDirs(dirname(target), root);
291
+ } else {
292
+ await mkdir(dirname(target), { recursive: true });
293
+ await writeFile(target, change.content, "utf8");
294
+ }
295
+ }
296
+ }
297
+ async function pruneEmptyDirs(from, root) {
298
+ let current = from;
299
+ while (current !== root && current.startsWith(root + sep)) {
300
+ let entries;
301
+ try {
302
+ entries = await readdir(current);
303
+ } catch {
304
+ return;
305
+ }
306
+ if (entries.length > 0) return;
307
+ await rm(current, { recursive: true });
308
+ current = dirname(current);
309
+ }
310
+ }
311
+ //#endregion
312
+ //#region src/io/package-path.ts
313
+ /**
314
+ * Тека встановленого пакета: перший предок `fromDir` (включно) з
315
+ * `node_modules/<pkg>/package.json`. Шлях навмисно не проходить `realpath`:
316
+ * pnpm робить `node_modules/<pkg>` симлінком у сховище, а значення, що потрапляє
317
+ * у файли метаданих, мусить бути однаковим на кожній машині й переживати
318
+ * перенос репо.
319
+ */
320
+ function installedPackageDir(fromDir, pkg) {
321
+ const start = resolve(fromDir);
322
+ let current = start;
323
+ for (;;) {
324
+ const candidate = join(current, "node_modules", pkg);
325
+ if (existsSync(join(candidate, "package.json"))) return candidate;
326
+ const parent = dirname(current);
327
+ if (parent === current) throw new UsageError(`${pkg} is not installed in node_modules above ${start}`);
328
+ current = parent;
329
+ }
330
+ }
331
+ //#endregion
332
+ //#region src/io/schema-path.ts
333
+ /**
334
+ * Резолвер `$schema` для теки метаданих: відносний POSIX-шлях від теки файлу
335
+ * до `node_modules/simetra/schemas/…` проєкту. Саме встановлений пакет, а не
336
+ * той, з якого запущено інструмент: `$schema` вказує на схеми тієї версії,
337
+ * з якою проєкт збирається (спека П2 §8.5). Пакет шукається ліниво — лише
338
+ * коли компілятор справді записує `$schema`, тож читальні виклики працюють і
339
+ * в теці без встановленого пакета.
340
+ */
341
+ function schemaPathResolver(metadataDir) {
342
+ const root = resolve(metadataDir);
343
+ let schemas;
344
+ return (file, schemaFile) => {
345
+ schemas ??= join(installedPackageDir(root, "simetra"), "schemas");
346
+ return relative(dirname(join(root, file)), join(schemas, schemaFile)).split(sep).join(posix.sep);
347
+ };
348
+ }
349
+ //#endregion
350
+ //#region src/tools/database-tools.ts
351
+ const PROJECT_FILE = "project.meta.json";
352
+ /**
353
+ * Двигун вантажиться лише викликом інструмента бази: `simetra compile` і
354
+ * MCP-сервер без бази не тягнуть pg-delta.
355
+ */
356
+ async function loadEngine() {
357
+ const { createPgDeltaEngine } = await import("./schema-engine-DAsJEc8K.js");
358
+ return createPgDeltaEngine();
359
+ }
360
+ /** Резолвер `invoke` гарантує ресурс для інструмента з віссю бази. */
361
+ function required(database) {
362
+ if (database === void 0) throw new Error("invoke passes the database to a database tool");
363
+ return database;
364
+ }
365
+ /**
366
+ * Діагностика двигуна у формі компілятора: без файлу (стосується бази, не
367
+ * теки), з параметрами, з яких звіт будує текст потрібною мовою. Ідентичність
368
+ * об'єкта й код двигуна — у параметрах, щоб JSON-вивід їх ніс.
369
+ */
370
+ function fromEngine(d) {
371
+ return {
372
+ code: d.code,
373
+ severity: d.severity,
374
+ file: "",
375
+ pointer: "",
376
+ message: d.message,
377
+ params: {
378
+ ...d.object === void 0 ? {} : { object: d.object },
379
+ ...d.engineCode === void 0 ? {} : { engineCode: d.engineCode },
380
+ ...d.params
381
+ }
382
+ };
383
+ }
384
+ const hasErrors = (diagnostics) => diagnostics.some((d) => d.severity === "error");
385
+ /** Тека, якої ще немає, — порожня тека: `introspect` створює проєкт. */
386
+ async function readFolder(dir) {
387
+ return await stat(dir).then(() => true, () => false) ? readMetadataDir(dir) : /* @__PURE__ */ new Map();
388
+ }
389
+ const schemaName = z.string().min(1).max(63);
390
+ const introspectTool = defineTool({
391
+ name: "introspect",
392
+ 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.",
393
+ input: z.strictObject({
394
+ 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." }),
395
+ project: z.strictObject({
396
+ name: z.string().min(1).optional(),
397
+ attributeCase: z.enum(ATTRIBUTE_CASES).optional(),
398
+ database: z.strictObject({ provider: z.enum(DATABASE_PROVIDERS).optional() }).optional()
399
+ }).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." })
400
+ }),
401
+ files: "write",
402
+ database: "read",
403
+ destructive: false,
404
+ async run({ dir, database }, input) {
405
+ const existing = await readFolder(dir);
406
+ const provider = new Set(SUPABASE_SCHEMAS);
407
+ const foreign = (input.schemas ?? []).filter((s) => provider.has(s));
408
+ if (foreign.length > 0) throw new UsageError(`Provider schemas are not introspected: ${foreign.join(", ")}. Nothing changed.`);
409
+ if ((input.schemas ?? []).includes(PLATFORM_SCHEMA)) throw new UsageError(`Schema ${PLATFORM_SCHEMA} belongs to the platform and is not introspected. Nothing changed.`);
410
+ let project;
411
+ let scope;
412
+ if (existing.has(PROJECT_FILE)) {
413
+ const compiled = await compile(existing);
414
+ if (compiled.model === void 0) return {
415
+ ok: false,
416
+ changes: [],
417
+ diagnostics: compiled.diagnostics
418
+ };
419
+ const own = compiled.model.project;
420
+ project = {
421
+ name: input.project?.name ?? own.name,
422
+ defaultSchema: own.defaultSchema,
423
+ attributeCase: input.project?.attributeCase ?? own.naming.attributeCase,
424
+ databaseProvider: own.database.provider
425
+ };
426
+ const modelScope = (await engineScope(compiled.model)).scope;
427
+ scope = {
428
+ ...modelScope,
429
+ schemas: [.../* @__PURE__ */ new Set([...modelScope.schemas, ...input.schemas ?? []])].filter((schema) => schema !== PLATFORM_SCHEMA).sort()
430
+ };
431
+ } else {
432
+ if (input.schemas === void 0) throw new UsageError(`${dir} has no ${PROJECT_FILE}, so there is no scope to read: pass schemas, e.g. {"schemas": ["public"]}. Nothing changed.`);
433
+ project = {
434
+ name: input.project?.name ?? "App",
435
+ defaultSchema: input.schemas[0],
436
+ attributeCase: input.project?.attributeCase ?? "camelCase",
437
+ databaseProvider: input.project?.database?.provider ?? "supabase"
438
+ };
439
+ scope = {
440
+ schemas: [...new Set(input.schemas)].sort(),
441
+ provider: project.databaseProvider
442
+ };
443
+ }
444
+ const engine = await loadEngine();
445
+ const read = await withDatabase(required(database), "introspect", (db) => engine.extract(db.target, scope));
446
+ if (!read.ok) return {
447
+ ok: false,
448
+ changes: [],
449
+ diagnostics: [read.diagnostic]
450
+ };
451
+ const extracted = read.value;
452
+ const extractDiagnostics = extracted.diagnostics.map(fromEngine);
453
+ const reversed = await reverseGenerate(extracted.model, {
454
+ project,
455
+ existing,
456
+ newId: () => crypto.randomUUID(),
457
+ schemaPath: schemaPathResolver(dir),
458
+ parse: await loadSqlParser()
459
+ });
460
+ const diagnostics = [...extractDiagnostics, ...reversed.diagnostics];
461
+ const ok = !hasErrors(diagnostics);
462
+ return {
463
+ ok,
464
+ changes: ok ? reversed.changes : [],
465
+ diagnostics,
466
+ data: { schemas: [...scope.schemas] }
467
+ };
468
+ }
469
+ });
470
+ /** Імена фільтра (`schema.table` чи `table`) у таблиці обох моделей. */
471
+ function resolveTables(filter, known) {
472
+ const tables = [];
473
+ const unknown = [];
474
+ for (const entry of filter) {
475
+ const dot = entry.indexOf(".");
476
+ const hits = known.filter((t) => dot < 0 ? t.name === entry : t.schema === entry.slice(0, dot) && t.name === entry.slice(dot + 1));
477
+ if (hits.length === 0) unknown.push(entry);
478
+ tables.push(...hits);
479
+ }
480
+ return {
481
+ tables,
482
+ unknown
483
+ };
484
+ }
485
+ /**
486
+ * Чи стосується ідентичність двигуна однієї з таблиць: сама таблиця, її
487
+ * колонки, обмеження, тригери, політики, типові значення, пов'язані з нею
488
+ * індекси, енами й послідовності (`related`) і обгортки (`comment:(…)`,
489
+ * `acl:(…)`) над будь-чим із цього. Індекс, енам і послідовність у Postgres
490
+ * адресуються схемою, а не таблицею, тож зв'язок з таблицею дають моделі.
491
+ */
492
+ function touchesTables(tables, related) {
493
+ const own = new Set(tables.map((t) => `table:${t.schema}.${t.name}`));
494
+ const prefixes = tables.map((t) => `${t.schema}.${t.name}.`);
495
+ const sub = /^(column|constraint|trigger|rule|policy|default):(.*)$/;
496
+ const touches = (id) => {
497
+ if (own.has(id) || related.has(id)) return true;
498
+ const m = sub.exec(id);
499
+ if (m !== null) return prefixes.some((p) => m[2].startsWith(p));
500
+ const wrapped = /^(?:comment|acl|securityLabel):\((.*)\)/.exec(id);
501
+ return wrapped !== null && touches(wrapped[1]);
502
+ };
503
+ return touches;
504
+ }
505
+ /**
506
+ * Ціль дії — те, що вона створює чи знищує. Лише в дій без них (GRANT,
507
+ * `ENABLE RLS`, `REPLICA IDENTITY`) ціль видно в `consumes`; інакше
508
+ * `consumes` — залежності, і FK чужої таблиці потрапив би у фільтр таблиці,
509
+ * на яку посилається.
510
+ */
511
+ function targetsOf(a) {
512
+ const own = [...a.produces, ...a.destroys];
513
+ return own.length > 0 ? own : a.consumes;
514
+ }
515
+ /** Частини `a.b.c` з лапками Postgres; `undefined` — не ім'я. */
516
+ function nameParts(text) {
517
+ const parts = [];
518
+ const part = /\s*(?:"((?:[^"]|"")+)"|([A-Za-z_][\w$]*))\s*(\.|$)/y;
519
+ while (part.lastIndex < text.length) {
520
+ const m = part.exec(text);
521
+ if (m === null) return void 0;
522
+ parts.push(m[1] === void 0 ? m[2].toLowerCase() : m[1].replace(/""/g, "\""));
523
+ if (m[3] === "") break;
524
+ }
525
+ return parts.length > 0 ? parts : void 0;
526
+ }
527
+ /**
528
+ * Енами й послідовності названих таблиць. Вони адресуються схемою, а не
529
+ * таблицею, тож зв'язок дають колонки (тип, identity, `nextval` у типовому
530
+ * значенні) і `OWNED BY` одиниць — з обох моделей: енам нової колонки є
531
+ * лише в бажаній, видаленої — лише в цільовій.
532
+ */
533
+ function dependentIds(keys, models) {
534
+ const enums = new Set(models.flatMap((m) => m.enumTypes.map((e) => `${e.schema}.${e.name}`)));
535
+ const ids = /* @__PURE__ */ new Set();
536
+ const sequence = (schema, parts) => {
537
+ if (parts === void 0 || parts.length > 2) return;
538
+ const key = (parts.length === 2 ? parts : [schema, parts[0]]).join(".");
539
+ ids.add(`sequence:${key}`).add(`sequenceOwnedBy:${key}`);
540
+ };
541
+ for (const table of models.flatMap((m) => m.tables)) {
542
+ if (!keys.has(`${table.schema}.${table.name}`)) continue;
543
+ for (const column of table.columns) {
544
+ const type = logicalTypeOf(column.type.replace(/(\[\])+$/, ""), enums);
545
+ if (type.form === "enum") ids.add(`type:${type.schema}.${type.name}`);
546
+ if (column.identity !== void 0) sequence(table.schema, [column.identity.sequence]);
547
+ const next = /nextval\('((?:[^']|'')+)'::regclass\)/.exec(column.default ?? "");
548
+ if (next !== null) sequence(table.schema, nameParts(next[1].replace(/''/g, "'")));
549
+ }
550
+ }
551
+ for (const unit of models.flatMap((m) => m.units)) {
552
+ if (unit.class !== "sequenceOwnedBy") continue;
553
+ const owner = /OWNED\s+BY\s+(.+?)\s*;?\s*$/i.exec(unit.sql);
554
+ const parts = owner === null ? void 0 : nameParts(owner[1]);
555
+ const table = parts === void 0 ? void 0 : parts.length === 3 ? `${parts[0]}.${parts[1]}` : parts.length === 2 ? `${unit.schema}.${parts[0]}` : void 0;
556
+ if (table !== void 0 && keys.has(table)) sequence(unit.schema, nameParts(unit.identity.slice(unit.identity.indexOf(":") + 1)));
557
+ }
558
+ return ids;
559
+ }
560
+ /**
561
+ * Чи належить ідентичність двигуна якійсь таблиці моделей, її індексу чи
562
+ * енаму: лише тоді фільтр може судити, що вона поза названими таблицями.
563
+ * Функція, в'юха, роль чи грант-одиниця таблиці не мають — їх не відкидаємо.
564
+ */
565
+ function attributable(models) {
566
+ const indexes = new Set(models.flatMap((m) => m.tables.flatMap((t) => t.indexes.map((i) => `index:${t.schema}.${i.name}`))));
567
+ const enums = new Set(models.flatMap((m) => m.enumTypes.map((e) => `type:${e.schema}.${e.name}`)));
568
+ const tableKinds = /^(?:table|column|constraint|trigger|rule|policy|default):/;
569
+ const check = (id) => {
570
+ const wrapped = /^(?:comment|acl|securityLabel):\((.*)\)/.exec(id);
571
+ if (wrapped !== null) return check(wrapped[1]);
572
+ return tableKinds.test(id) || indexes.has(id) || enums.has(id);
573
+ };
574
+ return check;
575
+ }
576
+ /**
577
+ * Звуження звірки до названих таблиць (§10.3 спеки П2: звірка документа з
578
+ * його ТЧ і регістрами, а не всієї бази) разом з їхніми енамами й
579
+ * послідовностями. Діагностика двигуна (без файлу) відкидається лише тоді,
580
+ * коли її об'єкт належить іншій таблиці; без атрибуції вона лишається, бо
581
+ * помилка, яку не віднести до таблиці, може стосуватися й названих.
582
+ */
583
+ function narrow(data, tables, models) {
584
+ const keys = new Set(tables.map((t) => `${t.schema}.${t.name}`));
585
+ 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}`))));
586
+ const dependent = dependentIds(keys, models);
587
+ const owned = attributable(models);
588
+ const touches = touchesTables(tables, /* @__PURE__ */ new Set([...indexes, ...dependent]));
589
+ const tablePaths = [...keys].map((k) => `tables.${k}`);
590
+ const enumPaths = new Set([...dependent].filter((id) => id.startsWith("type:")).map((id) => `enumTypes.${id.slice(5)}`));
591
+ return {
592
+ plan: data.plan.filter((a) => targetsOf(a).some(touches)),
593
+ 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))),
594
+ diagnostics: data.diagnostics.filter((d) => {
595
+ const object = d.params?.object;
596
+ return d.file !== "" || typeof object !== "string" || !owned(object) || touches(object);
597
+ })
598
+ };
599
+ }
600
+ const diffTool = defineTool({
601
+ name: "diff",
602
+ 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.",
603
+ input: z.strictObject({ tables: z.array(z.string().min(1)).min(1).optional().meta({ description: "Tables to compare: `schema.table` or `table`." }) }),
604
+ files: "read",
605
+ database: "read",
606
+ destructive: false,
607
+ async run({ dir, database }, input) {
608
+ const compiled = await compile(await readMetadataDir(dir));
609
+ const model = compiled.model;
610
+ if (model === void 0) return {
611
+ ok: false,
612
+ changes: [],
613
+ diagnostics: compiled.diagnostics
614
+ };
615
+ const desired = await desiredForApply(model);
616
+ const engine = await loadEngine();
617
+ const { createApplyDatabase } = await import("./schema-engine-DAsJEc8K.js");
618
+ const compared = await withDatabase(required(database), "diff", async (db) => {
619
+ const membership = await checkOwnerMembership(createApplyDatabase({ readOnly: true }), db.target, desired.scope, "engine.owner-not-member");
620
+ if (membership.refusal !== void 0) return { refusal: membership.refusal };
621
+ return { comparison: await compareWithDesired(engine, {
622
+ target: db.target,
623
+ ...db.shadowBase ? { shadowBase: db.shadowBase } : {}
624
+ }, desired.sql, desired.scope, desired.diagnostics) };
625
+ });
626
+ if (!compared.ok) return {
627
+ ok: false,
628
+ changes: [],
629
+ diagnostics: [...compiled.diagnostics, compared.diagnostic]
630
+ };
631
+ if (compared.value.refusal !== void 0) return {
632
+ ok: false,
633
+ changes: [],
634
+ diagnostics: [...compiled.diagnostics, fromEngine(compared.value.refusal)]
635
+ };
636
+ const comparison = compared.value.comparison;
637
+ const diagnostics = [...compiled.diagnostics, ...comparison.diagnostics.map(fromEngine)];
638
+ if (comparison.status === "shadow-failed") return {
639
+ ok: false,
640
+ changes: [],
641
+ diagnostics
642
+ };
643
+ const state = applyStateOf(comparison.target, comparison.plan, model);
644
+ const ownedAction = (a) => {
645
+ const targets = targetsOf(a).filter((id) => !id.startsWith("role:"));
646
+ return targets.length > 0 && targets.every(state.owns);
647
+ };
648
+ let data = state.state === "absent" ? {
649
+ plan: comparison.plan.actions.filter((a) => !ownedAction(a)),
650
+ differences: comparison.differences.filter((d) => !state.ownsPath(d.path)),
651
+ diagnostics
652
+ } : {
653
+ plan: comparison.plan.actions,
654
+ differences: comparison.differences,
655
+ diagnostics
656
+ };
657
+ if (input.tables !== void 0) {
658
+ const models = [comparison.target.model, comparison.desired.model];
659
+ const { tables, unknown } = resolveTables(input.tables, models.flatMap((m) => m.tables));
660
+ 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.`);
661
+ data = narrow(data, tables, models);
662
+ }
663
+ const ok = !hasErrors(data.diagnostics);
664
+ return {
665
+ ok,
666
+ changes: [],
667
+ diagnostics: data.diagnostics,
668
+ data: {
669
+ ...data,
670
+ applyState: state.state,
671
+ empty: ok && data.plan.length === 0 && data.differences.length === 0
672
+ }
673
+ };
674
+ }
675
+ });
676
+ //#endregion
677
+ //#region src/tools/apply-tools.ts
678
+ /**
679
+ * Пул лише на виклик: інструменти без застосування не тягнуть `pg`, як і
680
+ * двигун у `loadEngine`.
681
+ */
682
+ async function applyDatabase(o) {
683
+ const { createApplyDatabase } = await import("./schema-engine-DAsJEc8K.js");
684
+ return createApplyDatabase(o);
685
+ }
686
+ const refusedWith = (diagnostics) => ({
687
+ ok: false,
688
+ changes: [],
689
+ diagnostics
690
+ });
691
+ function planPromotion(section, model) {
692
+ const { record } = section;
693
+ const object = model.objects.find((o) => o.id === record.objectId);
694
+ return {
695
+ objectId: record.objectId,
696
+ kind: record.kind,
697
+ name: object?.name ?? record.objectId,
698
+ recordHash: section.recordHash,
699
+ tables: record.tables.map(({ schema, from, to }) => ({
700
+ schema,
701
+ from,
702
+ to
703
+ })),
704
+ columns: section.columns,
705
+ canonicalNames: section.canonicalNames,
706
+ permissionItems: section.permissionItems,
707
+ data: section.data
708
+ };
709
+ }
710
+ function planData(file, artifact, model, expectedBlindFunctions) {
711
+ const conversions = new Map((artifact.promotion?.conversions ?? []).map((c) => [c.step, c.class]));
712
+ return {
713
+ file,
714
+ planHash: artifact.planHash,
715
+ fromHash: artifact.fromHash,
716
+ toHash: artifact.toHash,
717
+ drift: artifact.drift,
718
+ promotion: artifact.promotion === null ? null : planPromotion(artifact.promotion, model),
719
+ steps: artifact.steps.map(({ id, origin, class: cls, lockClass, sql }) => {
720
+ const conversion = conversions.get(id);
721
+ return {
722
+ id,
723
+ origin,
724
+ class: cls,
725
+ lockClass,
726
+ sql,
727
+ ...conversion === void 0 ? {} : { conversion }
728
+ };
729
+ }),
730
+ locks: artifact.locks,
731
+ implicitLocks: artifact.implicitLocks,
732
+ requiredPermissions: artifact.requiredPermissions,
733
+ environment: {
734
+ role: artifact.role,
735
+ defaultPrivileges: artifact.environment.defaultPrivileges
736
+ },
737
+ plpgsqlCheck: artifact.plpgsqlCheck,
738
+ expectedBlindFunctions
739
+ };
740
+ }
741
+ /** Суфікс файлу запису промоції в `plans/` (`promotionFileName`). */
742
+ const RECORD_SUFFIX = promotionFileName("");
743
+ /**
744
+ * Записи промоції з `plans/` кореня (рішення 1 плану П3-2a), строго: файл, що
745
+ * не розбирається схемою чи названий не за своїм `objectId`, — відмова плану
746
+ * `plan.promotion-record-invalid`, а не пропуск. Пропущений запис перетворив
747
+ * би промоцію на «запису немає», а вгаданий — на чужий намір. Порядок — за
748
+ * іменем файлу: план детермінований незалежно від файлової системи.
749
+ */
750
+ async function readPromotionRecords(root) {
751
+ let names;
752
+ try {
753
+ names = await readdir(join(root, PLANS_DIR));
754
+ } catch (error) {
755
+ if (error.code === "ENOENT") return {
756
+ ok: true,
757
+ records: []
758
+ };
759
+ throw error;
760
+ }
761
+ const records = [];
762
+ for (const name of names.filter((n) => n.endsWith(RECORD_SUFFIX)).sort()) {
763
+ const file = `${PLANS_DIR}/${name}`;
764
+ const invalid = (detail) => ({
765
+ ok: false,
766
+ diagnostic: diagnostic("plan.promotion-record-invalid", "", "", {
767
+ file,
768
+ detail
769
+ })
770
+ });
771
+ let text;
772
+ try {
773
+ text = await readFile(join(root, file), "utf8");
774
+ } catch (error) {
775
+ const code = error.code;
776
+ if (code === void 0) throw error;
777
+ return invalid(`the file could not be read (${code})`);
778
+ }
779
+ let json;
780
+ try {
781
+ json = JSON.parse(text);
782
+ } catch (error) {
783
+ if (error instanceof SyntaxError) return invalid(error.message);
784
+ throw error;
785
+ }
786
+ const parsed = promotionRecordSchema.safeParse(json);
787
+ if (!parsed.success) return invalid(parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; "));
788
+ const record = parsed.data;
789
+ if (promotionFileName(record.objectId) !== name) return invalid(`the record is for object ${record.objectId}, so its file is ${PLANS_DIR}/${promotionFileName(record.objectId)}`);
790
+ records.push({
791
+ record,
792
+ file
793
+ });
794
+ }
795
+ return {
796
+ ok: true,
797
+ records
798
+ };
799
+ }
800
+ const planTool = defineTool({
801
+ name: "plan",
802
+ 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.",
803
+ input: z.strictObject({}),
804
+ files: "artifact",
805
+ database: "read",
806
+ destructive: false,
807
+ async run({ dir, root, database }) {
808
+ const compiled = await compile(await readMetadataDir(dir));
809
+ const model = compiled.model;
810
+ if (model === void 0) return refusedWith(compiled.diagnostics);
811
+ const promotions = await readPromotionRecords(root);
812
+ if (!promotions.ok) return refusedWith([...compiled.diagnostics, promotions.diagnostic]);
813
+ const engine = await loadEngine();
814
+ const dbs = {
815
+ reader: await applyDatabase({ readOnly: true }),
816
+ scratch: await applyDatabase({ readOnly: false })
817
+ };
818
+ const built = await withDatabase(required(database), "plan", (db) => buildPlan(engine, dbs, model, {
819
+ target: db.target,
820
+ ...db.shadowBase ? { shadowBase: db.shadowBase } : {}
821
+ }, promotions.records));
822
+ if (!built.ok) return refusedWith([...compiled.diagnostics, built.diagnostic]);
823
+ const outcome = built.value;
824
+ const diagnostics = [...compiled.diagnostics, ...outcome.diagnostics.map(fromEngine)];
825
+ switch (outcome.status) {
826
+ case "refused": return refusedWith(diagnostics);
827
+ case "unchanged": return {
828
+ ok: !hasErrors(diagnostics),
829
+ changes: [],
830
+ diagnostics,
831
+ artifacts: []
832
+ };
833
+ case "planned": {
834
+ const { artifact } = outcome;
835
+ const file = `${PLANS_DIR}/${planFileName(artifact.fromHash, artifact.toHash)}`;
836
+ return {
837
+ ok: !hasErrors(diagnostics),
838
+ changes: [],
839
+ diagnostics,
840
+ artifacts: [{
841
+ path: file,
842
+ content: serializePlan(artifact)
843
+ }],
844
+ data: planData(file, artifact, model, outcome.expectedBlindFunctions)
845
+ };
846
+ }
847
+ }
848
+ }
849
+ });
850
+ const engineLabel = (e) => `${e.name} ${e.version}`;
851
+ /** Перші 12 hex-символів, як у імені файлу плану. */
852
+ const short$1 = (hash) => hash.slice(0, 12);
853
+ /** Читає файл плану з `plans/` кореня; поза ним — помилка використання. */
854
+ async function readPlanFile(root, plan) {
855
+ const path = resolve(root, plan);
856
+ 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.`);
857
+ try {
858
+ return await readFile(path, "utf8");
859
+ } catch (error) {
860
+ const code = error.code;
861
+ if (code === "ENOENT" || code === "EISDIR") throw new UsageError(`Plan file not found: ${plan}. Nothing changed.`);
862
+ throw error;
863
+ }
864
+ }
865
+ /**
866
+ * Текст звіту репетиції з `plans/`; файлу немає — `undefined`, і раннер
867
+ * відмовить `apply.rehearsal-required`. Тека на місці звіту — те саме, що
868
+ * його немає, як у `readPlanFile`: звіту там нема, а сирий EISDIR людині
869
+ * нічого не скаже.
870
+ */
871
+ async function readReport(root, file) {
872
+ try {
873
+ return await readFile(join(root, file), "utf8");
874
+ } catch (error) {
875
+ const code = error.code;
876
+ if (code === "ENOENT" || code === "EISDIR") return void 0;
877
+ throw error;
878
+ }
879
+ }
880
+ /**
881
+ * Версії, з якими план побудовано й доведено, мусять бути поточними: інакше
882
+ * кроки чи відбитки значать інше (рішення 9 плану П3-1). Формат файлу звіряє
883
+ * вже `parsePlan`.
884
+ */
885
+ function versionMismatches(artifact, engine) {
886
+ return [
887
+ [
888
+ "fingerprintVersion",
889
+ artifact.fingerprintVersion,
890
+ FINGERPRINT_VERSION
891
+ ],
892
+ [
893
+ "platformVersion",
894
+ artifact.platformVersion,
895
+ PLATFORM_VERSION
896
+ ],
897
+ [
898
+ "engine",
899
+ engineLabel(artifact.engine),
900
+ engineLabel(engine)
901
+ ]
902
+ ].filter(([, plan, current]) => plan !== current).map(([field, plan, current]) => diagnostic("apply.plan-versions", "", "", {
903
+ field,
904
+ plan,
905
+ current
906
+ }));
907
+ }
908
+ const timeoutMs = z.number().int().positive();
909
+ const applyTool = defineTool({
910
+ name: "apply",
911
+ 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:, remove: and repair: items and a valid report from a rehearsal on a copy of the target with data.",
912
+ input: z.strictObject({
913
+ plan: z.string().min(1).meta({ description: "Plan file from `plan`, relative to the project root: plans/….plan.json." }),
914
+ planHash: z.string().regex(/^[0-9a-f]{64}$/).meta({ description: "planHash of the reviewed plan." }),
915
+ 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>." }),
916
+ rehearse: z.boolean().optional(),
917
+ lockTimeoutMs: timeoutMs.optional(),
918
+ statementTimeoutMs: timeoutMs.optional()
919
+ }),
920
+ files: "artifact",
921
+ database: "write",
922
+ destructive: true,
923
+ async run({ dir, root, database }, input) {
924
+ const parsed = parsePlan(await readPlanFile(root, input.plan));
925
+ if (!parsed.ok && parsed.reason === "format") return refusedWith([fromEngine(parsed.diagnostic)]);
926
+ if (!parsed.ok) throw new UsageError(`${input.plan} is not a plan file: ${parsed.message}. Nothing changed.`);
927
+ const { artifact } = parsed;
928
+ if (!await verifyPlanHash(artifact) || artifact.planHash !== input.planHash) return refusedWith([diagnostic("apply.plan-hash", "", "", {
929
+ file: input.plan,
930
+ planHash: input.planHash
931
+ })]);
932
+ const engine = await loadEngine();
933
+ const versions = versionMismatches(artifact, engine.identity);
934
+ if (versions.length > 0) return refusedWith(versions);
935
+ const compiled = await compile(await readMetadataDir(dir));
936
+ const model = compiled.model;
937
+ if (model === void 0) return refusedWith(compiled.diagnostics);
938
+ if (model.hash !== artifact.toHash) return refusedWith([diagnostic("apply.plan-stale", "", "", {
939
+ plan: short$1(artifact.toHash),
940
+ current: short$1(model.hash)
941
+ })]);
942
+ const allow = input.allow ?? [];
943
+ const permissions = checkPermissions({
944
+ steps: artifact.steps,
945
+ drift: artifact.drift,
946
+ promotion: artifact.promotion
947
+ }, allow);
948
+ if (permissions.length > 0) return refusedWith(permissions.map(fromEngine));
949
+ let report;
950
+ if (input.rehearse !== true && artifact.promotion !== null) {
951
+ const file = `${PLANS_DIR}/${rehearsalFileName(artifact.fromHash, artifact.toHash)}`;
952
+ const text = await readReport(root, file);
953
+ if (text !== void 0) {
954
+ const parsed = parseRehearsal(text);
955
+ if (!parsed.ok && parsed.reason === "format") return refusedWith([diagnostic("apply.rehearsal-stale", "", "", { reason: "format" })]);
956
+ if (!parsed.ok) throw new UsageError(`${file} is not a rehearsal report: ${parsed.message}. Nothing changed.`);
957
+ report = parsed.report;
958
+ }
959
+ }
960
+ const timeouts = {
961
+ ...input.lockTimeoutMs === void 0 ? {} : { lockTimeoutMs: input.lockTimeoutMs },
962
+ ...input.statementTimeoutMs === void 0 ? {} : { statementTimeoutMs: input.statementTimeoutMs }
963
+ };
964
+ const writer = await applyDatabase({ readOnly: false });
965
+ const base = {
966
+ planHash: artifact.planHash,
967
+ allow,
968
+ snapshot: canonicalSnapshot(model),
969
+ timeouts
970
+ };
971
+ const executed = await withDatabase(required(database), "apply", async (db) => {
972
+ if (input.rehearse !== true) return { outcome: await executePlan(writer, db.target, artifact, {
973
+ ...base,
974
+ mode: "apply",
975
+ ...report === void 0 ? {} : { report }
976
+ }) };
977
+ const desired = await desiredForApply(model);
978
+ const shadow = await engine.withDesiredShadow({
979
+ target: db.target,
980
+ ...db.shadowBase ? { shadowBase: db.shadowBase } : {}
981
+ }, desired.sql, artifact.scope, (shadowDb) => engine.extract(shadowDb, artifact.scope));
982
+ if (shadow.status === "shadow-failed") return { shadowFailed: shadow.diagnostics };
983
+ return { outcome: await executePlan(writer, db.target, artifact, {
984
+ ...base,
985
+ mode: "rehearse",
986
+ rehearsal: {
987
+ engine,
988
+ desired: shadow.value.catalog
989
+ }
990
+ }) };
991
+ });
992
+ if (!executed.ok) return refusedWith([executed.diagnostic]);
993
+ if ("shadowFailed" in executed.value) return refusedWith(executed.value.shadowFailed.map(fromEngine));
994
+ const outcome = executed.value.outcome;
995
+ const diagnostics = outcome.diagnostics.map(fromEngine);
996
+ const ok = !hasErrors(diagnostics);
997
+ switch (outcome.status) {
998
+ case "committed": return {
999
+ ok,
1000
+ changes: [],
1001
+ diagnostics,
1002
+ data: {
1003
+ status: outcome.status,
1004
+ attempts: outcome.attempts,
1005
+ report: null
1006
+ }
1007
+ };
1008
+ case "rolledBack": {
1009
+ const report = `${PLANS_DIR}/${rehearsalFileName(artifact.fromHash, artifact.toHash)}`;
1010
+ return {
1011
+ ok,
1012
+ changes: [],
1013
+ diagnostics,
1014
+ data: {
1015
+ status: outcome.status,
1016
+ attempts: outcome.attempts,
1017
+ report: ok ? report : null
1018
+ },
1019
+ artifacts: ok ? [{
1020
+ path: report,
1021
+ content: serializeRehearsal(rehearsalReport(artifact.planHash, outcome.evidence))
1022
+ }] : []
1023
+ };
1024
+ }
1025
+ case "refused":
1026
+ case "failed": return refusedWith(diagnostics);
1027
+ }
1028
+ }
1029
+ });
1030
+ //#endregion
1031
+ //#region src/tools/mutations.ts
1032
+ const completion = (dir) => ({
1033
+ schemaPath: schemaPathResolver(dir),
1034
+ newId: () => crypto.randomUUID()
1035
+ });
1036
+ /**
1037
+ * Тека читається заново на кожен виклик (стан — диск, не пам'ять процесу), а
1038
+ * в T1 іде лише валідований вхід операції. Запис і dry-run вирішує `invoke`.
1039
+ */
1040
+ async function apply(dir, operation) {
1041
+ const result = await operation(await readMetadataDir(dir));
1042
+ return {
1043
+ ok: result.ok,
1044
+ changes: result.changes,
1045
+ diagnostics: result.diagnostics
1046
+ };
1047
+ }
1048
+ /**
1049
+ * Те саме для `promote`: запис промоції їде в `data` і артефактом у
1050
+ * `plans/<objectId>.promotion.json` — план бази читає його звідти (рішення 1
1051
+ * плану П3-2a), бо мапінг у `metadata/` не лишається.
1052
+ */
1053
+ async function applyPromotion(dir, operation) {
1054
+ const result = await operation(await readMetadataDir(dir));
1055
+ const { record } = result;
1056
+ return {
1057
+ ok: result.ok,
1058
+ changes: result.changes,
1059
+ diagnostics: result.diagnostics,
1060
+ ...record === void 0 ? {} : {
1061
+ data: record,
1062
+ artifacts: [{
1063
+ path: `${PLANS_DIR}/${promotionFileName(record.objectId)}`,
1064
+ content: serializeCanonical(record)
1065
+ }]
1066
+ }
1067
+ };
1068
+ }
1069
+ const createTool = defineTool({
1070
+ name: "create",
1071
+ description: "Create a metadata object; ids and physical names are assigned. Writes only when the result compiles without errors.",
1072
+ input: createObjectInput,
1073
+ files: "write",
1074
+ database: "none",
1075
+ destructive: false,
1076
+ run: ({ dir }, input) => apply(dir, (files) => createObject(files, input, completion(dir)))
1077
+ });
1078
+ const addTool = defineTool({
1079
+ name: "add",
1080
+ 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.",
1081
+ input: addElementInput,
1082
+ files: "write",
1083
+ database: "none",
1084
+ destructive: false,
1085
+ run: ({ dir }, input) => apply(dir, (files) => addElement(files, input, completion(dir)))
1086
+ });
1087
+ const renameTool = defineTool({
1088
+ name: "rename",
1089
+ 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.",
1090
+ input: renameInput,
1091
+ files: "write",
1092
+ database: "none",
1093
+ destructive: false,
1094
+ run: ({ dir }, input) => apply(dir, (files) => renameElement(files, input))
1095
+ });
1096
+ const deleteTool = defineTool({
1097
+ name: "delete",
1098
+ description: "Delete an object or a nested element. Refused while anything references it.",
1099
+ input: deleteInput,
1100
+ files: "write",
1101
+ database: "none",
1102
+ destructive: true,
1103
+ run: ({ dir }, input) => apply(dir, (files) => deleteElement(files, input))
1104
+ });
1105
+ const promoteTool = defineTool({
1106
+ name: "promote",
1107
+ 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.",
1108
+ input: promoteInput,
1109
+ files: "write",
1110
+ database: "none",
1111
+ destructive: false,
1112
+ run: ({ dir }, input) => applyPromotion(dir, (files) => promoteObject(files, input, completion(dir)))
1113
+ });
1114
+ //#endregion
1115
+ //#region src/tools/catalog.ts
1116
+ /** Єдиний каталог інструментів: CLI, MCP і студія — лише його адаптери. */
1117
+ const TOOLS = [
1118
+ defineTool({
1119
+ name: "compile",
1120
+ description: "Compile the metadata directory and return diagnostics. Reads the disk on every call; writes nothing.",
1121
+ input: z.strictObject({}),
1122
+ files: "read",
1123
+ database: "none",
1124
+ destructive: false,
1125
+ async run({ dir, baseline }) {
1126
+ const result = await compile(await readMetadataDir(dir), baseline === void 0 ? void 0 : { baseline });
1127
+ return {
1128
+ ok: result.ok,
1129
+ changes: [],
1130
+ diagnostics: result.diagnostics,
1131
+ data: { model: result.model }
1132
+ };
1133
+ }
1134
+ }),
1135
+ defineTool({
1136
+ name: "explain",
1137
+ description: "Explain one object: its tables, columns, keys and movement queries. Needs a metadata directory that compiles without errors.",
1138
+ input: z.strictObject({
1139
+ kind: metadataKindSchema,
1140
+ name: objectNameSchema
1141
+ }),
1142
+ files: "read",
1143
+ database: "none",
1144
+ destructive: false,
1145
+ async run({ dir }, { kind, name }) {
1146
+ const result = await compile(await readMetadataDir(dir));
1147
+ if (result.model === void 0) return {
1148
+ ok: false,
1149
+ changes: [],
1150
+ diagnostics: result.diagnostics
1151
+ };
1152
+ const explanation = explainObject(result.model, {
1153
+ kind,
1154
+ name
1155
+ });
1156
+ if (explanation === void 0) return {
1157
+ ok: false,
1158
+ changes: [],
1159
+ diagnostics: result.diagnostics,
1160
+ refusal: `Object not found: ${kind} ${name}`
1161
+ };
1162
+ return {
1163
+ ok: true,
1164
+ changes: [],
1165
+ diagnostics: result.diagnostics,
1166
+ data: explanation
1167
+ };
1168
+ }
1169
+ }),
1170
+ defineTool({
1171
+ name: "fix",
1172
+ description: "Assign missing ids and physical names, set $schema and canonical form. Writes only when the result compiles without errors.",
1173
+ input: z.strictObject({}),
1174
+ files: "write",
1175
+ database: "none",
1176
+ destructive: false,
1177
+ async run({ dir }) {
1178
+ const result = await fixFiles(await readMetadataDir(dir), {
1179
+ schemaPath: schemaPathResolver(dir),
1180
+ newId: () => crypto.randomUUID()
1181
+ });
1182
+ return {
1183
+ ok: result.ok,
1184
+ changes: result.changes,
1185
+ diagnostics: result.diagnostics
1186
+ };
1187
+ }
1188
+ }),
1189
+ createTool,
1190
+ addTool,
1191
+ renameTool,
1192
+ deleteTool,
1193
+ promoteTool,
1194
+ introspectTool,
1195
+ diffTool,
1196
+ planTool,
1197
+ applyTool
1198
+ ];
1199
+ function toolByName(name) {
1200
+ return TOOLS.find((t) => t.name === name);
1201
+ }
1202
+ //#endregion
1203
+ //#region src/tools/hints.ts
1204
+ const READ_ONLY_FLAG = "--read-only";
1205
+ const ALLOW_DATABASE_WRITE_FLAG = "--allow-database-write";
1206
+ /** Типова змінна середовища з рядком підключення; ім'я фіксується при запуску. */
1207
+ const DEFAULT_DATABASE_URL_ENV = "SIMETRA_DATABASE_URL";
1208
+ /**
1209
+ * Єдине джерело тексту «як увімкнути запис»: його бачить і клієнт MCP в
1210
+ * `instructions`, і агент у відмові на запис у режимі лише читання.
1211
+ * `launchArgs` — справжній argv запуску сервера без node і скрипта, тобто
1212
+ * лише ХВІСТ `args` у конфігу клієнта: лаунчер (`pnpm exec simetra …`,
1213
+ * `npx …`, обгортка) додає свої аргументи попереду. Тому підказка каже
1214
+ * «прибери прапорець» і показує хвіст до й після, а не видає його за повний
1215
+ * `"args"` — буквальна заміна зламала б конфіг.
1216
+ */
1217
+ function readOnlyHint(launchArgs = [
1218
+ "simetra",
1219
+ "mcp",
1220
+ READ_ONLY_FLAG
1221
+ ]) {
1222
+ const before = launchArgs.includes("--read-only") ? launchArgs : [...launchArgs, READ_ONLY_FLAG];
1223
+ const after = before.filter((a) => a !== READ_ONLY_FLAG);
1224
+ return [
1225
+ `This server runs with ${READ_ONLY_FLAG}: tools that write are disabled.`,
1226
+ `To enable them, remove ${READ_ONLY_FLAG} from this server's args in the MCP client config and restart it:`,
1227
+ `args ending in ${JSON.stringify(before)} become ${JSON.stringify(after)}.`
1228
+ ].join(" ");
1229
+ }
1230
+ /**
1231
+ * Підказка відмови `apply` без прапорця запису в базу і її ж речення в
1232
+ * `instructions`. Як і `readOnlyHint`, показує лише хвіст `args`: прапорець
1233
+ * додається, а не замінює конфіг. Вмикає його людина, а не агент: запис у
1234
+ * базу поза git, тож рішення — при запуску сервера.
1235
+ */
1236
+ function databaseWriteHint(launchArgs = ["simetra", "mcp"], o = {}) {
1237
+ const before = launchArgs.filter((a) => a !== ALLOW_DATABASE_WRITE_FLAG);
1238
+ const after = [...before, ALLOW_DATABASE_WRITE_FLAG];
1239
+ return [
1240
+ `This server runs without ${ALLOW_DATABASE_WRITE_FLAG}: apply cannot write to the database.`,
1241
+ `Only the owner may enable it: add ${ALLOW_DATABASE_WRITE_FLAG} to this server's args in the MCP client config and restart it:`,
1242
+ `args ending in ${JSON.stringify(before)} become ${JSON.stringify(after)}.`,
1243
+ ...o.refusal === false ? [] : ["Nothing changed."]
1244
+ ].join(" ");
1245
+ }
1246
+ /**
1247
+ * Називає лише змінну, ніколи її значення: рядок підключення несе
1248
+ * користувача й пароль, а відмова йде агентові й у журнали клієнта.
1249
+ * Середовище команди задає сам викликач перед наступним запуском, а
1250
+ * середовище MCP-сервера фіксується при його старті — звідси дві поради.
1251
+ */
1252
+ function noDatabaseHint(envName, channel) {
1253
+ const how = channel === "cli" ? `Export the environment variable ${envName} with the connection string of the target database, or name another variable with --database-url-env.` : `Set the environment variable ${envName} to the connection string of the target database in this server's environment and restart the server.`;
1254
+ return [
1255
+ `This tool needs a database connection, and ${channel === "cli" ? "none is configured" : "the server has none"}.`,
1256
+ how,
1257
+ "Nothing changed."
1258
+ ].join(" ");
1259
+ }
1260
+ //#endregion
1261
+ //#region src/tools/queue.ts
1262
+ const tails = /* @__PURE__ */ new Map();
1263
+ /**
1264
+ * Черга викликів однієї теки метаданих. Адаптери (MCP-сервер, CLI) можуть
1265
+ * слати виклики паралельно, тож без черги дві мутації читали б той самий стан
1266
+ * і друга мовчки затирала б першу, а записана комбінація двох результатів не
1267
+ * проходила б компіляцію. Читальні інструменти стоять у тій самій черзі:
1268
+ * `writeChanges` пише файли по одному, і компіляція посеред запису побачила б
1269
+ * напівзаписане дерево. Ціна — послідовні компіляції; вони короткі, а
1270
+ * коректність відповіді важливіша за паралелізм. Ключ — розв'язаний шлях, щоб
1271
+ * `./metadata` і абсолютний шлях ділили одну чергу.
1272
+ */
1273
+ function queueFor(dir) {
1274
+ const key = resolve(dir);
1275
+ return (task) => {
1276
+ const run = (tails.get(key) ?? Promise.resolve()).then(task);
1277
+ const tail = run.catch(() => void 0);
1278
+ tails.set(key, tail);
1279
+ tail.then(() => {
1280
+ if (tails.get(key) === tail) tails.delete(key);
1281
+ });
1282
+ return run;
1283
+ };
1284
+ }
1285
+ //#endregion
1286
+ //#region src/tools/invoke.ts
1287
+ /**
1288
+ * Вичерпні switch по обох осях: нове значення осі не компілюється, доки не
1289
+ * вирішено його дозвіл. `--read-only` вимикає будь-який запис; запис у базу
1290
+ * ще й потребує рішення людини при запуску (`allowDatabaseWrite`), а власне
1291
+ * тертя (підтвердження з показаним планом) — ознака `destructive`.
1292
+ */
1293
+ function permits(tool, o) {
1294
+ const files = tool.files;
1295
+ const database = tool.database;
1296
+ let filesOk;
1297
+ switch (files) {
1298
+ case "read":
1299
+ filesOk = true;
1300
+ break;
1301
+ case "artifact":
1302
+ case "write": filesOk = !o.readOnly;
1303
+ }
1304
+ let databaseOk;
1305
+ switch (database) {
1306
+ case "none":
1307
+ case "read":
1308
+ databaseOk = true;
1309
+ break;
1310
+ case "write": databaseOk = !o.readOnly && o.allowDatabaseWrite;
1311
+ }
1312
+ return filesOk && databaseOk;
1313
+ }
1314
+ /**
1315
+ * Артефакт пишеться лише в `plans/` кореня проєкту (спека designer §3.2);
1316
+ * будь-який інший шлях — помилка інструмента, і перевіряється вона до
1317
+ * першого запису.
1318
+ */
1319
+ function checkArtifacts(root, artifacts) {
1320
+ const plans = resolve(root, PLANS_DIR) + sep;
1321
+ for (const a of artifacts) {
1322
+ if (a.content === null) throw new UsageError(`An artifact must never delete a file: ${a.path}`);
1323
+ 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}`);
1324
+ }
1325
+ }
1326
+ function refused(reason, message) {
1327
+ return {
1328
+ ok: false,
1329
+ written: false,
1330
+ changes: [],
1331
+ diagnostics: [],
1332
+ refusal: {
1333
+ reason,
1334
+ message
1335
+ }
1336
+ };
1337
+ }
1338
+ /**
1339
+ * Єдине місце рішень про розбір входу, дозволи, підтвердження й запис:
1340
+ * адаптери (CLI, MCP) лише переказують результат. Порядок має значення —
1341
+ * відмова на кожному кроці гарантує, що далі диск не чіпають.
1342
+ */
1343
+ async function invoke(tool, input, o) {
1344
+ const parsed = tool.input.safeParse(input);
1345
+ if (!parsed.success) return refused("invalid-input", parsed.error.issues.map((i) => i.path.length === 0 ? i.message : `${i.path.join(".")}: ${i.message}`).join("; "));
1346
+ 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.`);
1347
+ if (!permits(tool, o)) return permits(tool, {
1348
+ ...o,
1349
+ allowDatabaseWrite: true
1350
+ }) ? refused("database-write-disabled", databaseWriteHint(o.launchArgs)) : refused("read-only", readOnlyHint(o.launchArgs));
1351
+ if (tool.database !== "none" && o.database === void 0) return refused("no-database", noDatabaseHint(o.databaseEnv ?? "SIMETRA_DATABASE_URL", o.channel));
1352
+ if (tool.destructive && !o.dryRun && !o.confirmed) return refused("unconfirmed", `${tool.name} is destructive and needs confirmation. Nothing changed.`);
1353
+ const root = dirname(resolve(o.dir));
1354
+ return queueFor(o.dir)(async () => {
1355
+ try {
1356
+ const outcome = await tool.run({
1357
+ dir: o.dir,
1358
+ root,
1359
+ ...tool.database === "none" ? {} : { database: o.database },
1360
+ ...o.baseline === void 0 ? {} : { baseline: o.baseline }
1361
+ }, parsed.data);
1362
+ const artifacts = outcome.artifacts ?? [];
1363
+ checkArtifacts(root, artifacts);
1364
+ let write = false;
1365
+ let writeArtifacts = false;
1366
+ switch (tool.files) {
1367
+ case "read": break;
1368
+ case "artifact":
1369
+ if (outcome.changes.length > 0) throw new Error(`${tool.name} is an artifact tool and must not change the metadata directory`);
1370
+ writeArtifacts = outcome.ok && artifacts.length > 0;
1371
+ break;
1372
+ case "write":
1373
+ write = outcome.ok && !o.dryRun && outcome.changes.length > 0;
1374
+ writeArtifacts = outcome.ok && !o.dryRun && artifacts.length > 0;
1375
+ }
1376
+ if (writeArtifacts) await writeChanges(root, artifacts);
1377
+ if (write) await writeChanges(o.dir, outcome.changes);
1378
+ return {
1379
+ ok: outcome.ok,
1380
+ written: write || writeArtifacts,
1381
+ changes: outcome.changes.map((c) => ({
1382
+ path: c.path,
1383
+ deleted: c.content === null
1384
+ })),
1385
+ diagnostics: outcome.diagnostics,
1386
+ ...outcome.data === void 0 ? {} : { data: outcome.data },
1387
+ ...outcome.artifacts === void 0 ? {} : { artifacts: outcome.artifacts.map((a) => a.path) },
1388
+ ...outcome.refusal === void 0 ? {} : { refusal: {
1389
+ reason: "refused",
1390
+ message: outcome.refusal
1391
+ } }
1392
+ };
1393
+ } catch (error) {
1394
+ if (error instanceof UsageError) return refused("refused", error.message);
1395
+ throw error;
1396
+ }
1397
+ });
1398
+ }
1399
+ //#endregion
1400
+ //#region src/io/default-dir.ts
1401
+ /** Тека метаданих за замовчуванням — спільна для CLI і `simetra mcp`. */
1402
+ const DEFAULT_DIR = "./metadata";
1403
+ const trimSlash = (d) => d.replace(/(?<=.)[\\/]+$/, "");
1404
+ //#endregion
1405
+ //#region src/io/report.ts
1406
+ /** Діагностика з текстом потрібною мовою; саме її віддають обидва формати. */
1407
+ function localized(d, locale) {
1408
+ const { message, hint } = localize(d, locale);
1409
+ const rest = { ...d };
1410
+ delete rest.hint;
1411
+ return {
1412
+ ...rest,
1413
+ message,
1414
+ ...hint === void 0 ? {} : { hint }
1415
+ };
1416
+ }
1417
+ function formatDiagnostics(diagnostics, { dir, locale, format }) {
1418
+ const items = diagnostics.map((d) => localized(d, locale));
1419
+ if (format === "json") return JSON.stringify(items.map((d) => ({
1420
+ ...d,
1421
+ dir
1422
+ })), null, 2);
1423
+ const lines = [];
1424
+ for (const d of items) {
1425
+ lines.push(`${placeOf(d, dir)} ${d.severity} ${d.code} ${d.message}`);
1426
+ if (d.hint !== void 0) lines.push(` hint: ${d.hint}`);
1427
+ }
1428
+ const errors = items.filter((d) => d.severity === "error").length;
1429
+ lines.push(`${errors} error(s), ${items.length - errors} warning(s)`);
1430
+ return lines.join("\n");
1431
+ }
1432
+ /**
1433
+ * Місце діагностики в тексті. Позиція друкується лише тоді, коли вона є:
1434
+ * діагностика без файлу (вхід операції загалом) чи файлу, якого немає в
1435
+ * теці, отримала б фальшиве `:1:1`, а читач шукав би там неіснуючу причину.
1436
+ */
1437
+ function placeOf(d, dir) {
1438
+ if (d.file === "") return `${dir}:`;
1439
+ if (d.range === void 0) return `${dir}/${d.file}:`;
1440
+ const { line, character } = d.range.start;
1441
+ return `${dir}/${d.file}:${line + 1}:${character + 1}`;
1442
+ }
1443
+ /** Зведення звірки: дії плану, відмінності каталогу, діагностика. */
1444
+ function renderDiff(d, report) {
1445
+ const lines = [];
1446
+ if (d.plan.length > 0) {
1447
+ lines.push(`plan (${d.plan.length} action(s), database -> metadata):`);
1448
+ for (const a of d.plan) {
1449
+ const tags = [a.dataLoss ? "data loss" : void 0, a.rewriteRisk ? "rewrite" : void 0].filter((x) => x !== void 0);
1450
+ lines.push(` ${a.sql.trim()}${tags.length > 0 ? ` -- ${tags.join(", ")}` : ""}`);
1451
+ }
1452
+ }
1453
+ if (d.differences.length > 0) {
1454
+ lines.push(`differences (${d.differences.length}):`);
1455
+ for (const x of d.differences) lines.push(` ${x.kind} ${x.path}: ${x.detail}`);
1456
+ }
1457
+ if (d.applyState === "absent") lines.push("apply state: absent from the database; the first apply creates it");
1458
+ if (d.empty) lines.push("diff: the database matches the metadata");
1459
+ lines.push(report);
1460
+ return lines.join("\n");
1461
+ }
1462
+ const short = (hash) => hash === null ? "initial" : hash.slice(0, 12);
1463
+ /** Режим `plpgsql_check` плану словами виводу. */
1464
+ const PLPGSQL_CHECK_LABEL = {
1465
+ installed: "installed",
1466
+ transient: "transient (installed for the check, rolled back)",
1467
+ unavailable: "unavailable"
1468
+ };
1469
+ const qualified = (schema, name) => `${quoteIdent(schema)}.${quoteIdent(name)}`;
1470
+ /**
1471
+ * Блок «Promotion» (рішення 14 плану П3-2a): що стає чим і що людина
1472
+ * дозволяє. Таблиця, що лишає своє ім'я, рядка перейменування не дає:
1473
+ * `a -> a` читався б як зміна, якої немає.
1474
+ */
1475
+ function promotionLines(p, needs) {
1476
+ const lines = [`promotion: ${p.kind} ${p.name} (${p.objectId})`, ` record hash: ${p.recordHash}`];
1477
+ 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)}`);
1478
+ for (const c of p.columns) lines.push(` column ${qualified(c.table.schema, c.table.name)}: ${quoteIdent(c.from)} -> ${quoteIdent(c.to)}`);
1479
+ for (const c of p.canonicalNames) lines.push(` ${c.kind} ${qualified(c.table.schema, c.table.name)}: ${quoteIdent(c.from)} -> ${quoteIdent(c.to)}`);
1480
+ for (const t of p.data) {
1481
+ lines.push(` data steps ${qualified(t.after.schema, t.after.table)}:`);
1482
+ for (const c of t.columns) lines.push(` ${c.step} ${quoteIdent(c.column)} ← ${c.expression} (${c.kind})`);
1483
+ if (t.triggers.length > 0) lines.push(` triggers disabled during the write: ${t.triggers.map((x) => quoteIdent(x.name)).join(", ")}`);
1484
+ }
1485
+ for (const item of p.permissionItems) {
1486
+ lines.push(` ${item.token}${needs.has(item.token) ? ` (needs allow: ${item.token})` : ""}`);
1487
+ for (const s of item.summary) lines.push(` ${s}`);
1488
+ }
1489
+ return lines;
1490
+ }
1491
+ /**
1492
+ * Зведення плану для людини й агента: звідки й куди, `planHash` і файл,
1493
+ * дрейф — першим блоком, до кроків (рішення 16 плану П3-1): кроки читаються
1494
+ * вже знаючи, що ціль дрейфнула. Далі — промоція, бо кроки наміру й класи
1495
+ * конверсій читаються, знаючи, що стає чим (рішення 14 плану П3-2a). Повний
1496
+ * SQL — у файлі плану; тут перший рядок.
1497
+ */
1498
+ function renderPlan(d, report, o) {
1499
+ if (d === void 0) 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");
1500
+ const needs = new Set(d.requiredPermissions);
1501
+ const lines = [
1502
+ `plan ${short(d.fromHash)} -> ${short(d.toHash)}`,
1503
+ `${o.written ? "written" : "not written"} ${d.file}`,
1504
+ `planHash: ${d.planHash}`
1505
+ ];
1506
+ if (d.drift !== null) {
1507
+ lines.push(`drift (${d.drift.reason}): needs allow: drift`);
1508
+ if (d.drift.sections.length > 0) lines.push(` fingerprint sections: ${d.drift.sections.join(", ")}`);
1509
+ for (const path of d.drift.paths) lines.push(` ${path}`);
1510
+ }
1511
+ if (d.promotion !== null) lines.push(...promotionLines(d.promotion, needs));
1512
+ const stepLine = (s) => {
1513
+ const tags = [
1514
+ `lock ${s.lockClass}`,
1515
+ ...s.conversion === void 0 ? [] : [`conversion ${s.conversion}`],
1516
+ ...needs.has(s.id) ? [`needs allow: ${s.id}`] : []
1517
+ ];
1518
+ const first = s.sql.trim().split("\n")[0] ?? "";
1519
+ return ` ${s.id} ${s.origin} ${s.class} (${tags.join("; ")}) ${first}`;
1520
+ };
1521
+ const environment = d.steps.filter((s) => s.origin === "environment");
1522
+ const steps = d.steps.filter((s) => s.origin !== "environment");
1523
+ if (steps.length === 0) lines.push("steps: none");
1524
+ else {
1525
+ lines.push(`steps (${steps.length}):`);
1526
+ lines.push(...steps.map(stepLine));
1527
+ }
1528
+ if (environment.length > 0) {
1529
+ lines.push(`environment rights: the global default privileges of role ${quoteIdent(d.environment.role)}:`);
1530
+ lines.push(...environment.map(stepLine));
1531
+ }
1532
+ 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(", ")}`);
1533
+ 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`);
1534
+ lines.push(`plpgsql_check: ${PLPGSQL_CHECK_LABEL[d.plpgsqlCheck]}`);
1535
+ if (d.expectedBlindFunctions > 0) lines.push(`expected provider blind functions (preset): ${d.expectedBlindFunctions}`);
1536
+ lines.push(report);
1537
+ return lines.join("\n");
1538
+ }
1539
+ /**
1540
+ * Підсумок застосування; репетиція нагадує, що блокування були справжні.
1541
+ * Без даних заголовок судить за діагностикою: після обриву з невідомим
1542
+ * результатом «нічого не записано» було б неправдою, а повтор за нею міг би
1543
+ * застосувати план удруге.
1544
+ */
1545
+ function renderApply(d, diagnostics, report) {
1546
+ const unknown = diagnostics.find((x) => x.code === "apply.connection-lost" && x.params?.outcome === "unknown");
1547
+ 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");
1548
+ }
1549
+ //#endregion
1550
+ export { DEFAULT_DIR as a, DEFAULT_DATABASE_URL_ENV as c, TOOLS as d, toolByName as f, UsageError as g, databaseResource as h, renderPlan as i, databaseWriteHint as l, writeChanges as m, renderApply as n, trimSlash as o, isMetadataFile as p, renderDiff as r, invoke as s, formatDiagnostics as t, readOnlyHint as u };