@simetrajs/designer 0.1.0 → 0.3.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +39 -4
  2. package/dist/{command-CRUaUglx.js → command-CHk1P9Dp.js} +91 -108
  3. package/dist/default-dir-DerxTbci.js +158 -0
  4. package/dist/errors-D1P2kKbL.js +62 -0
  5. package/dist/init-jr0Xsrpp.js +832 -0
  6. package/dist/invoke-BwP_5iN6.js +2676 -0
  7. package/dist/main.js +6 -6
  8. package/dist/mcp-args-D63akJ97.js +56 -0
  9. package/dist/mcp-jLOz0W7f.js +219 -0
  10. package/dist/package-hA0J8AMK.js +4 -0
  11. package/dist/{schema-engine-DAsJEc8K.js → schema-engine-8rVHcVYO.js} +704 -195
  12. package/dist/{types-CSc8XWLd.js → types-CMcZhIci.js} +8 -3
  13. package/package.json +16 -12
  14. package/skills/simetra-adoption/SKILL.md +82 -3
  15. package/skills/simetra-metadata/SKILL.md +126 -136
  16. package/skills/simetra-metadata/references/agents-over-mcp.md +236 -0
  17. package/skills/simetra-metadata/references/attribute-load-and-size.md +57 -0
  18. package/skills/simetra-metadata/references/list-order-indexes.md +17 -0
  19. package/skills/simetra-metadata/references/object-modules.md +78 -0
  20. package/skills/simetra-metadata/references/people-and-rights.md +702 -9
  21. package/skills/simetra-metadata/references/plan-and-apply.md +81 -0
  22. package/skills/simetra-metadata/references/project-setup.md +28 -0
  23. package/skills/simetra-metadata/references/row-version-epoch.md +39 -0
  24. package/skills/simetra-metadata/references/search-fields.md +28 -0
  25. package/skills/simetra-metadata/references/sql-trust-boundary.md +225 -0
  26. package/dist/errors-D5pJLrjP.js +0 -36
  27. package/dist/mcp-CJDCleh-.js +0 -241
  28. package/dist/package-DDuGk6yE.js +0 -5
  29. package/dist/report-D2jBS_04.js +0 -1550
