@simetrajs/designer 0.2.0 → 0.3.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { r as defineTool, t as PLANS_DIR } from "./types-iWavtmdS.js";
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 ShadowServerError, r as ShadowServerMismatchError, t as ShadowCreateRefusedError } from "./errors-Brw6UjAD.js";
4
+ import { a as ShadowTemplateMissingError, i as ShadowServerMismatchError, n as ShadowCreateRefusedError, o as shadowDropOf, r as ShadowServerError, t as ShadowBaseUnsupportedError } from "./errors-D1P2kKbL.js";
5
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, KIND_REGISTRY, PLATFORM_LOGIN_ROLES, PLATFORM_ROLES, PLATFORM_SCHEMA, PROVIDER_API_ROLES, PROVIDER_SCHEMAS, SQL_DEBT_FILE, UUID_TEXT, batchSchema, logicalTypeOf, metadataKindSchema, objectNameSchema, quoteIdent, readQuerySchema } from "simetra/model";
8
- import { ApplyConnectionLost, ApplyDbError, FINGERPRINT_VERSION, LOCK_MODE_SQL, PLATFORM_VERSION, applyStateOf, buildPlan, checkOwnerMembership, checkPermissions, checkPlatformRoles, compareWithDesired, desiredForApply, engineScope, ensurePlatformRoles, executePlan, parsePlan, parseRehearsal, planFileName, platformRoleSet, rehearsalFileName, rehearsalReport, reverseGenerate, runRightsMaintenance, serializePlan, serializeRehearsal, verifyPlanHash } from "simetra/schema";
7
+ import { ATTRIBUTE_CASES, CENTRIFUGO_CHANNEL_MAX, CommandFailure, DATABASE_PROVIDERS, FUNCTIONS_FILE_SUFFIX, PLATFORM_LOGIN_ROLES, PLATFORM_ROLES, PLATFORM_SCHEMA, PROVIDER_API_ROLES, PROVIDER_IDENTITY_SOURCES, PROVIDER_SCHEMAS, SIGNAL_MERGE_THRESHOLD, SIGNAL_NOTIFY_CHANNEL, SIGNAL_OUTBOX, SQL_DEBT_FILE, UUID_TEXT, batchSchema, logicalTypeOf, metadataKindSchema, objectNameSchema, quoteIdent, readQuerySchema } from "simetra/model";
8
+ import { ApplyConnectionLost, ApplyDbError, FINGERPRINT_VERSION, LOCK_MODE_SQL, PLATFORM_VERSION, applyStateOf, buildPlan, checkOwnerAttributes, checkOwnerMembership, checkPermissions, checkPlatformRoles, compareWithDesired, copiesShadowFromTemplate, desiredForApply, engineScope, ensurePlatformRoles, ensurePostgresCluster, executePlan, folderReference, parsePlan, parseRehearsal, planFileName, platformRoleSet, postgresClusterSet, readShadowEnvironment, rehearsalFileName, rehearsalReport, reverseGenerate, runRightsMaintenance, serializePlan, serializeRehearsal, verifyPlanHash } from "simetra/schema";
9
9
  import pg from "pg";
10
- import { CommandFailure, createCommandRuntime, fromPgPool, readRoleOf } from "simetra/server";
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 u = new URL(url);
55
- const db = decodeURIComponent(u.pathname.replace(/^\//, ""));
56
- return `${u.hostname}:${u.port === "" ? "5432" : u.port}/${db}`;
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 "the configured database";
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
- return classify(error, names, "");
140
+ const c = classify(error, names, "");
141
+ const drop = shadowDropOf(error);
142
+ if (drop === void 0) return c;
143
+ const shadowDrop = diagnostic("engine.shadow-drop-failed", "", "", drop.params);
144
+ return c.kind === "refusal" ? {
145
+ kind: "refusal",
146
+ message: `${c.message} ${shadowDrop.message}`
147
+ } : {
148
+ ...c,
149
+ shadowDrop
150
+ };
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 ? "" : " Point --shadow-url-env at a server where it has it."}`);
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$1 = "project.meta.json";
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-DPPnife2.js");
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, enum types PgEnum, everything else verbatim .sql files; ids of known objects are kept. The connection comes from the server's environment. Scope: the schemas of the existing metadata plus `schemas`; a directory without project.meta.json needs `schemas`. Writes nothing when anything is unrepresentable or does not compile.",
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 provider = new Set(PROVIDER_SCHEMAS.supabase);
617
- const foreign = (input.schemas ?? []).filter((s) => provider.has(s));
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 (existing.has(PROJECT_FILE$1)) {
623
- const compiled = await compile(existing);
624
- if (compiled.model === void 0) return {
625
- ok: false,
626
- changes: [],
627
- diagnostics: compiled.diagnostics
628
- };
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$1}, so there is no scope to read: pass schemas, e.g. {"schemas": ["public"]}. Nothing changed.`);
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: input.project?.database?.provider ?? "supabase"
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 read = await withDatabase(required$1(database), "introspect", (db) => engine.extract(db.target, scope));
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: [read.diagnostic]
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 diagnostics = [...extractDiagnostics, ...reversed.diagnostics];
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
- changes: ok ? reversed.changes : [],
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 prefixes.some((p) => m[2].startsWith(p));
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 key = (parts.length === 2 ? parts : [schema, parts[0]]).join(".");
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, nameParts(unit.identity.slice(unit.identity.indexOf(":") + 1)));
1045
+ if (table !== void 0 && keys.has(table)) sequence(unit.schema, identityParts(unit.identity));
767
1046
  }
768
- return ids;
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.") && touches(d.path.slice(6))),
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-DPPnife2.js");
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.diagnostic]
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-DPPnife2.js");
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.diagnostic]);
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$1 = (hash) => hash.slice(0, 12);
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$1(artifact.toHash),
1160
- current: short$1(model.hash)
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 roles = await checkPlatformRoles(await applyDatabase({ readOnly: true }), db.target, db.shadowBase, desired.sql, await loadSqlParser());
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 { outcome: await executePlan(writer, db.target, artifact, {
1206
- ...base,
1207
- mode: "rehearse",
1208
- rehearsal: {
1209
- engine,
1210
- desired: shadow.value.catalog
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([executed.diagnostic]);
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
- * Чиста політика пакета `data-command` до першого з'єднання: база не
1256
- * бачить запиту, якому відмовлено. Перевіряється кожна фаза пакета, бо
1257
- * пакет — одна транзакція: дозволена перша фаза не робить дозволеною решту.
1258
- * Невідомий об'єкт пропускається — його відхилить схема каталогу T3
1259
- * (`command.invalid`), і політика не дублює її текст.
1567
+ * Чиста відмова модуля до першого з'єднання: designer модулів не завантажує,
1568
+ * тож хуки об'єкта мовчки не спрацювали б. Перевіряється весь пакет (він —
1569
+ * одна транзакція: дозволена перша фаза не робить дозволеною решту) і першою,
1570
+ * до запобіжника запису прав каталогу T3 (`agentWriteRefusal`), який лишається
1571
+ * власністю T3. Невідомий об'єкт пропускається — його відхилить схема
1572
+ * каталогу T3 (`command.invalid`), і політика не дублює її текст.
1260
1573
  */
1261
- function dataCommandRefusal(model, catalog, batch, o) {
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
- kind: "command",
1265
- error: {
1266
- code: "command.invalid",
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.create?.root?.membership : void 0;
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
- * JSON не має `bigint`, а формат передачі клієнтам — справа П4-B: інструмент
1295
- * не клієнт П4-B, тож віддає десятковий рядок, який вхід `BigInt` T0 уже
1296
- * приймає назад.
1594
+ * Єдина склейка порядку політики (Р-F3-13): відмова модуля на весь пакет —
1595
+ * першою, далі запобіжник запису прав каталогу T3. Порядок видно споживачеві:
1596
+ * пакет, який порушує обидва правила, дістає відмову модуля, бо прапорець
1597
+ * прав її не знімає.
1297
1598
  */
1298
- function toJson(value) {
1299
- if (typeof value === "bigint") return String(value);
1300
- if (Array.isArray(value)) return value.map(toJson);
1301
- if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toJson(v)]));
1302
- return value;
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,6 +1616,7 @@ 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"}`;
1619
+ if ("count" in data) return `${name}: ${data.capped === true ? "over " : ""}${count(data.count, "row")} counted`;
1311
1620
  return "rows" in data ? `${name}: ${count(data.rows.length, "row")}` : `${name}: ${count(data.result.changes.length, "change")}`;
1312
1621
  }
1313
1622
  const SQLSTATE = /^[0-9A-Z]{5}$/;
@@ -1328,7 +1637,18 @@ function required(data) {
1328
1637
  return data;
1329
1638
  }
1330
1639
  /**
1331
- * Компіляція на кожен виклик (Р-A5-5): зміна теки між викликами дає нову
1640
+ * Попередження компіляції, що стосуються об'єктів операції, і жодних
1641
+ * чужих: успішна модель може нести попередження про інші об'єкти проєкту, а
1642
+ * агентові по даних одного об'єкта вони лише шум. Об'єкт знаходиться за
1643
+ * файлом діагностики; невідомий об'єкт (його відхилить схема T3) нічого не
1644
+ * додає.
1645
+ */
1646
+ function warningsFor(model, diagnostics, objects) {
1647
+ const files = new Set(model.objects.filter((x) => objects.some((o) => o.kind === x.kind && o.name === x.name)).map((x) => x.file));
1648
+ return diagnostics.filter((d) => d.severity === "warning" && files.has(d.file));
1649
+ }
1650
+ /**
1651
+ * Компіляція на кожен виклик (спека П4 §6.14): зміна теки між викликами дає нову
1332
1652
  * модель, і рантайм звіряє її хеш із застосованим — кешу, який треба
1333
1653
  * інвалідувати, немає.
1334
1654
  */
@@ -1339,14 +1659,17 @@ async function compileDir(dir) {
1339
1659
  changes: [],
1340
1660
  diagnostics: compiled.diagnostics
1341
1661
  } };
1342
- return { model: compiled.model };
1662
+ return {
1663
+ model: compiled.model,
1664
+ diagnostics: compiled.diagnostics
1665
+ };
1343
1666
  }
