@simetrajs/designer 0.1.0 → 0.3.0-next.1
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/README.md +39 -4
- package/dist/{command-CRUaUglx.js → command-CHk1P9Dp.js} +91 -108
- package/dist/default-dir-DerxTbci.js +158 -0
- package/dist/errors-D1P2kKbL.js +62 -0
- package/dist/init-jr0Xsrpp.js +832 -0
- package/dist/invoke-BwP_5iN6.js +2676 -0
- package/dist/main.js +6 -6
- package/dist/mcp-args-D63akJ97.js +56 -0
- package/dist/mcp-jLOz0W7f.js +219 -0
- package/dist/package-hA0J8AMK.js +4 -0
- package/dist/{schema-engine-DAsJEc8K.js → schema-engine-8rVHcVYO.js} +704 -195
- package/dist/{types-CSc8XWLd.js → types-CMcZhIci.js} +8 -3
- package/package.json +16 -12
- package/skills/simetra-adoption/SKILL.md +82 -3
- package/skills/simetra-metadata/SKILL.md +126 -136
- package/skills/simetra-metadata/references/agents-over-mcp.md +236 -0
- package/skills/simetra-metadata/references/attribute-load-and-size.md +57 -0
- package/skills/simetra-metadata/references/list-order-indexes.md +17 -0
- package/skills/simetra-metadata/references/object-modules.md +78 -0
- package/skills/simetra-metadata/references/people-and-rights.md +702 -9
- package/skills/simetra-metadata/references/plan-and-apply.md +81 -0
- package/skills/simetra-metadata/references/project-setup.md +28 -0
- package/skills/simetra-metadata/references/row-version-epoch.md +39 -0
- package/skills/simetra-metadata/references/search-fields.md +28 -0
- package/skills/simetra-metadata/references/sql-trust-boundary.md +225 -0
- package/dist/errors-D5pJLrjP.js +0 -36
- package/dist/mcp-CJDCleh-.js +0 -241
- package/dist/package-DDuGk6yE.js +0 -5
- package/dist/report-D2jBS_04.js +0 -1550
|
@@ -0,0 +1,2676 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { r as defineTool, t as PLANS_DIR } from "./types-CMcZhIci.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 { a as ShadowTemplateMissingError, i as ShadowServerMismatchError, n as ShadowCreateRefusedError, o as shadowDropOf, r as ShadowServerError, t as ShadowBaseUnsupportedError } from "./errors-D1P2kKbL.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, CENTRIFUGO_CHANNEL_MAX, CommandFailure, DATABASE_PROVIDERS, FUNCTIONS_FILE_SUFFIX, PLATFORM_LOGIN_ROLES, PLATFORM_ROLES, PLATFORM_SCHEMA, PROVIDER_API_ROLES, PROVIDER_IDENTITY_SOURCES, PROVIDER_SCHEMAS, SIGNAL_MERGE_THRESHOLD, SIGNAL_NOTIFY_CHANNEL, SIGNAL_OUTBOX, 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, checkOwnerAttributes, checkOwnerMembership, checkPermissions, checkPlatformRoles, compareWithDesired, copiesShadowFromTemplate, desiredForApply, engineScope, ensurePlatformRoles, ensurePostgresCluster, executePlan, folderReference, parsePlan, parseRehearsal, planFileName, platformRoleSet, postgresClusterSet, readShadowEnvironment, rehearsalFileName, rehearsalReport, reverseGenerate, runRightsMaintenance, serializePlan, serializeRehearsal, verifyPlanHash } from "simetra/schema";
|
|
9
|
+
import pg from "pg";
|
|
10
|
+
import { agentWriteRefusal, createAgentCore, createCommandRuntime, fromPgPool, readRoleOf, toJson } from "simetra/server";
|
|
11
|
+
import { ZodError, z } from "zod";
|
|
12
|
+
import { addElement, addElementInput, buildRuntimeCatalog, canonicalSnapshot, compile, createObject, createObjectInput, declareFunction, declareFunctionInput, deleteElement, deleteInput, diagnostic, explainFunction, explainObject, fixFiles, identityParts, isRepairError, loadSqlParser, localize, promoteInput, promoteObject, promotionFileName, promotionRecordSchema, readProjectFile, renameElement, renameInput, serializeCanonical, unitIdentity } from "simetra/compiler";
|
|
13
|
+
import { parse } from "pg-connection-string";
|
|
14
|
+
import { existsSync } from "node:fs";
|
|
15
|
+
// src/io/data-guard-refusal.ts
|
|
16
|
+
/**
|
|
17
|
+
* Тексти не називають ні рядка підключення, ні ролі входу: відмова йде
|
|
18
|
+
* агентові й у журнали клієнта. Пізніша версія — П4-F (спека П4 §6.14);
|
|
19
|
+
* назву віхи споживачеві не показуємо.
|
|
20
|
+
*/
|
|
21
|
+
const MESSAGES = {
|
|
22
|
+
"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.",
|
|
23
|
+
"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.",
|
|
24
|
+
"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."
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Відмова запобіжника бази розробника. Окремий легкий модуль: його
|
|
28
|
+
* імпортує `invoke.ts`, і він не мусить тягнути `pg` чи ярус сервера.
|
|
29
|
+
* Запобіжники ловлять випадковий запуск, а не межа безпеки: межа —
|
|
30
|
+
* облікові дані ролі входу рантайму (спека П4 §6.14).
|
|
31
|
+
*/
|
|
32
|
+
var DataGuardRefusal = class extends UsageError {
|
|
33
|
+
detail;
|
|
34
|
+
name = "DataGuardRefusal";
|
|
35
|
+
constructor(detail) {
|
|
36
|
+
super(MESSAGES[detail]);
|
|
37
|
+
this.detail = detail;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
// src/io/database.ts
|
|
41
|
+
/**
|
|
42
|
+
* Відмова виклику бази з текстом, який уже безпечно показати: без рядка
|
|
43
|
+
* підключення, користувача й пароля. Помилка використання — викликач може
|
|
44
|
+
* виправити її сам (змінна середовища, сервер тіні).
|
|
45
|
+
*/
|
|
46
|
+
var DatabaseRefusal = class extends UsageError {
|
|
47
|
+
name = "DatabaseRefusal";
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* `host:port/db` — єдине про підключення, що можна показати. Рядок, який не
|
|
51
|
+
* розбирається як URL, не цитуємо: він міг би бути самим паролем.
|
|
52
|
+
*/
|
|
53
|
+
function describeConnection(url) {
|
|
54
|
+
if (!/^postgres(ql)?:\/\//i.test(url)) return UNDESCRIBED;
|
|
55
|
+
try {
|
|
56
|
+
const c = parse(url);
|
|
57
|
+
const host = c.host === null || c.host === "" ? "localhost" : c.host;
|
|
58
|
+
return `${host.includes(":") ? `[${host}]` : host}:${c.port === null || c.port === "" ? "5432" : c.port}/${c.database ?? ""}`;
|
|
59
|
+
} catch {
|
|
60
|
+
return UNDESCRIBED;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const UNDESCRIBED = "the configured database";
|
|
64
|
+
/**
|
|
65
|
+
* Ресурс запуску з імен змінних, зафіксованих при запуску. Без змінної цілі
|
|
66
|
+
* ресурсу немає — `invoke` відмовить з її ім'ям. Значення читається тут, а
|
|
67
|
+
* пули відкриває лише виклик інструмента бази.
|
|
68
|
+
*/
|
|
69
|
+
function databaseResource(env, names) {
|
|
70
|
+
const url = env[names.url];
|
|
71
|
+
if (url === void 0 || url === "") return void 0;
|
|
72
|
+
const describe = describeConnection(url);
|
|
73
|
+
return {
|
|
74
|
+
describe,
|
|
75
|
+
async connect() {
|
|
76
|
+
if (names.shadow === void 0) return {
|
|
77
|
+
target: { url },
|
|
78
|
+
describe
|
|
79
|
+
};
|
|
80
|
+
const shadowUrl = env[names.shadow];
|
|
81
|
+
if (shadowUrl === void 0 || shadowUrl === "") throw new DatabaseRefusal(`The environment variable ${names.shadow} named by --shadow-url-env is not set. Nothing changed.`);
|
|
82
|
+
return {
|
|
83
|
+
target: { url },
|
|
84
|
+
shadowBase: { url: shadowUrl },
|
|
85
|
+
describe
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/** Мережеві коди Node: база недосяжна, і повторити варто після виправлення адреси. */
|
|
91
|
+
const UNREACHABLE = /* @__PURE__ */ new Set([
|
|
92
|
+
"ECONNREFUSED",
|
|
93
|
+
"ECONNRESET",
|
|
94
|
+
"ENOTFOUND",
|
|
95
|
+
"EAI_AGAIN",
|
|
96
|
+
"ETIMEDOUT",
|
|
97
|
+
"EHOSTUNREACH",
|
|
98
|
+
"ENETUNREACH"
|
|
99
|
+
]);
|
|
100
|
+
/**
|
|
101
|
+
* Код Node (`EPIPE`, `ERR_INVALID_URL`) перевіряється раніше за SQLSTATE: обидва
|
|
102
|
+
* бувають п'ятисимвольними, а класу SQLSTATE на `E` у Postgres немає.
|
|
103
|
+
*/
|
|
104
|
+
const NODE_CODE = /^E[A-Z_]+$/;
|
|
105
|
+
const SQLSTATE$1 = /^[0-9A-Z]{5}$/;
|
|
106
|
+
/**
|
|
107
|
+
* Збій драйвера без коду, що означає втрачене чи не встановлене з'єднання.
|
|
108
|
+
* Текст лише розпізнається, ніколи не цитується.
|
|
109
|
+
*/
|
|
110
|
+
const LOST_CONNECTION = /^Connection terminated|^timeout expired/;
|
|
111
|
+
/**
|
|
112
|
+
* Код помилки: драйвер і Node кладуть його в `code`, а порт виконання T2 —
|
|
113
|
+
* SQLSTATE в `sqlstate` (клас T2 не знає драйвера й не імітує його поле).
|
|
114
|
+
*/
|
|
115
|
+
function codeOf(error) {
|
|
116
|
+
if (error instanceof ApplyDbError) return error.sqlstate;
|
|
117
|
+
const code = error.code;
|
|
118
|
+
return typeof code === "string" ? code : void 0;
|
|
119
|
+
}
|
|
120
|
+
const refusal = (message, note = "") => ({
|
|
121
|
+
kind: "refusal",
|
|
122
|
+
message: `${message}${note} Nothing changed.`
|
|
123
|
+
});
|
|
124
|
+
/**
|
|
125
|
+
* Тінь потребує сесійної семантики (`CREATE DATABASE`, підключення до нової
|
|
126
|
+
* бази за іменем, сесійні `SET` завантажувача), а детектора режиму пулера
|
|
127
|
+
* немає (спека designer §3.2): збій тіні з нерозпізнаною причиною лише
|
|
128
|
+
* називає вимогу. Відмова без `CREATEDB` чи через іншу мажорну версію її не
|
|
129
|
+
* отримує — причина там уже відома.
|
|
130
|
+
*/
|
|
131
|
+
const SHADOW_CONNECTION = " The shadow needs a direct or session-mode connection; a transaction-mode pooler is not guaranteed to support it.";
|
|
132
|
+
/**
|
|
133
|
+
* Єдина межа, на якій помилка підключення чи запиту стає текстом для
|
|
134
|
+
* виводу. Текст складається лише зі стабільних фраз, адреси `host:port/db` і
|
|
135
|
+
* коду помилки: повідомлення драйвера й двигуна не цитуються, бо несуть ім'я
|
|
136
|
+
* користувача («password authentication failed for user …»), а інші —
|
|
137
|
+
* будь-що з рядка підключення. Наші власні відмови вже безпечні й ідуть як є.
|
|
138
|
+
*/
|
|
139
|
+
function classifyDatabaseError(error, names) {
|
|
140
|
+
const c = classify(error, names, "");
|
|
141
|
+
const drop = shadowDropOf(error);
|
|
142
|
+
if (drop === void 0) return c;
|
|
143
|
+
const shadowDrop = diagnostic("engine.shadow-drop-failed", "", "", drop.params);
|
|
144
|
+
return c.kind === "refusal" ? {
|
|
145
|
+
kind: "refusal",
|
|
146
|
+
message: `${c.message} ${shadowDrop.message}`
|
|
147
|
+
} : {
|
|
148
|
+
...c,
|
|
149
|
+
shadowDrop
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** `note` — речення перед «Nothing changed.» у кожній відмові. */
|
|
153
|
+
function classify(error, names, note) {
|
|
154
|
+
const describe = names.target;
|
|
155
|
+
const refused = (message) => refusal(message, note);
|
|
156
|
+
if (error instanceof DatabaseRefusal) return {
|
|
157
|
+
kind: "refusal",
|
|
158
|
+
message: error.message
|
|
159
|
+
};
|
|
160
|
+
if (error instanceof ShadowServerMismatchError) return {
|
|
161
|
+
kind: "refusal",
|
|
162
|
+
message: error.message
|
|
163
|
+
};
|
|
164
|
+
if (error instanceof ShadowBaseUnsupportedError) return refusal(localize({
|
|
165
|
+
code: "plan.shadow-base-unsupported",
|
|
166
|
+
params: {}
|
|
167
|
+
}, "en").message);
|
|
168
|
+
if (error instanceof ShadowTemplateMissingError) return refusal(`The shadow template database "${error.template}" is missing or is not sealed by a superuser. Run \`simetra roles\` as a superuser to prepare it.`);
|
|
169
|
+
if (error instanceof ShadowCreateRefusedError) {
|
|
170
|
+
const where = error.onShadowBase ? names.shadow ?? describe : describe;
|
|
171
|
+
return refusal(`A shadow database cannot be created on ${where}: the connecting role lacks CREATEDB.${error.onShadowBase ? "" : " Grant CREATEDB to the role or, where the provider allows a separate shadow server, point --shadow-url-env at a server where it has it."}`);
|
|
172
|
+
}
|
|
173
|
+
if (error instanceof ShadowServerError) {
|
|
174
|
+
const where = error.onShadowBase ? names.shadow ?? describe : describe;
|
|
175
|
+
const c = classify(error.cause, { target: where }, SHADOW_CONNECTION);
|
|
176
|
+
if (c.kind === "refusal") return c;
|
|
177
|
+
const { error: name, sqlstate } = c.params;
|
|
178
|
+
return refusal(`A shadow database could not be created or reached on ${where} (${name}${sqlstate === void 0 ? "" : `, SQLSTATE ${sqlstate}`}).`, SHADOW_CONNECTION);
|
|
179
|
+
}
|
|
180
|
+
if (error instanceof AggregateError && error.errors.length > 0) return classify(error.errors[0], names, note);
|
|
181
|
+
if (!(error instanceof Error)) return {
|
|
182
|
+
kind: "failure",
|
|
183
|
+
params: {
|
|
184
|
+
database: describe,
|
|
185
|
+
error: "unknown"
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
if (error instanceof ApplyConnectionLost) return refused(`The connection to the database at ${describe} was lost or timed out.`);
|
|
189
|
+
const code = codeOf(error);
|
|
190
|
+
if (code !== void 0 && NODE_CODE.test(code)) {
|
|
191
|
+
if (UNREACHABLE.has(code)) return refused(`The database at ${describe} is unreachable (${code}). Check the host and port in the connection string.`);
|
|
192
|
+
if (code === "ERR_INVALID_URL") return refused("The connection string is not a valid URL.");
|
|
193
|
+
return {
|
|
194
|
+
kind: "failure",
|
|
195
|
+
params: {
|
|
196
|
+
database: describe,
|
|
197
|
+
error: `${error.name} ${code}`
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
if (code !== void 0 && SQLSTATE$1.test(code)) {
|
|
202
|
+
if (code.startsWith("28")) return refused(`Authentication to the database at ${describe} failed. Check the user and password in the connection string.`);
|
|
203
|
+
if (code.startsWith("08")) return refused(`The connection to the database at ${describe} failed (SQLSTATE ${code}).`);
|
|
204
|
+
if (code === "3D000") return refused(`The database at ${describe} does not exist.`);
|
|
205
|
+
if (code === "42501") return refused(`The connecting role lacks a privilege this tool needs on ${describe} (SQLSTATE 42501).`);
|
|
206
|
+
return {
|
|
207
|
+
kind: "failure",
|
|
208
|
+
params: {
|
|
209
|
+
database: describe,
|
|
210
|
+
error: error.name,
|
|
211
|
+
sqlstate: code
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
if (code === void 0 && LOST_CONNECTION.test(error.message)) return refused(`The connection to the database at ${describe} was lost or timed out.`);
|
|
216
|
+
return {
|
|
217
|
+
kind: "failure",
|
|
218
|
+
params: {
|
|
219
|
+
database: describe,
|
|
220
|
+
error: error.name
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Помилка програми, а не бази: вбудовані класи JS без коду драйвера чи Node
|
|
226
|
+
* (у Node `TypeError` буває з кодом `ERR_*`, як `ERR_INVALID_URL`). Драйвер
|
|
227
|
+
* кидає `Error` чи `DatabaseError`, тож його текст сюди не потрапляє, а
|
|
228
|
+
* баг не маскується під збій бази.
|
|
229
|
+
*/
|
|
230
|
+
function isProgramBug(error) {
|
|
231
|
+
return (error instanceof TypeError || error instanceof RangeError || error instanceof ReferenceError || error instanceof SyntaxError) && codeOf(error) === void 0;
|
|
232
|
+
}
|
|
233
|
+
/** Діагностики невдалого виклику: збій і, якщо була, невидалена тінь. */
|
|
234
|
+
function failureDiagnostics(outcome) {
|
|
235
|
+
return outcome.shadowDrop === void 0 ? [outcome.diagnostic] : [outcome.diagnostic, outcome.shadowDrop];
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Підключення одного виклику — єдина межа помилок бази. Відмова
|
|
239
|
+
* (`DatabaseRefusal`) летить до `invoke` і стає кодом 2; збій роботи з базою
|
|
240
|
+
* стає діагностикою `database.failed` (код 1, MCP `isError`). Сирий виняток
|
|
241
|
+
* бази далі не йде: SDK MCP показав би агенту його текст. Баг програми
|
|
242
|
+
* (`isProgramBug`) летить далі як є — шлях внутрішньої помилки `invoke`.
|
|
243
|
+
* Пули відкриває й закриває двигун усередині `fn`.
|
|
244
|
+
*/
|
|
245
|
+
async function withDatabase(resource, tool, fn) {
|
|
246
|
+
let names = { target: resource.describe };
|
|
247
|
+
try {
|
|
248
|
+
const db = await resource.connect();
|
|
249
|
+
if (db.shadowBase !== void 0) names = {
|
|
250
|
+
...names,
|
|
251
|
+
shadow: describeConnection(db.shadowBase.url)
|
|
252
|
+
};
|
|
253
|
+
return {
|
|
254
|
+
ok: true,
|
|
255
|
+
value: await fn(db)
|
|
256
|
+
};
|
|
257
|
+
} catch (error) {
|
|
258
|
+
if (isProgramBug(error)) throw error;
|
|
259
|
+
const c = classifyDatabaseError(error, names);
|
|
260
|
+
if (c.kind === "refusal") throw new DatabaseRefusal(c.message);
|
|
261
|
+
return {
|
|
262
|
+
ok: false,
|
|
263
|
+
diagnostic: diagnostic("database.failed", "", "", {
|
|
264
|
+
tool,
|
|
265
|
+
...c.params
|
|
266
|
+
}),
|
|
267
|
+
...c.shadowDrop === void 0 ? {} : { shadowDrop: c.shadowDrop }
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
// src/io/data.ts
|
|
272
|
+
/**
|
|
273
|
+
* Ознака бази розробника — налаштування рівня бази, яке ставить оператор
|
|
274
|
+
* (`ALTER DATABASE … SET` від суперкористувача). Сесійне `options=-c …` чи
|
|
275
|
+
* налаштування ролі її не дають: їх може задати сам рядок підключення.
|
|
276
|
+
*/
|
|
277
|
+
const DEVELOPMENT_ENVIRONMENT = {
|
|
278
|
+
setting: "simetra.environment",
|
|
279
|
+
value: "development"
|
|
280
|
+
};
|
|
281
|
+
const IPV4_LOOPBACK = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
|
|
282
|
+
/**
|
|
283
|
+
* Хост, який візьме `pg`, — машина розробника: `localhost`, петля IPv4
|
|
284
|
+
* `127.0.0.0/8`, `::1` чи шлях unix-сокета. DNS не розв'язується: ім'я, що
|
|
285
|
+
* лише вказує на петлю, — уже не «ця машина» за формою рядка.
|
|
286
|
+
*/
|
|
287
|
+
function isLocalHost(host) {
|
|
288
|
+
if (host === void 0 || host === "") return false;
|
|
289
|
+
if (host.startsWith("/")) return true;
|
|
290
|
+
const h = host.toLowerCase();
|
|
291
|
+
if (h === "localhost" || h === "::1") return true;
|
|
292
|
+
const m = IPV4_LOOPBACK.exec(h);
|
|
293
|
+
return m !== null && m.slice(1).every((octet) => Number(octet) <= 255);
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Факти ролі входу й ознаки бази одним оператором. Роль перевіряється
|
|
297
|
+
* фактами, не іменем: ім'я `simetra_runtime` не доводить, що роль не
|
|
298
|
+
* суперкористувач і не мігратор. Відсутня в кластері роль команд дає
|
|
299
|
+
* `false`, а не `42704`, — підзапит з `COALESCE`.
|
|
300
|
+
*/
|
|
301
|
+
const DATA_GUARD_FACTS_SQL = `SELECT r.rolsuper, r.rolbypassrls,
|
|
302
|
+
COALESCE((SELECT pg_catalog.pg_has_role(session_user, c.oid, 'SET')
|
|
303
|
+
FROM pg_catalog.pg_roles c WHERE c.rolname = $1), false) AS command,
|
|
304
|
+
COALESCE(pg_catalog.pg_has_role(session_user, n.nspowner, 'MEMBER'), false) AS migrator,
|
|
305
|
+
COALESCE((SELECT pg_catalog.pg_has_role(session_user, s.oid, 'MEMBER')
|
|
306
|
+
FROM pg_catalog.pg_roles s WHERE s.rolname = $2), false) AS service,
|
|
307
|
+
EXISTS (SELECT FROM pg_catalog.pg_db_role_setting d
|
|
308
|
+
JOIN pg_catalog.pg_database b ON b.oid = d.setdatabase
|
|
309
|
+
WHERE b.datname = pg_catalog.current_database() AND d.setrole = 0
|
|
310
|
+
AND $3 = ANY (d.setconfig)) AS development
|
|
311
|
+
FROM pg_catalog.pg_roles r
|
|
312
|
+
LEFT JOIN pg_catalog.pg_namespace n ON n.nspname = $4
|
|
313
|
+
WHERE r.rolname = session_user`;
|
|
314
|
+
/** Параметри {@link DATA_GUARD_FACTS_SQL} для профілю провайдера. */
|
|
315
|
+
function dataGuardFactsParams(provider) {
|
|
316
|
+
return [
|
|
317
|
+
PLATFORM_ROLES.command,
|
|
318
|
+
PROVIDER_API_ROLES[provider].service,
|
|
319
|
+
`${DEVELOPMENT_ENVIRONMENT.setting}=${DEVELOPMENT_ENVIRONMENT.value}`,
|
|
320
|
+
PLATFORM_SCHEMA
|
|
321
|
+
];
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Claims сесії інструмента: права — користувача `--as`, агент лише
|
|
325
|
+
* названий в `act` (RFC 8693) і прав не дає. Claim аноніма — явно `false`:
|
|
326
|
+
* сесію без нього рантайм відмовляє.
|
|
327
|
+
*/
|
|
328
|
+
function dataSession(provider, o) {
|
|
329
|
+
const role = readRoleOf(provider);
|
|
330
|
+
const claim = PROVIDER_IDENTITY_SOURCES[provider].anonymousClaim;
|
|
331
|
+
return {
|
|
332
|
+
sub: o.as,
|
|
333
|
+
...role === void 0 ? {} : { role },
|
|
334
|
+
...claim === null ? {} : { [claim]: false },
|
|
335
|
+
...o.agent === void 0 ? {} : { act: { sub: o.agent } }
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Запит фактів сирим клієнтом пулу (булеві — `boolean`, а не текст порту
|
|
340
|
+
* рантайму) у транзакції лише читання. Клієнт звільняється до повернення:
|
|
341
|
+
* за `max: 1` незвільнений клієнт заблокував би рантайм.
|
|
342
|
+
*/
|
|
343
|
+
async function checkGuards(pool, provider) {
|
|
344
|
+
const client = await pool.connect();
|
|
345
|
+
client.on("error", () => {});
|
|
346
|
+
let facts;
|
|
347
|
+
let broken = false;
|
|
348
|
+
try {
|
|
349
|
+
await client.query("BEGIN READ ONLY");
|
|
350
|
+
const { rows } = await client.query(DATA_GUARD_FACTS_SQL, dataGuardFactsParams(provider));
|
|
351
|
+
await client.query("COMMIT");
|
|
352
|
+
facts = rows[0];
|
|
353
|
+
} catch (error) {
|
|
354
|
+
broken = true;
|
|
355
|
+
throw error;
|
|
356
|
+
} finally {
|
|
357
|
+
client.release(broken);
|
|
358
|
+
}
|
|
359
|
+
if (facts === void 0 || facts.rolsuper || facts.rolbypassrls || facts.migrator || facts.service || !facts.command) throw new DataGuardRefusal("login-refused");
|
|
360
|
+
if (!facts.development) throw new DataGuardRefusal("not-development");
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Ресурс даних з імені змінної, зафіксованого при запуску. Порожня змінна —
|
|
364
|
+
* ресурсу немає, `invoke` відмовить `no-data`. Пул — на виклик (`open`), і
|
|
365
|
+
* кожен виклик заново проходить запобіжники.
|
|
366
|
+
*/
|
|
367
|
+
function dataResource(env, o) {
|
|
368
|
+
const url = env[o.urlEnv];
|
|
369
|
+
if (url === void 0 || url === "") return void 0;
|
|
370
|
+
return {
|
|
371
|
+
describe: describeConnection(url),
|
|
372
|
+
as: o.as,
|
|
373
|
+
...o.agent === void 0 ? {} : { agent: o.agent },
|
|
374
|
+
async open(provider) {
|
|
375
|
+
let host;
|
|
376
|
+
try {
|
|
377
|
+
host = new pg.Client({ connectionString: url }).host;
|
|
378
|
+
} catch {
|
|
379
|
+
throw new DatabaseRefusal(`The connection string in ${o.urlEnv} is not a valid URL. Nothing changed.`);
|
|
380
|
+
}
|
|
381
|
+
if (!isLocalHost(host)) throw new DataGuardRefusal("not-local");
|
|
382
|
+
const pool = new pg.Pool({
|
|
383
|
+
connectionString: url,
|
|
384
|
+
max: 1
|
|
385
|
+
});
|
|
386
|
+
pool.on("error", () => {});
|
|
387
|
+
try {
|
|
388
|
+
await checkGuards(pool, provider);
|
|
389
|
+
} catch (error) {
|
|
390
|
+
await pool.end().catch(() => {});
|
|
391
|
+
throw error;
|
|
392
|
+
}
|
|
393
|
+
return {
|
|
394
|
+
database: fromPgPool(pool),
|
|
395
|
+
session: dataSession(provider, o),
|
|
396
|
+
close: () => pool.end()
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Збій роботи з базою даних виклику: лише параметри `database.failed`
|
|
403
|
+
* (адреса й код), без `cause` і тексту драйвера, — `run` інструмента
|
|
404
|
+
* повертає їх діагностикою.
|
|
405
|
+
*/
|
|
406
|
+
var DataFailure = class extends Error {
|
|
407
|
+
params;
|
|
408
|
+
name = "DataFailure";
|
|
409
|
+
constructor(params) {
|
|
410
|
+
super("database.failed");
|
|
411
|
+
this.params = params;
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
/** Межа помилок `withData`: правило `withDatabase`, плюс власні відмови й вади. */
|
|
415
|
+
function boundary(error, describe) {
|
|
416
|
+
if (error instanceof DataGuardRefusal || error instanceof ZodError || isProgramBug(error)) return error;
|
|
417
|
+
const c = classifyDatabaseError(error, { target: describe });
|
|
418
|
+
if (c.kind === "refusal") return new DatabaseRefusal(c.message);
|
|
419
|
+
const { sqlstate, ...rest } = c.params;
|
|
420
|
+
return new DataFailure(sqlstate === void 0 ? rest : {
|
|
421
|
+
...rest,
|
|
422
|
+
sqlstate
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Сесія даних одного виклику — єдина межа помилок бази для інструментів
|
|
427
|
+
* даних. `CommandFailure` до неї не доходить: `fn` повертає її як дані.
|
|
428
|
+
* Пул закривається тут, у `finally`, на будь-якому результаті.
|
|
429
|
+
*/
|
|
430
|
+
async function withData(resource, provider, fn) {
|
|
431
|
+
let session;
|
|
432
|
+
try {
|
|
433
|
+
session = await resource.open(provider);
|
|
434
|
+
} catch (error) {
|
|
435
|
+
throw boundary(error, resource.describe);
|
|
436
|
+
}
|
|
437
|
+
let result;
|
|
438
|
+
try {
|
|
439
|
+
result = await fn(session);
|
|
440
|
+
} catch (error) {
|
|
441
|
+
await closeQuietly(session);
|
|
442
|
+
throw boundary(error, resource.describe);
|
|
443
|
+
}
|
|
444
|
+
await closeQuietly(session);
|
|
445
|
+
return result;
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Закриття пулу — поза межею результату: після успішного `fn` команда вже
|
|
449
|
+
* закомічена, тож збій закриття не має підміняти ні результат, ні помилку
|
|
450
|
+
* `fn`. У журнал — лише факт, без тексту драйвера (він несе ім'я входу).
|
|
451
|
+
*/
|
|
452
|
+
async function closeQuietly(session) {
|
|
453
|
+
try {
|
|
454
|
+
await session.close();
|
|
455
|
+
} catch {
|
|
456
|
+
process.stderr.write("simetra: closing the data session failed\n");
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
460
|
+
/**
|
|
461
|
+
* Прапорець бере ім'я змінної, а не значення: підказки й `instructions`
|
|
462
|
+
* повторюють argv запуску, тож рядок підключення, переданий замість імені,
|
|
463
|
+
* потрапив би агентові. Значення в тексті не цитується.
|
|
464
|
+
*/
|
|
465
|
+
function checkEnvName(flag, value) {
|
|
466
|
+
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.`);
|
|
467
|
+
}
|
|
468
|
+
const isGuid = (value) => z.guid().safeParse(value).success;
|
|
469
|
+
/**
|
|
470
|
+
* Спільна перевірка прапорців даних MCP і CLI. Типової змінної немає:
|
|
471
|
+
* доступ від імені користувача — явне рішення людини, тож прапорці йдуть
|
|
472
|
+
* разом або не йдуть зовсім. Значення в текст помилки не потрапляють.
|
|
473
|
+
*/
|
|
474
|
+
function parseDataLaunch(flags) {
|
|
475
|
+
const { dataUrlEnv, as, agent } = flags;
|
|
476
|
+
if (dataUrlEnv === void 0 && as === void 0 && agent === void 0) return void 0;
|
|
477
|
+
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.");
|
|
478
|
+
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.");
|
|
479
|
+
checkEnvName("--data-url-env", dataUrlEnv);
|
|
480
|
+
if (!isGuid(as)) throw new UsageError("--as takes a user UUID.");
|
|
481
|
+
if (agent !== void 0 && !isGuid(agent)) throw new UsageError("--agent takes an agent UUID.");
|
|
482
|
+
return {
|
|
483
|
+
urlEnv: dataUrlEnv,
|
|
484
|
+
as,
|
|
485
|
+
...agent === void 0 ? {} : { agent }
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
// src/io/metadata-dir.ts
|
|
489
|
+
/**
|
|
490
|
+
* Файли, які читає компілятор; усе інше в теці його не стосується. Перелік
|
|
491
|
+
* боргу — один файл у корені теки: без нього ратчет бачив би порожній перелік
|
|
492
|
+
* і звітував кожну одиницю боргу.
|
|
493
|
+
*/
|
|
494
|
+
const METADATA_SUFFIXES = [
|
|
495
|
+
".meta.json",
|
|
496
|
+
".sql",
|
|
497
|
+
".module.ts",
|
|
498
|
+
FUNCTIONS_FILE_SUFFIX
|
|
499
|
+
];
|
|
500
|
+
const isMetadataFile = (key) => key === SQL_DEBT_FILE || METADATA_SUFFIXES.some((suffix) => key.endsWith(suffix));
|
|
501
|
+
/**
|
|
502
|
+
* Єдине місце читання диска для дверей CLI: компілятор (T1) працює над мапою
|
|
503
|
+
* «шлях → текст» і не знає про файлову систему.
|
|
504
|
+
*/
|
|
505
|
+
async function readMetadataDir(dir) {
|
|
506
|
+
let isDirectory;
|
|
507
|
+
try {
|
|
508
|
+
isDirectory = (await stat(dir)).isDirectory();
|
|
509
|
+
} catch (error) {
|
|
510
|
+
const code = error.code;
|
|
511
|
+
if (code === "ENOENT" || code === "ENOTDIR") throw new UsageError(`metadata directory not found: ${dir}`);
|
|
512
|
+
throw error;
|
|
513
|
+
}
|
|
514
|
+
if (!isDirectory) throw new UsageError(`Not a directory: ${dir}`);
|
|
515
|
+
const entries = await readdir(dir, {
|
|
516
|
+
recursive: true,
|
|
517
|
+
withFileTypes: true
|
|
518
|
+
});
|
|
519
|
+
const files = /* @__PURE__ */ new Map();
|
|
520
|
+
for (const entry of entries) {
|
|
521
|
+
if (!entry.isFile()) continue;
|
|
522
|
+
const full = join(entry.parentPath, entry.name);
|
|
523
|
+
const key = relative(dir, full).split(sep).join("/");
|
|
524
|
+
if (!isMetadataFile(key)) continue;
|
|
525
|
+
files.set(key, await readFile(full, "utf8"));
|
|
526
|
+
}
|
|
527
|
+
return files;
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Єдине місце запису; `content: null` видаляє файл і прибирає порожні теки.
|
|
531
|
+
* Видалення йдуть першими: на регістронезалежній ФС перейменування лише
|
|
532
|
+
* регістру — це видалення старого шляху й запис нового, що вказують на той
|
|
533
|
+
* самий файл, і зворотний порядок стер би щойно записане.
|
|
534
|
+
*/
|
|
535
|
+
async function writeChanges(dir, changes) {
|
|
536
|
+
const root = resolve(dir);
|
|
537
|
+
const targets = /* @__PURE__ */ new Map();
|
|
538
|
+
for (const change of changes) {
|
|
539
|
+
const target = resolve(root, change.path);
|
|
540
|
+
if (!target.startsWith(root + sep)) throw new UsageError(`Path escapes the target directory: ${change.path}`);
|
|
541
|
+
targets.set(change, target);
|
|
542
|
+
}
|
|
543
|
+
const ordered = [...changes.filter((c) => c.content === null), ...changes.filter((c) => c.content !== null)];
|
|
544
|
+
for (const change of ordered) {
|
|
545
|
+
const target = targets.get(change);
|
|
546
|
+
if (change.content === null) {
|
|
547
|
+
await rm(target, { force: true });
|
|
548
|
+
await pruneEmptyDirs(dirname(target), root);
|
|
549
|
+
} else {
|
|
550
|
+
await mkdir(dirname(target), { recursive: true });
|
|
551
|
+
await writeFile(target, change.content, "utf8");
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
async function pruneEmptyDirs(from, root) {
|
|
556
|
+
let current = from;
|
|
557
|
+
while (current !== root && current.startsWith(root + sep)) {
|
|
558
|
+
let entries;
|
|
559
|
+
try {
|
|
560
|
+
entries = await readdir(current);
|
|
561
|
+
} catch {
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
if (entries.length > 0) return;
|
|
565
|
+
await rm(current, { recursive: true });
|
|
566
|
+
current = dirname(current);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
// src/io/report.ts
|
|
570
|
+
/** Діагностика з текстом потрібною мовою; саме її віддають обидва формати. */
|
|
571
|
+
function localized(d, locale) {
|
|
572
|
+
const { message, hint } = localize(d, locale);
|
|
573
|
+
const rest = { ...d };
|
|
574
|
+
delete rest.hint;
|
|
575
|
+
return {
|
|
576
|
+
...rest,
|
|
577
|
+
message,
|
|
578
|
+
...hint === void 0 ? {} : { hint }
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
function formatDiagnostics(diagnostics, { dir, locale, format }) {
|
|
582
|
+
const items = diagnostics.map((d) => localized(d, locale));
|
|
583
|
+
if (format === "json") return JSON.stringify(items.map((d) => ({
|
|
584
|
+
...d,
|
|
585
|
+
dir
|
|
586
|
+
})), null, 2);
|
|
587
|
+
const lines = [];
|
|
588
|
+
for (const d of items) {
|
|
589
|
+
lines.push(`${placeOf(d, dir)} ${d.severity} ${d.code} ${d.message}`);
|
|
590
|
+
if (d.hint !== void 0) lines.push(` hint: ${d.hint}`);
|
|
591
|
+
}
|
|
592
|
+
const errors = items.filter((d) => d.severity === "error").length;
|
|
593
|
+
lines.push(`${errors} error(s), ${items.length - errors} warning(s)`);
|
|
594
|
+
return lines.join("\n");
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Місце діагностики в тексті. Позиція друкується лише тоді, коли вона є:
|
|
598
|
+
* діагностика без файлу (вхід операції загалом) чи файлу, якого немає в
|
|
599
|
+
* теці, отримала б фальшиве `:1:1`, а читач шукав би там неіснуючу причину.
|
|
600
|
+
*/
|
|
601
|
+
function placeOf(d, dir) {
|
|
602
|
+
if (d.file === "") return `${dir}:`;
|
|
603
|
+
if (d.range === void 0) return `${dir}/${d.file}:`;
|
|
604
|
+
const { line, character } = d.range.start;
|
|
605
|
+
return `${dir}/${d.file}:${line + 1}:${character + 1}`;
|
|
606
|
+
}
|
|
607
|
+
/** Зведення звірки: дії плану, відмінності каталогу, діагностика. */
|
|
608
|
+
function renderDiff(d, report) {
|
|
609
|
+
const lines = [];
|
|
610
|
+
if (d.plan.length > 0) {
|
|
611
|
+
lines.push(`plan (${d.plan.length} action(s), database -> metadata):`);
|
|
612
|
+
for (const a of d.plan) {
|
|
613
|
+
const tags = [a.dataLoss ? "data loss" : void 0, a.rewriteRisk ? "rewrite" : void 0].filter((x) => x !== void 0);
|
|
614
|
+
lines.push(` ${a.sql.trim()}${tags.length > 0 ? ` -- ${tags.join(", ")}` : ""}`);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
if (d.differences.length > 0) {
|
|
618
|
+
lines.push(`differences (${d.differences.length}):`);
|
|
619
|
+
for (const x of d.differences) lines.push(` ${x.kind} ${x.path}: ${x.detail}`);
|
|
620
|
+
}
|
|
621
|
+
if (d.applyState === "absent") lines.push("apply state: absent from the database; the first apply creates it");
|
|
622
|
+
if (d.empty) lines.push("diff: the database matches the metadata");
|
|
623
|
+
lines.push(report);
|
|
624
|
+
return lines.join("\n");
|
|
625
|
+
}
|
|
626
|
+
const short$1 = (hash) => hash === null ? "initial" : hash.slice(0, 12);
|
|
627
|
+
/** Режим `plpgsql_check` плану словами виводу. */
|
|
628
|
+
const PLPGSQL_CHECK_LABEL = {
|
|
629
|
+
installed: "installed",
|
|
630
|
+
transient: "transient (installed for the check, rolled back)",
|
|
631
|
+
unavailable: "unavailable"
|
|
632
|
+
};
|
|
633
|
+
const qualified = (schema, name) => `${quoteIdent(schema)}.${quoteIdent(name)}`;
|
|
634
|
+
/**
|
|
635
|
+
* Блок «Promotion»: що стає чим і що людина
|
|
636
|
+
* дозволяє. Таблиця, що лишає своє ім'я, рядка перейменування не дає:
|
|
637
|
+
* `a -> a` читався б як зміна, якої немає.
|
|
638
|
+
*/
|
|
639
|
+
function promotionLines(p, needs) {
|
|
640
|
+
const lines = [`promotion: ${p.kind} ${p.name} (${p.objectId})`, ` record hash: ${p.recordHash}`];
|
|
641
|
+
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)}`);
|
|
642
|
+
for (const c of p.columns) lines.push(` column ${qualified(c.table.schema, c.table.name)}: ${quoteIdent(c.from)} -> ${quoteIdent(c.to)}`);
|
|
643
|
+
for (const c of p.canonicalNames) lines.push(` ${c.kind} ${qualified(c.table.schema, c.table.name)}: ${quoteIdent(c.from)} -> ${quoteIdent(c.to)}`);
|
|
644
|
+
for (const t of p.data) {
|
|
645
|
+
lines.push(` data steps ${qualified(t.after.schema, t.after.table)}:`);
|
|
646
|
+
for (const c of t.columns) lines.push(` ${c.step} ${quoteIdent(c.column)} ← ${c.expression} (${c.kind})`);
|
|
647
|
+
if (t.triggers.length > 0) lines.push(` triggers disabled during the write: ${t.triggers.map((x) => quoteIdent(x.name)).join(", ")}`);
|
|
648
|
+
}
|
|
649
|
+
for (const item of p.permissionItems) {
|
|
650
|
+
lines.push(` ${item.token}${needs.has(item.token) ? ` (needs allow: ${item.token})` : ""}`);
|
|
651
|
+
for (const s of item.summary) lines.push(` ${s}`);
|
|
652
|
+
}
|
|
653
|
+
return lines;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Зведення плану для людини й агента: звідки й куди, `planHash` і файл,
|
|
657
|
+
* дрейф — першим блоком, до кроків (платформна спека §6.2): кроки читаються
|
|
658
|
+
* вже знаючи, що ціль дрейфнула. Далі — промоція, бо кроки наміру й класи
|
|
659
|
+
* конверсій читаються, знаючи, що стає чим. Повний
|
|
660
|
+
* SQL — у файлі плану; тут перший рядок.
|
|
661
|
+
*/
|
|
662
|
+
function renderPlan(d, report, o) {
|
|
663
|
+
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");
|
|
664
|
+
const needs = new Set(d.requiredPermissions);
|
|
665
|
+
const lines = [
|
|
666
|
+
`plan ${short$1(d.fromHash)} -> ${short$1(d.toHash)}`,
|
|
667
|
+
`${o.written ? "written" : "not written"} ${d.file}`,
|
|
668
|
+
`planHash: ${d.planHash}`
|
|
669
|
+
];
|
|
670
|
+
if (d.drift !== null) {
|
|
671
|
+
lines.push(`drift (${d.drift.reason}): needs allow: drift`);
|
|
672
|
+
if (d.drift.sections.length > 0) lines.push(` fingerprint sections: ${d.drift.sections.join(", ")}`);
|
|
673
|
+
for (const path of d.drift.paths) lines.push(` ${path}`);
|
|
674
|
+
}
|
|
675
|
+
if (d.promotion !== null) lines.push(...promotionLines(d.promotion, needs));
|
|
676
|
+
const stepLine = (s) => {
|
|
677
|
+
const tags = [
|
|
678
|
+
`lock ${s.lockClass}`,
|
|
679
|
+
...s.conversion === void 0 ? [] : [`conversion ${s.conversion}`],
|
|
680
|
+
...needs.has(s.id) ? [`needs allow: ${s.id}`] : []
|
|
681
|
+
];
|
|
682
|
+
const first = s.sql.trim().split("\n")[0] ?? "";
|
|
683
|
+
return ` ${s.id} ${s.origin} ${s.class} (${tags.join("; ")}) ${first}`;
|
|
684
|
+
};
|
|
685
|
+
const backfillLines = (s) => {
|
|
686
|
+
const b = s.backfill;
|
|
687
|
+
if (b === void 0) return [];
|
|
688
|
+
return [
|
|
689
|
+
` backfill ${qualified(b.table.schema, b.table.name)}.${quoteIdent(b.column)}: ${b.rowsAtPlan} row(s) with NULL at plan`,
|
|
690
|
+
...needs.has(s.id) ? [` default: ${b.default}`] : [],
|
|
691
|
+
...b.triggers.length > 0 ? [` triggers disabled during the fill: ${b.triggers.map((x) => quoteIdent(x.name)).join(", ")}`] : []
|
|
692
|
+
];
|
|
693
|
+
};
|
|
694
|
+
const environment = d.steps.filter((s) => s.origin === "environment");
|
|
695
|
+
const steps = d.steps.filter((s) => s.origin !== "environment");
|
|
696
|
+
if (steps.length === 0) lines.push("steps: none");
|
|
697
|
+
else {
|
|
698
|
+
lines.push(`steps (${steps.length}):`);
|
|
699
|
+
lines.push(...steps.flatMap((s) => [stepLine(s), ...backfillLines(s)]));
|
|
700
|
+
}
|
|
701
|
+
if (environment.length > 0) {
|
|
702
|
+
lines.push(`environment rights: the global default privileges of role ${quoteIdent(d.environment.role)}:`);
|
|
703
|
+
lines.push(...environment.map(stepLine));
|
|
704
|
+
}
|
|
705
|
+
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(", ")}`);
|
|
706
|
+
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`);
|
|
707
|
+
lines.push(`plpgsql_check: ${PLPGSQL_CHECK_LABEL[d.plpgsqlCheck]}`);
|
|
708
|
+
if (d.expectedBlindFunctions > 0) lines.push(`expected provider blind functions (preset): ${d.expectedBlindFunctions}`);
|
|
709
|
+
lines.push(report);
|
|
710
|
+
return lines.join("\n");
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Підсумок застосування; репетиція нагадує, що блокування були справжні.
|
|
714
|
+
* Без даних заголовок судить за діагностикою: після обриву з невідомим
|
|
715
|
+
* результатом «нічого не записано» було б неправдою, а повтор за нею міг би
|
|
716
|
+
* застосувати план удруге.
|
|
717
|
+
*/
|
|
718
|
+
function renderApply(d, diagnostics, report) {
|
|
719
|
+
const unknown = diagnostics.find((x) => x.code === "apply.connection-lost" && x.params?.outcome === "unknown");
|
|
720
|
+
return [
|
|
721
|
+
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.`,
|
|
722
|
+
...(d?.backfills ?? []).map((b) => ` backfill ${b.step} ${qualified(b.schema, b.table)}.${quoteIdent(b.column)}: ${b.rows} row(s) filled with the default; ${b.rowsAtPlan} with NULL at plan`),
|
|
723
|
+
report
|
|
724
|
+
].join("\n");
|
|
725
|
+
}
|
|
726
|
+
/** Текст пояснення функції для терміналу. */
|
|
727
|
+
function renderFunctionExplanation(e) {
|
|
728
|
+
const lines = [`function ${e.function.schema}.${e.function.name}`];
|
|
729
|
+
if (e.callers === void 0) lines.push("not declared");
|
|
730
|
+
else {
|
|
731
|
+
lines.push(`callers: ${e.callers.join(", ") || "(none)"}`);
|
|
732
|
+
for (const [provider, roles] of Object.entries(e.roles ?? {})) lines.push(`EXECUTE (${provider}): ${roles.map((r) => `${r.role} (${r.caller})`).join(", ") || "(none)"}`);
|
|
733
|
+
}
|
|
734
|
+
if (e.check !== void 0) lines.push(`check: ${e.check}`);
|
|
735
|
+
lines.push(`state: ${e.state}`);
|
|
736
|
+
return lines.join("\n");
|
|
737
|
+
}
|
|
738
|
+
/** Текст пояснення об'єкта для терміналу; JSON-вигляд друкується як є. */
|
|
739
|
+
function renderExplanation(e) {
|
|
740
|
+
const lines = [`${e.object.kind} ${e.object.name} (${e.object.file})`];
|
|
741
|
+
if (e.object.scopeKind !== void 0) lines.push(`scope: ${e.object.scopeKind}`);
|
|
742
|
+
for (const t of e.tables) {
|
|
743
|
+
lines.push("", `table ${t.schema}.${t.name}${t.part ? ` [${t.part}]` : ""}`);
|
|
744
|
+
for (const c of t.columns) {
|
|
745
|
+
const tags = [
|
|
746
|
+
c.notNull ? "not null" : void 0,
|
|
747
|
+
c.logical === void 0 ? void 0 : `logical: ${c.logical}`,
|
|
748
|
+
c.standard === void 0 ? void 0 : `standard: ${c.standard}`,
|
|
749
|
+
c.scope === true ? "scope" : void 0
|
|
750
|
+
].filter((x) => x !== void 0);
|
|
751
|
+
lines.push(` ${c.name} ${c.type}${tags.length > 0 ? ` (${tags.join(", ")})` : ""}`);
|
|
752
|
+
}
|
|
753
|
+
if (t.primaryKey !== void 0) lines.push(` primary key (${t.primaryKey.join(", ")})`);
|
|
754
|
+
for (const u of t.uniques) lines.push(` unique (${u.join(", ")})`);
|
|
755
|
+
for (const f of t.foreignKeys) lines.push(` foreign key (${f.columns.join(", ")}) -> ${f.references}`);
|
|
756
|
+
}
|
|
757
|
+
for (const q of e.movementQueries) lines.push("", `movement query ${q.identity}`, q.sql);
|
|
758
|
+
for (const u of e.generatedUnits) lines.push("", `generated ${u.identity}`, u.sql);
|
|
759
|
+
if (e.contracts.length > 0) lines.push("", "contracts:", JSON.stringify(e.contracts, null, 2));
|
|
760
|
+
if (e.referencedBy.length > 0) {
|
|
761
|
+
lines.push("", "referenced by:");
|
|
762
|
+
for (const r of e.referencedBy) lines.push(` ${r.file}#${r.pointer} (${r.role})`);
|
|
763
|
+
}
|
|
764
|
+
return `${lines.join("\n")}\n`;
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Підсумок запису промоції для терміналу: що на що перетворилось і що
|
|
768
|
+
* лишається плану бази. Повний запис — у `--format json`.
|
|
769
|
+
*/
|
|
770
|
+
function renderPromotion(r, written) {
|
|
771
|
+
const lines = [`${written ? "promoted" : "would promote"} ${r.objectId} into ${r.kind}`];
|
|
772
|
+
for (const t of r.tables) lines.push(` table ${t.schema}.${t.from} -> ${t.to}`);
|
|
773
|
+
const counts = [
|
|
774
|
+
["columns renamed or moved", r.columns.length],
|
|
775
|
+
["type changes", r.typeChanges.length],
|
|
776
|
+
["data steps", r.dataSteps.length],
|
|
777
|
+
["columns retired", r.retired.length],
|
|
778
|
+
["constraints relaxed", r.relaxed.length],
|
|
779
|
+
["constraints tightened", r.tightened.length],
|
|
780
|
+
["row level security changes", r.rowLevelSecurity.length],
|
|
781
|
+
["delete semantics changes", r.deleteSemantics.length],
|
|
782
|
+
["conversions", r.conversions.length],
|
|
783
|
+
["units moved", r.movedUnits.length],
|
|
784
|
+
["units rewritten", r.rewrittenUnits.length],
|
|
785
|
+
["contract changes", r.contractChanges.length]
|
|
786
|
+
];
|
|
787
|
+
for (const [label, n] of counts) if (n > 0) lines.push(` ${label}: ${n}`);
|
|
788
|
+
return lines.join("\n");
|
|
789
|
+
}
|
|
790
|
+
// src/io/schema-path.ts
|
|
791
|
+
/**
|
|
792
|
+
* Резолвер `$schema` для теки метаданих: відносний POSIX-шлях від теки файлу
|
|
793
|
+
* до `node_modules/simetra/schemas/…` проєкту. Саме встановлений пакет, а не
|
|
794
|
+
* той, з якого запущено інструмент: `$schema` вказує на схеми тієї версії,
|
|
795
|
+
* з якою проєкт збирається (спека П2 §8.5). Пакет шукається ліниво — лише
|
|
796
|
+
* коли компілятор справді записує `$schema`, тож читальні виклики працюють і
|
|
797
|
+
* в теці без встановленого пакета.
|
|
798
|
+
*/
|
|
799
|
+
function schemaPathResolver(metadataDir) {
|
|
800
|
+
const root = resolve(metadataDir);
|
|
801
|
+
let schemas;
|
|
802
|
+
return (file, schemaFile) => {
|
|
803
|
+
schemas ??= join(installedPackageDir(root, "simetra"), "schemas");
|
|
804
|
+
return posixRelative(dirname(join(root, file)), join(schemas, schemaFile));
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
// src/tools/database-tools.ts
|
|
808
|
+
const PROJECT_FILE$2 = "project.meta.json";
|
|
809
|
+
/**
|
|
810
|
+
* Двигун вантажиться лише викликом інструмента бази: `simetra compile` і
|
|
811
|
+
* MCP-сервер без бази не тягнуть pg-delta.
|
|
812
|
+
*/
|
|
813
|
+
async function loadEngine() {
|
|
814
|
+
const { createPgDeltaEngine } = await import("./schema-engine-8rVHcVYO.js");
|
|
815
|
+
return createPgDeltaEngine();
|
|
816
|
+
}
|
|
817
|
+
/** Резолвер `invoke` гарантує ресурс для інструмента з віссю бази. */
|
|
818
|
+
function required$1(database) {
|
|
819
|
+
if (database === void 0) throw new Error("invoke passes the database to a database tool");
|
|
820
|
+
return database;
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Діагностика двигуна у формі компілятора: без файлу (стосується бази, не
|
|
824
|
+
* теки), з параметрами, з яких звіт будує текст потрібною мовою. Ідентичність
|
|
825
|
+
* об'єкта й код двигуна — у параметрах, щоб JSON-вивід їх ніс.
|
|
826
|
+
*/
|
|
827
|
+
function fromEngine(d) {
|
|
828
|
+
return {
|
|
829
|
+
code: d.code,
|
|
830
|
+
severity: d.severity,
|
|
831
|
+
file: "",
|
|
832
|
+
pointer: "",
|
|
833
|
+
message: d.message,
|
|
834
|
+
params: {
|
|
835
|
+
...d.object === void 0 ? {} : { object: d.object },
|
|
836
|
+
...d.engineCode === void 0 ? {} : { engineCode: d.engineCode },
|
|
837
|
+
...d.params
|
|
838
|
+
}
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
const hasErrors = (diagnostics) => diagnostics.some((d) => d.severity === "error");
|
|
842
|
+
/** Тека, якої ще немає, — порожня тека: `introspect` створює проєкт. */
|
|
843
|
+
async function readFolder(dir) {
|
|
844
|
+
return await stat(dir).then(() => true, () => false) ? readMetadataDir(dir) : /* @__PURE__ */ new Map();
|
|
845
|
+
}
|
|
846
|
+
const schemaName = z.string().min(1).max(63);
|
|
847
|
+
const introspectTool = defineTool({
|
|
848
|
+
name: "introspect",
|
|
849
|
+
description: "Read the live database into metadata: tables become CustomTable, enums PgEnum, the rest verbatim .sql; known ids are kept. Connection: server environment. Scope: existing metadata's schemas plus `schemas` (required without project.meta.json). Existing metadata loads into one throwaway shadow (like `diff`); a shadow that cannot be built is an error. Writes nothing if anything is unrepresentable or fails to compile, except repair-class errors.",
|
|
850
|
+
input: z.strictObject({
|
|
851
|
+
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." }),
|
|
852
|
+
project: z.strictObject({
|
|
853
|
+
name: z.string().min(1).optional(),
|
|
854
|
+
attributeCase: z.enum(ATTRIBUTE_CASES).optional(),
|
|
855
|
+
database: z.strictObject({ provider: z.enum(DATABASE_PROVIDERS).optional() }).optional()
|
|
856
|
+
}).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." })
|
|
857
|
+
}),
|
|
858
|
+
files: "write",
|
|
859
|
+
database: "read",
|
|
860
|
+
data: "none",
|
|
861
|
+
destructive: false,
|
|
862
|
+
async run({ dir, database }, input) {
|
|
863
|
+
const existing = await readFolder(dir);
|
|
864
|
+
const compiled = existing.has(PROJECT_FILE$2) ? await compile(existing, { repair: true }) : void 0;
|
|
865
|
+
if (compiled !== void 0 && compiled.model === void 0) return {
|
|
866
|
+
ok: false,
|
|
867
|
+
changes: [],
|
|
868
|
+
diagnostics: compiled.diagnostics
|
|
869
|
+
};
|
|
870
|
+
const databaseProvider = compiled?.model?.project.database.provider ?? input.project?.database?.provider ?? "supabase";
|
|
871
|
+
const providerSchemas = new Set(PROVIDER_SCHEMAS[databaseProvider]);
|
|
872
|
+
const foreign = (input.schemas ?? []).filter((s) => providerSchemas.has(s));
|
|
873
|
+
if (foreign.length > 0) throw new UsageError(`Provider schemas are not introspected: ${foreign.join(", ")}. Nothing changed.`);
|
|
874
|
+
if ((input.schemas ?? []).includes(PLATFORM_SCHEMA)) throw new UsageError(`Schema ${PLATFORM_SCHEMA} belongs to the platform and is not introspected. Nothing changed.`);
|
|
875
|
+
let project;
|
|
876
|
+
let scope;
|
|
877
|
+
if (compiled?.model !== void 0) {
|
|
878
|
+
const own = compiled.model.project;
|
|
879
|
+
project = {
|
|
880
|
+
name: input.project?.name ?? own.name,
|
|
881
|
+
defaultSchema: own.defaultSchema,
|
|
882
|
+
attributeCase: input.project?.attributeCase ?? own.naming.attributeCase,
|
|
883
|
+
databaseProvider: own.database.provider
|
|
884
|
+
};
|
|
885
|
+
const modelScope = (await engineScope(compiled.model)).scope;
|
|
886
|
+
scope = {
|
|
887
|
+
...modelScope,
|
|
888
|
+
schemas: [.../* @__PURE__ */ new Set([...modelScope.schemas, ...input.schemas ?? []])].filter((schema) => schema !== PLATFORM_SCHEMA).sort()
|
|
889
|
+
};
|
|
890
|
+
} else {
|
|
891
|
+
if (input.schemas === void 0) throw new UsageError(`${dir} has no ${PROJECT_FILE$2}, so there is no scope to read: pass schemas, e.g. {"schemas": ["public"]}. Nothing changed.`);
|
|
892
|
+
project = {
|
|
893
|
+
name: input.project?.name ?? "App",
|
|
894
|
+
defaultSchema: input.schemas[0],
|
|
895
|
+
attributeCase: input.project?.attributeCase ?? "camelCase",
|
|
896
|
+
databaseProvider
|
|
897
|
+
};
|
|
898
|
+
scope = {
|
|
899
|
+
schemas: [...new Set(input.schemas)].sort(),
|
|
900
|
+
provider: project.databaseProvider
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
const engine = await loadEngine();
|
|
904
|
+
const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
|
|
905
|
+
const read = await withDatabase(required$1(database), "introspect", async (db) => ({
|
|
906
|
+
...await engine.extractWithExecuteFacts(db.target, scope),
|
|
907
|
+
reference: await folderReference(engine, createApplyDatabase({ readOnly: true }), {
|
|
908
|
+
target: db.target,
|
|
909
|
+
...db.shadowBase ? { shadowBase: db.shadowBase } : {}
|
|
910
|
+
}, existing)
|
|
911
|
+
}));
|
|
912
|
+
if (!read.ok) return {
|
|
913
|
+
ok: false,
|
|
914
|
+
changes: [],
|
|
915
|
+
diagnostics: failureDiagnostics(read)
|
|
916
|
+
};
|
|
917
|
+
const { extracted, facts, reference } = read.value;
|
|
918
|
+
const extractDiagnostics = [...extracted.diagnostics, ...reference.diagnostics].map(fromEngine);
|
|
919
|
+
const reversed = await reverseGenerate(extracted.model, {
|
|
920
|
+
project,
|
|
921
|
+
existing,
|
|
922
|
+
newId: () => crypto.randomUUID(),
|
|
923
|
+
schemaPath: schemaPathResolver(dir),
|
|
924
|
+
parse: await loadSqlParser(),
|
|
925
|
+
executeFacts: facts,
|
|
926
|
+
...reference.catalog === void 0 ? {} : { reference: reference.catalog }
|
|
927
|
+
});
|
|
928
|
+
const changed = [...facts.catalogChanged ? [diagnostic("introspect.definer-acl-changed", "", "", { check: "fingerprint" })] : [], ...facts.crossCheckFailures.map((f) => diagnostic("introspect.definer-acl-changed", "", "", {
|
|
929
|
+
check: "privilege",
|
|
930
|
+
function: `${f.schema}.${f.name}(${f.identityArguments})`,
|
|
931
|
+
role: f.role,
|
|
932
|
+
privilege: f.privilege
|
|
933
|
+
}))];
|
|
934
|
+
const diagnostics = [
|
|
935
|
+
...extractDiagnostics,
|
|
936
|
+
...reversed.diagnostics,
|
|
937
|
+
...changed
|
|
938
|
+
];
|
|
939
|
+
const ok = !hasErrors(diagnostics);
|
|
940
|
+
const repairOnly = !ok && diagnostics.every((d) => d.severity !== "error" || isRepairError(d));
|
|
941
|
+
return {
|
|
942
|
+
ok,
|
|
943
|
+
...repairOnly ? { written: true } : {},
|
|
944
|
+
changes: ok || repairOnly ? reversed.changes : [],
|
|
945
|
+
diagnostics,
|
|
946
|
+
data: { schemas: [...scope.schemas] }
|
|
947
|
+
};
|
|
948
|
+
},
|
|
949
|
+
present: {}
|
|
950
|
+
});
|
|
951
|
+
/** Імена фільтра (`schema.table` чи `table`) у таблиці обох моделей. */
|
|
952
|
+
function resolveTables(filter, known) {
|
|
953
|
+
const tables = [];
|
|
954
|
+
const unknown = [];
|
|
955
|
+
for (const entry of filter) {
|
|
956
|
+
const dot = entry.indexOf(".");
|
|
957
|
+
const hits = known.filter((t) => dot < 0 ? t.name === entry : t.schema === entry.slice(0, dot) && t.name === entry.slice(dot + 1));
|
|
958
|
+
if (hits.length === 0) unknown.push(entry);
|
|
959
|
+
tables.push(...hits);
|
|
960
|
+
}
|
|
961
|
+
return {
|
|
962
|
+
tables,
|
|
963
|
+
unknown
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Чи стосується ідентичність двигуна однієї з таблиць: сама таблиця, її
|
|
968
|
+
* колонки, обмеження, тригери, політики, типові значення, пов'язані з нею
|
|
969
|
+
* індекси, енами й послідовності (`related`) і обгортки (`comment:(…)`,
|
|
970
|
+
* `acl:(…)`) над будь-чим із цього. Індекс, енам і послідовність у Postgres
|
|
971
|
+
* адресуються схемою, а не таблицею, тож зв'язок з таблицею дають моделі.
|
|
972
|
+
*/
|
|
973
|
+
function touchesTables(tables, related, language) {
|
|
974
|
+
const own = new Set(tables.map((t) => language === "unit" ? unitIdentity("table", t.schema, t.name) : `table:${t.schema}.${t.name}`));
|
|
975
|
+
const prefixes = tables.map((t) => `${t.schema}.${t.name}.`);
|
|
976
|
+
const inTable = (key) => {
|
|
977
|
+
if (language === "engine") return prefixes.some((p) => key.startsWith(p));
|
|
978
|
+
const parts = identityParts(`:${key}`);
|
|
979
|
+
return parts.length >= 3 && tables.some((t) => t.schema === parts[0] && t.name === parts[1]);
|
|
980
|
+
};
|
|
981
|
+
const sub = /^(column|constraint|trigger|rule|policy|default):(.*)$/;
|
|
982
|
+
const touches = (id) => {
|
|
983
|
+
if (own.has(id) || related.has(id)) return true;
|
|
984
|
+
const m = sub.exec(id);
|
|
985
|
+
if (m !== null) return inTable(m[2]);
|
|
986
|
+
const wrapped = /^(?:comment|acl|securityLabel):\((.*)\)/.exec(id);
|
|
987
|
+
return wrapped !== null && touches(wrapped[1]);
|
|
988
|
+
};
|
|
989
|
+
return touches;
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Ціль дії — те, що вона створює чи знищує. Лише в дій без них (GRANT,
|
|
993
|
+
* `ENABLE RLS`, `REPLICA IDENTITY`) ціль видно в `consumes`; інакше
|
|
994
|
+
* `consumes` — залежності, і FK чужої таблиці потрапив би у фільтр таблиці,
|
|
995
|
+
* на яку посилається.
|
|
996
|
+
*/
|
|
997
|
+
function targetsOf(a) {
|
|
998
|
+
const own = [...a.produces, ...a.destroys];
|
|
999
|
+
return own.length > 0 ? own : a.consumes;
|
|
1000
|
+
}
|
|
1001
|
+
/** Частини `a.b.c` з лапками Postgres; `undefined` — не ім'я. */
|
|
1002
|
+
function nameParts(text) {
|
|
1003
|
+
const parts = [];
|
|
1004
|
+
const part = /\s*(?:"((?:[^"]|"")+)"|([A-Za-z_][\w$]*))\s*(\.|$)/y;
|
|
1005
|
+
while (part.lastIndex < text.length) {
|
|
1006
|
+
const m = part.exec(text);
|
|
1007
|
+
if (m === null) return void 0;
|
|
1008
|
+
parts.push(m[1] === void 0 ? m[2].toLowerCase() : m[1].replace(/""/g, "\""));
|
|
1009
|
+
if (m[3] === "") break;
|
|
1010
|
+
}
|
|
1011
|
+
return parts.length > 0 ? parts : void 0;
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Енами й послідовності названих таблиць. Вони адресуються схемою, а не
|
|
1015
|
+
* таблицею, тож зв'язок дають колонки (тип, identity, `nextval` у типовому
|
|
1016
|
+
* значенні) і `OWNED BY` одиниць — з обох моделей: енам нової колонки є
|
|
1017
|
+
* лише в бажаній, видаленої — лише в цільовій.
|
|
1018
|
+
*/
|
|
1019
|
+
function dependentIds(keys, models) {
|
|
1020
|
+
const enums = new Set(models.flatMap((m) => m.enumTypes.map((e) => `${e.schema}.${e.name}`)));
|
|
1021
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1022
|
+
const unitIds = /* @__PURE__ */ new Set();
|
|
1023
|
+
const sequence = (schema, parts) => {
|
|
1024
|
+
if (parts === void 0 || parts.length > 2) return;
|
|
1025
|
+
const qualified = parts.length === 2 ? parts : [schema, parts[0]];
|
|
1026
|
+
const key = qualified.join(".");
|
|
1027
|
+
ids.add(`sequence:${key}`).add(`sequenceOwnedBy:${key}`);
|
|
1028
|
+
unitIds.add(unitIdentity("sequence", ...qualified)).add(unitIdentity("sequenceOwnedBy", ...qualified));
|
|
1029
|
+
};
|
|
1030
|
+
for (const table of models.flatMap((m) => m.tables)) {
|
|
1031
|
+
if (!keys.has(`${table.schema}.${table.name}`)) continue;
|
|
1032
|
+
for (const column of table.columns) {
|
|
1033
|
+
const type = logicalTypeOf(column.type.replace(/(\[\])+$/, ""), enums);
|
|
1034
|
+
if (type.form === "enum") ids.add(`type:${type.schema}.${type.name}`);
|
|
1035
|
+
if (column.identity !== void 0) sequence(table.schema, [column.identity.sequence]);
|
|
1036
|
+
const next = /nextval\('((?:[^']|'')+)'::regclass\)/.exec(column.default ?? "");
|
|
1037
|
+
if (next !== null) sequence(table.schema, nameParts(next[1].replace(/''/g, "'")));
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
for (const unit of models.flatMap((m) => m.units)) {
|
|
1041
|
+
if (unit.class !== "sequenceOwnedBy") continue;
|
|
1042
|
+
const owner = /OWNED\s+BY\s+(.+?)\s*;?\s*$/i.exec(unit.sql);
|
|
1043
|
+
const parts = owner === null ? void 0 : nameParts(owner[1]);
|
|
1044
|
+
const table = parts === void 0 ? void 0 : parts.length === 3 ? `${parts[0]}.${parts[1]}` : parts.length === 2 ? `${unit.schema}.${parts[0]}` : void 0;
|
|
1045
|
+
if (table !== void 0 && keys.has(table)) sequence(unit.schema, identityParts(unit.identity));
|
|
1046
|
+
}
|
|
1047
|
+
return {
|
|
1048
|
+
engine: ids,
|
|
1049
|
+
unit: unitIds
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Чи належить ідентичність двигуна якійсь таблиці моделей, її індексу чи
|
|
1054
|
+
* енаму: лише тоді фільтр може судити, що вона поза названими таблицями.
|
|
1055
|
+
* Функція, в'юха, роль чи грант-одиниця таблиці не мають — їх не відкидаємо.
|
|
1056
|
+
*/
|
|
1057
|
+
function attributable(models) {
|
|
1058
|
+
const indexes = new Set(models.flatMap((m) => m.tables.flatMap((t) => t.indexes.map((i) => `index:${t.schema}.${i.name}`))));
|
|
1059
|
+
const enums = new Set(models.flatMap((m) => m.enumTypes.map((e) => `type:${e.schema}.${e.name}`)));
|
|
1060
|
+
const tableKinds = /^(?:table|column|constraint|trigger|rule|policy|default):/;
|
|
1061
|
+
const check = (id) => {
|
|
1062
|
+
const wrapped = /^(?:comment|acl|securityLabel):\((.*)\)/.exec(id);
|
|
1063
|
+
if (wrapped !== null) return check(wrapped[1]);
|
|
1064
|
+
return tableKinds.test(id) || indexes.has(id) || enums.has(id);
|
|
1065
|
+
};
|
|
1066
|
+
return check;
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* Звуження звірки до названих таблиць (§10.3 спеки П2: звірка документа з
|
|
1070
|
+
* його ТЧ і регістрами, а не всієї бази) разом з їхніми енамами й
|
|
1071
|
+
* послідовностями. Діагностика двигуна (без файлу) відкидається лише тоді,
|
|
1072
|
+
* коли її об'єкт належить іншій таблиці; без атрибуції вона лишається, бо
|
|
1073
|
+
* помилка, яку не віднести до таблиці, може стосуватися й названих.
|
|
1074
|
+
*/
|
|
1075
|
+
function narrow(data, tables, models) {
|
|
1076
|
+
const keys = new Set(tables.map((t) => `${t.schema}.${t.name}`));
|
|
1077
|
+
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}`))));
|
|
1078
|
+
const dependent = dependentIds(keys, models);
|
|
1079
|
+
const owned = attributable(models);
|
|
1080
|
+
const touches = touchesTables(tables, /* @__PURE__ */ new Set([...indexes, ...dependent.engine]), "engine");
|
|
1081
|
+
const touchesUnit = touchesTables(tables, dependent.unit, "unit");
|
|
1082
|
+
const tablePaths = [...keys].map((k) => `tables.${k}`);
|
|
1083
|
+
const enumPaths = new Set([...dependent.engine].filter((id) => id.startsWith("type:")).map((id) => `enumTypes.${id.slice(5)}`));
|
|
1084
|
+
return {
|
|
1085
|
+
plan: data.plan.filter((a) => targetsOf(a).some(touches)),
|
|
1086
|
+
differences: data.differences.filter((d) => tablePaths.some((p) => d.path === p || d.path.startsWith(`${p}.`)) || enumPaths.has(d.path) || d.path.startsWith("units.") && touchesUnit(d.path.slice(6))),
|
|
1087
|
+
diagnostics: data.diagnostics.filter((d) => {
|
|
1088
|
+
const object = d.params?.object;
|
|
1089
|
+
return d.file !== "" || typeof object !== "string" || !owned(object) || touches(object);
|
|
1090
|
+
})
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
const diffTool = defineTool({
|
|
1094
|
+
name: "diff",
|
|
1095
|
+
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.",
|
|
1096
|
+
input: z.strictObject({ tables: z.array(z.string().min(1)).min(1).optional().meta({ description: "Tables to compare: `schema.table` or `table`." }) }),
|
|
1097
|
+
files: "read",
|
|
1098
|
+
database: "read",
|
|
1099
|
+
data: "none",
|
|
1100
|
+
destructive: false,
|
|
1101
|
+
async run({ dir, database }, input) {
|
|
1102
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
1103
|
+
const model = compiled.model;
|
|
1104
|
+
if (model === void 0) return {
|
|
1105
|
+
ok: false,
|
|
1106
|
+
changes: [],
|
|
1107
|
+
diagnostics: compiled.diagnostics
|
|
1108
|
+
};
|
|
1109
|
+
const desired = await desiredForApply(model);
|
|
1110
|
+
const engine = await loadEngine();
|
|
1111
|
+
const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
|
|
1112
|
+
const compared = await withDatabase(required$1(database), "diff", async (db) => {
|
|
1113
|
+
const reader = createApplyDatabase({ readOnly: true });
|
|
1114
|
+
const membership = await checkOwnerMembership(reader, db.target, desired.scope, "engine.owner-not-member");
|
|
1115
|
+
if (membership.refusal !== void 0) return { refusal: [membership.refusal] };
|
|
1116
|
+
const roles = await checkPlatformRoles(reader, db.target, db.shadowBase, desired.sql, await loadSqlParser(), desired.scope.provider);
|
|
1117
|
+
if (roles.refusal !== void 0) return { refusal: roles.refusal };
|
|
1118
|
+
const seeds = await reader.transaction(db.target, "rollback", (tx) => readShadowEnvironment(tx, desired.scope));
|
|
1119
|
+
if (!seeds.ok) return { refusal: seeds.diagnostics };
|
|
1120
|
+
return { comparison: await compareWithDesired(engine, {
|
|
1121
|
+
target: db.target,
|
|
1122
|
+
...db.shadowBase ? { shadowBase: db.shadowBase } : {},
|
|
1123
|
+
environment: seeds.statements
|
|
1124
|
+
}, desired.sql, desired.scope, desired.diagnostics) };
|
|
1125
|
+
});
|
|
1126
|
+
if (!compared.ok) return {
|
|
1127
|
+
ok: false,
|
|
1128
|
+
changes: [],
|
|
1129
|
+
diagnostics: [...compiled.diagnostics, ...failureDiagnostics(compared)]
|
|
1130
|
+
};
|
|
1131
|
+
if (compared.value.refusal !== void 0) return {
|
|
1132
|
+
ok: false,
|
|
1133
|
+
changes: [],
|
|
1134
|
+
diagnostics: [...compiled.diagnostics, ...compared.value.refusal.map(fromEngine)]
|
|
1135
|
+
};
|
|
1136
|
+
const comparison = compared.value.comparison;
|
|
1137
|
+
const diagnostics = [...compiled.diagnostics, ...comparison.diagnostics.map(fromEngine)];
|
|
1138
|
+
if (comparison.status === "shadow-failed") return {
|
|
1139
|
+
ok: false,
|
|
1140
|
+
changes: [],
|
|
1141
|
+
diagnostics
|
|
1142
|
+
};
|
|
1143
|
+
const state = applyStateOf(comparison.target, comparison.plan, model);
|
|
1144
|
+
const ownedAction = (a) => {
|
|
1145
|
+
const targets = targetsOf(a).filter((id) => !id.startsWith("role:"));
|
|
1146
|
+
return targets.length > 0 && targets.every(state.owns);
|
|
1147
|
+
};
|
|
1148
|
+
let data = state.state === "absent" ? {
|
|
1149
|
+
plan: comparison.plan.actions.filter((a) => !ownedAction(a)),
|
|
1150
|
+
differences: comparison.differences.filter((d) => !state.ownsPath(d.path)),
|
|
1151
|
+
diagnostics
|
|
1152
|
+
} : {
|
|
1153
|
+
plan: comparison.plan.actions,
|
|
1154
|
+
differences: comparison.differences,
|
|
1155
|
+
diagnostics
|
|
1156
|
+
};
|
|
1157
|
+
if (input.tables !== void 0) {
|
|
1158
|
+
const models = [comparison.target.model, comparison.desired.model];
|
|
1159
|
+
const { tables, unknown } = resolveTables(input.tables, models.flatMap((m) => m.tables));
|
|
1160
|
+
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.`);
|
|
1161
|
+
data = narrow(data, tables, models);
|
|
1162
|
+
}
|
|
1163
|
+
const ok = !hasErrors(data.diagnostics);
|
|
1164
|
+
return {
|
|
1165
|
+
ok,
|
|
1166
|
+
changes: [],
|
|
1167
|
+
diagnostics: data.diagnostics,
|
|
1168
|
+
data: {
|
|
1169
|
+
...data,
|
|
1170
|
+
applyState: state.state,
|
|
1171
|
+
empty: ok && data.plan.length === 0 && data.differences.length === 0
|
|
1172
|
+
}
|
|
1173
|
+
};
|
|
1174
|
+
},
|
|
1175
|
+
present: { text: (data, v) => data === void 0 ? void 0 : renderDiff(data, v.report) }
|
|
1176
|
+
});
|
|
1177
|
+
// src/tools/apply-tools.ts
|
|
1178
|
+
/**
|
|
1179
|
+
* Пул лише на виклик: інструменти без застосування не тягнуть `pg`, як і
|
|
1180
|
+
* двигун у `loadEngine`.
|
|
1181
|
+
*/
|
|
1182
|
+
async function applyDatabase(o) {
|
|
1183
|
+
const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
|
|
1184
|
+
return createApplyDatabase(o);
|
|
1185
|
+
}
|
|
1186
|
+
const refusedWith = (diagnostics) => ({
|
|
1187
|
+
ok: false,
|
|
1188
|
+
changes: [],
|
|
1189
|
+
diagnostics
|
|
1190
|
+
});
|
|
1191
|
+
function planPromotion(section, model) {
|
|
1192
|
+
const { record } = section;
|
|
1193
|
+
const object = model.objects.find((o) => o.id === record.objectId);
|
|
1194
|
+
return {
|
|
1195
|
+
objectId: record.objectId,
|
|
1196
|
+
kind: record.kind,
|
|
1197
|
+
name: object?.name ?? record.objectId,
|
|
1198
|
+
recordHash: section.recordHash,
|
|
1199
|
+
tables: record.tables.map(({ schema, from, to }) => ({
|
|
1200
|
+
schema,
|
|
1201
|
+
from,
|
|
1202
|
+
to
|
|
1203
|
+
})),
|
|
1204
|
+
columns: section.columns,
|
|
1205
|
+
canonicalNames: section.canonicalNames,
|
|
1206
|
+
permissionItems: section.permissionItems,
|
|
1207
|
+
data: section.data
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
function planData(file, artifact, model, expectedBlindFunctions, rightsOrphans) {
|
|
1211
|
+
const conversions = new Map((artifact.promotion?.conversions ?? []).map((c) => [c.step, c.class]));
|
|
1212
|
+
return {
|
|
1213
|
+
file,
|
|
1214
|
+
planHash: artifact.planHash,
|
|
1215
|
+
fromHash: artifact.fromHash,
|
|
1216
|
+
toHash: artifact.toHash,
|
|
1217
|
+
drift: artifact.drift,
|
|
1218
|
+
promotion: artifact.promotion === null ? null : planPromotion(artifact.promotion, model),
|
|
1219
|
+
steps: artifact.steps.map(({ id, origin, class: cls, lockClass, sql, backfill }) => {
|
|
1220
|
+
const conversion = conversions.get(id);
|
|
1221
|
+
return {
|
|
1222
|
+
id,
|
|
1223
|
+
origin,
|
|
1224
|
+
class: cls,
|
|
1225
|
+
lockClass,
|
|
1226
|
+
sql,
|
|
1227
|
+
...conversion === void 0 ? {} : { conversion },
|
|
1228
|
+
...backfill === void 0 ? {} : { backfill }
|
|
1229
|
+
};
|
|
1230
|
+
}),
|
|
1231
|
+
locks: artifact.locks,
|
|
1232
|
+
implicitLocks: artifact.implicitLocks,
|
|
1233
|
+
requiredPermissions: artifact.requiredPermissions,
|
|
1234
|
+
environment: {
|
|
1235
|
+
role: artifact.role,
|
|
1236
|
+
defaultPrivileges: artifact.environment.defaultPrivileges
|
|
1237
|
+
},
|
|
1238
|
+
plpgsqlCheck: artifact.plpgsqlCheck,
|
|
1239
|
+
expectedBlindFunctions,
|
|
1240
|
+
rightsOrphans
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
/** Суфікс файлу запису промоції в `plans/` (`promotionFileName`). */
|
|
1244
|
+
const RECORD_SUFFIX = promotionFileName("");
|
|
1245
|
+
/**
|
|
1246
|
+
* Записи промоції з `plans/` кореня (спека промоції §7.1), строго: файл, що
|
|
1247
|
+
* не розбирається схемою чи названий не за своїм `objectId`, — відмова плану
|
|
1248
|
+
* `plan.promotion-record-invalid`, а не пропуск. Пропущений запис перетворив
|
|
1249
|
+
* би промоцію на «запису немає», а вгаданий — на чужий намір. Порядок — за
|
|
1250
|
+
* іменем файлу: план детермінований незалежно від файлової системи.
|
|
1251
|
+
*/
|
|
1252
|
+
async function readPromotionRecords(root) {
|
|
1253
|
+
let names;
|
|
1254
|
+
try {
|
|
1255
|
+
names = await readdir(join(root, PLANS_DIR));
|
|
1256
|
+
} catch (error) {
|
|
1257
|
+
if (error.code === "ENOENT") return {
|
|
1258
|
+
ok: true,
|
|
1259
|
+
records: []
|
|
1260
|
+
};
|
|
1261
|
+
throw error;
|
|
1262
|
+
}
|
|
1263
|
+
const records = [];
|
|
1264
|
+
for (const name of names.filter((n) => n.endsWith(RECORD_SUFFIX)).sort()) {
|
|
1265
|
+
const file = `${PLANS_DIR}/${name}`;
|
|
1266
|
+
const invalid = (detail) => ({
|
|
1267
|
+
ok: false,
|
|
1268
|
+
diagnostic: diagnostic("plan.promotion-record-invalid", "", "", {
|
|
1269
|
+
file,
|
|
1270
|
+
detail
|
|
1271
|
+
})
|
|
1272
|
+
});
|
|
1273
|
+
let text;
|
|
1274
|
+
try {
|
|
1275
|
+
text = await readFile(join(root, file), "utf8");
|
|
1276
|
+
} catch (error) {
|
|
1277
|
+
const code = error.code;
|
|
1278
|
+
if (code === void 0) throw error;
|
|
1279
|
+
return invalid(`the file could not be read (${code})`);
|
|
1280
|
+
}
|
|
1281
|
+
let json;
|
|
1282
|
+
try {
|
|
1283
|
+
json = JSON.parse(text);
|
|
1284
|
+
} catch (error) {
|
|
1285
|
+
if (error instanceof SyntaxError) return invalid(error.message);
|
|
1286
|
+
throw error;
|
|
1287
|
+
}
|
|
1288
|
+
const parsed = promotionRecordSchema.safeParse(json);
|
|
1289
|
+
if (!parsed.success) return invalid(parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; "));
|
|
1290
|
+
const record = parsed.data;
|
|
1291
|
+
if (promotionFileName(record.objectId) !== name) return invalid(`the record is for object ${record.objectId}, so its file is ${PLANS_DIR}/${promotionFileName(record.objectId)}`);
|
|
1292
|
+
records.push({
|
|
1293
|
+
record,
|
|
1294
|
+
file
|
|
1295
|
+
});
|
|
1296
|
+
}
|
|
1297
|
+
return {
|
|
1298
|
+
ok: true,
|
|
1299
|
+
records
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
const planTool = defineTool({
|
|
1303
|
+
name: "plan",
|
|
1304
|
+
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.",
|
|
1305
|
+
input: z.strictObject({}),
|
|
1306
|
+
files: "artifact",
|
|
1307
|
+
database: "read",
|
|
1308
|
+
data: "none",
|
|
1309
|
+
destructive: false,
|
|
1310
|
+
async run({ dir, root, database }) {
|
|
1311
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
1312
|
+
const model = compiled.model;
|
|
1313
|
+
if (model === void 0) return refusedWith(compiled.diagnostics);
|
|
1314
|
+
const promotions = await readPromotionRecords(root);
|
|
1315
|
+
if (!promotions.ok) return refusedWith([...compiled.diagnostics, promotions.diagnostic]);
|
|
1316
|
+
const engine = await loadEngine();
|
|
1317
|
+
const dbs = {
|
|
1318
|
+
reader: await applyDatabase({ readOnly: true }),
|
|
1319
|
+
scratch: await applyDatabase({ readOnly: false })
|
|
1320
|
+
};
|
|
1321
|
+
const built = await withDatabase(required$1(database), "plan", (db) => buildPlan(engine, dbs, model, {
|
|
1322
|
+
target: db.target,
|
|
1323
|
+
...db.shadowBase ? { shadowBase: db.shadowBase } : {}
|
|
1324
|
+
}, promotions.records));
|
|
1325
|
+
if (!built.ok) return refusedWith([...compiled.diagnostics, ...failureDiagnostics(built)]);
|
|
1326
|
+
const outcome = built.value;
|
|
1327
|
+
const diagnostics = [...compiled.diagnostics, ...outcome.diagnostics.map(fromEngine)];
|
|
1328
|
+
switch (outcome.status) {
|
|
1329
|
+
case "refused": return refusedWith(diagnostics);
|
|
1330
|
+
case "unchanged": return {
|
|
1331
|
+
ok: !hasErrors(diagnostics),
|
|
1332
|
+
changes: [],
|
|
1333
|
+
diagnostics,
|
|
1334
|
+
artifacts: [],
|
|
1335
|
+
data: {
|
|
1336
|
+
unchanged: true,
|
|
1337
|
+
rightsOrphans: outcome.rightsOrphans
|
|
1338
|
+
}
|
|
1339
|
+
};
|
|
1340
|
+
case "planned": {
|
|
1341
|
+
const { artifact } = outcome;
|
|
1342
|
+
const file = `${PLANS_DIR}/${planFileName(artifact.fromHash, artifact.toHash)}`;
|
|
1343
|
+
return {
|
|
1344
|
+
ok: !hasErrors(diagnostics),
|
|
1345
|
+
changes: [],
|
|
1346
|
+
diagnostics,
|
|
1347
|
+
artifacts: [{
|
|
1348
|
+
path: file,
|
|
1349
|
+
content: serializePlan(artifact)
|
|
1350
|
+
}],
|
|
1351
|
+
data: planData(file, artifact, model, outcome.expectedBlindFunctions, outcome.rightsOrphans)
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
},
|
|
1356
|
+
present: { text: (data, v) => renderPlan(data, v.report, {
|
|
1357
|
+
ok: v.ok,
|
|
1358
|
+
written: v.written
|
|
1359
|
+
}) }
|
|
1360
|
+
});
|
|
1361
|
+
const engineLabel = (e) => `${e.name} ${e.version}`;
|
|
1362
|
+
/** Перші 12 hex-символів, як у імені файлу плану. */
|
|
1363
|
+
const short = (hash) => hash.slice(0, 12);
|
|
1364
|
+
/** Читає файл плану з `plans/` кореня; поза ним — помилка використання. */
|
|
1365
|
+
async function readPlanFile(root, plan) {
|
|
1366
|
+
const path = resolve(root, plan);
|
|
1367
|
+
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.`);
|
|
1368
|
+
try {
|
|
1369
|
+
return await readFile(path, "utf8");
|
|
1370
|
+
} catch (error) {
|
|
1371
|
+
const code = error.code;
|
|
1372
|
+
if (code === "ENOENT" || code === "EISDIR") throw new UsageError(`Plan file not found: ${plan}. Nothing changed.`);
|
|
1373
|
+
throw error;
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
/**
|
|
1377
|
+
* Текст звіту репетиції з `plans/`; файлу немає — `undefined`, і раннер
|
|
1378
|
+
* відмовить `apply.rehearsal-required`. Тека на місці звіту — те саме, що
|
|
1379
|
+
* його немає, як у `readPlanFile`: звіту там нема, а сирий EISDIR людині
|
|
1380
|
+
* нічого не скаже.
|
|
1381
|
+
*/
|
|
1382
|
+
async function readReport(root, file) {
|
|
1383
|
+
try {
|
|
1384
|
+
return await readFile(join(root, file), "utf8");
|
|
1385
|
+
} catch (error) {
|
|
1386
|
+
const code = error.code;
|
|
1387
|
+
if (code === "ENOENT" || code === "EISDIR") return void 0;
|
|
1388
|
+
throw error;
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* Версії, з якими план побудовано й доведено, мусять бути поточними: інакше
|
|
1393
|
+
* кроки чи відбитки значать інше (платформна спека §6.10). Формат файлу звіряє
|
|
1394
|
+
* вже `parsePlan`.
|
|
1395
|
+
*/
|
|
1396
|
+
function versionMismatches(artifact, engine) {
|
|
1397
|
+
return [
|
|
1398
|
+
[
|
|
1399
|
+
"fingerprintVersion",
|
|
1400
|
+
artifact.fingerprintVersion,
|
|
1401
|
+
FINGERPRINT_VERSION
|
|
1402
|
+
],
|
|
1403
|
+
[
|
|
1404
|
+
"platformVersion",
|
|
1405
|
+
artifact.platformVersion,
|
|
1406
|
+
PLATFORM_VERSION
|
|
1407
|
+
],
|
|
1408
|
+
[
|
|
1409
|
+
"engine",
|
|
1410
|
+
engineLabel(artifact.engine),
|
|
1411
|
+
engineLabel(engine)
|
|
1412
|
+
]
|
|
1413
|
+
].filter(([, plan, current]) => plan !== current).map(([field, plan, current]) => diagnostic("apply.plan-versions", "", "", {
|
|
1414
|
+
field,
|
|
1415
|
+
plan,
|
|
1416
|
+
current
|
|
1417
|
+
}));
|
|
1418
|
+
}
|
|
1419
|
+
const timeoutMs = z.number().int().positive();
|
|
1420
|
+
const applyTool = defineTool({
|
|
1421
|
+
name: "apply",
|
|
1422
|
+
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.",
|
|
1423
|
+
input: z.strictObject({
|
|
1424
|
+
plan: z.string().min(1).meta({ description: "Plan file from `plan`, relative to the project root: plans/….plan.json." }),
|
|
1425
|
+
planHash: z.string().regex(/^[0-9a-f]{64}$/).meta({ description: "planHash of the reviewed plan." }),
|
|
1426
|
+
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>." }),
|
|
1427
|
+
rehearse: z.boolean().optional(),
|
|
1428
|
+
lockTimeoutMs: timeoutMs.optional(),
|
|
1429
|
+
statementTimeoutMs: timeoutMs.optional()
|
|
1430
|
+
}),
|
|
1431
|
+
files: "artifact",
|
|
1432
|
+
database: "write",
|
|
1433
|
+
data: "none",
|
|
1434
|
+
destructive: true,
|
|
1435
|
+
async run({ dir, root, database }, input) {
|
|
1436
|
+
const parsed = parsePlan(await readPlanFile(root, input.plan));
|
|
1437
|
+
if (!parsed.ok && parsed.reason === "format") return refusedWith([fromEngine(parsed.diagnostic)]);
|
|
1438
|
+
if (!parsed.ok) throw new UsageError(`${input.plan} is not a plan file: ${parsed.message}. Nothing changed.`);
|
|
1439
|
+
const { artifact } = parsed;
|
|
1440
|
+
if (!await verifyPlanHash(artifact) || artifact.planHash !== input.planHash) return refusedWith([diagnostic("apply.plan-hash", "", "", {
|
|
1441
|
+
file: input.plan,
|
|
1442
|
+
planHash: input.planHash
|
|
1443
|
+
})]);
|
|
1444
|
+
const engine = await loadEngine();
|
|
1445
|
+
const versions = versionMismatches(artifact, engine.identity);
|
|
1446
|
+
if (versions.length > 0) return refusedWith(versions);
|
|
1447
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
1448
|
+
const model = compiled.model;
|
|
1449
|
+
if (model === void 0) return refusedWith(compiled.diagnostics);
|
|
1450
|
+
if (model.hash !== artifact.toHash) return refusedWith([diagnostic("apply.plan-stale", "", "", {
|
|
1451
|
+
plan: short(artifact.toHash),
|
|
1452
|
+
current: short(model.hash)
|
|
1453
|
+
})]);
|
|
1454
|
+
const allow = input.allow ?? [];
|
|
1455
|
+
const permissions = checkPermissions({
|
|
1456
|
+
steps: artifact.steps,
|
|
1457
|
+
drift: artifact.drift,
|
|
1458
|
+
promotion: artifact.promotion
|
|
1459
|
+
}, allow);
|
|
1460
|
+
if (permissions.length > 0) return refusedWith(permissions.map(fromEngine));
|
|
1461
|
+
let report;
|
|
1462
|
+
if (input.rehearse !== true && artifact.promotion !== null) {
|
|
1463
|
+
const file = `${PLANS_DIR}/${rehearsalFileName(artifact.fromHash, artifact.toHash)}`;
|
|
1464
|
+
const text = await readReport(root, file);
|
|
1465
|
+
if (text !== void 0) {
|
|
1466
|
+
const parsed = parseRehearsal(text);
|
|
1467
|
+
if (!parsed.ok && parsed.reason === "format") return refusedWith([diagnostic("apply.rehearsal-stale", "", "", { reason: "format" })]);
|
|
1468
|
+
if (!parsed.ok) throw new UsageError(`${file} is not a rehearsal report: ${parsed.message}. Nothing changed.`);
|
|
1469
|
+
report = parsed.report;
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
const timeouts = {
|
|
1473
|
+
...input.lockTimeoutMs === void 0 ? {} : { lockTimeoutMs: input.lockTimeoutMs },
|
|
1474
|
+
...input.statementTimeoutMs === void 0 ? {} : { statementTimeoutMs: input.statementTimeoutMs }
|
|
1475
|
+
};
|
|
1476
|
+
const writer = await applyDatabase({ readOnly: false });
|
|
1477
|
+
const base = {
|
|
1478
|
+
planHash: artifact.planHash,
|
|
1479
|
+
allow,
|
|
1480
|
+
snapshot: canonicalSnapshot(model),
|
|
1481
|
+
timeouts
|
|
1482
|
+
};
|
|
1483
|
+
const executed = await withDatabase(required$1(database), "apply", async (db) => {
|
|
1484
|
+
if (copiesShadowFromTemplate(artifact.scope.provider) && db.shadowBase !== void 0) return { unsupported: diagnostic("plan.shadow-base-unsupported", "", "") };
|
|
1485
|
+
if (input.rehearse !== true) return { outcome: await executePlan(writer, db.target, artifact, {
|
|
1486
|
+
...base,
|
|
1487
|
+
mode: "apply",
|
|
1488
|
+
...report === void 0 ? {} : { report }
|
|
1489
|
+
}) };
|
|
1490
|
+
const desired = await desiredForApply(model);
|
|
1491
|
+
const ownerGate = await (await applyDatabase({ readOnly: true })).transaction(db.target, "rollback", (tx) => checkOwnerAttributes(tx, artifact.scope.provider));
|
|
1492
|
+
if (ownerGate !== void 0) return { rolesRefused: [ownerGate] };
|
|
1493
|
+
const roles = await checkPlatformRoles(await applyDatabase({ readOnly: true }), db.target, db.shadowBase, desired.sql, await loadSqlParser(), artifact.scope.provider);
|
|
1494
|
+
if (roles.refusal !== void 0) return { rolesRefused: roles.refusal };
|
|
1495
|
+
const seeds = await (await applyDatabase({ readOnly: true })).transaction(db.target, "rollback", (tx) => readShadowEnvironment(tx, artifact.scope));
|
|
1496
|
+
if (!seeds.ok) return { shadowFailed: seeds.diagnostics };
|
|
1497
|
+
const shadow = await engine.withDesiredShadow({
|
|
1498
|
+
target: db.target,
|
|
1499
|
+
...db.shadowBase ? { shadowBase: db.shadowBase } : {},
|
|
1500
|
+
environment: seeds.statements
|
|
1501
|
+
}, desired.sql, artifact.scope, (shadowDb) => engine.extract(shadowDb, artifact.scope));
|
|
1502
|
+
if (shadow.status === "shadow-failed") return { shadowFailed: shadow.diagnostics };
|
|
1503
|
+
return {
|
|
1504
|
+
outcome: await executePlan(writer, db.target, artifact, {
|
|
1505
|
+
...base,
|
|
1506
|
+
mode: "rehearse",
|
|
1507
|
+
rehearsal: {
|
|
1508
|
+
engine,
|
|
1509
|
+
desired: shadow.value.catalog
|
|
1510
|
+
}
|
|
1511
|
+
}),
|
|
1512
|
+
shadow: shadow.diagnostics
|
|
1513
|
+
};
|
|
1514
|
+
});
|
|
1515
|
+
if (!executed.ok) return refusedWith(failureDiagnostics(executed));
|
|
1516
|
+
if ("shadowFailed" in executed.value) return refusedWith(executed.value.shadowFailed.map(fromEngine));
|
|
1517
|
+
if ("unsupported" in executed.value) return refusedWith([executed.value.unsupported]);
|
|
1518
|
+
if ("rolesRefused" in executed.value) return refusedWith(executed.value.rolesRefused.map(fromEngine));
|
|
1519
|
+
const outcome = executed.value.outcome;
|
|
1520
|
+
const diagnostics = [...executed.value.shadow ?? [], ...outcome.diagnostics].map(fromEngine);
|
|
1521
|
+
const ok = !hasErrors(diagnostics);
|
|
1522
|
+
switch (outcome.status) {
|
|
1523
|
+
case "committed": return {
|
|
1524
|
+
ok,
|
|
1525
|
+
changes: [],
|
|
1526
|
+
diagnostics,
|
|
1527
|
+
data: {
|
|
1528
|
+
status: outcome.status,
|
|
1529
|
+
attempts: outcome.attempts,
|
|
1530
|
+
report: null,
|
|
1531
|
+
backfills: outcome.backfills ?? []
|
|
1532
|
+
}
|
|
1533
|
+
};
|
|
1534
|
+
case "rolledBack": {
|
|
1535
|
+
const report = `${PLANS_DIR}/${rehearsalFileName(artifact.fromHash, artifact.toHash)}`;
|
|
1536
|
+
return {
|
|
1537
|
+
ok,
|
|
1538
|
+
changes: [],
|
|
1539
|
+
diagnostics,
|
|
1540
|
+
data: {
|
|
1541
|
+
status: outcome.status,
|
|
1542
|
+
attempts: outcome.attempts,
|
|
1543
|
+
report: ok ? report : null,
|
|
1544
|
+
backfills: outcome.evidence.backfills.map((b) => {
|
|
1545
|
+
const facts = artifact.steps.find((s) => s.id === b.step)?.backfill;
|
|
1546
|
+
if (facts === void 0) throw new Error(`rehearsal evidence names ${b.step}, which is not a backfill step of the plan`);
|
|
1547
|
+
return {
|
|
1548
|
+
...b,
|
|
1549
|
+
rowsAtPlan: facts.rowsAtPlan
|
|
1550
|
+
};
|
|
1551
|
+
})
|
|
1552
|
+
},
|
|
1553
|
+
artifacts: ok ? [{
|
|
1554
|
+
path: report,
|
|
1555
|
+
content: serializeRehearsal(rehearsalReport(artifact.planHash, outcome.evidence))
|
|
1556
|
+
}] : []
|
|
1557
|
+
};
|
|
1558
|
+
}
|
|
1559
|
+
case "refused":
|
|
1560
|
+
case "failed": return refusedWith(diagnostics);
|
|
1561
|
+
}
|
|
1562
|
+
},
|
|
1563
|
+
present: { text: (data, v) => renderApply(data, v.diagnostics, v.report) }
|
|
1564
|
+
});
|
|
1565
|
+
// src/tools/data-policy.ts
|
|
1566
|
+
/**
|
|
1567
|
+
* Чиста відмова модуля до першого з'єднання: designer модулів не завантажує,
|
|
1568
|
+
* тож хуки об'єкта мовчки не спрацювали б. Перевіряється весь пакет (він —
|
|
1569
|
+
* одна транзакція: дозволена перша фаза не робить дозволеною решту) і першою,
|
|
1570
|
+
* до запобіжника запису прав каталогу T3 (`agentWriteRefusal`), який лишається
|
|
1571
|
+
* власністю T3. Невідомий об'єкт пропускається — його відхилить схема
|
|
1572
|
+
* каталогу T3 (`command.invalid`), і політика не дублює її текст.
|
|
1573
|
+
*/
|
|
1574
|
+
function dataModuleRefusal(model, catalog, batch) {
|
|
1575
|
+
const hasModule = (x) => model.moduleFiles.some((m) => m.ownerObjectId === x.id);
|
|
1576
|
+
const moduleRefusal = (object) => ({
|
|
1577
|
+
code: "command.invalid",
|
|
1578
|
+
reason: "object-module",
|
|
1579
|
+
object
|
|
1580
|
+
});
|
|
1581
|
+
for (const op of batch) {
|
|
1582
|
+
const object = model.objects.find((x) => x.kind === op.object.kind && x.name === op.object.name);
|
|
1583
|
+
if (object === void 0) continue;
|
|
1584
|
+
if (hasModule(object)) return moduleRefusal(op.object);
|
|
1585
|
+
const membershipId = op.action === "create" ? catalog.objects.find((x) => x.id === object.id)?.operations?.create?.root?.membership : void 0;
|
|
1586
|
+
const membership = membershipId === void 0 ? void 0 : model.objects.find((x) => x.id === membershipId);
|
|
1587
|
+
if (membership !== void 0 && hasModule(membership)) return moduleRefusal({
|
|
1588
|
+
kind: membership.kind,
|
|
1589
|
+
name: membership.name
|
|
1590
|
+
});
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
/**
|
|
1594
|
+
* Єдина склейка порядку політики (Р-F3-13): відмова модуля на весь пакет —
|
|
1595
|
+
* першою, далі запобіжник запису прав каталогу T3. Порядок видно споживачеві:
|
|
1596
|
+
* пакет, який порушує обидва правила, дістає відмову модуля, бо прапорець
|
|
1597
|
+
* прав її не знімає.
|
|
1598
|
+
*/
|
|
1599
|
+
function dataPolicyRefusal(model, catalog, batch, options) {
|
|
1600
|
+
const error = dataModuleRefusal(model, catalog, batch);
|
|
1601
|
+
if (error !== void 0) return {
|
|
1602
|
+
kind: "command",
|
|
1603
|
+
error
|
|
1604
|
+
};
|
|
1605
|
+
const rights = agentWriteRefusal(catalog, batch, options);
|
|
1606
|
+
return rights === void 0 ? void 0 : {
|
|
1607
|
+
kind: "rights",
|
|
1608
|
+
...rights
|
|
1609
|
+
};
|
|
1610
|
+
}
|
|
1611
|
+
// src/tools/data-tools.ts
|
|
1612
|
+
/**
|
|
1613
|
+
* Зведення результату даних для тексту MCP і CLI: кількість рядків чи змін
|
|
1614
|
+
* або код помилки T3 з причиною — повні дані йдуть у структурований вивід.
|
|
1615
|
+
*/
|
|
1616
|
+
function summarizeData(name, data) {
|
|
1617
|
+
if ("error" in data) return `${name}: ${data.error.code}${data.error.reason === void 0 ? "" : `: ${data.error.reason}`}`;
|
|
1618
|
+
const count = (n, what) => `${n} ${what}${n === 1 ? "" : "s"}`;
|
|
1619
|
+
if ("count" in data) return `${name}: ${data.capped === true ? "over " : ""}${count(data.count, "row")} counted`;
|
|
1620
|
+
return "rows" in data ? `${name}: ${count(data.rows.length, "row")}` : `${name}: ${count(data.result.changes.length, "change")}`;
|
|
1621
|
+
}
|
|
1622
|
+
const SQLSTATE = /^[0-9A-Z]{5}$/;
|
|
1623
|
+
/**
|
|
1624
|
+
* Журнал рантайму: T3 кладе сюди сирий виняток бази, а stderr MCP-сервера
|
|
1625
|
+
* йде в журнали клієнта. Тож лише вид запису, SQLSTATE і таблиця — ні
|
|
1626
|
+
* тексту, ні `detail`, де Postgres цитує значення й ім'я входу. Stdout —
|
|
1627
|
+
* канал протоколу MCP, туди не пишемо нічого.
|
|
1628
|
+
*/
|
|
1629
|
+
function logRuntimeEntry(entry) {
|
|
1630
|
+
const error = entry.error;
|
|
1631
|
+
const code = typeof error?.code === "string" && SQLSTATE.test(error.code) ? ` SQLSTATE ${error.code}` : "";
|
|
1632
|
+
const table = typeof error?.table === "string" ? ` table ${JSON.stringify(error.table)}` : "";
|
|
1633
|
+
process.stderr.write(`simetra: runtime ${entry.kind} error${code}${table}\n`);
|
|
1634
|
+
}
|
|
1635
|
+
function required(data) {
|
|
1636
|
+
if (data === void 0) throw new Error("invoke passes the data resource to a data tool");
|
|
1637
|
+
return data;
|
|
1638
|
+
}
|
|
1639
|
+
/**
|
|
1640
|
+
* Попередження компіляції, що стосуються об'єктів операції, і жодних
|
|
1641
|
+
* чужих: успішна модель може нести попередження про інші об'єкти проєкту, а
|
|
1642
|
+
* агентові по даних одного об'єкта вони лише шум. Об'єкт знаходиться за
|
|
1643
|
+
* файлом діагностики; невідомий об'єкт (його відхилить схема T3) нічого не
|
|
1644
|
+
* додає.
|
|
1645
|
+
*/
|
|
1646
|
+
function warningsFor(model, diagnostics, objects) {
|
|
1647
|
+
const files = new Set(model.objects.filter((x) => objects.some((o) => o.kind === x.kind && o.name === x.name)).map((x) => x.file));
|
|
1648
|
+
return diagnostics.filter((d) => d.severity === "warning" && files.has(d.file));
|
|
1649
|
+
}
|
|
1650
|
+
/**
|
|
1651
|
+
* Компіляція на кожен виклик (спека П4 §6.14): зміна теки між викликами дає нову
|
|
1652
|
+
* модель, і рантайм звіряє її хеш із застосованим — кешу, який треба
|
|
1653
|
+
* інвалідувати, немає.
|
|
1654
|
+
*/
|
|
1655
|
+
async function compileDir(dir) {
|
|
1656
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
1657
|
+
if (compiled.model === void 0) return { failed: {
|
|
1658
|
+
ok: false,
|
|
1659
|
+
changes: [],
|
|
1660
|
+
diagnostics: compiled.diagnostics
|
|
1661
|
+
} };
|
|
1662
|
+
return {
|
|
1663
|
+
model: compiled.model,
|
|
1664
|
+
diagnostics: compiled.diagnostics
|
|
1665
|
+
};
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* Рантайм на виклик: пул ролі входу, звірка хешу, дія й закриття пулу
|
|
1669
|
+
* (`withData`). `CommandFailure` — відповідь T3, тож дані результату, а не
|
|
1670
|
+
* збій; збій бази — `database.failed` лише з адресою й кодом.
|
|
1671
|
+
*/
|
|
1672
|
+
async function onRuntime(tool, ctx, model, warnings, act) {
|
|
1673
|
+
try {
|
|
1674
|
+
const ran = await withData(required(ctx.data), model.project.database.provider, async (s) => {
|
|
1675
|
+
try {
|
|
1676
|
+
return {
|
|
1677
|
+
ok: true,
|
|
1678
|
+
data: await act(await createCommandRuntime({
|
|
1679
|
+
database: s.database,
|
|
1680
|
+
catalog: buildRuntimeCatalog(model),
|
|
1681
|
+
log: logRuntimeEntry
|
|
1682
|
+
}), s.session)
|
|
1683
|
+
};
|
|
1684
|
+
} catch (error) {
|
|
1685
|
+
if (error instanceof CommandFailure) return {
|
|
1686
|
+
ok: false,
|
|
1687
|
+
data: { error: error.error }
|
|
1688
|
+
};
|
|
1689
|
+
throw error;
|
|
1690
|
+
}
|
|
1691
|
+
});
|
|
1692
|
+
return {
|
|
1693
|
+
ok: ran.ok,
|
|
1694
|
+
changes: [],
|
|
1695
|
+
diagnostics: warnings,
|
|
1696
|
+
data: ran.data
|
|
1697
|
+
};
|
|
1698
|
+
} catch (error) {
|
|
1699
|
+
if (error instanceof DataFailure) return {
|
|
1700
|
+
ok: false,
|
|
1701
|
+
changes: [],
|
|
1702
|
+
diagnostics: [diagnostic("database.failed", "", "", {
|
|
1703
|
+
tool,
|
|
1704
|
+
...error.params
|
|
1705
|
+
})]
|
|
1706
|
+
};
|
|
1707
|
+
throw error;
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
const dataReadTool = defineTool({
|
|
1711
|
+
name: "data-read",
|
|
1712
|
+
description: "Reads rows under RLS as the user given by --as: a card by id, a page by filter tree (where, orderBy, offset, limit up to 200) or a capped count. A card may carry its tabular sections; a card or a page may include the target rows of Ref attributes. A tabular section reads as the lines of one owner (with ownerVersion), a page or a count. BigInt values come as decimal strings. A runtime error comes as data.error with a code.",
|
|
1713
|
+
input: z.strictObject({ query: readQuerySchema }),
|
|
1714
|
+
files: "read",
|
|
1715
|
+
database: "none",
|
|
1716
|
+
data: "read",
|
|
1717
|
+
destructive: false,
|
|
1718
|
+
async run(ctx, input) {
|
|
1719
|
+
const compiled = await compileDir(ctx.dir);
|
|
1720
|
+
if ("failed" in compiled) return compiled.failed;
|
|
1721
|
+
return onRuntime("data-read", ctx, compiled.model, warningsFor(compiled.model, compiled.diagnostics, [input.query.object]), async (rt, session) => await createAgentCore({ runtime: rt }).read(session, input.query));
|
|
1722
|
+
},
|
|
1723
|
+
present: {
|
|
1724
|
+
structure: (data) => toJson(data),
|
|
1725
|
+
text: (data, v) => data === void 0 ? void 0 : [summarizeData("data-read", data), ...v.diagnostics.length > 0 ? [v.report] : []].join("\n")
|
|
1726
|
+
}
|
|
1727
|
+
});
|
|
1728
|
+
const dataCommandTool = defineTool({
|
|
1729
|
+
name: "data-command",
|
|
1730
|
+
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). A tabular section array in update replaces the section: every existing row must be in the array or in deleteIds. 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. Each result row has the shape of a read card: the tabular sections the operation wrote come under tabularSections. A runtime error comes as data.error with a code.",
|
|
1731
|
+
input: z.strictObject({ operations: batchSchema }),
|
|
1732
|
+
files: "read",
|
|
1733
|
+
database: "none",
|
|
1734
|
+
data: "write",
|
|
1735
|
+
destructive: false,
|
|
1736
|
+
async run(ctx, input) {
|
|
1737
|
+
const compiled = await compileDir(ctx.dir);
|
|
1738
|
+
if ("failed" in compiled) return compiled.failed;
|
|
1739
|
+
const { model } = compiled;
|
|
1740
|
+
const warnings = warningsFor(model, compiled.diagnostics, input.operations.map((op) => op.object));
|
|
1741
|
+
const catalog = buildRuntimeCatalog(model);
|
|
1742
|
+
const rightsWrite = ctx.allowRightsWrite === true;
|
|
1743
|
+
const refusal = dataPolicyRefusal(model, catalog, input.operations, { rightsWrite });
|
|
1744
|
+
if (refusal?.kind === "command") return {
|
|
1745
|
+
ok: false,
|
|
1746
|
+
changes: [],
|
|
1747
|
+
diagnostics: [],
|
|
1748
|
+
data: { error: refusal.error }
|
|
1749
|
+
};
|
|
1750
|
+
if (refusal !== void 0) return {
|
|
1751
|
+
ok: false,
|
|
1752
|
+
changes: [],
|
|
1753
|
+
diagnostics: [],
|
|
1754
|
+
refusalReason: "rights-write-disabled"
|
|
1755
|
+
};
|
|
1756
|
+
return onRuntime("data-command", ctx, model, warnings, async (rt, session) => {
|
|
1757
|
+
return { result: await createAgentCore({
|
|
1758
|
+
runtime: rt,
|
|
1759
|
+
permissions: { rightsWrite }
|
|
1760
|
+
}).execute(session, input.operations) };
|
|
1761
|
+
});
|
|
1762
|
+
},
|
|
1763
|
+
present: {
|
|
1764
|
+
structure: (data) => toJson(data),
|
|
1765
|
+
text: (data, v) => data === void 0 ? void 0 : [summarizeData("data-command", data), ...v.diagnostics.length > 0 ? [v.report] : []].join("\n")
|
|
1766
|
+
}
|
|
1767
|
+
});
|
|
1768
|
+
// src/tools/mutations.ts
|
|
1769
|
+
const completion = (dir) => ({
|
|
1770
|
+
schemaPath: schemaPathResolver(dir),
|
|
1771
|
+
newId: () => crypto.randomUUID()
|
|
1772
|
+
});
|
|
1773
|
+
/**
|
|
1774
|
+
* Тека читається заново на кожен виклик (стан — диск, не пам'ять процесу), а
|
|
1775
|
+
* в T1 іде лише валідований вхід операції. Запис і dry-run вирішує `invoke`.
|
|
1776
|
+
*/
|
|
1777
|
+
async function apply(dir, operation) {
|
|
1778
|
+
const result = await operation(await readMetadataDir(dir));
|
|
1779
|
+
return {
|
|
1780
|
+
ok: result.ok,
|
|
1781
|
+
...result.written === true ? { written: true } : {},
|
|
1782
|
+
changes: result.changes,
|
|
1783
|
+
diagnostics: result.diagnostics
|
|
1784
|
+
};
|
|
1785
|
+
}
|
|
1786
|
+
/**
|
|
1787
|
+
* Те саме для `promote`: запис промоції їде в `data` і артефактом у
|
|
1788
|
+
* `plans/<objectId>.promotion.json` — план бази читає його звідти (спека
|
|
1789
|
+
* промоції §7.1), бо мапінг у `metadata/` не лишається.
|
|
1790
|
+
*/
|
|
1791
|
+
async function applyPromotion(dir, operation) {
|
|
1792
|
+
const result = await operation(await readMetadataDir(dir));
|
|
1793
|
+
const { record } = result;
|
|
1794
|
+
return {
|
|
1795
|
+
ok: result.ok,
|
|
1796
|
+
changes: result.changes,
|
|
1797
|
+
diagnostics: result.diagnostics,
|
|
1798
|
+
...record === void 0 ? {} : {
|
|
1799
|
+
data: record,
|
|
1800
|
+
artifacts: [{
|
|
1801
|
+
path: `${PLANS_DIR}/${promotionFileName(record.objectId)}`,
|
|
1802
|
+
content: serializeCanonical(record)
|
|
1803
|
+
}]
|
|
1804
|
+
}
|
|
1805
|
+
};
|
|
1806
|
+
}
|
|
1807
|
+
const createTool = defineTool({
|
|
1808
|
+
name: "create",
|
|
1809
|
+
description: "Create a metadata object; ids and physical names are assigned. Writes when the result compiles without errors, or when its only errors are repair-class errors the directory already had (then ok is false and written is true).",
|
|
1810
|
+
input: createObjectInput,
|
|
1811
|
+
files: "write",
|
|
1812
|
+
database: "none",
|
|
1813
|
+
data: "none",
|
|
1814
|
+
destructive: false,
|
|
1815
|
+
run: ({ dir }, input) => apply(dir, (files) => createObject(files, input, completion(dir)))
|
|
1816
|
+
});
|
|
1817
|
+
const addTool = defineTool({
|
|
1818
|
+
name: "add",
|
|
1819
|
+
description: "Add a named element (attribute, tabular section, value, scope kind, ...) to a collection of an object or of the project root. Writes when the result compiles without errors, or when its only errors are repair-class errors the directory already had (then ok is false and written is true).",
|
|
1820
|
+
input: addElementInput,
|
|
1821
|
+
files: "write",
|
|
1822
|
+
database: "none",
|
|
1823
|
+
data: "none",
|
|
1824
|
+
destructive: false,
|
|
1825
|
+
run: ({ dir }, input) => apply(dir, (files) => addElement(files, input, completion(dir)))
|
|
1826
|
+
});
|
|
1827
|
+
const declareFunctionTool = defineTool({
|
|
1828
|
+
name: "declare-function",
|
|
1829
|
+
description: "Create or replace the declaration (callers, check) of one SQL function of a sibling .sql file; the id of an existing record is kept. Refused for a function that is a platform form, overloaded or missing. Writes when the result compiles without errors, or when its only errors are repair-class errors the directory already had or the target's own check-not-applied (the body lacks the guard that fix inserts; then ok is false and written is true). Roles that gain EXECUTE are named in a warning.",
|
|
1830
|
+
input: declareFunctionInput,
|
|
1831
|
+
files: "write",
|
|
1832
|
+
database: "none",
|
|
1833
|
+
data: "none",
|
|
1834
|
+
destructive: false,
|
|
1835
|
+
run: ({ dir }, input) => apply(dir, (files) => declareFunction(files, input, completion(dir)))
|
|
1836
|
+
});
|
|
1837
|
+
const renameTool = defineTool({
|
|
1838
|
+
name: "rename",
|
|
1839
|
+
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.",
|
|
1840
|
+
input: renameInput,
|
|
1841
|
+
files: "write",
|
|
1842
|
+
database: "none",
|
|
1843
|
+
data: "none",
|
|
1844
|
+
destructive: false,
|
|
1845
|
+
run: ({ dir }, input) => apply(dir, (files) => renameElement(files, input))
|
|
1846
|
+
});
|
|
1847
|
+
const deleteTool = defineTool({
|
|
1848
|
+
name: "delete",
|
|
1849
|
+
description: "Delete an object or a nested element. Refused while anything references it.",
|
|
1850
|
+
input: deleteInput,
|
|
1851
|
+
files: "write",
|
|
1852
|
+
database: "none",
|
|
1853
|
+
data: "none",
|
|
1854
|
+
destructive: true,
|
|
1855
|
+
run: ({ dir }, input) => apply(dir, (files) => deleteElement(files, input))
|
|
1856
|
+
});
|
|
1857
|
+
const promoteTool = defineTool({
|
|
1858
|
+
name: "promote",
|
|
1859
|
+
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.",
|
|
1860
|
+
input: promoteInput,
|
|
1861
|
+
files: "write",
|
|
1862
|
+
database: "none",
|
|
1863
|
+
data: "none",
|
|
1864
|
+
destructive: false,
|
|
1865
|
+
present: {
|
|
1866
|
+
structure: (record) => ({ record }),
|
|
1867
|
+
appendix: (record, v) => v.channel === "cli" ? renderPromotion(record, v.written) : ["promotion record:", JSON.stringify(record, null, 2)].join("\n")
|
|
1868
|
+
},
|
|
1869
|
+
run: ({ dir }, input) => applyPromotion(dir, (files) => promoteObject(files, input, completion(dir)))
|
|
1870
|
+
});
|
|
1871
|
+
// src/tools/read.ts
|
|
1872
|
+
const compileTool = defineTool({
|
|
1873
|
+
name: "compile",
|
|
1874
|
+
description: "Compile the metadata directory and return diagnostics. Reads the disk on every call; writes nothing.",
|
|
1875
|
+
input: z.strictObject({}),
|
|
1876
|
+
files: "read",
|
|
1877
|
+
database: "none",
|
|
1878
|
+
data: "none",
|
|
1879
|
+
destructive: false,
|
|
1880
|
+
present: { diagnosticsOnly: true },
|
|
1881
|
+
async run({ dir, baseline }) {
|
|
1882
|
+
const result = await compile(await readMetadataDir(dir), baseline === void 0 ? void 0 : { baseline });
|
|
1883
|
+
return {
|
|
1884
|
+
ok: result.ok,
|
|
1885
|
+
changes: [],
|
|
1886
|
+
diagnostics: result.diagnostics,
|
|
1887
|
+
data: { model: result.model }
|
|
1888
|
+
};
|
|
1889
|
+
}
|
|
1890
|
+
});
|
|
1891
|
+
const explainInput = z.strictObject({
|
|
1892
|
+
kind: metadataKindSchema.optional(),
|
|
1893
|
+
name: objectNameSchema.optional(),
|
|
1894
|
+
function: z.strictObject({
|
|
1895
|
+
schema: z.string().min(1).optional(),
|
|
1896
|
+
name: z.string().min(1)
|
|
1897
|
+
}).optional()
|
|
1898
|
+
}).refine((i) => i.function === void 0 ? i.kind !== void 0 && i.name !== void 0 : i.kind === void 0 && i.name === void 0, { message: "Give either kind and name, or function." });
|
|
1899
|
+
const explainTool = defineTool({
|
|
1900
|
+
name: "explain",
|
|
1901
|
+
description: "Explain an object (kind, name; metadata must compile) or a SQL function (function: schema, name): callers, EXECUTE roles per provider, declared check, whether the body applies it.",
|
|
1902
|
+
input: explainInput,
|
|
1903
|
+
files: "read",
|
|
1904
|
+
database: "none",
|
|
1905
|
+
data: "none",
|
|
1906
|
+
destructive: false,
|
|
1907
|
+
async run({ dir }, { kind, name, function: fn }) {
|
|
1908
|
+
const files = await readMetadataDir(dir);
|
|
1909
|
+
if (fn !== void 0) {
|
|
1910
|
+
const result = await compile(files, { repair: true });
|
|
1911
|
+
if (result.model === void 0) return {
|
|
1912
|
+
ok: false,
|
|
1913
|
+
changes: [],
|
|
1914
|
+
diagnostics: result.diagnostics
|
|
1915
|
+
};
|
|
1916
|
+
const schema = fn.schema ?? result.model.project.defaultSchema;
|
|
1917
|
+
const explanation = explainFunction(result, {
|
|
1918
|
+
schema,
|
|
1919
|
+
name: fn.name
|
|
1920
|
+
});
|
|
1921
|
+
if (explanation === void 0) return {
|
|
1922
|
+
ok: false,
|
|
1923
|
+
changes: [],
|
|
1924
|
+
diagnostics: result.diagnostics,
|
|
1925
|
+
refusal: `Function not found: ${schema}.${fn.name}`
|
|
1926
|
+
};
|
|
1927
|
+
return {
|
|
1928
|
+
ok: true,
|
|
1929
|
+
changes: [],
|
|
1930
|
+
diagnostics: result.diagnostics,
|
|
1931
|
+
data: explanation
|
|
1932
|
+
};
|
|
1933
|
+
}
|
|
1934
|
+
const result = await compile(files);
|
|
1935
|
+
if (result.model === void 0) return {
|
|
1936
|
+
ok: false,
|
|
1937
|
+
changes: [],
|
|
1938
|
+
diagnostics: result.diagnostics
|
|
1939
|
+
};
|
|
1940
|
+
const explanation = explainObject(result.model, {
|
|
1941
|
+
kind,
|
|
1942
|
+
name
|
|
1943
|
+
});
|
|
1944
|
+
if (explanation === void 0) return {
|
|
1945
|
+
ok: false,
|
|
1946
|
+
changes: [],
|
|
1947
|
+
diagnostics: result.diagnostics,
|
|
1948
|
+
refusal: `Object not found: ${kind} ${name}`
|
|
1949
|
+
};
|
|
1950
|
+
return {
|
|
1951
|
+
ok: true,
|
|
1952
|
+
changes: [],
|
|
1953
|
+
diagnostics: result.diagnostics,
|
|
1954
|
+
data: explanation
|
|
1955
|
+
};
|
|
1956
|
+
},
|
|
1957
|
+
present: {
|
|
1958
|
+
bare: true,
|
|
1959
|
+
text: (data, v) => data === void 0 ? void 0 : v.channel === "mcp" ? JSON.stringify(data, null, 2) : "function" in data ? renderFunctionExplanation(data) : renderExplanation(data).trimEnd()
|
|
1960
|
+
}
|
|
1961
|
+
});
|
|
1962
|
+
const fixTool = defineTool({
|
|
1963
|
+
name: "fix",
|
|
1964
|
+
description: "Assign missing ids and physical names, set $schema and canonical form; repair function declarations (ids, call guard, default privileges). Writes when the result compiles, or when it removes repair-class errors and adds none (ok false, written true).",
|
|
1965
|
+
input: z.strictObject({}),
|
|
1966
|
+
files: "write",
|
|
1967
|
+
database: "none",
|
|
1968
|
+
data: "none",
|
|
1969
|
+
destructive: false,
|
|
1970
|
+
async run({ dir }) {
|
|
1971
|
+
const result = await fixFiles(await readMetadataDir(dir), {
|
|
1972
|
+
schemaPath: schemaPathResolver(dir),
|
|
1973
|
+
newId: () => crypto.randomUUID()
|
|
1974
|
+
});
|
|
1975
|
+
return {
|
|
1976
|
+
ok: result.ok,
|
|
1977
|
+
...result.written === true ? { written: true } : {},
|
|
1978
|
+
changes: result.changes,
|
|
1979
|
+
diagnostics: result.diagnostics
|
|
1980
|
+
};
|
|
1981
|
+
}
|
|
1982
|
+
});
|
|
1983
|
+
// src/tools/rights-maintenance-tool.ts
|
|
1984
|
+
const id = z.string().regex(UUID_TEXT, "expected a UUID");
|
|
1985
|
+
const role = z.string().min(1);
|
|
1986
|
+
/**
|
|
1987
|
+
* Вхід — JSON, одна дія на запуск: `strictObject` не пропускає поля
|
|
1988
|
+
* іншої дії, тож помилка написання не перетвориться на тиху іншу дію.
|
|
1989
|
+
*/
|
|
1990
|
+
const input = z.discriminatedUnion("action", [
|
|
1991
|
+
z.strictObject({
|
|
1992
|
+
action: z.literal("firstGlobalAssignment"),
|
|
1993
|
+
user: id,
|
|
1994
|
+
role
|
|
1995
|
+
}),
|
|
1996
|
+
z.strictObject({
|
|
1997
|
+
action: z.literal("restoreGlobalFullAccess"),
|
|
1998
|
+
user: id,
|
|
1999
|
+
role: role.optional()
|
|
2000
|
+
}),
|
|
2001
|
+
z.strictObject({
|
|
2002
|
+
action: z.literal("tenantFullAccess"),
|
|
2003
|
+
scopeKind: z.string().min(1),
|
|
2004
|
+
scope: id,
|
|
2005
|
+
user: id,
|
|
2006
|
+
role,
|
|
2007
|
+
member: z.record(z.string(), z.unknown()).optional()
|
|
2008
|
+
})
|
|
2009
|
+
]);
|
|
2010
|
+
/**
|
|
2011
|
+
* Аварійний вхід у права поза командами (спека П4 §6.12): режим
|
|
2012
|
+
* обслуговування бази діє лише для входу мігратора, тож інструмент — лише
|
|
2013
|
+
* командний рядок і лише з `--yes`; агент через MCP його не бачить.
|
|
2014
|
+
*/
|
|
2015
|
+
const rightsMaintenanceTool = defineTool({
|
|
2016
|
+
name: "rights-maintenance",
|
|
2017
|
+
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.",
|
|
2018
|
+
input,
|
|
2019
|
+
files: "read",
|
|
2020
|
+
database: "write",
|
|
2021
|
+
data: "none",
|
|
2022
|
+
destructive: true,
|
|
2023
|
+
cliOnly: true,
|
|
2024
|
+
async run({ dir, database }, request) {
|
|
2025
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
2026
|
+
const model = compiled.model;
|
|
2027
|
+
if (model === void 0) return {
|
|
2028
|
+
ok: false,
|
|
2029
|
+
changes: [],
|
|
2030
|
+
diagnostics: compiled.diagnostics
|
|
2031
|
+
};
|
|
2032
|
+
const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
|
|
2033
|
+
const ran = await withDatabase(required$1(database), "rights-maintenance", (db) => runRightsMaintenance(createApplyDatabase({ readOnly: false }), db.target, model, request));
|
|
2034
|
+
if (!ran.ok) return {
|
|
2035
|
+
ok: false,
|
|
2036
|
+
changes: [],
|
|
2037
|
+
diagnostics: failureDiagnostics(ran)
|
|
2038
|
+
};
|
|
2039
|
+
if (!ran.value.ok) return {
|
|
2040
|
+
ok: false,
|
|
2041
|
+
changes: [],
|
|
2042
|
+
diagnostics: [fromEngine(ran.value.diagnostic)]
|
|
2043
|
+
};
|
|
2044
|
+
return {
|
|
2045
|
+
ok: true,
|
|
2046
|
+
changes: [],
|
|
2047
|
+
diagnostics: [],
|
|
2048
|
+
data: ran.value.done
|
|
2049
|
+
};
|
|
2050
|
+
},
|
|
2051
|
+
present: { text: (data) => data === void 0 ? void 0 : `assigned ${data.assignment}${data.member === void 0 ? "" : ` to member ${data.member}`}` }
|
|
2052
|
+
});
|
|
2053
|
+
// src/tools/roles-tool.ts
|
|
2054
|
+
const PROJECT_FILE$1 = "project.meta.json";
|
|
2055
|
+
/**
|
|
2056
|
+
* Набір ролей теки проєкту (спека П4 §6.2): провайдер — з файлу проєкту, тим самим
|
|
2057
|
+
* читачем, що й `compile`. Без файлу ролі входу пропускаються явно — пропуск
|
|
2058
|
+
* видно у виводі, бо без провайдера невідомо, членом яких ролей запиту
|
|
2059
|
+
* роль рантайму мусить бути.
|
|
2060
|
+
*/
|
|
2061
|
+
async function projectRoleSet(dir) {
|
|
2062
|
+
const text = existsSync(dir) ? (await readMetadataDir(dir)).get(PROJECT_FILE$1) : void 0;
|
|
2063
|
+
if (text === void 0) return {
|
|
2064
|
+
ok: true,
|
|
2065
|
+
provider: void 0,
|
|
2066
|
+
roles: platformRoleSet(void 0),
|
|
2067
|
+
skipped: Object.values(PLATFORM_LOGIN_ROLES).map((name) => ({
|
|
2068
|
+
name,
|
|
2069
|
+
reason: "no-project-file"
|
|
2070
|
+
}))
|
|
2071
|
+
};
|
|
2072
|
+
const read = readProjectFile(text);
|
|
2073
|
+
if (read.project === void 0) return {
|
|
2074
|
+
ok: false,
|
|
2075
|
+
diagnostics: read.diagnostics
|
|
2076
|
+
};
|
|
2077
|
+
return {
|
|
2078
|
+
ok: true,
|
|
2079
|
+
provider: read.project.database.provider,
|
|
2080
|
+
roles: platformRoleSet(read.project.database.provider),
|
|
2081
|
+
skipped: []
|
|
2082
|
+
};
|
|
2083
|
+
}
|
|
2084
|
+
/** Ім'я бази з адреси цілі; порожнє, коли адреса бази не називає. */
|
|
2085
|
+
function databaseOf(url) {
|
|
2086
|
+
try {
|
|
2087
|
+
return decodeURIComponent(new URL(url).pathname.replace(/^\//, ""));
|
|
2088
|
+
} catch {
|
|
2089
|
+
return "";
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
/**
|
|
2093
|
+
* Підсумок підготовки кластера як рядки інструмента: створене й наявне — за іменем, а
|
|
2094
|
+
* доповнене членство — на рядку самої ролі входу (`present` з `added`), а не
|
|
2095
|
+
* окремою «роллю».
|
|
2096
|
+
*/
|
|
2097
|
+
function clusterRoles(value) {
|
|
2098
|
+
const outcome = (names, kind) => names.map((name) => {
|
|
2099
|
+
const parents = value.added?.find((a) => a.role === name)?.parents;
|
|
2100
|
+
return {
|
|
2101
|
+
server: "target",
|
|
2102
|
+
name,
|
|
2103
|
+
outcome: kind,
|
|
2104
|
+
...parents === void 0 ? {} : { added: parents }
|
|
2105
|
+
};
|
|
2106
|
+
});
|
|
2107
|
+
return [...outcome(value.created, "created"), ...outcome(value.present, "present")];
|
|
2108
|
+
}
|
|
2109
|
+
/**
|
|
2110
|
+
* Готує ролі (і, у профілі `postgres`, кластер) за провайдером проєкту.
|
|
2111
|
+
* `postgres` готує суперкористувач через службову базу того самого сервера,
|
|
2112
|
+
* ціль і шаблон; окремий сервер тіней там не підтримано.
|
|
2113
|
+
* Решта провайдерів і проєкт без файлу — ролі на цілі й на сервері тіні.
|
|
2114
|
+
*/
|
|
2115
|
+
async function runRoles(dbs, db, project) {
|
|
2116
|
+
if (project.provider === "postgres") {
|
|
2117
|
+
if (db.shadowBase !== void 0) return {
|
|
2118
|
+
roles: [],
|
|
2119
|
+
skipped: [],
|
|
2120
|
+
diagnostics: [diagnostic("plan.shadow-base-unsupported", "", "")]
|
|
2121
|
+
};
|
|
2122
|
+
const database = databaseOf(db.target.url);
|
|
2123
|
+
if (database === "") return {
|
|
2124
|
+
roles: [],
|
|
2125
|
+
skipped: [],
|
|
2126
|
+
diagnostics: [diagnostic("database.failed", "", "", {
|
|
2127
|
+
tool: "roles",
|
|
2128
|
+
database: db.describe,
|
|
2129
|
+
error: "the database address names no database"
|
|
2130
|
+
})]
|
|
2131
|
+
};
|
|
2132
|
+
const set = postgresClusterSet(database);
|
|
2133
|
+
const { withDatabaseName } = await import("@supabase/pg-delta");
|
|
2134
|
+
const result = await ensurePostgresCluster(dbs, {
|
|
2135
|
+
maintenance: { url: withDatabaseName(db.target.url, "postgres") },
|
|
2136
|
+
target: db.target,
|
|
2137
|
+
template: { url: withDatabaseName(db.target.url, set.template) }
|
|
2138
|
+
}, set);
|
|
2139
|
+
if (!result.ok) return {
|
|
2140
|
+
roles: [],
|
|
2141
|
+
skipped: [],
|
|
2142
|
+
diagnostics: result.error.map(fromEngine)
|
|
2143
|
+
};
|
|
2144
|
+
return {
|
|
2145
|
+
roles: clusterRoles(result.value),
|
|
2146
|
+
skipped: result.value.skipped.map((name) => ({
|
|
2147
|
+
name,
|
|
2148
|
+
reason: "identity-table-missing"
|
|
2149
|
+
})),
|
|
2150
|
+
diagnostics: []
|
|
2151
|
+
};
|
|
2152
|
+
}
|
|
2153
|
+
const ran = await ensurePlatformRoles(dbs, [{
|
|
2154
|
+
server: "target",
|
|
2155
|
+
db: db.target
|
|
2156
|
+
}, ...db.shadowBase === void 0 ? [] : [{
|
|
2157
|
+
server: "shadow",
|
|
2158
|
+
db: db.shadowBase
|
|
2159
|
+
}]], project.roles);
|
|
2160
|
+
return {
|
|
2161
|
+
roles: ran.created,
|
|
2162
|
+
skipped: [],
|
|
2163
|
+
diagnostics: (ran.refusal ?? []).map(fromEngine)
|
|
2164
|
+
};
|
|
2165
|
+
}
|
|
2166
|
+
/**
|
|
2167
|
+
* Платформні ролі кластерні, тож у бажаному стані бази їх немає, і план їх
|
|
2168
|
+
* не створює (спека П4 §6.2, спека designer §3.2): їх створює окремий крок з правом
|
|
2169
|
+
* `CREATEROLE`. Ролі грантів задає платформа; файл проєкту потрібен лише
|
|
2170
|
+
* ролі входу — її членство в ролі запиту залежить від провайдера.
|
|
2171
|
+
*/
|
|
2172
|
+
const rolesTool = defineTool({
|
|
2173
|
+
name: "roles",
|
|
2174
|
+
description: "Create the platform roles: NOLOGIN roles that generated SQL grants to on the target and the shadow server, and the login roles (the runtime and the signals consumer) on the target only, each a member of its parents WITH INHERIT FALSE, SET TRUE; the signals login role also gets a role setting (ALTER ROLE … SET) that makes its consumer group the role of every new session. Reads the project file for `database.provider`; without a project file the login roles are skipped, and the output says so. An existing role is only checked, its role setting included; the one change it makes is to add a missing membership of an existing login role in a parent of its profile, WITH INHERIT FALSE, SET TRUE, and the output names it. Needs CREATEROLE, and ADMIN OPTION on every parent role of a login role (without it that login role alone is refused, a missing membership with the GRANT statement to run); refuses before creating anything when a server lacks CREATEROLE or a role has an unsafe shape. With the provider `postgres` it prepares the cluster instead, as a superuser (the database URL is a superuser URL of the target database): the owner, auth, grant and request roles, the target database owned by the owner, the schemas `extensions` and `better_auth`, `plpgsql_check`, and the sealed template database for shadows. It refuses before writing when the session is not a superuser, an existing database or role has an unsafe shape, or a Simetra login role can connect to another database; a separate shadow server is not supported there.",
|
|
2175
|
+
input: z.strictObject({}),
|
|
2176
|
+
files: "read",
|
|
2177
|
+
database: "write",
|
|
2178
|
+
data: "none",
|
|
2179
|
+
destructive: false,
|
|
2180
|
+
async run({ dir, database }) {
|
|
2181
|
+
const set = await projectRoleSet(dir);
|
|
2182
|
+
if (!set.ok) return {
|
|
2183
|
+
ok: false,
|
|
2184
|
+
changes: [],
|
|
2185
|
+
diagnostics: set.diagnostics
|
|
2186
|
+
};
|
|
2187
|
+
const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
|
|
2188
|
+
const ran = await withDatabase(required$1(database), "roles", (db) => runRoles(createApplyDatabase({ readOnly: false }), db, set));
|
|
2189
|
+
if (!ran.ok) return {
|
|
2190
|
+
ok: false,
|
|
2191
|
+
changes: [],
|
|
2192
|
+
diagnostics: failureDiagnostics(ran)
|
|
2193
|
+
};
|
|
2194
|
+
const data = {
|
|
2195
|
+
roles: ran.value.roles,
|
|
2196
|
+
skipped: [...set.skipped, ...ran.value.skipped]
|
|
2197
|
+
};
|
|
2198
|
+
return {
|
|
2199
|
+
ok: ran.value.diagnostics.length === 0,
|
|
2200
|
+
changes: [],
|
|
2201
|
+
diagnostics: ran.value.diagnostics,
|
|
2202
|
+
data
|
|
2203
|
+
};
|
|
2204
|
+
},
|
|
2205
|
+
present: { text: (data, v) => data === void 0 || v.channel === "mcp" ? void 0 : [
|
|
2206
|
+
...data.roles.map((x) => `${x.server}: ${x.name} ${x.outcome}${x.added === void 0 ? "" : `; added membership in ${x.added.join(", ")}`}`),
|
|
2207
|
+
...data.skipped.map((x) => {
|
|
2208
|
+
if (x.reason === "no-project-file") return `target: ${x.name} skipped: the directory has no project.meta.json, so database.provider is unknown; run roles in a metadata directory with a project file to create it`;
|
|
2209
|
+
const at = x.name.lastIndexOf(":");
|
|
2210
|
+
return `target: ${x.name.slice(0, at)}: ${x.name.slice(at + 1)} not granted yet — run the Better Auth migration, then simetra roles again`;
|
|
2211
|
+
}),
|
|
2212
|
+
...v.diagnostics.length > 0 ? [v.report] : []
|
|
2213
|
+
].join("\n") }
|
|
2214
|
+
});
|
|
2215
|
+
// src/tools/signals-config.ts
|
|
2216
|
+
const PROJECT_FILE = "project.meta.json";
|
|
2217
|
+
/** Name of the outbox consumer in the Centrifugo config (postgres profile spec §6.1). */
|
|
2218
|
+
const SIGNAL_CONSUMER_NAME = "simetra_outbox";
|
|
2219
|
+
/**
|
|
2220
|
+
* Environment variables that give the consumer its DSNs (postgres profile spec
|
|
2221
|
+
* §10.1): Centrifugo overrides the consumer declared in the config with them,
|
|
2222
|
+
* so the password of `simetra_signals` never lands in the config file.
|
|
2223
|
+
*/
|
|
2224
|
+
const SIGNAL_CONSUMER_ENV = {
|
|
2225
|
+
dsn: "CENTRIFUGO_CONSUMERS_SIMETRA_OUTBOX_POSTGRESQL_DSN",
|
|
2226
|
+
notificationDsn: "CENTRIFUGO_CONSUMERS_SIMETRA_OUTBOX_POSTGRESQL_PARTITION_NOTIFICATION_DSN"
|
|
2227
|
+
};
|
|
2228
|
+
const NAMESPACES = [
|
|
2229
|
+
{
|
|
2230
|
+
name: "simetra",
|
|
2231
|
+
historySize: 100
|
|
2232
|
+
},
|
|
2233
|
+
{
|
|
2234
|
+
name: "simetra-rights",
|
|
2235
|
+
historySize: 20
|
|
2236
|
+
},
|
|
2237
|
+
{
|
|
2238
|
+
name: "simetra-user",
|
|
2239
|
+
historySize: 20
|
|
2240
|
+
}
|
|
2241
|
+
];
|
|
2242
|
+
const PRESENCE_UPDATE_INTERVAL = "5s";
|
|
2243
|
+
const EXPIRED_SUB_CLOSE_DELAY = "25s";
|
|
2244
|
+
const EXPIRED_CLOSE_DELAY = "25s";
|
|
2245
|
+
const HISTORY_TTL = "300s";
|
|
2246
|
+
const HISTORY_META_TTL = "24h";
|
|
2247
|
+
const RECOVERY_MAX_PUBLICATION_LIMIT = 300;
|
|
2248
|
+
const OUTBOX_TABLE = `${quoteIdent(SIGNAL_OUTBOX.schema)}.${quoteIdent(SIGNAL_OUTBOX.name)}`;
|
|
2249
|
+
/**
|
|
2250
|
+
* Centrifugo v6 config of one application (postgres profile spec §6.1, §5.3):
|
|
2251
|
+
* three namespaces with history and forced recovery, no client permission,
|
|
2252
|
+
* the outbox consumer with empty DSNs (they come from `SIGNAL_CONSUMER_ENV`),
|
|
2253
|
+
* the HTTP API off. No `http_server`: the address is the deployment's choice.
|
|
2254
|
+
*/
|
|
2255
|
+
function centrifugoConfig(o) {
|
|
2256
|
+
return {
|
|
2257
|
+
client: {
|
|
2258
|
+
allowed_origins: [o.origin],
|
|
2259
|
+
token: {
|
|
2260
|
+
jwks_public_endpoint: o.jwksUrl,
|
|
2261
|
+
audience: `centrifugo:${o.projectName}`,
|
|
2262
|
+
issuer: o.issuer
|
|
2263
|
+
},
|
|
2264
|
+
recovery_max_publication_limit: RECOVERY_MAX_PUBLICATION_LIMIT,
|
|
2265
|
+
presence_update_interval: PRESENCE_UPDATE_INTERVAL,
|
|
2266
|
+
expired_sub_close_delay: EXPIRED_SUB_CLOSE_DELAY,
|
|
2267
|
+
expired_close_delay: EXPIRED_CLOSE_DELAY
|
|
2268
|
+
},
|
|
2269
|
+
channel: {
|
|
2270
|
+
max_length: CENTRIFUGO_CHANNEL_MAX,
|
|
2271
|
+
without_namespace: {},
|
|
2272
|
+
namespaces: NAMESPACES.map((n) => ({
|
|
2273
|
+
name: n.name,
|
|
2274
|
+
history_size: n.historySize,
|
|
2275
|
+
history_ttl: HISTORY_TTL,
|
|
2276
|
+
history_meta_ttl: HISTORY_META_TTL,
|
|
2277
|
+
force_recovery: true
|
|
2278
|
+
}))
|
|
2279
|
+
},
|
|
2280
|
+
consumers: [{
|
|
2281
|
+
enabled: true,
|
|
2282
|
+
name: SIGNAL_CONSUMER_NAME,
|
|
2283
|
+
type: "postgresql",
|
|
2284
|
+
postgresql: {
|
|
2285
|
+
dsn: "",
|
|
2286
|
+
partition_notification_dsn: "",
|
|
2287
|
+
outbox_table_name: OUTBOX_TABLE,
|
|
2288
|
+
num_partitions: 1,
|
|
2289
|
+
partition_select_limit: 100,
|
|
2290
|
+
partition_poll_interval: `300ms`,
|
|
2291
|
+
partition_notification_channel: SIGNAL_NOTIFY_CHANNEL,
|
|
2292
|
+
use_try_lock: true
|
|
2293
|
+
}
|
|
2294
|
+
}],
|
|
2295
|
+
http_api: { disabled: true },
|
|
2296
|
+
health: { enabled: true },
|
|
2297
|
+
log: { level: "info" }
|
|
2298
|
+
};
|
|
2299
|
+
}
|
|
2300
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2301
|
+
function object(shape) {
|
|
2302
|
+
return (value, path) => {
|
|
2303
|
+
if (!isRecord(value)) return [`${path}: expected an object`];
|
|
2304
|
+
const extra = Object.keys(value).filter((key) => !Object.hasOwn(shape, key)).map((key) => `${path}.${key}: not an allowed option`);
|
|
2305
|
+
const own = Object.entries(shape).flatMap(([key, rule]) => Object.hasOwn(value, key) ? rule(value[key], `${path}.${key}`) : [`${path}.${key}: missing`]);
|
|
2306
|
+
return [...extra, ...own];
|
|
2307
|
+
};
|
|
2308
|
+
}
|
|
2309
|
+
const exactly = (expected) => (value, path) => value === expected ? [] : [`${path}: must be ${JSON.stringify(expected)}, got ${JSON.stringify(value)}`];
|
|
2310
|
+
const int = (min, max = Number.MAX_SAFE_INTEGER) => (value, path) => Number.isInteger(value) && value >= min && value <= max ? [] : [`${path}: must be an integer from ${min} to ${max}`];
|
|
2311
|
+
const duration = (value, path) => typeof value === "string" && /^\d+(ms|s|m|h)$/.test(value) ? [] : [`${path}: must be a duration such as "300s"`];
|
|
2312
|
+
const DURATION_MS = {
|
|
2313
|
+
ms: 1,
|
|
2314
|
+
s: 1e3,
|
|
2315
|
+
m: 6e4,
|
|
2316
|
+
h: 36e5
|
|
2317
|
+
};
|
|
2318
|
+
const durationMs = (value) => {
|
|
2319
|
+
const [, amount, unit] = /^(\d+)(ms|s|m|h)$/.exec(value);
|
|
2320
|
+
return Number(amount) * DURATION_MS[unit];
|
|
2321
|
+
};
|
|
2322
|
+
const durationAtMost = (bound) => (value, path) => duration(value, path).length === 0 && durationMs(value) > 0 && durationMs(value) <= durationMs(bound) ? [] : [`${path}: must be a positive duration not above ${bound}`];
|
|
2323
|
+
const nonEmpty = (value, path) => typeof value === "string" && value.trim() !== "" ? [] : [`${path}: must be a non-empty string`];
|
|
2324
|
+
const origin = (value, path) => {
|
|
2325
|
+
if (typeof value === "string" && URL.canParse(value)) {
|
|
2326
|
+
const url = new URL(value);
|
|
2327
|
+
if ((url.protocol === "https:" || url.protocol === "http:") && url.origin === value) return [];
|
|
2328
|
+
}
|
|
2329
|
+
return [`${path}: must be an http(s) origin, got ${JSON.stringify(value)}`];
|
|
2330
|
+
};
|
|
2331
|
+
const LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/;
|
|
2332
|
+
const SERVICE_NAME = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/i;
|
|
2333
|
+
/**
|
|
2334
|
+
* JWKS лише через TLS чи внутрішню адресу (спека профілю §6.3): підміна
|
|
2335
|
+
* відповіді JWKS дала б токен на будь-який канал.
|
|
2336
|
+
*/
|
|
2337
|
+
const jwksUrl = (value, path) => {
|
|
2338
|
+
const refused = [`${path}: must be an https: URL, or http: on a loopback address or a single-label service name, got ${JSON.stringify(value)}`];
|
|
2339
|
+
if (typeof value !== "string" || !URL.canParse(value)) return refused;
|
|
2340
|
+
const url = new URL(value);
|
|
2341
|
+
if (url.username !== "" || url.password !== "") return refused;
|
|
2342
|
+
if (url.protocol === "https:") return [];
|
|
2343
|
+
if (url.protocol !== "http:") return refused;
|
|
2344
|
+
return LOOPBACK_HOST.test(url.hostname) || SERVICE_NAME.test(url.hostname) && !/^\d+$/.test(url.hostname) ? [] : refused;
|
|
2345
|
+
};
|
|
2346
|
+
const namespace = object({
|
|
2347
|
+
name: nonEmpty,
|
|
2348
|
+
history_size: int(1),
|
|
2349
|
+
history_ttl: duration,
|
|
2350
|
+
history_meta_ttl: duration,
|
|
2351
|
+
force_recovery: exactly(true)
|
|
2352
|
+
});
|
|
2353
|
+
const namespaces = (value, path) => {
|
|
2354
|
+
if (!Array.isArray(value)) return [`${path}: expected an array`];
|
|
2355
|
+
const own = value.flatMap((n, i) => namespace(n, `${path}[${i}]`));
|
|
2356
|
+
const names = value.map((n) => isRecord(n) ? n.name : void 0);
|
|
2357
|
+
const expected = NAMESPACES.map((n) => n.name);
|
|
2358
|
+
const set = names.length === expected.length && expected.every((name) => names.includes(name)) ? [] : [`${path}: must be exactly the namespaces ${expected.join(", ")}`];
|
|
2359
|
+
const simetra = value.find((n) => isRecord(n) && n.name === "simetra");
|
|
2360
|
+
const history = isRecord(simetra) && Number.isInteger(simetra.history_size) && simetra.history_size < SIGNAL_MERGE_THRESHOLD + 1 ? [`${path}: history_size of simetra must be at least ${SIGNAL_MERGE_THRESHOLD + 1} (the default signal merge threshold + 1)`] : [];
|
|
2361
|
+
return [
|
|
2362
|
+
...own,
|
|
2363
|
+
...set,
|
|
2364
|
+
...history
|
|
2365
|
+
];
|
|
2366
|
+
};
|
|
2367
|
+
const consumer = object({
|
|
2368
|
+
enabled: exactly(true),
|
|
2369
|
+
name: exactly(SIGNAL_CONSUMER_NAME),
|
|
2370
|
+
type: exactly("postgresql"),
|
|
2371
|
+
postgresql: object({
|
|
2372
|
+
dsn: exactly(""),
|
|
2373
|
+
partition_notification_dsn: exactly(""),
|
|
2374
|
+
outbox_table_name: exactly(OUTBOX_TABLE),
|
|
2375
|
+
num_partitions: exactly(1),
|
|
2376
|
+
partition_select_limit: int(1),
|
|
2377
|
+
partition_poll_interval: duration,
|
|
2378
|
+
partition_notification_channel: exactly(SIGNAL_NOTIFY_CHANNEL),
|
|
2379
|
+
use_try_lock: exactly(true)
|
|
2380
|
+
})
|
|
2381
|
+
});
|
|
2382
|
+
const consumers = (value, path) => Array.isArray(value) && value.length === 1 ? consumer(value[0], `${path}[0]`) : [`${path}: must hold exactly the consumer ${SIGNAL_CONSUMER_NAME}`];
|
|
2383
|
+
const config = object({
|
|
2384
|
+
client: object({
|
|
2385
|
+
allowed_origins: (value, path) => Array.isArray(value) && value.length > 0 ? value.flatMap((o, i) => origin(o, `${path}[${i}]`)) : [`${path}: must list at least one origin`],
|
|
2386
|
+
token: object({
|
|
2387
|
+
jwks_public_endpoint: jwksUrl,
|
|
2388
|
+
audience: (value, path) => typeof value === "string" && /^centrifugo:\S+$/.test(value) ? [] : [`${path}: must be centrifugo:<project name>`],
|
|
2389
|
+
issuer: nonEmpty
|
|
2390
|
+
}),
|
|
2391
|
+
recovery_max_publication_limit: int(1),
|
|
2392
|
+
presence_update_interval: durationAtMost(PRESENCE_UPDATE_INTERVAL),
|
|
2393
|
+
expired_sub_close_delay: durationAtMost(EXPIRED_SUB_CLOSE_DELAY),
|
|
2394
|
+
expired_close_delay: durationAtMost(EXPIRED_CLOSE_DELAY)
|
|
2395
|
+
}),
|
|
2396
|
+
channel: object({
|
|
2397
|
+
max_length: int(1, CENTRIFUGO_CHANNEL_MAX),
|
|
2398
|
+
without_namespace: object({}),
|
|
2399
|
+
namespaces
|
|
2400
|
+
}),
|
|
2401
|
+
consumers,
|
|
2402
|
+
http_api: object({ disabled: exactly(true) }),
|
|
2403
|
+
health: object({ enabled: exactly(true) }),
|
|
2404
|
+
log: object({ level: exactly("info") })
|
|
2405
|
+
});
|
|
2406
|
+
/**
|
|
2407
|
+
* Refusals of a Centrifugo config (P4-B block B2, invariant 11): every level
|
|
2408
|
+
* is a whitelist of keys, so a client permission (`allow_*_for_*`,
|
|
2409
|
+
* anonymous connect, presence), an insecure or admin mode, a secret
|
|
2410
|
+
* (`hmac_secret_key`, a DSN), another listener (`http_server`, `grpc_api`)
|
|
2411
|
+
* or an open origin is refused. Empty for the output of `centrifugoConfig`.
|
|
2412
|
+
*/
|
|
2413
|
+
function centrifugoConfigRefusals(value) {
|
|
2414
|
+
return config(value, "config");
|
|
2415
|
+
}
|
|
2416
|
+
// src/tools/catalog.ts
|
|
2417
|
+
/** Єдиний каталог інструментів: CLI, MCP і студія — лише його адаптери. */
|
|
2418
|
+
const TOOLS = [
|
|
2419
|
+
compileTool,
|
|
2420
|
+
explainTool,
|
|
2421
|
+
fixTool,
|
|
2422
|
+
createTool,
|
|
2423
|
+
addTool,
|
|
2424
|
+
declareFunctionTool,
|
|
2425
|
+
renameTool,
|
|
2426
|
+
deleteTool,
|
|
2427
|
+
promoteTool,
|
|
2428
|
+
introspectTool,
|
|
2429
|
+
diffTool,
|
|
2430
|
+
planTool,
|
|
2431
|
+
applyTool,
|
|
2432
|
+
rolesTool,
|
|
2433
|
+
rightsMaintenanceTool,
|
|
2434
|
+
defineTool({
|
|
2435
|
+
name: "signals-config",
|
|
2436
|
+
description: `Generate the Centrifugo v6 config of the project's signals: three namespaces with history and forced recovery, no client permission, the outbox consumer, the HTTP API off. Input is JSON {origin, issuer, jwksUrl}: origin — the browser origin of the application; issuer — the host origin, the iss of every token (the audience is centrifugo:<project name>); jwksUrl — the JWKS address of the host, https: or http: on a loopback address or a single-label service name. The config holds no secret: set ${SIGNAL_CONSUMER_ENV.dsn} and ${SIGNAL_CONSUMER_ENV.notificationDsn} to the DSN of the login role simetra_signals (a direct connection; a pooler only in session mode) in the environment of Centrifugo. Run exactly one Centrifugo per application. The HTTP listener is the deployment's choice (CENTRIFUGO_HTTP_SERVER_ADDRESS, CENTRIFUGO_HTTP_SERVER_PORT). Refuses a config that breaks the whitelist.`,
|
|
2437
|
+
input: z.strictObject({
|
|
2438
|
+
origin: z.string(),
|
|
2439
|
+
issuer: z.string(),
|
|
2440
|
+
jwksUrl: z.string()
|
|
2441
|
+
}),
|
|
2442
|
+
files: "read",
|
|
2443
|
+
database: "none",
|
|
2444
|
+
data: "none",
|
|
2445
|
+
destructive: false,
|
|
2446
|
+
async run({ dir }, input) {
|
|
2447
|
+
const text = (await readMetadataDir(dir)).get(PROJECT_FILE);
|
|
2448
|
+
if (text === void 0) return {
|
|
2449
|
+
ok: false,
|
|
2450
|
+
changes: [],
|
|
2451
|
+
diagnostics: [diagnostic("project.missing", PROJECT_FILE, "")]
|
|
2452
|
+
};
|
|
2453
|
+
const read = readProjectFile(text);
|
|
2454
|
+
if (read.project === void 0) return {
|
|
2455
|
+
ok: false,
|
|
2456
|
+
changes: [],
|
|
2457
|
+
diagnostics: read.diagnostics
|
|
2458
|
+
};
|
|
2459
|
+
const config = centrifugoConfig({
|
|
2460
|
+
projectName: read.project.name,
|
|
2461
|
+
...input
|
|
2462
|
+
});
|
|
2463
|
+
const refusals = centrifugoConfigRefusals(config);
|
|
2464
|
+
if (refusals.length > 0) return {
|
|
2465
|
+
ok: false,
|
|
2466
|
+
changes: [],
|
|
2467
|
+
diagnostics: [],
|
|
2468
|
+
refusal: refusals.join("\n")
|
|
2469
|
+
};
|
|
2470
|
+
return {
|
|
2471
|
+
ok: true,
|
|
2472
|
+
changes: [],
|
|
2473
|
+
diagnostics: [],
|
|
2474
|
+
data: {
|
|
2475
|
+
config,
|
|
2476
|
+
environment: [SIGNAL_CONSUMER_ENV.dsn, SIGNAL_CONSUMER_ENV.notificationDsn]
|
|
2477
|
+
}
|
|
2478
|
+
};
|
|
2479
|
+
},
|
|
2480
|
+
present: { text: (data) => data === void 0 ? void 0 : JSON.stringify(data.config, null, 2) }
|
|
2481
|
+
}),
|
|
2482
|
+
dataReadTool,
|
|
2483
|
+
dataCommandTool
|
|
2484
|
+
];
|
|
2485
|
+
/**
|
|
2486
|
+
* Поля `data` інструмента у структурованому результаті обох каналів: їх
|
|
2487
|
+
* вирішує `tool.present`, не ім'я інструмента.
|
|
2488
|
+
*/
|
|
2489
|
+
function structureOf(tool, data) {
|
|
2490
|
+
return tool.present?.structure?.(data) ?? data;
|
|
2491
|
+
}
|
|
2492
|
+
/**
|
|
2493
|
+
* Що з результату показують канали: єдиний розв'язок для CLI і MCP. `data`
|
|
2494
|
+
* не показується, коли в інструмента нема `present`, коли він лише
|
|
2495
|
+
* діагностичний (`compile`: модель — не відповідь агентові, вона ~МБ) і коли
|
|
2496
|
+
* `bare`-результат не `ok`. Інструмент осі `artifact` показується й без
|
|
2497
|
+
* `data`: відмова теж має артефакти.
|
|
2498
|
+
*/
|
|
2499
|
+
function presentation(tool, r) {
|
|
2500
|
+
const p = tool.present;
|
|
2501
|
+
const shown = p !== void 0 && p.diagnosticsOnly !== true && (p.bare === true ? r.ok && r.data !== void 0 : r.data !== void 0 || tool.files === "artifact");
|
|
2502
|
+
return {
|
|
2503
|
+
shown,
|
|
2504
|
+
data: shown ? r.data : void 0
|
|
2505
|
+
};
|
|
2506
|
+
}
|
|
2507
|
+
function toolByName(name) {
|
|
2508
|
+
return TOOLS.find((t) => t.name === name);
|
|
2509
|
+
}
|
|
2510
|
+
// src/tools/queue.ts
|
|
2511
|
+
const tails = /* @__PURE__ */ new Map();
|
|
2512
|
+
/**
|
|
2513
|
+
* Черга викликів однієї теки метаданих. Адаптери (MCP-сервер, CLI) можуть
|
|
2514
|
+
* слати виклики паралельно, тож без черги дві мутації читали б той самий стан
|
|
2515
|
+
* і друга мовчки затирала б першу, а записана комбінація двох результатів не
|
|
2516
|
+
* проходила б компіляцію. Читальні інструменти стоять у тій самій черзі:
|
|
2517
|
+
* `writeChanges` пише файли по одному, і компіляція посеред запису побачила б
|
|
2518
|
+
* напівзаписане дерево. Ціна — послідовні компіляції; вони короткі, а
|
|
2519
|
+
* коректність відповіді важливіша за паралелізм. Ключ — розв'язаний шлях, щоб
|
|
2520
|
+
* `./metadata` і абсолютний шлях ділили одну чергу.
|
|
2521
|
+
*/
|
|
2522
|
+
function queueFor(dir) {
|
|
2523
|
+
const key = resolve(dir);
|
|
2524
|
+
return (task) => {
|
|
2525
|
+
const run = (tails.get(key) ?? Promise.resolve()).then(task);
|
|
2526
|
+
const tail = run.catch(() => void 0);
|
|
2527
|
+
tails.set(key, tail);
|
|
2528
|
+
tail.then(() => {
|
|
2529
|
+
if (tails.get(key) === tail) tails.delete(key);
|
|
2530
|
+
});
|
|
2531
|
+
return run;
|
|
2532
|
+
};
|
|
2533
|
+
}
|
|
2534
|
+
// src/tools/invoke.ts
|
|
2535
|
+
/**
|
|
2536
|
+
* Вичерпні switch по всіх осях: нове значення осі не компілюється, доки не
|
|
2537
|
+
* вирішено його дозвіл. `--read-only` вимикає будь-який запис; запис у базу
|
|
2538
|
+
* й запис даних ще й потребують рішення людини при запуску
|
|
2539
|
+
* (`allowDatabaseWrite`, `allowDataWrite`), а власне тертя (підтвердження з
|
|
2540
|
+
* показаним планом) — ознака `destructive`.
|
|
2541
|
+
*/
|
|
2542
|
+
function permits(tool, o) {
|
|
2543
|
+
const files = tool.files;
|
|
2544
|
+
const database = tool.database;
|
|
2545
|
+
const data = tool.data;
|
|
2546
|
+
let filesOk;
|
|
2547
|
+
switch (files) {
|
|
2548
|
+
case "read":
|
|
2549
|
+
filesOk = true;
|
|
2550
|
+
break;
|
|
2551
|
+
case "artifact":
|
|
2552
|
+
case "write": filesOk = !o.readOnly;
|
|
2553
|
+
}
|
|
2554
|
+
let databaseOk;
|
|
2555
|
+
switch (database) {
|
|
2556
|
+
case "none":
|
|
2557
|
+
case "read":
|
|
2558
|
+
databaseOk = true;
|
|
2559
|
+
break;
|
|
2560
|
+
case "write": databaseOk = !o.readOnly && o.allowDatabaseWrite;
|
|
2561
|
+
}
|
|
2562
|
+
let dataOk;
|
|
2563
|
+
switch (data) {
|
|
2564
|
+
case "none":
|
|
2565
|
+
case "read":
|
|
2566
|
+
dataOk = true;
|
|
2567
|
+
break;
|
|
2568
|
+
case "write": dataOk = !o.readOnly && o.allowDataWrite === true;
|
|
2569
|
+
}
|
|
2570
|
+
return filesOk && databaseOk && dataOk;
|
|
2571
|
+
}
|
|
2572
|
+
/**
|
|
2573
|
+
* Артефакт пишеться лише в `plans/` кореня проєкту (спека designer §3.2);
|
|
2574
|
+
* будь-який інший шлях — помилка інструмента, і перевіряється вона до
|
|
2575
|
+
* першого запису.
|
|
2576
|
+
*/
|
|
2577
|
+
function checkArtifacts(root, artifacts) {
|
|
2578
|
+
const plans = resolve(root, PLANS_DIR) + sep;
|
|
2579
|
+
for (const a of artifacts) {
|
|
2580
|
+
if (a.content === null) throw new UsageError(`An artifact must never delete a file: ${a.path}`);
|
|
2581
|
+
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}`);
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2584
|
+
function refused(reason, message, detail) {
|
|
2585
|
+
return {
|
|
2586
|
+
ok: false,
|
|
2587
|
+
written: false,
|
|
2588
|
+
changes: [],
|
|
2589
|
+
diagnostics: [],
|
|
2590
|
+
refusal: {
|
|
2591
|
+
reason,
|
|
2592
|
+
message,
|
|
2593
|
+
...detail === void 0 ? {} : { detail }
|
|
2594
|
+
}
|
|
2595
|
+
};
|
|
2596
|
+
}
|
|
2597
|
+
/**
|
|
2598
|
+
* Єдине місце рішень про розбір входу, дозволи, підтвердження й запис:
|
|
2599
|
+
* адаптери (CLI, MCP) лише переказують результат. Порядок має значення —
|
|
2600
|
+
* відмова на кожному кроці гарантує, що далі диск не чіпають.
|
|
2601
|
+
*/
|
|
2602
|
+
async function invoke(tool, input, o) {
|
|
2603
|
+
if (tool.cliOnly && o.channel !== "cli") return refused("cli-only", `${tool.name} is available only from the command line. Nothing changed.`);
|
|
2604
|
+
const parsed = tool.input.safeParse(input);
|
|
2605
|
+
if (!parsed.success) return refused("invalid-input", parsed.error.issues.map((i) => i.path.length === 0 ? i.message : `${i.path.join(".")}: ${i.message}`).join("; "));
|
|
2606
|
+
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.`);
|
|
2607
|
+
if (!permits(tool, o)) {
|
|
2608
|
+
if (permits(tool, {
|
|
2609
|
+
...o,
|
|
2610
|
+
allowDatabaseWrite: true
|
|
2611
|
+
})) return refused("database-write-disabled", databaseWriteHint(o.launchArgs, { tools: tool.name }));
|
|
2612
|
+
if (permits(tool, {
|
|
2613
|
+
...o,
|
|
2614
|
+
allowDataWrite: true
|
|
2615
|
+
})) return refused("data-write-disabled", dataWriteHint(o.launchArgs, { tools: tool.name }));
|
|
2616
|
+
return refused("read-only", readOnlyHint(o.launchArgs));
|
|
2617
|
+
}
|
|
2618
|
+
if (tool.database !== "none" && o.database === void 0) return refused("no-database", noDatabaseHint(o.databaseEnv ?? "SIMETRA_DATABASE_URL", o.channel));
|
|
2619
|
+
if (tool.data !== "none" && o.data === void 0) return refused("no-data", noDataHint(o.dataEnv, o.channel));
|
|
2620
|
+
if (tool.destructive && !o.dryRun && !o.confirmed) return refused("unconfirmed", `${tool.name} is destructive and needs confirmation. Nothing changed.`);
|
|
2621
|
+
const root = dirname(resolve(o.dir));
|
|
2622
|
+
return queueFor(o.dir)(async () => {
|
|
2623
|
+
try {
|
|
2624
|
+
const outcome = await tool.run({
|
|
2625
|
+
dir: o.dir,
|
|
2626
|
+
root,
|
|
2627
|
+
...tool.database === "none" ? {} : { database: o.database },
|
|
2628
|
+
...tool.data === "none" ? {} : { data: o.data },
|
|
2629
|
+
...tool.data === "write" ? { allowRightsWrite: o.allowRightsWrite === true } : {},
|
|
2630
|
+
...o.baseline === void 0 ? {} : { baseline: o.baseline }
|
|
2631
|
+
}, parsed.data);
|
|
2632
|
+
if (outcome.refusalReason === "rights-write-disabled") return refused("rights-write-disabled", rightsWriteHint(o.launchArgs, o.channel));
|
|
2633
|
+
const artifacts = outcome.artifacts ?? [];
|
|
2634
|
+
checkArtifacts(root, artifacts);
|
|
2635
|
+
let write = false;
|
|
2636
|
+
let writeArtifacts = false;
|
|
2637
|
+
let wouldWrite = false;
|
|
2638
|
+
switch (tool.files) {
|
|
2639
|
+
case "read": break;
|
|
2640
|
+
case "artifact":
|
|
2641
|
+
writeArtifacts = outcome.ok && artifacts.length > 0;
|
|
2642
|
+
break;
|
|
2643
|
+
case "write": {
|
|
2644
|
+
const accepted = outcome.ok || outcome.written === true;
|
|
2645
|
+
write = accepted && !o.dryRun && outcome.changes.length > 0;
|
|
2646
|
+
writeArtifacts = accepted && !o.dryRun && artifacts.length > 0;
|
|
2647
|
+
wouldWrite = accepted && o.dryRun && (outcome.changes.length > 0 || artifacts.length > 0);
|
|
2648
|
+
break;
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
if (writeArtifacts) await writeChanges(root, artifacts);
|
|
2652
|
+
if (write) await writeChanges(o.dir, outcome.changes);
|
|
2653
|
+
return {
|
|
2654
|
+
ok: outcome.ok,
|
|
2655
|
+
written: write || writeArtifacts,
|
|
2656
|
+
...wouldWrite ? { wouldWrite: true } : {},
|
|
2657
|
+
changes: outcome.changes.map((c) => ({
|
|
2658
|
+
path: c.path,
|
|
2659
|
+
deleted: c.content === null
|
|
2660
|
+
})),
|
|
2661
|
+
diagnostics: outcome.diagnostics,
|
|
2662
|
+
...outcome.data === void 0 ? {} : { data: outcome.data },
|
|
2663
|
+
...outcome.artifacts === void 0 ? {} : { artifacts: outcome.artifacts.map((a) => a.path) },
|
|
2664
|
+
...outcome.refusal === void 0 ? {} : { refusal: {
|
|
2665
|
+
reason: "refused",
|
|
2666
|
+
message: outcome.refusal
|
|
2667
|
+
} }
|
|
2668
|
+
};
|
|
2669
|
+
} catch (error) {
|
|
2670
|
+
if (error instanceof DataGuardRefusal) return refused("data-guard", error.message, error.detail);
|
|
2671
|
+
if (error instanceof UsageError) return refused("refused", error.message);
|
|
2672
|
+
throw error;
|
|
2673
|
+
}
|
|
2674
|
+
});
|
|
2675
|
+
}
|
|
2676
|
+
export { toolByName as a, writeChanges as c, parseDataLaunch as d, databaseResource as f, structureOf as i, checkEnvName as l, TOOLS as n, formatDiagnostics as o, presentation as r, isMetadataFile as s, invoke as t, dataResource as u };
|