package/README.md CHANGED
@@ -29,16 +29,51 @@ npx simetra mcp metadata # the same tools over MCP (stdio)
29
29
  ```
30
30
 
31
31
  `simetra --help` lists every command, and `simetra <command> --help` its
32
- options. Commands that read the database (`introspect`, `diff`, `plan`,
33
- `apply`) take the connection string from `SIMETRA_DATABASE_URL`; `apply`
34
- needs the hash of a reviewed plan file.
32
+ options. Commands that work with the database take the connection string from
33
+ `SIMETRA_DATABASE_URL`;
34
+ `apply` needs the hash of a reviewed plan file, and `roles` creates the
35
+ platform's cluster roles once, before the first `plan`.
36
+
37
+ ## Start a project
38
+
39
+ ```bash
40
+ pnpm add simetra
41
+ pnpm add -D @simetrajs/designer
42
+ pnpm exec simetra init [--agents claude,codex,cursor,vscode]
43
+ ```
44
+
45
+ `init` is idempotent and writes only inside the project:
46
+
47
+ - relative symlinks `.agents/skills/<skill>` and `.claude/skills/<skill>` to
48
+ the skills in `node_modules/@simetrajs/designer/skills/`, so an update of
49
+ the package updates the skills too (on Windows, junctions; a git checkout
50
+ without `core.symlinks` turns the committed links into files, and `init`
51
+ replaces them with junctions);
52
+ - the MCP server entry `simetra` for each agent in `--agents` (default:
53
+ `claude`): `.mcp.json`, `.codex/config.toml` (`[mcp_servers.simetra]`),
54
+ `.cursor/mcp.json` or `.vscode/mcp.json`. The server starts as
55
+ `node <path to the installed bin> mcp`.
56
+
57
+ Another directory or link with the same skill name, and another `simetra`
58
+ entry in a config, stay as they are; `init` prints a note. `init --dry-run`
59
+ prints the changes without writing; `init --check` exits with code 1 if
60
+ `init` would change anything. If `init` refuses, it writes nothing; an I/O
61
+ failure in the middle of writing may leave part of the changes done, and
62
+ running `init` again completes them.
63
+
64
+ Commit the links and the configs, and run `simetra init --check` in CI with
65
+ the same `--agents`. The server writes metadata by default; to forbid writes,
66
+ add `--read-only` to the `args` of the entry by hand. Codex reads
67
+ `.codex/config.toml` only in a trusted project. In a monorepo, run `init` in
68
+ the root the agent starts from, where the `metadata` directory lives.
35
69
 
36
70
  ## Agent skills
37
71
 
38
72
  The package ships skills for AI agents working in a Simetra project under
39
73
  `skills/`: `simetra-metadata` (editing metadata through the tools) and
40
74
  `simetra-adoption` (bringing an existing database under metadata). They
41
- match the installed version of the tools.
75
+ match the installed version of the tools. `simetra init` links them into the
76
+ project for the agents.
42
77
 
43
78
  ## License
44
79
 
@@ -1,19 +1,21 @@
1
1
  #!/usr/bin/env node
2
- import { a as DEFAULT_DIR, c as DEFAULT_DATABASE_URL_ENV, f as toolByName, g as UsageError, h as databaseResource, i as renderPlan, m as writeChanges, n as renderApply, o as trimSlash, p as isMetadataFile, r as renderDiff, s as invoke, t as formatDiagnostics } from "./report-D2jBS_04.js";
2
+ import { a as toolByName, c as writeChanges, d as parseDataLaunch, f as databaseResource, i as structureOf, l as checkEnvName, o as formatDiagnostics, r as presentation, s as isMetadataFile, t as invoke, u as dataResource } from "./invoke-BwP_5iN6.js";
3
+ import { i as DEFAULT_DATABASE_URL_ENV, n as trimSlash, p as UsageError, t as DEFAULT_DIR } from "./default-dir-DerxTbci.js";
3
4
  import { defineCommand } from "citty";
4
5
  import { mkdtemp, readdir, rm, stat } from "node:fs/promises";
5
6
  import { basename, dirname, join, resolve } from "node:path";
6
7
  import { ATTRIBUTE_CASES, DATABASE_PROVIDERS, METADATA_KINDS } from "simetra/model";
7
8
  import { DEFAULT_APPLY_TIMEOUTS, renderDesiredState } from "simetra/schema";
8
- import { canonicalSnapshot, emitEntityTypes } from "simetra/compiler";
9
+ import { buildClientCatalog, buildRuntimeCatalog, canonicalSnapshot, emitEntityTypes } from "simetra/compiler";
9
10
  import { spawn } from "node:child_process";
10
11
  import { tmpdir } from "node:os";
11
- //#region src/tools/artifacts.ts
12
+ // src/tools/artifacts.ts
12
13
  /**
13
14
  * Артефакти компіляції як зміни файлів: рішення, куди й чи писати, ухвалює
14
15
  * адаптер (`compile --out`), тут лише вміст.
15
16
  */
16
17
  function compileArtifacts(model) {
18
+ const runtime = buildRuntimeCatalog(model);
17
19
  return [
18
20
  {
19
21
  path: "snapshot.json",
@@ -26,11 +28,18 @@ function compileArtifacts(model) {
26
28
  {
27
29
  path: "entities.d.ts",
28
30
  content: emitEntityTypes(model)
31
+ },
32
+ {
33
+ path: "runtime-catalog.json",
34
+ content: `${JSON.stringify(runtime, null, 2)}\n`
35
+ },
36
+ {
37
+ path: "client-catalog.json",
38
+ content: `${JSON.stringify(buildClientCatalog(runtime), null, 2)}\n`
29
39
  }
30
40
  ];
31
41
  }
32
- //#endregion
33
- //#region src/cli/metadata-dirs.ts
42
+ // src/cli/metadata-dirs.ts
34
43
  const PROJECT_FILE = "project.meta.json";
35
44
  function git(cwd, args, input) {
36
45
  return new Promise((resolve, reject) => {
@@ -205,8 +214,7 @@ async function readHeadMetadata(cwd, dir) {
205
214
  const texts = entries.length === 0 ? [] : await readBlobs(at, entries.map((e) => e.sha));
206
215
  return new Map(entries.map((e, i) => [e.key, texts[i] ?? ""]));
207
216
  }
208
- //#endregion
209
- //#region src/cli/input.ts
217
+ // src/cli/input.ts
210
218
  /**
211
219
  * Читальні інструменти й `fix` мають зручні позиційні форми — це лише вигляд
212
220
  * над тим самим входом каталогу. Усі інші беруть вхід каталогу як JSON.
@@ -218,7 +226,8 @@ const ERGONOMIC = /* @__PURE__ */ new Set([
218
226
  "introspect",
219
227
  "diff",
220
228
  "plan",
221
- "apply"
229
+ "apply",
230
+ "roles"
222
231
  ]);
223
232
  /** `a,b` → `["a", "b"]`; порожні елементи — помилка написання, не фільтр. */
224
233
  function list(flag, value) {
@@ -242,12 +251,17 @@ async function cliInput(tool, args, stdin) {
242
251
  if (tool.name === "explain") {
243
252
  const target = positional[0] ?? "";
244
253
  const dot = target.indexOf(".");
245
- if (dot <= 0 || dot === target.length - 1) throw new UsageError(`Invalid target "${target}". Expected <Kind>.<Name>, e.g. Document.ServiceAccrual (kinds: ${METADATA_KINDS.join(", ")}).`);
254
+ if (dot <= 0 || dot === target.length - 1) throw new UsageError(`Invalid target "${target}". Expected <Kind>.<Name>, e.g. Document.ServiceAccrual (kinds: ${METADATA_KINDS.join(", ")}), or <schema>.<function>, e.g. public.post_order.`);
255
+ const head = target.slice(0, dot);
256
+ const tail = target.slice(dot + 1);
246
257
  return {
247
- input: {
248
- kind: target.slice(0, dot),
249
- name: target.slice(dot + 1)
250
- },
258
+ input: METADATA_KINDS.includes(head) ? {
259
+ kind: head,
260
+ name: tail
261
+ } : { function: {
262
+ schema: head,
263
+ name: tail
264
+ } },
251
265
  dirs: [trimSlash(positional[1] ?? "./metadata")]
252
266
  };
253
267
  }
@@ -276,7 +290,7 @@ async function cliInput(tool, args, stdin) {
276
290
  input: args.tables === void 0 ? {} : { tables: list("tables", args.tables) },
277
291
  dirs: [trimSlash(positional[0] ?? "./metadata")]
278
292
  };
279
- if (tool.name === "plan") return {
293
+ if (tool.name === "plan" || tool.name === "roles") return {
280
294
  input: {},
281
295
  dirs: [trimSlash(positional[0] ?? "./metadata")]
282
296
  };
@@ -313,113 +327,48 @@ async function cliInput(tool, args, stdin) {
313
327
  dirs: [trimSlash(rest[0] ?? "./metadata")]
314
328
  };
315
329
  }
316
- //#endregion
317
- //#region src/cli/render.ts
318
- /** Текст пояснення об'єкта для терміналу; JSON-вигляд друкується як є. */
319
- function renderExplanation(e) {
320
- const lines = [`${e.object.kind} ${e.object.name} (${e.object.file})`];
321
- if (e.object.scopeKind !== void 0) lines.push(`scope: ${e.object.scopeKind}`);
322
- for (const t of e.tables) {
323
- lines.push("", `table ${t.schema}.${t.name}${t.part ? ` [${t.part}]` : ""}`);
324
- for (const c of t.columns) {
325
- const tags = [
326
- c.notNull ? "not null" : void 0,
327
- c.logical === void 0 ? void 0 : `logical: ${c.logical}`,
328
- c.standard === void 0 ? void 0 : `standard: ${c.standard}`,
329
- c.scope === true ? "scope" : void 0
330
- ].filter((x) => x !== void 0);
331
- lines.push(` ${c.name} ${c.type}${tags.length > 0 ? ` (${tags.join(", ")})` : ""}`);
332
- }
333
- if (t.primaryKey !== void 0) lines.push(` primary key (${t.primaryKey.join(", ")})`);
334
- for (const u of t.uniques) lines.push(` unique (${u.join(", ")})`);
335
- for (const f of t.foreignKeys) lines.push(` foreign key (${f.columns.join(", ")}) -> ${f.references}`);
336
- }
337
- for (const q of e.movementQueries) lines.push("", `movement query ${q.identity}`, q.sql);
338
- for (const u of e.generatedUnits) lines.push("", `generated ${u.identity}`, u.sql);
339
- if (e.contracts.length > 0) lines.push("", "contracts:", JSON.stringify(e.contracts, null, 2));
340
- if (e.referencedBy.length > 0) {
341
- lines.push("", "referenced by:");
342
- for (const r of e.referencedBy) lines.push(` ${r.file}#${r.pointer} (${r.role})`);
343
- }
344
- return `${lines.join("\n")}\n`;
345
- }
346
- /**
347
- * Підсумок запису промоції для терміналу: що на що перетворилось і що
348
- * лишається плану бази. Повний запис — у `--format json`.
349
- */
350
- function renderPromotion(r, written) {
351
- const lines = [`${written ? "promoted" : "would promote"} ${r.objectId} into ${r.kind}`];
352
- for (const t of r.tables) lines.push(` table ${t.schema}.${t.from} -> ${t.to}`);
353
- const counts = [
354
- ["columns renamed or moved", r.columns.length],
355
- ["type changes", r.typeChanges.length],
356
- ["data steps", r.dataSteps.length],
357
- ["columns retired", r.retired.length],
358
- ["constraints relaxed", r.relaxed.length],
359
- ["constraints tightened", r.tightened.length],
360
- ["row level security changes", r.rowLevelSecurity.length],
361
- ["delete semantics changes", r.deleteSemantics.length],
362
- ["conversions", r.conversions.length],
363
- ["units moved", r.movedUnits.length],
364
- ["units rewritten", r.rewrittenUnits.length],
365
- ["contract changes", r.contractChanges.length]
366
- ];
367
- for (const [label, n] of counts) if (n > 0) lines.push(` ${label}: ${n}`);
368
- return lines.join("\n");
369
- }
330
+ // src/cli/render.ts
370
331
  /** Кінцевий результат одного виклику в тексті/JSON для терміналу. */
