@akal/supaforge 0.0.37 → 0.0.38

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.
@@ -6,31 +6,25 @@ import {
6
6
  formatSkips,
7
7
  renderDetailed,
8
8
  renderSummary
9
- } from "./chunk-MRXIE55Y.js";
9
+ } from "./chunk-LJY3AK2P.js";
10
10
  import {
11
11
  createDefaultRegistry,
12
+ proveBeforeApply,
12
13
  scan,
13
14
  summarizeByKind
14
- } from "./chunk-CAQ3QQFP.js";
15
- import {
16
- comparedSchemas,
17
- copyStructure,
18
- dropDatabase,
19
- proofScope,
20
- proveConvergence,
21
- psqlBeside,
22
- residualHeldBack,
23
- withDatabase
24
- } from "./chunk-GGZ7YWBZ.js";
15
+ } from "./chunk-PE5PENCB.js";
25
16
  import {
26
17
  CHECK_META,
27
18
  CHECK_NAMES,
19
+ copyStructure,
28
20
  describeTableFilter,
21
+ dropDatabase,
29
22
  isFiltered,
30
- planWork,
31
23
  promote,
32
- resolveTableFilter
33
- } from "./chunk-YUJ2MHLM.js";
24
+ psqlBeside,
25
+ resolveTableFilter,
26
+ withDatabase
27
+ } from "./chunk-2HJPUDPP.js";
34
28
  import {
35
29
  isCommentOnly,
36
30
  splitSqlStatements
@@ -68,7 +62,6 @@ import {
68
62
  errMsg,
69
63
  ok,
70
64
  redactUrls,
71
- schemaDiffIgnores,
72
65
  warn
73
66
  } from "./chunk-SQ52YBKK.js";
74
67
 
@@ -519,66 +512,56 @@ ${warn(`${result.errors.length} error(s):`)}`);
519
512
  const targetEnv = config.environments[config.target];
520
513
  const dryRun = flags["dry-run"];
521
514
  if (flags.prove && !dryRun) {
522
- const sourceEnv = config.environments[config.source];
523
- const planned = planWork(scanResult, {
524
- checks,
525
- only: parseFlagList(flags.only),
526
- allowDestructive: flags["allow-destructive"],
527
- tableFilter,
528
- applyPosture: flags["apply-posture"]
529
- });
530
- const { replay, unproved } = proofScope(planned.sqlStatements);
531
- const migrationSql = replay.map((s) => s.sql).join("\n");
532
515
  this.log(`
533
516
  ${dim("Proving convergence on a throwaway clone\u2026")}`);
534
- if (unproved.length > 0) {
535
- const byCheck = [...new Set(unproved.map((s) => s.check))].map((c) => `${c} \xD7${unproved.filter((s) => s.check === c).length}`).join(", ");
536
- this.log(` ${dim(`Not proved \u2014 act outside the proved schemas or on the whole server: ${byCheck}`)}`);
537
- }
538
- const proof = replay.length === 0 ? { converged: false, residual: [], cloneName: "", skipped: "none of the planned fixes is one the proof can replay" } : await proveConvergence({
539
- sourceUrl: sourceEnv.dbUrl,
517
+ const proof = await proveBeforeApply({
518
+ scanResult,
519
+ plan: {
520
+ checks,
521
+ only: parseFlagList(flags.only),
522
+ allowDestructive: flags["allow-destructive"],
523
+ tableFilter,
524
+ applyPosture: flags["apply-posture"]
525
+ },
526
+ sourceUrl: config.environments[config.source].dbUrl,
540
527
  targetUrl: targetEnv.dbUrl,
541
- migrationSql,
542
- fixes: replay,
543
- // Every schema the schema diff compares, not `public` alone: a
544
- // migration dropping a schema the source lacks runs against it.
545
- schemas: await comparedSchemas(
546
- sourceEnv.dbUrl,
547
- targetEnv.dbUrl,
548
- schemaDiffIgnores(config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS)
549
- ),
550
- // The checks this run compares: without the schema check, what the
551
- // target already lacks elsewhere is not this migration's to fix.
552
- checks: scanResult.checks.map((c) => c.check)
528
+ ignoreSchemas: config.ignoreSchemas
553
529
  });
554
- const heldBack = [...heldBackSql(scanResult, planned), ...(proof.notApplied ?? []).map((n) => n.sql)];
555
- if (proof.notApplied?.length) {
530
+ if (proof.unproved.length > 0) {
531
+ const byCheck = [...new Set(proof.unproved.map((s) => s.check))].map((c) => `${c} \xD7${proof.unproved.filter((s) => s.check === c).length}`).join(", ");
532
+ this.log(` ${dim(`Not proved \u2014 act outside the proved schemas or on the whole server: ${byCheck}`)}`);
533
+ }
534
+ if (proof.notApplied.length > 0) {
556
535
  this.log(` ${dim(`Left out, as the apply will leave them \u2014 this server can't hold them: ${proof.notApplied.map((n) => n.issueId).join(", ")}`)}`);
557
536
  }
558
- if (proof.skipped && replay.length === 0) {
559
- this.log(` ${dim(`Nothing to prove: ${proof.skipped}.`)}
537
+ switch (proof.verdict) {
538
+ case "nothing-to-prove":
539
+ this.log(` ${dim(`Nothing to prove: ${proof.reason}.`)}
560
540
  `);
561
- } else if (proof.skipped) {
562
- this.refuseUnproven(`Not proven: ${proof.skipped}`, [], flags.json);
563
- } else if (!proof.converged && residualHeldBack(proof.residual, heldBack).unexplained.length === 0) {
564
- this.log(` ${ok("Converged")}, apart from what is held back and stays on the target:`);
565
- for (const line of proof.residual.slice(0, 15)) this.log(` ${dim(line)}`);
566
- this.log("");
567
- } else if (!proof.converged) {
568
- const { unexplained } = residualHeldBack(proof.residual, heldBack);
569
- this.refuseUnproven("Migration does not reproduce the source.", unexplained, flags.json);
570
- } else {
571
- if (proof.outOfScope?.length) {
572
- this.log(` ${ok("Converged")} on what this run compares. Outside it, and already different before:`);
573
- for (const line of proof.outOfScope.slice(0, 15)) this.log(` ${dim(line)}`);
574
- if (proof.outOfScope.length > 15) this.log(` ${dim(`\u2026and ${proof.outOfScope.length - 15} more`)}`);
541
+ break;
542
+ case "not-proven":
543
+ this.refuseUnproven(`Not proven: ${proof.reason}`, [], flags.json);
544
+ break;
545
+ case "diverged":
546
+ this.refuseUnproven("Migration does not reproduce the source.", proof.residual, flags.json);
547
+ break;
548
+ case "converged-apart-from-held-back":
549
+ this.log(` ${ok("Converged")}, apart from what is held back and stays on the target:`);
550
+ for (const line of proof.residual.slice(0, 15)) this.log(` ${dim(line)}`);
575
551
  this.log("");
576
- } else {
577
- this.log(` ${ok("Converged")} \u2014 the migration reproduces the source exactly.
552
+ break;
553
+ case "converged":
554
+ if (proof.outOfScope.length > 0) {
555
+ this.log(` ${ok("Converged")} on what this run compares. Outside it, and already different before:`);
556
+ for (const line of proof.outOfScope.slice(0, 15)) this.log(` ${dim(line)}`);
557
+ if (proof.outOfScope.length > 15) this.log(` ${dim(`\u2026and ${proof.outOfScope.length - 15} more`)}`);
558
+ this.log("");
559
+ } else {
560
+ this.log(` ${ok("Converged")} \u2014 the migration reproduces the source exactly.
578
561
  `);
579
- }
562
+ }
580
563
  }
581
- if (proof.data && !proof.skipped) {
564
+ if (proof.data) {
582
565
  const { sampled, unchecked: unchecked2, rewritten } = proof.data;
583
566
  if (sampled.length > 0) this.log(` ${ok("Rows kept")} in the ${sampled.length} table(s) sampled.`);
584
567
  if (rewritten.length > 0) {
@@ -759,10 +742,6 @@ ${warn(`${result.errors.length} error(s):`)}`);
759
742
  this.error("Diff aborted \u2014 fix the issues above first.", { exit: 1 });
760
743
  }
761
744
  };
762
- function heldBackSql(scanResult, planned) {
763
- const skipped = new Set(planned.skipped.map((s) => s.issueId));
764
- return scanResult.checks.flatMap((c) => c.issues).filter((i) => skipped.has(i.id) && i.sql?.up).map((i) => i.sql.up);
765
- }
766
745
  function stripError(c) {
767
746
  return {
768
747
  label: c.label,
@@ -777,4 +756,4 @@ export {
777
756
  inertApplyFlags,
778
757
  Diff
779
758
  };
780
- //# sourceMappingURL=chunk-M2564IGT.js.map
759
+ //# sourceMappingURL=chunk-35TXJGDQ.js.map
@@ -0,0 +1,27 @@
1
+ import {
2
+ comparedSchemas,
3
+ fingerprint
4
+ } from "./chunk-2HJPUDPP.js";
5
+
6
+ // src/written-against.ts
7
+ import { createHash } from "crypto";
8
+ var WRITTEN_AGAINST = "-- supaforge:written-against";
9
+ async function targetFingerprint(dbUrl, ignoreSchemas) {
10
+ const schemas = await comparedSchemas(dbUrl, dbUrl, ignoreSchemas);
11
+ return createHash("sha256").update(await fingerprint(dbUrl, schemas)).digest("hex").slice(0, 16);
12
+ }
13
+ function writtenAgainstLine(env, digest) {
14
+ return `${WRITTEN_AGAINST} ${env} ${digest}`;
15
+ }
16
+ function writtenAgainst(sql) {
17
+ const line = sql.split("\n").find((l) => l.startsWith(WRITTEN_AGAINST + " "));
18
+ const [env, digest] = line?.slice(WRITTEN_AGAINST.length + 1).trim().split(/\s+/) ?? [];
19
+ return env && digest ? { env, digest } : void 0;
20
+ }
21
+
22
+ export {
23
+ targetFingerprint,
24
+ writtenAgainstLine,
25
+ writtenAgainst
26
+ };
27
+ //# sourceMappingURL=chunk-5RMEQPPU.js.map
@@ -1,14 +1,16 @@
1
1
  import {
2
- backup
3
- } from "./chunk-EWNZIRCD.js";
2
+ migrationsDir,
3
+ writeMigrationFile
4
+ } from "./chunk-EHJWKKFL.js";
4
5
  import {
5
6
  createDefaultRegistry,
7
+ proveBeforeApply,
6
8
  scan
7
- } from "./chunk-CAQ3QQFP.js";
9
+ } from "./chunk-PE5PENCB.js";
8
10
  import {
9
11
  CHECK_NAMES,
10
12
  promote
11
- } from "./chunk-YUJ2MHLM.js";
13
+ } from "./chunk-2HJPUDPP.js";
12
14
  import {
13
15
  captureSnapshot,
14
16
  unrestorableSchema
@@ -85,118 +87,165 @@ function createServer(cwd = process.cwd(), options = {}) {
85
87
  return resolve(configPath, "..");
86
88
  };
87
89
  const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION });
