Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(docs): redesign changelog page and add route progress bar

t8y23a0e86956cb9
diff --git a/.github/scripts/sync-changelog.mjs b/.github/scripts/sync-changelog.mjs
index 6d1616f9bb..b3ec839f59 100644
--- a/.github/scripts/sync-changelog.mjs
+++ b/.github/scripts/sync-changelog.mjs
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
-import { writeFileSync } from "node:fs";
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -10,6 +10,10 @@ const GITHUB_TOKEN = process.env.GITHUB_TOKEN || "";
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY || "";
const OUT_CN = "releases-cn.json";
const OUT_EN = "releases-en.json";
+const OUT_INDEX_CN = "index-cn.json";
+const OUT_INDEX_EN = "index-en.json";
+const RELEASES_CN_DIR = "releases-cn";
+const RELEASES_EN_DIR = "releases-en";
const LATEST_EN_OUT = "latest-en.json";
const LATEST_NOTES_OUT = "latest-notes.json";
const EN_CACHE_URL = process.env.CHANGELOG_EN_CACHE_URL || "https://dl.dbxio.com/changelog/releases-en.json";
@@ -68,6 +72,7 @@ function stripIssueRefs(text) {
// 可能是旧版脚本生成的(desc 仍含 closes #),在写文件前统一清理一次。
function stripIssueRefsInReleases(json) {
for (const release of json.releases || []) {
+ if (release.markdown) release.markdown = stripIssueRefs(release.markdown);
for (const section of release.sections || []) {
for (const item of section.items || []) {
if (item.desc) item.desc = stripIssueRefs(item.desc);
@@ -138,12 +143,30 @@ export function buildReleasesJson(releases, now = new Date()) {
name: r.name || r.tag_name,
date: r.published_at.slice(0, 10),
_sourceHash: buildReleaseSourceHash(r),
+ markdown: stripIssueRefs(stripDownloadSection(r.body || "")),
sections: parseBody(r.body || ""),
})),
};
}
+export function buildChangelogIndex(json) {
+ return {
+ updatedAt: json.updatedAt,
+ releases: json.releases.map(({ tag, name, date }) => ({ tag, name, date })),
+ };
+}
+
+function writeReleaseFiles(json, directory) {
+ rmSync(directory, { recursive: true, force: true });
+ mkdirSync(directory, { recursive: true });
+ for (const release of json.releases) {
+ writeFileSync(resolve(directory, `${release.tag}.json`), JSON.stringify(release, null, 2));
+ }
+}
+
function releaseToMarkdown(release) {
+ if (release.markdown !== undefined) return release.markdown;
+
return release.sections
.map((s) => {
const items = s.items.map((i) => (i.desc ? `- **${i.title}** — ${i.desc}` : `- ${i.title}`)).join("\n");
@@ -199,7 +222,7 @@ export async function translateToEnglish(cnJson, { cachedEnJson = null, deepseek
for (const release of cnJson.releases) {
const cachedRelease = cachedByTag.get(release.tag);
if (cachedRelease?._sourceHash === release._sourceHash) {
- enReleases.push({ ...cachedRelease, name: release.name, date: release.date, _sourceHash: release._sourceHash });
+ enReleases.push({ ...cachedRelease, name: release.name, date: release.date, _sourceHash: release._sourceHash, markdown: cachedRelease.markdown || releaseToMarkdown(cachedRelease) });
reusedCount++;
} else {
enReleases.push(release);
@@ -218,6 +241,7 @@ export async function translateToEnglish(cnJson, { cachedEnJson = null, deepseek
name: release.name,
date: release.date,
_sourceHash: release._sourceHash,
+ markdown: cachedRelease.markdown || releaseToMarkdown(cachedRelease),
});
reusedCount++;
continue;
@@ -226,7 +250,7 @@ export async function translateToEnglish(cnJson, { cachedEnJson = null, deepseek
const sectionsText = releaseToMarkdown(release);
if (!sectionsText.trim()) {
- enReleases.push({ ...release, sections: [] });
+ enReleases.push({ ...release, sections: [], markdown: "" });
continue;
}
@@ -256,7 +280,7 @@ export async function translateToEnglish(cnJson, { cachedEnJson = null, deepseek
const data = await res.json();
const translated = data.choices?.[0]?.message?.content || "";
const enSections = parseBody(translated);
- enReleases.push({ ...release, sections: enSections.length > 0 ? enSections : release.sections });
+ enReleases.push({ ...release, sections: enSections.length > 0 ? enSections : release.sections, markdown: enSections.length > 0 ? translated.trim() : release.markdown });
translatedCount++;
await sleep(200);
@@ -276,6 +300,9 @@ async function main() {
writeFileSync(OUT_CN, JSON.stringify(cnJson, null, 2));
console.log(`Wrote ${OUT_CN}`);
+ writeFileSync(OUT_INDEX_CN, JSON.stringify(buildChangelogIndex(cnJson), null, 2));
+ writeReleaseFiles(cnJson, RELEASES_CN_DIR);
+ console.log(`Wrote ${OUT_INDEX_CN} and ${RELEASES_CN_DIR}/`);
const latestNotes = buildLatestReleaseNotes(releases);
if (latestNotes) {
@@ -293,6 +320,9 @@ async function main() {
stripIssueRefsInReleases(enJson);
writeFileSync(OUT_EN, JSON.stringify(enJson, null, 2));
console.log(`Wrote ${OUT_EN}`);
+ writeFileSync(OUT_INDEX_EN, JSON.stringify(buildChangelogIndex(enJson), null, 2));
+ writeReleaseFiles(enJson, RELEASES_EN_DIR);
+ console.log(`Wrote ${OUT_INDEX_EN} and ${RELEASES_EN_DIR}/`);
// 应用内更新提示用的英文 notes(单条最新版本)
const latestEn = buildLatestEnNotes(enJson);
diff --git a/.github/workflows/sync-changelog.yml b/.github/workflows/sync-changelog.yml
index 1c8a4862ac..3033a67ac4 100644
--- a/.github/workflows/sync-changelog.yml
+++ b/.github/workflows/sync-changelog.yml
@@ -31,11 +31,29 @@ jobs:
pip install awscli --quiet
aws s3 cp releases-cn.json "s3://${R2_BUCKET_NAME}/changelog/releases-cn.json" \
--endpoint-url "https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com" \
- --content-type application/json
+ --content-type application/json \
+ --cache-control "public, max-age=300, stale-while-revalidate=86400"
+ aws s3 cp index-cn.json "s3://${R2_BUCKET_NAME}/changelog/index-cn.json" \
+ --endpoint-url "https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com" \
+ --content-type application/json \
+ --cache-control "public, max-age=300, stale-while-revalidate=86400"
+ aws s3 sync releases-cn/ "s3://${R2_BUCKET_NAME}/changelog/releases-cn/" \
+ --endpoint-url "https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com" \
+ --delete --content-type application/json \
+ --cache-control "public, max-age=86400, stale-while-revalidate=604800"
if [ -f releases-en.json ]; then
aws s3 cp releases-en.json "s3://${R2_BUCKET_NAME}/changelog/releases-en.json" \
--endpoint-url "https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com" \
- --content-type application/json
+ --content-type application/json \
+ --cache-control "public, max-age=300, stale-while-revalidate=86400"
+ aws s3 cp index-en.json "s3://${R2_BUCKET_NAME}/changelog/index-en.json" \
+ --endpoint-url "https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com" \
+ --content-type application/json \
+ --cache-control "public, max-age=300, stale-while-revalidate=86400"
+ aws s3 sync releases-en/ "s3://${R2_BUCKET_NAME}/changelog/releases-en/" \
+ --endpoint-url "https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com" \
+ --delete --content-type application/json \
+ --cache-control "public, max-age=86400, stale-while-revalidate=604800"
fi
if [ -f latest-en.json ]; then
aws s3 cp latest-en.json "s3://${R2_BUCKET_NAME}/changelog/latest-en.json" \
diff --git a/docs/app/[lang]/changelog/page.tsx b/docs/app/[lang]/changelog/page.tsx
index 8ac30da02c..89fb288368 100644
--- a/docs/app/[lang]/changelog/page.tsx
+++ b/docs/app/[lang]/changelog/page.tsx
@@ -1,7 +1,7 @@
import { LandingNav } from "@/components/landing/LandingNav";
import { LandingFooter } from "@/components/landing/LandingFooter";
import { ChangelogRuntime } from "@/components/landing/ChangelogRuntime";
-import { fetchChangelog } from "@/lib/changelog";
+import { loadChangelogBootstrap } from "@/lib/changelog";
import { buildMetadata } from "@/lib/metadata";
import type { Metadata } from "next";
@@ -33,19 +33,17 @@ export default async function ChangelogPage({ params }: { params: Promise<{ lang
const { lang } = await params;
const l = lang === "cn" ? "cn" : "en";
const t = i18n[l];
- const initialData = await fetchChangelog(l);
+ const initialData = await loadChangelogBootstrap(l);
return (
<main className="min-h-screen bg-[#08080a] text-landing-ink">
<LandingNav lang={l} active="changelog" />
- <div className="max-w-[860px] mx-auto px-6 pt-32 pb-4 max-[760px]:px-[18px] max-[760px]:pt-28">
- <h1 className="text-4xl font-[820] tracking-tight">{t.title}</h1>
- <p className="mt-3 text-landing-muted text-lg">{t.desc}</p>
- </div>
+ {/* 视觉隐藏:页面不再展示大标题,但保留语义 landmark 与 SEO */}
+ <h1 className="sr-only">{t.title}</h1>
- <div className="max-w-[860px] mx-auto px-6 pb-24 max-[760px]:px-[18px]">
- <ChangelogRuntime lang={l} initialReleases={initialData.releases} />
+ <div className="max-w-[1400px] mx-auto px-7 pt-28 pb-24 max-[760px]:px-[18px] max-[760px]:pt-24">
+ <ChangelogRuntime lang={l} index={initialData.index} initialRelease={initialData.initialRelease} fallbackReleases={initialData.fallbackReleases} />
</div>
<LandingFooter lang={l} />
diff --git a/docs/app/[lang]/layout.tsx b/docs/app/[lang]/layout.tsx
index 495a0c44f1..a0a3729e96 100644
--- a/docs/app/[lang]/layout.tsx
+++ b/docs/app/[lang]/layout.tsx
@@ -1,6 +1,7 @@
import "../global.css";
import type { ReactNode } from "react";
import type { Metadata, Viewport } from "next";
+import { RouteProgress } from "@/components/RouteProgress";
import { buildMetadata, DEFAULT_DESCRIPTION, getHtmlLang, SITE_NAME, SITE_URL } from "@/lib/metadata";
import { buildSiteStructuredData } from "@/lib/structuredData";
@@ -72,7 +73,10 @@ export default async function LangLayout({ params, children }: { params: Promise
<script key={structuredData["@id"]} type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }} />
))}
</head>
- <body className="flex min-h-screen flex-col">{children}</body>
+ <body className="flex min-h-screen flex-col">
+ <RouteProgress />
+ {children}
+ </body>
</html>
);
}
diff --git a/docs/app/global.css b/docs/app/global.css
index 44c3a1d3b0..b765007d1e 100644
--- a/docs/app/global.css
+++ b/docs/app/global.css
@@ -2,6 +2,26 @@
@import "fumadocs-ui/css/ocean.css";
@import "fumadocs-ui/css/preset.css";
+/* 路由跳转进度条(nprogress 风格),挂在语言布局 body 顶部 */
+
+.route-progress-bar {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ height: 2.5px;
+ z-index: 90;
+ transform-origin: 0 50%;
+ transform: scaleX(0);
+ opacity: 0;
+ background: linear-gradient(90deg, var(--color-landing-sky), var(--color-landing-blue));
+ box-shadow: 0 0 10px rgba(82, 213, 255, 0.5);
+ pointer-events: none;
+ transition:
+ transform 0.12s ease,
+ opacity 0.22s ease;
+}
+
@theme {
--color-landing-ink: #ededf0;
--color-landing-muted: #9c9ea3;
@@ -1178,12 +1198,238 @@ a {
transform: translateY(-1px);
}
-.changelog-release-summary {
- display: none;
+/* Changelog — three-pane layout */
+
+.changelog-shell {
+ display: grid;
+ grid-template-columns: 208px minmax(0, 1fr) 224px;
+ gap: 44px;
+ align-items: start;
+}
+
+.changelog-sidebar {
+ position: sticky;
+ top: 104px;
+}
+
+.changelog-sidebar-title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 14px;
+ color: var(--color-landing-ink);
+ font-size: 13.5px;
+ font-weight: 720;
+}
+
+.changelog-version-list {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ max-height: calc(100vh - 180px);
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ scrollbar-width: thin;
+ padding-right: 6px;
+}
+
+.changelog-version-link {
+ display: block;
+ padding: 7px 12px;
+ border: 1px solid transparent;
+ border-radius: 8px;
+ color: var(--color-landing-muted);
+ font-size: 13.5px;
+ font-weight: 560;
+ text-align: left;
+ white-space: nowrap;
+ transition:
+ color 0.15s ease,
+ background 0.15s ease,
+ border-color 0.15s ease;
+}
+
+.changelog-version-link:hover {
+ color: var(--color-landing-ink);
+ background: var(--color-landing-soft);
+}
+
+.changelog-version-link.is-active {
+ color: var(--color-landing-ink);
+ background: var(--color-landing-panel);
+ border-color: var(--color-landing-line);
+ font-weight: 700;
+}
+
+.changelog-content {
+ min-width: 0;
+}
+
+.changelog-release-loading {
+ display: grid;
+ place-items: center;
+ min-height: 320px;
+ color: var(--color-landing-muted);
+ font-size: 14px;
+}
+
+.changelog-toc-title {
+ margin: 0;
+ color: #e4e7ea;
+ font-size: 14px;
+ font-weight: 720;
+}
+
+.changelog-toc-subtitle {
+ margin: 3px 0 14px;
+ color: var(--color-landing-muted);
+ font-size: 12px;
+}
+
+.changelog-toc-list {
+ display: flex;
+ flex-direction: column;
+ border-left: 1px solid var(--color-landing-line);
+}
+
+.changelog-toc-list a {
+ display: block;
+ padding: 5px 0 5px 14px;
+ color: var(--color-landing-muted);
+ font-size: 13px;
+ transition: color 0.15s ease;
+}
+
+.changelog-toc-list a:hover {
+ color: var(--color-landing-ink);
+}
+
+/* Release body markdown */
+
+.changelog-markdown {
+ color: #bcc1c9;
+ font-size: 15px;
+ line-height: 1.72;
+}
+
+.changelog-markdown h2,
+.changelog-markdown h3 {
+ color: #ededf0;
+ font-weight: 720;
+ scroll-margin-top: 112px;
+}
+
+.changelog-markdown h2 {
+ margin: 48px 0 18px;
+ font-size: 24px;
}
-.changelog-release > .changelog-release-body {
- display: block !important;
+.changelog-markdown h3 {
+ margin: 44px 0 16px;
+ font-size: 20px;
+}
+
+.changelog-markdown h2:first-child,
+.changelog-markdown h3:first-child {
+ margin-top: 0;
+}
+
+.changelog-markdown ul {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.changelog-markdown li {
+ position: relative;
+ padding-left: 19px;
+}
+
+.changelog-markdown li::before {
+ content: "";
+ position: absolute;
+ top: 0.66em;
+ left: 0;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #52525b;
+}
+
+.changelog-markdown strong {
+ color: #e4e7ea;
+ font-weight: 660;
+}
+
+.changelog-markdown a {
+ color: var(--color-landing-blue);
+ text-decoration: none;
+ border-bottom: 1px solid rgba(110, 168, 255, 0.35);
+ transition: border-color 0.15s ease;
+}
+
+.changelog-markdown a:hover {
+ border-bottom-color: rgba(110, 168, 255, 0.75);
+}
+
+.changelog-markdown code {
+ padding: 2px 6px;
+ border-radius: 5px;
+ background: rgba(255, 255, 255, 0.07);
+ color: #e4e7ea;
+ font-size: 0.88em;
+}
+
+.changelog-markdown pre {
+ margin: 14px 0;
+ padding: 14px 16px;
+ border: 1px solid var(--color-landing-line);
+ border-radius: 10px;
+ background: rgba(13, 14, 17, 0.9);
+ overflow-x: auto;
+}
+
+.changelog-markdown pre code {
+ padding: 0;
+ background: none;
+}
+
+.changelog-markdown p {
+ margin: 12px 0;
+}
+
+.changelog-markdown hr {
+ margin: 28px 0;
+ border: 0;
+ border-top: 1px solid var(--color-landing-line);
+}
+
+.changelog-markdown table {
+ width: 100%;
+ margin: 16px 0;
+ border-collapse: collapse;
+ font-size: 14px;
+}
+
+.changelog-markdown th,
+.changelog-markdown td {
+ padding: 8px 12px;
+ border: 1px solid var(--color-landing-line);
+ text-align: left;
+}
+
+.changelog-markdown th {
+ color: #e4e7ea;
+ background: rgba(255, 255, 255, 0.03);
+}
+
+.changelog-markdown img {
+ max-width: 100%;
+ border: 1px solid var(--color-landing-line);
+ border-radius: 10px;
}
/* Responsive */
@@ -1200,6 +1446,15 @@ a {
.landing-workflow-card:nth-child(-n + 2) {
border-bottom: 1px solid var(--color-landing-line);
}
+
+ .changelog-shell {
+ grid-template-columns: 200px minmax(0, 1fr);
+ gap: 32px;
+ }
+
+ .changelog-sidebar-right {
+ display: none;
+ }
}
@media (max-width: 760px) {
@@ -1339,20 +1594,59 @@ a {
outline-offset: 2px;
}
- .changelog-release-summary {
- display: flex;
+ .changelog-shell {
+ display: block;
}
- .changelog-release:not([open]) > .changelog-release-body {
- display: none !important;
+ .changelog-sidebar,
+ .changelog-sidebar-left {
+ position: static;
+ }
+
+ .changelog-sidebar-title {
+ display: none;
+ }
+
+ .changelog-version-list {
+ flex-direction: row;
+ gap: 8px;
+ max-height: none;
+ margin: 0 -18px 6px;
+ padding: 0 18px 10px;
+ overflow-x: auto;
+ overscroll-behavior-inline: contain;
+ scrollbar-width: none;
}
- .changelog-release[open] .changelog-release-chevron {
- transform: rotate(180deg);
+ .changelog-version-list::-webkit-scrollbar {
+ display: none;
+ }
+
+ .changelog-version-link {
+ flex: 0 0 auto;
+ padding: 7px 14px;
+ border-color: var(--color-landing-line);
+ border-radius: 999px;
+ font-size: 13px;
+ }
+
+ .changelog-markdown {
+ font-size: 14px;
+ line-height: 1.66;
}
- .changelog-release-chevron {
- transition: transform 0.18s ease;
+ .changelog-markdown h2 {
+ margin: 34px 0 14px;
+ font-size: 20px;
+ }
+
+ .changelog-markdown h3 {
+ margin: 30px 0 13px;
+ font-size: 17px;
+ }
+
+ .changelog-markdown ul {
+ gap: 10px;
}
}
diff --git a/docs/components/RouteProgress.tsx b/docs/components/RouteProgress.tsx
new file mode 100644
index 0000000000..71f1070d02
--- /dev/null
+++ b/docs/components/RouteProgress.tsx
@@ -0,0 +1,106 @@
+"use client";
+
+import { usePathname } from "next/navigation";
+import { useEffect, useRef } from "react";
+
+type ProgressApi = { start: () => void; done: () => void };
+
+// nprogress 风格的路由跳转进度条:捕获站内链接点击或前进/后退时开始,
+// App Router 的 pathname 变化(导航完成)时冲到 100% 并淡出。
+// 全程命令式操作 DOM,不触发 React 渲染。
+export function RouteProgress() {
+ const pathname = usePathname();
+ const barRef = useRef<HTMLDivElement>(null);
+ const apiRef = useRef<ProgressApi | null>(null);
+ const isFirstRoute = useRef(true);
+
+ useEffect(() => {
+ const bar = barRef.current;
+ if (!bar) return;
+
+ let shown = false;
+ let progress = 0;
+ let trickleTimer = 0;
+ let hideTimer = 0;
+
+ const render = () => {
+ bar.style.transform = `scaleX(${progress})`;
+ bar.style.opacity = shown ? "1" : "0";
+ };
+
+ const start = () => {
+ if (shown) return;
+ shown = true;
+ progress = 0.08;
+ render();
+ window.clearInterval(trickleTimer);
+ trickleTimer = window.setInterval(() => {
+ // 越接近 90% 走得越慢,nprogress 的经典节奏
+ progress += (0.9 - progress) * 0.14;
+ render();
+ }, 120);
+ // 导航异常(目标不可达等)时兜底收尾,避免进度条卡在 90%
+ window.clearTimeout(hideTimer);
+ hideTimer = window.setTimeout(done, 6000);
+ };
+
+ const done = () => {
+ if (!shown) return;
+ window.clearInterval(trickleTimer);
+ window.clearTimeout(hideTimer);
+ progress = 1;
+ render();
+ hideTimer = window.setTimeout(() => {
+ shown = false;
+ render();
+ window.setTimeout(() => {
+ progress = 0;
+ bar.style.transform = "scaleX(0)";
+ }, 240);
+ }, 200);
+ };
+
+ apiRef.current = { start, done };
+
+ const isInternalNavigation = (href: string) => {
+ try {
+ const url = new URL(href, window.location.origin);
+ return url.origin === window.location.origin && (url.pathname !== window.location.pathname || url.search !== window.location.search);
+ } catch {
+ return false;
+ }
+ };
+
+ const onClick = (event: MouseEvent) => {
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
+ const anchor = (event.target as Element | null)?.closest?.("a[href]");
+ if (!anchor) return;
+ const href = anchor.getAttribute("href");
+ // 只处理站内路径跳转;纯 hash 锚点和外链不触发
+ if (!href || !href.startsWith("/") || href.startsWith("//")) return;
+ if (!isInternalNavigation(href)) return;
+ start();
+ };
+
+ const onPopState = () => start();
+
+ document.addEventListener("click", onClick, true);
+ window.addEventListener("popstate", onPopState);
+ return () => {
+ document.removeEventListener("click", onClick, true);
+ window.removeEventListener("popstate", onPopState);
+ window.clearInterval(trickleTimer);
+ window.clearTimeout(hideTimer);
+ };
+ }, []);
+
+ useEffect(() => {
+ if (isFirstRoute.current) {
+ isFirstRoute.current = false;
+ return;
+ }
+ apiRef.current?.done();
+ }, [pathname]);
+
+ return <div ref={barRef} className="route-progress-bar" aria-hidden="true" />;
+}
diff --git a/docs/components/aceternity/InfiniteMovingCards.tsx b/docs/components/aceternity/InfiniteMovingCards.tsx
index c4f8ea6688..49a1f13563 100644
--- a/docs/components/aceternity/InfiniteMovingCards.tsx
+++ b/docs/components/aceternity/InfiniteMovingCards.tsx
@@ -11,12 +11,24 @@ type InfiniteMovingCardsProps = {
speed?: "slow" | "normal";
};
+// 滚动一圈位移为半个 track(items.length × 卡片步距),
+// 按目标线速度反推 duration,保证不同条数的行视觉速度一致。
+// 36px/s 与首页数据库 pill 墙的最快行实测流速对齐。
+// track 必须 shrink-0,否则作为 flex 子项会被压回容器宽度,
+// -50% 位移随之下缩,实际线速度会远低于目标值。
+const CARD_PITCH_PX = 354; // 340px 卡片 + 14px 间距
+const SCROLL_SPEED_PX_PER_S = 36;
+
export function InfiniteMovingCards({ items, direction = "left", speed = "normal" }: InfiniteMovingCardsProps) {
const repeatedItems = [...items, ...items];
+ const durationSeconds = (items.length * CARD_PITCH_PX) / SCROLL_SPEED_PX_PER_S;
return (
<div className="landing-testimonial-marquee flex overflow-hidden" data-direction={direction} data-speed={speed} aria-label="Testimonials" tabIndex={0}>
- <div className="landing-testimonial-track flex w-max min-w-full gap-3.5 px-[7px]">
+ <div
+ className="landing-testimonial-track flex w-max min-w-full shrink-0 gap-3.5 px-[7px]"
+ style={{ "--testimonial-duration": `${durationSeconds}s` } as React.CSSProperties}
+ >
{repeatedItems.map((item, index) => (
<figure aria-hidden={index >= items.length} className="landing-testimonial-card flex-[0_0_340px] min-h-[188px] rounded-[9px] m-0 p-[22px] max-[760px]:flex-[0_0_286px] max-[760px]:min-h-[210px] max-[760px]:p-[18px]" key={`${item.name}-${index}`}>
<div className="flex gap-3 items-center">
diff --git a/docs/components/landing/ChangelogList.tsx b/docs/components/landing/ChangelogList.tsx
index 70f626df3b..81bfefac78 100644
--- a/docs/components/landing/ChangelogList.tsx
+++ b/docs/components/landing/ChangelogList.tsx
@@ -1,26 +1,8 @@
"use client";
-import { useState, useEffect, useRef, useSyncExternalStore } from "react";
-import type { ChangelogRelease } from "@/lib/changelog";
-import { ChevronDown, Tag } from "lucide-react";
-
-const PAGE_SIZE = 5;
-
-const DESKTOP_MEDIA = "(min-width: 761px)";
-
-function subscribeToDesktop(onChange: () => void) {
- const mql = window.matchMedia(DESKTOP_MEDIA);
- mql.addEventListener("change", onChange);
- return () => mql.removeEventListener("change", onChange);
-}
-
-function getDesktopSnapshot() {
- return window.matchMedia(DESKTOP_MEDIA).matches;
-}
-
-function getDesktopServerSnapshot() {
- return false;
-}
+import { marked, Renderer } from "marked";
+import type { ChangelogIndexEntry, ChangelogRelease } from "@/lib/changelog";
+import { Tag } from "lucide-react";
const sectionLabels: Record<string, Record<string, string>> = {
added: { en: "New Features", cn: "新功能" },
@@ -30,107 +12,201 @@ const sectionLabels: Record<string, Record<string, string>> = {
removed: { en: "Removed", cn: "移除" },
};
+// 与 .github/scripts/sync-changelog.mjs 的 SECTION_MAP 保持一致,
+// TOC 文案优先用本地化标签,未知标题原样展示。
+const sectionTypeByTitle: Record<string, string> = {
+ 新功能: "added",
+ Added: "added",
+ 改进: "improved",
+ Improved: "improved",
+ 修复: "fixed",
+ Fixed: "fixed",
+ 变更: "changed",
+ Changed: "changed",
+ 移除: "removed",
+ Removed: "removed",
+};
+
function formatDate(dateStr: string, lang: string) {
- const d = new Date(dateStr);
+ const date = new Date(dateStr);
if (lang === "cn") {
- return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
+ return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
+ }
+ return date.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
+}
+
+function releaseId(tag: string) {
+ return `changelog-release-${tag.replace(/[^a-zA-Z0-9-]/g, "-")}`;
+}
+
+function sectionId(tag: string, sectionIndex: number) {
+ return `${releaseId(tag)}-section-${sectionIndex}`;
+}
+
+function releaseToMarkdown(release: ChangelogRelease) {
+ return release.sections
+ .map((section) => {
+ const items = section.items.map((item) => (item.desc ? `- **${item.title}** — ${item.desc}` : `- ${item.title}`)).join("\n");
+ return `### ${section.title}\n${items}`;
+ })
+ .join("\n\n");
+}
+
+// 官网展示用:剥掉条目行尾的贡献/来源标注括号段,让页面更纯净,
+// 如 “(contributed by @user) (PR [#123](…)) (commit [sha](…)) (closes #456)”。
+// 括号段内可能嵌套 markdown 链接,需按配对括号从行尾向前定位段首;
+// 普通内容括号(如 “(默认关闭)”)不含这些特征词,不会被误伤。
+const ATTRIBUTION_HINT = /contributed by|\b(?:PR|closes|refs|fixes)\b|^commit\b|@[\w.-]+|^#\d/i;
+
+function stripTrailingAttribution(line: string) {
+ let out = line.trimEnd();
+ for (;;) {
+ if (!out.endsWith(")")) break;
+ let depth = 0;
+ let start = -1;
+ for (let i = out.length - 1; i >= 0; i--) {
+ if (out[i] === ")") depth++;
+ else if (out[i] === "(" && --depth === 0) {
+ start = i;
+ break;
+ }
+ }
+ if (start < 1 || !ATTRIBUTION_HINT.test(out.slice(start + 1, -1))) break;
+ out = out.slice(0, start).trimEnd();
}
- return d.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
+ // 整条 desc 都是标注时避免留下悬空的破折号;横线分隔线不受影响
+ return out.replace(/[ \t]*[—–]$/, "");
}
-function ReleaseCard({ release, lang, featured, expanded }: { release: ChangelogRelease; lang: string; featured: boolean; expanded: boolean }) {
- const t = lang === "cn" ? { publishedOn: "发布于", download: "下载", seeGitHub: "查看 GitHub Release 获取详情" } : { publishedOn: "Published on", download: "Download", seeGitHub: "See GitHub Release for details" };
+function releaseDisplayMarkdown(release: ChangelogRelease) {
+ return (release.markdown || releaseToMarkdown(release))
+ .split("\n")
+ .map(stripTrailingAttribution)
+ .join("\n");
+}
+
+function escapeHtml(value: string) {
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
+}
+
+function renderMarkdown(release: ChangelogRelease) {
+ const renderer = new Renderer();
+ let headingIndex = 0;
+
+ renderer.heading = ({ tokens, depth }) => {
+ const text = renderer.parser.parseInline(tokens);
+ const id = depth === 3 ? ` id="${sectionId(release.tag, headingIndex++)}"` : "";
+ return `<h${depth}${id}>${text}</h${depth}>`;
+ };
+ renderer.html = ({ text }) => escapeHtml(text);
+
+ return marked.parse(releaseDisplayMarkdown(release), { gfm: true, renderer }) as string;
+}
+
+// TOC 必须与 renderMarkdown 数的是同一批 h3(跳过代码围栏里的 "### "),
+// 否则 parseBody 过滤掉无条目小节后,锚点序号会整体错位。
+function buildTocEntries(release: ChangelogRelease, lang: string) {
+ const markdown = releaseDisplayMarkdown(release);
+ const titles: string[] = [];
+ let inFence = false;
+
+ for (const line of markdown.split("\n")) {
+ if (/^\s*(```|~~~)/.test(line)) {
+ inFence = !inFence;
+ continue;
+ }
+ if (inFence) continue;
+
+ const headingMatch = line.match(/^###\s+(.+)/);
+ if (headingMatch) titles.push(headingMatch[1].trim());
+ }
+
+ return titles.map((title, index) => ({
+ id: sectionId(release.tag, index),
+ label: sectionLabels[sectionTypeByTitle[title] ?? ""]?.[lang] || title,
+ }));
+}
+
+function ReleaseCard({ release, lang, isLoading, errorMessage }: { release: ChangelogRelease | null; lang: "en" | "cn"; isLoading: boolean; errorMessage?: string }) {
+ const text = lang === "cn" ? { publishedOn: "发布于", download: "下载", seeGitHub: "查看 GitHub Release 获取详情" } : { publishedOn: "Published on", download: "Download", seeGitHub: "See GitHub Release for details" };
+
+ if (!release) {
+ return (
+ <section className="changelog-release changelog-release-loading" aria-busy="true">
+ <div className="changelog-loading-inner">
+ <span>{errorMessage || (isLoading ? (lang === "cn" ? "正在加载版本…" : "Loading release…") : text.seeGitHub)}</span>
+ </div>
+ </section>
+ );
+ }
return (
- <details className="changelog-release border-t border-[rgba(173,176,182,0.18)]" open={featured || expanded || undefined}>
- <summary className="changelog-release-summary min-h-[72px] cursor-pointer list-none items-center justify-between gap-4 py-4 text-[#e4e7ea]">
- <span className="min-w-0">
- <strong className="block truncate text-[17px] font-[720]">Release {release.tag}</strong>
- <span className="mt-1 block text-xs text-[#71717a]">{formatDate(release.date, lang)}</span>
- </span>
- <ChevronDown className="changelog-release-chevron shrink-0 text-[#6ea8ff]" size={18} />
- </summary>
+ // 用 section 而非 article:docs 的 article 排版规则是浅色主题,
+ // 会把这里的链接/行内代码染黑。
+ <section id={releaseId(release.tag)} className="changelog-release">
<div className="changelog-release-body py-12 max-[760px]:py-8">
<div className="flex items-center justify-between gap-4 mb-8 max-[760px]:items-start max-[760px]:flex-wrap max-[760px]:mb-6">
<div className="flex items-center gap-4 max-[760px]:flex-wrap max-[760px]:gap-2.5">
<span className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-full border border-[rgba(173,176,182,0.25)] text-sm font-semibold text-[#e4e7ea]">
<Tag size={13} className="text-[#6ea8ff]" />
- {release.tag.replace("v", "")}
+ {release.tag.replace(/^v/, "")}
</span>
<span className="text-[15px] text-[#71717a] max-[760px]:text-[13px]">
- {t.publishedOn} {formatDate(release.date, lang)}
+ {text.publishedOn} {formatDate(release.date, lang)}
</span>
</div>
- <a href={`https://github.com/t8y2/dbx/releases/tag/${release.tag}`} target="_blank" rel="noopener noreferrer" className="flex min-h-11 items-center gap-1.5 px-4 rounded-full border border-[rgba(173,176,182,0.25)] text-sm text-[#e4e7ea] hover:border-[rgba(173,176,182,0.4)] transition-colors">
- {t.download}
- <ChevronDown size={14} />
+ <a href={`https://github.com/t8y2/dbx/releases/tag/${release.tag}`} target="_blank" rel="noopener noreferrer" className="flex min-h-9 items-center px-4 rounded-full border border-[rgba(173,176,182,0.25)] text-sm text-[#e4e7ea] hover:border-[rgba(173,176,182,0.4)] transition-colors">
+ {text.download}
</a>
</div>
- <h2 className="text-[28px] font-[720] text-[#ededf0] mb-10 max-[760px]:text-2xl max-[760px]:mb-7">Release {release.tag}</h2>
-
- {release.sections.map((section, sectionIndex) => (
- <div key={sectionIndex} className={sectionIndex > 0 ? "mt-10 max-[760px]:mt-8" : ""}>
- <h3 className="text-xl font-bold text-[#ededf0] mb-5 max-[760px]:text-lg max-[760px]:mb-4">{sectionLabels[section.type]?.[lang] || section.title}</h3>
- <ul className="space-y-3">
- {section.items.map((item, itemIndex) => (
- <li key={itemIndex} className="flex gap-3 text-[15px] leading-relaxed text-[#bcc1c9] max-[760px]:text-sm">
- <span className="mt-2 w-1.5 h-1.5 rounded-full bg-[#52525b] shrink-0" />
- <span>
- {item.desc ? (
- <>
- {item.title},{item.desc}
- </>
- ) : (
- item.title
- )}
- </span>
- </li>
- ))}
- </ul>
- </div>
- ))}
-
- {release.sections.length === 0 && <p className="text-[15px] text-[#71717a] italic">{t.seeGitHub}</p>}
+ <div className="changelog-markdown" dangerouslySetInnerHTML={{ __html: renderMarkdown(release) }} />
</div>
- </details>
+ </section>
);
}
-export function ChangelogList({ releases, lang }: { releases: ChangelogRelease[]; lang: string }) {
- const [count, setCount] = useState(PAGE_SIZE);
- const sentinelRef = useRef<HTMLDivElement>(null);
- const isDesktop = useSyncExternalStore(subscribeToDesktop, getDesktopSnapshot, getDesktopServerSnapshot);
- const visible = releases.slice(0, count);
- const hasMore = count < releases.length;
-
- useEffect(() => {
- const node = sentinelRef.current;
- if (!node || !hasMore) return;
-
- const observer = new IntersectionObserver(
- ([entry]) => {
- if (entry.isIntersecting) {
- setCount((c) => Math.min(c + PAGE_SIZE, releases.length));
- }
- },
- { rootMargin: "200px" },
- );
-
- observer.observe(node);
- return () => observer.disconnect();
- }, [count, hasMore, releases.length]);
+export function ChangelogList({ releaseIndex, selectedTag, release, lang, isLoading, errorMessage, onSelectRelease }: { releaseIndex: ChangelogIndexEntry[]; selectedTag: string; release: ChangelogRelease | null; lang: "en" | "cn"; isLoading: boolean; errorMessage?: string; onSelectRelease: (tag: string) => void }) {
+ const activeTag = release?.tag || selectedTag || releaseIndex[0]?.tag;
+ const tocEntries = release ? buildTocEntries(release, lang) : [];
return (
- <>
- {visible.map((release, index) => (
- <ReleaseCard key={release.tag} release={release} lang={lang} featured={index === 0} expanded={isDesktop} />
- ))}
- {hasMore && (
- <div ref={sentinelRef} className="flex justify-center py-12 text-[#71717a] text-sm">
- {lang === "cn" ? "加载更多版本…" : "Loading more versions…"}
+ <div className="changelog-shell">
+ <aside className="changelog-sidebar changelog-sidebar-left" aria-label={lang === "cn" ? "版本列表" : "Release list"}>
+ <div className="changelog-sidebar-inner">
+ <div className="changelog-sidebar-title">
+ <Tag size={18} strokeWidth={1.8} />
+ <span>{lang === "cn" ? "版本列表" : "Versions"}</span>
+ </div>
+ <nav className="changelog-version-list">
+ {releaseIndex.map((entry) => (
+ <button key={entry.tag} type="button" className={`changelog-version-link${entry.tag === selectedTag ? " is-active" : ""}`} onClick={() => onSelectRelease(entry.tag)} aria-current={entry.tag === selectedTag ? "page" : undefined}>
+ <span>{entry.tag}</span>
+ </button>
+ ))}
+ </nav>
</div>
+ </aside>
+
+ <section className="changelog-content" aria-label={lang === "cn" ? "更新日志内容" : "Changelog content"}>
+ <ReleaseCard release={release} lang={lang} isLoading={isLoading} errorMessage={errorMessage} />
+ </section>
+
+ {release && tocEntries.length > 0 && (
+ <aside className="changelog-sidebar changelog-sidebar-right" aria-label={lang === "cn" ? "当前版本目录" : "Current release contents"}>
+ <div className="changelog-sidebar-inner">
+ <p className="changelog-toc-title">{lang === "cn" ? `在 ${activeTag} 中` : `In ${activeTag}`}</p>
+ <p className="changelog-toc-subtitle">{lang === "cn" ? "更新内容" : "Release contents"}</p>
+ <nav className="changelog-toc-list">
+ {tocEntries.map((entry) => (
+ <a key={entry.id} href={`#${entry.id}`}>
+ {entry.label}
+ </a>
+ ))}
+ </nav>
+ </div>
+ </aside>
)}
- </>
+ </div>
);
}
diff --git a/docs/components/landing/ChangelogRuntime.tsx b/docs/components/landing/ChangelogRuntime.tsx
index 6b045fda51..07d8f9517b 100644
--- a/docs/components/landing/ChangelogRuntime.tsx
+++ b/docs/components/landing/ChangelogRuntime.tsx
@@ -1,26 +1,108 @@
"use client";
+import { useCallback, useEffect, useRef, useState } from "react";
import { ChangelogList } from "@/components/landing/ChangelogList";
-import type { ChangelogRelease } from "@/lib/changelog";
+import { changelogReleaseUrl, type ChangelogIndexEntry, type ChangelogRelease } from "@/lib/changelog";
+import { requestJson } from "@/lib/httpJson";
type ChangelogRuntimeProps = {
lang: "en" | "cn";
- initialReleases?: ChangelogRelease[];
+ index: ChangelogIndexEntry[];
+ initialRelease: ChangelogRelease | null;
+ fallbackReleases?: ChangelogRelease[] | null;
};
const text = {
en: {
empty: "No releases found.",
+ loadError: "Failed to load this release. Please retry or check GitHub Releases.",
},
cn: {
empty: "暂无版本记录。",
+ loadError: "该版本加载失败,请稍后重试或前往 GitHub Releases 查看。",
},
};
-export function ChangelogRuntime({ lang, initialReleases = [] }: ChangelogRuntimeProps) {
- if (initialReleases.length === 0) {
+export function ChangelogRuntime({ lang, index, initialRelease, fallbackReleases = null }: ChangelogRuntimeProps) {
+ const [selectedTag, setSelectedTag] = useState(initialRelease?.tag ?? index[0]?.tag ?? "");
+ const [release, setRelease] = useState<ChangelogRelease | null>(initialRelease);
+ const [isLoading, setIsLoading] = useState(false);
+ const [errorMessage, setErrorMessage] = useState<string>();
+ // tag -> 已加载的版本详情;SSR 注入的首个版本与全量兜底数据都放进同一缓存。
+ const releaseCacheRef = useRef<Map<string, ChangelogRelease>>(new Map());
+ const cache = releaseCacheRef.current;
+
+ if (initialRelease && !cache.has(initialRelease.tag)) {
+ cache.set(initialRelease.tag, initialRelease);
+ }
+ for (const fallback of fallbackReleases ?? []) {
+ if (!cache.has(fallback.tag)) cache.set(fallback.tag, fallback);
+ }
+
+ useEffect(() => {
+ if (!selectedTag) return;
+
+ const cached = cache.get(selectedTag);
+ if (cached) {
+ setRelease(cached);
+ setErrorMessage(undefined);
+ setIsLoading(false);
+ return;
+ }
+
+ let cancelled = false;
+ setIsLoading(true);
+ setErrorMessage(undefined);
+ setRelease(null);
+
+ requestJson<ChangelogRelease>(changelogReleaseUrl(lang, selectedTag))
+ .then((data) => {
+ if (cancelled) return;
+ cache.set(selectedTag, data);
+ setRelease(data);
+ })
+ .catch(() => {
+ if (cancelled) return;
+ setErrorMessage(text[lang].loadError);
+ })
+ .finally(() => {
+ if (!cancelled) setIsLoading(false);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [selectedTag, lang, cache]);
+
+ if (index.length === 0) {
return <p className="text-landing-muted py-12">{text[lang].empty}</p>;
}
- return <ChangelogList releases={initialReleases} lang={lang} />;
+ // 切换版本后把视口拉回该版本内容顶部;否则会停留在上一个版本的滚动位置,
+ // 右侧目录锚点看起来就像没有对上。
+ const selectRelease = useCallback(
+ (tag: string) => {
+ setSelectedTag(tag);
+ if (typeof document === "undefined") return;
+ const content = document.querySelector(".changelog-content");
+ if (!content) return;
+ const top = content.getBoundingClientRect().top + window.scrollY - 96;
+ if (Math.abs(top - window.scrollY) > 8) {
+ window.scrollTo({ top: Math.max(top, 0), behavior: "smooth" });
+ }
+ },
+ [],
+ );
+
+ return (
+ <ChangelogList
+ releaseIndex={index}
+ selectedTag={selectedTag}
+ release={release}
+ lang={lang}
+ isLoading={isLoading}
+ errorMessage={errorMessage}
+ onSelectRelease={selectRelease}
+ />
+ );
}
diff --git a/docs/lib/changelog.test.ts b/docs/lib/changelog.test.ts
index 206297303b..c7e67b10cf 100644
--- a/docs/lib/changelog.test.ts
+++ b/docs/lib/changelog.test.ts
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { afterEach, test, vi } from "vitest";
-import { fetchChangelog } from "./changelog";
+import { changelogIndexUrl, changelogReleaseUrl, changelogUrl, fetchChangelog, loadChangelogBootstrap } from "./changelog";
import { isAppReleaseTag } from "./releaseTags";
afterEach(() => {
@@ -16,6 +16,12 @@ test("recognizes only DBX app release tags", () => {
assert.equal(isAppReleaseTag("v0.5.x"), false);
});
+test("builds index and per-release URLs under the changelog base", () => {
+ assert.equal(changelogUrl("cn"), "https://dl.dbxio.com/changelog/releases-cn.json");
+ assert.equal(changelogIndexUrl("en"), "https://dl.dbxio.com/changelog/index-en.json");
+ assert.equal(changelogReleaseUrl("cn", "v1.2.3"), "https://dl.dbxio.com/changelog/releases-cn/v1.2.3.json");
+});
+
test("changelog build fails without falling back to GitHub API", async () => {
const requestedUrls = [];
vi.stubGlobal(
@@ -29,3 +35,65 @@ test("changelog build fails without falling back to GitHub API", async () => {
await assert.rejects(fetchChangelog("cn"), /Request failed with status 503/);
assert.deepEqual(requestedUrls, ["https://dl.dbxio.com/changelog/releases-cn.json"]);
});
+
+function jsonResponse(body: unknown, status = 200) {
+ return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
+}
+
+test("bootstrap prefers the index and per-release files when published", async () => {
+ const requestedUrls: string[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input) => {
+ const url = String(input);
+ requestedUrls.push(url);
+ if (url.endsWith("/index-cn.json")) {
+ return jsonResponse({ updatedAt: "2026-08-26T00:00:00Z", releases: [{ tag: "v1.0.0", name: "v1.0.0", date: "2026-08-20" }] });
+ }
+ if (url.endsWith("/releases-cn/v1.0.0.json")) {
+ return jsonResponse({ tag: "v1.0.0", name: "v1.0.0", date: "2026-08-20", markdown: "### 新功能\n- **A** — B", sections: [] });
+ }
+ return jsonResponse({}, 404);
+ }),
+ );
+
+ const bootstrap = await loadChangelogBootstrap("cn");
+ assert.deepEqual(bootstrap.index, [{ tag: "v1.0.0", name: "v1.0.0", date: "2026-08-20" }]);
+ assert.equal(bootstrap.initialRelease?.tag, "v1.0.0");
+ assert.equal(bootstrap.initialRelease?.markdown, "### 新功能\n- **A** — B");
+ assert.equal(bootstrap.fallbackReleases, null);
+ assert.deepEqual(requestedUrls, ["https://dl.dbxio.com/changelog/index-cn.json", "https://dl.dbxio.com/changelog/releases-cn/v1.0.0.json"]);
+});
+
+test("bootstrap falls back to the full listing while index files are unpublished", async () => {
+ const requestedUrls: string[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input) => {
+ const url = String(input);
+ requestedUrls.push(url);
+ if (url.endsWith("/index-cn.json")) {
+ return jsonResponse({}, 404);
+ }
+ if (url.endsWith("/releases-cn.json")) {
+ return jsonResponse({
+ updatedAt: "2026-08-26T00:00:00Z",
+ releases: [
+ { tag: "v1.0.0", name: "v1.0.0", date: "2026-08-20", sections: [] },
+ { tag: "v0.9.0", name: "v0.9.0", date: "2026-08-01", sections: [] },
+ ],
+ });
+ }
+ return jsonResponse({}, 404);
+ }),
+ );
+
+ const bootstrap = await loadChangelogBootstrap("cn");
+ assert.deepEqual(bootstrap.index, [
+ { tag: "v1.0.0", name: "v1.0.0", date: "2026-08-20" },
+ { tag: "v0.9.0", name: "v0.9.0", date: "2026-08-01" },
+ ]);
+ assert.equal(bootstrap.initialRelease?.tag, "v1.0.0");
+ assert.equal(bootstrap.fallbackReleases?.length, 2);
+ assert.deepEqual(requestedUrls, ["https://dl.dbxio.com/changelog/index-cn.json", "https://dl.dbxio.com/changelog/releases-cn.json"]);
+});
diff --git a/docs/lib/changelog.ts b/docs/lib/changelog.ts
index b7ebe5a504..fa71b787be 100644
--- a/docs/lib/changelog.ts
+++ b/docs/lib/changelog.ts
@@ -15,6 +15,7 @@ export type ChangelogRelease = {
tag: string;
name: string;
date: string;
+ markdown?: string;
sections: ChangelogSection[];
};
@@ -23,14 +24,70 @@ export type ChangelogData = {
releases: ChangelogRelease[];
};
+export type ChangelogIndexEntry = {
+ tag: string;
+ name: string;
+ date: string;
+};
+
+export type ChangelogIndex = {
+ updatedAt: string;
+ releases: ChangelogIndexEntry[];
+};
+
+export type ChangelogBootstrap = {
+ index: ChangelogIndexEntry[];
+ initialRelease: ChangelogRelease | null;
+ // index-cn.json 与 releases-cn/ 尚未发布到 R2 时,退回全量 releases JSON,
+ // 并把全量数据交给客户端按需取用,避免逐版本请求 404。
+ fallbackReleases: ChangelogRelease[] | null;
+};
+
const DEFAULT_BASE_URL = "https://dl.dbxio.com/changelog";
+function changelogBaseUrl() {
+ return (typeof process !== "undefined" && (process.env.NEXT_PUBLIC_CHANGELOG_BASE_URL || process.env.CHANGELOG_BASE_URL)) || DEFAULT_BASE_URL;
+}
+
export function changelogUrl(lang: "en" | "cn") {
- const baseUrl = (typeof process !== "undefined" && (process.env.NEXT_PUBLIC_CHANGELOG_BASE_URL || process.env.CHANGELOG_BASE_URL)) || DEFAULT_BASE_URL;
+ return `${changelogBaseUrl()}/releases-${lang}.json`;
+}
+
+export function changelogIndexUrl(lang: "en" | "cn") {
+ return `${changelogBaseUrl()}/index-${lang}.json`;
+}
- return `${baseUrl}/releases-${lang}.json`;
+export function changelogReleaseUrl(lang: "en" | "cn", tag: string) {
+ return `${changelogBaseUrl()}/releases-${lang}/${tag}.json`;
}
export async function fetchChangelog(lang: "en" | "cn"): Promise<ChangelogData> {
return requestJson<ChangelogData>(changelogUrl(lang), { cache: "force-cache" });
}
+
+export async function fetchChangelogIndex(lang: "en" | "cn"): Promise<ChangelogIndex> {
+ return requestJson<ChangelogIndex>(changelogIndexUrl(lang), { cache: "force-cache" });
+}
+
+export async function fetchChangelogRelease(lang: "en" | "cn", tag: string): Promise<ChangelogRelease> {
+ return requestJson<ChangelogRelease>(changelogReleaseUrl(lang, tag), { cache: "force-cache" });
+}
+
+export async function loadChangelogBootstrap(lang: "en" | "cn"): Promise<ChangelogBootstrap> {
+ try {
+ const index = await fetchChangelogIndex(lang);
+ if (index.releases.length > 0) {
+ const initialRelease = await fetchChangelogRelease(lang, index.releases[0].tag);
+ return { index: index.releases, initialRelease, fallbackReleases: null };
+ }
+ } catch {
+ // fall through to the full listing
+ }
+
+ const full = await fetchChangelog(lang);
+ return {
+ index: full.releases.map(({ tag, name, date }) => ({ tag, name, date })),
+ initialRelease: full.releases[0] ?? null,
+ fallbackReleases: full.releases,
+ };
+}
diff --git a/docs/package.json b/docs/package.json
index 2fbe17483a..793c111288 100644
--- a/docs/package.json
+++ b/docs/package.json
@@ -22,6 +22,7 @@
"fumadocs-mdx": "^14.3.2",
"fumadocs-ui": "^16.8.7",
"lucide-react": "^0.515.0",
+ "marked": "18.0.4",
"next": "^16.3.0",
"postcss": "^8.5.26",
"react": "^19.2.5",
diff --git a/docs/pnpm-lock.yaml b/docs/pnpm-lock.yaml
index f6733e7804..aec821b95e 100644
--- a/docs/pnpm-lock.yaml
+++ b/docs/pnpm-lock.yaml
@@ -5,9 +5,7 @@ settings:
excludeLinksFromLockfile: false
patchedDependencies:
- hash: bc954c2c679c43ecf5351d4a9d68d9f36a9b8fb2dc4237fdbf57304cae4b0c04
- path: patches/[email protected]
+ [email protected]: bc954c2c679c43ecf5351d4a9d68d9f36a9b8fb2dc4237fdbf57304cae4b0c04
importers:
@@ -40,6 +38,9 @@ importers:
lucide-react:
specifier: ^0.515.0
version: 0.515.0([email protected])
+ marked:
+ specifier: 18.0.4
+ version: 18.0.4
next:
specifier: ^16.3.0
@@ -289,89 +290,105 @@ packages:
resolution: {integrity: sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ==}
cpu: [arm]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw==}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w==}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA==}
engines: {node: '>=20.9.0'}
cpu: [arm]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA==}
engines: {node: '>=20.9.0'}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ==}
engines: {node: '>=20.9.0'}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw==}
engines: {node: '>=20.9.0'}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==}
@@ -439,24 +456,28 @@ packages:
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-tXXGKJw0m37O0eKJARVTX/TheKPhz0QFVtVVZXmOig+9YKLQOSP6hvf2pxv5DO7CLEJyTHx3Pg043CDQkv1G4Q==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-pjGxK5EY7yWml78ALejFkWmgHsU7wbFQrISiugpH6FbUJhgEvw3xFZ/EBAtLl7QtL0WdQKiG9eWJ3mOKGTukHw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-sjo++Xx+lomlPs3HRsHWhVDyGG6ms1kGW5EtHLERdII8AyG1i+f6aq68xHREO6AEMlhjTNEWBSmfJfqm9orf7g==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-C5JSgiO54wURdaxdEUIXqkz04uMqC9UmPX1gtDrV/5Tf1UowdWYI8uA5hfFbPolTlp0q4KZ60xlHePNibf0VIw==}
@@ -914,24 +935,28 @@ packages:
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-bBADEGAbo4ASnppIziaQJelekCxdMaxisrk+fB7Thit72IBnALp9K6ffA2G4ruj90G9XRS2VQ6q2bCKbfFV82g==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-7Mx25E4WTfnht0TVRTyC00j3i0M+EeFe7wguMDTlX4mRxafznw0CA8WJkFjWYH5BlgELd1kSjuU2JiPnNZbJDA==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-2wwJRF7nyhOR0hhHoChc04xngV3iS+akccHTGtz965FwF0up4b2lOdo6kI1EbDaEXKgvcrFBYcYQQ/rrnWFVfA==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-FQsqApeor8Fo6gUEklzmaa9994orJZZDBAlQpK2Mq+DslRKFJeD6AjHpBQ0kZFQohVr8o85PPh8eOy86VlSCmw==}
@@ -1387,24 +1412,28 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
@@ -1445,6 +1474,11 @@ packages:
resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}
+ resolution: {integrity: sha512-c/BTaKzg0G6ezQx97DAkYU7k0HM6ys0FqYeKBL6hlBByZwy+ycA1+f0vDdjMHKKeEjdgkx0GOv9Il6D+85cOqA==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==}
@@ -3205,6 +3239,8 @@ snapshots:
+
dependencies:
'@types/mdast': 4.0.4
diff --git a/docs/superpowers/plans/2026-07-16-field-mapping-dialog.md b/docs/superpowers/plans/2026-07-16-field-mapping-dialog.md
deleted file mode 100644
index 42b67c64f5..0000000000
--- a/docs/superpowers/plans/2026-07-16-field-mapping-dialog.md
+++ /dev/null
@@ -1,411 +0,0 @@
-# 字段类型映射独立弹窗 + JSON 导入/导出 实现计划
-
-> **面向 AI 代理的工作者:** 必需子技能:使用 superpowers:subagent-driven-development(推荐)或 superpowers:executing-plans 逐任务实现此计划。步骤使用复选框(`- [ ]`)语法来跟踪进度。
-
-**目标:** 在"比较架构"配置步骤的"选项"按钮后增加"字段类型映射"按钮,点击打开独立弹窗编辑映射(内部可滚动、底部操作栏始终可达),并支持映射配置的 JSON 导入/导出。
-
-**架构:** 新建 `FieldMappingDialog.vue` 复用 `SchemaDiffDialog` 已有的 overlay 弹窗模式;通过 `SchemaDiffConfigStep` 透传 `open-field-mapping` 事件到 `SchemaDiffDialog`;弹窗内持有本地副本(`editingMappings`),"完成"时 emit `save` 复用现有 `handleFieldMappingsUpdate` 写回 `activeConfig.options.fieldMappings`。导入/导出采用现有 `TagManagementPanel` 的 Blob 下载 + 隐藏 file input 模式。
-
-**技术栈:** Vue 3 `<script setup>` + TypeScript + Tailwind(shadcn-vue 风格)、`@lucide/vue` 图标、`vue-i18n`(`t()`)、`useToast` composable。无 Rust 变更。
-
----
-
-## 文件结构
-
-- 新建 `apps/desktop/src/components/diff/FieldMappingDialog.vue`
- - 职责:独立弹窗容器,渲染 `FieldMappingPanel` + 底部导入/导出/完成栏;持有 `editingMappings` 本地副本;实现 `handleExport` / `handleImport` / `onFileSelected`;深拷贝初始化。
-- 修改 `apps/desktop/src/components/diff/SchemaDiffConfigStep.vue`
- - 职责:在"选项"按钮后插入"字段类型映射"按钮,新增 `open-field-mapping` emit;保留内嵌 `FieldMappingPanel`。
-- 修改 `apps/desktop/src/components/diff/SchemaDiffDialog.vue`
- - 职责:新增 `showFieldMappingDialog` ref,挂载 `<FieldMappingDialog>` 并接线 `open` / `save` / `update:open`,传入 `sourceDbType` / `targetDbType`。
-- 修改 `apps/desktop/src/i18n/locales/zh-CN.ts`
- - 职责:在 `schemaDiff.fieldMapping` 对象内新增 `openFieldMapping` / `import` / `export` / `importError` / `done` 键。
-- 修改 `apps/desktop/src/i18n/locales/en.ts`
- - 职责:同上英文键。
-
----
-
-## 任务 1:新建 FieldMappingDialog.vue 容器与导入/导出
-
-**文件:**
-- 创建:`apps/desktop/src/components/diff/FieldMappingDialog.vue`
-
-- [ ] **步骤 1:编写组件(script + template + style)**
-
-完整内容如下(注意:`FieldMappingEntry` 来自 `@/types/schemaDiff`;`FieldMappingPanel` 已存在并可复用;`useToast` 提供 `toast(msg, duration?)`):
-
-```vue
-<script setup lang="ts">
-import { ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { Button } from "@/components/ui/button";
-import { Download, Upload, Check, X } from "@lucide/vue";
-import FieldMappingPanel from "@/components/diff/FieldMappingPanel.vue";
-import type { FieldMappingEntry } from "@/types/schemaDiff";
-import { useToast } from "@/composables/useToast";
-
-const props = defineProps<{
- open: boolean;
- mappings: FieldMappingEntry[];
- sourceDbType: string;
- targetDbType: string;
-}>();
-
-const emit = defineEmits<{
- (e: "update:open", value: boolean): void;
- (e: "save", value: FieldMappingEntry[]): void;
-}>();
-
-const { t } = useI18n();
-const toast = useToast();
-
-const editingMappings = ref<FieldMappingEntry[]>([]);
-const fileInputRef = ref<HTMLInputElement | null>(null);
-
-// 打开时深拷贝当前映射为本地副本(单向数据流,取消不写回)
-watch(
- () => props.open,
- (isOpen) => {
- if (isOpen) {
- editingMappings.value = props.mappings.map((m) => ({ ...m }));
- }
- },
- { immediate: true },
-);
-
-function handleUpdateMappings(v: FieldMappingEntry[]) {
- editingMappings.value = v;
-}
-
-function handleExport() {
- const blob = new Blob([JSON.stringify(editingMappings.value, null, 2)], {
- type: "application/json",
- });
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = "field-mappings.json";
- a.click();
- URL.revokeObjectURL(url);
-}
-
-function handleImportClick() {
- fileInputRef.value?.click();
-}
-
-function onFileSelected(event: Event) {
- const input = event.target as HTMLInputElement;
- const file = input.files?.[0];
- if (!file) return;
- const reader = new FileReader();
- reader.onload = () => {
- try {
- const parsed = JSON.parse(String(reader.result)) as unknown;
- if (!Array.isArray(parsed)) throw new Error("not an array");
- const normalized: FieldMappingEntry[] = parsed.map((item: any) => ({
- sourceType: String(item.sourceType ?? ""),
- targetType: String(item.targetType ?? ""),
- paramStrategy: item.paramStrategy === "strip" || item.paramStrategy === "custom" ? item.paramStrategy : "preserve",
- customParams: item.customParams ? String(item.customParams) : undefined,
- }));
- if (normalized.some((m) => !m.sourceType || !m.targetType)) {
- throw new Error("missing sourceType/targetType");
- }
- editingMappings.value = normalized;
- toast(t("diff.fieldMapping.importSuccess"), 2000);
- } catch {
- toast(t("diff.fieldMapping.importError"), 3000);
- } finally {
- input.value = "";
- }
- };
- reader.onerror = () => toast(t("diff.fieldMapping.importError"), 3000);
- reader.readAsText(file);
-}
-
-function handleDone() {
- emit("save", editingMappings.value.map((m) => ({ ...m })));
- emit("update:open", false);
-}
-
-function handleClose() {
- emit("update:open", false);
-}
-</script>
-
-<template>
- <div v-if="open" class="absolute inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center" @click.self="handleClose">
- <div class="bg-card border rounded-lg shadow-lg w-[760px] max-w-[calc(100vw-2rem)] max-h-[80vh] overflow-auto p-4">
- <div class="flex items-center justify-between mb-4">
- <h3 class="text-sm font-medium">{{ t("diff.fieldMapping.title") }}</h3>
- <Button variant="ghost" size="sm" @click="handleClose">
- <X class="w-3.5 h-3.5" />
- </Button>
- </div>
-
- <FieldMappingPanel
- :mappings="editingMappings"
- :source-db-type="sourceDbType"
- :target-db-type="targetDbType"
- @update:mappings="handleUpdateMappings"
- />
-
- <div class="flex items-center justify-between mt-4 pt-3 border-t">
- <div class="flex items-center gap-2">
- <Button variant="outline" size="sm" @click="handleImportClick">
- <Upload class="w-3.5 h-3.5 mr-1" />
- {{ t("diff.fieldMapping.import") }}
- </Button>
- <Button variant="outline" size="sm" @click="handleExport">
- <Download class="w-3.5 h-3.5 mr-1" />
- {{ t("diff.fieldMapping.export") }}
- </Button>
- </div>
- <Button size="sm" @click="handleDone">
- <Check class="w-3.5 h-3.5 mr-1" />
- {{ t("diff.fieldMapping.done") }}
- </Button>
- </div>
-
- <input ref="fileInputRef" type="file" accept=".json,application/json" class="hidden" @change="onFileSelected" />
- </div>
- </div>
-</template>
-```
-
-- [ ] **步骤 2:类型检查确认组件无错误**
-
-运行:`cd apps/desktop && pnpm vue-tsc --noEmit --project tsconfig.json`(或仓库根 `pnpm typecheck`)
-预期:该文件无 `FieldMappingDialog` 相关报错(已知 2 个与本次无关的预存错误:`dbAdminSql.ts` / `McpServerStatus.node_path`)。
-
-- [ ] **步骤 3:Commit**
-
-```bash
-git add apps/desktop/src/components/diff/FieldMappingDialog.vue
-git commit -m "feat(desktop): add FieldMappingDialog with JSON import/export"
-```
-
----
-
-## 任务 2:SchemaDiffConfigStep 增加"字段类型映射"按钮
-
-**文件:**
-- 修改:`apps/desktop/src/components/diff/SchemaDiffConfigStep.vue`
-
-- [ ] **步骤 1:在 defineEmits 中新增 open-field-mapping 事件**
-
-定位 `const emit = defineEmits<{ ... }>();` 块,在现有事件(如 `(e: "update:fieldMappings", value: FieldMappingEntry[]): void;`)之后新增一行:
-
-```ts
- (e: "open-field-mapping"): void;
-```
-
-- [ ] **步骤 2:在"选项"按钮后插入"字段类型映射"按钮**
-
-定位底部操作栏(约 468-488 行):
-
-```html
- <!-- Bottom Actions -->
- <div class="flex items-center justify-between pt-2">
- <div class="flex items-center gap-2">
- <Button variant="outline" size="sm" @click="$emit('saveConfig')">
- <Save class="w-3.5 h-3.5 mr-1" />
- {{ t("diff.saveConfig") }}
- </Button>
- <Button variant="outline" size="sm" @click="$emit('loadConfig')">
- <FolderOpen class="w-3.5 h-3.5 mr-1" />
- {{ t("diff.loadConfig") }}
- </Button>
- <Button variant="outline" size="sm" @click="$emit('showOptions')">
- <Settings class="w-3.5 h-3.5 mr-1" />
- {{ t("diff.options") }}
- </Button>
- </div>
-```
-
-在 `{{ t("diff.options") }}` 按钮的 `</Button>` 之后、`</div>` 之前,插入:
-
-```html
- <Button v-if="showFieldMapping" variant="outline" size="sm" @click="$emit('open-field-mapping')">
- <ArrowLeftRight class="w-3.5 h-3.5 mr-1" />
- {{ t("diff.openFieldMapping") }}
- </Button>
-```
-
-(注:`showFieldMapping` 已在 `<script>` 中定义为 `computed`,见 `SchemaDiffConfigStep.vue:66`。`ArrowLeftRight` 图标已在文件顶部 import。)
-
-- [ ] **步骤 3:类型检查**
-
-运行:`pnpm typecheck`
-预期:无新增该文件报错。
-
-- [ ] **步骤 4:Commit**
-
-```bash
-git add apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
-git commit -m "feat(desktop): add open-field-mapping button in config step"
-```
-
----
-
-## 任务 3:SchemaDiffDialog 挂载 FieldMappingDialog 并接线
-
-**文件:**
-- 修改:`apps/desktop/src/components/diff/SchemaDiffDialog.vue`
-
-- [ ] **步骤 1:导入组件与图标**
-
-在文件顶部 import 区(`SchemaDiffConfigStep` import 附近,约 11 行)新增:
-
-```ts
-import FieldMappingDialog from "@/components/diff/FieldMappingDialog.vue";
-```
-
-确认 `Download` / `Upload` / `Check` / `X` 不需要在此文件导入(`FieldMappingDialog` 内部已自带)。
-
-- [ ] **步骤 2:新增 ref 并接线到 SchemaDiffConfigStep**
-
-在 `showOptionsPanel` ref 定义附近(约 70 行 `const showOptionsPanel = ref(false);`)新增:
-
-```ts
-const showFieldMappingDialog = ref(false);
-```
-
-定位 `<SchemaDiffConfigStep ... >`(约 810-831 行),在其 `@update:field-mappings="handleFieldMappingsUpdate"` 之后新增一行:
-
-```html
- @open-field-mapping="showFieldMappingDialog = true"
-```
-
-- [ ] **步骤 3:渲染 FieldMappingDialog(放在 showOptionsPanel overlay 之后,约 1055 行 `</DialogContent>` 之前)**
-
-```html
- <!-- Field Mapping Dialog Overlay -->
- <FieldMappingDialog
- :open="showFieldMappingDialog"
- :mappings="activeConfig?.options.fieldMappings ?? []"
- :source-db-type="sourceDbType"
- :target-db-type="targetDbType"
- @update:open="showFieldMappingDialog = $event"
- @save="handleFieldMappingsUpdate"
- />
-```
-
-(注:`sourceDbType` / `targetDbType` 已在 `SchemaDiffDialog` 的 `<script>` 中计算,`handleFieldMappingsUpdate(mappings: FieldMappingEntry[])` 签名见 298 行,直接复用。)
-
-- [ ] **步骤 4:类型检查**
-
-运行:`pnpm typecheck`
-预期:无新增报错。
-
-- [ ] **步骤 5:Commit**
-
-```bash
-git add apps/desktop/src/components/diff/SchemaDiffDialog.vue
-git commit -m "feat(desktop): wire FieldMappingDialog into SchemaDiffDialog"
-```
-
----
-
-## 任务 4:i18n 新增键(zh-CN + en)
-
-**文件:**
-- 修改:`apps/desktop/src/i18n/locales/zh-CN.ts`
-- 修改:`apps/desktop/src/i18n/locales/en.ts`
-
-- [ ] **步骤 1:zh-CN 新增键**
-
-定位 `schemaDiff.fieldMapping` 对象(约 2444 行 `fieldMapping: {`)。在 `selectPreset: "选择预设...",` 行之后新增:
-
-```ts
- openFieldMapping: "字段类型映射",
- import: "导入",
- export: "导出",
- importSuccess: "导入成功",
- importError: "导入失败:文件不是合法的字段类型映射 JSON",
- done: "完成",
-```
-
-- [ ] **步骤 2:en 新增键**
-
-定位 `schemaDiff.fieldMapping` 对象(约 2457 行 `fieldMapping: {`)。在 `selectPreset: "Select preset...",` 行之后新增:
-
-```ts
- openFieldMapping: "Field Type Mapping",
- import: "Import",
- export: "Export",
- importSuccess: "Imported successfully",
- importError: "Import failed: file is not a valid field type mapping JSON",
- done: "Done",
-```
-
-- [ ] **步骤 3:类型检查(i18n 为运行时键,typecheck 不校验缺失键,但确认 JSON 结构无语法错误)**
-
-运行:`pnpm typecheck`
-预期:无新增报错。
-
-- [ ] **步骤 4:Commit**
-
-```bash
-git add apps/desktop/src/i18n/locales/zh-CN.ts apps/desktop/src/i18n/locales/en.ts
-git commit -m "feat(desktop): add i18n keys for field mapping dialog"
-```
-
----
-
-## 任务 5:FieldMappingPanel 内嵌滚动兜底
-
-**文件:**
-- 修改:`apps/desktop/src/components/diff/FieldMappingPanel.vue`
-
-- [ ] **步骤 1:给映射列表容器加最大高度与滚动**
-
-定位 `<div v-else class="p-3">`(约 100 行,内含映射列表的 `v-else` 分支)。将其改为带 `max-h` + `overflow-auto`,使内嵌面板(非弹窗场景)也能滚动:
-
-```html
- <div v-else class="p-3 max-h-[42vh] overflow-auto">
-```
-
-(弹窗场景下外层已有 `max-h-[80vh] overflow-auto`,内层再加一层可滚避免双重长列表;内嵌场景下这层是关键兜底。)
-
-- [ ] **步骤 2:类型检查**
-
-运行:`pnpm typecheck`
-预期:无新增报错。
-
-- [ ] **步骤 3:Commit**
-
-```bash
-git add apps/desktop/src/components/diff/FieldMappingPanel.vue
-git commit -m "feat(desktop): make FieldMappingPanel list scrollable as fallback"
-```
-
----
-
-## 自检(计划作者视角)
-
-**规格覆盖度:**
-- 独立弹窗(任务 1 + 3)✓
-- "选项"后按钮(任务 2)✓
-- 单向数据流 / 取消不写回(任务 1 watch + handleClose)✓
-- JSON 导出(任务 1 handleExport,参考 TagManagementPanel)✓
-- JSON 导入 + 校验(任务 1 onFileSelected)✓
-- 弹窗内滚动 + 内嵌兜底(任务 1 max-h-[80vh] + 任务 5)✓
-- 配置步骤底部操作栏始终可见(弹窗隔离映射,任务 3)✓
-- i18n(任务 4)✓
-
-**占位符扫描:** 无 TODO / 待定 / "补充细节"。所有步骤含完整代码。
-
-**类型一致性:** `FieldMappingEntry` 来自 `@/types/schemaDiff`;`handleFieldMappingsUpdate(mappings: FieldMappingEntry[])` 在任务 3 复用任务 1 emit 的 `save(FieldMappingEntry[])`;`sourceDbType` / `targetDbType` 在 `SchemaDiffDialog` 已存在;i18n 键在任务 4 定义、任务 1 使用,名称一致(`openFieldMapping` / `import` / `export` / `importSuccess` / `importError` / `done`)。
-
----
-
-## 验收(手动,pnpm dev)
-
-1. 打开"比较架构"弹窗,源/目标选不同类型 → 出现"字段类型映射"按钮。
-2. 点按钮 → 独立弹窗打开,渲染映射面板。
-3. 弹窗内添加大量映射 → 弹窗内部可滚动,底部"导入/导出/完成"始终可点。
-4. 点"导出" → 下载 `field-mappings.json`,内容为 `FieldMappingEntry[]`。
-5. 清空映射后点"导入"选该 json → 映射恢复;非法文件 → 报错 toast 且不替换。
-6. 点"完成" → 写回配置步骤;关闭弹窗后底部操作栏(保存/加载/选项/开始比较)始终可见可点。
-7. 点遮罩 / ✕ → 未"完成"的修改不写回。
diff --git a/docs/superpowers/plans/2026-07-29-clickhouse-syntax-highlighting.md b/docs/superpowers/plans/2026-07-29-clickhouse-syntax-highlighting.md
deleted file mode 100644
index fc1a0439cc..0000000000
--- a/docs/superpowers/plans/2026-07-29-clickhouse-syntax-highlighting.md
+++ /dev/null
@@ -1,542 +0,0 @@
-# ClickHouse SQL Syntax Highlighting Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Add a dedicated ClickHouse CodeMirror dialect so ClickHouse keywords, types, built-ins, comments, and table names receive correct editor highlighting.
-
-**Architecture:** Keep DBX's existing CodeMirror/Lezer pipeline and define a ClickHouse dialect by extending `StandardSQL` with a curated ClickHouse vocabulary and lexical options. Route ClickHouse connections to that syntax dialect without widening the existing completion/formatting dialect, and add a ClickHouse semantic adapter selected before the legacy MySQL behavior dialect.
-
-**Tech Stack:** TypeScript, Vue 3, CodeMirror 6 `@codemirror/[email protected]`, Lezer SQL parser, Vitest.
-
-## Global Constraints
-
-- Cover the main CodeMirror query editor and CodeMirror-based DDL/SQL viewers.
-- Do not change Shiki-rendered static SQL blocks in AI messages.
-- Do not change SQL formatting, execution, completion, snippets, or editor theme colors.
-- Use `StandardSQL`, not `MySQL`, as the ClickHouse parser base.
-- Preserve ClickHouse's compact `--SELECT 1` line-comment behavior.
-- Add no runtime dependency and no persisted-setting migration.
-
----
-
-## File Map
-
-- Modify `apps/desktop/src/lib/editor/codemirrorSqlDialect.ts`: own the ClickHouse CodeMirror dialect name, vocabulary, lexical configuration, and parser factory selection.
-- Modify `apps/desktop/src/lib/database/jdbcDialect.ts`: return the dedicated syntax dialect for native and inferred JDBC ClickHouse connections while retaining the existing three-value behavior dialect.
-- Modify `apps/desktop/src/components/editor/QueryEditor.vue`: allow `clickhouse` only for the syntax-dialect prop.
-- Modify `apps/desktop/src/components/layout/ContentArea.vue`: type the syntax dialect with the shared CodeMirror dialect type.
-- Modify `packages/app-tests/codemirrorSqlDialect.test.ts`: verify vocabulary parser nodes, comments, and database-to-syntax propagation.
-- Modify `packages/app-tests/jdbcDialect.test.ts`: verify inferred JDBC ClickHouse syntax selection.
-- Modify `apps/desktop/src/lib/sql/semantic/dialect.ts`: own the ClickHouse semantic adapter and prioritize it for ClickHouse database types.
-- Create `apps/desktop/src/lib/__tests__/sql/semantic/dialect.spec.ts`: verify adapter selection, quoting, and normalization.
-
-### Task 1: Dedicated ClickHouse CodeMirror dialect
-
-**Files:**
-
-- Modify: `packages/app-tests/codemirrorSqlDialect.test.ts`
-- Modify: `packages/app-tests/jdbcDialect.test.ts`
-- Modify: `apps/desktop/src/lib/editor/codemirrorSqlDialect.ts`
-- Modify: `apps/desktop/src/lib/database/jdbcDialect.ts`
-- Modify: `apps/desktop/src/components/editor/QueryEditor.vue`
-- Modify: `apps/desktop/src/components/layout/ContentArea.vue`
-
-**Interfaces:**
-
-- Produces: `CodeMirrorSqlDialectName = "mysql" | "postgres" | "sqlserver" | "clickhouse"`.
-- Produces: `codeMirrorSqlDialectForConnection(connection): CodeMirrorSqlDialectName`.
-- Preserves: `codeMirrorSqlDialect(dbType): "mysql" | "postgres" | "sqlserver"` for completion and formatting behavior.
-- Consumes: `createDbxCodeMirrorSqlDialect(langSql, dialectName, databaseType)`.
-
-- [ ] **Step 1: Write failing parser and mapping tests**
-
-Extend `packages/app-tests/codemirrorSqlDialect.test.ts` with:
-
-```ts
-import { codeMirrorSqlDialect, codeMirrorSqlDialectForConnection } from "../../apps/desktop/src/lib/database/jdbcDialect.ts";
-
-test("maps ClickHouse connections to the dedicated editor syntax dialect", () => {
- assert.equal(codeMirrorSqlDialectForConnection({ db_type: "clickhouse" }), "clickhouse");
- assert.equal(
- codeMirrorSqlDialectForConnection({
- db_type: "jdbc",
- connection_string: "jdbc:clickhouse://127.0.0.1:8123/default",
- }),
- "clickhouse",
- );
-});
-
-test("classifies ClickHouse-specific syntax", () => {
- const dialect = createDbxCodeMirrorSqlDialect(langSql, "clickhouse", "clickhouse");
- const sql = `
- CREATE TABLE events
- (
- id UInt64,
- created_at DateTime64(3),
- category LowCardinality(String),
- attributes Map(String, String)
- )
- ENGINE = MergeTree
- PARTITION BY toYYYYMM(created_at)
- ORDER BY id
- TTL created_at + INTERVAL 30 DAY
- SETTINGS index_granularity = 8192;
-
- SELECT uniqExact(id), argMax(category, created_at)
- FROM events
- PREWHERE created_at >= now() - INTERVAL 1 DAY
- ARRAY JOIN mapKeys(attributes) AS attribute_key
- LIMIT 10 BY category
- FORMAT JSONEachRow;
- `;
-
- for (const keyword of ["ENGINE", "PARTITION", "TTL", "SETTINGS", "PREWHERE", "ARRAY", "FORMAT"]) {
- assert.ok(countParsedNodes(dialect, sql, "Keyword", keyword) >= 1, keyword);
- }
- for (const type of ["UInt64", "DateTime64", "LowCardinality", "Map"]) {
- assert.equal(countParsedNodes(dialect, sql, "Type", type), 1, type);
- }
- for (const builtin of ["toYYYYMM", "uniqExact", "argMax", "mapKeys"]) {
- assert.equal(countParsedNodes(dialect, sql, "Builtin", builtin), 1, builtin);
- }
- assert.equal(countParsedNodes(dialect, "--SELECT 1", "LineComment", "--SELECT 1"), 1);
-});
-```
-
-Extend `packages/app-tests/jdbcDialect.test.ts` with:
-
-```ts
-test("uses dedicated ClickHouse editor syntax for inferred JDBC connections", () => {
- const connection = {
- db_type: "jdbc" as const,
- connection_string: "jdbc:clickhouse://127.0.0.1:8123/default",
- };
-
- assert.equal(inferJdbcDialect(connection), "clickhouse");
- assert.equal(codeMirrorSqlDialectForConnection(connection), "clickhouse");
-});
-```
-
-- [ ] **Step 2: Run the tests and verify the red state**
-
-Run:
-
-```bash
-pnpm vitest run packages/app-tests/codemirrorSqlDialect.test.ts packages/app-tests/jdbcDialect.test.ts
-```
-
-Expected: FAIL because `"clickhouse"` is not accepted as a CodeMirror dialect name and ClickHouse connections currently return `"mysql"`.
-
-- [ ] **Step 3: Add the ClickHouse dialect definition**
-
-In `apps/desktop/src/lib/editor/codemirrorSqlDialect.ts`, extend the shared name and add focused vocabulary constants:
-
-```ts
-export type CodeMirrorSqlDialectName = "mysql" | "postgres" | "sqlserver" | "clickhouse";
-
-const CLICKHOUSE_KEYWORDS = [
- "ATTACH",
- "DETACH",
- "OPTIMIZE",
- "SYSTEM",
- "KILL",
- "ENGINE",
- "PARTITION",
- "PRIMARY",
- "SAMPLE",
- "PREWHERE",
- "ARRAY",
- "GLOBAL",
- "FINAL",
- "WITH",
- "TOTALS",
- "ROLLUP",
- "CUBE",
- "LIMIT",
- "BY",
- "INTO",
- "OUTFILE",
- "COMPRESSION",
- "FORMAT",
- "SETTINGS",
- "TTL",
- "CODEC",
- "MATERIALIZED",
- "ALIAS",
- "PROJECTION",
- "INDEX",
- "GRANULARITY",
-].join(" ");
-
-const CLICKHOUSE_TYPES = [
- "Bool",
- "Int8",
- "Int16",
- "Int32",
- "Int64",
- "Int128",
- "Int256",
- "UInt8",
- "UInt16",
- "UInt32",
- "UInt64",
- "UInt128",
- "UInt256",
- "Float32",
- "Float64",
- "Decimal",
- "Decimal32",
- "Decimal64",
- "Decimal128",
- "Decimal256",
- "String",
- "FixedString",
- "Date",
- "Date32",
- "DateTime",
- "DateTime64",
- "Time",
- "Time64",
- "Enum8",
- "Enum16",
- "UUID",
- "IPv4",
- "IPv6",
- "Array",
- "Tuple",
- "Map",
- "Nested",
- "Nullable",
- "LowCardinality",
- "AggregateFunction",
- "SimpleAggregateFunction",
- "JSON",
- "Object",
- "Variant",
- "Dynamic",
- "Nothing",
-].join(" ");
-
-const CLICKHOUSE_BUILTINS = [
- "now",
- "today",
- "toDate",
- "toDateTime",
- "toDateTime64",
- "toYYYYMM",
- "count",
- "sum",
- "avg",
- "min",
- "max",
- "uniq",
- "uniqExact",
- "argMin",
- "argMax",
- "groupArray",
- "arrayJoin",
- "mapKeys",
- "mapValues",
- "JSONExtract",
- "JSONExtractString",
-].join(" ");
-```
-
-Make `codeMirrorBaseDialect()` select `StandardSQL` for either an explicit
-ClickHouse syntax name or `databaseType === "clickhouse"`:
-
-```ts
-if (databaseType) {
- if (databaseType === "clickhouse") return langSql.StandardSQL;
- // Existing database family checks remain in their current order.
-}
-if (dialectName === "clickhouse") return langSql.StandardSQL;
-```
-
-In `createDbxCodeMirrorSqlDialect()`, build ClickHouse-specific spec fields
-without changing other dialects:
-
-```ts
-const isClickHouse = databaseType === "clickhouse" || dialectName === "clickhouse";
-
-return langSql.SQLDialect.define({
- ...baseDialect.spec,
- keywords: [
- baseKeywords,
- DBX_COMMON_SQL_KEYWORDS,
- isClickHouse ? CLICKHOUSE_KEYWORDS : "",
- isPostgres ? POSTGRES_PLPGSQL_KEYWORDS : "",
- isSqlServer ? SQLSERVER_KEYWORDS : "",
- ]
- .filter(Boolean)
- .join(" "),
- types: [baseDialect.spec.types || "", isClickHouse ? CLICKHOUSE_TYPES : "", isPostgres ? POSTGRES_PLPGSQL_TYPES : ""]
- .filter(Boolean)
- .join(" ") || undefined,
- builtin: [baseDialect.spec.builtin || "", isClickHouse ? CLICKHOUSE_BUILTINS : "", isPostgres ? POSTGRES_PLPGSQL_BUILTIN : ""]
- .filter(Boolean)
- .join(" ") || undefined,
- identifierQuotes: isClickHouse ? '"`' : baseDialect.spec.identifierQuotes,
- backslashEscapes: isClickHouse ? true : baseDialect.spec.backslashEscapes,
- spaceAfterDashes: isClickHouse ? false : baseDialect.spec.spaceAfterDashes,
- doubleDollarQuotedStrings: false,
-});
-```
-
-- [ ] **Step 4: Route ClickHouse only through the syntax-dialect channel**
-
-In `apps/desktop/src/lib/database/jdbcDialect.ts`, import the type and keep the
-existing behavior-dialect function narrow:
-
-```ts
-import type { CodeMirrorSqlDialectName } from "@/lib/editor/codemirrorSqlDialect";
-
-export function codeMirrorSqlDialectForConnection(connection?: JdbcDialectConnection): CodeMirrorSqlDialectName {
- if (isJdbcAseProfile(connection)) return "sqlserver";
- const databaseType = effectiveDatabaseTypeForConnection(connection);
- if (databaseType === "clickhouse") return "clickhouse";
- return codeMirrorSqlDialect(databaseType);
-}
-```
-
-In `apps/desktop/src/components/editor/QueryEditor.vue`, import the type and
-change only the syntax prop:
-
-```ts
-import { createDbxCodeMirrorSqlDialect, type CodeMirrorSqlDialectName } from "@/lib/editor/codemirrorSqlDialect";
-
-syntaxDialect?: CodeMirrorSqlDialectName;
-```
-
-In `apps/desktop/src/components/layout/ContentArea.vue`, import the same type and
-change only the syntax computed value:
-
-```ts
-import type { CodeMirrorSqlDialectName } from "@/lib/editor/codemirrorSqlDialect";
-
-const editorSyntaxDialect = computed<CodeMirrorSqlDialectName>(() => codeMirrorSqlDialectForConnection(props.activeConnection));
-```
-
-The existing `editorDialect` remains `"mysql" | "postgres" | "sqlserver"` so
-completion, identifier quoting, and formatting behavior stay out of scope.
-
-- [ ] **Step 5: Run focused tests and typecheck**
-
-Run:
-
-```bash
-pnpm vitest run packages/app-tests/codemirrorSqlDialect.test.ts packages/app-tests/jdbcDialect.test.ts
-pnpm typecheck
-```
-
-Expected: both test files PASS and `vue-tsc` exits with code 0.
-
-- [ ] **Step 6: Commit the dedicated parser**
-
-```bash
-git add apps/desktop/src/lib/editor/codemirrorSqlDialect.ts \
- apps/desktop/src/lib/database/jdbcDialect.ts \
- apps/desktop/src/components/editor/QueryEditor.vue \
- apps/desktop/src/components/layout/ContentArea.vue \
- packages/app-tests/codemirrorSqlDialect.test.ts \
- packages/app-tests/jdbcDialect.test.ts
-git commit -m "feat(editor): add ClickHouse SQL highlighting"
-```
-
-### Task 2: ClickHouse semantic table-name adapter
-
-**Files:**
-
-- Create: `apps/desktop/src/lib/__tests__/sql/semantic/dialect.spec.ts`
-- Modify: `apps/desktop/src/lib/sql/semantic/dialect.ts`
-
-**Interfaces:**
-
-- Produces: `SQL_SEMANTIC_DIALECTS.clickhouse: SqlSemanticDialectAdapter`.
-- Preserves: `sqlSemanticDialectFor(options)` input type; ClickHouse is selected by `databaseType`, not by widening completion's three-value dialect.
-- Consumes: `SqlSemanticDialectAdapter` and `defaultNormalize`.
-
-- [ ] **Step 1: Write the failing semantic adapter test**
-
-Create `apps/desktop/src/lib/__tests__/sql/semantic/dialect.spec.ts`:
-
-```ts
-import { describe, expect, it } from "vitest";
-import { sqlSemanticDialectFor } from "@/lib/sql/semantic/dialect";
-
-describe("ClickHouse semantic dialect", () => {
- it("takes precedence over the legacy MySQL behavior dialect", () => {
- const dialect = sqlSemanticDialectFor({
- databaseType: "clickhouse",
- dialect: "mysql",
- });
-
- expect(dialect.id).toBe("clickhouse");
- expect(dialect.identifierQuotes).toEqual([
- { open: "`", close: "`" },
- { open: '"', close: '"' },
- ]);
- expect(dialect.normalizeIdentifier("EventName")).toBe("EventName");
- expect(dialect.quoteIdentifier("event`name")).toBe("`event``name`");
- });
-});
-```
-
-- [ ] **Step 2: Run the test and verify the red state**
-
-Run:
-
-```bash
-pnpm vitest run apps/desktop/src/lib/__tests__/sql/semantic/dialect.spec.ts
-```
-
-Expected: FAIL because the returned adapter id is currently `"mysql"`.
-
-- [ ] **Step 3: Implement the minimal ClickHouse semantic adapter**
-
-Add this entry to `SQL_SEMANTIC_DIALECTS` in
-`apps/desktop/src/lib/sql/semantic/dialect.ts`:
-
-```ts
-clickhouse: {
- id: "clickhouse",
- identifierQuotes: [
- { open: "`", close: "`" },
- { open: '"', close: '"' },
- ],
- supportsAsForTableAlias: true,
- projectionAliasVisibility: { where: false, groupBy: true, having: true, orderBy: true },
- normalizeIdentifier: defaultNormalize,
- quoteIdentifier: (identifier) => quoteWith(identifier, "`"),
- qualifierRole(parts, context) {
- if (context === "column") return parts.length >= 2 ? "table" : "table";
- if (context === "routine") return parts.length >= 2 ? "package" : "schema";
- return parts.length >= 1 ? "schema" : "unknown";
- },
-},
-```
-
-Select it before the explicit three-value behavior dialect:
-
-```ts
-export function sqlSemanticDialectFor(options: { databaseType?: DatabaseType; dialect?: "mysql" | "postgres" | "sqlserver" }): SqlSemanticDialectAdapter {
- if (options.databaseType === "clickhouse") return SQL_SEMANTIC_DIALECTS.clickhouse;
- if (options.dialect && SQL_SEMANTIC_DIALECTS[options.dialect]) return SQL_SEMANTIC_DIALECTS[options.dialect];
- // Existing switch remains unchanged.
-}
-```
-
-- [ ] **Step 4: Run semantic and parser regression tests**
-
-Run:
-
-```bash
-pnpm vitest run \
- apps/desktop/src/lib/__tests__/sql/semantic/dialect.spec.ts \
- apps/desktop/src/lib/__tests__/sql/semantic/model.spec.ts \
- packages/app-tests/codemirrorSqlDialect.test.ts
-```
-
-Expected: all tests PASS.
-
-- [ ] **Step 5: Commit the semantic adapter**
-
-```bash
-git add apps/desktop/src/lib/sql/semantic/dialect.ts \
- apps/desktop/src/lib/__tests__/sql/semantic/dialect.spec.ts
-git commit -m "feat(editor): add ClickHouse semantic SQL dialect"
-```
-
-### Task 3: Final verification and PR preparation
-
-**Files:**
-
-- Verify: all files changed by Tasks 1 and 2
-- Verify: `docs/superpowers/specs/2026-07-29-clickhouse-syntax-highlighting-design.md`
-- Verify: `docs/superpowers/plans/2026-07-29-clickhouse-syntax-highlighting.md`
-
-**Interfaces:**
-
-- Consumes: the dedicated ClickHouse parser and semantic adapter.
-- Produces: a reviewed, tested branch ready for a GitHub pull request.
-
-- [ ] **Step 1: Run the full relevant automated checks**
-
-Run:
-
-```bash
-pnpm vitest run \
- packages/app-tests/codemirrorSqlDialect.test.ts \
- packages/app-tests/jdbcDialect.test.ts \
- apps/desktop/src/lib/__tests__/editor/codemirrorSqlDialect.spec.ts \
- apps/desktop/src/lib/__tests__/sql/semantic/dialect.spec.ts \
- apps/desktop/src/lib/__tests__/sql/semantic/model.spec.ts
-pnpm typecheck
-```
-
-Expected: every Vitest file passes and typecheck exits with code 0.
-
-- [ ] **Step 2: Review parser output and scope boundaries**
-
-Run:
-
-```bash
-git diff main...HEAD --check
-git diff main...HEAD --stat
-git diff main...HEAD -- \
- apps/desktop/src/lib/editor/codemirrorSqlDialect.ts \
- apps/desktop/src/lib/database/jdbcDialect.ts \
- apps/desktop/src/lib/sql/semantic/dialect.ts
-rg -n "clickhouse" apps/desktop/src/lib/sql/sqlHighlighter.ts
-```
-
-Expected: no whitespace errors; changes stay in the planned CodeMirror and
-semantic paths; `sqlHighlighter.ts` has no new ClickHouse/Shiki modification.
-
-- [ ] **Step 3: Perform a local correctness review**
-
-Check each diff hunk against this exact checklist:
-
-```text
-[ ] ClickHouse uses StandardSQL, never MySQL, as its parser base.
-[ ] Compact -- comments remain LineComment nodes.
-[ ] Keywords, types, and built-ins are stored in separate spec fields.
-[ ] Only syntaxDialect accepts the new clickhouse value.
-[ ] Existing completion/formatting dialect types remain unchanged.
-[ ] databaseType=clickhouse wins over dialect=mysql in semantic selection.
-[ ] No dependency, persistence, theme, Shiki, execution, or formatter changes.
-```
-
-Expected: every item is satisfied; correct any violation and rerun Step 1.
-
-- [ ] **Step 4: Push and create the pull request**
-
-Run:
-
-```bash
-git status --short
-git push -u origin codex/clickhouse-syntax-highlighting
-gh pr create \
- --base main \
- --head codex/clickhouse-syntax-highlighting \
- --title "feat(editor): add dedicated ClickHouse SQL highlighting" \
- --body-file /tmp/dbx-clickhouse-highlighting-pr.md
-```
-
-Before the last command, create `/tmp/dbx-clickhouse-highlighting-pr.md` with:
-
-```markdown
-## Summary
-
-- add a dedicated ClickHouse CodeMirror SQL dialect
-- classify ClickHouse keywords, data types, and common built-in functions
-- select a ClickHouse semantic adapter for table-name highlighting
-- preserve existing completion, formatting, Shiki, and theme behavior
-
-## Test plan
-
-- `pnpm vitest run packages/app-tests/codemirrorSqlDialect.test.ts packages/app-tests/jdbcDialect.test.ts apps/desktop/src/lib/__tests__/editor/codemirrorSqlDialect.spec.ts apps/desktop/src/lib/__tests__/sql/semantic/dialect.spec.ts apps/desktop/src/lib/__tests__/sql/semantic/model.spec.ts`
-- `pnpm typecheck`
-```
-
-Expected: the branch is pushed and GitHub returns a new PR URL.
diff --git a/docs/superpowers/plans/2026-07-30-clickhouse-function-completion.md b/docs/superpowers/plans/2026-07-30-clickhouse-function-completion.md
deleted file mode 100644
index 6bd7dc614c..0000000000
--- a/docs/superpowers/plans/2026-07-30-clickhouse-function-completion.md
+++ /dev/null
@@ -1,896 +0,0 @@
-# ClickHouse Function Completion Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Add broad, static ClickHouse function completion with canonical casing, overload-aware and parametric signature help, table functions, and valid aggregate-combinator variants.
-
-**Architecture:** Keep ClickHouse definitions and deterministic combinator logic in `apps/desktop/src/lib/sql/clickhouse/`. Adapt that registry into the existing generic SQL completion provider without changing other database inventories. Extend signature help to return overloads and parameter groups, then render that richer result in the existing CodeMirror tooltip.
-
-**Tech Stack:** TypeScript 6, Vue 3, CodeMirror 6, Vitest 4, pnpm 10.
-
----
-
-## File Map
-
-**Create**
-
-- `apps/desktop/src/lib/sql/clickhouse/functionTypes.ts` — shared ClickHouse function, signature, category, status, and registry-query types.
-- `apps/desktop/src/lib/sql/clickhouse/regularFunctions.ts` — scalar and window-function inventory plus category manifest.
-- `apps/desktop/src/lib/sql/clickhouse/aggregateFunctions.ts` — ordinary and parametric aggregate inventory.
-- `apps/desktop/src/lib/sql/clickhouse/tableFunctions.ts` — functions valid as table sources.
-- `apps/desktop/src/lib/sql/clickhouse/aggregateCombinators.ts` — legal suffix transitions and signature transformations.
-- `apps/desktop/src/lib/sql/clickhouse/functionRegistry.ts` — validation, canonical lookup, prefix search, and lazy combinator generation.
-- `apps/desktop/src/lib/__tests__/sql/clickhouse/functionRegistry.spec.ts` — registry integrity and lookup coverage.
-- `apps/desktop/src/lib/__tests__/sql/clickhouse/aggregateCombinators.spec.ts` — combinator ordering and signature transformations.
-- `apps/desktop/src/lib/__tests__/sql/sqlCompletion.signature.spec.ts` — overload and parametric-call parsing.
-- `apps/desktop/src/lib/editor/sqlSignatureTooltip.ts` — render overload-aware signature help without coupling registry logic to Vue.
-- `apps/desktop/src/lib/__tests__/editor/sqlSignatureTooltip.spec.ts` — exercise the real tooltip DOM in happy-dom.
-
-**Modify**
-
-- `apps/desktop/src/lib/sql/sqlCompletion.ts` — ClickHouse registry adapter, table-function context, canonical apply text, and multi-signature resolver.
-- `apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts` — ClickHouse completion, table-function, isolation, and regression cases.
-- `apps/desktop/src/components/editor/QueryEditor.vue` — render all overloads and active parameters.
-
-**Reference**
-
-- `docs/superpowers/specs/2026-07-30-clickhouse-function-completion-design.md`
-- `apps/desktop/src/lib/__tests__/editor/queryEditorSqlSignature.spec.ts` — existing dialect reconfiguration regression to keep running.
-- <https://clickhouse.com/docs/reference/functions>
-- <https://clickhouse.com/docs/reference/functions/aggregate-functions/combinators>
-
-## Task 1: Introduce the ClickHouse Function Model and Validated Registry
-
-**Files:**
-
-- Create: `apps/desktop/src/lib/sql/clickhouse/functionTypes.ts`
-- Create: `apps/desktop/src/lib/sql/clickhouse/functionRegistry.ts`
-- Create: `apps/desktop/src/lib/__tests__/sql/clickhouse/functionRegistry.spec.ts`
-
-- [ ] **Step 1: Write failing registry-validation tests**
-
-Create `functionRegistry.spec.ts` with real definitions covering canonical lookup, overload preservation, duplicate detection, and invalid preferred indexes:
-
-```ts
-import { describe, expect, it } from "vitest";
-import { createClickHouseFunctionRegistry } from "@/lib/sql/clickhouse/functionRegistry";
-import type { ClickHouseFunctionDefinition } from "@/lib/sql/clickhouse/functionTypes";
-
-const toStartOfDay: ClickHouseFunctionDefinition = {
- name: "toStartOfDay",
- kind: "regular",
- category: "date-time",
- signatures: [{ parameterGroups: [["value", "time_zone?"]], returnType: "DateTime" }],
- aliases: ["startOfDay"],
-};
-
-describe("ClickHouse function registry", () => {
- it("looks up canonical names case-insensitively and preserves overloads", () => {
- const registry = createClickHouseFunctionRegistry([toStartOfDay]);
- expect(registry.get("TOSTARTOFDAY")).toEqual(toStartOfDay);
- expect(registry.search("tostart", 20)).toEqual([toStartOfDay]);
- expect(registry.search("startof", 20)).toEqual([toStartOfDay]);
- });
-
- it("rejects duplicate canonical names case-insensitively", () => {
- expect(() => createClickHouseFunctionRegistry([toStartOfDay, { ...toStartOfDay, name: "TOSTARTOFDAY" }])).toThrow(/duplicate/i);
- });
-
- it("rejects an invalid preferred signature index", () => {
- expect(() => createClickHouseFunctionRegistry([{ ...toStartOfDay, preferredSignature: 2 }])).toThrow(/preferred signature/i);
- });
-});
-```
-
-- [ ] **Step 2: Run the focused test and confirm the RED state**
-
-Run:
-
-```bash
-pnpm exec vitest run apps/desktop/src/lib/__tests__/sql/clickhouse/functionRegistry.spec.ts
-```
-
-Expected: FAIL because `functionTypes.ts` and `functionRegistry.ts` do not exist.
-
-- [ ] **Step 3: Add the function types**
-
-Create `functionTypes.ts`:
-
-```ts
-export type ClickHouseFunctionKind = "regular" | "aggregate" | "window" | "table";
-export type ClickHouseFunctionStatus = "stable" | "experimental" | "deprecated";
-
-export type ClickHouseFunctionCategory =
- | "aggregate"
- | "array"
- | "bitmap"
- | "comparison"
- | "conversion"
- | "date-time"
- | "dictionary"
- | "encoding"
- | "geo"
- | "hash"
- | "ip"
- | "json"
- | "map"
- | "math"
- | "nullable"
- | "random"
- | "string"
- | "table"
- | "tuple"
- | "url"
- | "window"
- | "other";
-
-export interface ClickHouseFunctionSignature {
- parameterGroups: string[][];
- returnType?: string;
-}
-
-export interface ClickHouseFunctionDefinition {
- name: string;
- kind: ClickHouseFunctionKind;
- category: ClickHouseFunctionCategory;
- signatures: ClickHouseFunctionSignature[];
- description?: string;
- preferredSignature?: number;
- status?: ClickHouseFunctionStatus;
- aliases?: string[];
- combinators?: boolean;
- generated?: boolean;
-}
-
-export interface ClickHouseFunctionRegistry {
- get(name: string): ClickHouseFunctionDefinition | undefined;
- search(prefix: string, limit: number, kind?: ClickHouseFunctionKind): ClickHouseFunctionDefinition[];
- all(): readonly ClickHouseFunctionDefinition[];
-}
-```
-
-- [ ] **Step 4: Implement strict construction and deterministic prefix search**
-
-Create `functionRegistry.ts` with a private lowercase index. Validate non-empty names, non-empty signatures, non-empty parameter groups, preferred indexes, canonical collisions, and alias collisions:
-
-```ts
-import type { ClickHouseFunctionDefinition, ClickHouseFunctionKind, ClickHouseFunctionRegistry } from "./functionTypes";
-
-function definitionKeys(definition: ClickHouseFunctionDefinition): string[] {
- return [definition.name, ...(definition.aliases ?? [])].map((name) => name.toLowerCase());
-}
-
-function validateDefinition(definition: ClickHouseFunctionDefinition): void {
- if (!definition.name.trim()) throw new Error("ClickHouse function name must not be empty");
- if (definition.signatures.length === 0) throw new Error(`ClickHouse function ${definition.name} must define a signature`);
- if (definition.signatures.some((signature) => signature.parameterGroups.length === 0)) {
- throw new Error(`ClickHouse function ${definition.name} must define a parameter group`);
- }
- const preferred = definition.preferredSignature ?? 0;
- if (preferred < 0 || preferred >= definition.signatures.length) {
- throw new Error(`ClickHouse function ${definition.name} has an invalid preferred signature`);
- }
-}
-
-export function createClickHouseFunctionRegistry(definitions: readonly ClickHouseFunctionDefinition[]): ClickHouseFunctionRegistry {
- const byKey = new Map<string, ClickHouseFunctionDefinition>();
- for (const definition of definitions) {
- validateDefinition(definition);
- for (const key of definitionKeys(definition)) {
- if (byKey.has(key)) throw new Error(`Duplicate ClickHouse function or alias: ${key}`);
- byKey.set(key, definition);
- }
- }
- const ordered = [...definitions].sort((left, right) => left.name.localeCompare(right.name));
- return {
- get: (name) => byKey.get(name.toLowerCase()),
- search: (prefix, limit, kind?: ClickHouseFunctionKind) => {
- const normalized = prefix.toLowerCase();
- return ordered.filter((definition) => (!kind || definition.kind === kind) && definitionKeys(definition).some((key) => key.startsWith(normalized))).slice(0, limit);
- },
- all: () => ordered,
- };
-}
-```
-
-- [ ] **Step 5: Run the focused test and confirm GREEN**
-
-Run the same Vitest command. Expected: 3 tests PASS.
-
-- [ ] **Step 6: Commit the registry foundation**
-
-```bash
-git add apps/desktop/src/lib/sql/clickhouse/functionTypes.ts apps/desktop/src/lib/sql/clickhouse/functionRegistry.ts apps/desktop/src/lib/__tests__/sql/clickhouse/functionRegistry.spec.ts
-git commit -m "feat(sql): add ClickHouse function registry"
-```
-
-## Task 2: Add the Regular, Window, and Table Function Inventories
-
-**Files:**
-
-- Create: `apps/desktop/src/lib/sql/clickhouse/regularFunctions.ts`
-- Create: `apps/desktop/src/lib/sql/clickhouse/tableFunctions.ts`
-- Modify: `apps/desktop/src/lib/sql/clickhouse/functionRegistry.ts`
-- Modify: `apps/desktop/src/lib/__tests__/sql/clickhouse/functionRegistry.spec.ts`
-
-- [ ] **Step 1: Add failing inventory-integrity and representative-coverage tests**
-
-Extend `functionRegistry.spec.ts`:
-
-```ts
-import { CLICKHOUSE_FUNCTION_CATEGORY_MANIFEST, CLICKHOUSE_REGULAR_FUNCTIONS } from "@/lib/sql/clickhouse/regularFunctions";
-import { CLICKHOUSE_TABLE_FUNCTIONS } from "@/lib/sql/clickhouse/tableFunctions";
-import { CLICKHOUSE_FUNCTION_REGISTRY } from "@/lib/sql/clickhouse/functionRegistry";
-
-it("keeps the checked-in category manifest and inventory counts aligned", () => {
- for (const entry of CLICKHOUSE_FUNCTION_CATEGORY_MANIFEST) {
- expect(CLICKHOUSE_REGULAR_FUNCTIONS.filter((definition) => definition.category === entry.category)).toHaveLength(entry.minimumCount);
- }
-});
-
-it.each([
- ["arrayMap", "array"],
- ["toStartOfDay", "date-time"],
- ["JSONExtractString", "json"],
- ["cityHash64", "hash"],
- ["URLHierarchy", "url"],
- ["lagInFrame", "window"],
-] as const)("contains %s with canonical casing and category %s", (name, category) => {
- expect(CLICKHOUSE_FUNCTION_REGISTRY.get(name)).toMatchObject({ name, category });
-});
-
-it.each(["numbers", "file", "url", "s3", "remote", "postgresql", "mysql"] as const)("contains the %s table function", (name) => {
- expect(CLICKHOUSE_TABLE_FUNCTIONS.some((definition) => definition.name === name && definition.kind === "table")).toBe(true);
-});
-```
-
-- [ ] **Step 2: Run the registry test and verify the missing-inventory failure**
-
-Expected: FAIL because the inventory modules and exported default registry do not exist.
-
-- [ ] **Step 3: Add regular-function helpers and the first documented categories**
-
-In `regularFunctions.ts`, use a small typed helper so data remains compact:
-
-```ts
-import type { ClickHouseFunctionCategory, ClickHouseFunctionDefinition, ClickHouseFunctionSignature } from "./functionTypes";
-
-const regular = (
- name: string,
- category: ClickHouseFunctionCategory,
- signatures: ClickHouseFunctionSignature[],
- options: Partial<ClickHouseFunctionDefinition> = {},
-): ClickHouseFunctionDefinition => ({ name, kind: "regular", category, signatures, ...options });
-
-export const CLICKHOUSE_REGULAR_FUNCTIONS: ClickHouseFunctionDefinition[] = [
- regular("arrayMap", "array", [{ parameterGroups: [["lambda", "array", "...arrays"]], returnType: "Array" }]),
- regular("toStartOfDay", "date-time", [
- { parameterGroups: [["value"]], returnType: "DateTime" },
- { parameterGroups: [["value", "time_zone"]], returnType: "DateTime" },
- ]),
- regular("JSONExtractString", "json", [{ parameterGroups: [["json", "path", "...paths"]], returnType: "String" }]),
- regular("cityHash64", "hash", [{ parameterGroups: [["argument", "...arguments"]], returnType: "UInt64" }]),
- regular("URLHierarchy", "url", [{ parameterGroups: [["url"]], returnType: "Array(String)" }]),
- { name: "lagInFrame", kind: "window", category: "window", signatures: [{ parameterGroups: [["value", "offset?", "default?"]] }] },
-];
-```
-
-Continue in category-sized edits using the official 2026-07-30 documentation snapshot. Each definition must include every documented overload needed to distinguish arity or parameter groups. Cover the manifest categories declared in `functionTypes.ts`; omit a category from the manifest only when ClickHouse has no public function page for it.
-
-- [ ] **Step 4: Add a checked-in manifest after each category batch**
-
-Append a manifest whose counts exactly equal the checked-in arrays:
-
-```ts
-export const CLICKHOUSE_FUNCTION_CATEGORY_MANIFEST = [
- { category: "array", minimumCount: CLICKHOUSE_REGULAR_FUNCTIONS.filter((item) => item.category === "array").length },
- { category: "date-time", minimumCount: CLICKHOUSE_REGULAR_FUNCTIONS.filter((item) => item.category === "date-time").length },
- { category: "json", minimumCount: CLICKHOUSE_REGULAR_FUNCTIONS.filter((item) => item.category === "json").length },
- { category: "hash", minimumCount: CLICKHOUSE_REGULAR_FUNCTIONS.filter((item) => item.category === "hash").length },
- { category: "url", minimumCount: CLICKHOUSE_REGULAR_FUNCTIONS.filter((item) => item.category === "url").length },
- { category: "window", minimumCount: CLICKHOUSE_REGULAR_FUNCTIONS.filter((item) => item.category === "window").length },
-] as const;
-```
-
-Expand this literal as each documented category is added. Do not derive the manifest at runtime; checked-in numeric literals are the reviewable deletion guard. Replace the `.length` expressions above with those final numeric literals before making the test green.
-
-- [ ] **Step 5: Add table-function definitions**
-
-Create `tableFunctions.ts`:
-
-```ts
-import type { ClickHouseFunctionDefinition } from "./functionTypes";
-
-export const CLICKHOUSE_TABLE_FUNCTIONS: ClickHouseFunctionDefinition[] = [
- {
- name: "numbers",
- kind: "table",
- category: "table",
- signatures: [
- { parameterGroups: [["count"]] },
- { parameterGroups: [["offset", "count"]] },
- { parameterGroups: [["offset", "count", "step"]] },
- ],
- },
- { name: "file", kind: "table", category: "table", signatures: [{ parameterGroups: [["path", "format?", "structure?", "compression?"]] }] },
- { name: "url", kind: "table", category: "table", signatures: [{ parameterGroups: [["url", "format", "structure?", "headers?"]] }] },
- { name: "s3", kind: "table", category: "table", signatures: [{ parameterGroups: [["url", "format?", "structure?", "compression?"]] }] },
- { name: "remote", kind: "table", category: "table", signatures: [{ parameterGroups: [["addresses", "database", "table", "user?", "password?"]] }] },
- { name: "postgresql", kind: "table", category: "table", signatures: [{ parameterGroups: [["address", "database", "table", "user", "password", "schema?"]] }] },
- { name: "mysql", kind: "table", category: "table", signatures: [{ parameterGroups: [["address", "database", "table", "user", "password"]] }] },
-];
-```
-
-Add all other documented public table functions from the same snapshot, retaining lowercase canonical names where ClickHouse documents them that way.
-
-- [ ] **Step 6: Export the complete direct-function registry**
-
-In `functionRegistry.ts`:
-
-```ts
-import { CLICKHOUSE_REGULAR_FUNCTIONS } from "./regularFunctions";
-import { CLICKHOUSE_TABLE_FUNCTIONS } from "./tableFunctions";
-
-export const CLICKHOUSE_FUNCTION_REGISTRY = createClickHouseFunctionRegistry([
- ...CLICKHOUSE_REGULAR_FUNCTIONS,
- ...CLICKHOUSE_TABLE_FUNCTIONS,
-]);
-```
-
-- [ ] **Step 7: Run formatting and the focused registry tests after every category batch**
-
-```bash
-pnpm exec oxfmt apps/desktop/src/lib/sql/clickhouse/regularFunctions.ts apps/desktop/src/lib/sql/clickhouse/tableFunctions.ts
-pnpm exec vitest run apps/desktop/src/lib/__tests__/sql/clickhouse/functionRegistry.spec.ts
-```
-
-Expected: all registry tests PASS and manifest counts remain literal, non-zero floors.
-
-- [ ] **Step 8: Commit the regular and table inventories**
-
-```bash
-git add apps/desktop/src/lib/sql/clickhouse/regularFunctions.ts apps/desktop/src/lib/sql/clickhouse/tableFunctions.ts apps/desktop/src/lib/sql/clickhouse/functionRegistry.ts apps/desktop/src/lib/__tests__/sql/clickhouse/functionRegistry.spec.ts
-git commit -m "feat(sql): add ClickHouse regular function inventory"
-```
-
-## Task 3: Add Aggregate Functions and Lazy Combinators
-
-**Files:**
-
-- Create: `apps/desktop/src/lib/sql/clickhouse/aggregateFunctions.ts`
-- Create: `apps/desktop/src/lib/sql/clickhouse/aggregateCombinators.ts`
-- Create: `apps/desktop/src/lib/__tests__/sql/clickhouse/aggregateCombinators.spec.ts`
-- Modify: `apps/desktop/src/lib/sql/clickhouse/functionRegistry.ts`
-- Modify: `apps/desktop/src/lib/__tests__/sql/clickhouse/functionRegistry.spec.ts`
-
-- [ ] **Step 1: Write failing aggregate and combinator tests**
-
-Create `aggregateCombinators.spec.ts`:
-
-```ts
-import { describe, expect, it } from "vitest";
-import { generateAggregateCombinatorCandidates } from "@/lib/sql/clickhouse/aggregateCombinators";
-import { CLICKHOUSE_FUNCTION_REGISTRY } from "@/lib/sql/clickhouse/functionRegistry";
-
-describe("ClickHouse aggregate combinators", () => {
- it("generates If with an appended condition argument", () => {
- const sumIf = generateAggregateCombinatorCandidates("sumIf", 20).find((item) => item.name === "sumIf");
- expect(sumIf?.signatures[0].parameterGroups).toEqual([["value", "condition"]]);
- });
-
- it("allows Array before If and rejects the reverse order", () => {
- expect(generateAggregateCombinatorCandidates("uniqArrayIf", 20).some((item) => item.name === "uniqArrayIf")).toBe(true);
- expect(generateAggregateCombinatorCandidates("uniqIfArray", 20).some((item) => item.name === "uniqIfArray")).toBe(false);
- });
-
- it("preserves parametric aggregate groups for State", () => {
- const state = generateAggregateCombinatorCandidates("quantilesTDigestState", 20).find((item) => item.name === "quantilesTDigestState");
- expect(state?.signatures[0].parameterGroups).toEqual([["level", "...levels"], ["expression"]]);
- });
-
- it("bounds generated results", () => {
- expect(generateAggregateCombinatorCandidates("", 7)).toHaveLength(7);
- });
-});
-
-it("contains ordinary and parametric aggregate definitions", () => {
- expect(CLICKHOUSE_FUNCTION_REGISTRY.get("uniqExact")).toMatchObject({ kind: "aggregate" });
- expect(CLICKHOUSE_FUNCTION_REGISTRY.get("quantilesTDigest")?.signatures[0].parameterGroups).toEqual([["level", "...levels"], ["expression"]]);
-});
-```
-
-- [ ] **Step 2: Run both ClickHouse test files and confirm RED**
-
-```bash
-pnpm exec vitest run apps/desktop/src/lib/__tests__/sql/clickhouse/functionRegistry.spec.ts apps/desktop/src/lib/__tests__/sql/clickhouse/aggregateCombinators.spec.ts
-```
-
-Expected: FAIL because aggregate modules and generated candidates do not exist.
-
-- [ ] **Step 3: Add the aggregate inventory**
-
-Create `aggregateFunctions.ts` with a compact helper and explicit parameter groups:
-
-```ts
-import type { ClickHouseFunctionDefinition, ClickHouseFunctionSignature } from "./functionTypes";
-
-const aggregate = (
- name: string,
- signatures: ClickHouseFunctionSignature[],
- options: Partial<ClickHouseFunctionDefinition> = {},
-): ClickHouseFunctionDefinition => ({
- name,
- kind: "aggregate",
- category: "aggregate",
- signatures,
- combinators: true,
- ...options,
-});
-
-export const CLICKHOUSE_AGGREGATE_FUNCTIONS: ClickHouseFunctionDefinition[] = [
- aggregate("count", [{ parameterGroups: [[]] }, { parameterGroups: [["expression"]] }]),
- aggregate("sum", [{ parameterGroups: [["value"]] }]),
- aggregate("uniq", [{ parameterGroups: [["expression", "...expressions"]] }]),
- aggregate("uniqExact", [{ parameterGroups: [["expression", "...expressions"]] }]),
- aggregate("quantilesTDigest", [{ parameterGroups: [["level", "...levels"], ["expression"]] }]),
-];
-```
-
-Add every documented ordinary and parametric aggregate from the snapshot. Mark aggregates that reject generic combinators with `combinators: false`; do not invent signatures for undocumented combinations.
-
-- [ ] **Step 4: Implement ordered combinator rules**
-
-In `aggregateCombinators.ts`, model suffix transitions rather than arbitrary permutations:
-
-```ts
-import { CLICKHOUSE_AGGREGATE_FUNCTIONS } from "./aggregateFunctions";
-import type { ClickHouseFunctionDefinition, ClickHouseFunctionSignature } from "./functionTypes";
-
-type CombinatorName = "Array" | "Map" | "ForEach" | "Distinct" | "If" | "OrDefault" | "OrNull" | "Resample" | "SimpleState" | "State" | "Merge" | "MergeState";
-
-const ORDER: readonly CombinatorName[] = ["Array", "Map", "ForEach", "Distinct", "If", "OrDefault", "OrNull", "Resample", "SimpleState", "State", "Merge", "MergeState"];
-
-function applyIf(signature: ClickHouseFunctionSignature): ClickHouseFunctionSignature {
- const groups = signature.parameterGroups.map((group) => [...group]);
- const target = groups.length - 1;
- groups[target] = [...groups[target], "condition"];
- return { ...signature, parameterGroups: groups };
-}
-```
-
-Add one transformer per documented combinator. Enforce `Array` before `If`, make terminal state/merge combinators stop further suffix expansion where required, and reject cycles. `generateAggregateCombinatorCandidates(prefix, limit)` must traverse only prefixes that can still match the typed text and stop at `limit`.
-
-- [ ] **Step 5: Merge direct aggregates and lazy generated results**
-
-Add direct aggregate definitions to `CLICKHOUSE_FUNCTION_REGISTRY`. Export:
-
-```ts
-export function searchClickHouseFunctions(prefix: string, limit: number, kind?: ClickHouseFunctionKind): ClickHouseFunctionDefinition[] {
- const direct = CLICKHOUSE_FUNCTION_REGISTRY.search(prefix, limit, kind);
- if (kind && kind !== "aggregate") return direct;
- const generated = generateAggregateCombinatorCandidates(prefix, Math.max(0, limit - direct.length));
- return [...direct, ...generated].slice(0, limit);
-}
-```
-
-- [ ] **Step 6: Run tests and confirm GREEN**
-
-Run the two focused files. Expected: all registry and combinator tests PASS.
-
-- [ ] **Step 7: Commit aggregate support**
-
-```bash
-git add apps/desktop/src/lib/sql/clickhouse/aggregateFunctions.ts apps/desktop/src/lib/sql/clickhouse/aggregateCombinators.ts apps/desktop/src/lib/sql/clickhouse/functionRegistry.ts apps/desktop/src/lib/__tests__/sql/clickhouse/functionRegistry.spec.ts apps/desktop/src/lib/__tests__/sql/clickhouse/aggregateCombinators.spec.ts
-git commit -m "feat(sql): add ClickHouse aggregate combinators"
-```
-
-## Task 4: Integrate ClickHouse Functions into SQL Completion
-
-**Files:**
-
-- Modify: `apps/desktop/src/lib/sql/sqlCompletion.ts`
-- Modify: `apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts`
-
-- [ ] **Step 1: Add failing completion tests**
-
-Extend `sqlCompletion.context.spec.ts`:
-
-```ts
-it("suggests ClickHouse functions with canonical casing and preferred placeholders", () => {
- const sql = "SELECT tostart";
- const items = buildSqlCompletionItems(sql, sql.length, { databaseType: "clickhouse", tables: [], columnsByTable: new Map() });
- expect(items.find((item) => item.label === "toStartOfDay")).toMatchObject({ type: "function", apply: "toStartOfDay(${value})" });
-});
-
-it("does not leak ClickHouse-only functions to MySQL", () => {
- const sql = "SELECT tostart";
- const items = buildSqlCompletionItems(sql, sql.length, { databaseType: "mysql", tables: [], columnsByTable: new Map() });
- expect(items.some((item) => item.label === "toStartOfDay")).toBe(false);
-});
-
-it("suggests only ClickHouse table functions alongside tables after FROM", () => {
- const sql = "SELECT * FROM num";
- const items = buildSqlCompletionItems(sql, sql.length, {
- databaseType: "clickhouse",
- tables: [{ name: "number_events", type: "table" }],
- columnsByTable: new Map(),
- });
- expect(items).toEqual(expect.arrayContaining([expect.objectContaining({ label: "numbers", type: "function" }), expect.objectContaining({ label: "number_events", type: "table" })]));
- expect(items.some((item) => item.label === "toStartOfDay")).toBe(false);
-});
-```
-
-Add a cursor-before-existing-parenthesis case:
-
-```ts
-it("does not insert a duplicate opening parenthesis before an existing call", () => {
- const sql = "SELECT toStart()";
- const cursor = "SELECT toStart".length;
- const items = buildSqlCompletionItems(sql, cursor, { databaseType: "clickhouse", tables: [], columnsByTable: new Map() });
- expect(items.find((item) => item.label === "toStartOfDay")?.apply).toBe("toStartOfDay");
-});
-```
-
-- [ ] **Step 2: Run the context test and confirm RED**
-
-```bash
-pnpm exec vitest run apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts
-```
-
-Expected: ClickHouse-specific labels are absent.
-
-- [ ] **Step 3: Add cursor lookahead to completion context**
-
-Add `openingParenAfterCursor: boolean` to `SqlCompletionContext`, populated by `/^\s*\(/.test(sql.slice(cursor))`. Preserve it in semantic-context merging.
-
-- [ ] **Step 4: Adapt registry definitions to completion items**
-
-Import `searchClickHouseFunctions`. Add helpers:
-
-```ts
-function formatFunctionSignatureApply(definition: ClickHouseFunctionDefinition, omitOpeningParen: boolean): string {
- if (omitOpeningParen) return definition.name;
- const signature = definition.signatures[definition.preferredSignature ?? 0];
- return (
- definition.name +
- signature.parameterGroups
- .map((group) => `(${group.filter((parameter) => !parameter.endsWith("?")).map((parameter) => `\${${parameter}}`).join(", ")})`)
- .join("")
- );
-}
-
-function clickHouseFunctionDetail(definition: ClickHouseFunctionDefinition): string {
- const status = definition.status && definition.status !== "stable" ? ` · ${definition.status}` : "";
- const overloads = definition.signatures.length > 1 ? ` · ${definition.signatures.length} overloads` : "";
- return `ClickHouse · ${definition.category}${overloads}${status}`;
-}
-```
-
-In `buildFunctionSnippetItems`, use the ClickHouse registry when `databaseType === "clickhouse"`; retain the existing map path for all other database types. Set `info` to `definition.description` when present. Apply a negative boost to experimental/deprecated definitions and a smaller negative boost to generated variants.
-
-- [ ] **Step 5: Add table-function completion only in table contexts**
-
-Inside the `context.suggestTables` branch, append `kind === "table"` results for ClickHouse. Do not relax `exclusiveTableSuggestions` for scalar or aggregate functions.
-
-- [ ] **Step 6: Run ClickHouse and existing database completion tests**
-
-```bash
-pnpm exec vitest run apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts apps/desktop/src/lib/__tests__/sql/sqlCompletion.snippet.spec.ts
-```
-
-Expected: ClickHouse tests PASS; existing MySQL and snippet tests remain PASS.
-
-- [ ] **Step 7: Commit completion integration**
-
-```bash
-git add apps/desktop/src/lib/sql/sqlCompletion.ts apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts
-git commit -m "feat(sql): complete ClickHouse functions"
-```
-
-## Task 5: Add Overload-Aware and Parametric Signature Resolution
-
-**Files:**
-
-- Modify: `apps/desktop/src/lib/sql/sqlCompletion.ts`
-- Create: `apps/desktop/src/lib/__tests__/sql/sqlCompletion.signature.spec.ts`
-
-- [ ] **Step 1: Write failing ordinary and parametric signature tests**
-
-Create `sqlCompletion.signature.spec.ts`:
-
-```ts
-import { describe, expect, it } from "vitest";
-import { getSqlFunctionSignatureHelp } from "@/lib/sql/sqlCompletion";
-
-describe("ClickHouse signature help", () => {
- it("returns every overload and highlights the active ordinary parameter", () => {
- const sql = "SELECT toStartOfInterval(ts, ";
- const help = getSqlFunctionSignatureHelp(sql, sql.length, "clickhouse");
- expect(help?.name).toBe("toStartOfInterval");
- expect(help?.overloads.length).toBeGreaterThan(1);
- expect(help?.overloads[0].activeGroup).toBe(0);
- expect(help?.overloads[0].activeParameter).toBe(1);
- });
-
- it("resolves the second parameter group of a parametric aggregate", () => {
- const sql = "SELECT quantilesTDigest(0.5, 0.9)(value";
- const help = getSqlFunctionSignatureHelp(sql, sql.length, "clickhouse");
- expect(help?.name).toBe("quantilesTDigest");
- expect(help?.overloads[0]).toMatchObject({ activeGroup: 1, activeParameter: 0 });
- expect(help?.overloads[0].parameterGroups).toEqual([["level", "...levels"], ["expression"]]);
- });
-
- it("keeps MySQL signature help as one overload and one parameter group", () => {
- const sql = "SELECT DATE_ADD(created_at, ";
- const help = getSqlFunctionSignatureHelp(sql, sql.length, "mysql");
- expect(help?.overloads).toHaveLength(1);
- expect(help?.overloads[0].parameterGroups).toEqual([["date", "INTERVAL expr unit"]]);
- });
-});
-```
-
-- [ ] **Step 2: Run the signature test and confirm RED**
-
-```bash
-pnpm exec vitest run apps/desktop/src/lib/__tests__/sql/sqlCompletion.signature.spec.ts
-```
-
-Expected: FAIL because the returned model has no `overloads`.
-
-- [ ] **Step 3: Replace the public signature-help shape**
-
-In `sqlCompletion.ts`:
-
-```ts
-export interface SqlFunctionSignatureHelpOverload {
- signature: string;
- parameterGroups: string[][];
- activeGroup: number;
- activeParameter: number;
-}
-
-export interface SqlFunctionSignatureHelp {
- name: string;
- overloads: SqlFunctionSignatureHelpOverload[];
- activeOverload: number;
-}
-```
-
-- [ ] **Step 4: Resolve the owning call and active group**
-
-Replace the flat `findActiveFunctionOpenParen` path with a helper returning:
-
-```ts
-interface ActiveFunctionCall {
- name: string;
- activeGroup: number;
- groupText: string;
-}
-```
-
-For a normal unmatched `(`, read the identifier directly before it and return group `0`. If the identifier position contains `)`, find that balanced group's opening parenthesis, read the identifier before the first group, and return group `1`. Count commas with the existing quote- and nesting-aware `countTopLevelCommas`.
-
-- [ ] **Step 5: Convert old database maps into one-overload definitions**
-
-When the database is not ClickHouse, wrap the existing `string[]` as `parameterGroups: [parameters]`. For ClickHouse, find an exact case-insensitive match across `searchClickHouseFunctions(name, 50)`, so lazily generated combinator names and aliases resolve as well as direct registry entries. Format all parameter groups into each overload's `signature`, while using the function spelling from the SQL text as the tooltip name.
-
-Rank overloads that can accept the observed parameter index first; keep source order as the stable tiebreaker. Set `activeOverload` to `0`.
-
-- [ ] **Step 6: Run signature and context tests**
-
-```bash
-pnpm exec vitest run apps/desktop/src/lib/__tests__/sql/sqlCompletion.signature.spec.ts apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts
-```
-
-Expected: all tests PASS.
-
-- [ ] **Step 7: Commit signature resolution**
-
-```bash
-git add apps/desktop/src/lib/sql/sqlCompletion.ts apps/desktop/src/lib/__tests__/sql/sqlCompletion.signature.spec.ts
-git commit -m "feat(sql): support ClickHouse function overloads"
-```
-
-## Task 6: Render Multiple Signatures in the Query Editor
-
-**Files:**
-
-- Create: `apps/desktop/src/lib/editor/sqlSignatureTooltip.ts`
-- Create: `apps/desktop/src/lib/__tests__/editor/sqlSignatureTooltip.spec.ts`
-- Modify: `apps/desktop/src/components/editor/QueryEditor.vue`
-
-- [ ] **Step 1: Add a failing real-DOM tooltip test**
-
-Create `sqlSignatureTooltip.spec.ts`:
-
-```ts
-// @vitest-environment happy-dom
-import { describe, expect, it } from "vitest";
-import { createSqlSignatureTooltipDom } from "@/lib/editor/sqlSignatureTooltip";
-
-describe("SQL signature tooltip", () => {
- it("renders every overload and highlights the active parameter in each one", () => {
- const dom = createSqlSignatureTooltipDom({
- name: "toStartOfInterval",
- activeOverload: 0,
- overloads: [
- {
- signature: "toStartOfInterval(value, interval)",
- parameterGroups: [["value", "interval"]],
- activeGroup: 0,
- activeParameter: 1,
- },
- {
- signature: "toStartOfInterval(value, interval, time_zone)",
- parameterGroups: [["value", "interval", "time_zone"]],
- activeGroup: 0,
- activeParameter: 1,
- },
- ],
- });
-
- expect(dom.textContent).toContain("1/2");
- expect(dom.textContent).toContain("2/2");
- expect(dom.textContent).toContain("time_zone");
- expect(dom.querySelectorAll("[data-active-parameter='true']")).toHaveLength(2);
- });
-});
-```
-
-- [ ] **Step 2: Run the editor test and confirm RED**
-
-```bash
-pnpm exec vitest run apps/desktop/src/lib/__tests__/editor/sqlSignatureTooltip.spec.ts
-```
-
-Expected: FAIL because `sqlSignatureTooltip.ts` does not exist.
-
-- [ ] **Step 3: Implement the overload-aware DOM renderer**
-
-Create `sqlSignatureTooltip.ts`:
-
-```ts
-import type { SqlFunctionSignatureHelp } from "@/lib/sql/sqlCompletion";
-
-export function createSqlSignatureTooltipDom(signature: SqlFunctionSignatureHelp | null): HTMLElement {
- const dom = document.createElement("div");
- dom.className = "rounded-md border bg-popover px-3 py-2 text-xs text-popover-foreground shadow-md";
- if (!signature) return dom;
-
- signature.overloads.forEach((overload, overloadIndex) => {
- const row = document.createElement("div");
- row.className = overloadIndex > 0 ? "mt-1 flex items-center gap-2 font-mono" : "flex items-center gap-2 font-mono";
- if (signature.overloads.length > 1) {
- const count = document.createElement("span");
- count.className = "text-[10px] text-muted-foreground";
- count.textContent = `${overloadIndex + 1}/${signature.overloads.length}`;
- row.appendChild(count);
- }
-
- const call = document.createElement("span");
- const name = document.createElement("span");
- name.className = "text-muted-foreground";
- name.textContent = signature.name;
- call.appendChild(name);
-
- overload.parameterGroups.forEach((group, groupIndex) => {
- const open = document.createElement("span");
- open.className = "text-muted-foreground";
- open.textContent = "(";
- call.appendChild(open);
- group.forEach((parameter, parameterIndex) => {
- if (parameterIndex > 0) call.append(", ");
- const node = document.createElement("span");
- const active = groupIndex === overload.activeGroup && parameterIndex === overload.activeParameter;
- node.className = active ? "font-semibold text-foreground" : "text-muted-foreground";
- if (active) node.dataset.activeParameter = "true";
- node.textContent = parameter;
- call.appendChild(node);
- });
- call.append(")");
- });
-
- row.appendChild(call);
- dom.appendChild(row);
- });
- return dom;
-}
-```
-
-- [ ] **Step 4: Wire the renderer into QueryEditor**
-
-Import `createSqlSignatureTooltipDom`, delete the local `createSignatureDom`, and change the signature extension to:
-
-```ts
-create: () => ({ dom: createSqlSignatureTooltipDom(signature) }),
-```
-
-- [ ] **Step 5: Run editor, signature, and context tests**
-
-```bash
-pnpm exec vitest run apps/desktop/src/lib/__tests__/editor/sqlSignatureTooltip.spec.ts apps/desktop/src/lib/__tests__/editor/queryEditorSqlSignature.spec.ts apps/desktop/src/lib/__tests__/sql/sqlCompletion.signature.spec.ts apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts
-```
-
-Expected: all tests PASS.
-
-- [ ] **Step 6: Commit tooltip rendering**
-
-```bash
-git add apps/desktop/src/lib/editor/sqlSignatureTooltip.ts apps/desktop/src/lib/__tests__/editor/sqlSignatureTooltip.spec.ts apps/desktop/src/components/editor/QueryEditor.vue
-git commit -m "feat(editor): render SQL function overloads"
-```
-
-## Task 7: Audit Coverage and Run Full Verification
-
-**Files:**
-
-- Modify only if verification finds an issue: files from Tasks 1–6.
-
-- [ ] **Step 1: Run registry integrity and review category floors**
-
-```bash
-pnpm exec vitest run apps/desktop/src/lib/__tests__/sql/clickhouse/functionRegistry.spec.ts apps/desktop/src/lib/__tests__/sql/clickhouse/aggregateCombinators.spec.ts
-```
-
-Expected: all tests PASS; every checked-in category floor equals its reviewed inventory count.
-
-- [ ] **Step 2: Run the complete SQL completion test set**
-
-```bash
-pnpm exec vitest run apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts apps/desktop/src/lib/__tests__/sql/sqlCompletion.snippet.spec.ts apps/desktop/src/lib/__tests__/sql/sqlCompletion.signature.spec.ts apps/desktop/src/lib/__tests__/sql/semantic/completion.spec.ts apps/desktop/src/lib/__tests__/editor/sqlSignatureTooltip.spec.ts apps/desktop/src/lib/__tests__/editor/queryEditorSqlSignature.spec.ts
-```
-
-Expected: all tests PASS with zero failures.
-
-- [ ] **Step 3: Run TypeScript checking**
-
-```bash
-pnpm typecheck
-```
-
-Expected: exit code 0 with no Vue or TypeScript errors.
-
-- [ ] **Step 4: Run lint on every changed TypeScript and Vue file**
-
-```bash
-pnpm exec oxlint --vue-plugin \
- apps/desktop/src/lib/sql/clickhouse \
- apps/desktop/src/lib/sql/sqlCompletion.ts \
- apps/desktop/src/lib/editor/sqlSignatureTooltip.ts \
- apps/desktop/src/components/editor/QueryEditor.vue \
- apps/desktop/src/lib/__tests__/sql/clickhouse \
- apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts \
- apps/desktop/src/lib/__tests__/sql/sqlCompletion.signature.spec.ts \
- apps/desktop/src/lib/__tests__/editor/sqlSignatureTooltip.spec.ts \
- apps/desktop/src/lib/__tests__/editor/queryEditorSqlSignature.spec.ts
-```
-
-Expected: exit code 0 with no lint errors.
-
-- [ ] **Step 5: Inspect the final diff against the approved design**
-
-```bash
-git diff --check
-git status --short
-git log --oneline -7
-```
-
-Confirm that:
-
-- no backend or server metadata query was added;
-- ClickHouse names retain canonical casing;
-- regular, aggregate, window, and table functions are represented;
-- overloads and multiple parameter groups are tested;
-- invalid combinator order is rejected;
-- non-ClickHouse regression tests pass;
-- only the planned files changed.
-
-- [ ] **Step 6: Commit any verification-only corrections**
-
-If Step 1–5 required a correction, stage only the corrected planned files and commit:
-
-```bash
-git commit -m "fix(sql): complete ClickHouse function verification"
-```
-
-If no correction was required, do not create an empty commit.
diff --git a/docs/superpowers/plans/2026-08-01-data-transfer-tree-selection.md b/docs/superpowers/plans/2026-08-01-data-transfer-tree-selection.md
deleted file mode 100644
index 9d1cfa7f60..0000000000
--- a/docs/superpowers/plans/2026-08-01-data-transfer-tree-selection.md
+++ /dev/null
@@ -1,1620 +0,0 @@
-# Data Transfer: Tree Object Selection and Transfer Modes — Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Turn the data transfer dialog's flat table picker into a type-grouped object tree (tables/views/procedures/functions/triggers/sequences/events) with three transfer modes (structure+data / structure only / data only), and copy non-table object DDL for PostgreSQL-family, MySQL, and Oracle/Dameng.
-
-**Architecture:** Backend `TransferRequest` gains `content` (TransferContent) and `objects` (Vec<TransferObjectSelection>); a new family-aware object transfer executor (`transfer_schema_objects`) runs after table data transfer, checking target existence per object (skip + count) and executing DDL in dependency order (sequences → views → functions → procedures → triggers → events). Frontend `DataTransferDialog.vue` swaps the flat list for an `ObjectSelectionTree` group component and a three-way content mode selector.
-
-**Tech Stack:** Rust (dbx-core, dbx-web), Vue 3 + TypeScript + Vitest (apps/desktop), i18n locales.
-
-**Branch:** create `feature/data-transfer-tree-selection` from current HEAD. The `docs/superpowers/` directory is git-ignored and never committed.
-
-**Spec:** `docs/superpowers/specs/2026-08-01-data-transfer-tree-selection-design.md` (local, untracked).
-
----
-
-## Task 0: Branch setup
-
-- [ ] **Step 1: Create the feature branch**
-
-```bash
-cd /d/git-clone-project/dbx && git checkout -b feature/data-transfer-tree-selection
-```
-
-Expected: switched to new branch. Note: it will carry the committed dameng-drop-schema fix (75238cde3) forward.
-
----
-
-## Task 1: Backend protocol — TransferContent / TransferObjectKind / TransferObjectSelection
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs` (after `TransferMode` definition, ~line 67; and `TransferRequest` struct at line 80)
-
-- [ ] **Step 1: Write the failing test** — add a `#[cfg(test)] mod protocol_tests` at the end of `transfer.rs` asserting serde round-trips and defaults:
-
-```rust
-#[cfg(test)]
-mod transfer_protocol_tests {
- use super::*;
-
- #[test]
- fn transfer_content_defaults_to_structure_and_data() {
- let request: TransferRequest = serde_json::from_value(serde_json::json!({
- "transferId": "t1", "sourceConnectionId": "s", "sourceDatabase": "db",
- "sourceSchema": "public", "targetConnectionId": "t", "targetDatabase": "db",
- "targetSchema": "public", "tables": ["a"], "createTable": true,
- "mode": "append", "targetTableNameCase": "preserve", "batchSize": 1000
- })).unwrap();
- assert_eq!(request.content, TransferContent::StructureAndData);
- assert!(request.objects.is_empty());
- }
-
- #[test]
- fn transfer_request_serializes_new_fields_camel_case() {
- let request = TransferRequest {
- transfer_id: "t1".into(), source_connection_id: "s".into(),
- source_database: "db".into(), source_schema: "public".into(), source_catalog: None,
- target_connection_id: "t".into(), target_database: "db".into(),
- target_schema: "public".into(), target_catalog: None,
- tables: vec!["a".into()], create_table: true,
- mode: TransferMode::Append, target_table_name_case: TransferTableNameCase::Preserve,
- ownership_policy: TransferOwnershipPolicy::Preserve, batch_size: 1000,
- content: TransferContent::StructureOnly,
- objects: vec![TransferObjectSelection {
- object_type: TransferObjectKind::View,
- names: vec!["v1".into()],
- }],
- };
- let json = serde_json::to_value(&request).unwrap();
- assert_eq!(json["content"], "structureOnly");
- assert_eq!(json["objects"][0]["objectType"], "VIEW");
- assert_eq!(json["objects"][0]["names"][0], "v1");
- }
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core transfer_protocol_tests 2>&1 | tail -5`
-Expected: FAIL — `content`/`objects` fields and enums do not exist yet.
-
-- [ ] **Step 3: Implement the protocol types** — insert after the `TransferMode` enum (line ~67):
-
-```rust
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
-#[serde(rename_all = "camelCase")]
-pub enum TransferContent {
- #[default]
- StructureAndData,
- StructureOnly,
- DataOnly,
-}
-
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum TransferObjectKind {
- Table,
- View,
- MaterializedView,
- Procedure,
- Function,
- Trigger,
- Sequence,
- Event,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
-pub struct TransferObjectSelection {
- pub object_type: TransferObjectKind,
- pub names: Vec<String>,
-}
-```
-
-Add to `TransferRequest` (after `tables`, keeping `create_table` for wire compatibility):
-
-```rust
- #[serde(default)]
- pub content: TransferContent,
- #[serde(default)]
- pub objects: Vec<TransferObjectSelection>,
-```
-
-Note: `TransferRequest` is constructed in tests (`transfer.rs:5364` area uses `create_table: true`) and in `crates/dbx-core/tests/live_postgres_transfer.rs` — all construction sites need the two new fields added. Fix compile errors by adding `content: TransferContent::default(), objects: Vec::new(),` wherever a literal is built.
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core transfer_protocol_tests 2>&1 | tail -5`
-Expected: PASS (2 tests).
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): add content and object selection protocol fields"
-```
-
----
-
-## Task 2: Transfer object families and per-family kind tables
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs`
-
-- [ ] **Step 1: Write the failing test** (module `transfer_family_tests`):
-
-```rust
-#[test]
-fn same_family_matrix() {
- // postgres family
- assert!(is_same_transfer_family(&DatabaseType::Postgres, &DatabaseType::Kingbase));
- assert!(is_same_transfer_family(&DatabaseType::Gaussdb, &DatabaseType::OpenGauss));
- // oracle family
- assert!(is_same_transfer_family(&DatabaseType::Oracle, &DatabaseType::Dameng));
- assert!(is_same_transfer_family(&DatabaseType::OceanbaseOracle, &DatabaseType::Dameng));
- // mysql
- assert!(is_same_transfer_family(&DatabaseType::Mysql, &DatabaseType::Mysql));
- // cross family
- assert!(!is_same_transfer_family(&DatabaseType::Mysql, &DatabaseType::Postgres));
- assert!(!is_same_transfer_family(&DatabaseType::Mysql, &DatabaseType::SqlServer));
-}
-
-#[test]
-fn object_kinds_per_family() {
- let mysql = transfer_object_kinds(&DatabaseType::Mysql);
- assert!(mysql.contains(&TransferObjectKind::Event));
- assert!(!mysql.contains(&TransferObjectKind::Sequence));
- let pg = transfer_object_kinds(&DatabaseType::Postgres);
- assert!(pg.contains(&TransferObjectKind::Sequence));
- assert!(!pg.contains(&TransferObjectKind::Event));
- let dm = transfer_object_kinds(&DatabaseType::Dameng);
- assert!(dm.contains(&TransferObjectKind::Trigger));
- assert!(dm.contains(&TransferObjectKind::Sequence));
- assert!(transfer_object_kinds(&DatabaseType::Sqlite).is_empty());
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core transfer_family_tests 2>&1 | tail -5`
-Expected: FAIL — functions undefined.
-
-- [ ] **Step 3: Implement** — add near the top of `transfer.rs`:
-
-```rust
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum TransferObjectFamily { Mysql, Postgres, Oracle }
-
-pub fn transfer_object_family(db_type: &DatabaseType) -> Option<TransferObjectFamily> {
- match db_type {
- DatabaseType::Mysql => Some(TransferObjectFamily::Mysql),
- DatabaseType::Postgres
- | DatabaseType::Kingbase
- | DatabaseType::Gaussdb
- | DatabaseType::Kwdb
- | DatabaseType::OpenGauss => Some(TransferObjectFamily::Postgres),
- DatabaseType::Oracle | DatabaseType::Dameng | DatabaseType::OceanbaseOracle => {
- Some(TransferObjectFamily::Oracle)
- }
- _ => None,
- }
-}
-
-pub fn is_same_transfer_family(a: &DatabaseType, b: &DatabaseType) -> bool {
- match (transfer_object_family(a), transfer_object_family(b)) {
- (Some(fa), Some(fb)) => fa == fb,
- _ => false,
- }
-}
-
-pub fn transfer_object_kinds(db_type: &DatabaseType) -> Vec<TransferObjectKind> {
- use TransferObjectKind::*;
- match transfer_object_family(db_type) {
- Some(TransferObjectFamily::Mysql) => {
- vec![Table, View, Procedure, Function, Trigger, Event]
- }
- Some(TransferObjectFamily::Postgres) => {
- vec![Table, View, MaterializedView, Procedure, Function, Trigger, Sequence]
- }
- Some(TransferObjectFamily::Oracle) => {
- vec![Table, View, MaterializedView, Procedure, Function, Trigger, Sequence]
- }
- None => Vec::new(),
- }
-}
-```
-
-Check `DatabaseType` variant names in `crates/dbx-core/src/models/connection.rs` (OceanbaseOracle may be `OceanbaseOracle` — verify; `Kwdb`/`Gaussdb` exist per `build_drop_schema_sql` match at line 583).
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core transfer_family_tests 2>&1 | tail -5`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): add object transfer families and per-family kind tables"
-```
-
----
-
-## Task 3: Request validation for content and objects
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs` (extend `validate_transfer_target_table_names` area — add a new `validate_transfer_request`)
-
-- [ ] **Step 1: Write the failing test**:
-
-```rust
-#[test]
-fn validates_content_and_object_rules() {
- let base = TransferRequest {
- transfer_id: "t".into(), source_connection_id: "s".into(), source_database: "db".into(),
- source_schema: "public".into(), source_catalog: None, target_connection_id: "t".into(),
- target_database: "db".into(), target_schema: "public".into(), target_catalog: None,
- tables: vec!["a".into()], create_table: true, mode: TransferMode::Append,
- target_table_name_case: TransferTableNameCase::Preserve,
- ownership_policy: TransferOwnershipPolicy::Preserve, batch_size: 1000,
- content: TransferContent::DataOnly, objects: Vec::new(),
- };
- assert!(validate_transfer_request(&base).is_ok());
-
- let with_objects = TransferRequest {
- objects: vec![TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v".into()] }],
- ..base.clone()
- };
- // DataOnly + objects → error
- assert!(validate_transfer_request(&with_objects).is_err());
-
- let structure_only = TransferRequest { content: TransferContent::StructureOnly, ..base.clone() };
- assert!(validate_transfer_request(&structure_only).is_ok());
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core validates_content_and_object_rules 2>&1 | tail -5`
-Expected: FAIL — function undefined.
-
-- [ ] **Step 3: Implement**:
-
-```rust
-pub fn validate_transfer_request(request: &TransferRequest) -> Result<(), String> {
- validate_transfer_target_table_names(request)?;
- if matches!(request.content, TransferContent::DataOnly) && !request.objects.is_empty() {
- return Err("仅数据模式不传输非表对象".to_string());
- }
- for selection in &request.objects {
- if selection.names.is_empty() {
- return Err(format!("Object selection for {:?} is empty", selection.object_type));
- }
- for name in &selection.names {
- if name.trim().is_empty() || name.contains('\0') {
- return Err(format!("Invalid object name: {name:?}"));
- }
- }
- }
- Ok(())
-}
-```
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core validates_content_and_object_rules 2>&1 | tail -5`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): validate transfer content and object selections"
-```
-
----
-
-## Task 4: Target-side object existence check SQL (per family)
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs`
-
-- [ ] **Step 1: Write the failing test**:
-
-```rust
-#[test]
-fn builds_target_existence_check_sql_per_family() {
- let mysql = target_object_exists_sql(&DatabaseType::Mysql, "shop", "v1", &TransferObjectKind::View).unwrap();
- assert!(mysql.contains("information_schema.TABLES"));
- assert!(mysql.contains("TABLE_TYPE = 'VIEW'"));
- let mysql_ev = target_object_exists_sql(&DatabaseType::Mysql, "shop", "e1", &TransferObjectKind::Event).unwrap();
- assert!(mysql_ev.contains("information_schema.EVENTS"));
- let mysql_tr = target_object_exists_sql(&DatabaseType::Mysql, "shop", "t1", &TransferObjectKind::Trigger).unwrap();
- assert!(mysql_tr.contains("information_schema.TRIGGERS"));
- let pg = target_object_exists_sql(&DatabaseType::Postgres, "public", "v1", &TransferObjectKind::View).unwrap();
- assert!(pg.contains("pg_class"));
- let orc = target_object_exists_sql(&DatabaseType::Oracle, "HR", "SEQ1", &TransferObjectKind::Sequence).unwrap();
- assert!(orc.contains("ALL_OBJECTS"));
- assert!(target_object_exists_sql(&DatabaseType::Sqlite, "m", "x", &TransferObjectKind::View).is_err());
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core builds_target_existence_check_sql 2>&1 | tail -5`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement**:
-
-```rust
-/// Returns a SQL statement selecting 1 row when `name` exists in `schema`
-/// on the target side; None-kind support per family mirrors
-/// `transfer_object_kinds`.
-pub fn target_object_exists_sql(
- db_type: &DatabaseType,
- schema: &str,
- name: &str,
- kind: &TransferObjectKind,
-) -> Result<String, String> {
- let schema = quote_string_literal(schema);
- let name = quote_string_literal(name);
- let q = |literal: &str| literal.to_string();
- let sql = match (transfer_object_family(db_type), kind) {
- (Some(TransferObjectFamily::Mysql), TransferObjectKind::Table | TransferObjectKind::View) => format!(
- "SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = {schema} AND TABLE_NAME = {name} \
- AND TABLE_TYPE {} 'VIEW'",
- if matches!(kind, TransferObjectKind::View) { "=" } else { "<>" }
- ),
- (Some(TransferObjectFamily::Mysql), TransferObjectKind::Procedure | TransferObjectKind::Function) => format!(
- "SELECT 1 FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = {schema} AND ROUTINE_NAME = {name} \
- AND ROUTINE_TYPE = {}",
- q(if matches!(kind, TransferObjectKind::Procedure) { "'PROCEDURE'" } else { "'FUNCTION'" })
- ),
- (Some(TransferObjectFamily::Mysql), TransferObjectKind::Trigger) => format!(
- "SELECT 1 FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = {schema} AND TRIGGER_NAME = {name}"
- ),
- (Some(TransferObjectFamily::Mysql), TransferObjectKind::Event) => format!(
- "SELECT 1 FROM information_schema.EVENTS WHERE EVENT_SCHEMA = {schema} AND EVENT_NAME = {name}"
- ),
- (Some(TransferObjectFamily::Postgres), TransferObjectKind::View | TransferObjectKind::MaterializedView) => format!(
- "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
- WHERE n.nspname = {schema} AND c.relname = {name} AND c.relkind {}",
- if matches!(kind, TransferObjectKind::MaterializedView) { "= 'm'" } else { "= 'v'" }
- ),
- (Some(TransferObjectFamily::Postgres), TransferObjectKind::Table) => format!(
- "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
- WHERE n.nspname = {schema} AND c.relname = {name} AND c.relkind = 'r'"
- ),
- (Some(TransferObjectFamily::Postgres), TransferObjectKind::Procedure | TransferObjectKind::Function) => format!(
- "SELECT 1 FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
- WHERE n.nspname = {schema} AND p.proname = {name}"
- ),
- (Some(TransferObjectFamily::Postgres), TransferObjectKind::Sequence) => format!(
- "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
- WHERE n.nspname = {schema} AND c.relname = {name} AND c.relkind = 'S'"
- ),
- (Some(TransferObjectFamily::Postgres), TransferObjectKind::Trigger) => format!(
- "SELECT 1 FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid \
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
- WHERE n.nspname = {schema} AND t.tgname = {name} AND NOT t.tgisinternal"
- ),
- (Some(TransferObjectFamily::Oracle), TransferObjectKind::View
- | TransferObjectKind::MaterializedView
- | TransferObjectKind::Procedure
- | TransferObjectKind::Function
- | TransferObjectKind::Trigger
- | TransferObjectKind::Sequence) => format!(
- "SELECT 1 FROM ALL_OBJECTS WHERE OWNER = {schema} AND OBJECT_NAME = {name} AND OBJECT_TYPE = {}",
- q(match kind {
- TransferObjectKind::View => "'VIEW'",
- TransferObjectKind::MaterializedView => "'MATERIALIZED VIEW'",
- TransferObjectKind::Procedure => "'PROCEDURE'",
- TransferObjectKind::Function => "'FUNCTION'",
- TransferObjectKind::Trigger => "'TRIGGER'",
- _ => "'SEQUENCE'",
- })
- ),
- _ => return Err(format!("Object existence check not supported for {:?} {:?}", db_type, kind)),
- };
- Ok(sql)
-}
-```
-
-Verify `quote_string_literal` exists in transfer.rs (used at line 3717) — yes.
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core builds_target_existence_check_sql 2>&1 | tail -5`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): target object existence check SQL per family"
-```
-
----
-
-## Task 5: MySQL list_objects gains TRIGGER and EVENT
-
-**Files:**
-- Modify: `crates/dbx-core/src/db/mysql.rs` (`list_objects` at 2844, `wants_table_objects`/`wants_routine_objects` at 2722, `object_query_supports_paging` at 2825)
-
-- [ ] **Step 1: Write the failing test** — add to existing test module in mysql.rs (pattern: `assert!(sql.contains("information_schema.TRIGGERS"))` at 5004):
-
-```rust
-#[test]
-fn lists_triggers_and_events_via_information_schema() {
- let sql = list_triggers_objects_sql("shop");
- assert!(sql.contains("information_schema.TRIGGERS"));
- assert!(sql.contains("TRIGGER_SCHEMA = 'shop'"));
- let sql = list_events_objects_sql("shop");
- assert!(sql.contains("information_schema.EVENTS"));
- assert!(sql.contains("EVENT_SCHEMA = 'shop'"));
- assert!(wants_trigger_objects(Some(&["TRIGGER".to_string()])));
- assert!(!wants_trigger_objects(Some(&["TABLE".to_string()])));
- assert!(wants_event_objects(Some(&["EVENT".to_string()])));
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core lists_triggers_and_events 2>&1 | tail -5`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement** — add functions mirroring `list_completion_triggers_sql` (2791) and `list_routines_sql` (2763):
-
-```rust
-fn wants_trigger_objects(object_types: Option<&[String]>) -> bool {
- requested_object_type(object_types, "TRIGGER")
-}
-fn wants_event_objects(object_types: Option<&[String]>) -> bool {
- requested_object_type(object_types, "EVENT")
-}
-
-fn list_triggers_objects_sql(database: &str) -> String {
- format!(
- "SELECT TRIGGER_NAME AS object_name, 'TRIGGER' AS object_type, NULL AS object_comment, \
- CREATED AS created_at, NULL AS updated_at, \
- TRIGGER_SCHEMA AS parent_schema, EVENT_OBJECT_TABLE AS parent_name, \
- 5 AS sort_order \
- FROM information_schema.TRIGGERS \
- WHERE TRIGGER_SCHEMA = {} \
- ORDER BY object_name",
- quote_value(database)
- )
-}
-
-fn list_events_objects_sql(database: &str) -> String {
- format!(
- "SELECT EVENT_NAME AS object_name, 'EVENT' AS object_type, NULL AS object_comment, \
- CREATED AS created_at, LAST_ALTERED AS updated_at, \
- EVENT_SCHEMA AS parent_schema, NULL AS parent_name, \
- 6 AS sort_order \
- FROM information_schema.EVENTS \
- WHERE EVENT_SCHEMA = {} \
- ORDER BY object_name",
- quote_value(database)
- )
-}
-```
-
-Wire into `list_objects` (after the routines block): fetch both lists when `wants_trigger_objects`/`wants_event_objects` and extend `objects` with `row_to_object`. Verify `requested_object_type`/`quote_value`/`row_to_object` signatures and reuse them.
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core lists_triggers_and_events 2>&1 | tail -5`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/db/mysql.rs
-git commit -m "feat(mysql): list triggers and events for object browsing"
-```
-
----
-
-## Task 6: MySQL object DDL assembly for transfer
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs`
-
-- [ ] **Step 1: Write the failing test** (pure-string functions; no DB needed):
-
-```rust
-#[test]
-fn strips_mysql_definer_clauses() {
- assert_eq!(
- strip_mysql_definer("CREATE DEFINER=`u`@`%` VIEW v AS SELECT 1"),
- "CREATE VIEW v AS SELECT 1"
- );
- assert_eq!(strip_mysql_definer("CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` VIEW v AS SELECT 1"),
- "CREATE ALGORITHM=UNDEFINED VIEW v AS SELECT 1");
- assert_eq!(strip_mysql_definer("CREATE PROCEDURE p() BEGIN END"), "CREATE PROCEDURE p() BEGIN END");
-}
-
-#[test]
-fn rewrites_mysql_schema_qualifiers() {
- assert_eq!(
- rewrite_mysql_schema_qualifier("CREATE VIEW `src`.`v` AS SELECT 1 FROM `src`.`t`", "src", "dst"),
- "CREATE VIEW `dst`.`v` AS SELECT 1 FROM `dst`.`t`"
- );
-}
-
-#[test]
-fn assembles_mysql_trigger_and_event_ddl() {
- let trigger = mysql_trigger_ddl("shop", "trg1", "BEFORE", "INSERT", "users", "SET NEW.updated = NOW()");
- assert_eq!(trigger, "CREATE TRIGGER `trg1` BEFORE INSERT ON `shop`.`users` FOR EACH ROW SET NEW.updated = NOW()");
- let event = mysql_event_ddl("shop", "ev1", "ENABLE", "EVERY 1 DAY", "DELETE FROM logs");
- assert_eq!(event, "CREATE EVENT `ev1` ON SCHEDULE EVERY 1 DAY ENABLE DO DELETE FROM logs");
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core strips_mysql_definer_clauses 2>&1 | tail -5`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement** — pure functions in `transfer.rs`:
-
-```rust
-/// Remove `DEFINER=`user`@`host`` tokens from MySQL DDL (they are not
-/// transferable and frequently reference accounts that don't exist on target).
-pub fn strip_mysql_definer(ddl: &str) -> String {
- let re = Regex::new(r"(?i)\bDEFINER\s*=\s*`[^`]*`@`[^`]*`\s*").unwrap();
- re.replace_all(ddl, "").to_string()
-}
-
-/// Rewrite backtick-qualified `schema`.`name` references from `source_schema`
-/// to `target_schema` in MySQL DDL.
-pub fn rewrite_mysql_schema_qualifier(ddl: &str, source_schema: &str, target_schema: &str) -> String {
- if source_schema == target_schema || source_schema.is_empty() {
- return ddl.to_string();
- }
- let re = Regex::new(&format!(r"`{}`\.", regex::escape(source_schema))).unwrap();
- re.replace_all(ddl, &format!("`{}`.", target_schema)).to_string()
-}
-
-pub fn mysql_trigger_ddl(schema: &str, name: &str, timing: &str, manipulation: &str, table: &str, statement: &str) -> String {
- format!(
- "CREATE TRIGGER `{name}` {timing} {manipulation} ON `{schema}`.`{table}` FOR EACH ROW {statement}",
- name = name, timing = timing, manipulation = manipulation,
- schema = schema, table = table, statement = statement.trim()
- )
-}
-
-pub fn mysql_event_ddl(schema: &str, name: &str, status: &str, schedule: &str, body: &str) -> String {
- format!(
- "CREATE EVENT `{name}` ON SCHEDULE {schedule} {status} DO {body}",
- name = name, schedule = schedule, status = status, body = body.trim()
- )
-}
-```
-
-Note: `Regex` is already imported in transfer.rs (line 1).
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core strips_mysql_definer_clauses 2>&1 | tail -5`
-Expected: PASS (3 tests).
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): mysql object DDL helpers (definer strip, schema rewrite, trigger/event assembly)"
-```
-
----
-
-## Task 7: MySQL object source fetching for transfer
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs`
-
-- [ ] **Step 1: Write the failing test** (SQL generation only):
-
-```rust
-#[test]
-fn builds_mysql_object_source_queries() {
- let sql = mysql_object_source_query(&TransferObjectKind::View, "shop", "v1").unwrap();
- assert!(sql.contains("SHOW CREATE VIEW"));
- let sql = mysql_object_source_query(&TransferObjectKind::Trigger, "shop", "trg1").unwrap();
- assert!(sql.contains("information_schema.TRIGGERS"));
- assert!(sql.contains("TRIGGER_NAME = 'trg1'"));
- let sql = mysql_object_source_query(&TransferObjectKind::Event, "shop", "ev1").unwrap();
- assert!(sql.contains("information_schema.EVENTS"));
- assert!(sql.contains("EVENT_NAME = 'ev1'"));
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core builds_mysql_object_source_queries 2>&1 | tail -5`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement**:
-
-```rust
-/// Builds the query that fetches DDL for one MySQL object.
-/// - View/Procedure/Function → `SHOW CREATE ...` (existing
-/// `schema::mysql_object_source_sql` shape; reuse it by importing the
-/// function or duplicating the format strings).
-/// - Trigger → information_schema.TRIGGERS row (timing/manipulation/table/
-/// statement) via `mysql_trigger_ddl`.
-/// - Event → information_schema.EVENTS row via `mysql_event_ddl`.
-pub fn mysql_object_source_query(
- kind: &TransferObjectKind,
- database: &str,
- name: &str,
-) -> Result<String, String> {
- let db = quote_string_literal(database);
- let n = quote_string_literal(name);
- let ddl = match kind {
- TransferObjectKind::View => format!("SHOW CREATE VIEW `{database}`.`{name}`"),
- TransferObjectKind::Procedure => format!("SHOW CREATE PROCEDURE `{database}`.`{name}`"),
- TransferObjectKind::Function => format!("SHOW CREATE FUNCTION `{database}`.`{name}`"),
- TransferObjectKind::Trigger => format!(
- "SELECT TRIGGER_NAME, ACTION_TIMING, EVENT_MANIPULATION, EVENT_OBJECT_TABLE, ACTION_STATEMENT \
- FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = {db} AND TRIGGER_NAME = {n}"
- ),
- TransferObjectKind::Event => format!(
- "SELECT EVENT_NAME, STATUS, EXECUTE_AT, INTERVAL_VALUE, INTERVAL_FIELD, EVENT_DEFINITION \
- FROM information_schema.EVENTS WHERE EVENT_SCHEMA = {db} AND EVENT_NAME = {n}"
- ),
- _ => return Err(format!("MySQL object source not supported for {:?}", kind)),
- };
- Ok(ddl)
-}
-```
-
-Also implement `mysql_object_ddl_from_result(kind, rows) -> Result<String, String>` mapping query rows to a single DDL string (SHOW CREATE column index: view=1, routine=2 — same convention as `schema::mysql_object_source_ddl_column_index`; trigger/event assembled from row cells). Add a unit test asserting the extraction for each kind with a fake `db::QueryResult`.
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core mysql_object_source_query 2>&1 | tail -5`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): mysql per-object DDL query and row extraction"
-```
-
----
-
-## Task 8: Oracle/Dameng object DDL via DBMS_METADATA for transfer
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs`
-
-- [ ] **Step 1: Write the failing test**:
-
-```rust
-#[test]
-fn builds_oracle_object_source_query() {
- let sql = oracle_object_source_query(&TransferObjectKind::Trigger, "HR", "TRG1").unwrap();
- assert!(sql.contains("DBMS_METADATA.GET_DDL('TRIGGER', 'TRG1', 'HR')"));
- let sql = oracle_object_source_query(&TransferObjectKind::Sequence, "HR", "SEQ1").unwrap();
- assert!(sql.contains("DBMS_METADATA.GET_DDL('SEQUENCE', 'SEQ1', 'HR')"));
- let sql = oracle_object_source_query(&TransferObjectKind::View, "", "V1").unwrap();
- assert!(!sql.contains(",'"));
-}
-
-#[test]
-fn rewrites_oracle_schema_qualifiers() {
- let ddl = "CREATE OR REPLACE TRIGGER \"HR\".\"TRG1\" ...";
- assert_eq!(rewrite_oracle_schema_qualifier(ddl, "HR", "APP"), "CREATE OR REPLACE TRIGGER \"APP\".\"TRG1\" ...");
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core builds_oracle_object_source_query 2>&1 | tail -5`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement**:
-
-```rust
-pub fn oracle_object_source_query(kind: &TransferObjectKind, schema: &str, name: &str) -> Result<String, String> {
- let object_type = match kind {
- TransferObjectKind::View => "VIEW",
- TransferObjectKind::MaterializedView => "MATERIALIZED_VIEW",
- TransferObjectKind::Procedure => "PROCEDURE",
- TransferObjectKind::Function => "FUNCTION",
- TransferObjectKind::Trigger => "TRIGGER",
- TransferObjectKind::Sequence => "SEQUENCE",
- _ => return Err(format!("Oracle object source not supported for {:?}", kind)),
- };
- let name_lit = quote_string_literal(name);
- if schema.trim().is_empty() {
- Ok(format!("SELECT DBMS_METADATA.GET_DDL({}, {}) FROM DUAL", quote_string_literal(object_type), name_lit))
- } else {
- Ok(format!(
- "SELECT DBMS_METADATA.GET_DDL({}, {}, {}) FROM DUAL",
- quote_string_literal(object_type),
- name_lit,
- quote_string_literal(schema)
- ))
- }
-}
-
-/// Rewrite `"SCHEMA"."NAME"` occurrences in Oracle/DM metadata DDL from
-/// source_schema to target_schema.
-pub fn rewrite_oracle_schema_qualifier(ddl: &str, source_schema: &str, target_schema: &str) -> String {
- if source_schema == target_schema || source_schema.is_empty() {
- return ddl.to_string();
- }
- let re = Regex::new(&format!(r#""{}"\."# , regex::escape(source_schema))).unwrap();
- re.replace_all(ddl, &format!("\"{target_schema}\".")).to_string()
-}
-```
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core builds_oracle_object_source_query 2>&1 | tail -5`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): oracle/dameng object DDL helpers"
-```
-
----
-
-## Task 9: Generic object transfer executor with skip-existing and ordering
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs`
-
-- [ ] **Step 1: Write the failing test** (pure ordering helper):
-
-```rust
-#[test]
-fn orders_object_selections_by_dependency() {
- let kinds = vec![
- TransferObjectKind::Trigger, TransferObjectKind::View, TransferObjectKind::Sequence,
- TransferObjectKind::Event, TransferObjectKind::Procedure, TransferObjectKind::Function,
- ];
- let ordered = ordered_transfer_object_kinds(kinds.iter().copied().collect());
- // sequences → views → functions → procedures → triggers → events
- assert_eq!(ordered[0], TransferObjectKind::Sequence);
- assert_eq!(ordered[1], TransferObjectKind::View);
- assert_eq!(ordered[2], TransferObjectKind::Function);
- assert_eq!(ordered[3], TransferObjectKind::Procedure);
- assert_eq!(ordered[4], TransferObjectKind::Trigger);
- assert_eq!(ordered[5], TransferObjectKind::Event);
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core orders_object_selections 2>&1 | tail -5`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement** — ordering + executor skeleton:
-
-```rust
-pub fn ordered_transfer_object_kinds(kinds: Vec<TransferObjectKind>) -> Vec<TransferObjectKind> {
- let rank = |kind: &TransferObjectKind| match kind {
- TransferObjectKind::Table => 0,
- TransferObjectKind::Sequence => 1,
- TransferObjectKind::View => 2,
- TransferObjectKind::MaterializedView => 2,
- TransferObjectKind::Function => 3,
- TransferObjectKind::Procedure => 4,
- TransferObjectKind::Trigger => 5,
- TransferObjectKind::Event => 6,
- };
- let mut kinds = kinds;
- kinds.sort_by_key(rank);
- kinds
-}
-
-#[derive(Debug, Clone, Default, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TransferObjectOutcome {
- pub transferred: Vec<String>,
- pub skipped: Vec<String>,
- pub failed: Vec<String>,
-}
-```
-
-Then the executor (async, one function per family):
-
-```rust
-/// Transfers selected non-table objects from source to target.
-/// Skips objects that already exist on the target; counts them in the
-/// outcome. Executes in dependency order (sequence → view → function →
-/// procedure → trigger → event). Errors are collected per object and the
-/// transfer continues.
-pub async fn transfer_schema_objects<F>(
- state: &AppState,
- request: &TransferRequest,
- source_pool_key: &str,
- target_pool_key: &str,
- mut progress_callback: F,
-) -> Result<TransferObjectOutcome, String>
-where
- F: FnMut(TransferProgress),
-{
- if request.objects.is_empty() {
- return Ok(TransferObjectOutcome::default());
- }
- let source_db_type = get_db_type(state, &request.source_connection_id).await?;
- let target_db_type = get_db_type(state, &request.target_connection_id).await?;
- if !is_same_transfer_family(&source_db_type, &target_db_type) {
- return Err("跨库暂不支持非表对象传输".to_string());
- }
- match transfer_object_family(&source_db_type) {
- Some(TransferObjectFamily::Postgres) => {
- transfer_postgres_schema_objects(state, request, source_pool_key, target_pool_key, progress_callback)
- .await
- .map(|_| TransferObjectOutcome::default())
- }
- Some(TransferObjectFamily::Mysql) => {
- transfer_mysql_schema_objects(state, request, source_pool_key, target_pool_key, progress_callback).await
- }
- Some(TransferObjectFamily::Oracle) => {
- transfer_oracle_schema_objects(state, request, source_pool_key, target_pool_key, progress_callback).await
- }
- None => Ok(TransferObjectOutcome::default()),
- }
-}
-```
-
-Note: this task lands the skeleton + ordering + outcome; per-family bodies are Tasks 10 (MySQL), 11 (Oracle), 12 (PG refactor). `transfer_mysql_schema_objects` and `transfer_oracle_schema_objects` are stubbed in this task (returning `Ok(TransferObjectOutcome::default())` guarded by a `todo!()`-free minimal implementation) so the crate compiles — they are filled in by Tasks 10/11.
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core orders_object_selections 2>&1 | tail -5`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): schema object transfer executor skeleton with ordering"
-```
-
----
-
-## Task 10: MySQL schema object transfer body
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs`
-
-- [ ] **Step 1: Write the failing test** (selection extraction helper):
-
-```rust
-#[test]
-fn extracts_selected_names_by_kind() {
- let selections = vec![
- TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v1".into()] },
- TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v2".into()] },
- TransferObjectSelection { object_type: TransferObjectKind::Trigger, names: vec!["t1".into()] },
- ];
- let views = selected_object_names(&selections, &TransferObjectKind::View);
- assert_eq!(views, vec!["v1", "v2"]);
- assert!(selected_object_names(&selections, &TransferObjectKind::Event).is_empty());
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core extracts_selected_names 2>&1 | tail -5`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement**:
-
-```rust
-pub fn selected_object_names(selections: &[TransferObjectSelection], kind: &TransferObjectKind) -> Vec<String> {
- selections
- .iter()
- .filter(|s| &s.object_type == kind)
- .flat_map(|s| s.names.clone())
- .collect::<Vec<_>>()
-}
-```
-
-Then `transfer_mysql_schema_objects`:
-
-```rust
-async fn transfer_mysql_schema_objects<F>(
- state: &AppState,
- request: &TransferRequest,
- source_pool_key: &str,
- target_pool_key: &str,
- mut progress_callback: F,
-) -> Result<TransferObjectOutcome, String>
-where
- F: FnMut(TransferProgress),
-{
- let mut outcome = TransferObjectOutcome::default();
- let source_db = &request.source_database;
- let target_db = if request.target_database.trim().is_empty() {
- source_db.as_str()
- } else {
- request.target_database.as_str()
- };
- let order = ordered_transfer_object_kinds(
- request.objects.iter().map(|s| s.object_type).collect(),
- );
- for kind in order {
- for name in selected_object_names(&request.objects, &kind) {
- if is_cancelled(&request.transfer_id).await {
- return Err("Cancelled".to_string());
- }
- let table = format!("schema object: {name}");
- let progress = |outcome: &mut TransferObjectOutcome, status: TransferStatus, error: Option<String>| {
- progress_callback(TransferProgress {
- transfer_id: request.transfer_id.clone(),
- table: table.clone(),
- table_index: request.tables.len(),
- total_tables: request.tables.len(),
- rows_transferred: (outcome.transferred.len() + outcome.skipped.len()) as u64,
- total_rows: None,
- status,
- error,
- terminal: false,
- });
- };
- // skip if target already has it
- let exists_sql =
- target_object_exists_sql(&DatabaseType::Mysql, target_db, &name, &kind).map_err(|e| e)?;
- let exists = execute_on_pool(state, target_pool_key, &exists_sql).await?.rows.first().is_some();
- if exists {
- outcome.skipped.push(format!("{kind:?}:{name}"));
- progress(&mut outcome, TransferStatus::Running, None);
- continue;
- }
- let query = mysql_object_source_query(&kind, source_db, &name)?;
- let result = execute_on_pool(state, source_pool_key, &query).await?;
- let raw_ddl = mysql_object_ddl_from_result(&kind, &result)?;
- let ddl = strip_mysql_definer(&raw_ddl);
- let ddl = rewrite_mysql_schema_qualifier(&ddl, source_db, target_db);
- match execute_on_pool(state, target_pool_key, &ddl).await {
- Ok(_) => {
- outcome.transferred.push(format!("{kind:?}:{name}"));
- progress(&mut outcome, TransferStatus::Running, None);
- }
- Err(e) => {
- outcome.failed.push(format!("{kind:?}:{name}"));
- progress(&mut outcome, TransferStatus::Error, Some(e));
- }
- }
- }
- }
- Ok(outcome)
-}
-```
-
-Check `TransferStatus` variant names (Running/Error/TableDone/Done/Cancelled — see route usage). `is_cancelled` is in transfer.rs:4076.
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core extracts_selected_names 2>&1 | tail -5`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): mysql schema object transfer (skip existing, definer strip, schema rewrite)"
-```
-
----
-
-## Task 11: Oracle/Dameng schema object transfer body
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs`
-
-- [ ] **Step 1: Write the failing test** (schema resolution for DM, where database==schema):
-
-```rust
-#[test]
-fn resolves_oracle_family_source_schema() {
- // For Oracle/Dameng the metadata lookup schema is the source_schema;
- // when empty, fall back to the database (DM lists users as databases).
- assert_eq!(resolve_oracle_schema("", "HR"), "HR");
- assert_eq!(resolve_oracle_schema("HR", "db"), "HR");
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core resolves_oracle_family 2>&1 | tail -5`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement**:
-
-```rust
-fn resolve_oracle_schema(schema: &str, database: &str) -> String {
- if schema.trim().is_empty() { database.to_string() } else { schema.to_string() }
-}
-```
-
-Then `transfer_oracle_schema_objects` mirroring the MySQL body: for each selected object, existence check via `target_object_exists_sql(&DatabaseType::Oracle, target_schema, name, kind)` (target_schema resolved the same way; for DM use the same ALL_OBJECTS query — Dameng supports `ALL_OBJECTS` view), DDL via `oracle_object_source_query` executed on the source pool with the source schema as query database, extract first cell, `rewrite_oracle_schema_qualifier(&ddl, source_schema, target_schema)`, execute on target. Oracle objects created through `build_executable_object_source_statements` are *not* needed here — DBMS_METADATA output is already executable; the body uses the MySQL loop shape with `execute_on_pool` and the same progress/outcome accounting.
-
-Note: `DBMS_METADATA.GET_DDL` requires a connection whose current schema is the owner schema; the agent executes the query with `database`/`schema` params (see `oracle_agent_object_source` at schema.rs:6566 which passes both). For transfers the pools execute plain SQL; if `GET_DDL` returns no row because the current schema differs, the object transfer reports it as a failed object (acceptable for v1; note in code comment).
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core resolves_oracle_family 2>&1 | tail -5`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): oracle/dameng schema object transfer"
-```
-
----
-
-## Task 12: PG object transfer — per-selection filtering + skip-existing
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs` (`transfer_postgres_schema_objects` at 5020)
-
-- [ ] **Step 1: Write the failing test** (filter helper for PG sources):
-
-```rust
-#[test]
-fn filters_postgres_object_sources_by_selection() {
- let sources = vec![
- db::ObjectSource { name: "v1".into(), object_type: db::ObjectSourceKind::View, schema: Some("public".into()), source: "SELECT 1".into(), editable: None },
- db::ObjectSource { name: "v2".into(), object_type: db::ObjectSourceKind::View, schema: Some("public".into()), source: "SELECT 2".into(), editable: None },
- ];
- let selection = vec![TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v1".into()] }];
- let filtered = filter_object_sources_by_selection(sources, &selection);
- assert_eq!(filtered.len(), 1);
- assert_eq!(filtered[0].name, "v1");
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core filters_postgres_object_sources 2>&1 | tail -5`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement** — in `transfer_postgres_schema_objects`:
-
-1. After fetching `object_sources`/`materialized_views`/`trigger_sources`, filter each by `selected_object_names(&request.objects, &kind)`:
- - `object_sources` (View/Procedure/Function/Sequence/…) → filter by kind-specific name lists.
- - `materialized_views` → filter by MaterializedView names.
- - `trigger_sources` → filter by Trigger names; if no Trigger selection, skip the whole trigger step (current behavior transfers triggers of selected tables — replace it with explicit selection; when `objects` is empty the function returns early anyway).
-2. Skip-existing: before executing each object's DDL, run `target_object_exists_sql(&DatabaseType::Postgres, &request.target_schema, name, kind)` on the target pool; on hit, record in a `skipped` list and `continue` (no execution, no error).
-3. Return `Ok(TransferObjectOutcome)` with transferred/skipped/failed populated from the loops (rename the current function's return or add a new wrapper that the executor calls; simplest: change the signature to return `Result<TransferObjectOutcome, String>` and update the route call in Task 14).
-
-Helper `filter_object_sources_by_selection` maps `db::ObjectSourceKind` ↔ `TransferObjectKind`:
-
-```rust
-fn transfer_kind_from_object_source_kind(kind: &db::ObjectSourceKind) -> Option<TransferObjectKind> {
- use db::ObjectSourceKind as S;
- Some(match kind {
- S::View => TransferObjectKind::View,
- S::MaterializedView => TransferObjectKind::MaterializedView,
- S::Procedure => TransferObjectKind::Procedure,
- S::Function => TransferObjectKind::Function,
- S::Trigger => TransferObjectKind::Trigger,
- S::Sequence => TransferObjectKind::Sequence,
- _ => return None,
- })
-}
-```
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core filters_postgres_object_sources 2>&1 | tail -5`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): postgres object transfer honors selection and skips existing"
-```
-
----
-
-## Task 13: transfer_table honors StructureOnly (no data copy)
-
-**Files:**
-- Modify: `crates/dbx-core/src/transfer.rs` (`transfer_table` around line 4730, before the "Truncate target if overwrite mode" block)
-
-- [ ] **Step 1: Write the failing test** — no pure unit test is feasible (async + DB); instead assert via a new pure helper:
-
-```rust
-#[test]
-fn structure_only_skips_data_steps() {
- assert!(should_copy_data(&TransferContent::StructureAndData));
- assert!(should_copy_data(&TransferContent::DataOnly));
- assert!(!should_copy_data(&TransferContent::StructureOnly));
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core structure_only_skips_data 2>&1 | tail -5`
-Expected: FAIL.
-
-- [ ] **Step 3: Implement**:
-
-```rust
-pub fn should_copy_data(content: &TransferContent) -> bool {
- !matches!(content, TransferContent::StructureOnly)
-}
-```
-
-In `transfer_table`, immediately before the `// Truncate target if overwrite mode` block (line ~4730):
-
-```rust
- // Structure-only transfer: DDL work (create table, indexes, comments) is
- // done above; skip everything data-related.
- if !should_copy_data(&request.content) {
- return Ok(0);
- }
-```
-
-Also apply the same early return at the top of the Mongo branch (`transfer_mongodb_table`): add a guard in the caller route instead — Task 14 rejects StructureOnly for Mongo sources/targets at validation time, so no change is needed inside the Mongo path. If Mongo `create_table` flow differs, validate in Task 14 tests.
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-core structure_only_skips_data 2>&1 | tail -5`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): structure-only mode skips data copy"
-```
-
----
-
-## Task 14: Route integration — validation, object step, summary counts
-
-**Files:**
-- Modify: `crates/dbx-web/src/routes/transfer.rs`
-
-- [ ] **Step 1: Write the failing test** — no unit test harness exists for routes; verification is compile + manual. Skip TDD here; the compile step below is the gate.
-
-- [ ] **Step 2: Wire validation**: replace `transfer::validate_transfer_target_table_names(&req)` (line ~63) with `transfer::validate_transfer_request(&req)`; after resolving `source_db_type`/`target_db_type` inside the spawned task, reject when `!request.objects.is_empty() && !transfer::is_same_transfer_family(&source_db_type, &target_db_type)` (terminal error via `terminal_transfer_error`), and reject `StructureOnly` when either side is Mongo (`matches!(source_db_type, DatabaseType::Mongodb) || matches!(target_db_type, ...)`).
-
-- [ ] **Step 3: Run object transfer step** — after the table loop, replace the PG-only `transfer_postgres_schema_objects` block (lines ~327-390) with:
-
-```rust
- let object_outcome = match transfer::transfer_schema_objects(
- &app,
- &req,
- &source_pool_key,
- &target_pool_key,
- |progress| {
- send_transfer_progress(&progress_channel, &progress);
- },
- )
- .await
- {
- Ok(outcome) => outcome,
- Err(e) if e == "Cancelled" => { /* existing cancelled terminal block */ return; }
- Err(e) => { /* existing error terminal block with table="schema objects" */ return; }
- };
-```
-
-Keep the existing `transfer_postgres_schema_dependencies` block (enum/domain) in place — it runs before the table loop and stays PG-only.
-
-- [ ] **Step 4: Merge skip count into the final summary**: extend the final `done` progress error text when `!object_outcome.skipped.is_empty()`: append `format!(",跳过 {} 个已存在对象", object_outcome.skipped.len())` — only when no failures; when failures exist, append to the failure message as well. Also add `outcome.transferred.len()` failures: failed object names go into `failed_tables` (they are reported per-object already via progress events; keep the aggregate simple: append `"schema objects"` to `failed_tables` when `!object_outcome.failed.is_empty()`).
-
-- [ ] **Step 5: Compile check**
-
-Run: `cargo check -p dbx-web 2>&1 | tail -10`
-Expected: no errors.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add crates/dbx-web/src/routes/transfer.rs crates/dbx-core/src/transfer.rs
-git commit -m "feat(transfer): route integration for content modes and schema objects"
-```
-
----
-
-## Task 15: Backend test sweep
-
-- [ ] **Step 1: Run all transfer-related unit tests**
-
-Run: `cargo test -p dbx-core transfer 2>&1 | tail -15`
-Expected: all transfer tests pass (protocol, family, validation, existence SQL, mysql DDL helpers, ordering, selections).
-
-- [ ] **Step 2: Run full dbx-core unit tests**
-
-Run: `cargo test -p dbx-core 2>&1 | tail -10`
-Expected: PASS (live-DB tests excluded by default; if any `#[ignore]`-less live tests fail, they are environment-dependent and were failing before this change).
-
-- [ ] **Step 3: Commit any stragglers**
-
-```bash
-git add -A && git commit -m "test(transfer): backfill transfer unit tests" --allow-empty
-```
-
----
-
-## Task 16: Frontend types (tauri.ts) and transfer object capability helpers
-
-**Files:**
-- Modify: `apps/desktop/src/lib/backend/tauri.ts` (TransferRequest at 3279; types at 3275)
-- Create: `apps/desktop/src/lib/database/transferObjectKinds.ts`
-- Test: `apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts`
-
-- [ ] **Step 1: Write the failing test**:
-
-```ts
-import { describe, expect, it } from "vitest";
-import {
- transferObjectFamily,
- transferObjectKindsForDatabase,
- isSameTransferFamily,
- TransferObjectFamily,
-} from "@/lib/database/transferObjectKinds";
-
-describe("transferObjectKinds", () => {
- it("groups databases into transfer families", () => {
- expect(transferObjectFamily("mysql")).toBe(TransferObjectFamily.Mysql);
- expect(transferObjectFamily("kingbase")).toBe(TransferObjectFamily.Postgres);
- expect(transferObjectFamily("dameng")).toBe(TransferObjectFamily.Oracle);
- expect(transferObjectFamily("sqlite")).toBeUndefined();
- });
-
- it("returns per-family object kinds", () => {
- expect(transferObjectKindsForDatabase("mysql")).toEqual([
- "TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "EVENT",
- ]);
- expect(transferObjectKindsForDatabase("postgres")).toContain("SEQUENCE");
- expect(transferObjectKindsForDatabase("dameng")).toContain("TRIGGER");
- expect(transferObjectKindsForDatabase("sqlite")).toEqual([]);
- });
-
- it("detects same-family transfers", () => {
- expect(isSameTransferFamily("mysql", "mysql")).toBe(true);
- expect(isSameTransferFamily("mysql", "postgres")).toBe(false);
- expect(isSameTransferFamily("oracle", "dameng")).toBe(true);
- expect(isSameTransferFamily("postgres", "sqlite")).toBe(false);
- });
-});
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `pnpm --dir apps/desktop vitest run transferObjectKinds 2>&1 | tail -8`
-Expected: FAIL — module missing.
-
-- [ ] **Step 3: Implement** — `transferObjectKinds.ts` mirrors the Rust tables:
-
-```ts
-import type { DatabaseType } from "@/types/database";
-
-export enum TransferObjectFamily {
- Mysql = "mysql",
- Postgres = "postgres",
- Oracle = "oracle",
-}
-
-export type TransferObjectKind =
- | "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE"
- | "FUNCTION" | "TRIGGER" | "SEQUENCE" | "EVENT";
-
-const MYSQL_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "EVENT"];
-const POSTGRES_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"];
-const ORACLE_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"];
-
-const FAMILY_BY_DB = new Map<DatabaseType, TransferObjectFamily>([
- ["mysql", TransferObjectFamily.Mysql],
- ["postgres", TransferObjectFamily.Postgres],
- ["kingbase", TransferObjectFamily.Postgres],
- ["gaussdb", TransferObjectFamily.Postgres],
- ["kwdb", TransferObjectFamily.Postgres],
- ["opengauss", TransferObjectFamily.Postgres],
- ["oracle", TransferObjectFamily.Oracle],
- ["dameng", TransferObjectFamily.Oracle],
- ["oceanbase-oracle", TransferObjectFamily.Oracle],
-]);
-
-export function transferObjectFamily(dbType?: DatabaseType): TransferObjectFamily | undefined {
- return dbType ? FAMILY_BY_DB.get(dbType) : undefined;
-}
-
-export function isSameTransferFamily(a?: DatabaseType, b?: DatabaseType): boolean {
- const fa = transferObjectFamily(a);
- const fb = transferObjectFamily(b);
- return !!fa && fa === fb;
-}
-
-export function transferObjectKindsForDatabase(dbType?: DatabaseType): TransferObjectKind[] {
- switch (transferObjectFamily(dbType)) {
- case TransferObjectFamily.Mysql: return [...MYSQL_KINDS];
- case TransferObjectFamily.Postgres: return [...POSTGRES_KINDS];
- case TransferObjectFamily.Oracle: return [...ORACLE_KINDS];
- default: return [];
- }
-}
-```
-
-Verify `DatabaseType` union includes `"kwdb"` and `"oceanbase-oracle"` in `apps/desktop/src/types/database.ts` — adjust keys to match.
-
-- [ ] **Step 4: Extend tauri.ts types**:
-
-```ts
-export type TransferContent = "structureAndData" | "structureOnly" | "dataOnly";
-export type TransferObjectKind =
- | "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE"
- | "FUNCTION" | "TRIGGER" | "SEQUENCE" | "EVENT";
-
-export interface TransferObjectSelection {
- objectType: TransferObjectKind;
- names: string[];
-}
-```
-
-Add to `TransferRequest`:
-```ts
- content: TransferContent;
- objects: TransferObjectSelection[];
-```
-
-(Keep `createTable` for wire compatibility; the dialog stops sending it — check http.ts `startDataTransferTask`/`api.TransferRequest` construction sites.)
-
-- [ ] **Step 5: Run the test to verify it passes**
-
-Run: `pnpm --dir apps/desktop vitest run transferObjectKinds 2>&1 | tail -8`
-Expected: PASS (3 tests).
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add apps/desktop/src/lib/database/transferObjectKinds.ts apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts apps/desktop/src/lib/backend/tauri.ts
-git commit -m "feat(transfer): frontend transfer object kind helpers and request types"
-```
-
----
-
-## Task 17: i18n keys
-
-**Files:**
-- Modify: all 9 locale files under `apps/desktop/src/i18n/locales/` (zh-CN, en, zh-TW, es, it, ja, ko, pt-BR, fallback) — `transfer:` namespace (~line 3712 in zh-CN)
-
-- [ ] **Step 1: Add keys to zh-CN.ts** (source of truth):
-
-```ts
- content: "传输方式",
- contentStructureAndData: "结构和数据",
- contentStructureOnly: "仅结构",
- contentDataOnly: "仅数据",
- contentStructureOnlyHint: "仅创建表和对象结构,不复制数据",
- contentDataOnlyHint: "仅复制数据到已存在的目标表",
- objects: "传输对象",
- searchObjects: "搜索对象名...",
- noObjects: "暂无对象",
- objectTypeTable: "表",
- objectTypeView: "视图",
- objectTypeMaterializedView: "物化视图",
- objectTypeProcedure: "存储过程",
- objectTypeFunction: "函数",
- objectTypeTrigger: "触发器",
- objectTypeSequence: "序列",
- objectTypeEvent: "事件",
- objectDataOnlyDisabled: "仅数据模式不传输非表对象",
- objectCrossFamilyDisabled: "跨数据库类型暂不支持非表对象传输",
- objectUnsupportedDisabled: "当前数据库不支持该对象类型传输",
- skippedExistingObjects: "跳过 {count} 个已存在对象",
- dataWriteMode: "数据写入方式",
-```
-
-- [ ] **Step 2: Mirror into the other 8 locales** — en: translate; zh-TW/es/it/ja/ko/pt-BR/fallback: use zh-CN text (existing project convention for untranslated keys is fallback; check how other new keys were added historically — `fallback.ts` contains zh-CN text; add the same keys there and to each locale with English or Chinese placeholder per convention).
-
-Verify by grep: `grep -c "contentStructureAndData" apps/desktop/src/i18n/locales/*.ts` → 9 files.
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add apps/desktop/src/i18n/locales/
-git commit -m "feat(i18n): transfer tree and content mode keys"
-```
-
----
-
-## Task 18: ObjectSelectionTree component
-
-**Files:**
-- Create: `apps/desktop/src/components/transfer/ObjectSelectionTree.vue`
-- Test: `apps/desktop/src/components/transfer/__tests__/ObjectSelectionTree.spec.ts`
-
-- [ ] **Step 1: Write the failing test** — component-level logic via mounted stubs:
-
-```ts
-import { describe, expect, it } from "vitest";
-import { mount } from "@vue/test-utils";
-import ObjectSelectionTree from "@/components/transfer/ObjectSelectionTree.vue";
-
-const groups = [
- { kind: "TABLE" as const, label: "表", items: ["a", "b"] },
- { kind: "VIEW" as const, label: "视图", items: ["v1"] },
-];
-
-function make(props: Record<string, unknown> = {}) {
- return mount(ObjectSelectionTree, {
- props: {
- groups,
- disabledGroups: [],
- modelValue: {},
- ...props,
- },
- global: { stubs: { Input: true, Button: true } },
- });
-}
-
-describe("ObjectSelectionTree", () => {
- it("renders group headers and items", () => {
- const wrapper = make();
- expect(wrapper.text()).toContain("表");
- expect(wrapper.text()).toContain("v1");
- });
-
- it("selects all items in a group when the header checkbox is toggled", async () => {
- const wrapper = make();
- await wrapper.findAll("[data-test='group-toggle']")[0].trigger("click");
- expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([
- { TABLE: ["a", "b"] },
- ]);
- });
-
- it("filters items by search text", async () => {
- const wrapper = make();
- await wrapper.find("[data-test='search']").setValue("v1");
- expect(wrapper.text()).toContain("v1");
- expect(wrapper.text()).not.toContain("a");
- });
-
- it("renders disabled groups with a hint", () => {
- const wrapper = make({ disabledGroups: ["VIEW"], disabledHints: { VIEW: "原因" } });
- const group = wrapper.find("[data-test='group-VIEW']");
- expect(group.classes()).toContain("opacity-50");
- expect(group.text()).toContain("原因");
- });
-});
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `pnpm --dir apps/desktop vitest run ObjectSelectionTree 2>&1 | tail -8`
-Expected: FAIL — component missing.
-
-- [ ] **Step 3: Implement the component** — props:
-
-```ts
-interface ObjectTreeGroup {
- kind: TransferObjectKind;
- label: string;
- items: string[];
-}
-
-props: {
- groups: ObjectTreeGroup[];
- disabledGroups: TransferObjectKind[]; // kinds rendered but greyed out
- disabledHints: Record<string, string>; // kind → reason
- modelValue: Record<string, string[]>; // kind → selected names
- search: string;
- loading: boolean;
-}
-```
-
-Template: per group — header row (CheckSquare/Square icon, label, count `(n/m)`, expand chevron) + collapsible item list (checkbox rows) with `data-test` attributes. Emits `update:modelValue` with the new selection object on every toggle (group header toggles all/none of the group's items). Search filter applies to item rows. Disabled groups render with `opacity-50` and the hint text; their checkboxes are disabled. A top-level select-all button operates across enabled groups.
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `pnpm --dir apps/desktop vitest run ObjectSelectionTree 2>&1 | tail -8`
-Expected: PASS (4 tests).
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add apps/desktop/src/components/transfer/ObjectSelectionTree.vue apps/desktop/src/components/transfer/__tests__/ObjectSelectionTree.spec.ts
-git commit -m "feat(transfer): object selection tree component"
-```
-
----
-
-## Task 19: DataTransferDialog integration
-
-**Files:**
-- Modify: `apps/desktop/src/components/transfer/DataTransferDialog.vue`
-
-- [ ] **Step 1: Write the failing test** — extend `apps/desktop/src/components/transfer/__tests__/DataTransferDialog.spec.ts`:
-
-```ts
-it("sends content and objects in the transfer request", async () => {
- // mount with a stub api.startDataTransferTask capturing the request
- // select a table + a view via the tree, choose "structure only",
- // assert request.content === "structureOnly",
- // request.objects contains { objectType: "VIEW", names: ["v1"] }
-});
-```
-
-Check how the existing spec stubs `api` (`vi.mock("@/lib/backend/api")`? verify from the existing spec file) and follow the same pattern.
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `pnpm --dir apps/desktop vitest run DataTransferDialog 2>&1 | tail -8`
-Expected: FAIL — request has no content/objects.
-
-- [ ] **Step 3: Implement** — in `DataTransferDialog.vue`:
-
-1. State: replace `sourceTables: string[]` + `selectedTables: Set<string>` with `objectGroups: Record<TransferObjectKind, string[]>` and `selectedObjects: Record<TransferObjectKind, Set<string>>` (keep a `selectedTables` computed derived from the TABLE group for minimal churn in the request builder and target-tree refresh logic).
-2. Data loading: `loadObjects()` calls `api.listObjects(sourceConnectionId, sourceDatabase, schema, [kind], undefined, undefined, undefined, catalog)` per kind from `transferObjectKindsForDatabase(sourceDbType)` and fills groups. Keep the existing `table_type` filtering for the TABLE group (`TABLE`/`BASE TABLE`).
-3. Mode: `transferContent = ref<api.TransferContent>("structureAndData")`; radio row with 3 options + hints (`contentStructureOnlyHint`/`contentDataOnlyHint`); when `dataOnly`, compute `disabledGroups = non-table kinds` with hint `objectDataOnlyDisabled`; when `!isSameTransferFamily(sourceDbType, targetDbType)`, all non-table kinds disabled with `objectCrossFamilyDisabled`; kinds missing from `transferObjectKindsForDatabase(source)` are not rendered.
-4. Request builder: `content: transferContent.value`, `objects: non-table kinds → { objectType, names: [...selected] }`, drop `createTable` (or send `createTable: transferContent.value !== "dataOnly"` for backward compat — check http.ts / tauri command signature; prefer sending both fields, frontend stays in control).
-5. Data-write-mode select (`transferMode`) visible only when content includes data (`structureAndData` or `dataOnly`); hidden for `structureOnly`.
-6. Ownership preview: only trigger when `content === "structureAndData"` (existing `createTable.value` condition at line ~471 becomes `transferContent.value !== "dataOnly"` — verify ownership applies to structure creation; keep current condition semantics: it ran when createTable was true, i.e. now `content !== "dataOnly"`).
-7. Remove the `createTable` checkbox row; remove `toggleSelectAll`/`filteredTables` table-only logic in favor of the tree.
-8. Keep `prefillTables` behavior: prefill maps into the TABLE group selection after load.
-9. `shouldRefreshTargetTree` (line ~451): refresh when `content !== "dataOnly"`.
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `pnpm --dir apps/desktop vitest run DataTransferDialog 2>&1 | tail -8`
-Expected: PASS (old + new tests).
-
-- [ ] **Step 5: Typecheck**
-
-Run: `pnpm --dir apps/desktop typecheck 2>&1 | tail -10`
-Expected: no errors.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add apps/desktop/src/components/transfer/
-git commit -m "feat(transfer): dialog tree selection and transfer content modes"
-```
-
----
-
-## Task 20: Final verification and review
-
-- [ ] **Step 1: Backend unit tests**
-
-Run: `cargo test -p dbx-core 2>&1 | tail -8`
-Expected: PASS.
-
-- [ ] **Step 2: Frontend tests**
-
-Run: `pnpm --dir apps/desktop vitest run 2>&1 | tail -8`
-Expected: PASS (including the pre-existing 30 tests from databaseCapabilities/databaseFeatureSupport).
-
-- [ ] **Step 3: Frontend typecheck**
-
-Run: `pnpm --dir apps/desktop typecheck 2>&1 | tail -8`
-Expected: no errors.
-
-- [ ] **Step 4: Manual smoke (optional, needs running app)**: open transfer dialog with MySQL source → tree shows 表/视图/存储过程/函数/触发器/事件; DM source → 表/视图/存储过程/函数/触发器/序列/物化视图; cross-family target → non-table groups disabled with hint; 仅数据 → non-table disabled; 仅结构 → data write mode hidden.
-
-- [ ] **Step 5: Verify git state**
-
-Run: `git status --short && git log --oneline -15`
-Expected: only feature commits; docs/superpowers untracked.
-
----
-
-## Notes / Risks
-
-- `DatabaseType` variant names must be verified against `crates/dbx-core/src/models/connection.rs` (Gaussdb/Kwdb/OceanbaseOracle) and `apps/desktop/src/types/database.ts` (kwdb/oceanbase-oracle) before compiling Task 2 / Task 16.
-- `TransferRequest` literal construction sites: `transfer.rs` tests (~line 5364) and `crates/dbx-core/tests/live_postgres_transfer.rs` — add the two new fields at every site.
-- `transfer_postgres_schema_objects` signature change (return `TransferObjectOutcome`) touches the route call in Task 14; keep both in the same commit so the crate stays green between commits only if the route is updated in the same commit — if not, keep the old signature and add a wrapper.
-- MySQL `SHOW CREATE` DDL column index differs by kind (view=1, routine=2) — reuse `schema::mysql_object_source_ddl_column_index` semantics in `mysql_object_ddl_from_result`.
-- DM `ALL_OBJECTS` availability: Dameng 8 supports `ALL_OBJECTS`; if a customer version lacks it, fall back to `SYS.SYSOBJECTS` (flagged as a follow-up).
-- `docs/superpowers/` must never be committed (`git add -f` avoided; it is gitignored).
diff --git a/docs/superpowers/plans/2026-08-02-database-documentation-annotations.md b/docs/superpowers/plans/2026-08-02-database-documentation-annotations.md
deleted file mode 100644
index f624fa557c..0000000000
--- a/docs/superpowers/plans/2026-08-02-database-documentation-annotations.md
+++ /dev/null
@@ -1,1218 +0,0 @@
-# Database Documentation Part 2: Annotation Store — Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Let users author table notes, column notes, project notes and table groups in a git-committable file, and have `dbx dbml --notes <path>` merge them into the generated DBML.
-
-**Architecture:** A new `crates/dbx-core/src/docs/annotations.rs` owns the notes file: load, validate, and merge into the `SchemaSnapshot` that Part 1's collector produces. Keys are `schema.table` / `schema.table.column`, case-folded per engine by a small `docs/keys.rs`. Merge precedence is `local ?? database_comment`, recorded in the `note_source` and `shadowed_note` fields Part 1 already defined but never populated. Notes whose target no longer exists are reported as `SnapshotWarning::OrphanedNotes`, never dropped.
-
-**Tech Stack:** Rust (dbx-core, dbx-cli), serde, serde_json. No new dependencies.
-
-**Branch:** continue on `feature/docs-snapshot-dbml` (Part 1's branch, 19 commits, unmerged) — Part 2 builds directly on its types. Worktree already exists at `/Users/possebon/workspaces/dbx.feature-docs-snapshot-dbml`.
-
-**Spec:** `docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.md`, Section 4.
-
-## Global Constraints
-
-- **NO new dependencies.** `serde`, `serde_json`, `chrono`, `futures` are already present in dbx-core.
-- **`cargo` is NOT on PATH.** Every cargo command must be prefixed with
- `export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"`.
- A bare `cargo` fails instantly with "Failed to spawn process: No such file or directory (os error 2)" — that is not a hang.
-- **A notes file that is ABSENT is fine; a notes file that is MALFORMED is a hard error.** User prose is at stake; proceeding silently would render apparently-complete docs while discarding writing.
-- **Never silently drop a note.** A note whose target no longer exists becomes a warning, not a deletion.
-- `format_version` in the notes file is `1`.
-- Group colour is `hue: u16` in `0..=359`. Never a hex string.
-- Run `cargo fmt` before every commit. Conventional Commits.
-- **Report mismatches, do not work around them.** If a signature differs from this plan, stop and report the actual compiler error. Part 1 had thirteen plan defects; every one was caught this way.
-
----
-
-## Pre-resolved facts (verified against the source — these override any assumption in the spec)
-
-1. **`schema/normalization.rs` is NOT where key folding goes.** Every function in it is `pub(super)` and it does table-list *filtering* (YashanDB recyclebin, object-type filters, column dedup) — not identifier case folding, and not reachable from `docs::`. Part 2 creates its own `crates/dbx-core/src/docs/keys.rs`.
-
-2. **`schema_diff::detect_renames` cannot be used for orphan suggestions.** Signature is
- `pub fn detect_renames(removed: &[String], added: &[String], source_details: &[TableSchemaDetail], target_details: &[TableSchemaDetail], threshold: f64) -> Vec<RenameCandidate>` (`schema_diff.rs:817`).
- It needs `TableSchemaDetail` for BOTH sides. The notes file stores prose only — it never retained the old schema — so there is nothing to diff against. **Rename suggestions are deferred** until snapshot history exists (spec Section 12). Part 2 detects and reports orphans; it does not suggest re-maps.
-
-3. **Per-connection persistence.** `DesktopSettings.saved_sql_sync_dir` is a GLOBAL setting, not per-connection — it is not the precedent the spec implies. `ConnectionConfig` already carries per-connection preferences (`note`, `color`, `init_script`, `visible_schemas`) and is serde-persisted into the `connections` table. **Add `docs_notes_path: Option<String>` to `ConnectionConfig` with `#[serde(default)]`** — non-breaking, no migration, no new table.
-
-4. **MySQL `lower_case_table_names`** is read in `transfer.rs:705-727` via `SHOW VARIABLES`, but that helper is private and costs a round-trip. Part 2 does NOT query it. MySQL keys fold to lowercase unconditionally (see Task 2 rationale).
-
-5. **Part 1 fields this plan populates** (all exist, currently hardcoded `None`/`NoteSource::None` at `collector.rs:206-209`): `DocTable::note`, `note_source`, `shadowed_note`, `column_notes`, `group_id`, and `SchemaSnapshot::groups`. `column_notes` is already consumed by the serializer at `dbml.rs:126`; `groups` already render via `render_group` with an empty-member guard. **No Part 1 type changes are required.**
-
-6. **Annotations are applied CLI-side, NOT inside the collector.** The notes file lives on the
- machine running `dbx`, and `WebBackend` talks to a remote DBX instance that cannot read it.
- Applying the merge after the snapshot returns keeps both transports identical — a property a
- Part 1 review specifically verified. Adding an `annotations` field to `CollectOptions` would
- therefore create a field written by nothing and read by nothing, which is exactly the
- "produced but never consumed" defect the Part 1 final review flagged. `collector.rs` is
- deliberately **not modified** by this plan.
-
----
-
-## File Structure
-
-| File | Responsibility |
-| --- | --- |
-| `crates/dbx-core/src/docs/keys.rs` | Per-engine identifier folding; `AnnotationKey` construction and matching |
-| `crates/dbx-core/src/docs/annotations.rs` | Notes-file model, load/save, merge into snapshot, orphan detection |
-| `crates/dbx-core/src/models/connection.rs` | `docs_notes_path` field |
-| `crates/dbx-cli/src/main.rs` | `--notes` flag, wiring into `run_dbml` |
-| `crates/dbx-core/tests/live_postgres_docs_annotations.rs` | Live verification with a real notes file |
-
----
-
-## Task 0: Confirm the starting point
-
-- [ ] **Step 1: Verify the branch and a green baseline**
-
-```bash
-cd /Users/possebon/workspaces/dbx.feature-docs-snapshot-dbml
-git branch --show-current # must print: feature/docs-snapshot-dbml
-git status --short # must be empty
-export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"
-cargo test -p dbx-core docs::
-```
-
-Expected: `feature/docs-snapshot-dbml`, clean tree, 60 tests passing. If any differs, stop and report — Part 2 builds on Part 1 and a dirty starting point makes every later failure ambiguous.
-
----
-
-## Task 1: Notes-file model
-
-**Files:**
-- Create: `crates/dbx-core/src/docs/annotations.rs`
-- Modify: `crates/dbx-core/src/docs/mod.rs`
-
-**Interfaces:**
-- Produces: `AnnotationFile`, `ProjectAnnotation`, `TableAnnotation`, `ColumnAnnotation`, `GroupAnnotation`
-
-- [ ] **Step 1: Write the failing test**
-
-Create `crates/dbx-core/src/docs/annotations.rs` containing only this test module:
-
-```rust
-#[cfg(test)]
-mod tests {
- use super::*;
-
- const SAMPLE: &str = r#"{
- "formatVersion": 1,
- "project": { "name": "Ecommerce", "note": "# Overview" },
- "groups": [
- { "id": "order-management", "name": "Order Management", "hue": 28, "note": "Checkout to handoff." }
- ],
- "tables": {
- "core.orders": {
- "group": "order-management",
- "note": "One row per checkout.",
- "columns": { "status": { "note": "State machine." } }
- }
- }
- }"#;
-
- #[test]
- fn parses_a_complete_notes_file() {
- let parsed: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
-
- assert_eq!(parsed.format_version, 1);
- assert_eq!(parsed.project.as_ref().unwrap().name.as_deref(), Some("Ecommerce"));
- assert_eq!(parsed.groups.len(), 1);
- assert_eq!(parsed.groups[0].hue, 28);
- assert_eq!(parsed.tables.len(), 1);
-
- let orders = parsed.tables.get("core.orders").expect("orders");
- assert_eq!(orders.group.as_deref(), Some("order-management"));
- assert_eq!(orders.note.as_deref(), Some("One row per checkout."));
- assert_eq!(orders.columns.get("status").unwrap().note, "State machine.");
- }
-
- #[test]
- fn a_minimal_file_needs_only_the_format_version() {
- let parsed: AnnotationFile = serde_json::from_str(r#"{"formatVersion": 1}"#).expect("parse");
- assert!(parsed.tables.is_empty());
- assert!(parsed.groups.is_empty());
- assert!(parsed.project.is_none());
- }
-
- #[test]
- fn round_trips_through_json() {
- let parsed: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
- let written = serde_json::to_string(&parsed).expect("serialize");
- let reparsed: AnnotationFile = serde_json::from_str(&written).expect("reparse");
- assert_eq!(reparsed.tables.len(), 1);
- assert_eq!(reparsed.groups[0].name, "Order Management");
- }
-
- #[test]
- fn rejects_a_file_with_an_unknown_top_level_field() {
- // Typos in a hand-edited file must not be silently ignored — a
- // misspelled "tabels" key would otherwise discard every note in it.
- let result: Result<AnnotationFile, _> =
- serde_json::from_str(r#"{"formatVersion": 1, "tabels": {}}"#);
- assert!(result.is_err(), "unknown fields must be rejected");
- }
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Add to `crates/dbx-core/src/docs/mod.rs`, keeping alphabetical order (it currently lists `color`, `collector`, `dbml`, `relations`, `snapshot`):
-
-```rust
-pub mod annotations;
-```
-
-Run: `cargo test -p dbx-core docs::annotations`
-Expected: FAIL — `cannot find type AnnotationFile`.
-
-- [ ] **Step 3: Write the types**
-
-At the top of `crates/dbx-core/src/docs/annotations.rs`:
-
-```rust
-use std::collections::BTreeMap;
-
-use serde::{Deserialize, Serialize};
-
-/// The on-disk notes file. This IS the store — not a cache of anything.
-/// It is meant to be committed to a repository and reviewed in pull
-/// requests, so it must stay small, readable, and stable in key order.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-pub struct AnnotationFile {
- pub format_version: u32,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub project: Option<ProjectAnnotation>,
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub groups: Vec<GroupAnnotation>,
- /// Keyed by `schema.table` (or bare `table` on schema-less engines).
- #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
- pub tables: BTreeMap<String, TableAnnotation>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-pub struct ProjectAnnotation {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub name: Option<String>,
- /// Markdown. Becomes the documentation landing page.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub note: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-pub struct GroupAnnotation {
- /// Stable slug, referenced by `TableAnnotation::group`.
- pub id: String,
- pub name: String,
- /// 0..=359. Lightness and chroma are theme-controlled, so any hue is
- /// legible on both light and dark grounds by construction.
- pub hue: u16,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub note: Option<String>,
-}
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-pub struct TableAnnotation {
- /// References `GroupAnnotation::id`.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub group: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub note: Option<String>,
- /// Keyed by bare column name.
- #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
- pub columns: BTreeMap<String, ColumnAnnotation>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-pub struct ColumnAnnotation {
- pub note: String,
-}
-```
-
-`BTreeMap` rather than `HashMap` is deliberate: it serializes in sorted key order, so a committed notes file produces a stable diff instead of a reshuffled one on every save.
-
-- [ ] **Step 4: Run the tests**
-
-Run: `cargo test -p dbx-core docs::annotations`
-Expected: PASS, 4 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/
-git commit -m "feat(docs): add annotation file model"
-```
-
----
-
-## Task 2: Per-engine key folding
-
-**Files:**
-- Create: `crates/dbx-core/src/docs/keys.rs`
-- Modify: `crates/dbx-core/src/docs/mod.rs`
-
-**Interfaces:**
-- Consumes: `crate::models::connection::DatabaseType`
-- Produces: `pub fn fold_identifier(db_type: DatabaseType, value: &str) -> String`, `pub fn table_key(db_type: DatabaseType, schema: Option<&str>, table: &str) -> String`, `pub fn column_key(db_type: DatabaseType, schema: Option<&str>, table: &str, column: &str) -> String`
-
-**Why this module exists:** the spec said folding belongs in `schema/normalization.rs`. It does not — everything there is `pub(super)` and it filters table lists rather than folding identifiers.
-
-**MySQL rationale:** MySQL's real behaviour depends on the server's `lower_case_table_names` variable. `transfer.rs:705` reads it via `SHOW VARIABLES`, but that helper is private and costs a round-trip per collection. Folding MySQL keys to lowercase unconditionally is correct for the common configurations (1 and 2) and, on the rare `0`, only risks matching a note to a table differing solely by case — which is a matching *hit*, never a wrong note on an unrelated table. The cost is bounded and the round-trip is not.
-
-- [ ] **Step 1: Write the failing test**
-
-Create `crates/dbx-core/src/docs/keys.rs` with only this test module:
-
-```rust
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::models::connection::DatabaseType;
-
- #[test]
- fn postgres_folds_to_lowercase() {
- assert_eq!(fold_identifier(DatabaseType::Postgres, "Orders"), "orders");
- assert_eq!(fold_identifier(DatabaseType::Postgres, "ORDERS"), "orders");
- }
-
- #[test]
- fn mysql_folds_to_lowercase() {
- assert_eq!(fold_identifier(DatabaseType::MySQL, "Orders"), "orders");
- }
-
- #[test]
- fn table_keys_are_qualified_when_a_schema_is_present() {
- assert_eq!(table_key(DatabaseType::Postgres, Some("Core"), "Orders"), "core.orders");
- assert_eq!(table_key(DatabaseType::Postgres, None, "Orders"), "orders");
- assert_eq!(table_key(DatabaseType::Postgres, Some(""), "Orders"), "orders");
- }
-
- #[test]
- fn column_keys_extend_the_table_key() {
- assert_eq!(
- column_key(DatabaseType::Postgres, Some("core"), "orders", "Status"),
- "core.orders.status"
- );
- }
-
- #[test]
- fn folding_is_idempotent() {
- let once = table_key(DatabaseType::Postgres, Some("Core"), "Orders");
- let twice = table_key(DatabaseType::Postgres, Some(&once), "x");
- assert!(twice.starts_with("core.orders"), "got {twice}");
- assert_eq!(fold_identifier(DatabaseType::Postgres, &once), once);
- }
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Add `pub mod keys;` to `crates/dbx-core/src/docs/mod.rs` (alphabetically, after `dbml`).
-
-Run: `cargo test -p dbx-core docs::keys`
-Expected: FAIL — `cannot find function fold_identifier`.
-
-**Note:** the exact `DatabaseType` variant spellings above (`Postgres`, `MySQL`) may differ. Check `crates/dbx-core/src/models/connection.rs` and use the real ones; report which you used.
-
-- [ ] **Step 3: Write the implementation**
-
-```rust
-use crate::models::connection::DatabaseType;
-
-/// Fold an identifier to its canonical case for note matching.
-///
-/// PostgreSQL folds unquoted identifiers to lower case, Oracle to upper.
-/// MySQL depends on the server's `lower_case_table_names`; we fold to lower
-/// unconditionally rather than pay a `SHOW VARIABLES` round-trip per
-/// collection — on the rare case-sensitive configuration the only risk is
-/// matching a note to a table differing solely by case, never attaching a
-/// note to an unrelated table.
-pub fn fold_identifier(db_type: DatabaseType, value: &str) -> String {
- match db_type {
- DatabaseType::Oracle => value.to_uppercase(),
- _ => value.to_lowercase(),
- }
-}
-
-/// `schema.table`, or bare `table` when there is no schema.
-pub fn table_key(db_type: DatabaseType, schema: Option<&str>, table: &str) -> String {
- match schema.filter(|value| !value.is_empty()) {
- Some(schema) => {
- format!("{}.{}", fold_identifier(db_type, schema), fold_identifier(db_type, table))
- }
- None => fold_identifier(db_type, table),
- }
-}
-
-/// `schema.table.column`, or `table.column` when there is no schema.
-pub fn column_key(db_type: DatabaseType, schema: Option<&str>, table: &str, column: &str) -> String {
- format!("{}.{}", table_key(db_type, schema, table), fold_identifier(db_type, column))
-}
-```
-
-Add `pub use keys::{column_key, fold_identifier, table_key};` to `docs/mod.rs`.
-
-- [ ] **Step 4: Run the tests**
-
-Run: `cargo test -p dbx-core docs::keys`
-Expected: PASS, 5 tests. Adjust the `DatabaseType::Oracle` arm if that variant is spelled differently.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/
-git commit -m "feat(docs): add per-engine annotation key folding"
-```
-
----
-
-## Task 3: Load the notes file
-
-**Files:**
-- Modify: `crates/dbx-core/src/docs/annotations.rs`
-
-**Interfaces:**
-- Produces: `pub fn load_annotations(path: &std::path::Path) -> Result<Option<AnnotationFile>, String>`
-
-**The rule this task encodes:** absent is fine, malformed is fatal.
-
-- [ ] **Step 1: Write the failing test**
-
-Append to the `tests` module in `annotations.rs`:
-
-```rust
- use std::io::Write;
-
- fn temp_notes(contents: &str) -> std::path::PathBuf {
- let mut path = std::env::temp_dir();
- path.push(format!("dbx-notes-test-{}.json", contents.len()));
- let mut file = std::fs::File::create(&path).expect("create");
- file.write_all(contents.as_bytes()).expect("write");
- path
- }
-
- #[test]
- fn an_absent_file_is_not_an_error() {
- let missing = std::path::Path::new("/nonexistent/dbx-notes-does-not-exist.json");
- assert!(matches!(load_annotations(missing), Ok(None)));
- }
-
- #[test]
- fn a_valid_file_loads() {
- let path = temp_notes(SAMPLE);
- let loaded = load_annotations(&path).expect("load").expect("some");
- assert_eq!(loaded.tables.len(), 1);
- let _ = std::fs::remove_file(&path);
- }
-
- #[test]
- fn a_malformed_file_is_a_hard_error_naming_the_path() {
- let path = temp_notes("{ this is not json");
- let error = load_annotations(&path).expect_err("must fail");
- assert!(error.contains(&path.display().to_string()), "error must name the file: {error}");
- let _ = std::fs::remove_file(&path);
- }
-
- #[test]
- fn an_unsupported_format_version_is_rejected() {
- let path = temp_notes(r#"{"formatVersion": 99}"#);
- let error = load_annotations(&path).expect_err("must fail");
- assert!(error.contains("99"), "error must name the version: {error}");
- let _ = std::fs::remove_file(&path);
- }
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core docs::annotations`
-Expected: FAIL — `cannot find function load_annotations`.
-
-- [ ] **Step 3: Write the implementation**
-
-```rust
-use std::path::Path;
-
-/// The only format version this build understands.
-pub const ANNOTATION_FORMAT_VERSION: u32 = 1;
-
-/// Load the notes file.
-///
-/// An ABSENT file returns `Ok(None)` — that is the normal first-run and
-/// first-CI-run state. A MALFORMED file is a hard error: someone's prose is
-/// in there, and rendering apparently-complete documentation while silently
-/// discarding it is worse than failing.
-pub fn load_annotations(path: &Path) -> Result<Option<AnnotationFile>, String> {
- let contents = match std::fs::read_to_string(path) {
- Ok(contents) => contents,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
- Err(error) => return Err(format!("Failed to read notes file {}: {error}", path.display())),
- };
-
- let parsed: AnnotationFile = serde_json::from_str(&contents)
- .map_err(|error| format!("Failed to parse notes file {}: {error}", path.display()))?;
-
- if parsed.format_version != ANNOTATION_FORMAT_VERSION {
- return Err(format!(
- "Notes file {} has formatVersion {}, but this build understands {}.",
- path.display(),
- parsed.format_version,
- ANNOTATION_FORMAT_VERSION
- ));
- }
-
- Ok(Some(parsed))
-}
-```
-
-- [ ] **Step 4: Run the tests**
-
-Run: `cargo test -p dbx-core docs::annotations`
-Expected: PASS, 8 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/
-git commit -m "feat(docs): load and validate the notes file"
-```
-
----
-
-## Task 4: Merge annotations into the snapshot
-
-**Files:**
-- Modify: `crates/dbx-core/src/docs/annotations.rs`
-
-**Interfaces:**
-- Consumes: `AnnotationFile` (Task 1), `table_key`/`column_key` (Task 2), `SchemaSnapshot`/`DocTable`/`ColumnNote`/`NoteSource`/`TableGroup`/`SnapshotWarning` (Part 1)
-- Produces: `pub fn apply_annotations(snapshot: &mut SchemaSnapshot, annotations: &AnnotationFile, db_type: DatabaseType)`
-
-**Merge precedence:** `local_annotation ?? database_comment`. When a local note shadows a database comment, the comment is preserved in `shadowed_note` so the UI can show what is being overridden — otherwise a DBA later writing a better `COMMENT ON` would have their improvement silently hidden.
-
-- [ ] **Step 1: Write the failing test**
-
-Append to the `tests` module:
-
-```rust
- use crate::docs::{DocTable, NoteSource, ProjectMeta, SchemaSnapshot, TableKind};
- use crate::models::connection::DatabaseType;
-
- fn snapshot_with(tables: Vec<DocTable>) -> SchemaSnapshot {
- SchemaSnapshot {
- format_version: 1,
- project: ProjectMeta {
- name: "conn".to_string(),
- database_type: "postgres".to_string(),
- database: None,
- schemas: vec!["core".to_string()],
- generated_at: String::new(),
- note: None,
- },
- tables,
- relationships: vec![],
- groups: vec![],
- enums: vec![],
- warnings: vec![],
- }
- }
-
- fn table_named(schema: &str, name: &str, comment: Option<&str>) -> DocTable {
- DocTable {
- schema: Some(schema.to_string()),
- name: name.to_string(),
- kind: TableKind::Table,
- columns: vec![],
- indexes: vec![],
- foreign_keys: vec![],
- group_id: None,
- note: comment.map(ToOwned::to_owned),
- note_source: if comment.is_some() { NoteSource::Database } else { NoteSource::None },
- shadowed_note: None,
- column_notes: BTreeMap::new(),
- estimated_rows: None,
- view_definition: None,
- }
- }
-
- #[test]
- fn a_local_note_shadows_the_database_comment_and_preserves_it() {
- let mut snapshot = snapshot_with(vec![table_named("core", "orders", Some("Old DB comment."))]);
- let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
-
- apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);
-
- let table = &snapshot.tables[0];
- assert_eq!(table.note.as_deref(), Some("One row per checkout."));
- assert_eq!(table.note_source, NoteSource::Local);
- assert_eq!(table.shadowed_note.as_deref(), Some("Old DB comment."));
- }
-
- #[test]
- fn a_database_comment_survives_when_there_is_no_local_note() {
- let mut snapshot = snapshot_with(vec![table_named("core", "users", Some("From the database."))]);
- let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
-
- apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);
-
- let table = &snapshot.tables[0];
- assert_eq!(table.note.as_deref(), Some("From the database."));
- assert_eq!(table.note_source, NoteSource::Database);
- assert_eq!(table.shadowed_note, None);
- }
-
- #[test]
- fn keys_match_case_insensitively_on_postgres() {
- // The notes file says "core.orders"; the live schema reports "Core"/"Orders".
- let mut snapshot = snapshot_with(vec![table_named("Core", "Orders", None)]);
- let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
-
- apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);
-
- assert_eq!(snapshot.tables[0].note.as_deref(), Some("One row per checkout."));
- }
-
- #[test]
- fn column_notes_are_applied_and_marked_local() {
- let mut table = table_named("core", "orders", None);
- table.columns.push(crate::types::ColumnInfo {
- name: "status".to_string(),
- data_type: "text".to_string(),
- ..Default::default()
- });
- let mut snapshot = snapshot_with(vec![table]);
- let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
-
- apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);
-
- let note = snapshot.tables[0].column_notes.get("status").expect("column note");
- assert_eq!(note.note, "State machine.");
- assert_eq!(note.source, NoteSource::Local);
- }
-
- #[test]
- fn the_project_note_and_name_are_applied() {
- let mut snapshot = snapshot_with(vec![]);
- let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
-
- apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);
-
- assert_eq!(snapshot.project.name, "Ecommerce");
- assert_eq!(snapshot.project.note.as_deref(), Some("# Overview"));
- }
-
- #[test]
- fn groups_are_copied_and_membership_is_assigned() {
- let mut snapshot = snapshot_with(vec![table_named("core", "orders", None)]);
- let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
-
- apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);
-
- assert_eq!(snapshot.groups.len(), 1);
- assert_eq!(snapshot.groups[0].id, "order-management");
- assert_eq!(snapshot.groups[0].hue, 28);
- assert_eq!(snapshot.tables[0].group_id.as_deref(), Some("order-management"));
- }
-
- #[test]
- fn a_table_referencing_an_undefined_group_is_left_ungrouped() {
- let mut snapshot = snapshot_with(vec![table_named("core", "orders", None)]);
- let mut annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
- annotations.groups.clear();
-
- apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);
-
- assert_eq!(snapshot.tables[0].group_id, None, "a dangling group reference must not be assigned");
- }
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core docs::annotations`
-Expected: FAIL — `cannot find function apply_annotations`.
-
-- [ ] **Step 3: Write the implementation**
-
-```rust
-use crate::docs::{ColumnNote, NoteSource, SchemaSnapshot, TableGroup};
-use crate::docs::keys::{column_key, table_key};
-use crate::models::connection::DatabaseType;
-
-/// Merge a notes file into a collected snapshot.
-///
-/// Precedence is `local ?? database_comment`. When a local note shadows a
-/// database comment the comment is kept in `shadowed_note`, so a later
-/// `COMMENT ON` improvement stays visible rather than being silently hidden.
-pub fn apply_annotations(
- snapshot: &mut SchemaSnapshot,
- annotations: &AnnotationFile,
- db_type: DatabaseType,
-) {
- if let Some(project) = annotations.project.as_ref() {
- if let Some(name) = project.name.as_deref().filter(|value| !value.trim().is_empty()) {
- snapshot.project.name = name.to_string();
- }
- if project.note.is_some() {
- snapshot.project.note = project.note.clone();
- }
- }
-
- let known_groups: std::collections::HashSet<&str> =
- annotations.groups.iter().map(|group| group.id.as_str()).collect();
-
- snapshot.groups = annotations
- .groups
- .iter()
- .map(|group| TableGroup {
- id: group.id.clone(),
- name: group.name.clone(),
- hue: group.hue,
- note: group.note.clone(),
- })
- .collect();
-
- for table in &mut snapshot.tables {
- let key = table_key(db_type, table.schema.as_deref(), &table.name);
- let Some(annotation) = annotations.tables.get(&key) else { continue };
-
- if let Some(note) = annotation.note.as_deref().filter(|value| !value.trim().is_empty()) {
- // Preserve whatever the database said before overwriting it.
- if matches!(table.note_source, NoteSource::Database) {
- table.shadowed_note = table.note.clone();
- }
- table.note = Some(note.to_string());
- table.note_source = NoteSource::Local;
- }
-
- // A group reference that names no defined group is dropped rather
- // than assigned — a dangling id would render an empty group header.
- table.group_id = annotation
- .group
- .as_deref()
- .filter(|id| known_groups.contains(id))
- .map(ToOwned::to_owned);
-
- for column in &table.columns {
- let column_fold = crate::docs::keys::fold_identifier(db_type, &column.name);
- let annotated = annotation
- .columns
- .iter()
- .find(|(name, _)| crate::docs::keys::fold_identifier(db_type, name) == column_fold);
-
- let Some((_, column_annotation)) = annotated else { continue };
- if column_annotation.note.trim().is_empty() {
- continue;
- }
-
- table.column_notes.insert(
- column.name.clone(),
- ColumnNote {
- note: column_annotation.note.clone(),
- source: NoteSource::Local,
- shadowed: column.comment.clone().filter(|value| !value.trim().is_empty()),
- },
- );
- }
- }
-
- // `column_key` is used by orphan detection in Task 5; referenced here so
- // the import is meaningful in both tasks.
- let _ = column_key;
-}
-```
-
-**Note for the implementer:** the trailing `let _ = column_key;` is a placeholder to keep the import valid before Task 5 uses it. If the compiler is satisfied without importing `column_key` in this task, omit both the import and that line and add the import in Task 5 instead. Report which you did.
-
-- [ ] **Step 4: Run the tests**
-
-Run: `cargo test -p dbx-core docs::annotations`
-Expected: PASS, 15 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/
-git commit -m "feat(docs): merge annotations into the schema snapshot"
-```
-
----
-
-## Task 5: Orphan detection
-
-**Files:**
-- Modify: `crates/dbx-core/src/docs/annotations.rs`
-
-**Interfaces:**
-- Produces: `pub fn detect_orphans(snapshot: &SchemaSnapshot, annotations: &AnnotationFile, db_type: DatabaseType) -> Vec<String>`; `apply_annotations` pushes `SnapshotWarning::OrphanedNotes { count }`
-
-**Why no re-map suggestion:** `schema_diff::detect_renames` needs `TableSchemaDetail` for both the old and new schema. The notes file stores prose only — it never retained the old schema — so there is nothing to diff. Suggestions become possible once snapshot history exists (spec Section 12). Part 2 detects and reports; it never deletes.
-
-- [ ] **Step 1: Write the failing test**
-
-Append to the `tests` module:
-
-```rust
- use crate::docs::SnapshotWarning;
-
- #[test]
- fn a_note_for_a_missing_table_is_reported_as_orphaned() {
- // The notes file describes core.orders; the schema no longer has it.
- let mut snapshot = snapshot_with(vec![table_named("core", "customers", None)]);
- let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
-
- let orphans = detect_orphans(&snapshot, &annotations, DatabaseType::Postgres);
- assert_eq!(orphans, vec!["core.orders".to_string()]);
-
- apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);
- let orphan_warnings: Vec<&SnapshotWarning> = snapshot
- .warnings
- .iter()
- .filter(|warning| matches!(warning, SnapshotWarning::OrphanedNotes { .. }))
- .collect();
- assert_eq!(orphan_warnings.len(), 1);
- match orphan_warnings[0] {
- SnapshotWarning::OrphanedNotes { count } => assert_eq!(*count, 1),
- other => panic!("unexpected: {other:?}"),
- }
- }
-
- #[test]
- fn a_note_for_a_missing_column_is_reported_as_orphaned() {
- // The table exists but no longer has the annotated column.
- let mut table = table_named("core", "orders", None);
- table.columns.push(crate::types::ColumnInfo {
- name: "id".to_string(),
- data_type: "integer".to_string(),
- ..Default::default()
- });
- let snapshot = snapshot_with(vec![table]);
- let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
-
- let orphans = detect_orphans(&snapshot, &annotations, DatabaseType::Postgres);
- assert_eq!(orphans, vec!["core.orders.status".to_string()]);
- }
-
- #[test]
- fn nothing_is_orphaned_when_everything_matches() {
- let mut table = table_named("core", "orders", None);
- table.columns.push(crate::types::ColumnInfo {
- name: "status".to_string(),
- data_type: "text".to_string(),
- ..Default::default()
- });
- let mut snapshot = snapshot_with(vec![table]);
- let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
-
- assert!(detect_orphans(&snapshot, &annotations, DatabaseType::Postgres).is_empty());
-
- apply_annotations(&mut snapshot, &annotations, DatabaseType::Postgres);
- assert!(
- !snapshot.warnings.iter().any(|w| matches!(w, SnapshotWarning::OrphanedNotes { .. })),
- "no orphan warning when everything matches"
- );
- }
-
- #[test]
- fn orphan_detection_never_removes_anything_from_the_file() {
- let snapshot = snapshot_with(vec![]);
- let annotations: AnnotationFile = serde_json::from_str(SAMPLE).expect("parse");
- let before = annotations.tables.len();
-
- let _ = detect_orphans(&snapshot, &annotations, DatabaseType::Postgres);
-
- assert_eq!(annotations.tables.len(), before, "detection must not mutate the file");
- }
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core docs::annotations`
-Expected: FAIL — `cannot find function detect_orphans`.
-
-- [ ] **Step 3: Write the implementation**
-
-```rust
-/// Annotation keys whose target no longer exists in the collected schema.
-///
-/// Returns fully-qualified keys, sorted, so the caller can list them for a
-/// human to re-map. This function NEVER mutates the notes file — user prose
-/// is only ever removed by an explicit human action.
-///
-/// Suggestions for where a renamed target went are deliberately absent:
-/// producing them requires the OLD schema to diff against, and the notes
-/// file stores prose only. That becomes possible once snapshot history
-/// exists (see the spec's deferred versioning seam).
-pub fn detect_orphans(
- snapshot: &SchemaSnapshot,
- annotations: &AnnotationFile,
- db_type: DatabaseType,
-) -> Vec<String> {
- use std::collections::HashSet;
-
- let live_tables: HashSet<String> = snapshot
- .tables
- .iter()
- .map(|table| table_key(db_type, table.schema.as_deref(), &table.name))
- .collect();
-
- let live_columns: HashSet<String> = snapshot
- .tables
- .iter()
- .flat_map(|table| {
- table.columns.iter().map(move |column| {
- column_key(db_type, table.schema.as_deref(), &table.name, &column.name)
- })
- })
- .collect();
-
- let mut orphans = Vec::new();
-
- for (key, annotation) in &annotations.tables {
- let folded_table = fold_key(db_type, key);
- if !live_tables.contains(&folded_table) {
- orphans.push(folded_table);
- continue;
- }
- for column in annotation.columns.keys() {
- let folded_column =
- format!("{folded_table}.{}", crate::docs::keys::fold_identifier(db_type, column));
- if !live_columns.contains(&folded_column) {
- orphans.push(folded_column);
- }
- }
- }
-
- orphans.sort();
- orphans
-}
-
-/// Fold an already-dotted key (e.g. `Core.Orders`) segment by segment.
-fn fold_key(db_type: DatabaseType, key: &str) -> String {
- key.split('.')
- .map(|segment| crate::docs::keys::fold_identifier(db_type, segment))
- .collect::<Vec<_>>()
- .join(".")
-}
-```
-
-Then, at the END of `apply_annotations` (replacing the `let _ = column_key;` placeholder from Task 4):
-
-```rust
- let orphans = detect_orphans(snapshot, annotations, db_type);
- if !orphans.is_empty() {
- snapshot.warnings.push(SnapshotWarning::OrphanedNotes { count: orphans.len() });
- }
-```
-
-Add `SnapshotWarning` to the `use crate::docs::{...}` line.
-
-- [ ] **Step 4: Run the tests**
-
-Run: `cargo test -p dbx-core docs::annotations`
-Expected: PASS, 19 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/
-git commit -m "feat(docs): detect orphaned annotations without deleting them"
-```
-
----
-
-## Task 6: `--notes` CLI flag
-
-**Files:**
-- Modify: `crates/dbx-cli/src/main.rs`
-
-**Interfaces:**
-- Consumes: `load_annotations` (Task 3), `apply_annotations` (Task 4)
-
-**Note:** `DocsSnapshotOptions` in `dbx_mcp::backend` carries options across the backend boundary. It does NOT need an `annotations` field — the CLI loads the file locally and, for `LocalBackend`, the annotations reach the collector directly. For `WebBackend` the notes file lives on the CLI's machine, not the server's, so annotations must be applied CLI-side after the snapshot returns. Implement it that way: load the file in `run_dbml`, and apply it to the returned snapshot with `apply_annotations` before calling `to_dbml`. This keeps both transports identical, which a Part 1 review specifically verified.
-
-- [ ] **Step 1: Write the failing test**
-
-Append to `main.rs`'s test module:
-
-```rust
- #[test]
- fn parses_the_notes_flag() {
- let flags = parse_flags(&args(&["dbml", "local", "--notes", "docs/dbx-docs.json"])).expect("parse");
- assert_eq!(flags.args, args(&["dbml", "local"]));
- assert_eq!(flags.notes.as_deref(), Some(std::path::Path::new("docs/dbx-docs.json")));
- }
-
- #[test]
- fn notes_requires_a_value() {
- let error = parse_flags(&args(&["dbml", "local", "--notes"])).expect_err("should fail");
- assert_eq!(error.code, "INVALID_OPTION");
- }
-
- #[test]
- fn notes_appears_in_the_usage_text() {
- assert!(usage().contains("--notes"), "got: {}", usage());
- }
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-cli`
-Expected: FAIL — `no field named notes on Flags`.
-
-- [ ] **Step 3: Write the implementation**
-
-- Add `notes: Option<PathBuf>` to `Flags` (NO `pub` — the struct and all its fields are private) and initialise it to `None` in `parse_flags`.
-- Add the parse arm beside `--out`:
- ```rust
- "--notes" => flags.notes = Some(PathBuf::from(option_value(argv, &mut index, "--notes")?)),
- ```
-- In `run_dbml`, after obtaining the snapshot and before `to_dbml`:
- ```rust
- let mut snapshot = snapshot;
- if let Some(path) = flags.notes.as_ref() {
- if let Some(annotations) = dbx_core::docs::annotations::load_annotations(path)
- .map_err(|error| CliError::new("NOTES_INVALID", error))?
- {
- dbx_core::docs::annotations::apply_annotations(
- &mut snapshot,
- &annotations,
- connection.db_type,
- );
- }
- }
- ```
- A malformed notes file must abort with a non-zero exit — it must NOT fall through to producing documentation without the prose.
-- Extend the `dbx dbml` line inside the single `usage()` `&'static str` literal so it reads:
- ```
- dbx dbml <connection> [--out path] [--notes path] [--schema name] [--database name] [--tables a,b]
- ```
-
-- [ ] **Step 4: Run the tests**
-
-Run: `cargo test -p dbx-cli`
-Expected: PASS.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-cli/src/main.rs
-git commit -m "feat(docs): add --notes to dbx dbml"
-```
-
----
-
-## Task 7: `docs_notes_path` on ConnectionConfig
-
-**Files:**
-- Modify: `crates/dbx-core/src/models/connection.rs`
-
-**Interfaces:**
-- Produces: `ConnectionConfig.docs_notes_path: Option<String>`
-
-**Why here rather than a new table:** `ConnectionConfig` already carries per-connection preferences (`note`, `color`, `init_script`, `visible_schemas`) and is serde-persisted into the `connections` table. `DesktopSettings.saved_sql_sync_dir` is a GLOBAL setting and is not the right precedent despite what the spec implies. `#[serde(default)]` makes this non-breaking for existing stored connections — no migration.
-
-This field is not consumed by anything in Part 2 (the CLI takes an explicit `--notes` path). It exists so Part 3's desktop dialog has somewhere to remember the path per connection.
-
-- [ ] **Step 1: Write the failing test**
-
-Append to `connection.rs`'s test module (or create one following the file's conventions):
-
-```rust
- #[test]
- fn docs_notes_path_defaults_to_none_for_existing_stored_connections() {
- // A connection persisted before this field existed must still load.
- let json = r#"{
- "id": "c1", "name": "local", "note": "", "db_type": "Postgres",
- "host": "127.0.0.1", "port": 5432, "username": "postgres",
- "password": "", "attached_databases": [], "agent_java_options": [],
- "connect_timeout_secs": 10, "transport_layers": []
- }"#;
- let parsed: ConnectionConfig = serde_json::from_str(json).expect("parse");
- assert_eq!(parsed.docs_notes_path, None);
- }
-```
-
-The exact JSON must satisfy every non-`default` field on `ConnectionConfig`. Run the test, read the serde error, and add whatever fields it names — do NOT add `#[serde(default)]` to other fields to make it pass.
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core docs_notes_path`
-Expected: FAIL — `no field docs_notes_path`.
-
-- [ ] **Step 3: Write the implementation**
-
-Add to `ConnectionConfig`, beside `init_script` / `color`:
-
-```rust
- /// Path to this connection's documentation notes file. Set by the
- /// desktop app; the CLI takes an explicit `--notes` path instead.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub docs_notes_path: Option<String>,
-```
-
-Then fix every `ConnectionConfig { .. }` literal the compiler flags. There are many (including `crates/dbx-core/tests/live_postgres_query_result_export.rs:12`); add `docs_notes_path: None` to each. Let the compiler enumerate them; report the count.
-
-- [ ] **Step 4: Run the tests**
-
-```bash
-cargo test -p dbx-core
-cargo check --workspace --all-targets
-```
-Expected: pass and clean.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add -A
-git commit -m "feat(docs): remember a notes file path per connection"
-```
-
----
-
-## Task 8: Live verification
-
-**Files:**
-- Create: `crates/dbx-core/tests/live_postgres_docs_annotations.rs`
-
-Follow the gating convention of `crates/dbx-core/tests/live_postgres_docs_snapshot.rs` exactly: `#[tokio::test]` + `#[ignore = "requires DBX_LIVE_POSTGRES_..."]`, env vars with defaults, and the `live_postgres_config(...)` builder. Do NOT invent a skip-helper — `#[ignore]` is what keeps the test from silently passing with no database.
-
-- [ ] **Step 1: Write the live test**
-
-The test must: write a temporary notes file annotating a table that genuinely exists in `keycloak` plus one that does not; collect a snapshot with those annotations; then assert
-- the real table's note is present with `note_source == NoteSource::Local`,
-- an `OrphanedNotes` warning is present with `count >= 1`,
-- the generated DBML contains the note text,
-- and the temp file is removed on both success and failure paths.
-
-Print the generated DBML with `println!` so `--nocapture` shows it.
-
-- [ ] **Step 2: Run it against the live database**
-
-```bash
-export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"
-DBX_LIVE_POSTGRES_HOST=127.0.0.1 DBX_LIVE_POSTGRES_PORT=5432 \
-DBX_LIVE_POSTGRES_USER=postgres DBX_LIVE_POSTGRES_PASSWORD=postgres \
-DBX_LIVE_POSTGRES_DATABASE=keycloak \
-cargo test -p dbx-core --test live_postgres_docs_annotations -- --ignored --nocapture
-```
-
-Paste the ACTUAL generated DBML into the report — specifically a `Table` block showing the merged note and the `Note:` line inside it.
-
-- [ ] **Step 3: Full sweep**
-
-```bash
-cargo test --workspace
-cargo clippy -p dbx-core -- -D warnings
-```
-
-Report clippy honestly. `crates/dbx-core/src/table_structure_sql/triggers.rs:58` fails on `map_or` — that is PRE-EXISTING on main, verified byte-identical, and is NOT yours to fix. Confirm it is the only remaining lint.
-
-- [ ] **Step 4: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/tests/
-git commit -m "test(docs): verify annotations against a live database"
-```
-
----
-
-## Done criteria
-
-- `dbx dbml <connection> --notes docs/dbx-docs.json` merges notes and groups into the emitted DBML.
-- An absent notes file is fine; a malformed one aborts with a non-zero exit naming the file.
-- A note whose target no longer exists produces an `OrphanedNotes` warning on stderr and is never deleted.
-- A local note shadowing a database comment preserves the comment in `shadowed_note`.
-- Table groups become `TableGroup` blocks with `[color: #rrggbb]` derived from each group's hue.
-- `cargo test --workspace` passes; clippy clean except the pre-existing `triggers.rs` lint.
-
-## Deferred to Part 3
-
-- The docs viewer, in-app editing dialog, group colour picker, and HTML export.
-- Rename suggestions for orphaned notes (needs snapshot history — spec Section 12).
-- Writing the notes file from DBX (Part 2 only reads it; the file is hand-edited or repo-managed).
-
----
-
-## Appendix: Corrections found during execution
-
-Defects in this plan's own text, found while executing it. Grouped by failure mode rather than by
-task, because the modes repeat and the tasks do not. Every one originated in the plan; none was an
-implementer error. The companion plan for the viewer carries its own appendix in the same form.
-
-### Mode A — compiles, passes its own test, and is silently wrong forever
-
-The most dangerous defect found anywhere in this feature, and the only one that would have shipped
-undetected.
-
-- **Task 7, `docs_notes_path`.** The plan added the field to `ConnectionConfig` and to its own
- test, which passed. But `ConnectionConfig` is not what deserialization reads — a mirror struct,
- `ConnectionConfigData`, carries the serde attributes, and a `From` impl copies fields across.
- Adding the field in one place compiles cleanly, satisfies a round-trip test written against the
- same struct, and then reads `None` forever after every load, because nothing ever populates it.
- Caught by pre-resolution, not by review: the field had to be added in **three** places, and only
- reading the deserialization path revealed the third.
-
-**The lesson:** when a struct has a serde mirror, "it compiles and the test passes" is evidence
-about the wrong object. Follow the value from the file on disk to the field being read.
-
-### Mode B — an assertion too weak to detect the failure it names
-
-Same failure mode as Mode 1 in the viewer plan's appendix, and the most common across both.
-
-- **Task 1, `round_trips_through_json`.** Asserted only `tables.len()` and a single group name. A
- serializer that silently dropped every note, hue, and column annotation would pass it. Fixed by
- asserting the full round-tripped structure.
-- **Task 5.** Each headline test individually survived a mutant; only the *pair* caught it.
- Accepted rather than fixed, but recorded, because a later edit that deletes one test would
- silently remove the coverage the other depends on.
-
-### Mode C — plan text written from memory instead of from the code
-
-Four instances, all caught before dispatch by reading the actual source. None would have survived
-compilation, so the cost was implementer time rather than correctness — but that cost is real.
-
-- `DatabaseType::Mysql`, which the plan spelled `MySQL`.
-- A borrow hazard in a code block the plan supplied verbatim (Task 4).
-- `let mut snapshot = snapshot;` in the `run_dbml` shape, which was a guess at the real signature.
-- `capabilities_for` is `pub(super)`, not `pub`, and `AppState`'s module path was wrong.
-
-**The lesson:** every identifier a plan names is a claim about the codebase. Checking them costs
-minutes; a dispatch that fails on one costs an implementer round-trip.
-
-### Mode D — matching logic that attaches data to the wrong object
-
-- **Task 2, identifier folding.** The original key-matching rule could fold two genuinely distinct
- identifiers to the same key, so a note written for one table would attach to another. The doc
- comment's stated MySQL rationale also described behaviour the code did not implement. Fixed by
- making `fold_identifier` engine-specific (Oracle uppercases, ClickHouse and MongoDB preserve,
- everything else lowercases) and correcting the comment to match.
-
-A related seam was investigated and cleared: Oracle folding is used **only** for matching, never
-for output — the serializer emits the collector's reported name verbatim, so folding cannot corrupt
-what is written.
-
-### Mode E — a test helper that is itself flaky
-
-- **Task 3.** The plan's own test helper had a race that would produce intermittent failures.
- Caught before dispatch. A flaky test in a new suite is worse than no test: it trains the reader
- to re-run rather than to read.
-
-### A controller hypothesis that was wrong
-
-Recorded because being wrong in this direction is cheap and worth doing more often. I suspected a
-second `apply_annotations` call would overwrite `shadowed_note` with the first local note and lose
-the database comment. Tracing it showed the guard simply does not fire on the second call, so
-`shadowed_note` keeps its first-call value. No defect existed. The check cost one read.
diff --git a/docs/superpowers/plans/2026-08-02-database-documentation-snapshot-dbml.md b/docs/superpowers/plans/2026-08-02-database-documentation-snapshot-dbml.md
deleted file mode 100644
index 3eb4ffb27a..0000000000
--- a/docs/superpowers/plans/2026-08-02-database-documentation-snapshot-dbml.md
+++ /dev/null
@@ -1,2712 +0,0 @@
-# Database Documentation Part 1: Snapshot and DBML Export — Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Build `SchemaSnapshot` — the normalized model every documentation output serializes from — plus a DBML serializer and a working `dbx dbml <connection>` CLI verb.
-
-**Architecture:** A new `crates/dbx-core/src/docs/` module. `snapshot.rs` defines a serde model composing the existing `crate::types::{TableInfo, ColumnInfo, IndexInfo, ForeignKeyInfo}` rather than redeclaring them. `relations.rs` ports the cardinality-inference half of `apps/desktop/src/lib/diagram/erDiagram.ts` to Rust. `collector.rs` fans out over the existing `schema::providers` functions with a bounded semaphore. `dbml.rs` is a pure function `SchemaSnapshot -> String`. The CLI reaches the database through a single new `DbxBackend::collect_docs_snapshot` method so `WebBackend` makes one HTTP call rather than 3×N.
-
-**Tech Stack:** Rust (dbx-core, dbx-web, dbx-mcp, dbx-cli), tokio, serde. No new dependencies.
-
-**Branch:** create `feature/docs-snapshot-dbml` from current HEAD.
-
-**Spec:** `docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.md`.
-
-**Scope note:** This is part 1 of 3, covering Build Order steps 1–2 from the spec. Table groups and notes are *serialized* here but not *authored* — `SchemaSnapshot.groups` and all note fields stay empty until Part 2 adds the annotation store. The serializer is tested against hand-built snapshots that do contain groups and notes, so Part 2 wires in a proven serializer. The docs viewer, HTML export and `dbx docs` are Part 3.
-
-## Global Constraints
-
-- **No new dependencies.** Everything here uses the existing crate graph.
-- **Reuse, never redeclare** `crate::types::{TableInfo, ColumnInfo, IndexInfo, ForeignKeyInfo}`.
-- `SchemaSnapshot.format_version` is `1` for every snapshot this plan produces.
-- Group colour is stored as `hue: u16` in `0..=359`, never a hex string. Hex appears only in DBML output.
-- Every DBML-inexpressible construct produces a `SnapshotWarning::DbmlOmitted`; none are silently dropped.
-- Conventional Commits (`feat(docs): …`), matching repo history.
-- Run `cargo fmt` before each commit; the repo has `rustfmt.toml` and `clippy.toml`.
-
----
-
-## File Structure
-
-| File | Responsibility |
-| --- | --- |
-| `crates/dbx-core/src/docs/mod.rs` | Module wiring + public API (`collect_snapshot`, `to_dbml`) |
-| `crates/dbx-core/src/docs/snapshot.rs` | `SchemaSnapshot` and all its member types |
-| `crates/dbx-core/src/docs/relations.rs` | FK → `Relationship` with cardinality inference |
-| `crates/dbx-core/src/docs/collector.rs` | Bounded metadata fan-out, progress, cancellation |
-| `crates/dbx-core/src/docs/dbml.rs` | `SchemaSnapshot` → DBML text |
-| `crates/dbx-core/src/docs/color.rs` | OKLCH hue → sRGB hex for DBML `[color: …]` |
-| `crates/dbx-web/src/routes/docs.rs` | `POST /api/docs/snapshot` |
-| `crates/dbx-mcp/src/backend.rs` | `DbxBackend::collect_docs_snapshot` + both impls |
-| `crates/dbx-cli/src/main.rs` | `dbx dbml` verb, `--out` flag, usage text |
-
----
-
-## Task 0: Branch setup
-
-- [ ] **Step 1: Create the branch**
-
-```bash
-cd /Users/possebon/workspaces/dbx
-git checkout -b feature/docs-snapshot-dbml
-```
-
-- [ ] **Step 2: Confirm a clean baseline**
-
-Run: `cargo check -p dbx-core`
-Expected: finishes with no errors. If it fails, stop — the baseline is broken and nothing below is diagnosable.
-
----
-
-## Task 1: Snapshot model
-
-**Files:**
-- Create: `crates/dbx-core/src/docs/mod.rs`
-- Create: `crates/dbx-core/src/docs/snapshot.rs`
-- Modify: `crates/dbx-core/src/lib.rs` (add `pub mod docs;`)
-
-**Interfaces:**
-- Consumes: `crate::types::{ColumnInfo, ForeignKeyInfo, IndexInfo}`
-- Produces: `SchemaSnapshot`, `ProjectMeta`, `DocTable`, `TableGroup`, `Relationship`, `FieldRef`, `ColumnNote`, `DocEnum`, `TableKind`, `NoteSource`, `Cardinality`, `SnapshotWarning`
-
-- [ ] **Step 1: Write the failing test**
-
-Create `crates/dbx-core/src/docs/snapshot.rs` with only this test module at the bottom (types come in Step 3):
-
-```rust
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn sample() -> SchemaSnapshot {
- SchemaSnapshot {
- format_version: 1,
- project: ProjectMeta {
- name: "Ecommerce".to_string(),
- database_type: "PostgreSQL".to_string(),
- database: Some("shop".to_string()),
- schemas: vec!["public".to_string()],
- generated_at: "2026-08-02T12:00:00Z".to_string(),
- note: None,
- },
- tables: vec![DocTable {
- schema: Some("public".to_string()),
- name: "orders".to_string(),
- kind: TableKind::Table,
- columns: vec![],
- indexes: vec![],
- foreign_keys: vec![],
- group_id: None,
- note: Some("Checkout rows.".to_string()),
- note_source: NoteSource::Database,
- shadowed_note: None,
- column_notes: BTreeMap::new(),
- estimated_rows: Some(2_400_000),
- view_definition: None,
- }],
- relationships: vec![],
- groups: vec![],
- enums: vec![],
- warnings: vec![],
- }
- }
-
- #[test]
- fn snapshot_round_trips_through_json() {
- let original = sample();
- let json = serde_json::to_string(&original).expect("serialize");
- let parsed: SchemaSnapshot = serde_json::from_str(&json).expect("deserialize");
-
- assert_eq!(parsed.format_version, 1);
- assert_eq!(parsed.project.name, "Ecommerce");
- assert_eq!(parsed.tables.len(), 1);
- assert_eq!(parsed.tables[0].name, "orders");
- assert_eq!(parsed.tables[0].note.as_deref(), Some("Checkout rows."));
- assert_eq!(parsed.tables[0].estimated_rows, Some(2_400_000));
- }
-
- #[test]
- fn snapshot_json_uses_camel_case_keys() {
- let json = serde_json::to_string(&sample()).expect("serialize");
- assert!(json.contains("\"formatVersion\""), "got: {json}");
- assert!(json.contains("\"generatedAt\""), "got: {json}");
- assert!(json.contains("\"noteSource\""), "got: {json}");
- }
-
- #[test]
- fn table_kind_serializes_as_screaming_snake_case() {
- let json = serde_json::to_string(&TableKind::MaterializedView).expect("serialize");
- assert_eq!(json, "\"MATERIALIZED_VIEW\"");
- }
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-First wire the module so the file compiles at all. Add to `crates/dbx-core/src/lib.rs` alongside the other `pub mod` lines:
-
-```rust
-pub mod docs;
-```
-
-Create `crates/dbx-core/src/docs/mod.rs`:
-
-```rust
-pub mod snapshot;
-
-pub use snapshot::*;
-```
-
-Run: `cargo test -p dbx-core docs::snapshot`
-Expected: FAIL — `cannot find struct SchemaSnapshot in this scope` and similar for every type.
-
-- [ ] **Step 3: Write the types**
-
-At the top of `crates/dbx-core/src/docs/snapshot.rs`, above the test module:
-
-```rust
-use std::collections::BTreeMap;
-
-use serde::{Deserialize, Serialize};
-
-use crate::types::{ColumnInfo, ForeignKeyInfo, IndexInfo};
-
-/// The normalized description of a relational schema. Every documentation
-/// output (DBML, HTML, future changelog records) is a serializer over this.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SchemaSnapshot {
- /// Guards viewer/data skew. Always 1 for now; bump only on a breaking
- /// change to this model.
- pub format_version: u32,
- pub project: ProjectMeta,
- pub tables: Vec<DocTable>,
- pub relationships: Vec<Relationship>,
- #[serde(default)]
- pub groups: Vec<TableGroup>,
- #[serde(default)]
- pub enums: Vec<DocEnum>,
- #[serde(default)]
- pub warnings: Vec<SnapshotWarning>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ProjectMeta {
- pub name: String,
- pub database_type: String,
- pub database: Option<String>,
- pub schemas: Vec<String>,
- /// RFC3339.
- pub generated_at: String,
- /// Markdown. Rendered as the documentation landing page.
- pub note: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DocTable {
- pub schema: Option<String>,
- pub name: String,
- pub kind: TableKind,
- pub columns: Vec<ColumnInfo>,
- pub indexes: Vec<IndexInfo>,
- pub foreign_keys: Vec<ForeignKeyInfo>,
- /// References `TableGroup::id`. Populated in Part 2.
- pub group_id: Option<String>,
- /// Merged note: local annotation, else database comment.
- pub note: Option<String>,
- pub note_source: NoteSource,
- /// The database comment a local note is overriding, if any. Shown on
- /// hover so a later `COMMENT ON` improvement is never invisible.
- pub shadowed_note: Option<String>,
- #[serde(default)]
- pub column_notes: BTreeMap<String, ColumnNote>,
- pub estimated_rows: Option<i64>,
- pub view_definition: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TableGroup {
- /// Stable slug. Survives a display-name change.
- pub id: String,
- pub name: String,
- /// 0..=359. Lightness and chroma are theme-controlled in CSS, so any
- /// hue is legible on both grounds by construction.
- pub hue: u16,
- pub note: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ColumnNote {
- pub note: String,
- pub source: NoteSource,
- pub shadowed: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DocEnum {
- pub schema: Option<String>,
- pub name: String,
- pub values: Vec<String>,
- pub note: Option<String>,
- /// True when synthesized from a MySQL inline `ENUM(...)` column rather
- /// than read from a named database type.
- #[serde(default)]
- pub synthesized: bool,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct Relationship {
- pub id: String,
- pub name: Option<String>,
- pub from: FieldRef,
- pub to: FieldRef,
- pub cardinality: Cardinality,
- pub on_update: Option<String>,
- pub on_delete: Option<String>,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct FieldRef {
- pub schema: Option<String>,
- pub table: String,
- pub column: String,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum TableKind {
- Table,
- View,
- MaterializedView,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum NoteSource {
- /// Read from a database COMMENT.
- Database,
- /// Authored in DBX, stored in the notes file.
- Local,
- None,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum Cardinality {
- OneToOne,
- ManyToOne,
-}
-
-/// Why a snapshot is less complete than it looks. Rendered as a dismissible
-/// banner rather than left for the reader to discover.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", tag = "kind")]
-pub enum SnapshotWarning {
- TableSkipped { table: String, reason: String },
- NoForeignKeyMetadata { engine: String },
- CommentsUnsupported { engine: String },
- OrphanedNotes { count: usize },
- DbmlOmitted { table: String, item: String, reason: String },
-}
-
-impl DocTable {
- /// `schema.name` when a schema is present, otherwise bare `name`.
- pub fn qualified_name(&self) -> String {
- match &self.schema {
- Some(schema) if !schema.is_empty() => format!("{schema}.{}", self.name),
- _ => self.name.clone(),
- }
- }
-}
-
-impl FieldRef {
- pub fn qualified_table(&self) -> String {
- match &self.schema {
- Some(schema) if !schema.is_empty() => format!("{schema}.{}", self.table),
- _ => self.table.clone(),
- }
- }
-}
-```
-
-- [ ] **Step 4: Run the tests to verify they pass**
-
-Run: `cargo test -p dbx-core docs::snapshot`
-Expected: PASS, 3 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/lib.rs crates/dbx-core/src/docs/
-git commit -m "feat(docs): add SchemaSnapshot model"
-```
-
----
-
-## Task 2: Relationship inference
-
-**Files:**
-- Create: `crates/dbx-core/src/docs/relations.rs`
-- Modify: `crates/dbx-core/src/docs/mod.rs`
-
-**Interfaces:**
-- Consumes: `DocTable`, `Relationship`, `FieldRef`, `Cardinality` from Task 1
-- Produces: `pub fn build_relationships(tables: &[DocTable]) -> Vec<Relationship>`
-
-This ports the data half of `apps/desktop/src/lib/diagram/erDiagram.ts`. The rule, from `foreignKeySourceCardinality`: a foreign key is `OneToOne` **only** when the source columns contain a unique key (unique index or primary key); otherwise `ManyToOne`.
-
-- [ ] **Step 1: Write the failing test**
-
-Create `crates/dbx-core/src/docs/relations.rs` with only this test module:
-
-```rust
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::docs::{NoteSource, TableKind};
- use crate::types::{ColumnInfo, ForeignKeyInfo, IndexInfo};
- use std::collections::BTreeMap;
-
- fn column(name: &str, primary: bool) -> ColumnInfo {
- ColumnInfo {
- name: name.to_string(),
- data_type: "integer".to_string(),
- is_nullable: false,
- is_primary_key: primary,
- ..ColumnInfo::default()
- }
- }
-
- fn fk(name: &str, column: &str, ref_table: &str, ref_column: &str) -> ForeignKeyInfo {
- ForeignKeyInfo {
- name: name.to_string(),
- column: column.to_string(),
- ref_schema: Some("public".to_string()),
- ref_table: ref_table.to_string(),
- ref_column: ref_column.to_string(),
- on_update: None,
- on_delete: Some("CASCADE".to_string()),
- }
- }
-
- fn unique_index(name: &str, columns: &[&str]) -> IndexInfo {
- IndexInfo {
- name: name.to_string(),
- columns: columns.iter().map(|c| c.to_string()).collect(),
- is_unique: true,
- is_primary: false,
- filter: None,
- index_type: None,
- included_columns: None,
- comment: None,
- }
- }
-
- fn table(name: &str, columns: Vec<ColumnInfo>, indexes: Vec<IndexInfo>, fks: Vec<ForeignKeyInfo>) -> DocTable {
- DocTable {
- schema: Some("public".to_string()),
- name: name.to_string(),
- kind: TableKind::Table,
- columns,
- indexes,
- foreign_keys: fks,
- group_id: None,
- note: None,
- note_source: NoteSource::None,
- shadowed_note: None,
- column_notes: BTreeMap::new(),
- estimated_rows: None,
- view_definition: None,
- }
- }
-
- #[test]
- fn plain_foreign_key_is_many_to_one() {
- let tables = vec![
- table("orders", vec![column("id", true), column("user_id", false)], vec![],
- vec![fk("fk_orders_user", "user_id", "users", "id")]),
- table("users", vec![column("id", true)], vec![], vec![]),
- ];
-
- let rels = build_relationships(&tables);
-
- assert_eq!(rels.len(), 1);
- assert_eq!(rels[0].cardinality, Cardinality::ManyToOne);
- assert_eq!(rels[0].from.table, "orders");
- assert_eq!(rels[0].from.column, "user_id");
- assert_eq!(rels[0].to.table, "users");
- assert_eq!(rels[0].to.column, "id");
- assert_eq!(rels[0].on_delete.as_deref(), Some("CASCADE"));
- }
-
- #[test]
- fn foreign_key_on_a_unique_column_is_one_to_one() {
- let tables = vec![
- table("shipments",
- vec![column("id", true), column("order_id", false)],
- vec![unique_index("uq_shipments_order", &["order_id"])],
- vec![fk("fk_shipments_order", "order_id", "orders", "id")]),
- table("orders", vec![column("id", true)], vec![], vec![]),
- ];
-
- let rels = build_relationships(&tables);
-
- assert_eq!(rels.len(), 1);
- assert_eq!(rels[0].cardinality, Cardinality::OneToOne);
- }
-
- #[test]
- fn foreign_key_on_a_primary_key_column_is_one_to_one() {
- let tables = vec![
- table("user_profiles", vec![column("user_id", true)], vec![],
- vec![fk("fk_profile_user", "user_id", "users", "id")]),
- table("users", vec![column("id", true)], vec![], vec![]),
- ];
-
- assert_eq!(build_relationships(&tables)[0].cardinality, Cardinality::OneToOne);
- }
-
- #[test]
- fn multi_column_unique_index_does_not_make_a_single_column_unique() {
- // uq(a, b) does NOT make `a` alone unique, so the FK stays many-to-one.
- let tables = vec![
- table("order_items",
- vec![column("order_id", false), column("product_id", false)],
- vec![unique_index("uq_items", &["order_id", "product_id"])],
- vec![fk("fk_items_order", "order_id", "orders", "id")]),
- table("orders", vec![column("id", true)], vec![], vec![]),
- ];
-
- assert_eq!(build_relationships(&tables)[0].cardinality, Cardinality::ManyToOne);
- }
-
- #[test]
- fn self_referencing_foreign_key_is_supported() {
- let tables = vec![table("categories",
- vec![column("id", true), column("parent_id", false)], vec![],
- vec![fk("fk_cat_parent", "parent_id", "categories", "id")])];
-
- let rels = build_relationships(&tables);
-
- assert_eq!(rels.len(), 1);
- assert_eq!(rels[0].from.table, "categories");
- assert_eq!(rels[0].to.table, "categories");
- }
-
- #[test]
- fn foreign_key_to_an_absent_table_is_dropped() {
- // The target may live outside the selected schema. A dangling edge
- // would render as a relationship to nothing.
- let tables = vec![table("orders", vec![column("user_id", false)], vec![],
- vec![fk("fk_orders_user", "user_id", "users", "id")])];
-
- assert!(build_relationships(&tables).is_empty());
- }
-
- #[test]
- fn relationship_ids_are_stable_and_unique() {
- let tables = vec![
- table("orders",
- vec![column("user_id", false), column("merchant_id", false)], vec![],
- vec![fk("fk_a", "user_id", "users", "id"),
- fk("fk_b", "merchant_id", "users", "id")]),
- table("users", vec![column("id", true)], vec![], vec![]),
- ];
-
- let rels = build_relationships(&tables);
- assert_eq!(rels.len(), 2);
- assert_ne!(rels[0].id, rels[1].id);
- assert_eq!(build_relationships(&tables)[0].id, rels[0].id);
- }
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Add to `crates/dbx-core/src/docs/mod.rs`:
-
-```rust
-pub mod relations;
-pub mod snapshot;
-
-pub use relations::build_relationships;
-pub use snapshot::*;
-```
-
-Run: `cargo test -p dbx-core docs::relations`
-Expected: FAIL — `cannot find function build_relationships`.
-
-- [ ] **Step 3: Write the implementation**
-
-At the top of `crates/dbx-core/src/docs/relations.rs`:
-
-```rust
-use std::collections::HashSet;
-
-use crate::docs::{Cardinality, DocTable, FieldRef, Relationship};
-use crate::types::ForeignKeyInfo;
-
-/// True when `column` alone is guaranteed unique on `table` — either it is a
-/// single-column primary key, or a single-column unique index covers it.
-///
-/// A composite unique index over (a, b) does NOT make `a` unique, which is
-/// why the column count is checked.
-fn column_is_unique(table: &DocTable, column: &str) -> bool {
- let primary_columns: Vec<&str> =
- table.columns.iter().filter(|c| c.is_primary_key).map(|c| c.name.as_str()).collect();
-
- if primary_columns.len() == 1 && primary_columns[0] == column {
- return true;
- }
-
- table
- .indexes
- .iter()
- .any(|index| (index.is_unique || index.is_primary) && index.columns.len() == 1 && index.columns[0] == column)
-}
-
-fn cardinality_for(table: &DocTable, foreign_key: &ForeignKeyInfo) -> Cardinality {
- if column_is_unique(table, &foreign_key.column) {
- Cardinality::OneToOne
- } else {
- Cardinality::ManyToOne
- }
-}
-
-fn relationship_id(source: &DocTable, foreign_key: &ForeignKeyInfo) -> String {
- [
- source.qualified_name().as_str(),
- if foreign_key.name.is_empty() { "foreign_key" } else { foreign_key.name.as_str() },
- foreign_key.column.as_str(),
- foreign_key.ref_table.as_str(),
- foreign_key.ref_column.as_str(),
- ]
- .join(":")
-}
-
-/// Resolve a foreign key's target against the tables actually present.
-///
-/// Resolution order mirrors SQL's own: an explicit `ref_schema` wins; an
-/// unqualified reference resolves inside the source table's own schema;
-/// only then do we consider a bare-name match elsewhere — and an ambiguous
-/// one is dropped rather than guessed at, because a wrong edge is worse
-/// than a missing one.
-///
-/// A naive first-match-by-name fallback is NOT safe here: a snapshot can
-/// hold `tenant_a.users` and `tenant_b.users` at once (the collector
-/// flattens every selected schema into one Vec), so it would silently bind
-/// foreign keys to the wrong table.
-fn find_target<'a>(
- tables: &'a [DocTable],
- source: &DocTable,
- foreign_key: &ForeignKeyInfo,
-) -> Option<&'a DocTable> {
- if let Some(ref_schema) = foreign_key.ref_schema.as_deref().filter(|s| !s.is_empty()) {
- if let Some(found) = tables
- .iter()
- .find(|t| t.name == foreign_key.ref_table && t.schema.as_deref() == Some(ref_schema))
- {
- return Some(found);
- }
- }
-
- if let Some(found) =
- tables.iter().find(|t| t.name == foreign_key.ref_table && t.schema == source.schema)
- {
- return Some(found);
- }
-
- let mut matches = tables.iter().filter(|t| t.name == foreign_key.ref_table);
- let first = matches.next()?;
- if matches.next().is_some() {
- return None;
- }
- Some(first)
-}
-
-/// Build the relationship set for a snapshot.
-///
-/// Foreign keys pointing at tables outside the collected set are dropped —
-/// the target may live in a schema the user did not select, and a dangling
-/// edge renders as a relationship to nothing.
-pub fn build_relationships(tables: &[DocTable]) -> Vec<Relationship> {
- let mut seen: HashSet<String> = HashSet::new();
- let mut relationships = Vec::new();
-
- for source in tables {
- for foreign_key in &source.foreign_keys {
- let Some(target) = find_target(tables, source, foreign_key) else { continue };
-
- if !source.columns.iter().any(|c| c.name == foreign_key.column) {
- continue;
- }
-
- let id = relationship_id(source, foreign_key);
- if !seen.insert(id.clone()) {
- continue;
- }
-
- relationships.push(Relationship {
- id,
- name: (!foreign_key.name.is_empty()).then(|| foreign_key.name.clone()),
- from: FieldRef {
- schema: source.schema.clone(),
- table: source.name.clone(),
- column: foreign_key.column.clone(),
- },
- to: FieldRef {
- schema: target.schema.clone(),
- table: target.name.clone(),
- column: foreign_key.ref_column.clone(),
- },
- cardinality: cardinality_for(source, foreign_key),
- on_update: foreign_key.on_update.clone(),
- on_delete: foreign_key.on_delete.clone(),
- });
- }
- }
-
- relationships
-}
-```
-
-- [ ] **Step 4: Run the tests to verify they pass**
-
-Run: `cargo test -p dbx-core docs::relations`
-Expected: PASS, 7 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/
-git commit -m "feat(docs): infer relationship cardinality from foreign keys"
-```
-
----
-
-## Task 3: OKLCH hue to sRGB hex
-
-**Files:**
-- Create: `crates/dbx-core/src/docs/color.rs`
-- Modify: `crates/dbx-core/src/docs/mod.rs`
-
-**Interfaces:**
-- Produces: `pub fn hue_to_hex(hue: u16) -> String`
-
-DBML's `TableGroup [color: #rrggbb]` needs hex, but groups store a hue. Convert at the theme-neutral lightness `L = 0.55`, `C = 0.15` — the light-theme `--group-c` from the spec — so an exported DBML file opened in dbdocs looks like DBX's light theme.
-
-- [ ] **Step 1: Write the failing test**
-
-Create `crates/dbx-core/src/docs/color.rs` with only this test module:
-
-```rust
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn produces_a_six_digit_lowercase_hex_string() {
- let hex = hue_to_hex(28);
- assert_eq!(hex.len(), 7, "got {hex}");
- assert!(hex.starts_with('#'), "got {hex}");
- assert!(hex[1..].chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()), "got {hex}");
- }
-
- #[test]
- fn hue_28_is_a_warm_orange_red() {
- // Sanity check against the group palette: red channel dominates.
- let hex = hue_to_hex(28);
- let r = u8::from_str_radix(&hex[1..3], 16).unwrap();
- let g = u8::from_str_radix(&hex[3..5], 16).unwrap();
- let b = u8::from_str_radix(&hex[5..7], 16).unwrap();
- assert!(r > g && g > b, "expected r > g > b, got {hex}");
- }
-
- #[test]
- fn hue_148_is_green_dominant() {
- let hex = hue_to_hex(148);
- let r = u8::from_str_radix(&hex[1..3], 16).unwrap();
- let g = u8::from_str_radix(&hex[3..5], 16).unwrap();
- assert!(g > r, "expected green to dominate, got {hex}");
- }
-
- #[test]
- fn every_hue_is_in_range_and_never_panics() {
- for hue in 0..=359u16 {
- let hex = hue_to_hex(hue);
- assert_eq!(hex.len(), 7, "hue {hue} produced {hex}");
- }
- }
-
- #[test]
- fn hue_wraps_past_360() {
- assert_eq!(hue_to_hex(0), hue_to_hex(360));
- assert_eq!(hue_to_hex(28), hue_to_hex(388));
- }
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Add `pub mod color;` and `pub use color::hue_to_hex;` to `crates/dbx-core/src/docs/mod.rs`.
-
-Run: `cargo test -p dbx-core docs::color`
-Expected: FAIL — `cannot find function hue_to_hex`.
-
-- [ ] **Step 3: Write the implementation**
-
-At the top of `crates/dbx-core/src/docs/color.rs`:
-
-```rust
-/// Lightness and chroma of the light-theme `--group-c` token. Only hue
-/// varies per group, which is what guarantees legible contrast.
-const GROUP_LIGHTNESS: f64 = 0.55;
-const GROUP_CHROMA: f64 = 0.15;
-
-fn linear_to_srgb(channel: f64) -> f64 {
- if channel <= 0.003_130_8 {
- 12.92 * channel
- } else {
- 1.055 * channel.powf(1.0 / 2.4) - 0.055
- }
-}
-
-fn to_byte(channel: f64) -> u8 {
- (linear_to_srgb(channel).clamp(0.0, 1.0) * 255.0).round() as u8
-}
-
-/// Convert a group hue to the sRGB hex DBML expects.
-///
-/// OKLCH -> OKLab -> LMS -> linear sRGB -> gamma-encoded sRGB.
-/// Coefficients are Björn Ottosson's published OKLab matrices.
-pub fn hue_to_hex(hue: u16) -> String {
- let radians = f64::from(hue % 360) * std::f64::consts::PI / 180.0;
- let a = GROUP_CHROMA * radians.cos();
- let b = GROUP_CHROMA * radians.sin();
-
- let l_ = GROUP_LIGHTNESS + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
- let m_ = GROUP_LIGHTNESS - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
- let s_ = GROUP_LIGHTNESS - 0.089_484_177_5 * a - 1.291_485_548_0 * b;
-
- let l = l_ * l_ * l_;
- let m = m_ * m_ * m_;
- let s = s_ * s_ * s_;
-
- let red = 4.076_741_662_1 * l - 3.307_711_591_3 * m + 0.230_969_929_2 * s;
- let green = -1.268_438_004_6 * l + 2.609_757_401_1 * m - 0.341_319_396_5 * s;
- let blue = -0.004_196_086_3 * l - 0.703_418_614_7 * m + 1.707_614_701_0 * s;
-
- format!("#{:02x}{:02x}{:02x}", to_byte(red), to_byte(green), to_byte(blue))
-}
-```
-
-- [ ] **Step 4: Run the tests to verify they pass**
-
-Run: `cargo test -p dbx-core docs::color`
-Expected: PASS, 5 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/
-git commit -m "feat(docs): convert group hue to sRGB hex for DBML"
-```
-
----
-
-## Task 4: DBML lexical primitives
-
-**Files:**
-- Create: `crates/dbx-core/src/docs/dbml.rs`
-- Modify: `crates/dbx-core/src/docs/mod.rs`
-
-**Interfaces:**
-- Produces (crate-internal): `fn quote_identifier(&str) -> String`, `fn render_note(&str) -> String`, `fn render_default(&ColumnInfo) -> Option<String>`, `fn render_type(&ColumnInfo) -> String`
-
-- [ ] **Step 1: Write the failing test**
-
-Create `crates/dbx-core/src/docs/dbml.rs` with only this test module:
-
-```rust
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::types::ColumnInfo;
-
- fn col(name: &str, data_type: &str) -> ColumnInfo {
- ColumnInfo { name: name.to_string(), data_type: data_type.to_string(), ..ColumnInfo::default() }
- }
-
- #[test]
- fn plain_identifiers_are_not_quoted() {
- assert_eq!(quote_identifier("orders"), "orders");
- assert_eq!(quote_identifier("order_items"), "order_items");
- assert_eq!(quote_identifier("_private"), "_private");
- assert_eq!(quote_identifier("t2"), "t2");
- }
-
- #[test]
- fn irregular_identifiers_are_quoted() {
- assert_eq!(quote_identifier("order items"), "\"order items\"");
- assert_eq!(quote_identifier("2fast"), "\"2fast\"");
- assert_eq!(quote_identifier("user-profile"), "\"user-profile\"");
- assert_eq!(quote_identifier(""), "\"\"");
- }
-
- #[test]
- fn embedded_double_quotes_are_escaped() {
- assert_eq!(quote_identifier("we\"ird"), "\"we\\\"ird\"");
- }
-
- #[test]
- fn notes_always_use_triple_quotes_so_apostrophes_are_safe() {
- assert_eq!(render_note("Bob's orders"), "'''Bob's orders'''");
- }
-
- #[test]
- fn notes_escape_a_literal_triple_quote() {
- assert_eq!(render_note("a ''' b"), "'''a \\''' b'''");
- }
-
- #[test]
- fn multiline_notes_are_preserved() {
- assert_eq!(render_note("line one\nline two"), "'''line one\nline two'''");
- }
-
- #[test]
- fn expression_defaults_use_backticks_and_literals_use_quotes() {
- let mut expression = col("created_at", "timestamptz");
- expression.column_default = Some("now()".to_string());
- assert_eq!(render_default(&expression).as_deref(), Some("default: `now()`"));
-
- let mut sequence = col("id", "integer");
- sequence.column_default = Some("nextval('orders_id_seq'::regclass)".to_string());
- assert_eq!(render_default(&sequence).as_deref(), Some("default: `nextval('orders_id_seq'::regclass)`"));
-
- let mut literal = col("status", "text");
- literal.column_default = Some("'pending'".to_string());
- assert_eq!(render_default(&literal).as_deref(), Some("default: 'pending'"));
-
- let mut number = col("qty", "integer");
- number.column_default = Some("0".to_string());
- assert_eq!(render_default(&number).as_deref(), Some("default: 0"));
-
- let mut boolean = col("active", "boolean");
- boolean.column_default = Some("true".to_string());
- assert_eq!(render_default(&boolean).as_deref(), Some("default: true"));
-
- assert_eq!(render_default(&col("plain", "text")), None);
- }
-
- #[test]
- fn types_pass_through_verbatim_when_already_parameterised() {
- assert_eq!(render_type(&col("total", "numeric(10,2)")), "numeric(10,2)");
- assert_eq!(render_type(&col("meta", "jsonb")), "jsonb");
- assert_eq!(render_type(&col("at", "timestamp with time zone")), "timestamp with time zone");
- }
-
- #[test]
- fn bare_types_are_reconstructed_from_precision_metadata() {
- let mut varchar = col("email", "character varying");
- varchar.character_maximum_length = Some(255);
- assert_eq!(render_type(&varchar), "character varying(255)");
-
- let mut decimal = col("total", "numeric");
- decimal.numeric_precision = Some(10);
- decimal.numeric_scale = Some(2);
- assert_eq!(render_type(&decimal), "numeric(10,2)");
-
- let mut integer = col("count", "numeric");
- integer.numeric_precision = Some(8);
- integer.numeric_scale = Some(0);
- assert_eq!(render_type(&integer), "numeric(8)");
- }
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Add `pub mod dbml;` to `crates/dbx-core/src/docs/mod.rs`.
-
-Run: `cargo test -p dbx-core docs::dbml`
-Expected: FAIL — `cannot find function quote_identifier`.
-
-- [ ] **Step 3: Write the implementation**
-
-At the top of `crates/dbx-core/src/docs/dbml.rs`:
-
-```rust
-use crate::types::ColumnInfo;
-
-/// DBML accepts bare identifiers matching `[A-Za-z_][A-Za-z0-9_]*`;
-/// everything else needs double quotes.
-pub(crate) fn quote_identifier(value: &str) -> String {
- let plain = !value.is_empty()
- && value.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
- && value.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
-
- if plain {
- value.to_string()
- } else {
- format!("\"{}\"", value.replace('"', "\\\""))
- }
-}
-
-/// Notes always use triple quotes so an apostrophe in prose can never break
-/// the file.
-///
-/// Two things need escaping. A literal `'''` inside the prose, obviously —
-/// and also a SINGLE trailing quote, which is subtler: the note `he said '`
-/// would otherwise render as `'''he said ''''`, four quotes in a row, and a
-/// parser scanning for the closing `'''` would close early and strand the
-/// fourth. DBML honours `\'` inside triple quotes.
-pub(crate) fn render_note(value: &str) -> String {
- let escaped = value.replace("'''", "\\'''");
- let escaped = match escaped.strip_suffix('\'') {
- Some(head) => format!("{head}\\'"),
- None => escaped,
- };
- format!("'''{escaped}'''")
-}
-
-fn looks_like_expression(value: &str) -> bool {
- let trimmed = value.trim();
- if trimmed.starts_with('\'') && trimmed.ends_with('\'') && trimmed.len() >= 2 {
- return false;
- }
- if trimmed.parse::<f64>().is_ok() {
- return false;
- }
- if matches!(trimmed.to_ascii_lowercase().as_str(), "true" | "false" | "null") {
- return false;
- }
- true
-}
-
-/// `default: …` for a column, or None when it has no default.
-/// Expressions go in backticks, literals stay as written.
-pub(crate) fn render_default(column: &ColumnInfo) -> Option<String> {
- let value = column.column_default.as_deref()?.trim();
- if value.is_empty() {
- return None;
- }
-
- if looks_like_expression(value) {
- Some(format!("default: `{value}`"))
- } else {
- Some(format!("default: {value}"))
- }
-}
-
-/// DBML does not validate type names, so native types pass through intact.
-/// Precision is reconstructed only when the engine reported a bare type.
-pub(crate) fn render_type(column: &ColumnInfo) -> String {
- let base = column.data_type.trim();
- if base.contains('(') {
- return base.to_string();
- }
-
- if let Some(length) = column.character_maximum_length.filter(|value| *value > 0) {
- return format!("{base}({length})");
- }
-
- if let Some(precision) = column.numeric_precision.filter(|value| *value > 0) {
- return match column.numeric_scale {
- Some(scale) if scale > 0 => format!("{base}({precision},{scale})"),
- _ => format!("{base}({precision})"),
- };
- }
-
- base.to_string()
-}
-```
-
-- [ ] **Step 4: Run the tests to verify they pass**
-
-Run: `cargo test -p dbx-core docs::dbml`
-Expected: PASS, 9 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/
-git commit -m "feat(docs): add DBML lexical primitives"
-```
-
----
-
-## Task 5: DBML table blocks
-
-**Files:**
-- Modify: `crates/dbx-core/src/docs/dbml.rs`
-
-**Interfaces:**
-- Consumes: Task 4 primitives, `DocTable`/`ColumnNote` from Task 1
-- Produces (crate-internal): `fn render_table(table: &DocTable, qualify: bool, warnings: &mut Vec<SnapshotWarning>) -> String`
-
-- [ ] **Step 1: Write the failing test**
-
-Append to the `tests` module in `crates/dbx-core/src/docs/dbml.rs`:
-
-```rust
- use crate::docs::{ColumnNote, DocTable, NoteSource, SnapshotWarning, TableKind};
- use crate::types::IndexInfo;
- use std::collections::BTreeMap;
-
- fn doc_table(name: &str, columns: Vec<ColumnInfo>, indexes: Vec<IndexInfo>) -> DocTable {
- DocTable {
- schema: Some("public".to_string()),
- name: name.to_string(),
- kind: TableKind::Table,
- columns,
- indexes,
- foreign_keys: vec![],
- group_id: None,
- note: None,
- note_source: NoteSource::None,
- shadowed_note: None,
- column_notes: BTreeMap::new(),
- estimated_rows: None,
- view_definition: None,
- }
- }
-
- #[test]
- fn renders_a_table_with_columns_and_settings() {
- let mut id = col("id", "integer");
- id.is_primary_key = true;
- id.extra = Some("auto_increment".to_string());
-
- let mut user_id = col("user_id", "integer");
- user_id.is_nullable = false;
-
- // ColumnInfo::default() gives is_nullable=false (i.e. NOT NULL), so a
- // genuinely nullable column has to say so explicitly.
- let mut nullable = col("shipped_at", "timestamptz");
- nullable.is_nullable = true;
-
- let mut table = doc_table("orders", vec![id, user_id, nullable], vec![]);
- table.note = Some("Checkout rows.".to_string());
- table.column_notes.insert(
- "user_id".to_string(),
- ColumnNote { note: "Owning customer".to_string(), source: NoteSource::Local, shadowed: None },
- );
-
- let mut warnings = Vec::new();
- let out = render_table(&table, false, &mut warnings);
-
- assert!(out.starts_with("Table orders {\n"), "got:\n{out}");
- assert!(out.contains("id integer [pk, increment]"), "got:\n{out}");
- assert!(out.contains("user_id integer [not null, note: '''Owning customer''']"), "got:\n{out}");
- assert!(out.contains("shipped_at timestamptz\n"), "got:\n{out}");
- assert!(out.contains("Note: '''Checkout rows.'''"), "got:\n{out}");
- assert!(out.ends_with("}\n"), "got:\n{out}");
- }
-
- #[test]
- fn qualifies_the_table_name_when_requested() {
- let table = doc_table("orders", vec![col("id", "integer")], vec![]);
- let mut warnings = Vec::new();
- assert!(render_table(&table, true, &mut warnings).starts_with("Table public.orders {"));
- }
-
- #[test]
- fn renders_an_indexes_block() {
- let index = IndexInfo {
- name: "idx_orders_user_placed".to_string(),
- columns: vec!["user_id".to_string(), "placed_at".to_string()],
- is_unique: false,
- is_primary: false,
- filter: None,
- index_type: None,
- included_columns: None,
- comment: None,
- };
- let table = doc_table("orders", vec![col("user_id", "integer")], vec![index]);
-
- let mut warnings = Vec::new();
- let out = render_table(&table, false, &mut warnings);
-
- assert!(out.contains("Indexes {"), "got:\n{out}");
- assert!(out.contains("(user_id, placed_at) [name: 'idx_orders_user_placed']"), "got:\n{out}");
- assert!(warnings.is_empty());
- }
-
- #[test]
- fn a_unique_index_carries_the_unique_setting() {
- let index = IndexInfo {
- name: "uq_orders_ref".to_string(),
- columns: vec!["reference".to_string()],
- is_unique: true,
- is_primary: false,
- filter: None,
- index_type: None,
- included_columns: None,
- comment: None,
- };
- let table = doc_table("orders", vec![col("reference", "text")], vec![index]);
- let mut warnings = Vec::new();
- let out = render_table(&table, false, &mut warnings);
- assert!(out.contains("(reference) [name: 'uq_orders_ref', unique]"), "got:\n{out}");
- }
-
- #[test]
- fn the_primary_key_index_is_skipped_because_columns_already_carry_pk() {
- let index = IndexInfo {
- name: "orders_pkey".to_string(),
- columns: vec!["id".to_string()],
- is_unique: true,
- is_primary: true,
- filter: None,
- index_type: None,
- included_columns: None,
- comment: None,
- };
- let mut id = col("id", "integer");
- id.is_primary_key = true;
- let table = doc_table("orders", vec![id], vec![index]);
-
- let mut warnings = Vec::new();
- let out = render_table(&table, false, &mut warnings);
- assert!(!out.contains("orders_pkey"), "got:\n{out}");
- }
-
- #[test]
- fn a_filtered_index_is_omitted_and_warned_about() {
- let index = IndexInfo {
- name: "idx_orders_open".to_string(),
- columns: vec!["status".to_string()],
- is_unique: false,
- is_primary: false,
- filter: Some("status <> 'cancelled'".to_string()),
- index_type: None,
- included_columns: None,
- comment: None,
- };
- let table = doc_table("orders", vec![col("status", "text")], vec![index]);
-
- let mut warnings = Vec::new();
- let out = render_table(&table, false, &mut warnings);
-
- assert!(!out.contains("idx_orders_open"), "filtered index must not be emitted, got:\n{out}");
- assert_eq!(warnings.len(), 1);
- match &warnings[0] {
- SnapshotWarning::DbmlOmitted { table, item, reason } => {
- assert_eq!(table, "public.orders");
- assert_eq!(item, "idx_orders_open");
- assert!(reason.contains("filter"), "got {reason}");
- }
- other => panic!("unexpected warning: {other:?}"),
- }
- }
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core docs::dbml`
-Expected: FAIL — `cannot find function render_table`.
-
-- [ ] **Step 3: Write the implementation**
-
-Add to `crates/dbx-core/src/docs/dbml.rs` (extend the existing `use` lines at the top):
-
-```rust
-use crate::docs::{DocTable, SnapshotWarning};
-use crate::types::IndexInfo;
-
-fn column_settings(column: &ColumnInfo, table: &DocTable) -> Vec<String> {
- let mut settings = Vec::new();
-
- if column.is_primary_key {
- settings.push("pk".to_string());
- }
-
- let extra = column.extra.as_deref().unwrap_or("").to_ascii_lowercase();
- if extra.contains("auto_increment") || extra.contains("identity") {
- settings.push("increment".to_string());
- }
-
- if !column.is_nullable && !column.is_primary_key {
- settings.push("not null".to_string());
- }
-
- if let Some(default) = render_default(column) {
- settings.push(default);
- }
-
- if let Some(note) = table.column_notes.get(&column.name) {
- settings.push(format!("note: {}", render_note(&note.note)));
- } else if let Some(comment) = column.comment.as_deref().filter(|value| !value.trim().is_empty()) {
- settings.push(format!("note: {}", render_note(comment)));
- }
-
- settings
-}
-
-fn render_index(index: &IndexInfo) -> String {
- let columns =
- index.columns.iter().map(|c| quote_identifier(c)).collect::<Vec<_>>().join(", ");
-
- let mut settings = vec![format!("name: '{}'", index.name.replace('\'', "\\'"))];
- if index.is_unique {
- settings.push("unique".to_string());
- }
-
- format!(" ({columns}) [{}]\n", settings.join(", "))
-}
-
-/// Render one `Table` block.
-///
-/// The primary-key index is skipped because columns already carry `pk`.
-/// Indexes DBML cannot express are skipped and recorded in `warnings`
-/// rather than dropped silently.
-pub(crate) fn render_table(table: &DocTable, qualify: bool, warnings: &mut Vec<SnapshotWarning>) -> String {
- let name = if qualify {
- match table.schema.as_deref().filter(|s| !s.is_empty()) {
- Some(schema) => format!("{}.{}", quote_identifier(schema), quote_identifier(&table.name)),
- None => quote_identifier(&table.name),
- }
- } else {
- quote_identifier(&table.name)
- };
-
- let mut out = format!("Table {name} {{\n");
-
- for column in &table.columns {
- let settings = column_settings(column, table);
- let rendered_settings =
- if settings.is_empty() { String::new() } else { format!(" [{}]", settings.join(", ")) };
- out.push_str(&format!(
- " {} {}{}\n",
- quote_identifier(&column.name),
- render_type(column),
- rendered_settings
- ));
- }
-
- let emittable: Vec<&IndexInfo> = table
- .indexes
- .iter()
- .filter(|index| {
- if index.is_primary {
- return false;
- }
- if index.filter.as_deref().is_some_and(|f| !f.trim().is_empty()) {
- warnings.push(SnapshotWarning::DbmlOmitted {
- table: table.qualified_name(),
- item: index.name.clone(),
- reason: "partial index filter has no DBML equivalent".to_string(),
- });
- return false;
- }
- if index.included_columns.as_ref().is_some_and(|columns| !columns.is_empty()) {
- warnings.push(SnapshotWarning::DbmlOmitted {
- table: table.qualified_name(),
- item: index.name.clone(),
- reason: "included columns have no DBML equivalent".to_string(),
- });
- return false;
- }
- !index.columns.is_empty()
- })
- .collect();
-
- if !emittable.is_empty() {
- out.push_str("\n Indexes {\n");
- for index in emittable {
- out.push_str(&render_index(index));
- }
- out.push_str(" }\n");
- }
-
- if let Some(note) = table.note.as_deref().filter(|value| !value.trim().is_empty()) {
- out.push_str(&format!("\n Note: {}\n", render_note(note)));
- }
-
- out.push_str("}\n");
- out
-}
-```
-
-- [ ] **Step 4: Run the tests to verify they pass**
-
-Run: `cargo test -p dbx-core docs::dbml`
-Expected: PASS, 15 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/
-git commit -m "feat(docs): render DBML table blocks"
-```
-
----
-
-## Task 6: DBML refs, enums and table groups
-
-**Files:**
-- Modify: `crates/dbx-core/src/docs/dbml.rs`
-
-**Interfaces:**
-- Produces (crate-internal): `fn render_ref(&Relationship, bool) -> String`, `fn render_enum(&DocEnum, bool) -> String`, `fn render_group(&TableGroup, &[&DocTable], bool) -> String`
-
-- [ ] **Step 1: Write the failing test**
-
-Append to the `tests` module in `crates/dbx-core/src/docs/dbml.rs`:
-
-```rust
- use crate::docs::{Cardinality, DocEnum, FieldRef, Relationship, TableGroup};
-
- fn relationship(cardinality: Cardinality) -> Relationship {
- Relationship {
- id: "r1".to_string(),
- name: Some("fk_orders_user".to_string()),
- from: FieldRef {
- schema: Some("public".to_string()),
- table: "orders".to_string(),
- column: "user_id".to_string(),
- },
- to: FieldRef {
- schema: Some("public".to_string()),
- table: "users".to_string(),
- column: "id".to_string(),
- },
- cardinality,
- on_update: None,
- on_delete: Some("CASCADE".to_string()),
- }
- }
-
- #[test]
- fn many_to_one_uses_the_gt_operator() {
- let out = render_ref(&relationship(Cardinality::ManyToOne), false);
- assert_eq!(out, "Ref fk_orders_user: orders.user_id > users.id [delete: cascade]\n");
- }
-
- #[test]
- fn one_to_one_uses_the_dash_operator() {
- let out = render_ref(&relationship(Cardinality::OneToOne), false);
- assert!(out.contains("orders.user_id - users.id"), "got {out}");
- }
-
- #[test]
- fn refs_qualify_both_sides_together() {
- let out = render_ref(&relationship(Cardinality::ManyToOne), true);
- assert!(out.contains("public.orders.user_id > public.users.id"), "got {out}");
- }
-
- #[test]
- fn referential_actions_are_lowercased_and_both_emitted() {
- let mut rel = relationship(Cardinality::ManyToOne);
- rel.on_update = Some("NO ACTION".to_string());
- rel.on_delete = Some("RESTRICT".to_string());
- let out = render_ref(&rel, false);
- assert!(out.contains("[update: no action, delete: restrict]"), "got {out}");
- }
-
- #[test]
- fn an_unnamed_ref_omits_the_name() {
- let mut rel = relationship(Cardinality::ManyToOne);
- rel.name = None;
- assert!(render_ref(&rel, false).starts_with("Ref: orders.user_id"), "got {}", render_ref(&rel, false));
- }
-
- #[test]
- fn renders_an_enum_block() {
- let value = DocEnum {
- schema: Some("public".to_string()),
- name: "order_status".to_string(),
- values: vec!["pending".to_string(), "shipped".to_string()],
- note: None,
- synthesized: false,
- };
- let out = render_enum(&value, false);
- assert_eq!(out, "Enum order_status {\n pending\n shipped\n}\n");
- }
-
- #[test]
- fn renders_a_table_group_with_colour_and_note() {
- let group = TableGroup {
- id: "order-management".to_string(),
- name: "Order Management".to_string(),
- hue: 28,
- note: Some("Checkout to carrier handoff.".to_string()),
- };
- let orders = doc_table("orders", vec![], vec![]);
- let items = doc_table("order_items", vec![], vec![]);
-
- let out = render_group(&group, &[&orders, &items], false);
-
- assert!(out.starts_with("TableGroup \"Order Management\" [color: #"), "got:\n{out}");
- assert!(out.contains("\n orders\n"), "got:\n{out}");
- assert!(out.contains("\n order_items\n"), "got:\n{out}");
- assert!(out.contains("Note: '''Checkout to carrier handoff.'''"), "got:\n{out}");
- }
-
- #[test]
- fn an_empty_group_renders_nothing() {
- let group = TableGroup {
- id: "empty".to_string(),
- name: "Empty".to_string(),
- hue: 0,
- note: None,
- };
- assert_eq!(render_group(&group, &[], false), "");
- }
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core docs::dbml`
-Expected: FAIL — `cannot find function render_ref`.
-
-- [ ] **Step 3: Write the implementation**
-
-Add to `crates/dbx-core/src/docs/dbml.rs`. Extend the top `use crate::docs::{…}` line so it reads:
-
-```rust
-use crate::docs::{Cardinality, DocEnum, DocTable, FieldRef, Relationship, SnapshotWarning, TableGroup};
-use crate::docs::color::hue_to_hex;
-```
-
-```rust
-fn qualified_field(field: &FieldRef, qualify: bool) -> String {
- let table = if qualify {
- match field.schema.as_deref().filter(|s| !s.is_empty()) {
- Some(schema) => format!("{}.{}", quote_identifier(schema), quote_identifier(&field.table)),
- None => quote_identifier(&field.table),
- }
- } else {
- quote_identifier(&field.table)
- };
- format!("{table}.{}", quote_identifier(&field.column))
-}
-
-/// One `Ref` line. `>` is many-to-one, `-` is one-to-one.
-pub(crate) fn render_ref(relationship: &Relationship, qualify: bool) -> String {
- let operator = match relationship.cardinality {
- Cardinality::ManyToOne => ">",
- Cardinality::OneToOne => "-",
- };
-
- let mut actions = Vec::new();
- if let Some(update) = relationship.on_update.as_deref().filter(|v| !v.trim().is_empty()) {
- actions.push(format!("update: {}", update.to_lowercase()));
- }
- if let Some(delete) = relationship.on_delete.as_deref().filter(|v| !v.trim().is_empty()) {
- actions.push(format!("delete: {}", delete.to_lowercase()));
- }
- let settings = if actions.is_empty() { String::new() } else { format!(" [{}]", actions.join(", ")) };
-
- let label = match relationship.name.as_deref().filter(|v| !v.trim().is_empty()) {
- Some(name) => format!("Ref {}", quote_identifier(name)),
- None => "Ref".to_string(),
- };
-
- format!(
- "{label}: {} {operator} {}{settings}\n",
- qualified_field(&relationship.from, qualify),
- qualified_field(&relationship.to, qualify)
- )
-}
-
-pub(crate) fn render_enum(value: &DocEnum, qualify: bool) -> String {
- let name = if qualify {
- match value.schema.as_deref().filter(|s| !s.is_empty()) {
- Some(schema) => format!("{}.{}", quote_identifier(schema), quote_identifier(&value.name)),
- None => quote_identifier(&value.name),
- }
- } else {
- quote_identifier(&value.name)
- };
-
- let mut out = format!("Enum {name} {{\n");
- for variant in &value.values {
- out.push_str(&format!(" {}\n", quote_identifier(variant)));
- }
- if let Some(note) = value.note.as_deref().filter(|v| !v.trim().is_empty()) {
- out.push_str(&format!("\n Note: {}\n", render_note(note)));
- }
- out.push_str("}\n");
- out
-}
-
-/// A `TableGroup` block. Returns an empty string when the group has no
-/// members, since DBML rejects an empty group body.
-pub(crate) fn render_group(group: &TableGroup, members: &[&DocTable], qualify: bool) -> String {
- if members.is_empty() {
- return String::new();
- }
-
- let mut out =
- format!("TableGroup {} [color: {}] {{\n", quote_identifier(&group.name), hue_to_hex(group.hue));
-
- for member in members {
- let name = if qualify {
- match member.schema.as_deref().filter(|s| !s.is_empty()) {
- Some(schema) => format!("{}.{}", quote_identifier(schema), quote_identifier(&member.name)),
- None => quote_identifier(&member.name),
- }
- } else {
- quote_identifier(&member.name)
- };
- out.push_str(&format!(" {name}\n"));
- }
-
- if let Some(note) = group.note.as_deref().filter(|v| !v.trim().is_empty()) {
- out.push_str(&format!("\n Note: {}\n", render_note(note)));
- }
-
- out.push_str("}\n");
- out
-}
-```
-
-Note: `quote_identifier("Order Management")` yields `"Order Management"` with quotes, which is what the test asserts.
-
-- [ ] **Step 4: Run the tests to verify they pass**
-
-Run: `cargo test -p dbx-core docs::dbml`
-Expected: PASS, 23 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/
-git commit -m "feat(docs): render DBML refs, enums and table groups"
-```
-
----
-
-## Task 7: Full DBML document assembly
-
-**Files:**
-- Modify: `crates/dbx-core/src/docs/dbml.rs`
-- Modify: `crates/dbx-core/src/docs/mod.rs`
-
-**Interfaces:**
-- Produces: `pub fn to_dbml(snapshot: &SchemaSnapshot) -> DbmlOutput` where `pub struct DbmlOutput { pub text: String, pub warnings: Vec<SnapshotWarning> }`
-
-Schema qualification is decided here: bare names for a single-schema snapshot (it reads better), fully qualified when more than one schema is present.
-
-- [ ] **Step 1: Write the failing test**
-
-Append to the `tests` module in `crates/dbx-core/src/docs/dbml.rs`:
-
-```rust
- use crate::docs::{ProjectMeta, SchemaSnapshot};
-
- fn snapshot(tables: Vec<DocTable>, schemas: Vec<&str>) -> SchemaSnapshot {
- SchemaSnapshot {
- format_version: 1,
- project: ProjectMeta {
- name: "Ecommerce".to_string(),
- database_type: "PostgreSQL".to_string(),
- database: Some("shop".to_string()),
- schemas: schemas.into_iter().map(str::to_string).collect(),
- generated_at: "2026-08-02T12:00:00Z".to_string(),
- note: Some("Storefront database.".to_string()),
- },
- tables,
- relationships: vec![],
- groups: vec![],
- enums: vec![],
- warnings: vec![],
- }
- }
-
- #[test]
- fn emits_a_project_block_first() {
- let out = to_dbml(&snapshot(vec![], vec!["public"]));
- assert!(out.text.starts_with("Project Ecommerce {\n"), "got:\n{}", out.text);
- assert!(out.text.contains("database_type: 'PostgreSQL'"), "got:\n{}", out.text);
- assert!(out.text.contains("Note: '''Storefront database.'''"), "got:\n{}", out.text);
- }
-
- #[test]
- fn a_single_schema_snapshot_uses_bare_table_names() {
- let out = to_dbml(&snapshot(vec![doc_table("orders", vec![col("id", "integer")], vec![])], vec!["public"]));
- assert!(out.text.contains("Table orders {"), "got:\n{}", out.text);
- assert!(!out.text.contains("Table public.orders"), "got:\n{}", out.text);
- }
-
- #[test]
- fn a_multi_schema_snapshot_qualifies_every_table() {
- let mut analytics = doc_table("daily_sales", vec![col("id", "integer")], vec![]);
- analytics.schema = Some("analytics".to_string());
-
- let out = to_dbml(&snapshot(
- vec![doc_table("orders", vec![col("id", "integer")], vec![]), analytics],
- vec!["public", "analytics"],
- ));
-
- assert!(out.text.contains("Table public.orders {"), "got:\n{}", out.text);
- assert!(out.text.contains("Table analytics.daily_sales {"), "got:\n{}", out.text);
- }
-
- #[test]
- fn sections_appear_in_order_project_enums_groups_tables_refs() {
- let mut snap = snapshot(vec![doc_table("orders", vec![col("id", "integer")], vec![])], vec!["public"]);
- snap.enums.push(DocEnum {
- schema: Some("public".to_string()),
- name: "order_status".to_string(),
- values: vec!["pending".to_string()],
- note: None,
- synthesized: false,
- });
- snap.groups.push(TableGroup {
- id: "order-management".to_string(),
- name: "Order Management".to_string(),
- hue: 28,
- note: None,
- });
- snap.tables[0].group_id = Some("order-management".to_string());
- snap.relationships.push(relationship(Cardinality::ManyToOne));
-
- let text = to_dbml(&snap).text;
- let project = text.find("Project ").expect("project");
- let enum_at = text.find("Enum ").expect("enum");
- let group = text.find("TableGroup ").expect("group");
- let table = text.find("Table orders").expect("table");
- let reference = text.find("Ref ").expect("ref");
-
- assert!(project < enum_at, "project before enums:\n{text}");
- assert!(enum_at < group, "enums before groups:\n{text}");
- assert!(group < table, "groups before tables:\n{text}");
- assert!(table < reference, "tables before refs:\n{text}");
- }
-
- #[test]
- fn warnings_from_table_rendering_reach_the_output() {
- let index = IndexInfo {
- name: "idx_partial".to_string(),
- columns: vec!["status".to_string()],
- is_unique: false,
- is_primary: false,
- filter: Some("status <> 'x'".to_string()),
- index_type: None,
- included_columns: None,
- comment: None,
- };
- let out = to_dbml(&snapshot(vec![doc_table("orders", vec![col("status", "text")], vec![index])], vec!["public"]));
- assert_eq!(out.warnings.len(), 1);
- }
-
- #[test]
- fn a_group_referencing_a_missing_table_is_skipped() {
- let mut snap = snapshot(vec![doc_table("orders", vec![col("id", "integer")], vec![])], vec!["public"]);
- snap.groups.push(TableGroup {
- id: "ghost".to_string(),
- name: "Ghost".to_string(),
- hue: 200,
- note: None,
- });
- assert!(!to_dbml(&snap).text.contains("Ghost"), "got:\n{}", to_dbml(&snap).text);
- }
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-core docs::dbml`
-Expected: FAIL — `cannot find function to_dbml`.
-
-- [ ] **Step 3: Write the implementation**
-
-Add to `crates/dbx-core/src/docs/dbml.rs` (extend the `use crate::docs::{…}` line with `SchemaSnapshot`):
-
-```rust
-/// DBML text plus every construct that could not be represented in it.
-#[derive(Debug, Clone)]
-pub struct DbmlOutput {
- pub text: String,
- pub warnings: Vec<SnapshotWarning>,
-}
-
-fn render_project(snapshot: &SchemaSnapshot) -> String {
- let mut out = format!("Project {} {{\n", quote_identifier(&snapshot.project.name));
- out.push_str(&format!(
- " database_type: '{}'\n",
- snapshot.project.database_type.replace('\'', "\\'")
- ));
- if let Some(note) = snapshot.project.note.as_deref().filter(|v| !v.trim().is_empty()) {
- out.push_str(&format!(" Note: {}\n", render_note(note)));
- }
- out.push_str("}\n");
- out
-}
-
-/// Serialize a snapshot to DBML.
-///
-/// DBML is an interchange format, not a backup: check constraints, partial
-/// indexes, included columns, collations and generated columns have no
-/// representation. Each omission is reported in `warnings` so the HTML
-/// documentation — which *is* the complete record — can mark it.
-pub fn to_dbml(snapshot: &SchemaSnapshot) -> DbmlOutput {
- let qualify = snapshot.project.schemas.len() > 1;
- let mut warnings = Vec::new();
- let mut sections: Vec<String> = vec![render_project(snapshot)];
-
- for value in &snapshot.enums {
- sections.push(render_enum(value, qualify));
- }
-
- for group in &snapshot.groups {
- let members: Vec<&DocTable> = snapshot
- .tables
- .iter()
- .filter(|table| table.group_id.as_deref() == Some(group.id.as_str()))
- .collect();
- let rendered = render_group(group, &members, qualify);
- if !rendered.is_empty() {
- sections.push(rendered);
- }
- }
-
- for table in &snapshot.tables {
- sections.push(render_table(table, qualify, &mut warnings));
- }
-
- if !snapshot.relationships.is_empty() {
- let refs: String =
- snapshot.relationships.iter().map(|rel| render_ref(rel, qualify)).collect();
- sections.push(refs);
- }
-
- DbmlOutput { text: sections.join("\n"), warnings }
-}
-```
-
-Add to `crates/dbx-core/src/docs/mod.rs`:
-
-```rust
-pub use dbml::{to_dbml, DbmlOutput};
-```
-
-- [ ] **Step 4: Run the tests to verify they pass**
-
-Run: `cargo test -p dbx-core docs::dbml`
-Expected: PASS, 29 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/
-git commit -m "feat(docs): assemble complete DBML documents"
-```
-
----
-
-## Task 8: Snapshot collector
-
-**Files:**
-- Create: `crates/dbx-core/src/docs/collector.rs`
-- Modify: `crates/dbx-core/src/docs/mod.rs`
-
-**Interfaces:**
-- Produces:
- - `pub struct CollectOptions { pub database: String, pub schemas: Vec<String>, pub tables: Vec<String>, pub project_name: String }`
- - `pub struct CollectProgress { pub completed: usize, pub total: usize, pub current: String }`
- - `pub async fn collect_snapshot(state: &AppState, connection: &ConnectionConfig, options: &CollectOptions, progress: &(dyn Fn(CollectProgress) + Send + Sync), cancel: &AtomicBool) -> Result<SchemaSnapshot, String>`
-
-**Verified metadata API** (`crates/dbx-core/src/schema.rs` — note this is a 357 KB module file paired with the `schema/` directory, and `db::*` re-exports `crate::types::*`, so `db::ColumnInfo` and `crate::types::ColumnInfo` are the same type):
-
-```rust
-schema::list_schemas_core(state, connection_id, database) -> Vec<String>
-schema::list_tables_core(state, connection_id, database, schema,
- filter, limit, offset, object_types, table_name_filter) -> Vec<db::TableInfo>
-schema::get_columns_core(state, connection_id, database, schema, table) -> Vec<db::ColumnInfo>
-schema::list_indexes_core(state, connection_id, database, schema, table) -> Vec<db::IndexInfo>
-schema::list_foreign_keys_core(state, connection_id, database, schema, table) -> Vec<db::ForeignKeyInfo>
-```
-
-These take `&AppState` and a connection id — **not** a pool. They also wrap `retry_metadata_connection` internally, so the collector inherits reconnect-on-drop for free and must not add its own retry layer.
-
-Fan-out is bounded at 8 concurrent table fetches. This is the naive-but-correct version by design: it works for every relational engine on day one because it reuses providers already proven against all of them. Per-engine bulk `information_schema` sweeps come later, only where a benchmark justifies them.
-
-- [ ] **Step 1: Write the failing test**
-
-Create `crates/dbx-core/src/docs/collector.rs` with only this test module. These tests cover the pure helpers; end-to-end collection is covered by the live test in Task 12.
-
-```rust
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn table_kind_maps_from_the_engine_reported_type() {
- assert_eq!(table_kind_from("TABLE"), TableKind::Table);
- assert_eq!(table_kind_from("BASE TABLE"), TableKind::Table);
- assert_eq!(table_kind_from("VIEW"), TableKind::View);
- assert_eq!(table_kind_from("MATERIALIZED VIEW"), TableKind::MaterializedView);
- assert_eq!(table_kind_from("materialized_view"), TableKind::MaterializedView);
- assert_eq!(table_kind_from("something else"), TableKind::Table);
- }
-
- #[test]
- fn table_filter_is_empty_means_include_everything() {
- let options = CollectOptions {
- database: "shop".to_string(),
- schemas: vec!["public".to_string()],
- tables: vec![],
- project_name: "Ecommerce".to_string(),
- };
- assert!(options.includes_table("public", "orders"));
- assert!(options.includes_table("public", "anything"));
- }
-
- #[test]
- fn table_filter_matches_bare_and_qualified_names() {
- let options = CollectOptions {
- database: "shop".to_string(),
- schemas: vec!["public".to_string()],
- tables: vec!["orders".to_string(), "analytics.daily_sales".to_string()],
- project_name: "Ecommerce".to_string(),
- };
- assert!(options.includes_table("public", "orders"));
- assert!(options.includes_table("analytics", "daily_sales"));
- assert!(!options.includes_table("public", "users"));
- assert!(!options.includes_table("public", "daily_sales"));
- }
-
- #[test]
- fn synthesises_a_named_enum_from_an_inline_enum_column() {
- let mut column = crate::types::ColumnInfo {
- name: "status".to_string(),
- data_type: "enum".to_string(),
- ..Default::default()
- };
- column.enum_values = Some(vec!["pending".to_string(), "shipped".to_string()]);
-
- let synthesized = synthesize_enum(Some("public"), "orders", &column).expect("enum");
-
- assert_eq!(synthesized.name, "orders_status");
- assert_eq!(synthesized.values, vec!["pending", "shipped"]);
- assert!(synthesized.synthesized);
- }
-
- #[test]
- fn a_column_without_enum_values_synthesises_nothing() {
- let column = crate::types::ColumnInfo {
- name: "status".to_string(),
- data_type: "text".to_string(),
- ..Default::default()
- };
- assert!(synthesize_enum(Some("public"), "orders", &column).is_none());
- }
-}
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Add `pub mod collector;` and `pub use collector::{collect_snapshot, CollectOptions, CollectProgress};` to `crates/dbx-core/src/docs/mod.rs`.
-
-Run: `cargo test -p dbx-core docs::collector`
-Expected: FAIL — `cannot find function table_kind_from`.
-
-- [ ] **Step 3: Write the implementation**
-
-At the top of `crates/dbx-core/src/docs/collector.rs`:
-
-```rust
-use std::collections::BTreeMap;
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::Arc;
-
-use futures::stream::{self, StreamExt};
-use tokio::sync::Semaphore;
-
-use crate::docs::{
- build_relationships, DocEnum, DocTable, NoteSource, ProjectMeta, SchemaSnapshot, SnapshotWarning, TableKind,
-};
-use crate::models::connection::ConnectionConfig;
-use crate::schema;
-use crate::state::AppState; // confirm the real path with: grep -rn "pub struct AppState" crates/dbx-core/src
-use crate::table_structure_sql::dialect::capabilities_for;
-use crate::types::ColumnInfo;
-
-/// Concurrent per-table metadata fetches. Bounded so documenting a large
-/// schema cannot starve the connection pool the UI is also using.
-const MAX_CONCURRENT_TABLES: usize = 8;
-
-#[derive(Debug, Clone)]
-pub struct CollectOptions {
- pub database: String,
- pub schemas: Vec<String>,
- /// Empty means every table. Entries may be bare (`orders`) or
- /// qualified (`analytics.daily_sales`).
- pub tables: Vec<String>,
- pub project_name: String,
-}
-
-impl CollectOptions {
- pub fn includes_table(&self, schema: &str, table: &str) -> bool {
- if self.tables.is_empty() {
- return true;
- }
- let qualified = format!("{schema}.{table}");
- self.tables.iter().any(|wanted| wanted == table || wanted == &qualified)
- }
-}
-
-#[derive(Debug, Clone)]
-pub struct CollectProgress {
- pub completed: usize,
- pub total: usize,
- pub current: String,
-}
-
-fn table_kind_from(table_type: &str) -> TableKind {
- let normalized = table_type.trim().to_ascii_uppercase().replace('_', " ");
- match normalized.as_str() {
- "VIEW" => TableKind::View,
- "MATERIALIZED VIEW" => TableKind::MaterializedView,
- _ => TableKind::Table,
- }
-}
-
-/// MySQL reports `ENUM('a','b')` inline rather than as a named type.
-/// DBML needs a named enum, so synthesize one per table+column.
-fn synthesize_enum(schema: Option<&str>, table: &str, column: &ColumnInfo) -> Option<DocEnum> {
- let values = column.enum_values.as_ref().filter(|values| !values.is_empty())?;
- Some(DocEnum {
- schema: schema.map(ToOwned::to_owned),
- name: format!("{table}_{}", column.name),
- values: values.clone(),
- note: None,
- synthesized: true,
- })
-}
-
-fn cancelled(cancel: &AtomicBool) -> bool {
- cancel.load(Ordering::Relaxed)
-}
-
-/// Collect a documentation snapshot.
-///
-/// A per-table failure is recorded as a `TableSkipped` warning and does not
-/// abort the run — a permissions gap on one table must not kill a
-/// 400-table documentation build.
-pub async fn collect_snapshot(
- state: &AppState,
- connection: &ConnectionConfig,
- options: &CollectOptions,
- progress: &(dyn Fn(CollectProgress) + Send + Sync),
- cancel: &AtomicBool,
-) -> Result<SchemaSnapshot, String> {
- let mut warnings: Vec<SnapshotWarning> = Vec::new();
- let engine = format!("{:?}", connection.db_type);
- let connection_id = connection.id.as_str();
-
- if !capabilities_for(connection.db_type).comment {
- warnings.push(SnapshotWarning::CommentsUnsupported { engine: engine.clone() });
- }
-
- let schemas = if options.schemas.is_empty() {
- schema::list_schemas_core(state, connection_id, &options.database).await.unwrap_or_default()
- } else {
- options.schemas.clone()
- };
- let effective_schemas = if schemas.is_empty() { vec![String::new()] } else { schemas };
-
- // Enumerate every table first so progress has a real total.
- let mut targets: Vec<(String, crate::types::TableInfo)> = Vec::new();
- for schema_name in &effective_schemas {
- match schema::list_tables_core(state, connection_id, &options.database, schema_name, None, None, None, None, None)
- .await
- {
- Ok(tables) => {
- for info in tables {
- if options.includes_table(schema_name, &info.name) {
- targets.push((schema_name.clone(), info));
- }
- }
- }
- Err(error) => warnings.push(SnapshotWarning::TableSkipped {
- table: format!("{schema_name}.*"),
- reason: error,
- }),
- }
- }
-
- let total = targets.len();
- let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_TABLES));
-
- let collected: Vec<Result<DocTable, SnapshotWarning>> = stream::iter(targets.into_iter().enumerate())
- .map(|(index, (schema_name, info))| {
- let semaphore = Arc::clone(&semaphore);
- let database = options.database.clone();
- async move {
- let _permit = semaphore.acquire().await.map_err(|_| SnapshotWarning::TableSkipped {
- table: info.name.clone(),
- reason: "collection cancelled".to_string(),
- })?;
-
- if cancelled(cancel) {
- return Err(SnapshotWarning::TableSkipped {
- table: info.name.clone(),
- reason: "cancelled".to_string(),
- });
- }
-
- progress(CollectProgress {
- completed: index,
- total,
- current: format!("{schema_name}.{}", info.name),
- });
-
- let columns = schema::get_columns_core(state, connection_id, &database, &schema_name, &info.name)
- .await
- .map_err(|error| SnapshotWarning::TableSkipped {
- table: format!("{schema_name}.{}", info.name),
- reason: error,
- })?;
-
- // Indexes and foreign keys degrade to empty rather than failing
- // the table: ClickHouse and friends have no FK metadata at all.
- let indexes = schema::list_indexes_core(state, connection_id, &database, &schema_name, &info.name)
- .await
- .unwrap_or_default();
- let foreign_keys =
- schema::list_foreign_keys_core(state, connection_id, &database, &schema_name, &info.name)
- .await
- .unwrap_or_default();
-
- Ok(DocTable {
- schema: (!schema_name.is_empty()).then(|| schema_name.clone()),
- name: info.name.clone(),
- kind: table_kind_from(&info.table_type),
- columns,
- indexes,
- foreign_keys,
- group_id: None,
- note: info.comment.clone().filter(|value| !value.trim().is_empty()),
- note_source: if info.comment.as_deref().is_some_and(|v| !v.trim().is_empty()) {
- NoteSource::Database
- } else {
- NoteSource::None
- },
- shadowed_note: None,
- column_notes: BTreeMap::new(),
- estimated_rows: None,
- view_definition: None,
- })
- }
- })
- .buffer_unordered(MAX_CONCURRENT_TABLES)
- .collect()
- .await;
-
- let mut tables = Vec::new();
- for outcome in collected {
- match outcome {
- Ok(table) => tables.push(table),
- Err(warning) => warnings.push(warning),
- }
- }
-
- tables.sort_by(|a, b| a.qualified_name().cmp(&b.qualified_name()));
-
- let mut enums: Vec<DocEnum> = Vec::new();
- for table in &tables {
- for column in &table.columns {
- if let Some(value) = synthesize_enum(table.schema.as_deref(), &table.name, column) {
- enums.push(value);
- }
- }
- }
-
- let relationships = build_relationships(&tables);
- if relationships.is_empty() && tables.iter().any(|t| !t.columns.is_empty()) {
- warnings.push(SnapshotWarning::NoForeignKeyMetadata { engine: engine.clone() });
- }
-
- progress(CollectProgress { completed: total, total, current: String::new() });
-
- Ok(SchemaSnapshot {
- format_version: 1,
- project: ProjectMeta {
- name: options.project_name.clone(),
- database_type: engine,
- database: (!options.database.is_empty()).then(|| options.database.clone()),
- schemas: effective_schemas.into_iter().filter(|s| !s.is_empty()).collect(),
- generated_at: chrono::Utc::now().to_rfc3339(),
- note: None,
- },
- tables,
- relationships,
- groups: Vec::new(),
- enums,
- warnings,
- })
-}
-```
-
-**Two things to verify before writing this file** (both are one command each, and both change the code above if they come back differently):
-
-1. `grep -rn "pub struct AppState" crates/dbx-core/src` — use the real module path in the `use` line.
-2. `grep -nE "^futures|^chrono|futures =|chrono =" crates/dbx-core/Cargo.toml` — the code above uses `futures::stream::buffer_unordered` and `chrono::Utc`. **If either is absent, do not add it** (Global Constraints forbid new dependencies). Substitute:
- - no `futures` → drive the fan-out with `tokio::task::JoinSet`, capping in-flight tasks at `MAX_CONCURRENT_TABLES` by draining with `join_next()` before spawning past the cap;
- - no `chrono` → build the RFC3339 timestamp from `std::time::SystemTime::now().duration_since(UNIX_EPOCH)`.
-
-- [ ] **Step 4: Run the tests to verify they pass**
-
-Run: `cargo test -p dbx-core docs::collector`
-Expected: PASS, 5 tests.
-
-- [ ] **Step 5: Verify the whole crate still builds**
-
-Run: `cargo check -p dbx-core`
-Expected: no errors.
-
-- [ ] **Step 6: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/src/docs/ crates/dbx-core/src/schema/
-git commit -m "feat(docs): collect schema snapshots with bounded fan-out"
-```
-
----
-
-## Task 9: Web route for snapshot collection
-
-**Files:**
-- Create: `crates/dbx-web/src/routes/docs.rs`
-- Modify: `crates/dbx-web/src/routes/mod.rs` (register the module and route)
-
-**Interfaces:**
-- Consumes: `collect_snapshot`, `CollectOptions` from Task 8
-- Produces: `POST /api/docs/snapshot` accepting `{ connectionId, database, schemas, tables, projectName }` and returning a `SchemaSnapshot` as JSON
-
-This exists so `WebBackend` (Task 10) makes **one** HTTP call instead of 3×N.
-
-- [ ] **Step 1: Read the neighbouring route to match its shape**
-
-Run: `sed -n '1,60p' crates/dbx-web/src/routes/database_export.rs`
-
-Copy its handler signature, state extractor, error mapping and JSON response conventions exactly. Do not invent a different shape.
-
-- [ ] **Step 2: Write the route**
-
-Create `crates/dbx-web/src/routes/docs.rs` following that shape. The handler must:
-
-1. Deserialize a `DocsSnapshotRequest { connection_id, database, schemas, tables, project_name }` with `#[serde(rename_all = "camelCase")]`.
-2. Resolve the `ConnectionConfig` for `connection_id` the same way the neighbouring routes do. The collector takes `&AppState` directly — `state.app`, exactly as `crates/dbx-web/src/routes/schema.rs:41` passes it to `dbx_core::schema::list_databases_core`. **No pool resolution is needed**; the `*_core` functions handle pooling and retry internally.
-3. Call:
-
-```rust
-let options = dbx_core::docs::CollectOptions {
- database: request.database.clone(),
- schemas: request.schemas.clone(),
- tables: request.tables.clone(),
- project_name: request.project_name.clone().unwrap_or_else(|| connection.name.clone()),
-};
-
-let snapshot = dbx_core::docs::collect_snapshot(
- &state.app,
- &connection,
- &options,
- &|_progress| {},
- &std::sync::atomic::AtomicBool::new(false),
-)
-.await
-.map_err(AppError::from)?;
-```
-
-4. Return `Json(snapshot)`, matching how `routes/schema.rs` returns its results.
-
-- [ ] **Step 3: Register the route**
-
-Add `pub mod docs;` to `crates/dbx-web/src/routes/mod.rs` and wire `POST /api/docs/snapshot` into the router beside the other `/api/...` routes, matching how `database_export` is registered.
-
-- [ ] **Step 4: Verify it compiles**
-
-Run: `cargo check -p dbx-web`
-Expected: no errors.
-
-- [ ] **Step 5: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-web/src/routes/
-git commit -m "feat(docs): add snapshot collection route"
-```
-
----
-
-## Task 10: Backend trait method
-
-**Files:**
-- Modify: `crates/dbx-mcp/src/backend.rs`
-
-**Interfaces:**
-- Produces: `async fn collect_docs_snapshot(&self, connection: &ConnectionConfig, database: &str, options: DocsSnapshotOptions) -> Result<SchemaSnapshot, String>` on `DbxBackend`, with implementations for `LocalBackend` and `WebBackend`
-
-`DbxBackend` currently exposes `list_tables` and `get_columns` but no schemas, indexes or foreign keys. Adding those three separately would make `WebBackend` issue 3×N HTTP requests. One snapshot method keeps it to a single round-trip.
-
-- [ ] **Step 1: Write the failing test**
-
-Append to the existing `#[cfg(test)] mod tests` in `crates/dbx-mcp/src/backend.rs` (or create one following the file's existing conventions):
-
-```rust
- struct StubBackend;
-
- #[async_trait]
- impl DbxBackend for StubBackend {
- async fn load_mcp_global_policy(&self) -> Result<McpGlobalPolicy, String> {
- Err("unused".to_string())
- }
- async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> {
- Ok(vec![])
- }
- async fn execute_agent_tool(
- &self,
- _connection: &ConnectionConfig,
- _database: &str,
- _tool_name: &str,
- _arguments: Value,
- _permissions: AgentSqlPermissions,
- ) -> ToolResult {
- unimplemented!("not exercised by this test")
- }
- async fn add_connection_for_mcp(&self, config: ConnectionConfig) -> Result<ConnectionConfig, String> {
- Ok(config)
- }
- async fn remove_connection_for_mcp(&self, _connection_id: &str) -> Result<bool, String> {
- Ok(false)
- }
- }
-
- #[tokio::test]
- async fn collect_docs_snapshot_defaults_to_unsupported() {
- let backend = StubBackend;
- let connection = new_connection_config(
- "c1".to_string(),
- "local".to_string(),
- DatabaseType::Postgres,
- "127.0.0.1".to_string(),
- );
-
- let result = backend
- .collect_docs_snapshot(&connection, "shop", DocsSnapshotOptions::default())
- .await;
-
- assert!(result.is_err());
- assert!(result.unwrap_err().contains("not supported"));
- }
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-mcp collect_docs_snapshot`
-Expected: FAIL — `no method named collect_docs_snapshot`.
-
-- [ ] **Step 3: Add the trait method with a default**
-
-Inside `pub trait DbxBackend`, following the pattern of the other optional methods:
-
-```rust
- async fn collect_docs_snapshot(
- &self,
- connection: &ConnectionConfig,
- database: &str,
- options: DocsSnapshotOptions,
- ) -> Result<dbx_core::docs::SchemaSnapshot, String> {
- let _ = (connection, database, options);
- Err("Documentation snapshots are not supported by this backend.".to_string())
- }
-```
-
-Above the trait, add the options type:
-
-```rust
-/// Wire-level options for a documentation snapshot. Mirrors
-/// `dbx_core::docs::CollectOptions` minus the fields the backend fills in.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DocsSnapshotOptions {
- #[serde(default)]
- pub schemas: Vec<String>,
- #[serde(default)]
- pub tables: Vec<String>,
- #[serde(default)]
- pub project_name: Option<String>,
-}
-```
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `cargo test -p dbx-mcp collect_docs_snapshot`
-Expected: PASS.
-
-- [ ] **Step 5: Implement for LocalBackend**
-
-In `impl DbxBackend for LocalBackend`, resolve the pool the same way its `get_columns` does, then:
-
-```rust
- async fn collect_docs_snapshot(
- &self,
- connection: &ConnectionConfig,
- database: &str,
- options: DocsSnapshotOptions,
- ) -> Result<dbx_core::docs::SchemaSnapshot, String> {
- let collect_options = dbx_core::docs::CollectOptions {
- database: database.to_string(),
- schemas: options.schemas,
- tables: options.tables,
- project_name: options.project_name.unwrap_or_else(|| connection.name.clone()),
- };
- dbx_core::docs::collect_snapshot(
- &self.state,
- connection,
- &collect_options,
- &|_progress| {},
- &std::sync::atomic::AtomicBool::new(false),
- )
- .await
- }
-```
-
-- [ ] **Step 6: Implement for WebBackend**
-
-In `impl DbxBackend for WebBackend`, POST once to the Task 9 route, following how its other methods build authenticated requests:
-
-```rust
- async fn collect_docs_snapshot(
- &self,
- connection: &ConnectionConfig,
- database: &str,
- options: DocsSnapshotOptions,
- ) -> Result<dbx_core::docs::SchemaSnapshot, String> {
- let body = serde_json::json!({
- "connectionId": connection.id,
- "database": database,
- "schemas": options.schemas,
- "tables": options.tables,
- "projectName": options.project_name.clone().unwrap_or_else(|| connection.name.clone()),
- });
- // Use this impl's existing authenticated-POST helper against
- // "/api/docs/snapshot" and deserialize the response into SchemaSnapshot.
- self.post_json("/api/docs/snapshot", body).await
- }
-```
-
-Replace `self.post_json` with whatever helper the impl actually uses — check the neighbouring methods first.
-
-- [ ] **Step 7: Verify everything builds**
-
-Run: `cargo check -p dbx-mcp && cargo test -p dbx-mcp`
-Expected: no errors, tests pass.
-
-- [ ] **Step 8: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-mcp/src/backend.rs
-git commit -m "feat(docs): add collect_docs_snapshot to DbxBackend"
-```
-
----
-
-## Task 11: `dbx dbml` CLI verb
-
-**Files:**
-- Modify: `crates/dbx-cli/src/main.rs`
-
-**Interfaces:**
-- Consumes: `DbxBackend::collect_docs_snapshot` (Task 10), `dbx_core::docs::to_dbml` (Task 7)
-- Produces: `dbx dbml <connection> [--out path] [--schema s] [--database d] [--tables a,b]`
-
-`--out` is a new flag. `--notes` is deliberately **not** added here — it needs the annotation store from Part 2.
-
-- [ ] **Step 1: Write the failing test**
-
-Append to the existing `#[cfg(test)] mod tests` in `crates/dbx-cli/src/main.rs`, matching the style of the existing `parse_flags` tests around line 934:
-
-```rust
- #[test]
- fn parses_the_out_flag() {
- let flags = parse_flags(&args(&["dbml", "local", "--out", "schema.dbml"])).expect("parse");
- assert_eq!(flags.args, args(&["dbml", "local"]));
- assert_eq!(flags.out.as_deref(), Some(std::path::Path::new("schema.dbml")));
- }
-
- #[test]
- fn out_requires_a_value() {
- let error = parse_flags(&args(&["dbml", "local", "--out"])).expect_err("should fail");
- assert_eq!(error.code, "INVALID_OPTION");
- }
-
- #[test]
- fn dbml_appears_in_the_usage_text() {
- assert!(usage().contains("dbx dbml <connection>"), "got: {}", usage());
- }
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p dbx-cli`
-Expected: FAIL — `no field named out on Flags`.
-
-- [ ] **Step 3: Add the flag**
-
-Add `pub out: Option<PathBuf>` to the `Flags` struct, initialise it to `None` in `parse_flags`, and add the match arm beside `--file`:
-
-```rust
- "--out" => flags.out = Some(PathBuf::from(option_value(argv, &mut index, "--out")?)),
-```
-
-- [ ] **Step 4: Add the verb dispatch**
-
-In `run_with_backend`, beside the existing `schema` / `query` / `context` checks:
-
-```rust
- if args.first().is_some_and(|arg| arg == "dbml") {
- return run_dbml(backend, &flags).await;
- }
-```
-
-And the handler, modelled on `run_context`:
-
-```rust
-async fn run_dbml(backend: &dyn DbxBackend, flags: &Flags) -> Result<String, (CliError, bool)> {
- let name = flags.args.get(1).ok_or_else(|| {
- (CliError::new("MISSING_ARGUMENT", "Usage: dbx dbml <connection> [--out path]"), false)
- })?;
-
- let connection = find_connection(backend, name).await.map_err(|error| (error, false))?;
- let database = selected_database(&connection, flags.database.as_deref());
-
- let options = DocsSnapshotOptions {
- schemas: flags.schema.clone().into_iter().collect(),
- tables: flags.tables.clone(),
- project_name: Some(connection.name.clone()),
- };
-
- let snapshot = backend
- .collect_docs_snapshot(&connection, &database, options)
- .await
- .map_err(|error| (CliError::new("DOCS_SNAPSHOT_FAILED", error), false))?;
-
- let output = dbx_core::docs::to_dbml(&snapshot);
-
- for warning in &output.warnings {
- eprintln!("warning: {warning:?}");
- }
-
- match flags.out.as_ref() {
- Some(path) => {
- std::fs::write(path, &output.text).map_err(|error| {
- (CliError::new("WRITE_FAILED", format!("Failed to write {}: {error}", path.display())), false)
- })?;
- Ok(format!("Wrote {} bytes to {}", output.text.len(), path.display()))
- }
- None => Ok(output.text),
- }
-}
-```
-
-- [ ] **Step 5: Update the usage text**
-
-In the `usage()` function, add this line to the existing string, after the `dbx context` line:
-
-```
- dbx dbml <connection> [--out path] [--schema name] [--database name] [--tables a,b]
-```
-
-- [ ] **Step 6: Run the tests to verify they pass**
-
-Run: `cargo test -p dbx-cli`
-Expected: PASS.
-
-- [ ] **Step 7: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-cli/src/main.rs
-git commit -m "feat(docs): add dbx dbml command"
-```
-
----
-
-## Task 12: Live end-to-end verification
-
-**Files:**
-- Create: `crates/dbx-core/tests/live_postgres_docs_snapshot.rs`
-
-**Interfaces:**
-- Consumes: everything above
-
-Follow the exact gating convention of `crates/dbx-core/tests/live_postgres_query_result_export.rs` — read it first and copy how it skips when no live database is configured.
-
-- [ ] **Step 1: Read the existing live test's harness**
-
-Run: `sed -n '1,50p' crates/dbx-core/tests/live_postgres_query_result_export.rs`
-
-Copy its env-var gating and connection setup verbatim.
-
-- [ ] **Step 2: Write the live test**
-
-```rust
-// Gating and connection setup copied from live_postgres_query_result_export.rs.
-
-#[tokio::test]
-async fn collects_a_snapshot_and_serializes_valid_dbml() {
- let Some((state, config)) = live_postgres().await else {
- eprintln!("skipping: no live PostgreSQL configured");
- return;
- };
-
- let options = dbx_core::docs::CollectOptions {
- database: config.database.clone().unwrap_or_default(),
- schemas: vec!["public".to_string()],
- tables: vec![],
- project_name: "live-test".to_string(),
- };
-
- let snapshot = dbx_core::docs::collect_snapshot(
- &state,
- &config,
- &options,
- &|_progress| {},
- &std::sync::atomic::AtomicBool::new(false),
- )
- .await
- .expect("collect");
-
- assert_eq!(snapshot.format_version, 1);
- assert!(!snapshot.tables.is_empty(), "expected at least one table");
-
- let dbml = dbx_core::docs::to_dbml(&snapshot);
- assert!(dbml.text.starts_with("Project "), "got:\n{}", dbml.text);
-
- for table in &snapshot.tables {
- assert!(
- dbml.text.contains(&format!("Table {}", table.name))
- || dbml.text.contains(&format!("Table {}.{}", table.schema.clone().unwrap_or_default(), table.name)),
- "table {} missing from DBML",
- table.name
- );
- }
-
- // Braces must balance, or the DBML is unparseable.
- let opens = dbml.text.matches('{').count();
- let closes = dbml.text.matches('}').count();
- assert_eq!(opens, closes, "unbalanced braces in:\n{}", dbml.text);
-}
-```
-
-- [ ] **Step 3: Run it**
-
-Run: `cargo test -p dbx-core --test live_postgres_docs_snapshot -- --nocapture`
-Expected: PASS, or a clean skip message when no live database is configured.
-
-- [ ] **Step 4: Manual smoke test**
-
-With a real connection configured in DBX:
-
-```bash
-cargo run -p dbx-cli -- dbml <your-connection> --schema public
-```
-
-Expected: DBML on stdout beginning with `Project`. Paste it into <https://dbdiagram.io> and confirm it renders without a parse error. **This is the acceptance gate for the whole plan** — a DBML file that dbdiagram rejects is a failure regardless of what the unit tests say.
-
-- [ ] **Step 5: Full sweep**
-
-Run: `cargo test -p dbx-core && cargo test -p dbx-cli && cargo test -p dbx-mcp && cargo clippy -p dbx-core -- -D warnings`
-Expected: all pass.
-
-- [ ] **Step 6: Commit**
-
-```bash
-cargo fmt
-git add crates/dbx-core/tests/
-git commit -m "test(docs): add live snapshot and DBML verification"
-```
-
----
-
-## Done criteria
-
-- `dbx dbml <connection>` prints DBML that dbdiagram.io parses.
-- `dbx dbml <connection> --out schema.dbml` writes the file and reports the byte count.
-- Every DBML-inexpressible construct appears on stderr as a warning; none vanish.
-- `cargo test -p dbx-core` passes with no live database configured.
-- `SchemaSnapshot` serializes to camelCase JSON, ready for Part 2 (annotations) and Part 3 (viewer + HTML export).
-
----
-
-## Appendix: Corrections found during execution
-
-This plan was written by reading the codebase rather than compiling against it, and thirteen of its
-assumptions turned out to be wrong. All were caught and fixed before merge. The sections above have
-been amended where a fix was small and local; this appendix records every correction so that nobody
-re-derives a wrong fact from the surrounding prose.
-
-The pattern is consistent and worth internalising for future plans: **symbol names are easy to
-verify with grep; visibility, arity, module paths, and required call-ordering are not** — and those
-are exactly what breaks a build or, worse, compiles and fails at runtime.
-
-### Contract errors (wrong signature, path, or visibility)
-
-| # | Plan said | Reality |
-| --- | --- | --- |
-| 1 | `use crate::state::AppState` | `crate::connection::AppState` (`connection.rs:200`) |
-| 2 | `capabilities_for(db_type).comment` callable from `docs::` | `capabilities_for` **and** `TableStructureCapabilities` are `pub(super)`; it takes `Option<DatabaseType>`. Fixed by adding narrow `pub(crate) fn supports_comments` / `supports_foreign_keys` accessors in `table_structure_sql.rs` |
-| 3 | collector takes `&PoolKind` | `schema::*_core` take `&AppState` + connection id, and already wrap `retry_metadata_connection` |
-| 4 | `WebBackend::post_json(...)` | No such helper. Real API is `request(Method, path, Option<Value>)` (`backend.rs:247`) |
-| 5 | `new_connection_config(a, b, c, d)` | Takes 10 positional args (`backend.rs:1517`) |
-| 6 | `run_dbml -> Result<String, (CliError, bool)>` | Siblings return `Result<String, CliError>`; the tuple wrap happens once in `run()` |
-| 7 | `DocsSnapshotOptions` at crate root | Only at `dbx_mcp::backend::DocsSnapshotOptions` |
-| 8 | `pub out: Option<PathBuf>` on `Flags` | `Flags` is private with private fields — no `pub` |
-
-### Runtime-only errors (compiled and passed tests; would fail only against a live system)
-
-| # | Plan said | Reality |
-| --- | --- | --- |
-| 9 | Register route as `/api/docs/snapshot` | Router does `.nest("/api", api)` (`main.rs:777`), so routes register bare: `/docs/snapshot`. The literal path would have served `/api/api/docs/snapshot` |
-| 10 | `WebBackend` posts directly | Must call `self.ensure_connected(connection).await?` first (`backend.rs:283`) or the remote instance returns connection-not-found |
-| 11 | Live test uses a `live_postgres() -> Option<..>` helper with skip-by-return | Repo convention is `#[ignore = "requires DBX_LIVE_POSTGRES_..."]`. The plan's version would have **run and silently passed** with no database configured |
-
-### Logic errors (correct-looking code producing wrong output)
-
-| # | Defect | Fix |
-| --- | --- | --- |
-| 12 | `find_target` fell back to first-match-by-name, so an FK could bind to a same-named table in another schema | Resolution order is now explicit `ref_schema` → source table's own schema → unique bare name; ambiguous matches are dropped rather than guessed (`relations.rs`) |
-| 13 | `render_note` escaped only a literal `'''`, so a note ending in an apostrophe emitted four consecutive quotes and broke parsing | Also escapes a trailing `'` as `\'` (`dbml.rs`) |
-
-### Defects found by review, not present in the plan text
-
-- **`NoForeignKeyMetadata` false positives.** The emptiness heuristic reported healthy PostgreSQL as
- lacking FK support via three paths (schema genuinely has no FKs; `--tables` subset drops dangling
- edges; a swallowed `list_foreign_keys_core` error). Now gated purely on engine capability, and a
- real FK query failure surfaces as `TableSkipped`.
-- **Orphan enums.** `synthesize_enum` emitted an `Enum` block that `render_type` never referenced —
- the named-enum feature silently did not land. `render_type` now routes through the same
- `qualified()` helper `render_enum` uses, so the two cannot drift.
-- **Dropped `snapshot.warnings`.** `to_dbml` built its warning list from scratch, discarding
- collector-side omissions. Now seeded from `snapshot.warnings`.
-
-### Test-quality lessons
-
-Two regression tests written during the fix rounds were themselves invalid — one too narrow (pinned
-a single-schema literal, blind to the multi-schema case), one too loose (`contains` matched a bare
-name as a substring of the qualified one, so it passed against the very bug it guarded).
-
-**A regression test is not known to work until it has been observed failing against the bug.**
-Deliberately break the fix, watch the test fail, restore, confirm it passes. It costs about ninety
-seconds and it is the only way to distinguish a guard from a decoration.
diff --git a/docs/superpowers/plans/2026-08-03-database-documentation-in-app.md b/docs/superpowers/plans/2026-08-03-database-documentation-in-app.md
deleted file mode 100644
index 7e09dd838b..0000000000
--- a/docs/superpowers/plans/2026-08-03-database-documentation-in-app.md
+++ /dev/null
@@ -1,1762 +0,0 @@
-# In-App Database Documentation Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Make the Part 3a documentation viewer reachable from inside DBX and editable — table and column notes, table groups, and per-group colour — autosaved to a notes file that can live in the user's repository.
-
-**Architecture:** The viewer components stay pure (snapshot in, DOM out, zero backend calls, enforced by an existing contract test) so Part 3c can bundle them into a standalone HTML file. `DatabaseDocsDialog.vue` sits outside `src/docs/` and owns all I/O. Edits are pure transformations of the `AnnotationFile`, applied by Rust so the `shadowedNote` rule has exactly one implementation.
-
-**Tech Stack:** Rust (`dbx-core`, `dbx-web`, `src-tauri`), Vue 3 `<script setup lang="ts">`, Tailwind, vitest, vue-tsc, oxlint.
-
-## Global Constraints
-
-- **`apps/desktop/src/docs/**/*.vue` must make ZERO backend calls.** `componentContract.spec.ts` forbids `@/lib/backend`, `@tauri-apps`, `invoke(`, `useConnectionStore`, `useQueryStore`, `useSettingsStore`, `fetch(`, `axios`, `innerHTML`, `oklch(`, six-digit hex literals, and any `v-html` binding (either quote style) not naming `renderNote`. Extend that test; never weaken it.
-- **Never import `vue-i18n` inside `apps/desktop/src/docs/`.** `useI18n()` throws without a provided instance, which is exactly the Part 3c standalone-export case. Modules there take a translator function as a parameter instead.
-- **Every backend operation exists twice.** `apps/desktop/src/lib/backend/api.ts` resolves either `tauri.ts` or `http.ts` via `isTauriRuntime()`. Both must be implemented, plus a Tauri command and a web route.
-- **All annotation structs carry `#[serde(rename_all = "camelCase", deny_unknown_fields)]`.** An extra key sent from TypeScript is a hard deserialization error, not a silent ignore. `format_version` serialises as `formatVersion`.
-- **`dbx-core` must not depend on `dbx-mcp`.** `app_data_dir()` lives in `dbx-mcp`, so anything in `dbx-core` needing it takes the directory as a parameter.
-- **Rust commands:** `export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"` before `cargo` or `git commit` (the pre-commit hook runs `cargo fmt`). Use `pnpm`, never `npm`.
-- **Every new test gets a deliberate break:** break the behaviour, watch the named test fail, restore, report the failure message. A test that cannot fail is worse than no test.
-- Baseline before this plan: 77 frontend tests, 4428 Rust tests, `vue-tsc` exit 0, `oxlint` clean.
-
----
-
-## File Structure
-
-**Rust — `dbx-core`**
-- `crates/dbx-core/src/docs/annotations.rs` — add `save_annotations`, `resolve_notes_path`
-
-**Rust — Tauri**
-- `src-tauri/src/commands/docs.rs` — CREATE: four commands
-- `src-tauri/src/commands/mod.rs` — declare the module
-- `src-tauri/src/lib.rs:1411` — register in `generate_handler!`
-
-**Rust — web parity**
-- `crates/dbx-web/src/routes/docs.rs` — add three handlers
-- `crates/dbx-web/src/main.rs:377` — register three routes
-
-**Frontend — data and logic**
-- `apps/desktop/src/docs/types.ts` — add annotation types
-- `apps/desktop/src/docs/annotationEdits.ts` — CREATE: pure edit transforms
-- `apps/desktop/src/docs/docsIndex.ts` — add `columnsUsingEnum`
-- `apps/desktop/src/docs/docsWarnings.ts` — take a translator parameter
-
-**Frontend — backend facade**
-- `apps/desktop/src/lib/backend/tauri.ts`, `http.ts`, `api.ts` — four operations each
-
-**Frontend — components**
-- `apps/desktop/src/docs/components/NoteEditor.vue`, `GroupEditor.vue`, `GroupPicker.vue`, `EnumPage.vue` — CREATE
-- `apps/desktop/src/docs/DocsApp.vue` — `readonly` prop, edit events
-- `apps/desktop/src/components/docs/DatabaseDocsDialog.vue` — CREATE: owns I/O and autosave
-
-**Frontend — wiring and i18n**
-- `apps/desktop/src/stores/connectionStore.ts` — `docsSource`
-- `apps/desktop/src/composables/useDialogSources.ts` — watcher
-- `apps/desktop/src/components/layout/AppDialogs.vue` — registration
-- `apps/desktop/src/i18n/locales/{en,es,it,ja,ko,pt-BR,zh-CN,zh-TW}.ts` — `docs` namespace
-- `apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.ts` — CREATE
-
----
-
-## Task 1: Atomic save and notes-path resolution
-
-**Files:**
-- Modify: `crates/dbx-core/src/docs/annotations.rs`
-- Test: same file's `mod tests`
-
-**Interfaces:**
-- Consumes: `AnnotationFile` (existing), `ConnectionConfig` (existing, `docs_notes_path: Option<String>`)
-- Produces: `save_annotations(path: &Path, annotations: &AnnotationFile) -> Result<(), String>`, `resolve_notes_path(connection_id: &str, docs_notes_path: Option<&str>, data_dir: &Path) -> PathBuf`
-
-- [x] **Step 1: Write the failing tests**
-
-Add to the existing `mod tests` in `annotations.rs`:
-
-```rust
- #[test]
- fn save_then_load_round_trips() {
- let dir = temp_case_dir("round-trip");
- let path = dir.join("notes.json");
- let file = AnnotationFile {
- format_version: 1,
- project: Some(ProjectAnnotation { name: Some("P".into()), note: Some("hello".into()) }),
- groups: vec![GroupAnnotation { id: "g".into(), name: "G".into(), hue: 200, note: None }],
- tables: BTreeMap::from([(
- "public.t".to_string(),
- TableAnnotation { group: Some("g".into()), note: Some("n".into()), columns: BTreeMap::new() },
- )]),
- };
-
- save_annotations(&path, &file).expect("save");
- let loaded = load_annotations(&path).expect("load").expect("present");
-
- assert_eq!(loaded.format_version, 1);
- assert_eq!(loaded.groups[0].hue, 200);
- assert_eq!(loaded.tables["public.t"].note.as_deref(), Some("n"));
- assert_eq!(loaded.project.and_then(|p| p.note).as_deref(), Some("hello"));
- }
-
- #[test]
- fn save_creates_missing_parent_directories() {
- let dir = temp_case_dir("nested");
- let path = dir.join("nested").join("deeper").join("notes.json");
- let file = AnnotationFile {
- format_version: 1,
- project: None,
- groups: Vec::new(),
- tables: BTreeMap::new(),
- };
- save_annotations(&path, &file).expect("save into a new directory");
- assert!(path.exists());
- }
-
- #[test]
- fn save_leaves_no_temp_file_behind() {
- // A stray notes.json.tmp would be picked up by nothing, but it means
- // the rename did not happen and the write was not atomic.
- let dir = temp_case_dir("no-temp-left");
- let path = dir.join("notes.json");
- let file = AnnotationFile {
- format_version: 1,
- project: None,
- groups: Vec::new(),
- tables: BTreeMap::new(),
- };
- save_annotations(&path, &file).expect("save");
-
- let leftovers: Vec<_> = std::fs::read_dir(&dir)
- .expect("read_dir")
- .filter_map(Result::ok)
- .map(|entry| entry.file_name().to_string_lossy().into_owned())
- .filter(|name| name.ends_with(".tmp"))
- .collect();
- assert!(leftovers.is_empty(), "temp files left behind: {leftovers:?}");
- }
-
- #[test]
- fn a_failed_save_leaves_the_previous_file_intact() {
- // The reason for writing to a temp file and renaming. If the write
- // fails partway, the reader must still find the last good notes —
- // load_annotations errors loudly on malformed JSON, so a torn write
- // would read as "your notes file is corrupt".
- let dir = temp_case_dir("failed-save");
- let path = dir.join("notes.json");
- let good = AnnotationFile {
- format_version: 1,
- project: None,
- groups: Vec::new(),
- tables: BTreeMap::from([(
- "public.keep".to_string(),
- TableAnnotation { group: None, note: Some("survives".into()), columns: BTreeMap::new() },
- )]),
- };
- save_annotations(&path, &good).expect("first save");
-
- // A directory where the temp file wants to be makes File::create fail.
- std::fs::create_dir(path.with_extension("json.tmp")).expect("block the temp path");
- let result = save_annotations(&path, &good);
-
- assert!(result.is_err(), "save must fail when the temp path is unusable");
- let loaded = load_annotations(&path).expect("load").expect("present");
- assert_eq!(loaded.tables["public.keep"].note.as_deref(), Some("survives"));
- }
-
- #[test]
- fn an_explicit_notes_path_wins_over_the_default() {
- let resolved =
- resolve_notes_path("conn-1", Some("/tmp/team/schema-notes.json"), std::path::Path::new("/data"));
- assert_eq!(resolved, std::path::PathBuf::from("/tmp/team/schema-notes.json"));
- }
-
- #[test]
- fn the_default_notes_path_is_keyed_by_connection_id() {
- let resolved = resolve_notes_path("conn-1", None, std::path::Path::new("/data"));
- assert_eq!(resolved, std::path::PathBuf::from("/data/docs-notes/conn-1.json"));
- }
-
- #[test]
- fn a_blank_notes_path_falls_back_to_the_default() {
- // An empty string in the config is a cleared field, not a path to a
- // file named "". Treating it as explicit would resolve to garbage.
- let resolved = resolve_notes_path("conn-1", Some(" "), std::path::Path::new("/data"));
- assert_eq!(resolved, std::path::PathBuf::from("/data/docs-notes/conn-1.json"));
- }
-```
-
-Callers pass `&config.id, config.docs_notes_path.as_deref(), data_dir`.
-
-`dbx-core` has NO `[dev-dependencies]` section and therefore no `tempfile`. The idiom already used
-in this file (around line 319) is `std::env::temp_dir()` plus a uuid suffix — `uuid` is a regular
-dependency of this crate. Add this helper inside `mod tests` beside the others:
-
-```rust
- fn temp_case_dir(label: &str) -> std::path::PathBuf {
- let dir = std::env::temp_dir().join(format!("dbx-notes-{label}-{}", uuid::Uuid::new_v4().simple()));
- std::fs::create_dir_all(&dir).expect("create temp dir");
- dir
- }
-```
-
-- [x] **Step 2: Run and watch them fail**
-
-```bash
-export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"
-cargo test -p dbx-core --lib docs::annotations
-```
-Expected: FAIL — `save_annotations` and `resolve_notes_path` are not defined.
-
-- [x] **Step 3: Implement**
-
-Add to `annotations.rs`. It already has `use std::path::Path`; add `std::io::Write` and `std::path::PathBuf`.
-
-```rust
-/// Write the notes file atomically.
-///
-/// A partial write destroys prose a human typed, and `load_annotations`
-/// errors loudly on malformed JSON — so a torn write becomes "your notes file
-/// is corrupt" the next time the viewer opens. Write a sibling temp file,
-/// flush it to disk, then rename: rename within a directory is atomic on
-/// every platform DBX targets.
-pub fn save_annotations(path: &Path, annotations: &AnnotationFile) -> Result<(), String> {
- let json = serde_json::to_string_pretty(annotations)
- .map_err(|error| format!("Failed to serialize notes: {error}"))?;
-
- if let Some(parent) = path.parent() {
- std::fs::create_dir_all(parent)
- .map_err(|error| format!("Failed to create {}: {error}", parent.display()))?;
- }
-
- let temp = path.with_extension("json.tmp");
- {
- let mut file = std::fs::File::create(&temp)
- .map_err(|error| format!("Failed to create {}: {error}", temp.display()))?;
- file.write_all(json.as_bytes())
- .map_err(|error| format!("Failed to write {}: {error}", temp.display()))?;
- file.sync_all().map_err(|error| format!("Failed to flush {}: {error}", temp.display()))?;
- }
-
- std::fs::rename(&temp, path).map_err(|error| format!("Failed to replace {}: {error}", path.display()))
-}
-
-/// Where a connection's notes file lives.
-///
-/// An explicit `docs_notes_path` wins — that is the entire point of the field.
-/// Pointing it at a file inside a repository is what lets schema documentation
-/// be reviewed in pull requests. Otherwise the file lives under the app data
-/// directory keyed by connection id, so the feature works with no setup.
-///
-/// Takes the two fields it needs rather than a whole `ConnectionConfig`:
-/// that struct has no `Default` and ~60 fields, so passing it would force
-/// every test to build a literal full of values the function never reads.
-/// `data_dir` is a parameter because `dbx-core` cannot reach the caller's
-/// data directory on its own.
-pub fn resolve_notes_path(connection_id: &str, docs_notes_path: Option<&str>, data_dir: &Path) -> PathBuf {
- if let Some(path) = docs_notes_path.map(str::trim).filter(|value| !value.is_empty()) {
- return PathBuf::from(path);
- }
- data_dir.join("docs-notes").join(format!("{connection_id}.json"))
-}
-```
-
-Add `use crate::models::connection::ConnectionConfig;` if the file does not already import it.
-
-- [x] **Step 4: Run and watch them pass**
-
-```bash
-cargo test -p dbx-core --lib docs::annotations
-```
-
-- [x] **Step 5: Verify two guards bite**
-
-One at a time, restoring between each. Report both failure messages.
-
-1. Replace the temp-file-and-rename body with a direct `std::fs::write(path, json)` → `a_failed_save_leaves_the_previous_file_intact` must fail.
-2. Delete the `.filter(|value| !value.is_empty())` from `resolve_notes_path` → `a_blank_notes_path_falls_back_to_the_default` must fail.
-
-- [x] **Step 6: Commit**
-
-```bash
-export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"
-cargo clippy -p dbx-core --all-targets
-git add crates/dbx-core/src/docs/annotations.rs
-git commit -m "feat(docs): add atomic annotation save and notes path resolution"
-```
-
----
-
-## Task 2: Tauri commands
-
-**Files:**
-- Create: `src-tauri/src/commands/docs.rs`
-- Modify: `src-tauri/src/commands/mod.rs`, `src-tauri/src/lib.rs:1411`
-
-**Interfaces:**
-- Consumes: `save_annotations`, `resolve_notes_path` (Task 1); existing `collect_snapshot`, `load_annotations`, `apply_annotations`
-- Produces: commands `docs_collect_snapshot`, `docs_load_annotations`, `docs_apply_annotations`, `docs_save_annotations`
-
-- [x] **Step 1: Create the command module**
-
-`src-tauri/src/commands/docs.rs`:
-
-```rust
-use std::sync::atomic::AtomicBool;
-use std::sync::Arc;
-
-use dbx_core::connection::AppState;
-// `apply_annotations` is NOT re-exported at `dbx_core::docs` — that module's
-// `pub use` list covers collector, color, dbml, keys, relations and snapshot,
-// but not annotations. It must come from the submodule path.
-use dbx_core::docs::annotations::{
- apply_annotations, load_annotations, resolve_notes_path, save_annotations, AnnotationFile,
-};
-use dbx_core::docs::{collect_snapshot, CollectOptions, SchemaSnapshot};
-use dbx_core::models::connection::ConnectionConfig;
-use tauri::State;
-
-async fn connection_of(state: &Arc<AppState>, connection_id: &str) -> Result<ConnectionConfig, String> {
- let configs = state.configs.read().await;
- configs.get(connection_id).cloned().ok_or_else(|| format!("Connection {connection_id} not found."))
-}
-
-/// The notes file for a connection, resolved against DBX's data directory.
-///
-/// `AppState.storage.data_dir()` is the directory DBX is actually using — it
-/// honours a custom data dir, which a fresh `app_data_dir()` lookup would not.
-/// (`dbx-mcp::paths::app_data_dir()` is NOT available here: src-tauri does not
-/// depend on dbx-mcp.)
-async fn notes_path_of(state: &Arc<AppState>, connection_id: &str) -> Result<std::path::PathBuf, String> {
- let config = connection_of(state, connection_id).await?;
- Ok(resolve_notes_path(&config.id, config.docs_notes_path.as_deref(), state.storage.data_dir()))
-}
-
-/// Collect a RAW snapshot — annotations are applied separately, so the
-/// frontend can re-derive after an edit without touching the database.
-#[tauri::command]
-pub async fn docs_collect_snapshot(
- state: State<'_, Arc<AppState>>,
- connection_id: String,
- database: String,
- schemas: Vec<String>,
- tables: Vec<String>,
- project_name: Option<String>,
-) -> Result<SchemaSnapshot, String> {
- let config = connection_of(&state, &connection_id).await?;
- let options = CollectOptions {
- database,
- schemas,
- tables,
- project_name: project_name.unwrap_or_else(|| config.name.clone()),
- };
- collect_snapshot(&state, &config, &options, &|_progress| {}, &AtomicBool::new(false)).await
-}
-
-#[tauri::command]
-pub async fn docs_load_annotations(
- state: State<'_, Arc<AppState>>,
- connection_id: String,
-) -> Result<Option<AnnotationFile>, String> {
- let path = notes_path_of(&state, &connection_id).await?;
- load_annotations(&path)
-}
-
-/// Apply annotations to a raw snapshot. Pure — no database access.
-///
-/// This exists so the `shadowedNote` rule has exactly ONE implementation.
-/// Re-implementing it in TypeScript to update the view optimistically is the
-/// drift this feature has repeatedly suffered from.
-#[tauri::command]
-pub async fn docs_apply_annotations(
- state: State<'_, Arc<AppState>>,
- connection_id: String,
- snapshot: SchemaSnapshot,
- annotations: AnnotationFile,
-) -> Result<SchemaSnapshot, String> {
- let config = connection_of(&state, &connection_id).await?;
- let mut applied = snapshot;
- apply_annotations(&mut applied, &annotations, config.db_type);
- Ok(applied)
-}
-
-#[tauri::command]
-pub async fn docs_save_annotations(
- state: State<'_, Arc<AppState>>,
- connection_id: String,
- annotations: AnnotationFile,
-) -> Result<(), String> {
- let path = notes_path_of(&state, &connection_id).await?;
- save_annotations(&path, &annotations)
-}
-```
-
-The `use` lines above are correct as written — I verified them against `crates/dbx-core/src/docs/mod.rs`. `collect_snapshot`, `CollectOptions` and `SchemaSnapshot` ARE re-exported at the `docs` root; `apply_annotations` and friends are NOT, and come from `docs::annotations`.
-
-- [x] **Step 2: Declare and register**
-
-Add `pub mod docs;` to `src-tauri/src/commands/mod.rs` beside its siblings. Add these four to the `generate_handler![` list at `src-tauri/src/lib.rs:1411`, matching the surrounding entries' formatting:
-
-```rust
- commands::docs::docs_collect_snapshot,
- commands::docs::docs_load_annotations,
- commands::docs::docs_apply_annotations,
- commands::docs::docs_save_annotations,
-```
-
-- [x] **Step 3: Build**
-
-```bash
-export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"
-cargo check -p dbx
-cargo clippy -p dbx --all-targets
-```
-Both must be clean. There are no unit tests for this task: the commands are thin adapters over Task 1's tested functions, and a test asserting a delegation reimplements the delegation.
-
-- [x] **Step 4: Commit**
-
-```bash
-git add src-tauri/src/commands/docs.rs src-tauri/src/commands/mod.rs src-tauri/src/lib.rs
-git commit -m "feat(docs): add Tauri commands for docs snapshot and annotations"
-```
-
----
-
-## Task 3: Web route parity
-
-**Files:**
-- Modify: `crates/dbx-web/src/routes/docs.rs`, `crates/dbx-web/src/main.rs:377`
-
-**Interfaces:**
-- Consumes: the same `dbx-core` functions as Task 2
-- Produces: `POST /api/docs/annotations/load`, `/api/docs/annotations/apply`, `/api/docs/annotations/save`
-
-- [x] **Step 1: Add three handlers**
-
-Append to `crates/dbx-web/src/routes/docs.rs`, matching the existing `collect_snapshot` handler's style and its `#[serde(rename_all = "camelCase")]` request structs:
-
-```rust
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DocsAnnotationsRequest {
- pub connection_id: String,
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DocsApplyRequest {
- pub connection_id: String,
- pub snapshot: SchemaSnapshot,
- pub annotations: dbx_core::docs::annotations::AnnotationFile,
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DocsSaveRequest {
- pub connection_id: String,
- pub annotations: dbx_core::docs::annotations::AnnotationFile,
-}
-
-/// `WebState` already carries the data directory (`pub data_dir: PathBuf`), so
-/// this needs no lookup and no new dependency — dbx-web does NOT depend on
-/// dbx-mcp.
-fn notes_path_for(state: &Arc<WebState>, config: &ConnectionConfig) -> std::path::PathBuf {
- dbx_core::docs::annotations::resolve_notes_path(&config.id, config.docs_notes_path.as_deref(), &state.data_dir)
-}
-
-pub async fn load_annotations(
- State(state): State<Arc<WebState>>,
- Json(request): Json<DocsAnnotationsRequest>,
-) -> Result<Json<Option<dbx_core::docs::annotations::AnnotationFile>>, AppError> {
- let config = load_connection(&state, &request.connection_id).await?;
- let path = notes_path_for(&state, &config);
- Ok(Json(dbx_core::docs::annotations::load_annotations(&path).map_err(AppError::from)?))
-}
-
-pub async fn apply_annotations(
- State(state): State<Arc<WebState>>,
- Json(request): Json<DocsApplyRequest>,
-) -> Result<Json<SchemaSnapshot>, AppError> {
- let config = load_connection(&state, &request.connection_id).await?;
- let mut applied = request.snapshot;
- dbx_core::docs::annotations::apply_annotations(&mut applied, &request.annotations, config.db_type);
- Ok(Json(applied))
-}
-
-pub async fn save_annotations(
- State(state): State<Arc<WebState>>,
- Json(request): Json<DocsSaveRequest>,
-) -> Result<Json<()>, AppError> {
- let config = load_connection(&state, &request.connection_id).await?;
- let path = notes_path_for(&state, &config);
- dbx_core::docs::annotations::save_annotations(&path, &request.annotations).map_err(AppError::from)?;
- Ok(Json(()))
-}
-```
-
-Do NOT add a `dbx-mcp` dependency to `dbx-web` — it has none, and it does not need one. `WebState` already carries `pub data_dir: PathBuf`, which is what the handlers use.
-
-- [x] **Step 2: Register the routes**
-
-At `crates/dbx-web/src/main.rs:377`, beside the existing `/docs/snapshot` line:
-
-```rust
- .route("/docs/annotations/load", post(routes::docs::load_annotations))
- .route("/docs/annotations/apply", post(routes::docs::apply_annotations))
- .route("/docs/annotations/save", post(routes::docs::save_annotations))
-```
-
-- [x] **Step 3: Build**
-
-```bash
-export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"
-cargo check -p dbx-web && cargo clippy -p dbx-web --all-targets
-```
-
-- [x] **Step 4: Commit**
-
-```bash
-git add crates/dbx-web/src/routes/docs.rs crates/dbx-web/src/main.rs
-git commit -m "feat(docs): add web routes for annotation load, apply and save"
-```
-
----
-
-## Task 4: Frontend backend facade and annotation types
-
-**Files:**
-- Modify: `apps/desktop/src/docs/types.ts`, `apps/desktop/src/lib/backend/tauri.ts`, `apps/desktop/src/lib/backend/http.ts`, `apps/desktop/src/lib/backend/api.ts`
-- Test: `apps/desktop/src/docs/__tests__/annotationTypes.spec.ts` (create)
-
-**Interfaces:**
-- Produces: TS types `AnnotationFile`, `ProjectAnnotation`, `GroupAnnotation`, `TableAnnotation`, `ColumnAnnotation`; and `collectDocsSnapshot`, `loadDocsAnnotations`, `applyDocsAnnotations`, `saveDocsAnnotations` exported from `@/lib/backend/api`
-
-- [x] **Step 1: Add the types**
-
-Append to `apps/desktop/src/docs/types.ts`. These mirror Rust structs carrying `deny_unknown_fields`, so an extra property is a hard deserialization error on the Rust side — the shapes must match exactly.
-
-```ts
-/** Mirrors `dbx_core::docs::annotations::ColumnAnnotation`. */
-export interface ColumnAnnotation {
- note: string;
-}
-
-/** Mirrors `TableAnnotation`. Absent keys are omitted, never sent as null. */
-export interface TableAnnotation {
- group?: string;
- note?: string;
- columns?: Record<string, ColumnAnnotation>;
-}
-
-/** Mirrors `GroupAnnotation`. `hue` is 0–359; lightness and chroma are the theme's. */
-export interface GroupAnnotation {
- id: string;
- name: string;
- hue: number;
- note?: string;
-}
-
-/** Mirrors `ProjectAnnotation`. */
-export interface ProjectAnnotation {
- name?: string;
- note?: string;
-}
-
-/**
- * The on-disk notes file. Rust declares `deny_unknown_fields`, so adding a
- * property here without adding it in Rust makes every save fail.
- */
-export interface AnnotationFile {
- formatVersion: number;
- project?: ProjectAnnotation;
- groups?: GroupAnnotation[];
- tables?: Record<string, TableAnnotation>;
-}
-```
-
-- [x] **Step 2: Write the failing conformance test**
-
-`apps/desktop/src/docs/__tests__/annotationTypes.spec.ts`:
-
-```ts
-import { readFileSync } from "node:fs";
-import path from "node:path";
-import { describe, expect, it } from "vitest";
-
-// The Rust structs carry deny_unknown_fields, so any property TypeScript adds
-// that Rust does not declare turns every save into a deserialization error at
-// runtime. vue-tsc cannot see across the language boundary, so this reads the
-// Rust source and compares the field sets directly.
-const rustSource = readFileSync(
- path.resolve(__dirname, "../../../../../crates/dbx-core/src/docs/annotations.rs"),
- "utf8",
-);
-
-function rustFields(structName: string): string[] {
- const start = rustSource.indexOf(`pub struct ${structName} {`);
- expect(start, `struct ${structName} not found in annotations.rs`).toBeGreaterThan(-1);
- const body = rustSource.slice(start, rustSource.indexOf("\n}", start));
- return [...body.matchAll(/^\s{4}pub ([a-z_]+):/gm)].map((match) => toCamel(match[1])).sort();
-}
-
-function toCamel(value: string): string {
- return value.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());
-}
-
-describe("annotation types match the Rust structs", () => {
- it.each([
- ["AnnotationFile", ["formatVersion", "groups", "project", "tables"]],
- ["ProjectAnnotation", ["name", "note"]],
- ["GroupAnnotation", ["hue", "id", "name", "note"]],
- ["TableAnnotation", ["columns", "group", "note"]],
- ["ColumnAnnotation", ["note"]],
- ])("%s", (structName, expected) => {
- expect(rustFields(structName as string)).toEqual(expected);
- });
-});
-```
-
-- [x] **Step 3: Run and watch it pass**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/annotationTypes.spec.ts
-```
-Expected: PASS, 5 cases. If a field set mismatches, the TypeScript above is wrong — fix the TypeScript, not the test, and report what differed.
-
-- [x] **Step 4: Verify it bites**
-
-Add `extra?: string;` to the TS `GroupAnnotation` and confirm the `GroupAnnotation` case FAILS. Restore. Report the message.
-
-- [x] **Step 5: Add the four backend functions**
-
-In `apps/desktop/src/lib/backend/tauri.ts`, following the file's existing `invoke` idiom:
-
-```ts
-export async function collectDocsSnapshot(
- connectionId: string,
- database: string,
- schemas: string[],
- tables: string[],
- projectName?: string,
-): Promise<SchemaSnapshot> {
- return invoke("docs_collect_snapshot", { connectionId, database, schemas, tables, projectName });
-}
-
-export async function loadDocsAnnotations(connectionId: string): Promise<AnnotationFile | null> {
- return invoke("docs_load_annotations", { connectionId });
-}
-
-export async function applyDocsAnnotations(
- connectionId: string,
- snapshot: SchemaSnapshot,
- annotations: AnnotationFile,
-): Promise<SchemaSnapshot> {
- return invoke("docs_apply_annotations", { connectionId, snapshot, annotations });
-}
-
-export async function saveDocsAnnotations(connectionId: string, annotations: AnnotationFile): Promise<void> {
- return invoke("docs_save_annotations", { connectionId, annotations });
-}
-```
-
-In `http.ts`, the same four signatures using that file's `post<T>(url, body)` helper (defined at
-`http.ts:222`, which throws `backendResponseError` on a non-OK status and returns `res.json()`):
-
-```ts
-export async function collectDocsSnapshot(
- connectionId: string,
- database: string,
- schemas: string[],
- tables: string[],
- projectName?: string,
-): Promise<SchemaSnapshot> {
- return post("/api/docs/snapshot", { connectionId, database, schemas, tables, projectName });
-}
-
-export async function loadDocsAnnotations(connectionId: string): Promise<AnnotationFile | null> {
- return post("/api/docs/annotations/load", { connectionId });
-}
-
-export async function applyDocsAnnotations(
- connectionId: string,
- snapshot: SchemaSnapshot,
- annotations: AnnotationFile,
-): Promise<SchemaSnapshot> {
- return post("/api/docs/annotations/apply", { connectionId, snapshot, annotations });
-}
-
-export async function saveDocsAnnotations(connectionId: string, annotations: AnnotationFile): Promise<void> {
- return post("/api/docs/annotations/save", { connectionId, annotations });
-}
-```
-
-**The two transports must expose identical signatures.** `api.ts` types the backend as `typeof TauriModule` and `forward()` re-exports by name, so a signature that differs between `tauri.ts` and `http.ts` is a type error at the facade — which is the only place it would ever be caught.
-
-**Tauri serialises command arguments BY NAME.** The Rust commands take `connection_id`, `database`, `schemas`, `tables`, `project_name`, `snapshot`, `annotations`; Tauri converts camelCase to snake_case automatically, so the `invoke` object keys above must be exactly `connectionId`, `database`, `schemas`, `tables`, `projectName`, `snapshot`, `annotations`. A mismatch compiles cleanly on both sides and fails only at runtime when a user clicks.
-
-In `api.ts`, beside the other forwards:
-
-```ts
-export const collectDocsSnapshot = forward("collectDocsSnapshot");
-export const loadDocsAnnotations = forward("loadDocsAnnotations");
-export const applyDocsAnnotations = forward("applyDocsAnnotations");
-export const saveDocsAnnotations = forward("saveDocsAnnotations");
-```
-
-- [x] **Step 6: Verify and commit**
-
-```bash
-pnpm vitest run apps/desktop/src/docs
-pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs
-git add apps/desktop/src/docs apps/desktop/src/lib/backend
-git commit -m "feat(docs): expose docs snapshot and annotations to the frontend"
-```
-
-`vue-tsc` must be clean — `tauri.ts` and `http.ts` are type-checked, and a signature mismatch between them is exactly what `forward()` cannot catch.
-
----
-
-## Task 5: Pure annotation edits
-
-**Files:**
-- Create: `apps/desktop/src/docs/annotationEdits.ts`
-- Test: `apps/desktop/src/docs/__tests__/annotationEdits.spec.ts`
-
-**Interfaces:**
-- Consumes: `AnnotationFile`, `TableAnnotation`, `GroupAnnotation` (Task 4)
-- Produces: `emptyAnnotations()`, `setProjectNote`, `setTableNote`, `setColumnNote`, `setTableGroup`, `upsertGroup`, `removeGroup` — every one `(file, ...args) => AnnotationFile`
-
-- [x] **Step 1: Write the failing tests**
-
-```ts
-import { describe, expect, it } from "vitest";
-import {
- emptyAnnotations,
- removeGroup,
- setColumnNote,
- setProjectNote,
- setTableGroup,
- setTableNote,
- upsertGroup,
-} from "../annotationEdits";
-
-const base = emptyAnnotations();
-
-describe("annotationEdits", () => {
- it("starts from a valid empty file", () => {
- expect(emptyAnnotations()).toEqual({ formatVersion: 1 });
- });
-
- it("never mutates its input", () => {
- // Every function returns a new file. Mutating in place would make Vue's
- // reactivity miss the change and make undo impossible to add later.
- const before = JSON.stringify(base);
- setTableNote(base, "public.orders", "hello");
- expect(JSON.stringify(base)).toBe(before);
- });
-
- it("sets and clears a table note", () => {
- const withNote = setTableNote(base, "public.orders", "One row per checkout.");
- expect(withNote.tables?.["public.orders"].note).toBe("One row per checkout.");
-
- const cleared = setTableNote(withNote, "public.orders", " ");
- expect(cleared.tables?.["public.orders"]).toBeUndefined();
- });
-
- it("keeps a table entry when it still carries a group after the note clears", () => {
- // Dropping the whole entry here would silently unassign the group.
- const grouped = setTableGroup(setTableNote(base, "public.orders", "n"), "public.orders", "g1");
- const cleared = setTableNote(grouped, "public.orders", "");
- expect(cleared.tables?.["public.orders"].group).toBe("g1");
- expect(cleared.tables?.["public.orders"].note).toBeUndefined();
- });
-
- it("sets and clears a column note", () => {
- const withNote = setColumnNote(base, "public.orders", "status", "Lifecycle state.");
- expect(withNote.tables?.["public.orders"].columns?.status.note).toBe("Lifecycle state.");
-
- const cleared = setColumnNote(withNote, "public.orders", "status", "");
- expect(cleared.tables?.["public.orders"]).toBeUndefined();
- });
-
- it("upserts a group by id", () => {
- const created = upsertGroup(base, { id: "g1", name: "Core", hue: 28 });
- expect(created.groups).toEqual([{ id: "g1", name: "Core", hue: 28 }]);
-
- const renamed = upsertGroup(created, { id: "g1", name: "Core Accounts", hue: 200 });
- expect(renamed.groups).toHaveLength(1);
- expect(renamed.groups?.[0]).toEqual({ id: "g1", name: "Core Accounts", hue: 200 });
- });
-
- it("removing a group also clears every table that referenced it", () => {
- // A dangling groupId renders as no group at all, so the file would look
- // correct while carrying a reference to something that does not exist.
- const withGroup = setTableGroup(upsertGroup(base, { id: "g1", name: "Core", hue: 28 }), "public.orders", "g1");
- const removed = removeGroup(withGroup, "g1");
-
- expect(removed.groups ?? []).toEqual([]);
- expect(removed.tables?.["public.orders"]).toBeUndefined();
- });
-
- it("removing a group keeps a table that still has a note", () => {
- const seeded = setTableNote(
- setTableGroup(upsertGroup(base, { id: "g1", name: "Core", hue: 28 }), "public.orders", "g1"),
- "public.orders",
- "keep me",
- );
- const removed = removeGroup(seeded, "g1");
- expect(removed.tables?.["public.orders"].note).toBe("keep me");
- expect(removed.tables?.["public.orders"].group).toBeUndefined();
- });
-
- it("sets and clears the project note", () => {
- const withNote = setProjectNote(base, "# Sales\n\nThe billing schema.");
- expect(withNote.project?.note).toBe("# Sales\n\nThe billing schema.");
- expect(setProjectNote(withNote, "").project).toBeUndefined();
- });
-});
-```
-
-- [x] **Step 2: Run and watch it fail**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/annotationEdits.spec.ts
-```
-Expected: FAIL — cannot resolve `../annotationEdits`.
-
-- [x] **Step 3: Implement**
-
-```ts
-import type { AnnotationFile, GroupAnnotation, TableAnnotation } from "./types";
-
-/**
- * Every function here returns a NEW file rather than mutating.
- *
- * Empty or whitespace-only prose removes the entry instead of storing "" —
- * the notes file is meant to be committed and reviewed, so it must not
- * accumulate keys holding nothing.
- */
-export function emptyAnnotations(): AnnotationFile {
- return { formatVersion: 1 };
-}
-
-function blank(value: string): boolean {
- return value.trim() === "";
-}
-
-/** Drop a table entry once it carries neither a note nor a group. */
-function pruneTable(tables: Record<string, TableAnnotation>, key: string): Record<string, TableAnnotation> {
- const entry = tables[key];
- const empty =
- entry !== undefined &&
- entry.note === undefined &&
- entry.group === undefined &&
- Object.keys(entry.columns ?? {}).length === 0;
- if (!empty) {
- return tables;
- }
- const { [key]: _dropped, ...rest } = tables;
- return rest;
-}
-
-function withTable(file: AnnotationFile, key: string, change: (entry: TableAnnotation) => TableAnnotation): AnnotationFile {
- const tables = { ...(file.tables ?? {}) };
- tables[key] = change(tables[key] ?? {});
- const pruned = pruneTable(tables, key);
- return { ...file, tables: Object.keys(pruned).length > 0 ? pruned : undefined };
-}
-
-export function setTableNote(file: AnnotationFile, tableKey: string, note: string): AnnotationFile {
- return withTable(file, tableKey, (entry) => {
- const { note: _old, ...rest } = entry;
- return blank(note) ? rest : { ...rest, note };
- });
-}
-
-export function setColumnNote(file: AnnotationFile, tableKey: string, column: string, note: string): AnnotationFile {
- return withTable(file, tableKey, (entry) => {
- const columns = { ...(entry.columns ?? {}) };
- if (blank(note)) {
- delete columns[column];
- } else {
- columns[column] = { note };
- }
- const { columns: _old, ...rest } = entry;
- return Object.keys(columns).length > 0 ? { ...rest, columns } : rest;
- });
-}
-
-export function setTableGroup(file: AnnotationFile, tableKey: string, groupId: string | null): AnnotationFile {
- return withTable(file, tableKey, (entry) => {
- const { group: _old, ...rest } = entry;
- return groupId === null ? rest : { ...rest, group: groupId };
- });
-}
-
-export function upsertGroup(file: AnnotationFile, group: GroupAnnotation): AnnotationFile {
- const groups = [...(file.groups ?? [])];
- const index = groups.findIndex((candidate) => candidate.id === group.id);
- if (index >= 0) {
- groups[index] = group;
- } else {
- groups.push(group);
- }
- return { ...file, groups };
-}
-
-/**
- * Remove a group and every reference to it.
- *
- * `docsIndex` already drops a dangling groupId when rendering, so the viewer
- * degrades correctly either way — but the committed file should not carry a
- * reference to a group that no longer exists.
- */
-export function removeGroup(file: AnnotationFile, groupId: string): AnnotationFile {
- const groups = (file.groups ?? []).filter((group) => group.id !== groupId);
- let next: AnnotationFile = { ...file, groups };
- for (const [key, entry] of Object.entries(file.tables ?? {})) {
- if (entry.group === groupId) {
- next = setTableGroup(next, key, null);
- }
- }
- return next;
-}
-
-export function setProjectNote(file: AnnotationFile, note: string): AnnotationFile {
- const project = { ...(file.project ?? {}) };
- if (blank(note)) {
- delete project.note;
- } else {
- project.note = note;
- }
- return { ...file, project: Object.keys(project).length > 0 ? project : undefined };
-}
-```
-
-- [x] **Step 4: Run and watch it pass**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/annotationEdits.spec.ts
-```
-
-- [x] **Step 5: Verify two guards bite**
-
-One at a time, restoring between each. Report both failure messages.
-
-1. In `removeGroup`, delete the loop that clears table references → `removing a group also clears every table that referenced it` must fail.
-2. In `pruneTable`, drop the `entry.group === undefined` condition → `keeps a table entry when it still carries a group after the note clears` must fail.
-
-- [x] **Step 6: Commit**
-
-```bash
-pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs
-git add apps/desktop/src/docs
-git commit -m "feat(docs): add pure annotation edit transforms"
-```
-
----
-
-## Task 6: i18n namespace and the parity guard
-
-**Files:**
-- Create: `apps/desktop/src/i18n/locales/docs/{en,es,it,ja,ko,pt-BR,zh-CN,zh-TW}.ts` — the namespace, one module per locale
-- Modify: all 8 files in `apps/desktop/src/i18n/locales/` — import and spread their docs module
-- Modify: `apps/desktop/src/docs/docsWarnings.ts` and its spec
-- Create: `apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.ts`
-
-**Why the namespace gets its own modules.** Every non-English locale is
-`export default withEnglishFallback({ … })` — the fallback is applied AT MODULE LEVEL, inside the
-locale file. Only `en.ts` is a bare object. So `import ja from "../locales/ja"` yields the
-ALREADY-MERGED object, and a parity test comparing default exports would find every key present in
-every locale and pass while translations were missing. The test written to catch silent English
-fallback would be silently defeated by it.
-
-Putting the new namespace in its own per-locale modules makes each locale's OWN keys importable
-without the merge, which is the only way this property is observable at all. It is a small
-structural change scoped entirely to the new namespace; the existing 315 KB of keys are untouched.
-
-**Interfaces:**
-- Produces: `describeWarning(warning: SnapshotWarning, translate: Translate): WarningNotice` — the existing return type, unchanged — where `type Translate = (key: string, params?: Record<string, string | number>) => string`
-
-- [x] **Step 1: Write the failing parity test**
-
-```ts
-import { describe, expect, it } from "vitest";
-import en from "../locales/docs/en";
-import es from "../locales/docs/es";
-import it_ from "../locales/docs/it";
-import ja from "../locales/docs/ja";
-import ko from "../locales/docs/ko";
-import ptBR from "../locales/docs/pt-BR";
-import zhCN from "../locales/docs/zh-CN";
-import zhTW from "../locales/docs/zh-TW";
-
-// These import the per-locale DOCS modules, NOT ../locales/<name>.
-//
-// Every non-English locale file is `export default withEnglishFallback({...})`,
-// which deep-merges `en` UNDER the locale at module level. Importing those
-// default exports yields the ALREADY-MERGED object, so every locale appears to
-// have every key and this test would pass while translations were missing —
-// the fallback would silently defeat the test written to catch it.
-const locales: Array<[string, Record<string, unknown>]> = [
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-function leafKeys(value: unknown, prefix = ""): string[] {
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
- return [prefix];
- }
- return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) =>
- leafKeys(child, prefix ? `${prefix}.${key}` : key),
- );
-}
-
-describe("docs i18n namespace parity", () => {
- const expected = leafKeys(en as Record<string, unknown>).sort();
-
- it("english declares the docs namespace", () => {
- expect(expected.length, "locales/docs/en.ts must declare keys").toBeGreaterThan(0);
- });
-
- it.each(locales)("%s declares exactly the same docs keys as en", (_name, locale) => {
- expect(leafKeys(locale).sort()).toEqual(expected);
- });
-});
-```
-
-- [x] **Step 2: Run and watch it fail**
-
-```bash
-pnpm vitest run apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.ts
-```
-Expected: FAIL — no locale declares `docs`, so `leafKeys(undefined)` yields `[""]` and the English assertion fails first.
-
-- [x] **Step 3: Create `apps/desktop/src/i18n/locales/docs/en.ts`**
-
-```ts
-export default {
- title: "Documentation",
- groupBySchema: "Schemas",
- groupByTableGroup: "Table Groups",
- noGroup: "(no group)",
- noSchema: "(no schema)",
- search: "Search tables, columns, groups…",
- columns: "Columns",
- indexes: "Indexes",
- references: "References",
- referencedBy: "Referenced by",
- localNote: "LOCAL",
- shadowedComment: "Database comment: {comment}",
- addNote: "Add a note",
- editNote: "Edit note",
- newGroup: "New group…",
- groupName: "Group name",
- groupColour: "Colour",
- deleteGroup: "Delete group",
- enumValues: "Values",
- usedBy: "Used by",
- openDiagram: "Open schema diagram",
- saving: "Saving…",
- saved: "Saved",
- saveFailed: "Could not save notes: {error}",
- warnings: {
- tableSkipped: "{table} could not be read: {reason}",
- noForeignKeyMetadata: "{engine} does not report foreign key metadata, so this schema has no relationships to show.",
- commentsUnsupported: "{engine} does not support table or column comments, so notes here come only from DBX.",
- orphanedNotes: "{count} note(s) refer to tables or columns that no longer exist. Nothing was deleted.",
- dbmlOmitted: "{item} on {table} was left out of the DBML: {reason}",
- },
-};
-```
-
-Then in `apps/desktop/src/i18n/locales/en.ts`, import it and spread it in alphabetical position:
-
-```ts
-import docs from "./docs/en";
-// …
- docs,
-```
-
-- [x] **Step 4: Translate into the other 7 locales**
-
-Create `locales/docs/{es,it,ja,ko,pt-BR,zh-CN,zh-TW}.ts` with the same key structure and translated
-values, and wire each into its locale file the same way (`import docs from "./docs/ja";` … `docs,`). Keep every interpolation placeholder (`{table}`, `{engine}`, `{count}`, `{reason}`, `{item}`, `{comment}`, `{error}`) exactly as written — a translated placeholder name renders literally.
-
-Keep technical terms in English where a developer would say them in English: for `pt-BR` that means "schema", "commit", "cache", "index" stay English while "banco de dados", "arquivo", "fila" are Portuguese.
-
-- [x] **Step 5: Run the parity test**
-
-```bash
-pnpm vitest run apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.ts
-```
-Expected: PASS, 8 cases.
-
-- [x] **Step 6: Verify it bites**
-
-Delete one key from `locales/docs/ja.ts` and confirm the `ja` case FAILS naming that key. Restore. Report the message.
-
-Then verify the test could not have been vacuous: temporarily point the imports at `../locales/<name>` instead of `../locales/docs/<name>`, delete a key from `locales/docs/ja.ts` again, and confirm the test now PASSES despite the missing key — that is the trap this structure exists to avoid. Restore both. Report what you saw.
-
-- [x] **Step 7: Change `describeWarning` to take a translator**
-
-`docsWarnings.ts` currently returns hardcoded English. Change its signature so `src/docs/` never imports vue-i18n — `useI18n()` throws without a provided instance, which is exactly the Part 3c export case:
-
-```ts
-export type Translate = (key: string, params?: Record<string, string | number>) => string;
-
-export function describeWarning(warning: SnapshotWarning, translate: Translate): WarningNotice {
- switch (warning.kind) {
- case "tableSkipped":
- return { severity: "warning", text: translate("docs.warnings.tableSkipped", { table: warning.table, reason: warning.reason }) };
- // …one arm per variant, each calling translate with the same params the
- // existing English strings interpolate. Keep the exhaustive switch with
- // NO default arm — the missing-arm compile error is the guard.
- }
-}
-```
-
-Update `docsWarnings.spec.ts` to pass a fake translator that returns `` `${key}:${JSON.stringify(params)}` ``, and assert on that rather than on English prose. The tests then check the key and params, which is what actually matters now.
-
-- [x] **Step 8: Verify and commit**
-
-```bash
-pnpm vitest run apps/desktop/src/docs apps/desktop/src/i18n
-pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
-git add apps/desktop/src/docs apps/desktop/src/i18n
-git commit -m "feat(docs): add the docs i18n namespace with a parity guard"
-```
-
----
-
-## Task 7: Editing components
-
-**Files:**
-- Create: `apps/desktop/src/docs/components/NoteEditor.vue`, `GroupEditor.vue`, `GroupPicker.vue`
-- Modify: `apps/desktop/src/docs/__tests__/componentContract.spec.ts`
-
-**Interfaces:**
-- Consumes: `renderNote` (Part 3a), `groupStyle` (Part 3a), `GroupAnnotation` (Task 4)
-- Produces: `NoteEditor` (`modelValue: string`, `readonly: boolean`, emits `update:modelValue`), `GroupEditor` (`group: GroupAnnotation`, emits `update:group`, `delete`), `GroupPicker` (`groups: GroupAnnotation[]`, `modelValue: string | null`, emits `update:modelValue`, `create`)
-
-- [x] **Step 1: Extend the contract test**
-
-In `componentContract.spec.ts`, update `EXPECTED` to include the three new files, and add:
-
-```ts
- it("editing components accept a readonly mode", () => {
- // Part 3c renders these same components with editing off inside an
- // exported HTML file. A component that cannot be made read-only would
- // have to be forked for the export.
- const files = vueFiles();
- expect(files.length).toBe(EXPECTED.length);
- const editors = files.filter((file) => path.basename(file) === "NoteEditor.vue");
- expect(editors.length).toBe(1);
- expect(readFileSync(editors[0], "utf8")).toContain("readonly");
- });
-```
-
-- [x] **Step 2: Run and watch it fail**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/componentContract.spec.ts
-```
-Expected: FAIL on the file list — the three components do not exist.
-
-- [x] **Step 3: Build the three components**
-
-`NoteEditor.vue` — renders `renderNote` output until clicked, then a raw markdown textarea. The `v-html` must bind `renderNote(...)`; the contract test enforces it in either quote style. When `readonly` is true it never becomes editable.
-
-`GroupEditor.vue` — a name input plus the hue picker from the approved mock: 12 preset swatches, a
-`<input type="range" min="0" max="359">`, and a preview element rendering the colour on light and
-dark grounds at once.
-
-**Match the swatch idiom DBX already uses**, in `ConnectionDialog.vue:4921-4931` — a row of
-`h-6 w-6 rounded-full border` buttons inside `flex items-center gap-1.5`, selected state
-`ring-2 ring-ring ring-offset-2`, unselected `border-border`, each with a `:title` from an i18n key.
-Read it before writing yours so the new picker looks native rather than invented.
-
-**But do NOT copy how it fills them.** Connection colours are hex values painted with Tailwind
-classes (`bg-green-500`, `#22c55e`). Group colours are hues: the swatch must carry
-`class="docs-group"` and `:style="groupStyle(hue)"` on the SAME element, and the colour is decided
-by `docs.css`. The contract test forbids `oklch(` and six-digit hex literals in these components,
-so a naive copy of `ConnectionDialog`'s approach fails the test — correctly, because a hardcoded
-hex cannot stay legible on both light and dark grounds, which is the entire reason groups store a
-hue rather than a colour.
-
-`GroupPicker.vue` — a `<select>` over `groups` plus a "New group…" option emitting `create`.
-
-All three: `<script setup lang="ts">`, Tailwind with DBX token names (`bg-background`, `text-foreground`, `border-border`, `text-muted-foreground`), no store or backend imports, all strings via a `translate` prop or `t` passed from the parent — never `useI18n()` inside `src/docs/`.
-
-- [x] **Step 4: Run the contract test**
-
-```bash
-pnpm vitest run apps/desktop/src/docs
-```
-
-- [x] **Step 5: Verify the v-html guard still bites on the new file**
-
-Change `NoteEditor.vue`'s `v-html="renderNote(modelValue)"` to `v-html='modelValue'` (single quotes, raw value) and confirm the contract test FAILS. Restore. Report the message. This is the single most dangerous thing a template here can do — a database `COMMENT ON` value going straight to the DOM.
-
-- [x] **Step 6: Commit**
-
-```bash
-pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs
-git add apps/desktop/src/docs
-git commit -m "feat(docs): add note editor, group editor and group picker"
-```
-
----
-
-## Task 8: Enum page
-
-**Files:**
-- Create: `apps/desktop/src/docs/components/EnumPage.vue`
-- Create: `apps/desktop/src/docs/docsKeys.ts`
-- Modify: `apps/desktop/src/docs/docsIndex.ts`, `docsSearch.ts`, `DocsApp.vue`, `components/DocsSidebar.vue`, `components/WikiIndex.vue` (and any other component holding a `tableKey` copy), `apps/desktop/src/docs/__tests__/docsIndex.spec.ts`, `componentContract.spec.ts` (`EXPECTED`)
-
-**Interfaces:**
-- Produces: `columnsUsingEnum(snapshot: SchemaSnapshot, enumName: string): Array<{ tableKey: string; table: string; column: string }>`
-
-- [x] **Step 1: Write the failing test**
-
-Add to `docsIndex.spec.ts`:
-
-```ts
- // The file's existing helper is `table(schema, name, groupId)` and builds a
- // table with NO columns, so these tests need columns attached. Add this
- // helper beside it rather than changing the existing signature — the other
- // tests in this file call it positionally.
- function withColumns(base: DocTable, columns: Array<{ name: string; type: string }>): DocTable {
- return {
- ...base,
- columns: columns.map((column) => ({
- name: column.name,
- data_type: column.type,
- is_nullable: false,
- column_default: null,
- is_primary_key: false,
- extra: "",
- comment: null,
- numeric_precision: null,
- numeric_scale: null,
- character_maximum_length: null,
- })),
- };
- }
-
- function snapshotOf(tables: DocTable[], enums: SchemaSnapshot["enums"]): SchemaSnapshot {
- return {
- formatVersion: 1,
- project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },
- tables,
- relationships: [],
- groups: [],
- enums,
- warnings: [],
- };
- }
-
- it("finds every column using an enum, across tables", () => {
- const snapshot = snapshotOf(
- [
- withColumns(table("public", "orders"), [{ name: "status", type: "order_status" }]),
- withColumns(table("public", "returns"), [{ name: "state", type: "order_status" }]),
- withColumns(table("public", "users"), [{ name: "id", type: "integer" }]),
- ],
- [{ schema: "public", name: "order_status", values: ["new"], note: null, synthesized: false }],
- );
-
- expect(columnsUsingEnum(snapshot, "order_status")).toEqual([
- { tableKey: "public.orders", table: "orders", column: "status" },
- { tableKey: "public.returns", table: "returns", column: "state" },
- ]);
- });
-
- it("returns nothing for an enum no column references", () => {
- // Must not fall back to "every column" or to a substring match — an enum
- // named `state` would otherwise claim every column whose type contains it.
- const snapshot = snapshotOf(
- [withColumns(table("public", "users"), [{ name: "id", type: "integer" }])],
- [{ schema: "public", name: "state", values: ["a"], note: null, synthesized: false }],
- );
- expect(columnsUsingEnum(snapshot, "state")).toEqual([]);
- });
-```
-
-Import `DocTable` and `SchemaSnapshot` as types if the spec file does not already. The `ColumnInfo` field list above is the full required set the conformance test pins — omitting one is a type error.
-
-- [ ] **Step 2: Run and watch it fail** <!-- not performed: columnsUsingEnum was already implemented and committed before this step was reached, so the failure was never observed. The exact-match guard was instead verified by Step 5. -->
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/docsIndex.spec.ts
-```
-Expected: FAIL — `columnsUsingEnum` is not exported.
-
-- [x] **Step 3: Implement**
-
-```ts
-/**
- * Every column whose declared type is this enum.
- *
- * Exact match on `data_type`, never a substring: an enum named `state` would
- * otherwise claim every column of type `estado` or `statement`.
- */
-export function columnsUsingEnum(
- snapshot: SchemaSnapshot,
- enumName: string,
-): Array<{ tableKey: string; table: string; column: string }> {
- const hits: Array<{ tableKey: string; table: string; column: string }> = [];
- for (const table of snapshot.tables) {
- for (const column of table.columns) {
- if (column.data_type === enumName) {
- hits.push({ tableKey: qualifiedTableKey(table), table: table.name, column: column.name });
- }
- }
- }
- return hits;
-}
-```
-
-**The qualified table key is currently duplicated at least four times**, and this task would add a
-fifth. Extract it first, into a new `apps/desktop/src/docs/docsKeys.ts`:
-
-```ts
-import type { DocTable } from "./types";
-
-/**
- * The key that identifies a table across the viewer — `schema.name`, or the
- * bare name on schema-less engines like SQLite and MySQL.
- *
- * This rule was copied into four places before it lived here. It is the key
- * that annotations are stored under, so two call sites disagreeing would
- * attach a note to the wrong table.
- */
-export function qualifiedTableKey(table: DocTable): string {
- return table.schema ? `${table.schema}.${table.name}` : table.name;
-}
-```
-
-Then replace every existing copy with an import of it:
-- `docsSearch.ts:12` — the private `qualified(schema, name)`. It is called with loose arguments in
- places, so either adapt those call sites or keep a thin local wrapper that delegates; say which
- you did.
-- `DocsApp.vue:22`, `components/DocsSidebar.vue:19`, `components/WikiIndex.vue:15` — each has its
- own `tableKey(table)`. Check the remaining components for further copies and replace those too;
- report how many you found in total.
-
-Note `docsIndex.ts` does NOT contain a copy — it groups by `table.schema ?? ""`, which is a
-*section* key, not a table key. Do not change that.
-
-This extraction is in scope deliberately: Part 3a's final review flagged the duplication as a
-Minor and it was deferred, and this task is the moment a new consumer appears.
-
-- [x] **Step 4: Run and watch it pass, then build `EnumPage.vue`**
-
-A thin template: the enum's qualified name, its values, its note via `NoteEditor`, and the `columnsUsingEnum` list with each entry clickable to that table. Add it to `EXPECTED` in the contract test.
-
-- [x] **Step 5: Verify it bites**
-
-Change `column.data_type === enumName` to `column.data_type.includes(enumName)` and confirm `returns nothing for an enum no column references` FAILS. Restore. Report the message.
-
-- [x] **Step 6: Commit**
-
-```bash
-pnpm vitest run apps/desktop/src/docs
-pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
-git add apps/desktop/src/docs
-git commit -m "feat(docs): add the enum page and its reverse column lookup"
-```
-
----
-
-## Task 9: Wire editing through `DocsApp`
-
-**Files:**
-- Modify: `apps/desktop/src/docs/DocsApp.vue` and the components it renders
-- Modify: `apps/desktop/src/docs/__tests__/componentContract.spec.ts`
-
-**Interfaces:**
-- Produces: `DocsApp` props `snapshot: SchemaSnapshot`, `annotations: AnnotationFile`, `readonly?: boolean`, `translate: Translate`; emits `edit` with a discriminated payload
-
-**`snapshot` and `translate` already exist** on `DocsApp` (`translate` was added when the i18n task
-made `describeWarning` take a translator). You are ADDING `annotations` and `readonly` to the
-existing `defineProps`, not writing it from scratch. `readonly` is the only optional one.
-
-- [x] **Step 1: Define the edit payload**
-
-In `apps/desktop/src/docs/types.ts`:
-
-```ts
-/**
- * What the viewer asks its host to do. The viewer never persists anything —
- * that is what keeps `src/docs/` free of backend calls and bundleable into a
- * standalone HTML file.
- */
-export type DocsEdit =
- | { kind: "projectNote"; note: string }
- | { kind: "tableNote"; tableKey: string; note: string }
- | { kind: "columnNote"; tableKey: string; column: string; note: string }
- | { kind: "tableGroup"; tableKey: string; groupId: string | null }
- | { kind: "upsertGroup"; group: GroupAnnotation }
- | { kind: "removeGroup"; groupId: string };
-```
-
-- [x] **Step 2: Add the contract test**
-
-```ts
- it("the viewer emits edits rather than persisting them", () => {
- // src/docs/ must stay free of I/O so Part 3c can bundle it. Editing works
- // by emitting upward; the dialog outside this directory does the saving.
- const files = vueFiles();
- expect(files.length).toBe(EXPECTED.length);
- for (const file of files) {
- const source = readFileSync(file, "utf8");
- for (const needle of ["saveDocsAnnotations", "loadDocsAnnotations", "applyDocsAnnotations"]) {
- expect(source.includes(needle), `${path.basename(file)} must not call ${needle}`).toBe(false);
- }
- }
- });
-```
-
-- [x] **Step 3: Thread `readonly` and `annotations` down; emit `edit` up**
-
-`translate` is already threaded to `WarningBanner`; extend the same pattern to the other components as they gain strings.
-
-`DocsApp` gains the props and re-emits `edit` from its children. Each component renders a `NoteEditor` where a note belongs and emits the matching `DocsEdit`. When `readonly` is true, no editor is interactive and `GroupEditor` / `GroupPicker` are not rendered.
-
-- [x] **Step 4: Verify and commit**
-
-```bash
-pnpm vitest run apps/desktop/src/docs
-pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs
-git add apps/desktop/src/docs
-git commit -m "feat(docs): thread editing through the viewer as emitted events"
-```
-
-`vue-tsc` is the only thing type-checking these templates — treat any error as the real test and report it rather than suppressing it.
-
----
-
-## Task 10: The dialog, autosave, and wiring
-
-**Files:**
-- Create: `apps/desktop/src/components/docs/DatabaseDocsDialog.vue`
-- Create: `apps/desktop/src/components/docs/__tests__/docsAutosave.spec.ts`
-- Create: `apps/desktop/src/components/docs/docsAutosave.ts`
-- Modify: `apps/desktop/src/stores/connectionStore.ts`, `apps/desktop/src/composables/useDialogSources.ts`, `apps/desktop/src/components/layout/AppDialogs.vue`
-
-**Interfaces:**
-- Consumes: everything above
-- Produces: `createAutosave(save, delayMs)` returning `{ schedule(file), status, flush() }`
-
-- [x] **Step 1: Write the failing autosave tests**
-
-Autosave logic goes in a `.ts` file so it is testable without mounting anything:
-
-```ts
-import { describe, expect, it, vi } from "vitest";
-import { createAutosave } from "../docsAutosave";
-
-const file = { formatVersion: 1 } as const;
-
-describe("createAutosave", () => {
- it("coalesces rapid edits into one save", async () => {
- vi.useFakeTimers();
- const save = vi.fn().mockResolvedValue(undefined);
- const autosave = createAutosave(save, 500);
-
- autosave.schedule(file);
- autosave.schedule(file);
- autosave.schedule(file);
- expect(save).not.toHaveBeenCalled();
-
- await vi.advanceTimersByTimeAsync(500);
- expect(save).toHaveBeenCalledTimes(1);
- vi.useRealTimers();
- });
-
- it("surfaces a failure instead of swallowing it", async () => {
- // A silently swallowed write failure is the worst outcome this feature
- // can produce: the user keeps typing and believes their notes are saved.
- vi.useFakeTimers();
- const save = vi.fn().mockRejectedValue(new Error("disk full"));
- const autosave = createAutosave(save, 500);
-
- autosave.schedule(file);
- await vi.advanceTimersByTimeAsync(500);
-
- expect(autosave.status.value.state).toBe("failed");
- expect(autosave.status.value.message).toContain("disk full");
- vi.useRealTimers();
- });
-
- it("reports saved after a successful write", async () => {
- vi.useFakeTimers();
- const autosave = createAutosave(vi.fn().mockResolvedValue(undefined), 500);
- autosave.schedule(file);
- await vi.advanceTimersByTimeAsync(500);
- expect(autosave.status.value.state).toBe("saved");
- vi.useRealTimers();
- });
-
- it("never runs two saves concurrently", async () => {
- // flush() clears the timer, but a debounced write may already be awaiting
- // save. Starting a second one issues two concurrent writes of the same
- // file — a wasted round trip, a stale-write race, and the exact
- // concurrency that corrupts the notes file.
- let concurrent = 0;
- let maxConcurrent = 0;
- const save = vi.fn().mockImplementation(async () => {
- concurrent += 1;
- maxConcurrent = Math.max(maxConcurrent, concurrent);
- await new Promise((resolve) => setTimeout(resolve, 10));
- concurrent -= 1;
- });
-
- const autosave = createAutosave(save, 0);
- autosave.schedule(file);
- await Promise.all([autosave.flush(), autosave.flush(), autosave.flush()]);
-
- expect(maxConcurrent).toBe(1);
- });
-
- it("flush writes immediately without waiting for the timer", async () => {
- // The dialog calls this on close, so a note typed a moment earlier is
- // not lost to a pending debounce.
- const save = vi.fn().mockResolvedValue(undefined);
- const autosave = createAutosave(save, 500);
- autosave.schedule(file);
- await autosave.flush();
- expect(save).toHaveBeenCalledTimes(1);
- });
-});
-```
-
-- [x] **Step 2: Run and watch it fail**
-
-```bash
-pnpm vitest run apps/desktop/src/components/docs/__tests__/docsAutosave.spec.ts
-```
-Expected: FAIL — cannot resolve `../docsAutosave`.
-
-- [x] **Step 3: Implement `docsAutosave.ts`**
-
-```ts
-import { ref, type Ref } from "vue";
-import type { AnnotationFile } from "@/docs/types";
-
-export type SaveStatus =
- | { state: "idle" }
- | { state: "saving" }
- | { state: "saved" }
- | { state: "failed"; message: string };
-
-export interface Autosave {
- schedule: (file: AnnotationFile) => void;
- flush: () => Promise<void>;
- status: Ref<SaveStatus>;
-}
-
-/**
- * Debounced autosave.
- *
- * A failed write MUST become visible: the user keeps typing and believes
- * their notes are saved otherwise. The pending file is retained on failure so
- * the next edit retries rather than discarding what they wrote.
- */
-export function createAutosave(save: (file: AnnotationFile) => Promise<void>, delayMs: number): Autosave {
- const status = ref<SaveStatus>({ state: "idle" });
- let timer: ReturnType<typeof setTimeout> | undefined;
- let pending: AnnotationFile | undefined;
- // The write currently in flight, if any. `flush()` clearing the timer is not
- // enough: a debounced write may already be awaiting `save`, and starting a
- // second one issues two concurrent saves of the same file. Beyond wasting a
- // round trip, the later one can land stale, and it is the exact concurrency
- // that corrupted the notes file before the Rust side used a unique temp path.
- let inFlight: Promise<void> | undefined;
-
- async function write(): Promise<void> {
- if (inFlight !== undefined) {
- // Wait for the current write, then run again if an edit arrived while it
- // was going — never two at once.
- await inFlight;
- if (pending === undefined) {
- return;
- }
- }
- if (pending === undefined) {
- return;
- }
- const file = pending;
- status.value = { state: "saving" };
- const attempt = (async () => {
- try {
- await save(file);
- // Only clear if no newer edit arrived while this was in flight.
- if (pending === file) {
- pending = undefined;
- }
- status.value = { state: "saved" };
- } catch (error) {
- status.value = { state: "failed", message: error instanceof Error ? error.message : String(error) };
- }
- })();
- inFlight = attempt;
- try {
- await attempt;
- } finally {
- if (inFlight === attempt) {
- inFlight = undefined;
- }
- }
- }
-
- return {
- status,
- schedule(file) {
- pending = file;
- if (timer !== undefined) {
- clearTimeout(timer);
- }
- timer = setTimeout(() => void write(), delayMs);
- },
- async flush() {
- if (timer !== undefined) {
- clearTimeout(timer);
- timer = undefined;
- }
- await write();
- },
- };
-}
-```
-
-- [x] **Step 4: Run and watch it pass**
-
-- [x] **Step 5: Build the dialog**
-
-**The dialog shell, matching `SchemaDiagramDialog.vue` — the closest comparable feature:**
-
-```vue
-<script setup lang="ts">
-import { computed, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
-import DocsApp from "@/docs/DocsApp.vue";
-
-const props = defineProps<{
- open: boolean;
- prefillConnectionId: string;
- prefillDatabase: string;
- prefillSchema?: string;
-}>();
-
-const emit = defineEmits<{ "update:open": [value: boolean] }>();
-
-// The get/set computed is how every dialog in this codebase bridges the
-// `open` prop to `v-model:open` on <Dialog>.
-const dialogOpen = computed({
- get: () => props.open,
- set: (value) => emit("update:open", value),
-});
-
-// This component lives OUTSIDE src/docs/, so it may and must use useI18n():
-// it is what supplies the `translate` prop that the viewer components need,
-// since they are banned from importing vue-i18n themselves.
-const { t } = useI18n();
-</script>
-
-<template>
- <Dialog v-model:open="dialogOpen">
- <DialogContent
- class="w-[94vw] max-w-[94vw] sm:max-w-[94vw] md:max-w-[94vw] lg:max-w-[94vw] xl:max-w-[94vw] h-[86vh] max-h-[86vh] gap-0 p-0 overflow-hidden flex flex-col"
- >
- <DialogHeader>
- <DialogTitle>{{ t("docs.title") }}</DialogTitle>
- </DialogHeader>
- <!-- snapshot / annotations / translate / readonly=false down, `edit` up -->
- </DialogContent>
- </Dialog>
-</template>
-```
-
-The sizing class is copied verbatim from `SchemaDiagramDialog.vue:827`. The docs viewer is the same
-kind of thing — a full-window workspace rather than a form — so it should not invent its own
-dimensions.
-
-
-`DatabaseDocsDialog.vue` — props `open`, `prefillConnectionId`, `prefillDatabase`, `prefillSchema`. On open: `collectDocsSnapshot(...)` for the raw snapshot, `loadDocsAnnotations(...)` for the file (falling back to `emptyAnnotations()` when null), then `applyDocsAnnotations(...)` for what it displays. Holds the raw snapshot for re-derivation.
-
-On an `edit` event from `DocsApp`: apply the matching `annotationEdits` function, `schedule` the autosave, and call `applyDocsAnnotations` to refresh the display. Show the save status. Call `flush()` before closing. Use `useI18n()` HERE — the dialog is outside `src/docs/` — and pass `t` down as the `translate` prop. Add a button opening the existing schema diagram via `connectionStore.diagramSource`.
-
-- [x] **Step 6: Wire the trigger**
-
-The schema diagram uses this exact five-point wiring. Mirror it — I verified every location:
-
-1. **`apps/desktop/src/stores/connectionStore.ts:381`** — `diagramSource` is
- `ref<{ connectionId: string; database: string; schema?: string; tableName?: string } | null>(null)`,
- returned from the store at line 6928. Add `docsSource` with the same shape beside it, and export it
- the same way.
-
-2. **`apps/desktop/src/composables/useDialogSources.ts` (~line 162)** — a `watch` on
- `connectionStore.diagramSource` copies the prefills, sets `showDiagramDialog.value = true`, then
- clears the source back to `null`. **Clearing it is what makes the dialog re-openable** — without
- that, setting the same value twice does not re-trigger the watcher. Add the docs equivalent.
-
-3. **`apps/desktop/src/components/layout/AppDialogs.vue:13`** — `defineAsyncComponent(() => import(...))`,
- and **line 198** — rendered with `v-if="dialogs.showDiagramDialog.value"`,
- `v-model:open`, and the prefill props. Follow both.
-
-4. **`apps/desktop/src/components/objects/ObjectBrowser.vue:1428`** — `openDiagram(row)` sets
- `connectionStore.diagramSource = { connectionId: props.connection.id, database: props.database,
- schema: row.schema || selectedSchema.value, tableName: ... }`. Add `openDocs(row)` the same way.
-
-5. **`apps/desktop/src/components/objects/ObjectBrowser.vue:2605`** — the context-menu entry, shaped
- `...(canOpenDiagram.value ? [{ label: t("diagram.open"), action: () => openDiagram(row) }] : [])`.
- Add the docs entry beside it using `t("docs.title")` from the namespace Task 6 added.
-
-**ObjectBrowser is the right entry point**, not the connection tree: the tree has no `diagram.open`
-entry either, and the docs dialog takes exactly the prefills ObjectBrowser already supplies
-(connection, database, schema). If a tree-level entry is wanted later it is one more call site
-setting the same `docsSource`.
-
-- [x] **Step 7: Verify two guards bite**
-
-One at a time, restoring between each. Report both failure messages.
-
-1. Make the `catch` in `write()` swallow its error (`catch { pending = undefined; }`) → `surfaces a failure instead of swallowing it` must fail.
-2. Delete the `inFlight` guard at the top of `write()` → `never runs two saves concurrently` must fail.
-
-- [x] **Step 8: Full verification and commit**
-
-```bash
-export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"
-pnpm vitest run apps/desktop/src
-pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs apps/desktop/src/components/docs
-cargo test --workspace
-git add apps/desktop/src src-tauri
-git commit -m "feat(docs): mount the documentation viewer in DBX with autosaved editing"
-```
-
----
-
-## Done criteria
-
-- Documentation opens from the connection tree, and edits to notes and group colours survive closing and reopening the dialog.
-- Pointing `docs_notes_path` at a repository file produces a reviewable diff.
-- `apps/desktop/src/docs/**/*.vue` still makes zero backend calls and persists nothing, enforced by the contract test.
-- All 8 locales declare the same `docs` keys, enforced by a test.
-- A failed save is visible and does not discard the user's work.
-- `cargo test --workspace` and `pnpm vitest run apps/desktop/src` pass; `vue-tsc` and `oxlint` clean.
-
-## Deferred to Part 3c
-
-The standalone Vite bundle and self-contained HTML export; the `dbx docs` verb; hash routing; a minimal read-only ER renderer for the export; inlining `apps/desktop/public/fonts/geist-latin-wght-normal.woff2`; and closing the `DocEnum` fixture gap, since an exportable demo wants an enum-bearing schema anyway.
diff --git a/docs/superpowers/plans/2026-08-03-database-documentation-viewer.md b/docs/superpowers/plans/2026-08-03-database-documentation-viewer.md
deleted file mode 100644
index 6f4b755149..0000000000
--- a/docs/superpowers/plans/2026-08-03-database-documentation-viewer.md
+++ /dev/null
@@ -1,1536 +0,0 @@
-# Database Documentation Part 3a: Docs Viewer — Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Build the dbdocs-style documentation viewer as a standalone Vue app that renders a `SchemaSnapshot` and makes **zero backend calls** — the contract that later lets the same components run inside DBX and inside an exported HTML file.
-
-**Architecture:** All decision-making logic lives in pure `.ts` modules under `apps/desktop/src/docs/` with thorough vitest coverage. The `.vue` files are thin templates verified by static SFC parsing, matching this repo's established `erDiagram.ts` (tested) / `SchemaDiagramDialog.vue` (untested) split. TypeScript interfaces mirror the Rust `SchemaSnapshot`; a committed fixture generated from **real Rust output** plus a conformance test turns model drift into a failing test rather than a silent bug.
-
-**Tech Stack:** Vue 3 + TypeScript + Tailwind v4, vitest. No new dependencies.
-
-**Branch:** continue on `feature/docs-snapshot-dbml` (Parts 1+2, 31 commits, unmerged). Worktree at `/Users/possebon/workspaces/dbx.feature-docs-snapshot-dbml`.
-
-**Spec:** `docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.md`, Section 6.
-
-**Approved visual reference:** the mock at the group/table/diagram level — sidebar with `Group by: Schemas | Table Groups`, wiki index with inline markdown notes, table page with columns/indexes/bidirectional relationships, `⬤ LOCAL` shadow marker, warning banner.
-
-## Global Constraints
-
-- **NO new dependencies.** In particular **do NOT add `@vue/test-utils`** — this repo has never mounted a component in a test and deliberately has no such harness.
-- **`cargo` is NOT on PATH.** Prefix Rust commands with
- `export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"`.
-- **`apps/desktop/src/docs/` makes NO backend calls.** No `@/lib/backend/*`, no Tauri, no Pinia stores, no `fetch`. Snapshot in, DOM out. A test enforces this.
-- **Logic in `.ts`, templates thin.** If a `.vue` file contains a non-trivial decision (filtering, sorting, formatting, colour maths), that decision belongs in a `.ts` module with a test.
-- **Group colour is a hue integer.** Lightness/chroma are theme-controlled in CSS; never store or compute hex in the viewer.
-- Run `pnpm lint` scoped to the touched directory, never repo-wide (root `pnpm lint` OOMs on this repo).
-- Conventional Commits.
-- **Report mismatches, do not work around them.** Twenty plan defects across Parts 1-2 were caught that way.
-
----
-
-## Pre-resolved facts (verified — these override any assumption in the spec)
-
-1. **The spec's testing plan does not work here.** Section 6 says "every docs component rendered against fixture snapshot JSON". This repo has **no component-mount harness**: `@vue/test-utils` is not a dependency and zero specs call `mount()`. `packages/app-tests/aiAssistantSendGuard.test.ts:13` documents this in a comment. The established pattern for verifying a `.vue` file is **static SFC parsing** via `readFileSync` + `vue/compiler-sfc`'s `parse`.
-
-2. **No Rust→TypeScript codegen exists.** `apps/desktop/src/types/database.ts` is a hand-maintained 1167-line mirror. Part 3a therefore hand-writes TS interfaces for `SchemaSnapshot` — a genuine drift seam. Task 2's conformance test is the mitigation.
-
-3. **vitest config** (`vitest.config.ts`): `@vitejs/plugin-vue` loaded; alias `@` → `apps/desktop/src`; `include` covers `apps/desktop/src/**/*.spec.ts`; `maxWorkers: 4`; `globalSetup: packages/test-globals.ts`. **No `environment:` is set**, so there is no DOM — another reason component mounting is out of scope.
-
-4. **`node_modules` does not exist** in this worktree or the main checkout. `pnpm install` is Task 0.
-
-5. **Rust field names arrive as camelCase.** `SchemaSnapshot` and friends use `#[serde(rename_all = "camelCase")]`, so the JSON has `formatVersion`, `noteSource`, `shadowedNote`, `columnNotes`, `groupId`, `estimatedRows`, `viewDefinition`.
-
-6. **`SnapshotWarning` is the exception.** It uses `#[serde(rename_all = "camelCase", tag = "kind")]`, so its discriminant is `{ "kind": "tableSkipped", ... }` — **camelCase**, unlike `TableKind`/`NoteSource`/`Cardinality` which are SCREAMING_SNAKE (`"MATERIALIZED_VIEW"`, `"LOCAL"`, `"MANY_TO_ONE"`). Getting this wrong silently breaks warning rendering.
-
----
-
-## File Structure
-
-| File | Responsibility |
-| --- | --- |
-| `apps/desktop/src/docs/types.ts` | TS interfaces mirroring the Rust `SchemaSnapshot` |
-| `apps/desktop/src/docs/fixtures/keycloak.snapshot.json` | Real snapshot from a live database, committed |
-| `apps/desktop/src/docs/docsIndex.ts` | Sidebar/index model: schema grouping, table-group grouping, `(no group)` bucket |
-| `apps/desktop/src/docs/docsSearch.ts` | Client-side search over tables, columns, groups, enums |
-| `apps/desktop/src/docs/docsWarnings.ts` | `SnapshotWarning` → human-readable banner text |
-| `apps/desktop/src/docs/groupColor.ts` | Hue → CSS custom properties (never hex) |
-| `apps/desktop/src/docs/DocsApp.vue` + `components/*.vue` | Thin templates |
-| `apps/desktop/src/docs/__tests__/*.spec.ts` | vitest coverage for every `.ts` module + SFC guards |
-
----
-
-## Task 0: Environment setup
-
-- [ ] **Step 1: Install dependencies**
-
-There is no `node_modules` in this worktree. From the worktree root:
-
-```bash
-cd /Users/possebon/workspaces/dbx.feature-docs-snapshot-dbml
-pnpm install
-```
-
-This takes several minutes and downloads 1-3GB. **Disk is at ~45Gi free — if you hit ENOSPC, STOP and report it; do not delete anything.**
-
-- [ ] **Step 2: Confirm the baseline**
-
-```bash
-pnpm vitest run apps/desktop/src/lib/__tests__ --reporter=dot
-git branch --show-current # must be feature/docs-snapshot-dbml
-git status --short # must be empty apart from node_modules being ignored
-```
-
-Expected: tests pass, branch correct. If `pnpm install` fails or tests fail before you have changed anything, STOP and report — Part 3a builds on Parts 1-2 and a broken baseline makes every later failure ambiguous.
-
----
-
-## Task 1: Snapshot types
-
-**Files:**
-- Create: `apps/desktop/src/docs/types.ts`
-- Test: `apps/desktop/src/docs/__tests__/types.spec.ts`
-
-**Interfaces:**
-- Produces: `SchemaSnapshot`, `ProjectMeta`, `DocTable`, `TableGroup`, `Relationship`, `FieldRef`, `ColumnNote`, `DocEnum`, `TableKind`, `NoteSource`, `Cardinality`, `SnapshotWarning`
-
-**Casing is load-bearing.** Struct fields are camelCase; `TableKind`/`NoteSource`/`Cardinality` are SCREAMING_SNAKE strings; `SnapshotWarning` is internally tagged with a **camelCase** `kind`.
-
-- [ ] **Step 1: Write the failing test**
-
-```ts
-import { describe, expect, it } from "vitest";
-import type { SchemaSnapshot, SnapshotWarning } from "../types";
-
-describe("snapshot types", () => {
- it("accepts a minimal snapshot shaped like the Rust output", () => {
- const snapshot: SchemaSnapshot = {
- formatVersion: 1,
- project: {
- name: "Ecommerce",
- databaseType: "postgres",
- database: "shop",
- schemas: ["public"],
- generatedAt: "2026-08-03T00:00:00Z",
- note: null,
- },
- tables: [
- {
- schema: "public",
- name: "orders",
- kind: "TABLE",
- columns: [],
- indexes: [],
- foreignKeys: [],
- groupId: null,
- note: "Checkout rows.",
- noteSource: "DATABASE",
- shadowedNote: null,
- columnNotes: {},
- estimatedRows: null,
- viewDefinition: null,
- },
- ],
- relationships: [],
- groups: [],
- enums: [],
- warnings: [],
- };
-
- expect(snapshot.tables[0].noteSource).toBe("DATABASE");
- expect(snapshot.tables[0].kind).toBe("TABLE");
- });
-
- it("discriminates warnings on a camelCase kind", () => {
- // Rust: #[serde(rename_all = "camelCase", tag = "kind")] — so the
- // discriminant is camelCase even though sibling enums are SCREAMING_SNAKE.
- const warning: SnapshotWarning = {
- kind: "tableSkipped",
- table: "public.secret",
- reason: "permission denied",
- };
- expect(warning.kind).toBe("tableSkipped");
-
- const orphans: SnapshotWarning = { kind: "orphanedNotes", count: 3 };
- if (orphans.kind === "orphanedNotes") {
- expect(orphans.count).toBe(3);
- } else {
- throw new Error("discriminated union must narrow on kind");
- }
- });
-});
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/types.spec.ts
-```
-Expected: FAIL — cannot resolve `../types`.
-
-- [ ] **Step 3: Write the types**
-
-Create `apps/desktop/src/docs/types.ts`:
-
-```ts
-// Mirrors crates/dbx-core/src/docs/snapshot.rs. There is no Rust->TS codegen
-// in this repo, so this file is maintained by hand — see
-// __tests__/fixtureConformance.spec.ts, which validates it against a snapshot
-// generated by the real Rust code and fails if the two drift apart.
-
-export type TableKind = "TABLE" | "VIEW" | "MATERIALIZED_VIEW";
-export type NoteSource = "DATABASE" | "LOCAL" | "NONE";
-export type Cardinality = "ONE_TO_ONE" | "MANY_TO_ONE";
-
-export interface ColumnInfo {
- name: string;
- data_type: string;
- is_nullable: boolean;
- column_default: string | null;
- is_primary_key: boolean;
- extra: string | null;
- comment?: string | null;
- numeric_precision?: number | null;
- numeric_scale?: number | null;
- character_maximum_length?: number | null;
- enum_values?: string[] | null;
-}
-
-export interface IndexInfo {
- name: string;
- columns: string[];
- is_unique: boolean;
- is_primary: boolean;
- filter?: string | null;
- index_type?: string | null;
- included_columns?: string[] | null;
- comment?: string | null;
-}
-
-export interface ForeignKeyInfo {
- name: string;
- column: string;
- ref_schema?: string | null;
- ref_table: string;
- ref_column: string;
- on_update?: string | null;
- on_delete?: string | null;
-}
-
-export interface ProjectMeta {
- name: string;
- databaseType: string;
- database: string | null;
- schemas: string[];
- generatedAt: string;
- note: string | null;
-}
-
-export interface ColumnNote {
- note: string;
- source: NoteSource;
- shadowed: string | null;
-}
-
-export interface DocTable {
- schema: string | null;
- name: string;
- kind: TableKind;
- columns: ColumnInfo[];
- indexes: IndexInfo[];
- foreignKeys: ForeignKeyInfo[];
- groupId: string | null;
- note: string | null;
- noteSource: NoteSource;
- shadowedNote: string | null;
- columnNotes: Record<string, ColumnNote>;
- estimatedRows: number | null;
- viewDefinition: string | null;
-}
-
-export interface TableGroup {
- id: string;
- name: string;
- /** 0-359. Lightness and chroma are theme-controlled in CSS. */
- hue: number;
- note: string | null;
-}
-
-export interface FieldRef {
- schema: string | null;
- table: string;
- column: string;
-}
-
-export interface Relationship {
- id: string;
- name: string | null;
- from: FieldRef;
- to: FieldRef;
- cardinality: Cardinality;
- onUpdate: string | null;
- onDelete: string | null;
-}
-
-export interface DocEnum {
- schema: string | null;
- name: string;
- values: string[];
- note: string | null;
- synthesized: boolean;
-}
-
-/**
- * Internally tagged on a camelCase `kind`. Note this differs from
- * TableKind/NoteSource/Cardinality, which are SCREAMING_SNAKE — the Rust enum
- * carries both `tag = "kind"` and `rename_all = "camelCase"`.
- */
-export type SnapshotWarning =
- | { kind: "tableSkipped"; table: string; reason: string }
- | { kind: "noForeignKeyMetadata"; engine: string }
- | { kind: "commentsUnsupported"; engine: string }
- | { kind: "orphanedNotes"; count: number }
- | { kind: "dbmlOmitted"; table: string; item: string; reason: string };
-
-export interface SchemaSnapshot {
- formatVersion: number;
- project: ProjectMeta;
- tables: DocTable[];
- relationships: Relationship[];
- groups: TableGroup[];
- enums: DocEnum[];
- warnings: SnapshotWarning[];
-}
-```
-
-Note `ColumnInfo`/`IndexInfo`/`ForeignKeyInfo` keep **snake_case** field names: those Rust structs come from `crate::types` and do NOT carry `rename_all`. Task 2's conformance test will confirm this against real output — if it disagrees, fix this file, not the test.
-
-- [ ] **Step 4: Run it and watch it pass**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/types.spec.ts
-```
-Expected: PASS, 2 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs
-git add apps/desktop/src/docs/
-git commit -m "feat(docs): add snapshot types for the docs viewer"
-```
-
----
-
-## Task 2: Real fixture + drift guard
-
-**Files:**
-- Create: `apps/desktop/src/docs/fixtures/keycloak.snapshot.json` (generated, committed)
-- Create: `apps/desktop/src/docs/__tests__/fixtureConformance.spec.ts`
-- Create: `crates/dbx-core/tests/dump_docs_fixture.rs`
-
-**This is the task that closes the drift seam.** The fixture must come from the real Rust serializer, not be hand-written — a hand-written fixture would encode the same assumptions as `types.ts` and prove nothing.
-
-**A live PostgreSQL is available:** `127.0.0.1:5432`, `postgres`/`postgres`, database `keycloak` (90 tables).
-
-- [ ] **Step 1: Write the Rust dumper**
-
-Create `crates/dbx-core/tests/dump_docs_fixture.rs`, copying the gating and setup from `crates/dbx-core/tests/live_postgres_docs_annotations.rs` (`#[tokio::test]`, `#[ignore = "..."]`, env vars with defaults, the `live_postgres_config(...)` builder). It must collect a snapshot of schema `public` from `keycloak`, apply a small in-memory `AnnotationFile` so that notes, a group and an orphan all appear, then write `serde_json::to_string_pretty(&snapshot)` to the path given by `DBX_FIXTURE_OUT`, defaulting to `apps/desktop/src/docs/fixtures/keycloak.snapshot.json` relative to the repo root.
-
-Include annotations covering every field the viewer must render: a table note, a column note, a group with a hue, and an annotation for a nonexistent table so an `orphanedNotes` warning is present.
-
-- [ ] **Step 2: Generate the fixture**
-
-```bash
-export PATH="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"
-DBX_LIVE_POSTGRES_HOST=127.0.0.1 DBX_LIVE_POSTGRES_PORT=5432 \
-DBX_LIVE_POSTGRES_USER=postgres DBX_LIVE_POSTGRES_PASSWORD=postgres \
-DBX_LIVE_POSTGRES_DATABASE=keycloak \
-cargo test -p dbx-core --test dump_docs_fixture -- --ignored --nocapture
-```
-
-Then confirm the file exists and contains real data:
-
-```bash
-head -30 apps/desktop/src/docs/fixtures/keycloak.snapshot.json
-grep -c '"name"' apps/desktop/src/docs/fixtures/keycloak.snapshot.json
-```
-
-**Report the file size.** If it exceeds ~500KB, trim to the first 12 tables inside the dumper (keeping the annotated table, the group and the orphan warning) rather than committing a huge fixture.
-
-- [ ] **Step 3: Write the conformance test**
-
-```ts
-import { readFileSync } from "node:fs";
-import path from "node:path";
-import { describe, expect, it } from "vitest";
-import type { SchemaSnapshot } from "../types";
-
-const fixturePath = path.resolve(__dirname, "../fixtures/keycloak.snapshot.json");
-
-function loadFixture(): SchemaSnapshot {
- return JSON.parse(readFileSync(fixturePath, "utf8")) as SchemaSnapshot;
-}
-
-describe("fixture conformance", () => {
- // This fixture is generated by the REAL Rust serializer. Its job is to fail
- // when the Rust model changes shape, so the hand-maintained types.ts cannot
- // drift silently.
-
- it("has the shape types.ts declares", () => {
- const snapshot = loadFixture();
- expect(snapshot.formatVersion).toBe(1);
- expect(Array.isArray(snapshot.tables)).toBe(true);
- expect(snapshot.tables.length).toBeGreaterThan(0);
- expect(typeof snapshot.project.databaseType).toBe("string");
- expect(Array.isArray(snapshot.project.schemas)).toBe(true);
- });
-
- it("uses camelCase for snapshot-owned fields", () => {
- const raw = JSON.parse(readFileSync(fixturePath, "utf8")) as Record<string, unknown>;
- expect(raw).toHaveProperty("formatVersion");
- expect(raw).not.toHaveProperty("format_version");
-
- const table = (raw.tables as Record<string, unknown>[])[0];
- expect(table).toHaveProperty("noteSource");
- expect(table).toHaveProperty("columnNotes");
- expect(table).toHaveProperty("foreignKeys");
- expect(table).not.toHaveProperty("note_source");
- });
-
- it("keeps snake_case on columns, which come from crate::types", () => {
- const snapshot = loadFixture();
- const withColumns = snapshot.tables.find((table) => table.columns.length > 0);
- expect(withColumns, "fixture must contain at least one table with columns").toBeDefined();
- const column = withColumns!.columns[0] as unknown as Record<string, unknown>;
- expect(column).toHaveProperty("data_type");
- expect(column).toHaveProperty("is_nullable");
- expect(column).not.toHaveProperty("dataType");
- });
-
- it("carries an annotated note, a group and an orphan warning", () => {
- const snapshot = loadFixture();
-
- const annotated = snapshot.tables.find((table) => table.noteSource === "LOCAL");
- expect(annotated, "fixture must include a LOCAL-sourced note").toBeDefined();
- expect(annotated!.note).toBeTruthy();
-
- expect(snapshot.groups.length).toBeGreaterThan(0);
- expect(typeof snapshot.groups[0].hue).toBe("number");
-
- const orphan = snapshot.warnings.find((warning) => warning.kind === "orphanedNotes");
- expect(orphan, "fixture must include an orphanedNotes warning").toBeDefined();
- });
-
- it("every warning discriminant is one types.ts knows", () => {
- const known = new Set([
- "tableSkipped",
- "noForeignKeyMetadata",
- "commentsUnsupported",
- "orphanedNotes",
- "dbmlOmitted",
- ]);
- for (const warning of loadFixture().warnings) {
- expect(known.has(warning.kind), `unknown warning kind: ${warning.kind}`).toBe(true);
- }
- });
-});
-```
-
-- [ ] **Step 4: Run it**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/fixtureConformance.spec.ts
-```
-Expected: PASS, 5 tests.
-
-**If any assertion fails, the fixture is telling you `types.ts` is wrong — fix `types.ts`, not the test.** Report exactly which field disagreed; that is a real Rust/TS mismatch and I want to know about it.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add apps/desktop/src/docs/ crates/dbx-core/tests/dump_docs_fixture.rs
-git commit -m "feat(docs): add a real-output fixture and drift conformance test"
-```
-
----
-
-## Task 3: Index model (grouping)
-
-**Files:**
-- Create: `apps/desktop/src/docs/docsIndex.ts`
-- Test: `apps/desktop/src/docs/__tests__/docsIndex.spec.ts`
-
-**Interfaces:**
-- Produces: `groupBySchema(snapshot): IndexSection[]`, `groupByTableGroup(snapshot): IndexSection[]`, `interface IndexSection { key: string; label: string; hue: number | null; note: string | null; tables: DocTable[] }`
-
-This is the `Group by: Schemas | Table Groups` switch from the approved mock, including the `(no group)` bucket.
-
-- [ ] **Step 1: Write the failing test**
-
-```ts
-import { describe, expect, it } from "vitest";
-import { groupBySchema, groupByTableGroup } from "../docsIndex";
-import type { DocTable, SchemaSnapshot, TableGroup } from "../types";
-
-function table(schema: string | null, name: string, groupId: string | null = null): DocTable {
- return {
- schema, name, kind: "TABLE", columns: [], indexes: [], foreignKeys: [],
- groupId, note: null, noteSource: "NONE", shadowedNote: null,
- columnNotes: {}, estimatedRows: null, viewDefinition: null,
- };
-}
-
-function snapshot(tables: DocTable[], groups: TableGroup[] = []): SchemaSnapshot {
- return {
- formatVersion: 1,
- project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },
- tables, relationships: [], groups, enums: [], warnings: [],
- };
-}
-
-describe("groupBySchema", () => {
- it("groups tables under their schema, sorted by schema then name", () => {
- const sections = groupBySchema(snapshot([
- table("public", "orders"),
- table("analytics", "daily_sales"),
- table("public", "customers"),
- ]));
-
- expect(sections.map((section) => section.key)).toEqual(["analytics", "public"]);
- expect(sections[1].tables.map((t) => t.name)).toEqual(["customers", "orders"]);
- });
-
- it("puts schema-less tables in a single bare section", () => {
- const sections = groupBySchema(snapshot([table(null, "orders")]));
- expect(sections).toHaveLength(1);
- expect(sections[0].tables[0].name).toBe("orders");
- });
-});
-
-describe("groupByTableGroup", () => {
- const groups: TableGroup[] = [
- { id: "order-mgmt", name: "Order Management", hue: 28, note: "Checkout." },
- { id: "product-mgmt", name: "Product Management", hue: 148, note: null },
- ];
-
- it("groups tables by their group, preserving the snapshot's group order", () => {
- const sections = groupByTableGroup(snapshot([
- table("product", "products", "product-mgmt"),
- table("core", "orders", "order-mgmt"),
- ], groups));
-
- expect(sections.map((section) => section.key)).toEqual(["order-mgmt", "product-mgmt"]);
- expect(sections[0].label).toBe("Order Management");
- expect(sections[0].hue).toBe(28);
- expect(sections[0].note).toBe("Checkout.");
- });
-
- it("collects ungrouped tables into a trailing (no group) section", () => {
- const sections = groupByTableGroup(snapshot([
- table("core", "orders", "order-mgmt"),
- table("core", "users", null),
- ], groups));
-
- const last = sections[sections.length - 1];
- expect(last.key).toBe("");
- expect(last.hue).toBeNull();
- expect(last.tables.map((t) => t.name)).toEqual(["users"]);
- });
-
- it("omits a group that has no members", () => {
- // render_group in the serializer skips empty groups; the viewer must not
- // show an empty header where the DBML shows nothing.
- const sections = groupByTableGroup(snapshot([table("core", "orders", "order-mgmt")], groups));
- expect(sections.map((section) => section.key)).not.toContain("product-mgmt");
- });
-
- it("treats a table whose groupId names no group as ungrouped", () => {
- const sections = groupByTableGroup(snapshot([table("core", "orders", "ghost")], groups));
- expect(sections).toHaveLength(1);
- expect(sections[0].key).toBe("");
- });
-});
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/docsIndex.spec.ts
-```
-Expected: FAIL — cannot resolve `../docsIndex`.
-
-- [ ] **Step 3: Implement**
-
-```ts
-import type { DocTable, SchemaSnapshot } from "./types";
-
-export interface IndexSection {
- /** Schema name, group id, or "" for the ungrouped bucket. */
- key: string;
- label: string;
- /** Group hue, or null for schema sections and the ungrouped bucket. */
- hue: number | null;
- note: string | null;
- tables: DocTable[];
-}
-
-function byName(a: DocTable, b: DocTable): number {
- return a.name.localeCompare(b.name);
-}
-
-export function groupBySchema(snapshot: SchemaSnapshot): IndexSection[] {
- const sections = new Map<string, DocTable[]>();
- for (const table of snapshot.tables) {
- const key = table.schema ?? "";
- const bucket = sections.get(key);
- if (bucket) {
- bucket.push(table);
- } else {
- sections.set(key, [table]);
- }
- }
-
- return [...sections.entries()]
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([key, tables]) => ({
- key,
- label: key,
- hue: null,
- note: null,
- tables: [...tables].sort(byName),
- }));
-}
-
-export function groupByTableGroup(snapshot: SchemaSnapshot): IndexSection[] {
- const known = new Map(snapshot.groups.map((group) => [group.id, group]));
- const sections: IndexSection[] = [];
-
- // Snapshot order is the notes file's order — the user's own arrangement.
- for (const group of snapshot.groups) {
- const tables = snapshot.tables.filter((table) => table.groupId === group.id).sort(byName);
- // An empty group renders nothing, matching render_group in the serializer.
- if (tables.length === 0) {
- continue;
- }
- sections.push({
- key: group.id,
- label: group.name,
- hue: group.hue,
- note: group.note,
- tables,
- });
- }
-
- // A groupId naming no known group is treated as ungrouped rather than
- // creating a phantom section.
- const ungrouped = snapshot.tables
- .filter((table) => table.groupId === null || !known.has(table.groupId))
- .sort(byName);
-
- if (ungrouped.length > 0) {
- sections.push({ key: "", label: "(no group)", hue: null, note: null, tables: ungrouped });
- }
-
- return sections;
-}
-```
-
-- [ ] **Step 4: Run it and watch it pass**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/docsIndex.spec.ts
-```
-Expected: PASS, 6 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs
-git add apps/desktop/src/docs/
-git commit -m "feat(docs): add index grouping for the docs viewer"
-```
-
----
-
-## Task 4: Warning presentation
-
-**Files:**
-- Create: `apps/desktop/src/docs/docsWarnings.ts`
-- Test: `apps/desktop/src/docs/__tests__/docsWarnings.spec.ts`
-
-**Interfaces:**
-- Produces: `describeWarning(warning: SnapshotWarning): WarningNotice`, `interface WarningNotice { severity: "info" | "warning"; title: string; detail: string }`
-
-**Why this matters:** the feature's stated principle is "degrade visibly, never silently". These strings are how degradation becomes visible. A warning rendered as `[object Object]` — which is what happens if the camelCase discriminant is mismatched — defeats the whole mechanism.
-
-- [ ] **Step 1: Write the failing test**
-
-```ts
-import { describe, expect, it } from "vitest";
-import { describeWarning } from "../docsWarnings";
-import type { SnapshotWarning } from "../types";
-
-describe("describeWarning", () => {
- it("explains a skipped table as a warning naming the table and reason", () => {
- const notice = describeWarning({ kind: "tableSkipped", table: "public.secret", reason: "permission denied" });
- expect(notice.severity).toBe("warning");
- expect(notice.detail).toContain("public.secret");
- expect(notice.detail).toContain("permission denied");
- });
-
- it("explains missing foreign-key metadata as an engine limitation, not a fault", () => {
- const notice = describeWarning({ kind: "noForeignKeyMetadata", engine: "ClickHouse" });
- expect(notice.detail).toContain("ClickHouse");
- // The diagram will have no edges — the user must learn why.
- expect(notice.detail.toLowerCase()).toContain("relationship");
- });
-
- it("explains unsupported comments", () => {
- const notice = describeWarning({ kind: "commentsUnsupported", engine: "SQLite" });
- expect(notice.detail).toContain("SQLite");
- });
-
- it("reports orphaned notes with the count", () => {
- const notice = describeWarning({ kind: "orphanedNotes", count: 3 });
- expect(notice.detail).toContain("3");
- });
-
- it("explains a DBML omission naming the item", () => {
- const notice = describeWarning({
- kind: "dbmlOmitted",
- table: "public.orders",
- item: "idx_orders_open",
- reason: "partial index filter has no DBML equivalent",
- });
- expect(notice.severity).toBe("info");
- expect(notice.detail).toContain("idx_orders_open");
- });
-
- it("never returns an empty or placeholder string for any known kind", () => {
- const samples: SnapshotWarning[] = [
- { kind: "tableSkipped", table: "t", reason: "r" },
- { kind: "noForeignKeyMetadata", engine: "e" },
- { kind: "commentsUnsupported", engine: "e" },
- { kind: "orphanedNotes", count: 1 },
- { kind: "dbmlOmitted", table: "t", item: "i", reason: "r" },
- ];
- for (const sample of samples) {
- const notice = describeWarning(sample);
- expect(notice.title.length, `empty title for ${sample.kind}`).toBeGreaterThan(0);
- expect(notice.detail.length, `empty detail for ${sample.kind}`).toBeGreaterThan(0);
- expect(notice.detail).not.toContain("[object Object]");
- expect(notice.detail).not.toContain("undefined");
- }
- });
-});
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/docsWarnings.spec.ts
-```
-Expected: FAIL — cannot resolve `../docsWarnings`.
-
-- [ ] **Step 3: Implement**
-
-```ts
-import type { SnapshotWarning } from "./types";
-
-export interface WarningNotice {
- severity: "info" | "warning";
- title: string;
- detail: string;
-}
-
-/**
- * Turn a snapshot warning into something a reader can act on.
- *
- * This is where "degrade visibly, never silently" becomes literal: if a table
- * could not be read, or an engine cannot report relationships, the reader has
- * to learn that from the page rather than infer it from an absence.
- */
-export function describeWarning(warning: SnapshotWarning): WarningNotice {
- switch (warning.kind) {
- case "tableSkipped":
- return {
- severity: "warning",
- title: "A table could not be documented",
- detail: `${warning.table} was skipped: ${warning.reason}. It is missing from this documentation.`,
- };
- case "noForeignKeyMetadata":
- return {
- severity: "info",
- title: "No relationships available",
- detail: `${warning.engine} does not report foreign key metadata, so no relationship edges could be derived. The diagram is complete for this engine.`,
- };
- case "commentsUnsupported":
- return {
- severity: "info",
- title: "Database comments unavailable",
- detail: `${warning.engine} does not support table or column comments, so every description here comes from this project's own notes.`,
- };
- case "orphanedNotes":
- return {
- severity: "warning",
- title: "Some notes no longer match anything",
- detail: `${warning.count} note(s) refer to a table or column that no longer exists. Nothing was deleted — re-map or remove them in the notes file.`,
- };
- case "dbmlOmitted":
- return {
- severity: "info",
- title: "Not representable in DBML",
- detail: `${warning.item} on ${warning.table} is documented here but omitted from the exported DBML: ${warning.reason}.`,
- };
- }
-}
-```
-
-- [ ] **Step 4: Run it and watch it pass**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/docsWarnings.spec.ts
-```
-Expected: PASS, 6 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs
-git add apps/desktop/src/docs/
-git commit -m "feat(docs): describe snapshot warnings for the viewer"
-```
-
----
-
-## Task 5: Search
-
-**Files:**
-- Create: `apps/desktop/src/docs/docsSearch.ts`
-- Test: `apps/desktop/src/docs/__tests__/docsSearch.spec.ts`
-
-**Interfaces:**
-- Produces: `searchDocs(snapshot, query): SearchHit[]`, `interface SearchHit { kind: "table" | "column" | "group" | "enum"; label: string; context: string; tableKey: string | null }`
-
-This is the ⌘K palette from the approved mock.
-
-- [ ] **Step 1: Write the failing test**
-
-```ts
-import { describe, expect, it } from "vitest";
-import { searchDocs } from "../docsSearch";
-import type { DocTable, SchemaSnapshot } from "../types";
-
-function column(name: string) {
- return {
- name, data_type: "text", is_nullable: true, column_default: null,
- is_primary_key: false, extra: null,
- };
-}
-
-function table(schema: string, name: string, columns: string[] = []): DocTable {
- return {
- schema, name, kind: "TABLE", columns: columns.map(column), indexes: [], foreignKeys: [],
- groupId: null, note: null, noteSource: "NONE", shadowedNote: null,
- columnNotes: {}, estimatedRows: null, viewDefinition: null,
- };
-}
-
-const snapshot: SchemaSnapshot = {
- formatVersion: 1,
- project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },
- tables: [table("public", "orders", ["status", "total"]), table("public", "customers", ["status"])],
- relationships: [],
- groups: [{ id: "g1", name: "Order Management", hue: 28, note: null }],
- enums: [{ schema: "public", name: "order_status", values: ["pending"], note: null, synthesized: false }],
- warnings: [],
-};
-
-describe("searchDocs", () => {
- it("returns nothing for an empty query", () => {
- expect(searchDocs(snapshot, "")).toEqual([]);
- expect(searchDocs(snapshot, " ")).toEqual([]);
- });
-
- it("matches table names case-insensitively", () => {
- const hits = searchDocs(snapshot, "ORD");
- expect(hits.some((hit) => hit.kind === "table" && hit.label === "orders")).toBe(true);
- });
-
- it("matches columns and reports which table they belong to", () => {
- const hits = searchDocs(snapshot, "total");
- const hit = hits.find((candidate) => candidate.kind === "column");
- expect(hit).toBeDefined();
- expect(hit!.label).toBe("total");
- expect(hit!.context).toContain("orders");
- });
-
- it("returns one hit per table for a column name shared by several tables", () => {
- const hits = searchDocs(snapshot, "status").filter((hit) => hit.kind === "column");
- expect(hits).toHaveLength(2);
- expect(hits.map((hit) => hit.context).sort()).toEqual(["public.customers", "public.orders"]);
- });
-
- it("matches groups and enums", () => {
- expect(searchDocs(snapshot, "Order Man").some((hit) => hit.kind === "group")).toBe(true);
- expect(searchDocs(snapshot, "order_status").some((hit) => hit.kind === "enum")).toBe(true);
- });
-
- it("ranks table matches above column matches for the same term", () => {
- // Someone typing "orders" almost always wants the table.
- const hits = searchDocs(snapshot, "orders");
- expect(hits[0].kind).toBe("table");
- });
-
- it("carries a tableKey so a hit can navigate", () => {
- const hit = searchDocs(snapshot, "total").find((candidate) => candidate.kind === "column");
- expect(hit!.tableKey).toBe("public.orders");
- });
-});
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/docsSearch.spec.ts
-```
-Expected: FAIL — cannot resolve `../docsSearch`.
-
-- [ ] **Step 3: Implement**
-
-```ts
-import type { SchemaSnapshot } from "./types";
-
-export interface SearchHit {
- kind: "table" | "column" | "group" | "enum";
- label: string;
- /** Where the hit lives — a qualified table name, or a count for groups. */
- context: string;
- /** Qualified table name for navigation, or null for groups and enums. */
- tableKey: string | null;
-}
-
-function qualified(schema: string | null, name: string): string {
- return schema ? `${schema}.${name}` : name;
-}
-
-/**
- * Case-insensitive substring search over the whole snapshot.
- *
- * Tables rank first: someone typing a table's name almost always wants the
- * table, not a column that happens to share the word.
- */
-export function searchDocs(snapshot: SchemaSnapshot, query: string): SearchHit[] {
- const needle = query.trim().toLowerCase();
- if (needle.length === 0) {
- return [];
- }
-
- const tables: SearchHit[] = [];
- const columns: SearchHit[] = [];
-
- for (const table of snapshot.tables) {
- const key = qualified(table.schema, table.name);
- if (table.name.toLowerCase().includes(needle)) {
- tables.push({ kind: "table", label: table.name, context: key, tableKey: key });
- }
- for (const column of table.columns) {
- if (column.name.toLowerCase().includes(needle)) {
- columns.push({ kind: "column", label: column.name, context: key, tableKey: key });
- }
- }
- }
-
- const groups: SearchHit[] = snapshot.groups
- .filter((group) => group.name.toLowerCase().includes(needle))
- .map((group) => ({
- kind: "group",
- label: group.name,
- context: `${snapshot.tables.filter((table) => table.groupId === group.id).length} tables`,
- tableKey: null,
- }));
-
- const enums: SearchHit[] = snapshot.enums
- .filter((value) => value.name.toLowerCase().includes(needle))
- .map((value) => ({
- kind: "enum",
- label: value.name,
- context: `${value.values.length} values`,
- tableKey: null,
- }));
-
- return [...tables, ...columns, ...groups, ...enums];
-}
-```
-
-- [ ] **Step 4: Run it and watch it pass**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/docsSearch.spec.ts
-```
-Expected: PASS, 7 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs
-git add apps/desktop/src/docs/
-git commit -m "feat(docs): add client-side search for the docs viewer"
-```
-
----
-
-## Task 6: Group colour
-
-**Files:**
-- Create: `apps/desktop/src/docs/groupColor.ts`
-- Test: `apps/desktop/src/docs/__tests__/groupColor.spec.ts`
-
-**Interfaces:**
-- Produces: `groupStyle(hue: number | null): Record<string, string>`
-
-**The design rule:** a group stores ONE number, a hue. Lightness and chroma are fixed per theme in CSS, so every hue is legible on both light and dark grounds by construction. The viewer must never compute hex — that would defeat the whole scheme and reintroduce the dark-mode mud problem the mock solved.
-
-- [ ] **Step 1: Write the failing test**
-
-```ts
-import { describe, expect, it } from "vitest";
-import { groupStyle } from "../groupColor";
-
-describe("groupStyle", () => {
- it("exposes the hue as a CSS custom property", () => {
- expect(groupStyle(28)).toEqual({ "--h": "28" });
- });
-
- it("returns no custom property for an ungrouped section", () => {
- expect(groupStyle(null)).toEqual({});
- });
-
- it("wraps hues into 0-359 rather than emitting an out-of-range value", () => {
- expect(groupStyle(360)).toEqual({ "--h": "0" });
- expect(groupStyle(388)).toEqual({ "--h": "28" });
- expect(groupStyle(-1)).toEqual({ "--h": "359" });
- });
-
- it("never emits a colour value", () => {
- // Lightness and chroma belong to the theme. If this function ever returns
- // a hex or oklch string, the dark-mode contrast guarantee is gone.
- const style = groupStyle(200);
- const serialized = JSON.stringify(style);
- expect(serialized).not.toContain("#");
- expect(serialized).not.toContain("oklch");
- expect(serialized).not.toContain("rgb");
- });
-
- it("coerces a non-integer hue to an integer", () => {
- expect(groupStyle(28.7)).toEqual({ "--h": "28" });
- });
-});
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/groupColor.spec.ts
-```
-Expected: FAIL — cannot resolve `../groupColor`.
-
-- [ ] **Step 3: Implement**
-
-```ts
-/**
- * Inline style exposing a table group's hue to CSS.
- *
- * A group stores ONE number. Lightness and chroma are fixed per theme in the
- * stylesheet — `--group-c: oklch(0.55 0.15 var(--h))` in light,
- * `oklch(0.76 0.13 var(--h))` in dark — so every hue is legible on both
- * grounds by construction. Computing a colour here would throw that away.
- */
-export function groupStyle(hue: number | null): Record<string, string> {
- if (hue === null) {
- return {};
- }
- const wrapped = ((Math.trunc(hue) % 360) + 360) % 360;
- return { "--h": String(wrapped) };
-}
-```
-
-- [ ] **Step 4: Run it and watch it pass**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/groupColor.spec.ts
-```
-Expected: PASS, 5 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs
-git add apps/desktop/src/docs/
-git commit -m "feat(docs): expose group hue as a CSS custom property"
-```
-
----
-
-## Task 7: Note markdown rendering
-
-> **This brief was corrected by the controller after empirically probing `[email protected]`.**
-> The original plan text contained three defects: an assertion that fails against a correct
-> implementation, a suggested approach that double-escapes HTML entities, and a URL filter
-> with several live bypasses. Everything below has been run against the installed `marked`
-> and its exact output verified. Use it verbatim.
-
-**Files:**
-- Create: `apps/desktop/src/docs/renderNote.ts`
-- Test: `apps/desktop/src/docs/__tests__/renderNote.spec.ts`
-
-**Interfaces:**
-- Produces: `renderNote(markdown: string | null): string`
-
-**Notes are markdown.** `[email protected]` is already a dependency — do NOT add one, and do NOT
-add a sanitiser (no DOMPurify).
-
-**This is the security-relevant task in Part 3a.** Note text comes from two places, and one of
-them — `COMMENT ON` values — lives in the *database*, which is not always under the document
-author's control. In Part 3b the same renderer runs inside a standalone HTML file people forward
-to colleagues. So raw HTML must be escaped, not rendered, and unsafe URL schemes must be dropped.
-
-**Verified facts about `marked@18` you must not re-derive:**
-- It escapes nothing by default. `<script>alert(1)</script>` passes straight through.
-- It does **not** block `javascript:`, `vbscript:`, or `data:` URLs in links or images.
-- Pre-escaping the source string before parsing is **wrong** — it double-escapes entities, so
- `a &amp; b` renders as the literal text `a &amp; b` instead of `a & b`.
-- In the `link` renderer, the `text` property is the **raw markdown source**, not parsed HTML.
- Returning it directly is an XSS hole and also breaks `**bold**` inside link text. You must use
- `this.parser.parseInline(tokens)` instead.
-
-- [ ] **Step 1: Write the failing test**
-
-```ts
-import { describe, expect, it } from "vitest";
-import { renderNote } from "../renderNote";
-
-describe("renderNote", () => {
- it("renders ordinary markdown", () => {
- expect(renderNote("One row per **checkout**.")).toContain("<strong>checkout</strong>");
- });
-
- it("renders inline code and fenced blocks", () => {
- expect(renderNote("see `order_status`")).toContain("<code>order_status</code>");
- expect(renderNote("```sql\nSELECT 1;\n```")).toContain("<pre>");
- });
-
- it("returns an empty string for null or blank input", () => {
- expect(renderNote(null)).toBe("");
- expect(renderNote(" ")).toBe("");
- });
-
- it("escapes a script tag rather than rendering it", () => {
- const html = renderNote("<script>alert(1)</script>");
- expect(html).not.toContain("<script>");
- expect(html).toContain("&lt;script&gt;");
- });
-
- it("escapes an img onerror payload", () => {
- // NB: asserting !contains("onerror=") would FAIL against a correct
- // implementation — the escaped text legitimately still contains that
- // substring. What matters is that no <img> ELEMENT is produced.
- const html = renderNote('<img src=x onerror="alert(1)">');
- expect(html.toLowerCase()).not.toContain("<img");
- expect(html).toContain("&lt;img");
- });
-
- it("escapes raw HTML even when it looks harmless", () => {
- // Blanket rule: no author-supplied HTML is rendered, ever. A rule with
- // exceptions is a rule someone will find a way around.
- const html = renderNote("<b>bold</b>");
- expect(html).not.toContain("<b>bold</b>");
- expect(html).toContain("&lt;b&gt;");
- });
-
- it("does not preserve HTML entities twice", () => {
- // Guards the pre-escaping approach, which turns "a &amp; b" into
- // "a &amp;amp; b" and renders the entity visibly to the reader.
- expect(renderNote("a &amp; b")).toContain("a &amp; b");
- expect(renderNote("a &amp; b")).not.toContain("&amp;amp;");
- });
-
- it.each([
- ["javascript:alert(1)", "javascript"],
- ["JaVaScRiPt:alert(1)", "javascript"],
- ["&#106;avascript:alert(1)", "avascript"],
- ["vbscript:alert(1)", "vbscript"],
- ["data:text/html;base64,PHNjcmlwdD4=", "data:"],
- ])("drops the unsafe link scheme %s", (href, forbidden) => {
- const html = renderNote(`[click](${href})`).toLowerCase();
- expect(html).not.toContain(forbidden);
- expect(html).toContain("click"); // the text survives; only the href is dropped
- });
-
- it("drops an unsafe image scheme", () => {
- const html = renderNote("![img](javascript:alert(1))").toLowerCase();
- expect(html).not.toContain("javascript");
- expect(html).not.toContain("<img");
- });
-
- it.each(["https://example.com", "http://example.com", "mailto:[email protected]", "#anchor", "./rel.html"])(
- "keeps the safe link target %s",
- (href) => {
- expect(renderNote(`[ok](${href})`)).toContain(`href="${href}"`);
- },
- );
-
- it("parses markdown inside link text instead of emitting it raw", () => {
- // marked hands the renderer the RAW source text. Emitting it directly
- // both breaks formatting and injects unescaped HTML.
- expect(renderNote("[**keep**](https://example.com)")).toContain("<strong>keep</strong>");
- const dropped = renderNote('[<img src=x onerror="alert(1)">](javascript:alert(1))');
- expect(dropped.toLowerCase()).not.toContain("<img");
- expect(dropped).toContain("&lt;img");
- });
-});
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/renderNote.spec.ts
-```
-Expected: FAIL — cannot resolve `../renderNote`.
-
-- [ ] **Step 3: Implement**
-
-This exact implementation was run against `[email protected]` and every assertion above verified.
-
-```ts
-import { Marked } from "marked";
-
-/** Escape the five characters that can break out of text or an attribute value. */
-function escapeHtml(value: unknown): string {
- return String(value ?? "")
- .replace(/&/g, "&amp;")
- .replace(/</g, "&lt;")
- .replace(/>/g, "&gt;")
- .replace(/"/g, "&quot;");
-}
-
-/**
- * URL allowlist. Blocklists lose: `javascript:` alone misses `JaVaScRiPt:`,
- * the entity-encoded `&#106;avascript:`, `vbscript:` and `data:text/html`.
- * Permitting only what we understand is both shorter and complete.
- */
-const SAFE_SCHEME = /^(https?:|mailto:)/i;
-
-function safeUrl(raw: unknown): string | null {
- const url = String(raw ?? "").trim();
- if (url === "") {
- return null;
- }
- if (url.startsWith("#") || url.startsWith("/") || url.startsWith("./") || url.startsWith("../")) {
- return url;
- }
- return SAFE_SCHEME.test(url) ? url : null;
-}
-
-const renderer = new Marked({
- renderer: {
- // Raw HTML in the source is shown as text, never rendered.
- html({ text }) {
- return escapeHtml(text);
- },
- link({ href, title, tokens }) {
- // `tokens`, not `text` — `text` is the raw markdown source, so returning
- // it would emit author HTML unescaped and swallow inline formatting.
- const inner = this.parser.parseInline(tokens);
- const safe = safeUrl(href);
- if (safe === null) {
- return inner;
- }
- const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";
- return `<a href="${escapeHtml(safe)}"${titleAttr}>${inner}</a>`;
- },
- image({ href, title, text }) {
- const safe = safeUrl(href);
- if (safe === null) {
- return escapeHtml(text);
- }
- const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";
- return `<img src="${escapeHtml(safe)}" alt="${escapeHtml(text)}"${titleAttr}>`;
- },
- },
-});
-
-/** Render a note's markdown to HTML with all author-supplied HTML escaped. */
-export function renderNote(markdown: string | null): string {
- if (markdown === null || markdown.trim() === "") {
- return "";
- }
- return renderer.parse(markdown) as string;
-}
-```
-
-If `vue-tsc` objects to the renderer callback signatures, fix the types rather than the
-behaviour, and report what you changed. Do NOT loosen the escaping to satisfy the compiler.
-
-- [ ] **Step 4: Run it and watch it pass**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/renderNote.spec.ts
-```
-
-- [ ] **Step 5: Verify the guards are real — three deliberate breaks**
-
-One at a time, restoring between each. Report each failure message.
-
-1. Delete the `html` renderer override entirely → the script-tag, img and `<b>` tests must fail.
-2. Change `safeUrl` to `return url;` unconditionally → the unsafe-scheme cases must fail.
-3. In `link`, replace `this.parser.parseInline(tokens)` with the token's `text` property →
- the "parses markdown inside link text" test must fail.
-
-If any deliberate break does NOT produce a failure, stop and tell me — that means the test is
-not actually pinning the guard, which is the exact defect this step exists to catch.
-
-- [ ] **Step 6: Commit**
-
-```bash
-pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs
-git add apps/desktop/src/docs/
-git commit -m "feat(docs): render note markdown with raw HTML escaped"
-```
-
-Confirm `git status` is clean after your restores, so no deliberate break leaks into the commit.
-
----
-
-## Task 8: Components
-
-**Files:**
-- Create: `apps/desktop/src/docs/DocsApp.vue`
-- Create: `apps/desktop/src/docs/components/DocsSidebar.vue`, `WikiIndex.vue`, `TablePage.vue`, `ColumnTable.vue`, `RelationshipList.vue`, `WarningBanner.vue`, `DocsSearch.vue`
-- Test: `apps/desktop/src/docs/__tests__/componentContract.spec.ts`
-
-Templates only. Every decision they display comes from Tasks 3-7. The visual reference is the approved mock: sidebar with the Group-by switch, wiki index with inline notes, table page with columns / indexes / bidirectional relationships, the `⬤ LOCAL` shadow marker, and the warning banner.
-
-**Because this repo has no component-mount harness, verification is static SFC parsing** — copy the technique from `packages/app-tests/aiAssistantSendGuard.test.ts` (`readFileSync` + `parse` from `vue/compiler-sfc`).
-
-- [ ] **Step 1: Write the contract test**
-
-```ts
-import { readdirSync, readFileSync } from "node:fs";
-import path from "node:path";
-import { describe, expect, it } from "vitest";
-import { parse } from "vue/compiler-sfc";
-
-const docsRoot = path.resolve(__dirname, "..");
-
-function vueFiles(): string[] {
- const found: string[] = [];
- const walk = (dir: string) => {
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
- const full = path.join(dir, entry.name);
- if (entry.isDirectory() && entry.name !== "__tests__" && entry.name !== "fixtures") {
- walk(full);
- } else if (entry.isFile() && entry.name.endsWith(".vue")) {
- found.push(full);
- }
- }
- };
- walk(docsRoot);
- return found;
-}
-
-function scriptOf(file: string): string {
- const { descriptor } = parse(readFileSync(file, "utf8"), { filename: file });
- return `${descriptor.script?.content ?? ""}\n${descriptor.scriptSetup?.content ?? ""}`;
-}
-
-describe("docs viewer component contract", () => {
- it("finds the expected components", () => {
- const names = vueFiles().map((file) => path.basename(file)).sort();
- expect(names).toContain("DocsApp.vue");
- expect(names).toContain("DocsSidebar.vue");
- expect(names).toContain("WikiIndex.vue");
- expect(names).toContain("TablePage.vue");
- expect(names).toContain("WarningBanner.vue");
- });
-
- it("makes no backend calls", () => {
- // The whole point of this directory: snapshot in, DOM out. If a component
- // ever reaches for the backend, the same code cannot run inside an
- // exported HTML file on a machine that has never installed DBX.
- const forbidden = [
- "@/lib/backend",
- "@tauri-apps",
- "invoke(",
- "useConnectionStore",
- "useQueryStore",
- "useSettingsStore",
- "fetch(",
- "axios",
- ];
- for (const file of vueFiles()) {
- const script = scriptOf(file);
- for (const needle of forbidden) {
- expect(script.includes(needle), `${path.basename(file)} must not reference ${needle}`).toBe(false);
- }
- }
- });
-
- it("keeps colour decisions out of templates", () => {
- // Hue -> CSS belongs in groupColor.ts so the theme keeps control of
- // lightness and chroma.
- for (const file of vueFiles()) {
- const source = readFileSync(file, "utf8");
- expect(source.includes("oklch("), `${path.basename(file)} must not compute colour`).toBe(false);
- }
- });
-
- it("uses <script setup lang=\"ts\">", () => {
- for (const file of vueFiles()) {
- const { descriptor } = parse(readFileSync(file, "utf8"), { filename: file });
- expect(descriptor.scriptSetup, `${path.basename(file)} must use <script setup>`).toBeTruthy();
- expect(descriptor.scriptSetup?.lang, `${path.basename(file)} must be TypeScript`).toBe("ts");
- }
- });
-});
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/componentContract.spec.ts
-```
-Expected: FAIL — no `.vue` files exist yet.
-
-- [ ] **Step 3: Build the components**
-
-Write the seven components as thin templates. Rules:
-
-- `DocsApp.vue` takes a single prop `snapshot: SchemaSnapshot` and a `readonly = true` prop, holds the current view (`index` | `table`) and the group-by mode, and renders the others. No editing affordances in Part 3a — `readonly` exists so Part 3b can flip it.
-- `DocsSidebar.vue` renders the `Group by: Schemas | Table Groups` segmented control and the section list, using `groupBySchema` / `groupByTableGroup` from Task 3 and `groupStyle` from Task 6.
-- `WikiIndex.vue` renders each section header (name, count, note) and its table list.
-- `TablePage.vue` renders the table's note with a `⬤ LOCAL` marker when `noteSource === "LOCAL"`, the shadowed database comment in a `title` attribute when `shadowedNote` is present, then `ColumnTable`, indexes, and `RelationshipList`.
-- `ColumnTable.vue` renders name / type / settings / note, reading notes from `columnNotes` by the column's real name.
-- `RelationshipList.vue` renders outgoing and incoming relationships in two lists, derived from `snapshot.relationships` filtered on the current table.
-- `WarningBanner.vue` renders `describeWarning` output from Task 4.
-- `DocsSearch.vue` renders the ⌘K palette using `searchDocs` from Task 5.
-
-Style with Tailwind classes and DBX's existing token names (`bg-background`, `text-foreground`, `border-border`, `text-muted-foreground`). Group colours come only from `var(--group-c)` / `var(--group-tint)` driven by the `--h` custom property.
-
-- [ ] **Step 4: Run the contract test**
-
-```bash
-pnpm vitest run apps/desktop/src/docs/__tests__/componentContract.spec.ts
-```
-Expected: PASS, 4 tests.
-
-- [ ] **Step 5: Run everything and lint**
-
-```bash
-pnpm vitest run apps/desktop/src/docs
-pnpm exec oxlint --vue-plugin apps/desktop/src/docs
-pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
-```
-All must pass. `vue-tsc` is the only thing that type-checks the templates, so it is doing the work a mount test would otherwise do — report any error rather than suppressing it.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add apps/desktop/src/docs/
-git commit -m "feat(docs): add docs viewer components"
-```
-
----
-
-## Done criteria
-
-- `apps/desktop/src/docs/` contains a viewer that renders a `SchemaSnapshot` with zero backend calls, enforced by a test.
-- Every decision (grouping, search, warning text, group colour) lives in a tested `.ts` module.
-- A fixture generated from real Rust output guards the hand-maintained TS types against drift.
-- `pnpm vitest run apps/desktop/src/docs` passes; `vue-tsc` and `oxlint` are clean.
-
-## Deferred to Part 3b
-
-- Mounting the viewer inside DBX (`DatabaseDocsDialog.vue`) and the editing affordances behind `readonly=false`.
-- The standalone Vite bundle, the committed `docs-viewer.js` artifact, and the self-contained HTML export — including inlining the real Geist font, which IS in the repo at `apps/desktop/public/fonts/geist-latin-wght-normal.woff2`.
-- The `dbx docs` CLI verb.
-- Hash routing (`#/table/public.orders`). Part 3a keeps the current view in `DocsApp` state; hash routing belongs with the standalone entry point, since its whole purpose is surviving a `file://` load.
-- The `EnumPage` view listing enum values.
-- The ER diagram view (reuses `layoutDiagramTables` from `lib/diagram/erDiagram.ts`, which imports only types and is therefore safe for the standalone bundle).
-- i18n: Part 3a hardcodes English strings in `docsWarnings.ts`; Part 3b extracts them into a `docs` namespace across all 8 locales.
-
----
-
-## Appendix: Corrections found during execution
-
-Defects in this plan's own text, found while executing it. Recorded by failure mode rather than
-by task, because the modes repeat and the tasks do not. Every one originated in the plan; none
-was an implementer error.
-
-### Mode 1 — a test whose fixture cannot distinguish the property from its negation
-
-The most common failure by a wide margin, and the hardest to see on a green run. The assertion
-names a real property; the data supplied cannot tell that property apart from its opposite.
-
-- **Task 5, ranking.** `expect(hits[0].kind).toBe("table")` for query `"orders"`. No column in
- the fixture contained that substring, so exactly one hit came back and the assertion held
- trivially. Reversing the concatenation order produced byte-identical output. Fixed by adding an
- `orders_count` column to a second table so the query yields both kinds, and by asserting
- `indexOf(first table) < indexOf(first column)` instead of inspecting element zero.
-- **Task 5, case-insensitivity.** Every identifier in the fixture was already lowercase, so a
- mutant lowercasing only the needle and not each candidate passed all seven tests. Fixed by
- adding a mixed-case `Invoices` table and `Amount` column.
-
-**The lesson:** write the assertion, then ask what fixture would make it fail. If no such fixture
-exists, the test is decorative. Watching the test fail once is the only cheap proof.
-
-### Mode 2 — an assertion that fails against a *correct* implementation
-
-- **Task 7.** `expect(html).not.toContain("onerror=")` for the input `<img src=x onerror="…">`.
- Correctly escaped output is `&lt;img src=x onerror=&quot;alert(1)&quot;&gt;`, which legitimately
- contains that substring as inert text. The test would have driven an implementer to strip
- attributes from text content — wrong, and a plausible route to breaking the escaping entirely.
- Fixed by asserting no `<img` *element* is produced and that `&lt;img` is present.
-
-**The lesson:** an assertion about a security property must target the dangerous *structure*, not
-a scary-looking *string*. Escaped text is supposed to still read like the attack.
-
-### Mode 3 — offering two approaches as equivalent when one is broken
-
-- **Task 7.** Step 3 presented "escape the source before parsing" and "override the renderer's
- html hook" as interchangeable. Pre-escaping double-escapes entities: `a &amp; b` renders as the
- literal text `a &amp; b`. Fixed by mandating the renderer hook and stating why.
-
-**The lesson:** when a plan says "either approach works", it usually means neither was tested.
-
-### Mode 4 — a blocklist where an allowlist was needed
-
-- **Task 7.** The instruction was to drop any `href` starting with `javascript:` after trimming and
- lowercasing. Probing `[email protected]` showed it blocks nothing and emits verbatim hrefs for
- `JaVaScRiPt:`, the entity-encoded `&#106;avascript:` (which the browser decodes and fires),
- `vbscript:`, and `data:text/html;base64,…`. The instruction also covered only `href`, never
- `<img src>`. Replaced with an allowlist of `https?:`, `mailto:`, and relative/anchor forms —
- shorter than the blocklist and complete without enumerating a single bypass.
-
-**The lesson:** enumerating what is forbidden requires knowing every attack; enumerating what is
-permitted requires knowing only the feature.
-
-### Mode 5 — assuming a library parameter contains what its name suggests
-
-- **Task 7.** Found while verifying the *replacement* for Mode 4, not in the original text. In
- `marked@18` the `link` renderer's `text` property is the **raw markdown source**, not the parsed
- inner HTML. Returning it emits author HTML unescaped — `[<img src=x onerror=…>](javascript:…)`
- renders a live element even though the URL was correctly dropped — and it also swallows inline
- formatting, so `[**keep**](…)` loses its emphasis. Fixed with `this.parser.parseInline(tokens)`.
-
-**The lesson:** the first ten payloads all put the attack in the URL, because that is where the
-danger was assumed to be. The hole was in the field nobody was thinking about. Passing security
-tests confirm the threat model they were written from; they do not probe it.
-
-### Mode 6 — a verification step that verifies nothing
-
-- **Task 1.** The drift check instructed renaming `types.ts` to confirm the conformance test would
- catch schema drift. Renaming the type file breaks the *import*, which fails for reasons having
- nothing to do with drift. Caught by the implementer, who proposed mutating the fixture instead —
- the only change that actually exercises the check. Fixed in the executed task.
diff --git a/docs/superpowers/plans/2026-08-06-database-documentation-export.md b/docs/superpowers/plans/2026-08-06-database-documentation-export.md
deleted file mode 100644
index 30c25997b3..0000000000
--- a/docs/superpowers/plans/2026-08-06-database-documentation-export.md
+++ /dev/null
@@ -1,1631 +0,0 @@
-# Standalone Documentation Export Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Produce one self-contained HTML file — from a `dbx docs` CLI verb and from a button in the app — that renders a database's documentation from `file://` on a machine with no DBX installed.
-
-**Architecture:** The existing pure viewer under `apps/desktop/src/docs/` is bundled by a dedicated Vite entry into one JS and one CSS file, committed into `crates/dbx-core/assets/` and embedded with `include_str!`. A Rust function `to_standalone_html` base64-encodes the snapshot payload and emits the HTML; the CLI and a Tauri command both call it. A build-derived manifest makes the committed artefact unable to drift from its sources without a test failing.
-
-**Tech Stack:** Rust (dbx-core, dbx-cli, Tauri), Vue 3.5 `<script setup lang="ts">`, Vite 8, Tailwind v4, vitest 4 + happy-dom 20, `base64 0.22` and `sha2 0.10` (both already dbx-core dependencies).
-
-## Global Constraints
-
-- **No new dependencies.** `base64 0.22` and `sha2 0.10` are already in `crates/dbx-core/Cargo.toml` (lines 61 and 67). `happy-dom ^20.10.6` is already a devDependency. Adding anything else requires explicit approval.
-- **`apps/desktop/src/docs/**/*.vue` must make zero backend calls.** Enforced by `apps/desktop/src/docs/__tests__/componentContract.spec.ts`, whose forbidden list is `["@/lib/backend", "@tauri-apps", "invoke(", "useConnectionStore", "useQueryStore", "useSettingsStore", "fetch(", "axios", "vue-i18n", "useI18n("]`. Extend it; never weaken it.
-- **Every component uses `<script setup lang="ts">`.** Asserted by the same contract test.
-- **No colour computed in a component.** `oklch(` and 6-digit hex literals are banned in `src/docs/**`; hues go through `groupStyle(hue)` from `apps/desktop/src/docs/groupColor.ts`.
-- **`v-html` may only ever be bound to `renderNote` output.** Both quote styles are checked; `innerHTML` is banned outright.
-- **All 8 locales.** `en`, `es`, `it`, `ja`, `ko`, `pt-BR`, `zh-CN`, `zh-TW` in `apps/desktop/src/i18n/locales/docs/`. Parity is enforced by `apps/desktop/src/i18n/__tests__/docsNamespaceParity.spec.ts`.
-- **Tests live at** `apps/desktop/src/**/*.spec.ts` (vitest `include` at `vitest.config.ts:14`). Run one with `pnpm vitest run <path> -t "<test name>"`.
-- **Rust docs tests** run with `cargo test -p dbx-core --lib docs`.
-- **Every new test gets the deliberate-break treatment:** break the behaviour, run the named test, confirm it fails, restore, and report the exact failure message in the task report. Parts 3a and 3b caught four defects this way that no amount of reading found.
-- **Commit after every task.** Conventional Commits. End every commit message with:
- ```
- Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH
- ```
-
----
-
-## File Structure
-
-**Created**
-
-| Path | Responsibility |
-|---|---|
-| `apps/desktop/src/docs/docsRoute.ts` | Pure parse/format between a hash string and `DocsRoute` |
-| `apps/desktop/src/docs/diagramGeometry.ts` | Pure edge clipping — line from card centre to card border |
-| `apps/desktop/src/docs/components/SchemaDiagram.vue` | Minimal read-only SVG ER renderer |
-| `apps/desktop/src/docs-export/main.ts` | Export entry: decode payload, mount `ExportApp` |
-| `apps/desktop/src/docs-export/ExportApp.vue` | Export shell: hash sync, language switcher, `readonly`, `diagram="inline"` |
-| `apps/desktop/src/docs-export/exportTranslate.ts` | Build a `Translate` from a bundled locale, English fallback |
-| `apps/desktop/src/docs-export/export.css` | Tailwind entry with `@source` narrowed to `../docs/**` |
-| `apps/desktop/src/styles/tokens.css` | Design tokens extracted from `globals.css` |
-| `apps/desktop/vite.docs-export.config.ts` | Single-file bundle config, font inlining, manifest emission |
-| `crates/dbx-core/src/docs/export.rs` | `to_standalone_html` + the staleness guard test |
-| `src-tauri/src/commands/docs.rs` (modify) | `docs_export_html` command |
-
-**Modified**
-
-| Path | Change |
-|---|---|
-| `apps/desktop/src/docs/DocsApp.vue` | Optional `v-model:route`, `diagram` prop, translate its own literals |
-| `apps/desktop/src/docs/components/{DocsSidebar,DocsSearch,TablePage,ColumnTable,RelationshipList}.vue` | Accept and use `translate` |
-| `apps/desktop/src/i18n/locales/docs/*.ts` (×8) | ~18 new keys |
-| `apps/desktop/src/docs/__tests__/componentContract.spec.ts` | Add `SchemaDiagram.vue`; add the hardcoded-literal guard |
-| `apps/desktop/src/styles/globals.css` | Token blocks replaced by `@import "./tokens.css"` |
-| `crates/dbx-core/src/docs/mod.rs` | `pub mod export;` + re-export |
-| `crates/dbx-cli/src/main.rs` | `--lang` flag, `run_docs`, usage line |
-| `apps/desktop/src/lib/backend/{api,tauri,http}.ts` | `exportDocsHtml` |
-| `apps/desktop/src/components/docs/DatabaseDocsDialog.vue` | Export HTML button |
-| `crates/dbx-web/src/{main.rs,routes/docs.rs}` | `/docs/export` route |
-| `package.json` | `build:docs-export` script |
-
----
-
-## Task 1: Internationalise the viewer
-
-The `docs` namespace has 40 keys across 8 locales and a passing parity test, but most of the viewer renders English literals instead of calling them. `groupBySchema: "Schemas"` and `groupByTableGroup: "Table Groups"` exist *specifically* for `DocsSidebar.vue`, which hardcodes both words.
-
-This is a prerequisite: a language switcher over a viewer that is two-thirds hardcoded English would be worse than none. It is also a live defect in the open PR — a Chinese user opening the docs dialog today sees mostly English chrome.
-
-**Files:**
-- Modify: `apps/desktop/src/docs/DocsApp.vue`
-- Modify: `apps/desktop/src/docs/components/DocsSidebar.vue`
-- Modify: `apps/desktop/src/docs/components/DocsSearch.vue`
-- Modify: `apps/desktop/src/docs/components/TablePage.vue`
-- Modify: `apps/desktop/src/docs/components/ColumnTable.vue`
-- Modify: `apps/desktop/src/docs/components/RelationshipList.vue`
-- Modify: `apps/desktop/src/i18n/locales/docs/{en,es,it,ja,ko,pt-BR,zh-CN,zh-TW}.ts`
-- Test: `apps/desktop/src/docs/__tests__/componentContract.spec.ts`
-
-**Interfaces:**
-- Consumes: `Translate` from `apps/desktop/src/docs/docsWarnings.ts` — exactly `export type Translate = (key: string, params?: Record<string, string | number>) => string;`
-- Produces: every component under `src/docs/` accepts a required `translate: Translate` prop. Later tasks rely on `DocsSidebar` and `SchemaDiagram` having it.
-
-**Keys already present — wire these, do not re-add:** `groupBySchema`, `groupByTableGroup`, `search`, `columns`, `indexes`, `references`, `referencedBy`, `noGroup`, `noSchema`.
-
-Leave the existing `search` value (`"Search tables, columns, groups…"`) unchanged even though search now also covers enums. Rewording one clause across 8 locales invites translation drift for negligible gain, and results are already labelled by kind.
-
-- [ ] **Step 1: Write the failing guard test**
-
-Append to `apps/desktop/src/docs/__tests__/componentContract.spec.ts`, inside the existing `describe`:
-
-```ts
- it("renders no English literal that already has a key", async () => {
- // Derived from the namespace, NOT an enumerated list of strings. A key
- // added tomorrow is covered tomorrow. This is the guard Part 3b lacked:
- // docsNamespaceParity compares locale files to EACH OTHER, so a key that
- // no component ever calls passes every existing test.
- const en = (await import("../../i18n/locales/docs/en")).default as Record<string, unknown>;
- const literals: string[] = [];
- const walk = (node: unknown) => {
- if (typeof node === "string") {
- // Skip short strings (false positives on words like "LOCAL") and any
- // string carrying a placeholder, which cannot appear verbatim anyway.
- if (node.length >= 4 && !node.includes("{")) literals.push(node);
- return;
- }
- if (node && typeof node === "object") Object.values(node).forEach(walk);
- };
- walk(en);
- expect(literals.length).toBeGreaterThan(10);
-
- const files = vueFiles();
- expect(files.length).toBe(EXPECTED.length);
- for (const file of files) {
- const source = readFileSync(file, "utf8");
- for (const literal of literals) {
- expect(source.includes(`>${literal}<`), `${path.basename(file)} hardcodes "${literal}" — call translate() instead`).toBe(false);
- expect(source.includes(`="${literal}"`), `${path.basename(file)} hardcodes "${literal}" — call translate() instead`).toBe(false);
- }
- }
- });
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-Run: `pnpm vitest run apps/desktop/src/docs/__tests__/componentContract.spec.ts -t "renders no English literal"`
-
-Expected: FAIL. `DocsSidebar.vue hardcodes "Schemas" — call translate() instead: expected true to be false` (or another of the six components; any one failing is the correct starting state).
-
-- [ ] **Step 3: Add the new keys to `en.ts`**
-
-Insert into `apps/desktop/src/i18n/locales/docs/en.ts` before the `warnings:` block:
-
-```ts
- overview: "Overview",
- groupBy: "Group by",
- searchLabel: "Search",
- groups: "Groups",
- relationships: "Relationships",
- columnHeader: "Column",
- typeHeader: "Type",
- settingsHeader: "Settings",
- noteHeader: "Note",
- nameHeader: "Name",
- definitionHeader: "Definition",
- noOutgoingRelationships: "This table references no other table.",
- noIncomingRelationships: "No table references this one.",
- diagram: "Diagram",
- language: "Language",
- exportHtml: "Export HTML…",
- exporting: "Exporting…",
- exportFailed: "Could not export: {error}",
-```
-
-- [ ] **Step 4: Translate the 18 new keys into the other 7 locales**
-
-Add the same 18 keys to `es.ts`, `it.ts`, `ja.ts`, `ko.ts`, `pt-BR.ts`, `zh-CN.ts`, `zh-TW.ts`, matching each file's existing tone and terminology.
-
-**`{error}` must survive verbatim in every locale.** The Part 3b review caught that no automated test verifies placeholder preservation — parity compares key *names*, so a translated or renamed `{error}` would render literal braces to users and pass every test. Check each one by eye.
-
-- [ ] **Step 5: Wire `DocsSidebar.vue`**
-
-Add to its `defineProps`: `translate: Translate;` with `import type { Translate } from "../docsWarnings";`. Then replace the four literals:
-
-```
->Overview< → >{{ translate("docs.overview") }}<
->Group by< → >{{ translate("docs.groupBy") }}<
->Schemas< → >{{ translate("docs.groupBySchema") }}<
->Table Groups< → >{{ translate("docs.groupByTableGroup") }}<
-```
-
-- [ ] **Step 6: Wire the remaining five components**
-
-`DocsSearch.vue` — add the `translate` prop; `>Search<` becomes `{{ translate("docs.searchLabel") }}`, and `placeholder="Search tables, columns, groups, enums…"` becomes `:placeholder='translate("docs.search")'`.
-
-`TablePage.vue` — already receives `translate` and passes it down; now use it for its own headings: `Columns` → `docs.columns`, `Indexes` → `docs.indexes`, `Relationships` → `docs.relationships`, `Name` → `docs.nameHeader`, `Settings` → `docs.settingsHeader`, `Definition` → `docs.definitionHeader`.
-
-`ColumnTable.vue` — headers `Column` → `docs.columnHeader`, `Type` → `docs.typeHeader`, `Settings` → `docs.settingsHeader`, `Note` → `docs.noteHeader`.
-
-`RelationshipList.vue` — add the `translate` prop and thread it from `TablePage.vue`:
-
-```
->References ({{ outgoing.length }})< → >{{ translate("docs.references") }} ({{ outgoing.length }})<
->Referenced by ({{ incoming.length }})< → >{{ translate("docs.referencedBy") }} ({{ incoming.length }})<
->This table references no other table.< → >{{ translate("docs.noOutgoingRelationships") }}<
->No table references this one.< → >{{ translate("docs.noIncomingRelationships") }}<
-```
-
-`DocsApp.vue` — `>Groups<` becomes `{{ translate("docs.groups") }}`.
-
-- [ ] **Step 7: Run the guard, the parity test and typecheck**
-
-Run: `pnpm vitest run apps/desktop/src/docs apps/desktop/src/i18n`
-Expected: PASS, with the new guard among them.
-
-Run: `pnpm typecheck`
-Expected: clean. A missing `translate` prop on a threaded component fails here.
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add apps/desktop/src/docs apps/desktop/src/i18n
-git commit -m "$(cat <<'EOF'
-fix(docs): translate the viewer's own chrome
-
-The docs namespace has carried 40 keys across 8 locales since Part 3b, with
-a parity test that passes — but most components rendered English literals
-instead of calling them. `groupBySchema: "Schemas"` existed specifically for
-DocsSidebar, which hardcoded the word.
-
-Parity compares locale files to each other, so a key no component ever calls
-is invisible to it. The new guard derives its forbidden literals FROM the
-English namespace, so a key added later is covered without anyone
-remembering to register it.
-
-Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
-Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH
-EOF
-)"
-```
-
----
-
-## Task 2: Extract the design tokens
-
-The export's Tailwind entry cannot import `globals.css`: line 40 is `@source "../**/*.{vue,ts,tsx,js,jsx,html}"`, which scans the whole application, and `@source` is additive with no way to un-source. But the viewer's utilities still resolve against tokens defined in `globals.css` from line 131.
-
-**Files:**
-- Create: `apps/desktop/src/styles/tokens.css`
-- Modify: `apps/desktop/src/styles/globals.css`
-- Test: `apps/desktop/src/docs/__tests__/tokens.spec.ts`
-
-**Interfaces:**
-- Produces: `apps/desktop/src/styles/tokens.css`, importable by both `globals.css` and (Task 5) `export.css`.
-
-This edits a 76 KB stylesheet the whole application depends on. The move is mechanical, but **cascade order between `:root` and `.dark` must be preserved exactly** — `.dark` must still be declared after `:root`.
-
-- [ ] **Step 1: Write the failing test**
-
-Create `apps/desktop/src/docs/__tests__/tokens.spec.ts`:
-
-```ts
-import { readFileSync } from "node:fs";
-import path from "node:path";
-import { describe, expect, it } from "vitest";
-
-const stylesDir = path.resolve(__dirname, "../../styles");
-
-/** Every `--name:` custom property declared in a stylesheet. */
-function declaredTokens(file: string): Set<string> {
- const source = readFileSync(path.join(stylesDir, file), "utf8");
- return new Set(Array.from(source.matchAll(/^\s*(--[a-z0-9-]+)\s*:/gm), (match) => match[1]));
-}
-
-describe("design tokens", () => {
- it("defines the tokens the docs viewer resolves against", () => {
- // These are the utilities used in src/docs/**: bg-background,
- // text-foreground, text-muted-foreground, bg-muted, border-border,
- // focus:border-ring. If a token stops being declared here the export
- // renders unstyled while the app, which has globals.css, looks fine —
- // so this must be checked against tokens.css, not globals.css.
- const tokens = declaredTokens("tokens.css");
- for (const token of ["--background", "--foreground", "--muted", "--muted-foreground", "--border", "--ring"]) {
- expect(tokens.has(token), `tokens.css must declare ${token}`).toBe(true);
- }
- });
-
- it("keeps globals.css importing the extracted tokens", () => {
- const globals = readFileSync(path.join(stylesDir, "globals.css"), "utf8");
- expect(globals.includes('@import "./tokens.css"')).toBe(true);
- });
-
- it("declares the dark overrides after the light ones", () => {
- // Custom properties resolve at use time, but override order still
- // decides which block wins. A tokens.css with .dark BEFORE :root leaves
- // dark mode rendering light values.
- const source = readFileSync(path.join(stylesDir, "tokens.css"), "utf8");
- const root = source.search(/^:root\s*\{/m);
- const dark = source.search(/^\.dark\s*\{/m);
- expect(root, "tokens.css must declare :root").toBeGreaterThan(-1);
- expect(dark, "tokens.css must declare .dark").toBeGreaterThan(-1);
- expect(dark).toBeGreaterThan(root);
- });
-});
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-Run: `pnpm vitest run apps/desktop/src/docs/__tests__/tokens.spec.ts`
-Expected: FAIL — `ENOENT: no such file or directory, open '.../styles/tokens.css'`.
-
-- [ ] **Step 3: Move the token blocks**
-
-Read `apps/desktop/src/styles/globals.css` and find the `:root { … }` block starting at line 131 and its corresponding `.dark { … }` block. Cut both **verbatim** into a new `apps/desktop/src/styles/tokens.css` with this header:
-
-```css
-/*
- * Design tokens, shared by the application shell and the standalone
- * documentation export.
- *
- * These live apart from globals.css because the export's Tailwind entry
- * cannot import globals.css: its `@source` scans the whole application and
- * `@source` is additive, so the export would emit every utility in DBX. The
- * export still needs these tokens, and duplicating them is how the values
- * drift.
- *
- * Order matters: `.dark` must stay declared after `:root`.
- */
-```
-
-Do not reformat, reorder or "tidy" the declarations while moving them — a diff that is a pure move is reviewable; one that also reformats is not.
-
-- [ ] **Step 4: Import from globals.css**
-
-At the point in `globals.css` where the `:root` block used to begin, put:
-
-```css
-@import "./tokens.css";
-```
-
-Leave `@theme inline` (line 71) and the `@import "tailwindcss"` / `@source` lines exactly where they are.
-
-- [ ] **Step 5: Verify the application is unchanged**
-
-Run: `pnpm vitest run apps/desktop/src/docs/__tests__/tokens.spec.ts`
-Expected: PASS (all three).
-
-Run: `pnpm build`
-Expected: succeeds. Then confirm the built CSS still carries the tokens:
-
-```bash
-grep -c -- "--muted-foreground" dist/assets/*.css
-```
-Expected: at least 1. A zero here means the `@import` did not resolve and the whole application would render unstyled.
-
-- [ ] **Step 6: Deliberate break**
-
-Reorder `tokens.css` so `.dark` precedes `:root`. Run the test; confirm it fails with `expected <n> to be greater than <m>`. Restore. Report the message.
-
-- [ ] **Step 7: Commit**
-
-```bash
-git add apps/desktop/src/styles apps/desktop/src/docs/__tests__/tokens.spec.ts
-git commit -m "$(cat <<'EOF'
-refactor(styles): extract design tokens for reuse by the export
-
-The standalone export's Tailwind entry cannot import globals.css — its
-`@source` scans the whole application and `@source` is additive, so the
-export would emit every utility in DBX rather than the ~40 the viewer uses.
-
-The tokens move verbatim; globals.css imports them. Copying the values into
-the export instead is exactly the duplication that has produced this
-feature's recurring defects.
-
-Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
-Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH
-EOF
-)"
-```
-
----
-
-## Task 3: `DocsRoute` and optional `v-model:route`
-
-**Files:**
-- Create: `apps/desktop/src/docs/docsRoute.ts`
-- Create: `apps/desktop/src/docs/__tests__/docsRoute.spec.ts`
-- Modify: `apps/desktop/src/docs/DocsApp.vue`
-
-**Interfaces:**
-- Produces: `export type DocsRoute`, `export function parseDocsHash(hash: string, snapshot: SchemaSnapshot, allowDiagram: boolean): DocsRoute`, `export function formatDocsHash(route: DocsRoute): string`. Task 5's `ExportApp.vue` consumes both.
-- Produces: `DocsApp` accepts optional `route?: DocsRoute` and emits `update:route`.
-
-`DocsApp` must stay uncontrolled when `route` is absent — DBX has no router (`vue-router` is not a dependency), so a `DocsApp` that always wrote to the URL would hijack the host application's address bar.
-
-- [ ] **Step 1: Write the failing test**
-
-Create `apps/desktop/src/docs/__tests__/docsRoute.spec.ts`:
-
-```ts
-import { describe, expect, it } from "vitest";
-import { formatDocsHash, parseDocsHash } from "../docsRoute";
-import type { SchemaSnapshot } from "../types";
-
-// `formatVersion` is top-level on SchemaSnapshot, not inside `project`.
-const snapshot = {
- formatVersion: 1,
- project: { name: "shop", databaseType: "postgres", database: "shop", schemas: ["public"], generatedAt: "2026-08-06T00:00:00Z", note: null },
- tables: [{ schema: "public", name: "orders", columns: [], indexes: [] }, { schema: null, name: "a/b", columns: [], indexes: [] }],
- enums: [{ schema: "public", name: "order_status", values: ["pending"] }],
- relationships: [],
- groups: [],
- warnings: [],
-} as unknown as SchemaSnapshot;
-
-describe("parseDocsHash", () => {
- it("reads a table route", () => {
- expect(parseDocsHash("#/table/public.orders", snapshot, true)).toEqual({ kind: "table", key: "public.orders" });
- });
-
- it("decodes an identifier containing a slash", () => {
- // A table named `a/b` must survive the round trip; an undecoded hash
- // would split into a bogus segment and silently fall back to the index.
- expect(parseDocsHash("#/table/a%2Fb", snapshot, true)).toEqual({ kind: "table", key: "a/b" });
- });
-
- it("reads an enum route", () => {
- expect(parseDocsHash("#/enum/order_status", snapshot, true)).toEqual({ kind: "enum", name: "order_status" });
- });
-
- it("falls back to the index for a table that is not in the snapshot", () => {
- // A deep link into a since-dropped table is the EXPECTED case for a file
- // someone saved months ago. It must never render a blank page.
- expect(parseDocsHash("#/table/public.gone", snapshot, true)).toEqual({ kind: "index" });
- });
-
- it("falls back to the index for junk, empty and bare hashes", () => {
- for (const hash of ["", "#", "#/", "#/nonsense", "#/table", "#/table/", "not-a-hash"]) {
- expect(parseDocsHash(hash, snapshot, true), hash).toEqual({ kind: "index" });
- }
- });
-
- it("refuses the diagram route when the host has not enabled it", () => {
- // The dialog passes diagram="external" and keeps its button to the full
- // SchemaDiagramDialog. A hash must not render a view that host declined.
- expect(parseDocsHash("#/diagram", snapshot, false)).toEqual({ kind: "index" });
- expect(parseDocsHash("#/diagram", snapshot, true)).toEqual({ kind: "diagram" });
- });
-});
-
-describe("formatDocsHash", () => {
- it("round-trips every route kind", () => {
- for (const route of [{ kind: "index" }, { kind: "table", key: "public.orders" }, { kind: "enum", name: "order_status" }, { kind: "diagram" }] as const) {
- expect(parseDocsHash(formatDocsHash(route), snapshot, true)).toEqual(route);
- }
- });
-
- it("encodes a slash in an identifier", () => {
- expect(formatDocsHash({ kind: "table", key: "a/b" })).toBe("#/table/a%2Fb");
- });
-});
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-Run: `pnpm vitest run apps/desktop/src/docs/__tests__/docsRoute.spec.ts`
-Expected: FAIL — `Failed to resolve import "../docsRoute"`.
-
-- [ ] **Step 3: Implement `docsRoute.ts`**
-
-```ts
-import { qualifiedTableKey } from "./docsKeys";
-import type { SchemaSnapshot } from "./types";
-
-/**
- * Where the viewer is pointing.
- *
- * This exists so the standalone export can drive navigation from
- * `location.hash` without DocsApp itself touching the URL: DBX has no
- * router, and a viewer that wrote to the address bar would hijack the host
- * application's.
- */
-export type DocsRoute = { kind: "index" } | { kind: "table"; key: string } | { kind: "enum"; name: string } | { kind: "diagram" };
-
-const INDEX: DocsRoute = { kind: "index" };
-
-/**
- * Resolve a hash against a snapshot.
- *
- * Anything unrecognised — junk, a table that no longer exists, the diagram
- * route on a host that did not enable it — resolves to the index. A saved
- * file whose schema has since changed is the expected case, not an exotic
- * one, and must never render blank.
- */
-export function parseDocsHash(hash: string, snapshot: SchemaSnapshot, allowDiagram: boolean): DocsRoute {
- if (!hash.startsWith("#")) return INDEX;
- const segments = hash.slice(1).replace(/^\//, "").split("/");
- const [kind, ...rest] = segments;
- const identifier = rest.join("/");
-
- if (kind === "diagram" && identifier === "") return allowDiagram ? { kind: "diagram" } : INDEX;
-
- if (identifier === "") return INDEX;
- let decoded: string;
- try {
- decoded = decodeURIComponent(identifier);
- } catch {
- // A malformed percent-escape throws rather than returning null.
- return INDEX;
- }
-
- if (kind === "table") {
- return snapshot.tables.some((table) => qualifiedTableKey(table) === decoded) ? { kind: "table", key: decoded } : INDEX;
- }
- if (kind === "enum") {
- return (snapshot.enums ?? []).some((value) => value.name === decoded) ? { kind: "enum", name: decoded } : INDEX;
- }
- return INDEX;
-}
-
-export function formatDocsHash(route: DocsRoute): string {
- switch (route.kind) {
- case "table":
- return `#/table/${encodeURIComponent(route.key)}`;
- case "enum":
- return `#/enum/${encodeURIComponent(route.name)}`;
- case "diagram":
- return "#/diagram";
- default:
- return "#/";
- }
-}
-```
-
-- [ ] **Step 4: Run the test**
-
-Run: `pnpm vitest run apps/desktop/src/docs/__tests__/docsRoute.spec.ts`
-Expected: PASS (8 tests).
-
-- [ ] **Step 5: Make `DocsApp` optionally controlled**
-
-In `apps/desktop/src/docs/DocsApp.vue`, add to `defineProps`:
-
-```ts
- /**
- * When provided, navigation is controlled by the host and mirrored back
- * through `update:route`. Absent — the dialog's case — DocsApp owns its
- * own navigation exactly as before and never touches the URL.
- */
- route?: DocsRoute;
- /** `inline` renders SchemaDiagram; `external` leaves the host to offer its own. */
- diagram?: "inline" | "external";
-```
-
-Add `"update:route": [route: DocsRoute]` to `defineEmits`. Replace the internal `activeKey` / `activeEnumName` reads with a computed that prefers `props.route` when present, and have `open()` / `home()` / `openEnum()` emit `update:route` in addition to setting internal state. Default `diagram` to `"external"`.
-
-- [ ] **Step 6: Verify nothing regressed**
-
-Run: `pnpm vitest run apps/desktop/src/docs && pnpm typecheck`
-Expected: PASS, clean.
-
-- [ ] **Step 7: Deliberate break**
-
-Change `parseDocsHash` to return `{ kind: "table", key: decoded }` without the `snapshot.tables.some(...)` check. Run the test; confirm `falls back to the index for a table that is not in the snapshot` fails. Restore. Report the message.
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add apps/desktop/src/docs
-git commit -m "$(cat <<'EOF'
-feat(docs): add a route model the export can drive from the URL
-
-DocsApp gains an OPTIONAL v-model:route. Absent, it owns navigation exactly
-as before — which is what the in-app dialog needs, since DBX has no router
-and a viewer that wrote to location.hash would hijack the host's address bar.
-
-Parsing is total: junk, a dropped table, or the diagram route on a host that
-did not enable it all resolve to the index. A deep link into a file saved
-months ago is the expected case, not an exotic one.
-
-Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
-Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH
-EOF
-)"
-```
-
----
-
-## Task 4: The minimal ER renderer
-
-**Files:**
-- Create: `apps/desktop/src/docs/diagramGeometry.ts`
-- Create: `apps/desktop/src/docs/__tests__/diagramGeometry.spec.ts`
-- Create: `apps/desktop/src/docs/components/SchemaDiagram.vue`
-- Modify: `apps/desktop/src/docs/DocsApp.vue`
-- Modify: `apps/desktop/src/docs/__tests__/componentContract.spec.ts`
-
-**Interfaces:**
-- Consumes: `layoutDiagramTables(tables: Pick<DiagramTable, "name" | "columns">[], options?: DiagramLayoutOptions): Record<string, DiagramPosition>` from `@/lib/diagram/erDiagram` — permitted by the contract test, which forbids only `@/lib/backend`; that module has exactly one import and it is `import type`, so it bundles cleanly.
-- Produces: `export function clipToCard(from: Point, to: Point, half: Size): Point` and `export interface Point { x: number; y: number }`.
-
-Layout is reused. **Edge routing is the genuinely new work** — nothing in the codebase draws a line between two cards.
-
-- [ ] **Step 1: Write the failing geometry test**
-
-Create `apps/desktop/src/docs/__tests__/diagramGeometry.spec.ts`:
-
-```ts
-import { describe, expect, it } from "vitest";
-import { clipToCard } from "../diagramGeometry";
-
-describe("clipToCard", () => {
- const half = { width: 100, height: 50 };
-
- it("exits through the vertical edge for a horizontal run", () => {
- // Centre (0,0) to (500,0): the line leaves through the right edge at
- // x = +100, not through the top or bottom.
- expect(clipToCard({ x: 0, y: 0 }, { x: 500, y: 0 }, half)).toEqual({ x: 100, y: 0 });
- });
-
- it("exits through the horizontal edge for a vertical run", () => {
- expect(clipToCard({ x: 0, y: 0 }, { x: 0, y: 500 }, half)).toEqual({ x: 0, y: 50 });
- });
-
- it("picks the nearer edge on a diagonal", () => {
- // Slope 1 against a 2:1 card: the vertical edge is reached first, so the
- // result sits ON x = 100 with |y| < 50. Clipping to the wrong axis puts
- // the endpoint outside the card and the line visibly overshoots.
- const point = clipToCard({ x: 0, y: 0 }, { x: 500, y: 500 }, half);
- expect(point.x).toBeCloseTo(50);
- expect(point.y).toBeCloseTo(50);
- });
-
- it("returns the centre when both points coincide", () => {
- // Two tables laid out at the same position would otherwise divide by zero
- // and emit NaN into the SVG path, which renders nothing at all.
- expect(clipToCard({ x: 7, y: 7 }, { x: 7, y: 7 }, half)).toEqual({ x: 7, y: 7 });
- });
-
- it("handles negative directions symmetrically", () => {
- expect(clipToCard({ x: 0, y: 0 }, { x: -500, y: 0 }, half)).toEqual({ x: -100, y: 0 });
- });
-});
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-Run: `pnpm vitest run apps/desktop/src/docs/__tests__/diagramGeometry.spec.ts`
-Expected: FAIL — `Failed to resolve import "../diagramGeometry"`.
-
-- [ ] **Step 3: Implement `diagramGeometry.ts`**
-
-```ts
-export interface Point {
- x: number;
- y: number;
-}
-
-export interface Size {
- width: number;
- height: number;
-}
-
-/**
- * Where a line from one card's centre towards another leaves the first card.
- *
- * Without this, edges terminate under the card and appear to sprout from a
- * table's middle. Scaling both axes and taking the smaller factor picks
- * whichever edge the ray actually reaches first.
- *
- * `half` is the card's HALF width and height, measured from its centre.
- */
-export function clipToCard(from: Point, to: Point, half: Size): Point {
- const dx = to.x - from.x;
- const dy = to.y - from.y;
- if (dx === 0 && dy === 0) {
- // Coincident centres would divide by zero and put NaN in the path data,
- // which renders as nothing rather than as an error.
- return { x: from.x, y: from.y };
- }
- const scaleX = dx === 0 ? Number.POSITIVE_INFINITY : half.width / Math.abs(dx);
- const scaleY = dy === 0 ? Number.POSITIVE_INFINITY : half.height / Math.abs(dy);
- const scale = Math.min(scaleX, scaleY);
- return { x: from.x + dx * scale, y: from.y + dy * scale };
-}
-```
-
-- [ ] **Step 4: Run the geometry test**
-
-Run: `pnpm vitest run apps/desktop/src/docs/__tests__/diagramGeometry.spec.ts`
-Expected: PASS (5 tests).
-
-- [ ] **Step 5: Create `SchemaDiagram.vue`**
-
-`apps/desktop/src/docs/components/SchemaDiagram.vue` — `<script setup lang="ts">`, props `{ snapshot: SchemaSnapshot; translate: Translate }`, emits `{ select: [tableKey: string] }`.
-
-Compute positions with `layoutDiagramTables(snapshot.tables.map((t) => ({ name: qualifiedTableKey(t), columns: t.columns })))`. Render an `<svg>` sized to the layout extent inside a `<div class="overflow-auto">` — scrolling *is* panning; there are no zoom controls by design.
-
-For each table draw a `<rect>` plus its qualified name and up to eight column names. Apply `groupStyle(hue)` and `style="background-color: var(--group-c)"` for the group accent — never a computed colour, which the contract test bans. For each relationship draw a `<line>` whose endpoints come from `clipToCard` in both directions. A `<rect>` per table carries `@click="emit('select', key)"`.
-
-- [ ] **Step 6: Register it in the contract test and render it in `DocsApp`**
-
-In `componentContract.spec.ts`, add `"SchemaDiagram.vue"` to `EXPECTED` — keep the array alphabetically sorted, since the first test compares against a sorted list.
-
-In `DocsApp.vue`, render `<SchemaDiagram v-else-if="view === 'diagram'" … />` and add a Diagram entry to the sidebar only when `diagram === "inline"`.
-
-- [ ] **Step 7: Run everything and typecheck**
-
-Run: `pnpm vitest run apps/desktop/src/docs && pnpm typecheck`
-Expected: PASS, clean. The contract test must confirm `SchemaDiagram.vue` references none of the forbidden needles and computes no colour.
-
-- [ ] **Step 8: Deliberate break**
-
-In `clipToCard`, replace `Math.min(scaleX, scaleY)` with `scaleX`. Run the geometry test; confirm `picks the nearer edge on a diagonal` fails with `expected 100 to be close to 50`. Restore. Report the message.
-
-- [ ] **Step 9: Commit**
-
-```bash
-git add apps/desktop/src/docs
-git commit -m "$(cat <<'EOF'
-feat(docs): add a minimal read-only ER renderer
-
-Reuses layoutDiagramTables from lib/diagram/erDiagram, which is bundleable
-as-is: 211 lines with exactly one import, and that import is `import type`.
-
-Edge routing is the new part — nothing in the codebase drew a line between
-two cards. clipToCard scales both axes and takes the smaller factor, so an
-edge stops on whichever border the ray reaches first instead of vanishing
-under the card.
-
-Deliberately minimal: scroll is the pan, there is no zoom, and the host
-chooses whether to show this at all. In-app the dialog keeps its button to
-the full SchemaDiagramDialog, so no screen offers two ER views.
-
-Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
-Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH
-EOF
-)"
-```
-
----
-
-## Task 5: The export shell and the bundle
-
-**Files:**
-- Create: `apps/desktop/src/docs-export/{main.ts,ExportApp.vue,exportTranslate.ts,export.css}`
-- Create: `apps/desktop/vite.docs-export.config.ts`
-- Create: `apps/desktop/src/docs-export/__tests__/exportTranslate.spec.ts`
-- Modify: `package.json`
-
-**Interfaces:**
-- Consumes: `parseDocsHash`, `formatDocsHash`, `DocsRoute` (Task 3); `DocsApp` with `route`/`diagram` props (Tasks 3–4); `tokens.css` (Task 2).
-- Produces: `crates/dbx-core/assets/docs-export.js`, `docs-export.css`, `docs-export.manifest.json`. Tasks 6 and 7 consume all three.
-- Produces: the payload contract — `{ snapshot, annotations, lang }` — which Task 6's Rust side must emit exactly.
-
-- [ ] **Step 1: Write the failing translate test**
-
-Create `apps/desktop/src/docs-export/__tests__/exportTranslate.spec.ts`:
-
-```ts
-import { describe, expect, it } from "vitest";
-import { createExportTranslate, EXPORT_LOCALES } from "../exportTranslate";
-
-describe("createExportTranslate", () => {
- it("carries every locale the app ships", () => {
- expect(Object.keys(EXPORT_LOCALES).sort()).toEqual(["en", "es", "it", "ja", "ko", "pt-BR", "zh-CN", "zh-TW"]);
- });
-
- it("resolves a nested key under the docs prefix", () => {
- expect(createExportTranslate("en")("docs.columns")).toBe("Columns");
- expect(createExportTranslate("en")("docs.warnings.orphanedNotes.title")).toBe("Some notes no longer match anything");
- });
-
- it("substitutes placeholders", () => {
- expect(createExportTranslate("en")("docs.shadowedComment", { comment: "hi" })).toBe("Database comment: hi");
- });
-
- it("falls back to English for an unknown locale", () => {
- // A hand-edited payload, or a --lang that slipped through, must render
- // English rather than raw keys in a file someone opens offline.
- expect(createExportTranslate("kl" as never)("docs.columns")).toBe("Columns");
- });
-
- it("returns the key when nothing resolves", () => {
- expect(createExportTranslate("en")("docs.nope.missing")).toBe("docs.nope.missing");
- });
-});
-```
-
-- [ ] **Step 2: Run it and watch it fail**
-
-Run: `pnpm vitest run apps/desktop/src/docs-export`
-Expected: FAIL — `Failed to resolve import "../exportTranslate"`.
-
-- [ ] **Step 3: Implement `exportTranslate.ts`**
-
-```ts
-import en from "@/i18n/locales/docs/en";
-import es from "@/i18n/locales/docs/es";
-import it from "@/i18n/locales/docs/it";
-import ja from "@/i18n/locales/docs/ja";
-import ko from "@/i18n/locales/docs/ko";
-import ptBR from "@/i18n/locales/docs/pt-BR";
-import zhCN from "@/i18n/locales/docs/zh-CN";
-import zhTW from "@/i18n/locales/docs/zh-TW";
-import type { Translate } from "@/docs/docsWarnings";
-
-export const EXPORT_LOCALES = { en, es, it, ja, ko, "pt-BR": ptBR, "zh-CN": zhCN, "zh-TW": zhTW } as const;
-
-export type ExportLocale = keyof typeof EXPORT_LOCALES;
-
-function lookup(source: unknown, key: string): string | null {
- const value = key.split(".").reduce<unknown>((node, part) => (node && typeof node === "object" ? (node as Record<string, unknown>)[part] : undefined), source);
- return typeof value === "string" ? value : null;
-}
-
-/**
- * Build a `Translate` over a bundled namespace.
- *
- * English is the fallback rather than the raw key. The parity test guarantees
- * all 8 namespaces agree, so this should never fire — it exists so an
- * artefact opened offline degrades to English instead of showing
- * `docs.columns` to a reader. This is not the Part 3b hazard where a fallback
- * masked drift: there the fallback replaced the guard, here the guard runs in
- * CI and this is only a runtime backstop.
- */
-export function createExportTranslate(lang: ExportLocale): Translate {
- const primary = EXPORT_LOCALES[lang] ?? EXPORT_LOCALES.en;
- return (key, params) => {
- // Keys arrive prefixed with `docs.` because that is how the namespace is
- // mounted in the app; the bundled modules are the namespace itself.
- const bare = key.startsWith("docs.") ? key.slice("docs.".length) : key;
- const template = lookup(primary, bare) ?? lookup(EXPORT_LOCALES.en, bare);
- if (template === null) return key;
- if (!params) return template;
- return template.replace(/\{(\w+)\}/g, (match, name: string) => (name in params ? String(params[name]) : match));
- };
-}
-```
-
-- [ ] **Step 4: Run the translate test**
-
-Run: `pnpm vitest run apps/desktop/src/docs-export`
-Expected: PASS (5 tests).
-
-- [ ] **Step 5: Write `export.css`**
-
-```css
-@import "tailwindcss";
-/*
- * Narrowed deliberately. globals.css sources the whole application, and
- * `@source` is additive with no way to un-source, so importing it would emit
- * every utility in DBX rather than the ~40 the viewer uses.
- */
-@source "../docs/**/*.vue";
-@source "../docs-export/**/*.vue";
-
-@import "../styles/tokens.css";
-```
-
-No `@font-face` here — the Vite plugin in Step 6 prepends it with the font already inlined, so no rule can reference a path that fails under `file://`.
-
-- [ ] **Step 6: Write `vite.docs-export.config.ts`**
-
-```ts
-import { createHash } from "node:crypto";
-import { readFileSync, writeFileSync } from "node:fs";
-import path from "node:path";
-import { defineConfig } from "vite";
-import vue from "@vitejs/plugin-vue";
-import tailwindcss from "@tailwindcss/vite";
-
-const repoRoot = path.resolve(__dirname, "../..");
-const assetsDir = path.join(repoRoot, "crates/dbx-core/assets");
-const fontPath = path.join(__dirname, "public/fonts/geist-latin-wght-normal.woff2");
-
-function sha256(buffer: Buffer | string): string {
- return createHash("sha256").update(buffer).digest("hex");
-}
-
-/**
- * Inline the font and write the staleness manifest.
- *
- * The manifest is derived from Rollup's ACTUAL module graph, never from a
- * hand-written glob. SchemaDiagram.vue imports erDiagram.ts from outside
- * src/docs/, so a glob of that directory would miss it and the guard would
- * pass while the artefact was stale — the same shape as the three guards
- * this feature has already had to widen after the fact.
- *
- * New files are covered for free: a module can only enter the bundle by being
- * imported, which means editing an existing file, which changes that file's
- * hash. The one hole would be `import.meta.glob`, which the viewer does not
- * use.
- */
-function exportBundlePlugin() {
- return {
- name: "dbx-docs-export",
- generateBundle(_options: unknown, bundle: Record<string, { type: string; source?: string | Uint8Array; code?: string; modules?: Record<string, unknown> }>) {
- const font = readFileSync(fontPath).toString("base64");
- const fontFace = `@font-face{font-family:"Geist Variable";font-style:normal;font-display:swap;font-weight:100 900;src:url("data:font/woff2;base64,${font}") format("woff2-variations")}\n`;
-
- const sources: Record<string, string> = {};
- const deps: Record<string, string> = {};
- for (const chunk of Object.values(bundle)) {
- for (const id of Object.keys(chunk.modules ?? {})) {
- if (!path.isAbsolute(id)) continue;
- const nodeModules = id.indexOf("/node_modules/");
- if (nodeModules !== -1) {
- const after = id.slice(nodeModules + "/node_modules/".length);
- const name = after.startsWith("@") ? after.split("/").slice(0, 2).join("/") : after.split("/")[0];
- if (!(name in deps)) {
- const pkg = JSON.parse(readFileSync(path.join(id.slice(0, nodeModules), "node_modules", name, "package.json"), "utf8"));
- deps[name] = pkg.version;
- }
- continue;
- }
- if (!id.startsWith(repoRoot)) continue;
- const relative = path.relative(repoRoot, id);
- sources[relative] = sha256(readFileSync(id));
- }
- }
- sources[path.relative(repoRoot, fontPath)] = sha256(readFileSync(fontPath));
-
- for (const [name, chunk] of Object.entries(bundle)) {
- if (name.endsWith(".css") && typeof chunk.source === "string") chunk.source = fontFace + chunk.source;
- }
-
- writeFileSync(
- path.join(assetsDir, "docs-export.manifest.json"),
- `${JSON.stringify({ sources: Object.fromEntries(Object.entries(sources).sort()), deps: Object.fromEntries(Object.entries(deps).sort()) }, null, 2)}\n`,
- );
- },
- };
-}
-
-export default defineConfig({
- plugins: [vue(), tailwindcss(), exportBundlePlugin()],
- resolve: { alias: { "@": path.resolve(__dirname, "src") } },
- build: {
- outDir: assetsDir,
- emptyOutDir: false,
- cssCodeSplit: false,
- // One JS file. Without this the export would need to load chunks over the
- // network, which is precisely what a file:// artefact cannot do.
- rollupOptions: {
- input: path.resolve(__dirname, "src/docs-export/main.ts"),
- output: { inlineDynamicImports: true, entryFileNames: "docs-export.js", assetFileNames: "docs-export.[ext]" },
- },
- },
-});
-```
-
-- [ ] **Step 7: Write `main.ts` and `ExportApp.vue`**
-
-`main.ts` reads the base64 payload from `<script type="application/dbx-snapshot">`, decodes it, and mounts:
-
-```ts
-import { createApp } from "vue";
-import ExportApp from "./ExportApp.vue";
-import "./export.css";
-
-const node = document.querySelector("script[type='application/dbx-snapshot']");
-// `atob` yields one byte per character; the payload is UTF-8, so it must be
-// widened before decoding or every non-ASCII table name and note is mangled.
-const binary = atob((node?.textContent ?? "").trim());
-const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
-const payload = JSON.parse(new TextDecoder().decode(bytes));
-
-createApp(ExportApp, { payload }).mount("#app");
-```
-
-`ExportApp.vue` holds a `route` ref initialised from `parseDocsHash(location.hash, payload.snapshot, true)`, listens for `hashchange`, writes `location.hash = formatDocsHash(route)` on `update:route`, renders a `<select>` of `EXPORT_LOCALES` bound to a `lang` ref, and renders:
-
-```
-<DocsApp :snapshot="payload.snapshot" :annotations="payload.annotations" :readonly="true"
- :translate="translate" :route="route" diagram="inline" @update:route="route = $event" />
-```
-
-Language is **not persisted**: under `file://` every document shares one opaque origin, so `localStorage` would leak one export's preference into an unrelated one.
-
-- [ ] **Step 8: Add the build script**
-
-In the root `package.json` `scripts`, after `"build"`:
-
-```json
- "build:docs-export": "vite build --config apps/desktop/vite.docs-export.config.ts",
-```
-
-- [ ] **Step 9: Build and inspect**
-
-Run: `pnpm build:docs-export`
-Expected: succeeds, writing three files. Verify:
-
-```bash
-ls -la crates/dbx-core/assets/docs-export.*
-grep -c "url(/" crates/dbx-core/assets/docs-export.css
-```
-Expected: three files; `0` external URL references.
-
-- [ ] **Step 10: Commit**
-
-```bash
-git add apps/desktop/src/docs-export apps/desktop/vite.docs-export.config.ts package.json crates/dbx-core/assets
-git commit -m "$(cat <<'EOF'
-feat(docs): bundle the viewer as a single-file export
-
-One JS and one CSS, with the font inlined as a data URI, built from the
-same components the app renders — which is what the purity contract on
-src/docs/ has been protecting since Part 3a.
-
-The staleness manifest is derived from Rollup's module graph rather than a
-glob. SchemaDiagram.vue imports erDiagram.ts from outside src/docs/, so a
-glob of that directory would miss it and pass while the artefact was stale.
-
-Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
-Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH
-EOF
-)"
-```
-
----
-
-## Task 6: `to_standalone_html`
-
-**Files:**
-- Create: `crates/dbx-core/src/docs/export.rs`
-- Modify: `crates/dbx-core/src/docs/mod.rs`
-
-**Interfaces:**
-- Consumes: `crates/dbx-core/assets/docs-export.{js,css}` (Task 5); `SchemaSnapshot` and `AnnotationFile` from `docs::snapshot` / `docs::annotations`.
-- Produces: `pub fn to_standalone_html(snapshot: &SchemaSnapshot, annotations: &AnnotationFile, lang: &str) -> Result<String, String>` and `pub const EXPORT_LANGUAGES: [&str; 8]`. Tasks 8 and 9 both call it.
-
-- [ ] **Step 1: Write the failing tests**
-
-Create `crates/dbx-core/src/docs/export.rs` with only its test module, so the tests fail to compile against a missing function:
-
-```rust
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::docs::annotations::AnnotationFile;
- use crate::docs::snapshot::SchemaSnapshot;
-
- /// `SchemaSnapshot` is `#[serde(rename_all = "camelCase")]` with
- /// `format_version` at the TOP level — not inside `project` — and
- /// `ProjectMeta` requires `name`, `databaseType`, `schemas` and
- /// `generatedAt`. `AnnotationFile` does NOT derive `Default`, and its
- /// `format_version` must be 1, so it is built explicitly.
- fn fixture() -> (SchemaSnapshot, AnnotationFile) {
- let snapshot: SchemaSnapshot = serde_json::from_str(
- r#"{"formatVersion":1,"project":{"name":"shop","databaseType":"postgres","database":"shop","schemas":["public"],"generatedAt":"2026-08-06T00:00:00Z","note":null},"tables":[],"enums":[],"relationships":[],"groups":[],"warnings":[]}"#,
- )
- .expect("fixture snapshot");
- let annotations = AnnotationFile {
- format_version: 1,
- project: None,
- groups: Vec::new(),
- tables: std::collections::BTreeMap::new(),
- };
- (snapshot, annotations)
- }
-
- #[test]
- fn a_note_containing_a_closing_script_tag_survives() {
- // THE reason the payload is base64. A note discussing HTML is
- // entirely plausible in a schema document, and inlined as text it
- // would terminate the script element early and inject the rest of
- // the payload as markup.
- let (snapshot, mut annotations) = fixture();
- annotations.project = Some(crate::docs::annotations::ProjectAnnotation {
- name: None,
- note: Some("</script><img src=x onerror=alert(1)>".into()),
- });
- let html = to_standalone_html(&snapshot, &annotations, "en").expect("export");
-
- assert!(!html.contains("<img src=x"), "the payload leaked into markup");
- assert_eq!(html.matches("</script>").count(), 2, "exactly the two real script elements");
- }
-
- #[test]
- fn the_payload_round_trips() {
- let (snapshot, annotations) = fixture();
- let html = to_standalone_html(&snapshot, &annotations, "en").expect("export");
- let start = html.find("application/dbx-snapshot").expect("payload element");
- let body = &html[start..];
- let encoded = body[body.find('>').unwrap() + 1..body.find("</script>").unwrap()].trim();
- let decoded = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, encoded).expect("valid base64");
- let value: serde_json::Value = serde_json::from_slice(&decoded).expect("valid json");
- assert_eq!(value["snapshot"]["project"]["name"], "shop");
- assert_eq!(value["lang"], "en");
- }
-
- #[test]
- fn nothing_is_loaded_from_the_network() {
- // The whole point of the artefact. A single absolute URL left in the
- // CSS means the file renders unstyled on a machine with no network,
- // and nothing else would catch it.
- let (snapshot, annotations) = fixture();
- let html = to_standalone_html(&snapshot, &annotations, "en").expect("export");
- for needle in ["http://", "https://", "url(/", "src=\"/", "href=\"/"] {
- assert!(!html.contains(needle), "export references {needle}");
- }
- }
-
- #[test]
- fn an_unknown_language_is_rejected() {
- let (snapshot, annotations) = fixture();
- let error = to_standalone_html(&snapshot, &annotations, "kl").expect_err("should reject");
- assert!(error.contains("kl"), "got: {error}");
- assert!(error.contains("en"), "the error must list the valid locales, got: {error}");
- }
-}
-```
-
-- [ ] **Step 2: Run and watch it fail**
-
-Run: `cargo test -p dbx-core --lib docs::export`
-Expected: FAIL to compile — `cannot find function to_standalone_html in this scope`.
-
-- [ ] **Step 3: Implement `to_standalone_html`**
-
-Above the test module in the same file:
-
-```rust
-use base64::Engine as _;
-
-use crate::docs::annotations::AnnotationFile;
-use crate::docs::snapshot::SchemaSnapshot;
-
-/// The viewer bundle, built by `pnpm build:docs-export` and committed.
-///
-/// Committed rather than built by cargo because Rust cannot run Vite and
-/// `dbx docs` must work from a plain `cargo install` on a machine with no
-/// Node. `docs_export_bundle_is_current` is what keeps it honest.
-const EXPORT_JS: &str = include_str!("../../assets/docs-export.js");
-const EXPORT_CSS: &str = include_str!("../../assets/docs-export.css");
-
-pub const EXPORT_LANGUAGES: [&str; 8] = ["en", "es", "it", "ja", "ko", "pt-BR", "zh-CN", "zh-TW"];
-
-/// Render a snapshot as one self-contained HTML file.
-///
-/// `snapshot` must already have annotations applied — `apply_annotations` is
-/// Rust and the export has no Rust at runtime. `annotations` travels too,
-/// because the merge erases what the viewer needs to colour groups:
-/// `snapshot.groups` holds resolved `TableGroup`s, `annotations.groups` holds
-/// the hue.
-pub fn to_standalone_html(snapshot: &SchemaSnapshot, annotations: &AnnotationFile, lang: &str) -> Result<String, String> {
- if !EXPORT_LANGUAGES.contains(&lang) {
- return Err(format!("Unknown language \"{lang}\". Valid values: {}.", EXPORT_LANGUAGES.join(", ")));
- }
-
- let payload = serde_json::json!({ "snapshot": snapshot, "annotations": annotations, "lang": lang });
- let json = serde_json::to_vec(&payload).map_err(|error| format!("Failed to serialise the documentation payload: {error}"))?;
- // base64 rather than escaped JSON: the alphabet cannot contain `<`, so no
- // escaping rule exists to forget. The alternative's correctness depends
- // on every serialisation path applying the escape.
- let encoded = base64::engine::general_purpose::STANDARD.encode(&json);
-
- let title = html_escape(&snapshot.project.name);
- Ok(format!(
- "<!doctype html>\n<html lang=\"{lang}\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>{title}</title>\n<style>{EXPORT_CSS}</style>\n</head>\n<body>\n<div id=\"app\"></div>\n<script type=\"application/dbx-snapshot\">{encoded}</script>\n<script>{EXPORT_JS}</script>\n</body>\n</html>\n"
- ))
-}
-
-fn html_escape(value: &str) -> String {
- value.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
-}
-```
-
-Add to `crates/dbx-core/src/docs/mod.rs`:
-
-```rust
-pub mod export;
-```
-and to the re-export list:
-```rust
-pub use export::{to_standalone_html, EXPORT_LANGUAGES};
-```
-
-- [ ] **Step 4: Run the tests**
-
-Run: `cargo test -p dbx-core --lib docs::export`
-Expected: PASS (4 tests).
-
-- [ ] **Step 5: Deliberate break**
-
-Replace the base64 encode with `String::from_utf8(json).unwrap()`. Run the tests; confirm `a_note_containing_a_closing_script_tag_survives` fails with `the payload leaked into markup`. Restore. Report the message.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add crates/dbx-core/src/docs
-git commit -m "$(cat <<'EOF'
-feat(docs): render a snapshot as one self-contained HTML file
-
-The payload is base64 rather than escaped JSON. A note containing the
-literal `</script>` — plausible in any schema document that discusses HTML —
-would otherwise terminate the script element early and inject the remainder
-as markup. base64's alphabet cannot contain `<`, so the property holds by
-construction rather than by remembering to escape on every path.
-
-Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
-Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH
-EOF
-)"
-```
-
----
-
-## Task 7: The staleness guard
-
-**Files:**
-- Modify: `crates/dbx-core/src/docs/export.rs`
-
-**Interfaces:**
-- Consumes: `crates/dbx-core/assets/docs-export.manifest.json` (Task 5).
-
-- [ ] **Step 1: Write the test**
-
-Append to the `tests` module in `export.rs`:
-
-```rust
- /// The committed bundle must match the sources it was built from.
- ///
- /// Skips only when the crate is consumed from a published package, where
- /// `apps/desktop/` does not exist. That skip is itself a hazard — a
- /// vacuous skip in CI would silently disable this guard — so it keys off
- /// a repository-only marker rather than off the absence of the sources.
- #[test]
- fn docs_export_bundle_is_current() {
- use sha2::{Digest, Sha256};
-
- let workspace = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").canonicalize().expect("workspace root");
- if !workspace.join("pnpm-workspace.yaml").exists() {
- return; // packaged crate: the sources are genuinely absent
- }
-
- let manifest: serde_json::Value =
- serde_json::from_str(include_str!("../../assets/docs-export.manifest.json")).expect("manifest is valid JSON");
- let sources = manifest["sources"].as_object().expect("manifest.sources");
- assert!(sources.len() > 5, "manifest lists only {} sources — the build emitted an empty graph", sources.len());
-
- let mut stale = Vec::new();
- for (relative, expected) in sources {
- let path = workspace.join(relative);
- let Ok(bytes) = std::fs::read(&path) else {
- stale.push(format!("{relative} (missing)"));
- continue;
- };
- let actual = format!("{:x}", Sha256::digest(&bytes));
- if actual != expected.as_str().unwrap_or_default() {
- stale.push(relative.clone());
- }
- }
-
- assert!(stale.is_empty(), "the committed docs export bundle is stale.\nChanged: {}\nRun: pnpm build:docs-export", stale.join(", "));
- }
-```
-
-- [ ] **Step 2: Run it**
-
-Run: `cargo test -p dbx-core --lib docs::export::tests::docs_export_bundle_is_current`
-Expected: PASS — the bundle was built in Task 5 and nothing has changed since.
-
-- [ ] **Step 3: Deliberate break**
-
-Append a blank line to `apps/desktop/src/docs/DocsApp.vue`. Run the test. Confirm it fails with `the committed docs export bundle is stale. Changed: apps/desktop/src/docs/DocsApp.vue`. Revert the edit and re-run to confirm it passes. Report the message.
-
-- [ ] **Step 4: Verify the guard reaches outside `src/docs/`**
-
-This is the whole reason the manifest is derived rather than globbed. Append a blank line to `apps/desktop/src/lib/diagram/erDiagram.ts` — a file a `src/docs/**` glob would have missed entirely. Run the test; confirm it fails naming that file. Revert. Report the message.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add crates/dbx-core/src/docs/export.rs
-git commit -m "$(cat <<'EOF'
-test(docs): fail when the committed export bundle is stale
-
-Verified to bite on a change to erDiagram.ts, which lives outside src/docs/
-and which a directory glob would have missed — the failure mode this guard
-exists to prevent.
-
-The packaged-crate skip keys off pnpm-workspace.yaml rather than off the
-absence of the sources, so a CI checkout cannot silently skip it.
-
-Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
-Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH
-EOF
-)"
-```
-
----
-
-## Task 8: The `dbx docs` verb
-
-**Files:**
-- Modify: `crates/dbx-cli/src/main.rs`
-
-**Interfaces:**
-- Consumes: `dbx_core::docs::to_standalone_html` and `EXPORT_LANGUAGES` (Task 6).
-
-`run_docs` mirrors `run_dbml` (line 461) exactly, with one difference: `run_dbml` scopes `annotations` inside its `if let`, but the export needs the `AnnotationFile` **after** applying it, so it must be hoisted.
-
-- [ ] **Step 1: Write the failing flag tests**
-
-Add beside the existing `dbml` flag tests (around line 1148):
-
-```rust
- #[test]
- fn parses_the_lang_flag() {
- let flags = parse_flags(&args(&["docs", "local", "--lang", "zh-CN"])).expect("parse");
- assert_eq!(flags.args, args(&["docs", "local"]));
- assert_eq!(flags.lang.as_deref(), Some("zh-CN"));
- }
-
- #[test]
- fn lang_requires_a_value() {
- parse_flags(&args(&["docs", "local", "--lang"])).expect_err("should fail");
- }
-
- #[test]
- fn docs_appears_in_the_usage_text() {
- assert!(usage().contains("dbx docs <connection>"), "got: {}", usage());
- }
-```
-
-- [ ] **Step 2: Run and watch them fail**
-
-Run: `cargo test -p dbx-cli parses_the_lang_flag`
-Expected: FAIL to compile — `no field 'lang' on type 'Flags'`.
-
-- [ ] **Step 3: Add the flag**
-
-Add `lang: Option<String>,` to `struct Flags`, and beside the `"--notes"` arm (line 573):
-
-```rust
- "--lang" => flags.lang = Some(option_value(argv, &mut index, "--lang")?),
-```
-
-- [ ] **Step 4: Add the verb**
-
-Beside the `dbml` dispatch (line 245):
-
-```rust
- if args.first().is_some_and(|arg| arg == "docs") {
- return run_docs(backend, &flags).await;
- }
-```
-
-And the function, mirroring `run_dbml`:
-
-```rust
-async fn run_docs(backend: &dyn DbxBackend, flags: &Flags) -> Result<String, CliError> {
- let args = &flags.args;
- let connection_name = required(args.get(1), "Connection name is required.")?;
- let connection = find_connection(backend, connection_name).await?;
- let database = selected_database(&connection, flags.database.as_deref());
-
- let options = DocsSnapshotOptions {
- schemas: flags.schema.clone().into_iter().collect(),
- tables: flags.tables.clone(),
- project_name: Some(connection.name.clone()),
- };
-
- let mut snapshot = backend.collect_docs_snapshot(&connection, &database, options).await.map_err(command_error)?;
-
- // Unlike run_dbml, the AnnotationFile is needed AFTER it has been applied:
- // the merge resolves groups into TableGroups and drops the hue the viewer
- // colours with, so the raw file has to travel too.
- //
- // AnnotationFile does not derive Default and `format_version` must be 1,
- // so the empty value is constructed explicitly rather than defaulted.
- let mut annotations = dbx_core::docs::annotations::AnnotationFile {
- format_version: 1,
- project: None,
- groups: Vec::new(),
- tables: std::collections::BTreeMap::new(),
- };
- if let Some(path) = flags.notes.as_ref() {
- require_notes_file(path)?;
- if let Some(loaded) = dbx_core::docs::annotations::load_annotations(path)
- .map_err(|error| CliError::new("NOTES_INVALID", error))?
- {
- dbx_core::docs::annotations::apply_annotations(&mut snapshot, &loaded, connection.db_type);
- annotations = loaded;
- }
- }
-
- for warning in &snapshot.warnings {
- eprintln!("warning: {warning}");
- }
-
- let lang = flags.lang.as_deref().unwrap_or("en");
- let html = dbx_core::docs::to_standalone_html(&snapshot, &annotations, lang).map_err(|error| CliError::new("EXPORT_FAILED", error))?;
-
- match flags.out.as_ref() {
- Some(path) => {
- std::fs::write(path, &html)
- .map_err(|error| CliError::new("WRITE_FAILED", format!("Failed to write {}: {error}", path.display())))?;
- Ok(format!("Wrote {} bytes to {}", html.len(), path.display()))
- }
- None => Ok(html),
- }
-}
-```
-
-- [ ] **Step 5: Add the usage line**
-
-In `usage()`, after the `dbx dbml` line:
-
-```
-\n dbx docs <connection> [--out path] [--notes path] [--lang code] [--schema name] [--database name] [--tables a,b]
-```
-
-- [ ] **Step 6: Run the tests and try it**
-
-Run: `cargo test -p dbx-cli`
-Expected: PASS.
-
-Run against a live connection:
-```bash
-cargo run -p dbx-cli -- docs <connection> --database <db> --schema public --out /tmp/schema.html
-```
-Expected: `Wrote N bytes to /tmp/schema.html`. Then open it in a browser over `file://` and confirm the index renders, a table page opens, the hash updates, a reload keeps the page, and the language switcher works.
-
-- [ ] **Step 7: Commit**
-
-```bash
-git add crates/dbx-cli/src/main.rs
-git commit -m "$(cat <<'EOF'
-feat(cli): add the dbx docs verb
-
-Mirrors dbx dbml's flags and collector, plus --lang. An unknown language
-fails with the list of valid values rather than falling back — the same
-reasoning that made --notes explicit in Part 2.
-
-Unlike run_dbml, the AnnotationFile is kept after being applied: the merge
-resolves groups into TableGroups and drops the hue the viewer colours with.
-
-Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
-Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH
-EOF
-)"
-```
-
----
-
-## Task 9: The in-app export button
-
-**Files:**
-- Modify: `src-tauri/src/commands/docs.rs`, `src-tauri/src/lib.rs`
-- Modify: `crates/dbx-web/src/routes/docs.rs`, `crates/dbx-web/src/main.rs`
-- Modify: `apps/desktop/src/lib/backend/{api,tauri,http}.ts`
-- Modify: `apps/desktop/src/components/docs/DatabaseDocsDialog.vue`
-
-**Interfaces:**
-- Consumes: `to_standalone_html` (Task 6); the `docs.exportHtml` / `docs.exporting` / `docs.exportFailed` keys (Task 1).
-- Produces: `exportDocsHtml(filePath: string, snapshot: SchemaSnapshot, annotations: AnnotationFile, lang: string): Promise<void>` on both transports.
-
-**Rust writes the file; the frontend supplies the path.** This mirrors `exportQueryResultCsv(filePath, columns, rows)` at `apps/desktop/src/lib/backend/tauri.ts:3807`, and avoids returning a ~400 KB string across IPC only to write it back out.
-
-**Every backend operation exists twice** — once in `tauri.ts`, once in `http.ts`. `api.ts` types the backend as `typeof TauriModule` and resolves either at runtime, so a signature that differs between them compiles on both sides and fails only when a user clicks the button. Add both.
-
-- [ ] **Step 1: Add the Tauri command**
-
-In `src-tauri/src/commands/docs.rs`, following the shape at line 34:
-
-```rust
-#[tauri::command]
-pub async fn docs_export_html(
- file_path: String,
- snapshot: SchemaSnapshot,
- annotations: AnnotationFile,
- lang: String,
-) -> Result<(), String> {
- let html = dbx_core::docs::to_standalone_html(&snapshot, &annotations, &lang)?;
- std::fs::write(&file_path, html).map_err(|error| format!("Failed to write {file_path}: {error}"))
-}
-```
-
-Tauri converts argument names between camelCase and snake_case **by name**: the frontend sends `filePath` and this receives `file_path`. A mismatch compiles cleanly on both sides and fails only at runtime, so keep the names aligned.
-
-Register it in `src-tauri/src/lib.rs` beside the other four (lines 1742–1745): `commands::docs::docs_export_html,`.
-
-- [ ] **Step 2: Add the web route**
-
-In `crates/dbx-web/src/routes/docs.rs` add a handler with a `#[serde(rename_all = "camelCase")]` request struct carrying `snapshot`, `annotations`, `lang`, returning the HTML string. Register it in `crates/dbx-web/src/main.rs` beside the existing docs routes (around line 377):
-
-```rust
- .route("/docs/export", post(routes::docs::export_html))
-```
-
-- [ ] **Step 3: Add both transports**
-
-`apps/desktop/src/lib/backend/tauri.ts`, beside `collectDocsSnapshot` (line 1626):
-
-```ts
-export async function exportDocsHtml(filePath: string, snapshot: SchemaSnapshot, annotations: AnnotationFile, lang: string): Promise<void> {
- return invoke("docs_export_html", { filePath, snapshot, annotations, lang });
-}
-```
-
-`http.ts` gets the same signature posting to `/docs/export`. `api.ts`, after line 185:
-
-```ts
-export const exportDocsHtml = forward("exportDocsHtml");
-```
-
-- [ ] **Step 4: Add the button**
-
-In `DatabaseDocsDialog.vue`, beside the existing diagram button (line ~182), add an Export button. Follow the established export pattern from `apps/desktop/src/composables/useDataGridExport.ts:649-662` — a default filename, replaced by a real path from the Tauri save dialog when running in Tauri, then one call that is identical in both runtimes:
-
-```ts
-async function exportHtml(): Promise<void> {
- if (!snapshot.value) return;
- exporting.value = true;
- exportError.value = null;
- try {
- let outputPath = `${snapshot.value.project.name}-docs.html`;
- if (isTauriRuntime()) {
- const { save } = await import("@tauri-apps/plugin-dialog");
- const chosen = await save({ defaultPath: outputPath, filters: [{ name: "HTML", extensions: ["html"] }] });
- if (!chosen) return; // the user cancelled; not an error
- outputPath = chosen as string;
- }
- await api.exportDocsHtml(outputPath, snapshot.value, annotations.value, locale.value);
- } catch (error) {
- // Never swallowed: a failed export that reports success is the worst
- // outcome here, exactly as with a failed autosave.
- exportError.value = translate("docs.exportFailed", { error: String(error) });
- } finally {
- exporting.value = false;
- }
-}
-```
-
-`locale.value` comes from `useI18n()`, which this component already imports — it lives outside `src/docs/` and so is permitted to. If the app's locale is not one of the eight, `to_standalone_html` rejects it; map it to `"en"` before calling rather than surfacing that error.
-
-Show `docs.exporting` on the button while in flight and `docs.exportFailed` on failure.
-
-- [ ] **Step 5: Verify**
-
-Run: `cargo check --workspace && pnpm typecheck`
-Expected: clean.
-
-Then run the app (`pnpm dev:web` with `DBX_DISABLE_PASSWORD=1` plus the backend) and click Export. Confirm the saved file opens over `file://` and is **byte-identical** to the CLI's output for the same inputs:
-
-```bash
-cmp /tmp/from-cli.html /tmp/from-app.html && echo "identical"
-```
-Expected: `identical`. They call the same function; any difference means one caller is passing something the other is not.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add src-tauri crates/dbx-web apps/desktop/src
-git commit -m "$(cat <<'EOF'
-feat(docs): export documentation as HTML from the app
-
-The button and `dbx docs` call the same Rust function, so the two cannot
-drift — verified by comparing their output byte-for-byte.
-
-Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
-Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH
-EOF
-)"
-```
-
----
-
-## Task 10: Prove the exported file actually runs
-
-Every test so far checks that the artefact *looks* right. None executes it. This task attempts the one that does.
-
-**Files:**
-- Create: `apps/desktop/src/docs-export/__tests__/exportSmoke.spec.ts`
-
-- [ ] **Step 1: Attempt the happy-dom smoke test**
-
-```ts
-import { execFileSync } from "node:child_process";
-import { readFileSync } from "node:fs";
-import path from "node:path";
-import { beforeAll, describe, expect, it } from "vitest";
-
-// @vitest-environment happy-dom
-
-const htmlPath = path.resolve(__dirname, "../../../../../target/docs-export-smoke.html");
-
-describe("the exported file", () => {
- beforeAll(() => {
- // Generated by a small Rust example so the test exercises the REAL
- // to_standalone_html output rather than a hand-built approximation.
- execFileSync("cargo", ["run", "-p", "dbx-core", "--example", "docs_export_smoke", "--", htmlPath], { stdio: "inherit" });
- });
-
- it("mounts and renders a table name", async () => {
- document.documentElement.innerHTML = readFileSync(htmlPath, "utf8");
- for (const script of Array.from(document.querySelectorAll("script"))) {
- if (script.getAttribute("type") === null) new Function(script.textContent ?? "")();
- }
- await new Promise((resolve) => setTimeout(resolve, 100));
- expect(document.querySelector("#app")?.textContent ?? "").toContain("public.orders");
- });
-});
-```
-
-This needs a `crates/dbx-core/examples/docs_export_smoke.rs` that builds a two-table snapshot, calls `to_standalone_html`, and writes it to `argv[1]`.
-
-- [ ] **Step 2: Run it**
-
-Run: `pnpm vitest run apps/desktop/src/docs-export/__tests__/exportSmoke.spec.ts`
-
-- [ ] **Step 3: Decide honestly**
-
-If it passes, keep it — it is the most valuable test in this part.
-
-**If happy-dom cannot execute the Vue bundle, delete the test rather than weakening it into something that passes without proving anything.** Record in the task report exactly what failed and with what message, and note that the artefact is instead covered by `nothing_is_loaded_from_the_network` plus manual `file://` verification. A test that mounts nothing but asserts `true` is worse than no test, because it reads as coverage.
-
-- [ ] **Step 4: Manual verification either way**
-
-Open the generated file in a real browser over `file://` with the network disabled. Confirm: the index renders with the correct font; a table page opens; the hash updates; a reload lands on the same page; a deep link to a removed table falls back to the index; the language switcher changes the chrome; the diagram renders and clicking a table navigates.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add apps/desktop/src/docs-export crates/dbx-core/examples
-git commit -m "$(cat <<'EOF'
-test(docs): execute the exported file rather than only inspecting it
-
-Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
-Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH
-EOF
-)"
-```
-
----
-
-## Final verification
-
-- [ ] `make check` — format, lint, typecheck, tests
-- [ ] `make cargo-check-fast`
-- [ ] `cargo test -p dbx-core --lib docs`
-- [ ] `pnpm vitest run apps/desktop/src/docs apps/desktop/src/docs-export apps/desktop/src/i18n`
-- [ ] `pnpm build:docs-export && git diff --exit-code crates/dbx-core/assets/` — confirms the committed bundle is what the current sources produce
-- [ ] Update PR #5559's body with the export screenshots and the `dbx docs` usage
-
-Note: `queryStore.test.ts > result cache eviction keeps recently accessed inactive tabs` is a known wall-clock-timeout flake under full-suite load. It passes in isolation and on re-run, and is untouched by this work. Re-run before investigating.
diff --git a/docs/superpowers/plans/2026-08-07-docs-menu-database-scope.md b/docs/superpowers/plans/2026-08-07-docs-menu-database-scope.md
deleted file mode 100644
index c4d68ad889..0000000000
--- a/docs/superpowers/plans/2026-08-07-docs-menu-database-scope.md
+++ /dev/null
@@ -1,309 +0,0 @@
-# Documentation Menu at Database Scope Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Move the "Documentation" context-menu entry out of the object browser's table and view menus and into the sidebar's database and schema context menu, so the entry sits at the scope it actually documents.
-
-**Architecture:** A new `openDocs` action in `useSidebarTreeToolRuntime` writes `connectionStore.docsSource` from the active tree node, exactly as the neighbouring `openDiagram` does. One `items.push` in `buildDatabaseSidebarMenu` exposes it on database and schema nodes. The two `ObjectBrowser.vue` entries and their helper are deleted. No backend, dialog, or viewer code changes.
-
-**Tech Stack:** Vue 3 SFC with `<script setup>`, TypeScript, Pinia (`connectionStore`), vue-i18n, `@lucide/vue` icons, Vitest.
-
-## Global Constraints
-
-- Branch is `fix/docs-menu-database-scope`, cut from `upstream/main` at `29fe57143`. Work on it directly; do not create a worktree.
-- Do not modify `VERSION`, `package.json`, or any file under `crates/`. Version numbers belong to upstream's `scripts/release.mjs`.
-- Do not add an i18n key. `docs.title` already resolves to "Documentation" in all eight locales, added by PR #5559.
-- Icons come from `@lucide/vue`, not `lucide-vue-next`.
-- Do not touch either `t("diagram.open")` menu entry.
-- Reuse the existing `canOpenDiagram` computed as the visibility gate. Do not add a `docs` key to `DATABASE_PRODUCT_CAPABILITY_KEYS`; that is deliberately out of scope and flagged as a follow-up in the PR description.
-
----
-
-## File Structure
-
-| File | Responsibility | Change |
-|---|---|---|
-| `apps/desktop/src/composables/useSidebarTreeToolRuntime.ts` | Sidebar actions that open a tool dialog by writing a `*Source` field on `connectionStore`. | Add `openDocs`; export it. |
-| `apps/desktop/src/composables/__tests__/useSidebarTreeToolRuntime.docs.spec.ts` | Behavioural cover for `openDocs`. | Create. |
-| `apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue` | Builds every sidebar context menu. | Import `BookOpen`, destructure `openDocs`, push one menu item in `buildDatabaseSidebarMenu`. |
-| `apps/desktop/src/components/objects/ObjectBrowser.vue` | Object list panel and its per-object context menus. | Delete the docs entries, the `openDocs` helper, and the orphaned `BookOpen` import. |
-| `apps/desktop/src/components/objects/__tests__/docsMenuPlacement.spec.ts` | Guards the placement so the entry cannot drift back onto table menus. | Create. |
-
----
-
-## Task 1: Sidebar `openDocs` action
-
-**Files:**
-- Modify: `apps/desktop/src/composables/useSidebarTreeToolRuntime.ts:55-64` (insert after `openDiagram`), and the return block at `:132-145`
-- Test: `apps/desktop/src/composables/__tests__/useSidebarTreeToolRuntime.docs.spec.ts` (create)
-
-**Interfaces:**
-- Consumes: `options.activeNode: ShallowRef<TreeNode>` and `options.connectionStore`, both already destructured at the top of `useSidebarTreeToolRuntime`.
-- Produces: `openDocs(): void`, returned from `useSidebarTreeToolRuntime`. It sets `connectionStore.docsSource` to `{ connectionId: string; database: string; schema: string | undefined }`. Task 2 binds this to a menu item.
-
-**Why `schema` is passed through untouched:** `DatabaseDocsDialog.vue:93` reads `props.prefillSchema ? [props.prefillSchema] : []`. An `undefined` schema therefore sends an empty schema list, which the collector treats as "everything it finds" — the whole database. A database tree node has no `schema`, a schema node does, so forwarding the field verbatim gives both scopes for free.
-
-**Why no `tableName`:** `openDiagram` passes one because the diagram dialog has a `tableName` prop. `DatabaseDocsDialog` has only `prefillConnectionId`, `prefillDatabase`, and `prefillSchema`. Passing `tableName` would be dead data.
-
-- [ ] **Step 1: Write the failing test**
-
-Create `apps/desktop/src/composables/__tests__/useSidebarTreeToolRuntime.docs.spec.ts`.
-
-The composable imports only types plus two pure helpers from `@/lib/sidebar/sidebarExportRuntime`, so no `vi.mock` is needed. `queryStore`, `settingsStore`, and `tableChildObjectName` are unused by `openDocs`; they are passed as minimal stubs because the options object requires them.
-
-```ts
-import { shallowRef } from "vue";
-import { describe, expect, it } from "vitest";
-import type { TreeNode } from "@/types/database";
-
-import { useSidebarTreeToolRuntime } from "@/composables/useSidebarTreeToolRuntime";
-
-function setup(node: Partial<TreeNode>) {
- const activeNode = shallowRef({ id: "n-1", label: "node", children: [], ...node } as TreeNode);
- const connectionStore = { docsSource: null as unknown };
- const runtime = useSidebarTreeToolRuntime({
- activeNode,
- connectionStore: connectionStore as never,
- queryStore: {} as never,
- settingsStore: {} as never,
- tableChildObjectName: () => "",
- });
- return { connectionStore, runtime };
-}
-
-describe("useSidebarTreeToolRuntime openDocs", () => {
- it("documents the whole database when invoked on a database node", () => {
- const { connectionStore, runtime } = setup({ type: "database", label: "shop", connectionId: "conn-1", database: "shop" });
-
- runtime.openDocs();
-
- // An absent schema is what makes the collector document every schema.
- expect(connectionStore.docsSource).toEqual({ connectionId: "conn-1", database: "shop", schema: undefined });
- });
-
- it("narrows to a single schema when invoked on a schema node", () => {
- const { connectionStore, runtime } = setup({ type: "schema", label: "public", connectionId: "conn-1", database: "shop", schema: "public" });
-
- runtime.openDocs();
-
- expect(connectionStore.docsSource).toEqual({ connectionId: "conn-1", database: "shop", schema: "public" });
- });
-
- it("does nothing when the node carries no database", () => {
- const { connectionStore, runtime } = setup({ type: "connection", label: "local", connectionId: "conn-1" });
-
- runtime.openDocs();
-
- expect(connectionStore.docsSource).toBeNull();
- });
-});
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `npx vitest run apps/desktop/src/composables/__tests__/useSidebarTreeToolRuntime.docs.spec.ts`
-
-Expected: FAIL. All three cases error with `runtime.openDocs is not a function`.
-
-- [ ] **Step 3: Write the implementation**
-
-In `apps/desktop/src/composables/useSidebarTreeToolRuntime.ts`, insert immediately after the closing brace of `openDiagram` (currently line 64):
-
-```ts
- function openDocs() {
- const node = activeNode.value;
- if (!node.connectionId || !node.database) return;
- connectionStore.docsSource = {
- connectionId: node.connectionId,
- database: node.database,
- // A database node has no schema, and an absent schema is what tells the
- // collector to document every schema in the database.
- schema: node.schema,
- };
- }
-```
-
-Then add `openDocs,` to the returned object, keeping the existing alphabetical order — between `openDiagram,` and `openFieldLineage,`:
-
-```ts
- return {
- openAllDatabasesExport,
- openDataCompare,
- openDatabaseExport,
- openDatabaseSearch,
- openDiagram,
- openDocs,
- openFieldLineage,
- openScheduledBackups,
- openSchemaDiff,
- openSqlFileExecution,
- openStructureEditor,
- openTableImport,
- openTransfer,
- };
-```
-
-- [ ] **Step 4: Run the test to verify it passes**
-
-Run: `npx vitest run apps/desktop/src/composables/__tests__/useSidebarTreeToolRuntime.docs.spec.ts`
-
-Expected: PASS, 3 tests.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add apps/desktop/src/composables/useSidebarTreeToolRuntime.ts apps/desktop/src/composables/__tests__/useSidebarTreeToolRuntime.docs.spec.ts
-git commit -m "feat(docs): add a sidebar action opening documentation for a node"
-```
-
----
-
-## Task 2: Move the menu entry
-
-**Files:**
-- Modify: `apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue:13` (icon import), `:312` (destructure), `:4204-4206` (menu push)
-- Modify: `apps/desktop/src/components/objects/ObjectBrowser.vue:9` (icon import), `:1466-1474` (helper), `:2666-2671` and `:2721-2726` (menu entries)
-- Test: `apps/desktop/src/components/objects/__tests__/docsMenuPlacement.spec.ts` (create)
-
-**Interfaces:**
-- Consumes: `openDocs()` from Task 1, reached through the existing `useSidebarTreeToolRuntime(...)` destructure at `SidebarTreeRuntimeHost.vue:312`.
-- Produces: no new exports.
-
-**Why the single push covers both node types:** line 4204 sits inside `buildDatabaseSidebarMenu` (lines 4147-4259), whose outer guard is `node.type === "database" || node.type === "schema"`. The other `t("diagram.open")` push, at line 4483, is in `buildObjectSidebarMenu` and must be left alone.
-
-**On the placement test:** this repository contains both mounted component specs and source-text specs. A mounted test is impractical for a 4700-line SFC whose menus are assembled from dozens of store-backed computeds, and the behaviour that matters — what `openDocs` writes — is already covered by Task 1. The spec below is a deliberately narrow placement guard: it asserts which file registers `docs.title`, nothing about rendering. Do not extend it into a substitute for behavioural cover.
-
-- [ ] **Step 1: Write the failing test**
-
-Create `apps/desktop/src/components/objects/__tests__/docsMenuPlacement.spec.ts`:
-
-```ts
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { describe, expect, it } from "vitest";
-
-function source(relative: string): string {
- return readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");
-}
-
-describe("documentation menu placement", () => {
- it("registers the entry in the sidebar database menu", () => {
- // The docs viewer documents a database or a schema, so it belongs on the
- // tree nodes that name one.
- expect(source("../../sidebar/SidebarTreeRuntimeHost.vue")).toContain('t("docs.title"), action: openDocs');
- });
-
- it("keeps the entry off per-object menus", () => {
- // openDocs never read the row's table: a table-level entry advertised a
- // scope the viewer cannot render.
- expect(source("../ObjectBrowser.vue")).not.toContain("docs.title");
- });
-});
-```
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `npx vitest run apps/desktop/src/components/objects/__tests__/docsMenuPlacement.spec.ts`
-
-Expected: FAIL, both cases. The first fails because `SidebarTreeRuntimeHost.vue` has no `docs.title`; the second fails because `ObjectBrowser.vue` still has two.
-
-- [ ] **Step 3: Register the entry in the sidebar**
-
-In `apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue`:
-
-Add `BookOpen,` as the first name in the `@lucide/vue` import block, immediately after `import {` on line 13. The block is not alphabetically ordered, so position is a matter of readability only:
-
-```ts
-import {
- BookOpen,
- Database,
- ChevronsDown,
-```
-
-Add `openDocs` to the destructure on line 312, keeping alphabetical order:
-
-```ts
-const { openAllDatabasesExport, openDataCompare, openDatabaseExport, openDatabaseSearch, openDiagram, openDocs, openFieldLineage, openScheduledBackups, openSchemaDiff, openSqlFileExecution, openStructureEditor, openTableImport, openTransfer } = useSidebarTreeToolRuntime({
-```
-
-Replace lines 4204-4206:
-
-```ts
- if (canOpenDiagram.value) {
- items.push({ label: t("diagram.open"), action: openDiagram, icon: Network });
- items.push({ label: t("docs.title"), action: openDocs, icon: BookOpen });
- }
-```
-
-- [ ] **Step 4: Remove the object browser entries**
-
-In `apps/desktop/src/components/objects/ObjectBrowser.vue`:
-
-Delete `BookOpen,` from the icon import on line 9. It has no other use in the file.
-
-Delete the `openDocs` helper, lines 1466-1474 inclusive, together with the blank line that followed it:
-
-```ts
-function openDocs(row: ObjectBrowserRow) {
- // The docs viewer documents the whole schema rather than one object, so the
- // row only supplies which schema to collect.
- connectionStore.docsSource = {
- connectionId: props.connection.id,
- database: props.database,
- schema: row.schema || selectedSchema.value,
- };
-}
-```
-
-In `getTableMenuItems`, collapse lines 2666-2671 back to the single-entry form:
-
-```ts
- ...(canOpenDiagram.value ? [{ label: t("diagram.open"), action: () => openDiagram(item), icon: Network }] : []),
-```
-
-In `getViewMenuItems`, collapse lines 2721-2726 to exactly the same single line.
-
-- [ ] **Step 5: Run the placement test to verify it passes**
-
-Run: `npx vitest run apps/desktop/src/components/objects/__tests__/docsMenuPlacement.spec.ts`
-
-Expected: PASS, 2 tests.
-
-- [ ] **Step 6: Typecheck**
-
-Run: `pnpm typecheck`
-
-Expected: no errors. This is what catches a stale `BookOpen` reference or a mistyped `openDocs` in the destructure. An unused-import error here means step 4 removed a menu entry but left the icon, or the reverse.
-
-- [ ] **Step 7: Run the surrounding suites**
-
-Run: `npx vitest run apps/desktop/src/composables apps/desktop/src/components/objects apps/desktop/src/components/sidebar`
-
-Expected: PASS. No existing spec asserts on the docs menu entries, so nothing should need updating. If a sidebar spec fails on menu-item counts or ordering, that spec is the source of truth for the menu's shape — read it before changing it.
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue apps/desktop/src/components/objects/ObjectBrowser.vue apps/desktop/src/components/objects/__tests__/docsMenuPlacement.spec.ts
-git commit -m "fix(docs): move Documentation to the database context menu"
-```
-
----
-
-## Manual verification
-
-Automated cover stops at "the right store field gets the right value". Confirm the dialog end of the wire once, by hand:
-
-```bash
-pnpm dev
-```
-
-1. Right-click a PostgreSQL database node in the connections sidebar. "Documentation" appears directly below "View Diagram", with a book icon.
-2. Click it. The viewer opens listing tables from **every** schema in that database, not just `public`.
-3. Close it, right-click a schema node, pick "Documentation". Only that schema's tables are listed.
-4. Open the object browser for the same database and right-click a table. There is no "Documentation" entry; "View Diagram" is still there.
-5. Right-click a Redis or MongoDB connection's database node. No "Documentation" entry, because `supportsSchemaDiagram` is false for those drivers — the same visibility set that shipped in v0.5.77.
-
-## Pull request
-
-Target `t8y2/dbx`, base `main`. The description should state that PR #5559's entry point never used the row's table (`ObjectBrowser.vue:1466` read only `row.schema`), so this is a placement correction rather than a feature change, and should flag the follow-up the spec records: documentation visibility currently rides on `supportsSchemaDiagram`, and a dedicated `docs` capability key in `database-drivers.manifest.json` is worth considering separately.
diff --git a/docs/superpowers/specs/2026-06-08-sql-formatter-config-design.md b/docs/superpowers/specs/2026-06-08-sql-formatter-config-design.md
deleted file mode 100644
index 7d1a4d0a6e..0000000000
--- a/docs/superpowers/specs/2026-06-08-sql-formatter-config-design.md
+++ /dev/null
@@ -1,169 +0,0 @@
-# SQL Formatter Configuration Design
-
-## Summary
-
-DBX will add a lightweight SQL formatter configuration experience. Users can tune formatter options in a settings window, import and export a small JSON configuration file, and use a capable JSON editor inside that window. The editor shortcuts are part of the configuration window experience only; they are not stored in the SQL formatter configuration file.
-
-## Goals
-
-- Let users customize SQL formatting without replacing the existing `sql-formatter` dependency.
-- Keep startup and idle memory low by loading formatter and advanced JSON editor code only when needed.
-- Support importing and exporting a dedicated SQL formatter configuration file.
-- Provide a comfortable JSON configuration editor in the SQL formatter settings window.
-- Make editor shortcuts work consistently on Windows, Linux, and macOS.
-- Validate imported configuration before applying it to stored editor settings.
-
-## Non-Goals
-
-- Do not introduce Monaco, Prettier, WASM parsers, or multiple formatter engines.
-- Do not turn this into a full editor profile export system.
-- Do not store configuration-window shortcuts in the SQL formatter configuration file.
-- Do not run SQL formatting automatically while typing.
-- Do not implement per-connection formatter profiles in the first version.
-
-## Current Context
-
-The current formatter path is intentionally small:
-
-- `apps/desktop/src/lib/sqlFormatter.ts` imports `format` from `sql-formatter`.
-- `formatSqlText(sql, dialect)` maps the DBX dialect to the formatter language.
-- The only current formatting option is `keywordCase: "upper"`.
-- `QueryEditor.vue` calls `formatSqlText()` only when the user triggers SQL formatting.
-- Editor settings already live in `settingsStore.editorSettings` and are persisted through `localStorage`.
-
-This design keeps that structure and adds a typed formatter settings object to the existing editor settings.
-
-## Configuration File
-
-The imported and exported file is a dedicated SQL formatter config:
-
-```json
-{
- "version": 1,
- "formatter": "sql-formatter",
- "options": {
- "keywordCase": "upper",
- "functionCase": "preserve",
- "dataTypeCase": "preserve",
- "indentStyle": "spaces",
- "tabWidth": 2,
- "linesBetweenQueries": 1,
- "expressionWidth": 80,
- "semicolonNewline": false
- }
-}
-```
-
-`version` enables future migrations. `formatter` must be `sql-formatter` in the first version. `options` contains only validated SQL formatter options. Unknown top-level fields are ignored during import. Unknown option fields are rejected with a validation message so users can find mistakes in hand-edited files.
-
-## Stored Settings
-
-Add `sqlFormatter` to `EditorSettings`:
-
-```ts
-interface SqlFormatterSettings {
- keywordCase: "upper" | "lower" | "preserve";
- functionCase: "upper" | "lower" | "preserve";
- dataTypeCase: "upper" | "lower" | "preserve";
- indentStyle: "spaces" | "tabs";
- tabWidth: 2 | 4;
- linesBetweenQueries: 0 | 1 | 2;
- expressionWidth: 50 | 80 | 120;
- semicolonNewline: boolean;
-}
-```
-
-Normalization clamps every field to a known value. Missing fields fall back to defaults. Existing users get the current behavior by default: uppercase keywords and two-space readable formatting.
-
-The exact mapping to `sql-formatter` options should be confirmed against the installed `[email protected]` type definitions during implementation. Unsupported options are hidden rather than simulated with fragile string rewriting.
-
-## Settings Window
-
-The SQL formatter settings window has two modes:
-
-- Form mode: select controls for common options such as keyword case, indentation, line spacing, and expression width.
-- Advanced JSON mode: a JSON editor for the same configuration envelope used by import and export.
-
-Both modes edit the same local draft. Applying settings normalizes and persists the draft. Canceling closes the dialog without touching stored settings.
-
-The window includes:
-
-- Import config
-- Export config
-- Restore defaults
-- Validate
-- Apply
-
-Import reads the file once, validates it, updates the local draft, and shows validation errors without applying partial invalid state. Export writes the normalized draft as pretty JSON.
-
-## JSON Editor Shortcuts
-
-The advanced JSON editor should reuse CodeMirror instead of adding a heavier editor. It supports common editing actions with platform-aware shortcuts:
-
-| Action | Windows/Linux | macOS |
-| --- | --- | --- |
-| Undo | `Ctrl+Z` | `Cmd+Z` |
-| Redo | `Ctrl+Y`, `Ctrl+Shift+Z` | `Cmd+Shift+Z` |
-| Find | `Ctrl+F` | `Cmd+F` |
-| Replace | `Ctrl+H` | `Cmd+Alt+F` or an in-window button |
-| Select all | `Ctrl+A` | `Cmd+A` |
-| Indent more | `Tab` | `Tab` |
-| Indent less | `Shift+Tab` | `Shift+Tab` |
-| Duplicate current line | `Ctrl+D` | `Cmd+D` |
-| Delete current line | `Ctrl+Shift+K` | `Cmd+Shift+K` |
-| Move line up/down | `Alt+Up/Down` | `Option+Up/Down` |
-| Copy line up/down | `Shift+Alt+Up/Down` | `Shift+Option+Up/Down` |
-| Format config JSON | `Shift+Alt+F` | `Shift+Option+F` |
-| Apply config | `Ctrl+S` | `Cmd+S` |
-
-Most of these actions come from CodeMirror's existing commands and keymaps. `Duplicate current line` can use `copyLineDown`. `Indent less` can use `indentLess`. The JSON editor uses platform-sensitive display labels, while the command mapping uses CodeMirror's `Mod` abstraction where appropriate.
-
-These shortcuts are local to the SQL formatter configuration window. They do not change the main SQL editor shortcut settings and are not written into exported formatter config files.
-
-## Low-Memory Strategy
-
-- Keep `sql-formatter` as the only SQL formatting engine.
-- Lazy-load `sql-formatter` when the user formats SQL or opens the formatter settings preview.
-- Lazy-load CodeMirror JSON support only when the user opens Advanced JSON mode.
-- Store only a small normalized settings object, not generated formatter state.
-- Format only on explicit user action.
-- Add a size guard for SQL text. Very large SQL should prompt before formatting or skip formatting with a clear message.
-- Avoid background workers in the first version unless formatting proves to block the UI on realistic input.
-
-## Data Flow
-
-1. User opens SQL formatter settings.
-2. The window copies `settingsStore.editorSettings.sqlFormatter` into a local draft.
-3. Form controls or JSON editor update the draft.
-4. Validation normalizes the draft and reports errors.
-5. Apply persists the normalized settings through `settingsStore.updateEditorSettings()`.
-6. SQL formatting calls `formatSqlText(sql, dialect, sqlFormatterSettings)`.
-7. `formatSqlText()` maps DBX settings to `sql-formatter` options and returns formatted SQL.
-
-## Error Handling
-
-- Blank SQL remains unchanged.
-- Invalid JSON in Advanced mode shows a local validation error and disables Apply.
-- Invalid imported files do not mutate stored settings.
-- Unsupported formatter names are rejected.
-- Unsupported option values are rejected with field-specific messages.
-- Formatter runtime errors keep the existing `formatError` event path and toast behavior.
-
-## Testing
-
-Add focused tests for:
-
-- Default SQL formatter settings preserve current formatting behavior.
-- Settings normalization clamps invalid values to defaults.
-- Exported config is stable and contains only allowed fields.
-- Imported config accepts valid files and rejects invalid files.
-- `formatSqlText()` maps settings to formatter options.
-- Blank SQL remains unchanged.
-- Advanced JSON editor keymap includes `Shift+Tab`, duplicate line, delete line, move line, copy line, and apply shortcuts.
-
-Manual verification should include:
-
-- Windows/Linux shortcut behavior using `Ctrl`.
-- macOS shortcut behavior using `Cmd`.
-- Import/export round trip.
-- No large formatter/editor code loaded before formatting or opening Advanced JSON mode, checked through the built bundle chunks.
diff --git a/docs/superpowers/specs/2026-07-06-gridfs-manager-filter-sort-design.md b/docs/superpowers/specs/2026-07-06-gridfs-manager-filter-sort-design.md
deleted file mode 100644
index 08122bb3a7..0000000000
--- a/docs/superpowers/specs/2026-07-06-gridfs-manager-filter-sort-design.md
+++ /dev/null
@@ -1,247 +0,0 @@
-# GridFS Manager Filter And Sort Design
-
-**Date:** 2026-07-06
-
-## Goal
-
-Extend the existing GridFS manager and bucket browser so MongoDB users can filter and sort GridFS data without leaving the dedicated GridFS workflow.
-
-This work covers three user-facing improvements:
-
-- add query-style filter and sort controls to the GridFS file list
-- add filter and sort controls to the GridFS bucket manager
-- make the GridFS sidebar node more visually distinct from regular Mongo collections
-
-## Background
-
-The dedicated GridFS browser shipped on 2026-07-03 and already provides:
-
-- a single `GridFS` sidebar entry per Mongo database
-- a database-level manager page for bucket CRUD
-- a bucket-level file browser for upload, download, and delete
-
-Issue #2589 reports that the new Mongo manager flow still lacks filtering. The current UI shows static tables only:
-
-- `MongoGridFsBrowser.vue` lists bucket summaries with no filter or sort controls
-- `MongoBucketBrowser.vue` lists bucket files with a fixed default ordering
-- the backend `list_gridfs_files` API always runs an empty `find({})` with a built-in descending upload date sort
-
-The goal of this iteration is to keep the dedicated GridFS UX, but make it feel closer to the existing Mongo document query experience.
-
-## Current State
-
-### File browser
-
-`MongoBucketBrowser.vue` currently:
-
-- loads every file in the selected bucket
-- shows a table with metadata columns
-- supports upload, download, delete, refresh
-- has no filter input
-- has no user-controlled sort
-- has no query preview
-
-### Bucket manager
-
-`MongoGridFsBrowser.vue` currently:
-
-- loads every GridFS bucket summary for the database
-- shows bucket name, file count, and total size
-- supports create, delete, open, refresh
-- has no filter input
-- has no user-controlled sort
-
-### Sidebar
-
-`TreeItem.vue` currently renders:
-
-- `mongo-gridfs` and `mongo-buckets` with `Archive` plus amber styling
-- `mongo-bucket` with a very similar `Archive` plus lighter amber styling
-
-This makes the GridFS entry readable, but not especially distinct from other MongoDB tree nodes.
-
-## Requirements
-
-### Functional
-
-- users can filter GridFS files within a bucket
-- users can sort GridFS files within a bucket
-- users can filter GridFS buckets within a database
-- users can sort GridFS buckets within a database
-- file-list sorting works both from explicit sort input and column-header sort actions
-- the GridFS sidebar entry has a clearer dedicated visual treatment
-
-### Behavioral
-
-- existing upload, download, delete, create, and open flows keep working
-- existing callers that omit new query parameters retain current behavior
-- invalid filter or sort input produces visible errors rather than silent fallback
-
-## Chosen Approach
-
-### Query model
-
-Use one consistent principle across both GridFS pages:
-
-- execute filter and sort on the server
-- keep frontend controls visually aligned with the document query UI
-- only reuse document-query semantics where the underlying data shape supports it cleanly
-
-### Bucket file browser
-
-The file browser should closely mirror Mongo document query behavior.
-
-Frontend:
-
-- add `filter` and `sort` text inputs to `MongoBucketBrowser.vue`
-- show a query preview string for the effective GridFS file query
-- trigger reload on Enter, refresh click, and table-header sort changes
-- map header sort actions back into the `sort` input, matching `DocumentBrowser.vue`
-
-Backend:
-
-- extend the GridFS file list API to accept optional `filter` and `sort` strings
-- parse them with the same Mongo document parsing helpers already used by document queries
-- run the query against `<bucket>.files` as `find(filter).sort(sort)`
-- preserve the existing default sort of `uploadDate desc, _id desc` when no sort is provided
-
-Preview format:
-
-- use `db.getCollection("<bucket>.files").find(...).sort(...).skip(0).limit(...)` style output
-- the preview exists for transparency and consistency, even if the file browser continues returning a plain row list instead of a paged document result object
-
-### Bucket manager
-
-The bucket manager should adopt the same interaction style, but not pretend bucket summaries are raw Mongo documents.
-
-Frontend:
-
-- add a lightweight `filter` input for bucket-name matching
-- add a sort control that behaves like the existing query toolbar and table-header sorting
-- keep the manager table focused on `name`, `fileCount`, and `totalBytes`
-
-Backend:
-
-- extend the bucket list API to accept optional filter and sort parameters
-- filter bucket summaries by normalized bucket name match
-- sort bucket summaries by one of:
- - `name`
- - `fileCount`
- - `totalBytes`
-- default to `name asc` when no explicit sort is provided
-
-This gives the manager page service-side filtering and sorting while staying honest about the underlying data model, which is aggregated summary data rather than a directly queried collection.
-
-### Sidebar icon treatment
-
-Keep the existing icon family but make the top-level GridFS entry visually stand apart.
-
-- `mongo-gridfs`: keep `Archive` but switch to a more distinctive cool color so it no longer blends with ordinary Mongo tree items
-- `mongo-bucket`: keep the same icon family with a related but softer shade
-
-The goal is recognition, not a broad tree redesign.
-
-## Architecture
-
-### Backend layers
-
-Update the GridFS query path across all transport layers:
-
-- `crates/dbx-core/src/db/mongo_driver.rs`
-- `crates/dbx-core/src/document_ops.rs`
-- `src-tauri/src/commands/document_cmd.rs`
-- `crates/dbx-web/src/routes/document_store.rs`
-- `apps/desktop/src/lib/backend/tauri.ts`
-- `apps/desktop/src/lib/backend/http.ts`
-
-The backend remains backward compatible by treating all new parameters as optional.
-
-### Frontend layers
-
-Update the dedicated GridFS views:
-
-- `apps/desktop/src/components/document/MongoBucketBrowser.vue`
-- `apps/desktop/src/components/document/MongoGridFsBrowser.vue`
-
-Reuse document-query support where it fits:
-
-- `apps/desktop/src/lib/app/documentStoreProvider.ts`
-
-Update the sidebar presentation in:
-
-- `apps/desktop/src/components/sidebar/TreeItem.vue`
-
-## Data Flow
-
-### File browser
-
-1. User opens a GridFS bucket tab.
-2. `MongoBucketBrowser.vue` builds the current `filter` and `sort` state.
-3. Frontend sends the new parameters through the shared document-store API.
-4. Rust applies the filter and sort to `<bucket>.files`.
-5. The returned file list renders in the table and side detail panel.
-6. If the user clicks a sortable header, the UI rewrites the `sort` input and reloads.
-
-### Bucket manager
-
-1. User opens the `GridFS` manager tab.
-2. `MongoGridFsBrowser.vue` sends current manager filter and sort state.
-3. Rust collects bucket summaries, filters them, sorts them, and returns the list.
-4. The manager table and summary pane update in place.
-
-## Error Handling
-
-- invalid Mongo-style file filter input should surface as a visible page error
-- invalid file sort input should surface as a visible page error
-- unsupported bucket-manager sort fields should return a clear backend error
-- empty filter input should behave like no filter
-- missing sort input should fall back to the page default sort
-- write operations continue to use the existing read-only safeguards
-
-## Testing
-
-### Frontend
-
-Add or update Vitest coverage for:
-
-- GridFS query preview formatting in `documentStoreProvider`
-- request assembly for GridFS file filter and sort loading
-- request assembly for GridFS bucket filter and sort loading
-- sidebar icon and color mapping for `mongo-gridfs` and `mongo-bucket`
-
-### Backend
-
-Add Rust coverage for:
-
-- GridFS file filter parsing
-- default file sort fallback
-- explicit file sort handling
-- bucket summary filtering
-- bucket summary sorting by supported fields
-
-## Scope Boundaries
-
-### Included now
-
-- service-side GridFS file filtering
-- service-side GridFS file sorting
-- service-side GridFS bucket filtering
-- service-side GridFS bucket sorting
-- query-style toolbar inputs for the file browser
-- visually improved GridFS sidebar node styling
-
-### Not included now
-
-- pagination contract changes for GridFS APIs
-- turning bucket summaries into full Mongo document queries
-- advanced bucket filter builders
-- drag-and-drop upload improvements
-- inline file editing or file preview
-
-## Success Criteria
-
-- users can narrow GridFS files with Mongo-style filter input
-- users can sort GridFS files from either toolbar input or table headers
-- users can narrow and sort GridFS bucket summaries from the manager page
-- the dedicated GridFS sidebar node is easier to distinguish at a glance
-- existing GridFS CRUD flows keep working without regression
diff --git a/docs/superpowers/specs/2026-07-16-field-mapping-dialog-design.md b/docs/superpowers/specs/2026-07-16-field-mapping-dialog-design.md
deleted file mode 100644
index 68e9b6af53..0000000000
--- a/docs/superpowers/specs/2026-07-16-field-mapping-dialog-design.md
+++ /dev/null
@@ -1,167 +0,0 @@
-# 字段类型映射:独立弹窗 + 导入/导出
-
-日期:2026-07-16
-状态:已批准(待实现)
-
-## 背景 / 问题
-
-在"比较架构"配置步骤(`SchemaDiffConfigStep.vue`)中,字段类型映射面板
-(`FieldMappingPanel`)直接内嵌在配置步骤里,没有内部滚动。当用户添加大量
-映射条目时,面板会把底部的操作栏(保存配置 / 加载配置 / 选项 / 开始比较)
-顶出视口,导致这些按钮无法点击、看不到。
-
-用户要求:在"选项"按钮后面增加一个"字段类型映射"按钮,点击打开一个独立的
-页面/弹窗来配置映射;并且该弹窗需要支持以 JSON 格式导入、导出映射配置,
-参考现有导出功能。
-
-## 目标
-
-1. 字段类型映射添加再多,配置步骤底部的操作栏始终可见、可点击。
-2. 提供独立弹窗编辑映射,体验与现有"选项"弹窗一致。
-3. 弹窗内支持映射配置的 JSON 导入与导出。
-
-## 非目标(YAGNI)
-
-- 不新增映射列表内的搜索/过滤框(后续可加)。
-- 不改动 Rust 侧逻辑(`FieldMapping` / `generate_schema_sync_sql` 已在上一个
- 会话修复)。
-- 不改动配置整体的保存/加载/历史逻辑。
-
-## 方案
-
-采用方案 A:在"选项"按钮后增加一个"字段类型映射"按钮,点击打开一个叠加
-Dialog(overlay),与现有"选项"弹窗(`SchemaDiffDialog` 的 `showOptionsPanel`)
-同一风格。
-
-### 1. 组件结构
-
-- **新建 `apps/desktop/src/components/diff/FieldMappingDialog.vue`**
- - 复用 `SchemaDiffDialog` 的 overlay 模式:`absolute inset-0 bg-background/80
- backdrop-blur-sm z-50 flex items-center justify-center`,内层
- `bg-card border rounded-lg shadow-lg w-[760px] max-w-[calc(100vw-2rem)]
- max-h-[80vh] overflow-auto p-4`。
- - 内部渲染 `FieldMappingPanel`(`source-db-type` / `target-db-type` /
- `:mappings` / `@update:mappings`)。
- - 底部操作栏:导入 / 导出 / 完成(✕ 关闭在右上角)。
- - Props:`open: boolean`、`mappings: FieldMappingEntry[]`、
- `sourceDbType: string`、`targetDbType: string`。
- - Emits:`update:open(boolean)`、`save(FieldMappingEntry[])`。
- - 打开时把 `mappings` 深拷贝为本地 `editingMappings`(单向数据流,取消不写回)。
-
-- **改动 `apps/desktop/src/components/diff/SchemaDiffConfigStep.vue`**
- - 在"选项"按钮(`@show-options`)之后、同一 `<div class="flex items-center gap-2">`
- 内,插入"字段类型映射"按钮:`v-if="showFieldMapping"`,
- `@click="$emit('open-field-mapping')"`,文案 `t('diff.openFieldMapping')`,
- 图标 `ListChecks` 或 `ArrowLeftRight`。
- - 保留现有内嵌 `<FieldMappingPanel>`(行 429)作为快捷入口,行为不变。
- - `defineEmits` 新增 `(e: "open-field-mapping"): void;`。
-
-- **改动 `apps/desktop/src/components/diff/SchemaDiffDialog.vue`**
- - 新增 `const showFieldMappingDialog = ref(false);`
- - `<SchemaDiffConfigStep>` 增加 `@open-field-mapping="showFieldMappingDialog = true"`。
- - 在 `showOptionsPanel` overlay 之后,新增 `<FieldMappingDialog>`:
- - `:open="showFieldMappingDialog"`
- - `:mappings="activeConfig?.options.fieldMappings ?? []"`
- - `:source-db-type="sourceDbType"`、`:target-db-type="targetDbType"`
- (沿用 `SchemaDiffConfigStep` 中既有的 source/target db type 取值方式)
- - `@update:open="showFieldMappingDialog = $event"`
- - `@save="handleFieldMappingsUpdate"`(复用现有写回函数,签名一致:
- `(v: FieldMappingEntry[]) => void`)
-
-### 2. 数据流(单向,与 Options 一致)
-
-打开弹窗 → 用当前 `fieldMappings` 深拷贝为本地 `editingMappings`
-(`JSON.parse(JSON.stringify(...))` 或 `map` 拷贝)→ 弹窗内增删改只动本地副本
-→ 点"完成" → `emit('save', editingMappings)` → `handleFieldMappingsUpdate`
-写回 `activeConfig.options.fieldMappings` → 关闭弹窗。
-点遮罩 / ✕ 仅关闭,不写回(取消)。
-
-### 3. 导入 / 导出(JSON)
-
-参考现有 `TagManagementPanel.handleExport`(Blob 下载)与
-`useSchemaDiffConfig`(JSON 解析校验)。
-
-- **导出**(`FieldMappingDialog` 内 `handleExport`):
- ```ts
- const blob = new Blob([JSON.stringify(editingMappings, null, 2)], { type: "application/json" });
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = "field-mappings.json";
- a.click();
- URL.revokeObjectURL(url);
- ```
-
-- **导入**(`FieldMappingDialog` 内 `handleImport` + 隐藏 file input):
- - `<input ref="fileInputRef" type="file" accept=".json,application/json" class="hidden" @change="onFileSelected" />`
- - 读取文本 → `JSON.parse` → 校验为数组且每项含 `sourceType` / `targetType` /
- `paramStrategy`(缺 `paramStrategy` 默认 `"preserve"`,缺 `customParams`
- 默认 `undefined`)→ 替换本地 `editingMappings`。
- - 解析失败或结构不合法:`toast(t('diff.fieldMapping.importError'))` 并报错,
- 不替换。
-
-- **JSON 结构**:即 `FieldMappingEntry[]`:
- ```json
- [
- { "sourceType": "VARCHAR", "targetType": "character", "paramStrategy": "preserve" },
- { "sourceType": "DECIMAL", "targetType": "numeric", "paramStrategy": "custom", "customParams": "(10,2)" }
- ]
- ```
- 与运行时 / Rust 侧 `FieldMapping` 对齐,可被 `generate_schema_sync_sql`
- 直接消费。
-
-### 4. 滚动与可达性(根本修复)
-
-- 弹窗内部 `max-h-[80vh] overflow-auto`:映射再多也在弹窗内滚动,绝不撑出视口。
-- 同时给 `FieldMappingPanel` 的映射列表容器(`v-else` 分支根 `div`)加
- `max-h-[40vh] overflow-auto` 作为内嵌兜底,保证即便内嵌面板也滚动。
-
-### 5. i18n
-
-复用现有 `diff.fieldMapping.*` 键。新增(zh-CN / en,其余语言按现有
-`exportConfig`/`importConfig` 模式补,本次至少保证 zh-CN + en):
-
-- `diff.openFieldMapping`:打开字段类型映射弹窗的按钮文案
- (zh-CN: "字段类型映射";en: "Field Type Mapping")
-- `diff.fieldMapping.import`:导入(zh-CN: "导入";en: "Import")
-- `diff.fieldMapping.export`:导出(zh-CN: "导出";en: "Export")
-- `diff.fieldMapping.importError`:导入失败提示
- (zh-CN: "导入失败:文件不是合法的字段类型映射 JSON";
- en: "Import failed: file is not a valid field type mapping JSON")
-- `diff.fieldMapping.done`:完成按钮(zh-CN: "完成";en: "Done")
-
-位置:zh-CN.ts 的 `schemaDiff.fieldMapping` 对象内(约 2444 行);
-en.ts 的 `schemaDiff.fieldMapping` 对象内(约 2457 行)。
-
-### 6. 测试 / 验收
-
-纯前端改动,无 Rust 逻辑变更。手动验收(`pnpm dev`):
-
-1. 打开"比较架构"弹窗,源/目标选择不同类型(触发 `showFieldMapping`)。
-2. 点"选项"后的"字段类型映射"按钮 → 弹出独立弹窗。
-3. 在弹窗内添加大量映射,确认弹窗内部可滚动、底部"导入/导出/完成"始终可点。
-4. 点"导出" → 下载 `field-mappings.json`,内容正确。
-5. 清空映射后点"导入",选择刚导出的 json → 映射恢复。
-6. 点"完成" → 映射写回配置步骤;关闭弹窗后配置步骤底部操作栏(保存/加载/
- 选项/开始比较)始终可见可点。
-7. 点遮罩 / ✕ 关闭弹窗 → 本地未"完成"的修改不写回。
-
-类型检查:`pnpm typecheck`(仅关注本次改动文件无新增错误;已知 2 个与本次无关的
-预存错误:`dbAdminSql.ts` / `McpServerStatus.node_path`)。
-
-## 受影响文件
-
-- 新建 `apps/desktop/src/components/diff/FieldMappingDialog.vue`
-- 改 `apps/desktop/src/components/diff/SchemaDiffConfigStep.vue`
-- 改 `apps/desktop/src/components/diff/SchemaDiffDialog.vue`
-- 改 `apps/desktop/src/i18n/locales/zh-CN.ts`
-- 改 `apps/desktop/src/i18n/locales/en.ts`
-- (可选,非必须)其他语言 locale 的 `schemaDiff.fieldMapping` 补键
-
-## 风险 / 注意
-
-- `FieldMappingPanel` 现有 `space-y-3` 列表容器加上 `max-h` + `overflow-auto`
- 后,嵌套在弹窗的 `overflow-auto` 里可能产生双重滚动条;需实测,优先让弹窗
- 外层滚动,内层列表仅在高度受限时滚动。
-- 导入校验要宽松:允许缺省 `customParams` / `paramStrategy`,避免严格校验把
- 合法旧配置拒掉。
diff --git a/docs/superpowers/specs/2026-07-21-connection-list-alphabetical-sort-design.md b/docs/superpowers/specs/2026-07-21-connection-list-alphabetical-sort-design.md
deleted file mode 100644
index 37849a3221..0000000000
--- a/docs/superpowers/specs/2026-07-21-connection-list-alphabetical-sort-design.md
+++ /dev/null
@@ -1,133 +0,0 @@
-# Connection List Alphabetical Sort Design
-
-**Date:** 2026-07-21
-
-## Goal
-
-Add a connection-list sort control to the desktop sidebar. Users can view saved
-connections by name in ascending or descending alphabetical order, without
-destroying their existing group and drag-and-drop layout.
-
-## Background
-
-The source repository was searched before this change. Issue #72, "连接分组和拖拽排序",
-is closed because DBX already supports groups and manual drag sorting. No issue
-or announced plan covers alphabetical ordering of connection names.
-
-The current sidebar builds its root tree from the persisted `SidebarLayout`.
-That layout captures manual root and group ordering. Rewriting it for an
-alphabetical view would silently discard a user's manual arrangement.
-
-## Requirements
-
-- provide ascending and descending connection-name ordering from the sidebar
-- retain a way to return to the saved manual order
-- sort connections both at the root and inside each connection group
-- keep connection groups themselves in their saved order
-- do not mutate the persisted drag-and-drop layout when changing display sort
-- remember the selected sort mode across application restarts
-- keep search, selection, expand/collapse state, and virtualized rendering
- working
-
-## Chosen Approach
-
-### Sort mode
-
-Add `sidebarConnectionSortMode` to editor settings with three values:
-
-- `manual` — existing persisted drag-and-drop order (default)
-- `asc` — connection names from A to Z
-- `desc` — connection names from Z to A
-
-The setting is normalized on load and saved through the existing editor-settings
-store, so old profiles safely default to `manual`.
-
-### Display transformation
-
-Create a pure sidebar utility that produces a display-only tree:
-
-- it recursively visits only `connection-group` nodes
-- at every such level, it sorts only sibling nodes whose type is `connection`
-- it preserves the positions and order of group nodes and any non-connection
- nodes
-- it copies only the group branches whose child order changes; stored tree nodes
- remain unmodified
-- it uses an `Intl.Collator` with numeric, case-insensitive comparison; names
- that compare equally retain their manual relative order
-
-`ConnectionTree.vue` uses this transformed tree before it applies the existing
-search filter and flattening flow. This means all of the existing selection and
-virtualization logic continues to operate on the currently visible order.
-
-### User interface
-
-Add a compact sort dropdown next to the existing sidebar locate and filter
-controls. It exposes:
-
-- Manual order
-- Name: A–Z
-- Name: Z–A
-
-The active mode has an accessible label and visible selected state. New labels
-are added to every supported locale, with fallback coverage for any locale that
-does not yet provide a translation.
-
-Manual drag-and-drop is disabled while either alphabetical sort is active. This
-avoids a misleading interaction in which a successful drag immediately appears
-to be undone by the active display sort. Switching back to `manual` restores
-the untouched stored layout and drag behavior.
-
-## Files And Boundaries
-
-- `apps/desktop/src/lib/sidebar/connectionListSort.ts` — pure ordering utility
- and its Vitest coverage
-- `apps/desktop/src/stores/settingsStore.ts` — typed default, normalization,
- and persistence update for the mode
-- `apps/desktop/src/components/sidebar/ConnectionTree.vue` — dropdown,
- display-tree integration, and drag guard
-- `apps/desktop/src/i18n/locales/*.ts` — sort-control labels
-
-No Rust backend, connection storage schema, or sidebar-layout persistence code
-changes. Sorting is entirely a frontend presentation preference.
-
-## Error Handling And Compatibility
-
-- missing, invalid, or legacy setting values normalize to `manual`
-- empty trees and groups remain unchanged
-- duplicate or equivalent names remain stable in their manual order
-- filtering continues to run after display sorting, so disconnected-connection
- filtering has no new special case
-
-## Testing
-
-- unit-test ascending and descending ordering
-- verify groups retain their relative order while root and nested connections
- sort independently
-- verify manual mode returns original references/order and input trees are not
- mutated
-- test editor-settings default, normalization, and persisted update behavior
-- run targeted Vitest tests, frontend typecheck, Rust fast check, and local
- `make dev-fast` native startup
-
-## Scope Boundaries
-
-Included:
-
-- connection-name alphabetical ascending/descending display sorting
-- remembered sort mode
-- grouped connection support
-
-Not included:
-
-- sorting databases, schemas, tables, or other tree objects
-- replacing manual drag ordering
-- changing connection configuration or the persisted sidebar layout format
-- per-group independent sort preferences
-
-## Success Criteria
-
-- a user can choose A–Z or Z–A from the sidebar and see all connections sorted
- accordingly within their current groups
-- manual ordering can be restored without data loss
-- the chosen mode survives restart
-- native local startup completes with the control present and functional
diff --git a/docs/superpowers/specs/2026-07-25-query-result-sql-export-background-task-design.md b/docs/superpowers/specs/2026-07-25-query-result-sql-export-background-task-design.md
deleted file mode 100644
index 6648f2014f..0000000000
--- a/docs/superpowers/specs/2026-07-25-query-result-sql-export-background-task-design.md
+++ /dev/null
@@ -1,380 +0,0 @@
-# Query Result SQL INSERT Async Background Export
-
-Date: 2026-07-25
-Author: dbx team
-Status: Draft
-
-## Problem
-
-点击"导出当前结果集全部数据 SQL INSERT"后,UI 会冻结数十秒甚至一分钟(4 万行 ~20s,10 万行 ~1min+),然后才弹出保存对话框。用户以为功能坏了。
-
-## Root Cause
-
-当前 `exportSql()` 对 query-result 场景走 `resultToExport()` → 全量数据先拉到前端内存 → `formatSqlInsert()` 通过 Tauri IPC 发给 Rust 生成 INSERT → 再回前端 → `saveTextFile()` 写入。整个过程阻塞 UI 线程,保存对话框出现在最后。
-
-**对比 CSV/XLSX/TXT 的后台流式导出**(右键表名导出、工具栏导出 query result):
-1. 先弹保存对话框(立即响应)
-2. 注册后台任务(进度显示在 toolbar popover)
-3. Rust 端流式分页读取 DB → 直接写入文件
-4. 完成后 toast 通知
-
-## Design
-
-### 方案
-
-在 `export_query_result_core_inner()` 的通用 JDBC 分页循环中添加 `"sql"` 格式支持。复用 `build_export_insert_statements()`,按 100 行一批 flush 到文件。
-
-**不碰** Postgres/MySQL/ClickHouse/SQL Server 四个原生流式路径——SQL 格式只走分页循环(原生路径检测到 `format == "sql"` 返回 `false` 后回退)。
-
-前端 `exportSql()` 增加 Step 2:先尝试 `exportQueryResultSqlViaBackend()` 走后台流式导出,失败/Web 才回退到当前本地导出。
-
-### 修复的 Blocker
-
-1. **复用 `buildQueryResultExportRequest`**(`queryResultExportRequest` callback),不手撸 request 对象。保留 `rowLimit`、`totalRows`、`timeoutSecs`、`useAgentCursor`、`setupSql`、`clientSessionId`、`executionId`、`keysetOptimizationEnabled` 等字段。
-2. **`export_table_name` 兜底**:Rust 侧当 `export_table_name` 为空时回退到 `"query_result"`,纯 `SELECT` 查询不再报错。
-3. **启动失败处理**:`startQueryResultExport()` rejecting 时将后台任务标记为 `Error`,清理 cancel handler,防止任务卡在 `Running` 状态。
-
-## Files Changed
-
-| File | What | Lines |
-|------|------|-------|
-| `crates/dbx-core/src/query_result_export.rs` | 格式守卫放松 + 分页循环 SQL 分支 + 新字段 + helper | ~80 |
-| `apps/desktop/src/composables/useDataGridExport.ts` | 新增 `exportQueryResultSqlViaBackend`,`exportSql()` 增加 Step 2 | ~50 |
-| `apps/desktop/src/components/grid/DataGrid.vue` | `queryResultExportRequest` prop 类型加 `"sql"` 和两个 new fields | ~5 |
-| `apps/desktop/src/components/layout/ContentArea.vue` | 同 DataGrid.vue 类型更新 | ~3 |
-| `apps/desktop/src/stores/queryStore.ts` | `BuildQueryResultExportRequestOptions` 加 `exportTableName`、`exportColumnTypes` | ~5 |
-| `packages/app-tests/useDataGridExport.test.ts` | 测试适配(TXT/SQL Web fallback) | ~5 |
-
-**Total: ~148 lines, zero new files, zero new dependencies.**
-
-## Detailed Design
-
-### 1. Rust: `QueryResultExportRequest` — new optional fields
-
-File: `crates/dbx-core/src/query_result_export.rs`
-
-```rust
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub date_time_format: Option<String>,
- // -- new fields --
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub export_table_name: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub export_column_types: Option<Vec<String>>,
-}
-```
-
-### 2. Rust: format guard
-
-Relax the existing guard to accept `"sql"`:
-
-```rust
-if format != "csv" && format != "xlsx" && format != "txt" && format != "sql" {
- return Err(format!("Unsupported streaming query-result export format: {format}"));
-}
-```
-
-### 3. Rust: effective_row_limit
-
-SQL format has no XLSX row cap:
-
-```rust
-fn effective_row_limit(format: &str, request: &QueryResultExportRequest) -> Option<usize> {
- if format == "xlsx" {
- Some(request.row_limit.map_or(XLSX_MAX_DATA_ROWS, |limit| limit.min(XLSX_MAX_DATA_ROWS)))
- } else {
- request.row_limit
- }
-}
-```
-
-### 4. Rust: native stream skip
-
-原生流式路径(Postgres/MySQL/ClickHouse/SQL Server)只支持 CSV/TXT/XLSX。在 `export_query_result_core_inner` 中跳过它们对 `"sql"` 的调用,改为直接走通用分页循环:
-
-```rust
-// Before: 对每种格式都尝试原生流
-// After: SQL 格式跳过原生流路径
-if format != "sql" {
- if try_export_postgres_query_result_stream(state, request, &format, cancel_token.clone(), on_progress).await? { return Ok(()); }
- if try_export_sqlserver_query_result_stream(state, request, &format, cancel_token.clone(), on_progress).await? { return Ok(()); }
- if try_export_mysql_query_result_stream(state, request, &format, cancel_token.clone(), on_progress).await? { return Ok(()); }
- if try_export_clickhouse_query_result_stream(state, request, &format, cancel_token.clone(), on_progress).await? { return Ok(()); }
-}
-```
-
-1 行变更(在原有 `if` 外包装一个 `format != "sql"` 条件),避免了修改 4 个原生函数的 60+ 行。
-
-### 5. Rust: pagination loop — `"sql"` branch
-
-Inserted alongside existing CSV/TXT branch. Uses a `pending_rows` buffer that flushes via `build_export_insert_statements` every 100 rows.
-
-**New imports:**
-
-```rust
-use std::mem;
-use crate::database_export::{build_export_insert_statements, BuildExportInsertStatementsOptions};
-```
-
-**New constant:**
-
-```rust
-const SQL_INSERT_BATCH_SIZE: usize = 100;
-```
-
-**New helper:**
-
-```rust
-fn sql_insert_column_types(request: &QueryResultExportRequest, column_types: &[String]) -> Vec<Option<String>> {
- request.export_column_types
- .as_ref()
- .map(|types| types.iter().map(|t| if t.is_empty() { None } else { Some(t.clone()) }).collect())
- .unwrap_or_else(|| vec![None; column_types.len()])
-}
-```
-
-**New variables** (alongside existing `columns`/`column_types`):
-
-```rust
-let mut sql_file: Option<BufWriter<File>> = None;
-let mut pending_rows: Vec<Vec<Value>> = Vec::new();
-let mut sql_insert_col_types: Vec<Option<String>> = Vec::new();
-```
-
-**Initialize types** (inside existing `if columns.is_empty()` block):
-
-```rust
-if columns.is_empty() {
- columns = result.columns.clone();
- column_types = result.column_types.clone();
- sql_insert_col_types = sql_insert_column_types(request, &column_types);
-}
-```
-
-**Write branch** (after the `if format == "csv" || format == "txt"` block):
-
-```rust
-} else if format == "sql" {
- if sql_file.is_none() {
- sql_file = Some(BufWriter::new(
- File::create(&request.file_path)
- .map_err(|e| format!("Failed to create SQL file: {e}"))?,
- ));
- }
- pending_rows.extend(formatted_rows);
- if pending_rows.len() >= SQL_INSERT_BATCH_SIZE {
- let col_types = sql_insert_col_types.clone();
- let table_name = request.export_table_name
- .as_deref()
- .filter(|n| !n.trim().is_empty())
- .unwrap_or("query_result");
- let stmts = build_export_insert_statements(BuildExportInsertStatementsOptions {
- database_type: Some(request.database_type),
- schema: request.schema.clone(),
- table_name: Some(table_name.to_string()),
- qualified_table_name: None,
- columns: columns.clone(),
- column_types: col_types,
- column_extras: Vec::new(),
- rows: mem::take(&mut pending_rows),
- batch_size: Some(SQL_INSERT_BATCH_SIZE),
- })?;
- let file = sql_file.as_mut().unwrap();
- for stmt in &stmts {
- writeln!(file, "{stmt}").map_err(|e| format!("Failed to write SQL: {e}"))?;
- }
- }
-}
-```
-
-**Post-loop flush** (alongside CSV/TXT flush):
-
-```rust
-} else if format == "sql" {
- if !pending_rows.is_empty() {
- let col_types = sql_insert_col_types.clone();
- let table_name = request.export_table_name
- .as_deref()
- .filter(|n| !n.trim().is_empty())
- .unwrap_or("query_result");
- let stmts = build_export_insert_statements(BuildExportInsertStatementsOptions {
- database_type: Some(request.database_type),
- schema: request.schema.clone(),
- table_name: Some(table_name.to_string()),
- qualified_table_name: None,
- columns: columns.clone(),
- column_types: col_types,
- column_extras: Vec::new(),
- rows: mem::take(&mut pending_rows),
- batch_size: Some(SQL_INSERT_BATCH_SIZE),
- })?;
- for stmt in &stmts {
- writeln!(sql_file.as_mut().unwrap(), "{stmt}")
- .map_err(|e| format!("Failed to write SQL: {e}"))?;
- }
- }
- if let Some(file) = sql_file.as_mut() {
- file.flush().map_err(|e| format!("Failed to flush SQL file: {e}"))?;
- }
-}
-```
-
-**File open output**: the `File::create` overwrites by design — same behavior as all other export formats.
-
-### 6. Frontend: Types
-
-**queryStore.ts:**
-
-```typescript
-interface BuildQueryResultExportRequestOptions {
- exportId: string;
- filePath: string;
- format: "csv" | "xlsx" | "txt" | "sql"; // ← "sql" 新增
- includeSqlSheet?: boolean;
- exportTableName?: string; // ← new
- exportColumnTypes?: Array<string | null | undefined>; // ← new
-}
-```
-
-**DataGrid.vue prop type:**
-
-```typescript
-queryResultExportRequest?: (options: {
- exportId: string;
- filePath: string;
- format: "csv" | "xlsx" | "txt" | "sql"; // ← "sql" 新增
- includeSqlSheet?: boolean;
- exportTableName?: string; // ← new
- exportColumnTypes?: Array<string | null | undefined>; // ← new
-}) => Promise<api.QueryResultExportRequest | undefined>;
-```
-
-### 6. Frontend: `exportQueryResultSqlViaBackend`
-
-New function in `useDataGridExport.ts`.
-
-**新增 import** (文件头部):
-
-```typescript
-import { useExportTracker } from "@/composables/useExportTracker";
-```
-
-**新增 destructure** (在 `useDataGridExport` 函数体开头):
-
-```typescript
-const { addTask, updateTableExportTask, registerTaskCancelHandler, unregisterTaskCancelHandler } = useExportTracker();
-```
-
-```typescript
-async function exportQueryResultSqlViaBackend(rowIds?: number[]): Promise<boolean> {
- // Guard: 仅用于 query-result、无完整结果、桌面端
- if (rowIds !== undefined || context.value !== "results" || !queryResultExportRequest) return false;
- if (hasCompleteLocalResult?.value) return false;
- if (!isTauriRuntime()) return false; // Web fall through → local export
-
- // 1. 保存对话框 FIRST(立即响应)
- let outputPath = exportFileName("query-result", "sql");
- const { save } = await import("@tauri-apps/plugin-dialog");
- const path = await save({
- defaultPath: outputPath,
- filters: [{ name: "SQL", extensions: ["sql"] }],
- });
- if (!path) return true;
- outputPath = path as string;
-
- // 2. 通过 buildQueryResultExportRequest 构建完整 request
- const exportId = uuid();
- const request = await queryResultExportRequest({
- exportId,
- filePath: outputPath,
- format: "sql",
- exportTableName: tableMeta.value?.tableName,
- exportColumnTypes: columnTypes.value?.map(
- t => t ?? null
- ) as Array<string | null | undefined> | undefined,
- });
- if (!request) throw new Error("Unable to build query result export request");
-
- // 3. 注册后台任务 + cancel handler
- registerTaskCancelHandler(exportId, () => api.cancelQueryResultExport(exportId, request.executionId));
- addTask(tableMeta.value?.tableName || "Query Result", "sql", outputPath, exportId);
-
- try {
- await api.startQueryResultExport(request, (progress) => {
- updateTableExportTask(exportId, progress);
- if (progress.status === "Done") {
- toast(t("grid.exported"));
- }
- });
- } catch (e) {
- // 4. 启动失败 → 标记 Error(修复 Blocker 3)
- updateTableExportTask(exportId, {
- exportId,
- tableName: tableMeta.value?.tableName || "Query Result",
- rowsExported: 0,
- totalRows: null,
- status: "Error" as const,
- errorMessage: e?.message || String(e),
- });
- throw e;
- } finally {
- unregisterTaskCancelHandler(exportId);
- }
- return true;
-}
-```
-
-### 7. Frontend: `exportSql()` — new middle step
-
-```typescript
-async function exportSql(rowIds?: number[]) {
- await runExclusiveExport(async () => {
- try {
- // Step 1: table-data context — 已有后台表导出(不变)
- if (await exportFullTableDataViaBackend("sql", rowIds)) return;
-
- // Step 2: query-result context — NEW 后台流式导出
- if (await exportQueryResultSqlViaBackend(rowIds)) return;
-
- // Step 3: fallback — 本地导出(Web 和异常场景)
- const result = await resultToExport(rowIds, undefined, true, false);
- const exportData = sqlInsertExportData(result);
- const content = await formatSqlInsert({ ... });
- await saveTextFile(content, exportFileName(..., "sql", ...), "SQL", "sql");
- toast(t("grid.exported"));
- } catch (e: any) {
- toast(t("grid.exportFailed", { message: e?.message || String(e) }), 5000);
- }
- });
-}
-```
-
-## User Experience Flow
-
-```
-1. 用户点击 "导出当前结果集全部数据 SQL INSERT"
-2. 系统保存对话框立即弹出 ← 无冻结
-3. 用户选择路径 → 点击保存
-4. 后台任务指示器在 toolbar 出现(带进度条)
-5. Export 分页流式执行:DB → 分批读取 → build INSERT → 写入文件
-6. 完成 → toast "已导出"
- 或
- 失败 → 后台任务显示 Error 状态
-```
-
-## Backward Compatibility
-
-- 新增字段均为 `Option` + `skip_serializing_if`,现有 caller 无损
-- SQL INSERT 输出格式与现有 `build_export_insert_statements` 完全一致(batch 从 1→100,语义等价)
-- 纯查询兜底表名 `"query_result"`,导出文件内容与之前不同(之前失败),属于 bugfix 而非 regression
-- Web 端保持不变,仍走本地导出(Blob download)
-
-## Error Handling
-
-| Scenario | Behavior |
-|----------|----------|
-| `startQueryResultExport` 拒绝启动 | catch 中标记 task Error + 清理 cancel handler |
-| 文件创建失败 | 错误传播到前端,task 标记 Error |
-| 磁盘满 | `std::io::Error` → 游标中断 → task Error |
-| 用户取消 | CancellationToken → OnProgress(Cancelled) → 清理文件 |
-| SQL 表单 export_table_name 为空 | Rust 回退到 `"query_result"` |
diff --git a/docs/superpowers/specs/2026-07-29-clickhouse-syntax-highlighting-design.md b/docs/superpowers/specs/2026-07-29-clickhouse-syntax-highlighting-design.md
deleted file mode 100644
index eeb24e43c4..0000000000
--- a/docs/superpowers/specs/2026-07-29-clickhouse-syntax-highlighting-design.md
+++ /dev/null
@@ -1,141 +0,0 @@
-# ClickHouse SQL Syntax Highlighting Design
-
-**Date:** 2026-07-29
-
-## Goal
-
-Give ClickHouse connections a dedicated SQL highlighting dialect in DBX's
-CodeMirror query editors and DDL viewers. ClickHouse keywords, data types, and
-common built-in functions should receive the same semantic colors that the
-existing editor themes already assign to those token classes.
-
-## Background
-
-DBX currently has separate dialect-selection paths for SQL formatting and SQL
-highlighting:
-
-- `sqlFormatter.ts` maps ClickHouse to the formatter's native `clickhouse`
- language.
-- `jdbcDialect.ts` maps ClickHouse to the generic `mysql` CodeMirror dialect
- name.
-- `codemirrorSqlDialect.ts` does not recognize the ClickHouse database type and
- therefore selects `StandardSQL` as its parser base.
-- the semantic table-name overlay receives the explicit `mysql` dialect and
- consequently applies MySQL rules to ClickHouse SQL.
-
-This explains why formatting can look correct while highlighting does not.
-Editor themes already distinguish keywords, types, functions, strings, and
-identifiers; the parser is producing incomplete or incorrect token classes.
-
-## Scope
-
-Included:
-
-- the main CodeMirror query editor
-- CodeMirror-based DDL and SQL viewers that use the shared DBX dialect factory
-- ClickHouse keyword, data-type, built-in-function, comment, and table-name
- classification
-- focused parser and propagation tests
-
-Not included:
-
-- Shiki-rendered static SQL blocks in AI messages
-- SQL formatting, execution, completion, or snippet behavior
-- a complete ClickHouse grammar or query validator
-- theme color changes
-
-## Chosen Approach
-
-Add `clickhouse` as a first-class DBX CodeMirror dialect name. Define its
-CodeMirror dialect from `StandardSQL`, then extend the dialect specification
-with ClickHouse-specific keywords, data types, and common built-in functions.
-
-`StandardSQL` is the safer parser base than `MySQL` because ClickHouse and MySQL
-do not share all lexical behavior. In particular, DBX already tests that
-ClickHouse accepts `--` comments without the whitespace requirement used by the
-CodeMirror MySQL dialect.
-
-The vocabulary will be curated from the official ClickHouse SQL reference and
-kept as named constants next to the existing PostgreSQL and SQL Server
-extensions. Representative coverage includes:
-
-- clauses and DDL terms such as `PREWHERE`, `ARRAY JOIN`, `ENGINE`,
- `PARTITION BY`, `SAMPLE BY`, `TTL`, `SETTINGS`, `CODEC`, and `FORMAT`
-- types such as `UInt64`, `DateTime64`, `LowCardinality`, `Nullable`, `Map`,
- `Tuple`, `Nested`, `AggregateFunction`, and `SimpleAggregateFunction`
-- common functions such as `toYYYYMM`, `uniqExact`, `argMax`, `groupArray`,
- `arrayJoin`, and `JSONExtractString`
-
-This is vocabulary-driven syntax highlighting, not validation. Unknown future
-functions will still parse as callable identifiers instead of breaking editor
-input.
-
-## Data Flow
-
-1. A ClickHouse connection resolves to the new `clickhouse` CodeMirror dialect
- name in `jdbcDialect.ts`.
-2. QueryEditor and DDL viewers pass that name and the ClickHouse database type
- into `createDbxCodeMirrorSqlDialect()`.
-3. The dialect factory selects the dedicated ClickHouse specification.
-4. CodeMirror's Lezer SQL parser assigns keyword, type, built-in, comment, and
- identifier tags.
-5. Existing editor themes render those tags with their current colors.
-6. The semantic overlay selects a ClickHouse adapter for table-name
- decorations instead of inheriting MySQL behavior accidentally.
-
-## Semantic Adapter
-
-Add a ClickHouse semantic dialect adapter rather than silently treating
-ClickHouse as MySQL. It will support ClickHouse's backtick and double-quote
-identifier quoting and use the project's existing default identifier
-normalization unless a verified ClickHouse-specific rule is required.
-
-This adapter is limited to tokenization and table-reference decoration. It does
-not change query execution or attempt to model every ClickHouse alias-resolution
-extension.
-
-## Compatibility And Failure Behavior
-
-- Existing MySQL, PostgreSQL, SQL Server, Oracle, SQLite, and generic database
- mappings remain unchanged.
-- ClickHouse keeps its current `--SELECT 1` line-comment behavior.
-- An unlisted ClickHouse keyword or function remains readable as an identifier;
- highlighting degrades locally without blocking editing.
-- All changes remain frontend-only and require no persisted-setting migration.
-
-## Testing
-
-Use test-driven development:
-
-1. Add parser tests that initially fail under the current StandardSQL fallback.
-2. Assert representative ClickHouse terms produce keyword, type, and built-in
- parser nodes.
-3. Retain and strengthen the line-comment regression test.
-4. Assert the JDBC database-type mapping returns `clickhouse`.
-5. Assert QueryEditor and DDL viewers pass the dedicated dialect through the
- shared factory.
-6. Add semantic-dialect coverage for ClickHouse identifier quoting and
- selection.
-7. Run focused tests, the relevant desktop test suite, and frontend typecheck.
-
-## Alternatives Considered
-
-### Extend the MySQL dialect
-
-This is smaller but preserves known lexical mismatches and continues to make
-ClickHouse behavior depend on unrelated MySQL changes.
-
-### Integrate the ClickHouse lexer or WebAssembly
-
-ClickHouse exposes native query-highlighting capabilities, including recent
-lexer/WASM work. That route could eventually provide higher fidelity, but it
-adds runtime, bundle-size, and CodeMirror syntax-tree integration costs that are
-disproportionate to this focused highlighting fix.
-
-## Success Criteria
-
-- ClickHouse-specific clauses, types, and common functions are visually
- differentiated in query and DDL editors.
-- ClickHouse no longer resolves to MySQL or generic StandardSQL by accident.
-- existing dialect behavior and editor themes do not regress.
-- the implementation is covered by focused parser, mapping, and semantic tests.
diff --git a/docs/superpowers/specs/2026-07-30-clickhouse-function-completion-design.md b/docs/superpowers/specs/2026-07-30-clickhouse-function-completion-design.md
deleted file mode 100644
index c85e0ae57d..0000000000
--- a/docs/superpowers/specs/2026-07-30-clickhouse-function-completion-design.md
+++ /dev/null
@@ -1,301 +0,0 @@
-# ClickHouse Function Completion Design
-
-Date: 2026-07-30
-
-## Summary
-
-DBX currently provides database-specific static function completion for MySQL, PostgreSQL, SQLite, SQL Server, and Manticore Search. It also loads stored routines dynamically for selected databases. ClickHouse receives only the small common SQL function set, so native functions such as `toStartOfDay`, `uniqExact`, and `JSONExtractString` are absent.
-
-This change adds a static, ClickHouse-specific function registry with broad official-function coverage, overload-aware signature help, ClickHouse parametric aggregate support, table-function completion, and aggregate combinator generation. It does not query the connected ClickHouse server.
-
-## Goals
-
-- Provide broad completion coverage for documented ClickHouse regular, aggregate, window, and table functions.
-- Preserve canonical ClickHouse casing when inserting camelCase function names.
-- Support multiple signatures per function and highlight the active parameter.
-- Support ClickHouse functions with multiple parameter groups, such as `quantilesTDigest(levels...)(expression)`.
-- Generate valid aggregate-combinator completions without storing an unbounded Cartesian product.
-- Keep existing MySQL, PostgreSQL, SQLite, SQL Server, and Manticore Search completion behavior unchanged.
-- Keep the ClickHouse inventory maintainable and isolated from the already large generic SQL completion module.
-
-## Non-goals
-
-- Query `system.functions`, `system.user_defined_functions`, or any other server metadata table.
-- Complete server-defined UDFs in the first version.
-- Treat operators, keywords, or data types as functions.
-- Include undocumented internal functions without a stable user-facing interface.
-- Migrate every existing database function inventory to the new representation in the same change.
-
-## Existing Design to Reuse
-
-`sqlCompletion.ts` already provides:
-
-- database-specific function filtering;
-- prefix matching and ranking;
-- function snippets with CodeMirror placeholders;
-- function-versus-keyword de-duplication;
-- a signature tooltip driven by the cursor's active argument;
-- regression coverage proving that database-specific functions do not leak across dialects.
-
-The existing `DATABASE_FUNCTION_SIGNATURES` maps demonstrate the desired database isolation, but their `Map<string, string[]>` value type represents only one flat signature. ClickHouse requires a richer model because overloads and two-stage parameter lists are common.
-
-The dynamic stored-routine path used by MySQL, PostgreSQL, SQL Server, and Oracle is not reused for built-in ClickHouse functions. Static built-in completion and dynamic stored-routine completion solve different problems.
-
-## Architecture
-
-Add a ClickHouse-specific directory:
-
-```text
-apps/desktop/src/lib/sql/clickhouse/
- functionTypes.ts
- regularFunctions.ts
- aggregateFunctions.ts
- tableFunctions.ts
- aggregateCombinators.ts
- functionRegistry.ts
-```
-
-Responsibilities:
-
-- `functionTypes.ts` defines function, overload, parameter-group, category, and lifecycle-status types.
-- `regularFunctions.ts` contains documented scalar functions, organized into readable category sections.
-- `aggregateFunctions.ts` contains ordinary and parametric aggregate functions.
-- `tableFunctions.ts` contains functions valid in table-target contexts such as `FROM` and `JOIN`.
-- `aggregateCombinators.ts` defines suffix compatibility, ordering, signature transformations, and lazy generation.
-- `functionRegistry.ts` merges definitions, validates lookup keys, performs case-insensitive lookup, preserves canonical names, and exposes prefix queries.
-- `sqlCompletion.ts` adapts registry results into the existing generic completion item type and uses the richer signatures for tooltip rendering.
-
-The ClickHouse module contains data and deterministic transformation logic only. It does not depend on Vue, CodeMirror, a connection, or backend APIs.
-
-## Function Model
-
-The shared model is:
-
-```ts
-interface SqlFunctionDefinition {
- name: string;
- category: SqlFunctionCategory;
- signatures: SqlFunctionSignature[];
- description?: string;
- preferredSignature?: number;
- aggregate?: boolean;
- status?: "stable" | "experimental" | "deprecated";
- aliases?: string[];
-}
-
-interface SqlFunctionSignature {
- parameterGroups: string[][];
- returnType?: string;
-}
-```
-
-One parameter group represents an ordinary function:
-
-```ts
-{
- name: "toStartOfInterval",
- category: "date-time",
- signatures: [
- {
- parameterGroups: [["value", "INTERVAL x unit"]],
- returnType: "DateTime"
- },
- {
- parameterGroups: [["value", "INTERVAL x unit", "time_zone"]],
- returnType: "DateTime"
- }
- ]
-}
-```
-
-Multiple groups represent a parametric aggregate:
-
-```ts
-{
- name: "quantilesTDigest",
- category: "aggregate",
- aggregate: true,
- signatures: [
- {
- parameterGroups: [
- ["level", "...levels"],
- ["expression"]
- ]
- }
- ]
-}
-```
-
-`preferredSignature` selects the inserted snippet. When it is omitted, the first signature is preferred. Optional arguments remain visible in alternate signatures but are excluded from the default insertion when a shorter common form exists.
-
-## Inventory Scope
-
-The static inventory follows the public ClickHouse function reference and records the documentation snapshot date in source comments. It covers:
-
-- regular scalar functions, including array, string, date/time, JSON, Map, Tuple, URL, IP, mathematical, hashing, encoding, conversion, Nullable, dictionary, geography, and related documented categories;
-- regular and parametric aggregate functions;
-- window functions;
-- table functions;
-- documented aliases with canonical insertion names;
-- experimental and deprecated functions, marked with status and ranked below stable functions.
-
-The official ClickHouse documentation separates regular, aggregate, table, window, and user-defined functions. The first version covers the first four static categories and excludes user-defined functions:
-
-- <https://clickhouse.com/docs/reference/functions>
-- <https://clickhouse.com/docs/reference/functions/aggregate-functions/combinators>
-
-Every function must have an official name and an accurate parameter-group shape. A concise description is optional. When absent, the completion detail falls back to `ClickHouse · <category>` so full internationalization coverage is not required to ship the inventory.
-
-The checked-in inventory also contains a category manifest that records the documentation pages used for the 2026-07-30 snapshot and the number of definitions in each category. Integrity tests use those checked-in category counts as minimum floors, so removing a documented batch requires an intentional manifest update rather than silently reducing coverage.
-
-## Completion Behavior
-
-Matching is case-insensitive, while labels and inserted text retain canonical ClickHouse casing. For example, `tostart` can match and insert `toStartOfDay(${value})`.
-
-Each completion item displays:
-
-- canonical function name;
-- `ClickHouse` and the function category;
-- the preferred signature;
-- overload count when greater than one;
-- experimental or deprecated status;
-- a concise description when available.
-
-Accepting a completion:
-
-- inserts the preferred signature with CodeMirror placeholders;
-- avoids adding a second opening parenthesis when the user already typed one;
-- inserts `function()` for zero-argument functions;
-- preserves multiple parameter groups for parametric functions;
-- continues to use existing ranking history and prefix scoring.
-
-ClickHouse-specific signatures override common SQL signatures for names shared with the common registry.
-
-## Table Functions
-
-Table functions are a distinct function kind. In ClickHouse table-target contexts, including `FROM` and `JOIN`, the provider includes matching table functions alongside tables and views. It does not include ordinary scalar or aggregate functions in those exclusive contexts.
-
-Table-function completions use the same overload and placeholder model as regular functions. This requires a narrow exception to the existing `exclusiveTableSuggestions` path rather than globally enabling all functions after `FROM`.
-
-## Signature Help
-
-The generic signature-help result is extended from one flat signature to multiple overloads containing one or more parameter groups.
-
-The resolver:
-
-1. finds the function call that owns the cursor;
-2. determines the active parameter group;
-3. counts top-level commas only within that group;
-4. ranks signatures that can accept the observed argument count first;
-5. returns every matching overload for display;
-6. highlights the active parameter in each displayed overload.
-
-For `quantilesTDigest(0.5, 0.9)(value)`, the resolver recognizes both pairs of parentheses as one function call. It can distinguish the level list from the expression list.
-
-Ordinary existing database functions are adapted as one overload with one parameter group, preserving their current behavior.
-
-## Aggregate Combinators
-
-Aggregate combinators are generated lazily from aggregate definitions. The rules describe:
-
-- which base aggregates accept a combinator;
-- valid suffix order;
-- how parameter groups change;
-- how return metadata changes;
-- whether a combinator can be followed by another combinator.
-
-The initial rule set covers the documented combinators, including `If`, `Array`, `Map`, `SimpleState`, `State`, `Merge`, `MergeState`, `ForEach`, `Distinct`, `OrDefault`, `OrNull`, and `Resample`.
-
-Generation follows official ordering constraints. For example, `Array` precedes `If`, producing `uniqArrayIf`, while `uniqIfArray` is not generated. `If` appends a condition argument to the data-argument group. State and merge combinators transform the expected input or output shape rather than merely renaming the function.
-
-The registry generates candidates only for the active prefix and enforces a deterministic maximum candidate count. It does not materialize every possible suffix permutation at module initialization.
-
-## Ranking and Lifecycle Status
-
-Stable direct functions rank above generated combinator variants when match quality is equal. Exact prefix and exact label matches continue to receive the existing strong boosts.
-
-Generated variants remain competitive once the typed prefix includes their suffix. Experimental and deprecated entries receive a modest negative boost and a visible status label, but remain discoverable.
-
-Aliases de-duplicate against canonical functions case-insensitively. An alias can match the typed prefix, but accepting it inserts the canonical ClickHouse function name and casing.
-
-## Validation and Failure Handling
-
-The static path has no network failures. Registry validation catches authoring problems:
-
-- duplicate case-insensitive names;
-- aliases colliding with canonical names;
-- empty signature lists;
-- empty parameter groups where they are not meaningful;
-- out-of-range preferred signature indexes;
-- invalid lifecycle status;
-- illegal combinator ordering;
-- combinator cycles;
-- aliases that do not belong to a canonical definition.
-
-Tests fail on invalid inventory data. At runtime, an isolated malformed entry is skipped rather than breaking the entire completion popup, while development builds may log a diagnostic.
-
-## Testing Strategy
-
-Implementation follows test-driven development: add one failing behavioral test, confirm the expected failure, add the minimum implementation, and keep the focused suite green before proceeding.
-
-### Registry integrity
-
-- canonical names and case-insensitive lookup keys are unique;
-- every definition has at least one valid signature;
-- preferred signature indexes are valid;
-- every declared category has representative coverage;
-- an expected inventory-size floor guards against accidental bulk deletion.
-
-### Completion behavior
-
-- `toStart` returns canonical camelCase ClickHouse functions;
-- completion inserts the preferred placeholder template;
-- an already typed `(` is not duplicated;
-- common functions use ClickHouse-specific signatures;
-- ClickHouse-only names do not appear for MySQL or PostgreSQL.
-
-### Multiple signatures
-
-- all overloads are available to signature help;
-- overload ranking reacts to top-level comma count;
-- active parameters are highlighted correctly;
-- parametric aggregate calls distinguish the first and second parameter groups.
-
-### Combinators
-
-- valid examples such as `sumIf`, `uniqArrayIf`, and `quantilesState` are generated;
-- invalid suffix orders such as `uniqIfArray` are not generated;
-- `If` adds the condition parameter;
-- generation respects its deterministic result bound.
-
-### Table functions
-
-- ClickHouse table functions appear in `FROM` and `JOIN`;
-- scalar and aggregate functions remain excluded from exclusive table contexts;
-- ordinary table and view completion continues to work.
-
-### Regression coverage
-
-- current MySQL function suggestions and special insertion templates remain unchanged;
-- PostgreSQL, SQLite, SQL Server, and Manticore Search functions remain isolated;
-- existing snippet, keyword, column, table, and routine completion tests remain green.
-
-Final verification includes the focused SQL completion tests, frontend type checking, and the repository's relevant frontend test suite.
-
-## Success Criteria
-
-- A ClickHouse query can autocomplete representative functions from every supported category using canonical casing.
-- Multiple overloads and current-parameter highlighting work for ordinary and parametric functions.
-- Valid aggregate combinator variants are discoverable without invalid-order noise or eager combinatorial expansion.
-- Table functions are suggested only where a table source is valid.
-- No server query is required for built-in completion.
-- Existing database-specific completion behavior remains covered by passing regression tests.
-
-## Future Work
-
-Possible follow-up work, intentionally excluded from this implementation:
-
-- optional discovery of SQL or executable UDFs from ClickHouse system tables;
-- a generated inventory pipeline sourced from an official machine-readable index;
-- migration of other database function maps to the overload-aware registry;
-- localized descriptions for the complete ClickHouse inventory.
diff --git a/docs/superpowers/specs/2026-08-01-data-transfer-tree-selection-design.md b/docs/superpowers/specs/2026-08-01-data-transfer-tree-selection-design.md
deleted file mode 100644
index ff8601597e..0000000000
--- a/docs/superpowers/specs/2026-08-01-data-transfer-tree-selection-design.md
+++ /dev/null
@@ -1,171 +0,0 @@
-# Data Transfer: Tree Object Selection and Transfer Modes Design
-
-Date: 2026-08-01
-
-## Summary
-
-The data transfer dialog (`apps/desktop/src/components/transfer/DataTransferDialog.vue`) currently lets the user pick tables from a flat checkbox list and copy table **data** between connections. Non-table objects (views, stored procedures, functions, triggers, sequences, events) are only copied for PostgreSQL→PostgreSQL transfers, and then only as an all-or-nothing schema sweep performed after the table data copy.
-
-This change turns the table picker into a tree that groups selectable objects by type (tables, views, stored procedures, functions, triggers, sequences, events), and adds an explicit transfer mode: **structure and data** (default), **structure only**, and **data only**. Non-table object DDL copying is implemented for PostgreSQL and PG-family databases (Kingbase, GaussDB, KWDB, OpenGauss), MySQL, Dameng, and Oracle. Cross-database-family object DDL copy is out of scope for the first version.
-
-## Goals
-
-- Select transfer content via a tree grouped by object type, with per-group select-all and object-level checkboxes.
-- Support three transfer modes: structure and data, structure only, data only.
-- Copy non-table object DDL for PostgreSQL/PG-family, MySQL, Dameng, and Oracle, within the same database family.
-- Skip objects that already exist on the target side (by name), and report the skip count on completion.
-- Preserve the existing table data transfer behavior (append/overwrite/upsert write modes, FK dependency ordering, ownership preview, target-table-name case handling).
-
-## Non-goals
-
-- Cross-family non-table object DDL transfer (e.g., MySQL view → PostgreSQL view). The tree disables non-table groups with a hint in that case.
-- Object transfer for databases outside the supported family set (SQLite, ClickHouse, SQL Server, MongoDB, Hive, Spark, etc.).
-- Editing object DDL inside the transfer dialog (users use the object source editor for that).
-- Differential/sync behavior beyond "skip existing" (no replacement of changed objects).
-
-## Existing Design to Reuse
-
-- `crates/dbx-core/src/transfer.rs` — table data transfer core: `TransferRequest`, `transfer_table`, FK dependency sorting (`sort_tables_by_fk_dependency`), progress reporting (`TransferProgress`), DDL generation (`generate_create_table_ddl`), column type mapping (`map_column_type`).
-- `crates/dbx-core/src/transfer.rs:5020` — `transfer_postgres_schema_objects`: existing PostgreSQL schema object DDL copy (views, materialized views, procedures, functions, sequences, triggers, types, packages, synonyms + ownership/grants/policies). Reused and extended with per-object selection filtering.
-- `crates/dbx-core/src/object_source_sql.rs` — `build_executable_object_source_statements`, `ObjectSourceKind`, `EditableObjectSourceSqlInput`: per-database object source DDL machinery (already used by the PG object transfer).
-- `crates/dbx-web/src/routes/transfer.rs` — transfer orchestration route, progress channel, per-object failure handling.
-- `apps/desktop/src/lib/backend/api.ts` — `listObjects(connectionId, database, schema, objectTypes?, filter?, limit?, offset?, catalog?)` returning `ObjectInfo[]`; `TransferRequest` types.
-- `apps/desktop/src/lib/database/databaseObjectCapabilities.ts` — per-database sidebar object kind lists.
-
-## Design
-
-### 1. Backend protocol (`crates/dbx-core/src/transfer.rs`, `crates/dbx-web/src/routes/transfer.rs`)
-
-Extend `TransferRequest`:
-
-```rust
-#[serde(rename_all = "camelCase")]
-pub enum TransferContent {
- #[default]
- StructureAndData,
- StructureOnly,
- DataOnly,
-}
-
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")] // matches SidebarObjectKind conventions
-pub enum TransferObjectKind {
- Table, View, MaterializedView, Procedure, Function, Trigger, Sequence, Event,
-}
-
-pub struct TransferObjectSelection {
- pub object_type: TransferObjectKind,
- pub names: Vec<String>,
-}
-```
-
-New fields on `TransferRequest`:
-
-- `content: TransferContent` — defaults to `StructureAndData`. Replaces the `create_table` boolean (`create_table == (content != DataOnly)`); the field is kept for wire compatibility but the frontend stops sending it.
-- `objects: Vec<TransferObjectSelection>` — non-table object selections. The table selection stays in the existing `tables: Vec<String>` field (also mirrored as a `TransferObjectKind::Table` entry when the tree sends it).
-
-Validation (in the route, before transfer starts):
-
-- `DataOnly` with non-empty `objects` → error "仅数据模式不传输非表对象".
-- `StructureOnly` with empty `tables` and empty `objects` → error (nothing to do).
-- Non-table objects are rejected when source and target database families differ (see family rules below).
-- Non-table object names are validated like table names (non-empty, no NUL bytes).
-
-`TransferMode` (append/overwrite/upsert) is unchanged; it only takes effect when the content includes data (`StructureAndData` or `DataOnly`).
-
-### 2. Database family rules
-
-| Family | Database types | Non-table object DDL support |
-|---|---|---|
-| mysql | mysql | yes (views, procedures, functions, triggers, events) |
-| postgres | postgres, kingbase, gaussdb, kwdb, opengauss | yes |
-| oracle | oracle, dameng, oceanbase-oracle | yes (views, procedures, functions, triggers, sequences) |
-| other | everything else | no — tree groups disabled, backend rejects |
-
-`is_same_transfer_family(source, target)` — a new pure function in `transfer.rs`, unit-tested. Cross-family transfers keep table data copy working exactly as today, with non-table groups disabled in the UI.
-
-Object type availability per family (drives which tree groups render):
-
-| Object kind | mysql | postgres family | oracle/dameng |
-|---|---|---|---|
-| TABLE | ✓ | ✓ | ✓ |
-| VIEW | ✓ | ✓ | ✓ |
-| MATERIALIZED_VIEW | ✗ | ✓ | ✓ |
-| PROCEDURE | ✓ | ✓ | ✓ |
-| FUNCTION | ✓ | ✓ | ✓ |
-| TRIGGER | ✓ | ✓ | ✓ |
-| SEQUENCE | ✗ (MariaDB only, first version: no) | ✓ | ✓ |
-| EVENT | ✓ | ✗ | ✗ |
-
-### 3. Object listing (backend)
-
-Extend the existing `listObjects` path (per-database object listing in `crates/dbx-core/src/schema.rs` and the agent-side listing) so the transfer tree can fetch objects grouped by type:
-
-- **PostgreSQL family**: already supported kinds (TABLE, VIEW, MATERIALIZED_VIEW, PROCEDURE, FUNCTION, SEQUENCE) via `pg_catalog`; add TRIGGER listing (`pg_trigger` join `pg_class`/`pg_namespace`, names of triggers in the schema).
-- **MySQL**: add TRIGGER (`information_schema.TRIGGERS` filtered by `EVENT_OBJECT_SCHEMA`) and EVENT (`information_schema.EVENTS`); VIEW/PROCEDURE/FUNCTION listing already exists.
-- **Oracle/Dameng**: add TRIGGER and SEQUENCE (`ALL_OBJECTS` filtered by `OBJECT_TYPE`); VIEW/PROCEDURE/FUNCTION listing already exists (Dameng already has `SYS.SYSOBJECTS`-based listing).
-
-The `Event` kind is transfer-only: it is added to the backend `ObjectSourceKind`/listing mapping but not to the sidebar object capability lists (the sidebar does not gain new node types in this change).
-
-### 4. Non-table object DDL copy (backend)
-
-New `transfer_objects` flow in `crates/dbx-core/src/transfer.rs`, invoked from the route after table data transfer and after the existing PG schema-dependency step. Execution order:
-
-1. tables (existing flow, FK sorted)
-2. sequences
-3. views, materialized views
-4. functions
-5. procedures
-6. triggers
-7. events
-
-DDL fetching per family:
-
-- **PostgreSQL family**: reuse `get_postgres_schema_object_sources_for_transfer` + `get_postgres_materialized_view_sources_for_transfer` + new `get_postgres_trigger_sources_for_transfer`-style queries, filtered by the selected names. Existing schema rewrite (`rewrite_postgres_routine_schema`) and `build_executable_object_source_statements` apply. The current "transfer everything in the schema" behavior becomes "transfer only selected objects"; when the request carries no object selection the step is skipped entirely (no behavior surprise for table-only transfers).
-- **MySQL**: VIEW/PROCEDURE/FUNCTION DDL via `SHOW CREATE` (existing `mysql_object_source_sql`); TRIGGER DDL assembled from `information_schema.TRIGGERS` (`CREATE TRIGGER` with ACTION_TIMING/EVENT_MANIPULATION/EVENT_OBJECT_TABLE/ACTION_STATEMENT — the per-table trigger query at `crates/dbx-core/src/db/mysql.rs:4239` is the basis); EVENT DDL assembled from `information_schema.EVENTS`; strip `DEFINER=` clauses; rewrite the schema qualifier from source schema to target schema when they differ.
-- **Oracle/Dameng**: fetch DDL via `DBMS_METADATA.GET_DDL('<TYPE>', '<name>')` (the existing object-source machinery already implements per-type metadata DDL for these databases; reuse those code paths where possible); rewrite schema qualifiers; execute per statement.
-
-Target-side existence check, per object, immediately before executing its DDL:
-
-- **PostgreSQL family**: `SELECT 1 FROM pg_class/pg_proc ...` by schema+name.
-- **MySQL**: `information_schema` lookups (VIEWS, ROUTINES, TRIGGERS, EVENTS).
-- **Oracle/Dameng**: `ALL_OBJECTS` (or `SYS.SYSOBJECTS` for Dameng) by schema+name.
-
-Existing objects are skipped and counted; the count is included in the final summary progress message ("skipped N existing objects"). Failed objects follow the existing pattern: recorded in the failure list, transfer continues, final status reflects the failures.
-
-Progress: reuse `TransferProgress` with `table = "schema object: <name>"` (already the convention used by the PG object transfer). The `DataOnly` mode skips the whole object-DDL step.
-
-### 5. Frontend (`apps/desktop/src/components/transfer/DataTransferDialog.vue`)
-
-- Replace the flat table list with a tree:
- - Top-level groups rendered from the source database family capability table (tables, views, materialized views, procedures, functions, triggers, sequences, events as applicable).
- - Group header checkbox = select all / clear group; per-object checkboxes; expand/collapse per group; a search filter box filters object names across groups.
- - Groups that cannot be transferred (cross-family, unsupported kind, or `DataOnly` mode) are rendered disabled with a tooltip explaining why.
- - Table selection stays in `tables`; non-table selections serialize into `objects`.
-- Transfer mode selector: 结构和数据 / 仅结构 / 仅数据 (i18n keys in the `transfer.*` namespace).
- - `DataOnly`: non-table groups disabled ("仅数据模式不传输非表对象"); table group enabled.
- - `StructureOnly`: data write mode (append/overwrite/upsert) selector hidden/disabled; ownership preview and target-table-name case options only apply when data is copied (ownership preview only relevant with `StructureAndData`; keep the existing behavior for that mode).
- - The `createTable` checkbox is removed.
-- Load object lists per group from `listObjects` with the per-kind object type filter; loading states per group; error states surface inline.
-
-### 6. Error handling
-
-- Validation errors from the route are shown inline in the dialog (existing error display pattern).
-- Per-object DDL failures: existing `failed_tables` mechanism extended to carry object entries; final status `Error` with the failure list, transfer continues for remaining objects.
-- Cancellation: existing `transfer_id` cancellation checks are threaded through the object-DDL loop (mirroring the PG object transfer loop).
-
-### 7. Testing
-
-Backend unit tests (`crates/dbx-core/src/transfer.rs` test module + `crates/dbx-core/tests/live_postgres_transfer.rs`):
-
-- `is_same_transfer_family` matrix.
-- Request validation (DataOnly + objects, cross-family objects).
-- Per-family object DDL statement generation (MySQL `SHOW CREATE` handling with DEFINER stripping; schema rewriting).
-- Target existence check SQL per family.
-- Live PG transfer: object filtering by selection, skip-existing behavior, `StructureOnly` (no data rows copied), `DataOnly` (no DDL executed).
-
-Frontend tests (`apps/desktop/src/components/transfer/__tests__/`):
-
-- Tree group rendering per database family.
-- Group select-all, object toggle, search filtering.
-- Disable rules: `DataOnly` mode, cross-family, unsupported kinds.
-- Request serialization (`tables` + `objects` + `content`).
diff --git a/docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.md b/docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.md
deleted file mode 100644
index 06cdff7289..0000000000
--- a/docs/superpowers/specs/2026-08-02-database-documentation-dbml-design.md
+++ /dev/null
@@ -1,388 +0,0 @@
-# Database Documentation and DBML Export Design
-
-Date: 2026-08-02
-
-## Summary
-
-DBX can inspect a schema but cannot document it. There is no way to produce a browsable, shareable description of a database, and no occurrence of DBML anywhere in the repository.
-
-This change adds a **documentation subsystem** built around one idea: `SchemaSnapshot` is the product, and every output is a serializer over it. `crates/dbx-core/src/docs/` collects a normalized snapshot of a relational schema, merges it with user-authored notes and table groups, and serializes it to two artifacts — a `.dbml` interchange file and a self-contained HTML documentation site in the style of [dbdocs.io](https://dbdocs.io/Holistics/Ecommerce).
-
-The documentation UI is a **standalone Vue application that makes no backend calls**. The same component tree renders inside DBX as a dialog and inside an exported single-file HTML page. Generation is available headless through `dbx docs` and `dbx dbml`, so documentation can be regenerated in CI and schema drift can fail a build.
-
-Schema versioning (a Changelog tab and per-table "Last Updated") is explicitly deferred, but the snapshot is version-stamped and storable from day one so that adding it later is additive rather than a refactor.
-
-## Goals
-
-- Collect a normalized `SchemaSnapshot` for any relational engine DBX already supports, reusing the existing `schema::providers` metadata layer.
-- Serialize the snapshot to valid DBML, including `TableGroup` blocks, `Enum` blocks, and `Ref` cardinality.
-- Render dbdocs-style documentation: project overview, per-group table index with inline markdown notes, per-table pages with columns/indexes/bidirectional relationships, an ER diagram with group containers, and client-side search.
-- Let users author table notes, column notes, project notes, and **table groups** in DBX, persisted in a human-readable, git-committable file.
-- Export a self-contained HTML file that works over `file://` with no network access.
-- Provide `dbx docs` and `dbx dbml` CLI verbs producing byte-identical output to the desktop app.
-- Degrade visibly, never silently, when an engine cannot supply metadata.
-
-## Non-goals
-
-- **Schema versioning / Changelog / "Last Updated"** — deferred. Live databases mostly cannot report a DDL timestamp (PostgreSQL has none; MySQL's `information_schema.tables.update_time` is NULL for most InnoDB tables), so this is a derivative of stored snapshot history, not of metadata. Section 12 defines the seam.
-- **DBML import / parsing.** The serializer is one-way. A `.dbml` file is an output, never a source of truth.
-- **Non-relational engines** (MongoDB, Redis, Elasticsearch, InfluxDB, HBase). DBML has no vocabulary for them and schema inference from documents is a separate feature.
-- **Non-table objects** — triggers, procedures, functions, sequences, packages, grants, partitions. `ObjectInfo` exists for these but none map to DBML and dbdocs does not document them. `format_version` makes adding them additive.
-- **Write-back to the database.** DBX never issues `COMMENT ON` as a side effect of documentation.
-- **Publishing/hosting.** DBX writes a file; distributing it is the user's business.
-
-## Existing Design to Reuse
-
-- `crates/dbx-core/src/types.rs:57-141` — `TableInfo`, `ColumnInfo`, `IndexInfo`, `ForeignKeyInfo`. These are serde mirrors of the TS interfaces in `apps/desktop/src/types/database.ts` and are **composed directly** into the snapshot rather than re-declared.
-- `crates/dbx-core/src/schema/providers/native.rs` — `list_databases`, `list_schemas`, `list_tables`, `get_columns`, `list_foreign_keys`, `list_indexes`, already dispatching across every supported engine.
-- `crates/dbx-core/src/schema/normalization.rs` — identifier normalization; the home for per-engine case folding of annotation keys.
-- `crates/dbx-core/src/table_structure_sql/dialect.rs` — `capabilities_for(database_type).comment`, the authority on whether an engine supports comments at all.
-- `crates/dbx-core/src/schema_diff.rs:772` — `RenameCandidate { source_name, target_name, score, column_jaccard, type_similarity }` plus `jaccard_similarity` and `column_type_similarity`. Reused to *suggest* re-mapping orphaned notes after a rename.
-- `crates/dbx-core/src/database_export.rs` — the established progress-callback and cancellation shape.
-- `apps/desktop/src/lib/diagram/erDiagram.ts` — `layoutDiagramTables` and `diagramZoom.ts`. This module imports **only types**, so the standalone docs bundle can import it without pulling in DBX runtime code. `buildDiagramRelationships` / `foreignKeySourceCardinality` are the reference implementation for the Rust port in Section 3.
-- `apps/desktop/src/lib/export/diagramSvgExport.ts` — existing SVG serialization for diagram export.
-- `apps/desktop/src/styles/globals.css:1310+` — the DBX token palette (strictly achromatic, `oklch(… 0 0)`), from which the docs theme subset is derived.
-- `marked@18` and `shiki@4` are already dependencies. **No new dependency is required by this design.**
-
-## Design
-
-### 1. Snapshot model (`crates/dbx-core/src/docs/snapshot.rs`)
-
-```rust
-use crate::types::{ColumnInfo, ForeignKeyInfo, IndexInfo};
-
-#[derive(Serialize, Deserialize)]
-pub struct SchemaSnapshot {
- pub format_version: u32, // 1
- pub project: ProjectMeta,
- pub tables: Vec<DocTable>,
- pub relationships: Vec<Relationship>,
- pub groups: Vec<TableGroup>,
- pub enums: Vec<DocEnum>,
- pub warnings: Vec<SnapshotWarning>,
-}
-
-pub struct ProjectMeta {
- pub name: String,
- pub database_type: String,
- pub database: Option<String>,
- pub schemas: Vec<String>,
- pub generated_at: String, // RFC3339
- pub note: Option<String>, // markdown, the landing page
-}
-
-pub struct DocTable {
- pub schema: Option<String>,
- pub name: String,
- pub kind: TableKind, // Table | View | MaterializedView
- pub columns: Vec<ColumnInfo>,
- pub indexes: Vec<IndexInfo>,
- pub foreign_keys: Vec<ForeignKeyInfo>,
- pub group_id: Option<String>,
- pub note: Option<String>,
- pub note_source: NoteSource, // Database | Local | None
- pub shadowed_note: Option<String>, // db comment a local note overrides
- pub column_notes: BTreeMap<String, ColumnNote>,
- pub estimated_rows: Option<i64>,
- pub view_definition: Option<String>,
-}
-
-pub struct TableGroup {
- pub id: String, // slug, stable across renames
- pub name: String,
- pub hue: u16, // 0-359 — see Section 4
- pub note: Option<String>,
-}
-
-pub struct Relationship {
- pub id: String,
- pub name: Option<String>,
- pub from: FieldRef,
- pub to: FieldRef,
- pub cardinality: Cardinality,
- pub on_update: Option<String>,
- pub on_delete: Option<String>,
-}
-
-pub struct FieldRef { pub schema: Option<String>, pub table: String, pub column: String }
-pub struct ColumnNote { pub note: String, pub source: NoteSource, pub shadowed: Option<String> }
-pub struct DocEnum { pub schema: Option<String>, pub name: String,
- pub values: Vec<String>, pub note: Option<String>,
- pub synthesized: bool } // true for MySQL inline ENUM(...)
-
-pub enum TableKind { Table, View, MaterializedView }
-pub enum NoteSource { Database, Local, None }
-pub enum Cardinality { OneToOne, ManyToOne }
-
-pub enum SnapshotWarning {
- TableSkipped { table: String, reason: String },
- NoForeignKeyMetadata { engine: String },
- CommentsUnsupported { engine: String },
- OrphanedNotes { count: usize },
- DbmlOmitted { table: String, item: String, reason: String },
-}
-```
-
-Four decisions are embedded here:
-
-- **`format_version`** guards viewer/data skew. The exported HTML pins a snapshot beside a viewer built from the same commit, but an in-app viewer may load a snapshot produced by an older DBX. One integer prevents a class of blank-render bugs and makes future additions additive.
-- **`note_source` and `shadowed_note`** exist so the UI can show *where* prose came from. When a local note shadows a database comment, both are available; the original is shown on hover. Without this, a DBA later writing a better `COMMENT ON` would have their improvement silently hidden forever.
-- **`warnings`** is the honest-degradation channel (Section 10).
-- **Enums are first-class** because DBML has native `enum` blocks. `ColumnInfo.enum_values` is already populated for MySQL inline `ENUM(...)`; PostgreSQL named enums are collected from `pg_type`/`pg_enum`. MySQL inline enums are synthesized into a named enum per `table_column`. This is the one place the snapshot normalizes rather than passes through.
-
-### 2. Collection (`crates/dbx-core/src/docs/collector.rs`)
-
-v1 fetches through the **existing** provider functions, fanned out with a bounded semaphore (8 concurrent). No new per-engine SQL.
-
-This is deliberately the naive-but-correct version: it works for every supported relational engine on day one because it reuses code already proven against all of them. A 400-table schema costs roughly 1200 queries — bounded, cancellable, and measurable.
-
-The optimization path is targeted rather than speculative: PostgreSQL and MySQL can collect all columns, FKs and indexes for a schema in three `information_schema` sweeps instead of 3×N. That belongs in a `collector::bulk` specialization behind the same interface, added only where a benchmark under `scripts/bench/` shows it matters.
-
-Progress is reported through an `impl Fn(DocsProgress)` callback and cancellation via a checked `AtomicBool`, matching `database_export.rs`.
-
-### 3. Relationship inference (`crates/dbx-core/src/docs/relations.rs`)
-
-A port of the data half of `erDiagram.ts`. The split is deliberate:
-
-- **Data logic moves to Rust** — given foreign keys and unique indexes, is an edge 1:1 or N:1? This is the `foreignKeySourceCardinality` check: a relationship is `OneToOne` only when the source columns contain a unique key, otherwise `ManyToOne`.
-- **Layout stays in the renderer** — `layoutDiagramTables` is a view concern and remains in TypeScript, imported by the docs bundle.
-
-This keeps the port to roughly 100 lines rather than a rewrite of the diagram feature. `SchemaDiagramDialog.vue` is **not modified** by this change; once `relations.rs` is proven it becomes the obvious candidate to consume the same inference, removing the duplicate.
-
-### 4. Annotations and table groups (`crates/dbx-core/src/docs/annotations.rs`)
-
-**The notes file is the store** — not a cache, not an export. `dbx.db` persists exactly one thing per connection: the path to this file.
-
-```jsonc
-// default: <app-data>/docs-notes/<connection-id>.json
-// overridable per connection to e.g. ./docs/dbx-docs.json inside a repository
-{
- "format_version": 1,
- "project": { "name": "Ecommerce", "note": "# Overview\n\nMarkdown." },
- "groups": [
- { "id": "order-management", "name": "Order Management", "hue": 28,
- "note": "Everything from checkout to carrier handoff." }
- ],
- "tables": {
- "core.orders": {
- "group": "order-management",
- "note": "One row per completed checkout.",
- "columns": { "status": { "note": "State machine; only moves forward." } }
- }
- }
-}
-```
-
-This shape is required by the CI goal. If notes lived only in `dbx.db`, `dbx docs` in CI would render documentation with every note missing — polished pages, empty of the prose that justifies them. As a file, notes are also reviewable in pull requests, which is arguably better than `COMMENT ON` (invisible to code review). `DesktopSettings.saved_sql_sync_dir` is the existing precedent for a user-chosen path.
-
-**Table groups** are cross-schema domain groupings, authored by the user, stored here alongside notes, and serialized to DBML `TableGroup` blocks. A table belongs to at most one group; unassigned tables render under `(no group)`. Grouping is documentation, not configuration — it never affects what is collected.
-
-**Group colour is stored as a hue integer (0–359), not a hex string.** Lightness and chroma are fixed per theme in CSS and only the hue varies per group:
-
-```css
-.group { --h: 28; }
-/* light */ --group-c: oklch(0.55 0.15 var(--h)); --group-tint: oklch(0.965 0.022 var(--h));
-/* dark */ --group-c: oklch(0.76 0.13 var(--h)); --group-tint: oklch(0.27 0.038 var(--h));
-```
-
-Storing a hex colour the dbdocs way would force either an unreadable dark mode (pastels tuned for a white page turn to mud on `rgb(19 20 22)`) or two colours per group that the user must choose twice. One hue guarantees legible contrast on both grounds by construction, and converts to hex on DBML export.
-
-**Group editor UI.** Groups are created and edited in a dialog reached from the group header on the wiki index, the group badge on a table page, and the diagram group popover. Fields: name, note (markdown), colour, and member tables.
-
-The colour control is **12 curated swatches plus a full 0–359 hue slider** — every hue is reachable, but lightness and chroma remain theme-controlled, so no selection can produce an illegible group. The dialog renders a **two-ground preview**, showing the group chrome on a forced-light and a forced-dark tile simultaneously, because the user may be editing in one theme while a colleague reads the exported HTML in the other.
-
-A native hex/RGB picker is deliberately not offered. It would let a user choose a colour that disappears against one of the two grounds, and the only remedies are to render something different from what the picker showed, or to ship an unreadable group. Hue-plus-fixed-lightness makes the illegible state unrepresentable rather than merely discouraged.
-
-On save, the group is written to the notes file. Since colour is one integer, a group's full definition is a four-field object and diffs cleanly in review.
-
-**Keys and renames.** Keys are `schema.table` and `schema.table.column`, case-folded per engine (PostgreSQL lower, Oracle upper, MySQL per `lower_case_table_names`) in `schema/normalization.rs`.
-
-When a table or column is renamed its note orphans. **User prose is never silently deleted.** Orphans remain in the file, the collector emits `SnapshotWarning::OrphanedNotes { count }`, and the dialog shows an "Unmatched notes" panel. For each orphan, `schema_diff::RenameCandidate` is used to **suggest** the most likely new owner along with its confidence score; the user confirms, re-maps manually, or deletes. Suggestion plus confirmation, never automatic re-attachment — a wrong auto-guess would attach misleading documentation to the wrong column, which is worse than an honest orphan.
-
-**Merge precedence** is `local_annotation ?? database_comment`, recorded in `note_source`. On engines where `capabilities_for(db_type).comment == false` (SQLite, ClickHouse) the annotation layer is the only prose channel, and the UI states this once rather than offering an inert "read from database" affordance.
-
-### 5. DBML serialization (`crates/dbx-core/src/docs/dbml.rs`)
-
-A hand-written serializer, roughly 250 lines. The `@dbml/core` npm package is unusable from Rust and the grammar is small enough not to warrant a dependency.
-
-```dbml
-Project ecommerce {
- database_type: 'PostgreSQL'
- Note: '''Generated by DBX on 2026-08-02'''
-}
-
-Enum order_status { pending shipped cancelled }
-
-TableGroup order_management [color: #c2410c] {
- core.orders
- core.order_items
- Note: '''Everything from checkout to carrier handoff.'''
-}
-
-Table core.orders {
- id integer [pk, increment]
- user_id integer [not null, note: 'Owning customer']
- status order_status [not null, default: 'pending']
- placed_at timestamptz [default: `now()`]
-
- Indexes {
- (user_id, placed_at) [name: 'idx_orders_user_placed']
- }
-
- Note: '''One row per completed checkout.'''
-}
-
-Ref fk_orders_user: core.orders.user_id > core.users.id [delete: restrict]
-```
-
-Rules:
-
-- **Types pass through verbatim.** DBML does not validate type names, so `timestamptz`, `jsonb` and `numeric(10,2)` survive. Where `data_type` arrives bare, precision is reconstructed from `character_maximum_length` / `numeric_precision` / `numeric_scale`.
-- **Cardinality comes from `relations.rs`**: `>` for many-to-one, `-` for one-to-one.
-- **Schema qualification is conditional** — bare names for a single-schema snapshot (it reads better), fully qualified for multi-schema, since DBML has no `search_path`.
-- **Escaping** — identifiers quoted when not `[A-Za-z_][A-Za-z0-9_]*`; notes always in `'''triple quotes'''` so apostrophes cannot break the file; expression defaults in backticks, literals in single quotes.
-- **Group colour** is converted from hue to hex at the theme-neutral lightness.
-
-**DBML is lossy and this is documented in the output.** It cannot express check constraints, partial or filtered indexes (`IndexInfo.filter`), included columns, collations, or generated columns. Composite foreign keys are emitted in the grouped `(a, b) > (c, d)` form, whose support across dbdocs/dbdiagram is uneven. Every omission produces a `SnapshotWarning`, and the HTML documentation renders the omitted item with a "not in DBML" marker.
-
-The asymmetry is intentional: **DBML is the interchange format; the HTML documentation is the complete record.** Treating DBML as a source of truth would silently drop constraints.
-
-### 6. Docs viewer (`apps/desktop/src/docs/`)
-
-```
-main.ts — standalone entry; reads window.__DBX_DOCS__, mounts
-DocsApp.vue — root; hash routing
-components/
- DocsShell.vue — sidebar + main
- DocsSidebar.vue — Group by: Schemas | Table Groups switch, trees, enums
- DocsSearch.vue — ⌘K palette, client-side fuzzy over tables/columns/groups
- WikiIndex.vue — stats, project note, per-group table index
- TablePage.vue — orchestrates the sections below
- ColumnTable.vue — columns grid; inline note editing when !readonly
- IndexList.vue RelationshipList.vue GroupHeader.vue EnumPage.vue
- GroupEditorDialog.vue — name/note/hue/members; rendered only when !readonly
- ErdView.vue — pan/zoom SVG with group containers; reuses layoutDiagramTables()
- NoteMarkdown.vue — marked → sanitized HTML
- WarningBanner.vue — renders snapshot.warnings
-__tests__/ — fixture snapshots in, rendered output asserted
-```
-
-**The contract: this directory makes no backend calls.** No `api.*`, no Tauri, no Pinia stores. Snapshot in, DOM out. This is what allows the same code to run inside an HTML file on a machine that has never installed DBX, and what makes the entire documentation UI testable without a database.
-
-Editing is expressed as a `readonly` prop — `true` in exported HTML, `false` in-app. Components emit `@update:note`, `@update:group` and `@update:table-group`; `DatabaseDocsDialog.vue` performs the writes. `GroupEditorDialog.vue` is not rendered at all when `readonly`, so the exported HTML never ships an editor that cannot save.
-
-Six further decisions:
-
-- **Hash routing** (`#/table/core.orders`), not the History API, which breaks over `file://`. Also makes every table deep-linkable.
-- **Raw HTML is stripped from markdown.** `marked` removed `sanitize` in v5 and DOMPurify is not in the tree. Notes come partly from `COMMENT ON` values living in the database, which is not always under the document author's control, and the output is a file people forward to colleagues. `marked` is configured to escape raw HTML: markdown formatting works, `<script>` and `<img onerror>` do not.
-- **The information architecture follows dbdocs**: the Wiki tab is a scrolling per-group index whose Table Notes column renders **full markdown inline** (headings, prose, code blocks), with table detail pages behind it — not a bare list of links.
-- **Theme tokens are a curated subset**, not `globals.css` (2362 lines). The viewer has its own Tailwind v4 entry scanning only `src/docs/**` plus roughly 25 hand-picked tokens matching DBX's variable names, so it inherits live tokens in-app and ships its own values (with `prefers-color-scheme` and a manual toggle) when exported.
-- **No Shiki in the exported bundle.** View definitions render in a plain `<pre>`. Shiki's grammars would dominate the artifact weight for a feature nobody generates documentation to obtain.
-- **i18n uses a `docs` namespace only** — roughly 40 keys, imported directly, never `i18n/locales/en.ts` wholesale, or the standalone bundle inherits the whole application translation table. All 8 locales ship, selected from `navigator.language`, with a switcher.
-
-### 7. Static HTML export (`crates/dbx-core/src/docs/html.rs`)
-
-Output is `HTML shell + inlined CSS + inlined viewer bundle + window.__DBX_DOCS__ = {snapshot}`.
-
-The viewer bundle is produced by `pnpm build:docs-viewer` into `crates/dbx-core/src/docs/assets/docs-viewer.js`, and **that artifact is committed to git**. `cargo build` never invokes Vite; it only `include_str!`s what is present.
-
-This is the one piece of build coupling in the design, accepted deliberately:
-
-- Rust-only contributors can still `cargo build` without a Node toolchain.
-- The artifact is reviewable in diffs.
-- A CI job rebuilds the bundle and fails if the committed copy is stale.
-
-The cost is a generated file in the tree that must be regenerated when the viewer changes. The CI check is what makes that safe.
-
-**Budget: under 400 KB uncompressed** for a self-contained page documenting a 50-table schema, asserted by test (Section 11). If the real figure lands materially above this, the correct response is to question the Vue-in-a-file approach, not to ship something sluggish.
-
-### 8. Desktop integration (`apps/desktop/src/components/docs/DatabaseDocsDialog.vue`)
-
-The dialog owns all I/O: connection/database/schema selection, invoking the collector, progress and cancellation, note and group writes, the orphan re-map panel, and the two export actions. It mounts `<DocsApp :snapshot :readonly="false">`.
-
-Entry point follows `SchemaDiagramDialog.vue` — a dialog reached from the connection context menu and the toolbar, not a new tab kind.
-
-### 9. CLI (`crates/dbx-cli/src/main.rs`)
-
-```
-dbx docs <connection> --out <dir-or-file> [--schema s] [--database d]
- [--notes path] [--tables a,b] [--open]
-dbx dbml <connection> [--out path] [--schema s] [--database d] [--notes path]
-```
-
-`dbx docs` writes a self-contained `index.html`. `dbx dbml` writes to `--out` or stdout so it pipes.
-
-The existing `--format table|json|csv` flag is **not** extended with `html|dbml`. That flag means "how do I tabulate result rows"; overloading it would invite `dbx query --format dbml`. Two verbs, one output each, matching the existing `dbx schema list` / `dbx schema describe` style.
-
-Target CI shape:
-
-```yaml
-- run: dbx dbml prod --notes docs/dbx-docs.json --out docs/schema.dbml
-- run: git diff --exit-code docs/schema.dbml # migration drift fails the build
-```
-
-### 10. Error handling
-
-| Situation | Behavior | Rationale |
-| --- | --- | --- |
-| Notes file absent | Proceed with empty notes | First CI run, or a user who has not annotated yet. Not an error. |
-| Notes file malformed | **Hard fail**, non-zero exit | User prose is at stake. Proceeding would render apparently-complete docs while discarding writing. |
-| One table's metadata fails | `SnapshotWarning::TableSkipped`, continue | A permission gap on one table must not kill a 400-table build. |
-| Engine lacks FK metadata | Warning banner; ERD with no edges | ClickHouse, Doris, StarRocks. Honest degradation over a blank page. |
-| Engine lacks comment support | Stated once in the UI | SQLite, ClickHouse — via `capabilities_for()`. |
-| Orphaned notes after rename | Warning + re-map panel with suggestions | Section 4. |
-| DBML-inexpressible construct | Warning + "not in DBML" marker in HTML | Section 5. |
-| Connection failure | Existing error path | Already solved. |
-| Stale committed viewer bundle | CI job fails | Guards the Section 7 build coupling. |
-
-The through-line: **fail loudly when user-authored content is at risk; degrade visibly when the database simply cannot answer.**
-
-### 11. Testing
-
-**Rust**
-
-- DBML snapshot tests following `crates/dbx-core/src/sql_dialect/snapshots/`.
-- `relations.rs`: FK with unique source → `OneToOne`; without → `ManyToOne`; composite FK grouping; self-referencing FK.
-- `annotations.rs`: merge precedence; per-engine key folding; orphan detection; `RenameCandidate` suggestion ranking; group assignment and hue round-trip through DBML hex.
-- Live-engine tests as `crates/dbx-core/tests/live_postgres_docs_snapshot.rs`, matching the existing `live_postgres_query_result_export.rs` convention.
-
-**Frontend** (`packages/app-tests/`, following `erDiagram.test.ts` and `diagramSvgExport.test.ts`)
-
-- Every docs component rendered against **fixture snapshot JSON** — no database, no Tauri. This is the payoff of the Section 6 contract.
-- `NoteMarkdown` tested explicitly against `<script>`, `<img onerror=…>` and `javascript:` hrefs.
-- **Self-containment test**: generate HTML from a fixture and assert zero `http://` / `https://` in any `src`, `href` or `@import`. This catches a stray CDN font before it breaks someone's offline documentation.
-- **Artifact size assertion** against the 400 KB budget, so bloat fails a test rather than accumulating.
-- Group colour contrast: assert computed `--group-c` meets the contrast floor against both grounds **across all 360 hues**, not only the 12 curated swatches — the slider makes every hue reachable, so the guarantee must hold for every one of them.
-- `GroupEditorDialog` is absent from the rendered tree when `readonly` is true.
-
-### 12. Deferred: the versioning seam
-
-The Changelog tab and per-table "Last Updated" are out of scope, but the design must not preclude them. Three constraints carry forward:
-
-1. `SchemaSnapshot` is `Serialize + Deserialize` and carries `format_version` and `generated_at`, so it is already storable as a version record.
-2. `crates/dbx-core/src/schema_diff.rs` (8728 lines) already computes `TableDiff` / `ColumnDiff` / `ForeignKeyDiff` between two schemas. A future Changelog is a storage and UI problem, not an algorithm problem.
-3. The docs viewer's tab strip reserves the Changelog slot.
-
-No storage, retention policy, or snapshot history is built in this change.
-
-## Build Order
-
-Each step is independently verifiable; steps 1–2 have standalone value if work stops there.
-
-1. `SchemaSnapshot` + `collector.rs` + `relations.rs` — pure data, fully testable, no UI.
-2. `dbml.rs` + `dbx dbml` — first shippable user value, small surface.
-3. `annotations.rs` — notes, groups, merge, orphan handling.
-4. Docs viewer against fixture snapshots — UI with no backend at all.
-5. `DatabaseDocsDialog.vue` — wire into DBX.
-6. `html.rs` + committed bundle + `dbx docs` — the build coupling last, once the UI has settled.
-
-## Versioning and Documentation
-
-- Version bump `0.5.73 → 0.6.0` (feature, pre-1.0) in `package.json`.
-- Changelog entry through the existing CDN JSON flow (`crates/dbx-core/src/changelog.rs`), not a root `CHANGELOG.md` — this repository does not use one.
-- A feature page in the `docs/` Next.js site.
-- A `docs` i18n namespace across all 8 locales (`en`, `es`, `it`, `ja`, `ko`, `pt-BR`, `zh-CN`, `zh-TW`).
-
-## Validated Mock
-
-The UI was prototyped and approved before this spec was written. The throwaway mock covered: the wiki index with inline markdown notes, a table page with the shadowed-note marker, table groups across sidebar/index/diagram/search, the `Group by` switch, group containers in the ERD, the DBML-lossiness banner, and both themes. It is not part of the implementation.
diff --git a/docs/superpowers/specs/2026-08-03-database-documentation-in-app-design.md b/docs/superpowers/specs/2026-08-03-database-documentation-in-app-design.md
deleted file mode 100644
index 8dfc058420..0000000000
--- a/docs/superpowers/specs/2026-08-03-database-documentation-in-app-design.md
+++ /dev/null
@@ -1,218 +0,0 @@
-# Database documentation in DBX — design
-
-**Part 3b of the database-documentation feature.** Parts 1, 2 and 3a are complete and merged into
-`feature/docs-snapshot-dbml`: `SchemaSnapshot` collection with a DBML serializer and a `dbx dbml`
-verb, a file-backed annotation store for notes and table groups, and a read-only Vue viewer tested
-against a real backend-generated fixture.
-
-This part makes the viewer reachable and editable inside DBX. The standalone HTML export, the
-`dbx docs` verb and hash routing are deliberately **not** here — they are Part 3c.
-
-## Goal
-
-A user opens a connection's documentation from the tree, reads a dbdocs.io-style wiki of their
-schema, and edits it in place: table and column notes, table groups, and each group's colour.
-Everything they write persists to a JSON notes file that can live inside their repository.
-
-## Scope
-
-**In scope**
-
-- `DatabaseDocsDialog.vue`, mounted through the existing dialog pattern
-- Backend reachability: the desktop frontend currently cannot call the docs collector at all
-- Editing: table notes, column notes, project note, group create/rename/delete/assign, group hue
-- Debounced autosave to the notes file, with a visible saved/failed indicator
-- `EnumPage.vue`
-- An i18n `docs` namespace across all 8 locales, with a parity guard
-- A link from the docs viewer to the existing `SchemaDiagramDialog`
-
-**Out of scope (Part 3c)**
-
-- The standalone Vite bundle and self-contained HTML export
-- The `dbx docs` CLI verb
-- Hash routing (`#/table/public.orders`) — its purpose is surviving a `file://` load
-- A minimal read-only ER renderer for the export
-- Inlining the Geist woff2 at `apps/desktop/public/fonts/geist-latin-wght-normal.woff2`
-
-**Explicitly not built**: a second ER diagram. DBX already ships `SchemaDiagramDialog.vue`
-(51.6 KB) with custom relationships, join-SQL generation and zoom. In-app, the docs viewer links
-to it. Only the export needs its own minimal renderer, because that dialog reaches into stores and
-the backend and therefore cannot be inlined.
-
-## Architecture
-
-### The viewer stays pure; the dialog owns all I/O
-
-Part 3a's contract test forbids `apps/desktop/src/docs/**/*.vue` from referencing `@/lib/backend`,
-`@tauri-apps`, `invoke(`, `fetch(`, or any store. Editing preserves that rule: components emit
-edit intents upward, and only `DatabaseDocsDialog.vue` — which lives outside `src/docs/` — talks to
-the backend.
-
-This is not ceremony. It is what allows Part 3c to bundle the identical components into an HTML
-file that runs on a machine with no DBX installed.
-
-```
-connectionStore.docsSource set by the connection-tree context menu
- → useDialogSources.ts watcher mirrors the existing diagramSource pattern
- → showDocsDialog + prefills
- → DatabaseDocsDialog.vue owns: collect, load notes, save notes, autosave
- │ props: snapshot, annotations ↓ emits: update:note, update:group, …
- └─ DocsApp.vue Part 3a, unchanged apart from readonly=false
-```
-
-### Four backend operations, five touchpoints each
-
-`apps/desktop/src/lib/backend/api.ts` is a facade that lazily resolves either `tauri.ts` or
-`http.ts` via `isTauriRuntime()` and re-exports each function through `forward()`. Every operation
-therefore exists twice, once per transport. There is currently **no docs entry in `api.ts` at
-all** — Part 1's collector is reachable from the CLI, MCP and the web route, but never from the
-desktop frontend.
-
-| Operation | Returns | Existing | New |
-|---|---|---|---|
-| `collectDocsSnapshot` | raw `SchemaSnapshot` | web route | Tauri command, both transports, `api.ts` forward |
-| `loadDocsAnnotations` | `AnnotationFile \| null` | `load_annotations` | path resolution, command, routes, forward |
-| `applyDocsAnnotations` | applied `SchemaSnapshot` | `apply_annotations` | command, routes, forward |
-| `saveDocsAnnotations` | `()` | — | **`save_annotations` does not exist** |
-
-### Why `applyDocsAnnotations` is a separate call
-
-The viewer renders a snapshot with annotations already applied, but edits target the
-`AnnotationFile`. After an edit the displayed snapshot is stale.
-
-Applying the edit optimistically in TypeScript would mean reimplementing `apply_annotations`,
-including the `shadowedNote` rule where a local note displaces a database `COMMENT ON` and
-preserves it underneath. A second implementation of that rule in a second language is exactly the
-drift this feature has repeatedly suffered from.
-
-Instead, `collect` returns the **raw** snapshot, and `applyDocsAnnotations(raw, file)` is a pure
-Rust call with no database access. The dialog keeps the raw snapshot from open and re-derives on
-demand. One implementation of the rule, in the language where it is already tested.
-
-While the user types, nothing is re-derived: the editor binds to the raw note text in the
-`AnnotationFile`, not to rendered output. The round trip happens on blur, not per keystroke.
-
-### Notes file location
-
-`config.docs_notes_path` when set; otherwise `<app_data>/docs-notes/<connection_id>.json`.
-
-The default makes the feature work with no setup. The override is the point: pointing it at a file
-inside a repository is what lets schema documentation be code-reviewed and committed alongside the
-schema it describes.
-
-`docs_notes_path` already exists on `ConnectionConfig`, `ConnectionConfigData` and the `From` impl
-(Part 2). Nothing reads it yet.
-
-### `save_annotations` must be atomic
-
-Write to a temporary file in the same directory, fsync, then rename. A partial write destroys prose
-a human typed, and `load_annotations` errors loudly on malformed JSON — so a torn write becomes
-"your notes file is corrupt" the next time the dialog opens.
-
-A failed save must surface in the UI. A silently swallowed write failure is the worst outcome this
-feature can produce.
-
-## Editing
-
-### Edits are pure transformations of the `AnnotationFile`
-
-`apps/desktop/src/docs/annotationEdits.ts` — every function takes an `AnnotationFile` and returns a
-new one, with no I/O:
-
-- `setProjectNote(file, note)`
-- `setTableNote(file, tableKey, note)`
-- `setColumnNote(file, tableKey, column, note)`
-- `setTableGroup(file, tableKey, groupId | null)`
-- `upsertGroup(file, group)` — create or update name, hue, note
-- `removeGroup(file, groupId)` — also clears the reference from every table that used it
-
-Empty or whitespace-only notes remove the entry rather than storing an empty string, so the file
-does not accumulate dead keys.
-
-**Deleting a group clears its references.** `docsIndex.ts` already drops a dangling `groupId` when
-rendering, so the viewer degrades correctly either way — but the file should not carry references
-to a group that no longer exists.
-
-### Components
-
-All thin; every decision lives in `annotationEdits.ts` or an existing Part 3a module.
-
-- **`NoteEditor.vue`** — renders `renderNote(...)` output until clicked, then swaps to a raw
- markdown textarea. Reused for table, column, group and project notes. The `v-html` contract rule
- applies here as everywhere: only `renderNote` output may be bound.
-- **`GroupEditor.vue`** — name field plus the hue picker from the approved mock: 12 swatches, a
- 360° slider, and a preview showing the colour on light and dark grounds simultaneously. The
- two-ground preview is why the hue-only model exists, so it belongs in front of the user while
- they choose.
-- **`GroupPicker.vue`** — assigns a table to a group; a select plus "New group…".
-- **`EnumPage.vue`** — a `DocEnum`'s values, its note, and the columns using it. The reverse lookup
- from enum to using columns is a tested function in `docsIndex.ts`, not template logic.
-
-### `readonly` returns
-
-Part 3a removed the `readonly` prop as YAGNI, since nothing read it. Part 3b reintroduces it
-because Part 3c renders the identical components with editing disabled.
-
-### Autosave
-
-Debounced ~500 ms after the last edit, owned by the dialog. A small indicator shows saved / saving
-/ failed. Failure is visible and the in-memory state is retained so the user can retry rather than
-losing what they wrote.
-
-## i18n
-
-A `docs` namespace added to all 8 locales: `en`, `es`, `it`, `ja`, `ko`, `pt-BR`, `zh-CN`, `zh-TW`.
-
-`withEnglishFallback` deep-merges `en` underneath every locale, so a key missing from `ja.ts`
-silently renders English with no error, no warning, and no failing test. Translation completeness
-is therefore unobservable at runtime.
-
-**A key-parity test is required**: import the raw locale modules — not the merged output — and
-assert every locale declares the same key set under `docs` as `en` does. Scoped to the new
-namespace only; parity across the existing 315 KB of keys is out of scope and would fail
-immediately.
-
-Part 3a hardcoded English strings in `docsWarnings.ts`. Those move into the namespace, which is a
-breaking change to that module: `describeWarning(warning)` becomes
-`describeWarning(warning, translate)`, and its existing tests change with it.
-
-It takes a **translator function** rather than importing `useI18n` directly, and that is
-deliberate. `useI18n()` throws without a provided instance, which is exactly the Part 3c
-standalone-export case — a bare HTML file with no Vue app bootstrapped around it. Passing the
-translator in keeps `docsWarnings.ts` a pure module the export can call with an English identity
-function. Importing vue-i18n inside `src/docs/` would make the export impossible.
-
-## Testing
-
-| Layer | Approach |
-|---|---|
-| `annotationEdits.ts` | Pure unit tests — the bulk of the coverage |
-| `save_annotations` | Rust: atomicity; a failed write leaves the previous file intact |
-| Path resolution | Rust: override wins; default when unset |
-| Components | The Part 3a static SFC contract test, extended to the new files |
-| i18n | Key parity across 8 locales for the `docs` namespace |
-| Dialog | Autosave debounce; the failure indicator |
-
-**Every new test gets the deliberate-break treatment**: break the behaviour, watch the named test
-fail, restore, report the failure message. In Part 3a this caught a vacuous ranking test, a CSS
-ordering bug that let a whole theme's colours be deleted silently, and a capability warning that
-contradicted its own data. It is the highest-yield practice carried forward.
-
-### Known gap: `DocEnum` drift is unguarded
-
-The conformance fixture is generated from `keycloak`, which declares no PostgreSQL enum types, so
-`snapshot.enums` is empty and `DocEnum` field renames are not detectable. `EnumPage` tests use
-in-memory snapshots, which prove the rendering logic but not the Rust↔TS boundary.
-
-`fixtureConformance.spec.ts` carries a self-correcting assertion that fails the day the fixture
-source gains an enum, with the exact `pinShape` call to restore. Part 3c is the natural time to
-close this, since an exportable demo wants an enum-bearing schema anyway.
-
-## Success criteria
-
-- A user opens documentation from the connection tree, reads it, edits notes and group colours, and
- the changes survive closing and reopening the dialog.
-- Pointing `docs_notes_path` at a repository file produces a diff a colleague can review.
-- `apps/desktop/src/docs/**/*.vue` still makes zero backend calls, enforced by the contract test.
-- All 8 locales declare the same `docs` keys, enforced by a test.
-- A failed save is visible to the user and does not discard their work.
diff --git a/docs/superpowers/specs/2026-08-06-database-documentation-export-design.md b/docs/superpowers/specs/2026-08-06-database-documentation-export-design.md
deleted file mode 100644
index e8e76df746..0000000000
--- a/docs/superpowers/specs/2026-08-06-database-documentation-export-design.md
+++ /dev/null
@@ -1,302 +0,0 @@
-# Standalone documentation export — design
-
-**Part 3c of the database-documentation feature.** Parts 1, 2, 3a and 3b are complete on
-`feature/docs-snapshot-dbml` and open upstream as PR #5559: `SchemaSnapshot` collection with a DBML
-serializer and a `dbx dbml` verb, a file-backed annotation store, a pure Vue viewer, and that
-viewer mounted in DBX with autosaved editing.
-
-This part makes the documentation leave the application: one self-contained HTML file, produced by
-a `dbx docs` verb and by a button in the app, that opens from `file://` on a machine with no DBX
-installed.
-
-## Goal
-
-A user runs `dbx docs prod --out schema.html` in CI, or clicks **Export HTML** in the docs dialog,
-and gets a single file they can commit, attach to a ticket, or email to a colleague. It opens with
-no network, no server and no install. Deep links into it survive a reload, and the reader chooses
-their own language.
-
-## Scope
-
-**In scope**
-
-- A standalone Vite bundle of the existing viewer, built to one JS and one CSS
-- `crates/dbx-core/src/docs/export.rs` — `to_standalone_html(snapshot, annotations, lang)`
-- The `dbx docs` CLI verb, mirroring `dbx dbml`'s flags
-- A Tauri command and an **Export HTML** button in `DatabaseDocsDialog.vue`
-- Hash routing in the export shell, so `schema.html#/table/public.orders` is a link
-- A language switcher over all 8 bundled `docs` namespaces
-- `SchemaDiagram.vue` — a minimal read-only ER renderer
-- A staleness guard so the committed bundle cannot drift from its sources
-
-**Out of scope**
-
-- Editing in the export. It is read-only; `readonly` exists on `DocsApp` for exactly this.
-- Zoom, pan controls, drag, custom relationships or join-SQL in the diagram — that is what the
- full `SchemaDiagramDialog` is for.
-- The `latin-ext` font subset. The latin subset is inlined; `latin-ext` doubles the font cost to
- serve characters most schemas never use, and the fallback is graceful.
-- Persisting the reader's language choice. See "Language" below.
-
-## Decisions taken before design
-
-| Question | Decision |
-|---|---|
-| How does the built bundle reach the Rust binary? | Committed build artefact in `crates/dbx-core/assets/`, embedded with `include_str!`, with a staleness guard |
-| Where does the ER renderer live? | `src/docs/`, with the host choosing the affordance |
-| What language is the export? | All 8 namespaces bundled, switchable by the reader |
-| Is there an in-app export button? | Yes — same Rust function, two callers |
-| How is a stale bundle detected? | Content hash against a manifest, derived from the build |
-| How is the payload embedded? | base64 |
-
-## Architecture
-
-### Three pieces, each with one job
-
-```
-apps/desktop/src/docs-export/ the export shell (browser)
- main.ts mounts ExportApp, decodes the payload
- ExportApp.vue hash routing, language switcher, readonly=true, diagram="inline"
- export.css @source narrowed to ../docs/** + inlined @font-face
-
-pnpm build:docs-export vite.docs-export.config.ts
- → one JS, one CSS, font as data URI, no code splitting
- → crates/dbx-core/assets/docs-export.{js,css,manifest.json}
-
-crates/dbx-core/src/docs/export.rs to_standalone_html(snapshot, annotations, lang)
- → include_str! the two assets, base64 the payload, emit one HTML file
-```
-
-### Why the bundle is committed rather than built by cargo
-
-Rust cannot run Vite, and `dbx docs` must work from a plain `cargo install` on a machine with no
-Node. A `build.rs` that shells out to pnpm would break exactly that case, and neither existing
-`build.rs` invokes an external toolchain.
-
-There is partial precedent: `crates/dbx-core/src/ai_pi_agent_cli.rs:24` embeds
-`include_str!("../assets/pi-mcp-bridge.mjs")`, and `crates/dbx-core/assets/` already carries a
-54.8 KB driver manifest. The caveat is honest and belongs in the PR: `pi-mcp-bridge.mjs` is
-hand-written, so the precedent covers committing a *source* asset, not a *build artefact*. The
-staleness guard is what makes the difference acceptable.
-
-### Data flow
-
-`dbx docs` collects a snapshot exactly as `dbx dbml` does — same collector, same `--schema`,
-`--database`, `--tables`, `--notes` flags, same warnings on stderr through the `Display` impl. It
-then calls `to_standalone_html`. The Tauri command calls the identical function.
-
-The snapshot is passed **with annotations already applied**, because `apply_annotations` is Rust
-and the export has no Rust at runtime. The raw `AnnotationFile` also travels, for the same reason
-the dialog needs it: `snapshot.groups` holds resolved `TableGroup`s, while `annotations.groups`
-holds the `GroupAnnotation` records that carry each group's hue.
-
-### The payload is base64
-
-The exported page contains user-authored Markdown. A note containing the literal text `</script>`
-— entirely plausible in a schema document that discusses HTML — would terminate the script element
-early and inject the remainder as markup.
-
-base64 removes the problem structurally rather than procedurally: the alphabet is `A-Za-z0-9+/=`,
-so no escaping rule exists to forget, and the property is auditable by inspection instead of by
-reviewing every serialization path. It costs +33% on the JSON only.
-
-The alternatives were considered and rejected. A `<script type="application/json">` in which every
-`<` is rewritten as its JSON unicode escape (backslash, `u`, `003c`) is what SSR frameworks do and
-is sound, but its correctness depends on that rewrite being applied on every path. A JS string literal needs four independent escaping rules —
-quotes, backslashes, `</script>`, and U+2028/U+2029, which `JSON.stringify` emits raw because they
-are valid JSON but which were line terminators inside JS string literals until ES2019.
-
-The cost of base64 is that the embedded schema is no longer readable in a text editor. That is
-accepted.
-
-### Styling: `globals.css` cannot be reused
-
-Two facts decide this.
-
-`apps/desktop/src/styles/globals.css:40` is `@source "../**/*.{vue,ts,tsx,js,jsx,html}"`. Tailwind
-v4 scans the entire application, so importing `globals.css` into the export would emit every
-utility used anywhere in DBX. The 76 KB of source is not the cost; the generated utility surface
-is. `@source` is additive — there is no way to un-source it.
-
-Its four `@font-face` blocks use absolute `/fonts/…` URLs, which under `file://` resolve against
-the filesystem root and fail silently to a system font.
-
-So `export.css` is its own entry: `@source` narrowed to `../docs/**`, and `@font-face` redeclared
-with the woff2 inlined as a data URI (~38 KB base64).
-
-### One shared-file change: `tokens.css`
-
-The viewer's utilities resolve against tokens — `--background`, `--foreground`,
-`--muted-foreground`, `--border`, `--ring` — defined in `globals.css` from line 131, interleaved
-with roughly 2300 lines of application-specific rules. A narrowed `@source` still needs those
-tokens.
-
-The token blocks move to `apps/desktop/src/styles/tokens.css`, imported by **both** `globals.css`
-and `export.css`. One definition, no drift. Copying the values into the export instead is exactly
-the duplication that produced this feature's recurring defects.
-
-**This is a real risk and the plan must treat it as one.** It edits a 76 KB stylesheet the whole
-application depends on, on an already-large branch. The move is mechanical — a contiguous block
-plus one `@import` — but the cascade order between `:root` and `.dark` must be preserved exactly.
-A test asserts every custom property defined at `:root` before the extraction still resolves after
-it.
-
-## The export shell
-
-### Hash routing stays out of the shared tree
-
-`DocsApp` owns navigation internally today: `activeKey`, `activeEnumName`, and a computed
-`view: "index" | "table" | "enum"`. It gains an **optional** `v-model:route`:
-
-```ts
-type DocsRoute =
- | { kind: "index" }
- | { kind: "table"; key: string }
- | { kind: "enum"; name: string }
- | { kind: "diagram" };
-```
-
-Absent, `DocsApp` behaves exactly as it does today and the dialog is untouched. Present, the shell
-controls navigation and mirrors `location.hash`.
-
-`{ kind: "diagram" }` is only reachable when `diagram="inline"`. Under `diagram="external"` the
-route resolves to the index, so a hash of `#/diagram` in the dialog's context cannot render a view
-that host has deliberately not enabled.
-
-This separation is not stylistic. DBX has **no router at all** — `vue-router` is not a dependency,
-and the only `location.hash` reference in the frontend is a debug logger at
-`lib/backend/debugLog.ts:214`. A `DocsApp` that wrote to the URL would hijack the host
-application's address bar.
-
-Hash grammar, with `encodeURIComponent` on the identifier so a table named `a/b` round-trips:
-
-```
-#/ index
-#/table/public.orders table page
-#/enum/order_status enum page
-#/diagram ER diagram
-```
-
-Hash routing rather than `pushState` because the target is `file://`, where `pushState` is
-unusable but a fragment survives a reload and makes `schema.html#/table/public.orders` a link
-worth pasting.
-
-**Parsing is defensive by contract.** An unparseable hash, or one naming a table or enum absent
-from the payload, resolves to the index. A stale deep link into a since-dropped table is the
-expected case, not an exotic one, and must never produce a blank page.
-
-### Language
-
-All 8 `docs` namespaces are bundled. They total 15,197 bytes of source across
-`apps/desktop/src/i18n/locales/docs/{en,es,it,ja,ko,pt-BR,zh-CN,zh-TW}.ts` — roughly 3 KB gzipped,
-negligible against the bundle. The payload carries an initial `lang` from `--lang` or the app's
-current locale; the switcher rebuilds `translate` from the bundled namespace.
-
-**No persistence.** Under `file://` every document shares one opaque origin, so `localStorage`
-would leak one export's preference into an unrelated one. A single-session document is the honest
-model.
-
-**Missing keys fall back to English.** The parity test guarantees all 8 namespaces agree, so this
-should never fire; it exists so an artefact opened offline degrades to English rather than
-rendering a raw key. This does not repeat the Part 3b hazard where a fallback masked drift — there
-the fallback replaced the guard, here the guard runs in CI and the fallback is a runtime backstop.
-
-The switcher is worth having because **the reader is usually not the exporter**: the file gets
-sent to someone else, and upstream's largest user base does not read English.
-
-### The ER renderer
-
-`SchemaDiagram.vue` lives in `src/docs/` and is added to the contract test's expected component
-list. It imports `layoutDiagramTables` from `@/lib/diagram/erDiagram` — permitted, since only
-`@/lib/backend` is forbidden, and that module has exactly one import which is `import type`,
-making it fully bundleable.
-
-So the grid layout is reused, not reinvented. What is genuinely new is **edge routing**, which
-exists nowhere in the codebase today: a straight line between two cards' centres, clipped at each
-card's border so it terminates on the edge rather than under the box. Crossings are tolerated.
-
-Deliberately minimal: SVG at natural size inside an `overflow: auto` container, because scrolling
-*is* panning. No zoom, no drag, no custom relationships, no join-SQL. Group colours come from
-`groupStyle(hue)` so the diagram agrees with the wiki, and clicking a table navigates to its page —
-which under hash routing makes the diagram a usable table of contents.
-
-The host chooses the affordance. `DatabaseDocsDialog` passes `diagram="external"` and keeps its
-existing button to the full `SchemaDiagramDialog`; the export passes `diagram="inline"`. No screen
-shows both, and neither host gets a worse diagram than it could have.
-
-## The staleness guard
-
-`pnpm build:docs-export` emits `docs-export.js`, `docs-export.css` and `docs-export.manifest.json`
-into `crates/dbx-core/assets/`.
-
-**The manifest is derived from Rollup's module graph, not from a hand-written glob.** This is the
-single most important detail in this section. `SchemaDiagram.vue` imports `erDiagram.ts`, which
-lives outside `src/docs/` — a glob of `src/docs/**` would miss it and the guard would pass while
-the artefact was stale. That is the same defect shape that has now bitten this feature three times:
-`vue-i18n` absent from the contract test's forbidden list, `DocEnum` unpinned by an enum-free
-fixture, `.docs-ground-light` absent from the CSS selector list. **A guard that enumerates its
-targets silently excludes everything added later.**
-
-So the build script writes the manifest from every repo file that actually entered the bundle,
-plus the resolved versions of the node_modules packages it pulled in.
-
-This closes the loop on new files, and the reason should be stated in the plan rather than left
-implied: a new module can only enter the bundle by being imported, which means editing an existing
-file, which changes that file's hash. The one hole is `import.meta.glob`, which would add modules
-without editing an importer — the viewer does not use it, and the plan says so explicitly.
-
-The Rust test recomputes the hashes and fails with the regeneration command. It must skip when the
-crate is consumed from a published package where `apps/desktop/` does not exist — and that skip is
-itself a hazard, since a vacuous skip in CI would silently disable the guard. The skip therefore
-keys off a repository-only marker (`pnpm-workspace.yaml`): marker present, the test runs; marker
-absent, the crate is genuinely packaged and there is nothing to check.
-
-## Error handling
-
-- `--out` omitted writes to stdout, matching `dbx dbml`. A 400 KB HTML in a terminal is unpleasant,
- but consistency and `dbx docs prod | gzip > docs.html.gz` are worth more than a special case.
-- `--lang xx` fails with the list of valid locales rather than falling back. A typo should be loud,
- the same reasoning that made `--notes` an explicit flag in Part 2.
-- A missing or malformed notes file behaves exactly as `dbx dbml` does, through the existing
- `require_notes_file`.
-
-## Testing
-
-| Layer | Approach |
-|---|---|
-| `to_standalone_html` | Rust: base64 round-trip; a note containing `</script>` survives intact |
-| Self-containedness | Rust: the emitted HTML contains no `http://`, `https://`, `url(/`, or external `src`/`href` |
-| Route parsing | TS: pure parse/format — unknown table resolves to index, encoded identifiers, empty hash |
-| Language | TS: the translate factory picks the right namespace; unknown lang falls back to English |
-| Edge clipping | TS: the line-to-card-border intersection is a pure function |
-| Contract | `SchemaDiagram.vue` added to the expected component list |
-| Token extraction | Every custom property defined at `:root` before the move still resolves after it |
-| Staleness | The manifest test, verified by touching a source file and watching it fail |
-
-**Every new test gets the deliberate-break treatment**: break the behaviour, watch the named test
-fail, restore, report the failure message. Across Parts 3a and 3b this caught a vacuous ranking
-test, a CSS ordering bug that let a whole theme's colours be deleted silently, a capability warning
-that contradicted its own data, and an atomicity test that was vacuous because of the fix
-instruction I had written myself.
-
-### The test worth attempting but not promising
-
-A `happy-dom` smoke test that loads the generated HTML, executes the inline bundle, and asserts a
-known table name reaches the DOM is the only test that proves the artefact *works* rather than
-merely looks right. `happy-dom ^20.10.6` is already a dependency; Playwright and Puppeteer are not.
-
-happy-dom can execute scripts, but running a full Vue bundle in it is not guaranteed. If it works
-it is the most valuable test in this part. If it does not, the plan says so plainly and falls back
-to the structural self-containedness test plus opening the file in a real browser over `file://` —
-the method already used to verify the viewer for PR #5559's screenshots.
-
-## Success criteria
-
-- `dbx docs prod --out schema.html` produces one file that opens from `file://` with no network, no
- server and no DBX installed.
-- `schema.html#/table/public.orders` survives a reload and can be pasted to a colleague.
-- A reader switches language without re-exporting.
-- The in-app button and the CLI produce byte-identical output for the same inputs, because they
- call the same function.
-- The committed bundle cannot drift from its sources without a test failing.
-- `apps/desktop/src/docs/**/*.vue` still makes zero backend calls, enforced by the contract test.
diff --git a/docs/superpowers/specs/2026-08-07-docs-menu-database-scope-design.md b/docs/superpowers/specs/2026-08-07-docs-menu-database-scope-design.md
deleted file mode 100644
index cc2b63164b..0000000000
--- a/docs/superpowers/specs/2026-08-07-docs-menu-database-scope-design.md
+++ /dev/null
@@ -1,150 +0,0 @@
-# Documentation Menu at Database Scope Design
-
-**Date:** 2026-08-07
-
-## Goal
-
-Move the "Documentation" context-menu entry from the object browser's table and
-view menus to the sidebar's database and schema context menu, so the entry
-appears at the scope it actually documents.
-
-## Background
-
-PR #5559 ("feat(docs): database documentation viewer and DBML export") shipped in
-v0.5.77. It added the only entry point for the docs viewer to
-`ObjectBrowser.vue`, in the table menu and the view menu, nested inside the
-existing `canOpenDiagram` branch alongside "View Diagram".
-
-That placement misrepresents what the action does. `openDocs(row)` in
-`ObjectBrowser.vue:1466` reads only `row.schema`; the row's table is discarded.
-`DatabaseDocsDialog.vue` accepts `prefillConnectionId`, `prefillDatabase`, and
-`prefillSchema` — there is no table prop, so the viewer cannot deep-link to a
-table even in principle. A user who right-clicks `orders` and picks
-"Documentation" gets documentation for the whole schema.
-
-The docs collector was designed for the wider scope. `DatabaseDocsDialog.vue:91`
-carries the comment "An absent schema means 'everything the collector finds'",
-and `connectionStore.docsSource.schema` is already optional. Database-scoped
-documentation is the case the backend was built for and is currently
-unreachable from the UI.
-
-Users therefore look for the entry on the database node in the connections
-sidebar, where "View Diagram" already sits, and do not find it.
-
-## Requirements
-
-- offer "Documentation" on sidebar database nodes, documenting the whole database
-- offer "Documentation" on sidebar schema nodes, documenting that schema only
-- remove the entry from the object browser's table and view menus
-- keep the set of drivers that expose the entry identical to v0.5.77
-- change no backend, dialog, or viewer code
-- leave the "View Diagram" entries in both menus untouched
-
-## Non-Goals
-
-- deep-linking the viewer to a single table (would need a new dialog prop and a
- viewer route change; a separate change if it is ever wanted)
-- introducing a `docs` driver capability key (see Gating below)
-- any change to `crates/dbx-core`
-
-## Design
-
-### Sidebar action
-
-`useSidebarTreeToolRuntime.ts` gains `openDocs`, mirroring `openDiagram` at
-line 55:
-
-```ts
-function openDocs() {
- const node = activeNode.value;
- if (!node.connectionId || !node.database) return;
- connectionStore.docsSource = {
- connectionId: node.connectionId,
- database: node.database,
- schema: node.schema,
- };
-}
-```
-
-`node.schema` carries the whole behaviour. It is `undefined` on a database node,
-so `DatabaseDocsDialog.vue:93` (`props.prefillSchema ? [props.prefillSchema] : []`)
-sends an empty schema list and the collector documents the entire database. On a
-schema node it is set, and the collector is limited to that schema.
-
-`openDiagram` also passes `tableName`; `openDocs` does not. The docs dialog has
-no corresponding prop, so passing it would be dead data.
-
-### Menu registration
-
-One `items.push` in `SidebarTreeRuntimeHost.vue`, immediately after the
-"View Diagram" push at line 4205:
-
-```ts
-if (canOpenDiagram.value) {
- items.push({ label: t("diagram.open"), action: openDiagram, icon: Network });
- items.push({ label: t("docs.title"), action: openDocs, icon: BookOpen });
-}
-```
-
-Line 4205 sits inside `buildDatabaseSidebarMenu` (lines 4147-4259), whose guard
-is `node.type === "database" || node.type === "schema"`. A single push therefore
-covers both node types. The other "View Diagram" push, at line 4483, belongs to
-`buildObjectSidebarMenu` and is not touched.
-
-`openDocs` is destructured from `useSidebarTreeToolRuntime` at line 312, and
-`BookOpen` is added to the existing `@lucide/vue` icon import (lines 13-57).
-
-### Object browser removal
-
-`ObjectBrowser.vue` loses the docs entry from the table menu (line 2669) and the
-view menu (line 2724), the `openDocs` function (line 1466), and the now-orphaned
-`BookOpen` import (line 9). The `canOpenDiagram` ternaries collapse back to the
-single-element form they had before PR #5559.
-
-### Gating
-
-The new entry reuses the sidebar's existing `canOpenDiagram` computed
-(line 3386): `!!activeNode.value.database && supportsSchemaDiagram(currentDatabaseType())`.
-
-This is a deliberate compromise rather than a principled gate. Documentation and
-diagrams are separate features; a driver that supported one but not the other
-would be misrepresented. The principled alternative is a `docs` key in
-`DATABASE_PRODUCT_CAPABILITY_KEYS`, but that list is backed by
-`crates/dbx-core/assets/database-drivers.manifest.json`, shared with the Rust
-side, and would require a per-support-level default plus per-driver overrides
-across every driver.
-
-Reusing the diagram gate keeps this change's visible behaviour identical to
-v0.5.77 except for *where* the entry appears, which is the point of the change.
-A capability key is worth proposing separately; it is called out in the PR
-description rather than bundled here.
-
-## Testing
-
-New spec `apps/desktop/src/composables/__tests__/useSidebarTreeToolRuntime.docs.spec.ts`,
-following the `shallowRef` node plus stub-store pattern of the neighbouring
-`useSidebarTreeExportRuntime.spec.ts`:
-
-- database node: `docsSource` receives `connectionId` and `database`, and
- `schema` is `undefined`
-- schema node: `schema` is propagated
-- node without `database`: `docsSource` is left untouched
-
-No i18n work is required. `docs.title` was added to all eight locales by
-PR #5559, so this change introduces no locale-drift exposure.
-
-Verification:
-
-```
-pnpm typecheck
-npx vitest run apps/desktop/src/composables apps/desktop/src/components/objects
-```
-
-## Delivery
-
-Branch `fix/docs-menu-database-scope`, cut from `upstream/main` at `29fe57143`.
-One commit, then a PR to `t8y2/dbx`.
-
-No `VERSION` or `CHANGELOG.md` bump: this repository has no changelog, and
-`package.json` version is managed by upstream's `scripts/release.mjs`. Version
-numbers belong to the maintainer's release process, not to a contribution PR.