@simetrajs/designer 0.3.0-next.1 → 0.3.0-next.3

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
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";
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-Dkbpi4Fq.js";
3
3
  import { i as DEFAULT_DATABASE_URL_ENV, n as trimSlash, p as UsageError, t as DEFAULT_DIR } from "./default-dir-DerxTbci.js";
4
4
  import { defineCommand } from "citty";
5
5
  import { mkdtemp, readdir, rm, stat } from "node:fs/promises";
@@ -290,10 +290,14 @@ async function cliInput(tool, args, stdin) {
290
290
  input: args.tables === void 0 ? {} : { tables: list("tables", args.tables) },
291
291
  dirs: [trimSlash(positional[0] ?? "./metadata")]
292
292
  };
293
- if (tool.name === "plan" || tool.name === "roles") return {
293
+ if (tool.name === "plan") return {
294
294
  input: {},
295
295
  dirs: [trimSlash(positional[0] ?? "./metadata")]
296
296
  };
297
+ if (tool.name === "roles") return {
298
+ input: args["dev-passwords"] === true ? { devPasswords: true } : {},
299
+ dirs: [trimSlash(positional[0] ?? "./metadata")]
300
+ };
297
301
  if (tool.name === "apply") {
298
302
  const plan = positional[0];
299
303
  if (plan === void 0) throw new UsageError("apply needs the plan file: simetra apply <plans/….plan.json> [dir] --plan-hash <hex> --yes.");
@@ -465,6 +469,7 @@ async function runTool(tool, argv, stdin = readStdin, cwd = process.cwd(), env =
465
469
  channel: "cli",
466
470
  database,
467
471
  databaseEnv,
472
+ env,
468
473
  ...baseline === void 0 ? {} : { baseline }
469
474
  });
470
475
  if (result.refusal !== void 0) return fail(result.refusal.message);
@@ -604,6 +609,11 @@ function argsFor(tool) {
604
609
  description: `statement_timeout of the apply transaction (default ${DEFAULT_APPLY_TIMEOUTS.statementTimeoutMs})`
605
610
  };
606
611
  }