90
+ const configPathArg = z.string().optional().describe(
91
+ "Absolute path to supaforge.config.json. Rejected unless the server was started with --allow-config-path; otherwise the config in the server's own working directory is used."
92
+ );
93
+ const comparisonArgs = {
94
+ configPath: configPathArg,
95
+ source: z.string().optional().describe("Source environment name; list_environments shows them. Defaults to the config's source."),
96
+ target: z.string().optional().describe("Target environment name. Defaults to the config's target."),
97
+ checks: z.array(z.enum(CHECK_NAMES)).optional().describe('Compare only these checks (e.g. ["schema", "rls"]).'),
98
+ skip: z.array(z.enum(CHECK_NAMES)).optional().describe("Leave these checks out, as the CLI --skip flag does. Added to checks.exclude from the config."),
99
+ only: z.array(z.string()).optional().describe('Fix only these findings, by id from diff (globs allowed, e.g. "rls-*").'),
100
+ allowDestructive: z.boolean().optional().default(false).describe("Include fixes that drop tables or columns. Off by default: they are reported but held back.")
101
+ };
102
+ const loadComparison = async (args) => {
103
+ const effectiveCwd = resolveCwd(args.configPath);
104
+ const raw = JSON.parse(await readFile(resolve(effectiveCwd, "supaforge.config.json"), "utf-8"));
105
+ const config = resolveConfig({
106
+ ...raw,
107
+ ...args.source ? { source: args.source } : {},
108
+ ...args.target ? { target: args.target } : {}
109
+ });
110
+ const errors = validateConfig(config);
111
+ if (errors.length > 0) return { error: `Config errors:
112
+ ${errors.join("\n")}` };
113
+ const unreachable = [];
114
+ for (const [label, name] of [["Source", config.source], ["Target", config.target]]) {
115
+ const conn = await checkConnection(config.environments[name].dbUrl);
116
+ if (!conn.reachable) unreachable.push(`${label} (${name}) not reachable: ${redactUrls(describeFailure(conn.error))}`);
117
+ }
118
+ if (unreachable.length > 0) return { error: `Nothing compared.
119
+ ${unreachable.join("\n")}` };
120
+ return { config, cwd: effectiveCwd };
121
+ };
122
+ const textResult = (body, isError = false) => ({
123
+ content: [{ type: "text", text: typeof body === "string" ? body : JSON.stringify(body, null, 2) }],
124
+ ...isError ? { isError: true } : {}
125
+ });
126
+ const failure = (err) => textResult(`Error: ${err instanceof Error ? err.message : String(err)}`, true);
127
+ const uncheckedOf = (scanResult) => scanResult.checks.filter((c) => c.status === "error").map((c) => ({ check: c.check, error: c.error ?? "check failed" }));
88
128
  server.registerTool(
89
- "scan_drift",
129
+ "list_environments",
90
130
  {
91
- // Reads both databases and writes nothing. Without annotations a client
92
- // could not tell this from apply_fixes, so it could not ask for
93
- // confirmation on the one that writes (issue #96).
94
131
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
95
- description: "Scan for drift between Supabase environments and return a structured report. Results include per-check status, issues with SQL fixes, and a health score.",
96
- inputSchema: {
97
- configPath: z.string().optional().describe(
98
- "Absolute path to supaforge.config.json. Rejected unless the server was started with --allow-config-path; otherwise the config in the server's own working directory is used."
99
- ),
100
- source: z.string().optional().describe("Source environment name (overrides config default)."),
101
- target: z.string().optional().describe("Target environment name (overrides config default)."),
102
- checks: z.array(z.enum(CHECK_NAMES)).optional().describe('Limit scan to specific checks (e.g. ["rls", "rls-coverage"]).'),
103
- skip: z.array(z.enum(CHECK_NAMES)).optional().describe(
104
- "Skip specific checks, the equivalent of the CLI --skip flag. Unioned with checks.exclude from the config file. Use this to avoid a slow or failing layer without editing the project config."
105
- )
106
- }
132
+ description: "List the environments in supaforge.config.json, and which are the default source and target. Says whether each has the Supabase project details the API-based checks need; never returns credentials.",
133
+ inputSchema: { configPath: configPathArg }
107
134
  },
108
- async ({ configPath, source, target, checks, skip }) => {
135
+ async ({ configPath }) => {
109
136
  try {
110
- const effectiveCwd = resolveCwd(configPath);
111
- const raw = JSON.parse(await readFile(resolve(effectiveCwd, "supaforge.config.json"), "utf-8"));
112
- const config = resolveConfig({
113
- ...raw,
114
- ...source ? { source } : {},
115
- ...target ? { target } : {}
137
+ const raw = JSON.parse(await readFile(resolve(resolveCwd(configPath), "supaforge.config.json"), "utf-8"));
138
+ const config = resolveConfig(raw);
139
+ return textResult({
140
+ source: config.source ?? null,
141
+ target: config.target ?? null,
142
+ environments: Object.entries(config.environments).map(([name, env]) => ({
143
+ name,
144
+ database: Boolean(env.dbUrl),
145
+ supabaseProject: Boolean(env.projectRef),
146
+ accessToken: Boolean(env.accessToken)
147
+ }))
116
148
  });
117
- const errors = validateConfig(config);
118
- if (errors.length > 0) {
119
- return { content: [{ type: "text", text: `Config errors:
120
- ${errors.join("\n")}` }], isError: true };
121
- }
122
- const registry = createDefaultRegistry();
123
- const result = await scan(registry, {
149
+ } catch (err) {
150
+ return failure(err);
151
+ }
152
+ }
153
+ );
154
+ server.registerTool(
155
+ "diff",
156
+ {
157
+ // Reads both databases and writes nothing, so a client can let it run
158
+ // without asking. sync is the one that writes.
159
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
160
+ description: "Compare two Supabase environments and report every difference: schema, RLS, roles and grants, auth, storage, Edge Functions, cron and more. Returns the findings with their SQL, a drift score, and the plan: the statements sync would run, in order, and what it would hold back and why. Writes nothing. Show the plan to the user before calling sync.",
161
+ inputSchema: comparisonArgs
162
+ },
163
+ async ({ configPath, source, target, checks, skip, only, allowDestructive }) => {
164
+ try {
165
+ const loaded = await loadComparison({ configPath, source, target });
166
+ if ("error" in loaded) return textResult(loaded.error, true);
167
+ const { config } = loaded;
168
+ const scanResult = await scan(createDefaultRegistry(), {
124
169
  config,
125
170
  checks,
126
171
  skip
127
172
  });
128
- setLastScanResult(result);
129
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
173
+ setLastScanResult(scanResult);
174
+ const preview = await promote({
175
+ dbUrl: config.environments[config.target].dbUrl,
176
+ sourceUrl: config.environments[config.source].dbUrl,
177
+ scanResult,
178
+ checks,
179
+ only,
180
+ allowDestructive,
181
+ dryRun: true
182
+ });
183
+ const unchecked = uncheckedOf(scanResult);
184
+ return textResult({
185
+ ...scanResult,
186
+ plan: {
187
+ statements: preview.applied,
188
+ heldBack: preview.skipped,
189
+ ...preview.warnings?.length ? { warnings: preview.warnings } : {}
190
+ },
191
+ ...unchecked.length ? { unchecked } : {}
192
+ });
130
193
  } catch (err) {
131
- const msg = err instanceof Error ? err.message : String(err);
132
- return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
194
+ return failure(err);
133
195
  }
134
196
  }
135
197
  );
136
198
  server.registerTool(
137
- "apply_fixes",
199
+ "sync",
138
200
  {
139
- // Writes to the target database, and destructively when
140
- // allowDestructive is set. This is the one a client should confirm.
201
+ // Writes to the target database. This is the one a client should confirm.
141
202
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
142
- description: "Apply SQL fixes to resolve drift detected by scan_drift. Previews by default \u2014 pass dryRun=false to actually write to the target database.",
203
+ description: "Make the target environment match the source by running the plan diff shows. WRITES TO THE TARGET DATABASE: call diff first, show the user the plan, and call this only once they agree, with the same arguments. SQL fixes run in one transaction and roll back together if any fails. prove=true first rehearses the plan on a throwaway copy of the target and refuses to write if the result would not match the source.",
143
204
  inputSchema: {
144
- configPath: z.string().optional().describe(
145
- "Absolute path to supaforge.config.json. Rejected unless the server was started with --allow-config-path; otherwise the config in the server's own working directory is used."
146
- ),
147
- source: z.string().optional().describe("Source environment name."),
148
- target: z.string().optional().describe("Target environment name."),
149
- checks: z.array(z.enum(CHECK_NAMES)).optional().describe("Apply fixes only for specific checks."),
150
- dryRun: z.boolean().optional().default(true).describe(
151
- "Preview SQL without executing it. Defaults to true: writing is opt-in here as it is everywhere else in supaforge, where it needs --apply. Pass dryRun=false to actually apply the fixes."
205
+ ...comparisonArgs,
206
+ prove: z.boolean().optional().default(false).describe(
207
+ "Rehearse on a throwaway copy of the target first, and write nothing unless the copy ends up matching the source. Needs permission to create a database on the target's server."
152
208
  )
153
209
  }
154
210
  },
155
- async ({ configPath, source, target, checks, dryRun }) => {
211
+ async ({ configPath, source, target, checks, skip, only, allowDestructive, prove }) => {
156
212
  try {
157
- const effectiveCwd = resolveCwd(configPath);
158
- const raw = JSON.parse(await readFile(resolve(effectiveCwd, "supaforge.config.json"), "utf-8"));
159
- const config = resolveConfig({
160
- ...raw,
161
- ...source ? { source } : {},
162
- ...target ? { target } : {}
163
- });
164
- const errors = validateConfig(config);
165
- if (errors.length > 0) {
166
- return { content: [{ type: "text", text: `Config errors:
167
- ${errors.join("\n")}` }], isError: true };
168
- }
169
- const unreachable = [];
170
- for (const [label, name] of [["Source", config.source], ["Target", config.target]]) {
171
- const conn = await checkConnection(config.environments[name].dbUrl);
172
- if (!conn.reachable) unreachable.push(`${label} (${name}) not reachable: ${redactUrls(describeFailure(conn.error))}`);
173
- }
174
- if (unreachable.length > 0) {
175
- return { content: [{ type: "text", text: `Nothing compared or applied.
176
- ${unreachable.join("\n")}` }], isError: true };
177
- }
178
- const registry = createDefaultRegistry();
179
- const scanResult = await scan(registry, {
213
+ const loaded = await loadComparison({ configPath, source, target });
214
+ if ("error" in loaded) return textResult(loaded.error, true);
215
+ const { config } = loaded;
216
+ const sourceUrl = config.environments[config.source].dbUrl;
217
+ const targetUrl = config.environments[config.target].dbUrl;
218
+ const scanResult = await scan(createDefaultRegistry(), {
180
219
  config,
181
- checks
220
+ checks,
221
+ skip
182
222
  });
183
223
  setLastScanResult(scanResult);
184
- const targetEnv = config.environments[config.target];
185
- const promoteResult = await promote({
186
- dbUrl: targetEnv.dbUrl,
224
+ const proof = prove ? await proveBeforeApply({
225
+ scanResult,
226
+ plan: { checks, only, allowDestructive },
227
+ sourceUrl,
228
+ targetUrl,
229
+ ignoreSchemas: config.ignoreSchemas
230
+ }) : void 0;
231
+ if (proof && !proof.proceed) {
232
+ return textResult({ written: false, proof, applied: [], skipped: [], errors: [] }, true);
233
+ }
234
+ const result = await promote({
235
+ dbUrl: targetUrl,
236
+ sourceUrl,
187
237
  scanResult,
188
238
  checks,
189
- dryRun
239
+ only,
240
+ allowDestructive
190
241
  });
191
- const unchecked = scanResult.checks.filter((c) => c.status === "error").map((c) => ({ check: c.check, error: c.error ?? "check failed" }));
192
- const body = unchecked.length ? { ...promoteResult, unchecked } : promoteResult;
193
- return {
194
- content: [{ type: "text", text: JSON.stringify(body, null, 2) }],
195
- ...unchecked.length || promoteResult.errors.length ? { isError: true } : {}
196
- };
242
+ const unchecked = uncheckedOf(scanResult);
243
+ return textResult(
244
+ { ...result, ...proof ? { proof } : {}, ...unchecked.length ? { unchecked } : {} },
245
+ unchecked.length > 0 || result.errors.length > 0
246
+ );
197
247
  } catch (err) {
198
- const msg = err instanceof Error ? err.message : String(err);
199
- return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
248
+ return failure(err);
200
249
  }
201
250
  }
202
251
  );
@@ -252,57 +301,34 @@ ${unreachable.join("\n")}` }], isError: true };
252
301
  server.registerTool(
253
302
  "create_migration",
254
303
  {
255
- // Local files only, as with take_snapshot.
304
+ // Reads both databases and writes one local file; no database changes.
256
305
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
257
- description: "Capture a snapshot and generate a migration file containing the diff against the previous snapshot. Migration files are stored under .supaforge/migrations/.",
306
+ description: "Write the schema difference between source and target as a migration file, as `supaforge migrate create` does: the SQL that brings the target to the source, the grants on what it creates (so it works where new tables are not granted by default), and a DOWN to revert it. Written to the configured migrations directory (supabase/migrations by default). Changes no database.",
258
307
  inputSchema: {
259
- configPath: z.string().optional().describe(
260
- "Absolute path to supaforge.config.json. Rejected unless the server was started with --allow-config-path; otherwise the config in the server's own working directory is used."
261
- ),
262
- environment: z.string().optional().describe("Environment to snapshot (defaults to config source)."),
263
- description: z.string().optional().describe('Human-readable description for the migration (e.g. "add-rls-to-orders").')
308
+ configPath: configPathArg,
309
+ source: comparisonArgs.source,
310
+ target: comparisonArgs.target,
311
+ name: z.string().min(1).describe('Name for the migration, used in the file name (e.g. "add_rls_to_orders").')
264
312
  }
265
313
  },
266
- async ({ configPath, environment, description }) => {
314
+ async ({ configPath, source, target, name }) => {
267
315
  try {
268
- const effectiveCwd = resolveCwd(configPath);
269
- const raw = JSON.parse(await readFile(resolve(effectiveCwd, "supaforge.config.json"), "utf-8"));
270
- const config = resolveConfig(raw);
271
- const envName = environment ?? config.source ?? Object.keys(config.environments)[0];
272
- const env = config.environments[envName];
273
- if (!env) {
274
- return {
275
- content: [{ type: "text", text: `Environment "${envName}" not found in config.` }],
276
- isError: true
277
- };
278
- }
279
- const result = await backup({
280
- envName,
281
- env,
316
+ const loaded = await loadComparison({ configPath, source, target });
317
+ if ("error" in loaded) return textResult(loaded.error, true);
318
+ const { config, cwd: effectiveCwd } = loaded;
319
+ const { filePath, destructive } = await writeMigrationFile({
282
320
  config,
283
- cwd: effectiveCwd,
284
- description
321
+ name,
322
+ dir: migrationsDir(config, effectiveCwd)
323
+ });
324
+ if (!filePath) return textResult({ written: false, reason: "No schema drift between source and target." });
325
+ return textResult({
326
+ written: true,
327
+ migrationFile: filePath,
328
+ ...destructive.length > 0 ? { destructive, warning: "These statements drop or delete data. migrate run applies them only with --allow-destructive." } : {}
285
329
  });
286
- return {
287
- content: [
288
- {
289
- type: "text",
290
- text: JSON.stringify(
291
- {
292
- isBaseline: result.isBaseline,
293
- migrationFile: result.migrationFile,
294
- snapshotDir: result.snapshot.dir,
295
- timestamp: result.snapshot.timestamp
296
- },
297
- null,
298
- 2
299
- )
300
- }
301
- ]
302
- };
303
330
  } catch (err) {
304
- const msg = err instanceof Error ? err.message : String(err);
305
- return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
331
+ return failure(err);
306
332
  }
307
333
  }
308
334
  );
@@ -311,7 +337,7 @@ ${unreachable.join("\n")}` }], isError: true };
311
337
  {
312
338
  // Reads the last scan held in memory.
313
339
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
314
- description: "Retrieve the result for a specific check from the most recent scan_drift call. Returns issues, status, and duration for the named check.",
340
+ description: "Retrieve the result for one check from the most recent diff or sync call. Returns issues, status, and duration for the named check.",
315
341
  inputSchema: {
316
342
  check: z.enum(CHECK_NAMES).describe('The check name to retrieve (e.g. "rls-coverage").')
317
343
  }
@@ -320,7 +346,7 @@ ${unreachable.join("\n")}` }], isError: true };
320
346
  const result = getLastScanResult();
321
347
  if (!result) {
322
348
  return {
323
- content: [{ type: "text", text: "No scan result available. Run scan_drift first." }],
349
+ content: [{ type: "text", text: "No scan result available. Run diff first." }],
324
350
  isError: true
325
351
  };
326
352
  }
@@ -372,7 +398,7 @@ ${unreachable.join("\n")}` }], isError: true };
372
398
  contents: [
373
399
  {
374
400
  uri: uri.href,
375
- text: JSON.stringify({ message: "No scan result yet. Run scan_drift first." }),
401
+ text: JSON.stringify({ message: "No scan result yet. Run diff first." }),
376
402
  mimeType: "application/json"
377
403
  }
378
404
  ]
@@ -391,14 +417,14 @@ ${unreachable.join("\n")}` }], isError: true };
391
417
  },
392
418
  async (uri) => {
393
419
  try {
394
- const migrationsDir = join(cwd, ".supaforge", "migrations");
395
- const files = await readdir(migrationsDir).catch(() => []);
420
+ const migrationsDir2 = join(cwd, ".supaforge", "migrations");
421
+ const files = await readdir(migrationsDir2).catch(() => []);
396
422
  const jsonFiles = files.filter((f) => f.endsWith(".json")).sort();
397
423
  return {
398
424
  contents: [
399
425
  {
400
426
  uri: uri.href,
401
- text: JSON.stringify({ directory: migrationsDir, files: jsonFiles }, null, 2),
427
+ text: JSON.stringify({ directory: migrationsDir2, files: jsonFiles }, null, 2),
402
428
  mimeType: "application/json"
403
429
  }
404
430
  ]
@@ -425,7 +451,7 @@ ${unreachable.join("\n")}` }], isError: true };
425
451
  Last scan result (${lastScan.timestamp}):
426
452
  - Score: ${lastScan.score}
427
453
  - Total issues: ${lastScan.summary.total} (${lastScan.summary.critical} critical, ${lastScan.summary.warning} warnings)
428
- - Checks: ${lastScan.checks.filter((c) => c.status === "drifted").map((c) => c.check).join(", ") || "none drifted"}` : "\n\nNo recent scan found \u2014 run scan_drift first for a current drift report.";
454
+ - Checks: ${lastScan.checks.filter((c) => c.status === "drifted").map((c) => c.check).join(", ") || "none drifted"}` : "\n\nNo recent scan found \u2014 run diff first for a current drift report.";
429
455
  return {
430
456
  messages: [
431
457
  {
@@ -437,10 +463,10 @@ Last scan result (${lastScan.timestamp}):
437
463
  scanContext,
438
464
  "",
439
465
  "Steps:",
440
- "1. Call scan_drift to get the latest drift report.",
466
+ "1. Call diff to get the latest drift report and the plan.",
441
467
  "2. Review critical issues (especially rls-coverage and rls checks).",
442
468
  "3. Confirm all SQL fixes look correct before applying.",
443
- "4. If safe, run apply_fixes with dryRun=true first, then dryRun=false."
469
+ "4. If safe, and the user agrees to the plan, run sync (prove=true to rehearse it first)."
444
470
  ].join("\n")
445
471
  }
446
472
  }
@@ -456,7 +482,7 @@ Last scan result (${lastScan.timestamp}):
456
482
  },
457
483
  () => {
458
484
  const lastScan = getLastScanResult();
459
- let criticalSummary = "No recent scan \u2014 run scan_drift first.";
485
+ let criticalSummary = "No recent scan \u2014 run diff first.";
460
486
  if (lastScan) {
461
487
  const criticalIssues = lastScan.checks.flatMap((c) => c.issues).filter((i) => i.severity === "critical");
462
488
  if (criticalIssues.length === 0) {
@@ -480,11 +506,11 @@ Last scan result (${lastScan.timestamp}):
480
506
  criticalSummary,
481
507
  "",
482
508
  "Recommended steps:",
483
- "1. Run scan_drift to confirm the current state.",
509
+ "1. Run diff to confirm the current state and see the plan.",
484
510
  "2. Review each critical issue and its sql.up fix.",
485
- "3. Run apply_fixes with dryRun=true to preview the SQL.",
486
- "4. Confirm the SQL is safe, then run apply_fixes with dryRun=false.",
487
- "5. Run scan_drift again to confirm all critical issues are resolved.",
511
+ "3. Check the plan diff returned: the SQL sync will run, in order.",
512
+ "4. Confirm with the user, then run sync with the same arguments (prove=true to rehearse it first).",
513
+ "5. Run diff again to confirm all critical issues are resolved.",
488
514
  "",
489
515
  "Pay special attention to rls-coverage issues \u2014 tables without RLS enabled",
490
516
  "are the CVE-2025-48757 vulnerability pattern."
@@ -504,4 +530,4 @@ export {
504
530
  clearLastScanResult,
505
531
  createServer
506
532
  };
507
- //# sourceMappingURL=chunk-MZPWRWBL.js.map
533
+ //# sourceMappingURL=chunk-64S3EP7Y.js.map