@simetrajs/designer 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -4
- package/dist/{command-CRUaUglx.js → command-BCAw6Fsb.js} +81 -17
- package/dist/default-dir-DerxTbci.js +158 -0
- package/dist/{errors-D5pJLrjP.js → errors-Brw6UjAD.js} +1 -2
- package/dist/init-jr0Xsrpp.js +832 -0
- package/dist/main.js +6 -6
- package/dist/{mcp-CJDCleh-.js → mcp-ChltmHBb.js} +108 -72
- package/dist/mcp-args-D63akJ97.js +56 -0
- package/dist/package-Dg3MXPve.js +4 -0
- package/dist/{report-D2jBS_04.js → report-DV4deFdu.js} +733 -224
- package/dist/{schema-engine-DAsJEc8K.js → schema-engine-DPPnife2.js} +82 -78
- package/dist/{types-CSc8XWLd.js → types-iWavtmdS.js} +6 -3
- package/package.json +12 -11
- package/skills/simetra-adoption/SKILL.md +15 -1
- package/skills/simetra-metadata/SKILL.md +71 -68
- package/skills/simetra-metadata/references/agents-over-mcp.md +119 -0
- package/skills/simetra-metadata/references/object-modules.md +60 -0
- package/skills/simetra-metadata/references/people-and-rights.md +609 -8
- package/skills/simetra-metadata/references/project-setup.md +28 -0
- package/skills/simetra-metadata/references/sql-trust-boundary.md +194 -0
- package/dist/package-DDuGk6yE.js +0 -5
|
@@ -1,24 +1,42 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { r as defineTool, t as PLANS_DIR } from "./types-
|
|
3
|
-
import {
|
|
2
|
+
import { r as defineTool, t as PLANS_DIR } from "./types-iWavtmdS.js";
|
|
3
|
+
import { a as dataWriteHint, c as noDatabaseHint, d as installedPackageDir, f as posixRelative, l as readOnlyHint, o as databaseWriteHint, p as UsageError, s as noDataHint, u as rightsWriteHint } from "./default-dir-DerxTbci.js";
|
|
4
|
+
import { n as ShadowServerError, r as ShadowServerMismatchError, t as ShadowCreateRefusedError } from "./errors-Brw6UjAD.js";
|
|
4
5
|
import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
5
|
-
import { dirname, join,
|
|
6
|
-
import { ATTRIBUTE_CASES, DATABASE_PROVIDERS, PLATFORM_SCHEMA, SQL_DEBT_FILE, logicalTypeOf, metadataKindSchema, objectNameSchema, quoteIdent } from "simetra/model";
|
|
7
|
-
import { ApplyConnectionLost, ApplyDbError, FINGERPRINT_VERSION, LOCK_MODE_SQL, PLATFORM_VERSION,
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
6
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
7
|
+
import { ATTRIBUTE_CASES, DATABASE_PROVIDERS, KIND_REGISTRY, PLATFORM_LOGIN_ROLES, PLATFORM_ROLES, PLATFORM_SCHEMA, PROVIDER_API_ROLES, PROVIDER_SCHEMAS, SQL_DEBT_FILE, UUID_TEXT, batchSchema, logicalTypeOf, metadataKindSchema, objectNameSchema, quoteIdent, readQuerySchema } from "simetra/model";
|
|
8
|
+
import { ApplyConnectionLost, ApplyDbError, FINGERPRINT_VERSION, LOCK_MODE_SQL, PLATFORM_VERSION, applyStateOf, buildPlan, checkOwnerMembership, checkPermissions, checkPlatformRoles, compareWithDesired, desiredForApply, engineScope, ensurePlatformRoles, executePlan, parsePlan, parseRehearsal, planFileName, platformRoleSet, rehearsalFileName, rehearsalReport, reverseGenerate, runRightsMaintenance, serializePlan, serializeRehearsal, verifyPlanHash } from "simetra/schema";
|
|
9
|
+
import pg from "pg";
|
|
10
|
+
import { CommandFailure, createCommandRuntime, fromPgPool, readRoleOf } from "simetra/server";
|
|
11
|
+
import { ZodError, z } from "zod";
|
|
12
|
+
import { addElement, addElementInput, buildRuntimeCatalog, canonicalSnapshot, compile, createObject, createObjectInput, deleteElement, deleteInput, diagnostic, explainObject, fixFiles, loadSqlParser, localize, promoteInput, promoteObject, promotionFileName, promotionRecordSchema, readProjectFile, renameElement, renameInput, serializeCanonical } from "simetra/compiler";
|
|
10
13
|
import { existsSync } from "node:fs";
|
|
11
|
-
|
|
14
|
+
// src/io/data-guard-refusal.ts
|
|
12
15
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
+
* Тексти не називають ні рядка підключення, ні ролі входу: відмова йде
|
|
17
|
+
* агентові й у журнали клієнта. Пізніша версія — П4-F (спека П4 §6.14);
|
|
18
|
+
* назву віхи споживачеві не показуємо.
|
|
16
19
|
*/
|
|
17
|
-
|
|
18
|
-
|
|
20
|
+
const MESSAGES = {
|
|
21
|
+
"not-local": "Data tools work only with a development database on this machine: the connection string must point to localhost, a 127.x.x.x address, ::1 or a unix socket. Agent access to other databases comes in a later version. Nothing changed.",
|
|
22
|
+
"not-development": "The database is not marked as a development database: the database-level setting simetra.environment = 'development' is missing. A superuser sets it on the local development database only. Agent access to other databases comes in a later version. Nothing changed.",
|
|
23
|
+
"login-refused": "The connection string must use the runtime login role: a role that is not a superuser, does not bypass row-level security, is neither the migrator nor the provider service role, and may switch to the platform command role. Nothing changed."
|
|
19
24
|
};
|
|
20
|
-
|
|
21
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Відмова запобіжника бази розробника. Окремий легкий модуль: його
|
|
27
|
+
* імпортує `invoke.ts`, і він не мусить тягнути `pg` чи ярус сервера.
|
|
28
|
+
* Запобіжники ловлять випадковий запуск, а не межа безпеки: межа —
|
|
29
|
+
* облікові дані ролі входу рантайму (спека П4 §6.14).
|
|
30
|
+
*/
|
|
31
|
+
var DataGuardRefusal = class extends UsageError {
|
|
32
|
+
detail;
|
|
33
|
+
name = "DataGuardRefusal";
|
|
34
|
+
constructor(detail) {
|
|
35
|
+
super(MESSAGES[detail]);
|
|
36
|
+
this.detail = detail;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
// src/io/database.ts
|
|
22
40
|
/**
|
|
23
41
|
* Відмова виклику бази з текстом, який уже безпечно показати: без рядка
|
|
24
42
|
* підключення, користувача й пароля. Помилка використання — викликач може
|
|
@@ -81,7 +99,7 @@ const UNREACHABLE = /* @__PURE__ */ new Set([
|
|
|
81
99
|
* бувають п'ятисимвольними, а класу SQLSTATE на `E` у Postgres немає.
|
|
82
100
|
*/
|
|
83
101
|
const NODE_CODE = /^E[A-Z_]+$/;
|
|
84
|
-
const SQLSTATE = /^[0-9A-Z]{5}$/;
|
|
102
|
+
const SQLSTATE$1 = /^[0-9A-Z]{5}$/;
|
|
85
103
|
/**
|
|
86
104
|
* Збій драйвера без коду, що означає втрачене чи не встановлене з'єднання.
|
|
87
105
|
* Текст лише розпізнається, ніколи не цитується.
|
|
@@ -162,7 +180,7 @@ function classify(error, names, note) {
|
|
|
162
180
|
}
|
|
163
181
|
};
|
|
164
182
|
}
|
|
165
|
-
if (code !== void 0 && SQLSTATE.test(code)) {
|
|
183
|
+
if (code !== void 0 && SQLSTATE$1.test(code)) {
|
|
166
184
|
if (code.startsWith("28")) return refused(`Authentication to the database at ${describe} failed. Check the user and password in the connection string.`);
|
|
167
185
|
if (code.startsWith("08")) return refused(`The connection to the database at ${describe} failed (SQLSTATE ${code}).`);
|
|
168
186
|
if (code === "3D000") return refused(`The database at ${describe} does not exist.`);
|
|
@@ -227,8 +245,221 @@ async function withDatabase(resource, tool, fn) {
|
|
|
227
245
|
};
|
|
228
246
|
}
|
|
229
247
|
}
|
|
230
|
-
|
|
231
|
-
|
|
248
|
+
// src/io/data.ts
|
|
249
|
+
/**
|
|
250
|
+
* Ознака бази розробника — налаштування рівня бази, яке ставить оператор
|
|
251
|
+
* (`ALTER DATABASE … SET` від суперкористувача). Сесійне `options=-c …` чи
|
|
252
|
+
* налаштування ролі її не дають: їх може задати сам рядок підключення.
|
|
253
|
+
*/
|
|
254
|
+
const DEVELOPMENT_ENVIRONMENT = {
|
|
255
|
+
setting: "simetra.environment",
|
|
256
|
+
value: "development"
|
|
257
|
+
};
|
|
258
|
+
const IPV4_LOOPBACK = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
|
|
259
|
+
/**
|
|
260
|
+
* Хост, який візьме `pg`, — машина розробника: `localhost`, петля IPv4
|
|
261
|
+
* `127.0.0.0/8`, `::1` чи шлях unix-сокета. DNS не розв'язується: ім'я, що
|
|
262
|
+
* лише вказує на петлю, — уже не «ця машина» за формою рядка.
|
|
263
|
+
*/
|
|
264
|
+
function isLocalHost(host) {
|
|
265
|
+
if (host === void 0 || host === "") return false;
|
|
266
|
+
if (host.startsWith("/")) return true;
|
|
267
|
+
const h = host.toLowerCase();
|
|
268
|
+
if (h === "localhost" || h === "::1") return true;
|
|
269
|
+
const m = IPV4_LOOPBACK.exec(h);
|
|
270
|
+
return m !== null && m.slice(1).every((octet) => Number(octet) <= 255);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Факти ролі входу й ознаки бази одним оператором. Роль перевіряється
|
|
274
|
+
* фактами, не іменем: ім'я `simetra_runtime` не доводить, що роль не
|
|
275
|
+
* суперкористувач і не мігратор. Відсутня в кластері роль команд дає
|
|
276
|
+
* `false`, а не `42704`, — підзапит з `COALESCE`.
|
|
277
|
+
*/
|
|
278
|
+
const DATA_GUARD_FACTS_SQL = `SELECT r.rolsuper, r.rolbypassrls,
|
|
279
|
+
COALESCE((SELECT pg_catalog.pg_has_role(session_user, c.oid, 'SET')
|
|
280
|
+
FROM pg_catalog.pg_roles c WHERE c.rolname = $1), false) AS command,
|
|
281
|
+
COALESCE(pg_catalog.pg_has_role(session_user, n.nspowner, 'MEMBER'), false) AS migrator,
|
|
282
|
+
COALESCE((SELECT pg_catalog.pg_has_role(session_user, s.oid, 'MEMBER')
|
|
283
|
+
FROM pg_catalog.pg_roles s WHERE s.rolname = $2), false) AS service,
|
|
284
|
+
EXISTS (SELECT FROM pg_catalog.pg_db_role_setting d
|
|
285
|
+
JOIN pg_catalog.pg_database b ON b.oid = d.setdatabase
|
|
286
|
+
WHERE b.datname = pg_catalog.current_database() AND d.setrole = 0
|
|
287
|
+
AND $3 = ANY (d.setconfig)) AS development
|
|
288
|
+
FROM pg_catalog.pg_roles r
|
|
289
|
+
LEFT JOIN pg_catalog.pg_namespace n ON n.nspname = $4
|
|
290
|
+
WHERE r.rolname = session_user`;
|
|
291
|
+
/** Параметри {@link DATA_GUARD_FACTS_SQL} для профілю провайдера. */
|
|
292
|
+
function dataGuardFactsParams(provider) {
|
|
293
|
+
return [
|
|
294
|
+
PLATFORM_ROLES.command,
|
|
295
|
+
PROVIDER_API_ROLES[provider].service,
|
|
296
|
+
`${DEVELOPMENT_ENVIRONMENT.setting}=${DEVELOPMENT_ENVIRONMENT.value}`,
|
|
297
|
+
PLATFORM_SCHEMA
|
|
298
|
+
];
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Claims сесії інструмента: права — користувача `--as`, агент лише
|
|
302
|
+
* названий в `act` (RFC 8693) і прав не дає.
|
|
303
|
+
*/
|
|
304
|
+
function dataSession(provider, o) {
|
|
305
|
+
const role = readRoleOf(provider);
|
|
306
|
+
return {
|
|
307
|
+
sub: o.as,
|
|
308
|
+
...role === void 0 ? {} : { role },
|
|
309
|
+
...o.agent === void 0 ? {} : { act: { sub: o.agent } }
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Запит фактів сирим клієнтом пулу (булеві — `boolean`, а не текст порту
|
|
314
|
+
* рантайму) у транзакції лише читання. Клієнт звільняється до повернення:
|
|
315
|
+
* за `max: 1` незвільнений клієнт заблокував би рантайм.
|
|
316
|
+
*/
|
|
317
|
+
async function checkGuards(pool, provider) {
|
|
318
|
+
const client = await pool.connect();
|
|
319
|
+
client.on("error", () => {});
|
|
320
|
+
let facts;
|
|
321
|
+
let broken = false;
|
|
322
|
+
try {
|
|
323
|
+
await client.query("BEGIN READ ONLY");
|
|
324
|
+
const { rows } = await client.query(DATA_GUARD_FACTS_SQL, dataGuardFactsParams(provider));
|
|
325
|
+
await client.query("COMMIT");
|
|
326
|
+
facts = rows[0];
|
|
327
|
+
} catch (error) {
|
|
328
|
+
broken = true;
|
|
329
|
+
throw error;
|
|
330
|
+
} finally {
|
|
331
|
+
client.release(broken);
|
|
332
|
+
}
|
|
333
|
+
if (facts === void 0 || facts.rolsuper || facts.rolbypassrls || facts.migrator || facts.service || !facts.command) throw new DataGuardRefusal("login-refused");
|
|
334
|
+
if (!facts.development) throw new DataGuardRefusal("not-development");
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Ресурс даних з імені змінної, зафіксованого при запуску. Порожня змінна —
|
|
338
|
+
* ресурсу немає, `invoke` відмовить `no-data`. Пул — на виклик (`open`), і
|
|
339
|
+
* кожен виклик заново проходить запобіжники.
|
|
340
|
+
*/
|
|
341
|
+
function dataResource(env, o) {
|
|
342
|
+
const url = env[o.urlEnv];
|
|
343
|
+
if (url === void 0 || url === "") return void 0;
|
|
344
|
+
return {
|
|
345
|
+
describe: describeConnection(url),
|
|
346
|
+
as: o.as,
|
|
347
|
+
...o.agent === void 0 ? {} : { agent: o.agent },
|
|
348
|
+
async open(provider) {
|
|
349
|
+
let host;
|
|
350
|
+
try {
|
|
351
|
+
host = new pg.Client({ connectionString: url }).host;
|
|
352
|
+
} catch {
|
|
353
|
+
throw new DatabaseRefusal(`The connection string in ${o.urlEnv} is not a valid URL. Nothing changed.`);
|
|
354
|
+
}
|
|
355
|
+
if (!isLocalHost(host)) throw new DataGuardRefusal("not-local");
|
|
356
|
+
const pool = new pg.Pool({
|
|
357
|
+
connectionString: url,
|
|
358
|
+
max: 1
|
|
359
|
+
});
|
|
360
|
+
pool.on("error", () => {});
|
|
361
|
+
try {
|
|
362
|
+
await checkGuards(pool, provider);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
await pool.end().catch(() => {});
|
|
365
|
+
throw error;
|
|
366
|
+
}
|
|
367
|
+
return {
|
|
368
|
+
database: fromPgPool(pool),
|
|
369
|
+
session: dataSession(provider, o),
|
|
370
|
+
close: () => pool.end()
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Збій роботи з базою даних виклику: лише параметри `database.failed`
|
|
377
|
+
* (адреса й код), без `cause` і тексту драйвера, — `run` інструмента
|
|
378
|
+
* повертає їх діагностикою.
|
|
379
|
+
*/
|
|
380
|
+
var DataFailure = class extends Error {
|
|
381
|
+
params;
|
|
382
|
+
name = "DataFailure";
|
|
383
|
+
constructor(params) {
|
|
384
|
+
super("database.failed");
|
|
385
|
+
this.params = params;
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
/** Межа помилок `withData`: правило `withDatabase`, плюс власні відмови й вади. */
|
|
389
|
+
function boundary(error, describe) {
|
|
390
|
+
if (error instanceof DataGuardRefusal || error instanceof ZodError || isProgramBug(error)) return error;
|
|
391
|
+
const c = classifyDatabaseError(error, { target: describe });
|
|
392
|
+
if (c.kind === "refusal") return new DatabaseRefusal(c.message);
|
|
393
|
+
const { sqlstate, ...rest } = c.params;
|
|
394
|
+
return new DataFailure(sqlstate === void 0 ? rest : {
|
|
395
|
+
...rest,
|
|
396
|
+
sqlstate
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Сесія даних одного виклику — єдина межа помилок бази для інструментів
|
|
401
|
+
* даних. `CommandFailure` до неї не доходить: `fn` повертає її як дані.
|
|
402
|
+
* Пул закривається тут, у `finally`, на будь-якому результаті.
|
|
403
|
+
*/
|
|
404
|
+
async function withData(resource, provider, fn) {
|
|
405
|
+
let session;
|
|
406
|
+
try {
|
|
407
|
+
session = await resource.open(provider);
|
|
408
|
+
} catch (error) {
|
|
409
|
+
throw boundary(error, resource.describe);
|
|
410
|
+
}
|
|
411
|
+
let result;
|
|
412
|
+
try {
|
|
413
|
+
result = await fn(session);
|
|
414
|
+
} catch (error) {
|
|
415
|
+
await closeQuietly(session);
|
|
416
|
+
throw boundary(error, resource.describe);
|
|
417
|
+
}
|
|
418
|
+
await closeQuietly(session);
|
|
419
|
+
return result;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Закриття пулу — поза межею результату: після успішного `fn` команда вже
|
|
423
|
+
* закомічена, тож збій закриття не має підміняти ні результат, ні помилку
|
|
424
|
+
* `fn`. У журнал — лише факт, без тексту драйвера (він несе ім'я входу).
|
|
425
|
+
*/
|
|
426
|
+
async function closeQuietly(session) {
|
|
427
|
+
try {
|
|
428
|
+
await session.close();
|
|
429
|
+
} catch {
|
|
430
|
+
process.stderr.write("simetra: closing the data session failed\n");
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
434
|
+
/**
|
|
435
|
+
* Прапорець бере ім'я змінної, а не значення: підказки й `instructions`
|
|
436
|
+
* повторюють argv запуску, тож рядок підключення, переданий замість імені,
|
|
437
|
+
* потрапив би агентові. Значення в тексті не цитується.
|
|
438
|
+
*/
|
|
439
|
+
function checkEnvName(flag, value) {
|
|
440
|
+
if (!ENV_NAME.test(value)) throw new UsageError(`${flag} takes the name of an environment variable (letters, digits and underscores, not starting with a digit), not its value.`);
|
|
441
|
+
}
|
|
442
|
+
const isGuid = (value) => z.guid().safeParse(value).success;
|
|
443
|
+
/**
|
|
444
|
+
* Спільна перевірка прапорців даних MCP і CLI. Типової змінної немає:
|
|
445
|
+
* доступ від імені користувача — явне рішення людини, тож прапорці йдуть
|
|
446
|
+
* разом або не йдуть зовсім. Значення в текст помилки не потрапляють.
|
|
447
|
+
*/
|
|
448
|
+
function parseDataLaunch(flags) {
|
|
449
|
+
const { dataUrlEnv, as, agent } = flags;
|
|
450
|
+
if (dataUrlEnv === void 0 && as === void 0 && agent === void 0) return void 0;
|
|
451
|
+
if (as === void 0) throw new UsageError(agent === void 0 ? "--data-url-env needs --as with the UUID of the user the data tools act as." : "--agent needs --as: the agent acts on behalf of the user named by --as.");
|
|
452
|
+
if (dataUrlEnv === void 0) throw new UsageError("--as needs --data-url-env with the name of the environment variable that holds the connection string of the development database.");
|
|
453
|
+
checkEnvName("--data-url-env", dataUrlEnv);
|
|
454
|
+
if (!isGuid(as)) throw new UsageError("--as takes a user UUID.");
|
|
455
|
+
if (agent !== void 0 && !isGuid(agent)) throw new UsageError("--agent takes an agent UUID.");
|
|
456
|
+
return {
|
|
457
|
+
urlEnv: dataUrlEnv,
|
|
458
|
+
as,
|
|
459
|
+
...agent === void 0 ? {} : { agent }
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
// src/io/metadata-dir.ts
|
|
232
463
|
/**
|
|
233
464
|
* Файли, які читає компілятор; усе інше в теці його не стосується. Перелік
|
|
234
465
|
* боргу — один файл у корені теки: без нього ратчет бачив би порожній перелік
|
|
@@ -308,28 +539,7 @@ async function pruneEmptyDirs(from, root) {
|
|
|
308
539
|
current = dirname(current);
|
|
309
540
|
}
|
|
310
541
|
}
|
|
311
|
-
|
|
312
|
-
//#region src/io/package-path.ts
|
|
313
|
-
/**
|
|
314
|
-
* Тека встановленого пакета: перший предок `fromDir` (включно) з
|
|
315
|
-
* `node_modules/<pkg>/package.json`. Шлях навмисно не проходить `realpath`:
|
|
316
|
-
* pnpm робить `node_modules/<pkg>` симлінком у сховище, а значення, що потрапляє
|
|
317
|
-
* у файли метаданих, мусить бути однаковим на кожній машині й переживати
|
|
318
|
-
* перенос репо.
|
|
319
|
-
*/
|
|
320
|
-
function installedPackageDir(fromDir, pkg) {
|
|
321
|
-
const start = resolve(fromDir);
|
|
322
|
-
let current = start;
|
|
323
|
-
for (;;) {
|
|
324
|
-
const candidate = join(current, "node_modules", pkg);
|
|
325
|
-
if (existsSync(join(candidate, "package.json"))) return candidate;
|
|
326
|
-
const parent = dirname(current);
|
|
327
|
-
if (parent === current) throw new UsageError(`${pkg} is not installed in node_modules above ${start}`);
|
|
328
|
-
current = parent;
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
//#endregion
|
|
332
|
-
//#region src/io/schema-path.ts
|
|
542
|
+
// src/io/schema-path.ts
|
|
333
543
|
/**
|
|
334
544
|
* Резолвер `$schema` для теки метаданих: відносний POSIX-шлях від теки файлу
|
|
335
545
|
* до `node_modules/simetra/schemas/…` проєкту. Саме встановлений пакет, а не
|
|
@@ -343,22 +553,21 @@ function schemaPathResolver(metadataDir) {
|
|
|
343
553
|
let schemas;
|
|
344
554
|
return (file, schemaFile) => {
|
|
345
555
|
schemas ??= join(installedPackageDir(root, "simetra"), "schemas");
|
|
346
|
-
return
|
|
556
|
+
return posixRelative(dirname(join(root, file)), join(schemas, schemaFile));
|
|
347
557
|
};
|
|
348
558
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
const PROJECT_FILE = "project.meta.json";
|
|
559
|
+
// src/tools/database-tools.ts
|
|
560
|
+
const PROJECT_FILE$1 = "project.meta.json";
|
|
352
561
|
/**
|
|
353
562
|
* Двигун вантажиться лише викликом інструмента бази: `simetra compile` і
|
|
354
563
|
* MCP-сервер без бази не тягнуть pg-delta.
|
|
355
564
|
*/
|
|
356
565
|
async function loadEngine() {
|
|
357
|
-
const { createPgDeltaEngine } = await import("./schema-engine-
|
|
566
|
+
const { createPgDeltaEngine } = await import("./schema-engine-DPPnife2.js");
|
|
358
567
|
return createPgDeltaEngine();
|
|
359
568
|
}
|
|
360
569
|
/** Резолвер `invoke` гарантує ресурс для інструмента з віссю бази. */
|
|
361
|
-
function required(database) {
|
|
570
|
+
function required$1(database) {
|
|
362
571
|
if (database === void 0) throw new Error("invoke passes the database to a database tool");
|
|
363
572
|
return database;
|
|
364
573
|
}
|
|
@@ -400,16 +609,17 @@ const introspectTool = defineTool({
|
|
|
400
609
|
}),
|
|
401
610
|
files: "write",
|
|
402
611
|
database: "read",
|
|
612
|
+
data: "none",
|
|
403
613
|
destructive: false,
|
|
404
614
|
async run({ dir, database }, input) {
|
|
405
615
|
const existing = await readFolder(dir);
|
|
406
|
-
const provider = new Set(
|
|
616
|
+
const provider = new Set(PROVIDER_SCHEMAS.supabase);
|
|
407
617
|
const foreign = (input.schemas ?? []).filter((s) => provider.has(s));
|
|
408
618
|
if (foreign.length > 0) throw new UsageError(`Provider schemas are not introspected: ${foreign.join(", ")}. Nothing changed.`);
|
|
409
619
|
if ((input.schemas ?? []).includes(PLATFORM_SCHEMA)) throw new UsageError(`Schema ${PLATFORM_SCHEMA} belongs to the platform and is not introspected. Nothing changed.`);
|
|
410
620
|
let project;
|
|
411
621
|
let scope;
|
|
412
|
-
if (existing.has(PROJECT_FILE)) {
|
|
622
|
+
if (existing.has(PROJECT_FILE$1)) {
|
|
413
623
|
const compiled = await compile(existing);
|
|
414
624
|
if (compiled.model === void 0) return {
|
|
415
625
|
ok: false,
|
|
@@ -429,7 +639,7 @@ const introspectTool = defineTool({
|
|
|
429
639
|
schemas: [.../* @__PURE__ */ new Set([...modelScope.schemas, ...input.schemas ?? []])].filter((schema) => schema !== PLATFORM_SCHEMA).sort()
|
|
430
640
|
};
|
|
431
641
|
} else {
|
|
432
|
-
if (input.schemas === void 0) throw new UsageError(`${dir} has no ${PROJECT_FILE}, so there is no scope to read: pass schemas, e.g. {"schemas": ["public"]}. Nothing changed.`);
|
|
642
|
+
if (input.schemas === void 0) throw new UsageError(`${dir} has no ${PROJECT_FILE$1}, so there is no scope to read: pass schemas, e.g. {"schemas": ["public"]}. Nothing changed.`);
|
|
433
643
|
project = {
|
|
434
644
|
name: input.project?.name ?? "App",
|
|
435
645
|
defaultSchema: input.schemas[0],
|
|
@@ -442,7 +652,7 @@ const introspectTool = defineTool({
|
|
|
442
652
|
};
|
|
443
653
|
}
|
|
444
654
|
const engine = await loadEngine();
|
|
445
|
-
const read = await withDatabase(required(database), "introspect", (db) => engine.extract(db.target, scope));
|
|
655
|
+
const read = await withDatabase(required$1(database), "introspect", (db) => engine.extract(db.target, scope));
|
|
446
656
|
if (!read.ok) return {
|
|
447
657
|
ok: false,
|
|
448
658
|
changes: [],
|
|
@@ -603,6 +813,7 @@ const diffTool = defineTool({
|
|
|
603
813
|
input: z.strictObject({ tables: z.array(z.string().min(1)).min(1).optional().meta({ description: "Tables to compare: `schema.table` or `table`." }) }),
|
|
604
814
|
files: "read",
|
|
605
815
|
database: "read",
|
|
816
|
+
data: "none",
|
|
606
817
|
destructive: false,
|
|
607
818
|
async run({ dir, database }, input) {
|
|
608
819
|
const compiled = await compile(await readMetadataDir(dir));
|
|
@@ -614,10 +825,13 @@ const diffTool = defineTool({
|
|
|
614
825
|
};
|
|
615
826
|
const desired = await desiredForApply(model);
|
|
616
827
|
const engine = await loadEngine();
|
|
617
|
-
const { createApplyDatabase } = await import("./schema-engine-
|
|
618
|
-
const compared = await withDatabase(required(database), "diff", async (db) => {
|
|
619
|
-
const
|
|
620
|
-
|
|
828
|
+
const { createApplyDatabase } = await import("./schema-engine-DPPnife2.js");
|
|
829
|
+
const compared = await withDatabase(required$1(database), "diff", async (db) => {
|
|
830
|
+
const reader = createApplyDatabase({ readOnly: true });
|
|
831
|
+
const membership = await checkOwnerMembership(reader, db.target, desired.scope, "engine.owner-not-member");
|
|
832
|
+
if (membership.refusal !== void 0) return { refusal: [membership.refusal] };
|
|
833
|
+
const roles = await checkPlatformRoles(reader, db.target, db.shadowBase, desired.sql, await loadSqlParser());
|
|
834
|
+
if (roles.refusal !== void 0) return { refusal: roles.refusal };
|
|
621
835
|
return { comparison: await compareWithDesired(engine, {
|
|
622
836
|
target: db.target,
|
|
623
837
|
...db.shadowBase ? { shadowBase: db.shadowBase } : {}
|
|
@@ -631,7 +845,7 @@ const diffTool = defineTool({
|
|
|
631
845
|
if (compared.value.refusal !== void 0) return {
|
|
632
846
|
ok: false,
|
|
633
847
|
changes: [],
|
|
634
|
-
diagnostics: [...compiled.diagnostics,
|
|
848
|
+
diagnostics: [...compiled.diagnostics, ...compared.value.refusal.map(fromEngine)]
|
|
635
849
|
};
|
|
636
850
|
const comparison = compared.value.comparison;
|
|
637
851
|
const diagnostics = [...compiled.diagnostics, ...comparison.diagnostics.map(fromEngine)];
|
|
@@ -673,14 +887,13 @@ const diffTool = defineTool({
|
|
|
673
887
|
};
|
|
674
888
|
}
|
|
675
889
|
});
|
|
676
|
-
|
|
677
|
-
//#region src/tools/apply-tools.ts
|
|
890
|
+
// src/tools/apply-tools.ts
|
|
678
891
|
/**
|
|
679
892
|
* Пул лише на виклик: інструменти без застосування не тягнуть `pg`, як і
|
|
680
893
|
* двигун у `loadEngine`.
|
|
681
894
|
*/
|
|
682
895
|
async function applyDatabase(o) {
|
|
683
|
-
const { createApplyDatabase } = await import("./schema-engine-
|
|
896
|
+
const { createApplyDatabase } = await import("./schema-engine-DPPnife2.js");
|
|
684
897
|
return createApplyDatabase(o);
|
|
685
898
|
}
|
|
686
899
|
const refusedWith = (diagnostics) => ({
|
|
@@ -707,7 +920,7 @@ function planPromotion(section, model) {
|
|
|
707
920
|
data: section.data
|
|
708
921
|
};
|
|
709
922
|
}
|
|
710
|
-
function planData(file, artifact, model, expectedBlindFunctions) {
|
|
923
|
+
function planData(file, artifact, model, expectedBlindFunctions, rightsOrphans) {
|
|
711
924
|
const conversions = new Map((artifact.promotion?.conversions ?? []).map((c) => [c.step, c.class]));
|
|
712
925
|
return {
|
|
713
926
|
file,
|
|
@@ -735,13 +948,14 @@ function planData(file, artifact, model, expectedBlindFunctions) {
|
|
|
735
948
|
defaultPrivileges: artifact.environment.defaultPrivileges
|
|
736
949
|
},
|
|
737
950
|
plpgsqlCheck: artifact.plpgsqlCheck,
|
|
738
|
-
expectedBlindFunctions
|
|
951
|
+
expectedBlindFunctions,
|
|
952
|
+
rightsOrphans
|
|
739
953
|
};
|
|
740
954
|
}
|
|
741
955
|
/** Суфікс файлу запису промоції в `plans/` (`promotionFileName`). */
|
|
742
956
|
const RECORD_SUFFIX = promotionFileName("");
|
|
743
957
|
/**
|
|
744
|
-
* Записи промоції з `plans/` кореня (
|
|
958
|
+
* Записи промоції з `plans/` кореня (спека промоції §7.1), строго: файл, що
|
|
745
959
|
* не розбирається схемою чи названий не за своїм `objectId`, — відмова плану
|
|
746
960
|
* `plan.promotion-record-invalid`, а не пропуск. Пропущений запис перетворив
|
|
747
961
|
* би промоцію на «запису немає», а вгаданий — на чужий намір. Порядок — за
|
|
@@ -803,6 +1017,7 @@ const planTool = defineTool({
|
|
|
803
1017
|
input: z.strictObject({}),
|
|
804
1018
|
files: "artifact",
|
|
805
1019
|
database: "read",
|
|
1020
|
+
data: "none",
|
|
806
1021
|
destructive: false,
|
|
807
1022
|
async run({ dir, root, database }) {
|
|
808
1023
|
const compiled = await compile(await readMetadataDir(dir));
|
|
@@ -815,7 +1030,7 @@ const planTool = defineTool({
|
|
|
815
1030
|
reader: await applyDatabase({ readOnly: true }),
|
|
816
1031
|
scratch: await applyDatabase({ readOnly: false })
|
|
817
1032
|
};
|
|
818
|
-
const built = await withDatabase(required(database), "plan", (db) => buildPlan(engine, dbs, model, {
|
|
1033
|
+
const built = await withDatabase(required$1(database), "plan", (db) => buildPlan(engine, dbs, model, {
|
|
819
1034
|
target: db.target,
|
|
820
1035
|
...db.shadowBase ? { shadowBase: db.shadowBase } : {}
|
|
821
1036
|
}, promotions.records));
|
|
@@ -828,7 +1043,11 @@ const planTool = defineTool({
|
|
|
828
1043
|
ok: !hasErrors(diagnostics),
|
|
829
1044
|
changes: [],
|
|
830
1045
|
diagnostics,
|
|
831
|
-
artifacts: []
|
|
1046
|
+
artifacts: [],
|
|
1047
|
+
data: {
|
|
1048
|
+
unchanged: true,
|
|
1049
|
+
rightsOrphans: outcome.rightsOrphans
|
|
1050
|
+
}
|
|
832
1051
|
};
|
|
833
1052
|
case "planned": {
|
|
834
1053
|
const { artifact } = outcome;
|
|
@@ -841,7 +1060,7 @@ const planTool = defineTool({
|
|
|
841
1060
|
path: file,
|
|
842
1061
|
content: serializePlan(artifact)
|
|
843
1062
|
}],
|
|
844
|
-
data: planData(file, artifact, model, outcome.expectedBlindFunctions)
|
|
1063
|
+
data: planData(file, artifact, model, outcome.expectedBlindFunctions, outcome.rightsOrphans)
|
|
845
1064
|
};
|
|
846
1065
|
}
|
|
847
1066
|
}
|
|
@@ -879,7 +1098,7 @@ async function readReport(root, file) {
|
|
|
879
1098
|
}
|
|
880
1099
|
/**
|
|
881
1100
|
* Версії, з якими план побудовано й доведено, мусять бути поточними: інакше
|
|
882
|
-
* кроки чи відбитки значать інше (
|
|
1101
|
+
* кроки чи відбитки значать інше (платформна спека §6.10). Формат файлу звіряє
|
|
883
1102
|
* вже `parsePlan`.
|
|
884
1103
|
*/
|
|
885
1104
|
function versionMismatches(artifact, engine) {
|
|
@@ -908,7 +1127,7 @@ function versionMismatches(artifact, engine) {
|
|
|
908
1127
|
const timeoutMs = z.number().int().positive();
|
|
909
1128
|
const applyTool = defineTool({
|
|
910
1129
|
name: "apply",
|
|
911
|
-
description: "Apply a reviewed plan file to the live database in one transaction, or rehearse it (rolled back; still takes the plan's locks). A rehearsal also builds the desired shadow and proves the resulting state with the engine on the same connection, holding the plan's locks a little longer; a successful rehearsal writes its report to plans/<from>-<to>.rehearsal.json next to the plan. Needs the plan's hash; destructive and relaxing steps need `allow` by id, drift needs `drift`, and a promotion needs its access:, delete:, remove: and repair: items and a valid report from a rehearsal on a copy of the target with data.",
|
|
1130
|
+
description: "Apply a reviewed plan file to the live database in one transaction, or rehearse it (rolled back; still takes the plan's locks). A rehearsal also builds the desired shadow and proves the resulting state with the engine on the same connection, holding the plan's locks a little longer; a successful rehearsal writes its report to plans/<from>-<to>.rehearsal.json next to the plan. Needs the plan's hash; destructive and relaxing steps need `allow` by id, drift needs `drift`, and a promotion needs its access:, delete:, update:, remove: and repair: items and a valid report from a rehearsal on a copy of the target with data.",
|
|
912
1131
|
input: z.strictObject({
|
|
913
1132
|
plan: z.string().min(1).meta({ description: "Plan file from `plan`, relative to the project root: plans/….plan.json." }),
|
|
914
1133
|
planHash: z.string().regex(/^[0-9a-f]{64}$/).meta({ description: "planHash of the reviewed plan." }),
|
|
@@ -919,6 +1138,7 @@ const applyTool = defineTool({
|
|
|
919
1138
|
}),
|
|
920
1139
|
files: "artifact",
|
|
921
1140
|
database: "write",
|
|
1141
|
+
data: "none",
|
|
922
1142
|
destructive: true,
|
|
923
1143
|
async run({ dir, root, database }, input) {
|
|
924
1144
|
const parsed = parsePlan(await readPlanFile(root, input.plan));
|
|
@@ -968,13 +1188,15 @@ const applyTool = defineTool({
|
|
|
968
1188
|
snapshot: canonicalSnapshot(model),
|
|
969
1189
|
timeouts
|
|
970
1190
|
};
|
|
971
|
-
const executed = await withDatabase(required(database), "apply", async (db) => {
|
|
1191
|
+
const executed = await withDatabase(required$1(database), "apply", async (db) => {
|
|
972
1192
|
if (input.rehearse !== true) return { outcome: await executePlan(writer, db.target, artifact, {
|
|
973
1193
|
...base,
|
|
974
1194
|
mode: "apply",
|
|
975
1195
|
...report === void 0 ? {} : { report }
|
|
976
1196
|
}) };
|
|
977
1197
|
const desired = await desiredForApply(model);
|
|
1198
|
+
const roles = await checkPlatformRoles(await applyDatabase({ readOnly: true }), db.target, db.shadowBase, desired.sql, await loadSqlParser());
|
|
1199
|
+
if (roles.refusal !== void 0) return { rolesRefused: roles.refusal };
|
|
978
1200
|
const shadow = await engine.withDesiredShadow({
|
|
979
1201
|
target: db.target,
|
|
980
1202
|
...db.shadowBase ? { shadowBase: db.shadowBase } : {}
|
|
@@ -991,6 +1213,7 @@ const applyTool = defineTool({
|
|
|
991
1213
|
});
|
|
992
1214
|
if (!executed.ok) return refusedWith([executed.diagnostic]);
|
|
993
1215
|
if ("shadowFailed" in executed.value) return refusedWith(executed.value.shadowFailed.map(fromEngine));
|
|
1216
|
+
if ("rolesRefused" in executed.value) return refusedWith(executed.value.rolesRefused.map(fromEngine));
|
|
994
1217
|
const outcome = executed.value.outcome;
|
|
995
1218
|
const diagnostics = outcome.diagnostics.map(fromEngine);
|
|
996
1219
|
const ok = !hasErrors(diagnostics);
|
|
@@ -1027,8 +1250,185 @@ const applyTool = defineTool({
|
|
|
1027
1250
|
}
|
|
1028
1251
|
}
|
|
1029
1252
|
});
|
|
1030
|
-
|
|
1031
|
-
|
|
1253
|
+
// src/tools/data-policy.ts
|
|
1254
|
+
/**
|
|
1255
|
+
* Чиста політика пакета `data-command` до першого з'єднання: база не
|
|
1256
|
+
* бачить запиту, якому відмовлено. Перевіряється кожна фаза пакета, бо
|
|
1257
|
+
* пакет — одна транзакція: дозволена перша фаза не робить дозволеною решту.
|
|
1258
|
+
* Невідомий об'єкт пропускається — його відхилить схема каталогу T3
|
|
1259
|
+
* (`command.invalid`), і політика не дублює її текст.
|
|
1260
|
+
*/
|
|
1261
|
+
function dataCommandRefusal(model, catalog, batch, o) {
|
|
1262
|
+
const hasModule = (x) => model.moduleFiles.some((m) => m.ownerObjectId === x.id);
|
|
1263
|
+
const moduleRefusal = (object) => ({
|
|
1264
|
+
kind: "command",
|
|
1265
|
+
error: {
|
|
1266
|
+
code: "command.invalid",
|
|
1267
|
+
reason: "object-module",
|
|
1268
|
+
object
|
|
1269
|
+
}
|
|
1270
|
+
});
|
|
1271
|
+
for (const op of batch) {
|
|
1272
|
+
const object = model.objects.find((x) => x.kind === op.object.kind && x.name === op.object.name);
|
|
1273
|
+
if (object === void 0) continue;
|
|
1274
|
+
if (hasModule(object)) return moduleRefusal(op.object);
|
|
1275
|
+
const membershipId = op.action === "create" ? catalog.objects.find((x) => x.id === object.id)?.operations.create?.root?.membership : void 0;
|
|
1276
|
+
const membership = membershipId === void 0 ? void 0 : model.objects.find((x) => x.id === membershipId);
|
|
1277
|
+
if (membership !== void 0 && hasModule(membership)) return moduleRefusal({
|
|
1278
|
+
kind: membership.kind,
|
|
1279
|
+
name: membership.name
|
|
1280
|
+
});
|
|
1281
|
+
if (o.allowRightsWrite) continue;
|
|
1282
|
+
if (KIND_REGISTRY[object.kind].rightsSystem?.(object.data) !== void 0) return {
|
|
1283
|
+
kind: "rights",
|
|
1284
|
+
object: op.object
|
|
1285
|
+
};
|
|
1286
|
+
if (membershipId !== void 0) return {
|
|
1287
|
+
kind: "rights",
|
|
1288
|
+
object: op.object
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
// src/tools/data-tools.ts
|
|
1293
|
+
/**
|
|
1294
|
+
* JSON не має `bigint`, а формат передачі клієнтам — справа П4-B: інструмент
|
|
1295
|
+
* не клієнт П4-B, тож віддає десятковий рядок, який вхід `BigInt` T0 уже
|
|
1296
|
+
* приймає назад.
|
|
1297
|
+
*/
|
|
1298
|
+
function toJson(value) {
|
|
1299
|
+
if (typeof value === "bigint") return String(value);
|
|
1300
|
+
if (Array.isArray(value)) return value.map(toJson);
|
|
1301
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toJson(v)]));
|
|
1302
|
+
return value;
|
|
1303
|
+
}
|
|
1304
|
+
/**
|
|
1305
|
+
* Зведення результату даних для тексту MCP і CLI: кількість рядків чи змін
|
|
1306
|
+
* або код помилки T3 з причиною — повні дані йдуть у структурований вивід.
|
|
1307
|
+
*/
|
|
1308
|
+
function summarizeData(name, data) {
|
|
1309
|
+
if ("error" in data) return `${name}: ${data.error.code}${data.error.reason === void 0 ? "" : `: ${data.error.reason}`}`;
|
|
1310
|
+
const count = (n, what) => `${n} ${what}${n === 1 ? "" : "s"}`;
|
|
1311
|
+
return "rows" in data ? `${name}: ${count(data.rows.length, "row")}` : `${name}: ${count(data.result.changes.length, "change")}`;
|
|
1312
|
+
}
|
|
1313
|
+
const SQLSTATE = /^[0-9A-Z]{5}$/;
|
|
1314
|
+
/**
|
|
1315
|
+
* Журнал рантайму: T3 кладе сюди сирий виняток бази, а stderr MCP-сервера
|
|
1316
|
+
* йде в журнали клієнта. Тож лише вид запису, SQLSTATE і таблиця — ні
|
|
1317
|
+
* тексту, ні `detail`, де Postgres цитує значення й ім'я входу. Stdout —
|
|
1318
|
+
* канал протоколу MCP, туди не пишемо нічого.
|
|
1319
|
+
*/
|
|
1320
|
+
function logRuntimeEntry(entry) {
|
|
1321
|
+
const error = entry.error;
|
|
1322
|
+
const code = typeof error?.code === "string" && SQLSTATE.test(error.code) ? ` SQLSTATE ${error.code}` : "";
|
|
1323
|
+
const table = typeof error?.table === "string" ? ` table ${JSON.stringify(error.table)}` : "";
|
|
1324
|
+
process.stderr.write(`simetra: runtime ${entry.kind} error${code}${table}\n`);
|
|
1325
|
+
}
|
|
1326
|
+
function required(data) {
|
|
1327
|
+
if (data === void 0) throw new Error("invoke passes the data resource to a data tool");
|
|
1328
|
+
return data;
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* Компіляція на кожен виклик (Р-A5-5): зміна теки між викликами дає нову
|
|
1332
|
+
* модель, і рантайм звіряє її хеш із застосованим — кешу, який треба
|
|
1333
|
+
* інвалідувати, немає.
|
|
1334
|
+
*/
|
|
1335
|
+
async function compileDir(dir) {
|
|
1336
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
1337
|
+
if (compiled.model === void 0) return { failed: {
|
|
1338
|
+
ok: false,
|
|
1339
|
+
changes: [],
|
|
1340
|
+
diagnostics: compiled.diagnostics
|
|
1341
|
+
} };
|
|
1342
|
+
return { model: compiled.model };
|
|
1343
|
+
}
|
|
1344
|
+
/**
|
|
1345
|
+
* Рантайм на виклик: пул ролі входу, звірка хешу, дія й закриття пулу
|
|
1346
|
+
* (`withData`). `CommandFailure` — відповідь T3, тож дані результату, а не
|
|
1347
|
+
* збій; збій бази — `database.failed` лише з адресою й кодом.
|
|
1348
|
+
*/
|
|
1349
|
+
async function onRuntime(tool, ctx, model, act) {
|
|
1350
|
+
try {
|
|
1351
|
+
const ran = await withData(required(ctx.data), model.project.database.provider, async (s) => {
|
|
1352
|
+
try {
|
|
1353
|
+
return {
|
|
1354
|
+
ok: true,
|
|
1355
|
+
data: await act(await createCommandRuntime({
|
|
1356
|
+
database: s.database,
|
|
1357
|
+
catalog: buildRuntimeCatalog(model),
|
|
1358
|
+
log: logRuntimeEntry
|
|
1359
|
+
}), s.session)
|
|
1360
|
+
};
|
|
1361
|
+
} catch (error) {
|
|
1362
|
+
if (error instanceof CommandFailure) return {
|
|
1363
|
+
ok: false,
|
|
1364
|
+
data: { error: error.error }
|
|
1365
|
+
};
|
|
1366
|
+
throw error;
|
|
1367
|
+
}
|
|
1368
|
+
});
|
|
1369
|
+
return {
|
|
1370
|
+
ok: ran.ok,
|
|
1371
|
+
changes: [],
|
|
1372
|
+
diagnostics: [],
|
|
1373
|
+
data: ran.data
|
|
1374
|
+
};
|
|
1375
|
+
} catch (error) {
|
|
1376
|
+
if (error instanceof DataFailure) return {
|
|
1377
|
+
ok: false,
|
|
1378
|
+
changes: [],
|
|
1379
|
+
diagnostics: [diagnostic("database.failed", "", "", {
|
|
1380
|
+
tool,
|
|
1381
|
+
...error.params
|
|
1382
|
+
})]
|
|
1383
|
+
};
|
|
1384
|
+
throw error;
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
const dataReadTool = defineTool({
|
|
1388
|
+
name: "data-read",
|
|
1389
|
+
description: "Read application data of the development database as the user given by --as, with that user's rights: one row by id, or a page of rows by equality filter (where, after, limit up to 200). BigInt values come as decimal strings. A runtime error comes as data.error with a code.",
|
|
1390
|
+
input: z.strictObject({ query: readQuerySchema }),
|
|
1391
|
+
files: "read",
|
|
1392
|
+
database: "none",
|
|
1393
|
+
data: "read",
|
|
1394
|
+
destructive: false,
|
|
1395
|
+
async run(ctx, input) {
|
|
1396
|
+
const compiled = await compileDir(ctx.dir);
|
|
1397
|
+
if ("failed" in compiled) return compiled.failed;
|
|
1398
|
+
return onRuntime("data-read", ctx, compiled.model, async (rt, session) => ({ rows: toJson(await rt.read(session, input.query)) }));
|
|
1399
|
+
}
|
|
1400
|
+
});
|
|
1401
|
+
const dataCommandTool = defineTool({
|
|
1402
|
+
name: "data-command",
|
|
1403
|
+
description: "Change application data of the development database as the user given by --as, with that user's rights: a batch of create, update, markDeletion and delete operations in one transaction (update, markDeletion and delete need expectedVersion). Rights catalogs and create of a scope root whose creator gets a role need --allow-rights-write; objects with a module are refused, and for such a root also when its membership catalog has one. BigInt values may be passed as decimal strings. A runtime error comes as data.error with a code.",
|
|
1404
|
+
input: z.strictObject({ operations: batchSchema }),
|
|
1405
|
+
files: "read",
|
|
1406
|
+
database: "none",
|
|
1407
|
+
data: "write",
|
|
1408
|
+
destructive: false,
|
|
1409
|
+
async run(ctx, input) {
|
|
1410
|
+
const compiled = await compileDir(ctx.dir);
|
|
1411
|
+
if ("failed" in compiled) return compiled.failed;
|
|
1412
|
+
const { model } = compiled;
|
|
1413
|
+
const refusal = dataCommandRefusal(model, buildRuntimeCatalog(model), input.operations, { allowRightsWrite: ctx.allowRightsWrite === true });
|
|
1414
|
+
if (refusal?.kind === "command") return {
|
|
1415
|
+
ok: false,
|
|
1416
|
+
changes: [],
|
|
1417
|
+
diagnostics: [],
|
|
1418
|
+
data: { error: refusal.error }
|
|
1419
|
+
};
|
|
1420
|
+
if (refusal?.kind === "rights") return {
|
|
1421
|
+
ok: false,
|
|
1422
|
+
changes: [],
|
|
1423
|
+
diagnostics: [],
|
|
1424
|
+
refusalReason: "rights-write-disabled"
|
|
1425
|
+
};
|
|
1426
|
+
return onRuntime("data-command", ctx, model, async (rt, session) => {
|
|
1427
|
+
return { result: toJson(await rt.run(session, input.operations)) };
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
});
|
|
1431
|
+
// src/tools/mutations.ts
|
|
1032
1432
|
const completion = (dir) => ({
|
|
1033
1433
|
schemaPath: schemaPathResolver(dir),
|
|
1034
1434
|
newId: () => crypto.randomUUID()
|
|
@@ -1047,8 +1447,8 @@ async function apply(dir, operation) {
|
|
|
1047
1447
|
}
|
|
1048
1448
|
/**
|
|
1049
1449
|
* Те саме для `promote`: запис промоції їде в `data` і артефактом у
|
|
1050
|
-
* `plans/<objectId>.promotion.json` — план бази читає його звідти (
|
|
1051
|
-
*
|
|
1450
|
+
* `plans/<objectId>.promotion.json` — план бази читає його звідти (спека
|
|
1451
|
+
* промоції §7.1), бо мапінг у `metadata/` не лишається.
|
|
1052
1452
|
*/
|
|
1053
1453
|
async function applyPromotion(dir, operation) {
|
|
1054
1454
|
const result = await operation(await readMetadataDir(dir));
|
|
@@ -1072,6 +1472,7 @@ const createTool = defineTool({
|
|
|
1072
1472
|
input: createObjectInput,
|
|
1073
1473
|
files: "write",
|
|
1074
1474
|
database: "none",
|
|
1475
|
+
data: "none",
|
|
1075
1476
|
destructive: false,
|
|
1076
1477
|
run: ({ dir }, input) => apply(dir, (files) => createObject(files, input, completion(dir)))
|
|
1077
1478
|
});
|
|
@@ -1081,6 +1482,7 @@ const addTool = defineTool({
|
|
|
1081
1482
|
input: addElementInput,
|
|
1082
1483
|
files: "write",
|
|
1083
1484
|
database: "none",
|
|
1485
|
+
data: "none",
|
|
1084
1486
|
destructive: false,
|
|
1085
1487
|
run: ({ dir }, input) => apply(dir, (files) => addElement(files, input, completion(dir)))
|
|
1086
1488
|
});
|
|
@@ -1090,6 +1492,7 @@ const renameTool = defineTool({
|
|
|
1090
1492
|
input: renameInput,
|
|
1091
1493
|
files: "write",
|
|
1092
1494
|
database: "none",
|
|
1495
|
+
data: "none",
|
|
1093
1496
|
destructive: false,
|
|
1094
1497
|
run: ({ dir }, input) => apply(dir, (files) => renameElement(files, input))
|
|
1095
1498
|
});
|
|
@@ -1099,6 +1502,7 @@ const deleteTool = defineTool({
|
|
|
1099
1502
|
input: deleteInput,
|
|
1100
1503
|
files: "write",
|
|
1101
1504
|
database: "none",
|
|
1505
|
+
data: "none",
|
|
1102
1506
|
destructive: true,
|
|
1103
1507
|
run: ({ dir }, input) => apply(dir, (files) => deleteElement(files, input))
|
|
1104
1508
|
});
|
|
@@ -1108,157 +1512,246 @@ const promoteTool = defineTool({
|
|
|
1108
1512
|
input: promoteInput,
|
|
1109
1513
|
files: "write",
|
|
1110
1514
|
database: "none",
|
|
1515
|
+
data: "none",
|
|
1111
1516
|
destructive: false,
|
|
1112
1517
|
run: ({ dir }, input) => applyPromotion(dir, (files) => promoteObject(files, input, completion(dir)))
|
|
1113
1518
|
});
|
|
1114
|
-
|
|
1115
|
-
|
|
1519
|
+
// src/tools/read.ts
|
|
1520
|
+
const compileTool = defineTool({
|
|
1521
|
+
name: "compile",
|
|
1522
|
+
description: "Compile the metadata directory and return diagnostics. Reads the disk on every call; writes nothing.",
|
|
1523
|
+
input: z.strictObject({}),
|
|
1524
|
+
files: "read",
|
|
1525
|
+
database: "none",
|
|
1526
|
+
data: "none",
|
|
1527
|
+
destructive: false,
|
|
1528
|
+
async run({ dir, baseline }) {
|
|
1529
|
+
const result = await compile(await readMetadataDir(dir), baseline === void 0 ? void 0 : { baseline });
|
|
1530
|
+
return {
|
|
1531
|
+
ok: result.ok,
|
|
1532
|
+
changes: [],
|
|
1533
|
+
diagnostics: result.diagnostics,
|
|
1534
|
+
data: { model: result.model }
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
});
|
|
1538
|
+
const explainTool = defineTool({
|
|
1539
|
+
name: "explain",
|
|
1540
|
+
description: "Explain one object: its tables, columns, keys and movement queries. Needs a metadata directory that compiles without errors.",
|
|
1541
|
+
input: z.strictObject({
|
|
1542
|
+
kind: metadataKindSchema,
|
|
1543
|
+
name: objectNameSchema
|
|
1544
|
+
}),
|
|
1545
|
+
files: "read",
|
|
1546
|
+
database: "none",
|
|
1547
|
+
data: "none",
|
|
1548
|
+
destructive: false,
|
|
1549
|
+
async run({ dir }, { kind, name }) {
|
|
1550
|
+
const result = await compile(await readMetadataDir(dir));
|
|
1551
|
+
if (result.model === void 0) return {
|
|
1552
|
+
ok: false,
|
|
1553
|
+
changes: [],
|
|
1554
|
+
diagnostics: result.diagnostics
|
|
1555
|
+
};
|
|
1556
|
+
const explanation = explainObject(result.model, {
|
|
1557
|
+
kind,
|
|
1558
|
+
name
|
|
1559
|
+
});
|
|
1560
|
+
if (explanation === void 0) return {
|
|
1561
|
+
ok: false,
|
|
1562
|
+
changes: [],
|
|
1563
|
+
diagnostics: result.diagnostics,
|
|
1564
|
+
refusal: `Object not found: ${kind} ${name}`
|
|
1565
|
+
};
|
|
1566
|
+
return {
|
|
1567
|
+
ok: true,
|
|
1568
|
+
changes: [],
|
|
1569
|
+
diagnostics: result.diagnostics,
|
|
1570
|
+
data: explanation
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
});
|
|
1574
|
+
const fixTool = defineTool({
|
|
1575
|
+
name: "fix",
|
|
1576
|
+
description: "Assign missing ids and physical names, set $schema and canonical form. Writes only when the result compiles without errors.",
|
|
1577
|
+
input: z.strictObject({}),
|
|
1578
|
+
files: "write",
|
|
1579
|
+
database: "none",
|
|
1580
|
+
data: "none",
|
|
1581
|
+
destructive: false,
|
|
1582
|
+
async run({ dir }) {
|
|
1583
|
+
const result = await fixFiles(await readMetadataDir(dir), {
|
|
1584
|
+
schemaPath: schemaPathResolver(dir),
|
|
1585
|
+
newId: () => crypto.randomUUID()
|
|
1586
|
+
});
|
|
1587
|
+
return {
|
|
1588
|
+
ok: result.ok,
|
|
1589
|
+
changes: result.changes,
|
|
1590
|
+
diagnostics: result.diagnostics
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
});
|
|
1594
|
+
// src/tools/rights-maintenance-tool.ts
|
|
1595
|
+
const id = z.string().regex(UUID_TEXT, "expected a UUID");
|
|
1596
|
+
const role = z.string().min(1);
|
|
1597
|
+
/**
|
|
1598
|
+
* Вхід — JSON, одна дія на запуск (Р-A4-8): `strictObject` не пропускає поля
|
|
1599
|
+
* іншої дії, тож помилка написання не перетвориться на тиху іншу дію.
|
|
1600
|
+
*/
|
|
1601
|
+
const input = z.discriminatedUnion("action", [
|
|
1602
|
+
z.strictObject({
|
|
1603
|
+
action: z.literal("firstGlobalAssignment"),
|
|
1604
|
+
user: id,
|
|
1605
|
+
role
|
|
1606
|
+
}),
|
|
1607
|
+
z.strictObject({
|
|
1608
|
+
action: z.literal("restoreGlobalFullAccess"),
|
|
1609
|
+
user: id,
|
|
1610
|
+
role: role.optional()
|
|
1611
|
+
}),
|
|
1612
|
+
z.strictObject({
|
|
1613
|
+
action: z.literal("tenantFullAccess"),
|
|
1614
|
+
scopeKind: z.string().min(1),
|
|
1615
|
+
scope: id,
|
|
1616
|
+
user: id,
|
|
1617
|
+
role,
|
|
1618
|
+
member: z.record(z.string(), z.unknown()).optional()
|
|
1619
|
+
})
|
|
1620
|
+
]);
|
|
1621
|
+
/**
|
|
1622
|
+
* Аварійний вхід у права поза командами (спека П4 §6.12): режим
|
|
1623
|
+
* обслуговування бази діє лише для входу мігратора, тож інструмент — лише
|
|
1624
|
+
* командний рядок і лише з `--yes`; агент через MCP його не бачить (Р-A4-7).
|
|
1625
|
+
*/
|
|
1626
|
+
const rightsMaintenanceTool = defineTool({
|
|
1627
|
+
name: "rights-maintenance",
|
|
1628
|
+
description: "Command line only, needs --yes. Writes one rights assignment in the database maintenance mode, connected as the migrator that applied the plan (SIMETRA_DATABASE_URL). Input is JSON with one action: firstGlobalAssignment {user, role} makes the first global assignment; restoreGlobalFullAccess {user, role?} restores a global fullAccess holder when none is effective; tenantFullAccess {scopeKind, scope, user, role, member?} restores the fullAccess owner of one scope, adding the user's member row from member when the user is not a member yet. Refuses without writing when another apply or maintenance run holds the lock, the applied model is not the compiled one, the user or the scope is unknown, the role does not fit the action, or the level already has what the action makes; a write the user would not hold effectively is rolled back.",
|
|
1629
|
+
input,
|
|
1630
|
+
files: "read",
|
|
1631
|
+
database: "write",
|
|
1632
|
+
data: "none",
|
|
1633
|
+
destructive: true,
|
|
1634
|
+
cliOnly: true,
|
|
1635
|
+
async run({ dir, database }, request) {
|
|
1636
|
+
const compiled = await compile(await readMetadataDir(dir));
|
|
1637
|
+
const model = compiled.model;
|
|
1638
|
+
if (model === void 0) return {
|
|
1639
|
+
ok: false,
|
|
1640
|
+
changes: [],
|
|
1641
|
+
diagnostics: compiled.diagnostics
|
|
1642
|
+
};
|
|
1643
|
+
const { createApplyDatabase } = await import("./schema-engine-DPPnife2.js");
|
|
1644
|
+
const ran = await withDatabase(required$1(database), "rights-maintenance", (db) => runRightsMaintenance(createApplyDatabase({ readOnly: false }), db.target, model, request));
|
|
1645
|
+
if (!ran.ok) return {
|
|
1646
|
+
ok: false,
|
|
1647
|
+
changes: [],
|
|
1648
|
+
diagnostics: [ran.diagnostic]
|
|
1649
|
+
};
|
|
1650
|
+
if (!ran.value.ok) return {
|
|
1651
|
+
ok: false,
|
|
1652
|
+
changes: [],
|
|
1653
|
+
diagnostics: [fromEngine(ran.value.diagnostic)]
|
|
1654
|
+
};
|
|
1655
|
+
return {
|
|
1656
|
+
ok: true,
|
|
1657
|
+
changes: [],
|
|
1658
|
+
diagnostics: [],
|
|
1659
|
+
data: ran.value.done
|
|
1660
|
+
};
|
|
1661
|
+
}
|
|
1662
|
+
});
|
|
1663
|
+
// src/tools/roles-tool.ts
|
|
1664
|
+
const PROJECT_FILE = "project.meta.json";
|
|
1665
|
+
/**
|
|
1666
|
+
* Набір ролей теки проєкту (спека П4 §6.2): провайдер — з файлу проєкту, тим самим
|
|
1667
|
+
* читачем, що й `compile`. Без файлу роль входу пропускається явно — пропуск
|
|
1668
|
+
* видно у виводі, бо роль без членства в ролі запиту `roles` потім не
|
|
1669
|
+
* виправив би (наявну лише звіряє).
|
|
1670
|
+
*/
|
|
1671
|
+
async function projectRoleSet(dir) {
|
|
1672
|
+
const text = existsSync(dir) ? (await readMetadataDir(dir)).get(PROJECT_FILE) : void 0;
|
|
1673
|
+
if (text === void 0) return {
|
|
1674
|
+
ok: true,
|
|
1675
|
+
roles: platformRoleSet(void 0),
|
|
1676
|
+
skipped: [{
|
|
1677
|
+
name: PLATFORM_LOGIN_ROLES.runtime,
|
|
1678
|
+
reason: "no-project-file"
|
|
1679
|
+
}]
|
|
1680
|
+
};
|
|
1681
|
+
const read = readProjectFile(text);
|
|
1682
|
+
if (read.project === void 0) return {
|
|
1683
|
+
ok: false,
|
|
1684
|
+
diagnostics: read.diagnostics
|
|
1685
|
+
};
|
|
1686
|
+
return {
|
|
1687
|
+
ok: true,
|
|
1688
|
+
roles: platformRoleSet(read.project.database.provider),
|
|
1689
|
+
skipped: []
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
// src/tools/catalog.ts
|
|
1116
1693
|
/** Єдиний каталог інструментів: CLI, MCP і студія — лише його адаптери. */
|
|
1117
1694
|
const TOOLS = [
|
|
1695
|
+
compileTool,
|
|
1696
|
+
explainTool,
|
|
1697
|
+
fixTool,
|
|
1698
|
+
createTool,
|
|
1699
|
+
addTool,
|
|
1700
|
+
renameTool,
|
|
1701
|
+
deleteTool,
|
|
1702
|
+
promoteTool,
|
|
1703
|
+
introspectTool,
|
|
1704
|
+
diffTool,
|
|
1705
|
+
planTool,
|
|
1706
|
+
applyTool,
|
|
1118
1707
|
defineTool({
|
|
1119
|
-
name: "
|
|
1120
|
-
description: "
|
|
1708
|
+
name: "roles",
|
|
1709
|
+
description: "Create the platform roles: NOLOGIN roles that generated SQL grants to on the target and the shadow server, and the runtime login role on the target only. Reads the project file for `database.provider`; without a project file the login role is skipped, and the output says so. An existing role is only checked. Needs CREATEROLE, and ADMIN OPTION on every parent role of the login role; refuses before creating anything when a server lacks CREATEROLE or a role has an unsafe shape.",
|
|
1121
1710
|
input: z.strictObject({}),
|
|
1122
1711
|
files: "read",
|
|
1123
|
-
database: "
|
|
1124
|
-
|
|
1125
|
-
async run({ dir, baseline }) {
|
|
1126
|
-
const result = await compile(await readMetadataDir(dir), baseline === void 0 ? void 0 : { baseline });
|
|
1127
|
-
return {
|
|
1128
|
-
ok: result.ok,
|
|
1129
|
-
changes: [],
|
|
1130
|
-
diagnostics: result.diagnostics,
|
|
1131
|
-
data: { model: result.model }
|
|
1132
|
-
};
|
|
1133
|
-
}
|
|
1134
|
-
}),
|
|
1135
|
-
defineTool({
|
|
1136
|
-
name: "explain",
|
|
1137
|
-
description: "Explain one object: its tables, columns, keys and movement queries. Needs a metadata directory that compiles without errors.",
|
|
1138
|
-
input: z.strictObject({
|
|
1139
|
-
kind: metadataKindSchema,
|
|
1140
|
-
name: objectNameSchema
|
|
1141
|
-
}),
|
|
1142
|
-
files: "read",
|
|
1143
|
-
database: "none",
|
|
1712
|
+
database: "write",
|
|
1713
|
+
data: "none",
|
|
1144
1714
|
destructive: false,
|
|
1145
|
-
async run({ dir
|
|
1146
|
-
const
|
|
1147
|
-
if (
|
|
1715
|
+
async run({ dir, database }) {
|
|
1716
|
+
const set = await projectRoleSet(dir);
|
|
1717
|
+
if (!set.ok) return {
|
|
1148
1718
|
ok: false,
|
|
1149
1719
|
changes: [],
|
|
1150
|
-
diagnostics:
|
|
1720
|
+
diagnostics: set.diagnostics
|
|
1151
1721
|
};
|
|
1152
|
-
const
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1722
|
+
const { createApplyDatabase } = await import("./schema-engine-DPPnife2.js");
|
|
1723
|
+
const ran = await withDatabase(required$1(database), "roles", (db) => ensurePlatformRoles(createApplyDatabase({ readOnly: false }), [{
|
|
1724
|
+
server: "target",
|
|
1725
|
+
db: db.target
|
|
1726
|
+
}, ...db.shadowBase === void 0 ? [] : [{
|
|
1727
|
+
server: "shadow",
|
|
1728
|
+
db: db.shadowBase
|
|
1729
|
+
}]], set.roles));
|
|
1730
|
+
if (!ran.ok) return {
|
|
1157
1731
|
ok: false,
|
|
1158
1732
|
changes: [],
|
|
1159
|
-
diagnostics:
|
|
1160
|
-
refusal: `Object not found: ${kind} ${name}`
|
|
1733
|
+
diagnostics: [ran.diagnostic]
|
|
1161
1734
|
};
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
diagnostics: result.diagnostics,
|
|
1166
|
-
data: explanation
|
|
1735
|
+
const data = {
|
|
1736
|
+
roles: ran.value.created,
|
|
1737
|
+
skipped: set.skipped
|
|
1167
1738
|
};
|
|
1168
|
-
}
|
|
1169
|
-
}),
|
|
1170
|
-
defineTool({
|
|
1171
|
-
name: "fix",
|
|
1172
|
-
description: "Assign missing ids and physical names, set $schema and canonical form. Writes only when the result compiles without errors.",
|
|
1173
|
-
input: z.strictObject({}),
|
|
1174
|
-
files: "write",
|
|
1175
|
-
database: "none",
|
|
1176
|
-
destructive: false,
|
|
1177
|
-
async run({ dir }) {
|
|
1178
|
-
const result = await fixFiles(await readMetadataDir(dir), {
|
|
1179
|
-
schemaPath: schemaPathResolver(dir),
|
|
1180
|
-
newId: () => crypto.randomUUID()
|
|
1181
|
-
});
|
|
1182
1739
|
return {
|
|
1183
|
-
ok:
|
|
1184
|
-
changes:
|
|
1185
|
-
diagnostics:
|
|
1740
|
+
ok: ran.value.refusal === void 0,
|
|
1741
|
+
changes: [],
|
|
1742
|
+
diagnostics: (ran.value.refusal ?? []).map(fromEngine),
|
|
1743
|
+
data
|
|
1186
1744
|
};
|
|
1187
1745
|
}
|
|
1188
1746
|
}),
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
deleteTool,
|
|
1193
|
-
promoteTool,
|
|
1194
|
-
introspectTool,
|
|
1195
|
-
diffTool,
|
|
1196
|
-
planTool,
|
|
1197
|
-
applyTool
|
|
1747
|
+
rightsMaintenanceTool,
|
|
1748
|
+
dataReadTool,
|
|
1749
|
+
dataCommandTool
|
|
1198
1750
|
];
|
|
1199
1751
|
function toolByName(name) {
|
|
1200
1752
|
return TOOLS.find((t) => t.name === name);
|
|
1201
1753
|
}
|
|
1202
|
-
|
|
1203
|
-
//#region src/tools/hints.ts
|
|
1204
|
-
const READ_ONLY_FLAG = "--read-only";
|
|
1205
|
-
const ALLOW_DATABASE_WRITE_FLAG = "--allow-database-write";
|
|
1206
|
-
/** Типова змінна середовища з рядком підключення; ім'я фіксується при запуску. */
|
|
1207
|
-
const DEFAULT_DATABASE_URL_ENV = "SIMETRA_DATABASE_URL";
|
|
1208
|
-
/**
|
|
1209
|
-
* Єдине джерело тексту «як увімкнути запис»: його бачить і клієнт MCP в
|
|
1210
|
-
* `instructions`, і агент у відмові на запис у режимі лише читання.
|
|
1211
|
-
* `launchArgs` — справжній argv запуску сервера без node і скрипта, тобто
|
|
1212
|
-
* лише ХВІСТ `args` у конфігу клієнта: лаунчер (`pnpm exec simetra …`,
|
|
1213
|
-
* `npx …`, обгортка) додає свої аргументи попереду. Тому підказка каже
|
|
1214
|
-
* «прибери прапорець» і показує хвіст до й після, а не видає його за повний
|
|
1215
|
-
* `"args"` — буквальна заміна зламала б конфіг.
|
|
1216
|
-
*/
|
|
1217
|
-
function readOnlyHint(launchArgs = [
|
|
1218
|
-
"simetra",
|
|
1219
|
-
"mcp",
|
|
1220
|
-
READ_ONLY_FLAG
|
|
1221
|
-
]) {
|
|
1222
|
-
const before = launchArgs.includes("--read-only") ? launchArgs : [...launchArgs, READ_ONLY_FLAG];
|
|
1223
|
-
const after = before.filter((a) => a !== READ_ONLY_FLAG);
|
|
1224
|
-
return [
|
|
1225
|
-
`This server runs with ${READ_ONLY_FLAG}: tools that write are disabled.`,
|
|
1226
|
-
`To enable them, remove ${READ_ONLY_FLAG} from this server's args in the MCP client config and restart it:`,
|
|
1227
|
-
`args ending in ${JSON.stringify(before)} become ${JSON.stringify(after)}.`
|
|
1228
|
-
].join(" ");
|
|
1229
|
-
}
|
|
1230
|
-
/**
|
|
1231
|
-
* Підказка відмови `apply` без прапорця запису в базу і її ж речення в
|
|
1232
|
-
* `instructions`. Як і `readOnlyHint`, показує лише хвіст `args`: прапорець
|
|
1233
|
-
* додається, а не замінює конфіг. Вмикає його людина, а не агент: запис у
|
|
1234
|
-
* базу поза git, тож рішення — при запуску сервера.
|
|
1235
|
-
*/
|
|
1236
|
-
function databaseWriteHint(launchArgs = ["simetra", "mcp"], o = {}) {
|
|
1237
|
-
const before = launchArgs.filter((a) => a !== ALLOW_DATABASE_WRITE_FLAG);
|
|
1238
|
-
const after = [...before, ALLOW_DATABASE_WRITE_FLAG];
|
|
1239
|
-
return [
|
|
1240
|
-
`This server runs without ${ALLOW_DATABASE_WRITE_FLAG}: apply cannot write to the database.`,
|
|
1241
|
-
`Only the owner may enable it: add ${ALLOW_DATABASE_WRITE_FLAG} to this server's args in the MCP client config and restart it:`,
|
|
1242
|
-
`args ending in ${JSON.stringify(before)} become ${JSON.stringify(after)}.`,
|
|
1243
|
-
...o.refusal === false ? [] : ["Nothing changed."]
|
|
1244
|
-
].join(" ");
|
|
1245
|
-
}
|
|
1246
|
-
/**
|
|
1247
|
-
* Називає лише змінну, ніколи її значення: рядок підключення несе
|
|
1248
|
-
* користувача й пароль, а відмова йде агентові й у журнали клієнта.
|
|
1249
|
-
* Середовище команди задає сам викликач перед наступним запуском, а
|
|
1250
|
-
* середовище MCP-сервера фіксується при його старті — звідси дві поради.
|
|
1251
|
-
*/
|
|
1252
|
-
function noDatabaseHint(envName, channel) {
|
|
1253
|
-
const how = channel === "cli" ? `Export the environment variable ${envName} with the connection string of the target database, or name another variable with --database-url-env.` : `Set the environment variable ${envName} to the connection string of the target database in this server's environment and restart the server.`;
|
|
1254
|
-
return [
|
|
1255
|
-
`This tool needs a database connection, and ${channel === "cli" ? "none is configured" : "the server has none"}.`,
|
|
1256
|
-
how,
|
|
1257
|
-
"Nothing changed."
|
|
1258
|
-
].join(" ");
|
|
1259
|
-
}
|
|
1260
|
-
//#endregion
|
|
1261
|
-
//#region src/tools/queue.ts
|
|
1754
|
+
// src/tools/queue.ts
|
|
1262
1755
|
const tails = /* @__PURE__ */ new Map();
|
|
1263
1756
|
/**
|
|
1264
1757
|
* Черга викликів однієї теки метаданих. Адаптери (MCP-сервер, CLI) можуть
|
|
@@ -1282,17 +1775,18 @@ function queueFor(dir) {
|
|
|
1282
1775
|
return run;
|
|
1283
1776
|
};
|
|
1284
1777
|
}
|
|
1285
|
-
|
|
1286
|
-
//#region src/tools/invoke.ts
|
|
1778
|
+
// src/tools/invoke.ts
|
|
1287
1779
|
/**
|
|
1288
|
-
* Вичерпні switch по
|
|
1780
|
+
* Вичерпні switch по всіх осях: нове значення осі не компілюється, доки не
|
|
1289
1781
|
* вирішено його дозвіл. `--read-only` вимикає будь-який запис; запис у базу
|
|
1290
|
-
* ще й
|
|
1291
|
-
*
|
|
1782
|
+
* й запис даних ще й потребують рішення людини при запуску
|
|
1783
|
+
* (`allowDatabaseWrite`, `allowDataWrite`), а власне тертя (підтвердження з
|
|
1784
|
+
* показаним планом) — ознака `destructive`.
|
|
1292
1785
|
*/
|
|
1293
1786
|
function permits(tool, o) {
|
|
1294
1787
|
const files = tool.files;
|
|
1295
1788
|
const database = tool.database;
|
|
1789
|
+
const data = tool.data;
|
|
1296
1790
|
let filesOk;
|
|
1297
1791
|
switch (files) {
|
|
1298
1792
|
case "read":
|
|
@@ -1309,7 +1803,15 @@ function permits(tool, o) {
|
|
|
1309
1803
|
break;
|
|
1310
1804
|
case "write": databaseOk = !o.readOnly && o.allowDatabaseWrite;
|
|
1311
1805
|
}
|
|
1312
|
-
|
|
1806
|
+
let dataOk;
|
|
1807
|
+
switch (data) {
|
|
1808
|
+
case "none":
|
|
1809
|
+
case "read":
|
|
1810
|
+
dataOk = true;
|
|
1811
|
+
break;
|
|
1812
|
+
case "write": dataOk = !o.readOnly && o.allowDataWrite === true;
|
|
1813
|
+
}
|
|
1814
|
+
return filesOk && databaseOk && dataOk;
|
|
1313
1815
|
}
|
|
1314
1816
|
/**
|
|
1315
1817
|
* Артефакт пишеться лише в `plans/` кореня проєкту (спека designer §3.2);
|
|
@@ -1323,7 +1825,7 @@ function checkArtifacts(root, artifacts) {
|
|
|
1323
1825
|
if (!resolve(root, a.path).startsWith(plans)) throw new UsageError(`An artifact must be written under ${PLANS_DIR}/ next to the metadata directory: ${a.path}`);
|
|
1324
1826
|
}
|
|
1325
1827
|
}
|
|
1326
|
-
function refused(reason, message) {
|
|
1828
|
+
function refused(reason, message, detail) {
|
|
1327
1829
|
return {
|
|
1328
1830
|
ok: false,
|
|
1329
1831
|
written: false,
|
|
@@ -1331,7 +1833,8 @@ function refused(reason, message) {
|
|
|
1331
1833
|
diagnostics: [],
|
|
1332
1834
|
refusal: {
|
|
1333
1835
|
reason,
|
|
1334
|
-
message
|
|
1836
|
+
message,
|
|
1837
|
+
...detail === void 0 ? {} : { detail }
|
|
1335
1838
|
}
|
|
1336
1839
|
};
|
|
1337
1840
|
}
|
|
@@ -1341,14 +1844,23 @@ function refused(reason, message) {
|
|
|
1341
1844
|
* відмова на кожному кроці гарантує, що далі диск не чіпають.
|
|
1342
1845
|
*/
|
|
1343
1846
|
async function invoke(tool, input, o) {
|
|
1847
|
+
if (tool.cliOnly && o.channel !== "cli") return refused("cli-only", `${tool.name} is available only from the command line. Nothing changed.`);
|
|
1344
1848
|
const parsed = tool.input.safeParse(input);
|
|
1345
1849
|
if (!parsed.success) return refused("invalid-input", parsed.error.issues.map((i) => i.path.length === 0 ? i.message : `${i.path.join(".")}: ${i.message}`).join("; "));
|
|
1346
1850
|
if (o.dryRun && tool.files !== "write") return refused("dry-run-unsupported", tool.name === "apply" ? "apply has no dry run: it writes the database, not files. To run the plan and roll it back, rehearse it. Nothing changed." : `${tool.name} has no dry run: only tools that change the metadata directory preview their changes. Nothing changed.`);
|
|
1347
|
-
if (!permits(tool, o))
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1851
|
+
if (!permits(tool, o)) {
|
|
1852
|
+
if (permits(tool, {
|
|
1853
|
+
...o,
|
|
1854
|
+
allowDatabaseWrite: true
|
|
1855
|
+
})) return refused("database-write-disabled", databaseWriteHint(o.launchArgs, { tools: tool.name }));
|
|
1856
|
+
if (permits(tool, {
|
|
1857
|
+
...o,
|
|
1858
|
+
allowDataWrite: true
|
|
1859
|
+
})) return refused("data-write-disabled", dataWriteHint(o.launchArgs, { tools: tool.name }));
|
|
1860
|
+
return refused("read-only", readOnlyHint(o.launchArgs));
|
|
1861
|
+
}
|
|
1351
1862
|
if (tool.database !== "none" && o.database === void 0) return refused("no-database", noDatabaseHint(o.databaseEnv ?? "SIMETRA_DATABASE_URL", o.channel));
|
|
1863
|
+
if (tool.data !== "none" && o.data === void 0) return refused("no-data", noDataHint(o.dataEnv, o.channel));
|
|
1352
1864
|
if (tool.destructive && !o.dryRun && !o.confirmed) return refused("unconfirmed", `${tool.name} is destructive and needs confirmation. Nothing changed.`);
|
|
1353
1865
|
const root = dirname(resolve(o.dir));
|
|
1354
1866
|
return queueFor(o.dir)(async () => {
|
|
@@ -1357,8 +1869,11 @@ async function invoke(tool, input, o) {
|
|
|
1357
1869
|
dir: o.dir,
|
|
1358
1870
|
root,
|
|
1359
1871
|
...tool.database === "none" ? {} : { database: o.database },
|
|
1872
|
+
...tool.data === "none" ? {} : { data: o.data },
|
|
1873
|
+
...tool.data === "write" ? { allowRightsWrite: o.allowRightsWrite === true } : {},
|
|
1360
1874
|
...o.baseline === void 0 ? {} : { baseline: o.baseline }
|
|
1361
1875
|
}, parsed.data);
|
|
1876
|
+
if (outcome.refusalReason === "rights-write-disabled") return refused("rights-write-disabled", rightsWriteHint(o.launchArgs, o.channel));
|
|
1362
1877
|
const artifacts = outcome.artifacts ?? [];
|
|
1363
1878
|
checkArtifacts(root, artifacts);
|
|
1364
1879
|
let write = false;
|
|
@@ -1391,18 +1906,13 @@ async function invoke(tool, input, o) {
|
|
|
1391
1906
|
} }
|
|
1392
1907
|
};
|
|
1393
1908
|
} catch (error) {
|
|
1909
|
+
if (error instanceof DataGuardRefusal) return refused("data-guard", error.message, error.detail);
|
|
1394
1910
|
if (error instanceof UsageError) return refused("refused", error.message);
|
|
1395
1911
|
throw error;
|
|
1396
1912
|
}
|
|
1397
1913
|
});
|
|
1398
1914
|
}
|
|
1399
|
-
|
|
1400
|
-
//#region src/io/default-dir.ts
|
|
1401
|
-
/** Тека метаданих за замовчуванням — спільна для CLI і `simetra mcp`. */
|
|
1402
|
-
const DEFAULT_DIR = "./metadata";
|
|
1403
|
-
const trimSlash = (d) => d.replace(/(?<=.)[\\/]+$/, "");
|
|
1404
|
-
//#endregion
|
|
1405
|
-
//#region src/io/report.ts
|
|
1915
|
+
// src/io/report.ts
|
|
1406
1916
|
/** Діагностика з текстом потрібною мовою; саме її віддають обидва формати. */
|
|
1407
1917
|
function localized(d, locale) {
|
|
1408
1918
|
const { message, hint } = localize(d, locale);
|
|
@@ -1468,7 +1978,7 @@ const PLPGSQL_CHECK_LABEL = {
|
|
|
1468
1978
|
};
|
|
1469
1979
|
const qualified = (schema, name) => `${quoteIdent(schema)}.${quoteIdent(name)}`;
|
|
1470
1980
|
/**
|
|
1471
|
-
* Блок «Promotion
|
|
1981
|
+
* Блок «Promotion»: що стає чим і що людина
|
|
1472
1982
|
* дозволяє. Таблиця, що лишає своє ім'я, рядка перейменування не дає:
|
|
1473
1983
|
* `a -> a` читався б як зміна, якої немає.
|
|
1474
1984
|
*/
|
|
@@ -1490,13 +2000,13 @@ function promotionLines(p, needs) {
|
|
|
1490
2000
|
}
|
|
1491
2001
|
/**
|
|
1492
2002
|
* Зведення плану для людини й агента: звідки й куди, `planHash` і файл,
|
|
1493
|
-
* дрейф — першим блоком, до кроків (
|
|
2003
|
+
* дрейф — першим блоком, до кроків (платформна спека §6.2): кроки читаються
|
|
1494
2004
|
* вже знаючи, що ціль дрейфнула. Далі — промоція, бо кроки наміру й класи
|
|
1495
|
-
* конверсій читаються, знаючи, що стає
|
|
2005
|
+
* конверсій читаються, знаючи, що стає чим. Повний
|
|
1496
2006
|
* SQL — у файлі плану; тут перший рядок.
|
|
1497
2007
|
*/
|
|
1498
2008
|
function renderPlan(d, report, o) {
|
|
1499
|
-
if (d === void 0) return [o.ok ? "plan: nothing to apply; the database is at the metadata" : "plan: no plan written: the plan was refused or has errors", report].join("\n");
|
|
2009
|
+
if (d === void 0 || "unchanged" in d) return [o.ok ? "plan: nothing to apply; the database is at the metadata" : "plan: no plan written: the plan was refused or has errors", report].join("\n");
|
|
1500
2010
|
const needs = new Set(d.requiredPermissions);
|
|
1501
2011
|
const lines = [
|
|
1502
2012
|
`plan ${short(d.fromHash)} -> ${short(d.toHash)}`,
|
|
@@ -1546,5 +2056,4 @@ function renderApply(d, diagnostics, report) {
|
|
|
1546
2056
|
const unknown = diagnostics.find((x) => x.code === "apply.connection-lost" && x.params?.outcome === "unknown");
|
|
1547
2057
|
return [d === void 0 ? unknown === void 0 ? "apply: nothing was written" : `apply: outcome unknown — check simetra.ledger for apply id ${String(unknown.params?.applyId)}` : d.status === "committed" ? `apply: committed in ${d.attempts} attempt(s)` : `rehearse: rolled back after ${d.attempts} attempt(s); the database was not changed; ${d.report === null ? "no rehearsal report was written" : `rehearsal report written to ${d.report}`}. The rehearsal took the plan's locks, as apply does.`, report].join("\n");
|
|
1548
2058
|
}
|
|
1549
|
-
|
|
1550
|
-
export { DEFAULT_DIR as a, DEFAULT_DATABASE_URL_ENV as c, TOOLS as d, toolByName as f, UsageError as g, databaseResource as h, renderPlan as i, databaseWriteHint as l, writeChanges as m, renderApply as n, trimSlash as o, isMetadataFile as p, renderDiff as r, invoke as s, formatDiagnostics as t, readOnlyHint as u };
|
|
2059
|
+
export { invoke as a, summarizeData as c, writeChanges as d, checkEnvName as f, databaseResource as h, renderPlan as i, toJson as l, parseDataLaunch as m, renderApply as n, TOOLS as o, dataResource as p, renderDiff as r, toolByName as s, formatDiagnostics as t, isMetadataFile as u };
|