@akal/supaforge 0.0.0-stage → 0.0.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +350 -2
- package/bin/dev.js +10 -0
- package/bin/run.js +18 -0
- package/dist/base-command.d.ts +135 -0
- package/dist/base-command.js +9 -0
- package/dist/base-command.js.map +1 -0
- package/dist/branch-C4ndfoj5.d.ts +58 -0
- package/dist/chunk-2SELREHW.js +156 -0
- package/dist/chunk-2SELREHW.js.map +1 -0
- package/dist/chunk-3HGAV5CC.js +2073 -0
- package/dist/chunk-3HGAV5CC.js.map +1 -0
- package/dist/chunk-4IVN7QVY.js +632 -0
- package/dist/chunk-4IVN7QVY.js.map +1 -0
- package/dist/chunk-6LJERPUN.js +499 -0
- package/dist/chunk-6LJERPUN.js.map +1 -0
- package/dist/chunk-6Q7MHFBM.js +13 -0
- package/dist/chunk-6Q7MHFBM.js.map +1 -0
- package/dist/chunk-6WAMNZLO.js +336 -0
- package/dist/chunk-6WAMNZLO.js.map +1 -0
- package/dist/chunk-7NAZGZPV.js +868 -0
- package/dist/chunk-7NAZGZPV.js.map +1 -0
- package/dist/chunk-BLKJWDTL.js +153 -0
- package/dist/chunk-BLKJWDTL.js.map +1 -0
- package/dist/chunk-BUOWHE36.js +1311 -0
- package/dist/chunk-BUOWHE36.js.map +1 -0
- package/dist/chunk-DMIWAJRB.js +602 -0
- package/dist/chunk-DMIWAJRB.js.map +1 -0
- package/dist/chunk-DQQ5E563.js +64 -0
- package/dist/chunk-DQQ5E563.js.map +1 -0
- package/dist/chunk-G2DIPIYU.js +94 -0
- package/dist/chunk-G2DIPIYU.js.map +1 -0
- package/dist/chunk-GEHPTPNZ.js +240 -0
- package/dist/chunk-GEHPTPNZ.js.map +1 -0
- package/dist/chunk-GZREXCQZ.js +207 -0
- package/dist/chunk-GZREXCQZ.js.map +1 -0
- package/dist/chunk-MIRLB5JM.js +1292 -0
- package/dist/chunk-MIRLB5JM.js.map +1 -0
- package/dist/chunk-NTUASFQ3.js +248 -0
- package/dist/chunk-NTUASFQ3.js.map +1 -0
- package/dist/chunk-ORQJVE57.js +642 -0
- package/dist/chunk-ORQJVE57.js.map +1 -0
- package/dist/chunk-SC2XHGIS.js +122 -0
- package/dist/chunk-SC2XHGIS.js.map +1 -0
- package/dist/chunk-SQPCWGQO.js +657 -0
- package/dist/chunk-SQPCWGQO.js.map +1 -0
- package/dist/chunk-UWAVXC57.js +916 -0
- package/dist/chunk-UWAVXC57.js.map +1 -0
- package/dist/commands/clone.d.ts +66 -0
- package/dist/commands/clone.js +416 -0
- package/dist/commands/clone.js.map +1 -0
- package/dist/commands/diff.d.ts +81 -0
- package/dist/commands/diff.js +23 -0
- package/dist/commands/diff.js.map +1 -0
- package/dist/commands/help.d.ts +32 -0
- package/dist/commands/help.js +36 -0
- package/dist/commands/help.js.map +1 -0
- package/dist/commands/hukam.d.ts +13 -0
- package/dist/commands/hukam.js +28 -0
- package/dist/commands/hukam.js.map +1 -0
- package/dist/commands/init.d.ts +47 -0
- package/dist/commands/init.js +388 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/commands/mcp.d.ts +13 -0
- package/dist/commands/mcp.js +43 -0
- package/dist/commands/mcp.js.map +1 -0
- package/dist/commands/migrate/baseline.d.ts +24 -0
- package/dist/commands/migrate/baseline.js +69 -0
- package/dist/commands/migrate/baseline.js.map +1 -0
- package/dist/commands/migrate/create.d.ts +36 -0
- package/dist/commands/migrate/create.js +127 -0
- package/dist/commands/migrate/create.js.map +1 -0
- package/dist/commands/migrate/list.d.ts +23 -0
- package/dist/commands/migrate/list.js +110 -0
- package/dist/commands/migrate/list.js.map +1 -0
- package/dist/commands/migrate/run.d.ts +61 -0
- package/dist/commands/migrate/run.js +18 -0
- package/dist/commands/migrate/run.js.map +1 -0
- package/dist/commands/report.d.ts +27 -0
- package/dist/commands/report.js +210 -0
- package/dist/commands/report.js.map +1 -0
- package/dist/commands/restore.d.ts +26 -0
- package/dist/commands/restore.js +266 -0
- package/dist/commands/restore.js.map +1 -0
- package/dist/commands/snapshot.d.ts +33 -0
- package/dist/commands/snapshot.js +249 -0
- package/dist/commands/snapshot.js.map +1 -0
- package/dist/commands/sync.d.ts +16 -0
- package/dist/commands/sync.js +38 -0
- package/dist/commands/sync.js.map +1 -0
- package/dist/config-CTbeRlJk.d.ts +134 -0
- package/dist/help.d.ts +28 -0
- package/dist/help.js +64 -0
- package/dist/help.js.map +1 -0
- package/dist/index.d.ts +498 -0
- package/dist/index.js +147 -0
- package/dist/index.js.map +1 -0
- package/package.json +74 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/diff.ts","../src/ci.ts"],"sourcesContent":["import { Flags } from '@oclif/core'\nimport { BaseCommand } from '../base-command.js'\nimport { createDefaultRegistry } from '../checks/index.js'\nimport { scan } from '../scanner.js'\nimport type { ScanProgressEvent } from '../scanner.js'\nimport { renderSummary, renderDetailed, formatSkips } from '../render.js'\nimport { promote, planWork, type PromoteResult } from '../promote.js'\nimport type { CheckName, ScanResult } from '../types/drift.js'\nimport { CHECK_NAMES, CHECK_META } from '../types/drift.js'\nimport { ok, warn, dim, cmd, bold } from '../ui.js'\nimport { sanitizeForReport } from '../utils/sanitize.js'\nimport { renderTip } from '../tips.js'\nimport { formatGitHubAnnotations, computeCiExitCode, formatCiSummary, type FailOn } from '../ci.js'\nimport { resolveTableFilter, isFiltered, describeTableFilter } from '../utils/table-filter.js'\nimport { parseFlagList } from '../utils/strings.js'\nimport { isCloneDatabase, sourceLooksLikeCloneOf } from '../branch.js'\nimport { proveConvergence, residualHeldBack, proofScope, comparedSchemas } from '../prove.js'\nimport { summarizeByKind } from '../scoring.js'\nimport { CLONE_SKIP_FLAGS, DEFAULT_IGNORE_SCHEMAS, schemaDiffIgnores } from '../defaults.js'\nimport { Preflight } from '../preflight.js'\nimport type { SupaForgeConfig } from '../types/config.js'\nimport { redactUrls, describeFailure } from '../utils/error.js'\n\n/**\n * Glyph and text for a finished check, so the three outcomes are visually\n * distinct in the live progress list.\n */\nfunction describeCheckOutcome(\n status: 'clean' | 'drifted' | 'error' | 'skipped',\n issueCount: number,\n skipReason?: string,\n): { glyph: string; text: string } {\n if (status === 'error') return { glyph: warn('✗'), text: warn('error') }\n if (status === 'skipped') {\n return { glyph: dim('○'), text: dim(`skipped — ${skipReason ?? 'no reason given'}`) }\n }\n return { glyph: ok('✓'), text: `${issueCount} ${issueCount === 1 ? 'issue' : 'issues'}` }\n}\n\n/**\n * Flags that only mean something when fixes are being planned or executed.\n *\n * Passed on their own they used to be inert *and silent* — the run printed\n * byte-identical output to one with no flag at all. Worst for the two that read\n * as safety measures: someone reaching for `--prove` or `--dry-run` alone, the\n * natural instinct for \"don't actually do it\", got an ordinary diff and no sign\n * they had neither previewed nor proved anything (issue #71).\n *\n * `--dry-run` is deliberately absent: it now selects the planning path by\n * itself, so previewing never requires typing the flag that writes. Flags that\n * shape the *plan* rather than the execution are honoured under `--dry-run`, so\n * they are only inert when neither flag is present.\n */\nconst APPLY_ONLY_FLAGS: ReadonlyArray<{ flag: string; shapesThePlan: boolean }> = [\n { flag: 'prove', shapesThePlan: false },\n { flag: 'no-transaction', shapesThePlan: false },\n { flag: 'only', shapesThePlan: true },\n { flag: 'apply-posture', shapesThePlan: true },\n { flag: 'allow-destructive', shapesThePlan: true },\n]\n\n/** Which apply-only flags this invocation will silently ignore. */\nexport function inertApplyFlags(\n flags: Record<string, unknown>,\n): ReadonlyArray<{ flag: string; shapesThePlan: boolean }> {\n if (flags['apply']) return []\n const dryRun = Boolean(flags['dry-run'])\n\n return APPLY_ONLY_FLAGS.filter(({ flag, shapesThePlan }) => {\n const given = flags[flag]\n const passed = Array.isArray(given) ? given.length > 0 : Boolean(given)\n if (!passed) return false\n return !(dryRun && shapesThePlan)\n })\n}\n\n/**\n * Unified drift detection & resolution command.\n *\n * Default: summary of what's drifted (was: scan)\n * --detail: full SQL diffs (was: diff)\n * --apply: fix the drift (was: promote)\n * --ci: emit GitHub Actions annotations + structured exit codes\n */\nexport default class Diff extends BaseCommand {\n static override description = 'Detect drift between Supabase environments and optionally fix it'\n\n static override examples = [\n '<%= config.bin %> diff',\n '<%= config.bin %> diff --detail',\n '<%= config.bin %> diff --apply',\n '<%= config.bin %> diff --check=rls',\n '<%= config.bin %> diff --check=rls --apply',\n '<%= config.bin %> diff --source=staging --target=production',\n '<%= config.bin %> diff --skip=storage --skip=vault',\n '<%= config.bin %> diff --tables=orders,order_items',\n \"<%= config.bin %> diff --tables='billing_*' --exclude-tables='*_audit'\",\n '<%= config.bin %> diff --tables=orders --detail',\n // Built from the same constant the tips and the post-clone output use, so\n // the advice cannot fall behind the check list again: this example predated\n // Layer 14 and omitted `roles`, which on a real clone → remote diff is 227\n // of the findings someone following it was left to puzzle over (issue #70).\n `<%= config.bin %> diff ${CLONE_SKIP_FLAGS}`,\n '<%= config.bin %> diff --ci',\n '<%= config.bin %> diff --ci --fail-on=warning',\n ]\n\n /**\n * Read from the environment rather than passed as flags, because they tune\n * limits rather than select behaviour. Rendered as their own `--help`\n * section (issue #40); the README carries the same table plus the timeout\n * precedence chain.\n */\n static envVars = [\n { name: 'SUPAFORGE_CONNECT_TIMEOUT', description: 'Seconds before a database connection attempt is abandoned (default 15).' },\n { name: 'SUPAFORGE_DBDIFF_TIMEOUT', description: 'Seconds before the schema/data diff is abandoned. Overrides checks.schema.timeout (default 600).' },\n { name: 'SUPAFORGE_DBDIFF_MEMORY', description: \"PHP memory limit for @dbdiff/cli — 512M, 2G, or -1 for unlimited (default dbdiff's own 1G).\" },\n ]\n\n static override flags = {\n check: Flags.string({\n char: 'l',\n description: 'Limit to a specific check',\n options: [...CHECK_NAMES],\n }),\n skip: Flags.string({\n char: 'x',\n description: 'Skip a specific check (repeatable). Also configurable via checks.exclude in supaforge.config.json.',\n options: [...CHECK_NAMES],\n multiple: true,\n }),\n detail: Flags.boolean({\n description: 'Show detailed SQL diffs (default: summary)',\n default: false,\n }),\n apply: Flags.boolean({\n description: 'Apply SQL fixes to resolve drift in the target environment',\n default: false,\n }),\n 'allow-destructive': Flags.boolean({\n description: 'With --apply, also run fixes that drop tables or columns (destroys data)',\n default: false,\n }),\n 'dry-run': Flags.boolean({\n description: 'With --apply, print the fixes in the order they would run without executing any of them',\n default: false,\n }),\n 'no-transaction': Flags.boolean({\n description: 'With --apply, run each fix on its own instead of rolling the whole set back on the first failure',\n aliases: ['continue-on-error'],\n default: false,\n }),\n only: Flags.string({\n description: 'With --apply, only apply these issue ids (repeatable, comma-separated, globs allowed). Ids come from --json.',\n multiple: true,\n }),\n 'include-files': Flags.boolean({\n description: 'Include file-level drift detection in storage check',\n default: false,\n }),\n tables: Flags.string({\n description: 'Only compare these tables in the schema and data checks (repeatable, comma-separated, globs allowed). Overrides checks.tables.',\n multiple: true,\n }),\n 'exclude-tables': Flags.string({\n description: 'Never compare these tables (repeatable, comma-separated, globs allowed). Merged with checks.excludeTables.',\n multiple: true,\n }),\n json: Flags.boolean({ description: 'Output results as JSON' }),\n source: Flags.string({ char: 's', description: 'Source environment name' }),\n target: Flags.string({ char: 't', description: 'Target environment name' }),\n ci: Flags.boolean({\n description: 'CI mode: emit GitHub Actions annotations and use semantic exit codes (0=clean, 1=drift, 2=error)',\n default: false,\n }),\n prove: Flags.boolean({\n description:\n 'Before applying, replay the migration on a throwaway clone of the target '\n + 'and verify it reproduces the source exactly. Refuses to apply if it does not.',\n default: false,\n }),\n 'apply-posture': Flags.boolean({\n description:\n 'With --apply, also apply fixes from checks that judge the target on its own '\n + '(RLS coverage, migration history). Off by default: those fixes move the target '\n + 'away from the source and so create drift.',\n default: false,\n }),\n 'fail-on': Flags.string({\n description: 'Threshold for a non-zero exit in CI mode',\n options: ['critical', 'warning', 'any'],\n default: 'critical',\n }),\n 'fail-on-posture': Flags.boolean({\n description:\n 'Let findings from the target-only checks (RLS coverage, migration history) '\n + 'affect the exit code too. Off by default: they fire identically whichever '\n + 'pair you diff, so they cannot indicate that the environments have diverged.',\n default: false,\n }),\n }\n\n /**\n * Report what `--apply` did, or — under `--dry-run` — what it would do.\n *\n * The applied list is printed in execution order, which is now dependency\n * order rather than the order the checks reported the issues. That ordering\n * is the whole point of the dry run: it is what makes the outcome of a real\n * apply predictable before running it (issue #48).\n */\n private renderApplyResult(result: PromoteResult, dryRun: boolean): void {\n const verb = dryRun ? 'Would apply' : 'Applied'\n if (result.applied.length > 0) {\n const heading = `${verb} ${result.applied.length} fix(es)${dryRun ? ', in this order' : ''}:`\n this.log(dryRun ? bold(heading) : ok(heading))\n result.applied.forEach((stmt, i) => {\n const glyph = dryRun ? dim(`${i + 1}.`) : ok('✓')\n this.log(` ${glyph} ${dim(`[${stmt.check}]`)} ${stmt.issueId}`)\n // The SQL itself only in a dry run: it is the thing being reviewed,\n // and printing it after the fact would just repeat --detail.\n if (dryRun && stmt.sql) this.log(` ${dim(stmt.sql.replace(/\\s*\\n\\s*/g, ' '))}`)\n if (dryRun && stmt.action) this.log(` ${dim(stmt.action)}`)\n })\n }\n\n if (result.skipped.length > 0) {\n this.log(`\\n${dim(`Skipped ${result.skipped.length} issue(s):`)}`)\n // Collapsed where several share a reason: a posture check on a project\n // with 47 tables lacking RLS printed the same sentence 47 times, and\n // pushed the result of the apply off the top of the screen (issue #84).\n for (const line of formatSkips(result.skipped)) this.log(` ${dim(line)}`)\n }\n\n // Printed before the errors: the first thing to know about a failed apply\n // is whether anything landed, and the answer here is that nothing did.\n if (result.rolledBack?.length) {\n this.log(`\\n${warn(`Rolled back ${result.rolledBack.length} fix(es)`)} — the target is unchanged:`)\n for (const item of result.rolledBack) {\n this.log(` ${dim('↩')} ${dim(`[${item.check}]`)} ${item.issueId}`)\n }\n }\n\n if (result.errors.length > 0) {\n this.log(`\\n${warn(`${result.errors.length} error(s):`)}`)\n for (const item of result.errors) {\n this.log(` ${warn('✗')} ${dim(`[${item.check}]`)} ${item.issueId}: ${item.error}`)\n }\n if (result.rolledBack) {\n this.log(`\\n ${dim(`Nothing was written. Re-run with ${cmd('--no-transaction')} to apply the fixes that do work.`)}`)\n }\n }\n\n if (dryRun) {\n this.log(`\\n ${dim(`Nothing was executed. Drop ${cmd('--dry-run')} to apply.`)}`)\n }\n }\n\n async run(): Promise<void> {\n const { flags } = await this.parse(Diff)\n\n // On stderr, so a --json or --ci consumer still gets clean stdout while a\n // human is told the flag did nothing.\n for (const { flag, shapesThePlan } of inertApplyFlags(flags as unknown as Record<string, unknown>)) {\n const suggestion = shapesThePlan\n ? `Add ${cmd('--apply')} (or ${cmd('--dry-run')} to preview) for it to take effect.`\n : `Add ${cmd('--apply')} for it to take effect.`\n process.stderr.write(` ${warn(`--${flag} has no effect without --apply.`)} ${suggestion}\\n`)\n }\n\n const config = await this.loadConfigOrFail()\n this.validateDualEnvConfig(config, flags.source, flags.target)\n\n const registry = createDefaultRegistry({ includeFiles: flags['include-files'] })\n const checks = flags.check ? [flags.check as CheckName] : undefined\n const skip = flags.skip?.length ? (flags.skip as CheckName[]) : undefined\n\n const tableFilter = resolveTableFilter(config, {\n tables: flags.tables,\n excludeTables: flags['exclude-tables'],\n })\n\n // Stated up front: a narrowed run must not look like a full one, and with\n // --apply the difference is which statements actually execute (issue #43).\n if (isFiltered(tableFilter) && !flags.json && !flags.ci) {\n this.log(`\\n ${dim(describeTableFilter(tableFilter)!)}`)\n }\n\n // ── Preflight: verify both databases are reachable ────────────────────────\n // In every mode. --json and --ci used to skip it, and with an unreadable\n // source every check that read nothing reported the target's objects as\n // extra — and --apply dropped them.\n await this.preflightBothDatabases(config, flags)\n\n /** Build a progress callback for scan calls. Only active when not --json or --ci. */\n const makeProgress = (): ((event: ScanProgressEvent) => void) | undefined => {\n if (flags.json || flags.ci) return undefined\n process.stdout.write('\\n Scanning...\\n')\n return (event: ScanProgressEvent) => {\n const meta = CHECK_META[event.check]\n const label = meta?.label ?? event.check\n const idx = `[${event.index + 1}/${event.total}]`\n if (event.phase === 'check:start') {\n process.stdout.write(` ▶ ${idx} ${label}...\\n`)\n } else {\n // Clear any in-place detail line before the final result line.\n if (process.stdout.isTTY) process.stdout.write('\\r\\u001b[2K')\n const dur = `${(event.durationMs / 1000).toFixed(1)}s`\n // A skipped layer gets its own glyph and its reason. A green tick\n // beside \"0 issues\" was indistinguishable from a comparison that\n // passed (issue #42).\n const { glyph, text } = describeCheckOutcome(event.status, event.issueCount, event.skipReason)\n process.stdout.write(` ${glyph} ${idx} ${label.padEnd(24)} ${text} (${dur})\\n`)\n }\n }\n }\n\n /**\n * Render fine-grained progress from within a check, in place.\n *\n * A ~100s schema diff on one static spinner line reads as a hang\n * (issue #29). Only used on a TTY — piped or CI output would otherwise\n * accumulate thousands of partial lines.\n */\n const makeDetail = (): ((check: CheckName, detail: string) => void) | undefined => {\n if (flags.json || flags.ci || !process.stdout.isTTY) return undefined\n return (_check, detail) => {\n process.stdout.write(`\\r\\u001b[2K ${dim(detail)}`)\n }\n }\n\n // ── Apply mode (was: promote) ───────────────────────────────────────────────\n // `--dry-run` enters here without `--apply`: it plans, prints the execution\n // order, and writes nothing. Previewing an apply should not require typing\n // the flag that performs one (issue #71).\n if (flags.apply || flags['dry-run']) {\n const onProgress = makeProgress()\n const scanResult = await scan(registry, { config, checks, skip, tableFilter, onProgress, onDetail: makeDetail() })\n this.setCheckSummaries(scanResult.checks.map(c => ({\n check: c.check,\n status: c.status,\n issueCount: c.issues.length,\n durationMs: c.durationMs,\n ...(c.error ? { error: sanitizeForReport(c.error) } : {}),\n })))\n\n // A check that failed measured nothing, so whatever it would have found\n // is not applied. The run says so and exits 1 rather than reporting a\n // clean sync.\n const unchecked = scanResult.checks\n .filter(c => c.status === 'error')\n .map(c => ({ check: c.check, error: sanitizeForReport(c.error ?? 'check failed') }))\n\n if (scanResult.summary.total === 0) {\n // --json promises JSON on stdout whatever the outcome. This branch used\n // to print the sentence below instead, so a script reading the result\n // of an apply failed on the one run where there was nothing to do.\n if (flags.json) {\n const empty: PromoteResult = { applied: [], skipped: [], errors: [] }\n this.json(unchecked.length ? { ...empty, unchecked } : empty)\n if (unchecked.length) this.exit(1)\n return\n }\n if (unchecked.length) {\n this.reportUnchecked(unchecked)\n this.exit(1)\n }\n this.log(`${ok('No drift detected.')} Nothing to apply. ✓`)\n this.log(renderTip({ command: 'diff', apply: true, driftTotal: 0 }))\n return\n }\n\n const targetEnv = config.environments[config.target!]\n const dryRun = flags['dry-run']\n\n // Prove before touching the target. A migration that executes without\n // error can still leave the database in a state that is not the source —\n // a flattened partition or an index that never reached its partitions\n // both apply cleanly. Only replaying it and looking at the result catches\n // that, so when --prove is set a failure blocks the apply rather than\n // warning after the fact.\n if (flags.prove && !dryRun) {\n const sourceEnv = config.environments[config.source!]\n const planned = planWork(scanResult, {\n checks, only: parseFlagList(flags.only),\n allowDestructive: flags['allow-destructive'], tableFilter,\n applyPosture: flags['apply-posture'],\n })\n const { replay, unproved } = proofScope(planned.sqlStatements)\n const migrationSql = replay.map(s => s.sql).join('\\n')\n\n this.log(`\\n ${dim('Proving convergence on a throwaway clone…')}`)\n if (unproved.length > 0) {\n // Applied all the same; the proof just cannot speak for them.\n const byCheck = [...new Set(unproved.map(s => s.check))]\n .map(c => `${c} ×${unproved.filter(s => s.check === c).length}`).join(', ')\n this.log(` ${dim(`Not proved — act outside the proved schemas or on the whole server: ${byCheck}`)}`)\n }\n // Nothing left to replay means nothing to prove. Running it anyway\n // compared the whole schema, and refused a cron-only apply over\n // tables it was never going to touch.\n const proof = replay.length === 0\n ? { converged: false, residual: [], cloneName: '', skipped: 'none of the planned fixes is one the proof can replay' }\n : await proveConvergence({\n sourceUrl: sourceEnv.dbUrl,\n targetUrl: targetEnv.dbUrl,\n migrationSql,\n fixes: replay,\n // Every schema the schema diff compares, not `public` alone: a\n // migration dropping a schema the source lacks runs against it.\n schemas: await comparedSchemas(sourceEnv.dbUrl, targetEnv.dbUrl,\n schemaDiffIgnores(config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS)),\n // The checks this run compares: without the schema check, what the\n // target already lacks elsewhere is not this migration's to fix.\n checks: scanResult.checks.map(c => c.check),\n })\n\n // What the replay left out because this server can't hold it, as the\n // apply will: expected to stay different, so it counts as held back.\n const heldBack = [...heldBackSql(scanResult, planned), ...(proof.notApplied ?? []).map(n => n.sql)]\n if (proof.notApplied?.length) {\n this.log(` ${dim(`Left out, as the apply will leave them — this server can't hold them: ${proof.notApplied.map(n => n.issueId).join(', ')}`)}`)\n }\n\n if (proof.skipped && replay.length === 0) {\n // Nothing the proof could replay: every planned fix is listed above\n // as not proved, and there is nothing a rehearsal would add.\n this.log(` ${dim(`Nothing to prove: ${proof.skipped}.`)}\\n`)\n } else if (proof.skipped) {\n // Could not prove is not the same as failed to converge, so say which —\n // but either way nothing is applied. --prove is asked for as a gate,\n // and it used to apply anyway, exiting 0, when it could not run.\n this.refuseUnproven(`Not proven: ${proof.skipped}`, [], flags.json)\n } else if (!proof.converged && residualHeldBack(proof.residual, heldBack).unexplained.length === 0) {\n // Everything left over is what this run deliberately holds back.\n this.log(` ${ok('Converged')}, apart from what is held back and stays on the target:`)\n for (const line of proof.residual.slice(0, 15)) this.log(` ${dim(line)}`)\n this.log('')\n } else if (!proof.converged) {\n const { unexplained } = residualHeldBack(proof.residual, heldBack)\n this.refuseUnproven('Migration does not reproduce the source.', unexplained, flags.json)\n } else {\n if (proof.outOfScope?.length) {\n this.log(` ${ok('Converged')} on what this run compares. Outside it, and already different before:`)\n for (const line of proof.outOfScope.slice(0, 15)) this.log(` ${dim(line)}`)\n if (proof.outOfScope.length > 15) this.log(` ${dim(`…and ${proof.outOfScope.length - 15} more`)}`)\n this.log('')\n } else {\n this.log(` ${ok('Converged')} — the migration reproduces the source exactly.\\n`)\n }\n }\n }\n\n const result = await promote({\n dbUrl: targetEnv.dbUrl,\n scanResult,\n checks,\n dryRun,\n allowDestructive: flags['allow-destructive'],\n tableFilter,\n only: parseFlagList(flags.only),\n applyPosture: flags['apply-posture'],\n transactional: !flags['no-transaction'],\n })\n\n if (flags.json) {\n this.json(unchecked.length ? { ...result, unchecked } : result)\n // The same exit code as text mode: a failed fix, or a check that never\n // ran, is not a successful apply.\n if (result.errors.length > 0 || unchecked.length > 0) this.exit(1)\n return\n }\n\n this.renderApplyResult(result, dryRun)\n\n if (unchecked.length > 0) this.reportUnchecked(unchecked)\n if (result.errors.length > 0 || unchecked.length > 0) {\n this.exit(1)\n }\n\n this.log(renderTip({\n command: 'diff',\n apply: true,\n driftTotal: scanResult.summary.total,\n driftedChecks: scanResult.checks.filter(c => c.status === 'drifted').map(c => c.check),\n }))\n return\n }\n\n // ── Scan mode (summary, detail, CI, or JSON) ────────────────────────────\n const onProgress = makeProgress()\n const result = await scan(registry, { config, checks, skip, tableFilter, onProgress, onDetail: makeDetail() })\n this.setCheckSummaries(result.checks.map(c => ({\n check: c.check,\n status: c.status,\n issueCount: c.issues.length,\n durationMs: c.durationMs,\n ...(c.error ? { error: sanitizeForReport(c.error) } : {}),\n })))\n\n // Whether the source is a local clone changes what `--apply` means, and so\n // changes what the closing tip should say about it (issue #48).\n //\n // Two signals, because the bookkeeping one is local and exact: a clone\n // diffed from another directory, or renamed, answered \"not a clone\" and got\n // the unqualified \"add --apply\" advice in the most destructive direction\n // (issue #71). The second signal asks the databases whether the source is\n // missing the Supabase substrate the target has, which is the property that\n // makes the advice wrong.\n const sourceUrl = config.environments[config.source!]?.dbUrl\n const sourceIsClone = await isCloneDatabase(sourceUrl)\n || await sourceLooksLikeCloneOf(sourceUrl, config.environments[config.target!]?.dbUrl)\n\n const driftedChecks = result.checks.filter(c => c.status === 'drifted').map(c => c.check)\n const skippedChecks = result.checks.filter(c => c.status === 'skipped').map(c => c.check)\n // A check that errored measured nothing — surfaced so the summary and tips\n // never present an unmeasured scan as a clean one (issue #29).\n const erroredChecks = result.checks.filter(c => c.status === 'error').map(c => c.check)\n\n // ── CI mode ──────────────────────────────────────────────────────────────\n if (flags.ci) {\n const failOn = (flags['fail-on'] ?? 'critical') as FailOn\n // Annotations go to stderr; the machine-readable summary is the *only*\n // thing on stdout. This lets a workflow capture a clean JSON artifact\n // (`supaforge diff --ci > report.json`) while GitHub Actions still renders\n // the `::error`/`::warning` workflow commands from stderr.\n const annotations = formatGitHubAnnotations(result)\n for (const line of annotations) {\n process.stderr.write(line + '\\n')\n }\n const summary = formatCiSummary(result)\n process.stdout.write(JSON.stringify(summary, null, 2) + '\\n')\n const exitCode = computeCiExitCode(result, failOn, {\n failOnPosture: flags['fail-on-posture'],\n })\n if (exitCode !== 0) {\n this.exit(exitCode)\n }\n return\n }\n\n if (flags.json) {\n this.json(result)\n } else if (flags.detail) {\n this.log(renderDetailed(result))\n this.log(renderTip({\n command: 'diff',\n detail: true,\n driftTotal: result.summary.total,\n driftedChecks,\n skippedChecks,\n erroredChecks,\n singleCheck: checks?.[0],\n sourceIsClone,\n }))\n } else {\n this.log(renderSummary(result))\n\n if (result.summary.total > 0) {\n this.log(` → Run with ${cmd('--detail')} to see SQL diffs`)\n // Direction matters here, not just in the tip below. From a clone this\n // line was recommending the command that reshapes a shared remote to\n // match a vanilla-PostgreSQL copy — dropping the roles, grants and\n // policies the clone never had (issue #71).\n this.log(\n sourceIsClone\n ? ` → ${cmd('--apply')} would push this clone's shape onto the target, `\n + `absences included — preview it first with ${cmd('--apply --dry-run')}\\n`\n : ` → Run with ${cmd('--apply')} to fix drift\\n`,\n )\n }\n\n this.log(renderTip({\n command: 'diff',\n detail: false,\n driftTotal: result.summary.total,\n driftedChecks,\n skippedChecks,\n erroredChecks,\n singleCheck: checks?.[0],\n sourceIsClone,\n }))\n }\n\n // A check that errored measured nothing, so the run can't vouch for the\n // pair: exit 1, as the exit-code table says for \"something failed\". It\n // exited 0, and with an unreadable source --json reported a score and\n // succeeded. (--ci keeps its own contract and exits 2.)\n //\n // Otherwise only drift decides the code. A critical posture finding — RLS disabled on\n // a table, a migration file with no tracking row — is true of the target\n // whichever pair you diff, so letting it exit 1 meant a perfectly\n // synchronised pair failed a sync check forever (issue #66).\n const { drift, posture } = summarizeByKind(result.checks)\n\n // Said once, where it changes what the reader should conclude: the report\n // above shows critical findings and the command is about to succeed.\n if (drift.critical === 0 && posture.critical > 0 && !flags.json) {\n this.log(\n ` ${dim('Posture findings do not affect the exit code — they describe the target, '\n + 'not drift from the source. Add')} ${cmd('--fail-on-posture')} ${dim('to gate on them.')}\\n`,\n )\n }\n\n if (drift.critical > 0 || (flags['fail-on-posture'] && posture.critical > 0) || erroredChecks.length > 0) {\n this.exit(1)\n }\n }\n\n /**\n * Stop before applying anything: the proof could not run, or ran and found\n * the migration would not reproduce the source. Under --json the reason is\n * the output, rather than nothing at all.\n */\n private refuseUnproven(reason: string, residual: string[], json?: boolean): never {\n if (json) {\n this.json({ proved: false, reason, residual, applied: [], skipped: [], errors: [] })\n this.exit(1)\n }\n this.log(` ${warn(/[.!?]$/.test(reason) ? reason : `${reason}.`)} Nothing was applied.\\n`)\n for (const line of residual.slice(0, 15)) this.log(` ${line}`)\n if (residual.length > 15) this.log(` ${dim(`…and ${residual.length - 15} more`)}`)\n if (residual.length > 0) this.log(`\\n ${dim('These objects would still differ after applying.')}`)\n else this.log(` ${dim('Re-run without --prove to apply without the proof.')}`)\n this.exit(1)\n }\n\n /** Name the checks that failed, whose drift this run neither saw nor applied. */\n private reportUnchecked(unchecked: Array<{ check: string; error: string }>): void {\n this.log(`\\n ${warn(`${unchecked.length} check(s) could not run, so nothing of theirs was applied:`)}`)\n for (const u of unchecked) this.log(` ${u.check}: ${u.error}`)\n this.log('')\n }\n\n /**\n * Abort before scanning when either database can't be reached.\n *\n * Text mode prints the preflight as before. Under --json the report goes to\n * stdout as JSON; under --ci it becomes an error annotation, with exit 2\n * (couldn't run) as the CI contract says.\n */\n private async preflightBothDatabases(\n config: SupaForgeConfig,\n flags: { json?: boolean; ci?: boolean },\n ): Promise<void> {\n const quiet = Boolean(flags.json || flags.ci)\n const pre = new Preflight('Diff preflight checks', quiet ? () => undefined : (m) => this.log(m))\n .addDatabase('Source', config.source!, config.environments[config.source!].dbUrl)\n .addDatabase('Target', config.target!, config.environments[config.target!].dbUrl)\n const report = await pre.run()\n if (report.passed) return\n\n const failures = report.checks\n .filter(c => !c.passed)\n .map(c => `${c.label} not reachable: ${redactUrls(describeFailure(c.error))}`)\n const message = `Diff aborted — ${failures.join('; ')}`\n if (flags.ci) {\n process.stderr.write(`::error title=Diff aborted::${failures.join('; ')}\\n`)\n // The summary's usual shape, so a workflow reading the artifact needs no\n // special case: nothing compared, and the reason in `errors`.\n process.stdout.write(JSON.stringify({\n timestamp: new Date().toISOString(),\n error: message,\n score: null,\n postureScore: null,\n summary: { total: 0, critical: 0, warning: 0, info: 0 },\n errors: failures.map(f => ({ check: 'preflight', message: f })),\n skipped: [],\n coverage: { compared: 0, total: 0 },\n criticalIssues: [],\n warningIssues: [],\n preflight: report.checks.map(stripError),\n }, null, 2) + '\\n')\n this.exit(2)\n }\n if (flags.json) {\n this.json({ error: message, preflight: report.checks.map(stripError) })\n this.exit(1)\n }\n this.error('Diff aborted — fix the issues above first.', { exit: 1 })\n }\n}\n\n/** The SQL of the fixes this run plans to skip, which the proof did not replay. */\nfunction heldBackSql(scanResult: ScanResult, planned: { skipped: Array<{ issueId: string }> }): string[] {\n const skipped = new Set(planned.skipped.map(s => s.issueId))\n return scanResult.checks.flatMap(c => c.issues)\n .filter(i => skipped.has(i.id) && i.sql?.up)\n .map(i => i.sql!.up)\n}\n\n\n/** A preflight entry without the raw error object, which may not serialise. */\nfunction stripError(c: { label: string; passed: boolean; detail?: string; error?: unknown }) {\n return { label: c.label, passed: c.passed, ...(c.detail ? { detail: c.detail } : {}),\n ...(c.error ? { error: redactUrls(describeFailure(c.error)) } : {}) }\n}\n","import type { ScanResult, DriftIssue } from './types/drift.js'\nimport { coverage } from './render.js'\nimport { summarizeByKind } from './scoring.js'\n\nexport type FailOn = 'critical' | 'warning' | 'any'\n\n/**\n * Escape a workflow-command *message* (the text after `::`).\n *\n * GitHub Actions uses percent-encoding, not backslash escaping. `%` must be\n * encoded first so the percent signs introduced by the other replacements are\n * not double-encoded. Mirrors `@actions/core`'s `escapeData`.\n */\nfunction escapeData(value: string): string {\n return value\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n}\n\n/**\n * Escape a workflow-command *property* value (e.g. `title=`). In addition to\n * the message escapes, `:` and `,` must be encoded because they delimit\n * properties. Mirrors `@actions/core`'s `escapeProperty`.\n */\nfunction escapeProperty(value: string): string {\n return escapeData(value)\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C')\n}\n\n/**\n * Format a DriftIssue as a GitHub Actions annotation line.\n * Spec: https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions#setting-a-notice-message\n */\nexport function formatAnnotation(issue: DriftIssue): string {\n const level = issue.severity === 'critical' ? 'error' : 'warning'\n const title = escapeProperty(issue.title)\n const message = escapeData(issue.description)\n return `::${level} title=${title}::${message}`\n}\n\n/** Emit all drift issues as GitHub Actions annotation lines. */\nexport function formatGitHubAnnotations(result: ScanResult): string[] {\n const lines: string[] = []\n for (const check of result.checks) {\n for (const issue of check.issues) {\n lines.push(formatAnnotation(issue))\n }\n }\n return lines\n}\n\n/** Does this set of counts cross the threshold? */\nfunction exceeds(counts: { critical: number; warning: number; total: number }, failOn: FailOn): boolean {\n if (failOn === 'critical') return counts.critical > 0\n if (failOn === 'warning') return counts.critical > 0 || counts.warning > 0\n return counts.total > 0\n}\n\n/**\n * Determine the exit code for CI.\n *\n * 0 = no drift above threshold\n * 1 = drift exceeds threshold\n * 2 = scan error (connection failure, etc.)\n *\n * Only the comparison checks count. RLS Coverage and Migration History judge\n * the target on its own and fire identically whichever pair you diff, so\n * including them made the exit code unable to distinguish \"the environments\n * have diverged\" from \"the target has a pre-existing gap\" — a sync check failed\n * permanently against an identical target (issue #66). `--fail-on` is a\n * *severity* threshold and could not express the difference, because the\n * difference is one of scope.\n *\n * Pass `failOnPosture` to gate on those findings too. They are never silenced:\n * they keep their severity, appear in the report and the annotations, and are\n * scored as `postureScore`.\n */\nexport function computeCiExitCode(\n result: ScanResult, failOn: FailOn = 'critical', opts: { failOnPosture?: boolean } = {},\n): number {\n const hasError = result.checks.some(c => c.status === 'error')\n if (hasError) return 2\n\n const { drift, posture } = summarizeByKind(result.checks)\n if (exceeds(drift, failOn)) return 1\n if (opts.failOnPosture && exceeds(posture, failOn)) return 1\n\n return 0\n}\n\n/**\n * Produce a structured CI summary object for GitHub Actions step summaries\n * or artifact upload.\n */\nexport function formatCiSummary(result: ScanResult): {\n timestamp: string\n /** Drift between the two environments, over the comparison checks only. */\n score: number\n /**\n * The target's own security and tracking posture, over the non-comparative\n * checks. Reported separately so a pre-existing RLS gap cannot mask, or be\n * mistaken for, environments having diverged (issue #40).\n */\n postureScore: number | null\n summary: ScanResult['summary']\n /**\n * Checks that failed to run. Empty on a healthy scan.\n *\n * Without this a reader of the uploaded artifact saw only a clean summary\n * and had no way to tell that a check never ran — the exit code carried\n * that signal, but the artifact did not (issue #29).\n */\n errors: Array<{ check: string; message: string }>\n /**\n * Checks that declined to run, with the reason.\n *\n * A skipped check is not a failure, so it does not belong in `errors` — but\n * omitting it entirely left a CI artifact that read as full coverage when\n * three layers had never opened a connection (issue #42).\n */\n skipped: Array<{ check: string; reason: string }>\n /** How many checks compared the two environments, over how many were attempted. */\n coverage: { compared: number; total: number }\n criticalIssues: Array<{ check: string; id: string; title: string }>\n warningIssues: Array<{ check: string; id: string; title: string }>\n} {\n const criticalIssues: Array<{ check: string; id: string; title: string }> = []\n const warningIssues: Array<{ check: string; id: string; title: string }> = []\n const errors: Array<{ check: string; message: string }> = []\n const skipped: Array<{ check: string; reason: string }> = []\n\n for (const check of result.checks ?? []) {\n if (check?.status === 'error') {\n errors.push({ check: check.check, message: check.error ?? 'Check failed with no error message' })\n }\n if (check?.status === 'skipped') {\n skipped.push({ check: check.check, reason: check.skipReason ?? 'no reason given' })\n }\n for (const issue of check?.issues ?? []) {\n const entry = { check: check.check, id: issue.id, title: issue.title }\n if (issue.severity === 'critical') {\n criticalIssues.push(entry)\n } else if (issue.severity === 'warning') {\n warningIssues.push(entry)\n }\n }\n }\n\n return {\n timestamp: result.timestamp,\n score: result.score,\n postureScore: result.postureScore ?? null,\n summary: result.summary,\n errors,\n skipped,\n coverage: coverage(result),\n criticalIssues,\n warningIssues,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;;;ACatB,SAAS,WAAW,OAAuB;AACzC,SAAO,MACJ,QAAQ,MAAM,KAAK,EACnB,QAAQ,OAAO,KAAK,EACpB,QAAQ,OAAO,KAAK;AACzB;AAOA,SAAS,eAAe,OAAuB;AAC7C,SAAO,WAAW,KAAK,EACpB,QAAQ,MAAM,KAAK,EACnB,QAAQ,MAAM,KAAK;AACxB;AAMO,SAAS,iBAAiB,OAA2B;AAC1D,QAAM,QAAU,MAAM,aAAa,aAAa,UAAU;AAC1D,QAAM,QAAU,eAAe,MAAM,KAAK;AAC1C,QAAM,UAAU,WAAW,MAAM,WAAW;AAC5C,SAAO,KAAK,KAAK,UAAU,KAAK,KAAK,OAAO;AAC9C;AAGO,SAAS,wBAAwB,QAA8B;AACpE,QAAM,QAAkB,CAAC;AACzB,aAAW,SAAS,OAAO,QAAQ;AACjC,eAAW,SAAS,MAAM,QAAQ;AAChC,YAAM,KAAK,iBAAiB,KAAK,CAAC;AAAA,IACpC;AAAA,EACF;AACA,SAAO;AACT;AAGA,SAAS,QAAQ,QAA8D,QAAyB;AACtG,MAAI,WAAW,WAAY,QAAO,OAAO,WAAW;AACpD,MAAI,WAAW,UAAW,QAAO,OAAO,WAAW,KAAK,OAAO,UAAU;AACzE,SAAO,OAAO,QAAQ;AACxB;AAqBO,SAAS,kBACd,QAAoB,SAAiB,YAAY,OAAoC,CAAC,GAC9E;AACR,QAAM,WAAW,OAAO,OAAO,KAAK,OAAK,EAAE,WAAW,OAAO;AAC7D,MAAI,SAAU,QAAO;AAErB,QAAM,EAAE,OAAO,QAA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,OAAK,EAAE,MAAM,EAC3C,OAAO,OAAK,QAAQ,IAAI,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,EAC1C,IAAI,OAAK,EAAE,IAAK,EAAE;AACvB;AAIA,SAAS,WAAW,GAAyE;AAC3F,SAAO;AAAA,IAAE,OAAO,EAAE;AAAA,IAAO,QAAQ,EAAE;AAAA,IAAQ,GAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,IAAI,CAAC;AAAA,IAChF,GAAI,EAAE,QAAQ,EAAE,OAAO,WAAW,gBAAgB,EAAE,KAAK,CAAC,EAAE,IAAI,CAAC;AAAA,EAAG;AACxE;","names":["onProgress","result"]}
|
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
import {
|
|
2
|
+
backup
|
|
3
|
+
} from "./chunk-NTUASFQ3.js";
|
|
4
|
+
import {
|
|
5
|
+
createDefaultRegistry,
|
|
6
|
+
scan
|
|
7
|
+
} from "./chunk-3HGAV5CC.js";
|
|
8
|
+
import {
|
|
9
|
+
CHECK_NAMES,
|
|
10
|
+
promote
|
|
11
|
+
} from "./chunk-UWAVXC57.js";
|
|
12
|
+
import {
|
|
13
|
+
captureSnapshot
|
|
14
|
+
} from "./chunk-MIRLB5JM.js";
|
|
15
|
+
import {
|
|
16
|
+
checkConnection,
|
|
17
|
+
describeFailure,
|
|
18
|
+
redactUrls
|
|
19
|
+
} from "./chunk-SQPCWGQO.js";
|
|
20
|
+
import {
|
|
21
|
+
resolveConfig,
|
|
22
|
+
validateConfig
|
|
23
|
+
} from "./chunk-6WAMNZLO.js";
|
|
24
|
+
|
|
25
|
+
// src/mcp/state.ts
|
|
26
|
+
var lastScanResult = null;
|
|
27
|
+
function setLastScanResult(result) {
|
|
28
|
+
lastScanResult = result;
|
|
29
|
+
}
|
|
30
|
+
function getLastScanResult() {
|
|
31
|
+
return lastScanResult;
|
|
32
|
+
}
|
|
33
|
+
function clearLastScanResult() {
|
|
34
|
+
lastScanResult = null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/mcp/server.ts
|
|
38
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
39
|
+
import { z } from "zod";
|
|
40
|
+
import { readFile, readdir } from "fs/promises";
|
|
41
|
+
import { existsSync, readFileSync } from "fs";
|
|
42
|
+
import { resolve, join, dirname } from "path";
|
|
43
|
+
import { fileURLToPath } from "url";
|
|
44
|
+
var SERVER_NAME = "supaforge";
|
|
45
|
+
var SERVER_VERSION = resolveVersion();
|
|
46
|
+
function resolveVersion() {
|
|
47
|
+
try {
|
|
48
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
49
|
+
for (const relative of ["../package.json", "../../package.json", "../../../package.json"]) {
|
|
50
|
+
const candidate = resolve(here, relative);
|
|
51
|
+
if (!existsSync(candidate)) continue;
|
|
52
|
+
const pkg = JSON.parse(readFileSync(candidate, "utf-8"));
|
|
53
|
+
if (typeof pkg.version === "string" && pkg.name?.includes("supaforge")) {
|
|
54
|
+
return pkg.version;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
} catch {
|
|
58
|
+
}
|
|
59
|
+
return "0.0.0-unknown";
|
|
60
|
+
}
|
|
61
|
+
function maskConfig(config) {
|
|
62
|
+
if (typeof config !== "object" || config === null) return config;
|
|
63
|
+
const result = {};
|
|
64
|
+
for (const [key, value] of Object.entries(config)) {
|
|
65
|
+
if (key === "dbUrl" || key === "accessToken") {
|
|
66
|
+
result[key] = typeof value === "string" && value.length > 0 ? "***" : value;
|
|
67
|
+
} else if (typeof value === "object" && value !== null) {
|
|
68
|
+
result[key] = maskConfig(value);
|
|
69
|
+
} else {
|
|
70
|
+
result[key] = value;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
function createServer(cwd = process.cwd(), options = {}) {
|
|
76
|
+
const allowConfigPath = options.allowConfigPath ?? false;
|
|
77
|
+
const resolveCwd = (configPath) => {
|
|
78
|
+
if (!configPath) return cwd;
|
|
79
|
+
if (!allowConfigPath) {
|
|
80
|
+
throw new Error(
|
|
81
|
+
`configPath is not accepted by this server. It was started without --allow-config-path, so it reads only the config in its own working directory (${cwd}). Restart it with --allow-config-path to permit other projects.`
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
return resolve(configPath, "..");
|
|
85
|
+
};
|
|
86
|
+
const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION });
|
|
87
|
+
server.registerTool(
|
|
88
|
+
"scan_drift",
|
|
89
|
+
{
|
|
90
|
+
// Reads both databases and writes nothing. Without annotations a client
|
|
91
|
+
// could not tell this from apply_fixes, so it could not ask for
|
|
92
|
+
// confirmation on the one that writes (issue #96).
|
|
93
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
|
|
94
|
+
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.",
|
|
95
|
+
inputSchema: {
|
|
96
|
+
configPath: z.string().optional().describe(
|
|
97
|
+
"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."
|
|
98
|
+
),
|
|
99
|
+
source: z.string().optional().describe("Source environment name (overrides config default)."),
|
|
100
|
+
target: z.string().optional().describe("Target environment name (overrides config default)."),
|
|
101
|
+
checks: z.array(z.enum(CHECK_NAMES)).optional().describe('Limit scan to specific checks (e.g. ["rls", "rls-coverage"]).'),
|
|
102
|
+
skip: z.array(z.enum(CHECK_NAMES)).optional().describe(
|
|
103
|
+
"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."
|
|
104
|
+
)
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
async ({ configPath, source, target, checks, skip }) => {
|
|
108
|
+
try {
|
|
109
|
+
const effectiveCwd = resolveCwd(configPath);
|
|
110
|
+
const raw = JSON.parse(await readFile(resolve(effectiveCwd, "supaforge.config.json"), "utf-8"));
|
|
111
|
+
const config = resolveConfig({
|
|
112
|
+
...raw,
|
|
113
|
+
...source ? { source } : {},
|
|
114
|
+
...target ? { target } : {}
|
|
115
|
+
});
|
|
116
|
+
const errors = validateConfig(config);
|
|
117
|
+
if (errors.length > 0) {
|
|
118
|
+
return { content: [{ type: "text", text: `Config errors:
|
|
119
|
+
${errors.join("\n")}` }], isError: true };
|
|
120
|
+
}
|
|
121
|
+
const registry = createDefaultRegistry();
|
|
122
|
+
const result = await scan(registry, {
|
|
123
|
+
config,
|
|
124
|
+
checks,
|
|
125
|
+
skip
|
|
126
|
+
});
|
|
127
|
+
setLastScanResult(result);
|
|
128
|
+
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
129
|
+
} catch (err) {
|
|
130
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
131
|
+
return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
);
|
|
135
|
+
server.registerTool(
|
|
136
|
+
"apply_fixes",
|
|
137
|
+
{
|
|
138
|
+
// Writes to the target database, and destructively when
|
|
139
|
+
// allowDestructive is set. This is the one a client should confirm.
|
|
140
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
|
|
141
|
+
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.",
|
|
142
|
+
inputSchema: {
|
|
143
|
+
configPath: z.string().optional().describe(
|
|
144
|
+
"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."
|
|
145
|
+
),
|
|
146
|
+
source: z.string().optional().describe("Source environment name."),
|
|
147
|
+
target: z.string().optional().describe("Target environment name."),
|
|
148
|
+
checks: z.array(z.enum(CHECK_NAMES)).optional().describe("Apply fixes only for specific checks."),
|
|
149
|
+
dryRun: z.boolean().optional().default(true).describe(
|
|
150
|
+
"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."
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
},
|
|
154
|
+
async ({ configPath, source, target, checks, dryRun }) => {
|
|
155
|
+
try {
|
|
156
|
+
const effectiveCwd = resolveCwd(configPath);
|
|
157
|
+
const raw = JSON.parse(await readFile(resolve(effectiveCwd, "supaforge.config.json"), "utf-8"));
|
|
158
|
+
const config = resolveConfig({
|
|
159
|
+
...raw,
|
|
160
|
+
...source ? { source } : {},
|
|
161
|
+
...target ? { target } : {}
|
|
162
|
+
});
|
|
163
|
+
const errors = validateConfig(config);
|
|
164
|
+
if (errors.length > 0) {
|
|
165
|
+
return { content: [{ type: "text", text: `Config errors:
|
|
166
|
+
${errors.join("\n")}` }], isError: true };
|
|
167
|
+
}
|
|
168
|
+
const unreachable = [];
|
|
169
|
+
for (const [label, name] of [["Source", config.source], ["Target", config.target]]) {
|
|
170
|
+
const conn = await checkConnection(config.environments[name].dbUrl);
|
|
171
|
+
if (!conn.reachable) unreachable.push(`${label} (${name}) not reachable: ${redactUrls(describeFailure(conn.error))}`);
|
|
172
|
+
}
|
|
173
|
+
if (unreachable.length > 0) {
|
|
174
|
+
return { content: [{ type: "text", text: `Nothing compared or applied.
|
|
175
|
+
${unreachable.join("\n")}` }], isError: true };
|
|
176
|
+
}
|
|
177
|
+
const registry = createDefaultRegistry();
|
|
178
|
+
const scanResult = await scan(registry, {
|
|
179
|
+
config,
|
|
180
|
+
checks
|
|
181
|
+
});
|
|
182
|
+
setLastScanResult(scanResult);
|
|
183
|
+
const targetEnv = config.environments[config.target];
|
|
184
|
+
const promoteResult = await promote({
|
|
185
|
+
dbUrl: targetEnv.dbUrl,
|
|
186
|
+
scanResult,
|
|
187
|
+
checks,
|
|
188
|
+
dryRun
|
|
189
|
+
});
|
|
190
|
+
const unchecked = scanResult.checks.filter((c) => c.status === "error").map((c) => ({ check: c.check, error: c.error ?? "check failed" }));
|
|
191
|
+
const body = unchecked.length ? { ...promoteResult, unchecked } : promoteResult;
|
|
192
|
+
return {
|
|
193
|
+
content: [{ type: "text", text: JSON.stringify(body, null, 2) }],
|
|
194
|
+
...unchecked.length || promoteResult.errors.length ? { isError: true } : {}
|
|
195
|
+
};
|
|
196
|
+
} catch (err) {
|
|
197
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
198
|
+
return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
);
|
|
202
|
+
server.registerTool(
|
|
203
|
+
"take_snapshot",
|
|
204
|
+
{
|
|
205
|
+
// Reads the database and writes local files only — nothing in any
|
|
206
|
+
// database changes.
|
|
207
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
|
|
208
|
+
description: "Capture a point-in-time snapshot of a Supabase environment. Snapshots are stored under .supaforge/snapshots/ and can be used to restore state.",
|
|
209
|
+
inputSchema: {
|
|
210
|
+
configPath: z.string().optional().describe(
|
|
211
|
+
"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."
|
|
212
|
+
),
|
|
213
|
+
environment: z.string().optional().describe("Environment to snapshot (defaults to config source).")
|
|
214
|
+
}
|
|
215
|
+
},
|
|
216
|
+
async ({ configPath, environment }) => {
|
|
217
|
+
try {
|
|
218
|
+
const effectiveCwd = resolveCwd(configPath);
|
|
219
|
+
const raw = JSON.parse(await readFile(resolve(effectiveCwd, "supaforge.config.json"), "utf-8"));
|
|
220
|
+
const config = resolveConfig(raw);
|
|
221
|
+
const envName = environment ?? config.source ?? Object.keys(config.environments)[0];
|
|
222
|
+
const env = config.environments[envName];
|
|
223
|
+
if (!env) {
|
|
224
|
+
return {
|
|
225
|
+
content: [{ type: "text", text: `Environment "${envName}" not found in config.` }],
|
|
226
|
+
isError: true
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
const result = await captureSnapshot({ envName, env, config, cwd: effectiveCwd });
|
|
230
|
+
return {
|
|
231
|
+
content: [
|
|
232
|
+
{
|
|
233
|
+
type: "text",
|
|
234
|
+
text: JSON.stringify({ timestamp: result.timestamp, dir: result.dir, manifest: result.manifest }, null, 2)
|
|
235
|
+
}
|
|
236
|
+
]
|
|
237
|
+
};
|
|
238
|
+
} catch (err) {
|
|
239
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
240
|
+
return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
);
|
|
244
|
+
server.registerTool(
|
|
245
|
+
"create_migration",
|
|
246
|
+
{
|
|
247
|
+
// Local files only, as with take_snapshot.
|
|
248
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
|
|
249
|
+
description: "Capture a snapshot and generate a migration file containing the diff against the previous snapshot. Migration files are stored under .supaforge/migrations/.",
|
|
250
|
+
inputSchema: {
|
|
251
|
+
configPath: z.string().optional().describe(
|
|
252
|
+
"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."
|
|
253
|
+
),
|
|
254
|
+
environment: z.string().optional().describe("Environment to snapshot (defaults to config source)."),
|
|
255
|
+
description: z.string().optional().describe('Human-readable description for the migration (e.g. "add-rls-to-orders").')
|
|
256
|
+
}
|
|
257
|
+
},
|
|
258
|
+
async ({ configPath, environment, description }) => {
|
|
259
|
+
try {
|
|
260
|
+
const effectiveCwd = resolveCwd(configPath);
|
|
261
|
+
const raw = JSON.parse(await readFile(resolve(effectiveCwd, "supaforge.config.json"), "utf-8"));
|
|
262
|
+
const config = resolveConfig(raw);
|
|
263
|
+
const envName = environment ?? config.source ?? Object.keys(config.environments)[0];
|
|
264
|
+
const env = config.environments[envName];
|
|
265
|
+
if (!env) {
|
|
266
|
+
return {
|
|
267
|
+
content: [{ type: "text", text: `Environment "${envName}" not found in config.` }],
|
|
268
|
+
isError: true
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
const result = await backup({
|
|
272
|
+
envName,
|
|
273
|
+
env,
|
|
274
|
+
config,
|
|
275
|
+
cwd: effectiveCwd,
|
|
276
|
+
description
|
|
277
|
+
});
|
|
278
|
+
return {
|
|
279
|
+
content: [
|
|
280
|
+
{
|
|
281
|
+
type: "text",
|
|
282
|
+
text: JSON.stringify(
|
|
283
|
+
{
|
|
284
|
+
isBaseline: result.isBaseline,
|
|
285
|
+
migrationFile: result.migrationFile,
|
|
286
|
+
snapshotDir: result.snapshot.dir,
|
|
287
|
+
timestamp: result.snapshot.timestamp
|
|
288
|
+
},
|
|
289
|
+
null,
|
|
290
|
+
2
|
|
291
|
+
)
|
|
292
|
+
}
|
|
293
|
+
]
|
|
294
|
+
};
|
|
295
|
+
} catch (err) {
|
|
296
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
297
|
+
return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
);
|
|
301
|
+
server.registerTool(
|
|
302
|
+
"get_check_result",
|
|
303
|
+
{
|
|
304
|
+
// Reads the last scan held in memory.
|
|
305
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
|
|
306
|
+
description: "Retrieve the result for a specific check from the most recent scan_drift call. Returns issues, status, and duration for the named check.",
|
|
307
|
+
inputSchema: {
|
|
308
|
+
check: z.enum(CHECK_NAMES).describe('The check name to retrieve (e.g. "rls-coverage").')
|
|
309
|
+
}
|
|
310
|
+
},
|
|
311
|
+
async ({ check }) => {
|
|
312
|
+
const result = getLastScanResult();
|
|
313
|
+
if (!result) {
|
|
314
|
+
return {
|
|
315
|
+
content: [{ type: "text", text: "No scan result available. Run scan_drift first." }],
|
|
316
|
+
isError: true
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
const checkResult = result.checks.find((c) => c.check === check);
|
|
320
|
+
if (!checkResult) {
|
|
321
|
+
return {
|
|
322
|
+
content: [
|
|
323
|
+
{ type: "text", text: `Check "${check}" not found in last scan. Was it included in the scan?` }
|
|
324
|
+
],
|
|
325
|
+
isError: true
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
return { content: [{ type: "text", text: JSON.stringify(checkResult, null, 2) }] };
|
|
329
|
+
}
|
|
330
|
+
);
|
|
331
|
+
server.registerResource(
|
|
332
|
+
"config",
|
|
333
|
+
"supaforge://config",
|
|
334
|
+
{
|
|
335
|
+
title: "SupaForge Config",
|
|
336
|
+
description: "Current supaforge.config.json (sensitive fields masked)",
|
|
337
|
+
mimeType: "application/json"
|
|
338
|
+
},
|
|
339
|
+
async (uri) => {
|
|
340
|
+
try {
|
|
341
|
+
const raw = JSON.parse(await readFile(resolve(cwd, "supaforge.config.json"), "utf-8"));
|
|
342
|
+
const masked = maskConfig(raw);
|
|
343
|
+
return {
|
|
344
|
+
contents: [{ uri: uri.href, text: JSON.stringify(masked, null, 2), mimeType: "application/json" }]
|
|
345
|
+
};
|
|
346
|
+
} catch (err) {
|
|
347
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
348
|
+
return { contents: [{ uri: uri.href, text: `Error loading config: ${msg}`, mimeType: "text/plain" }] };
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
);
|
|
352
|
+
server.registerResource(
|
|
353
|
+
"last-scan",
|
|
354
|
+
"supaforge://last-scan",
|
|
355
|
+
{
|
|
356
|
+
title: "Last Scan Result",
|
|
357
|
+
description: "The most recent drift scan result",
|
|
358
|
+
mimeType: "application/json"
|
|
359
|
+
},
|
|
360
|
+
async (uri) => {
|
|
361
|
+
const result = getLastScanResult();
|
|
362
|
+
if (!result) {
|
|
363
|
+
return {
|
|
364
|
+
contents: [
|
|
365
|
+
{
|
|
366
|
+
uri: uri.href,
|
|
367
|
+
text: JSON.stringify({ message: "No scan result yet. Run scan_drift first." }),
|
|
368
|
+
mimeType: "application/json"
|
|
369
|
+
}
|
|
370
|
+
]
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
return { contents: [{ uri: uri.href, text: JSON.stringify(result, null, 2), mimeType: "application/json" }] };
|
|
374
|
+
}
|
|
375
|
+
);
|
|
376
|
+
server.registerResource(
|
|
377
|
+
"migrations",
|
|
378
|
+
"supaforge://migrations",
|
|
379
|
+
{
|
|
380
|
+
title: "Migration Files",
|
|
381
|
+
description: "Migration files under .supaforge/migrations/",
|
|
382
|
+
mimeType: "application/json"
|
|
383
|
+
},
|
|
384
|
+
async (uri) => {
|
|
385
|
+
try {
|
|
386
|
+
const migrationsDir = join(cwd, ".supaforge", "migrations");
|
|
387
|
+
const files = await readdir(migrationsDir).catch(() => []);
|
|
388
|
+
const jsonFiles = files.filter((f) => f.endsWith(".json")).sort();
|
|
389
|
+
return {
|
|
390
|
+
contents: [
|
|
391
|
+
{
|
|
392
|
+
uri: uri.href,
|
|
393
|
+
text: JSON.stringify({ directory: migrationsDir, files: jsonFiles }, null, 2),
|
|
394
|
+
mimeType: "application/json"
|
|
395
|
+
}
|
|
396
|
+
]
|
|
397
|
+
};
|
|
398
|
+
} catch (err) {
|
|
399
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
400
|
+
return { contents: [{ uri: uri.href, text: `Error: ${msg}`, mimeType: "text/plain" }] };
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
);
|
|
404
|
+
server.registerPrompt(
|
|
405
|
+
"review_drift_before_deploy",
|
|
406
|
+
{
|
|
407
|
+
description: "Generate a drift review context to share with an AI agent before deploying.",
|
|
408
|
+
argsSchema: {
|
|
409
|
+
environment: z.string().optional().describe('Target environment name (e.g. "production")')
|
|
410
|
+
}
|
|
411
|
+
},
|
|
412
|
+
({ environment }) => {
|
|
413
|
+
const envNote = environment ? ` to **${environment}**` : "";
|
|
414
|
+
const lastScan = getLastScanResult();
|
|
415
|
+
const scanContext = lastScan ? `
|
|
416
|
+
|
|
417
|
+
Last scan result (${lastScan.timestamp}):
|
|
418
|
+
- Score: ${lastScan.score}
|
|
419
|
+
- Total issues: ${lastScan.summary.total} (${lastScan.summary.critical} critical, ${lastScan.summary.warning} warnings)
|
|
420
|
+
- 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.";
|
|
421
|
+
return {
|
|
422
|
+
messages: [
|
|
423
|
+
{
|
|
424
|
+
role: "user",
|
|
425
|
+
content: {
|
|
426
|
+
type: "text",
|
|
427
|
+
text: [
|
|
428
|
+
`Before deploying${envNote}, please review the current SupaForge drift report.`,
|
|
429
|
+
scanContext,
|
|
430
|
+
"",
|
|
431
|
+
"Steps:",
|
|
432
|
+
"1. Call scan_drift to get the latest drift report.",
|
|
433
|
+
"2. Review critical issues (especially rls-coverage and rls checks).",
|
|
434
|
+
"3. Confirm all SQL fixes look correct before applying.",
|
|
435
|
+
"4. If safe, run apply_fixes with dryRun=true first, then dryRun=false."
|
|
436
|
+
].join("\n")
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
]
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
);
|
|
443
|
+
server.registerPrompt(
|
|
444
|
+
"fix_critical_issues",
|
|
445
|
+
{
|
|
446
|
+
description: "Generate a step-by-step plan to fix all critical drift issues.",
|
|
447
|
+
argsSchema: {}
|
|
448
|
+
},
|
|
449
|
+
() => {
|
|
450
|
+
const lastScan = getLastScanResult();
|
|
451
|
+
let criticalSummary = "No recent scan \u2014 run scan_drift first.";
|
|
452
|
+
if (lastScan) {
|
|
453
|
+
const criticalIssues = lastScan.checks.flatMap((c) => c.issues).filter((i) => i.severity === "critical");
|
|
454
|
+
if (criticalIssues.length === 0) {
|
|
455
|
+
criticalSummary = "No critical issues found in the last scan. The target environment looks healthy.";
|
|
456
|
+
} else {
|
|
457
|
+
criticalSummary = [
|
|
458
|
+
`Found ${criticalIssues.length} critical issue(s) in last scan (${lastScan.timestamp}):`,
|
|
459
|
+
...criticalIssues.map((i) => `- [${i.check}] ${i.title}`)
|
|
460
|
+
].join("\n");
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return {
|
|
464
|
+
messages: [
|
|
465
|
+
{
|
|
466
|
+
role: "user",
|
|
467
|
+
content: {
|
|
468
|
+
type: "text",
|
|
469
|
+
text: [
|
|
470
|
+
"Fix all critical drift issues in the target Supabase environment.",
|
|
471
|
+
"",
|
|
472
|
+
criticalSummary,
|
|
473
|
+
"",
|
|
474
|
+
"Recommended steps:",
|
|
475
|
+
"1. Run scan_drift to confirm the current state.",
|
|
476
|
+
"2. Review each critical issue and its sql.up fix.",
|
|
477
|
+
"3. Run apply_fixes with dryRun=true to preview the SQL.",
|
|
478
|
+
"4. Confirm the SQL is safe, then run apply_fixes with dryRun=false.",
|
|
479
|
+
"5. Run scan_drift again to confirm all critical issues are resolved.",
|
|
480
|
+
"",
|
|
481
|
+
"Pay special attention to rls-coverage issues \u2014 tables without RLS enabled",
|
|
482
|
+
"are the CVE-2025-48757 vulnerability pattern."
|
|
483
|
+
].join("\n")
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
]
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
);
|
|
490
|
+
return server;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
export {
|
|
494
|
+
setLastScanResult,
|
|
495
|
+
getLastScanResult,
|
|
496
|
+
clearLastScanResult,
|
|
497
|
+
createServer
|
|
498
|
+
};
|
|
499
|
+
//# sourceMappingURL=chunk-6LJERPUN.js.map
|