371
332
  function renderResult(tool, r, o) {
372
333
  const report = formatDiagnostics(r.diagnostics, o);
373
- if (tool.name === "compile") return o.format === "json" ? {
334
+ const present = tool.present;
335
+ if (present?.diagnosticsOnly === true) return o.format === "json" ? {
374
336
  stdout: "",
375
337
  json: JSON.parse(report)
376
338
  } : { stdout: report };
377
- if (tool.name === "explain" && r.ok && r.data !== void 0) {
378
- const explanation = r.data;
379
- return { stdout: o.format === "json" ? JSON.stringify(explanation, null, 2) : renderExplanation(explanation).trimEnd() };
380
- }
381
- if (tool.name === "diff" && r.data !== void 0) {
382
- const data = r.data;
383
- return { stdout: o.format === "json" ? JSON.stringify({
384
- ok: r.ok,
385
- empty: data.empty,
386
- plan: data.plan,
387
- differences: data.differences,
388
- diagnostics: JSON.parse(report)
389
- }, null, 2) : renderDiff(data, report) };
390
- }
391
- if (tool.name === "plan" || tool.name === "apply") {
392
- if (o.format === "json") return { stdout: JSON.stringify({
393
- ok: r.ok,
394
- written: r.written,
395
- artifacts: r.artifacts ?? [],
396
- ...r.data,
397
- diagnostics: JSON.parse(report)
398
- }, null, 2) };
399
- return { stdout: tool.name === "plan" ? renderPlan(r.data, report, {
400
- ok: r.ok,
401
- written: r.written
402
- }) : renderApply(r.data, r.diagnostics, report) };
339
+ const view = {
340
+ channel: "cli",
341
+ ok: r.ok,
342
+ written: r.written,
343
+ diagnostics: r.diagnostics,
344
+ report
345
+ };
346
+ const { shown: shows, data } = presentation(tool, r);
347
+ if (shows && present?.bare === true && o.format === "json") return { stdout: JSON.stringify(r.data, null, 2) };
348
+ if (shows && o.format === "text") {
349
+ const text = present?.text?.(r.data, view);
350
+ if (text !== void 0) return { stdout: text };
403
351
  }
404
- if (tool.files === "read") return { stdout: report };
352
+ if (!shows && tool.files === "read") return { stdout: report };
405
353
  const changed = r.changes.map((c) => c.path);
406
354
  if (o.format === "json") return { stdout: JSON.stringify({
407
355
  ok: r.ok,
408
356
  written: r.written,
357
+ ...r.wouldWrite === true ? { wouldWrite: true } : {},
409
358
  changed,
410
- diagnostics: JSON.parse(report),
411
- ...tool.name === "promote" && r.data !== void 0 ? { record: r.data } : {}
359
+ ...tool.files === "artifact" ? { artifacts: r.artifacts ?? [] } : {},
360
+ ...data !== void 0 ? structureOf(tool, data) : {},
361
+ diagnostics: JSON.parse(report)
412
362
  }, null, 2) };
413
363
  const verb = (deleted) => r.written ? deleted ? "deleted" : "written" : deleted ? "would delete" : "would write";
414
364
  return { stdout: [
415
365
  ...r.changes.map((c) => `${verb(c.deleted)} ${o.dir}/${c.path}`),
416
- ...r.ok ? [] : ["nothing written: the result has errors"],
366
+ ...r.ok ? [] : r.written ? ["written: the result keeps only repair-class errors the directory already had"] : r.wouldWrite === true ? ["would write: the result keeps only repair-class errors the directory already had"] : ["nothing written: the result has errors"],
417
367
  report,
418
- ...tool.name === "promote" && r.data !== void 0 ? [renderPromotion(r.data, r.written)] : []
368
+ ...data !== void 0 && present?.appendix !== void 0 ? [present.appendix(data, view)] : []
419
369
  ].join("\n") };
420
370
  }
421
- //#endregion
422
- //#region src/cli/command.ts
371
+ // src/cli/command.ts
423
372
  const readStdin = async () => {
424
373
  const chunks = [];
425
374
  for await (const chunk of process.stdin) chunks.push(chunk);
@@ -462,10 +411,18 @@ async function runTool(tool, argv, stdin = readStdin, cwd = process.cwd(), env =
462
411
  } : await cliInput(tool, argv, stdin);
463
412
  const { input } = parsed;
464
413
  const databaseEnv = argv["database-url-env"] ?? "SIMETRA_DATABASE_URL";
414
+ checkEnvName("--database-url-env", databaseEnv);
415
+ if (argv["shadow-url-env"] !== void 0) checkEnvName("--shadow-url-env", argv["shadow-url-env"]);
465
416
  const database = tool.database === "none" ? void 0 : databaseResource(env, {
466
417
  url: databaseEnv,
467
418
  ...argv["shadow-url-env"] === void 0 ? {} : { shadow: argv["shadow-url-env"] }
468
419
  });
420
+ const launch = tool.data === "none" ? void 0 : parseDataLaunch({
421
+ dataUrlEnv: argv["data-url-env"],
422
+ as: argv.as,
423
+ agent: argv.agent
424
+ });
425
+ const data = launch === void 0 ? void 0 : dataResource(env, launch);
469
426
  let { dirs } = parsed;
470
427
  const shown = dirs;
471
428
  if (sweep) dirs = dirs.map((d) => resolve(cwd, d));
@@ -499,6 +456,10 @@ async function runTool(tool, argv, stdin = readStdin, cwd = process.cwd(), env =
499
456
  dir,
500
457
  readOnly: false,
501
458
  allowDatabaseWrite: true,
459
+ allowDataWrite: true,
460
+ allowRightsWrite: argv["allow-rights-write"] === true,
461
+ ...data === void 0 ? {} : { data },
462
+ ...launch === void 0 ? {} : { dataEnv: launch.urlEnv },
502
463
  dryRun: argv["dry-run"] === true,
503
464
  confirmed: argv.yes === true,
504
465
  channel: "cli",
@@ -552,12 +513,12 @@ function argsFor(tool) {
552
513
  };
553
514
  args.out = {
554
515
  type: "string",
555
- description: "Write snapshot.json, desired-state.sql, entities.d.ts here"
516
+ description: "Write snapshot.json, desired-state.sql, entities.d.ts, runtime-catalog.json, client-catalog.json here"
556
517
  };
557
518
  } else if (tool.name === "explain") {
558
519
  args.target = {
559
520
  type: "positional",
560
- description: "<Kind>.<Name>, e.g. Document.ServiceAccrual",
521
+ description: "<Kind>.<Name>, e.g. Document.ServiceAccrual, or <schema>.<function>, e.g. public.post_order (a schema named like a kind, or containing a dot, needs the JSON input of MCP)",
561
522
  required: true
562
523
  };
563
524
  args.dir = {
@@ -613,7 +574,7 @@ function argsFor(tool) {
613
574
  args["database-provider"] = {
614
575
  type: "enum",
615
576
  options: [...DATABASE_PROVIDERS],
616
- description: "Database provider of a new project (default \"supabase\")"
577
+ description: "Database provider of a new project: supabase | postgres (default \"supabase\")"
617
578
  };
618
579
  }
619
580
  if (tool.name === "diff") args.tables = {
@@ -627,7 +588,7 @@ function argsFor(tool) {
627
588
  };
628
589
  args.allow = {
629
590
  type: "string",
630
- description: "Comma-separated plan items to permit: step ids (s1,s2), drift, access:, delete:, remove: and repair: items (a name with a comma only via MCP)"
591
+ description: "Comma-separated plan items to permit: step ids (s1,s2), drift, access:, delete:, update:, remove: and repair: items (a name with a comma only via MCP)"
631
592
  };
632
593
  args.rehearse = {
633
594
  type: "boolean",
@@ -653,6 +614,25 @@ function argsFor(tool) {
653
614
  description: "Environment variable with a connection string to another server of the same PostgreSQL major version for the shadow database"
654
615
  };
655
616
  }
617
+ if (tool.data !== "none") {
618
+ args["data-url-env"] = {
619
+ type: "string",
620
+ description: "Environment variable with the connection string of the runtime login role to the development database"
621
+ };
622
+ args.as = {
623
+ type: "string",
624
+ description: "UUID of the user the command acts as, with that user's rights"
625
+ };
626
+ args.agent = {
627
+ type: "string",
628
+ description: "UUID of the agent, recorded as the act claim; it grants no rights"
629
+ };
630
+ }
631
+ if (tool.data === "write") args["allow-rights-write"] = {
632
+ type: "boolean",
633
+ default: false,
634
+ description: "Write rights catalogs and create scope roots whose creator receives a role"
635
+ };
656
636
  if (tool.files === "write") args["dry-run"] = {
657
637
  type: "boolean",
658
638
  default: false,
@@ -701,7 +681,11 @@ function toCliArgs(args) {
701
681
  allow: str(args.allow),
702
682
  rehearse: args.rehearse === true,
703
683
  "lock-timeout-ms": str(args["lock-timeout-ms"]),
704
- "statement-timeout-ms": str(args["statement-timeout-ms"])
684
+ "statement-timeout-ms": str(args["statement-timeout-ms"]),
685
+ "data-url-env": str(args["data-url-env"]),
686
+ as: str(args.as),
687
+ agent: str(args.agent),
688
+ "allow-rights-write": args["allow-rights-write"] === true
705
689
  };
706
690
  }
707
691
  /** Підкоманда з запису каталогу: опис, прапорці й дозволи беруться з нього. */
@@ -726,5 +710,4 @@ function commandByName(name) {
726
710
  if (tool === void 0) throw new Error(`unknown tool: ${name}`);
727
711
  return toolCommand(tool);
728
712
  }
729
- //#endregion
730
713
  export { commandByName };
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env node
2
+ import { dirname, join, posix, relative, resolve, sep } from "node:path";
3
+ import { existsSync } from "node:fs";
4
+ // src/io/usage-error.ts
5
+ /**
6
+ * Помилка використання (немає теки, шлях поза текою): викликач може виправити
7
+ * її сам. Лише її `invoke` перетворює на відмову; будь-який інший виняток —
8
+ * баг, і він не повинен маскуватися під відмову.
9
+ */
10
+ var UsageError = class extends Error {
11
+ name = "UsageError";
12
+ };
13
+ // src/io/package-path.ts
14
+ /**
15
+ * Тека встановленого пакета: перший предок `fromDir` (включно) з
16
+ * `node_modules/<pkg>/package.json`. Шлях навмисно не проходить `realpath`:
17
+ * pnpm робить `node_modules/<pkg>` симлінком у сховище, а значення, що потрапляє
18
+ * у файли метаданих, мусить бути однаковим на кожній машині й переживати
19
+ * перенос репо.
20
+ */
21
+ function installedPackageDir(fromDir, pkg) {
22
+ const start = resolve(fromDir);
23
+ let current = start;
24
+ for (;;) {
25
+ const candidate = join(current, "node_modules", pkg);
26
+ if (existsSync(join(candidate, "package.json"))) return candidate;
27
+ const parent = dirname(current);
28
+ if (parent === current) throw new UsageError(`${pkg} is not installed in node_modules above ${start}`);
29
+ current = parent;
30
+ }
31
+ }
32
+ /**
33
+ * Відносний шлях із роздільниками `/`: він потрапляє у файли, які комітять і
34
+ * читають на будь-якій ОС (`$schema`, ціль лінка скіла, шлях до бінарника в
35
+ * MCP-конфігу), тож форма не може залежати від машини, де його пораховано.
36
+ */
37
+ function posixRelative(fromDir, to) {
38
+ return relative(fromDir, to).split(sep).join(posix.sep);
39
+ }
40
+ // src/tools/hints.ts
41
+ const READ_ONLY_FLAG = "--read-only";
42
+ const ALLOW_DATABASE_WRITE_FLAG = "--allow-database-write";
43
+ const ALLOW_DATA_WRITE_FLAG = "--allow-data-write";
44
+ const ALLOW_RIGHTS_WRITE_FLAG = "--allow-rights-write";
45
+ /** Типова змінна середовища з рядком підключення; ім'я фіксується при запуску. */
46
+ const DEFAULT_DATABASE_URL_ENV = "SIMETRA_DATABASE_URL";
47
+ /**
48
+ * Єдине джерело тексту «як увімкнути запис»: його бачить і клієнт MCP в
49
+ * `instructions`, і агент у відмові на запис у режимі лише читання.
50
+ * `launchArgs` — справжній argv запуску сервера без node і скрипта, тобто
51
+ * лише ХВІСТ `args` у конфігу клієнта: лаунчер (`pnpm exec simetra …`,
52
+ * `npx …`, обгортка) додає свої аргументи попереду. Тому підказка каже
53
+ * «прибери прапорець» і показує хвіст до й після, а не видає його за повний
54
+ * `"args"` — буквальна заміна зламала б конфіг.
55
+ */
56
+ function readOnlyHint(launchArgs = [
57
+ "simetra",
58
+ "mcp",
59
+ READ_ONLY_FLAG
60
+ ]) {
61
+ const before = launchArgs.includes("--read-only") ? launchArgs : [...launchArgs, READ_ONLY_FLAG];
62
+ const after = before.filter((a) => a !== READ_ONLY_FLAG);
63
+ return [
64
+ `This server runs with ${READ_ONLY_FLAG}: tools that write are disabled.`,
65
+ `To enable them, remove ${READ_ONLY_FLAG} from this server's args in the MCP client config and restart it:`,
66
+ `args ending in ${JSON.stringify(before)} become ${JSON.stringify(after)}.`
67
+ ].join(" ");
68
+ }
69
+ /**
70
+ * Підказка відмови `apply` без прапорця запису в базу і її ж речення в
71
+ * `instructions`. Як і `readOnlyHint`, показує лише хвіст `args`: прапорець
72
+ * додається, а не замінює конфіг. Вмикає його людина, а не агент: запис у
73
+ * базу поза git, тож рішення — при запуску сервера.
74
+ */
75
+ function databaseWriteHint(launchArgs = ["simetra", "mcp"], o = {}) {
76
+ const before = launchArgs.filter((a) => a !== ALLOW_DATABASE_WRITE_FLAG);
77
+ const after = [...before, ALLOW_DATABASE_WRITE_FLAG];
78
+ return [
79
+ `This server runs without ${ALLOW_DATABASE_WRITE_FLAG}: ${o.tools ?? "apply"} cannot write to the database.`,
80
+ `Only the owner may enable it: add ${ALLOW_DATABASE_WRITE_FLAG} to this server's args in the MCP client config and restart it:`,
81
+ `args ending in ${JSON.stringify(before)} become ${JSON.stringify(after)}.`,
82
+ ...o.refusal === false ? [] : ["Nothing changed."]
83
+ ].join(" ");
84
+ }
85
+ /**
86
+ * Називає лише змінну, ніколи її значення: рядок підключення несе
87
+ * користувача й пароль, а відмова йде агентові й у журнали клієнта.
88
+ * Середовище команди задає сам викликач перед наступним запуском, а
89
+ * середовище MCP-сервера фіксується при його старті — звідси дві поради.
90
+ */
91
+ function noDatabaseHint(envName, channel) {
92
+ const how = channel === "cli" ? `Export the environment variable ${envName} with the connection string of the target database, or name another variable with --database-url-env.` : `Set the environment variable ${envName} to the connection string of the target database in this server's environment and restart the server.`;
93
+ return [
94
+ `This tool needs a database connection, and ${channel === "cli" ? "none is configured" : "the server has none"}.`,
95
+ how,
96
+ "Nothing changed."
97
+ ].join(" ");
98
+ }
99
+ /**
100
+ * Підказка відмови запису даних без прапорця і її речення в `instructions`.
101
+ * Окремий прапорець від запису в базу: засів тестових даних не дає права
102
+ * змінювати схему, і навпаки. Форма — як `databaseWriteHint`: хвіст `args`
103
+ * до й після.
104
+ */
105
+ function dataWriteHint(launchArgs = ["simetra", "mcp"], o = {}) {
106
+ const before = launchArgs.filter((a) => a !== ALLOW_DATA_WRITE_FLAG);
107
+ const after = [...before, ALLOW_DATA_WRITE_FLAG];
108
+ return [
109
+ `This server runs without ${ALLOW_DATA_WRITE_FLAG}: ${o.tools ?? "data-command"} cannot change application data.`,
110
+ `Only the owner may enable it: add ${ALLOW_DATA_WRITE_FLAG} to this server's args in the MCP client config and restart it:`,
111
+ `args ending in ${JSON.stringify(before)} become ${JSON.stringify(after)}.`,
112
+ ...o.refusal === false ? [] : ["Nothing changed."]
113
+ ].join(" ");
114
+ }
115
+ /**
116
+ * Відмова запису прав без прапорця. Довідники прав (і створення кореня
117
+ * скоупу, творець якого отримує роль) змінюють, хто що може, тож їх вмикає
118
+ * людина окремим прапорцем навіть там, де запис даних уже дозволено. CLI
119
+ * радить прапорець команди, MCP — прапорець запуску сервера.
120
+ */
121
+ function rightsWriteHint(launchArgs = ["simetra", "mcp"], channel = "mcp") {
122
+ const what = "This operation changes rights: it writes a rights catalog (roles or role assignments) or creates a scope root whose creator receives a role.";
123
+ if (channel === "cli") return [
124
+ what,
125
+ `Run the command again with ${ALLOW_RIGHTS_WRITE_FLAG} if you mean to change rights.`,
126
+ "Nothing changed."
127
+ ].join(" ");
128
+ const before = launchArgs.filter((a) => a !== ALLOW_RIGHTS_WRITE_FLAG);
129
+ const after = [...before, ALLOW_RIGHTS_WRITE_FLAG];
130
+ return [
131
+ what,
132
+ `This server runs without ${ALLOW_RIGHTS_WRITE_FLAG}. Only the owner may enable it: add ${ALLOW_RIGHTS_WRITE_FLAG} to this server's args in the MCP client config and restart it:`,
133
+ `args ending in ${JSON.stringify(before)} become ${JSON.stringify(after)}.`,
134
+ "Nothing changed."
135
+ ].join(" ");
136
+ }
137
+ /**
138
+ * Відмова без ресурсу даних. Як і `noDatabaseHint`, називає лише змінну,
139
+ * ніколи її значення. Типової змінної немає: доступ від імені користувача —
140
+ * явне рішення людини (`--data-url-env` і `--as`), тож без імені підказка
141
+ * називає обидва прапорці, а з іменем — порожню змінну.
142
+ */
143
+ function noDataHint(envName, channel) {
144
+ const flags = "--data-url-env <name of the environment variable with the connection string of the runtime login role> and --as <user uuid>";
145
+ let how;
146
+ if (envName === void 0) how = channel === "cli" ? `Pass ${flags}.` : `Add ${flags} to this server's args in the MCP client config and restart it.`;
147
+ else how = channel === "cli" ? `The environment variable ${envName} is empty: export it with the connection string of the development database.` : `The environment variable ${envName} is empty: set it to the connection string of the development database in this server's environment and restart the server.`;
148
+ return [
149
+ `This tool needs access to the development database data, and ${channel === "cli" ? "none is configured" : "the server has none"}.`,
150
+ how,
151
+ "Nothing changed."
152
+ ].join(" ");
153
+ }
154
+ // src/io/default-dir.ts
155
+ /** Тека метаданих за замовчуванням — спільна для CLI і `simetra mcp`. */
156
+ const DEFAULT_DIR = "./metadata";
157
+ const trimSlash = (d) => d.replace(/(?<=.)[\\/]+$/, "");
158
+ export { dataWriteHint as a, noDatabaseHint as c, installedPackageDir as d, posixRelative as f, DEFAULT_DATABASE_URL_ENV as i, readOnlyHint as l, trimSlash as n, databaseWriteHint as o, UsageError as p, ALLOW_RIGHTS_WRITE_FLAG as r, noDataHint as s, DEFAULT_DIR as t, rightsWriteHint as u };
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ // src/schema-engine/errors.ts
3
+ /** Тінь на сервері іншої мажорної версії: каталоги двох версій не порівнюються. */
4
+ var ShadowServerMismatchError = class extends Error {
5
+ name = "ShadowServerMismatchError";
6
+ };
7
+ /** Роль підключення не має `CREATEDB` на сервері, де мала б з'явитися тінь. */
8
+ var ShadowCreateRefusedError = class extends Error {
9
+ onShadowBase;
10
+ name = "ShadowCreateRefusedError";
11
+ constructor(onShadowBase) {
12
+ super("the connecting role lacks CREATEDB");
13
+ this.onShadowBase = onShadowBase;
14
+ }
15
+ };
16
+ /**
17
+ * Збій створення тіні чи підключення до неї з причиною, якої адаптер не
18
+ * розпізнав: причина — у `cause`. Межа описує її адресою сервера, де мала
19
+ * з'явитися тінь, і називає вимогу тіні до режиму з'єднання (спека designer
20
+ * §3.2).
21
+ */
22
+ var ShadowServerError = class extends Error {
23
+ onShadowBase;
24
+ shadowDrop;
25
+ name = "ShadowServerError";
26
+ constructor(cause, onShadowBase, shadowDrop) {
27
+ super("the shadow could not be created or reached", { cause });
28
+ this.onShadowBase = onShadowBase;
29
+ this.shadowDrop = shadowDrop;
30
+ }
31
+ };
32
+ /**
33
+ * Збій видалення тіні на шляху винятку: виняток лишається тим самим (його
34
+ * клас розпізнає межа), а попередження `engine.shadow-drop-failed` стає його
35
+ * полем `shadowDrop`. Значення, що не є `Error`, поля не несе.
36
+ */
37
+ function withShadowDrop(error, drop) {
38
+ if (error instanceof Error) Object.assign(error, { shadowDrop: drop });
39
+ return error;
40
+ }
41
+ /** Попередження про невидалену тінь, яке несе виняток, якщо несе. */
42
+ function shadowDropOf(error) {
43
+ if (!(error instanceof Error)) return void 0;
44
+ return error.shadowDrop;
45
+ }
46
+ /** Шаблон тіні профілю відсутній або не запечатаний суперкористувачем: його готує `simetra roles`. */
47
+ var ShadowTemplateMissingError = class extends Error {
48
+ template;
49
+ name = "ShadowTemplateMissingError";
50
+ constructor(template) {
51
+ super(`the shadow template database "${template}" is missing or not sealed`);
52
+ this.template = template;
53
+ }
54
+ };
55
+ /** Профіль `postgres` будує тіні з шаблону кластера цілі й окремого сервера тіней не має. */
56
+ var ShadowBaseUnsupportedError = class extends Error {
57
+ name = "ShadowBaseUnsupportedError";
58
+ constructor() {
59
+ super("a separate shadow server is not supported with the postgres profile");
60
+ }
61
+ };
62
+ export { ShadowTemplateMissingError as a, ShadowServerMismatchError as i, ShadowCreateRefusedError as n, shadowDropOf as o, ShadowServerError as r, withShadowDrop as s, ShadowBaseUnsupportedError as t };