612
+ if (tool.name === "roles") args["dev-passwords"] = {
613
+ type: "boolean",
614
+ default: false,
615
+ description: "Postgres provider, a database on this machine only: set the passwords of the login roles this run creates from SIMETRA_OWNER_DEV_PASSWORD, SIMETRA_AUTH_DEV_PASSWORD, SIMETRA_RUNTIME_DEV_PASSWORD and SIMETRA_SIGNALS_DEV_PASSWORD"
616
+ };
607
617
  if (tool.database !== "none") {
608
618
  args["database-url-env"] = {
609
619
  type: "string",
@@ -680,6 +690,7 @@ function toCliArgs(args) {
680
690
  "plan-hash": str(args["plan-hash"]),
681
691
  allow: str(args.allow),
682
692
  rehearse: args.rehearse === true,
693
+ "dev-passwords": args["dev-passwords"] === true,
683
694
  "lock-timeout-ms": str(args["lock-timeout-ms"]),
684
695
  "statement-timeout-ms": str(args["statement-timeout-ms"]),
685
696
  "data-url-env": str(args["data-url-env"]),
@@ -3,7 +3,7 @@ import { d as installedPackageDir, f as posixRelative, p as UsageError, t as DEF
3
3
  import { t as mcpArgs } from "./mcp-args-D63akJ97.js";
4
4
  import { defineCommand, parseArgs } from "citty";
5
5
  import { lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
6
- import { basename, dirname, join, posix, resolve, win32 } from "node:path";
6
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, win32 } from "node:path";
7
7
  import { parse } from "smol-toml";
8
8
  import { randomUUID } from "node:crypto";
9
9
  // src/init/fs-probe.ts
@@ -60,6 +60,7 @@ const DEFAULT_AGENTS = ["claude"];
60
60
  const MCP_SERVER_NAME = "simetra";
61
61
  const WORKSPACE = "${workspaceFolder}";
62
62
  const CURSOR_METADATA_DIR = `${WORKSPACE}/${DEFAULT_DIR.replace(/^\.\//, "")}`;
63
+ const argsOf = (l) => l.dir === void 0 ? l.args : [...l.args, l.dir];
63
64
  const CLIENTS = {
64
65
  claude: {
65
66
  file: ".mcp.json",
@@ -67,7 +68,7 @@ const CLIENTS = {
67
68
  container: "mcpServers",
68
69
  entry: (l) => ({
69
70
  command: l.command,
70
- args: l.args
71
+ args: argsOf(l)
71
72
  })
72
73
  },
73
74
  codex: {
@@ -76,20 +77,20 @@ const CLIENTS = {
76
77
  container: "mcp_servers",
77
78
  entry: (l) => ({
78
79
  command: l.command,
79
- args: l.args
80
+ args: argsOf(l)
80
81
  })
81
82
  },
82
83
  cursor: {
83
84
  file: ".cursor/mcp.json",
84
85
  format: "json",
85
86
  container: "mcpServers",
86
- entry: ({ command, args: [bin, ...rest] }) => ({
87
+ entry: ({ command, args: [bin, ...rest], dir }) => ({
87
88
  type: "stdio",
88
89
  command,
89
90
  args: [
90
91
  `${WORKSPACE}/${bin}`,
91
92
  ...rest,
92
- CURSOR_METADATA_DIR
93
+ dir === void 0 ? CURSOR_METADATA_DIR : `${WORKSPACE}/${dir}`
93
94
  ]
94
95
  })
95
96
  },
@@ -100,7 +101,7 @@ const CLIENTS = {
100
101
  entry: (l) => ({
101
102
  type: "stdio",
102
103
  command: l.command,
103
- args: l.args,
104
+ args: argsOf(l),
104
105
  cwd: WORKSPACE
105
106
  })
106
107
  }
@@ -616,14 +617,20 @@ async function classifyFile(path, expected) {
616
617
  }
617
618
  // src/init/plan.ts
618
619
  /**
619
- * Повний план `init`: лише читає диск. Пакет шукається вгору від кореня тим
620
- * самим механізмом, що й `$schema` (спека designer §4.2); його відсутність —
621
- * `UsageError` з назвою пакета.
620
+ * Повний план `init`: лише читає диск. Пакет шукається вгору від теки
621
+ * метаданих тим самим механізмом, що й `$schema` (спека designer §4.2): корінь
622
+ * агента може лежати над проєктом, чий `node_modules` до нього не видно. Його
623
+ * відсутність — `UsageError` з назвою пакета. Тека метаданих іде в запис MCP
624
+ * відносно кореня, коли вона не типова для нього.
622
625
  */
623
- async function planInit(root, agents, platform) {
624
- const pkgDir = installedPackageDir(root, DESIGNER_PACKAGE);
626
+ async function planInit(root, metadataDir, agents, platform) {
627
+ const pkgDir = installedPackageDir(metadataDir, DESIGNER_PACKAGE);
625
628
  const skills = await planSkillLinks(root, pkgDir, platform);
626
- const configs = await planMcpConfigs(root, agents, await mcpLaunch(root, pkgDir), platform);
629
+ const dir = posixRelative(root, metadataDir) || ".";
630
+ const configs = await planMcpConfigs(root, agents, {
631
+ ...await mcpLaunch(root, pkgDir),
632
+ ...dir === posixRelative(root, resolve(root, "./metadata")) ? {} : { dir }
633
+ }, platform);
627
634
  return {
628
635
  actions: [...skills.actions, ...configs.actions],
629
636
  notes: [...skills.notes, ...configs.notes],
@@ -705,6 +712,15 @@ async function writeAtomic(path, content) {
705
712
  }
706
713
  // src/commands/init.ts
707
714
  const initArgs = {
715
+ dir: {
716
+ type: "positional",
717
+ description: `Metadata directory (default: ${DEFAULT_DIR}); the package is looked up from it`,
718
+ required: false
719
+ },
720
+ root: {
721
+ type: "string",
722
+ description: "Directory the agent starts in, where the skill links and MCP configs are written (default: the current directory)"
723
+ },
708
724
  agents: {
709
725
  type: "string",
710
726
  description: `Comma-separated agents to write MCP configs for: ${AGENTS.join(", ")} (default: ${DEFAULT_AGENTS.join(",")})`
@@ -720,6 +736,8 @@ const initArgs = {
720
736
  };
721
737
  const KNOWN_KEYS = /* @__PURE__ */ new Set([
722
738
  "_",
739
+ "dir",
740
+ "root",
723
741
  "agents",
724
742
  "dry-run",
725
743
  "dryRun",
@@ -745,11 +763,15 @@ var init_default = defineCommand({
745
763
  * поганий аргумент, а не відсутній пакет.
746
764
  */
747
765
  async function runInit(args, cwd, platform = process.platform) {
748
- const root = resolve(cwd);
749
- const rel = (path) => posixRelative(root, path);
766
+ const rel = (path) => posixRelative(resolve(cwd), path);
750
767
  try {
751
- const { agents, mode } = parseInitArgs(args);
752
- const plan = await planInit(root, agents, platform);
768
+ const { agents, mode, dir, root: rootArg } = parseInitArgs(args);
769
+ const root = resolve(cwd, rootArg);
770
+ if (!await isDirectory(root)) throw new UsageError(`--root ${rootArg} is not a directory`);
771
+ if (dir !== void 0 && !await isDirectory(resolve(cwd, dir))) throw new UsageError(`metadata directory ${dir} is not a directory`);
772
+ const metadataDir = resolve(cwd, dir ?? "./metadata");
773
+ if (isAbsolute(relative(root, metadataDir))) throw new UsageError(`metadata directory ${dir ?? "./metadata"} is on another drive than the root ${rootArg}; keep them on one drive`);
774
+ const plan = await planInit(root, metadataDir, agents, platform);
753
775
  if (plan.refusals.length > 0) return refused(plan, rel);
754
776
  const lines = plan.actions.map(renderAction(rel));
755
777
  const notes = plan.notes.map(renderNote(rel));
@@ -775,16 +797,20 @@ async function runInit(args, cwd, platform = process.platform) {
775
797
  throw e;
776
798
  }
777
799
  }
800
+ const isDirectory = (path) => stat(path).then((s) => s.isDirectory(), () => false);
778
801
  function parseInitArgs(args) {
779
802
  for (const key of Object.keys(args)) if (!KNOWN_KEYS.has(key)) throw new UsageError(`unknown option --${key}`);
780
803
  const positional = Array.isArray(args._) ? args._ : [];
781
- if (positional.length > 0) throw new UsageError(`unexpected argument "${String(positional[0])}": init takes no positional arguments`);
804
+ if (positional.length > 1) throw new UsageError(`unexpected argument "${String(positional[1])}": init takes one metadata directory`);
805
+ if (args.root !== void 0 && typeof args.root !== "string") throw new UsageError("--root needs a directory");
782
806
  const check = args.check === true;
783
807
  const dryRun = args["dry-run"] === true;
784
808
  if (check && dryRun) throw new UsageError("--check and --dry-run cannot be combined");
785
809
  return {
786
810
  agents: args.agents === void 0 ? DEFAULT_AGENTS : agentList(args.agents),
787
- mode: check ? "check" : dryRun ? "dry-run" : "init"
811
+ mode: check ? "check" : dryRun ? "dry-run" : "init",
812
+ dir: positional.length === 0 ? void 0 : String(positional[0]),
813
+ root: args.root ?? "."
788
814
  };
789
815
  }
790
816
  function agentList(value) {
@@ -4,7 +4,7 @@ import { a as dataWriteHint, c as noDatabaseHint, d as installedPackageDir, f as
4
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, 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";
7
+ import { ATTRIBUTE_CASES, CENTRIFUGO_CHANNEL_MAX, CommandFailure, DATABASE_PROVIDERS, FUNCTIONS_FILE_SUFFIX, PLATFORM_LOGIN_ROLES, PLATFORM_ROLES, PLATFORM_SCHEMA, PROVIDER_API_ROLES, PROVIDER_IDENTITY_SOURCES, PROVIDER_LOGIN_ROLES, PROVIDER_OWNER_ROLES, PROVIDER_SCHEMAS, SIGNAL_MERGE_THRESHOLD, SIGNAL_NOTIFY_CHANNEL, SIGNAL_OUTBOX, SQL_DEBT_FILE, UUID_TEXT, batchSchema, logicalTypeOf, metadataKindSchema, objectNameSchema, quoteIdent, readQuerySchema } from "simetra/model";
8
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
10
  import { agentWriteRefusal, createAgentCore, createCommandRuntime, fromPgPool, readRoleOf, toJson } from "simetra/server";
@@ -1617,7 +1617,75 @@ function summarizeData(name, data) {
1617
1617
  if ("error" in data) return `${name}: ${data.error.code}${data.error.reason === void 0 ? "" : `: ${data.error.reason}`}`;
1618
1618
  const count = (n, what) => `${n} ${what}${n === 1 ? "" : "s"}`;
1619
1619
  if ("count" in data) return `${name}: ${data.capped === true ? "over " : ""}${count(data.count, "row")} counted`;
1620
- return "rows" in data ? `${name}: ${count(data.rows.length, "row")}` : `${name}: ${count(data.result.changes.length, "change")}`;
1620
+ if ("rows" in data) return `${name}: ${count(data.rows.length, "row")}`;
1621
+ const created = data.result.changes.filter((c) => c.operation === "create").map((c) => `created ${c.object.kind} ${c.object.name} ${c.id}`);
1622
+ return [`${name}: ${count(data.result.changes.length, "change")}`, ...created].join("\n");
1623
+ }
1624
+ /**
1625
+ * `id` для `create` без нього (спека designer §3.2): ключ рядка — UUID, і викликач не
1626
+ * мусить його вигадувати. Корінь виду скоупу лишається без `id`: його генерує
1627
+ * T3 і відмовляє на переданий; невідомий об'єкт відхилить T3.
1628
+ */
1629
+ function withCreateIds(catalog, batch, newId = () => crypto.randomUUID()) {
1630
+ return batch.map((op) => {
1631
+ if (op.action !== "create" || op.id !== void 0) return op;
1632
+ const object = catalog.objects.find((o) => o.kind === op.object.kind && o.name === op.object.name);
1633
+ if (object === void 0 || object.operations?.create?.root !== void 0) return op;
1634
+ return {
1635
+ ...op,
1636
+ id: newId()
1637
+ };
1638
+ });
1639
+ }
1640
+ /**
1641
+ * Скоуп для `create` скоупленого об'єкта без нього (спека designer §3.2): єдиний скоуп
1642
+ * цього виду, де користувач — учасник; інакше вибір неоднозначний, і
1643
+ * designer відмовляє діагностикою, а не підставляє навмання. Скоупи
1644
+ * читаються лише тоді, коли хоч одній операції скоупу бракує.
1645
+ */
1646
+ async function withCreateScopes(model, catalog, batch, myScopes) {
1647
+ let scopes;
1648
+ const operations = [];
1649
+ for (const [index, op] of batch.entries()) {
1650
+ const object = op.action === "create" ? catalog.objects.find((o) => o.kind === op.object.kind && o.name === op.object.name) : void 0;
1651
+ const attribute = object?.attributes.find((a) => a.column === object.scopeColumn);
1652
+ if (op.action !== "create" || object?.scopeKindId === void 0 || attribute?.insert !== true || Object.hasOwn(op.values ?? {}, attribute.name)) {
1653
+ operations.push(op);
1654
+ continue;
1655
+ }
1656
+ scopes ??= await myScopes();
1657
+ const mine = [...new Set(scopes.filter((s) => s.scopeKind === object.scopeKindId).map((s) => s.scope))];
1658
+ if (mine.length !== 1) {
1659
+ const kind = model.scopeKinds.find((k) => k.id === object.scopeKindId);
1660
+ return { diagnostic: diagnostic("data.scope-unspecified", "", `/operations/${index}/values`, {
1661
+ object: `${op.object.kind} ${op.object.name}`,
1662
+ scopeKind: kind?.name ?? object.scopeKindId,
1663
+ attribute: attribute.name,
1664
+ scopes: mine.length
1665
+ }) };
1666
+ }
1667
+ operations.push({
1668
+ ...op,
1669
+ values: {
1670
+ ...op.values,
1671
+ [attribute.name]: mine[0]
1672
+ }
1673
+ });
1674
+ }
1675
+ return { operations };
1676
+ }
1677
+ /**
1678
+ * Скоупи користувача сесії зі знімка прав (`members`). Проєкт без функцій
1679
+ * прав знімка не має (`command.invalid`) — тоді скоупів немає, і рішення
1680
+ * лишається за діагностикою, а не за помилкою рантайму.
1681
+ */
1682
+ async function membersOf(runtime, session) {
1683
+ try {
1684
+ return (await runtime.rightsSnapshot(session)).snapshot.members;
1685
+ } catch (error) {
1686
+ if (error instanceof CommandFailure && error.error.code === "command.invalid") return [];
1687
+ throw error;
1688
+ }
1621
1689
  }
1622
1690
  const SQLSTATE = /^[0-9A-Z]{5}$/;
1623
1691
  /**
@@ -1727,7 +1795,7 @@ const dataReadTool = defineTool({
1727
1795
  });
1728
1796
  const dataCommandTool = defineTool({
1729
1797
  name: "data-command",
1730
- description: "Change application data of the development database as the user given by --as, with that user's rights: a batch of create, update, markDeletion and delete operations in one transaction (update, markDeletion and delete need expectedVersion). A tabular section array in update replaces the section: every existing row must be in the array or in deleteIds. Rights catalogs and create of a scope root whose creator gets a role need --allow-rights-write; objects with a module are refused, and for such a root also when its membership catalog has one. BigInt values may be passed as decimal strings. Each result row has the shape of a read card: the tabular sections the operation wrote come under tabularSections. A runtime error comes as data.error with a code.",
1798
+ description: "Change application data of the development database as the user given by --as, with that user's rights: a batch of create, update, markDeletion and delete operations in one transaction (update, markDeletion and delete need expectedVersion). A create without id gets a fresh one; without its scope it takes the user's only scope of that kind. A tabular section array in update replaces the section: every existing row must be in the array or in deleteIds. Rights catalogs and create of a scope root whose creator gets a role need --allow-rights-write; objects with a module are refused, and for such a root also when its membership catalog has one. BigInt values may be passed as decimal strings. Each result row has the shape of a read card: the tabular sections the operation wrote come under tabularSections. A runtime error comes as data.error with a code.",
1731
1799
  input: z.strictObject({ operations: batchSchema }),
1732
1800
  files: "read",
1733
1801
  database: "none",
@@ -1739,8 +1807,9 @@ const dataCommandTool = defineTool({
1739
1807
  const { model } = compiled;
1740
1808
  const warnings = warningsFor(model, compiled.diagnostics, input.operations.map((op) => op.object));
1741
1809
  const catalog = buildRuntimeCatalog(model);
1810
+ const operations = withCreateIds(catalog, input.operations);
1742
1811
  const rightsWrite = ctx.allowRightsWrite === true;
1743
- const refusal = dataPolicyRefusal(model, catalog, input.operations, { rightsWrite });
1812
+ const refusal = dataPolicyRefusal(model, catalog, operations, { rightsWrite });
1744
1813
  if (refusal?.kind === "command") return {
1745
1814
  ok: false,
1746
1815
  changes: [],
@@ -1753,12 +1822,20 @@ const dataCommandTool = defineTool({
1753
1822
  diagnostics: [],
1754
1823
  refusalReason: "rights-write-disabled"
1755
1824
  };
1756
- return onRuntime("data-command", ctx, model, warnings, async (rt, session) => {
1825
+ const ran = await onRuntime("data-command", ctx, model, warnings, async (rt, session) => {
1826
+ const scoped = await withCreateScopes(model, catalog, operations, () => membersOf(rt, session));
1827
+ if ("diagnostic" in scoped) return scoped;
1757
1828
  return { result: await createAgentCore({
1758
1829
  runtime: rt,
1759
1830
  permissions: { rightsWrite }
1760
- }).execute(session, input.operations) };
1831
+ }).execute(session, scoped.operations) };
1761
1832
  });
1833
+ if (ran.data !== void 0 && "diagnostic" in ran.data) return {
1834
+ ok: false,
1835
+ changes: [],
1836
+ diagnostics: [...warnings, ran.data.diagnostic]
1837
+ };
1838
+ return ran;
1762
1839
  },
1763
1840
  present: {
1764
1841
  structure: (data) => toJson(data),
@@ -2052,6 +2129,60 @@ const rightsMaintenanceTool = defineTool({
2052
2129
  });
2053
2130
  // src/tools/roles-tool.ts
2054
2131
  const PROJECT_FILE$1 = "project.meta.json";
2132
+ const [AUTH_ROLE] = PROVIDER_LOGIN_ROLES.postgres;
2133
+ if (AUTH_ROLE === void 0) throw new Error("the postgres profile data has no auth login role");
2134
+ /**
2135
+ * Змінні середовища з паролями розробника ролей входу профілю `postgres`
2136
+ * (спека профілю §3.4): імена ролей — з даних T0, змінні — ті самі, що в
2137
+ * стеку розробки (`login-secrets.env`).
2138
+ */
2139
+ const DEV_PASSWORD_VARIABLES = [
2140
+ {
2141
+ role: PROVIDER_OWNER_ROLES.postgres,
2142
+ variable: "SIMETRA_OWNER_DEV_PASSWORD"
2143
+ },
2144
+ {
2145
+ role: AUTH_ROLE,
2146
+ variable: "SIMETRA_AUTH_DEV_PASSWORD"
2147
+ },
2148
+ {
2149
+ role: PLATFORM_LOGIN_ROLES.runtime,
2150
+ variable: "SIMETRA_RUNTIME_DEV_PASSWORD"
2151
+ },
2152
+ {
2153
+ role: PLATFORM_LOGIN_ROLES.signals,
2154
+ variable: "SIMETRA_SIGNALS_DEV_PASSWORD"
2155
+ }
2156
+ ];
2157
+ /**
2158
+ * Паролі розробника за роллю або відмови до будь-якого з'єднання: хост, який
2159
+ * візьме `pg` (`?host=`, `PGHOST` теж), — лише ця машина, бо відомий пароль
2160
+ * на спільному сервері відкрив би його; кожна змінна задана й не порожня.
2161
+ * Значення в діагностики не потрапляють — лише імена змінних і хост.
2162
+ */
2163
+ function devPasswordsFrom(env, url) {
2164
+ const diagnostics = [];
2165
+ let host;
2166
+ try {
2167
+ host = new pg.Client({ connectionString: url }).host;
2168
+ } catch {
2169
+ host = void 0;
2170
+ }
2171
+ if (!isLocalHost(host)) diagnostics.push(diagnostic("roles.dev-passwords-remote", "", "", { host: host === void 0 || host === "" ? "(none)" : host }));
2172
+ const passwords = /* @__PURE__ */ new Map();
2173
+ for (const { role, variable } of DEV_PASSWORD_VARIABLES) {
2174
+ const value = env[variable];
2175
+ if (value === void 0 || value === "") diagnostics.push(diagnostic("roles.dev-password-missing", "", "", { variable }));
2176
+ else passwords.set(role, value);
2177
+ }
2178
+ return diagnostics.length > 0 ? {
2179
+ ok: false,
2180
+ diagnostics
2181
+ } : {
2182
+ ok: true,
2183
+ passwords
2184
+ };
2185
+ }
2055
2186
  /**
2056
2187
  * Набір ролей теки проєкту (спека П4 §6.2): провайдер — з файлу проєкту, тим самим
2057
2188
  * читачем, що й `compile`. Без файлу ролі входу пропускаються явно — пропуск
@@ -2112,7 +2243,12 @@ function clusterRoles(value) {
2112
2243
  * ціль і шаблон; окремий сервер тіней там не підтримано.
2113
2244
  * Решта провайдерів і проєкт без файлу — ролі на цілі й на сервері тіні.
2114
2245
  */
2115
- async function runRoles(dbs, db, project) {
2246
+ async function runRoles(dbs, db, project, options = {}) {
2247
+ if (options.devPasswords !== void 0 && project.provider !== "postgres") return {
2248
+ roles: [],
2249
+ skipped: [],
2250
+ diagnostics: [diagnostic("roles.dev-passwords-unsupported", "", "", project.provider === void 0 ? {} : { provider: project.provider })]
2251
+ };
2116
2252
  if (project.provider === "postgres") {
2117
2253
  if (db.shadowBase !== void 0) return {
2118
2254
  roles: [],
@@ -2129,13 +2265,19 @@ async function runRoles(dbs, db, project) {
2129
2265
  error: "the database address names no database"
2130
2266
  })]
2131
2267
  };
2268
+ const dev = options.devPasswords === void 0 ? void 0 : devPasswordsFrom(options.devPasswords, db.target.url);
2269
+ if (dev?.ok === false) return {
2270
+ roles: [],
2271
+ skipped: [],
2272
+ diagnostics: dev.diagnostics
2273
+ };
2132
2274
  const set = postgresClusterSet(database);
2133
2275
  const { withDatabaseName } = await import("@supabase/pg-delta");
2134
2276
  const result = await ensurePostgresCluster(dbs, {
2135
2277
  maintenance: { url: withDatabaseName(db.target.url, "postgres") },
2136
2278
  target: db.target,
2137
2279
  template: { url: withDatabaseName(db.target.url, set.template) }
2138
- }, set);
2280
+ }, set, dev === void 0 ? {} : { passwords: dev.passwords });
2139
2281
  if (!result.ok) return {
2140
2282
  roles: [],
2141
2283
  skipped: [],
@@ -2147,7 +2289,8 @@ async function runRoles(dbs, db, project) {
2147
2289
  name,
2148
2290
  reason: "identity-table-missing"
2149
2291
  })),
2150
- diagnostics: []
2292
+ diagnostics: [],
2293
+ ...dev === void 0 ? {} : { passwords: DEV_PASSWORD_VARIABLES.filter((v) => result.value.passwords?.includes(v.role)) }
2151
2294
  };
2152
2295
  }
2153
2296
  const ran = await ensurePlatformRoles(dbs, [{
@@ -2171,13 +2314,13 @@ async function runRoles(dbs, db, project) {
2171
2314
  */
2172
2315
  const rolesTool = defineTool({
2173
2316
  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({}),
2317
+ description: "Create the platform roles: NOLOGIN roles that generated SQL grants to on the target and the shadow server, and the login roles (the runtime and the signals consumer) on the target only, each a member of its parents WITH INHERIT FALSE, SET TRUE; the signals login role also gets a role setting (ALTER ROLE … SET) that makes its consumer group the role of every new session. Reads `database.provider` from the project file; without it the login roles are skipped, and the output says so. An existing role is only checked, its role setting included; the one change is a missing membership of an existing login role in a parent of its profile, added WITH INHERIT FALSE, SET TRUE and named in the output. Needs CREATEROLE, and ADMIN OPTION on every parent role of a login role (without it that login role alone is refused, a missing membership with the GRANT statement to run); refuses before creating anything when a server lacks CREATEROLE or a role has an unsafe shape. With the provider `postgres` it prepares the cluster instead, as a superuser (a superuser URL of the target database): the owner, auth, grant and request roles, the target database owned by the owner, the schemas `extensions` and `better_auth`, `plpgsql_check`, and the sealed template for shadows. It refuses before writing when the session is not a superuser, a database or role has an unsafe shape, a Simetra login role can connect to another database, or the server lacks plpgsql_check; a separate shadow server is not supported there. devPasswords (postgres, local database only) sets the password of each login role it creates from SIMETRA_{OWNER,AUTH,RUNTIME,SIGNALS}_DEV_PASSWORD.",
2318
+ input: z.strictObject({ devPasswords: z.boolean().optional() }),
2176
2319
  files: "read",
2177
2320
  database: "write",
2178
2321
  data: "none",
2179
2322
  destructive: false,
2180
- async run({ dir, database }) {
2323
+ async run({ dir, database, env }, input) {
2181
2324
  const set = await projectRoleSet(dir);
2182
2325
  if (!set.ok) return {
2183
2326
  ok: false,
@@ -2185,7 +2328,7 @@ const rolesTool = defineTool({
2185
2328
  diagnostics: set.diagnostics
2186
2329
  };
2187
2330
  const { createApplyDatabase } = await import("./schema-engine-8rVHcVYO.js");
2188
- const ran = await withDatabase(required$1(database), "roles", (db) => runRoles(createApplyDatabase({ readOnly: false }), db, set));
2331
+ const ran = await withDatabase(required$1(database), "roles", (db) => runRoles(createApplyDatabase({ readOnly: false }), db, set, input.devPasswords === true ? { devPasswords: env ?? {} } : {}));
2189
2332
  if (!ran.ok) return {
2190
2333
  ok: false,
2191
2334
  changes: [],
@@ -2193,7 +2336,8 @@ const rolesTool = defineTool({
2193
2336
  };
2194
2337
  const data = {
2195
2338
  roles: ran.value.roles,
2196
- skipped: [...set.skipped, ...ran.value.skipped]
2339
+ skipped: [...set.skipped, ...ran.value.skipped],
2340
+ ...ran.value.passwords === void 0 ? {} : { passwords: ran.value.passwords }
2197
2341
  };
2198
2342
  return {
2199
2343
  ok: ran.value.diagnostics.length === 0,
@@ -2209,6 +2353,7 @@ const rolesTool = defineTool({
2209
2353
  const at = x.name.lastIndexOf(":");
2210
2354
  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
2355
  }),
2356
+ ...(data.passwords ?? []).map((x) => `target: ${x.role} password set from ${x.variable}`),
2212
2357
  ...v.diagnostics.length > 0 ? [v.report] : []
2213
2358
  ].join("\n") }
2214
2359
  });
@@ -2625,6 +2770,7 @@ async function invoke(tool, input, o) {
2625
2770
  dir: o.dir,
2626
2771
  root,
2627
2772
  ...tool.database === "none" ? {} : { database: o.database },
2773
+ ...tool.database === "none" || o.env === void 0 ? {} : { env: o.env },
2628
2774
  ...tool.data === "none" ? {} : { data: o.data },
2629
2775
  ...tool.data === "write" ? { allowRightsWrite: o.allowRightsWrite === true } : {},
2630
2776
  ...o.baseline === void 0 ? {} : { baseline: o.baseline }
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as version } from "./package-hA0J8AMK.js";
2
+ import { t as version } from "./package-mib3h81L.js";
3
3
  import { n as TOOL_NAMES } from "./types-CMcZhIci.js";
4
4
  import { defineCommand, runCommand, runMain, showUsage } from "citty";
5
5
  // src/main.ts
@@ -10,9 +10,9 @@ const main = defineCommand({
10
10
  description: "Simetra metadata tooling"
11
11
  },
12
12
  subCommands: {
13
- ...Object.fromEntries(TOOL_NAMES.map((name) => [name, () => import("./command-CHk1P9Dp.js").then((m) => m.commandByName(name))])),
14
- mcp: () => import("./mcp-jLOz0W7f.js").then((m) => m.default),
15
- init: () => import("./init-jr0Xsrpp.js").then((m) => m.default)
13
+ ...Object.fromEntries(TOOL_NAMES.map((name) => [name, () => import("./command-BfioPN5J.js").then((m) => m.commandByName(name))])),
14
+ mcp: () => import("./mcp-CdKzqojk.js").then((m) => m.default),
15
+ init: () => import("./init-BS7fCOls.js").then((m) => m.default)
16
16
  }
17
17
  });
18
18
  const rawArgs = process.argv.slice(2);
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { d as parseDataLaunch, f as databaseResource, i as structureOf, l as checkEnvName, n as TOOLS, o as formatDiagnostics, r as presentation, t as invoke, u as dataResource } from "./invoke-BwP_5iN6.js";
2
+ import { d as parseDataLaunch, f as databaseResource, i as structureOf, l as checkEnvName, n as TOOLS, o as formatDiagnostics, r as presentation, t as invoke, u as dataResource } from "./invoke-Dkbpi4Fq.js";
3
3
  import { a as dataWriteHint, l as readOnlyHint, n as trimSlash, o as databaseWriteHint, p as UsageError, r as ALLOW_RIGHTS_WRITE_FLAG } from "./default-dir-DerxTbci.js";
4
- import { t as version } from "./package-hA0J8AMK.js";
4
+ import { t as version } from "./package-mib3h81L.js";
5
5
  import { t as mcpArgs } from "./mcp-args-D63akJ97.js";
6
6
  import { defineCommand } from "citty";
7
7
  import { z } from "zod";
@@ -130,7 +130,8 @@ function registerCatalog(server, o) {
130
130
  ...o.databaseEnv === void 0 ? {} : { databaseEnv: o.databaseEnv },
131
131
  ...o.data === void 0 ? {} : { data: o.data },
132
132
  ...o.dataEnv === void 0 ? {} : { dataEnv: o.dataEnv },
133
- launchArgs: o.launchArgs
133
+ launchArgs: o.launchArgs,
134
+ ...o.env === void 0 ? {} : { env: o.env }
134
135
  });
135
136
  return toResponse(tool, result, o, dry === true);
136
137
  });
@@ -194,7 +195,8 @@ function mcpOptionsFrom(args, env, argv) {
194
195
  databaseEnv,
195
196
  ...data === void 0 ? {} : { data },
196
197
  ...launch === void 0 ? {} : { dataEnv: launch.urlEnv },
197
- launchArgs: argv
198
+ launchArgs: argv,
199
+ env
198
200
  };
199
201
  }
200
202
  var mcp_default = defineCommand({
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // package.json
3
- var version = "0.3.0-next.1";
3
+ var version = "0.3.0-next.3";
4
4
  export { version as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simetrajs/designer",
3
- "version": "0.3.0-next.1",
3
+ "version": "0.3.0-next.3",
4
4
  "description": "Simetra developer tools: command line and MCP server over the metadata compiler",
5
5
  "keywords": [
6
6
  "simetra",
@@ -37,7 +37,7 @@
37
37
  "pg-connection-string": "2.14.1",
38
38
  "smol-toml": "1.9.1",
39
39
  "zod": "^4.6.7",
40
- "simetra": "0.3.0-next.1"
40
+ "simetra": "0.3.0-next.3"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@arethetypeswrong/cli": "0.18.5",
@@ -57,6 +57,7 @@
57
57
  "publishConfig": {
58
58
  "access": "public"
59
59
  },
60
+ "gitHead": "02c584e117fd4495e4b75baa9872bb8ac54e3af0",
60
61
  "scripts": {
61
62
  "build": "tsc --noEmit",
62
63
  "build:package": "tsdown",
@@ -323,6 +323,9 @@ system rights catalogs and tenant creation: a scope root whose creator gets a
323
323
  }
324
324
  ```
325
325
 
326
+ A new scope kind comes with its root and membership catalog in one `add`
327
+ (`objects`): `references/people-and-rights.md`.
328
+
326
329
  The PG schema `simetra` (identities, the current user, provisioning) belongs
327
330
  to the platform and is reserved (`schema.reserved`); in SQL the current user is
328
331
  `(select simetra.current_user_id())`. Both rules in full: the same reference.
@@ -156,8 +156,12 @@ Read a card with the rows its references point to:
156
156
  }
157
157
  ```
158
158
 
159
- Seed rows in one transaction (`id` is a new UUID you generate; `update`,
160
- `markDeletion` and `delete` also need `expectedVersion`):
159
+ Seed rows in one transaction (`update`, `markDeletion` and `delete` also
160
+ need `expectedVersion`). A `create` without `id` gets a fresh UUID, and the
161
+ CLI text output prints `created <kind> <name> <id>` for every new row. A
162
+ `create` of a scoped object without its scope value takes the only scope of
163
+ that kind the `--as` user is a member of; with none or several the batch is
164
+ refused with `data.scope-unspecified` — pass the scope in `values` then:
161
165
 
162
166
  ```json simetra:data-command
163
167
  {
@@ -165,7 +169,6 @@ Seed rows in one transaction (`id` is a new UUID you generate; `update`,
165
169
  {
166
170
  "action": "create",
167
171
  "object": { "kind": "Catalog", "name": "Currency" },
168
- "id": "0b9d4c5e-8f1a-4c3b-9e2d-6a7f8b9c0d1e",
169
172
  "values": { "description": "US dollar", "symbol": "$" }
170
173
  }
171
174
  ]
@@ -52,6 +52,38 @@ People are platform data, not tables you write yourself:
52
52
  its scope set function from that catalog. Use it instead of a hand-written
53
53
  member table and set function. One membership catalog per scope kind.
54
54
 
55
+ A scope kind needs its root (scoped by the kind itself) and, with
56
+ `"setFunction": "membership"`, a membership catalog; none of the three compiles
57
+ alone, so `add` creates them in one change with `objects`. Every existing
58
+ object that takes a scope must already declare one (`"scope": "none"` or a
59
+ kind), or the first kind fails with `scope.declaration-missing`:
60
+
61
+ ```json simetra:add
62
+ {
63
+ "target": { "kind": "Project" },
64
+ "collection": "scopeKinds",
65
+ "element": {
66
+ "name": "org",
67
+ "root": { "object": { "kind": "Catalog", "name": "Organization" } },
68
+ "setFunction": "membership"
69
+ },
70
+ "objects": [
71
+ { "kind": "Catalog", "name": "Organization", "data": { "scope": "org" } },
72
+ {
73
+ "kind": "Catalog",
74
+ "name": "OrgMember",
75
+ "data": {
76
+ "scope": "org",
77
+ "membership": { "user": "user" },
78
+ "attributes": [
79
+ { "name": "user", "type": "Ref", "ref": { "kind": "Catalog", "name": "Users" } }
80
+ ]
81
+ }
82
+ }
83
+ ]
84
+ }
85
+ ```
86
+
55
87
  The platform layer (identities, the current user, provisioning) lives in the
56
88
  PG schema `simetra`, generated when a users catalog exists, or when the
57
89
  project has a membership source and its provider's user id is the `sub` claim
@@ -633,6 +665,34 @@ the scope kind in `project.meta.json`) says that no role reads any object of
633
665
  that scope kind, so nobody will see their rows: grant `read` to a role or
634
666
  declare one with `fullAccess`.
635
667
 
668
+ **Open self sign-up.** `"selfSignUp": true` in `project.meta.json` declares
669
+ that anyone may register, so whatever every signed-in user sees is open to
670
+ anyone. The warning `project.self-sign-up` then lists the objects with
671
+ `publicRead` `authenticated` and the grants of `everyUser` roles. List what you
672
+ open on purpose in `selfSignUpAccepted`, and the warning names only the rest;
673
+ a new object, action or wider form warns again:
674
+
675
+ ```json
676
+ "selfSignUpAccepted": {
677
+ "objects": [{ "object": { "kind": "Catalog", "name": "Country" } }],
678
+ "grants": [
679
+ {
680
+ "role": { "kind": "Role", "name": "ClientOwner" },
681
+ "object": { "kind": "Catalog", "name": "Client" },
682
+ "actions": ["read", "update"],
683
+ "extent": "own"
684
+ }
685
+ ]
686
+ }
687
+ ```
688
+
689
+ `"published": true` on an object entry accepts only the published rows of the
690
+ conditional `publicRead`. The names are references: `rename` rewrites them, and
691
+ `delete` of an accepted object, role, custom action or dimension is refused
692
+ until the entry is removed. An entry that matches nothing open any more warns
693
+ with `project.self-sign-up-stale`: remove it, and accept the openness again
694
+ when it comes back.
695
+
636
696
  ## Who writes what
637
697
 
638
698
  Kind tables are written **only by commands**: the write policies grant the
@@ -689,7 +749,8 @@ on the target only (`LOGIN NOINHERIT`, a member of `simetra_command` and, for
689
749
  `supabase`, of `authenticated` and `anon`, each `WITH INHERIT FALSE, SET TRUE`). It reads
690
750
  `database.provider` from the project file; without a project file it skips the
691
751
  login role, and the output says why. The operator sets the login role's
692
- password; the platform keeps no secrets.
752
+ password; the platform keeps no secrets (the one exception, a database on your
753
+ machine, is `--dev-passwords` below).
693
754
 
694
755
  The login role needs `ADMIN OPTION` on each of its parent roles in the role
695
756
  that runs `roles`. Without it `roles` still creates the grant roles, but
@@ -710,6 +771,19 @@ the profile, the application database owned by `simetra_owner`,
710
771
  `simetra_template` that shadows and proof copies are built from. Running it
711
772
  again converges the declared state and creates nothing.
712
773
 
774
+ For a database on your machine, `simetra roles --dev-passwords` (MCP input
775
+ `devPasswords: true`) also sets the password of each login role this run
776
+ creates (`simetra_owner`, `simetra_auth`, `simetra_runtime`,
777
+ `simetra_signals`) from `SIMETRA_OWNER_DEV_PASSWORD`,
778
+ `SIMETRA_AUTH_DEV_PASSWORD`, `SIMETRA_RUNTIME_DEV_PASSWORD` and
779
+ `SIMETRA_SIGNALS_DEV_PASSWORD` in the environment. A role that already exists
780
+ keeps its password. It refuses before anything is written when a variable is
781
+ missing or empty (`roles.dev-password-missing`), when the database host is not
782
+ this machine — `localhost`, `127.0.0.0/8`, `::1` or a unix socket
783
+ (`roles.dev-passwords-remote`), or when the provider is not `postgres`
784
+ (`roles.dev-passwords-unsupported`). On any other server set the passwords
785
+ yourself.
786
+
713
787
  The identity provider's own roles get their grants here too: the role of the
714
788
  platform owner receives `USAGE` on the `better_auth` schema and `TRIGGER` and
715
789
  `REFERENCES` on `better_auth."user"`, so the provision triggers and the foreign
@@ -737,6 +811,12 @@ otherwise:
737
811
  restore it by hand around a new `roles` run (the template is only dropped).
738
812
  - `roles.shared-cluster` — a Simetra login role has an explicit `CONNECT` on
739
813
  other databases; one cluster serves one application.
814
+ - `roles.extension-unavailable` — the server does not offer `plpgsql_check`
815
+ in `pg_available_extensions`; install the extension's package on the
816
+ database server (`postgresql-<major>-plpgsql-check` from PGDG) and run
817
+ `roles` again. `apply` refuses the same way with
818
+ `apply.extension-unavailable` before it locks any table when its plan checks
819
+ function bodies with the extension and the server no longer offers it.
740
820
  - `plan.owner-not-bypassrls` — the role of `plan`, `apply` or `rehearse` has
741
821
  neither `BYPASSRLS` nor superuser; run `ALTER ROLE <role> BYPASSRLS` as a
742
822
  superuser.
@@ -5,8 +5,18 @@ package skills into `.agents/skills/` and `.claude/skills/` and writes the MCP
5
5
  server entry for the chosen agents. Run it from the project root — the
6
6
  directory the agent starts in, where `metadata/` lives.
7
7
 
8
+ When the agent starts in another directory (a monorepo root above the app),
9
+ name it with `--root`, or run `init` from there with the metadata directory as
10
+ the argument. The package is looked up from the metadata directory; the links
11
+ and configs go into the root, and the MCP entry names the metadata directory
12
+ relative to the root. A directory an own entry already names is kept. A
13
+ named metadata directory must exist, and on Windows it must be on the same
14
+ drive as the root.
15
+
8
16
  ```sh
9
17
  pnpm exec simetra init
18
+ pnpm exec simetra init --root ..
19
+ pnpm exec simetra init apps/app/metadata
10
20
  pnpm exec simetra init --agents claude,codex,cursor,vscode
11
21
  pnpm exec simetra init --dry-run
12
22
  pnpm exec simetra init --check --agents claude,codex
@@ -15,7 +25,7 @@ pnpm exec simetra init --check --agents claude,codex
15
25
  - Without `--agents` only Claude Code's `.mcp.json` is written. The skill
16
26
  links are made in both skill directories for every agent.
17
27
  - The links and configs belong in git. In CI run `init --check` with the same
18
- `--agents`: it exits 1 when a link or an MCP entry is missing or stale, and
28
+ `--agents`, `--root` and metadata directory: it exits 1 when a link or an MCP entry is missing or stale, and
19
29
  changes nothing.
20
30
  - `init` never overwrites what it does not own: a skill directory with the
21
31
  same name, or a `simetra` MCP entry with another command, is left alone and