1344
1667
  /**
1345
1668
  * Рантайм на виклик: пул ролі входу, звірка хешу, дія й закриття пулу
1346
1669
  * (`withData`). `CommandFailure` — відповідь T3, тож дані результату, а не
1347
1670
  * збій; збій бази — `database.failed` лише з адресою й кодом.
1348
1671
  */
1349
- async function onRuntime(tool, ctx, model, act) {
1672
+ async function onRuntime(tool, ctx, model, warnings, act) {
1350
1673
  try {
1351
1674
  const ran = await withData(required(ctx.data), model.project.database.provider, async (s) => {
1352
1675
  try {
@@ -1369,7 +1692,7 @@ async function onRuntime(tool, ctx, model, act) {
1369
1692
  return {
1370
1693
  ok: ran.ok,
1371
1694
  changes: [],
1372
- diagnostics: [],
1695
+ diagnostics: warnings,
1373
1696
  data: ran.data
1374
1697
  };
1375
1698
  } catch (error) {
@@ -1386,7 +1709,7 @@ async function onRuntime(tool, ctx, model, act) {
1386
1709
  }
1387
1710
  const dataReadTool = defineTool({
1388
1711
  name: "data-read",
1389
- description: "Read application data of the development database as the user given by --as, with that user's rights: one row by id, or a page of rows by equality filter (where, after, limit up to 200). BigInt values come as decimal strings. A runtime error comes as data.error with a code.",
1712
+ description: "Reads rows under RLS as the user given by --as: a card by id, a page by filter tree (where, orderBy, offset, limit up to 200) or a capped count. A card may carry its tabular sections; a card or a page may include the target rows of Ref attributes. A tabular section reads as the lines of one owner (with ownerVersion), a page or a count. BigInt values come as decimal strings. A runtime error comes as data.error with a code.",
1390
1713
  input: z.strictObject({ query: readQuerySchema }),
1391
1714
  files: "read",
1392
1715
  database: "none",
@@ -1395,12 +1718,16 @@ const dataReadTool = defineTool({
1395
1718
  async run(ctx, input) {
1396
1719
  const compiled = await compileDir(ctx.dir);
1397
1720
  if ("failed" in compiled) return compiled.failed;
1398
- return onRuntime("data-read", ctx, compiled.model, async (rt, session) => ({ rows: toJson(await rt.read(session, input.query)) }));
1721
+ return onRuntime("data-read", ctx, compiled.model, warningsFor(compiled.model, compiled.diagnostics, [input.query.object]), async (rt, session) => await createAgentCore({ runtime: rt }).read(session, input.query));
1722
+ },
1723
+ present: {
1724
+ structure: (data) => toJson(data),
1725
+ text: (data, v) => data === void 0 ? void 0 : [summarizeData("data-read", data), ...v.diagnostics.length > 0 ? [v.report] : []].join("\n")
1399
1726
  }
1400
1727
  });
1401
1728
  const dataCommandTool = defineTool({
1402
1729
  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.",
1730
+ description: "Change application data of the development database as the user given by --as, with that user's rights: a batch of create, update, markDeletion and delete operations in one transaction (update, markDeletion and delete need expectedVersion). A tabular section array in update replaces the section: every existing row must be in the array or in deleteIds. Rights catalogs and create of a scope root whose creator gets a role need --allow-rights-write; objects with a module are refused, and for such a root also when its membership catalog has one. BigInt values may be passed as decimal strings. Each result row has the shape of a read card: the tabular sections the operation wrote come under tabularSections. A runtime error comes as data.error with a code.",
1404
1731
  input: z.strictObject({ operations: batchSchema }),
1405
1732
  files: "read",
1406
1733
  database: "none",
@@ -1410,22 +1737,32 @@ const dataCommandTool = defineTool({
1410
1737
  const compiled = await compileDir(ctx.dir);
1411
1738
  if ("failed" in compiled) return compiled.failed;
1412
1739
  const { model } = compiled;
1413
- const refusal = dataCommandRefusal(model, buildRuntimeCatalog(model), input.operations, { allowRightsWrite: ctx.allowRightsWrite === true });
1740
+ const warnings = warningsFor(model, compiled.diagnostics, input.operations.map((op) => op.object));
1741
+ const catalog = buildRuntimeCatalog(model);
1742
+ const rightsWrite = ctx.allowRightsWrite === true;
1743
+ const refusal = dataPolicyRefusal(model, catalog, input.operations, { rightsWrite });
1414
1744
  if (refusal?.kind === "command") return {
1415
1745
  ok: false,
1416
1746
  changes: [],
1417
1747
  diagnostics: [],
1418
1748
  data: { error: refusal.error }
1419
1749
  };
1420
- if (refusal?.kind === "rights") return {
1750
+ if (refusal !== void 0) return {
1421
1751
  ok: false,
1422
1752
  changes: [],
1423
1753
  diagnostics: [],
1424
1754
  refusalReason: "rights-write-disabled"
1425
1755
  };
1426
- return onRuntime("data-command", ctx, model, async (rt, session) => {
1427
- return { result: toJson(await rt.run(session, input.operations)) };
1756
+ return onRuntime("data-command", ctx, model, warnings, async (rt, session) => {
1757
+ return { result: await createAgentCore({
1758
+ runtime: rt,
1759
+ permissions: { rightsWrite }
1760
+ }).execute(session, input.operations) };
1428
1761
  });
1762
+ },
1763
+ present: {
1764
+ structure: (data) => toJson(data),
1765
+ text: (data, v) => data === void 0 ? void 0 : [summarizeData("data-command", data), ...v.diagnostics.length > 0 ? [v.report] : []].join("\n")
1429
1766
  }
1430
1767
  });
1431
1768
  // src/tools/mutations.ts
@@ -1441,6 +1778,7 @@ async function apply(dir, operation) {
1441
1778
  const result = await operation(await readMetadataDir(dir));
1442
1779
  return {
1443
1780
  ok: result.ok,
1781
+ ...result.written === true ? { written: true } : {},
1444
1782
  changes: result.changes,
1445
1783
  diagnostics: result.diagnostics
1446
1784
  };
@@ -1468,7 +1806,7 @@ async function applyPromotion(dir, operation) {
1468
1806
  }
1469
1807
  const createTool = defineTool({
1470
1808
  name: "create",
1471
- description: "Create a metadata object; ids and physical names are assigned. Writes only when the result compiles without errors.",
1809
+ description: "Create a metadata object; ids and physical names are assigned. Writes when the result compiles without errors, or when its only errors are repair-class errors the directory already had (then ok is false and written is true).",
1472
1810
  input: createObjectInput,
1473
1811
  files: "write",
1474
1812
  database: "none",
@@ -1478,7 +1816,7 @@ const createTool = defineTool({
1478
1816
  });
1479
1817
  const addTool = defineTool({
1480
1818
  name: "add",
1481
- description: "Add a named element (attribute, tabular section, value, scope kind, ...) to a collection of an object or of the project root. Writes only when the result compiles without errors.",
1819
+ description: "Add a named element (attribute, tabular section, value, scope kind, ...) to a collection of an object or of the project root. Writes when the result compiles without errors, or when its only errors are repair-class errors the directory already had (then ok is false and written is true).",
1482
1820
  input: addElementInput,
1483
1821
  files: "write",
1484
1822
  database: "none",
@@ -1486,6 +1824,16 @@ const addTool = defineTool({
1486
1824
  destructive: false,
1487
1825
  run: ({ dir }, input) => apply(dir, (files) => addElement(files, input, completion(dir)))
1488
1826
  });
1827
+ const declareFunctionTool = defineTool({
1828
+ name: "declare-function",
1829
+ description: "Create or replace the declaration (callers, check) of one SQL function of a sibling .sql file; the id of an existing record is kept. Refused for a function that is a platform form, overloaded or missing. Writes when the result compiles without errors, or when its only errors are repair-class errors the directory already had or the target's own check-not-applied (the body lacks the guard that fix inserts; then ok is false and written is true). Roles that gain EXECUTE are named in a warning.",
1830
+ input: declareFunctionInput,
1831
+ files: "write",
1832
+ database: "none",
1833
+ data: "none",
1834
+ destructive: false,
1835
+ run: ({ dir }, input) => apply(dir, (files) => declareFunction(files, input, completion(dir)))
1836
+ });
1489
1837
  const renameTool = defineTool({
1490
1838
  name: "rename",
1491
1839
  description: "Rename an object or a nested element; references are rewritten, ids and physical names never change. Writes only when the result compiles without errors.",
@@ -1514,6 +1862,10 @@ const promoteTool = defineTool({
1514
1862
  database: "none",
1515
1863
  data: "none",
1516
1864
  destructive: false,
1865
+ present: {
1866
+ structure: (record) => ({ record }),
1867
+ appendix: (record, v) => v.channel === "cli" ? renderPromotion(record, v.written) : ["promotion record:", JSON.stringify(record, null, 2)].join("\n")
1868
+ },
1517
1869
  run: ({ dir }, input) => applyPromotion(dir, (files) => promoteObject(files, input, completion(dir)))
1518
1870
  });
1519
1871
  // src/tools/read.ts
@@ -1525,6 +1877,7 @@ const compileTool = defineTool({
1525
1877
  database: "none",
1526
1878
  data: "none",
1527
1879
  destructive: false,
1880
+ present: { diagnosticsOnly: true },
1528
1881
  async run({ dir, baseline }) {
1529
1882
  const result = await compile(await readMetadataDir(dir), baseline === void 0 ? void 0 : { baseline });
1530
1883
  return {
@@ -1535,19 +1888,50 @@ const compileTool = defineTool({
1535
1888
  };
1536
1889
  }
1537
1890
  });
1891
+ const explainInput = z.strictObject({
1892
+ kind: metadataKindSchema.optional(),
1893
+ name: objectNameSchema.optional(),
1894
+ function: z.strictObject({
1895
+ schema: z.string().min(1).optional(),
1896
+ name: z.string().min(1)
1897
+ }).optional()
1898
+ }).refine((i) => i.function === void 0 ? i.kind !== void 0 && i.name !== void 0 : i.kind === void 0 && i.name === void 0, { message: "Give either kind and name, or function." });
1538
1899
  const explainTool = defineTool({
1539
1900
  name: "explain",
1540
- description: "Explain one object: its tables, columns, keys and movement queries. Needs a metadata directory that compiles without errors.",
1541
- input: z.strictObject({
1542
- kind: metadataKindSchema,
1543
- name: objectNameSchema
1544
- }),
1901
+ description: "Explain an object (kind, name; metadata must compile) or a SQL function (function: schema, name): callers, EXECUTE roles per provider, declared check, whether the body applies it.",
1902
+ input: explainInput,
1545
1903
  files: "read",
1546
1904
  database: "none",
1547
1905
  data: "none",
1548
1906
  destructive: false,
1549
- async run({ dir }, { kind, name }) {
1550
- const result = await compile(await readMetadataDir(dir));
1907
+ async run({ dir }, { kind, name, function: fn }) {
1908
+ const files = await readMetadataDir(dir);
1909
+ if (fn !== void 0) {
1910
+ const result = await compile(files, { repair: true });
1911
+ if (result.model === void 0) return {
1912
+ ok: false,
1913
+ changes: [],
1914
+ diagnostics: result.diagnostics
1915
+ };
1916
+ const schema = fn.schema ?? result.model.project.defaultSchema;
1917
+ const explanation = explainFunction(result, {
1918
+ schema,
1919
+ name: fn.name
1920
+ });
1921
+ if (explanation === void 0) return {
1922
+ ok: false,
1923
+ changes: [],
1924
+ diagnostics: result.diagnostics,
1925
+ refusal: `Function not found: ${schema}.${fn.name}`
1926
+ };
1927
+ return {
1928
+ ok: true,
1929
+ changes: [],
1930
+ diagnostics: result.diagnostics,
1931
+ data: explanation
1932
+ };
1933
+ }
1934
+ const result = await compile(files);
1551
1935
  if (result.model === void 0) return {
1552
1936
  ok: false,
1553
1937
  changes: [],
@@ -1569,11 +1953,15 @@ const explainTool = defineTool({
1569
1953
  diagnostics: result.diagnostics,
1570
1954
  data: explanation
1571
1955
  };
1956
+ },
1957
+ present: {
1958
+ bare: true,
1959
+ text: (data, v) => data === void 0 ? void 0 : v.channel === "mcp" ? JSON.stringify(data, null, 2) : "function" in data ? renderFunctionExplanation(data) : renderExplanation(data).trimEnd()
1572
1960
  }
1573
1961
  });
1574
1962
  const fixTool = defineTool({
1575
1963
  name: "fix",
1576
- description: "Assign missing ids and physical names, set $schema and canonical form. Writes only when the result compiles without errors.",
1964
+ description: "Assign missing ids and physical names, set $schema and canonical form; repair function declarations (ids, call guard, default privileges). Writes when the result compiles, or when it removes repair-class errors and adds none (ok false, written true).",
1577
1965
  input: z.strictObject({}),
1578
1966
  files: "write",
1579
1967
  database: "none",
@@ -1586,6 +1974,7 @@ const fixTool = defineTool({
1586
1974
  });
1587
1975
  return {
1588
1976
  ok: result.ok,
1977
+ ...result.written === true ? { written: true } : {},
1589
1978
  changes: result.changes,
1590
1979
  diagnostics: result.diagnostics
1591
1980
  };
@@ -1595,7 +1984,7 @@ const fixTool = defineTool({
1595
1984
  const id = z.string().regex(UUID_TEXT, "expected a UUID");
1596
1985
  const role = z.string().min(1);
1597
1986
  /**
1598
- * Вхід — JSON, одна дія на запуск (Р-A4-8): `strictObject` не пропускає поля
1987
+ * Вхід — JSON, одна дія на запуск: `strictObject` не пропускає поля
1599
1988
  * іншої дії, тож помилка написання не перетвориться на тиху іншу дію.
1600
1989
  */
1601
1990
  const input = z.discriminatedUnion("action", [
@@ -1621,7 +2010,7 @@ const input = z.discriminatedUnion("action", [
1621
2010
  /**
1622
2011
  * Аварійний вхід у права поза командами (спека П4 §6.12): режим
1623
2012
  * обслуговування бази діє лише для входу мігратора, тож інструмент — лише
1624
- * командний рядок і лише з `--yes`; агент через MCP його не бачить (Р-A4-7).
2013
+ * командний рядок і лише з `--yes`; агент через MCP його не бачить.
1625
2014
  */
1626
2015
  const rightsMaintenanceTool = defineTool({
1627
2016
  name: "rights-maintenance",
@@ -1640,12 +2029,12 @@ const rightsMaintenanceTool = defineTool({
1640
2029
  changes: [],
1641
2030
  diagnostics: compiled.diagnostics
1642
2031
  };
1643
- const { createApplyDatabase } = await import("./schema-engine-DPPnife2.js");
2032
+ const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
1644
2033
  const ran = await withDatabase(required$1(database), "rights-maintenance", (db) => runRightsMaintenance(createApplyDatabase({ readOnly: false }), db.target, model, request));
1645
2034
  if (!ran.ok) return {
1646
2035
  ok: false,
1647
2036
  changes: [],
1648
- diagnostics: [ran.diagnostic]
2037
+ diagnostics: failureDiagnostics(ran)
1649
2038
  };
1650
2039
  if (!ran.value.ok) return {
1651
2040
  ok: false,
@@ -1658,25 +2047,27 @@ const rightsMaintenanceTool = defineTool({
1658
2047
  diagnostics: [],
1659
2048
  data: ran.value.done
1660
2049
  };
1661
- }
2050
+ },
2051
+ present: { text: (data) => data === void 0 ? void 0 : `assigned ${data.assignment}${data.member === void 0 ? "" : ` to member ${data.member}`}` }
1662
2052
  });
1663
2053
  // src/tools/roles-tool.ts
1664
- const PROJECT_FILE = "project.meta.json";
2054
+ const PROJECT_FILE$1 = "project.meta.json";
1665
2055
  /**
1666
2056
  * Набір ролей теки проєкту (спека П4 §6.2): провайдер — з файлу проєкту, тим самим
1667
- * читачем, що й `compile`. Без файлу роль входу пропускається явно — пропуск
1668
- * видно у виводі, бо роль без членства в ролі запиту `roles` потім не
1669
- * виправив би (наявну лише звіряє).
2057
+ * читачем, що й `compile`. Без файлу ролі входу пропускаються явно — пропуск
2058
+ * видно у виводі, бо без провайдера невідомо, членом яких ролей запиту
2059
+ * роль рантайму мусить бути.
1670
2060
  */
1671
2061
  async function projectRoleSet(dir) {
1672
- const text = existsSync(dir) ? (await readMetadataDir(dir)).get(PROJECT_FILE) : void 0;
2062
+ const text = existsSync(dir) ? (await readMetadataDir(dir)).get(PROJECT_FILE$1) : void 0;
1673
2063
  if (text === void 0) return {
1674
2064
  ok: true,
2065
+ provider: void 0,
1675
2066
  roles: platformRoleSet(void 0),
1676
- skipped: [{
1677
- name: PLATFORM_LOGIN_ROLES.runtime,
2067
+ skipped: Object.values(PLATFORM_LOGIN_ROLES).map((name) => ({
2068
+ name,
1678
2069
  reason: "no-project-file"
1679
- }]
2070
+ }))
1680
2071
  };
1681
2072
  const read = readProjectFile(text);
1682
2073
  if (read.project === void 0) return {
@@ -1685,10 +2076,343 @@ async function projectRoleSet(dir) {
1685
2076
  };
1686
2077
  return {
1687
2078
  ok: true,
2079
+ provider: read.project.database.provider,
1688
2080
  roles: platformRoleSet(read.project.database.provider),
1689
2081
  skipped: []
1690
2082
  };
1691
2083
  }
2084
+ /** Ім'я бази з адреси цілі; порожнє, коли адреса бази не називає. */
2085
+ function databaseOf(url) {
2086
+ try {
2087
+ return decodeURIComponent(new URL(url).pathname.replace(/^\//, ""));
2088
+ } catch {
2089
+ return "";
2090
+ }
2091
+ }
2092
+ /**
2093
+ * Підсумок підготовки кластера як рядки інструмента: створене й наявне — за іменем, а
2094
+ * доповнене членство — на рядку самої ролі входу (`present` з `added`), а не
2095
+ * окремою «роллю».
2096
+ */
2097
+ function clusterRoles(value) {
2098
+ const outcome = (names, kind) => names.map((name) => {
2099
+ const parents = value.added?.find((a) => a.role === name)?.parents;
2100
+ return {
2101
+ server: "target",
2102
+ name,
2103
+ outcome: kind,
2104
+ ...parents === void 0 ? {} : { added: parents }
2105
+ };
2106
+ });
2107
+ return [...outcome(value.created, "created"), ...outcome(value.present, "present")];
2108
+ }
2109
+ /**
2110
+ * Готує ролі (і, у профілі `postgres`, кластер) за провайдером проєкту.
2111
+ * `postgres` готує суперкористувач через службову базу того самого сервера,
2112
+ * ціль і шаблон; окремий сервер тіней там не підтримано.
2113
+ * Решта провайдерів і проєкт без файлу — ролі на цілі й на сервері тіні.
2114
+ */
2115
+ async function runRoles(dbs, db, project) {
2116
+ if (project.provider === "postgres") {
2117
+ if (db.shadowBase !== void 0) return {
2118
+ roles: [],
2119
+ skipped: [],
2120
+ diagnostics: [diagnostic("plan.shadow-base-unsupported", "", "")]
2121
+ };
2122
+ const database = databaseOf(db.target.url);
2123
+ if (database === "") return {
2124
+ roles: [],
2125
+ skipped: [],
2126
+ diagnostics: [diagnostic("database.failed", "", "", {
2127
+ tool: "roles",
2128
+ database: db.describe,
2129
+ error: "the database address names no database"
2130
+ })]
2131
+ };
2132
+ const set = postgresClusterSet(database);
2133
+ const { withDatabaseName } = await import("@supabase/pg-delta");
2134
+ const result = await ensurePostgresCluster(dbs, {
2135
+ maintenance: { url: withDatabaseName(db.target.url, "postgres") },
2136
+ target: db.target,
2137
+ template: { url: withDatabaseName(db.target.url, set.template) }
2138
+ }, set);
2139
+ if (!result.ok) return {
2140
+ roles: [],
2141
+ skipped: [],
2142
+ diagnostics: result.error.map(fromEngine)
2143
+ };
2144
+ return {
2145
+ roles: clusterRoles(result.value),
2146
+ skipped: result.value.skipped.map((name) => ({
2147
+ name,
2148
+ reason: "identity-table-missing"
2149
+ })),
2150
+ diagnostics: []
2151
+ };
2152
+ }
2153
+ const ran = await ensurePlatformRoles(dbs, [{
2154
+ server: "target",
2155
+ db: db.target
2156
+ }, ...db.shadowBase === void 0 ? [] : [{
2157
+ server: "shadow",
2158
+ db: db.shadowBase
2159
+ }]], project.roles);
2160
+ return {
2161
+ roles: ran.created,
2162
+ skipped: [],
2163
+ diagnostics: (ran.refusal ?? []).map(fromEngine)
2164
+ };
2165
+ }
2166
+ /**
2167
+ * Платформні ролі кластерні, тож у бажаному стані бази їх немає, і план їх
2168
+ * не створює (спека П4 §6.2, спека designer §3.2): їх створює окремий крок з правом
2169
+ * `CREATEROLE`. Ролі грантів задає платформа; файл проєкту потрібен лише
2170
+ * ролі входу — її членство в ролі запиту залежить від провайдера.
2171
+ */
2172
+ const rolesTool = defineTool({
2173
+ name: "roles",
2174
+ description: "Create the platform roles: NOLOGIN roles that generated SQL grants to on the target and the shadow server, and the login roles (the runtime and the signals consumer) on the target only, each a member of its parents WITH INHERIT FALSE, SET TRUE; the signals login role also gets a role setting (ALTER ROLE … SET) that makes its consumer group the role of every new session. Reads the project file for `database.provider`; without a project file the login roles are skipped, and the output says so. An existing role is only checked, its role setting included; the one change it makes is to add a missing membership of an existing login role in a parent of its profile, WITH INHERIT FALSE, SET TRUE, and the output names it. Needs CREATEROLE, and ADMIN OPTION on every parent role of a login role (without it that login role alone is refused, a missing membership with the GRANT statement to run); refuses before creating anything when a server lacks CREATEROLE or a role has an unsafe shape. With the provider `postgres` it prepares the cluster instead, as a superuser (the database URL is a superuser URL of the target database): the owner, auth, grant and request roles, the target database owned by the owner, the schemas `extensions` and `better_auth`, `plpgsql_check`, and the sealed template database for shadows. It refuses before writing when the session is not a superuser, an existing database or role has an unsafe shape, or a Simetra login role can connect to another database; a separate shadow server is not supported there.",
2175
+ input: z.strictObject({}),
2176
+ files: "read",
2177
+ database: "write",
2178
+ data: "none",
2179
+ destructive: false,
2180
+ async run({ dir, database }) {
2181
+ const set = await projectRoleSet(dir);
2182
+ if (!set.ok) return {
2183
+ ok: false,
2184
+ changes: [],
2185
+ diagnostics: set.diagnostics
2186
+ };
2187
+ const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
2188
+ const ran = await withDatabase(required$1(database), "roles", (db) => runRoles(createApplyDatabase({ readOnly: false }), db, set));
2189
+ if (!ran.ok) return {
2190
+ ok: false,
2191
+ changes: [],
2192
+ diagnostics: failureDiagnostics(ran)
2193
+ };
2194
+ const data = {
2195
+ roles: ran.value.roles,
2196
+ skipped: [...set.skipped, ...ran.value.skipped]
2197
+ };
2198
+ return {
2199
+ ok: ran.value.diagnostics.length === 0,
2200
+ changes: [],
2201
+ diagnostics: ran.value.diagnostics,
2202
+ data
2203
+ };
2204
+ },
2205
+ present: { text: (data, v) => data === void 0 || v.channel === "mcp" ? void 0 : [
2206
+ ...data.roles.map((x) => `${x.server}: ${x.name} ${x.outcome}${x.added === void 0 ? "" : `; added membership in ${x.added.join(", ")}`}`),
2207
+ ...data.skipped.map((x) => {
2208
+ if (x.reason === "no-project-file") return `target: ${x.name} skipped: the directory has no project.meta.json, so database.provider is unknown; run roles in a metadata directory with a project file to create it`;
2209
+ const at = x.name.lastIndexOf(":");
2210
+ return `target: ${x.name.slice(0, at)}: ${x.name.slice(at + 1)} not granted yet — run the Better Auth migration, then simetra roles again`;
2211
+ }),
2212
+ ...v.diagnostics.length > 0 ? [v.report] : []
2213
+ ].join("\n") }
2214
+ });
2215
+ // src/tools/signals-config.ts
2216
+ const PROJECT_FILE = "project.meta.json";
2217
+ /** Name of the outbox consumer in the Centrifugo config (postgres profile spec §6.1). */
2218
+ const SIGNAL_CONSUMER_NAME = "simetra_outbox";
2219
+ /**
2220
+ * Environment variables that give the consumer its DSNs (postgres profile spec
2221
+ * §10.1): Centrifugo overrides the consumer declared in the config with them,
2222
+ * so the password of `simetra_signals` never lands in the config file.
2223
+ */
2224
+ const SIGNAL_CONSUMER_ENV = {
2225
+ dsn: "CENTRIFUGO_CONSUMERS_SIMETRA_OUTBOX_POSTGRESQL_DSN",
2226
+ notificationDsn: "CENTRIFUGO_CONSUMERS_SIMETRA_OUTBOX_POSTGRESQL_PARTITION_NOTIFICATION_DSN"
2227
+ };
2228
+ const NAMESPACES = [
2229
+ {
2230
+ name: "simetra",
2231
+ historySize: 100
2232
+ },
2233
+ {
2234
+ name: "simetra-rights",
2235
+ historySize: 20
2236
+ },
2237
+ {
2238
+ name: "simetra-user",
2239
+ historySize: 20
2240
+ }
2241
+ ];
2242
+ const PRESENCE_UPDATE_INTERVAL = "5s";
2243
+ const EXPIRED_SUB_CLOSE_DELAY = "25s";
2244
+ const EXPIRED_CLOSE_DELAY = "25s";
2245
+ const HISTORY_TTL = "300s";
2246
+ const HISTORY_META_TTL = "24h";
2247
+ const RECOVERY_MAX_PUBLICATION_LIMIT = 300;
2248
+ const OUTBOX_TABLE = `${quoteIdent(SIGNAL_OUTBOX.schema)}.${quoteIdent(SIGNAL_OUTBOX.name)}`;
2249
+ /**
2250
+ * Centrifugo v6 config of one application (postgres profile spec §6.1, §5.3):
2251
+ * three namespaces with history and forced recovery, no client permission,
2252
+ * the outbox consumer with empty DSNs (they come from `SIGNAL_CONSUMER_ENV`),
2253
+ * the HTTP API off. No `http_server`: the address is the deployment's choice.
2254
+ */
2255
+ function centrifugoConfig(o) {
2256
+ return {
2257
+ client: {
2258
+ allowed_origins: [o.origin],
2259
+ token: {
2260
+ jwks_public_endpoint: o.jwksUrl,
2261
+ audience: `centrifugo:${o.projectName}`,
2262
+ issuer: o.issuer
2263
+ },
2264
+ recovery_max_publication_limit: RECOVERY_MAX_PUBLICATION_LIMIT,
2265
+ presence_update_interval: PRESENCE_UPDATE_INTERVAL,
2266
+ expired_sub_close_delay: EXPIRED_SUB_CLOSE_DELAY,
2267
+ expired_close_delay: EXPIRED_CLOSE_DELAY
2268
+ },
2269
+ channel: {
2270
+ max_length: CENTRIFUGO_CHANNEL_MAX,
2271
+ without_namespace: {},
2272
+ namespaces: NAMESPACES.map((n) => ({
2273
+ name: n.name,
2274
+ history_size: n.historySize,
2275
+ history_ttl: HISTORY_TTL,
2276
+ history_meta_ttl: HISTORY_META_TTL,
2277
+ force_recovery: true
2278
+ }))
2279
+ },
2280
+ consumers: [{
2281
+ enabled: true,
2282
+ name: SIGNAL_CONSUMER_NAME,
2283
+ type: "postgresql",
2284
+ postgresql: {
2285
+ dsn: "",
2286
+ partition_notification_dsn: "",
2287
+ outbox_table_name: OUTBOX_TABLE,
2288
+ num_partitions: 1,
2289
+ partition_select_limit: 100,
2290
+ partition_poll_interval: `300ms`,
2291
+ partition_notification_channel: SIGNAL_NOTIFY_CHANNEL,
2292
+ use_try_lock: true
2293
+ }
2294
+ }],
2295
+ http_api: { disabled: true },
2296
+ health: { enabled: true },
2297
+ log: { level: "info" }
2298
+ };
2299
+ }
2300
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2301
+ function object(shape) {
2302
+ return (value, path) => {
2303
+ if (!isRecord(value)) return [`${path}: expected an object`];
2304
+ const extra = Object.keys(value).filter((key) => !Object.hasOwn(shape, key)).map((key) => `${path}.${key}: not an allowed option`);
2305
+ const own = Object.entries(shape).flatMap(([key, rule]) => Object.hasOwn(value, key) ? rule(value[key], `${path}.${key}`) : [`${path}.${key}: missing`]);
2306
+ return [...extra, ...own];
2307
+ };
2308
+ }
2309
+ const exactly = (expected) => (value, path) => value === expected ? [] : [`${path}: must be ${JSON.stringify(expected)}, got ${JSON.stringify(value)}`];
2310
+ const int = (min, max = Number.MAX_SAFE_INTEGER) => (value, path) => Number.isInteger(value) && value >= min && value <= max ? [] : [`${path}: must be an integer from ${min} to ${max}`];
2311
+ const duration = (value, path) => typeof value === "string" && /^\d+(ms|s|m|h)$/.test(value) ? [] : [`${path}: must be a duration such as "300s"`];
2312
+ const DURATION_MS = {
2313
+ ms: 1,
2314
+ s: 1e3,
2315
+ m: 6e4,
2316
+ h: 36e5
2317
+ };
2318
+ const durationMs = (value) => {
2319
+ const [, amount, unit] = /^(\d+)(ms|s|m|h)$/.exec(value);
2320
+ return Number(amount) * DURATION_MS[unit];
2321
+ };
2322
+ const durationAtMost = (bound) => (value, path) => duration(value, path).length === 0 && durationMs(value) > 0 && durationMs(value) <= durationMs(bound) ? [] : [`${path}: must be a positive duration not above ${bound}`];
2323
+ const nonEmpty = (value, path) => typeof value === "string" && value.trim() !== "" ? [] : [`${path}: must be a non-empty string`];
2324
+ const origin = (value, path) => {
2325
+ if (typeof value === "string" && URL.canParse(value)) {
2326
+ const url = new URL(value);
2327
+ if ((url.protocol === "https:" || url.protocol === "http:") && url.origin === value) return [];
2328
+ }
2329
+ return [`${path}: must be an http(s) origin, got ${JSON.stringify(value)}`];
2330
+ };
2331
+ const LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/;
2332
+ const SERVICE_NAME = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/i;
2333
+ /**
2334
+ * JWKS лише через TLS чи внутрішню адресу (спека профілю §6.3): підміна
2335
+ * відповіді JWKS дала б токен на будь-який канал.
2336
+ */
2337
+ const jwksUrl = (value, path) => {
2338
+ const refused = [`${path}: must be an https: URL, or http: on a loopback address or a single-label service name, got ${JSON.stringify(value)}`];
2339
+ if (typeof value !== "string" || !URL.canParse(value)) return refused;
2340
+ const url = new URL(value);
2341
+ if (url.username !== "" || url.password !== "") return refused;
2342
+ if (url.protocol === "https:") return [];
2343
+ if (url.protocol !== "http:") return refused;
2344
+ return LOOPBACK_HOST.test(url.hostname) || SERVICE_NAME.test(url.hostname) && !/^\d+$/.test(url.hostname) ? [] : refused;
2345
+ };
2346
+ const namespace = object({
2347
+ name: nonEmpty,
2348
+ history_size: int(1),
2349
+ history_ttl: duration,
2350
+ history_meta_ttl: duration,
2351
+ force_recovery: exactly(true)
2352
+ });
2353
+ const namespaces = (value, path) => {
2354
+ if (!Array.isArray(value)) return [`${path}: expected an array`];
2355
+ const own = value.flatMap((n, i) => namespace(n, `${path}[${i}]`));
2356
+ const names = value.map((n) => isRecord(n) ? n.name : void 0);
2357
+ const expected = NAMESPACES.map((n) => n.name);
2358
+ const set = names.length === expected.length && expected.every((name) => names.includes(name)) ? [] : [`${path}: must be exactly the namespaces ${expected.join(", ")}`];
2359
+ const simetra = value.find((n) => isRecord(n) && n.name === "simetra");
2360
+ const history = isRecord(simetra) && Number.isInteger(simetra.history_size) && simetra.history_size < SIGNAL_MERGE_THRESHOLD + 1 ? [`${path}: history_size of simetra must be at least ${SIGNAL_MERGE_THRESHOLD + 1} (the default signal merge threshold + 1)`] : [];
2361
+ return [
2362
+ ...own,
2363
+ ...set,
2364
+ ...history
2365
+ ];
2366
+ };
2367
+ const consumer = object({
2368
+ enabled: exactly(true),
2369
+ name: exactly(SIGNAL_CONSUMER_NAME),
2370
+ type: exactly("postgresql"),
2371
+ postgresql: object({
2372
+ dsn: exactly(""),
2373
+ partition_notification_dsn: exactly(""),
2374
+ outbox_table_name: exactly(OUTBOX_TABLE),
2375
+ num_partitions: exactly(1),
2376
+ partition_select_limit: int(1),
2377
+ partition_poll_interval: duration,
2378
+ partition_notification_channel: exactly(SIGNAL_NOTIFY_CHANNEL),
2379
+ use_try_lock: exactly(true)
2380
+ })
2381
+ });
2382
+ const consumers = (value, path) => Array.isArray(value) && value.length === 1 ? consumer(value[0], `${path}[0]`) : [`${path}: must hold exactly the consumer ${SIGNAL_CONSUMER_NAME}`];
2383
+ const config = object({
2384
+ client: object({
2385
+ allowed_origins: (value, path) => Array.isArray(value) && value.length > 0 ? value.flatMap((o, i) => origin(o, `${path}[${i}]`)) : [`${path}: must list at least one origin`],
2386
+ token: object({
2387
+ jwks_public_endpoint: jwksUrl,
2388
+ audience: (value, path) => typeof value === "string" && /^centrifugo:\S+$/.test(value) ? [] : [`${path}: must be centrifugo:<project name>`],
2389
+ issuer: nonEmpty
2390
+ }),
2391
+ recovery_max_publication_limit: int(1),
2392
+ presence_update_interval: durationAtMost(PRESENCE_UPDATE_INTERVAL),
2393
+ expired_sub_close_delay: durationAtMost(EXPIRED_SUB_CLOSE_DELAY),
2394
+ expired_close_delay: durationAtMost(EXPIRED_CLOSE_DELAY)
2395
+ }),
2396
+ channel: object({
2397
+ max_length: int(1, CENTRIFUGO_CHANNEL_MAX),
2398
+ without_namespace: object({}),
2399
+ namespaces
2400
+ }),
2401
+ consumers,
2402
+ http_api: object({ disabled: exactly(true) }),
2403
+ health: object({ enabled: exactly(true) }),
2404
+ log: object({ level: exactly("info") })
2405
+ });
2406
+ /**
2407
+ * Refusals of a Centrifugo config (P4-B block B2, invariant 11): every level
2408
+ * is a whitelist of keys, so a client permission (`allow_*_for_*`,
2409
+ * anonymous connect, presence), an insecure or admin mode, a secret
2410
+ * (`hmac_secret_key`, a DSN), another listener (`http_server`, `grpc_api`)
2411
+ * or an open origin is refused. Empty for the output of `centrifugoConfig`.
2412
+ */
2413
+ function centrifugoConfigRefusals(value) {
2414
+ return config(value, "config");
2415
+ }
1692
2416
  // src/tools/catalog.ts
1693
2417
  /** Єдиний каталог інструментів: CLI, MCP і студія — лише його адаптери. */
1694
2418
  const TOOLS = [
@@ -1697,6 +2421,7 @@ const TOOLS = [
1697
2421
  fixTool,
1698
2422
  createTool,
1699
2423
  addTool,
2424
+ declareFunctionTool,
1700
2425
  renameTool,
1701
2426
  deleteTool,
1702
2427
  promoteTool,
@@ -1704,50 +2429,81 @@ const TOOLS = [
1704
2429
  diffTool,
1705
2430
  planTool,
1706
2431
  applyTool,
2432
+ rolesTool,
2433
+ rightsMaintenanceTool,
1707
2434
  defineTool({
1708
- name: "roles",
1709
- description: "Create the platform roles: NOLOGIN roles that generated SQL grants to on the target and the shadow server, and the runtime login role on the target only. Reads the project file for `database.provider`; without a project file the login role is skipped, and the output says so. An existing role is only checked. Needs CREATEROLE, and ADMIN OPTION on every parent role of the login role; refuses before creating anything when a server lacks CREATEROLE or a role has an unsafe shape.",
1710
- input: z.strictObject({}),
2435
+ name: "signals-config",
2436
+ description: `Generate the Centrifugo v6 config of the project's signals: three namespaces with history and forced recovery, no client permission, the outbox consumer, the HTTP API off. Input is JSON {origin, issuer, jwksUrl}: origin — the browser origin of the application; issuer — the host origin, the iss of every token (the audience is centrifugo:<project name>); jwksUrl — the JWKS address of the host, https: or http: on a loopback address or a single-label service name. The config holds no secret: set ${SIGNAL_CONSUMER_ENV.dsn} and ${SIGNAL_CONSUMER_ENV.notificationDsn} to the DSN of the login role simetra_signals (a direct connection; a pooler only in session mode) in the environment of Centrifugo. Run exactly one Centrifugo per application. The HTTP listener is the deployment's choice (CENTRIFUGO_HTTP_SERVER_ADDRESS, CENTRIFUGO_HTTP_SERVER_PORT). Refuses a config that breaks the whitelist.`,
2437
+ input: z.strictObject({
2438
+ origin: z.string(),
2439
+ issuer: z.string(),
2440
+ jwksUrl: z.string()
2441
+ }),
1711
2442
  files: "read",
1712
- database: "write",
2443
+ database: "none",
1713
2444
  data: "none",
1714
2445
  destructive: false,
1715
- async run({ dir, database }) {
1716
- const set = await projectRoleSet(dir);
1717
- if (!set.ok) return {
2446
+ async run({ dir }, input) {
2447
+ const text = (await readMetadataDir(dir)).get(PROJECT_FILE);
2448
+ if (text === void 0) return {
1718
2449
  ok: false,
1719
2450
  changes: [],
1720
- diagnostics: set.diagnostics
2451
+ diagnostics: [diagnostic("project.missing", PROJECT_FILE, "")]
1721
2452
  };
1722
- const { createApplyDatabase } = await import("./schema-engine-DPPnife2.js");
1723
- const ran = await withDatabase(required$1(database), "roles", (db) => ensurePlatformRoles(createApplyDatabase({ readOnly: false }), [{
1724
- server: "target",
1725
- db: db.target
1726
- }, ...db.shadowBase === void 0 ? [] : [{
1727
- server: "shadow",
1728
- db: db.shadowBase
1729
- }]], set.roles));
1730
- if (!ran.ok) return {
2453
+ const read = readProjectFile(text);
2454
+ if (read.project === void 0) return {
1731
2455
  ok: false,
1732
2456
  changes: [],
1733
- diagnostics: [ran.diagnostic]
2457
+ diagnostics: read.diagnostics
1734
2458
  };
1735
- const data = {
1736
- roles: ran.value.created,
1737
- skipped: set.skipped
2459
+ const config = centrifugoConfig({
2460
+ projectName: read.project.name,
2461
+ ...input
2462
+ });
2463
+ const refusals = centrifugoConfigRefusals(config);
2464
+ if (refusals.length > 0) return {
2465
+ ok: false,
2466
+ changes: [],
2467
+ diagnostics: [],
2468
+ refusal: refusals.join("\n")
1738
2469
  };
1739
2470
  return {
1740
- ok: ran.value.refusal === void 0,
2471
+ ok: true,
1741
2472
  changes: [],
1742
- diagnostics: (ran.value.refusal ?? []).map(fromEngine),
1743
- data
2473
+ diagnostics: [],
2474
+ data: {
2475
+ config,
2476
+ environment: [SIGNAL_CONSUMER_ENV.dsn, SIGNAL_CONSUMER_ENV.notificationDsn]
2477
+ }
1744
2478
  };
1745
- }
2479
+ },
2480
+ present: { text: (data) => data === void 0 ? void 0 : JSON.stringify(data.config, null, 2) }
1746
2481
  }),
1747
- rightsMaintenanceTool,
1748
2482
  dataReadTool,
1749
2483
  dataCommandTool
1750
2484
  ];
2485
+ /**
2486
+ * Поля `data` інструмента у структурованому результаті обох каналів: їх
2487
+ * вирішує `tool.present`, не ім'я інструмента.
2488
+ */
2489
+ function structureOf(tool, data) {
2490
+ return tool.present?.structure?.(data) ?? data;
2491
+ }
2492
+ /**
2493
+ * Що з результату показують канали: єдиний розв'язок для CLI і MCP. `data`
2494
+ * не показується, коли в інструмента нема `present`, коли він лише
2495
+ * діагностичний (`compile`: модель — не відповідь агентові, вона ~МБ) і коли
2496
+ * `bare`-результат не `ok`. Інструмент осі `artifact` показується й без
2497
+ * `data`: відмова теж має артефакти.
2498
+ */
2499
+ function presentation(tool, r) {
2500
+ const p = tool.present;
2501
+ const shown = p !== void 0 && p.diagnosticsOnly !== true && (p.bare === true ? r.ok && r.data !== void 0 : r.data !== void 0 || tool.files === "artifact");
2502
+ return {
2503
+ shown,
2504
+ data: shown ? r.data : void 0
2505
+ };
2506
+ }
1751
2507
  function toolByName(name) {
1752
2508
  return TOOLS.find((t) => t.name === name);
1753
2509
  }
@@ -1878,21 +2634,26 @@ async function invoke(tool, input, o) {
1878
2634
  checkArtifacts(root, artifacts);
1879
2635
  let write = false;
1880
2636
  let writeArtifacts = false;
2637
+ let wouldWrite = false;
1881
2638
  switch (tool.files) {
1882
2639
  case "read": break;
1883
2640
  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
2641
  writeArtifacts = outcome.ok && artifacts.length > 0;
1886
2642
  break;
1887
- case "write":
1888
- write = outcome.ok && !o.dryRun && outcome.changes.length > 0;
1889
- writeArtifacts = outcome.ok && !o.dryRun && artifacts.length > 0;
2643
+ case "write": {
2644
+ const accepted = outcome.ok || outcome.written === true;
2645
+ write = accepted && !o.dryRun && outcome.changes.length > 0;
2646
+ writeArtifacts = accepted && !o.dryRun && artifacts.length > 0;
2647
+ wouldWrite = accepted && o.dryRun && (outcome.changes.length > 0 || artifacts.length > 0);
2648
+ break;
2649
+ }
1890
2650
  }
1891
2651
  if (writeArtifacts) await writeChanges(root, artifacts);
1892
2652
  if (write) await writeChanges(o.dir, outcome.changes);
1893
2653
  return {
1894
2654
  ok: outcome.ok,
1895
2655
  written: write || writeArtifacts,
2656
+ ...wouldWrite ? { wouldWrite: true } : {},
1896
2657
  changes: outcome.changes.map((c) => ({
1897
2658
  path: c.path,
1898
2659
  deleted: c.content === null
@@ -1912,148 +2673,4 @@ async function invoke(tool, input, o) {
1912
2673
  }
1913
2674
  });
1914
2675
  }
1915
- // src/io/report.ts
1916
- /** Діагностика з текстом потрібною мовою; саме її віддають обидва формати. */
1917
- function localized(d, locale) {
1918
- const { message, hint } = localize(d, locale);
1919
- const rest = { ...d };
1920
- delete rest.hint;
1921
- return {
1922
- ...rest,
1923
- message,
1924
- ...hint === void 0 ? {} : { hint }
1925
- };
1926
- }
1927
- function formatDiagnostics(diagnostics, { dir, locale, format }) {
1928
- const items = diagnostics.map((d) => localized(d, locale));
1929
- if (format === "json") return JSON.stringify(items.map((d) => ({
1930
- ...d,
1931
- dir
1932
- })), null, 2);
1933
- const lines = [];
1934
- for (const d of items) {
1935
- lines.push(`${placeOf(d, dir)} ${d.severity} ${d.code} ${d.message}`);
1936
- if (d.hint !== void 0) lines.push(` hint: ${d.hint}`);
1937
- }
1938
- const errors = items.filter((d) => d.severity === "error").length;
1939
- lines.push(`${errors} error(s), ${items.length - errors} warning(s)`);
1940
- return lines.join("\n");
1941
- }
1942
- /**
1943
- * Місце діагностики в тексті. Позиція друкується лише тоді, коли вона є:
1944
- * діагностика без файлу (вхід операції загалом) чи файлу, якого немає в
1945
- * теці, отримала б фальшиве `:1:1`, а читач шукав би там неіснуючу причину.
1946
- */
1947
- function placeOf(d, dir) {
1948
- if (d.file === "") return `${dir}:`;
1949
- if (d.range === void 0) return `${dir}/${d.file}:`;
1950
- const { line, character } = d.range.start;
1951
- return `${dir}/${d.file}:${line + 1}:${character + 1}`;
1952
- }
1953
- /** Зведення звірки: дії плану, відмінності каталогу, діагностика. */
1954
- function renderDiff(d, report) {
1955
- const lines = [];
1956
- if (d.plan.length > 0) {
1957
- lines.push(`plan (${d.plan.length} action(s), database -> metadata):`);
1958
- for (const a of d.plan) {
1959
- const tags = [a.dataLoss ? "data loss" : void 0, a.rewriteRisk ? "rewrite" : void 0].filter((x) => x !== void 0);
1960
- lines.push(` ${a.sql.trim()}${tags.length > 0 ? ` -- ${tags.join(", ")}` : ""}`);
1961
- }
1962
- }
1963
- if (d.differences.length > 0) {
1964
- lines.push(`differences (${d.differences.length}):`);
1965
- for (const x of d.differences) lines.push(` ${x.kind} ${x.path}: ${x.detail}`);
1966
- }
1967
- if (d.applyState === "absent") lines.push("apply state: absent from the database; the first apply creates it");
1968
- if (d.empty) lines.push("diff: the database matches the metadata");
1969
- lines.push(report);
1970
- return lines.join("\n");
1971
- }
1972
- const short = (hash) => hash === null ? "initial" : hash.slice(0, 12);
1973
- /** Режим `plpgsql_check` плану словами виводу. */
1974
- const PLPGSQL_CHECK_LABEL = {
1975
- installed: "installed",
1976
- transient: "transient (installed for the check, rolled back)",
1977
- unavailable: "unavailable"
1978
- };
1979
- const qualified = (schema, name) => `${quoteIdent(schema)}.${quoteIdent(name)}`;
1980
- /**
1981
- * Блок «Promotion»: що стає чим і що людина
1982
- * дозволяє. Таблиця, що лишає своє ім'я, рядка перейменування не дає:
1983
- * `a -> a` читався б як зміна, якої немає.
1984
- */
1985
- function promotionLines(p, needs) {
1986
- const lines = [`promotion: ${p.kind} ${p.name} (${p.objectId})`, ` record hash: ${p.recordHash}`];
1987
- for (const t of p.tables.filter((x) => x.from !== x.to)) lines.push(` table ${qualified(t.schema, t.from)} -> ${qualified(t.schema, t.to)}`);
1988
- for (const c of p.columns) lines.push(` column ${qualified(c.table.schema, c.table.name)}: ${quoteIdent(c.from)} -> ${quoteIdent(c.to)}`);
1989
- for (const c of p.canonicalNames) lines.push(` ${c.kind} ${qualified(c.table.schema, c.table.name)}: ${quoteIdent(c.from)} -> ${quoteIdent(c.to)}`);
1990
- for (const t of p.data) {
1991
- lines.push(` data steps ${qualified(t.after.schema, t.after.table)}:`);
1992
- for (const c of t.columns) lines.push(` ${c.step} ${quoteIdent(c.column)} ← ${c.expression} (${c.kind})`);
1993
- if (t.triggers.length > 0) lines.push(` triggers disabled during the write: ${t.triggers.map((x) => quoteIdent(x.name)).join(", ")}`);
1994
- }
1995
- for (const item of p.permissionItems) {
1996
- lines.push(` ${item.token}${needs.has(item.token) ? ` (needs allow: ${item.token})` : ""}`);
1997
- for (const s of item.summary) lines.push(` ${s}`);
1998
- }
1999
- return lines;
2000
- }
2001
- /**
2002
- * Зведення плану для людини й агента: звідки й куди, `planHash` і файл,
2003
- * дрейф — першим блоком, до кроків (платформна спека §6.2): кроки читаються
2004
- * вже знаючи, що ціль дрейфнула. Далі — промоція, бо кроки наміру й класи
2005
- * конверсій читаються, знаючи, що стає чим. Повний
2006
- * SQL — у файлі плану; тут перший рядок.
2007
- */
2008
- function renderPlan(d, report, o) {
2009
- if (d === void 0 || "unchanged" in d) return [o.ok ? "plan: nothing to apply; the database is at the metadata" : "plan: no plan written: the plan was refused or has errors", report].join("\n");
2010
- const needs = new Set(d.requiredPermissions);
2011
- const lines = [
2012
- `plan ${short(d.fromHash)} -> ${short(d.toHash)}`,
2013
- `${o.written ? "written" : "not written"} ${d.file}`,
2014
- `planHash: ${d.planHash}`
2015
- ];
2016
- if (d.drift !== null) {
2017
- lines.push(`drift (${d.drift.reason}): needs allow: drift`);
2018
- if (d.drift.sections.length > 0) lines.push(` fingerprint sections: ${d.drift.sections.join(", ")}`);
2019
- for (const path of d.drift.paths) lines.push(` ${path}`);
2020
- }
2021
- if (d.promotion !== null) lines.push(...promotionLines(d.promotion, needs));
2022
- const stepLine = (s) => {
2023
- const tags = [
2024
- `lock ${s.lockClass}`,
2025
- ...s.conversion === void 0 ? [] : [`conversion ${s.conversion}`],
2026
- ...needs.has(s.id) ? [`needs allow: ${s.id}`] : []
2027
- ];
2028
- const first = s.sql.trim().split("\n")[0] ?? "";
2029
- return ` ${s.id} ${s.origin} ${s.class} (${tags.join("; ")}) ${first}`;
2030
- };
2031
- const environment = d.steps.filter((s) => s.origin === "environment");
2032
- const steps = d.steps.filter((s) => s.origin !== "environment");
2033
- if (steps.length === 0) lines.push("steps: none");
2034
- else {
2035
- lines.push(`steps (${steps.length}):`);
2036
- lines.push(...steps.map(stepLine));
2037
- }
2038
- if (environment.length > 0) {
2039
- lines.push(`environment rights: the global default privileges of role ${quoteIdent(d.environment.role)}:`);
2040
- lines.push(...environment.map(stepLine));
2041
- }
2042
- if (d.locks.length > 0) lines.push(`locks up front: ${d.locks.map((l) => `${qualified(l.schema, l.name)} ${LOCK_MODE_SQL[l.mode]}`).join(", ")}`);
2043
- for (const l of d.implicitLocks) lines.push(`implicit lock: ${qualified(l.schema, l.name)} ${LOCK_MODE_SQL[l.mode]} taken by step ${l.step}, not up front: the apply role may not lock it explicitly`);
2044
- lines.push(`plpgsql_check: ${PLPGSQL_CHECK_LABEL[d.plpgsqlCheck]}`);
2045
- if (d.expectedBlindFunctions > 0) lines.push(`expected provider blind functions (preset): ${d.expectedBlindFunctions}`);
2046
- lines.push(report);
2047
- return lines.join("\n");
2048
- }
2049
- /**
2050
- * Підсумок застосування; репетиція нагадує, що блокування були справжні.
2051
- * Без даних заголовок судить за діагностикою: після обриву з невідомим
2052
- * результатом «нічого не записано» було б неправдою, а повтор за нею міг би
2053
- * застосувати план удруге.
2054
- */
2055
- function renderApply(d, diagnostics, report) {
2056
- const unknown = diagnostics.find((x) => x.code === "apply.connection-lost" && x.params?.outcome === "unknown");
2057
- return [d === void 0 ? unknown === void 0 ? "apply: nothing was written" : `apply: outcome unknown — check simetra.ledger for apply id ${String(unknown.params?.applyId)}` : d.status === "committed" ? `apply: committed in ${d.attempts} attempt(s)` : `rehearse: rolled back after ${d.attempts} attempt(s); the database was not changed; ${d.report === null ? "no rehearsal report was written" : `rehearsal report written to ${d.report}`}. The rehearsal took the plan's locks, as apply does.`, report].join("\n");
2058
- }
2059
- export { invoke as a, summarizeData as c, writeChanges as d, checkEnvName as f, databaseResource as h, renderPlan as i, toJson as l, parseDataLaunch as m, renderApply as n, TOOLS as o, dataResource as p, renderDiff as r, toolByName as s, formatDiagnostics as t, isMetadataFile as u };
2676
+ export { toolByName as a, writeChanges as c, parseDataLaunch as d, databaseResource as f, structureOf as i, checkEnvName as l, TOOLS as n, formatDiagnostics as o, presentation as r, isMetadataFile as s, invoke as t, dataResource as u };