@simetrajs/designer 0.2.0 → 0.3.0-next.10
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/dist/{command-BCAw6Fsb.js → command-BUIz4QxS.js} +54 -124
- package/dist/errors-D1P2kKbL.js +62 -0
- package/dist/{init-jr0Xsrpp.js → init-BS7fCOls.js} +44 -18
- package/dist/{report-DV4deFdu.js → invoke-B6ljdX5t.js} +1084 -315
- package/dist/main.js +5 -5
- package/dist/{mcp-ChltmHBb.js → mcp-CLc4ByOi.js} +30 -86
- package/dist/{package-Dg3MXPve.js → package-CJuyaMGH.js} +1 -1
- package/dist/{schema-engine-DPPnife2.js → schema-engine-8rVHcVYO.js} +627 -122
- package/dist/{types-iWavtmdS.js → types-CMcZhIci.js} +2 -0
- package/package.json +7 -3
- package/skills/simetra-adoption/SKILL.md +67 -2
- package/skills/simetra-metadata/SKILL.md +77 -87
- package/skills/simetra-metadata/references/agents-over-mcp.md +126 -6
- 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 +20 -2
- package/skills/simetra-metadata/references/people-and-rights.md +237 -18
- package/skills/simetra-metadata/references/plan-and-apply.md +81 -0
- package/skills/simetra-metadata/references/project-setup.md +11 -1
- 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 +41 -10
- package/dist/errors-Brw6UjAD.js +0 -35
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { r as defineTool, t as PLANS_DIR } from "./types-
|
|
2
|
+
import { r as defineTool, t as PLANS_DIR } from "./types-CMcZhIci.js";
|
|
3
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
|
|
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
5
|
import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
6
6
|
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
7
|
-
import { ATTRIBUTE_CASES, DATABASE_PROVIDERS,
|
|
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";
|
|
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_LOGIN_ROLES, PROVIDER_OWNER_ROLES, 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
9
|
import pg from "pg";
|
|
10
|
-
import {
|
|
10
|
+
import { agentWriteRefusal, createAgentCore, createCommandRuntime, fromPgPool, readRoleOf, toJson } from "simetra/server";
|
|
11
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";
|
|
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";
|
|
13
14
|
import { existsSync } from "node:fs";
|
|
14
15
|
// src/io/data-guard-refusal.ts
|
|
15
16
|
/**
|
|
@@ -50,14 +51,16 @@ var DatabaseRefusal = class extends UsageError {
|
|
|
50
51
|
* розбирається як URL, не цитуємо: він міг би бути самим паролем.
|
|
51
52
|
*/
|
|
52
53
|
function describeConnection(url) {
|
|
54
|
+
if (!/^postgres(ql)?:\/\//i.test(url)) return UNDESCRIBED;
|
|
53
55
|
try {
|
|
54
|
-
const
|
|
55
|
-
const
|
|
56
|
-
return `${
|
|
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 ?? ""}`;
|
|
57
59
|
} catch {
|
|
58
|
-
return
|
|
60
|
+
return UNDESCRIBED;
|
|
59
61
|
}
|
|
60
62
|
}
|
|
63
|
+
const UNDESCRIBED = "the configured database";
|
|
61
64
|
/**
|
|
62
65
|
* Ресурс запуску з імен змінних, зафіксованих при запуску. Без змінної цілі
|
|
63
66
|
* ресурсу немає — `invoke` відмовить з її ім'ям. Значення читається тут, а
|
|
@@ -134,7 +137,17 @@ const SHADOW_CONNECTION = " The shadow needs a direct or session-mode connection
|
|
|
134
137
|
* будь-що з рядка підключення. Наші власні відмови вже безпечні й ідуть як є.
|
|
135
138
|
*/
|
|
136
139
|
function classifyDatabaseError(error, names) {
|
|
137
|
-
|
|
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
|
+
};
|
|
138
151
|
}
|
|
139
152
|
/** `note` — речення перед «Nothing changed.» у кожній відмові. */
|
|
140
153
|
function classify(error, names, note) {
|
|
@@ -148,9 +161,14 @@ function classify(error, names, note) {
|
|
|
148
161
|
kind: "refusal",
|
|
149
162
|
message: error.message
|
|
150
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.`);
|
|
151
169
|
if (error instanceof ShadowCreateRefusedError) {
|
|
152
170
|
const where = error.onShadowBase ? names.shadow ?? describe : describe;
|
|
153
|
-
return refusal(`A shadow database cannot be created on ${where}: the connecting role lacks CREATEDB.${error.onShadowBase ? "" : "
|
|
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."}`);
|
|
154
172
|
}
|
|
155
173
|
if (error instanceof ShadowServerError) {
|
|
156
174
|
const where = error.onShadowBase ? names.shadow ?? describe : describe;
|
|
@@ -212,6 +230,10 @@ function classify(error, names, note) {
|
|
|
212
230
|
function isProgramBug(error) {
|
|
213
231
|
return (error instanceof TypeError || error instanceof RangeError || error instanceof ReferenceError || error instanceof SyntaxError) && codeOf(error) === void 0;
|
|
214
232
|
}
|
|
233
|
+
/** Діагностики невдалого виклику: збій і, якщо була, невидалена тінь. */
|
|
234
|
+
function failureDiagnostics(outcome) {
|
|
235
|
+
return outcome.shadowDrop === void 0 ? [outcome.diagnostic] : [outcome.diagnostic, outcome.shadowDrop];
|
|
236
|
+
}
|
|
215
237
|
/**
|
|
216
238
|
* Підключення одного виклику — єдина межа помилок бази. Відмова
|
|
217
239
|
* (`DatabaseRefusal`) летить до `invoke` і стає кодом 2; збій роботи з базою
|
|
@@ -241,7 +263,8 @@ async function withDatabase(resource, tool, fn) {
|
|
|
241
263
|
diagnostic: diagnostic("database.failed", "", "", {
|
|
242
264
|
tool,
|
|
243
265
|
...c.params
|
|
244
|
-
})
|
|
266
|
+
}),
|
|
267
|
+
...c.shadowDrop === void 0 ? {} : { shadowDrop: c.shadowDrop }
|
|
245
268
|
};
|
|
246
269
|
}
|
|
247
270
|
}
|
|
@@ -299,13 +322,16 @@ function dataGuardFactsParams(provider) {
|
|
|
299
322
|
}
|
|
300
323
|
/**
|
|
301
324
|
* Claims сесії інструмента: права — користувача `--as`, агент лише
|
|
302
|
-
* названий в `act` (RFC 8693) і прав не дає.
|
|
325
|
+
* названий в `act` (RFC 8693) і прав не дає. Claim аноніма — явно `false`:
|
|
326
|
+
* сесію без нього рантайм відмовляє.
|
|
303
327
|
*/
|
|
304
328
|
function dataSession(provider, o) {
|
|
305
329
|
const role = readRoleOf(provider);
|
|
330
|
+
const claim = PROVIDER_IDENTITY_SOURCES[provider].anonymousClaim;
|
|
306
331
|
return {
|
|
307
332
|
sub: o.as,
|
|
308
333
|
...role === void 0 ? {} : { role },
|
|
334
|
+
...claim === null ? {} : { [claim]: false },
|
|
309
335
|
...o.agent === void 0 ? {} : { act: { sub: o.agent } }
|
|
310
336
|
};
|
|
311
337
|
}
|
|
@@ -468,7 +494,8 @@ function parseDataLaunch(flags) {
|
|
|
468
494
|
const METADATA_SUFFIXES = [
|
|
469
495
|
".meta.json",
|
|
470
496
|
".sql",
|
|
471
|
-
".module.ts"
|
|
497
|
+
".module.ts",
|
|
498
|
+
FUNCTIONS_FILE_SUFFIX
|
|
472
499
|
];
|
|
473
500
|
const isMetadataFile = (key) => key === SQL_DEBT_FILE || METADATA_SUFFIXES.some((suffix) => key.endsWith(suffix));
|
|
474
501
|
/**
|
|
@@ -539,6 +566,227 @@ async function pruneEmptyDirs(from, root) {
|
|
|
539
566
|
current = dirname(current);
|
|
540
567
|
}
|
|
541
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
|
+
}
|
|
542
790
|
// src/io/schema-path.ts
|
|
543
791
|
/**
|
|
544
792
|
* Резолвер `$schema` для теки метаданих: відносний POSIX-шлях від теки файлу
|
|
@@ -557,13 +805,13 @@ function schemaPathResolver(metadataDir) {
|
|
|
557
805
|
};
|
|
558
806
|
}
|
|
559
807
|
// src/tools/database-tools.ts
|
|
560
|
-
const PROJECT_FILE$
|
|
808
|
+
const PROJECT_FILE$2 = "project.meta.json";
|
|
561
809
|
/**
|
|
562
810
|
* Двигун вантажиться лише викликом інструмента бази: `simetra compile` і
|
|
563
811
|
* MCP-сервер без бази не тягнуть pg-delta.
|
|
564
812
|
*/
|
|
565
813
|
async function loadEngine() {
|
|
566
|
-
const { createPgDeltaEngine } = await import("./schema-engine-
|
|
814
|
+
const { createPgDeltaEngine } = await import("./schema-engine-8rVHcVYO.js");
|
|
567
815
|
return createPgDeltaEngine();
|
|
568
816
|
}
|
|
569
817
|
/** Резолвер `invoke` гарантує ресурс для інструмента з віссю бази. */
|
|
@@ -598,7 +846,7 @@ async function readFolder(dir) {
|
|
|
598
846
|
const schemaName = z.string().min(1).max(63);
|
|
599
847
|
const introspectTool = defineTool({
|
|
600
848
|
name: "introspect",
|
|
601
|
-
description: "Read the live database into metadata: tables become CustomTable,
|
|
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.",
|
|
602
850
|
input: z.strictObject({
|
|
603
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." }),
|
|
604
852
|
project: z.strictObject({
|
|
@@ -613,19 +861,20 @@ const introspectTool = defineTool({
|
|
|
613
861
|
destructive: false,
|
|
614
862
|
async run({ dir, database }, input) {
|
|
615
863
|
const existing = await readFolder(dir);
|
|
616
|
-
const
|
|
617
|
-
|
|
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));
|
|
618
873
|
if (foreign.length > 0) throw new UsageError(`Provider schemas are not introspected: ${foreign.join(", ")}. Nothing changed.`);
|
|
619
874
|
if ((input.schemas ?? []).includes(PLATFORM_SCHEMA)) throw new UsageError(`Schema ${PLATFORM_SCHEMA} belongs to the platform and is not introspected. Nothing changed.`);
|
|
620
875
|
let project;
|
|
621
876
|
let scope;
|
|
622
|
-
if (
|
|
623
|
-
const compiled = await compile(existing);
|
|
624
|
-
if (compiled.model === void 0) return {
|
|
625
|
-
ok: false,
|
|
626
|
-
changes: [],
|
|
627
|
-
diagnostics: compiled.diagnostics
|
|
628
|
-
};
|
|
877
|
+
if (compiled?.model !== void 0) {
|
|
629
878
|
const own = compiled.model.project;
|
|
630
879
|
project = {
|
|
631
880
|
name: input.project?.name ?? own.name,
|
|
@@ -639,12 +888,12 @@ const introspectTool = defineTool({
|
|
|
639
888
|
schemas: [.../* @__PURE__ */ new Set([...modelScope.schemas, ...input.schemas ?? []])].filter((schema) => schema !== PLATFORM_SCHEMA).sort()
|
|
640
889
|
};
|
|
641
890
|
} else {
|
|
642
|
-
if (input.schemas === void 0) throw new UsageError(`${dir} has no ${PROJECT_FILE$
|
|
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.`);
|
|
643
892
|
project = {
|
|
644
893
|
name: input.project?.name ?? "App",
|
|
645
894
|
defaultSchema: input.schemas[0],
|
|
646
895
|
attributeCase: input.project?.attributeCase ?? "camelCase",
|
|
647
|
-
databaseProvider
|
|
896
|
+
databaseProvider
|
|
648
897
|
};
|
|
649
898
|
scope = {
|
|
650
899
|
schemas: [...new Set(input.schemas)].sort(),
|
|
@@ -652,30 +901,52 @@ const introspectTool = defineTool({
|
|
|
652
901
|
};
|
|
653
902
|
}
|
|
654
903
|
const engine = await loadEngine();
|
|
655
|
-
const
|
|
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
|
+
}));
|
|
656
912
|
if (!read.ok) return {
|
|
657
913
|
ok: false,
|
|
658
914
|
changes: [],
|
|
659
|
-
diagnostics:
|
|
915
|
+
diagnostics: failureDiagnostics(read)
|
|
660
916
|
};
|
|
661
|
-
const extracted = read.value;
|
|
662
|
-
const extractDiagnostics = extracted.diagnostics.map(fromEngine);
|
|
917
|
+
const { extracted, facts, reference } = read.value;
|
|
918
|
+
const extractDiagnostics = [...extracted.diagnostics, ...reference.diagnostics].map(fromEngine);
|
|
663
919
|
const reversed = await reverseGenerate(extracted.model, {
|
|
664
920
|
project,
|
|
665
921
|
existing,
|
|
666
922
|
newId: () => crypto.randomUUID(),
|
|
667
923
|
schemaPath: schemaPathResolver(dir),
|
|
668
|
-
parse: await loadSqlParser()
|
|
924
|
+
parse: await loadSqlParser(),
|
|
925
|
+
executeFacts: facts,
|
|
926
|
+
...reference.catalog === void 0 ? {} : { reference: reference.catalog }
|
|
669
927
|
});
|
|
670
|
-
const
|
|
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
|
+
];
|
|
671
939
|
const ok = !hasErrors(diagnostics);
|
|
940
|
+
const repairOnly = !ok && diagnostics.every((d) => d.severity !== "error" || isRepairError(d));
|
|
672
941
|
return {
|
|
673
942
|
ok,
|
|
674
|
-
|
|
943
|
+
...repairOnly ? { written: true } : {},
|
|
944
|
+
changes: ok || repairOnly ? reversed.changes : [],
|
|
675
945
|
diagnostics,
|
|
676
946
|
data: { schemas: [...scope.schemas] }
|
|
677
947
|
};
|
|
678
|
-
}
|
|
948
|
+
},
|
|
949
|
+
present: {}
|
|
679
950
|
});
|
|
680
951
|
/** Імена фільтра (`schema.table` чи `table`) у таблиці обох моделей. */
|
|
681
952
|
function resolveTables(filter, known) {
|
|
@@ -699,14 +970,19 @@ function resolveTables(filter, known) {
|
|
|
699
970
|
* `acl:(…)`) над будь-чим із цього. Індекс, енам і послідовність у Postgres
|
|
700
971
|
* адресуються схемою, а не таблицею, тож зв'язок з таблицею дають моделі.
|
|
701
972
|
*/
|
|
702
|
-
function touchesTables(tables, related) {
|
|
703
|
-
const own = new Set(tables.map((t) => `table:${t.schema}.${t.name}`));
|
|
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}`));
|
|
704
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
|
+
};
|
|
705
981
|
const sub = /^(column|constraint|trigger|rule|policy|default):(.*)$/;
|
|
706
982
|
const touches = (id) => {
|
|
707
983
|
if (own.has(id) || related.has(id)) return true;
|
|
708
984
|
const m = sub.exec(id);
|
|
709
|
-
if (m !== null) return
|
|
985
|
+
if (m !== null) return inTable(m[2]);
|
|
710
986
|
const wrapped = /^(?:comment|acl|securityLabel):\((.*)\)/.exec(id);
|
|
711
987
|
return wrapped !== null && touches(wrapped[1]);
|
|
712
988
|
};
|
|
@@ -743,10 +1019,13 @@ function nameParts(text) {
|
|
|
743
1019
|
function dependentIds(keys, models) {
|
|
744
1020
|
const enums = new Set(models.flatMap((m) => m.enumTypes.map((e) => `${e.schema}.${e.name}`)));
|
|
745
1021
|
const ids = /* @__PURE__ */ new Set();
|
|
1022
|
+
const unitIds = /* @__PURE__ */ new Set();
|
|
746
1023
|
const sequence = (schema, parts) => {
|
|
747
1024
|
if (parts === void 0 || parts.length > 2) return;
|
|
748
|
-
const
|
|
1025
|
+
const qualified = parts.length === 2 ? parts : [schema, parts[0]];
|
|
1026
|
+
const key = qualified.join(".");
|
|
749
1027
|
ids.add(`sequence:${key}`).add(`sequenceOwnedBy:${key}`);
|
|
1028
|
+
unitIds.add(unitIdentity("sequence", ...qualified)).add(unitIdentity("sequenceOwnedBy", ...qualified));
|
|
750
1029
|
};
|
|
751
1030
|
for (const table of models.flatMap((m) => m.tables)) {
|
|
752
1031
|
if (!keys.has(`${table.schema}.${table.name}`)) continue;
|
|
@@ -763,9 +1042,12 @@ function dependentIds(keys, models) {
|
|
|
763
1042
|
const owner = /OWNED\s+BY\s+(.+?)\s*;?\s*$/i.exec(unit.sql);
|
|
764
1043
|
const parts = owner === null ? void 0 : nameParts(owner[1]);
|
|
765
1044
|
const table = parts === void 0 ? void 0 : parts.length === 3 ? `${parts[0]}.${parts[1]}` : parts.length === 2 ? `${unit.schema}.${parts[0]}` : void 0;
|
|
766
|
-
if (table !== void 0 && keys.has(table)) sequence(unit.schema,
|
|
1045
|
+
if (table !== void 0 && keys.has(table)) sequence(unit.schema, identityParts(unit.identity));
|
|
767
1046
|
}
|
|
768
|
-
return
|
|
1047
|
+
return {
|
|
1048
|
+
engine: ids,
|
|
1049
|
+
unit: unitIds
|
|
1050
|
+
};
|
|
769
1051
|
}
|
|
770
1052
|
/**
|
|
771
1053
|
* Чи належить ідентичність двигуна якійсь таблиці моделей, її індексу чи
|
|
@@ -795,12 +1077,13 @@ function narrow(data, tables, models) {
|
|
|
795
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}`))));
|
|
796
1078
|
const dependent = dependentIds(keys, models);
|
|
797
1079
|
const owned = attributable(models);
|
|
798
|
-
const touches = touchesTables(tables, /* @__PURE__ */ new Set([...indexes, ...dependent]));
|
|
1080
|
+
const touches = touchesTables(tables, /* @__PURE__ */ new Set([...indexes, ...dependent.engine]), "engine");
|
|
1081
|
+
const touchesUnit = touchesTables(tables, dependent.unit, "unit");
|
|
799
1082
|
const tablePaths = [...keys].map((k) => `tables.${k}`);
|
|
800
|
-
const enumPaths = new Set([...dependent].filter((id) => id.startsWith("type:")).map((id) => `enumTypes.${id.slice(5)}`));
|
|
1083
|
+
const enumPaths = new Set([...dependent.engine].filter((id) => id.startsWith("type:")).map((id) => `enumTypes.${id.slice(5)}`));
|
|
801
1084
|
return {
|
|
802
1085
|
plan: data.plan.filter((a) => targetsOf(a).some(touches)),
|
|
803
|
-
differences: data.differences.filter((d) => tablePaths.some((p) => d.path === p || d.path.startsWith(`${p}.`)) || enumPaths.has(d.path) || d.path.startsWith("units.") &&
|
|
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))),
|
|
804
1087
|
diagnostics: data.diagnostics.filter((d) => {
|
|
805
1088
|
const object = d.params?.object;
|
|
806
1089
|
return d.file !== "" || typeof object !== "string" || !owned(object) || touches(object);
|
|
@@ -825,22 +1108,25 @@ const diffTool = defineTool({
|
|
|
825
1108
|
};
|
|
826
1109
|
const desired = await desiredForApply(model);
|
|
827
1110
|
const engine = await loadEngine();
|
|
828
|
-
const { createApplyDatabase } = await import("./schema-engine-
|
|
1111
|
+
const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
|
|
829
1112
|
const compared = await withDatabase(required$1(database), "diff", async (db) => {
|
|
830
1113
|
const reader = createApplyDatabase({ readOnly: true });
|
|
831
1114
|
const membership = await checkOwnerMembership(reader, db.target, desired.scope, "engine.owner-not-member");
|
|
832
1115
|
if (membership.refusal !== void 0) return { refusal: [membership.refusal] };
|
|
833
|
-
const roles = await checkPlatformRoles(reader, db.target, db.shadowBase, desired.sql, await loadSqlParser());
|
|
1116
|
+
const roles = await checkPlatformRoles(reader, db.target, db.shadowBase, desired.sql, await loadSqlParser(), desired.scope.provider);
|
|
834
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 };
|
|
835
1120
|
return { comparison: await compareWithDesired(engine, {
|
|
836
1121
|
target: db.target,
|
|
837
|
-
...db.shadowBase ? { shadowBase: db.shadowBase } : {}
|
|
1122
|
+
...db.shadowBase ? { shadowBase: db.shadowBase } : {},
|
|
1123
|
+
environment: seeds.statements
|
|
838
1124
|
}, desired.sql, desired.scope, desired.diagnostics) };
|
|
839
1125
|
});
|
|
840
1126
|
if (!compared.ok) return {
|
|
841
1127
|
ok: false,
|
|
842
1128
|
changes: [],
|
|
843
|
-
diagnostics: [...compiled.diagnostics, compared
|
|
1129
|
+
diagnostics: [...compiled.diagnostics, ...failureDiagnostics(compared)]
|
|
844
1130
|
};
|
|
845
1131
|
if (compared.value.refusal !== void 0) return {
|
|
846
1132
|
ok: false,
|
|
@@ -885,7 +1171,8 @@ const diffTool = defineTool({
|
|
|
885
1171
|
empty: ok && data.plan.length === 0 && data.differences.length === 0
|
|
886
1172
|
}
|
|
887
1173
|
};
|
|
888
|
-
}
|
|
1174
|
+
},
|
|
1175
|
+
present: { text: (data, v) => data === void 0 ? void 0 : renderDiff(data, v.report) }
|
|
889
1176
|
});
|
|
890
1177
|
// src/tools/apply-tools.ts
|
|
891
1178
|
/**
|
|
@@ -893,7 +1180,7 @@ const diffTool = defineTool({
|
|
|
893
1180
|
* двигун у `loadEngine`.
|
|
894
1181
|
*/
|
|
895
1182
|
async function applyDatabase(o) {
|
|
896
|
-
const { createApplyDatabase } = await import("./schema-engine-
|
|
1183
|
+
const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
|
|
897
1184
|
return createApplyDatabase(o);
|
|
898
1185
|
}
|
|
899
1186
|
const refusedWith = (diagnostics) => ({
|
|
@@ -929,7 +1216,7 @@ function planData(file, artifact, model, expectedBlindFunctions, rightsOrphans)
|
|
|
929
1216
|
toHash: artifact.toHash,
|
|
930
1217
|
drift: artifact.drift,
|
|
931
1218
|
promotion: artifact.promotion === null ? null : planPromotion(artifact.promotion, model),
|
|
932
|
-
steps: artifact.steps.map(({ id, origin, class: cls, lockClass, sql }) => {
|
|
1219
|
+
steps: artifact.steps.map(({ id, origin, class: cls, lockClass, sql, backfill }) => {
|
|
933
1220
|
const conversion = conversions.get(id);
|
|
934
1221
|
return {
|
|
935
1222
|
id,
|
|
@@ -937,7 +1224,8 @@ function planData(file, artifact, model, expectedBlindFunctions, rightsOrphans)
|
|
|
937
1224
|
class: cls,
|
|
938
1225
|
lockClass,
|
|
939
1226
|
sql,
|
|
940
|
-
...conversion === void 0 ? {} : { conversion }
|
|
1227
|
+
...conversion === void 0 ? {} : { conversion },
|
|
1228
|
+
...backfill === void 0 ? {} : { backfill }
|
|
941
1229
|
};
|
|
942
1230
|
}),
|
|
943
1231
|
locks: artifact.locks,
|
|
@@ -1034,7 +1322,7 @@ const planTool = defineTool({
|
|
|
1034
1322
|
target: db.target,
|
|
1035
1323
|
...db.shadowBase ? { shadowBase: db.shadowBase } : {}
|
|
1036
1324
|
}, promotions.records));
|
|
1037
|
-
if (!built.ok) return refusedWith([...compiled.diagnostics, built
|
|
1325
|
+
if (!built.ok) return refusedWith([...compiled.diagnostics, ...failureDiagnostics(built)]);
|
|
1038
1326
|
const outcome = built.value;
|
|
1039
1327
|
const diagnostics = [...compiled.diagnostics, ...outcome.diagnostics.map(fromEngine)];
|
|
1040
1328
|
switch (outcome.status) {
|
|
@@ -1064,11 +1352,15 @@ const planTool = defineTool({
|
|
|
1064
1352
|
};
|
|
1065
1353
|
}
|
|
1066
1354
|
}
|
|
1067
|
-
}
|
|
1355
|
+
},
|
|
1356
|
+
present: { text: (data, v) => renderPlan(data, v.report, {
|
|
1357
|
+
ok: v.ok,
|
|
1358
|
+
written: v.written
|
|
1359
|
+
}) }
|
|
1068
1360
|
});
|
|
1069
1361
|
const engineLabel = (e) => `${e.name} ${e.version}`;
|
|
1070
1362
|
/** Перші 12 hex-символів, як у імені файлу плану. */
|
|
1071
|
-
const short
|
|
1363
|
+
const short = (hash) => hash.slice(0, 12);
|
|
1072
1364
|
/** Читає файл плану з `plans/` кореня; поза ним — помилка використання. */
|
|
1073
1365
|
async function readPlanFile(root, plan) {
|
|
1074
1366
|
const path = resolve(root, plan);
|
|
@@ -1156,8 +1448,8 @@ const applyTool = defineTool({
|
|
|
1156
1448
|
const model = compiled.model;
|
|
1157
1449
|
if (model === void 0) return refusedWith(compiled.diagnostics);
|
|
1158
1450
|
if (model.hash !== artifact.toHash) return refusedWith([diagnostic("apply.plan-stale", "", "", {
|
|
1159
|
-
plan: short
|
|
1160
|
-
current: short
|
|
1451
|
+
plan: short(artifact.toHash),
|
|
1452
|
+
current: short(model.hash)
|
|
1161
1453
|
})]);
|
|
1162
1454
|
const allow = input.allow ?? [];
|
|
1163
1455
|
const permissions = checkPermissions({
|
|
@@ -1189,33 +1481,43 @@ const applyTool = defineTool({
|
|
|
1189
1481
|
timeouts
|
|
1190
1482
|
};
|
|
1191
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", "", "") };
|
|
1192
1485
|
if (input.rehearse !== true) return { outcome: await executePlan(writer, db.target, artifact, {
|
|
1193
1486
|
...base,
|
|
1194
1487
|
mode: "apply",
|
|
1195
1488
|
...report === void 0 ? {} : { report }
|
|
1196
1489
|
}) };
|
|
1197
1490
|
const desired = await desiredForApply(model);
|
|
1198
|
-
const
|
|
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);
|
|
1199
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 };
|
|
1200
1497
|
const shadow = await engine.withDesiredShadow({
|
|
1201
1498
|
target: db.target,
|
|
1202
|
-
...db.shadowBase ? { shadowBase: db.shadowBase } : {}
|
|
1499
|
+
...db.shadowBase ? { shadowBase: db.shadowBase } : {},
|
|
1500
|
+
environment: seeds.statements
|
|
1203
1501
|
}, desired.sql, artifact.scope, (shadowDb) => engine.extract(shadowDb, artifact.scope));
|
|
1204
1502
|
if (shadow.status === "shadow-failed") return { shadowFailed: shadow.diagnostics };
|
|
1205
|
-
return {
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
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
|
+
};
|
|
1213
1514
|
});
|
|
1214
|
-
if (!executed.ok) return refusedWith(
|
|
1515
|
+
if (!executed.ok) return refusedWith(failureDiagnostics(executed));
|
|
1215
1516
|
if ("shadowFailed" in executed.value) return refusedWith(executed.value.shadowFailed.map(fromEngine));
|
|
1517
|
+
if ("unsupported" in executed.value) return refusedWith([executed.value.unsupported]);
|
|
1216
1518
|
if ("rolesRefused" in executed.value) return refusedWith(executed.value.rolesRefused.map(fromEngine));
|
|
1217
1519
|
const outcome = executed.value.outcome;
|
|
1218
|
-
const diagnostics = outcome.diagnostics.map(fromEngine);
|
|
1520
|
+
const diagnostics = [...executed.value.shadow ?? [], ...outcome.diagnostics].map(fromEngine);
|
|
1219
1521
|
const ok = !hasErrors(diagnostics);
|
|
1220
1522
|
switch (outcome.status) {
|
|
1221
1523
|
case "committed": return {
|
|
@@ -1225,7 +1527,8 @@ const applyTool = defineTool({
|
|
|
1225
1527
|
data: {
|
|
1226
1528
|
status: outcome.status,
|
|
1227
1529
|
attempts: outcome.attempts,
|
|
1228
|
-
report: null
|
|
1530
|
+
report: null,
|
|
1531
|
+
backfills: outcome.backfills ?? []
|
|
1229
1532
|
}
|
|
1230
1533
|
};
|
|
1231
1534
|
case "rolledBack": {
|
|
@@ -1237,7 +1540,15 @@ const applyTool = defineTool({
|
|
|
1237
1540
|
data: {
|
|
1238
1541
|
status: outcome.status,
|
|
1239
1542
|
attempts: outcome.attempts,
|
|
1240
|
-
report: ok ? report : null
|
|
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
|
+
})
|
|
1241
1552
|
},
|
|
1242
1553
|
artifacts: ok ? [{
|
|
1243
1554
|
path: report,
|
|
@@ -1248,59 +1559,56 @@ const applyTool = defineTool({
|
|
|
1248
1559
|
case "refused":
|
|
1249
1560
|
case "failed": return refusedWith(diagnostics);
|
|
1250
1561
|
}
|
|
1251
|
-
}
|
|
1562
|
+
},
|
|
1563
|
+
present: { text: (data, v) => renderApply(data, v.diagnostics, v.report) }
|
|
1252
1564
|
});
|
|
1253
1565
|
// src/tools/data-policy.ts
|
|
1254
1566
|
/**
|
|
1255
|
-
* Чиста
|
|
1256
|
-
*
|
|
1257
|
-
*
|
|
1258
|
-
*
|
|
1259
|
-
*
|
|
1567
|
+
* Чиста відмова модуля до першого з'єднання: designer модулів не завантажує,
|
|
1568
|
+
* тож хуки об'єкта мовчки не спрацювали б. Перевіряється весь пакет (він —
|
|
1569
|
+
* одна транзакція: дозволена перша фаза не робить дозволеною решту) і першою,
|
|
1570
|
+
* до запобіжника запису прав каталогу T3 (`agentWriteRefusal`), який лишається
|
|
1571
|
+
* власністю T3. Невідомий об'єкт пропускається — його відхилить схема
|
|
1572
|
+
* каталогу T3 (`command.invalid`), і політика не дублює її текст.
|
|
1260
1573
|
*/
|
|
1261
|
-
function
|
|
1574
|
+
function dataModuleRefusal(model, catalog, batch) {
|
|
1262
1575
|
const hasModule = (x) => model.moduleFiles.some((m) => m.ownerObjectId === x.id);
|
|
1263
1576
|
const moduleRefusal = (object) => ({
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
reason: "object-module",
|
|
1268
|
-
object
|
|
1269
|
-
}
|
|
1577
|
+
code: "command.invalid",
|
|
1578
|
+
reason: "object-module",
|
|
1579
|
+
object
|
|
1270
1580
|
});
|
|
1271
1581
|
for (const op of batch) {
|
|
1272
1582
|
const object = model.objects.find((x) => x.kind === op.object.kind && x.name === op.object.name);
|
|
1273
1583
|
if (object === void 0) continue;
|
|
1274
1584
|
if (hasModule(object)) return moduleRefusal(op.object);
|
|
1275
|
-
const membershipId = op.action === "create" ? catalog.objects.find((x) => x.id === object.id)?.operations
|
|
1585
|
+
const membershipId = op.action === "create" ? catalog.objects.find((x) => x.id === object.id)?.operations?.create?.root?.membership : void 0;
|
|
1276
1586
|
const membership = membershipId === void 0 ? void 0 : model.objects.find((x) => x.id === membershipId);
|
|
1277
1587
|
if (membership !== void 0 && hasModule(membership)) return moduleRefusal({
|
|
1278
1588
|
kind: membership.kind,
|
|
1279
1589
|
name: membership.name
|
|
1280
1590
|
});
|
|
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
1591
|
}
|
|
1291
1592
|
}
|
|
1292
|
-
// src/tools/data-tools.ts
|
|
1293
1593
|
/**
|
|
1294
|
-
*
|
|
1295
|
-
*
|
|
1296
|
-
*
|
|
1594
|
+
* Єдина склейка порядку політики (Р-F3-13): відмова модуля на весь пакет —
|
|
1595
|
+
* першою, далі запобіжник запису прав каталогу T3. Порядок видно споживачеві:
|
|
1596
|
+
* пакет, який порушує обидва правила, дістає відмову модуля, бо прапорець
|
|
1597
|
+
* прав її не знімає.
|
|
1297
1598
|
*/
|
|
1298
|
-
function
|
|
1299
|
-
|
|
1300
|
-
if (
|
|
1301
|
-
|
|
1302
|
-
|
|
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
|
+
};
|
|
1303
1610
|
}
|
|
1611
|
+
// src/tools/data-tools.ts
|
|
1304
1612
|
/**
|
|
1305
1613
|
* Зведення результату даних для тексту MCP і CLI: кількість рядків чи змін
|
|
1306
1614
|
* або код помилки T3 з причиною — повні дані йдуть у структурований вивід.
|
|
@@ -1308,7 +1616,76 @@ function toJson(value) {
|
|
|
1308
1616
|
function summarizeData(name, data) {
|
|
1309
1617
|
if ("error" in data) return `${name}: ${data.error.code}${data.error.reason === void 0 ? "" : `: ${data.error.reason}`}`;
|
|
1310
1618
|
const count = (n, what) => `${n} ${what}${n === 1 ? "" : "s"}`;
|
|
1311
|
-
|
|
1619
|
+
if ("count" in data) return `${name}: ${data.capped === true ? "over " : ""}${count(data.count, "row")} counted`;
|
|
1620
|
+
if ("rows" in data) return `${name}: ${count(data.rows.length, "row")}`;
|
|
1621
|
+
const created = data.result.changes.filter((c) => c.operation === "create").map((c) => `created ${c.object.kind} ${c.object.name} ${c.id}`);
|
|
1622
|
+
return [`${name}: ${count(data.result.changes.length, "change")}`, ...created].join("\n");
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* `id` для `create` без нього (спека designer §3.2): ключ рядка — UUID, і викликач не
|
|
1626
|
+
* мусить його вигадувати. Корінь виду скоупу лишається без `id`: його генерує
|
|
1627
|
+
* T3 і відмовляє на переданий; невідомий об'єкт відхилить T3.
|
|
1628
|
+
*/
|
|
1629
|
+
function withCreateIds(catalog, batch, newId = () => crypto.randomUUID()) {
|
|
1630
|
+
return batch.map((op) => {
|
|
1631
|
+
if (op.action !== "create" || op.id !== void 0) return op;
|
|
1632
|
+
const object = catalog.objects.find((o) => o.kind === op.object.kind && o.name === op.object.name);
|
|
1633
|
+
if (object === void 0 || object.operations?.create?.root !== void 0) return op;
|
|
1634
|
+
return {
|
|
1635
|
+
...op,
|
|
1636
|
+
id: newId()
|
|
1637
|
+
};
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
/**
|
|
1641
|
+
* Скоуп для `create` скоупленого об'єкта без нього (спека designer §3.2): єдиний скоуп
|
|
1642
|
+
* цього виду, де користувач — учасник; інакше вибір неоднозначний, і
|
|
1643
|
+
* designer відмовляє діагностикою, а не підставляє навмання. Скоупи
|
|
1644
|
+
* читаються лише тоді, коли хоч одній операції скоупу бракує.
|
|
1645
|
+
*/
|
|
1646
|
+
async function withCreateScopes(model, catalog, batch, myScopes) {
|
|
1647
|
+
let scopes;
|
|
1648
|
+
const operations = [];
|
|
1649
|
+
for (const [index, op] of batch.entries()) {
|
|
1650
|
+
const object = op.action === "create" ? catalog.objects.find((o) => o.kind === op.object.kind && o.name === op.object.name) : void 0;
|
|
1651
|
+
const attribute = object?.attributes.find((a) => a.column === object.scopeColumn);
|
|
1652
|
+
if (op.action !== "create" || object?.scopeKindId === void 0 || attribute?.insert !== true || Object.hasOwn(op.values ?? {}, attribute.name)) {
|
|
1653
|
+
operations.push(op);
|
|
1654
|
+
continue;
|
|
1655
|
+
}
|
|
1656
|
+
scopes ??= await myScopes();
|
|
1657
|
+
const mine = [...new Set(scopes.filter((s) => s.scopeKind === object.scopeKindId).map((s) => s.scope))];
|
|
1658
|
+
if (mine.length !== 1) {
|
|
1659
|
+
const kind = model.scopeKinds.find((k) => k.id === object.scopeKindId);
|
|
1660
|
+
return { diagnostic: diagnostic("data.scope-unspecified", "", `/operations/${index}/values`, {
|
|
1661
|
+
object: `${op.object.kind} ${op.object.name}`,
|
|
1662
|
+
scopeKind: kind?.name ?? object.scopeKindId,
|
|
1663
|
+
attribute: attribute.name,
|
|
1664
|
+
scopes: mine.length
|
|
1665
|
+
}) };
|
|
1666
|
+
}
|
|
1667
|
+
operations.push({
|
|
1668
|
+
...op,
|
|
1669
|
+
values: {
|
|
1670
|
+
...op.values,
|
|
1671
|
+
[attribute.name]: mine[0]
|
|
1672
|
+
}
|
|
1673
|
+
});
|
|
1674
|
+
}
|
|
1675
|
+
return { operations };
|
|
1676
|
+
}
|
|
1677
|
+
/**
|
|
1678
|
+
* Скоупи користувача сесії зі знімка прав (`members`). Проєкт без функцій
|
|
1679
|
+
* прав знімка не має (`command.invalid`) — тоді скоупів немає, і рішення
|
|
1680
|
+
* лишається за діагностикою, а не за помилкою рантайму.
|
|
1681
|
+
*/
|
|
1682
|
+
async function membersOf(runtime, session) {
|
|
1683
|
+
try {
|
|
1684
|
+
return (await runtime.rightsSnapshot(session)).snapshot.members;
|
|
1685
|
+
} catch (error) {
|
|
1686
|
+
if (error instanceof CommandFailure && error.error.code === "command.invalid") return [];
|
|
1687
|
+
throw error;
|
|
1688
|
+
}
|
|
1312
1689
|
}
|
|
1313
1690
|
const SQLSTATE = /^[0-9A-Z]{5}$/;
|
|
1314
1691
|
/**
|
|
@@ -1328,7 +1705,18 @@ function required(data) {
|
|
|
1328
1705
|
return data;
|
|
1329
1706
|
}
|
|
1330
1707
|
/**
|
|
1331
|
-
*
|
|
1708
|
+
* Попередження компіляції, що стосуються об'єктів операції, і жодних
|
|
1709
|
+
* чужих: успішна модель може нести попередження про інші об'єкти проєкту, а
|
|
1710
|
+
* агентові по даних одного об'єкта вони лише шум. Об'єкт знаходиться за
|
|
1711
|
+
* файлом діагностики; невідомий об'єкт (його відхилить схема T3) нічого не
|
|
1712
|
+
* додає.
|
|
1713
|
+
*/
|
|
1714
|
+
function warningsFor(model, diagnostics, objects) {
|
|
1715
|
+
const files = new Set(model.objects.filter((x) => objects.some((o) => o.kind === x.kind && o.name === x.name)).map((x) => x.file));
|
|
1716
|
+
return diagnostics.filter((d) => d.severity === "warning" && files.has(d.file));
|
|
1717
|
+
}
|
|
1718
|
+
/**
|
|
1719
|
+
* Компіляція на кожен виклик (спека П4 §6.14): зміна теки між викликами дає нову
|
|
1332
1720
|
* модель, і рантайм звіряє її хеш із застосованим — кешу, який треба
|
|
1333
1721
|
* інвалідувати, немає.
|
|
1334
1722
|
*/
|
|
@@ -1339,14 +1727,17 @@ async function compileDir(dir) {
|
|
|
1339
1727
|
changes: [],
|
|
1340
1728
|
diagnostics: compiled.diagnostics
|
|
1341
1729
|
} };
|
|
1342
|
-
return {
|
|
1730
|
+
return {
|
|
1731
|
+
model: compiled.model,
|
|
1732
|
+
diagnostics: compiled.diagnostics
|
|
1733
|
+
};
|
|
1343
1734
|
}
|
|
1344
1735
|
/**
|
|
1345
1736
|
* Рантайм на виклик: пул ролі входу, звірка хешу, дія й закриття пулу
|
|
1346
1737
|
* (`withData`). `CommandFailure` — відповідь T3, тож дані результату, а не
|
|
1347
1738
|
* збій; збій бази — `database.failed` лише з адресою й кодом.
|
|
1348
1739
|
*/
|
|
1349
|
-
async function onRuntime(tool, ctx, model, act) {
|
|
1740
|
+
async function onRuntime(tool, ctx, model, warnings, act) {
|
|
1350
1741
|
try {
|
|
1351
1742
|
const ran = await withData(required(ctx.data), model.project.database.provider, async (s) => {
|
|
1352
1743
|
try {
|
|
@@ -1369,7 +1760,7 @@ async function onRuntime(tool, ctx, model, act) {
|
|
|
1369
1760
|
return {
|
|
1370
1761
|
ok: ran.ok,
|
|
1371
1762
|
changes: [],
|
|
1372
|
-
diagnostics:
|
|
1763
|
+
diagnostics: warnings,
|
|
1373
1764
|
data: ran.data
|
|
1374
1765
|
};
|
|
1375
1766
|
} catch (error) {
|
|
@@ -1386,7 +1777,7 @@ async function onRuntime(tool, ctx, model, act) {
|
|
|
1386
1777
|
}
|
|
1387
1778
|
const dataReadTool = defineTool({
|
|
1388
1779
|
name: "data-read",
|
|
1389
|
-
description: "
|
|
1780
|
+
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.",
|
|
1390
1781
|
input: z.strictObject({ query: readQuerySchema }),
|
|
1391
1782
|
files: "read",
|
|
1392
1783
|
database: "none",
|
|
@@ -1395,37 +1786,66 @@ const dataReadTool = defineTool({
|
|
|
1395
1786
|
async run(ctx, input) {
|
|
1396
1787
|
const compiled = await compileDir(ctx.dir);
|
|
1397
1788
|
if ("failed" in compiled) return compiled.failed;
|
|
1398
|
-
return onRuntime("data-read", ctx, compiled.model, async (rt, session) => ({
|
|
1789
|
+
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));
|
|
1790
|
+
},
|
|
1791
|
+
present: {
|
|
1792
|
+
structure: (data) => toJson(data),
|
|
1793
|
+
text: (data, v) => data === void 0 ? void 0 : [summarizeData("data-read", data), ...v.diagnostics.length > 0 ? [v.report] : []].join("\n")
|
|
1399
1794
|
}
|
|
1400
1795
|
});
|
|
1401
1796
|
const dataCommandTool = defineTool({
|
|
1402
1797
|
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.",
|
|
1798
|
+
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 create without id gets a fresh one; without its scope it takes the user's only scope of that kind. 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.",
|
|
1404
1799
|
input: z.strictObject({ operations: batchSchema }),
|
|
1405
1800
|
files: "read",
|
|
1406
1801
|
database: "none",
|
|
1407
1802
|
data: "write",
|
|
1408
1803
|
destructive: false,
|
|
1409
1804
|
async run(ctx, input) {
|
|
1805
|
+
if (input.operations.some((op) => op.action === "issueInvitation")) return {
|
|
1806
|
+
ok: false,
|
|
1807
|
+
changes: [],
|
|
1808
|
+
diagnostics: [],
|
|
1809
|
+
refusal: "data-command never runs issueInvitation: the secret would reach the model. Issue invitations in the application."
|
|
1810
|
+
};
|
|
1410
1811
|
const compiled = await compileDir(ctx.dir);
|
|
1411
1812
|
if ("failed" in compiled) return compiled.failed;
|
|
1412
1813
|
const { model } = compiled;
|
|
1413
|
-
const
|
|
1814
|
+
const warnings = warningsFor(model, compiled.diagnostics, input.operations.map((op) => op.object));
|
|
1815
|
+
const catalog = buildRuntimeCatalog(model);
|
|
1816
|
+
const operations = withCreateIds(catalog, input.operations);
|
|
1817
|
+
const rightsWrite = ctx.allowRightsWrite === true;
|
|
1818
|
+
const refusal = dataPolicyRefusal(model, catalog, operations, { rightsWrite });
|
|
1414
1819
|
if (refusal?.kind === "command") return {
|
|
1415
1820
|
ok: false,
|
|
1416
1821
|
changes: [],
|
|
1417
1822
|
diagnostics: [],
|
|
1418
1823
|
data: { error: refusal.error }
|
|
1419
1824
|
};
|
|
1420
|
-
if (refusal
|
|
1825
|
+
if (refusal !== void 0) return {
|
|
1421
1826
|
ok: false,
|
|
1422
1827
|
changes: [],
|
|
1423
1828
|
diagnostics: [],
|
|
1424
1829
|
refusalReason: "rights-write-disabled"
|
|
1425
1830
|
};
|
|
1426
|
-
|
|
1427
|
-
|
|
1831
|
+
const ran = await onRuntime("data-command", ctx, model, warnings, async (rt, session) => {
|
|
1832
|
+
const scoped = await withCreateScopes(model, catalog, operations, () => membersOf(rt, session));
|
|
1833
|
+
if ("diagnostic" in scoped) return scoped;
|
|
1834
|
+
return { result: await createAgentCore({
|
|
1835
|
+
runtime: rt,
|
|
1836
|
+
permissions: { rightsWrite }
|
|
1837
|
+
}).execute(session, scoped.operations) };
|
|
1428
1838
|
});
|
|
1839
|
+
if (ran.data !== void 0 && "diagnostic" in ran.data) return {
|
|
1840
|
+
ok: false,
|
|
1841
|
+
changes: [],
|
|
1842
|
+
diagnostics: [...warnings, ran.data.diagnostic]
|
|
1843
|
+
};
|
|
1844
|
+
return ran;
|
|
1845
|
+
},
|
|
1846
|
+
present: {
|
|
1847
|
+
structure: (data) => toJson(data),
|
|
1848
|
+
text: (data, v) => data === void 0 ? void 0 : [summarizeData("data-command", data), ...v.diagnostics.length > 0 ? [v.report] : []].join("\n")
|
|
1429
1849
|
}
|
|
1430
1850
|
});
|
|
1431
1851
|
// src/tools/mutations.ts
|
|
@@ -1441,6 +1861,7 @@ async function apply(dir, operation) {
|
|
|
1441
1861
|
const result = await operation(await readMetadataDir(dir));
|
|
1442
1862
|
return {
|
|
1443
1863
|
ok: result.ok,
|
|
1864
|
+
...result.written === true ? { written: true } : {},
|
|
1444
1865
|
changes: result.changes,
|
|
1445
1866
|
diagnostics: result.diagnostics
|
|
1446
1867
|
};
|
|
@@ -1468,7 +1889,7 @@ async function applyPromotion(dir, operation) {
|
|
|
1468
1889
|
}
|
|
1469
1890
|
const createTool = defineTool({
|
|
1470
1891
|
name: "create",
|
|
1471
|
-
description: "Create a metadata object; ids and physical names are assigned. Writes
|
|
1892
|
+
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).",
|
|
1472
1893
|
input: createObjectInput,
|
|
1473
1894
|
files: "write",
|
|
1474
1895
|
database: "none",
|
|
@@ -1478,7 +1899,7 @@ const createTool = defineTool({
|
|
|
1478
1899
|
});
|
|
1479
1900
|
const addTool = defineTool({
|
|
1480
1901
|
name: "add",
|
|
1481
|
-
description: "Add a named element (attribute, tabular section, value, scope kind, ...) to a collection of an object or of the project root. Writes
|
|
1902
|
+
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).",
|
|
1482
1903
|
input: addElementInput,
|
|
1483
1904
|
files: "write",
|
|
1484
1905
|
database: "none",
|
|
@@ -1486,6 +1907,16 @@ const addTool = defineTool({
|
|
|
1486
1907
|
destructive: false,
|
|
1487
1908
|
run: ({ dir }, input) => apply(dir, (files) => addElement(files, input, completion(dir)))
|
|
1488
1909
|
});
|
|
1910
|
+
const declareFunctionTool = defineTool({
|
|
1911
|
+
name: "declare-function",
|
|
1912
|
+
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.",
|
|
1913
|
+
input: declareFunctionInput,
|
|
1914
|
+
files: "write",
|
|
1915
|
+
database: "none",
|
|
1916
|
+
data: "none",
|
|
1917
|
+
destructive: false,
|
|
1918
|
+
run: ({ dir }, input) => apply(dir, (files) => declareFunction(files, input, completion(dir)))
|
|
1919
|
+
});
|
|
1489
1920
|
const renameTool = defineTool({
|
|
1490
1921
|
name: "rename",
|
|
1491
1922
|
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.",
|
|
@@ -1514,6 +1945,10 @@ const promoteTool = defineTool({
|
|
|
1514
1945
|
database: "none",
|
|
1515
1946
|
data: "none",
|
|
1516
1947
|
destructive: false,
|
|
1948
|
+
present: {
|
|
1949
|
+
structure: (record) => ({ record }),
|
|
1950
|
+
appendix: (record, v) => v.channel === "cli" ? renderPromotion(record, v.written) : ["promotion record:", JSON.stringify(record, null, 2)].join("\n")
|
|
1951
|
+
},
|
|
1517
1952
|
run: ({ dir }, input) => applyPromotion(dir, (files) => promoteObject(files, input, completion(dir)))
|
|
1518
1953
|
});
|
|
1519
1954
|
// src/tools/read.ts
|
|
@@ -1525,6 +1960,7 @@ const compileTool = defineTool({
|
|
|
1525
1960
|
database: "none",
|
|
1526
1961
|
data: "none",
|
|
1527
1962
|
destructive: false,
|
|
1963
|
+
present: { diagnosticsOnly: true },
|
|
1528
1964
|
async run({ dir, baseline }) {
|
|
1529
1965
|
const result = await compile(await readMetadataDir(dir), baseline === void 0 ? void 0 : { baseline });
|
|
1530
1966
|
return {
|
|
@@ -1535,19 +1971,50 @@ const compileTool = defineTool({
|
|
|
1535
1971
|
};
|
|
1536
1972
|
}
|
|
1537
1973
|
});
|
|
1974
|
+
const explainInput = z.strictObject({
|
|
1975
|
+
kind: metadataKindSchema.optional(),
|
|
1976
|
+
name: objectNameSchema.optional(),
|
|
1977
|
+
function: z.strictObject({
|
|
1978
|
+
schema: z.string().min(1).optional(),
|
|
1979
|
+
name: z.string().min(1)
|
|
1980
|
+
}).optional()
|
|
1981
|
+
}).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." });
|
|
1538
1982
|
const explainTool = defineTool({
|
|
1539
1983
|
name: "explain",
|
|
1540
|
-
description: "Explain
|
|
1541
|
-
input:
|
|
1542
|
-
kind: metadataKindSchema,
|
|
1543
|
-
name: objectNameSchema
|
|
1544
|
-
}),
|
|
1984
|
+
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.",
|
|
1985
|
+
input: explainInput,
|
|
1545
1986
|
files: "read",
|
|
1546
1987
|
database: "none",
|
|
1547
1988
|
data: "none",
|
|
1548
1989
|
destructive: false,
|
|
1549
|
-
async run({ dir }, { kind, name }) {
|
|
1550
|
-
const
|
|
1990
|
+
async run({ dir }, { kind, name, function: fn }) {
|
|
1991
|
+
const files = await readMetadataDir(dir);
|
|
1992
|
+
if (fn !== void 0) {
|
|
1993
|
+
const result = await compile(files, { repair: true });
|
|
1994
|
+
if (result.model === void 0) return {
|
|
1995
|
+
ok: false,
|
|
1996
|
+
changes: [],
|
|
1997
|
+
diagnostics: result.diagnostics
|
|
1998
|
+
};
|
|
1999
|
+
const schema = fn.schema ?? result.model.project.defaultSchema;
|
|
2000
|
+
const explanation = explainFunction(result, {
|
|
2001
|
+
schema,
|
|
2002
|
+
name: fn.name
|
|
2003
|
+
});
|
|
2004
|
+
if (explanation === void 0) return {
|
|
2005
|
+
ok: false,
|
|
2006
|
+
changes: [],
|
|
2007
|
+
diagnostics: result.diagnostics,
|
|
2008
|
+
refusal: `Function not found: ${schema}.${fn.name}`
|
|
2009
|
+
};
|
|
2010
|
+
return {
|
|
2011
|
+
ok: true,
|
|
2012
|
+
changes: [],
|
|
2013
|
+
diagnostics: result.diagnostics,
|
|
2014
|
+
data: explanation
|
|
2015
|
+
};
|
|
2016
|
+
}
|
|
2017
|
+
const result = await compile(files);
|
|
1551
2018
|
if (result.model === void 0) return {
|
|
1552
2019
|
ok: false,
|
|
1553
2020
|
changes: [],
|
|
@@ -1569,11 +2036,15 @@ const explainTool = defineTool({
|
|
|
1569
2036
|
diagnostics: result.diagnostics,
|
|
1570
2037
|
data: explanation
|
|
1571
2038
|
};
|
|
2039
|
+
},
|
|
2040
|
+
present: {
|
|
2041
|
+
bare: true,
|
|
2042
|
+
text: (data, v) => data === void 0 ? void 0 : v.channel === "mcp" ? JSON.stringify(data, null, 2) : "function" in data ? renderFunctionExplanation(data) : renderExplanation(data).trimEnd()
|
|
1572
2043
|
}
|
|
1573
2044
|
});
|
|
1574
2045
|
const fixTool = defineTool({
|
|
1575
2046
|
name: "fix",
|
|
1576
|
-
description: "Assign missing ids and physical names, set $schema and canonical form. Writes
|
|
2047
|
+
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).",
|
|
1577
2048
|
input: z.strictObject({}),
|
|
1578
2049
|
files: "write",
|
|
1579
2050
|
database: "none",
|
|
@@ -1586,6 +2057,7 @@ const fixTool = defineTool({
|
|
|
1586
2057
|
});
|
|
1587
2058
|
return {
|
|
1588
2059
|
ok: result.ok,
|
|
2060
|
+
...result.written === true ? { written: true } : {},
|
|
1589
2061
|
changes: result.changes,
|
|
1590
2062
|
diagnostics: result.diagnostics
|
|
1591
2063
|
};
|
|
@@ -1595,7 +2067,7 @@ const fixTool = defineTool({
|
|
|
1595
2067
|
const id = z.string().regex(UUID_TEXT, "expected a UUID");
|
|
1596
2068
|
const role = z.string().min(1);
|
|
1597
2069
|
/**
|
|
1598
|
-
* Вхід — JSON, одна дія на
|
|
2070
|
+
* Вхід — JSON, одна дія на запуск: `strictObject` не пропускає поля
|
|
1599
2071
|
* іншої дії, тож помилка написання не перетвориться на тиху іншу дію.
|
|
1600
2072
|
*/
|
|
1601
2073
|
const input = z.discriminatedUnion("action", [
|
|
@@ -1621,7 +2093,7 @@ const input = z.discriminatedUnion("action", [
|
|
|
1621
2093
|
/**
|
|
1622
2094
|
* Аварійний вхід у права поза командами (спека П4 §6.12): режим
|
|
1623
2095
|
* обслуговування бази діє лише для входу мігратора, тож інструмент — лише
|
|
1624
|
-
* командний рядок і лише з `--yes`; агент через MCP його не
|
|
2096
|
+
* командний рядок і лише з `--yes`; агент через MCP його не бачить.
|
|
1625
2097
|
*/
|
|
1626
2098
|
const rightsMaintenanceTool = defineTool({
|
|
1627
2099
|
name: "rights-maintenance",
|
|
@@ -1640,12 +2112,12 @@ const rightsMaintenanceTool = defineTool({
|
|
|
1640
2112
|
changes: [],
|
|
1641
2113
|
diagnostics: compiled.diagnostics
|
|
1642
2114
|
};
|
|
1643
|
-
const { createApplyDatabase } = await import("./schema-engine-
|
|
2115
|
+
const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
|
|
1644
2116
|
const ran = await withDatabase(required$1(database), "rights-maintenance", (db) => runRightsMaintenance(createApplyDatabase({ readOnly: false }), db.target, model, request));
|
|
1645
2117
|
if (!ran.ok) return {
|
|
1646
2118
|
ok: false,
|
|
1647
2119
|
changes: [],
|
|
1648
|
-
diagnostics:
|
|
2120
|
+
diagnostics: failureDiagnostics(ran)
|
|
1649
2121
|
};
|
|
1650
2122
|
if (!ran.value.ok) return {
|
|
1651
2123
|
ok: false,
|
|
@@ -1658,25 +2130,81 @@ const rightsMaintenanceTool = defineTool({
|
|
|
1658
2130
|
diagnostics: [],
|
|
1659
2131
|
data: ran.value.done
|
|
1660
2132
|
};
|
|
1661
|
-
}
|
|
2133
|
+
},
|
|
2134
|
+
present: { text: (data) => data === void 0 ? void 0 : `assigned ${data.assignment}${data.member === void 0 ? "" : ` to member ${data.member}`}` }
|
|
1662
2135
|
});
|
|
1663
2136
|
// src/tools/roles-tool.ts
|
|
1664
|
-
const PROJECT_FILE = "project.meta.json";
|
|
2137
|
+
const PROJECT_FILE$1 = "project.meta.json";
|
|
2138
|
+
const [AUTH_ROLE] = PROVIDER_LOGIN_ROLES.postgres;
|
|
2139
|
+
if (AUTH_ROLE === void 0) throw new Error("the postgres profile data has no auth login role");
|
|
2140
|
+
/**
|
|
2141
|
+
* Змінні середовища з паролями розробника ролей входу профілю `postgres`
|
|
2142
|
+
* (спека профілю §3.4): імена ролей — з даних T0, змінні — ті самі, що в
|
|
2143
|
+
* стеку розробки (`login-secrets.env`).
|
|
2144
|
+
*/
|
|
2145
|
+
const DEV_PASSWORD_VARIABLES = [
|
|
2146
|
+
{
|
|
2147
|
+
role: PROVIDER_OWNER_ROLES.postgres,
|
|
2148
|
+
variable: "SIMETRA_OWNER_DEV_PASSWORD"
|
|
2149
|
+
},
|
|
2150
|
+
{
|
|
2151
|
+
role: AUTH_ROLE,
|
|
2152
|
+
variable: "SIMETRA_AUTH_DEV_PASSWORD"
|
|
2153
|
+
},
|
|
2154
|
+
{
|
|
2155
|
+
role: PLATFORM_LOGIN_ROLES.runtime,
|
|
2156
|
+
variable: "SIMETRA_RUNTIME_DEV_PASSWORD"
|
|
2157
|
+
},
|
|
2158
|
+
{
|
|
2159
|
+
role: PLATFORM_LOGIN_ROLES.signals,
|
|
2160
|
+
variable: "SIMETRA_SIGNALS_DEV_PASSWORD"
|
|
2161
|
+
}
|
|
2162
|
+
];
|
|
2163
|
+
/**
|
|
2164
|
+
* Паролі розробника за роллю або відмови до будь-якого з'єднання: хост, який
|
|
2165
|
+
* візьме `pg` (`?host=`, `PGHOST` теж), — лише ця машина, бо відомий пароль
|
|
2166
|
+
* на спільному сервері відкрив би його; кожна змінна задана й не порожня.
|
|
2167
|
+
* Значення в діагностики не потрапляють — лише імена змінних і хост.
|
|
2168
|
+
*/
|
|
2169
|
+
function devPasswordsFrom(env, url) {
|
|
2170
|
+
const diagnostics = [];
|
|
2171
|
+
let host;
|
|
2172
|
+
try {
|
|
2173
|
+
host = new pg.Client({ connectionString: url }).host;
|
|
2174
|
+
} catch {
|
|
2175
|
+
host = void 0;
|
|
2176
|
+
}
|
|
2177
|
+
if (!isLocalHost(host)) diagnostics.push(diagnostic("roles.dev-passwords-remote", "", "", { host: host === void 0 || host === "" ? "(none)" : host }));
|
|
2178
|
+
const passwords = /* @__PURE__ */ new Map();
|
|
2179
|
+
for (const { role, variable } of DEV_PASSWORD_VARIABLES) {
|
|
2180
|
+
const value = env[variable];
|
|
2181
|
+
if (value === void 0 || value === "") diagnostics.push(diagnostic("roles.dev-password-missing", "", "", { variable }));
|
|
2182
|
+
else passwords.set(role, value);
|
|
2183
|
+
}
|
|
2184
|
+
return diagnostics.length > 0 ? {
|
|
2185
|
+
ok: false,
|
|
2186
|
+
diagnostics
|
|
2187
|
+
} : {
|
|
2188
|
+
ok: true,
|
|
2189
|
+
passwords
|
|
2190
|
+
};
|
|
2191
|
+
}
|
|
1665
2192
|
/**
|
|
1666
2193
|
* Набір ролей теки проєкту (спека П4 §6.2): провайдер — з файлу проєкту, тим самим
|
|
1667
|
-
* читачем, що й `compile`. Без файлу
|
|
1668
|
-
* видно у виводі, бо
|
|
1669
|
-
*
|
|
2194
|
+
* читачем, що й `compile`. Без файлу ролі входу пропускаються явно — пропуск
|
|
2195
|
+
* видно у виводі, бо без провайдера невідомо, членом яких ролей запиту
|
|
2196
|
+
* роль рантайму мусить бути.
|
|
1670
2197
|
*/
|
|
1671
2198
|
async function projectRoleSet(dir) {
|
|
1672
|
-
const text = existsSync(dir) ? (await readMetadataDir(dir)).get(PROJECT_FILE) : void 0;
|
|
2199
|
+
const text = existsSync(dir) ? (await readMetadataDir(dir)).get(PROJECT_FILE$1) : void 0;
|
|
1673
2200
|
if (text === void 0) return {
|
|
1674
2201
|
ok: true,
|
|
2202
|
+
provider: void 0,
|
|
1675
2203
|
roles: platformRoleSet(void 0),
|
|
1676
|
-
skipped:
|
|
1677
|
-
name
|
|
2204
|
+
skipped: Object.values(PLATFORM_LOGIN_ROLES).map((name) => ({
|
|
2205
|
+
name,
|
|
1678
2206
|
reason: "no-project-file"
|
|
1679
|
-
}
|
|
2207
|
+
}))
|
|
1680
2208
|
};
|
|
1681
2209
|
const read = readProjectFile(text);
|
|
1682
2210
|
if (read.project === void 0) return {
|
|
@@ -1685,10 +2213,357 @@ async function projectRoleSet(dir) {
|
|
|
1685
2213
|
};
|
|
1686
2214
|
return {
|
|
1687
2215
|
ok: true,
|
|
2216
|
+
provider: read.project.database.provider,
|
|
1688
2217
|
roles: platformRoleSet(read.project.database.provider),
|
|
1689
2218
|
skipped: []
|
|
1690
2219
|
};
|
|
1691
2220
|
}
|
|
2221
|
+
/** Ім'я бази з адреси цілі; порожнє, коли адреса бази не називає. */
|
|
2222
|
+
function databaseOf(url) {
|
|
2223
|
+
try {
|
|
2224
|
+
return decodeURIComponent(new URL(url).pathname.replace(/^\//, ""));
|
|
2225
|
+
} catch {
|
|
2226
|
+
return "";
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
/**
|
|
2230
|
+
* Підсумок підготовки кластера як рядки інструмента: створене й наявне — за іменем, а
|
|
2231
|
+
* доповнене членство — на рядку самої ролі входу (`present` з `added`), а не
|
|
2232
|
+
* окремою «роллю».
|
|
2233
|
+
*/
|
|
2234
|
+
function clusterRoles(value) {
|
|
2235
|
+
const outcome = (names, kind) => names.map((name) => {
|
|
2236
|
+
const parents = value.added?.find((a) => a.role === name)?.parents;
|
|
2237
|
+
return {
|
|
2238
|
+
server: "target",
|
|
2239
|
+
name,
|
|
2240
|
+
outcome: kind,
|
|
2241
|
+
...parents === void 0 ? {} : { added: parents }
|
|
2242
|
+
};
|
|
2243
|
+
});
|
|
2244
|
+
return [...outcome(value.created, "created"), ...outcome(value.present, "present")];
|
|
2245
|
+
}
|
|
2246
|
+
/**
|
|
2247
|
+
* Готує ролі (і, у профілі `postgres`, кластер) за провайдером проєкту.
|
|
2248
|
+
* `postgres` готує суперкористувач через службову базу того самого сервера,
|
|
2249
|
+
* ціль і шаблон; окремий сервер тіней там не підтримано.
|
|
2250
|
+
* Решта провайдерів і проєкт без файлу — ролі на цілі й на сервері тіні.
|
|
2251
|
+
*/
|
|
2252
|
+
async function runRoles(dbs, db, project, options = {}) {
|
|
2253
|
+
if (options.devPasswords !== void 0 && project.provider !== "postgres") return {
|
|
2254
|
+
roles: [],
|
|
2255
|
+
skipped: [],
|
|
2256
|
+
diagnostics: [diagnostic("roles.dev-passwords-unsupported", "", "", project.provider === void 0 ? {} : { provider: project.provider })]
|
|
2257
|
+
};
|
|
2258
|
+
if (project.provider === "postgres") {
|
|
2259
|
+
if (db.shadowBase !== void 0) return {
|
|
2260
|
+
roles: [],
|
|
2261
|
+
skipped: [],
|
|
2262
|
+
diagnostics: [diagnostic("plan.shadow-base-unsupported", "", "")]
|
|
2263
|
+
};
|
|
2264
|
+
const database = databaseOf(db.target.url);
|
|
2265
|
+
if (database === "") return {
|
|
2266
|
+
roles: [],
|
|
2267
|
+
skipped: [],
|
|
2268
|
+
diagnostics: [diagnostic("database.failed", "", "", {
|
|
2269
|
+
tool: "roles",
|
|
2270
|
+
database: db.describe,
|
|
2271
|
+
error: "the database address names no database"
|
|
2272
|
+
})]
|
|
2273
|
+
};
|
|
2274
|
+
const dev = options.devPasswords === void 0 ? void 0 : devPasswordsFrom(options.devPasswords, db.target.url);
|
|
2275
|
+
if (dev?.ok === false) return {
|
|
2276
|
+
roles: [],
|
|
2277
|
+
skipped: [],
|
|
2278
|
+
diagnostics: dev.diagnostics
|
|
2279
|
+
};
|
|
2280
|
+
const set = postgresClusterSet(database);
|
|
2281
|
+
const { withDatabaseName } = await import("@supabase/pg-delta");
|
|
2282
|
+
const result = await ensurePostgresCluster(dbs, {
|
|
2283
|
+
maintenance: { url: withDatabaseName(db.target.url, "postgres") },
|
|
2284
|
+
target: db.target,
|
|
2285
|
+
template: { url: withDatabaseName(db.target.url, set.template) }
|
|
2286
|
+
}, set, dev === void 0 ? {} : { passwords: dev.passwords });
|
|
2287
|
+
if (!result.ok) return {
|
|
2288
|
+
roles: [],
|
|
2289
|
+
skipped: [],
|
|
2290
|
+
diagnostics: result.error.map(fromEngine)
|
|
2291
|
+
};
|
|
2292
|
+
return {
|
|
2293
|
+
roles: clusterRoles(result.value),
|
|
2294
|
+
skipped: result.value.skipped.map((name) => ({
|
|
2295
|
+
name,
|
|
2296
|
+
reason: "identity-table-missing"
|
|
2297
|
+
})),
|
|
2298
|
+
diagnostics: [],
|
|
2299
|
+
...dev === void 0 ? {} : { passwords: DEV_PASSWORD_VARIABLES.filter((v) => result.value.passwords?.includes(v.role)) }
|
|
2300
|
+
};
|
|
2301
|
+
}
|
|
2302
|
+
const ran = await ensurePlatformRoles(dbs, [{
|
|
2303
|
+
server: "target",
|
|
2304
|
+
db: db.target
|
|
2305
|
+
}, ...db.shadowBase === void 0 ? [] : [{
|
|
2306
|
+
server: "shadow",
|
|
2307
|
+
db: db.shadowBase
|
|
2308
|
+
}]], project.roles);
|
|
2309
|
+
return {
|
|
2310
|
+
roles: ran.created,
|
|
2311
|
+
skipped: [],
|
|
2312
|
+
diagnostics: (ran.refusal ?? []).map(fromEngine)
|
|
2313
|
+
};
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* Платформні ролі кластерні, тож у бажаному стані бази їх немає, і план їх
|
|
2317
|
+
* не створює (спека П4 §6.2, спека designer §3.2): їх створює окремий крок з правом
|
|
2318
|
+
* `CREATEROLE`. Ролі грантів задає платформа; файл проєкту потрібен лише
|
|
2319
|
+
* ролі входу — її членство в ролі запиту залежить від провайдера.
|
|
2320
|
+
*/
|
|
2321
|
+
const rolesTool = defineTool({
|
|
2322
|
+
name: "roles",
|
|
2323
|
+
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 `database.provider` from the project file; without it the login roles are skipped, and the output says so. An existing role is only checked, its role setting included; the one change is a missing membership of an existing login role in a parent of its profile, added WITH INHERIT FALSE, SET TRUE and named in the output. 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 (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 for shadows. It refuses before writing when the session is not a superuser, a database or role has an unsafe shape, a Simetra login role can connect to another database, or the server lacks plpgsql_check; a separate shadow server is not supported there. devPasswords (postgres, local database only) sets the password of each login role it creates from SIMETRA_{OWNER,AUTH,RUNTIME,SIGNALS}_DEV_PASSWORD.",
|
|
2324
|
+
input: z.strictObject({ devPasswords: z.boolean().optional() }),
|
|
2325
|
+
files: "read",
|
|
2326
|
+
database: "write",
|
|
2327
|
+
data: "none",
|
|
2328
|
+
destructive: false,
|
|
2329
|
+
async run({ dir, database, env }, input) {
|
|
2330
|
+
const set = await projectRoleSet(dir);
|
|
2331
|
+
if (!set.ok) return {
|
|
2332
|
+
ok: false,
|
|
2333
|
+
changes: [],
|
|
2334
|
+
diagnostics: set.diagnostics
|
|
2335
|
+
};
|
|
2336
|
+
const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
|
|
2337
|
+
const ran = await withDatabase(required$1(database), "roles", (db) => runRoles(createApplyDatabase({ readOnly: false }), db, set, input.devPasswords === true ? { devPasswords: env ?? {} } : {}));
|
|
2338
|
+
if (!ran.ok) return {
|
|
2339
|
+
ok: false,
|
|
2340
|
+
changes: [],
|
|
2341
|
+
diagnostics: failureDiagnostics(ran)
|
|
2342
|
+
};
|
|
2343
|
+
const data = {
|
|
2344
|
+
roles: ran.value.roles,
|
|
2345
|
+
skipped: [...set.skipped, ...ran.value.skipped],
|
|
2346
|
+
...ran.value.passwords === void 0 ? {} : { passwords: ran.value.passwords }
|
|
2347
|
+
};
|
|
2348
|
+
return {
|
|
2349
|
+
ok: ran.value.diagnostics.length === 0,
|
|
2350
|
+
changes: [],
|
|
2351
|
+
diagnostics: ran.value.diagnostics,
|
|
2352
|
+
data
|
|
2353
|
+
};
|
|
2354
|
+
},
|
|
2355
|
+
present: { text: (data, v) => data === void 0 || v.channel === "mcp" ? void 0 : [
|
|
2356
|
+
...data.roles.map((x) => `${x.server}: ${x.name} ${x.outcome}${x.added === void 0 ? "" : `; added membership in ${x.added.join(", ")}`}`),
|
|
2357
|
+
...data.skipped.map((x) => {
|
|
2358
|
+
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`;
|
|
2359
|
+
const at = x.name.lastIndexOf(":");
|
|
2360
|
+
return `target: ${x.name.slice(0, at)}: ${x.name.slice(at + 1)} not granted yet — run the Better Auth migration, then simetra roles again`;
|
|
2361
|
+
}),
|
|
2362
|
+
...(data.passwords ?? []).map((x) => `target: ${x.role} password set from ${x.variable}`),
|
|
2363
|
+
...v.diagnostics.length > 0 ? [v.report] : []
|
|
2364
|
+
].join("\n") }
|
|
2365
|
+
});
|
|
2366
|
+
// src/tools/signals-config.ts
|
|
2367
|
+
const PROJECT_FILE = "project.meta.json";
|
|
2368
|
+
/** Name of the outbox consumer in the Centrifugo config (postgres profile spec §6.1). */
|
|
2369
|
+
const SIGNAL_CONSUMER_NAME = "simetra_outbox";
|
|
2370
|
+
/**
|
|
2371
|
+
* Environment variables that give the consumer its DSNs (postgres profile spec
|
|
2372
|
+
* §10.1): Centrifugo overrides the consumer declared in the config with them,
|
|
2373
|
+
* so the password of `simetra_signals` never lands in the config file.
|
|
2374
|
+
*/
|
|
2375
|
+
const SIGNAL_CONSUMER_ENV = {
|
|
2376
|
+
dsn: "CENTRIFUGO_CONSUMERS_SIMETRA_OUTBOX_POSTGRESQL_DSN",
|
|
2377
|
+
notificationDsn: "CENTRIFUGO_CONSUMERS_SIMETRA_OUTBOX_POSTGRESQL_PARTITION_NOTIFICATION_DSN"
|
|
2378
|
+
};
|
|
2379
|
+
const NAMESPACES = [
|
|
2380
|
+
{
|
|
2381
|
+
name: "simetra",
|
|
2382
|
+
historySize: 100
|
|
2383
|
+
},
|
|
2384
|
+
{
|
|
2385
|
+
name: "simetra-rights",
|
|
2386
|
+
historySize: 20
|
|
2387
|
+
},
|
|
2388
|
+
{
|
|
2389
|
+
name: "simetra-user",
|
|
2390
|
+
historySize: 20
|
|
2391
|
+
}
|
|
2392
|
+
];
|
|
2393
|
+
const PRESENCE_UPDATE_INTERVAL = "5s";
|
|
2394
|
+
const EXPIRED_SUB_CLOSE_DELAY = "25s";
|
|
2395
|
+
const EXPIRED_CLOSE_DELAY = "25s";
|
|
2396
|
+
const HISTORY_TTL = "300s";
|
|
2397
|
+
const HISTORY_META_TTL = "24h";
|
|
2398
|
+
const RECOVERY_MAX_PUBLICATION_LIMIT = 300;
|
|
2399
|
+
const OUTBOX_TABLE = `${quoteIdent(SIGNAL_OUTBOX.schema)}.${quoteIdent(SIGNAL_OUTBOX.name)}`;
|
|
2400
|
+
/**
|
|
2401
|
+
* Centrifugo v6 config of one application (postgres profile spec §6.1, §5.3):
|
|
2402
|
+
* three namespaces with history and forced recovery, no client permission,
|
|
2403
|
+
* the outbox consumer with empty DSNs (they come from `SIGNAL_CONSUMER_ENV`),
|
|
2404
|
+
* the HTTP API off. No `http_server`: the address is the deployment's choice.
|
|
2405
|
+
*/
|
|
2406
|
+
function centrifugoConfig(o) {
|
|
2407
|
+
return {
|
|
2408
|
+
client: {
|
|
2409
|
+
allowed_origins: [o.origin],
|
|
2410
|
+
token: {
|
|
2411
|
+
jwks_public_endpoint: o.jwksUrl,
|
|
2412
|
+
audience: `centrifugo:${o.projectName}`,
|
|
2413
|
+
issuer: o.issuer
|
|
2414
|
+
},
|
|
2415
|
+
recovery_max_publication_limit: RECOVERY_MAX_PUBLICATION_LIMIT,
|
|
2416
|
+
presence_update_interval: PRESENCE_UPDATE_INTERVAL,
|
|
2417
|
+
expired_sub_close_delay: EXPIRED_SUB_CLOSE_DELAY,
|
|
2418
|
+
expired_close_delay: EXPIRED_CLOSE_DELAY
|
|
2419
|
+
},
|
|
2420
|
+
channel: {
|
|
2421
|
+
max_length: CENTRIFUGO_CHANNEL_MAX,
|
|
2422
|
+
without_namespace: {},
|
|
2423
|
+
namespaces: NAMESPACES.map((n) => ({
|
|
2424
|
+
name: n.name,
|
|
2425
|
+
history_size: n.historySize,
|
|
2426
|
+
history_ttl: HISTORY_TTL,
|
|
2427
|
+
history_meta_ttl: HISTORY_META_TTL,
|
|
2428
|
+
force_recovery: true
|
|
2429
|
+
}))
|
|
2430
|
+
},
|
|
2431
|
+
consumers: [{
|
|
2432
|
+
enabled: true,
|
|
2433
|
+
name: SIGNAL_CONSUMER_NAME,
|
|
2434
|
+
type: "postgresql",
|
|
2435
|
+
postgresql: {
|
|
2436
|
+
dsn: "",
|
|
2437
|
+
partition_notification_dsn: "",
|
|
2438
|
+
outbox_table_name: OUTBOX_TABLE,
|
|
2439
|
+
num_partitions: 1,
|
|
2440
|
+
partition_select_limit: 100,
|
|
2441
|
+
partition_poll_interval: `300ms`,
|
|
2442
|
+
partition_notification_channel: SIGNAL_NOTIFY_CHANNEL,
|
|
2443
|
+
use_try_lock: true
|
|
2444
|
+
}
|
|
2445
|
+
}],
|
|
2446
|
+
http_api: { disabled: true },
|
|
2447
|
+
health: { enabled: true },
|
|
2448
|
+
log: { level: "info" }
|
|
2449
|
+
};
|
|
2450
|
+
}
|
|
2451
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2452
|
+
function object(shape) {
|
|
2453
|
+
return (value, path) => {
|
|
2454
|
+
if (!isRecord(value)) return [`${path}: expected an object`];
|
|
2455
|
+
const extra = Object.keys(value).filter((key) => !Object.hasOwn(shape, key)).map((key) => `${path}.${key}: not an allowed option`);
|
|
2456
|
+
const own = Object.entries(shape).flatMap(([key, rule]) => Object.hasOwn(value, key) ? rule(value[key], `${path}.${key}`) : [`${path}.${key}: missing`]);
|
|
2457
|
+
return [...extra, ...own];
|
|
2458
|
+
};
|
|
2459
|
+
}
|
|
2460
|
+
const exactly = (expected) => (value, path) => value === expected ? [] : [`${path}: must be ${JSON.stringify(expected)}, got ${JSON.stringify(value)}`];
|
|
2461
|
+
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}`];
|
|
2462
|
+
const duration = (value, path) => typeof value === "string" && /^\d+(ms|s|m|h)$/.test(value) ? [] : [`${path}: must be a duration such as "300s"`];
|
|
2463
|
+
const DURATION_MS = {
|
|
2464
|
+
ms: 1,
|
|
2465
|
+
s: 1e3,
|
|
2466
|
+
m: 6e4,
|
|
2467
|
+
h: 36e5
|
|
2468
|
+
};
|
|
2469
|
+
const durationMs = (value) => {
|
|
2470
|
+
const [, amount, unit] = /^(\d+)(ms|s|m|h)$/.exec(value);
|
|
2471
|
+
return Number(amount) * DURATION_MS[unit];
|
|
2472
|
+
};
|
|
2473
|
+
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}`];
|
|
2474
|
+
const nonEmpty = (value, path) => typeof value === "string" && value.trim() !== "" ? [] : [`${path}: must be a non-empty string`];
|
|
2475
|
+
const origin = (value, path) => {
|
|
2476
|
+
if (typeof value === "string" && URL.canParse(value)) {
|
|
2477
|
+
const url = new URL(value);
|
|
2478
|
+
if ((url.protocol === "https:" || url.protocol === "http:") && url.origin === value) return [];
|
|
2479
|
+
}
|
|
2480
|
+
return [`${path}: must be an http(s) origin, got ${JSON.stringify(value)}`];
|
|
2481
|
+
};
|
|
2482
|
+
const LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/;
|
|
2483
|
+
const SERVICE_NAME = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/i;
|
|
2484
|
+
/**
|
|
2485
|
+
* JWKS лише через TLS чи внутрішню адресу (спека профілю §6.3): підміна
|
|
2486
|
+
* відповіді JWKS дала б токен на будь-який канал.
|
|
2487
|
+
*/
|
|
2488
|
+
const jwksUrl = (value, path) => {
|
|
2489
|
+
const refused = [`${path}: must be an https: URL, or http: on a loopback address or a single-label service name, got ${JSON.stringify(value)}`];
|
|
2490
|
+
if (typeof value !== "string" || !URL.canParse(value)) return refused;
|
|
2491
|
+
const url = new URL(value);
|
|
2492
|
+
if (url.username !== "" || url.password !== "") return refused;
|
|
2493
|
+
if (url.protocol === "https:") return [];
|
|
2494
|
+
if (url.protocol !== "http:") return refused;
|
|
2495
|
+
return LOOPBACK_HOST.test(url.hostname) || SERVICE_NAME.test(url.hostname) && !/^\d+$/.test(url.hostname) ? [] : refused;
|
|
2496
|
+
};
|
|
2497
|
+
const namespace = object({
|
|
2498
|
+
name: nonEmpty,
|
|
2499
|
+
history_size: int(1),
|
|
2500
|
+
history_ttl: duration,
|
|
2501
|
+
history_meta_ttl: duration,
|
|
2502
|
+
force_recovery: exactly(true)
|
|
2503
|
+
});
|
|
2504
|
+
const namespaces = (value, path) => {
|
|
2505
|
+
if (!Array.isArray(value)) return [`${path}: expected an array`];
|
|
2506
|
+
const own = value.flatMap((n, i) => namespace(n, `${path}[${i}]`));
|
|
2507
|
+
const names = value.map((n) => isRecord(n) ? n.name : void 0);
|
|
2508
|
+
const expected = NAMESPACES.map((n) => n.name);
|
|
2509
|
+
const set = names.length === expected.length && expected.every((name) => names.includes(name)) ? [] : [`${path}: must be exactly the namespaces ${expected.join(", ")}`];
|
|
2510
|
+
const simetra = value.find((n) => isRecord(n) && n.name === "simetra");
|
|
2511
|
+
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)`] : [];
|
|
2512
|
+
return [
|
|
2513
|
+
...own,
|
|
2514
|
+
...set,
|
|
2515
|
+
...history
|
|
2516
|
+
];
|
|
2517
|
+
};
|
|
2518
|
+
const consumer = object({
|
|
2519
|
+
enabled: exactly(true),
|
|
2520
|
+
name: exactly(SIGNAL_CONSUMER_NAME),
|
|
2521
|
+
type: exactly("postgresql"),
|
|
2522
|
+
postgresql: object({
|
|
2523
|
+
dsn: exactly(""),
|
|
2524
|
+
partition_notification_dsn: exactly(""),
|
|
2525
|
+
outbox_table_name: exactly(OUTBOX_TABLE),
|
|
2526
|
+
num_partitions: exactly(1),
|
|
2527
|
+
partition_select_limit: int(1),
|
|
2528
|
+
partition_poll_interval: duration,
|
|
2529
|
+
partition_notification_channel: exactly(SIGNAL_NOTIFY_CHANNEL),
|
|
2530
|
+
use_try_lock: exactly(true)
|
|
2531
|
+
})
|
|
2532
|
+
});
|
|
2533
|
+
const consumers = (value, path) => Array.isArray(value) && value.length === 1 ? consumer(value[0], `${path}[0]`) : [`${path}: must hold exactly the consumer ${SIGNAL_CONSUMER_NAME}`];
|
|
2534
|
+
const config = object({
|
|
2535
|
+
client: object({
|
|
2536
|
+
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`],
|
|
2537
|
+
token: object({
|
|
2538
|
+
jwks_public_endpoint: jwksUrl,
|
|
2539
|
+
audience: (value, path) => typeof value === "string" && /^centrifugo:\S+$/.test(value) ? [] : [`${path}: must be centrifugo:<project name>`],
|
|
2540
|
+
issuer: nonEmpty
|
|
2541
|
+
}),
|
|
2542
|
+
recovery_max_publication_limit: int(1),
|
|
2543
|
+
presence_update_interval: durationAtMost(PRESENCE_UPDATE_INTERVAL),
|
|
2544
|
+
expired_sub_close_delay: durationAtMost(EXPIRED_SUB_CLOSE_DELAY),
|
|
2545
|
+
expired_close_delay: durationAtMost(EXPIRED_CLOSE_DELAY)
|
|
2546
|
+
}),
|
|
2547
|
+
channel: object({
|
|
2548
|
+
max_length: int(1, CENTRIFUGO_CHANNEL_MAX),
|
|
2549
|
+
without_namespace: object({}),
|
|
2550
|
+
namespaces
|
|
2551
|
+
}),
|
|
2552
|
+
consumers,
|
|
2553
|
+
http_api: object({ disabled: exactly(true) }),
|
|
2554
|
+
health: object({ enabled: exactly(true) }),
|
|
2555
|
+
log: object({ level: exactly("info") })
|
|
2556
|
+
});
|
|
2557
|
+
/**
|
|
2558
|
+
* Refusals of a Centrifugo config (P4-B block B2, invariant 11): every level
|
|
2559
|
+
* is a whitelist of keys, so a client permission (`allow_*_for_*`,
|
|
2560
|
+
* anonymous connect, presence), an insecure or admin mode, a secret
|
|
2561
|
+
* (`hmac_secret_key`, a DSN), another listener (`http_server`, `grpc_api`)
|
|
2562
|
+
* or an open origin is refused. Empty for the output of `centrifugoConfig`.
|
|
2563
|
+
*/
|
|
2564
|
+
function centrifugoConfigRefusals(value) {
|
|
2565
|
+
return config(value, "config");
|
|
2566
|
+
}
|
|
1692
2567
|
// src/tools/catalog.ts
|
|
1693
2568
|
/** Єдиний каталог інструментів: CLI, MCP і студія — лише його адаптери. */
|
|
1694
2569
|
const TOOLS = [
|
|
@@ -1697,6 +2572,7 @@ const TOOLS = [
|
|
|
1697
2572
|
fixTool,
|
|
1698
2573
|
createTool,
|
|
1699
2574
|
addTool,
|
|
2575
|
+
declareFunctionTool,
|
|
1700
2576
|
renameTool,
|
|
1701
2577
|
deleteTool,
|
|
1702
2578
|
promoteTool,
|
|
@@ -1704,50 +2580,81 @@ const TOOLS = [
|
|
|
1704
2580
|
diffTool,
|
|
1705
2581
|
planTool,
|
|
1706
2582
|
applyTool,
|
|
2583
|
+
rolesTool,
|
|
2584
|
+
rightsMaintenanceTool,
|
|
1707
2585
|
defineTool({
|
|
1708
|
-
name: "
|
|
1709
|
-
description:
|
|
1710
|
-
input: z.strictObject({
|
|
2586
|
+
name: "signals-config",
|
|
2587
|
+
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.`,
|
|
2588
|
+
input: z.strictObject({
|
|
2589
|
+
origin: z.string(),
|
|
2590
|
+
issuer: z.string(),
|
|
2591
|
+
jwksUrl: z.string()
|
|
2592
|
+
}),
|
|
1711
2593
|
files: "read",
|
|
1712
|
-
database: "
|
|
2594
|
+
database: "none",
|
|
1713
2595
|
data: "none",
|
|
1714
2596
|
destructive: false,
|
|
1715
|
-
async run({ dir,
|
|
1716
|
-
const
|
|
1717
|
-
if (
|
|
2597
|
+
async run({ dir }, input) {
|
|
2598
|
+
const text = (await readMetadataDir(dir)).get(PROJECT_FILE);
|
|
2599
|
+
if (text === void 0) return {
|
|
1718
2600
|
ok: false,
|
|
1719
2601
|
changes: [],
|
|
1720
|
-
diagnostics:
|
|
2602
|
+
diagnostics: [diagnostic("project.missing", PROJECT_FILE, "")]
|
|
1721
2603
|
};
|
|
1722
|
-
const
|
|
1723
|
-
|
|
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 {
|
|
2604
|
+
const read = readProjectFile(text);
|
|
2605
|
+
if (read.project === void 0) return {
|
|
1731
2606
|
ok: false,
|
|
1732
2607
|
changes: [],
|
|
1733
|
-
diagnostics:
|
|
2608
|
+
diagnostics: read.diagnostics
|
|
1734
2609
|
};
|
|
1735
|
-
const
|
|
1736
|
-
|
|
1737
|
-
|
|
2610
|
+
const config = centrifugoConfig({
|
|
2611
|
+
projectName: read.project.name,
|
|
2612
|
+
...input
|
|
2613
|
+
});
|
|
2614
|
+
const refusals = centrifugoConfigRefusals(config);
|
|
2615
|
+
if (refusals.length > 0) return {
|
|
2616
|
+
ok: false,
|
|
2617
|
+
changes: [],
|
|
2618
|
+
diagnostics: [],
|
|
2619
|
+
refusal: refusals.join("\n")
|
|
1738
2620
|
};
|
|
1739
2621
|
return {
|
|
1740
|
-
ok:
|
|
2622
|
+
ok: true,
|
|
1741
2623
|
changes: [],
|
|
1742
|
-
diagnostics:
|
|
1743
|
-
data
|
|
2624
|
+
diagnostics: [],
|
|
2625
|
+
data: {
|
|
2626
|
+
config,
|
|
2627
|
+
environment: [SIGNAL_CONSUMER_ENV.dsn, SIGNAL_CONSUMER_ENV.notificationDsn]
|
|
2628
|
+
}
|
|
1744
2629
|
};
|
|
1745
|
-
}
|
|
2630
|
+
},
|
|
2631
|
+
present: { text: (data) => data === void 0 ? void 0 : JSON.stringify(data.config, null, 2) }
|
|
1746
2632
|
}),
|
|
1747
|
-
rightsMaintenanceTool,
|
|
1748
2633
|
dataReadTool,
|
|
1749
2634
|
dataCommandTool
|
|
1750
2635
|
];
|
|
2636
|
+
/**
|
|
2637
|
+
* Поля `data` інструмента у структурованому результаті обох каналів: їх
|
|
2638
|
+
* вирішує `tool.present`, не ім'я інструмента.
|
|
2639
|
+
*/
|
|
2640
|
+
function structureOf(tool, data) {
|
|
2641
|
+
return tool.present?.structure?.(data) ?? data;
|
|
2642
|
+
}
|
|
2643
|
+
/**
|
|
2644
|
+
* Що з результату показують канали: єдиний розв'язок для CLI і MCP. `data`
|
|
2645
|
+
* не показується, коли в інструмента нема `present`, коли він лише
|
|
2646
|
+
* діагностичний (`compile`: модель — не відповідь агентові, вона ~МБ) і коли
|
|
2647
|
+
* `bare`-результат не `ok`. Інструмент осі `artifact` показується й без
|
|
2648
|
+
* `data`: відмова теж має артефакти.
|
|
2649
|
+
*/
|
|
2650
|
+
function presentation(tool, r) {
|
|
2651
|
+
const p = tool.present;
|
|
2652
|
+
const shown = p !== void 0 && p.diagnosticsOnly !== true && (p.bare === true ? r.ok && r.data !== void 0 : r.data !== void 0 || tool.files === "artifact");
|
|
2653
|
+
return {
|
|
2654
|
+
shown,
|
|
2655
|
+
data: shown ? r.data : void 0
|
|
2656
|
+
};
|
|
2657
|
+
}
|
|
1751
2658
|
function toolByName(name) {
|
|
1752
2659
|
return TOOLS.find((t) => t.name === name);
|
|
1753
2660
|
}
|
|
@@ -1869,6 +2776,7 @@ async function invoke(tool, input, o) {
|
|
|
1869
2776
|
dir: o.dir,
|
|
1870
2777
|
root,
|
|
1871
2778
|
...tool.database === "none" ? {} : { database: o.database },
|
|
2779
|
+
...tool.database === "none" || o.env === void 0 ? {} : { env: o.env },
|
|
1872
2780
|
...tool.data === "none" ? {} : { data: o.data },
|
|
1873
2781
|
...tool.data === "write" ? { allowRightsWrite: o.allowRightsWrite === true } : {},
|
|
1874
2782
|
...o.baseline === void 0 ? {} : { baseline: o.baseline }
|
|
@@ -1878,21 +2786,26 @@ async function invoke(tool, input, o) {
|
|
|
1878
2786
|
checkArtifacts(root, artifacts);
|
|
1879
2787
|
let write = false;
|
|
1880
2788
|
let writeArtifacts = false;
|
|
2789
|
+
let wouldWrite = false;
|
|
1881
2790
|
switch (tool.files) {
|
|
1882
2791
|
case "read": break;
|
|
1883
2792
|
case "artifact":
|
|
1884
|
-
if (outcome.changes.length > 0) throw new Error(`${tool.name} is an artifact tool and must not change the metadata directory`);
|
|
1885
2793
|
writeArtifacts = outcome.ok && artifacts.length > 0;
|
|
1886
2794
|
break;
|
|
1887
|
-
case "write":
|
|
1888
|
-
|
|
1889
|
-
|
|
2795
|
+
case "write": {
|
|
2796
|
+
const accepted = outcome.ok || outcome.written === true;
|
|
2797
|
+
write = accepted && !o.dryRun && outcome.changes.length > 0;
|
|
2798
|
+
writeArtifacts = accepted && !o.dryRun && artifacts.length > 0;
|
|
2799
|
+
wouldWrite = accepted && o.dryRun && (outcome.changes.length > 0 || artifacts.length > 0);
|
|
2800
|
+
break;
|
|
2801
|
+
}
|
|
1890
2802
|
}
|
|
1891
2803
|
if (writeArtifacts) await writeChanges(root, artifacts);
|
|
1892
2804
|
if (write) await writeChanges(o.dir, outcome.changes);
|
|
1893
2805
|
return {
|
|
1894
2806
|
ok: outcome.ok,
|
|
1895
2807
|
written: write || writeArtifacts,
|
|
2808
|
+
...wouldWrite ? { wouldWrite: true } : {},
|
|
1896
2809
|
changes: outcome.changes.map((c) => ({
|
|
1897
2810
|
path: c.path,
|
|
1898
2811
|
deleted: c.content === null
|
|
@@ -1912,148 +2825,4 @@ async function invoke(tool, input, o) {
|
|
|
1912
2825
|
}
|
|
1913
2826
|
});
|
|
1914
2827
|
}
|
|
1915
|
-
|
|
1916
|
-
/** Діагностика з текстом потрібною мовою; саме її віддають обидва формати. */
|
|
1917
|
-
function localized(d, locale) {
|
|
1918
|
-
const { message, hint } = localize(d, locale);
|
|
1919
|
-
const rest = { ...d };
|
|
1920
|
-
delete rest.hint;
|
|
1921
|
-
return {
|
|
1922
|
-
...rest,
|
|
1923
|
-
message,
|
|
1924
|
-
...hint === void 0 ? {} : { hint }
|
|
1925
|
-
};
|
|
1926
|
-
}
|
|
1927
|
-
function formatDiagnostics(diagnostics, { dir, locale, format }) {
|
|
1928
|
-
const items = diagnostics.map((d) => localized(d, locale));
|
|
1929
|
-
if (format === "json") return JSON.stringify(items.map((d) => ({
|
|
1930
|
-
...d,
|
|
1931
|
-
dir
|
|
1932
|
-
})), null, 2);
|
|
1933
|
-
const lines = [];
|
|
1934
|
-
for (const d of items) {
|
|
1935
|
-
lines.push(`${placeOf(d, dir)} ${d.severity} ${d.code} ${d.message}`);
|
|
1936
|
-
if (d.hint !== void 0) lines.push(` hint: ${d.hint}`);
|
|
1937
|
-
}
|
|
1938
|
-
const errors = items.filter((d) => d.severity === "error").length;
|
|
1939
|
-
lines.push(`${errors} error(s), ${items.length - errors} warning(s)`);
|
|
1940
|
-
return lines.join("\n");
|
|
1941
|
-
}
|
|
1942
|
-
/**
|
|
1943
|
-
* Місце діагностики в тексті. Позиція друкується лише тоді, коли вона є:
|
|
1944
|
-
* діагностика без файлу (вхід операції загалом) чи файлу, якого немає в
|
|
1945
|
-
* теці, отримала б фальшиве `:1:1`, а читач шукав би там неіснуючу причину.
|
|
1946
|
-
*/
|
|
1947
|
-
function placeOf(d, dir) {
|
|
1948
|
-
if (d.file === "") return `${dir}:`;
|
|
1949
|
-
if (d.range === void 0) return `${dir}/${d.file}:`;
|
|
1950
|
-
const { line, character } = d.range.start;
|
|
1951
|
-
return `${dir}/${d.file}:${line + 1}:${character + 1}`;
|
|
1952
|
-
}
|
|
1953
|
-
/** Зведення звірки: дії плану, відмінності каталогу, діагностика. */
|
|
1954
|
-
function renderDiff(d, report) {
|
|
1955
|
-
const lines = [];
|
|
1956
|
-
if (d.plan.length > 0) {
|
|
1957
|
-
lines.push(`plan (${d.plan.length} action(s), database -> metadata):`);
|
|
1958
|
-
for (const a of d.plan) {
|
|
1959
|
-
const tags = [a.dataLoss ? "data loss" : void 0, a.rewriteRisk ? "rewrite" : void 0].filter((x) => x !== void 0);
|
|
1960
|
-
lines.push(` ${a.sql.trim()}${tags.length > 0 ? ` -- ${tags.join(", ")}` : ""}`);
|
|
1961
|
-
}
|
|
1962
|
-
}
|
|
1963
|
-
if (d.differences.length > 0) {
|
|
1964
|
-
lines.push(`differences (${d.differences.length}):`);
|
|
1965
|
-
for (const x of d.differences) lines.push(` ${x.kind} ${x.path}: ${x.detail}`);
|
|
1966
|
-
}
|
|
1967
|
-
if (d.applyState === "absent") lines.push("apply state: absent from the database; the first apply creates it");
|
|
1968
|
-
if (d.empty) lines.push("diff: the database matches the metadata");
|
|
1969
|
-
lines.push(report);
|
|
1970
|
-
return lines.join("\n");
|
|
1971
|
-
}
|
|
1972
|
-
const short = (hash) => hash === null ? "initial" : hash.slice(0, 12);
|
|
1973
|
-
/** Режим `plpgsql_check` плану словами виводу. */
|
|
1974
|
-
const PLPGSQL_CHECK_LABEL = {
|
|
1975
|
-
installed: "installed",
|
|
1976
|
-
transient: "transient (installed for the check, rolled back)",
|
|
1977
|
-
unavailable: "unavailable"
|
|
1978
|
-
};
|
|
1979
|
-
const qualified = (schema, name) => `${quoteIdent(schema)}.${quoteIdent(name)}`;
|
|
1980
|
-
/**
|
|
1981
|
-
* Блок «Promotion»: що стає чим і що людина
|
|
1982
|
-
* дозволяє. Таблиця, що лишає своє ім'я, рядка перейменування не дає:
|
|
1983
|
-
* `a -> a` читався б як зміна, якої немає.
|
|
1984
|
-
*/
|
|
1985
|
-
function promotionLines(p, needs) {
|
|
1986
|
-
const lines = [`promotion: ${p.kind} ${p.name} (${p.objectId})`, ` record hash: ${p.recordHash}`];
|
|
1987
|
-
for (const t of p.tables.filter((x) => x.from !== x.to)) lines.push(` table ${qualified(t.schema, t.from)} -> ${qualified(t.schema, t.to)}`);
|
|
1988
|
-
for (const c of p.columns) lines.push(` column ${qualified(c.table.schema, c.table.name)}: ${quoteIdent(c.from)} -> ${quoteIdent(c.to)}`);
|
|
1989
|
-
for (const c of p.canonicalNames) lines.push(` ${c.kind} ${qualified(c.table.schema, c.table.name)}: ${quoteIdent(c.from)} -> ${quoteIdent(c.to)}`);
|
|
1990
|
-
for (const t of p.data) {
|
|
1991
|
-
lines.push(` data steps ${qualified(t.after.schema, t.after.table)}:`);
|
|
1992
|
-
for (const c of t.columns) lines.push(` ${c.step} ${quoteIdent(c.column)} ← ${c.expression} (${c.kind})`);
|
|
1993
|
-
if (t.triggers.length > 0) lines.push(` triggers disabled during the write: ${t.triggers.map((x) => quoteIdent(x.name)).join(", ")}`);
|
|
1994
|
-
}
|
|
1995
|
-
for (const item of p.permissionItems) {
|
|
1996
|
-
lines.push(` ${item.token}${needs.has(item.token) ? ` (needs allow: ${item.token})` : ""}`);
|
|
1997
|
-
for (const s of item.summary) lines.push(` ${s}`);
|
|
1998
|
-
}
|
|
1999
|
-
return lines;
|
|
2000
|
-
}
|
|
2001
|
-
/**
|
|
2002
|
-
* Зведення плану для людини й агента: звідки й куди, `planHash` і файл,
|
|
2003
|
-
* дрейф — першим блоком, до кроків (платформна спека §6.2): кроки читаються
|
|
2004
|
-
* вже знаючи, що ціль дрейфнула. Далі — промоція, бо кроки наміру й класи
|
|
2005
|
-
* конверсій читаються, знаючи, що стає чим. Повний
|
|
2006
|
-
* SQL — у файлі плану; тут перший рядок.
|
|
2007
|
-
*/
|
|
2008
|
-
function renderPlan(d, report, o) {
|
|
2009
|
-
if (d === void 0 || "unchanged" in d) return [o.ok ? "plan: nothing to apply; the database is at the metadata" : "plan: no plan written: the plan was refused or has errors", report].join("\n");
|
|
2010
|
-
const needs = new Set(d.requiredPermissions);
|
|
2011
|
-
const lines = [
|
|
2012
|
-
`plan ${short(d.fromHash)} -> ${short(d.toHash)}`,
|
|
2013
|
-
`${o.written ? "written" : "not written"} ${d.file}`,
|
|
2014
|
-
`planHash: ${d.planHash}`
|
|
2015
|
-
];
|
|
2016
|
-
if (d.drift !== null) {
|
|
2017
|
-
lines.push(`drift (${d.drift.reason}): needs allow: drift`);
|
|
2018
|
-
if (d.drift.sections.length > 0) lines.push(` fingerprint sections: ${d.drift.sections.join(", ")}`);
|
|
2019
|
-
for (const path of d.drift.paths) lines.push(` ${path}`);
|
|
2020
|
-
}
|
|
2021
|
-
if (d.promotion !== null) lines.push(...promotionLines(d.promotion, needs));
|
|
2022
|
-
const stepLine = (s) => {
|
|
2023
|
-
const tags = [
|
|
2024
|
-
`lock ${s.lockClass}`,
|
|
2025
|
-
...s.conversion === void 0 ? [] : [`conversion ${s.conversion}`],
|
|
2026
|
-
...needs.has(s.id) ? [`needs allow: ${s.id}`] : []
|
|
2027
|
-
];
|
|
2028
|
-
const first = s.sql.trim().split("\n")[0] ?? "";
|
|
2029
|
-
return ` ${s.id} ${s.origin} ${s.class} (${tags.join("; ")}) ${first}`;
|
|
2030
|
-
};
|
|
2031
|
-
const environment = d.steps.filter((s) => s.origin === "environment");
|
|
2032
|
-
const steps = d.steps.filter((s) => s.origin !== "environment");
|
|
2033
|
-
if (steps.length === 0) lines.push("steps: none");
|
|
2034
|
-
else {
|
|
2035
|
-
lines.push(`steps (${steps.length}):`);
|
|
2036
|
-
lines.push(...steps.map(stepLine));
|
|
2037
|
-
}
|
|
2038
|
-
if (environment.length > 0) {
|
|
2039
|
-
lines.push(`environment rights: the global default privileges of role ${quoteIdent(d.environment.role)}:`);
|
|
2040
|
-
lines.push(...environment.map(stepLine));
|
|
2041
|
-
}
|
|
2042
|
-
if (d.locks.length > 0) lines.push(`locks up front: ${d.locks.map((l) => `${qualified(l.schema, l.name)} ${LOCK_MODE_SQL[l.mode]}`).join(", ")}`);
|
|
2043
|
-
for (const l of d.implicitLocks) lines.push(`implicit lock: ${qualified(l.schema, l.name)} ${LOCK_MODE_SQL[l.mode]} taken by step ${l.step}, not up front: the apply role may not lock it explicitly`);
|
|
2044
|
-
lines.push(`plpgsql_check: ${PLPGSQL_CHECK_LABEL[d.plpgsqlCheck]}`);
|
|
2045
|
-
if (d.expectedBlindFunctions > 0) lines.push(`expected provider blind functions (preset): ${d.expectedBlindFunctions}`);
|
|
2046
|
-
lines.push(report);
|
|
2047
|
-
return lines.join("\n");
|
|
2048
|
-
}
|
|
2049
|
-
/**
|
|
2050
|
-
* Підсумок застосування; репетиція нагадує, що блокування були справжні.
|
|
2051
|
-
* Без даних заголовок судить за діагностикою: після обриву з невідомим
|
|
2052
|
-
* результатом «нічого не записано» було б неправдою, а повтор за нею міг би
|
|
2053
|
-
* застосувати план удруге.
|
|
2054
|
-
*/
|
|
2055
|
-
function renderApply(d, diagnostics, report) {
|
|
2056
|
-
const unknown = diagnostics.find((x) => x.code === "apply.connection-lost" && x.params?.outcome === "unknown");
|
|
2057
|
-
return [d === void 0 ? unknown === void 0 ? "apply: nothing was written" : `apply: outcome unknown — check simetra.ledger for apply id ${String(unknown.params?.applyId)}` : d.status === "committed" ? `apply: committed in ${d.attempts} attempt(s)` : `rehearse: rolled back after ${d.attempts} attempt(s); the database was not changed; ${d.report === null ? "no rehearsal report was written" : `rehearsal report written to ${d.report}`}. The rehearsal took the plan's locks, as apply does.`, report].join("\n");
|
|
2058
|
-
}
|
|
2059
|
-
export { invoke as a, summarizeData as c, writeChanges as d, checkEnvName as f, databaseResource as h, renderPlan as i, toJson as l, parseDataLaunch as m, renderApply as n, TOOLS as o, dataResource as p, renderDiff as r, toolByName as s, formatDiagnostics as t, isMetadataFile as u };
|
|
2828
|
+
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 };
|